org-latex.el: New option `org-export-latex-hyperref-options-format'.
[org-mode.git] / lisp / org.el
blob428fb9c581cfcc2dff8b18f4a0bf51c03d2fe1f6
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-trash (or
226 (and (fboundp 'org-release) (fboundp 'org-git-version))
227 (load (concat org-dir "org-version.el")
228 'noerror 'nomessage 'nosuffix)))
229 (org-version (org-release))
230 (git-version (org-git-version))
231 (version (format "Org-mode version %s (%s @ %s)"
232 org-version
233 git-version
234 (if org-install-dir
235 (if (string= org-dir org-install-dir)
236 org-install-dir
237 (concat "mixed installation! " org-install-dir " and " org-dir))
238 "org-install.el can not be found!")))
239 (_version (if full version org-version)))
240 (if (org-called-interactively-p 'interactive)
241 (if here
242 (insert version)
243 (message version))
244 (if message (message _version))
245 _version)))
247 ;;; Compatibility constants
249 ;;; The custom variables
251 (defgroup org nil
252 "Outline-based notes management and organizer."
253 :tag "Org"
254 :group 'outlines
255 :group 'calendar)
257 (defcustom org-mode-hook nil
258 "Mode hook for Org-mode, run after the mode was turned on."
259 :group 'org
260 :type 'hook)
262 (defcustom org-load-hook nil
263 "Hook that is run after org.el has been loaded."
264 :group 'org
265 :type 'hook)
267 (defcustom org-log-buffer-setup-hook nil
268 "Hook that is run after an Org log buffer is created."
269 :group 'org
270 :version "24.1"
271 :type 'hook)
273 (defvar org-modules) ; defined below
274 (defvar org-modules-loaded nil
275 "Have the modules been loaded already?")
277 (defun org-load-modules-maybe (&optional force)
278 "Load all extensions listed in `org-modules'."
279 (when (or force (not org-modules-loaded))
280 (mapc (lambda (ext)
281 (condition-case nil (require ext)
282 (error (message "Problems while trying to load feature `%s'" ext))))
283 org-modules)
284 (setq org-modules-loaded t)))
286 (defun org-set-modules (var value)
287 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
288 (set var value)
289 (when (featurep 'org)
290 (org-load-modules-maybe 'force)))
292 (when (org-bound-and-true-p org-modules)
293 (let ((a (member 'org-infojs org-modules)))
294 (and a (setcar a 'org-jsinfo))))
296 (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)
297 "Modules that should always be loaded together with org.el.
298 If a description starts with <C>, the file is not part of Emacs
299 and loading it will require that you have downloaded and properly installed
300 the org-mode distribution.
302 You can also use this system to load external packages (i.e. neither Org
303 core modules, nor modules from the CONTRIB directory). Just add symbols
304 to the end of the list. If the package is called org-xyz.el, then you need
305 to add the symbol `xyz', and the package must have a call to
307 (provide 'org-xyz)"
308 :group 'org
309 :set 'org-set-modules
310 :type
311 '(set :greedy t
312 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
313 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
314 (const :tag " crypt: Encryption of subtrees" org-crypt)
315 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
316 (const :tag " docview: Links to doc-view buffers" org-docview)
317 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
318 (const :tag " id: Global IDs for identifying entries" org-id)
319 (const :tag " info: Links to Info nodes" org-info)
320 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
321 (const :tag " habit: Track your consistency with habits" org-habit)
322 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
323 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
324 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
325 (const :tag " mew Links to Mew folders/messages" org-mew)
326 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
327 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
328 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
329 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
330 (const :tag " vm: Links to VM folders/messages" org-vm)
331 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
332 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
333 (const :tag " mouse: Additional mouse support" org-mouse)
334 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
336 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
337 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
338 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
339 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
340 (const :tag "C collector: Collect properties into tables" org-collector)
341 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
342 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
343 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
344 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
345 (const :tag "C eval: Include command output as text" org-eval)
346 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
347 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
348 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
349 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
350 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
352 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
354 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
355 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
356 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
357 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
358 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
359 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
360 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
361 (const :tag "C mtags: Support for muse-like tags" org-mtags)
362 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
363 (const :tag "C registry: A registry for Org-mode links" org-registry)
364 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
365 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
366 (const :tag "C secretary: Team management with org-mode" org-secretary)
367 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
368 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
369 (const :tag "C track: Keep up with Org-mode development" org-track)
370 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
371 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
372 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
374 (defcustom org-support-shift-select nil
375 "Non-nil means make shift-cursor commands select text when possible.
377 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
378 start selecting a region, or enlarge regions started in this way.
379 In Org-mode, in special contexts, these same keys are used for
380 other purposes, important enough to compete with shift selection.
381 Org tries to balance these needs by supporting `shift-select-mode'
382 outside these special contexts, under control of this variable.
384 The default of this variable is nil, to avoid confusing behavior. Shifted
385 cursor keys will then execute Org commands in the following contexts:
386 - on a headline, changing TODO state (left/right) and priority (up/down)
387 - on a time stamp, changing the time
388 - in a plain list item, changing the bullet type
389 - in a property definition line, switching between allowed values
390 - in the BEGIN line of a clock table (changing the time block).
391 Outside these contexts, the commands will throw an error.
393 When this variable is t and the cursor is not in a special
394 context, Org-mode will support shift-selection for making and
395 enlarging regions. To make this more effective, the bullet
396 cycling will no longer happen anywhere in an item line, but only
397 if the cursor is exactly on the bullet.
399 If you set this variable to the symbol `always', then the keys
400 will not be special in headlines, property lines, and item lines,
401 to make shift selection work there as well. If this is what you
402 want, you can use the following alternative commands: `C-c C-t'
403 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
404 can be used to switch TODO sets, `C-c -' to cycle item bullet
405 types, and properties can be edited by hand or in column view.
407 However, when the cursor is on a timestamp, shift-cursor commands
408 will still edit the time stamp - this is just too good to give up.
410 XEmacs user should have this variable set to nil, because
411 `shift-select-mode' is in Emacs 23 or later only."
412 :group 'org
413 :type '(choice
414 (const :tag "Never" nil)
415 (const :tag "When outside special context" t)
416 (const :tag "Everywhere except timestamps" always)))
418 (defcustom org-loop-over-headlines-in-active-region nil
419 "Shall some commands act upon headlines in the active region?
421 When set to `t', some commands will be performed in all headlines
422 within the active region.
424 When set to `start-level', some commands will be performed in all
425 headlines within the active region, provided that these headlines
426 are of the same level than the first one.
428 When set to a string, those commands will be performed on the
429 matching headlines within the active region. Such string must be
430 a tags/property/todo match as it is used in the agenda tags view.
432 The list of commands is: `org-schedule', `org-deadline',
433 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
434 `org-archive-to-archive-sibling'. The archiving commands skip
435 already archived entries."
436 :type '(choice (const :tag "Don't loop" nil)
437 (const :tag "All headlines in active region" t)
438 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
439 (string :tag "Tags/Property/Todo matcher"))
440 :version "24.1"
441 :group 'org-todo
442 :group 'org-archive)
444 (defgroup org-startup nil
445 "Options concerning startup of Org-mode."
446 :tag "Org Startup"
447 :group 'org)
449 (defcustom org-startup-folded t
450 "Non-nil means entering Org-mode will switch to OVERVIEW.
451 This can also be configured on a per-file basis by adding one of
452 the following lines anywhere in the buffer:
454 #+STARTUP: fold (or `overview', this is equivalent)
455 #+STARTUP: nofold (or `showall', this is equivalent)
456 #+STARTUP: content
457 #+STARTUP: showeverything"
458 :group 'org-startup
459 :type '(choice
460 (const :tag "nofold: show all" nil)
461 (const :tag "fold: overview" t)
462 (const :tag "content: all headlines" content)
463 (const :tag "show everything, even drawers" showeverything)))
465 (defcustom org-startup-truncated t
466 "Non-nil means entering Org-mode will set `truncate-lines'.
467 This is useful since some lines containing links can be very long and
468 uninteresting. Also tables look terrible when wrapped."
469 :group 'org-startup
470 :type 'boolean)
472 (defcustom org-startup-indented nil
473 "Non-nil means turn on `org-indent-mode' on startup.
474 This can also be configured on a per-file basis by adding one of
475 the following lines anywhere in the buffer:
477 #+STARTUP: indent
478 #+STARTUP: noindent"
479 :group 'org-structure
480 :type '(choice
481 (const :tag "Not" nil)
482 (const :tag "Globally (slow on startup in large files)" t)))
484 (defcustom org-use-sub-superscripts t
485 "Non-nil means interpret \"_\" and \"^\" for export.
486 When this option is turned on, you can use TeX-like syntax for sub- and
487 superscripts. Several characters after \"_\" or \"^\" will be
488 considered as a single item - so grouping with {} is normally not
489 needed. For example, the following things will be parsed as single
490 sub- or superscripts.
492 10^24 or 10^tau several digits will be considered 1 item.
493 10^-12 or 10^-tau a leading sign with digits or a word
494 x^2-y^3 will be read as x^2 - y^3, because items are
495 terminated by almost any nonword/nondigit char.
496 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
498 Still, ambiguity is possible - so when in doubt use {} to enclose the
499 sub/superscript. If you set this variable to the symbol `{}',
500 the braces are *required* in order to trigger interpretations as
501 sub/superscript. This can be helpful in documents that need \"_\"
502 frequently in plain text.
504 Not all export backends support this, but HTML does.
506 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
507 :group 'org-startup
508 :group 'org-export-translation
509 :version "24.1"
510 :type '(choice
511 (const :tag "Always interpret" t)
512 (const :tag "Only with braces" {})
513 (const :tag "Never interpret" nil)))
515 (if (fboundp 'defvaralias)
516 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
519 (defcustom org-startup-with-beamer-mode nil
520 "Non-nil means turn on `org-beamer-mode' on startup.
521 This can also be configured on a per-file basis by adding one of
522 the following lines anywhere in the buffer:
524 #+STARTUP: beamer"
525 :group 'org-startup
526 :version "24.1"
527 :type 'boolean)
529 (defcustom org-startup-align-all-tables nil
530 "Non-nil means align all tables when visiting a file.
531 This is useful when the column width in tables is forced with <N> cookies
532 in table fields. Such tables will look correct only after the first re-align.
533 This can also be configured on a per-file basis by adding one of
534 the following lines anywhere in the buffer:
535 #+STARTUP: align
536 #+STARTUP: noalign"
537 :group 'org-startup
538 :type 'boolean)
540 (defcustom org-startup-with-inline-images nil
541 "Non-nil means show inline images when loading a new Org file.
542 This can also be configured on a per-file basis by adding one of
543 the following lines anywhere in the buffer:
544 #+STARTUP: inlineimages
545 #+STARTUP: noinlineimages"
546 :group 'org-startup
547 :version "24.1"
548 :type 'boolean)
550 (defcustom org-insert-mode-line-in-empty-file nil
551 "Non-nil means insert the first line setting Org-mode in empty files.
552 When the function `org-mode' is called interactively in an empty file, this
553 normally means that the file name does not automatically trigger Org-mode.
554 To ensure that the file will always be in Org-mode in the future, a
555 line enforcing Org-mode will be inserted into the buffer, if this option
556 has been set."
557 :group 'org-startup
558 :type 'boolean)
560 (defcustom org-replace-disputed-keys nil
561 "Non-nil means use alternative key bindings for some keys.
562 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
563 These keys are also used by other packages like shift-selection-mode'
564 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
565 If you want to use Org-mode together with one of these other modes,
566 or more generally if you would like to move some Org-mode commands to
567 other keys, set this variable and configure the keys with the variable
568 `org-disputed-keys'.
570 This option is only relevant at load-time of Org-mode, and must be set
571 *before* org.el is loaded. Changing it requires a restart of Emacs to
572 become effective."
573 :group 'org-startup
574 :type 'boolean)
576 (defcustom org-use-extra-keys nil
577 "Non-nil means use extra key sequence definitions for certain commands.
578 This happens automatically if you run XEmacs or if `window-system'
579 is nil. This variable lets you do the same manually. You must
580 set it before loading org.
582 Example: on Carbon Emacs 22 running graphically, with an external
583 keyboard on a Powerbook, the default way of setting M-left might
584 not work for either Alt or ESC. Setting this variable will make
585 it work for ESC."
586 :group 'org-startup
587 :type 'boolean)
589 (if (fboundp 'defvaralias)
590 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
592 (defcustom org-disputed-keys
593 '(([(shift up)] . [(meta p)])
594 ([(shift down)] . [(meta n)])
595 ([(shift left)] . [(meta -)])
596 ([(shift right)] . [(meta +)])
597 ([(control shift right)] . [(meta shift +)])
598 ([(control shift left)] . [(meta shift -)]))
599 "Keys for which Org-mode and other modes compete.
600 This is an alist, cars are the default keys, second element specifies
601 the alternative to use when `org-replace-disputed-keys' is t.
603 Keys can be specified in any syntax supported by `define-key'.
604 The value of this option takes effect only at Org-mode's startup,
605 therefore you'll have to restart Emacs to apply it after changing."
606 :group 'org-startup
607 :type 'alist)
609 (defun org-key (key)
610 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
611 Or return the original if not disputed.
612 Also apply the translations defined in `org-xemacs-key-equivalents'."
613 (when org-replace-disputed-keys
614 (let* ((nkey (key-description key))
615 (x (org-find-if (lambda (x)
616 (equal (key-description (car x)) nkey))
617 org-disputed-keys)))
618 (setq key (if x (cdr x) key))))
619 (when (featurep 'xemacs)
620 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
621 key)
623 (defun org-find-if (predicate seq)
624 (catch 'exit
625 (while seq
626 (if (funcall predicate (car seq))
627 (throw 'exit (car seq))
628 (pop seq)))))
630 (defun org-defkey (keymap key def)
631 "Define a key, possibly translated, as returned by `org-key'."
632 (define-key keymap (org-key key) def))
634 (defcustom org-ellipsis nil
635 "The ellipsis to use in the Org-mode outline.
636 When nil, just use the standard three dots. When a string, use that instead,
637 When a face, use the standard 3 dots, but with the specified face.
638 The change affects only Org-mode (which will then use its own display table).
639 Changing this requires executing `M-x org-mode' in a buffer to become
640 effective."
641 :group 'org-startup
642 :type '(choice (const :tag "Default" nil)
643 (face :tag "Face" :value org-warning)
644 (string :tag "String" :value "...#")))
646 (defvar org-display-table nil
647 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
649 (defgroup org-keywords nil
650 "Keywords in Org-mode."
651 :tag "Org Keywords"
652 :group 'org)
654 (defcustom org-deadline-string "DEADLINE:"
655 "String to mark deadline entries.
656 A deadline is this string, followed by a time stamp. Should be a word,
657 terminated by a colon. You can insert a schedule keyword and
658 a timestamp with \\[org-deadline].
659 Changes become only effective after restarting Emacs."
660 :group 'org-keywords
661 :type 'string)
663 (defcustom org-scheduled-string "SCHEDULED:"
664 "String to mark scheduled TODO entries.
665 A schedule is this string, followed by a time stamp. Should be a word,
666 terminated by a colon. You can insert a schedule keyword and
667 a timestamp with \\[org-schedule].
668 Changes become only effective after restarting Emacs."
669 :group 'org-keywords
670 :type 'string)
672 (defcustom org-closed-string "CLOSED:"
673 "String used as the prefix for timestamps logging closing a TODO entry."
674 :group 'org-keywords
675 :type 'string)
677 (defcustom org-clock-string "CLOCK:"
678 "String used as prefix for timestamps clocking work hours on an item."
679 :group 'org-keywords
680 :type 'string)
682 (defcustom org-comment-string "COMMENT"
683 "Entries starting with this keyword will never be exported.
684 An entry can be toggled between COMMENT and normal with
685 \\[org-toggle-comment].
686 Changes become only effective after restarting Emacs."
687 :group 'org-keywords
688 :type 'string)
690 (defcustom org-quote-string "QUOTE"
691 "Entries starting with this keyword will be exported in fixed-width font.
692 Quoting applies only to the text in the entry following the headline, and does
693 not extend beyond the next headline, even if that is lower level.
694 An entry can be toggled between QUOTE and normal with
695 \\[org-toggle-fixed-width-section]."
696 :group 'org-keywords
697 :type 'string)
699 (defconst org-repeat-re
700 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
701 "Regular expression for specifying repeated events.
702 After a match, group 1 contains the repeat expression.")
704 (defgroup org-structure nil
705 "Options concerning the general structure of Org-mode files."
706 :tag "Org Structure"
707 :group 'org)
709 (defgroup org-reveal-location nil
710 "Options about how to make context of a location visible."
711 :tag "Org Reveal Location"
712 :group 'org-structure)
714 (defconst org-context-choice
715 '(choice
716 (const :tag "Always" t)
717 (const :tag "Never" nil)
718 (repeat :greedy t :tag "Individual contexts"
719 (cons
720 (choice :tag "Context"
721 (const agenda)
722 (const org-goto)
723 (const occur-tree)
724 (const tags-tree)
725 (const link-search)
726 (const mark-goto)
727 (const bookmark-jump)
728 (const isearch)
729 (const default))
730 (boolean))))
731 "Contexts for the reveal options.")
733 (defcustom org-show-hierarchy-above '((default . t))
734 "Non-nil means show full hierarchy when revealing a location.
735 Org-mode often shows locations in an org-mode file which might have
736 been invisible before. When this is set, the hierarchy of headings
737 above the exposed location is shown.
738 Turning this off for example for sparse trees makes them very compact.
739 Instead of t, this can also be an alist specifying this option for different
740 contexts. Valid contexts are
741 agenda when exposing an entry from the agenda
742 org-goto when using the command `org-goto' on key C-c C-j
743 occur-tree when using the command `org-occur' on key C-c /
744 tags-tree when constructing a sparse tree based on tags matches
745 link-search when exposing search matches associated with a link
746 mark-goto when exposing the jump goal of a mark
747 bookmark-jump when exposing a bookmark location
748 isearch when exiting from an incremental search
749 default default for all contexts not set explicitly"
750 :group 'org-reveal-location
751 :type org-context-choice)
753 (defcustom org-show-following-heading '((default . nil))
754 "Non-nil means show following heading when revealing a location.
755 Org-mode often shows locations in an org-mode file which might have
756 been invisible before. When this is set, the heading following the
757 match is shown.
758 Turning this off for example for sparse trees makes them very compact,
759 but makes it harder to edit the location of the match. In such a case,
760 use the command \\[org-reveal] to show more context.
761 Instead of t, this can also be an alist specifying this option for different
762 contexts. See `org-show-hierarchy-above' for valid contexts."
763 :group 'org-reveal-location
764 :type org-context-choice)
766 (defcustom org-show-siblings '((default . nil) (isearch t))
767 "Non-nil means show all sibling heading when revealing a location.
768 Org-mode often shows locations in an org-mode file which might have
769 been invisible before. When this is set, the sibling of the current entry
770 heading are all made visible. If `org-show-hierarchy-above' is t,
771 the same happens on each level of the hierarchy above the current entry.
773 By default this is on for the isearch context, off for all other contexts.
774 Turning this off for example for sparse trees makes them very compact,
775 but makes it harder to edit the location of the match. In such a case,
776 use the command \\[org-reveal] to show more context.
777 Instead of t, this can also be an alist specifying this option for different
778 contexts. See `org-show-hierarchy-above' for valid contexts."
779 :group 'org-reveal-location
780 :type org-context-choice)
782 (defcustom org-show-entry-below '((default . nil))
783 "Non-nil means show the entry below a headline when revealing a location.
784 Org-mode often shows locations in an org-mode file which might have
785 been invisible before. When this is set, the text below the headline that is
786 exposed is also shown.
788 By default this is off for all contexts.
789 Instead of t, this can also be an alist specifying this option for different
790 contexts. See `org-show-hierarchy-above' for valid contexts."
791 :group 'org-reveal-location
792 :type org-context-choice)
794 (defcustom org-indirect-buffer-display 'other-window
795 "How should indirect tree buffers be displayed?
796 This applies to indirect buffers created with the commands
797 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
798 Valid values are:
799 current-window Display in the current window
800 other-window Just display in another window.
801 dedicated-frame Create one new frame, and re-use it each time.
802 new-frame Make a new frame each time. Note that in this case
803 previously-made indirect buffers are kept, and you need to
804 kill these buffers yourself."
805 :group 'org-structure
806 :group 'org-agenda-windows
807 :type '(choice
808 (const :tag "In current window" current-window)
809 (const :tag "In current frame, other window" other-window)
810 (const :tag "Each time a new frame" new-frame)
811 (const :tag "One dedicated frame" dedicated-frame)))
813 (defcustom org-use-speed-commands nil
814 "Non-nil means activate single letter commands at beginning of a headline.
815 This may also be a function to test for appropriate locations where speed
816 commands should be active."
817 :group 'org-structure
818 :type '(choice
819 (const :tag "Never" nil)
820 (const :tag "At beginning of headline stars" t)
821 (function)))
823 (defcustom org-speed-commands-user nil
824 "Alist of additional speed commands.
825 This list will be checked before `org-speed-commands-default'
826 when the variable `org-use-speed-commands' is non-nil
827 and when the cursor is at the beginning of a headline.
828 The car if each entry is a string with a single letter, which must
829 be assigned to `self-insert-command' in the global map.
830 The cdr is either a command to be called interactively, a function
831 to be called, or a form to be evaluated.
832 An entry that is just a list with a single string will be interpreted
833 as a descriptive headline that will be added when listing the speed
834 commands in the Help buffer using the `?' speed command."
835 :group 'org-structure
836 :type '(repeat :value ("k" . ignore)
837 (choice :value ("k" . ignore)
838 (list :tag "Descriptive Headline" (string :tag "Headline"))
839 (cons :tag "Letter and Command"
840 (string :tag "Command letter")
841 (choice
842 (function)
843 (sexp))))))
845 (defgroup org-cycle nil
846 "Options concerning visibility cycling in Org-mode."
847 :tag "Org Cycle"
848 :group 'org-structure)
850 (defcustom org-cycle-skip-children-state-if-no-children t
851 "Non-nil means skip CHILDREN state in entries that don't have any."
852 :group 'org-cycle
853 :type 'boolean)
855 (defcustom org-cycle-max-level nil
856 "Maximum level which should still be subject to visibility cycling.
857 Levels higher than this will, for cycling, be treated as text, not a headline.
858 When `org-odd-levels-only' is set, a value of N in this variable actually
859 means 2N-1 stars as the limiting headline.
860 When nil, cycle all levels.
861 Note that the limiting level of cycling is also influenced by
862 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
863 `org-inlinetask-min-level' is, cycling will be limited to levels one less
864 than its value."
865 :group 'org-cycle
866 :type '(choice
867 (const :tag "No limit" nil)
868 (integer :tag "Maximum level")))
870 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
871 "Names of drawers. Drawers are not opened by cycling on the headline above.
872 Drawers only open with a TAB on the drawer line itself. A drawer looks like
873 this:
874 :DRAWERNAME:
875 .....
876 :END:
877 The drawer \"PROPERTIES\" is special for capturing properties through
878 the property API.
880 Drawers can be defined on the per-file basis with a line like:
882 #+DRAWERS: HIDDEN STATE PROPERTIES"
883 :group 'org-structure
884 :group 'org-cycle
885 :type '(repeat (string :tag "Drawer Name")))
887 (defcustom org-hide-block-startup nil
888 "Non-nil means entering Org-mode will fold all blocks.
889 This can also be set in on a per-file basis with
891 #+STARTUP: hideblocks
892 #+STARTUP: showblocks"
893 :group 'org-startup
894 :group 'org-cycle
895 :type 'boolean)
897 (defcustom org-cycle-global-at-bob nil
898 "Cycle globally if cursor is at beginning of buffer and not at a headline.
899 This makes it possible to do global cycling without having to use S-TAB or
900 \\[universal-argument] TAB. For this special case to work, the first line \
901 of the buffer
902 must not be a headline - it may be empty or some other text. When used in
903 this way, `org-cycle-hook' is disables temporarily, to make sure the
904 cursor stays at the beginning of the buffer.
905 When this option is nil, don't do anything special at the beginning
906 of the buffer."
907 :group 'org-cycle
908 :type 'boolean)
910 (defcustom org-cycle-level-after-item/entry-creation t
911 "Non-nil means cycle entry level or item indentation in new empty entries.
913 When the cursor is at the end of an empty headline, i.e with only stars
914 and maybe a TODO keyword, TAB will then switch the entry to become a child,
915 and then all possible ancestor states, before returning to the original state.
916 This makes data entry extremely fast: M-RET to create a new headline,
917 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
919 When the cursor is at the end of an empty plain list item, one TAB will
920 make it a subitem, two or more tabs will back up to make this an item
921 higher up in the item hierarchy."
922 :group 'org-cycle
923 :type 'boolean)
925 (defcustom org-cycle-emulate-tab t
926 "Where should `org-cycle' emulate TAB.
927 nil Never
928 white Only in completely white lines
929 whitestart Only at the beginning of lines, before the first non-white char
930 t Everywhere except in headlines
931 exc-hl-bol Everywhere except at the start of a headline
932 If TAB is used in a place where it does not emulate TAB, the current subtree
933 visibility is cycled."
934 :group 'org-cycle
935 :type '(choice (const :tag "Never" nil)
936 (const :tag "Only in completely white lines" white)
937 (const :tag "Before first char in a line" whitestart)
938 (const :tag "Everywhere except in headlines" t)
939 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
942 (defcustom org-cycle-separator-lines 2
943 "Number of empty lines needed to keep an empty line between collapsed trees.
944 If you leave an empty line between the end of a subtree and the following
945 headline, this empty line is hidden when the subtree is folded.
946 Org-mode will leave (exactly) one empty line visible if the number of
947 empty lines is equal or larger to the number given in this variable.
948 So the default 2 means at least 2 empty lines after the end of a subtree
949 are needed to produce free space between a collapsed subtree and the
950 following headline.
952 If the number is negative, and the number of empty lines is at least -N,
953 all empty lines are shown.
955 Special case: when 0, never leave empty lines in collapsed view."
956 :group 'org-cycle
957 :type 'integer)
958 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
960 (defcustom org-pre-cycle-hook nil
961 "Hook that is run before visibility cycling is happening.
962 The function(s) in this hook must accept a single argument which indicates
963 the new state that will be set right after running this hook. The
964 argument is a symbol. Before a global state change, it can have the values
965 `overview', `content', or `all'. Before a local state change, it can have
966 the values `folded', `children', or `subtree'."
967 :group 'org-cycle
968 :type 'hook)
970 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
971 org-cycle-hide-drawers
972 org-cycle-show-empty-lines
973 org-optimize-window-after-visibility-change)
974 "Hook that is run after `org-cycle' has changed the buffer visibility.
975 The function(s) in this hook must accept a single argument which indicates
976 the new state that was set by the most recent `org-cycle' command. The
977 argument is a symbol. After a global state change, it can have the values
978 `overview', `content', or `all'. After a local state change, it can have
979 the values `folded', `children', or `subtree'."
980 :group 'org-cycle
981 :type 'hook)
983 (defgroup org-edit-structure nil
984 "Options concerning structure editing in Org-mode."
985 :tag "Org Edit Structure"
986 :group 'org-structure)
988 (defcustom org-odd-levels-only nil
989 "Non-nil means skip even levels and only use odd levels for the outline.
990 This has the effect that two stars are being added/taken away in
991 promotion/demotion commands. It also influences how levels are
992 handled by the exporters.
993 Changing it requires restart of `font-lock-mode' to become effective
994 for fontification also in regions already fontified.
995 You may also set this on a per-file basis by adding one of the following
996 lines to the buffer:
998 #+STARTUP: odd
999 #+STARTUP: oddeven"
1000 :group 'org-edit-structure
1001 :group 'org-appearance
1002 :type 'boolean)
1004 (defcustom org-adapt-indentation t
1005 "Non-nil means adapt indentation to outline node level.
1007 When this variable is set, Org assumes that you write outlines by
1008 indenting text in each node to align with the headline (after the stars).
1009 The following issues are influenced by this variable:
1011 - When this is set and the *entire* text in an entry is indented, the
1012 indentation is increased by one space in a demotion command, and
1013 decreased by one in a promotion command. If any line in the entry
1014 body starts with text at column 0, indentation is not changed at all.
1016 - Property drawers and planning information is inserted indented when
1017 this variable s set. When nil, they will not be indented.
1019 - TAB indents a line relative to context. The lines below a headline
1020 will be indented when this variable is set.
1022 Note that this is all about true indentation, by adding and removing
1023 space characters. See also `org-indent.el' which does level-dependent
1024 indentation in a virtual way, i.e. at display time in Emacs."
1025 :group 'org-edit-structure
1026 :type 'boolean)
1028 (defcustom org-special-ctrl-a/e nil
1029 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1031 When t, `C-a' will bring back the cursor to the beginning of the
1032 headline text, i.e. after the stars and after a possible TODO
1033 keyword. In an item, this will be the position after bullet and
1034 check-box, if any. When the cursor is already at that position,
1035 another `C-a' will bring it to the beginning of the line.
1037 `C-e' will jump to the end of the headline, ignoring the presence
1038 of tags in the headline. A second `C-e' will then jump to the
1039 true end of the line, after any tags. This also means that, when
1040 this variable is non-nil, `C-e' also will never jump beyond the
1041 end of the heading of a folded section, i.e. not after the
1042 ellipses.
1044 When set to the symbol `reversed', the first `C-a' or `C-e' works
1045 normally, going to the true line boundary first. Only a directly
1046 following, identical keypress will bring the cursor to the
1047 special positions.
1049 This may also be a cons cell where the behavior for `C-a' and
1050 `C-e' is set separately."
1051 :group 'org-edit-structure
1052 :type '(choice
1053 (const :tag "off" nil)
1054 (const :tag "on: after stars/bullet and before tags first" t)
1055 (const :tag "reversed: true line boundary first" reversed)
1056 (cons :tag "Set C-a and C-e separately"
1057 (choice :tag "Special C-a"
1058 (const :tag "off" nil)
1059 (const :tag "on: after stars/bullet first" t)
1060 (const :tag "reversed: before stars/bullet first" reversed))
1061 (choice :tag "Special C-e"
1062 (const :tag "off" nil)
1063 (const :tag "on: before tags first" t)
1064 (const :tag "reversed: after tags first" reversed)))))
1065 (if (fboundp 'defvaralias)
1066 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1068 (defcustom org-special-ctrl-k nil
1069 "Non-nil means `C-k' will behave specially in headlines.
1070 When nil, `C-k' will call the default `kill-line' command.
1071 When t, the following will happen while the cursor is in the headline:
1073 - When the cursor is at the beginning of a headline, kill the entire
1074 line and possible the folded subtree below the line.
1075 - When in the middle of the headline text, kill the headline up to the tags.
1076 - When after the headline text, kill the tags."
1077 :group 'org-edit-structure
1078 :type 'boolean)
1080 (defcustom org-ctrl-k-protect-subtree nil
1081 "Non-nil means, do not delete a hidden subtree with C-k.
1082 When set to the symbol `error', simply throw an error when C-k is
1083 used to kill (part-of) a headline that has hidden text behind it.
1084 Any other non-nil value will result in a query to the user, if it is
1085 OK to kill that hidden subtree. When nil, kill without remorse."
1086 :group 'org-edit-structure
1087 :version "24.1"
1088 :type '(choice
1089 (const :tag "Do not protect hidden subtrees" nil)
1090 (const :tag "Protect hidden subtrees with a security query" t)
1091 (const :tag "Never kill a hidden subtree with C-k" error)))
1093 (defcustom org-catch-invisible-edits nil
1094 "Check if in invisible region before inserting or deleting a character.
1095 Valid values are:
1097 nil Do not check, so just do invisible edits.
1098 error Throw an error and do nothing.
1099 show Make point visible, and do the requested edit.
1100 show-and-error Make point visible, then throw an error and abort the edit.
1101 smart Make point visible, and do insertion/deletion if it is
1102 adjacent to visible text and the change feels predictable.
1103 Never delete a previously invisible character or add in the
1104 middle or right after an invisible region. Basically, this
1105 allows insertion and backward-delete right before ellipses.
1106 FIXME: maybe in this case we should not even show?"
1107 :group 'org-edit-structure
1108 :version "24.1"
1109 :type '(choice
1110 (const :tag "Do not check" nil)
1111 (const :tag "Throw error when trying to edit" error)
1112 (const :tag "Unhide, but do not do the edit" show-and-error)
1113 (const :tag "Show invisible part and do the edit" show)
1114 (const :tag "Be smart and do the right thing" smart)))
1116 (defcustom org-yank-folded-subtrees t
1117 "Non-nil means when yanking subtrees, fold them.
1118 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1119 it starts with a heading and all other headings in it are either children
1120 or siblings, then fold all the subtrees. However, do this only if no
1121 text after the yank would be swallowed into a folded tree by this action."
1122 :group 'org-edit-structure
1123 :type 'boolean)
1125 (defcustom org-yank-adjusted-subtrees nil
1126 "Non-nil means when yanking subtrees, adjust the level.
1127 With this setting, `org-paste-subtree' is used to insert the subtree, see
1128 this function for details."
1129 :group 'org-edit-structure
1130 :type 'boolean)
1132 (defcustom org-M-RET-may-split-line '((default . t))
1133 "Non-nil means M-RET will split the line at the cursor position.
1134 When nil, it will go to the end of the line before making a
1135 new line.
1136 You may also set this option in a different way for different
1137 contexts. Valid contexts are:
1139 headline when creating a new headline
1140 item when creating a new item
1141 table in a table field
1142 default the value to be used for all contexts not explicitly
1143 customized"
1144 :group 'org-structure
1145 :group 'org-table
1146 :type '(choice
1147 (const :tag "Always" t)
1148 (const :tag "Never" nil)
1149 (repeat :greedy t :tag "Individual contexts"
1150 (cons
1151 (choice :tag "Context"
1152 (const headline)
1153 (const item)
1154 (const table)
1155 (const default))
1156 (boolean)))))
1159 (defcustom org-insert-heading-respect-content nil
1160 "Non-nil means insert new headings after the current subtree.
1161 When nil, the new heading is created directly after the current line.
1162 The commands \\[org-insert-heading-respect-content] and
1163 \\[org-insert-todo-heading-respect-content] turn this variable on
1164 for the duration of the command."
1165 :group 'org-structure
1166 :type 'boolean)
1168 (defcustom org-blank-before-new-entry '((heading . auto)
1169 (plain-list-item . auto))
1170 "Should `org-insert-heading' leave a blank line before new heading/item?
1171 The value is an alist, with `heading' and `plain-list-item' as CAR,
1172 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1173 which case Org will look at the surrounding headings/items and try to
1174 make an intelligent decision whether to insert a blank line or not.
1176 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1177 set, the setting here is ignored and no empty line is inserted, to avoid
1178 breaking the list structure."
1179 :group 'org-edit-structure
1180 :type '(list
1181 (cons (const heading)
1182 (choice (const :tag "Never" nil)
1183 (const :tag "Always" t)
1184 (const :tag "Auto" auto)))
1185 (cons (const plain-list-item)
1186 (choice (const :tag "Never" nil)
1187 (const :tag "Always" t)
1188 (const :tag "Auto" auto)))))
1190 (defcustom org-insert-heading-hook nil
1191 "Hook being run after inserting a new heading."
1192 :group 'org-edit-structure
1193 :type 'hook)
1195 (defcustom org-enable-fixed-width-editor t
1196 "Non-nil means lines starting with \":\" are treated as fixed-width.
1197 This currently only means they are never auto-wrapped.
1198 When nil, such lines will be treated like ordinary lines.
1199 See also the QUOTE keyword."
1200 :group 'org-edit-structure
1201 :type 'boolean)
1203 (defcustom org-goto-auto-isearch t
1204 "Non-nil means typing characters in `org-goto' starts incremental search."
1205 :group 'org-edit-structure
1206 :type 'boolean)
1208 (defgroup org-sparse-trees nil
1209 "Options concerning sparse trees in Org-mode."
1210 :tag "Org Sparse Trees"
1211 :group 'org-structure)
1213 (defcustom org-highlight-sparse-tree-matches t
1214 "Non-nil means highlight all matches that define a sparse tree.
1215 The highlights will automatically disappear the next time the buffer is
1216 changed by an edit command."
1217 :group 'org-sparse-trees
1218 :type 'boolean)
1220 (defcustom org-remove-highlights-with-change t
1221 "Non-nil means any change to the buffer will remove temporary highlights.
1222 Such highlights are created by `org-occur' and `org-clock-display'.
1223 When nil, `C-c C-c needs to be used to get rid of the highlights.
1224 The highlights created by `org-preview-latex-fragment' always need
1225 `C-c C-c' to be removed."
1226 :group 'org-sparse-trees
1227 :group 'org-time
1228 :type 'boolean)
1231 (defcustom org-occur-hook '(org-first-headline-recenter)
1232 "Hook that is run after `org-occur' has constructed a sparse tree.
1233 This can be used to recenter the window to show as much of the structure
1234 as possible."
1235 :group 'org-sparse-trees
1236 :type 'hook)
1238 (defgroup org-imenu-and-speedbar nil
1239 "Options concerning imenu and speedbar in Org-mode."
1240 :tag "Org Imenu and Speedbar"
1241 :group 'org-structure)
1243 (defcustom org-imenu-depth 2
1244 "The maximum level for Imenu access to Org-mode headlines.
1245 This also applied for speedbar access."
1246 :group 'org-imenu-and-speedbar
1247 :type 'integer)
1249 (defgroup org-table nil
1250 "Options concerning tables in Org-mode."
1251 :tag "Org Table"
1252 :group 'org)
1254 (defcustom org-enable-table-editor 'optimized
1255 "Non-nil means lines starting with \"|\" are handled by the table editor.
1256 When nil, such lines will be treated like ordinary lines.
1258 When equal to the symbol `optimized', the table editor will be optimized to
1259 do the following:
1260 - Automatic overwrite mode in front of whitespace in table fields.
1261 This makes the structure of the table stay in tact as long as the edited
1262 field does not exceed the column width.
1263 - Minimize the number of realigns. Normally, the table is aligned each time
1264 TAB or RET are pressed to move to another field. With optimization this
1265 happens only if changes to a field might have changed the column width.
1266 Optimization requires replacing the functions `self-insert-command',
1267 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1268 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1269 very good at guessing when a re-align will be necessary, but you can always
1270 force one with \\[org-ctrl-c-ctrl-c].
1272 If you would like to use the optimized version in Org-mode, but the
1273 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1275 This variable can be used to turn on and off the table editor during a session,
1276 but in order to toggle optimization, a restart is required.
1278 See also the variable `org-table-auto-blank-field'."
1279 :group 'org-table
1280 :type '(choice
1281 (const :tag "off" nil)
1282 (const :tag "on" t)
1283 (const :tag "on, optimized" optimized)))
1285 (defcustom org-self-insert-cluster-for-undo t
1286 "Non-nil means cluster self-insert commands for undo when possible.
1287 If this is set, then, like in the Emacs command loop, 20 consecutive
1288 characters will be undone together.
1289 This is configurable, because there is some impact on typing performance."
1290 :group 'org-table
1291 :type 'boolean)
1293 (defcustom org-table-tab-recognizes-table.el t
1294 "Non-nil means TAB will automatically notice a table.el table.
1295 When it sees such a table, it moves point into it and - if necessary -
1296 calls `table-recognize-table'."
1297 :group 'org-table-editing
1298 :type 'boolean)
1300 (defgroup org-link nil
1301 "Options concerning links in Org-mode."
1302 :tag "Org Link"
1303 :group 'org)
1305 (defvar org-link-abbrev-alist-local nil
1306 "Buffer-local version of `org-link-abbrev-alist', which see.
1307 The value of this is taken from the #+LINK lines.")
1308 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1310 (defcustom org-link-abbrev-alist nil
1311 "Alist of link abbreviations.
1312 The car of each element is a string, to be replaced at the start of a link.
1313 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1314 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1316 [[linkkey:tag][description]]
1318 The 'linkkey' must be a word word, starting with a letter, followed
1319 by letters, numbers, '-' or '_'.
1321 If REPLACE is a string, the tag will simply be appended to create the link.
1322 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1323 the placeholder \"%h\" will cause a url-encoded version of the tag to
1324 be inserted at that point (see the function `url-hexify-string').
1326 REPLACE may also be a function that will be called with the tag as the
1327 only argument to create the link, which should be returned as a string.
1329 See the manual for examples."
1330 :group 'org-link
1331 :type '(repeat
1332 (cons
1333 (string :tag "Protocol")
1334 (choice
1335 (string :tag "Format")
1336 (function)))))
1338 (defcustom org-descriptive-links t
1339 "Non-nil means Org will display descriptive links.
1340 E.g. [[http://orgmode.org][Org website]] will be displayed as
1341 \"Org Website\", hiding the link itself and just displaying its
1342 description. When set to `nil', Org will display the full links
1343 literally.
1345 You can interactively set the value of this variable by calling
1346 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1347 :group 'org-link
1348 :type 'boolean)
1350 (defcustom org-link-file-path-type 'adaptive
1351 "How the path name in file links should be stored.
1352 Valid values are:
1354 relative Relative to the current directory, i.e. the directory of the file
1355 into which the link is being inserted.
1356 absolute Absolute path, if possible with ~ for home directory.
1357 noabbrev Absolute path, no abbreviation of home directory.
1358 adaptive Use relative path for files in the current directory and sub-
1359 directories of it. For other files, use an absolute path."
1360 :group 'org-link
1361 :type '(choice
1362 (const relative)
1363 (const absolute)
1364 (const noabbrev)
1365 (const adaptive)))
1367 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1368 "Types of links that should be activated in Org-mode files.
1369 This is a list of symbols, each leading to the activation of a certain link
1370 type. In principle, it does not hurt to turn on most link types - there may
1371 be a small gain when turning off unused link types. The types are:
1373 bracket The recommended [[link][description]] or [[link]] links with hiding.
1374 angle Links in angular brackets that may contain whitespace like
1375 <bbdb:Carsten Dominik>.
1376 plain Plain links in normal text, no whitespace, like http://google.com.
1377 radio Text that is matched by a radio target, see manual for details.
1378 tag Tag settings in a headline (link to tag search).
1379 date Time stamps (link to calendar).
1380 footnote Footnote labels.
1382 Changing this variable requires a restart of Emacs to become effective."
1383 :group 'org-link
1384 :type '(set :greedy t
1385 (const :tag "Double bracket links" bracket)
1386 (const :tag "Angular bracket links" angle)
1387 (const :tag "Plain text links" plain)
1388 (const :tag "Radio target matches" radio)
1389 (const :tag "Tags" tag)
1390 (const :tag "Timestamps" date)
1391 (const :tag "Footnotes" footnote)))
1393 (defcustom org-make-link-description-function nil
1394 "Function to use to generate link descriptions from links.
1395 If nil the link location will be used. This function must take
1396 two parameters; the first is the link and the second the
1397 description `org-insert-link' has generated, and should return the
1398 description to use."
1399 :group 'org-link
1400 :type 'function)
1402 (defgroup org-link-store nil
1403 "Options concerning storing links in Org-mode."
1404 :tag "Org Store Link"
1405 :group 'org-link)
1407 (defcustom org-email-link-description-format "Email %c: %.30s"
1408 "Format of the description part of a link to an email or usenet message.
1409 The following %-escapes will be replaced by corresponding information:
1411 %F full \"From\" field
1412 %f name, taken from \"From\" field, address if no name
1413 %T full \"To\" field
1414 %t first name in \"To\" field, address if no name
1415 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1416 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1417 %s subject
1418 %d date
1419 %m message-id.
1421 You may use normal field width specification between the % and the letter.
1422 This is for example useful to limit the length of the subject.
1424 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1425 :group 'org-link-store
1426 :type 'string)
1428 (defcustom org-from-is-user-regexp
1429 (let (r1 r2)
1430 (when (and user-mail-address (not (string= user-mail-address "")))
1431 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1432 (when (and user-full-name (not (string= user-full-name "")))
1433 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1434 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1435 "Regexp matched against the \"From:\" header of an email or usenet message.
1436 It should match if the message is from the user him/herself."
1437 :group 'org-link-store
1438 :type 'regexp)
1440 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1441 "Non-nil means storing a link to an Org file will use entry IDs.
1443 Note that before this variable is even considered, org-id must be loaded,
1444 so please customize `org-modules' and turn it on.
1446 The variable can have the following values:
1448 t Create an ID if needed to make a link to the current entry.
1450 create-if-interactive
1451 If `org-store-link' is called directly (interactively, as a user
1452 command), do create an ID to support the link. But when doing the
1453 job for remember, only use the ID if it already exists. The
1454 purpose of this setting is to avoid proliferation of unwanted
1455 IDs, just because you happen to be in an Org file when you
1456 call `org-remember' that automatically and preemptively
1457 creates a link. If you do want to get an ID link in a remember
1458 template to an entry not having an ID, create it first by
1459 explicitly creating a link to it, using `C-c C-l' first.
1461 create-if-interactive-and-no-custom-id
1462 Like create-if-interactive, but do not create an ID if there is
1463 a CUSTOM_ID property defined in the entry. This is the default.
1465 use-existing
1466 Use existing ID, do not create one.
1468 nil Never use an ID to make a link, instead link using a text search for
1469 the headline text."
1470 :group 'org-link-store
1471 :type '(choice
1472 (const :tag "Create ID to make link" t)
1473 (const :tag "Create if storing link interactively"
1474 create-if-interactive)
1475 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1476 create-if-interactive-and-no-custom-id)
1477 (const :tag "Only use existing" use-existing)
1478 (const :tag "Do not use ID to create link" nil)))
1480 (defcustom org-context-in-file-links t
1481 "Non-nil means file links from `org-store-link' contain context.
1482 A search string will be added to the file name with :: as separator and
1483 used to find the context when the link is activated by the command
1484 `org-open-at-point'. When this option is t, the entire active region
1485 will be placed in the search string of the file link. If set to a
1486 positive integer, only the first n lines of context will be stored.
1488 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1489 negates this setting for the duration of the command."
1490 :group 'org-link-store
1491 :type '(choice boolean integer))
1493 (defcustom org-keep-stored-link-after-insertion nil
1494 "Non-nil means keep link in list for entire session.
1496 The command `org-store-link' adds a link pointing to the current
1497 location to an internal list. These links accumulate during a session.
1498 The command `org-insert-link' can be used to insert links into any
1499 Org-mode file (offering completion for all stored links). When this
1500 option is nil, every link which has been inserted once using \\[org-insert-link]
1501 will be removed from the list, to make completing the unused links
1502 more efficient."
1503 :group 'org-link-store
1504 :type 'boolean)
1506 (defgroup org-link-follow nil
1507 "Options concerning following links in Org-mode."
1508 :tag "Org Follow Link"
1509 :group 'org-link)
1511 (defcustom org-link-translation-function nil
1512 "Function to translate links with different syntax to Org syntax.
1513 This can be used to translate links created for example by the Planner
1514 or emacs-wiki packages to Org syntax.
1515 The function must accept two parameters, a TYPE containing the link
1516 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1517 which is everything after the link protocol. It should return a cons
1518 with possibly modified values of type and path.
1519 Org contains a function for this, so if you set this variable to
1520 `org-translate-link-from-planner', you should be able follow many
1521 links created by planner."
1522 :group 'org-link-follow
1523 :type 'function)
1525 (defcustom org-follow-link-hook nil
1526 "Hook that is run after a link has been followed."
1527 :group 'org-link-follow
1528 :type 'hook)
1530 (defcustom org-tab-follows-link nil
1531 "Non-nil means on links TAB will follow the link.
1532 Needs to be set before org.el is loaded.
1533 This really should not be used, it does not make sense, and the
1534 implementation is bad."
1535 :group 'org-link-follow
1536 :type 'boolean)
1538 (defcustom org-return-follows-link nil
1539 "Non-nil means on links RET will follow the link."
1540 :group 'org-link-follow
1541 :type 'boolean)
1543 (defcustom org-mouse-1-follows-link
1544 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1545 "Non-nil means mouse-1 on a link will follow the link.
1546 A longer mouse click will still set point. Does not work on XEmacs.
1547 Needs to be set before org.el is loaded."
1548 :group 'org-link-follow
1549 :type 'boolean)
1551 (defcustom org-mark-ring-length 4
1552 "Number of different positions to be recorded in the ring.
1553 Changing this requires a restart of Emacs to work correctly."
1554 :group 'org-link-follow
1555 :type 'integer)
1557 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1558 "Non-nil means internal links in Org files must exactly match a headline.
1559 When nil, the link search tries to match a phrase with all words
1560 in the search text."
1561 :group 'org-link-follow
1562 :version "24.1"
1563 :type '(choice
1564 (const :tag "Use fuzzy text search" nil)
1565 (const :tag "Match only exact headline" t)
1566 (const :tag "Match exact headline or query to create it"
1567 query-to-create)))
1569 (defcustom org-link-frame-setup
1570 '((vm . vm-visit-folder-other-frame)
1571 (vm-imap . vm-visit-imap-folder-other-frame)
1572 (gnus . org-gnus-no-new-news)
1573 (file . find-file-other-window)
1574 (wl . wl-other-frame))
1575 "Setup the frame configuration for following links.
1576 When following a link with Emacs, it may often be useful to display
1577 this link in another window or frame. This variable can be used to
1578 set this up for the different types of links.
1579 For VM, use any of
1580 `vm-visit-folder'
1581 `vm-visit-folder-other-window'
1582 `vm-visit-folder-other-frame'
1583 For Gnus, use any of
1584 `gnus'
1585 `gnus-other-frame'
1586 `org-gnus-no-new-news'
1587 For FILE, use any of
1588 `find-file'
1589 `find-file-other-window'
1590 `find-file-other-frame'
1591 For Wanderlust use any of
1592 `wl'
1593 `wl-other-frame'
1594 For the calendar, use the variable `calendar-setup'.
1595 For BBDB, it is currently only possible to display the matches in
1596 another window."
1597 :group 'org-link-follow
1598 :type '(list
1599 (cons (const vm)
1600 (choice
1601 (const vm-visit-folder)
1602 (const vm-visit-folder-other-window)
1603 (const vm-visit-folder-other-frame)))
1604 (cons (const gnus)
1605 (choice
1606 (const gnus)
1607 (const gnus-other-frame)
1608 (const org-gnus-no-new-news)))
1609 (cons (const file)
1610 (choice
1611 (const find-file)
1612 (const find-file-other-window)
1613 (const find-file-other-frame)))
1614 (cons (const wl)
1615 (choice
1616 (const wl)
1617 (const wl-other-frame)))))
1619 (defcustom org-display-internal-link-with-indirect-buffer nil
1620 "Non-nil means use indirect buffer to display infile links.
1621 Activating internal links (from one location in a file to another location
1622 in the same file) normally just jumps to the location. When the link is
1623 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1624 is displayed in
1625 another window. When this option is set, the other window actually displays
1626 an indirect buffer clone of the current buffer, to avoid any visibility
1627 changes to the current buffer."
1628 :group 'org-link-follow
1629 :type 'boolean)
1631 (defcustom org-open-non-existing-files nil
1632 "Non-nil means `org-open-file' will open non-existing files.
1633 When nil, an error will be generated.
1634 This variable applies only to external applications because they
1635 might choke on non-existing files. If the link is to a file that
1636 will be opened in Emacs, the variable is ignored."
1637 :group 'org-link-follow
1638 :type 'boolean)
1640 (defcustom org-open-directory-means-index-dot-org nil
1641 "Non-nil means a link to a directory really means to index.org.
1642 When nil, following a directory link will run dired or open a finder/explorer
1643 window on that directory."
1644 :group 'org-link-follow
1645 :type 'boolean)
1647 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1648 "Function and arguments to call for following mailto links.
1649 This is a list with the first element being a Lisp function, and the
1650 remaining elements being arguments to the function. In string arguments,
1651 %a will be replaced by the address, and %s will be replaced by the subject
1652 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1653 :group 'org-link-follow
1654 :type '(choice
1655 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1656 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1657 (const :tag "message-mail" (message-mail "%a" "%s"))
1658 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1660 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1661 "Non-nil means ask for confirmation before executing shell links.
1662 Shell links can be dangerous: just think about a link
1664 [[shell:rm -rf ~/*][Google Search]]
1666 This link would show up in your Org-mode document as \"Google Search\",
1667 but really it would remove your entire home directory.
1668 Therefore we advise against setting this variable to nil.
1669 Just change it to `y-or-n-p' if you want to confirm with a
1670 single keystroke rather than having to type \"yes\"."
1671 :group 'org-link-follow
1672 :type '(choice
1673 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1674 (const :tag "with y-or-n (faster)" y-or-n-p)
1675 (const :tag "no confirmation (dangerous)" nil)))
1676 (put 'org-confirm-shell-link-function
1677 'safe-local-variable
1678 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1680 (defcustom org-confirm-shell-link-not-regexp ""
1681 "A regexp to skip confirmation for shell links."
1682 :group 'org-link-follow
1683 :version "24.1"
1684 :type 'regexp)
1686 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1687 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1688 Elisp links can be dangerous: just think about a link
1690 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1692 This link would show up in your Org-mode document as \"Google Search\",
1693 but really it would remove your entire home directory.
1694 Therefore we advise against setting this variable to nil.
1695 Just change it to `y-or-n-p' if you want to confirm with a
1696 single keystroke rather than having to type \"yes\"."
1697 :group 'org-link-follow
1698 :type '(choice
1699 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1700 (const :tag "with y-or-n (faster)" y-or-n-p)
1701 (const :tag "no confirmation (dangerous)" nil)))
1702 (put 'org-confirm-shell-link-function
1703 'safe-local-variable
1704 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1706 (defcustom org-confirm-elisp-link-not-regexp ""
1707 "A regexp to skip confirmation for Elisp links."
1708 :group 'org-link-follow
1709 :version "24.1"
1710 :type 'regexp)
1712 (defconst org-file-apps-defaults-gnu
1713 '((remote . emacs)
1714 (system . mailcap)
1715 (t . mailcap))
1716 "Default file applications on a UNIX or GNU/Linux system.
1717 See `org-file-apps'.")
1719 (defconst org-file-apps-defaults-macosx
1720 '((remote . emacs)
1721 (t . "open %s")
1722 (system . "open %s")
1723 ("ps.gz" . "gv %s")
1724 ("eps.gz" . "gv %s")
1725 ("dvi" . "xdvi %s")
1726 ("fig" . "xfig %s"))
1727 "Default file applications on a MacOS X system.
1728 The system \"open\" is known as a default, but we use X11 applications
1729 for some files for which the OS does not have a good default.
1730 See `org-file-apps'.")
1732 (defconst org-file-apps-defaults-windowsnt
1733 (list
1734 '(remote . emacs)
1735 (cons t
1736 (list (if (featurep 'xemacs)
1737 'mswindows-shell-execute
1738 'w32-shell-execute)
1739 "open" 'file))
1740 (cons 'system
1741 (list (if (featurep 'xemacs)
1742 'mswindows-shell-execute
1743 'w32-shell-execute)
1744 "open" 'file)))
1745 "Default file applications on a Windows NT system.
1746 The system \"open\" is used for most files.
1747 See `org-file-apps'.")
1749 (defcustom org-file-apps
1751 (auto-mode . emacs)
1752 ("\\.mm\\'" . default)
1753 ("\\.x?html?\\'" . default)
1754 ("\\.pdf\\'" . default)
1756 "External applications for opening `file:path' items in a document.
1757 Org-mode uses system defaults for different file types, but
1758 you can use this variable to set the application for a given file
1759 extension. The entries in this list are cons cells where the car identifies
1760 files and the cdr the corresponding command. Possible values for the
1761 file identifier are
1762 \"string\" A string as a file identifier can be interpreted in different
1763 ways, depending on its contents:
1765 - Alphanumeric characters only:
1766 Match links with this file extension.
1767 Example: (\"pdf\" . \"evince %s\")
1768 to open PDFs with evince.
1770 - Regular expression: Match links where the
1771 filename matches the regexp. If you want to
1772 use groups here, use shy groups.
1774 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1775 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1776 to open *.html and *.xhtml with firefox.
1778 - Regular expression which contains (non-shy) groups:
1779 Match links where the whole link, including \"::\", and
1780 anything after that, matches the regexp.
1781 In a custom command string, %1, %2, etc. are replaced with
1782 the parts of the link that were matched by the groups.
1783 For backwards compatibility, if a command string is given
1784 that does not use any of the group matches, this case is
1785 handled identically to the second one (i.e. match against
1786 file name only).
1787 In a custom lisp form, you can access the group matches with
1788 (match-string n link).
1790 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1791 to open [[file:document.pdf::5]] with evince at page 5.
1793 `directory' Matches a directory
1794 `remote' Matches a remote file, accessible through tramp or efs.
1795 Remote files most likely should be visited through Emacs
1796 because external applications cannot handle such paths.
1797 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1798 so all files Emacs knows how to handle. Using this with
1799 command `emacs' will open most files in Emacs. Beware that this
1800 will also open html files inside Emacs, unless you add
1801 (\"html\" . default) to the list as well.
1802 t Default for files not matched by any of the other options.
1803 `system' The system command to open files, like `open' on Windows
1804 and Mac OS X, and mailcap under GNU/Linux. This is the command
1805 that will be selected if you call `C-c C-o' with a double
1806 \\[universal-argument] \\[universal-argument] prefix.
1808 Possible values for the command are:
1809 `emacs' The file will be visited by the current Emacs process.
1810 `default' Use the default application for this file type, which is the
1811 association for t in the list, most likely in the system-specific
1812 part.
1813 This can be used to overrule an unwanted setting in the
1814 system-specific variable.
1815 `system' Use the system command for opening files, like \"open\".
1816 This command is specified by the entry whose car is `system'.
1817 Most likely, the system-specific version of this variable
1818 does define this command, but you can overrule/replace it
1819 here.
1820 string A command to be executed by a shell; %s will be replaced
1821 by the path to the file.
1822 sexp A Lisp form which will be evaluated. The file path will
1823 be available in the Lisp variable `file'.
1824 For more examples, see the system specific constants
1825 `org-file-apps-defaults-macosx'
1826 `org-file-apps-defaults-windowsnt'
1827 `org-file-apps-defaults-gnu'."
1828 :group 'org-link-follow
1829 :type '(repeat
1830 (cons (choice :value ""
1831 (string :tag "Extension")
1832 (const :tag "System command to open files" system)
1833 (const :tag "Default for unrecognized files" t)
1834 (const :tag "Remote file" remote)
1835 (const :tag "Links to a directory" directory)
1836 (const :tag "Any files that have Emacs modes"
1837 auto-mode))
1838 (choice :value ""
1839 (const :tag "Visit with Emacs" emacs)
1840 (const :tag "Use default" default)
1841 (const :tag "Use the system command" system)
1842 (string :tag "Command")
1843 (sexp :tag "Lisp form")))))
1845 (defcustom org-doi-server-url "http://dx.doi.org/"
1846 "The URL of the DOI server."
1847 :type 'string
1848 :version "24.2"
1849 :group 'org-link-follow)
1851 (defgroup org-refile nil
1852 "Options concerning refiling entries in Org-mode."
1853 :tag "Org Refile"
1854 :group 'org)
1856 (defcustom org-directory "~/org"
1857 "Directory with org files.
1858 This is just a default location to look for Org files. There is no need
1859 at all to put your files into this directory. It is only used in the
1860 following situations:
1862 1. When a remember template specifies a target file that is not an
1863 absolute path. The path will then be interpreted relative to
1864 `org-directory'
1865 2. When a remember note is filed away in an interactive way (when exiting the
1866 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1867 with `org-directory' as the default path."
1868 :group 'org-refile
1869 :group 'org-remember
1870 :type 'directory)
1872 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1873 "Default target for storing notes.
1874 Used as a fall back file for org-remember.el and org-capture.el, for
1875 templates that do not specify a target file."
1876 :group 'org-refile
1877 :group 'org-remember
1878 :type '(choice
1879 (const :tag "Default from remember-data-file" nil)
1880 file))
1882 (defcustom org-goto-interface 'outline
1883 "The default interface to be used for `org-goto'.
1884 Allowed values are:
1885 outline The interface shows an outline of the relevant file
1886 and the correct heading is found by moving through
1887 the outline or by searching with incremental search.
1888 outline-path-completion Headlines in the current buffer are offered via
1889 completion. This is the interface also used by
1890 the refile command."
1891 :group 'org-refile
1892 :type '(choice
1893 (const :tag "Outline" outline)
1894 (const :tag "Outline-path-completion" outline-path-completion)))
1896 (defcustom org-goto-max-level 5
1897 "Maximum target level when running `org-goto' with refile interface."
1898 :group 'org-refile
1899 :type 'integer)
1901 (defcustom org-reverse-note-order nil
1902 "Non-nil means store new notes at the beginning of a file or entry.
1903 When nil, new notes will be filed to the end of a file or entry.
1904 This can also be a list with cons cells of regular expressions that
1905 are matched against file names, and values."
1906 :group 'org-remember
1907 :group 'org-refile
1908 :type '(choice
1909 (const :tag "Reverse always" t)
1910 (const :tag "Reverse never" nil)
1911 (repeat :tag "By file name regexp"
1912 (cons regexp boolean))))
1914 (defcustom org-log-refile nil
1915 "Information to record when a task is refiled.
1917 Possible values are:
1919 nil Don't add anything
1920 time Add a time stamp to the task
1921 note Prompt for a note and add it with template `org-log-note-headings'
1923 This option can also be set with on a per-file-basis with
1925 #+STARTUP: nologrefile
1926 #+STARTUP: logrefile
1927 #+STARTUP: lognoterefile
1929 You can have local logging settings for a subtree by setting the LOGGING
1930 property to one or more of these keywords.
1932 When bulk-refiling from the agenda, the value `note' is forbidden and
1933 will temporarily be changed to `time'."
1934 :group 'org-refile
1935 :group 'org-progress
1936 :version "24.1"
1937 :type '(choice
1938 (const :tag "No logging" nil)
1939 (const :tag "Record timestamp" time)
1940 (const :tag "Record timestamp with note." note)))
1942 (defcustom org-refile-targets nil
1943 "Targets for refiling entries with \\[org-refile].
1944 This is a list of cons cells. Each cell contains:
1945 - a specification of the files to be considered, either a list of files,
1946 or a symbol whose function or variable value will be used to retrieve
1947 a file name or a list of file names. If you use `org-agenda-files' for
1948 that, all agenda files will be scanned for targets. Nil means consider
1949 headings in the current buffer.
1950 - A specification of how to find candidate refile targets. This may be
1951 any of:
1952 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1953 This tag has to be present in all target headlines, inheritance will
1954 not be considered.
1955 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1956 todo keyword.
1957 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1958 headlines that are refiling targets.
1959 - a cons cell (:level . N). Any headline of level N is considered a target.
1960 Note that, when `org-odd-levels-only' is set, level corresponds to
1961 order in hierarchy, not to the number of stars.
1962 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1963 Note that, when `org-odd-levels-only' is set, level corresponds to
1964 order in hierarchy, not to the number of stars.
1966 Each element of this list generates a set of possible targets.
1967 The union of these sets is presented (with completion) to
1968 the user by `org-refile'.
1970 You can set the variable `org-refile-target-verify-function' to a function
1971 to verify each headline found by the simple criteria above.
1973 When this variable is nil, all top-level headlines in the current buffer
1974 are used, equivalent to the value `((nil . (:level . 1))'."
1975 :group 'org-refile
1976 :type '(repeat
1977 (cons
1978 (choice :value org-agenda-files
1979 (const :tag "All agenda files" org-agenda-files)
1980 (const :tag "Current buffer" nil)
1981 (function) (variable) (file))
1982 (choice :tag "Identify target headline by"
1983 (cons :tag "Specific tag" (const :value :tag) (string))
1984 (cons :tag "TODO keyword" (const :value :todo) (string))
1985 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1986 (cons :tag "Level number" (const :value :level) (integer))
1987 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1989 (defcustom org-refile-target-verify-function nil
1990 "Function to verify if the headline at point should be a refile target.
1991 The function will be called without arguments, with point at the
1992 beginning of the headline. It should return t and leave point
1993 where it is if the headline is a valid target for refiling.
1995 If the target should not be selected, the function must return nil.
1996 In addition to this, it may move point to a place from where the search
1997 should be continued. For example, the function may decide that the entire
1998 subtree of the current entry should be excluded and move point to the end
1999 of the subtree."
2000 :group 'org-refile
2001 :type 'function)
2003 (defcustom org-refile-use-cache nil
2004 "Non-nil means cache refile targets to speed up the process.
2005 The cache for a particular file will be updated automatically when
2006 the buffer has been killed, or when any of the marker used for flagging
2007 refile targets no longer points at a live buffer.
2008 If you have added new entries to a buffer that might themselves be targets,
2009 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2010 find that easier, `C-u C-u C-u C-c C-w'."
2011 :group 'org-refile
2012 :version "24.1"
2013 :type 'boolean)
2015 (defcustom org-refile-use-outline-path nil
2016 "Non-nil means provide refile targets as paths.
2017 So a level 3 headline will be available as level1/level2/level3.
2019 When the value is `file', also include the file name (without directory)
2020 into the path. In this case, you can also stop the completion after
2021 the file name, to get entries inserted as top level in the file.
2023 When `full-file-path', include the full file path."
2024 :group 'org-refile
2025 :type '(choice
2026 (const :tag "Not" nil)
2027 (const :tag "Yes" t)
2028 (const :tag "Start with file name" file)
2029 (const :tag "Start with full file path" full-file-path)))
2031 (defcustom org-outline-path-complete-in-steps t
2032 "Non-nil means complete the outline path in hierarchical steps.
2033 When Org-mode uses the refile interface to select an outline path
2034 \(see variable `org-refile-use-outline-path'), the completion of
2035 the path can be done is a single go, or if can be done in steps down
2036 the headline hierarchy. Going in steps is probably the best if you
2037 do not use a special completion package like `ido' or `icicles'.
2038 However, when using these packages, going in one step can be very
2039 fast, while still showing the whole path to the entry."
2040 :group 'org-refile
2041 :type 'boolean)
2043 (defcustom org-refile-allow-creating-parent-nodes nil
2044 "Non-nil means allow to create new nodes as refile targets.
2045 New nodes are then created by adding \"/new node name\" to the completion
2046 of an existing node. When the value of this variable is `confirm',
2047 new node creation must be confirmed by the user (recommended)
2048 When nil, the completion must match an existing entry.
2050 Note that, if the new heading is not seen by the criteria
2051 listed in `org-refile-targets', multiple instances of the same
2052 heading would be created by trying again to file under the new
2053 heading."
2054 :group 'org-refile
2055 :type '(choice
2056 (const :tag "Never" nil)
2057 (const :tag "Always" t)
2058 (const :tag "Prompt for confirmation" confirm)))
2060 (defcustom org-refile-active-region-within-subtree nil
2061 "Non-nil means also refile active region within a subtree.
2063 By default `org-refile' doesn't allow refiling regions if they
2064 don't contain a set of subtrees, but it might be convenient to
2065 do so sometimes: in that case, the first line of the region is
2066 converted to a headline before refiling."
2067 :group 'org-refile
2068 :version "24.1"
2069 :type 'boolean)
2071 (defgroup org-todo nil
2072 "Options concerning TODO items in Org-mode."
2073 :tag "Org TODO"
2074 :group 'org)
2076 (defgroup org-progress nil
2077 "Options concerning Progress logging in Org-mode."
2078 :tag "Org Progress"
2079 :group 'org-time)
2081 (defvar org-todo-interpretation-widgets
2082 '((:tag "Sequence (cycling hits every state)" sequence)
2083 (:tag "Type (cycling directly to DONE)" type))
2084 "The available interpretation symbols for customizing `org-todo-keywords'.
2085 Interested libraries should add to this list.")
2087 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2088 "List of TODO entry keyword sequences and their interpretation.
2089 \\<org-mode-map>This is a list of sequences.
2091 Each sequence starts with a symbol, either `sequence' or `type',
2092 indicating if the keywords should be interpreted as a sequence of
2093 action steps, or as different types of TODO items. The first
2094 keywords are states requiring action - these states will select a headline
2095 for inclusion into the global TODO list Org-mode produces. If one of
2096 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2097 signify that no further action is necessary. If \"|\" is not found,
2098 the last keyword is treated as the only DONE state of the sequence.
2100 The command \\[org-todo] cycles an entry through these states, and one
2101 additional state where no keyword is present. For details about this
2102 cycling, see the manual.
2104 TODO keywords and interpretation can also be set on a per-file basis with
2105 the special #+SEQ_TODO and #+TYP_TODO lines.
2107 Each keyword can optionally specify a character for fast state selection
2108 \(in combination with the variable `org-use-fast-todo-selection')
2109 and specifiers for state change logging, using the same syntax
2110 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2111 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2112 indicates to record a time stamp each time this state is selected.
2114 Each keyword may also specify if a timestamp or a note should be
2115 recorded when entering or leaving the state, by adding additional
2116 characters in the parenthesis after the keyword. This looks like this:
2117 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2118 record only the time of the state change. With X and Y being either
2119 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2120 Y when leaving the state if and only if the *target* state does not
2121 define X. You may omit any of the fast-selection key or X or /Y,
2122 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2124 For backward compatibility, this variable may also be just a list
2125 of keywords - in this case the interpretation (sequence or type) will be
2126 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2127 :group 'org-todo
2128 :group 'org-keywords
2129 :type '(choice
2130 (repeat :tag "Old syntax, just keywords"
2131 (string :tag "Keyword"))
2132 (repeat :tag "New syntax"
2133 (cons
2134 (choice
2135 :tag "Interpretation"
2136 ;;Quick and dirty way to see
2137 ;;`org-todo-interpretations'. This takes the
2138 ;;place of item arguments
2139 :convert-widget
2140 (lambda (widget)
2141 (widget-put widget
2142 :args (mapcar
2143 #'(lambda (x)
2144 (widget-convert
2145 (cons 'const x)))
2146 org-todo-interpretation-widgets))
2147 widget))
2148 (repeat
2149 (string :tag "Keyword"))))))
2151 (defvar org-todo-keywords-1 nil
2152 "All TODO and DONE keywords active in a buffer.")
2153 (make-variable-buffer-local 'org-todo-keywords-1)
2154 (defvar org-todo-keywords-for-agenda nil)
2155 (defvar org-done-keywords-for-agenda nil)
2156 (defvar org-drawers-for-agenda nil)
2157 (defvar org-todo-keyword-alist-for-agenda nil)
2158 (defvar org-tag-alist-for-agenda nil)
2159 (defvar org-agenda-contributing-files nil)
2160 (defvar org-not-done-keywords nil)
2161 (make-variable-buffer-local 'org-not-done-keywords)
2162 (defvar org-done-keywords nil)
2163 (make-variable-buffer-local 'org-done-keywords)
2164 (defvar org-todo-heads nil)
2165 (make-variable-buffer-local 'org-todo-heads)
2166 (defvar org-todo-sets nil)
2167 (make-variable-buffer-local 'org-todo-sets)
2168 (defvar org-todo-log-states nil)
2169 (make-variable-buffer-local 'org-todo-log-states)
2170 (defvar org-todo-kwd-alist nil)
2171 (make-variable-buffer-local 'org-todo-kwd-alist)
2172 (defvar org-todo-key-alist nil)
2173 (make-variable-buffer-local 'org-todo-key-alist)
2174 (defvar org-todo-key-trigger nil)
2175 (make-variable-buffer-local 'org-todo-key-trigger)
2177 (defcustom org-todo-interpretation 'sequence
2178 "Controls how TODO keywords are interpreted.
2179 This variable is in principle obsolete and is only used for
2180 backward compatibility, if the interpretation of todo keywords is
2181 not given already in `org-todo-keywords'. See that variable for
2182 more information."
2183 :group 'org-todo
2184 :group 'org-keywords
2185 :type '(choice (const sequence)
2186 (const type)))
2188 (defcustom org-use-fast-todo-selection t
2189 "Non-nil means use the fast todo selection scheme with C-c C-t.
2190 This variable describes if and under what circumstances the cycling
2191 mechanism for TODO keywords will be replaced by a single-key, direct
2192 selection scheme.
2194 When nil, fast selection is never used.
2196 When the symbol `prefix', it will be used when `org-todo' is called with
2197 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2198 in an agenda buffer.
2200 When t, fast selection is used by default. In this case, the prefix
2201 argument forces cycling instead.
2203 In all cases, the special interface is only used if access keys have actually
2204 been assigned by the user, i.e. if keywords in the configuration are followed
2205 by a letter in parenthesis, like TODO(t)."
2206 :group 'org-todo
2207 :type '(choice
2208 (const :tag "Never" nil)
2209 (const :tag "By default" t)
2210 (const :tag "Only with C-u C-c C-t" prefix)))
2212 (defcustom org-provide-todo-statistics t
2213 "Non-nil means update todo statistics after insert and toggle.
2214 ALL-HEADLINES means update todo statistics by including headlines
2215 with no TODO keyword as well, counting them as not done.
2216 A list of TODO keywords means the same, but skip keywords that are
2217 not in this list.
2219 When this is set, todo statistics is updated in the parent of the
2220 current entry each time a todo state is changed."
2221 :group 'org-todo
2222 :type '(choice
2223 (const :tag "Yes, only for TODO entries" t)
2224 (const :tag "Yes, including all entries" 'all-headlines)
2225 (repeat :tag "Yes, for TODOs in this list"
2226 (string :tag "TODO keyword"))
2227 (other :tag "No TODO statistics" nil)))
2229 (defcustom org-hierarchical-todo-statistics t
2230 "Non-nil means TODO statistics covers just direct children.
2231 When nil, all entries in the subtree are considered.
2232 This has only an effect if `org-provide-todo-statistics' is set.
2233 To set this to nil for only a single subtree, use a COOKIE_DATA
2234 property and include the word \"recursive\" into the value."
2235 :group 'org-todo
2236 :type 'boolean)
2238 (defcustom org-after-todo-state-change-hook nil
2239 "Hook which is run after the state of a TODO item was changed.
2240 The new state (a string with a TODO keyword, or nil) is available in the
2241 Lisp variable `org-state'."
2242 :group 'org-todo
2243 :type 'hook)
2245 (defvar org-blocker-hook nil
2246 "Hook for functions that are allowed to block a state change.
2248 Each function gets as its single argument a property list, see
2249 `org-trigger-hook' for more information about this list.
2251 If any of the functions in this hook returns nil, the state change
2252 is blocked.")
2254 (defvar org-trigger-hook nil
2255 "Hook for functions that are triggered by a state change.
2257 Each function gets as its single argument a property list with at least
2258 the following elements:
2260 (:type type-of-change :position pos-at-entry-start
2261 :from old-state :to new-state)
2263 Depending on the type, more properties may be present.
2265 This mechanism is currently implemented for:
2267 TODO state changes
2268 ------------------
2269 :type todo-state-change
2270 :from previous state (keyword as a string), or nil, or a symbol
2271 'todo' or 'done', to indicate the general type of state.
2272 :to new state, like in :from")
2274 (defcustom org-enforce-todo-dependencies nil
2275 "Non-nil means undone TODO entries will block switching the parent to DONE.
2276 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2277 be blocked if any prior sibling is not yet done.
2278 Finally, if the parent is blocked because of ordered siblings of its own,
2279 the child will also be blocked."
2280 :set (lambda (var val)
2281 (set var val)
2282 (if val
2283 (add-hook 'org-blocker-hook
2284 'org-block-todo-from-children-or-siblings-or-parent)
2285 (remove-hook 'org-blocker-hook
2286 'org-block-todo-from-children-or-siblings-or-parent)))
2287 :group 'org-todo
2288 :type 'boolean)
2290 (defcustom org-enforce-todo-checkbox-dependencies nil
2291 "Non-nil means unchecked boxes will block switching the parent to DONE.
2292 When this is nil, checkboxes have no influence on switching TODO states.
2293 When non-nil, you first need to check off all check boxes before the TODO
2294 entry can be switched to DONE.
2295 This variable needs to be set before org.el is loaded, and you need to
2296 restart Emacs after a change to make the change effective. The only way
2297 to change is while Emacs is running is through the customize interface."
2298 :set (lambda (var val)
2299 (set var val)
2300 (if val
2301 (add-hook 'org-blocker-hook
2302 'org-block-todo-from-checkboxes)
2303 (remove-hook 'org-blocker-hook
2304 'org-block-todo-from-checkboxes)))
2305 :group 'org-todo
2306 :type 'boolean)
2308 (defcustom org-treat-insert-todo-heading-as-state-change nil
2309 "Non-nil means inserting a TODO heading is treated as state change.
2310 So when the command \\[org-insert-todo-heading] is used, state change
2311 logging will apply if appropriate. When nil, the new TODO item will
2312 be inserted directly, and no logging will take place."
2313 :group 'org-todo
2314 :type 'boolean)
2316 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2317 "Non-nil means switching TODO states with S-cursor counts as state change.
2318 This is the default behavior. However, setting this to nil allows a
2319 convenient way to select a TODO state and bypass any logging associated
2320 with that."
2321 :group 'org-todo
2322 :type 'boolean)
2324 (defcustom org-todo-state-tags-triggers nil
2325 "Tag changes that should be triggered by TODO state changes.
2326 This is a list. Each entry is
2328 (state-change (tag . flag) .......)
2330 State-change can be a string with a state, and empty string to indicate the
2331 state that has no TODO keyword, or it can be one of the symbols `todo'
2332 or `done', meaning any not-done or done state, respectively."
2333 :group 'org-todo
2334 :group 'org-tags
2335 :type '(repeat
2336 (cons (choice :tag "When changing to"
2337 (const :tag "Not-done state" todo)
2338 (const :tag "Done state" done)
2339 (string :tag "State"))
2340 (repeat
2341 (cons :tag "Tag action"
2342 (string :tag "Tag")
2343 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2345 (defcustom org-log-done nil
2346 "Information to record when a task moves to the DONE state.
2348 Possible values are:
2350 nil Don't add anything, just change the keyword
2351 time Add a time stamp to the task
2352 note Prompt for a note and add it with template `org-log-note-headings'
2354 This option can also be set with on a per-file-basis with
2356 #+STARTUP: nologdone
2357 #+STARTUP: logdone
2358 #+STARTUP: lognotedone
2360 You can have local logging settings for a subtree by setting the LOGGING
2361 property to one or more of these keywords."
2362 :group 'org-todo
2363 :group 'org-progress
2364 :type '(choice
2365 (const :tag "No logging" nil)
2366 (const :tag "Record CLOSED timestamp" time)
2367 (const :tag "Record CLOSED timestamp with note." note)))
2369 ;; Normalize old uses of org-log-done.
2370 (cond
2371 ((eq org-log-done t) (setq org-log-done 'time))
2372 ((and (listp org-log-done) (memq 'done org-log-done))
2373 (setq org-log-done 'note)))
2375 (defcustom org-log-reschedule nil
2376 "Information to record when the scheduling date of a tasks is modified.
2378 Possible values are:
2380 nil Don't add anything, just change the date
2381 time Add a time stamp to the task
2382 note Prompt for a note and add it with template `org-log-note-headings'
2384 This option can also be set with on a per-file-basis with
2386 #+STARTUP: nologreschedule
2387 #+STARTUP: logreschedule
2388 #+STARTUP: lognotereschedule"
2389 :group 'org-todo
2390 :group 'org-progress
2391 :type '(choice
2392 (const :tag "No logging" nil)
2393 (const :tag "Record timestamp" time)
2394 (const :tag "Record timestamp with note." note)))
2396 (defcustom org-log-redeadline nil
2397 "Information to record when the deadline date of a tasks is modified.
2399 Possible values are:
2401 nil Don't add anything, just change the date
2402 time Add a time stamp to the task
2403 note Prompt for a note and add it with template `org-log-note-headings'
2405 This option can also be set with on a per-file-basis with
2407 #+STARTUP: nologredeadline
2408 #+STARTUP: logredeadline
2409 #+STARTUP: lognoteredeadline
2411 You can have local logging settings for a subtree by setting the LOGGING
2412 property to one or more of these keywords."
2413 :group 'org-todo
2414 :group 'org-progress
2415 :type '(choice
2416 (const :tag "No logging" nil)
2417 (const :tag "Record timestamp" time)
2418 (const :tag "Record timestamp with note." note)))
2420 (defcustom org-log-note-clock-out nil
2421 "Non-nil means record a note when clocking out of an item.
2422 This can also be configured on a per-file basis by adding one of
2423 the following lines anywhere in the buffer:
2425 #+STARTUP: lognoteclock-out
2426 #+STARTUP: nolognoteclock-out"
2427 :group 'org-todo
2428 :group 'org-progress
2429 :type 'boolean)
2431 (defcustom org-log-done-with-time t
2432 "Non-nil means the CLOSED time stamp will contain date and time.
2433 When nil, only the date will be recorded."
2434 :group 'org-progress
2435 :type 'boolean)
2437 (defcustom org-log-note-headings
2438 '((done . "CLOSING NOTE %t")
2439 (state . "State %-12s from %-12S %t")
2440 (note . "Note taken on %t")
2441 (reschedule . "Rescheduled from %S on %t")
2442 (delschedule . "Not scheduled, was %S on %t")
2443 (redeadline . "New deadline from %S on %t")
2444 (deldeadline . "Removed deadline, was %S on %t")
2445 (refile . "Refiled on %t")
2446 (clock-out . ""))
2447 "Headings for notes added to entries.
2448 The value is an alist, with the car being a symbol indicating the note
2449 context, and the cdr is the heading to be used. The heading may also be the
2450 empty string.
2451 %t in the heading will be replaced by a time stamp.
2452 %T will be an active time stamp instead the default inactive one
2453 %d will be replaced by a short-format time stamp.
2454 %D will be replaced by an active short-format time stamp.
2455 %s will be replaced by the new TODO state, in double quotes.
2456 %S will be replaced by the old TODO state, in double quotes.
2457 %u will be replaced by the user name.
2458 %U will be replaced by the full user name.
2460 In fact, it is not a good idea to change the `state' entry, because
2461 agenda log mode depends on the format of these entries."
2462 :group 'org-todo
2463 :group 'org-progress
2464 :type '(list :greedy t
2465 (cons (const :tag "Heading when closing an item" done) string)
2466 (cons (const :tag
2467 "Heading when changing todo state (todo sequence only)"
2468 state) string)
2469 (cons (const :tag "Heading when just taking a note" note) string)
2470 (cons (const :tag "Heading when clocking out" clock-out) string)
2471 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2472 (cons (const :tag "Heading when rescheduling" reschedule) string)
2473 (cons (const :tag "Heading when changing deadline" redeadline) string)
2474 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2475 (cons (const :tag "Heading when refiling" refile) string)))
2477 (unless (assq 'note org-log-note-headings)
2478 (push '(note . "%t") org-log-note-headings))
2480 (defcustom org-log-into-drawer nil
2481 "Non-nil means insert state change notes and time stamps into a drawer.
2482 When nil, state changes notes will be inserted after the headline and
2483 any scheduling and clock lines, but not inside a drawer.
2485 The value of this variable should be the name of the drawer to use.
2486 LOGBOOK is proposed as the default drawer for this purpose, you can
2487 also set this to a string to define the drawer of your choice.
2489 A value of t is also allowed, representing \"LOGBOOK\".
2491 If this variable is set, `org-log-state-notes-insert-after-drawers'
2492 will be ignored.
2494 You can set the property LOG_INTO_DRAWER to overrule this setting for
2495 a subtree."
2496 :group 'org-todo
2497 :group 'org-progress
2498 :type '(choice
2499 (const :tag "Not into a drawer" nil)
2500 (const :tag "LOGBOOK" t)
2501 (string :tag "Other")))
2503 (if (fboundp 'defvaralias)
2504 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2506 (defun org-log-into-drawer ()
2507 "Return the value of `org-log-into-drawer', but let properties overrule.
2508 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2509 used instead of the default value."
2510 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2511 (cond
2512 ((or (not p) (equal p "nil")) org-log-into-drawer)
2513 ((equal p "t") "LOGBOOK")
2514 (t p))))
2516 (defcustom org-log-state-notes-insert-after-drawers nil
2517 "Non-nil means insert state change notes after any drawers in entry.
2518 Only the drawers that *immediately* follow the headline and the
2519 deadline/scheduled line are skipped.
2520 When nil, insert notes right after the heading and perhaps the line
2521 with deadline/scheduling if present.
2523 This variable will have no effect if `org-log-into-drawer' is
2524 set."
2525 :group 'org-todo
2526 :group 'org-progress
2527 :type 'boolean)
2529 (defcustom org-log-states-order-reversed t
2530 "Non-nil means the latest state note will be directly after heading.
2531 When nil, the state change notes will be ordered according to time."
2532 :group 'org-todo
2533 :group 'org-progress
2534 :type 'boolean)
2536 (defcustom org-todo-repeat-to-state nil
2537 "The TODO state to which a repeater should return the repeating task.
2538 By default this is the first task in a TODO sequence, or the previous state
2539 in a TODO_TYP set. But you can specify another task here.
2540 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2541 :group 'org-todo
2542 :version "24.1"
2543 :type '(choice (const :tag "Head of sequence" nil)
2544 (string :tag "Specific state")))
2546 (defcustom org-log-repeat 'time
2547 "Non-nil means record moving through the DONE state when triggering repeat.
2548 An auto-repeating task is immediately switched back to TODO when
2549 marked DONE. If you are not logging state changes (by adding \"@\"
2550 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2551 record a closing note, there will be no record of the task moving
2552 through DONE. This variable forces taking a note anyway.
2554 nil Don't force a record
2555 time Record a time stamp
2556 note Record a note
2558 This option can also be set with on a per-file-basis with
2560 #+STARTUP: logrepeat
2561 #+STARTUP: lognoterepeat
2562 #+STARTUP: nologrepeat
2564 You can have local logging settings for a subtree by setting the LOGGING
2565 property to one or more of these keywords."
2566 :group 'org-todo
2567 :group 'org-progress
2568 :type '(choice
2569 (const :tag "Don't force a record" nil)
2570 (const :tag "Force recording the DONE state" time)
2571 (const :tag "Force recording a note with the DONE state" note)))
2574 (defgroup org-priorities nil
2575 "Priorities in Org-mode."
2576 :tag "Org Priorities"
2577 :group 'org-todo)
2579 (defcustom org-enable-priority-commands t
2580 "Non-nil means priority commands are active.
2581 When nil, these commands will be disabled, so that you never accidentally
2582 set a priority."
2583 :group 'org-priorities
2584 :type 'boolean)
2586 (defcustom org-highest-priority ?A
2587 "The highest priority of TODO items. A character like ?A, ?B etc.
2588 Must have a smaller ASCII number than `org-lowest-priority'."
2589 :group 'org-priorities
2590 :type 'character)
2592 (defcustom org-lowest-priority ?C
2593 "The lowest priority of TODO items. A character like ?A, ?B etc.
2594 Must have a larger ASCII number than `org-highest-priority'."
2595 :group 'org-priorities
2596 :type 'character)
2598 (defcustom org-default-priority ?B
2599 "The default priority of TODO items.
2600 This is the priority an item gets if no explicit priority is given.
2601 When starting to cycle on an empty priority the first step in the cycle
2602 depends on `org-priority-start-cycle-with-default'. The resulting first
2603 step priority must not exceed the range from `org-highest-priority' to
2604 `org-lowest-priority' which means that `org-default-priority' has to be
2605 in this range exclusive or inclusive the range boundaries. Else the
2606 first step refuses to set the default and the second will fall back
2607 to (depending on the command used) the highest or lowest priority."
2608 :group 'org-priorities
2609 :type 'character)
2611 (defcustom org-priority-start-cycle-with-default t
2612 "Non-nil means start with default priority when starting to cycle.
2613 When this is nil, the first step in the cycle will be (depending on the
2614 command used) one higher or lower than the default priority.
2615 See also `org-default-priority'."
2616 :group 'org-priorities
2617 :type 'boolean)
2619 (defcustom org-get-priority-function nil
2620 "Function to extract the priority from a string.
2621 The string is normally the headline. If this is nil Org computes the
2622 priority from the priority cookie like [#A] in the headline. It returns
2623 an integer, increasing by 1000 for each priority level.
2624 The user can set a different function here, which should take a string
2625 as an argument and return the numeric priority."
2626 :group 'org-priorities
2627 :version "24.1"
2628 :type 'function)
2630 (defgroup org-time nil
2631 "Options concerning time stamps and deadlines in Org-mode."
2632 :tag "Org Time"
2633 :group 'org)
2635 (defcustom org-insert-labeled-timestamps-at-point nil
2636 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2637 When nil, these labeled time stamps are forces into the second line of an
2638 entry, just after the headline. When scheduling from the global TODO list,
2639 the time stamp will always be forced into the second line."
2640 :group 'org-time
2641 :type 'boolean)
2643 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2644 "Formats for `format-time-string' which are used for time stamps.
2645 It is not recommended to change this constant.")
2647 (defcustom org-time-stamp-rounding-minutes '(0 5)
2648 "Number of minutes to round time stamps to.
2649 These are two values, the first applies when first creating a time stamp.
2650 The second applies when changing it with the commands `S-up' and `S-down'.
2651 When changing the time stamp, this means that it will change in steps
2652 of N minutes, as given by the second value.
2654 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2655 numbers should be factors of 60, so for example 5, 10, 15.
2657 When this is larger than 1, you can still force an exact time stamp by using
2658 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2659 and by using a prefix arg to `S-up/down' to specify the exact number
2660 of minutes to shift."
2661 :group 'org-time
2662 :get #'(lambda (var) ; Make sure both elements are there
2663 (if (integerp (default-value var))
2664 (list (default-value var) 5)
2665 (default-value var)))
2666 :type '(list
2667 (integer :tag "when inserting times")
2668 (integer :tag "when modifying times")))
2670 ;; Normalize old customizations of this variable.
2671 (when (integerp org-time-stamp-rounding-minutes)
2672 (setq org-time-stamp-rounding-minutes
2673 (list org-time-stamp-rounding-minutes
2674 org-time-stamp-rounding-minutes)))
2676 (defcustom org-display-custom-times nil
2677 "Non-nil means overlay custom formats over all time stamps.
2678 The formats are defined through the variable `org-time-stamp-custom-formats'.
2679 To turn this on on a per-file basis, insert anywhere in the file:
2680 #+STARTUP: customtime"
2681 :group 'org-time
2682 :set 'set-default
2683 :type 'sexp)
2684 (make-variable-buffer-local 'org-display-custom-times)
2686 (defcustom org-time-stamp-custom-formats
2687 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2688 "Custom formats for time stamps. See `format-time-string' for the syntax.
2689 These are overlaid over the default ISO format if the variable
2690 `org-display-custom-times' is set. Time like %H:%M should be at the
2691 end of the second format. The custom formats are also honored by export
2692 commands, if custom time display is turned on at the time of export."
2693 :group 'org-time
2694 :type 'sexp)
2696 (defun org-time-stamp-format (&optional long inactive)
2697 "Get the right format for a time string."
2698 (let ((f (if long (cdr org-time-stamp-formats)
2699 (car org-time-stamp-formats))))
2700 (if inactive
2701 (concat "[" (substring f 1 -1) "]")
2702 f)))
2704 (defcustom org-time-clocksum-format "%d:%02d"
2705 "The format string used when creating CLOCKSUM lines.
2706 This is also used when org-mode generates a time duration."
2707 :group 'org-time
2708 :type 'string)
2710 (defcustom org-time-clocksum-use-fractional nil
2711 "If non-nil, \\[org-clock-display] uses fractional times.
2712 org-mode generates a time duration."
2713 :group 'org-time
2714 :type 'boolean)
2716 (defcustom org-time-clocksum-fractional-format "%.2f"
2717 "The format string used when creating CLOCKSUM lines, or when
2718 org-mode generates a time duration."
2719 :group 'org-time
2720 :type 'string)
2722 (defcustom org-deadline-warning-days 14
2723 "No. of days before expiration during which a deadline becomes active.
2724 This variable governs the display in sparse trees and in the agenda.
2725 When 0 or negative, it means use this number (the absolute value of it)
2726 even if a deadline has a different individual lead time specified.
2728 Custom commands can set this variable in the options section."
2729 :group 'org-time
2730 :group 'org-agenda-daily/weekly
2731 :type 'integer)
2733 (defcustom org-read-date-prefer-future t
2734 "Non-nil means assume future for incomplete date input from user.
2735 This affects the following situations:
2736 1. The user gives a month but not a year.
2737 For example, if it is April and you enter \"feb 2\", this will be read
2738 as Feb 2, *next* year. \"May 5\", however, will be this year.
2739 2. The user gives a day, but no month.
2740 For example, if today is the 15th, and you enter \"3\", Org-mode will
2741 read this as the third of *next* month. However, if you enter \"17\",
2742 it will be considered as *this* month.
2744 If you set this variable to the symbol `time', then also the following
2745 will work:
2747 3. If the user gives a time, but no day. If the time is before now,
2748 to will be interpreted as tomorrow.
2750 Currently none of this works for ISO week specifications.
2752 When this option is nil, the current day, month and year will always be
2753 used as defaults.
2755 See also `org-agenda-jump-prefer-future'."
2756 :group 'org-time
2757 :type '(choice
2758 (const :tag "Never" nil)
2759 (const :tag "Check month and day" t)
2760 (const :tag "Check month, day, and time" time)))
2762 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2763 "Should the agenda jump command prefer the future for incomplete dates?
2764 The default is to do the same as configured in `org-read-date-prefer-future'.
2765 But you can also set a deviating value here.
2766 This may t or nil, or the symbol `org-read-date-prefer-future'."
2767 :group 'org-agenda
2768 :group 'org-time
2769 :version "24.1"
2770 :type '(choice
2771 (const :tag "Use org-read-date-prefer-future"
2772 org-read-date-prefer-future)
2773 (const :tag "Never" nil)
2774 (const :tag "Always" t)))
2776 (defcustom org-read-date-force-compatible-dates t
2777 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2779 Depending on the system Emacs is running on, certain dates cannot
2780 be represented with the type used internally to represent time.
2781 Dates between 1970-1-1 and 2038-1-1 can always be represented
2782 correctly. Some systems allow for earlier dates, some for later,
2783 some for both. One way to find out it to insert any date into an
2784 Org buffer, putting the cursor on the year and hitting S-up and
2785 S-down to test the range.
2787 When this variable is set to t, the date/time prompt will not let
2788 you specify dates outside the 1970-2037 range, so it is certain that
2789 these dates will work in whatever version of Emacs you are
2790 running, and also that you can move a file from one Emacs implementation
2791 to another. WHenever Org is forcing the year for you, it will display
2792 a message and beep.
2794 When this variable is nil, Org will check if the date is
2795 representable in the specific Emacs implementation you are using.
2796 If not, it will force a year, usually the current year, and beep
2797 to remind you. Currently this setting is not recommended because
2798 the likelihood that you will open your Org files in an Emacs that
2799 has limited date range is not negligible.
2801 A workaround for this problem is to use diary sexp dates for time
2802 stamps outside of this range."
2803 :group 'org-time
2804 :version "24.1"
2805 :type 'boolean)
2807 (defcustom org-read-date-display-live t
2808 "Non-nil means display current interpretation of date prompt live.
2809 This display will be in an overlay, in the minibuffer."
2810 :group 'org-time
2811 :type 'boolean)
2813 (defcustom org-read-date-popup-calendar t
2814 "Non-nil means pop up a calendar when prompting for a date.
2815 In the calendar, the date can be selected with mouse-1. However, the
2816 minibuffer will also be active, and you can simply enter the date as well.
2817 When nil, only the minibuffer will be available."
2818 :group 'org-time
2819 :type 'boolean)
2820 (if (fboundp 'defvaralias)
2821 (defvaralias 'org-popup-calendar-for-date-prompt
2822 'org-read-date-popup-calendar))
2824 (defcustom org-read-date-minibuffer-setup-hook nil
2825 "Hook to be used to set up keys for the date/time interface.
2826 Add key definitions to `minibuffer-local-map', which will be a temporary
2827 copy."
2828 :group 'org-time
2829 :type 'hook)
2831 (defcustom org-extend-today-until 0
2832 "The hour when your day really ends. Must be an integer.
2833 This has influence for the following applications:
2834 - When switching the agenda to \"today\". It it is still earlier than
2835 the time given here, the day recognized as TODAY is actually yesterday.
2836 - When a date is read from the user and it is still before the time given
2837 here, the current date and time will be assumed to be yesterday, 23:59.
2838 Also, timestamps inserted in remember templates follow this rule.
2840 IMPORTANT: This is a feature whose implementation is and likely will
2841 remain incomplete. Really, it is only here because past midnight seems to
2842 be the favorite working time of John Wiegley :-)"
2843 :group 'org-time
2844 :type 'integer)
2846 (defcustom org-use-effective-time nil
2847 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2848 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2849 \"effective time\" of any timestamps between midnight and 8am will be
2850 23:59 of the previous day."
2851 :group 'org-time
2852 :version "24.1"
2853 :type 'boolean)
2855 (defcustom org-edit-timestamp-down-means-later nil
2856 "Non-nil means S-down will increase the time in a time stamp.
2857 When nil, S-up will increase."
2858 :group 'org-time
2859 :type 'boolean)
2861 (defcustom org-calendar-follow-timestamp-change t
2862 "Non-nil means make the calendar window follow timestamp changes.
2863 When a timestamp is modified and the calendar window is visible, it will be
2864 moved to the new date."
2865 :group 'org-time
2866 :type 'boolean)
2868 (defgroup org-tags nil
2869 "Options concerning tags in Org-mode."
2870 :tag "Org Tags"
2871 :group 'org)
2873 (defcustom org-tag-alist nil
2874 "List of tags allowed in Org-mode files.
2875 When this list is nil, Org-mode will base TAG input on what is already in the
2876 buffer.
2877 The value of this variable is an alist, the car of each entry must be a
2878 keyword as a string, the cdr may be a character that is used to select
2879 that tag through the fast-tag-selection interface.
2880 See the manual for details."
2881 :group 'org-tags
2882 :type '(repeat
2883 (choice
2884 (cons (string :tag "Tag name")
2885 (character :tag "Access char"))
2886 (list :tag "Start radio group"
2887 (const :startgroup)
2888 (option (string :tag "Group description")))
2889 (list :tag "End radio group"
2890 (const :endgroup)
2891 (option (string :tag "Group description")))
2892 (const :tag "New line" (:newline)))))
2894 (defcustom org-tag-persistent-alist nil
2895 "List of tags that will always appear in all Org-mode files.
2896 This is in addition to any in buffer settings or customizations
2897 of `org-tag-alist'.
2898 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2899 The value of this variable is an alist, the car of each entry must be a
2900 keyword as a string, the cdr may be a character that is used to select
2901 that tag through the fast-tag-selection interface.
2902 See the manual for details.
2903 To disable these tags on a per-file basis, insert anywhere in the file:
2904 #+STARTUP: noptag"
2905 :group 'org-tags
2906 :type '(repeat
2907 (choice
2908 (cons (string :tag "Tag name")
2909 (character :tag "Access char"))
2910 (const :tag "Start radio group" (:startgroup))
2911 (const :tag "End radio group" (:endgroup))
2912 (const :tag "New line" (:newline)))))
2914 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2915 "If non-nil, always offer completion for all tags of all agenda files.
2916 Instead of customizing this variable directly, you might want to
2917 set it locally for capture buffers, because there no list of
2918 tags in that file can be created dynamically (there are none).
2920 (add-hook 'org-capture-mode-hook
2921 (lambda ()
2922 (set (make-local-variable
2923 'org-complete-tags-always-offer-all-agenda-tags)
2924 t)))"
2925 :group 'org-tags
2926 :version "24.1"
2927 :type 'boolean)
2929 (defvar org-file-tags nil
2930 "List of tags that can be inherited by all entries in the file.
2931 The tags will be inherited if the variable `org-use-tag-inheritance'
2932 says they should be.
2933 This variable is populated from #+FILETAGS lines.")
2935 (defcustom org-use-fast-tag-selection 'auto
2936 "Non-nil means use fast tag selection scheme.
2937 This is a special interface to select and deselect tags with single keys.
2938 When nil, fast selection is never used.
2939 When the symbol `auto', fast selection is used if and only if selection
2940 characters for tags have been configured, either through the variable
2941 `org-tag-alist' or through a #+TAGS line in the buffer.
2942 When t, fast selection is always used and selection keys are assigned
2943 automatically if necessary."
2944 :group 'org-tags
2945 :type '(choice
2946 (const :tag "Always" t)
2947 (const :tag "Never" nil)
2948 (const :tag "When selection characters are configured" 'auto)))
2950 (defcustom org-fast-tag-selection-single-key nil
2951 "Non-nil means fast tag selection exits after first change.
2952 When nil, you have to press RET to exit it.
2953 During fast tag selection, you can toggle this flag with `C-c'.
2954 This variable can also have the value `expert'. In this case, the window
2955 displaying the tags menu is not even shown, until you press C-c again."
2956 :group 'org-tags
2957 :type '(choice
2958 (const :tag "No" nil)
2959 (const :tag "Yes" t)
2960 (const :tag "Expert" expert)))
2962 (defvar org-fast-tag-selection-include-todo nil
2963 "Non-nil means fast tags selection interface will also offer TODO states.
2964 This is an undocumented feature, you should not rely on it.")
2966 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2967 "The column to which tags should be indented in a headline.
2968 If this number is positive, it specifies the column. If it is negative,
2969 it means that the tags should be flushright to that column. For example,
2970 -80 works well for a normal 80 character screen.
2971 When 0, place tags directly after headline text, with only one space in
2972 between."
2973 :group 'org-tags
2974 :type 'integer)
2976 (defcustom org-auto-align-tags t
2977 "Non-nil keeps tags aligned when modifying headlines.
2978 Some operations (i.e. demoting) change the length of a headline and
2979 therefore shift the tags around. With this option turned on, after
2980 each such operation the tags are again aligned to `org-tags-column'."
2981 :group 'org-tags
2982 :type 'boolean)
2984 (defcustom org-use-tag-inheritance t
2985 "Non-nil means tags in levels apply also for sublevels.
2986 When nil, only the tags directly given in a specific line apply there.
2987 This may also be a list of tags that should be inherited, or a regexp that
2988 matches tags that should be inherited. Additional control is possible
2989 with the variable `org-tags-exclude-from-inheritance' which gives an
2990 explicit list of tags to be excluded from inheritance., even if the value of
2991 `org-use-tag-inheritance' would select it for inheritance.
2993 If this option is t, a match early-on in a tree can lead to a large
2994 number of matches in the subtree when constructing the agenda or creating
2995 a sparse tree. If you only want to see the first match in a tree during
2996 a search, check out the variable `org-tags-match-list-sublevels'."
2997 :group 'org-tags
2998 :type '(choice
2999 (const :tag "Not" nil)
3000 (const :tag "Always" t)
3001 (repeat :tag "Specific tags" (string :tag "Tag"))
3002 (regexp :tag "Tags matched by regexp")))
3004 (defcustom org-tags-exclude-from-inheritance nil
3005 "List of tags that should never be inherited.
3006 This is a way to exclude a few tags from inheritance. For way to do
3007 the opposite, to actively allow inheritance for selected tags,
3008 see the variable `org-use-tag-inheritance'."
3009 :group 'org-tags
3010 :type '(repeat (string :tag "Tag")))
3012 (defun org-tag-inherit-p (tag)
3013 "Check if TAG is one that should be inherited."
3014 (cond
3015 ((member tag org-tags-exclude-from-inheritance) nil)
3016 ((eq org-use-tag-inheritance t) t)
3017 ((not org-use-tag-inheritance) nil)
3018 ((stringp org-use-tag-inheritance)
3019 (string-match org-use-tag-inheritance tag))
3020 ((listp org-use-tag-inheritance)
3021 (member tag org-use-tag-inheritance))
3022 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3024 (defcustom org-tags-match-list-sublevels t
3025 "Non-nil means list also sublevels of headlines matching a search.
3026 This variable applies to tags/property searches, and also to stuck
3027 projects because this search is based on a tags match as well.
3029 When set to the symbol `indented', sublevels are indented with
3030 leading dots.
3032 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3033 the sublevels of a headline matching a tag search often also match
3034 the same search. Listing all of them can create very long lists.
3035 Setting this variable to nil causes subtrees of a match to be skipped.
3037 This variable is semi-obsolete and probably should always be true. It
3038 is better to limit inheritance to certain tags using the variables
3039 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3040 :group 'org-tags
3041 :type '(choice
3042 (const :tag "No, don't list them" nil)
3043 (const :tag "Yes, do list them" t)
3044 (const :tag "List them, indented with leading dots" indented)))
3046 (defcustom org-tags-sort-function nil
3047 "When set, tags are sorted using this function as a comparator."
3048 :group 'org-tags
3049 :type '(choice
3050 (const :tag "No sorting" nil)
3051 (const :tag "Alphabetical" string<)
3052 (const :tag "Reverse alphabetical" string>)
3053 (function :tag "Custom function" nil)))
3055 (defvar org-tags-history nil
3056 "History of minibuffer reads for tags.")
3057 (defvar org-last-tags-completion-table nil
3058 "The last used completion table for tags.")
3059 (defvar org-after-tags-change-hook nil
3060 "Hook that is run after the tags in a line have changed.")
3062 (defgroup org-properties nil
3063 "Options concerning properties in Org-mode."
3064 :tag "Org Properties"
3065 :group 'org)
3067 (defcustom org-property-format "%-10s %s"
3068 "How property key/value pairs should be formatted by `indent-line'.
3069 When `indent-line' hits a property definition, it will format the line
3070 according to this format, mainly to make sure that the values are
3071 lined-up with respect to each other."
3072 :group 'org-properties
3073 :type 'string)
3075 (defcustom org-properties-postprocess-alist nil
3076 "Alist of properties and functions to adjust inserted values.
3077 Elements of this alist must be of the form
3079 ([string] [function])
3081 where [string] must be a property name and [function] must be a
3082 lambda expression: this lambda expression must take one argument,
3083 the value to adjust, and return the new value as a string.
3085 For example, this element will allow the property \"Remaining\"
3086 to be updated wrt the relation between the \"Effort\" property
3087 and the clock summary:
3089 ((\"Remaining\" (lambda(value)
3090 (let ((clocksum (org-clock-sum-current-item))
3091 (effort (org-duration-string-to-minutes
3092 (org-entry-get (point) \"Effort\"))))
3093 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3094 :group 'org-properties
3095 :version "24.1"
3096 :type '(alist :key-type (string :tag "Property")
3097 :value-type (function :tag "Function")))
3099 (defcustom org-use-property-inheritance nil
3100 "Non-nil means properties apply also for sublevels.
3102 This setting is chiefly used during property searches. Turning it on can
3103 cause significant overhead when doing a search, which is why it is not
3104 on by default.
3106 When nil, only the properties directly given in the current entry count.
3107 When t, every property is inherited. The value may also be a list of
3108 properties that should have inheritance, or a regular expression matching
3109 properties that should be inherited.
3111 However, note that some special properties use inheritance under special
3112 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3113 and the properties ending in \"_ALL\" when they are used as descriptor
3114 for valid values of a property.
3116 Note for programmers:
3117 When querying an entry with `org-entry-get', you can control if inheritance
3118 should be used. By default, `org-entry-get' looks only at the local
3119 properties. You can request inheritance by setting the inherit argument
3120 to t (to force inheritance) or to `selective' (to respect the setting
3121 in this variable)."
3122 :group 'org-properties
3123 :type '(choice
3124 (const :tag "Not" nil)
3125 (const :tag "Always" t)
3126 (repeat :tag "Specific properties" (string :tag "Property"))
3127 (regexp :tag "Properties matched by regexp")))
3129 (defun org-property-inherit-p (property)
3130 "Check if PROPERTY is one that should be inherited."
3131 (cond
3132 ((eq org-use-property-inheritance t) t)
3133 ((not org-use-property-inheritance) nil)
3134 ((stringp org-use-property-inheritance)
3135 (string-match org-use-property-inheritance property))
3136 ((listp org-use-property-inheritance)
3137 (member property org-use-property-inheritance))
3138 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3140 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3141 "The default column format, if no other format has been defined.
3142 This variable can be set on the per-file basis by inserting a line
3144 #+COLUMNS: %25ITEM ....."
3145 :group 'org-properties
3146 :type 'string)
3148 (defcustom org-columns-ellipses ".."
3149 "The ellipses to be used when a field in column view is truncated.
3150 When this is the empty string, as many characters as possible are shown,
3151 but then there will be no visual indication that the field has been truncated.
3152 When this is a string of length N, the last N characters of a truncated
3153 field are replaced by this string. If the column is narrower than the
3154 ellipses string, only part of the ellipses string will be shown."
3155 :group 'org-properties
3156 :type 'string)
3158 (defcustom org-columns-modify-value-for-display-function nil
3159 "Function that modifies values for display in column view.
3160 For example, it can be used to cut out a certain part from a time stamp.
3161 The function must take 2 arguments:
3163 column-title The title of the column (*not* the property name)
3164 value The value that should be modified.
3166 The function should return the value that should be displayed,
3167 or nil if the normal value should be used."
3168 :group 'org-properties
3169 :type 'function)
3171 (defcustom org-effort-property "Effort"
3172 "The property that is being used to keep track of effort estimates.
3173 Effort estimates given in this property need to have the format H:MM."
3174 :group 'org-properties
3175 :group 'org-progress
3176 :type '(string :tag "Property"))
3178 (defconst org-global-properties-fixed
3179 '(("VISIBILITY_ALL" . "folded children content all")
3180 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3181 "List of property/value pairs that can be inherited by any entry.
3183 These are fixed values, for the preset properties. The user variable
3184 that can be used to add to this list is `org-global-properties'.
3186 The entries in this list are cons cells where the car is a property
3187 name and cdr is a string with the value. If the value represents
3188 multiple items like an \"_ALL\" property, separate the items by
3189 spaces.")
3191 (defcustom org-global-properties nil
3192 "List of property/value pairs that can be inherited by any entry.
3194 This list will be combined with the constant `org-global-properties-fixed'.
3196 The entries in this list are cons cells where the car is a property
3197 name and cdr is a string with the value.
3199 You can set buffer-local values for the same purpose in the variable
3200 `org-file-properties' this by adding lines like
3202 #+PROPERTY: NAME VALUE"
3203 :group 'org-properties
3204 :type '(repeat
3205 (cons (string :tag "Property")
3206 (string :tag "Value"))))
3208 (defvar org-file-properties nil
3209 "List of property/value pairs that can be inherited by any entry.
3210 Valid for the current buffer.
3211 This variable is populated from #+PROPERTY lines.")
3212 (make-variable-buffer-local 'org-file-properties)
3214 (defgroup org-agenda nil
3215 "Options concerning agenda views in Org-mode."
3216 :tag "Org Agenda"
3217 :group 'org)
3219 (defvar org-category nil
3220 "Variable used by org files to set a category for agenda display.
3221 Such files should use a file variable to set it, for example
3223 # -*- mode: org; org-category: \"ELisp\"
3225 or contain a special line
3227 #+CATEGORY: ELisp
3229 If the file does not specify a category, then file's base name
3230 is used instead.")
3231 (make-variable-buffer-local 'org-category)
3232 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3234 (defcustom org-agenda-files nil
3235 "The files to be used for agenda display.
3236 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3237 \\[org-remove-file]. You can also use customize to edit the list.
3239 If an entry is a directory, all files in that directory that are matched by
3240 `org-agenda-file-regexp' will be part of the file list.
3242 If the value of the variable is not a list but a single file name, then
3243 the list of agenda files is actually stored and maintained in that file, one
3244 agenda file per line. In this file paths can be given relative to
3245 `org-directory'. Tilde expansion and environment variable substitution
3246 are also made."
3247 :group 'org-agenda
3248 :type '(choice
3249 (repeat :tag "List of files and directories" file)
3250 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3252 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3253 "Regular expression to match files for `org-agenda-files'.
3254 If any element in the list in that variable contains a directory instead
3255 of a normal file, all files in that directory that are matched by this
3256 regular expression will be included."
3257 :group 'org-agenda
3258 :type 'regexp)
3260 (defcustom org-agenda-text-search-extra-files nil
3261 "List of extra files to be searched by text search commands.
3262 These files will be search in addition to the agenda files by the
3263 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3264 Note that these files will only be searched for text search commands,
3265 not for the other agenda views like todo lists, tag searches or the weekly
3266 agenda. This variable is intended to list notes and possibly archive files
3267 that should also be searched by these two commands.
3268 In fact, if the first element in the list is the symbol `agenda-archives',
3269 than all archive files of all agenda files will be added to the search
3270 scope."
3271 :group 'org-agenda
3272 :type '(set :greedy t
3273 (const :tag "Agenda Archives" agenda-archives)
3274 (repeat :inline t (file))))
3276 (if (fboundp 'defvaralias)
3277 (defvaralias 'org-agenda-multi-occur-extra-files
3278 'org-agenda-text-search-extra-files))
3280 (defcustom org-agenda-skip-unavailable-files nil
3281 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3282 A nil value means to remove them, after a query, from the list."
3283 :group 'org-agenda
3284 :type 'boolean)
3286 (defcustom org-calendar-to-agenda-key [?c]
3287 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3288 The command `org-calendar-goto-agenda' will be bound to this key. The
3289 default is the character `c' because then `c' can be used to switch back and
3290 forth between agenda and calendar."
3291 :group 'org-agenda
3292 :type 'sexp)
3294 (defcustom org-calendar-agenda-action-key [?k]
3295 "The key to be installed in `calendar-mode-map' for agenda-action.
3296 The command `org-agenda-action' will be bound to this key. The
3297 default is the character `k' because we use the same key in the agenda."
3298 :group 'org-agenda
3299 :type 'sexp)
3301 (defcustom org-calendar-insert-diary-entry-key [?i]
3302 "The key to be installed in `calendar-mode-map' for adding diary entries.
3303 This option is irrelevant until `org-agenda-diary-file' has been configured
3304 to point to an Org-mode file. When that is the case, the command
3305 `org-agenda-diary-entry' will be bound to the key given here, by default
3306 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3307 if you want to continue doing this, you need to change this to a different
3308 key."
3309 :group 'org-agenda
3310 :type 'sexp)
3312 (defcustom org-agenda-diary-file 'diary-file
3313 "File to which to add new entries with the `i' key in agenda and calendar.
3314 When this is the symbol `diary-file', the functionality in the Emacs
3315 calendar will be used to add entries to the `diary-file'. But when this
3316 points to a file, `org-agenda-diary-entry' will be used instead."
3317 :group 'org-agenda
3318 :type '(choice
3319 (const :tag "The standard Emacs diary file" diary-file)
3320 (file :tag "Special Org file diary entries")))
3322 (eval-after-load "calendar"
3323 '(progn
3324 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3325 'org-calendar-goto-agenda)
3326 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3327 'org-agenda-action)
3328 (add-hook 'calendar-mode-hook
3329 (lambda ()
3330 (unless (eq org-agenda-diary-file 'diary-file)
3331 (define-key calendar-mode-map
3332 org-calendar-insert-diary-entry-key
3333 'org-agenda-diary-entry))))))
3335 (defgroup org-latex nil
3336 "Options for embedding LaTeX code into Org-mode."
3337 :tag "Org LaTeX"
3338 :group 'org)
3340 (defcustom org-format-latex-options
3341 '(:foreground default :background default :scale 1.0
3342 :html-foreground "Black" :html-background "Transparent"
3343 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3344 "Options for creating images from LaTeX fragments.
3345 This is a property list with the following properties:
3346 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3347 `default' means use the foreground of the default face.
3348 :background the background color, or \"Transparent\".
3349 `default' means use the background of the default face.
3350 :scale a scaling factor for the size of the images, to get more pixels
3351 :html-foreground, :html-background, :html-scale
3352 the same numbers for HTML export.
3353 :matchers a list indicating which matchers should be used to
3354 find LaTeX fragments. Valid members of this list are:
3355 \"begin\" find environments
3356 \"$1\" find single characters surrounded by $.$
3357 \"$\" find math expressions surrounded by $...$
3358 \"$$\" find math expressions surrounded by $$....$$
3359 \"\\(\" find math expressions surrounded by \\(...\\)
3360 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3361 :group 'org-latex
3362 :type 'plist)
3364 (defcustom org-format-latex-signal-error t
3365 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3366 When nil, just push out a message."
3367 :group 'org-latex
3368 :version "24.1"
3369 :type 'boolean)
3371 (defcustom org-latex-to-mathml-jar-file nil
3372 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3373 Use this to specify additional executable file say a jar file.
3375 When using MathToWeb as the converter, specify the full-path to
3376 your mathtoweb.jar file."
3377 :group 'org-latex
3378 :version "24.1"
3379 :type '(choice
3380 (const :tag "None" nil)
3381 (file :tag "JAR file" :must-match t)))
3383 (defcustom org-latex-to-mathml-convert-command nil
3384 "Command to convert LaTeX fragments to MathML.
3385 Replace format-specifiers in the command as noted below and use
3386 `shell-command' to convert LaTeX to MathML.
3387 %j: Executable file in fully expanded form as specified by
3388 `org-latex-to-mathml-jar-file'.
3389 %I: Input LaTeX file in fully expanded form
3390 %o: Output MathML file
3391 This command is used by `org-create-math-formula'.
3393 When using MathToWeb as the converter, set this to
3394 \"java -jar %j -unicode -force -df %o %I\"."
3395 :group 'org-latex
3396 :version "24.1"
3397 :type '(choice
3398 (const :tag "None" nil)
3399 (string :tag "\nShell command")))
3401 (defcustom org-latex-create-formula-image-program 'dvipng
3402 "Program to convert LaTeX fragments with.
3404 dvipng Process the LaTeX fragments to dvi file, then convert
3405 dvi files to png files using dvipng.
3406 This will also include processing of non-math environments.
3407 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3408 to convert pdf files to png files"
3409 :group 'org-latex
3410 :version "24.1"
3411 :type '(choice
3412 (const :tag "dvipng" dvipng)
3413 (const :tag "imagemagick" imagemagick)))
3415 (defun org-format-latex-mathml-available-p ()
3416 "Return t if `org-latex-to-mathml-convert-command' is usable."
3417 (save-match-data
3418 (when (and (boundp 'org-latex-to-mathml-convert-command)
3419 org-latex-to-mathml-convert-command)
3420 (let ((executable (car (split-string
3421 org-latex-to-mathml-convert-command))))
3422 (when (executable-find executable)
3423 (if (string-match
3424 "%j" org-latex-to-mathml-convert-command)
3425 (file-readable-p org-latex-to-mathml-jar-file)
3426 t))))))
3428 (defcustom org-format-latex-header "\\documentclass{article}
3429 \\usepackage[usenames]{color}
3430 \\usepackage{amsmath}
3431 \\usepackage[mathscr]{eucal}
3432 \\pagestyle{empty} % do not remove
3433 \[PACKAGES]
3434 \[DEFAULT-PACKAGES]
3435 % The settings below are copied from fullpage.sty
3436 \\setlength{\\textwidth}{\\paperwidth}
3437 \\addtolength{\\textwidth}{-3cm}
3438 \\setlength{\\oddsidemargin}{1.5cm}
3439 \\addtolength{\\oddsidemargin}{-2.54cm}
3440 \\setlength{\\evensidemargin}{\\oddsidemargin}
3441 \\setlength{\\textheight}{\\paperheight}
3442 \\addtolength{\\textheight}{-\\headheight}
3443 \\addtolength{\\textheight}{-\\headsep}
3444 \\addtolength{\\textheight}{-\\footskip}
3445 \\addtolength{\\textheight}{-3cm}
3446 \\setlength{\\topmargin}{1.5cm}
3447 \\addtolength{\\topmargin}{-2.54cm}"
3448 "The document header used for processing LaTeX fragments.
3449 It is imperative that this header make sure that no page number
3450 appears on the page. The package defined in the variables
3451 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3452 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3453 will be appended."
3454 :group 'org-latex
3455 :type 'string)
3457 (defvar org-format-latex-header-extra nil)
3459 (defun org-set-packages-alist (var val)
3460 "Set the packages alist and make sure it has 3 elements per entry."
3461 (set var (mapcar (lambda (x)
3462 (if (and (consp x) (= (length x) 2))
3463 (list (car x) (nth 1 x) t)
3465 val)))
3467 (defun org-get-packages-alist (var)
3469 "Get the packages alist and make sure it has 3 elements per entry."
3470 (mapcar (lambda (x)
3471 (if (and (consp x) (= (length x) 2))
3472 (list (car x) (nth 1 x) t)
3474 (default-value var)))
3476 ;; The following variables are defined here because is it also used
3477 ;; when formatting latex fragments. Originally it was part of the
3478 ;; LaTeX exporter, which is why the name includes "export".
3479 (defcustom org-export-latex-default-packages-alist
3480 '(("AUTO" "inputenc" t)
3481 ("T1" "fontenc" t)
3482 ("" "fixltx2e" nil)
3483 ("" "graphicx" t)
3484 ("" "longtable" nil)
3485 ("" "float" nil)
3486 ("" "wrapfig" nil)
3487 ("" "soul" t)
3488 ("" "textcomp" t)
3489 ("" "marvosym" t)
3490 ("" "wasysym" t)
3491 ("" "latexsym" t)
3492 ("" "amssymb" t)
3493 ("" "hyperref" nil)
3494 "\\tolerance=1000"
3496 "Alist of default packages to be inserted in the header.
3497 Change this only if one of the packages here causes an incompatibility
3498 with another package you are using.
3499 The packages in this list are needed by one part or another of Org-mode
3500 to function properly.
3502 - inputenc, fontenc: for basic font and character selection
3503 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3504 for interpreting the entities in `org-entities'. You can skip some of these
3505 packages if you don't use any of the symbols in it.
3506 - graphicx: for including images
3507 - float, wrapfig: for figure placement
3508 - longtable: for long tables
3509 - hyperref: for cross references
3511 Therefore you should not modify this variable unless you know what you
3512 are doing. The one reason to change it anyway is that you might be loading
3513 some other package that conflicts with one of the default packages.
3514 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3515 If SNIPPET-FLAG is t, the package also needs to be included when
3516 compiling LaTeX snippets into images for inclusion into HTML."
3517 :group 'org-export-latex
3518 :set 'org-set-packages-alist
3519 :get 'org-get-packages-alist
3520 :version "24.1"
3521 :type '(repeat
3522 (choice
3523 (list :tag "options/package pair"
3524 (string :tag "options")
3525 (string :tag "package")
3526 (boolean :tag "Snippet"))
3527 (string :tag "A line of LaTeX"))))
3529 (defcustom org-export-latex-packages-alist nil
3530 "Alist of packages to be inserted in every LaTeX header.
3531 These will be inserted after `org-export-latex-default-packages-alist'.
3532 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3533 SNIPPET-FLAG, when t, indicates that this package is also needed when
3534 turning LaTeX snippets into images for inclusion into HTML.
3535 Make sure that you only list packages here which:
3536 - you want in every file
3537 - do not conflict with the default packages in
3538 `org-export-latex-default-packages-alist'
3539 - do not conflict with the setup in `org-format-latex-header'."
3540 :group 'org-export-latex
3541 :set 'org-set-packages-alist
3542 :get 'org-get-packages-alist
3543 :type '(repeat
3544 (choice
3545 (list :tag "options/package pair"
3546 (string :tag "options")
3547 (string :tag "package")
3548 (boolean :tag "Snippet"))
3549 (string :tag "A line of LaTeX"))))
3552 (defgroup org-appearance nil
3553 "Settings for Org-mode appearance."
3554 :tag "Org Appearance"
3555 :group 'org)
3557 (defcustom org-level-color-stars-only nil
3558 "Non-nil means fontify only the stars in each headline.
3559 When nil, the entire headline is fontified.
3560 Changing it requires restart of `font-lock-mode' to become effective
3561 also in regions already fontified."
3562 :group 'org-appearance
3563 :type 'boolean)
3565 (defcustom org-hide-leading-stars nil
3566 "Non-nil means hide the first N-1 stars in a headline.
3567 This works by using the face `org-hide' for these stars. This
3568 face is white for a light background, and black for a dark
3569 background. You may have to customize the face `org-hide' to
3570 make this work.
3571 Changing it requires restart of `font-lock-mode' to become effective
3572 also in regions already fontified.
3573 You may also set this on a per-file basis by adding one of the following
3574 lines to the buffer:
3576 #+STARTUP: hidestars
3577 #+STARTUP: showstars"
3578 :group 'org-appearance
3579 :type 'boolean)
3581 (defcustom org-hidden-keywords nil
3582 "List of symbols corresponding to keywords to be hidden the org buffer.
3583 For example, a value '(title) for this list will make the document's title
3584 appear in the buffer without the initial #+TITLE: keyword."
3585 :group 'org-appearance
3586 :version "24.1"
3587 :type '(set (const :tag "#+AUTHOR" author)
3588 (const :tag "#+DATE" date)
3589 (const :tag "#+EMAIL" email)
3590 (const :tag "#+TITLE" title)))
3592 (defcustom org-fontify-done-headline nil
3593 "Non-nil means change the face of a headline if it is marked DONE.
3594 Normally, only the TODO/DONE keyword indicates the state of a headline.
3595 When this is non-nil, the headline after the keyword is set to the
3596 `org-headline-done' as an additional indication."
3597 :group 'org-appearance
3598 :type 'boolean)
3600 (defcustom org-fontify-emphasized-text t
3601 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3602 Changing this variable requires a restart of Emacs to take effect."
3603 :group 'org-appearance
3604 :type 'boolean)
3606 (defcustom org-fontify-whole-heading-line nil
3607 "Non-nil means fontify the whole line for headings.
3608 This is useful when setting a background color for the
3609 org-level-* faces."
3610 :group 'org-appearance
3611 :type 'boolean)
3613 (defcustom org-highlight-latex-fragments-and-specials nil
3614 "Non-nil means fontify what is treated specially by the exporters."
3615 :group 'org-appearance
3616 :type 'boolean)
3618 (defcustom org-hide-emphasis-markers nil
3619 "Non-nil mean font-lock should hide the emphasis marker characters."
3620 :group 'org-appearance
3621 :type 'boolean)
3623 (defcustom org-pretty-entities nil
3624 "Non-nil means show entities as UTF8 characters.
3625 When nil, the \\name form remains in the buffer."
3626 :group 'org-appearance
3627 :version "24.1"
3628 :type 'boolean)
3630 (defcustom org-pretty-entities-include-sub-superscripts t
3631 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3632 :group 'org-appearance
3633 :version "24.1"
3634 :type 'boolean)
3636 (defvar org-emph-re nil
3637 "Regular expression for matching emphasis.
3638 After a match, the match groups contain these elements:
3639 0 The match of the full regular expression, including the characters
3640 before and after the proper match
3641 1 The character before the proper match, or empty at beginning of line
3642 2 The proper match, including the leading and trailing markers
3643 3 The leading marker like * or /, indicating the type of highlighting
3644 4 The text between the emphasis markers, not including the markers
3645 5 The character after the match, empty at the end of a line")
3646 (defvar org-verbatim-re nil
3647 "Regular expression for matching verbatim text.")
3648 (defvar org-emphasis-regexp-components) ; defined just below
3649 (defvar org-emphasis-alist) ; defined just below
3650 (defun org-set-emph-re (var val)
3651 "Set variable and compute the emphasis regular expression."
3652 (set var val)
3653 (when (and (boundp 'org-emphasis-alist)
3654 (boundp 'org-emphasis-regexp-components)
3655 org-emphasis-alist org-emphasis-regexp-components)
3656 (let* ((e org-emphasis-regexp-components)
3657 (pre (car e))
3658 (post (nth 1 e))
3659 (border (nth 2 e))
3660 (body (nth 3 e))
3661 (nl (nth 4 e))
3662 (body1 (concat body "*?"))
3663 (markers (mapconcat 'car org-emphasis-alist ""))
3664 (vmarkers (mapconcat
3665 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3666 org-emphasis-alist "")))
3667 ;; make sure special characters appear at the right position in the class
3668 (if (string-match "\\^" markers)
3669 (setq markers (concat (replace-match "" t t markers) "^")))
3670 (if (string-match "-" markers)
3671 (setq markers (concat (replace-match "" t t markers) "-")))
3672 (if (string-match "\\^" vmarkers)
3673 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3674 (if (string-match "-" vmarkers)
3675 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3676 (if (> nl 0)
3677 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3678 (int-to-string nl) "\\}")))
3679 ;; Make the regexp
3680 (setq org-emph-re
3681 (concat "\\([" pre "]\\|^\\)"
3682 "\\("
3683 "\\([" markers "]\\)"
3684 "\\("
3685 "[^" border "]\\|"
3686 "[^" border "]"
3687 body1
3688 "[^" border "]"
3689 "\\)"
3690 "\\3\\)"
3691 "\\([" post "]\\|$\\)"))
3692 (setq org-verbatim-re
3693 (concat "\\([" pre "]\\|^\\)"
3694 "\\("
3695 "\\([" vmarkers "]\\)"
3696 "\\("
3697 "[^" border "]\\|"
3698 "[^" border "]"
3699 body1
3700 "[^" border "]"
3701 "\\)"
3702 "\\3\\)"
3703 "\\([" post "]\\|$\\)")))))
3705 (defcustom org-emphasis-regexp-components
3706 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3707 "Components used to build the regular expression for emphasis.
3708 This is a list with five entries. Terminology: In an emphasis string
3709 like \" *strong word* \", we call the initial space PREMATCH, the final
3710 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3711 and \"trong wor\" is the body. The different components in this variable
3712 specify what is allowed/forbidden in each part:
3714 pre Chars allowed as prematch. Beginning of line will be allowed too.
3715 post Chars allowed as postmatch. End of line will be allowed too.
3716 border The chars *forbidden* as border characters.
3717 body-regexp A regexp like \".\" to match a body character. Don't use
3718 non-shy groups here, and don't allow newline here.
3719 newline The maximum number of newlines allowed in an emphasis exp.
3721 Use customize to modify this, or restart Emacs after changing it."
3722 :group 'org-appearance
3723 :set 'org-set-emph-re
3724 :type '(list
3725 (sexp :tag "Allowed chars in pre ")
3726 (sexp :tag "Allowed chars in post ")
3727 (sexp :tag "Forbidden chars in border ")
3728 (sexp :tag "Regexp for body ")
3729 (integer :tag "number of newlines allowed")
3730 (option (boolean :tag "Please ignore this button"))))
3732 (defcustom org-emphasis-alist
3733 `(("*" bold "<b>" "</b>")
3734 ("/" italic "<i>" "</i>")
3735 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3736 ("=" org-code "<code>" "</code>" verbatim)
3737 ("~" org-verbatim "<code>" "</code>" verbatim)
3738 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3739 "<del>" "</del>")
3741 "Special syntax for emphasized text.
3742 Text starting and ending with a special character will be emphasized, for
3743 example *bold*, _underlined_ and /italic/. This variable sets the marker
3744 characters, the face to be used by font-lock for highlighting in Org-mode
3745 Emacs buffers, and the HTML tags to be used for this.
3746 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3747 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3748 Use customize to modify this, or restart Emacs after changing it."
3749 :group 'org-appearance
3750 :set 'org-set-emph-re
3751 :type '(repeat
3752 (list
3753 (string :tag "Marker character")
3754 (choice
3755 (face :tag "Font-lock-face")
3756 (plist :tag "Face property list"))
3757 (string :tag "HTML start tag")
3758 (string :tag "HTML end tag")
3759 (option (const verbatim)))))
3761 (defvar org-protecting-blocks
3762 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3763 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3764 This is needed for font-lock setup.")
3766 ;;; Miscellaneous options
3768 (defgroup org-completion nil
3769 "Completion in Org-mode."
3770 :tag "Org Completion"
3771 :group 'org)
3773 (defcustom org-completion-use-ido nil
3774 "Non-nil means use ido completion wherever possible.
3775 Note that `ido-mode' must be active for this variable to be relevant.
3776 If you decide to turn this variable on, you might well want to turn off
3777 `org-outline-path-complete-in-steps'.
3778 See also `org-completion-use-iswitchb'."
3779 :group 'org-completion
3780 :type 'boolean)
3782 (defcustom org-completion-use-iswitchb nil
3783 "Non-nil means use iswitchb completion wherever possible.
3784 Note that `iswitchb-mode' must be active for this variable to be relevant.
3785 If you decide to turn this variable on, you might well want to turn off
3786 `org-outline-path-complete-in-steps'.
3787 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3788 :group 'org-completion
3789 :type 'boolean)
3791 (defcustom org-completion-fallback-command 'hippie-expand
3792 "The expansion command called by \\[pcomplete] in normal context.
3793 Normal means, no org-mode-specific context."
3794 :group 'org-completion
3795 :type 'function)
3797 ;;; Functions and variables from their packages
3798 ;; Declared here to avoid compiler warnings
3800 ;; XEmacs only
3801 (defvar outline-mode-menu-heading)
3802 (defvar outline-mode-menu-show)
3803 (defvar outline-mode-menu-hide)
3804 (defvar zmacs-regions) ; XEmacs regions
3806 ;; Emacs only
3807 (defvar mark-active)
3809 ;; Various packages
3810 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3811 (declare-function calendar-forward-day "cal-move" (arg))
3812 (declare-function calendar-goto-date "cal-move" (date))
3813 (declare-function calendar-goto-today "cal-move" ())
3814 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3815 (defvar calc-embedded-close-formula)
3816 (defvar calc-embedded-open-formula)
3817 (declare-function cdlatex-tab "ext:cdlatex" ())
3818 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3819 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3820 (defvar font-lock-unfontify-region-function)
3821 (declare-function iswitchb-read-buffer "iswitchb"
3822 (prompt &optional default require-match start matches-set))
3823 (defvar iswitchb-temp-buflist)
3824 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3825 (defvar org-agenda-tags-todo-honor-ignore-options)
3826 (declare-function org-agenda-skip "org-agenda" ())
3827 (declare-function
3828 org-agenda-format-item "org-agenda"
3829 (extra txt &optional category tags dotime noprefix remove-re habitp))
3830 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3831 (declare-function org-agenda-change-all-lines "org-agenda"
3832 (newhead hdmarker &optional fixface just-this))
3833 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3834 (declare-function org-agenda-maybe-redo "org-agenda" ())
3835 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3836 (beg end))
3837 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3838 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3839 "org-agenda" (&optional end))
3840 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3841 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3842 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3843 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3844 (declare-function org-indent-mode "org-indent" (&optional arg))
3845 (declare-function parse-time-string "parse-time" (string))
3846 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3847 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3848 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3849 (defvar remember-data-file)
3850 (defvar texmathp-why)
3851 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3852 (declare-function table--at-cell-p "table" (position &optional object at-column))
3854 (defvar w3m-current-url)
3855 (defvar w3m-current-title)
3857 (defvar org-latex-regexps)
3859 ;;; Autoload and prepare some org modules
3861 ;; Some table stuff that needs to be defined here, because it is used
3862 ;; by the functions setting up org-mode or checking for table context.
3864 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3865 "Detect an org-type or table-type table.")
3866 (defconst org-table-line-regexp "^[ \t]*|"
3867 "Detect an org-type table line.")
3868 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3869 "Detect an org-type table line.")
3870 (defconst org-table-hline-regexp "^[ \t]*|-"
3871 "Detect an org-type table hline.")
3872 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3873 "Detect a table-type table hline.")
3874 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3875 "Detect the first line outside a table when searching from within it.
3876 This works for both table types.")
3878 ;; Autoload the functions in org-table.el that are needed by functions here.
3880 (eval-and-compile
3881 (org-autoload "org-table"
3882 '(org-table-align org-table-begin org-table-blank-field
3883 org-table-convert org-table-convert-region org-table-copy-down
3884 org-table-copy-region org-table-create
3885 org-table-create-or-convert-from-region
3886 org-table-create-with-table.el org-table-current-dline
3887 org-table-cut-region org-table-delete-column org-table-edit-field
3888 org-table-edit-formulas org-table-end org-table-eval-formula
3889 org-table-export org-table-field-info
3890 org-table-get-stored-formulas org-table-goto-column
3891 org-table-hline-and-move org-table-import org-table-insert-column
3892 org-table-insert-hline org-table-insert-row org-table-iterate
3893 org-table-justify-field-maybe org-table-kill-row
3894 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3895 org-table-move-column org-table-move-column-left
3896 org-table-move-column-right org-table-move-row
3897 org-table-move-row-down org-table-move-row-up
3898 org-table-next-field org-table-next-row org-table-paste-rectangle
3899 org-table-previous-field org-table-recalculate
3900 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3901 org-table-toggle-coordinate-overlays
3902 org-table-toggle-formula-debugger org-table-wrap-region
3903 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3904 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3905 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3907 (defun org-at-table-p (&optional table-type)
3908 "Return t if the cursor is inside an org-type table.
3909 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3910 (if org-enable-table-editor
3911 (save-excursion
3912 (beginning-of-line 1)
3913 (looking-at (if table-type org-table-any-line-regexp
3914 org-table-line-regexp)))
3915 nil))
3916 (defsubst org-table-p () (org-at-table-p))
3918 (defun org-at-table.el-p ()
3919 "Return t if and only if we are at a table.el table."
3920 (and (org-at-table-p 'any)
3921 (save-excursion
3922 (goto-char (org-table-begin 'any))
3923 (looking-at org-table1-hline-regexp))))
3924 (defun org-table-recognize-table.el ()
3925 "If there is a table.el table nearby, recognize it and move into it."
3926 (if org-table-tab-recognizes-table.el
3927 (if (org-at-table.el-p)
3928 (progn
3929 (beginning-of-line 1)
3930 (if (looking-at org-table-dataline-regexp)
3932 (if (looking-at org-table1-hline-regexp)
3933 (progn
3934 (beginning-of-line 2)
3935 (if (looking-at org-table-any-border-regexp)
3936 (beginning-of-line -1)))))
3937 (if (re-search-forward "|" (org-table-end t) t)
3938 (progn
3939 (require 'table)
3940 (if (table--at-cell-p (point))
3942 (message "recognizing table.el table...")
3943 (table-recognize-table)
3944 (message "recognizing table.el table...done")))
3945 (error "This should not happen"))
3947 nil)
3948 nil))
3950 (defun org-at-table-hline-p ()
3951 "Return t if the cursor is inside a hline in a table."
3952 (if org-enable-table-editor
3953 (save-excursion
3954 (beginning-of-line 1)
3955 (looking-at org-table-hline-regexp))
3956 nil))
3958 (defvar org-table-clean-did-remove-column nil)
3960 (defun org-table-map-tables (function &optional quietly)
3961 "Apply FUNCTION to the start of all tables in the buffer."
3962 (save-excursion
3963 (save-restriction
3964 (widen)
3965 (goto-char (point-min))
3966 (while (re-search-forward org-table-any-line-regexp nil t)
3967 (unless quietly
3968 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3969 (beginning-of-line 1)
3970 (when (and (looking-at org-table-line-regexp)
3971 ;; Exclude tables in src/example/verbatim/clocktable blocks
3972 (not (org-in-block-p '("src" "example"))))
3973 (save-excursion (funcall function))
3974 (or (looking-at org-table-line-regexp)
3975 (forward-char 1)))
3976 (re-search-forward org-table-any-border-regexp nil 1))))
3977 (unless quietly (message "Mapping tables: done")))
3979 ;; Declare and autoload functions from org-exp.el & Co
3981 (declare-function org-default-export-plist "org-exp")
3982 (declare-function org-infile-export-plist "org-exp")
3983 (declare-function org-get-current-options "org-exp")
3984 (eval-and-compile
3985 (org-autoload "org-exp"
3986 '(org-export org-export-visible
3987 org-insert-export-options-template
3988 org-table-clean-before-export))
3989 (org-autoload "org-ascii"
3990 '(org-export-as-ascii org-export-ascii-preprocess
3991 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3992 org-export-region-as-ascii))
3993 (org-autoload "org-latex"
3994 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3995 org-replace-region-by-latex org-export-region-as-latex
3996 org-export-as-latex org-export-as-pdf
3997 org-export-as-pdf-and-open))
3998 (org-autoload "org-html"
3999 '(org-export-as-html-and-open
4000 org-export-as-html-batch org-export-as-html-to-buffer
4001 org-replace-region-by-html org-export-region-as-html
4002 org-export-as-html))
4003 (org-autoload "org-docbook"
4004 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4005 org-replace-region-by-docbook org-export-region-as-docbook
4006 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4007 org-export-as-docbook))
4008 (org-autoload "org-icalendar"
4009 '(org-export-icalendar-this-file
4010 org-export-icalendar-all-agenda-files
4011 org-export-icalendar-combine-agenda-files))
4012 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4013 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4015 ;; Declare and autoload functions from org-agenda.el
4017 (eval-and-compile
4018 (org-autoload "org-agenda"
4019 '(org-agenda org-agenda-list org-search-view
4020 org-todo-list org-tags-view org-agenda-list-stuck-projects
4021 org-diary org-agenda-to-appt
4022 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4024 ;; Autoload org-remember
4026 (eval-and-compile
4027 (org-autoload "org-remember"
4028 '(org-remember-insinuate org-remember-annotation
4029 org-remember-apply-template org-remember org-remember-handler)))
4031 (eval-and-compile
4032 (org-autoload "org-capture"
4033 '(org-capture org-capture-insert-template-here
4034 org-capture-import-remember-templates)))
4036 ;; Autoload org-clock.el
4038 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4039 (beg end))
4040 (declare-function org-clock-update-mode-line "org-clock" ())
4041 (declare-function org-resolve-clocks "org-clock"
4042 (&optional also-non-dangling-p prompt last-valid))
4043 (defvar org-clock-start-time)
4044 (defvar org-clock-marker (make-marker)
4045 "Marker recording the last clock-in.")
4046 (defvar org-clock-hd-marker (make-marker)
4047 "Marker recording the last clock-in, but the headline position.")
4048 (defvar org-clock-heading ""
4049 "The heading of the current clock entry.")
4050 (defun org-clock-is-active ()
4051 "Return non-nil if clock is currently running.
4052 The return value is actually the clock marker."
4053 (marker-buffer org-clock-marker))
4055 (eval-and-compile
4056 (org-autoload
4057 "org-clock"
4058 '(org-clock-in org-clock-out org-clock-cancel
4059 org-clock-goto org-clock-sum org-clock-display
4060 org-clock-remove-overlays org-clock-report
4061 org-clocktable-shift org-dblock-write:clocktable
4062 org-get-clocktable org-resolve-clocks)))
4064 (defun org-clock-update-time-maybe ()
4065 "If this is a CLOCK line, update it and return t.
4066 Otherwise, return nil."
4067 (interactive)
4068 (save-excursion
4069 (beginning-of-line 1)
4070 (skip-chars-forward " \t")
4071 (when (looking-at org-clock-string)
4072 (let ((re (concat "[ \t]*" org-clock-string
4073 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4074 "\\([ \t]*=>.*\\)?\\)?"))
4075 ts te h m s neg)
4076 (cond
4077 ((not (looking-at re))
4078 nil)
4079 ((not (match-end 2))
4080 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4081 (> org-clock-marker (point))
4082 (<= org-clock-marker (point-at-eol)))
4083 ;; The clock is running here
4084 (setq org-clock-start-time
4085 (apply 'encode-time
4086 (org-parse-time-string (match-string 1))))
4087 (org-clock-update-mode-line)))
4089 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4090 (end-of-line 1)
4091 (setq ts (match-string 1)
4092 te (match-string 3))
4093 (setq s (- (org-float-time
4094 (apply 'encode-time (org-parse-time-string te)))
4095 (org-float-time
4096 (apply 'encode-time (org-parse-time-string ts))))
4097 neg (< s 0)
4098 s (abs s)
4099 h (floor (/ s 3600))
4100 s (- s (* 3600 h))
4101 m (floor (/ s 60))
4102 s (- s (* 60 s)))
4103 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4104 t))))))
4106 (defun org-check-running-clock ()
4107 "Check if the current buffer contains the running clock.
4108 If yes, offer to stop it and to save the buffer with the changes."
4109 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4110 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4111 (buffer-name))))
4112 (org-clock-out)
4113 (when (y-or-n-p "Save changed buffer?")
4114 (save-buffer))))
4116 (defun org-clocktable-try-shift (dir n)
4117 "Check if this line starts a clock table, if yes, shift the time block."
4118 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4119 (org-clocktable-shift dir n)))
4121 ;; Autoload org-timer.el
4123 (eval-and-compile
4124 (org-autoload
4125 "org-timer"
4126 '(org-timer-start org-timer org-timer-item
4127 org-timer-change-times-in-region
4128 org-timer-set-timer
4129 org-timer-reset-timers
4130 org-timer-show-remaining-time)))
4132 ;; Autoload org-feed.el
4134 (eval-and-compile
4135 (org-autoload
4136 "org-feed"
4137 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4140 ;; Autoload org-indent.el
4142 ;; Define the variable already here, to make sure we have it.
4143 (defvar org-indent-mode nil
4144 "Non-nil if Org-Indent mode is enabled.
4145 Use the command `org-indent-mode' to change this variable.")
4147 (eval-and-compile
4148 (org-autoload
4149 "org-indent"
4150 '(org-indent-mode)))
4152 ;; Autoload org-mobile.el
4154 (eval-and-compile
4155 (org-autoload
4156 "org-mobile"
4157 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4159 ;; Autoload archiving code
4160 ;; The stuff that is needed for cycling and tags has to be defined here.
4162 (defgroup org-archive nil
4163 "Options concerning archiving in Org-mode."
4164 :tag "Org Archive"
4165 :group 'org-structure)
4167 (defcustom org-archive-location "%s_archive::"
4168 "The location where subtrees should be archived.
4170 The value of this variable is a string, consisting of two parts,
4171 separated by a double-colon. The first part is a filename and
4172 the second part is a headline.
4174 When the filename is omitted, archiving happens in the same file.
4175 %s in the filename will be replaced by the current file
4176 name (without the directory part). Archiving to a different file
4177 is useful to keep archived entries from contributing to the
4178 Org-mode Agenda.
4180 The archived entries will be filed as subtrees of the specified
4181 headline. When the headline is omitted, the subtrees are simply
4182 filed away at the end of the file, as top-level entries. Also in
4183 the heading you can use %s to represent the file name, this can be
4184 useful when using the same archive for a number of different files.
4186 Here are a few examples:
4187 \"%s_archive::\"
4188 If the current file is Projects.org, archive in file
4189 Projects.org_archive, as top-level trees. This is the default.
4191 \"::* Archived Tasks\"
4192 Archive in the current file, under the top-level headline
4193 \"* Archived Tasks\".
4195 \"~/org/archive.org::\"
4196 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4198 \"~/org/archive.org::* From %s\"
4199 Archive in file ~/org/archive.org (absolute path), under headlines
4200 \"From FILENAME\" where file name is the current file name.
4202 \"~/org/datetree.org::datetree/* Finished Tasks\"
4203 The \"datetree/\" string is special, signifying to archive
4204 items to the datetree. Items are placed in either the CLOSED
4205 date of the item, or the current date if there is no CLOSED date.
4206 The heading will be a subentry to the current date. There doesn't
4207 need to be a heading, but there always needs to be a slash after
4208 datetree. For example, to store archived items directly in the
4209 datetree, use \"~/org/datetree.org::datetree/\".
4211 \"basement::** Finished Tasks\"
4212 Archive in file ./basement (relative path), as level 3 trees
4213 below the level 2 heading \"** Finished Tasks\".
4215 You may set this option on a per-file basis by adding to the buffer a
4216 line like
4218 #+ARCHIVE: basement::** Finished Tasks
4220 You may also define it locally for a subtree by setting an ARCHIVE property
4221 in the entry. If such a property is found in an entry, or anywhere up
4222 the hierarchy, it will be used."
4223 :group 'org-archive
4224 :type 'string)
4226 (defcustom org-archive-tag "ARCHIVE"
4227 "The tag that marks a subtree as archived.
4228 An archived subtree does not open during visibility cycling, and does
4229 not contribute to the agenda listings.
4230 After changing this, font-lock must be restarted in the relevant buffers to
4231 get the proper fontification."
4232 :group 'org-archive
4233 :group 'org-keywords
4234 :type 'string)
4236 (defcustom org-agenda-skip-archived-trees t
4237 "Non-nil means the agenda will skip any items located in archived trees.
4238 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4239 variable is no longer recommended, you should leave it at the value t.
4240 Instead, use the key `v' to cycle the archives-mode in the agenda."
4241 :group 'org-archive
4242 :group 'org-agenda-skip
4243 :type 'boolean)
4245 (defcustom org-columns-skip-archived-trees t
4246 "Non-nil means ignore archived trees when creating column view."
4247 :group 'org-archive
4248 :group 'org-properties
4249 :type 'boolean)
4251 (defcustom org-cycle-open-archived-trees nil
4252 "Non-nil means `org-cycle' will open archived trees.
4253 An archived tree is a tree marked with the tag ARCHIVE.
4254 When nil, archived trees will stay folded. You can still open them with
4255 normal outline commands like `show-all', but not with the cycling commands."
4256 :group 'org-archive
4257 :group 'org-cycle
4258 :type 'boolean)
4260 (defcustom org-sparse-tree-open-archived-trees nil
4261 "Non-nil means sparse tree construction shows matches in archived trees.
4262 When nil, matches in these trees are highlighted, but the trees are kept in
4263 collapsed state."
4264 :group 'org-archive
4265 :group 'org-sparse-trees
4266 :type 'boolean)
4268 (defun org-cycle-hide-archived-subtrees (state)
4269 "Re-hide all archived subtrees after a visibility state change."
4270 (when (and (not org-cycle-open-archived-trees)
4271 (not (memq state '(overview folded))))
4272 (save-excursion
4273 (let* ((globalp (memq state '(contents all)))
4274 (beg (if globalp (point-min) (point)))
4275 (end (if globalp (point-max) (org-end-of-subtree t))))
4276 (org-hide-archived-subtrees beg end)
4277 (goto-char beg)
4278 (if (looking-at (concat ".*:" org-archive-tag ":"))
4279 (message "%s" (substitute-command-keys
4280 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4282 (defun org-force-cycle-archived ()
4283 "Cycle subtree even if it is archived."
4284 (interactive)
4285 (setq this-command 'org-cycle)
4286 (let ((org-cycle-open-archived-trees t))
4287 (call-interactively 'org-cycle)))
4289 (defun org-hide-archived-subtrees (beg end)
4290 "Re-hide all archived subtrees after a visibility state change."
4291 (save-excursion
4292 (let* ((re (concat ":" org-archive-tag ":")))
4293 (goto-char beg)
4294 (while (re-search-forward re end t)
4295 (when (org-at-heading-p)
4296 (org-flag-subtree t)
4297 (org-end-of-subtree t))))))
4299 (defun org-flag-subtree (flag)
4300 (save-excursion
4301 (org-back-to-heading t)
4302 (outline-end-of-heading)
4303 (outline-flag-region (point)
4304 (progn (org-end-of-subtree t) (point))
4305 flag)))
4307 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4309 (eval-and-compile
4310 (org-autoload "org-archive"
4311 '(org-add-archive-files org-archive-subtree
4312 org-archive-to-archive-sibling org-toggle-archive-tag
4313 org-archive-subtree-default
4314 org-archive-subtree-default-with-confirmation)))
4316 ;; Autoload Column View Code
4318 (declare-function org-columns-number-to-string "org-colview")
4319 (declare-function org-columns-get-format-and-top-level "org-colview")
4320 (declare-function org-columns-compute "org-colview")
4322 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4323 '(org-columns-number-to-string org-columns-get-format-and-top-level
4324 org-columns-compute org-agenda-columns org-columns-remove-overlays
4325 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4327 ;; Autoload ID code
4329 (declare-function org-id-store-link "org-id")
4330 (declare-function org-id-locations-load "org-id")
4331 (declare-function org-id-locations-save "org-id")
4332 (defvar org-id-track-globally)
4333 (org-autoload "org-id"
4334 '(org-id-get-create org-id-new org-id-copy org-id-get
4335 org-id-get-with-outline-path-completion
4336 org-id-get-with-outline-drilling org-id-store-link
4337 org-id-goto org-id-find org-id-store-link))
4339 ;; Autoload Plotting Code
4341 (org-autoload "org-plot"
4342 '(org-plot/gnuplot))
4344 ;;; Variables for pre-computed regular expressions, all buffer local
4346 (defvar org-drawer-regexp nil
4347 "Matches first line of a hidden block.")
4348 (make-variable-buffer-local 'org-drawer-regexp)
4349 (defvar org-todo-regexp nil
4350 "Matches any of the TODO state keywords.")
4351 (make-variable-buffer-local 'org-todo-regexp)
4352 (defvar org-not-done-regexp nil
4353 "Matches any of the TODO state keywords except the last one.")
4354 (make-variable-buffer-local 'org-not-done-regexp)
4355 (defvar org-not-done-heading-regexp nil
4356 "Matches a TODO headline that is not done.")
4357 (make-variable-buffer-local 'org-not-done-regexp)
4358 (defvar org-todo-line-regexp nil
4359 "Matches a headline and puts TODO state into group 2 if present.")
4360 (make-variable-buffer-local 'org-todo-line-regexp)
4361 (defvar org-complex-heading-regexp nil
4362 "Matches a headline and puts everything into groups:
4363 group 1: the stars
4364 group 2: The todo keyword, maybe
4365 group 3: Priority cookie
4366 group 4: True headline
4367 group 5: Tags")
4368 (make-variable-buffer-local 'org-complex-heading-regexp)
4369 (defvar org-complex-heading-regexp-format nil
4370 "Printf format to make regexp to match an exact headline.
4371 This regexp will match the headline of any node which has the
4372 exact headline text that is put into the format, but may have any
4373 TODO state, priority and tags.")
4374 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4375 (defvar org-todo-line-tags-regexp nil
4376 "Matches a headline and puts TODO state into group 2 if present.
4377 Also put tags into group 4 if tags are present.")
4378 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4379 (defvar org-ds-keyword-length 12
4380 "Maximum length of the Deadline and SCHEDULED keywords.")
4381 (make-variable-buffer-local 'org-ds-keyword-length)
4382 (defvar org-deadline-regexp nil
4383 "Matches the DEADLINE keyword.")
4384 (make-variable-buffer-local 'org-deadline-regexp)
4385 (defvar org-deadline-time-regexp nil
4386 "Matches the DEADLINE keyword together with a time stamp.")
4387 (make-variable-buffer-local 'org-deadline-time-regexp)
4388 (defvar org-deadline-line-regexp nil
4389 "Matches the DEADLINE keyword and the rest of the line.")
4390 (make-variable-buffer-local 'org-deadline-line-regexp)
4391 (defvar org-scheduled-regexp nil
4392 "Matches the SCHEDULED keyword.")
4393 (make-variable-buffer-local 'org-scheduled-regexp)
4394 (defvar org-scheduled-time-regexp nil
4395 "Matches the SCHEDULED keyword together with a time stamp.")
4396 (make-variable-buffer-local 'org-scheduled-time-regexp)
4397 (defvar org-closed-time-regexp nil
4398 "Matches the CLOSED keyword together with a time stamp.")
4399 (make-variable-buffer-local 'org-closed-time-regexp)
4401 (defvar org-keyword-time-regexp nil
4402 "Matches any of the 4 keywords, together with the time stamp.")
4403 (make-variable-buffer-local 'org-keyword-time-regexp)
4404 (defvar org-keyword-time-not-clock-regexp nil
4405 "Matches any of the 3 keywords, together with the time stamp.")
4406 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4407 (defvar org-maybe-keyword-time-regexp nil
4408 "Matches a timestamp, possibly preceded by a keyword.")
4409 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4410 (defvar org-planning-or-clock-line-re nil
4411 "Matches a line with planning or clock info.")
4412 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4413 (defvar org-all-time-keywords nil
4414 "List of time keywords.")
4415 (make-variable-buffer-local 'org-all-time-keywords)
4417 (defconst org-plain-time-of-day-regexp
4418 (concat
4419 "\\(\\<[012]?[0-9]"
4420 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4421 "\\(--?"
4422 "\\(\\<[012]?[0-9]"
4423 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4424 "\\)?")
4425 "Regular expression to match a plain time or time range.
4426 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4427 groups carry important information:
4428 0 the full match
4429 1 the first time, range or not
4430 8 the second time, if it is a range.")
4432 (defconst org-plain-time-extension-regexp
4433 (concat
4434 "\\(\\<[012]?[0-9]"
4435 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4436 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4437 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4438 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4439 groups carry important information:
4440 0 the full match
4441 7 hours of duration
4442 9 minutes of duration")
4444 (defconst org-stamp-time-of-day-regexp
4445 (concat
4446 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4447 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4448 "\\(--?"
4449 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4450 "Regular expression to match a timestamp time or time range.
4451 After a match, the following groups carry important information:
4452 0 the full match
4453 1 date plus weekday, for back referencing to make sure both times are on the same day
4454 2 the first time, range or not
4455 4 the second time, if it is a range.")
4457 (defconst org-startup-options
4458 '(("fold" org-startup-folded t)
4459 ("overview" org-startup-folded t)
4460 ("nofold" org-startup-folded nil)
4461 ("showall" org-startup-folded nil)
4462 ("showeverything" org-startup-folded showeverything)
4463 ("content" org-startup-folded content)
4464 ("indent" org-startup-indented t)
4465 ("noindent" org-startup-indented nil)
4466 ("hidestars" org-hide-leading-stars t)
4467 ("showstars" org-hide-leading-stars nil)
4468 ("odd" org-odd-levels-only t)
4469 ("oddeven" org-odd-levels-only nil)
4470 ("align" org-startup-align-all-tables t)
4471 ("noalign" org-startup-align-all-tables nil)
4472 ("inlineimages" org-startup-with-inline-images t)
4473 ("noinlineimages" org-startup-with-inline-images nil)
4474 ("customtime" org-display-custom-times t)
4475 ("logdone" org-log-done time)
4476 ("lognotedone" org-log-done note)
4477 ("nologdone" org-log-done nil)
4478 ("lognoteclock-out" org-log-note-clock-out t)
4479 ("nolognoteclock-out" org-log-note-clock-out nil)
4480 ("logrepeat" org-log-repeat state)
4481 ("lognoterepeat" org-log-repeat note)
4482 ("nologrepeat" org-log-repeat nil)
4483 ("logreschedule" org-log-reschedule time)
4484 ("lognotereschedule" org-log-reschedule note)
4485 ("nologreschedule" org-log-reschedule nil)
4486 ("logredeadline" org-log-redeadline time)
4487 ("lognoteredeadline" org-log-redeadline note)
4488 ("nologredeadline" org-log-redeadline nil)
4489 ("logrefile" org-log-refile time)
4490 ("lognoterefile" org-log-refile note)
4491 ("nologrefile" org-log-refile nil)
4492 ("fninline" org-footnote-define-inline t)
4493 ("nofninline" org-footnote-define-inline nil)
4494 ("fnlocal" org-footnote-section nil)
4495 ("fnauto" org-footnote-auto-label t)
4496 ("fnprompt" org-footnote-auto-label nil)
4497 ("fnconfirm" org-footnote-auto-label confirm)
4498 ("fnplain" org-footnote-auto-label plain)
4499 ("fnadjust" org-footnote-auto-adjust t)
4500 ("nofnadjust" org-footnote-auto-adjust nil)
4501 ("constcgs" constants-unit-system cgs)
4502 ("constSI" constants-unit-system SI)
4503 ("noptag" org-tag-persistent-alist nil)
4504 ("hideblocks" org-hide-block-startup t)
4505 ("nohideblocks" org-hide-block-startup nil)
4506 ("beamer" org-startup-with-beamer-mode t)
4507 ("entitiespretty" org-pretty-entities t)
4508 ("entitiesplain" org-pretty-entities nil))
4509 "Variable associated with STARTUP options for org-mode.
4510 Each element is a list of three items: The startup options as written
4511 in the #+STARTUP line, the corresponding variable, and the value to
4512 set this variable to if the option is found. An optional forth element PUSH
4513 means to push this value onto the list in the variable.")
4515 (defun org-update-property-plist (key val props)
4516 "Update PROPS with KEY and VAL."
4517 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4518 (key (if appending (substring key 0 (- (length key) 1)) key))
4519 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4520 (previous (cdr (assoc key props))))
4521 (if appending
4522 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4523 (cons (cons key val) remainder))))
4525 (defconst org-block-regexp
4526 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4527 "Regular expression for hiding blocks.")
4528 (defconst org-heading-keyword-regexp-format
4529 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4530 "Printf format for a regexp matching an headline with some keyword.
4531 This regexp will match the headline of any node which has the
4532 exact keyword that is put into the format. The keyword isn't in
4533 any group by default, but the stars and the body are.")
4534 (defconst org-heading-keyword-maybe-regexp-format
4535 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4536 "Printf format for a regexp matching an headline, possibly with some keyword.
4537 This regexp can match any headline with the specified keyword, or
4538 without a keyword. The keyword isn't in any group by default,
4539 but the stars and the body are.")
4541 (defun org-set-regexps-and-options ()
4542 "Precompute regular expressions for current buffer."
4543 (when (derived-mode-p 'org-mode)
4544 (org-set-local 'org-todo-kwd-alist nil)
4545 (org-set-local 'org-todo-key-alist nil)
4546 (org-set-local 'org-todo-key-trigger nil)
4547 (org-set-local 'org-todo-keywords-1 nil)
4548 (org-set-local 'org-done-keywords nil)
4549 (org-set-local 'org-todo-heads nil)
4550 (org-set-local 'org-todo-sets nil)
4551 (org-set-local 'org-todo-log-states nil)
4552 (org-set-local 'org-file-properties nil)
4553 (org-set-local 'org-file-tags nil)
4554 (let ((re (org-make-options-regexp
4555 '("CATEGORY" "TODO" "COLUMNS"
4556 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4557 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4558 "OPTIONS")
4559 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4560 (splitre "[ \t]+")
4561 (scripts org-use-sub-superscripts)
4562 kwds kws0 kwsa key log value cat arch tags const links hw dws
4563 tail sep kws1 prio props ftags drawers beamer-p
4564 ext-setup-or-nil setup-contents (start 0))
4565 (save-excursion
4566 (save-restriction
4567 (widen)
4568 (goto-char (point-min))
4569 (while (or (and ext-setup-or-nil
4570 (string-match re ext-setup-or-nil start)
4571 (setq start (match-end 0)))
4572 (and (setq ext-setup-or-nil nil start 0)
4573 (re-search-forward re nil t)))
4574 (setq key (upcase (match-string 1 ext-setup-or-nil))
4575 value (org-match-string-no-properties 2 ext-setup-or-nil))
4576 (if (stringp value) (setq value (org-trim value)))
4577 (cond
4578 ((equal key "CATEGORY")
4579 (setq cat value))
4580 ((member key '("SEQ_TODO" "TODO"))
4581 (push (cons 'sequence (org-split-string value splitre)) kwds))
4582 ((equal key "TYP_TODO")
4583 (push (cons 'type (org-split-string value splitre)) kwds))
4584 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4585 ;; general TODO-like setup
4586 (push (cons (intern (downcase (match-string 1 key)))
4587 (org-split-string value splitre)) kwds))
4588 ((equal key "TAGS")
4589 (setq tags (append tags (if tags '("\\n") nil)
4590 (org-split-string value splitre))))
4591 ((equal key "COLUMNS")
4592 (org-set-local 'org-columns-default-format value))
4593 ((equal key "LINK")
4594 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4595 (push (cons (match-string 1 value)
4596 (org-trim (match-string 2 value)))
4597 links)))
4598 ((equal key "PRIORITIES")
4599 (setq prio (org-split-string value " +")))
4600 ((equal key "PROPERTY")
4601 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4602 (setq props (org-update-property-plist (match-string 1 value)
4603 (match-string 2 value)
4604 props))))
4605 ((equal key "FILETAGS")
4606 (when (string-match "\\S-" value)
4607 (setq ftags
4608 (append
4609 ftags
4610 (apply 'append
4611 (mapcar (lambda (x) (org-split-string x ":"))
4612 (org-split-string value)))))))
4613 ((equal key "DRAWERS")
4614 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4615 ((equal key "CONSTANTS")
4616 (setq const (append const (org-split-string value splitre))))
4617 ((equal key "STARTUP")
4618 (let ((opts (org-split-string value splitre))
4619 l var val)
4620 (while (setq l (pop opts))
4621 (when (setq l (assoc l org-startup-options))
4622 (setq var (nth 1 l) val (nth 2 l))
4623 (if (not (nth 3 l))
4624 (set (make-local-variable var) val)
4625 (if (not (listp (symbol-value var)))
4626 (set (make-local-variable var) nil))
4627 (set (make-local-variable var) (symbol-value var))
4628 (add-to-list var val))))))
4629 ((equal key "ARCHIVE")
4630 (setq arch value)
4631 (remove-text-properties 0 (length arch)
4632 '(face t fontified t) arch))
4633 ((equal key "LATEX_CLASS")
4634 (setq beamer-p (equal value "beamer")))
4635 ((equal key "OPTIONS")
4636 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4637 (setq scripts (read (match-string 2 value)))))
4638 ((equal key "SETUPFILE")
4639 (setq setup-contents (org-file-contents
4640 (expand-file-name
4641 (org-remove-double-quotes value))
4642 'noerror))
4643 (if (not ext-setup-or-nil)
4644 (setq ext-setup-or-nil setup-contents start 0)
4645 (setq ext-setup-or-nil
4646 (concat (substring ext-setup-or-nil 0 start)
4647 "\n" setup-contents "\n"
4648 (substring ext-setup-or-nil start)))))))
4649 ;; search for property blocks
4650 (goto-char (point-min))
4651 (while (re-search-forward org-block-regexp nil t)
4652 (when (equal "PROPERTY" (upcase (match-string 1)))
4653 (setq value (replace-regexp-in-string
4654 "[\n\r]" " " (match-string 4)))
4655 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4656 (setq props (org-update-property-plist (match-string 1 value)
4657 (match-string 2 value)
4658 props)))))))
4659 (org-set-local 'org-use-sub-superscripts scripts)
4660 (when cat
4661 (org-set-local 'org-category (intern cat))
4662 (push (cons "CATEGORY" cat) props))
4663 (when prio
4664 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4665 (setq prio (mapcar 'string-to-char prio))
4666 (org-set-local 'org-highest-priority (nth 0 prio))
4667 (org-set-local 'org-lowest-priority (nth 1 prio))
4668 (org-set-local 'org-default-priority (nth 2 prio)))
4669 (and props (org-set-local 'org-file-properties (nreverse props)))
4670 (and ftags (org-set-local 'org-file-tags
4671 (mapcar 'org-add-prop-inherited ftags)))
4672 (and drawers (org-set-local 'org-drawers drawers))
4673 (and arch (org-set-local 'org-archive-location arch))
4674 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4675 ;; Process the TODO keywords
4676 (unless kwds
4677 ;; Use the global values as if they had been given locally.
4678 (setq kwds (default-value 'org-todo-keywords))
4679 (if (stringp (car kwds))
4680 (setq kwds (list (cons org-todo-interpretation
4681 (default-value 'org-todo-keywords)))))
4682 (setq kwds (reverse kwds)))
4683 (setq kwds (nreverse kwds))
4684 (let (inter kws kw)
4685 (while (setq kws (pop kwds))
4686 (let ((kws (or
4687 (run-hook-with-args-until-success
4688 'org-todo-setup-filter-hook kws)
4689 kws)))
4690 (setq inter (pop kws) sep (member "|" kws)
4691 kws0 (delete "|" (copy-sequence kws))
4692 kwsa nil
4693 kws1 (mapcar
4694 (lambda (x)
4695 ;; 1 2
4696 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4697 (progn
4698 (setq kw (match-string 1 x)
4699 key (and (match-end 2) (match-string 2 x))
4700 log (org-extract-log-state-settings x))
4701 (push (cons kw (and key (string-to-char key))) kwsa)
4702 (and log (push log org-todo-log-states))
4704 (error "Invalid TODO keyword %s" x)))
4705 kws0)
4706 kwsa (if kwsa (append '((:startgroup))
4707 (nreverse kwsa)
4708 '((:endgroup))))
4709 hw (car kws1)
4710 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4711 tail (list inter hw (car dws) (org-last dws))))
4712 (add-to-list 'org-todo-heads hw 'append)
4713 (push kws1 org-todo-sets)
4714 (setq org-done-keywords (append org-done-keywords dws nil))
4715 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4716 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4717 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4718 (setq org-todo-sets (nreverse org-todo-sets)
4719 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4720 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4721 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4722 ;; Process the constants
4723 (when const
4724 (let (e cst)
4725 (while (setq e (pop const))
4726 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4727 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4728 (setq org-table-formula-constants-local cst)))
4730 ;; Process the tags.
4731 (when tags
4732 (let (e tgs)
4733 (while (setq e (pop tags))
4734 (cond
4735 ((equal e "{") (push '(:startgroup) tgs))
4736 ((equal e "}") (push '(:endgroup) tgs))
4737 ((equal e "\\n") (push '(:newline) tgs))
4738 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4739 (push (cons (match-string 1 e)
4740 (string-to-char (match-string 2 e)))
4741 tgs))
4742 (t (push (list e) tgs))))
4743 (org-set-local 'org-tag-alist nil)
4744 (while (setq e (pop tgs))
4745 (or (and (stringp (car e))
4746 (assoc (car e) org-tag-alist))
4747 (push e org-tag-alist)))))
4749 ;; Compute the regular expressions and other local variables.
4750 ;; Using `org-outline-regexp-bol' would complicate them much,
4751 ;; because of the fixed white space at the end of that string.
4752 (if (not org-done-keywords)
4753 (setq org-done-keywords (and org-todo-keywords-1
4754 (list (org-last org-todo-keywords-1)))))
4755 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4756 (length org-scheduled-string)
4757 (length org-clock-string)
4758 (length org-closed-string)))
4759 org-drawer-regexp
4760 (concat "^[ \t]*:\\("
4761 (mapconcat 'regexp-quote org-drawers "\\|")
4762 "\\):[ \t]*$")
4763 org-not-done-keywords
4764 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4765 org-todo-regexp
4766 (concat "\\("
4767 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4768 "\\)")
4769 org-not-done-regexp
4770 (concat "\\("
4771 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4772 "\\)")
4773 org-not-done-heading-regexp
4774 (format org-heading-keyword-regexp-format org-not-done-regexp)
4775 org-todo-line-regexp
4776 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4777 org-complex-heading-regexp
4778 (concat "^\\(\\*+\\)"
4779 "\\(?: +" org-todo-regexp "\\)?"
4780 "\\(?: +\\(\\[#.\\]\\)\\)?"
4781 "\\(?: +\\(.*?\\)\\)?"
4782 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4783 "[ \t]*$")
4784 org-complex-heading-regexp-format
4785 (concat "^\\(\\*+\\)"
4786 "\\(?: +" org-todo-regexp "\\)?"
4787 "\\(?: +\\(\\[#.\\]\\)\\)?"
4788 "\\(?: +"
4789 ;; Stats cookies can be stuck to body.
4790 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4791 "\\(%s\\)"
4792 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4793 "\\)"
4794 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4795 "[ \t]*$")
4796 org-todo-line-tags-regexp
4797 (concat "^\\(\\*+\\)"
4798 "\\(?: +" org-todo-regexp "\\)?"
4799 "\\(?: +\\(.*?\\)\\)?"
4800 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4801 "[ \t]*$")
4802 org-deadline-regexp (concat "\\<" org-deadline-string)
4803 org-deadline-time-regexp
4804 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4805 org-deadline-line-regexp
4806 (concat "\\<\\(" org-deadline-string "\\).*")
4807 org-scheduled-regexp
4808 (concat "\\<" org-scheduled-string)
4809 org-scheduled-time-regexp
4810 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4811 org-closed-time-regexp
4812 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4813 org-keyword-time-regexp
4814 (concat "\\<\\(" org-scheduled-string
4815 "\\|" org-deadline-string
4816 "\\|" org-closed-string
4817 "\\|" org-clock-string "\\)"
4818 " *[[<]\\([^]>]+\\)[]>]")
4819 org-keyword-time-not-clock-regexp
4820 (concat "\\<\\(" org-scheduled-string
4821 "\\|" org-deadline-string
4822 "\\|" org-closed-string
4823 "\\)"
4824 " *[[<]\\([^]>]+\\)[]>]")
4825 org-maybe-keyword-time-regexp
4826 (concat "\\(\\<\\(" org-scheduled-string
4827 "\\|" org-deadline-string
4828 "\\|" org-closed-string
4829 "\\|" org-clock-string "\\)\\)?"
4830 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4831 org-planning-or-clock-line-re
4832 (concat "^[ \t]*\\("
4833 org-scheduled-string "\\|"
4834 org-deadline-string "\\|"
4835 org-closed-string "\\|"
4836 org-clock-string "\\)")
4837 org-all-time-keywords
4838 (mapcar (lambda (w) (substring w 0 -1))
4839 (list org-scheduled-string org-deadline-string
4840 org-clock-string org-closed-string))
4842 (org-compute-latex-and-specials-regexp)
4843 (org-set-font-lock-defaults))))
4845 (defun org-file-contents (file &optional noerror)
4846 "Return the contents of FILE, as a string."
4847 (if (or (not file)
4848 (not (file-readable-p file)))
4849 (if noerror
4850 (progn
4851 (message "Cannot read file \"%s\"" file)
4852 (ding) (sit-for 2)
4854 (error "Cannot read file \"%s\"" file))
4855 (with-temp-buffer
4856 (insert-file-contents file)
4857 (buffer-string))))
4859 (defun org-extract-log-state-settings (x)
4860 "Extract the log state setting from a TODO keyword string.
4861 This will extract info from a string like \"WAIT(w@/!)\"."
4862 (let (kw key log1 log2)
4863 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4864 (setq kw (match-string 1 x)
4865 key (and (match-end 2) (match-string 2 x))
4866 log1 (and (match-end 3) (match-string 3 x))
4867 log2 (and (match-end 4) (match-string 4 x)))
4868 (and (or log1 log2)
4869 (list kw
4870 (and log1 (if (equal log1 "!") 'time 'note))
4871 (and log2 (if (equal log2 "!") 'time 'note)))))))
4873 (defun org-remove-keyword-keys (list)
4874 "Remove a pair of parenthesis at the end of each string in LIST."
4875 (mapcar (lambda (x)
4876 (if (string-match "(.*)$" x)
4877 (substring x 0 (match-beginning 0))
4879 list))
4881 (defun org-assign-fast-keys (alist)
4882 "Assign fast keys to a keyword-key alist.
4883 Respect keys that are already there."
4884 (let (new e (alt ?0))
4885 (while (setq e (pop alist))
4886 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4887 (cdr e)) ;; Key already assigned.
4888 (push e new)
4889 (let ((clist (string-to-list (downcase (car e))))
4890 (used (append new alist)))
4891 (when (= (car clist) ?@)
4892 (pop clist))
4893 (while (and clist (rassoc (car clist) used))
4894 (pop clist))
4895 (unless clist
4896 (while (rassoc alt used)
4897 (incf alt)))
4898 (push (cons (car e) (or (car clist) alt)) new))))
4899 (nreverse new)))
4901 ;;; Some variables used in various places
4903 (defvar org-window-configuration nil
4904 "Used in various places to store a window configuration.")
4905 (defvar org-selected-window nil
4906 "Used in various places to store a window configuration.")
4907 (defvar org-finish-function nil
4908 "Function to be called when `C-c C-c' is used.
4909 This is for getting out of special buffers like remember.")
4912 ;; FIXME: Occasionally check by commenting these, to make sure
4913 ;; no other functions uses these, forgetting to let-bind them.
4914 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4915 (defvar org-last-state)
4916 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4918 ;; Defined somewhere in this file, but used before definition.
4919 (defvar org-entities) ;; defined in org-entities.el
4920 (defvar org-struct-menu)
4921 (defvar org-org-menu)
4922 (defvar org-tbl-menu)
4924 ;;;; Define the Org-mode
4926 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4927 (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"))
4930 ;; We use a before-change function to check if a table might need
4931 ;; an update.
4932 (defvar org-table-may-need-update t
4933 "Indicates that a table might need an update.
4934 This variable is set by `org-before-change-function'.
4935 `org-table-align' sets it back to nil.")
4936 (defun org-before-change-function (beg end)
4937 "Every change indicates that a table might need an update."
4938 (setq org-table-may-need-update t))
4939 (defvar org-mode-map)
4940 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4941 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4942 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4943 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4944 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4945 (defvar org-table-buffer-is-an nil)
4947 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4948 ;; some places -- e.g. see the macro org-with-limited-levels.
4950 ;; In Org buffers, the value of `outline-regexp' is that of
4951 ;; `org-outline-regexp'. The only function still directly relying on
4952 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4953 ;; job when `orgstruct-mode' is active.
4954 (defvar org-outline-regexp "\\*+ "
4955 "Regexp to match Org headlines.")
4956 (defconst org-outline-regexp-bol "^\\*+ "
4957 "Regexp to match Org headlines.
4958 This is similar to `org-outline-regexp' but additionally makes
4959 sure that we are at the beginning of the line.")
4961 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4962 "Matches an headline, putting stars and text into groups.
4963 Stars are put in group 1 and the trimmed body in group 2.")
4965 (defvar bidi-paragraph-direction)
4966 (defvar buffer-face-mode-face)
4968 ;;;###autoload
4969 (define-derived-mode org-mode outline-mode "Org"
4970 "Outline-based notes management and organizer, alias
4971 \"Carsten's outline-mode for keeping track of everything.\"
4973 Org-mode develops organizational tasks around a NOTES file which
4974 contains information about projects as plain text. Org-mode is
4975 implemented on top of outline-mode, which is ideal to keep the content
4976 of large files well structured. It supports ToDo items, deadlines and
4977 time stamps, which magically appear in the diary listing of the Emacs
4978 calendar. Tables are easily created with a built-in table editor.
4979 Plain text URL-like links connect to websites, emails (VM), Usenet
4980 messages (Gnus), BBDB entries, and any files related to the project.
4981 For printing and sharing of notes, an Org-mode file (or a part of it)
4982 can be exported as a structured ASCII or HTML file.
4984 The following commands are available:
4986 \\{org-mode-map}"
4988 ;; Get rid of Outline menus, they are not needed
4989 ;; Need to do this here because define-derived-mode sets up
4990 ;; the keymap so late. Still, it is a waste to call this each time
4991 ;; we switch another buffer into org-mode.
4992 (if (featurep 'xemacs)
4993 (when (boundp 'outline-mode-menu-heading)
4994 ;; Assume this is Greg's port, it uses easymenu
4995 (easy-menu-remove outline-mode-menu-heading)
4996 (easy-menu-remove outline-mode-menu-show)
4997 (easy-menu-remove outline-mode-menu-hide))
4998 (define-key org-mode-map [menu-bar headings] 'undefined)
4999 (define-key org-mode-map [menu-bar hide] 'undefined)
5000 (define-key org-mode-map [menu-bar show] 'undefined))
5002 (org-load-modules-maybe)
5003 (easy-menu-add org-org-menu)
5004 (easy-menu-add org-tbl-menu)
5005 (org-install-agenda-files-menu)
5006 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5007 (add-to-invisibility-spec '(org-cwidth))
5008 (add-to-invisibility-spec '(org-hide-block . t))
5009 (when (featurep 'xemacs)
5010 (org-set-local 'line-move-ignore-invisible t))
5011 (org-set-local 'outline-regexp org-outline-regexp)
5012 (org-set-local 'outline-level 'org-outline-level)
5013 (setq bidi-paragraph-direction 'left-to-right)
5014 (when (and org-ellipsis
5015 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5016 (fboundp 'make-glyph-code))
5017 (unless org-display-table
5018 (setq org-display-table (make-display-table)))
5019 (set-display-table-slot
5020 org-display-table 4
5021 (vconcat (mapcar
5022 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5023 org-ellipsis)))
5024 (if (stringp org-ellipsis) org-ellipsis "..."))))
5025 (setq buffer-display-table org-display-table))
5026 (org-set-regexps-and-options)
5027 (when (and org-tag-faces (not org-tags-special-faces-re))
5028 ;; tag faces set outside customize.... force initialization.
5029 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5030 ;; Calc embedded
5031 (org-set-local 'calc-embedded-open-mode "# ")
5032 (modify-syntax-entry ?@ "w")
5033 (if org-startup-truncated (setq truncate-lines t))
5034 (org-set-local 'font-lock-unfontify-region-function
5035 'org-unfontify-region)
5036 ;; Activate before-change-function
5037 (org-set-local 'org-table-may-need-update t)
5038 (org-add-hook 'before-change-functions 'org-before-change-function nil
5039 'local)
5040 ;; Check for running clock before killing a buffer
5041 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5042 ;; Paragraphs and auto-filling
5043 (org-set-autofill-regexps)
5044 (setq indent-line-function 'org-indent-line-function)
5045 (org-update-radio-target-regexp)
5046 ;; Beginning/end of defun
5047 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5048 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5049 ;; Next error for sparse trees
5050 (org-set-local 'next-error-function 'org-occur-next-match)
5051 ;; Make sure dependence stuff works reliably, even for users who set it
5052 ;; too late :-(
5053 (if org-enforce-todo-dependencies
5054 (add-hook 'org-blocker-hook
5055 'org-block-todo-from-children-or-siblings-or-parent)
5056 (remove-hook 'org-blocker-hook
5057 'org-block-todo-from-children-or-siblings-or-parent))
5058 (if org-enforce-todo-checkbox-dependencies
5059 (add-hook 'org-blocker-hook
5060 'org-block-todo-from-checkboxes)
5061 (remove-hook 'org-blocker-hook
5062 'org-block-todo-from-checkboxes))
5064 ;; Comment characters
5065 (org-set-local 'comment-start "#")
5066 (org-set-local 'comment-padding " ")
5068 ;; Align options lines
5069 (org-set-local
5070 'align-mode-rules-list
5071 '((org-in-buffer-settings
5072 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5073 (modes . '(org-mode)))))
5075 ;; Imenu
5076 (org-set-local 'imenu-create-index-function
5077 'org-imenu-get-tree)
5079 ;; Make isearch reveal context
5080 (if (or (featurep 'xemacs)
5081 (not (boundp 'outline-isearch-open-invisible-function)))
5082 ;; Emacs 21 and XEmacs make use of the hook
5083 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5084 ;; Emacs 22 deals with this through a special variable
5085 (org-set-local 'outline-isearch-open-invisible-function
5086 (lambda (&rest ignore) (org-show-context 'isearch))))
5088 ;; Turn on org-beamer-mode?
5089 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5091 ;; Setup the pcomplete hooks
5092 (set (make-local-variable 'pcomplete-command-completion-function)
5093 'org-pcomplete-initial)
5094 (set (make-local-variable 'pcomplete-command-name-function)
5095 'org-command-at-point)
5096 (set (make-local-variable 'pcomplete-default-completion-function)
5097 'ignore)
5098 (set (make-local-variable 'pcomplete-parse-arguments-function)
5099 'org-parse-arguments)
5100 (set (make-local-variable 'pcomplete-termination-string) "")
5101 (when (>= emacs-major-version 23)
5102 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5104 ;; If empty file that did not turn on org-mode automatically, make it to.
5105 (if (and org-insert-mode-line-in-empty-file
5106 (org-called-interactively-p 'any)
5107 (= (point-min) (point-max)))
5108 (insert "# -*- mode: org -*-\n\n"))
5109 (unless org-inhibit-startup
5110 (when org-startup-align-all-tables
5111 (let ((bmp (buffer-modified-p)))
5112 (org-table-map-tables 'org-table-align 'quietly)
5113 (set-buffer-modified-p bmp)))
5114 (when org-startup-with-inline-images
5115 (org-display-inline-images))
5116 (when org-startup-indented
5117 (require 'org-indent)
5118 (org-indent-mode 1))
5119 (unless org-inhibit-startup-visibility-stuff
5120 (org-set-startup-visibility))))
5122 (when (fboundp 'abbrev-table-put)
5123 (abbrev-table-put org-mode-abbrev-table
5124 :parents (list text-mode-abbrev-table)))
5126 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5128 (defun org-current-time ()
5129 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5130 (if (> (car org-time-stamp-rounding-minutes) 1)
5131 (let ((r (car org-time-stamp-rounding-minutes))
5132 (time (decode-time)))
5133 (apply 'encode-time
5134 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5135 (nthcdr 2 time))))
5136 (current-time)))
5138 (defun org-today ()
5139 "Return today date, considering `org-extend-today-until'."
5140 (time-to-days
5141 (time-subtract (current-time)
5142 (list 0 (* 3600 org-extend-today-until) 0))))
5144 ;;;; Font-Lock stuff, including the activators
5146 (defvar org-mouse-map (make-sparse-keymap))
5147 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5148 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5149 (when org-mouse-1-follows-link
5150 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5151 (when org-tab-follows-link
5152 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5153 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5155 (require 'font-lock)
5157 (defconst org-non-link-chars "]\t\n\r<>")
5158 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5159 "shell" "elisp" "doi" "message"))
5160 (defvar org-link-types-re nil
5161 "Matches a link that has a url-like prefix like \"http:\"")
5162 (defvar org-link-re-with-space nil
5163 "Matches a link with spaces, optional angular brackets around it.")
5164 (defvar org-link-re-with-space2 nil
5165 "Matches a link with spaces, optional angular brackets around it.")
5166 (defvar org-link-re-with-space3 nil
5167 "Matches a link with spaces, only for internal part in bracket links.")
5168 (defvar org-angle-link-re nil
5169 "Matches link with angular brackets, spaces are allowed.")
5170 (defvar org-plain-link-re nil
5171 "Matches plain link, without spaces.")
5172 (defvar org-bracket-link-regexp nil
5173 "Matches a link in double brackets.")
5174 (defvar org-bracket-link-analytic-regexp nil
5175 "Regular expression used to analyze links.
5176 Here is what the match groups contain after a match:
5177 1: http:
5178 2: http
5179 3: path
5180 4: [desc]
5181 5: desc")
5182 (defvar org-bracket-link-analytic-regexp++ nil
5183 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5184 (defvar org-any-link-re nil
5185 "Regular expression matching any link.")
5187 (defcustom org-match-sexp-depth 3
5188 "Number of stacked braces for sub/superscript matching.
5189 This has to be set before loading org.el to be effective."
5190 :group 'org-export-translation ; ??????????????????????????/
5191 :type 'integer)
5193 (defun org-create-multibrace-regexp (left right n)
5194 "Create a regular expression which will match a balanced sexp.
5195 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5196 as single character strings.
5197 The regexp returned will match the entire expression including the
5198 delimiters. It will also define a single group which contains the
5199 match except for the outermost delimiters. The maximum depth of
5200 stacked delimiters is N. Escaping delimiters is not possible."
5201 (let* ((nothing (concat "[^" left right "]*?"))
5202 (or "\\|")
5203 (re nothing)
5204 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5205 (while (> n 1)
5206 (setq n (1- n)
5207 re (concat re or next)
5208 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5209 (concat left "\\(" re "\\)" right)))
5211 (defvar org-match-substring-regexp
5212 (concat
5213 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5214 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5215 "\\|"
5216 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5217 "\\|"
5218 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5219 "The regular expression matching a sub- or superscript.")
5221 (defvar org-match-substring-with-braces-regexp
5222 (concat
5223 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5224 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5225 "\\)")
5226 "The regular expression matching a sub- or superscript, forcing braces.")
5228 (defun org-make-link-regexps ()
5229 "Update the link regular expressions.
5230 This should be called after the variable `org-link-types' has changed."
5231 (setq org-link-types-re
5232 (concat
5233 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5234 org-link-re-with-space
5235 (concat
5236 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5237 "\\([^" org-non-link-chars " ]"
5238 "[^" org-non-link-chars "]*"
5239 "[^" org-non-link-chars " ]\\)>?")
5240 org-link-re-with-space2
5241 (concat
5242 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5243 "\\([^" org-non-link-chars " ]"
5244 "[^\t\n\r]*"
5245 "[^" org-non-link-chars " ]\\)>?")
5246 org-link-re-with-space3
5247 (concat
5248 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5249 "\\([^" org-non-link-chars " ]"
5250 "[^\t\n\r]*\\)")
5251 org-angle-link-re
5252 (concat
5253 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5254 "\\([^" org-non-link-chars " ]"
5255 "[^" org-non-link-chars "]*"
5256 "\\)>")
5257 org-plain-link-re
5258 (concat
5259 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5260 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5261 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5262 org-bracket-link-regexp
5263 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5264 org-bracket-link-analytic-regexp
5265 (concat
5266 "\\[\\["
5267 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5268 "\\([^]]+\\)"
5269 "\\]"
5270 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5271 "\\]")
5272 org-bracket-link-analytic-regexp++
5273 (concat
5274 "\\[\\["
5275 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5276 "\\([^]]+\\)"
5277 "\\]"
5278 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5279 "\\]")
5280 org-any-link-re
5281 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5282 org-angle-link-re "\\)\\|\\("
5283 org-plain-link-re "\\)")))
5285 (org-make-link-regexps)
5287 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5288 "Regular expression for fast time stamp matching.")
5289 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5290 "Regular expression for fast time stamp matching.")
5291 (defconst org-ts-regexp0
5292 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5293 "Regular expression matching time strings for analysis.
5294 This one does not require the space after the date, so it can be used
5295 on a string that terminates immediately after the date.")
5296 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5297 "Regular expression matching time strings for analysis.")
5298 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5299 "Regular expression matching time stamps, with groups.")
5300 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5301 "Regular expression matching time stamps (also [..]), with groups.")
5302 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5303 "Regular expression matching a time stamp range.")
5304 (defconst org-tr-regexp-both
5305 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5306 "Regular expression matching a time stamp range.")
5307 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5308 org-ts-regexp "\\)?")
5309 "Regular expression matching a time stamp or time stamp range.")
5310 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5311 org-ts-regexp-both "\\)?")
5312 "Regular expression matching a time stamp or time stamp range.
5313 The time stamps may be either active or inactive.")
5315 (defvar org-emph-face nil)
5317 (defun org-do-emphasis-faces (limit)
5318 "Run through the buffer and add overlays to emphasized strings."
5319 (let (rtn a)
5320 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5321 (if (not (= (char-after (match-beginning 3))
5322 (char-after (match-beginning 4))))
5323 (progn
5324 (setq rtn t)
5325 (setq a (assoc (match-string 3) org-emphasis-alist))
5326 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5327 'face
5328 (nth 1 a))
5329 (and (nth 4 a)
5330 (org-remove-flyspell-overlays-in
5331 (match-beginning 0) (match-end 0)))
5332 (add-text-properties (match-beginning 2) (match-end 2)
5333 '(font-lock-multiline t org-emphasis t))
5334 (when org-hide-emphasis-markers
5335 (add-text-properties (match-end 4) (match-beginning 5)
5336 '(invisible org-link))
5337 (add-text-properties (match-beginning 3) (match-end 3)
5338 '(invisible org-link)))))
5339 (backward-char 1))
5340 rtn))
5342 (defun org-emphasize (&optional char)
5343 "Insert or change an emphasis, i.e. a font like bold or italic.
5344 If there is an active region, change that region to a new emphasis.
5345 If there is no region, just insert the marker characters and position
5346 the cursor between them.
5347 CHAR should be either the marker character, or the first character of the
5348 HTML tag associated with that emphasis. If CHAR is a space, the means
5349 to remove the emphasis of the selected region.
5350 If char is not given (for example in an interactive call) it
5351 will be prompted for."
5352 (interactive)
5353 (let ((eal org-emphasis-alist) e det
5354 (erc org-emphasis-regexp-components)
5355 (prompt "")
5356 (string "") beg end move tag c s)
5357 (if (org-region-active-p)
5358 (setq beg (region-beginning) end (region-end)
5359 string (buffer-substring beg end))
5360 (setq move t))
5362 (while (setq e (pop eal))
5363 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5364 c (aref tag 0))
5365 (push (cons c (string-to-char (car e))) det)
5366 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5367 (substring tag 1)))))
5368 (setq det (nreverse det))
5369 (unless char
5370 (message "%s" (concat "Emphasis marker or tag:" prompt))
5371 (setq char (read-char-exclusive)))
5372 (setq char (or (cdr (assoc char det)) char))
5373 (if (equal char ?\ )
5374 (setq s "" move nil)
5375 (unless (assoc (char-to-string char) org-emphasis-alist)
5376 (error "No such emphasis marker: \"%c\"" char))
5377 (setq s (char-to-string char)))
5378 (while (and (> (length string) 1)
5379 (equal (substring string 0 1) (substring string -1))
5380 (assoc (substring string 0 1) org-emphasis-alist))
5381 (setq string (substring string 1 -1)))
5382 (setq string (concat s string s))
5383 (if beg (delete-region beg end))
5384 (unless (or (bolp)
5385 (string-match (concat "[" (nth 0 erc) "\n]")
5386 (char-to-string (char-before (point)))))
5387 (insert " "))
5388 (unless (or (eobp)
5389 (string-match (concat "[" (nth 1 erc) "\n]")
5390 (char-to-string (char-after (point)))))
5391 (insert " ") (backward-char 1))
5392 (insert string)
5393 (and move (backward-char 1))))
5395 (defconst org-nonsticky-props
5396 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5398 (defsubst org-rear-nonsticky-at (pos)
5399 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5401 (defun org-activate-plain-links (limit)
5402 "Run through the buffer and add overlays to links."
5403 (catch 'exit
5404 (let (f)
5405 (if (re-search-forward org-plain-link-re limit t)
5406 (progn
5407 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5408 (setq f (get-text-property (match-beginning 0) 'face))
5409 (if (or (eq f 'org-tag)
5410 (and (listp f) (memq 'org-tag f)))
5412 (add-text-properties (match-beginning 0) (match-end 0)
5413 (list 'mouse-face 'highlight
5414 'face 'org-link
5415 'keymap org-mouse-map))
5416 (org-rear-nonsticky-at (match-end 0)))
5417 t)))))
5419 (defun org-activate-code (limit)
5420 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5421 (progn
5422 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5423 (remove-text-properties (match-beginning 0) (match-end 0)
5424 '(display t invisible t intangible t))
5425 t)))
5427 (defcustom org-src-fontify-natively nil
5428 "When non-nil, fontify code in code blocks."
5429 :type 'boolean
5430 :version "24.1"
5431 :group 'org-appearance
5432 :group 'org-babel)
5434 (defcustom org-src-prevent-auto-filling nil
5435 "When non-nil, prevent auto-filling in src blocks."
5436 :type 'boolean
5437 :version "24.1"
5438 :group 'org-appearance
5439 :group 'org-babel)
5441 (defcustom org-allow-promoting-top-level-subtree nil
5442 "When non-nil, allow promoting a top level subtree.
5443 The leading star of the top level headline will be replaced
5444 by a #."
5445 :type 'boolean
5446 :version "24.1"
5447 :group 'org-appearance)
5449 (defun org-fontify-meta-lines-and-blocks (limit)
5450 (condition-case nil
5451 (org-fontify-meta-lines-and-blocks-1 limit)
5452 (error (message "org-mode fontification error"))))
5454 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5455 "Fontify #+ lines and blocks, in the correct ways."
5456 (let ((case-fold-search t))
5457 (if (re-search-forward
5458 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5459 limit t)
5460 (let ((beg (match-beginning 0))
5461 (block-start (match-end 0))
5462 (block-end nil)
5463 (lang (match-string 7))
5464 (beg1 (line-beginning-position 2))
5465 (dc1 (downcase (match-string 2)))
5466 (dc3 (downcase (match-string 3)))
5467 end end1 quoting block-type ovl)
5468 (cond
5469 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5470 ;; a single line of backend-specific content
5471 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5472 (remove-text-properties (match-beginning 0) (match-end 0)
5473 '(display t invisible t intangible t))
5474 (add-text-properties (match-beginning 1) (match-end 3)
5475 '(font-lock-fontified t face org-meta-line))
5476 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5477 '(font-lock-fontified t face org-block))
5478 ; for backend-specific code
5480 ((and (match-end 4) (equal dc3 "begin"))
5481 ;; Truly a block
5482 (setq block-type (downcase (match-string 5))
5483 quoting (member block-type org-protecting-blocks))
5484 (when (re-search-forward
5485 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5486 nil t) ;; on purpose, we look further than LIMIT
5487 (setq end (min (point-max) (match-end 0))
5488 end1 (min (point-max) (1- (match-beginning 0))))
5489 (setq block-end (match-beginning 0))
5490 (when quoting
5491 (remove-text-properties beg end
5492 '(display t invisible t intangible t)))
5493 (add-text-properties
5494 beg end
5495 '(font-lock-fontified t font-lock-multiline t))
5496 (add-text-properties beg beg1 '(face org-meta-line))
5497 (add-text-properties end1 (min (point-max) (1+ end))
5498 '(face org-meta-line)) ; for end_src
5499 (cond
5500 ((and lang (not (string= lang "")) org-src-fontify-natively)
5501 (org-src-font-lock-fontify-block lang block-start block-end)
5502 ;; remove old background overlays
5503 (mapc (lambda (ov)
5504 (if (eq (overlay-get ov 'face) 'org-block-background)
5505 (delete-overlay ov)))
5506 (overlays-at (/ (+ beg1 block-end) 2)))
5507 ;; add a background overlay
5508 (setq ovl (make-overlay beg1 block-end))
5509 (overlay-put ovl 'face 'org-block-background)
5510 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5511 (quoting
5512 (add-text-properties beg1 (min (point-max) (1+ end1))
5513 '(face org-block))) ; end of source block
5514 ((not org-fontify-quote-and-verse-blocks))
5515 ((string= block-type "quote")
5516 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5517 ((string= block-type "verse")
5518 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5519 (add-text-properties beg beg1 '(face org-block-begin-line))
5520 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5521 '(face org-block-end-line))
5523 ((member dc1 '("title:" "author:" "email:" "date:"))
5524 (add-text-properties
5525 beg (match-end 3)
5526 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5527 '(font-lock-fontified t invisible t)
5528 '(font-lock-fontified t face org-document-info-keyword)))
5529 (add-text-properties
5530 (match-beginning 6) (match-end 6)
5531 (if (string-equal dc1 "title:")
5532 '(font-lock-fontified t face org-document-title)
5533 '(font-lock-fontified t face org-document-info))))
5534 ((not (member (char-after beg) '(?\ ?\t)))
5535 ;; just any other in-buffer setting, but not indented
5536 (add-text-properties
5537 beg (match-end 0)
5538 '(font-lock-fontified t face org-meta-line))
5540 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5541 "orgtbl:" "tblfm:" "tblname:" "results:"
5542 "call:" "header:" "headers:" "name:"))
5543 (and (match-end 4) (equal dc3 "attr")))
5544 (add-text-properties
5545 beg (match-end 0)
5546 '(font-lock-fontified t face org-meta-line))
5548 ((member dc3 '(" " ""))
5549 (add-text-properties
5550 beg (match-end 0)
5551 '(font-lock-fontified t face font-lock-comment-face)))
5552 (t nil))))))
5554 (defun org-strip-protective-commas (beg end)
5555 "Strip protective commas between BEG and END in the current buffer."
5556 (interactive "r")
5557 (save-excursion
5558 (save-match-data
5559 (goto-char beg)
5560 (let ((front-line (save-excursion
5561 (re-search-forward
5562 "[^[:space:]]" end t)
5563 (goto-char (match-beginning 0))
5564 (current-column))))
5565 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5566 (goto-char (match-beginning 1))
5567 (when (= (current-column) front-line)
5568 (replace-match "" nil nil nil 1)))))))
5570 (defun org-activate-angle-links (limit)
5571 "Run through the buffer and add overlays to links."
5572 (if (re-search-forward org-angle-link-re limit t)
5573 (progn
5574 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5575 (add-text-properties (match-beginning 0) (match-end 0)
5576 (list 'mouse-face 'highlight
5577 'keymap org-mouse-map))
5578 (org-rear-nonsticky-at (match-end 0))
5579 t)))
5581 (defun org-activate-footnote-links (limit)
5582 "Run through the buffer and add overlays to footnotes."
5583 (let ((fn (org-footnote-next-reference-or-definition limit)))
5584 (when fn
5585 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5586 (org-remove-flyspell-overlays-in beg end)
5587 (add-text-properties beg end
5588 (list 'mouse-face 'highlight
5589 'keymap org-mouse-map
5590 'help-echo
5591 (if (= (point-at-bol) beg)
5592 "Footnote definition"
5593 "Footnote reference")
5594 'font-lock-fontified t
5595 'font-lock-multiline t
5596 'face 'org-footnote))))))
5598 (defun org-activate-bracket-links (limit)
5599 "Run through the buffer and add overlays to bracketed links."
5600 (if (re-search-forward org-bracket-link-regexp limit t)
5601 (let* ((help (concat "LINK: "
5602 (org-match-string-no-properties 1)))
5603 ;; FIXME: above we should remove the escapes.
5604 ;; but that requires another match, protecting match data,
5605 ;; a lot of overhead for font-lock.
5606 (ip (org-maybe-intangible
5607 (list 'invisible 'org-link
5608 'keymap org-mouse-map 'mouse-face 'highlight
5609 'font-lock-multiline t 'help-echo help)))
5610 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5611 'font-lock-multiline t 'help-echo help)))
5612 ;; We need to remove the invisible property here. Table narrowing
5613 ;; may have made some of this invisible.
5614 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5615 (remove-text-properties (match-beginning 0) (match-end 0)
5616 '(invisible nil))
5617 (if (match-end 3)
5618 (progn
5619 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5620 (org-rear-nonsticky-at (match-beginning 3))
5621 (add-text-properties (match-beginning 3) (match-end 3) vp)
5622 (org-rear-nonsticky-at (match-end 3))
5623 (add-text-properties (match-end 3) (match-end 0) ip)
5624 (org-rear-nonsticky-at (match-end 0)))
5625 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5626 (org-rear-nonsticky-at (match-beginning 1))
5627 (add-text-properties (match-beginning 1) (match-end 1) vp)
5628 (org-rear-nonsticky-at (match-end 1))
5629 (add-text-properties (match-end 1) (match-end 0) ip)
5630 (org-rear-nonsticky-at (match-end 0)))
5631 t)))
5633 (defun org-activate-dates (limit)
5634 "Run through the buffer and add overlays to dates."
5635 (if (re-search-forward org-tsr-regexp-both limit t)
5636 (progn
5637 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5638 (add-text-properties (match-beginning 0) (match-end 0)
5639 (list 'mouse-face 'highlight
5640 'keymap org-mouse-map))
5641 (org-rear-nonsticky-at (match-end 0))
5642 (when org-display-custom-times
5643 (if (match-end 3)
5644 (org-display-custom-time (match-beginning 3) (match-end 3)))
5645 (org-display-custom-time (match-beginning 1) (match-end 1)))
5646 t)))
5648 (defvar org-target-link-regexp nil
5649 "Regular expression matching radio targets in plain text.")
5650 (make-variable-buffer-local 'org-target-link-regexp)
5651 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5652 "Regular expression matching a link target.")
5653 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5654 "Regular expression matching a radio target.")
5655 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5656 "Regular expression matching any target.")
5658 (defun org-activate-target-links (limit)
5659 "Run through the buffer and add overlays to target matches."
5660 (when org-target-link-regexp
5661 (let ((case-fold-search t))
5662 (if (re-search-forward org-target-link-regexp limit t)
5663 (progn
5664 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5665 (add-text-properties (match-beginning 0) (match-end 0)
5666 (list 'mouse-face 'highlight
5667 'keymap org-mouse-map
5668 'help-echo "Radio target link"
5669 'org-linked-text t))
5670 (org-rear-nonsticky-at (match-end 0))
5671 t)))))
5673 (defun org-update-radio-target-regexp ()
5674 "Find all radio targets in this file and update the regular expression."
5675 (interactive)
5676 (when (memq 'radio org-activate-links)
5677 (setq org-target-link-regexp
5678 (org-make-target-link-regexp (org-all-targets 'radio)))
5679 (org-restart-font-lock)))
5681 (defun org-hide-wide-columns (limit)
5682 (let (s e)
5683 (setq s (text-property-any (point) (or limit (point-max))
5684 'org-cwidth t))
5685 (when s
5686 (setq e (next-single-property-change s 'org-cwidth))
5687 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5688 (goto-char e)
5689 t)))
5691 (defvar org-latex-and-specials-regexp nil
5692 "Regular expression for highlighting export special stuff.")
5693 (defvar org-match-substring-regexp)
5694 (defvar org-match-substring-with-braces-regexp)
5696 ;; This should be with the exporter code, but we also use if for font-locking
5697 (defconst org-export-html-special-string-regexps
5698 '(("\\\\-" . "&shy;")
5699 ("---\\([^-]\\)" . "&mdash;\\1")
5700 ("--\\([^-]\\)" . "&ndash;\\1")
5701 ("\\.\\.\\." . "&hellip;"))
5702 "Regular expressions for special string conversion.")
5705 (defun org-compute-latex-and-specials-regexp ()
5706 "Compute regular expression for stuff treated specially by exporters."
5707 (if (not org-highlight-latex-fragments-and-specials)
5708 (org-set-local 'org-latex-and-specials-regexp nil)
5709 (require 'org-exp)
5710 (let*
5711 ((matchers (plist-get org-format-latex-options :matchers))
5712 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5713 org-latex-regexps)))
5714 (org-export-allow-BIND nil)
5715 (options (org-combine-plists (org-default-export-plist)
5716 (org-infile-export-plist)))
5717 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5718 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5719 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5720 (org-export-html-expand (plist-get options :expand-quoted-html))
5721 (org-export-with-special-strings (plist-get options :special-strings))
5722 (re-sub
5723 (cond
5724 ((equal org-export-with-sub-superscripts '{})
5725 (list org-match-substring-with-braces-regexp))
5726 (org-export-with-sub-superscripts
5727 (list org-match-substring-regexp))
5728 (t nil)))
5729 (re-latex
5730 (if org-export-with-LaTeX-fragments
5731 (mapcar (lambda (x) (nth 1 x)) latexs)))
5732 (re-macros
5733 (if org-export-with-TeX-macros
5734 (list (concat "\\\\"
5735 (regexp-opt
5736 (append
5738 (delq nil
5739 (mapcar 'car-safe
5740 (append org-entities-user
5741 org-entities)))
5742 (if (boundp 'org-latex-entities)
5743 (mapcar (lambda (x)
5744 (or (car-safe x) x))
5745 org-latex-entities)
5746 nil))
5747 'words))) ; FIXME
5749 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5750 (re-special (if org-export-with-special-strings
5751 (mapcar (lambda (x) (car x))
5752 org-export-html-special-string-regexps)))
5753 (re-rest
5754 (delq nil
5755 (list
5756 (if org-export-html-expand "@<[^>\n]+>")
5757 ))))
5758 (org-set-local
5759 'org-latex-and-specials-regexp
5760 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5761 re-rest) "\\|")))))
5763 (defun org-do-latex-and-special-faces (limit)
5764 "Run through the buffer and add overlays to links."
5765 (when org-latex-and-specials-regexp
5766 (let (rtn d)
5767 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5768 limit t))
5769 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5770 'face))
5771 '(org-code org-verbatim underline)))
5772 (progn
5773 (setq rtn t
5774 d (cond ((member (char-after (1+ (match-beginning 0)))
5775 '(?_ ?^)) 1)
5776 (t 0)))
5777 (font-lock-prepend-text-property
5778 (+ d (match-beginning 0)) (match-end 0)
5779 'face 'org-latex-and-export-specials)
5780 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5781 '(font-lock-multiline t)))))
5782 rtn)))
5784 (defun org-restart-font-lock ()
5785 "Restart `font-lock-mode', to force refontification."
5786 (when (and (boundp 'font-lock-mode) font-lock-mode)
5787 (font-lock-mode -1)
5788 (font-lock-mode 1)))
5790 (defun org-all-targets (&optional radio)
5791 "Return a list of all targets in this file.
5792 With optional argument RADIO, only find radio targets."
5793 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5794 rtn)
5795 (save-excursion
5796 (goto-char (point-min))
5797 (while (re-search-forward re nil t)
5798 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5799 rtn)))
5801 (defun org-make-target-link-regexp (targets)
5802 "Make regular expression matching all strings in TARGETS.
5803 The regular expression finds the targets also if there is a line break
5804 between words."
5805 (and targets
5806 (concat
5807 "\\<\\("
5808 (mapconcat
5809 (lambda (x)
5810 (setq x (regexp-quote x))
5811 (while (string-match " +" x)
5812 (setq x (replace-match "\\s-+" t t x)))
5814 targets
5815 "\\|")
5816 "\\)\\>")))
5818 (defun org-activate-tags (limit)
5819 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5820 (progn
5821 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5822 (add-text-properties (match-beginning 1) (match-end 1)
5823 (list 'mouse-face 'highlight
5824 'keymap org-mouse-map))
5825 (org-rear-nonsticky-at (match-end 1))
5826 t)))
5828 (defun org-outline-level ()
5829 "Compute the outline level of the heading at point.
5830 This function assumes that the cursor is at the beginning of a line matched
5831 by `outline-regexp'. Otherwise it returns garbage.
5832 If this is called at a normal headline, the level is the number of stars.
5833 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5834 (save-excursion
5835 (looking-at org-outline-regexp)
5836 (1- (- (match-end 0) (match-beginning 0)))))
5838 (defvar org-font-lock-keywords nil)
5840 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5841 "Regular expression matching a property line.")
5843 (defvar org-font-lock-hook nil
5844 "Functions to be called for special font lock stuff.")
5846 (defvar org-font-lock-set-keywords-hook nil
5847 "Functions that can manipulate `org-font-lock-extra-keywords'.
5848 This is called after `org-font-lock-extra-keywords' is defined, but before
5849 it is installed to be used by font lock. This can be useful if something
5850 needs to be inserted at a specific position in the font-lock sequence.")
5852 (defun org-font-lock-hook (limit)
5853 (run-hook-with-args 'org-font-lock-hook limit))
5855 (defun org-set-font-lock-defaults ()
5856 (let* ((em org-fontify-emphasized-text)
5857 (lk org-activate-links)
5858 (org-font-lock-extra-keywords
5859 (list
5860 ;; Call the hook
5861 '(org-font-lock-hook)
5862 ;; Headlines
5863 `(,(if org-fontify-whole-heading-line
5864 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5865 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5866 (1 (org-get-level-face 1))
5867 (2 (org-get-level-face 2))
5868 (3 (org-get-level-face 3)))
5869 ;; Table lines
5870 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5871 (1 'org-table t))
5872 ;; Table internals
5873 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5874 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5875 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5876 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5877 ;; Drawers
5878 (list org-drawer-regexp '(0 'org-special-keyword t))
5879 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5880 ;; Properties
5881 (list org-property-re
5882 '(1 'org-special-keyword t)
5883 '(3 'org-property-value t))
5884 ;; Links
5885 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5886 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5887 (if (memq 'plain lk) '(org-activate-plain-links))
5888 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5889 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5890 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5891 (if (memq 'footnote lk) '(org-activate-footnote-links))
5892 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5893 '(org-hide-wide-columns (0 nil append))
5894 ;; TODO keyword
5895 (list (format org-heading-keyword-regexp-format
5896 org-todo-regexp)
5897 '(2 (org-get-todo-face 2) t))
5898 ;; DONE
5899 (if org-fontify-done-headline
5900 (list (format org-heading-keyword-regexp-format
5901 (concat
5902 "\\(?:"
5903 (mapconcat 'regexp-quote org-done-keywords "\\|")
5904 "\\)"))
5905 '(2 'org-headline-done t))
5906 nil)
5907 ;; Priorities
5908 '(org-font-lock-add-priority-faces)
5909 ;; Tags
5910 '(org-font-lock-add-tag-faces)
5911 ;; Special keywords
5912 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5913 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5914 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5915 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5916 ;; Emphasis
5917 (if em
5918 (if (featurep 'xemacs)
5919 '(org-do-emphasis-faces (0 nil append))
5920 '(org-do-emphasis-faces)))
5921 ;; Checkboxes
5922 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5923 1 'org-checkbox prepend)
5924 (if (cdr (assq 'checkbox org-list-automatic-rules))
5925 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5926 (0 (org-get-checkbox-statistics-face) t)))
5927 ;; Description list items
5928 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5929 1 'org-list-dt prepend)
5930 ;; ARCHIVEd headings
5931 (list (concat
5932 org-outline-regexp-bol
5933 "\\(.*:" org-archive-tag ":.*\\)")
5934 '(1 'org-archived prepend))
5935 ;; Specials
5936 '(org-do-latex-and-special-faces)
5937 '(org-fontify-entities)
5938 '(org-raise-scripts)
5939 ;; Code
5940 '(org-activate-code (1 'org-code t))
5941 ;; COMMENT
5942 (list (format org-heading-keyword-regexp-format
5943 (concat "\\("
5944 org-comment-string "\\|" org-quote-string
5945 "\\)"))
5946 '(2 'org-special-keyword t))
5947 '("^#.*" (0 'font-lock-comment-face t))
5948 ;; Blocks and meta lines
5949 '(org-fontify-meta-lines-and-blocks)
5951 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5952 (run-hooks 'org-font-lock-set-keywords-hook)
5953 ;; Now set the full font-lock-keywords
5954 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5955 (org-set-local 'font-lock-defaults
5956 '(org-font-lock-keywords t nil nil backward-paragraph))
5957 (kill-local-variable 'font-lock-keywords) nil))
5959 (defun org-toggle-pretty-entities ()
5960 "Toggle the composition display of entities as UTF8 characters."
5961 (interactive)
5962 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5963 (org-restart-font-lock)
5964 (if org-pretty-entities
5965 (message "Entities are displayed as UTF8 characters")
5966 (save-restriction
5967 (widen)
5968 (org-decompose-region (point-min) (point-max))
5969 (message "Entities are displayed plain"))))
5971 (defun org-fontify-entities (limit)
5972 "Find an entity to fontify."
5973 (let (ee)
5974 (when org-pretty-entities
5975 (catch 'match
5976 (while (re-search-forward
5977 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5978 limit t)
5979 (if (and (not (org-in-indented-comment-line))
5980 (setq ee (org-entity-get (match-string 1)))
5981 (= (length (nth 6 ee)) 1))
5982 (let*
5983 ((end (if (equal (match-string 2) "{}")
5984 (match-end 2)
5985 (match-end 1))))
5986 (add-text-properties
5987 (match-beginning 0) end
5988 (list 'font-lock-fontified t))
5989 (compose-region (match-beginning 0) end
5990 (nth 6 ee) nil)
5991 (backward-char 1)
5992 (throw 'match t))))
5993 nil))))
5995 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5996 "Fontify string S like in Org-mode."
5997 (with-temp-buffer
5998 (insert s)
5999 (let ((org-odd-levels-only odd-levels))
6000 (org-mode)
6001 (font-lock-fontify-buffer)
6002 (buffer-string))))
6004 (defvar org-m nil)
6005 (defvar org-l nil)
6006 (defvar org-f nil)
6007 (defun org-get-level-face (n)
6008 "Get the right face for match N in font-lock matching of headlines."
6009 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6010 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6011 (if org-cycle-level-faces
6012 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6013 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6014 (cond
6015 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6016 ((eq n 2) org-f)
6017 (t (if org-level-color-stars-only nil org-f))))
6020 (defun org-get-todo-face (kwd)
6021 "Get the right face for a TODO keyword KWD.
6022 If KWD is a number, get the corresponding match group."
6023 (if (numberp kwd) (setq kwd (match-string kwd)))
6024 (or (org-face-from-face-or-color
6025 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6026 (and (member kwd org-done-keywords) 'org-done)
6027 'org-todo))
6029 (defun org-face-from-face-or-color (context inherit face-or-color)
6030 "Create a face list that inherits INHERIT, but sets the foreground color.
6031 When FACE-OR-COLOR is not a string, just return it."
6032 (if (stringp face-or-color)
6033 (list :inherit inherit
6034 (cdr (assoc context org-faces-easy-properties))
6035 face-or-color)
6036 face-or-color))
6038 (defun org-font-lock-add-tag-faces (limit)
6039 "Add the special tag faces."
6040 (when (and org-tag-faces org-tags-special-faces-re)
6041 (while (re-search-forward org-tags-special-faces-re limit t)
6042 (add-text-properties (match-beginning 1) (match-end 1)
6043 (list 'face (org-get-tag-face 1)
6044 'font-lock-fontified t))
6045 (backward-char 1))))
6047 (defun org-font-lock-add-priority-faces (limit)
6048 "Add the special priority faces."
6049 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6050 (when (save-match-data (org-at-heading-p))
6051 (add-text-properties
6052 (match-beginning 0) (match-end 0)
6053 (list 'face (or (org-face-from-face-or-color
6054 'priority 'org-special-keyword
6055 (cdr (assoc (char-after (match-beginning 1))
6056 org-priority-faces)))
6057 'org-special-keyword)
6058 'font-lock-fontified t)))))
6060 (defun org-get-tag-face (kwd)
6061 "Get the right face for a TODO keyword KWD.
6062 If KWD is a number, get the corresponding match group."
6063 (if (numberp kwd) (setq kwd (match-string kwd)))
6064 (or (org-face-from-face-or-color
6065 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6066 'org-tag))
6068 (defun org-unfontify-region (beg end &optional maybe_loudly)
6069 "Remove fontification and activation overlays from links."
6070 (font-lock-default-unfontify-region beg end)
6071 (let* ((buffer-undo-list t)
6072 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6073 (inhibit-modification-hooks t)
6074 deactivate-mark buffer-file-name buffer-file-truename)
6075 (org-decompose-region beg end)
6076 (remove-text-properties beg end
6077 '(mouse-face t keymap t org-linked-text t
6078 invisible t intangible t
6079 org-no-flyspell t org-emphasis t))
6080 (org-remove-font-lock-display-properties beg end)))
6082 (defconst org-script-display '(((raise -0.3) (height 0.7))
6083 ((raise 0.3) (height 0.7))
6084 ((raise -0.5))
6085 ((raise 0.5)))
6086 "Display properties for showing superscripts and subscripts.")
6088 (defun org-remove-font-lock-display-properties (beg end)
6089 "Remove specific display properties that have been added by font lock.
6090 The will remove the raise properties that are used to show superscripts
6091 and subscripts."
6092 (let (next prop)
6093 (while (< beg end)
6094 (setq next (next-single-property-change beg 'display nil end)
6095 prop (get-text-property beg 'display))
6096 (if (member prop org-script-display)
6097 (put-text-property beg next 'display nil))
6098 (setq beg next))))
6100 (defun org-raise-scripts (limit)
6101 "Add raise properties to sub/superscripts."
6102 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6103 (if (re-search-forward
6104 (if (eq org-use-sub-superscripts t)
6105 org-match-substring-regexp
6106 org-match-substring-with-braces-regexp)
6107 limit t)
6108 (let* ((pos (point)) table-p comment-p
6109 (mpos (match-beginning 3))
6110 (emph-p (get-text-property mpos 'org-emphasis))
6111 (link-p (get-text-property mpos 'mouse-face))
6112 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6113 (goto-char (point-at-bol))
6114 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6115 comment-p (org-looking-at-p "[ \t]*#"))
6116 (goto-char pos)
6117 ;; FIXME: Should we go back one character here, for a_b^c
6118 ;; (goto-char (1- pos)) ;????????????????????
6119 (if (or comment-p emph-p link-p keyw-p)
6121 (put-text-property (match-beginning 3) (match-end 0)
6122 'display
6123 (if (equal (char-after (match-beginning 2)) ?^)
6124 (nth (if table-p 3 1) org-script-display)
6125 (nth (if table-p 2 0) org-script-display)))
6126 (add-text-properties (match-beginning 2) (match-end 2)
6127 (list 'invisible t
6128 'org-dwidth t 'org-dwidth-n 1))
6129 (if (and (eq (char-after (match-beginning 3)) ?{)
6130 (eq (char-before (match-end 3)) ?}))
6131 (progn
6132 (add-text-properties
6133 (match-beginning 3) (1+ (match-beginning 3))
6134 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6135 (add-text-properties
6136 (1- (match-end 3)) (match-end 3)
6137 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6138 t)))))
6140 ;;;; Visibility cycling, including org-goto and indirect buffer
6142 ;;; Cycling
6144 (defvar org-cycle-global-status nil)
6145 (make-variable-buffer-local 'org-cycle-global-status)
6146 (defvar org-cycle-subtree-status nil)
6147 (make-variable-buffer-local 'org-cycle-subtree-status)
6149 ;;;###autoload
6151 (defvar org-inlinetask-min-level)
6153 (defun org-cycle (&optional arg)
6154 "TAB-action and visibility cycling for Org-mode.
6156 This is the command invoked in Org-mode by the TAB key. Its main purpose
6157 is outline visibility cycling, but it also invokes other actions
6158 in special contexts.
6160 - When this function is called with a prefix argument, rotate the entire
6161 buffer through 3 states (global cycling)
6162 1. OVERVIEW: Show only top-level headlines.
6163 2. CONTENTS: Show all headlines of all levels, but no body text.
6164 3. SHOW ALL: Show everything.
6165 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6166 determined by the variable `org-startup-folded', and by any VISIBILITY
6167 properties in the buffer.
6168 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6169 including any drawers.
6171 - When inside a table, re-align the table and move to the next field.
6173 - When point is at the beginning of a headline, rotate the subtree started
6174 by this line through 3 different states (local cycling)
6175 1. FOLDED: Only the main headline is shown.
6176 2. CHILDREN: The main headline and the direct children are shown.
6177 From this state, you can move to one of the children
6178 and zoom in further.
6179 3. SUBTREE: Show the entire subtree, including body text.
6180 If there is no subtree, switch directly from CHILDREN to FOLDED.
6182 - When point is at the beginning of an empty headline and the variable
6183 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6184 of the headline by demoting and promoting it to likely levels. This
6185 speeds up creation document structure by pressing TAB once or several
6186 times right after creating a new headline.
6188 - When there is a numeric prefix, go up to a heading with level ARG, do
6189 a `show-subtree' and return to the previous cursor position. If ARG
6190 is negative, go up that many levels.
6192 - When point is not at the beginning of a headline, execute the global
6193 binding for TAB, which is re-indenting the line. See the option
6194 `org-cycle-emulate-tab' for details.
6196 - Special case: if point is at the beginning of the buffer and there is
6197 no headline in line 1, this function will act as if called with prefix arg
6198 (C-u TAB, same as S-TAB) also when called without prefix arg.
6199 But only if also the variable `org-cycle-global-at-bob' is t."
6200 (interactive "P")
6201 (org-load-modules-maybe)
6202 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6203 (and org-cycle-level-after-item/entry-creation
6204 (or (org-cycle-level)
6205 (org-cycle-item-indentation))))
6206 (let* ((limit-level
6207 (or org-cycle-max-level
6208 (and (boundp 'org-inlinetask-min-level)
6209 org-inlinetask-min-level
6210 (1- org-inlinetask-min-level))))
6211 (nstars (and limit-level
6212 (if org-odd-levels-only
6213 (and limit-level (1- (* limit-level 2)))
6214 limit-level)))
6215 (org-outline-regexp
6216 (if (not (derived-mode-p 'org-mode))
6217 outline-regexp
6218 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6219 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6220 (not (looking-at org-outline-regexp))))
6221 (org-cycle-hook
6222 (if bob-special
6223 (delq 'org-optimize-window-after-visibility-change
6224 (copy-sequence org-cycle-hook))
6225 org-cycle-hook))
6226 (pos (point)))
6228 (if (or bob-special (equal arg '(4)))
6229 ;; special case: use global cycling
6230 (setq arg t))
6232 (cond
6234 ((equal arg '(16))
6235 (setq last-command 'dummy)
6236 (org-set-startup-visibility)
6237 (message "Startup visibility, plus VISIBILITY properties"))
6239 ((equal arg '(64))
6240 (show-all)
6241 (message "Entire buffer visible, including drawers"))
6243 ;; Table: enter it or move to the next field.
6244 ((org-at-table-p 'any)
6245 (if (org-at-table.el-p)
6246 (message "Use C-c ' to edit table.el tables")
6247 (if arg (org-table-edit-field t)
6248 (org-table-justify-field-maybe)
6249 (call-interactively 'org-table-next-field))))
6251 ((run-hook-with-args-until-success
6252 'org-tab-after-check-for-table-hook))
6254 ;; Global cycling: delegate to `org-cycle-internal-global'.
6255 ((eq arg t) (org-cycle-internal-global))
6257 ;; Drawers: delegate to `org-flag-drawer'.
6258 ((and org-drawers org-drawer-regexp
6259 (save-excursion
6260 (beginning-of-line 1)
6261 (looking-at org-drawer-regexp)))
6262 (org-flag-drawer ; toggle block visibility
6263 (not (get-char-property (match-end 0) 'invisible))))
6265 ;; Show-subtree, ARG levels up from here.
6266 ((integerp arg)
6267 (save-excursion
6268 (org-back-to-heading)
6269 (outline-up-heading (if (< arg 0) (- arg)
6270 (- (funcall outline-level) arg)))
6271 (org-show-subtree)))
6273 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6274 ((and (featurep 'org-inlinetask)
6275 (org-inlinetask-at-task-p)
6276 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6277 (org-inlinetask-toggle-visibility))
6279 ((org-try-cdlatex-tab))
6281 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6282 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6283 (save-excursion (beginning-of-line 1)
6284 (looking-at org-outline-regexp)))
6285 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6286 (org-cycle-internal-local))
6288 ;; From there: TAB emulation and template completion.
6289 (buffer-read-only (org-back-to-heading))
6291 ((run-hook-with-args-until-success
6292 'org-tab-after-check-for-cycling-hook))
6294 ((org-try-structure-completion))
6296 ((run-hook-with-args-until-success
6297 'org-tab-before-tab-emulation-hook))
6299 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6300 (or (not (bolp))
6301 (not (looking-at org-outline-regexp))))
6302 (call-interactively (global-key-binding "\t")))
6304 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6305 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6306 (or (and (eq org-cycle-emulate-tab 'white)
6307 (= (match-end 0) (point-at-eol)))
6308 (and (eq org-cycle-emulate-tab 'whitestart)
6309 (>= (match-end 0) pos))))
6311 (eq org-cycle-emulate-tab t))
6312 (call-interactively (global-key-binding "\t")))
6314 (t (save-excursion
6315 (org-back-to-heading)
6316 (org-cycle)))))))
6318 (defun org-cycle-internal-global ()
6319 "Do the global cycling action."
6320 ;; Hack to avoid display of messages for .org attachments in Gnus
6321 (let ((ga (string-match "\\*fontification" (buffer-name))))
6322 (cond
6323 ((and (eq last-command this-command)
6324 (eq org-cycle-global-status 'overview))
6325 ;; We just created the overview - now do table of contents
6326 ;; This can be slow in very large buffers, so indicate action
6327 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6328 (unless ga (message "CONTENTS..."))
6329 (org-content)
6330 (unless ga (message "CONTENTS...done"))
6331 (setq org-cycle-global-status 'contents)
6332 (run-hook-with-args 'org-cycle-hook 'contents))
6334 ((and (eq last-command this-command)
6335 (eq org-cycle-global-status 'contents))
6336 ;; We just showed the table of contents - now show everything
6337 (run-hook-with-args 'org-pre-cycle-hook 'all)
6338 (show-all)
6339 (unless ga (message "SHOW ALL"))
6340 (setq org-cycle-global-status 'all)
6341 (run-hook-with-args 'org-cycle-hook 'all))
6344 ;; Default action: go to overview
6345 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6346 (org-overview)
6347 (unless ga (message "OVERVIEW"))
6348 (setq org-cycle-global-status 'overview)
6349 (run-hook-with-args 'org-cycle-hook 'overview)))))
6351 (defun org-cycle-internal-local ()
6352 "Do the local cycling action."
6353 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6354 ;; First, determine end of headline (EOH), end of subtree or item
6355 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6356 (save-excursion
6357 (if (org-at-item-p)
6358 (progn
6359 (beginning-of-line)
6360 (setq struct (org-list-struct))
6361 (setq eoh (point-at-eol))
6362 (setq eos (org-list-get-item-end-before-blank (point) struct))
6363 (setq has-children (org-list-has-child-p (point) struct)))
6364 (org-back-to-heading)
6365 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6366 (setq eos (save-excursion
6367 (org-end-of-subtree t)
6368 (unless (eobp)
6369 (skip-chars-forward " \t\n"))
6370 (if (eobp) (point) (1- (point)))))
6371 (setq has-children
6372 (or (save-excursion
6373 (let ((level (funcall outline-level)))
6374 (outline-next-heading)
6375 (and (org-at-heading-p t)
6376 (> (funcall outline-level) level))))
6377 (save-excursion
6378 (org-list-search-forward (org-item-beginning-re) eos t)))))
6379 ;; Determine end invisible part of buffer (EOL)
6380 (beginning-of-line 2)
6381 ;; XEmacs doesn't have `next-single-char-property-change'
6382 (if (featurep 'xemacs)
6383 (while (and (not (eobp)) ;; this is like `next-line'
6384 (get-char-property (1- (point)) 'invisible))
6385 (beginning-of-line 2))
6386 (while (and (not (eobp)) ;; this is like `next-line'
6387 (get-char-property (1- (point)) 'invisible))
6388 (goto-char (next-single-char-property-change (point) 'invisible))
6389 (and (eolp) (beginning-of-line 2))))
6390 (setq eol (point)))
6391 ;; Find out what to do next and set `this-command'
6392 (cond
6393 ((= eos eoh)
6394 ;; Nothing is hidden behind this heading
6395 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6396 (message "EMPTY ENTRY")
6397 (setq org-cycle-subtree-status nil)
6398 (save-excursion
6399 (goto-char eos)
6400 (outline-next-heading)
6401 (if (outline-invisible-p) (org-flag-heading nil))))
6402 ((and (or (>= eol eos)
6403 (not (string-match "\\S-" (buffer-substring eol eos))))
6404 (or has-children
6405 (not (setq children-skipped
6406 org-cycle-skip-children-state-if-no-children))))
6407 ;; Entire subtree is hidden in one line: children view
6408 (run-hook-with-args 'org-pre-cycle-hook 'children)
6409 (if (org-at-item-p)
6410 (org-list-set-item-visibility (point-at-bol) struct 'children)
6411 (org-show-entry)
6412 (org-with-limited-levels (show-children))
6413 ;; FIXME: This slows down the func way too much.
6414 ;; How keep drawers hidden in subtree anyway?
6415 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6416 ;; (org-cycle-hide-drawers 'subtree))
6418 ;; Fold every list in subtree to top-level items.
6419 (when (eq org-cycle-include-plain-lists 'integrate)
6420 (save-excursion
6421 (org-back-to-heading)
6422 (while (org-list-search-forward (org-item-beginning-re) eos t)
6423 (beginning-of-line 1)
6424 (let* ((struct (org-list-struct))
6425 (prevs (org-list-prevs-alist struct))
6426 (end (org-list-get-bottom-point struct)))
6427 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6428 (org-list-get-all-items (point) struct prevs))
6429 (goto-char end))))))
6430 (message "CHILDREN")
6431 (save-excursion
6432 (goto-char eos)
6433 (outline-next-heading)
6434 (if (outline-invisible-p) (org-flag-heading nil)))
6435 (setq org-cycle-subtree-status 'children)
6436 (run-hook-with-args 'org-cycle-hook 'children))
6437 ((or children-skipped
6438 (and (eq last-command this-command)
6439 (eq org-cycle-subtree-status 'children)))
6440 ;; We just showed the children, or no children are there,
6441 ;; now show everything.
6442 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6443 (outline-flag-region eoh eos nil)
6444 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6445 (setq org-cycle-subtree-status 'subtree)
6446 (run-hook-with-args 'org-cycle-hook 'subtree))
6448 ;; Default action: hide the subtree.
6449 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6450 (outline-flag-region eoh eos t)
6451 (message "FOLDED")
6452 (setq org-cycle-subtree-status 'folded)
6453 (run-hook-with-args 'org-cycle-hook 'folded)))))
6455 ;;;###autoload
6456 (defun org-global-cycle (&optional arg)
6457 "Cycle the global visibility. For details see `org-cycle'.
6458 With \\[universal-argument] prefix arg, switch to startup visibility.
6459 With a numeric prefix, show all headlines up to that level."
6460 (interactive "P")
6461 (let ((org-cycle-include-plain-lists
6462 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6463 (cond
6464 ((integerp arg)
6465 (show-all)
6466 (hide-sublevels arg)
6467 (setq org-cycle-global-status 'contents))
6468 ((equal arg '(4))
6469 (org-set-startup-visibility)
6470 (message "Startup visibility, plus VISIBILITY properties."))
6472 (org-cycle '(4))))))
6474 (defun org-set-startup-visibility ()
6475 "Set the visibility required by startup options and properties."
6476 (cond
6477 ((eq org-startup-folded t)
6478 (org-cycle '(4)))
6479 ((eq org-startup-folded 'content)
6480 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6481 (org-cycle '(4)) (org-cycle '(4)))))
6482 (unless (eq org-startup-folded 'showeverything)
6483 (if org-hide-block-startup (org-hide-block-all))
6484 (org-set-visibility-according-to-property 'no-cleanup)
6485 (org-cycle-hide-archived-subtrees 'all)
6486 (org-cycle-hide-drawers 'all)
6487 (org-cycle-show-empty-lines t)))
6489 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6490 "Switch subtree visibilities according to :VISIBILITY: property."
6491 (interactive)
6492 (let (org-show-entry-below state)
6493 (save-excursion
6494 (goto-char (point-min))
6495 (while (re-search-forward
6496 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6497 nil t)
6498 (setq state (match-string 1))
6499 (save-excursion
6500 (org-back-to-heading t)
6501 (hide-subtree)
6502 (org-reveal)
6503 (cond
6504 ((equal state '("fold" "folded"))
6505 (hide-subtree))
6506 ((equal state "children")
6507 (org-show-hidden-entry)
6508 (show-children))
6509 ((equal state "content")
6510 (save-excursion
6511 (save-restriction
6512 (org-narrow-to-subtree)
6513 (org-content))))
6514 ((member state '("all" "showall"))
6515 (show-subtree)))))
6516 (unless no-cleanup
6517 (org-cycle-hide-archived-subtrees 'all)
6518 (org-cycle-hide-drawers 'all)
6519 (org-cycle-show-empty-lines 'all)))))
6521 ;; This function uses outline-regexp instead of the more fundamental
6522 ;; org-outline-regexp so that org-cycle-global works outside of Org
6523 ;; buffers, where outline-regexp is needed.
6524 (defun org-overview ()
6525 "Switch to overview mode, showing only top-level headlines.
6526 Really, this shows all headlines with level equal or greater than the level
6527 of the first headline in the buffer. This is important, because if the
6528 first headline is not level one, then (hide-sublevels 1) gives confusing
6529 results."
6530 (interactive)
6531 (let ((level (save-excursion
6532 (goto-char (point-min))
6533 (if (re-search-forward (concat "^" outline-regexp) nil t)
6534 (progn
6535 (goto-char (match-beginning 0))
6536 (funcall outline-level))))))
6537 (and level (hide-sublevels level))))
6539 (defun org-content (&optional arg)
6540 "Show all headlines in the buffer, like a table of contents.
6541 With numerical argument N, show content up to level N."
6542 (interactive "P")
6543 (save-excursion
6544 ;; Visit all headings and show their offspring
6545 (and (integerp arg) (org-overview))
6546 (goto-char (point-max))
6547 (catch 'exit
6548 (while (and (progn (condition-case nil
6549 (outline-previous-visible-heading 1)
6550 (error (goto-char (point-min))))
6552 (looking-at org-outline-regexp))
6553 (if (integerp arg)
6554 (show-children (1- arg))
6555 (show-branches))
6556 (if (bobp) (throw 'exit nil))))))
6559 (defun org-optimize-window-after-visibility-change (state)
6560 "Adjust the window after a change in outline visibility.
6561 This function is the default value of the hook `org-cycle-hook'."
6562 (when (get-buffer-window (current-buffer))
6563 (cond
6564 ((eq state 'content) nil)
6565 ((eq state 'all) nil)
6566 ((eq state 'folded) nil)
6567 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6568 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6570 (defun org-remove-empty-overlays-at (pos)
6571 "Remove outline overlays that do not contain non-white stuff."
6572 (mapc
6573 (lambda (o)
6574 (and (eq 'outline (overlay-get o 'invisible))
6575 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6576 (overlay-end o))))
6577 (delete-overlay o)))
6578 (overlays-at pos)))
6580 (defun org-clean-visibility-after-subtree-move ()
6581 "Fix visibility issues after moving a subtree."
6582 ;; First, find a reasonable region to look at:
6583 ;; Start two siblings above, end three below
6584 (let* ((beg (save-excursion
6585 (and (org-get-last-sibling)
6586 (org-get-last-sibling))
6587 (point)))
6588 (end (save-excursion
6589 (and (org-get-next-sibling)
6590 (org-get-next-sibling)
6591 (org-get-next-sibling))
6592 (if (org-at-heading-p)
6593 (point-at-eol)
6594 (point))))
6595 (level (looking-at "\\*+"))
6596 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6597 (save-excursion
6598 (save-restriction
6599 (narrow-to-region beg end)
6600 (when re
6601 ;; Properly fold already folded siblings
6602 (goto-char (point-min))
6603 (while (re-search-forward re nil t)
6604 (if (and (not (outline-invisible-p))
6605 (save-excursion
6606 (goto-char (point-at-eol)) (outline-invisible-p)))
6607 (hide-entry))))
6608 (org-cycle-show-empty-lines 'overview)
6609 (org-cycle-hide-drawers 'overview)))))
6611 (defun org-cycle-show-empty-lines (state)
6612 "Show empty lines above all visible headlines.
6613 The region to be covered depends on STATE when called through
6614 `org-cycle-hook'. Lisp program can use t for STATE to get the
6615 entire buffer covered. Note that an empty line is only shown if there
6616 are at least `org-cycle-separator-lines' empty lines before the headline."
6617 (when (not (= org-cycle-separator-lines 0))
6618 (save-excursion
6619 (let* ((n (abs org-cycle-separator-lines))
6620 (re (cond
6621 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6622 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6623 (t (let ((ns (number-to-string (- n 2))))
6624 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6625 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6626 beg end b e)
6627 (cond
6628 ((memq state '(overview contents t))
6629 (setq beg (point-min) end (point-max)))
6630 ((memq state '(children folded))
6631 (setq beg (point) end (progn (org-end-of-subtree t t)
6632 (beginning-of-line 2)
6633 (point)))))
6634 (when beg
6635 (goto-char beg)
6636 (while (re-search-forward re end t)
6637 (unless (get-char-property (match-end 1) 'invisible)
6638 (setq e (match-end 1))
6639 (if (< org-cycle-separator-lines 0)
6640 (setq b (save-excursion
6641 (goto-char (match-beginning 0))
6642 (org-back-over-empty-lines)
6643 (if (save-excursion
6644 (goto-char (max (point-min) (1- (point))))
6645 (org-at-heading-p))
6646 (1- (point))
6647 (point))))
6648 (setq b (match-beginning 1)))
6649 (outline-flag-region b e nil)))))))
6650 ;; Never hide empty lines at the end of the file.
6651 (save-excursion
6652 (goto-char (point-max))
6653 (outline-previous-heading)
6654 (outline-end-of-heading)
6655 (if (and (looking-at "[ \t\n]+")
6656 (= (match-end 0) (point-max)))
6657 (outline-flag-region (point) (match-end 0) nil))))
6659 (defun org-show-empty-lines-in-parent ()
6660 "Move to the parent and re-show empty lines before visible headlines."
6661 (save-excursion
6662 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6663 (org-cycle-show-empty-lines context))))
6665 (defun org-files-list ()
6666 "Return `org-agenda-files' list, plus all open org-mode files.
6667 This is useful for operations that need to scan all of a user's
6668 open and agenda-wise Org files."
6669 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6670 (dolist (buf (buffer-list))
6671 (with-current-buffer buf
6672 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6673 (let ((file (expand-file-name (buffer-file-name))))
6674 (unless (member file files)
6675 (push file files))))))
6676 files))
6678 (defsubst org-entry-beginning-position ()
6679 "Return the beginning position of the current entry."
6680 (save-excursion (outline-back-to-heading t) (point)))
6682 (defsubst org-entry-end-position ()
6683 "Return the end position of the current entry."
6684 (save-excursion (outline-next-heading) (point)))
6686 (defun org-cycle-hide-drawers (state)
6687 "Re-hide all drawers after a visibility state change."
6688 (when (and (derived-mode-p 'org-mode)
6689 (not (memq state '(overview folded contents))))
6690 (save-excursion
6691 (let* ((globalp (memq state '(contents all)))
6692 (beg (if globalp (point-min) (point)))
6693 (end (if globalp (point-max)
6694 (if (eq state 'children)
6695 (save-excursion (outline-next-heading) (point))
6696 (org-end-of-subtree t)))))
6697 (goto-char beg)
6698 (while (re-search-forward org-drawer-regexp end t)
6699 (org-flag-drawer t))))))
6701 (defun org-flag-drawer (flag)
6702 (save-excursion
6703 (beginning-of-line 1)
6704 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6705 (let ((b (match-end 0)))
6706 (if (re-search-forward
6707 "^[ \t]*:END:"
6708 (save-excursion (outline-next-heading) (point)) t)
6709 (outline-flag-region b (point-at-eol) flag)
6710 (error ":END: line missing at position %s" b))))))
6712 (defun org-subtree-end-visible-p ()
6713 "Is the end of the current subtree visible?"
6714 (pos-visible-in-window-p
6715 (save-excursion (org-end-of-subtree t) (point))))
6717 (defun org-first-headline-recenter (&optional N)
6718 "Move cursor to the first headline and recenter the headline.
6719 Optional argument N means put the headline into the Nth line of the window."
6720 (goto-char (point-min))
6721 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6722 (beginning-of-line)
6723 (recenter (prefix-numeric-value N))))
6725 ;;; Saving and restoring visibility
6727 (defun org-outline-overlay-data (&optional use-markers)
6728 "Return a list of the locations of all outline overlays.
6729 These are overlays with the `invisible' property value `outline'.
6730 The return value is a list of cons cells, with start and stop
6731 positions for each overlay.
6732 If USE-MARKERS is set, return the positions as markers."
6733 (let (beg end)
6734 (save-excursion
6735 (save-restriction
6736 (widen)
6737 (delq nil
6738 (mapcar (lambda (o)
6739 (when (eq (overlay-get o 'invisible) 'outline)
6740 (setq beg (overlay-start o)
6741 end (overlay-end o))
6742 (and beg end (> end beg)
6743 (if use-markers
6744 (cons (move-marker (make-marker) beg)
6745 (move-marker (make-marker) end))
6746 (cons beg end)))))
6747 (overlays-in (point-min) (point-max))))))))
6749 (defun org-set-outline-overlay-data (data)
6750 "Create visibility overlays for all positions in DATA.
6751 DATA should have been made by `org-outline-overlay-data'."
6752 (let (o)
6753 (save-excursion
6754 (save-restriction
6755 (widen)
6756 (show-all)
6757 (mapc (lambda (c)
6758 (outline-flag-region (car c) (cdr c) t))
6759 data)))))
6761 ;;; Folding of blocks
6763 (defvar org-hide-block-overlays nil
6764 "Overlays hiding blocks.")
6765 (make-variable-buffer-local 'org-hide-block-overlays)
6767 (defun org-block-map (function &optional start end)
6768 "Call FUNCTION at the head of all source blocks in the current buffer.
6769 Optional arguments START and END can be used to limit the range."
6770 (let ((start (or start (point-min)))
6771 (end (or end (point-max))))
6772 (save-excursion
6773 (goto-char start)
6774 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6775 (save-excursion
6776 (save-match-data
6777 (goto-char (match-beginning 0))
6778 (funcall function)))))))
6780 (defun org-hide-block-toggle-all ()
6781 "Toggle the visibility of all blocks in the current buffer."
6782 (org-block-map #'org-hide-block-toggle))
6784 (defun org-hide-block-all ()
6785 "Fold all blocks in the current buffer."
6786 (interactive)
6787 (org-show-block-all)
6788 (org-block-map #'org-hide-block-toggle-maybe))
6790 (defun org-show-block-all ()
6791 "Unfold all blocks in the current buffer."
6792 (interactive)
6793 (mapc 'delete-overlay org-hide-block-overlays)
6794 (setq org-hide-block-overlays nil))
6796 (defun org-hide-block-toggle-maybe ()
6797 "Toggle visibility of block at point."
6798 (interactive)
6799 (let ((case-fold-search t))
6800 (if (save-excursion
6801 (beginning-of-line 1)
6802 (looking-at org-block-regexp))
6803 (progn (org-hide-block-toggle)
6804 t) ;; to signal that we took action
6805 nil))) ;; to signal that we did not
6807 (defun org-hide-block-toggle (&optional force)
6808 "Toggle the visibility of the current block."
6809 (interactive)
6810 (save-excursion
6811 (beginning-of-line)
6812 (if (re-search-forward org-block-regexp nil t)
6813 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6814 (end (match-end 0)) ;; end of entire body
6816 (if (memq t (mapcar (lambda (overlay)
6817 (eq (overlay-get overlay 'invisible)
6818 'org-hide-block))
6819 (overlays-at start)))
6820 (if (or (not force) (eq force 'off))
6821 (mapc (lambda (ov)
6822 (when (member ov org-hide-block-overlays)
6823 (setq org-hide-block-overlays
6824 (delq ov org-hide-block-overlays)))
6825 (when (eq (overlay-get ov 'invisible)
6826 'org-hide-block)
6827 (delete-overlay ov)))
6828 (overlays-at start)))
6829 (setq ov (make-overlay start end))
6830 (overlay-put ov 'invisible 'org-hide-block)
6831 ;; make the block accessible to isearch
6832 (overlay-put
6833 ov 'isearch-open-invisible
6834 (lambda (ov)
6835 (when (member ov org-hide-block-overlays)
6836 (setq org-hide-block-overlays
6837 (delq ov org-hide-block-overlays)))
6838 (when (eq (overlay-get ov 'invisible)
6839 'org-hide-block)
6840 (delete-overlay ov))))
6841 (push ov org-hide-block-overlays)))
6842 (error "Not looking at a source block"))))
6844 ;; org-tab-after-check-for-cycling-hook
6845 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6846 ;; Remove overlays when changing major mode
6847 (add-hook 'org-mode-hook
6848 (lambda () (org-add-hook 'change-major-mode-hook
6849 'org-show-block-all 'append 'local)))
6851 ;;; Org-goto
6853 (defvar org-goto-window-configuration nil)
6854 (defvar org-goto-marker nil)
6855 (defvar org-goto-map
6856 (let ((map (make-sparse-keymap)))
6857 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6858 (while (setq cmd (pop cmds))
6859 (substitute-key-definition cmd cmd map global-map)))
6860 (suppress-keymap map)
6861 (org-defkey map "\C-m" 'org-goto-ret)
6862 (org-defkey map [(return)] 'org-goto-ret)
6863 (org-defkey map [(left)] 'org-goto-left)
6864 (org-defkey map [(right)] 'org-goto-right)
6865 (org-defkey map [(control ?g)] 'org-goto-quit)
6866 (org-defkey map "\C-i" 'org-cycle)
6867 (org-defkey map [(tab)] 'org-cycle)
6868 (org-defkey map [(down)] 'outline-next-visible-heading)
6869 (org-defkey map [(up)] 'outline-previous-visible-heading)
6870 (if org-goto-auto-isearch
6871 (if (fboundp 'define-key-after)
6872 (define-key-after map [t] 'org-goto-local-auto-isearch)
6873 nil)
6874 (org-defkey map "q" 'org-goto-quit)
6875 (org-defkey map "n" 'outline-next-visible-heading)
6876 (org-defkey map "p" 'outline-previous-visible-heading)
6877 (org-defkey map "f" 'outline-forward-same-level)
6878 (org-defkey map "b" 'outline-backward-same-level)
6879 (org-defkey map "u" 'outline-up-heading))
6880 (org-defkey map "/" 'org-occur)
6881 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6882 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6883 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6884 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6885 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6886 map))
6888 (defconst org-goto-help
6889 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6890 RET=jump to location [Q]uit and return to previous location
6891 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6893 (defvar org-goto-start-pos) ; dynamically scoped parameter
6895 ;; FIXME: Docstring does not mention both interfaces
6896 (defun org-goto (&optional alternative-interface)
6897 "Look up a different location in the current file, keeping current visibility.
6899 When you want look-up or go to a different location in a
6900 document, the fastest way is often to fold the entire buffer and
6901 then dive into the tree. This method has the disadvantage, that
6902 the previous location will be folded, which may not be what you
6903 want.
6905 This command works around this by showing a copy of the current
6906 buffer in an indirect buffer, in overview mode. You can dive
6907 into the tree in that copy, use org-occur and incremental search
6908 to find a location. When pressing RET or `Q', the command
6909 returns to the original buffer in which the visibility is still
6910 unchanged. After RET it will also jump to the location selected
6911 in the indirect buffer and expose the headline hierarchy above.
6913 With a prefix argument, use the alternative interface: e.g. if
6914 `org-goto-interface' is 'outline use 'outline-path-completion."
6915 (interactive "P")
6916 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6917 (org-refile-use-outline-path t)
6918 (org-refile-target-verify-function nil)
6919 (interface
6920 (if (not alternative-interface)
6921 org-goto-interface
6922 (if (eq org-goto-interface 'outline)
6923 'outline-path-completion
6924 'outline)))
6925 (org-goto-start-pos (point))
6926 (selected-point
6927 (if (eq interface 'outline)
6928 (car (org-get-location (current-buffer) org-goto-help))
6929 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6930 (org-refile-check-position pa)
6931 (nth 3 pa)))))
6932 (if selected-point
6933 (progn
6934 (org-mark-ring-push org-goto-start-pos)
6935 (goto-char selected-point)
6936 (if (or (outline-invisible-p) (org-invisible-p2))
6937 (org-show-context 'org-goto)))
6938 (message "Quit"))))
6940 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6941 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6942 (defvar org-goto-local-auto-isearch-map) ; defined below
6944 (defun org-get-location (buf help)
6945 "Let the user select a location in the Org-mode buffer BUF.
6946 This function uses a recursive edit. It returns the selected position
6947 or nil."
6948 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6949 (isearch-hide-immediately nil)
6950 (isearch-search-fun-function
6951 (lambda () 'org-goto-local-search-headings))
6952 (org-goto-selected-point org-goto-exit-command)
6953 (pop-up-frames nil)
6954 (special-display-buffer-names nil)
6955 (special-display-regexps nil)
6956 (special-display-function nil))
6957 (save-excursion
6958 (save-window-excursion
6959 (delete-other-windows)
6960 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6961 (org-pop-to-buffer-same-window
6962 (condition-case nil
6963 (make-indirect-buffer (current-buffer) "*org-goto*")
6964 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6965 (with-output-to-temp-buffer "*Help*"
6966 (princ help))
6967 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6968 (setq buffer-read-only nil)
6969 (let ((org-startup-truncated t)
6970 (org-startup-folded nil)
6971 (org-startup-align-all-tables nil))
6972 (org-mode)
6973 (org-overview))
6974 (setq buffer-read-only t)
6975 (if (and (boundp 'org-goto-start-pos)
6976 (integer-or-marker-p org-goto-start-pos))
6977 (let ((org-show-hierarchy-above t)
6978 (org-show-siblings t)
6979 (org-show-following-heading t))
6980 (goto-char org-goto-start-pos)
6981 (and (outline-invisible-p) (org-show-context)))
6982 (goto-char (point-min)))
6983 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6984 (message "Select location and press RET")
6985 (use-local-map org-goto-map)
6986 (recursive-edit)
6988 (kill-buffer "*org-goto*")
6989 (cons org-goto-selected-point org-goto-exit-command)))
6991 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6992 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6993 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6994 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6996 (defun org-goto-local-search-headings (string bound noerror)
6997 "Search and make sure that any matches are in headlines."
6998 (catch 'return
6999 (while (if isearch-forward
7000 (search-forward string bound noerror)
7001 (search-backward string bound noerror))
7002 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7003 (and (member :headline context)
7004 (not (member :tags context))))
7005 (throw 'return (point))))))
7007 (defun org-goto-local-auto-isearch ()
7008 "Start isearch."
7009 (interactive)
7010 (goto-char (point-min))
7011 (let ((keys (this-command-keys)))
7012 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7013 (isearch-mode t)
7014 (isearch-process-search-char (string-to-char keys)))))
7016 (defun org-goto-ret (&optional arg)
7017 "Finish `org-goto' by going to the new location."
7018 (interactive "P")
7019 (setq org-goto-selected-point (point)
7020 org-goto-exit-command 'return)
7021 (throw 'exit nil))
7023 (defun org-goto-left ()
7024 "Finish `org-goto' by going to the new location."
7025 (interactive)
7026 (if (org-at-heading-p)
7027 (progn
7028 (beginning-of-line 1)
7029 (setq org-goto-selected-point (point)
7030 org-goto-exit-command 'left)
7031 (throw 'exit nil))
7032 (error "Not on a heading")))
7034 (defun org-goto-right ()
7035 "Finish `org-goto' by going to the new location."
7036 (interactive)
7037 (if (org-at-heading-p)
7038 (progn
7039 (setq org-goto-selected-point (point)
7040 org-goto-exit-command 'right)
7041 (throw 'exit nil))
7042 (error "Not on a heading")))
7044 (defun org-goto-quit ()
7045 "Finish `org-goto' without cursor motion."
7046 (interactive)
7047 (setq org-goto-selected-point nil)
7048 (setq org-goto-exit-command 'quit)
7049 (throw 'exit nil))
7051 ;;; Indirect buffer display of subtrees
7053 (defvar org-indirect-dedicated-frame nil
7054 "This is the frame being used for indirect tree display.")
7055 (defvar org-last-indirect-buffer nil)
7057 (defun org-tree-to-indirect-buffer (&optional arg)
7058 "Create indirect buffer and narrow it to current subtree.
7059 With numerical prefix ARG, go up to this level and then take that tree.
7060 If ARG is negative, go up that many levels.
7061 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7062 indirect buffer previously made with this command, to avoid proliferation of
7063 indirect buffers. However, when you call the command with a \
7064 \\[universal-argument] prefix, or
7065 when `org-indirect-buffer-display' is `new-frame', the last buffer
7066 is kept so that you can work with several indirect buffers at the same time.
7067 If `org-indirect-buffer-display' is `dedicated-frame', the \
7068 \\[universal-argument] prefix also
7069 requests that a new frame be made for the new buffer, so that the dedicated
7070 frame is not changed."
7071 (interactive "P")
7072 (let ((cbuf (current-buffer))
7073 (cwin (selected-window))
7074 (pos (point))
7075 beg end level heading ibuf)
7076 (save-excursion
7077 (org-back-to-heading t)
7078 (when (numberp arg)
7079 (setq level (org-outline-level))
7080 (if (< arg 0) (setq arg (+ level arg)))
7081 (while (> (setq level (org-outline-level)) arg)
7082 (outline-up-heading 1 t)))
7083 (setq beg (point)
7084 heading (org-get-heading))
7085 (org-end-of-subtree t t)
7086 (if (org-at-heading-p) (backward-char 1))
7087 (setq end (point)))
7088 (if (and (buffer-live-p org-last-indirect-buffer)
7089 (not (eq org-indirect-buffer-display 'new-frame))
7090 (not arg))
7091 (kill-buffer org-last-indirect-buffer))
7092 (setq ibuf (org-get-indirect-buffer cbuf)
7093 org-last-indirect-buffer ibuf)
7094 (cond
7095 ((or (eq org-indirect-buffer-display 'new-frame)
7096 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7097 (select-frame (make-frame))
7098 (delete-other-windows)
7099 (org-pop-to-buffer-same-window ibuf)
7100 (org-set-frame-title heading))
7101 ((eq org-indirect-buffer-display 'dedicated-frame)
7102 (raise-frame
7103 (select-frame (or (and org-indirect-dedicated-frame
7104 (frame-live-p org-indirect-dedicated-frame)
7105 org-indirect-dedicated-frame)
7106 (setq org-indirect-dedicated-frame (make-frame)))))
7107 (delete-other-windows)
7108 (org-pop-to-buffer-same-window ibuf)
7109 (org-set-frame-title (concat "Indirect: " heading)))
7110 ((eq org-indirect-buffer-display 'current-window)
7111 (org-pop-to-buffer-same-window ibuf))
7112 ((eq org-indirect-buffer-display 'other-window)
7113 (pop-to-buffer ibuf))
7114 (t (error "Invalid value")))
7115 (if (featurep 'xemacs)
7116 (save-excursion (org-mode) (turn-on-font-lock)))
7117 (narrow-to-region beg end)
7118 (show-all)
7119 (goto-char pos)
7120 (run-hook-with-args 'org-cycle-hook 'all)
7121 (and (window-live-p cwin) (select-window cwin))))
7123 (defun org-get-indirect-buffer (&optional buffer)
7124 (setq buffer (or buffer (current-buffer)))
7125 (let ((n 1) (base (buffer-name buffer)) bname)
7126 (while (buffer-live-p
7127 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7128 (setq n (1+ n)))
7129 (condition-case nil
7130 (make-indirect-buffer buffer bname 'clone)
7131 (error (make-indirect-buffer buffer bname)))))
7133 (defun org-set-frame-title (title)
7134 "Set the title of the current frame to the string TITLE."
7135 ;; FIXME: how to name a single frame in XEmacs???
7136 (unless (featurep 'xemacs)
7137 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7139 ;;;; Structure editing
7141 ;;; Inserting headlines
7143 (defun org-previous-line-empty-p ()
7144 (save-excursion
7145 (and (not (bobp))
7146 (or (beginning-of-line 0) t)
7147 (save-match-data
7148 (looking-at "[ \t]*$")))))
7150 (defun org-insert-heading (&optional force-heading invisible-ok)
7151 "Insert a new heading or item with same depth at point.
7152 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7153 If point is at the beginning of a headline, insert a sibling before the
7154 current headline. If point is not at the beginning, split the line,
7155 create the new headline with the text in the current line after point
7156 \(but see also the variable `org-M-RET-may-split-line').
7158 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7159 This is important for non-interactive uses of the command."
7160 (interactive "P")
7161 (if (or (= (buffer-size) 0)
7162 (and (not (save-excursion
7163 (and (ignore-errors (org-back-to-heading invisible-ok))
7164 (org-at-heading-p))))
7165 (or force-heading (not (org-in-item-p)))))
7166 (progn
7167 (insert "\n* ")
7168 (run-hooks 'org-insert-heading-hook))
7169 (when (or force-heading (not (org-insert-item)))
7170 (let* ((empty-line-p nil)
7171 (level nil)
7172 (on-heading (org-at-heading-p))
7173 (head (save-excursion
7174 (condition-case nil
7175 (progn
7176 (org-back-to-heading invisible-ok)
7177 (when (and (not on-heading)
7178 (featurep 'org-inlinetask)
7179 (integerp org-inlinetask-min-level)
7180 (>= (length (match-string 0))
7181 org-inlinetask-min-level))
7182 ;; Find a heading level before the inline task
7183 (while (and (setq level (org-up-heading-safe))
7184 (>= level org-inlinetask-min-level)))
7185 (if (org-at-heading-p)
7186 (org-back-to-heading invisible-ok)
7187 (error "This should not happen")))
7188 (setq empty-line-p (org-previous-line-empty-p))
7189 (match-string 0))
7190 (error "*"))))
7191 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7192 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7193 pos hide-previous previous-pos)
7194 (cond
7195 ((and (org-at-heading-p) (bolp)
7196 (or (bobp)
7197 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7198 ;; insert before the current line
7199 (open-line (if blank 2 1)))
7200 ((and (bolp)
7201 (not org-insert-heading-respect-content)
7202 (or (bobp)
7203 (save-excursion
7204 (backward-char 1) (not (outline-invisible-p)))))
7205 ;; insert right here
7206 nil)
7208 ;; somewhere in the line
7209 (save-excursion
7210 (setq previous-pos (point-at-bol))
7211 (end-of-line)
7212 (setq hide-previous (outline-invisible-p)))
7213 (and org-insert-heading-respect-content (org-show-subtree))
7214 (let ((split
7215 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7216 (save-excursion
7217 (let ((p (point)))
7218 (goto-char (point-at-bol))
7219 (and (looking-at org-complex-heading-regexp)
7220 (match-beginning 4)
7221 (> p (match-beginning 4)))))))
7222 tags pos)
7223 (cond
7224 (org-insert-heading-respect-content
7225 (org-end-of-subtree nil t)
7226 (when (featurep 'org-inlinetask)
7227 (while (and (not (eobp))
7228 (looking-at "\\(\\*+\\)[ \t]+")
7229 (>= (length (match-string 1))
7230 org-inlinetask-min-level))
7231 (org-end-of-subtree nil t)))
7232 (or (bolp) (newline))
7233 (or (org-previous-line-empty-p)
7234 (and blank (newline)))
7235 (open-line 1))
7236 ((org-at-heading-p)
7237 (when hide-previous
7238 (show-children)
7239 (org-show-entry))
7240 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7241 (setq tags (and (match-end 2) (match-string 2)))
7242 (and (match-end 1)
7243 (delete-region (match-beginning 1) (match-end 1)))
7244 (setq pos (point-at-bol))
7245 (or split (end-of-line 1))
7246 (delete-horizontal-space)
7247 (if (string-match "\\`\\*+\\'"
7248 (buffer-substring (point-at-bol) (point)))
7249 (insert " "))
7250 (newline (if blank 2 1))
7251 (when tags
7252 (save-excursion
7253 (goto-char pos)
7254 (end-of-line 1)
7255 (insert " " tags)
7256 (org-set-tags nil 'align))))
7258 (or split (end-of-line 1))
7259 (newline (if blank 2 1)))))))
7260 (insert head) (just-one-space)
7261 (setq pos (point))
7262 (end-of-line 1)
7263 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7264 (when (and org-insert-heading-respect-content hide-previous)
7265 (save-excursion
7266 (goto-char previous-pos)
7267 (hide-subtree)))
7268 (run-hooks 'org-insert-heading-hook)))))
7270 (defun org-get-heading (&optional no-tags no-todo)
7271 "Return the heading of the current entry, without the stars.
7272 When NO-TAGS is non-nil, don't include tags.
7273 When NO-TODO is non-nil, don't include TODO keywords."
7274 (save-excursion
7275 (org-back-to-heading t)
7276 (cond
7277 ((and no-tags no-todo)
7278 (looking-at org-complex-heading-regexp)
7279 (match-string 4))
7280 (no-tags
7281 (looking-at (concat org-outline-regexp
7282 "\\(.*?\\)"
7283 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7284 (match-string 1))
7285 (no-todo
7286 (looking-at org-todo-line-regexp)
7287 (match-string 3))
7288 (t (looking-at org-heading-regexp)
7289 (match-string 2)))))
7291 (defun org-heading-components ()
7292 "Return the components of the current heading.
7293 This is a list with the following elements:
7294 - the level as an integer
7295 - the reduced level, different if `org-odd-levels-only' is set.
7296 - the TODO keyword, or nil
7297 - the priority character, like ?A, or nil if no priority is given
7298 - the headline text itself, or the tags string if no headline text
7299 - the tags string, or nil."
7300 (save-excursion
7301 (org-back-to-heading t)
7302 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7303 (list (length (match-string 1))
7304 (org-reduced-level (length (match-string 1)))
7305 (org-match-string-no-properties 2)
7306 (and (match-end 3) (aref (match-string 3) 2))
7307 (org-match-string-no-properties 4)
7308 (org-match-string-no-properties 5)))))
7310 (defun org-get-entry ()
7311 "Get the entry text, after heading, entire subtree."
7312 (save-excursion
7313 (org-back-to-heading t)
7314 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7316 (defun org-insert-heading-after-current ()
7317 "Insert a new heading with same level as current, after current subtree."
7318 (interactive)
7319 (org-back-to-heading)
7320 (org-insert-heading)
7321 (org-move-subtree-down)
7322 (end-of-line 1))
7324 (defun org-insert-heading-respect-content ()
7325 (interactive)
7326 (let ((org-insert-heading-respect-content t))
7327 (org-insert-heading t)))
7329 (defun org-insert-todo-heading-respect-content (&optional force-state)
7330 (interactive "P")
7331 (let ((org-insert-heading-respect-content t))
7332 (org-insert-todo-heading force-state t)))
7334 (defun org-insert-todo-heading (arg &optional force-heading)
7335 "Insert a new heading with the same level and TODO state as current heading.
7336 If the heading has no TODO state, or if the state is DONE, use the first
7337 state (TODO by default). Also with prefix arg, force first state."
7338 (interactive "P")
7339 (when (or force-heading (not (org-insert-item 'checkbox)))
7340 (org-insert-heading force-heading)
7341 (save-excursion
7342 (org-back-to-heading)
7343 (outline-previous-heading)
7344 (looking-at org-todo-line-regexp))
7345 (let*
7346 ((new-mark-x
7347 (if (or arg
7348 (not (match-beginning 2))
7349 (member (match-string 2) org-done-keywords))
7350 (car org-todo-keywords-1)
7351 (match-string 2)))
7352 (new-mark
7354 (run-hook-with-args-until-success
7355 'org-todo-get-default-hook new-mark-x nil)
7356 new-mark-x)))
7357 (beginning-of-line 1)
7358 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7359 (if org-treat-insert-todo-heading-as-state-change
7360 (org-todo new-mark)
7361 (insert new-mark " "))))
7362 (when org-provide-todo-statistics
7363 (org-update-parent-todo-statistics))))
7365 (defun org-insert-subheading (arg)
7366 "Insert a new subheading and demote it.
7367 Works for outline headings and for plain lists alike."
7368 (interactive "P")
7369 (org-insert-heading arg)
7370 (cond
7371 ((org-at-heading-p) (org-do-demote))
7372 ((org-at-item-p) (org-indent-item))))
7374 (defun org-insert-todo-subheading (arg)
7375 "Insert a new subheading with TODO keyword or checkbox and demote it.
7376 Works for outline headings and for plain lists alike."
7377 (interactive "P")
7378 (org-insert-todo-heading arg)
7379 (cond
7380 ((org-at-heading-p) (org-do-demote))
7381 ((org-at-item-p) (org-indent-item))))
7383 ;;; Promotion and Demotion
7385 (defvar org-after-demote-entry-hook nil
7386 "Hook run after an entry has been demoted.
7387 The cursor will be at the beginning of the entry.
7388 When a subtree is being demoted, the hook will be called for each node.")
7390 (defvar org-after-promote-entry-hook nil
7391 "Hook run after an entry has been promoted.
7392 The cursor will be at the beginning of the entry.
7393 When a subtree is being promoted, the hook will be called for each node.")
7395 (defun org-promote-subtree ()
7396 "Promote the entire subtree.
7397 See also `org-promote'."
7398 (interactive)
7399 (save-excursion
7400 (org-with-limited-levels (org-map-tree 'org-promote)))
7401 (org-fix-position-after-promote))
7403 (defun org-demote-subtree ()
7404 "Demote the entire subtree. See `org-demote'.
7405 See also `org-promote'."
7406 (interactive)
7407 (save-excursion
7408 (org-with-limited-levels (org-map-tree 'org-demote)))
7409 (org-fix-position-after-promote))
7412 (defun org-do-promote ()
7413 "Promote the current heading higher up the tree.
7414 If the region is active in `transient-mark-mode', promote all headings
7415 in the region."
7416 (interactive)
7417 (save-excursion
7418 (if (org-region-active-p)
7419 (org-map-region 'org-promote (region-beginning) (region-end))
7420 (org-promote)))
7421 (org-fix-position-after-promote))
7423 (defun org-do-demote ()
7424 "Demote the current heading lower down the tree.
7425 If the region is active in `transient-mark-mode', demote all headings
7426 in the region."
7427 (interactive)
7428 (save-excursion
7429 (if (org-region-active-p)
7430 (org-map-region 'org-demote (region-beginning) (region-end))
7431 (org-demote)))
7432 (org-fix-position-after-promote))
7434 (defun org-fix-position-after-promote ()
7435 "Make sure that after pro/demotion cursor position is right."
7436 (let ((pos (point)))
7437 (when (save-excursion
7438 (beginning-of-line 1)
7439 (looking-at org-todo-line-regexp)
7440 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7441 (cond ((eobp) (insert " "))
7442 ((eolp) (insert " "))
7443 ((equal (char-after) ?\ ) (forward-char 1))))))
7445 (defun org-current-level ()
7446 "Return the level of the current entry, or nil if before the first headline.
7447 The level is the number of stars at the beginning of the headline."
7448 (save-excursion
7449 (org-with-limited-levels
7450 (if (ignore-errors (org-back-to-heading t))
7451 (funcall outline-level)))))
7453 (defun org-get-previous-line-level ()
7454 "Return the outline depth of the last headline before the current line.
7455 Returns 0 for the first headline in the buffer, and nil if before the
7456 first headline."
7457 (let ((current-level (org-current-level))
7458 (prev-level (when (> (line-number-at-pos) 1)
7459 (save-excursion
7460 (beginning-of-line 0)
7461 (org-current-level)))))
7462 (cond ((null current-level) nil) ; Before first headline
7463 ((null prev-level) 0) ; At first headline
7464 (prev-level))))
7466 (defun org-reduced-level (l)
7467 "Compute the effective level of a heading.
7468 This takes into account the setting of `org-odd-levels-only'."
7469 (cond
7470 ((zerop l) 0)
7471 (org-odd-levels-only (1+ (floor (/ l 2))))
7472 (t l)))
7474 (defun org-level-increment ()
7475 "Return the number of stars that will be added or removed at a
7476 time to headlines when structure editing, based on the value of
7477 `org-odd-levels-only'."
7478 (if org-odd-levels-only 2 1))
7480 (defun org-get-valid-level (level &optional change)
7481 "Rectify a level change under the influence of `org-odd-levels-only'
7482 LEVEL is a current level, CHANGE is by how much the level should be
7483 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7484 even level numbers will become the next higher odd number."
7485 (if org-odd-levels-only
7486 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7487 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7488 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7489 (max 1 (+ level (or change 0)))))
7491 (if (boundp 'define-obsolete-function-alias)
7492 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7493 (define-obsolete-function-alias 'org-get-legal-level
7494 'org-get-valid-level)
7495 (define-obsolete-function-alias 'org-get-legal-level
7496 'org-get-valid-level "23.1")))
7498 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7499 ;; ̀org-with-limited-levels'
7500 (defun org-promote ()
7501 "Promote the current heading higher up the tree.
7502 If the region is active in `transient-mark-mode', promote all headings
7503 in the region."
7504 (org-back-to-heading t)
7505 (let* ((level (save-match-data (funcall outline-level)))
7506 (after-change-functions (remove 'flyspell-after-change-function
7507 after-change-functions))
7508 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7509 (diff (abs (- level (length up-head) -1))))
7510 (cond ((and (= level 1) org-called-with-limited-levels
7511 org-allow-promoting-top-level-subtree)
7512 (replace-match "# " nil t))
7513 ((= level 1)
7514 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7515 (t (replace-match up-head nil t)))
7516 ;; Fixup tag positioning
7517 (unless (= level 1)
7518 (and org-auto-align-tags (org-set-tags nil t))
7519 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7520 (run-hooks 'org-after-promote-entry-hook)))
7522 (defun org-demote ()
7523 "Demote the current heading lower down the tree.
7524 If the region is active in `transient-mark-mode', demote all headings
7525 in the region."
7526 (org-back-to-heading t)
7527 (let* ((level (save-match-data (funcall outline-level)))
7528 (after-change-functions (remove 'flyspell-after-change-function
7529 after-change-functions))
7530 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7531 (diff (abs (- level (length down-head) -1))))
7532 (replace-match down-head nil t)
7533 ;; Fixup tag positioning
7534 (and org-auto-align-tags (org-set-tags nil t))
7535 (if org-adapt-indentation (org-fixup-indentation diff))
7536 (run-hooks 'org-after-demote-entry-hook)))
7538 (defun org-cycle-level ()
7539 "Cycle the level of an empty headline through possible states.
7540 This goes first to child, then to parent, level, then up the hierarchy.
7541 After top level, it switches back to sibling level."
7542 (interactive)
7543 (let ((org-adapt-indentation nil))
7544 (when (org-point-at-end-of-empty-headline)
7545 (setq this-command 'org-cycle-level) ; Only needed for caching
7546 (let ((cur-level (org-current-level))
7547 (prev-level (org-get-previous-line-level)))
7548 (cond
7549 ;; If first headline in file, promote to top-level.
7550 ((= prev-level 0)
7551 (loop repeat (/ (- cur-level 1) (org-level-increment))
7552 do (org-do-promote)))
7553 ;; If same level as prev, demote one.
7554 ((= prev-level cur-level)
7555 (org-do-demote))
7556 ;; If parent is top-level, promote to top level if not already.
7557 ((= prev-level 1)
7558 (loop repeat (/ (- cur-level 1) (org-level-increment))
7559 do (org-do-promote)))
7560 ;; If top-level, return to prev-level.
7561 ((= cur-level 1)
7562 (loop repeat (/ (- prev-level 1) (org-level-increment))
7563 do (org-do-demote)))
7564 ;; If less than prev-level, promote one.
7565 ((< cur-level prev-level)
7566 (org-do-promote))
7567 ;; If deeper than prev-level, promote until higher than
7568 ;; prev-level.
7569 ((> cur-level prev-level)
7570 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7571 do (org-do-promote))))
7572 t))))
7574 (defun org-map-tree (fun)
7575 "Call FUN for every heading underneath the current one."
7576 (org-back-to-heading)
7577 (let ((level (funcall outline-level)))
7578 (save-excursion
7579 (funcall fun)
7580 (while (and (progn
7581 (outline-next-heading)
7582 (> (funcall outline-level) level))
7583 (not (eobp)))
7584 (funcall fun)))))
7586 (defun org-map-region (fun beg end)
7587 "Call FUN for every heading between BEG and END."
7588 (let ((org-ignore-region t))
7589 (save-excursion
7590 (setq end (copy-marker end))
7591 (goto-char beg)
7592 (if (and (re-search-forward org-outline-regexp-bol nil t)
7593 (< (point) end))
7594 (funcall fun))
7595 (while (and (progn
7596 (outline-next-heading)
7597 (< (point) end))
7598 (not (eobp)))
7599 (funcall fun)))))
7601 (defvar org-property-end-re) ; silence byte-compiler
7602 (defun org-fixup-indentation (diff)
7603 "Change the indentation in the current entry by DIFF.
7604 However, if any line in the current entry has no indentation, or if it
7605 would end up with no indentation after the change, nothing at all is done."
7606 (save-excursion
7607 (let ((end (save-excursion (outline-next-heading)
7608 (point-marker)))
7609 (prohibit (if (> diff 0)
7610 "^\\S-"
7611 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7612 col)
7613 (unless (save-excursion (end-of-line 1)
7614 (re-search-forward prohibit end t))
7615 (while (and (< (point) end)
7616 (re-search-forward "^[ \t]+" end t))
7617 (goto-char (match-end 0))
7618 (setq col (current-column))
7619 (if (< diff 0) (replace-match ""))
7620 (org-indent-to-column (+ diff col))))
7621 (move-marker end nil))))
7623 (defun org-convert-to-odd-levels ()
7624 "Convert an org-mode file with all levels allowed to one with odd levels.
7625 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7626 level 5 etc."
7627 (interactive)
7628 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7629 (let ((outline-level 'org-outline-level)
7630 (org-odd-levels-only nil) n)
7631 (save-excursion
7632 (goto-char (point-min))
7633 (while (re-search-forward "^\\*\\*+ " nil t)
7634 (setq n (- (length (match-string 0)) 2))
7635 (while (>= (setq n (1- n)) 0)
7636 (org-demote))
7637 (end-of-line 1))))))
7639 (defun org-convert-to-oddeven-levels ()
7640 "Convert an org-mode file with only odd levels to one with odd/even levels.
7641 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7642 file contains a section with an even level, conversion would
7643 destroy the structure of the file. An error is signaled in this
7644 case."
7645 (interactive)
7646 (goto-char (point-min))
7647 ;; First check if there are no even levels
7648 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7649 (org-show-context t)
7650 (error "Not all levels are odd in this file. Conversion not possible"))
7651 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7652 (let ((outline-regexp org-outline-regexp)
7653 (outline-level 'org-outline-level)
7654 (org-odd-levels-only nil) n)
7655 (save-excursion
7656 (goto-char (point-min))
7657 (while (re-search-forward "^\\*\\*+ " nil t)
7658 (setq n (/ (1- (length (match-string 0))) 2))
7659 (while (>= (setq n (1- n)) 0)
7660 (org-promote))
7661 (end-of-line 1))))))
7663 (defun org-tr-level (n)
7664 "Make N odd if required."
7665 (if org-odd-levels-only (1+ (/ n 2)) n))
7667 ;;; Vertical tree motion, cutting and pasting of subtrees
7669 (defun org-move-subtree-up (&optional arg)
7670 "Move the current subtree up past ARG headlines of the same level."
7671 (interactive "p")
7672 (org-move-subtree-down (- (prefix-numeric-value arg))))
7674 (defun org-move-subtree-down (&optional arg)
7675 "Move the current subtree down past ARG headlines of the same level."
7676 (interactive "p")
7677 (setq arg (prefix-numeric-value arg))
7678 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7679 'org-get-last-sibling))
7680 (ins-point (make-marker))
7681 (cnt (abs arg))
7682 (col (current-column))
7683 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7684 ;; Select the tree
7685 (org-back-to-heading)
7686 (setq beg0 (point))
7687 (save-excursion
7688 (setq ne-beg (org-back-over-empty-lines))
7689 (setq beg (point)))
7690 (save-match-data
7691 (save-excursion (outline-end-of-heading)
7692 (setq folded (outline-invisible-p)))
7693 (outline-end-of-subtree))
7694 (outline-next-heading)
7695 (setq ne-end (org-back-over-empty-lines))
7696 (setq end (point))
7697 (goto-char beg0)
7698 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7699 ;; include less whitespace
7700 (save-excursion
7701 (goto-char beg)
7702 (forward-line (- ne-beg ne-end))
7703 (setq beg (point))))
7704 ;; Find insertion point, with error handling
7705 (while (> cnt 0)
7706 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7707 (progn (goto-char beg0)
7708 (error "Cannot move past superior level or buffer limit")))
7709 (setq cnt (1- cnt)))
7710 (if (> arg 0)
7711 ;; Moving forward - still need to move over subtree
7712 (progn (org-end-of-subtree t t)
7713 (save-excursion
7714 (org-back-over-empty-lines)
7715 (or (bolp) (newline)))))
7716 (setq ne-ins (org-back-over-empty-lines))
7717 (move-marker ins-point (point))
7718 (setq txt (buffer-substring beg end))
7719 (org-save-markers-in-region beg end)
7720 (delete-region beg end)
7721 (org-remove-empty-overlays-at beg)
7722 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7723 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7724 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7725 (let ((bbb (point)))
7726 (insert-before-markers txt)
7727 (org-reinstall-markers-in-region bbb)
7728 (move-marker ins-point bbb))
7729 (or (bolp) (insert "\n"))
7730 (setq ins-end (point))
7731 (goto-char ins-point)
7732 (org-skip-whitespace)
7733 (when (and (< arg 0)
7734 (org-first-sibling-p)
7735 (> ne-ins ne-beg))
7736 ;; Move whitespace back to beginning
7737 (save-excursion
7738 (goto-char ins-end)
7739 (let ((kill-whole-line t))
7740 (kill-line (- ne-ins ne-beg)) (point)))
7741 (insert (make-string (- ne-ins ne-beg) ?\n)))
7742 (move-marker ins-point nil)
7743 (if folded
7744 (hide-subtree)
7745 (org-show-entry)
7746 (show-children)
7747 (org-cycle-hide-drawers 'children))
7748 (org-clean-visibility-after-subtree-move)
7749 ;; move back to the initial column we were at
7750 (move-to-column col)))
7752 (defvar org-subtree-clip ""
7753 "Clipboard for cut and paste of subtrees.
7754 This is actually only a copy of the kill, because we use the normal kill
7755 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7757 (defvar org-subtree-clip-folded nil
7758 "Was the last copied subtree folded?
7759 This is used to fold the tree back after pasting.")
7761 (defun org-cut-subtree (&optional n)
7762 "Cut the current subtree into the clipboard.
7763 With prefix arg N, cut this many sequential subtrees.
7764 This is a short-hand for marking the subtree and then cutting it."
7765 (interactive "p")
7766 (org-copy-subtree n 'cut))
7768 (defun org-copy-subtree (&optional n cut force-store-markers)
7769 "Cut the current subtree into the clipboard.
7770 With prefix arg N, cut this many sequential subtrees.
7771 This is a short-hand for marking the subtree and then copying it.
7772 If CUT is non-nil, actually cut the subtree.
7773 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7774 of some markers in the region, even if CUT is non-nil. This is
7775 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7776 (interactive "p")
7777 (let (beg end folded (beg0 (point)))
7778 (if (org-called-interactively-p 'any)
7779 (org-back-to-heading nil) ; take what looks like a subtree
7780 (org-back-to-heading t)) ; take what is really there
7781 (org-back-over-empty-lines)
7782 (setq beg (point))
7783 (skip-chars-forward " \t\r\n")
7784 (save-match-data
7785 (save-excursion (outline-end-of-heading)
7786 (setq folded (outline-invisible-p)))
7787 (condition-case nil
7788 (org-forward-same-level (1- n) t)
7789 (error nil))
7790 (org-end-of-subtree t t))
7791 (org-back-over-empty-lines)
7792 (setq end (point))
7793 (goto-char beg0)
7794 (when (> end beg)
7795 (setq org-subtree-clip-folded folded)
7796 (when (or cut force-store-markers)
7797 (org-save-markers-in-region beg end))
7798 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7799 (setq org-subtree-clip (current-kill 0))
7800 (message "%s: Subtree(s) with %d characters"
7801 (if cut "Cut" "Copied")
7802 (length org-subtree-clip)))))
7804 (defun org-paste-subtree (&optional level tree for-yank)
7805 "Paste the clipboard as a subtree, with modification of headline level.
7806 The entire subtree is promoted or demoted in order to match a new headline
7807 level.
7809 If the cursor is at the beginning of a headline, the same level as
7810 that headline is used to paste the tree
7812 If not, the new level is derived from the *visible* headings
7813 before and after the insertion point, and taken to be the inferior headline
7814 level of the two. So if the previous visible heading is level 3 and the
7815 next is level 4 (or vice versa), level 4 will be used for insertion.
7816 This makes sure that the subtree remains an independent subtree and does
7817 not swallow low level entries.
7819 You can also force a different level, either by using a numeric prefix
7820 argument, or by inserting the heading marker by hand. For example, if the
7821 cursor is after \"*****\", then the tree will be shifted to level 5.
7823 If optional TREE is given, use this text instead of the kill ring.
7825 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7826 move back over whitespace before inserting, and move point to the end of
7827 the inserted text when done."
7828 (interactive "P")
7829 (setq tree (or tree (and kill-ring (current-kill 0))))
7830 (unless (org-kill-is-subtree-p tree)
7831 (error "%s"
7832 (substitute-command-keys
7833 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7834 (org-with-limited-levels
7835 (let* ((visp (not (outline-invisible-p)))
7836 (txt tree)
7837 (^re_ "\\(\\*+\\)[ \t]*")
7838 (old-level (if (string-match org-outline-regexp-bol txt)
7839 (- (match-end 0) (match-beginning 0) 1)
7840 -1))
7841 (force-level (cond (level (prefix-numeric-value level))
7842 ((and (looking-at "[ \t]*$")
7843 (string-match
7844 "^\\*+$" (buffer-substring
7845 (point-at-bol) (point))))
7846 (- (match-end 1) (match-beginning 1)))
7847 ((and (bolp)
7848 (looking-at org-outline-regexp))
7849 (- (match-end 0) (point) 1))
7850 (t nil)))
7851 (previous-level (save-excursion
7852 (condition-case nil
7853 (progn
7854 (outline-previous-visible-heading 1)
7855 (if (looking-at ^re_)
7856 (- (match-end 0) (match-beginning 0) 1)
7858 (error 1))))
7859 (next-level (save-excursion
7860 (condition-case nil
7861 (progn
7862 (or (looking-at org-outline-regexp)
7863 (outline-next-visible-heading 1))
7864 (if (looking-at ^re_)
7865 (- (match-end 0) (match-beginning 0) 1)
7867 (error 1))))
7868 (new-level (or force-level (max previous-level next-level)))
7869 (shift (if (or (= old-level -1)
7870 (= new-level -1)
7871 (= old-level new-level))
7873 (- new-level old-level)))
7874 (delta (if (> shift 0) -1 1))
7875 (func (if (> shift 0) 'org-demote 'org-promote))
7876 (org-odd-levels-only nil)
7877 beg end newend)
7878 ;; Remove the forced level indicator
7879 (if force-level
7880 (delete-region (point-at-bol) (point)))
7881 ;; Paste
7882 (beginning-of-line (if (bolp) 1 2))
7883 (unless for-yank (org-back-over-empty-lines))
7884 (setq beg (point))
7885 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7886 (insert-before-markers txt)
7887 (unless (string-match "\n\\'" txt) (insert "\n"))
7888 (setq newend (point))
7889 (org-reinstall-markers-in-region beg)
7890 (setq end (point))
7891 (goto-char beg)
7892 (skip-chars-forward " \t\n\r")
7893 (setq beg (point))
7894 (if (and (outline-invisible-p) visp)
7895 (save-excursion (outline-show-heading)))
7896 ;; Shift if necessary
7897 (unless (= shift 0)
7898 (save-restriction
7899 (narrow-to-region beg end)
7900 (while (not (= shift 0))
7901 (org-map-region func (point-min) (point-max))
7902 (setq shift (+ delta shift)))
7903 (goto-char (point-min))
7904 (setq newend (point-max))))
7905 (when (or (org-called-interactively-p 'interactive) for-yank)
7906 (message "Clipboard pasted as level %d subtree" new-level))
7907 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7908 kill-ring
7909 (eq org-subtree-clip (current-kill 0))
7910 org-subtree-clip-folded)
7911 ;; The tree was folded before it was killed/copied
7912 (hide-subtree))
7913 (and for-yank (goto-char newend)))))
7915 (defun org-kill-is-subtree-p (&optional txt)
7916 "Check if the current kill is an outline subtree, or a set of trees.
7917 Returns nil if kill does not start with a headline, or if the first
7918 headline level is not the largest headline level in the tree.
7919 So this will actually accept several entries of equal levels as well,
7920 which is OK for `org-paste-subtree'.
7921 If optional TXT is given, check this string instead of the current kill."
7922 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7923 (re (org-get-limited-outline-regexp))
7924 (^re (concat "^" re))
7925 (start-level (and kill
7926 (string-match
7927 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7928 kill)
7929 (- (match-end 2) (match-beginning 2) 1)))
7930 (start (1+ (or (match-beginning 2) -1))))
7931 (if (not start-level)
7932 (progn
7933 nil) ;; does not even start with a heading
7934 (catch 'exit
7935 (while (setq start (string-match ^re kill (1+ start)))
7936 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7937 (throw 'exit nil)))
7938 t))))
7940 (defvar org-markers-to-move nil
7941 "Markers that should be moved with a cut-and-paste operation.
7942 Those markers are stored together with their positions relative to
7943 the start of the region.")
7945 (defun org-save-markers-in-region (beg end)
7946 "Check markers in region.
7947 If these markers are between BEG and END, record their position relative
7948 to BEG, so that after moving the block of text, we can put the markers back
7949 into place.
7950 This function gets called just before an entry or tree gets cut from the
7951 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7952 called immediately, to move the markers with the entries."
7953 (setq org-markers-to-move nil)
7954 (when (featurep 'org-clock)
7955 (org-clock-save-markers-for-cut-and-paste beg end))
7956 (when (featurep 'org-agenda)
7957 (org-agenda-save-markers-for-cut-and-paste beg end)))
7959 (defun org-check-and-save-marker (marker beg end)
7960 "Check if MARKER is between BEG and END.
7961 If yes, remember the marker and the distance to BEG."
7962 (when (and (marker-buffer marker)
7963 (equal (marker-buffer marker) (current-buffer)))
7964 (if (and (>= marker beg) (< marker end))
7965 (push (cons marker (- marker beg)) org-markers-to-move))))
7967 (defun org-reinstall-markers-in-region (beg)
7968 "Move all remembered markers to their position relative to BEG."
7969 (mapc (lambda (x)
7970 (move-marker (car x) (+ beg (cdr x))))
7971 org-markers-to-move)
7972 (setq org-markers-to-move nil))
7974 (defun org-narrow-to-subtree ()
7975 "Narrow buffer to the current subtree."
7976 (interactive)
7977 (save-excursion
7978 (save-match-data
7979 (org-with-limited-levels
7980 (narrow-to-region
7981 (progn (org-back-to-heading t) (point))
7982 (progn (org-end-of-subtree t t)
7983 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7984 (point)))))))
7986 (defun org-narrow-to-block ()
7987 "Narrow buffer to the current block."
7988 (interactive)
7989 (let* ((case-fold-search t)
7990 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7991 "^[ \t]*#\\+end_.*")))
7992 (if blockp
7993 (narrow-to-region (car blockp) (cdr blockp))
7994 (error "Not in a block"))))
7996 (eval-when-compile
7997 (defvar org-property-drawer-re))
7999 (defvar org-property-start-re) ;; defined below
8000 (defun org-clone-subtree-with-time-shift (n &optional shift)
8001 "Clone the task (subtree) at point N times.
8002 The clones will be inserted as siblings.
8004 In interactive use, the user will be prompted for the number of
8005 clones to be produced, and for a time SHIFT, which may be a
8006 repeater as used in time stamps, for example `+3d'.
8008 When a valid repeater is given and the entry contains any time
8009 stamps, the clones will become a sequence in time, with time
8010 stamps in the subtree shifted for each clone produced. If SHIFT
8011 is nil or the empty string, time stamps will be left alone. The
8012 ID property of the original subtree is removed.
8014 If the original subtree did contain time stamps with a repeater,
8015 the following will happen:
8016 - the repeater will be removed in each clone
8017 - an additional clone will be produced, with the current, unshifted
8018 date(s) in the entry.
8019 - the original entry will be placed *after* all the clones, with
8020 repeater intact.
8021 - the start days in the repeater in the original entry will be shifted
8022 to past the last clone.
8023 In this way you can spell out a number of instances of a repeating task,
8024 and still retain the repeater to cover future instances of the task."
8025 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8026 (let (beg end template task idprop
8027 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8028 (drawer-re org-drawer-regexp))
8029 (if (not (and (integerp n) (> n 0)))
8030 (error "Invalid number of replications %s" n))
8031 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8032 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8033 shift)))
8034 (error "Invalid shift specification %s" shift))
8035 (when doshift
8036 (setq shift-n (string-to-number (match-string 1 shift))
8037 shift-what (cdr (assoc (match-string 2 shift)
8038 '(("d" . day) ("w" . week)
8039 ("m" . month) ("y" . year))))))
8040 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8041 (setq nmin 1 nmax n)
8042 (org-back-to-heading t)
8043 (setq beg (point))
8044 (setq idprop (org-entry-get nil "ID"))
8045 (org-end-of-subtree t t)
8046 (or (bolp) (insert "\n"))
8047 (setq end (point))
8048 (setq template (buffer-substring beg end))
8049 (when (and doshift
8050 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8051 (delete-region beg end)
8052 (setq end beg)
8053 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8054 (goto-char end)
8055 (loop for n from nmin to nmax do
8056 ;; prepare clone
8057 (with-temp-buffer
8058 (insert template)
8059 (org-mode)
8060 (goto-char (point-min))
8061 (org-show-subtree)
8062 (and idprop (if org-clone-delete-id
8063 (org-entry-delete nil "ID")
8064 (org-id-get-create t)))
8065 (unless (= n 0)
8066 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8067 (kill-whole-line))
8068 (goto-char (point-min))
8069 (while (re-search-forward drawer-re nil t)
8070 (mapc (lambda (d)
8071 (org-remove-empty-drawer-at d (point))) org-drawers)))
8072 (goto-char (point-min))
8073 (when doshift
8074 (while (re-search-forward org-ts-regexp-both nil t)
8075 (org-timestamp-change (* n shift-n) shift-what))
8076 (unless (= n n-no-remove)
8077 (goto-char (point-min))
8078 (while (re-search-forward org-ts-regexp nil t)
8079 (save-excursion
8080 (goto-char (match-beginning 0))
8081 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8082 (delete-region (match-beginning 1) (match-end 1)))))))
8083 (setq task (buffer-string)))
8084 (insert task))
8085 (goto-char beg)))
8087 ;;; Outline Sorting
8089 (defun org-sort (with-case)
8090 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8091 Optional argument WITH-CASE means sort case-sensitively."
8092 (interactive "P")
8093 (cond
8094 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8095 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8097 (org-call-with-arg 'org-sort-entries with-case))))
8099 (defun org-sort-remove-invisible (s)
8100 (remove-text-properties 0 (length s) org-rm-props s)
8101 (while (string-match org-bracket-link-regexp s)
8102 (setq s (replace-match (if (match-end 2)
8103 (match-string 3 s)
8104 (match-string 1 s)) t t s)))
8107 (defvar org-priority-regexp) ; defined later in the file
8109 (defvar org-after-sorting-entries-or-items-hook nil
8110 "Hook that is run after a bunch of entries or items have been sorted.
8111 When children are sorted, the cursor is in the parent line when this
8112 hook gets called. When a region or a plain list is sorted, the cursor
8113 will be in the first entry of the sorted region/list.")
8115 (defun org-sort-entries
8116 (&optional with-case sorting-type getkey-func compare-func property)
8117 "Sort entries on a certain level of an outline tree.
8118 If there is an active region, the entries in the region are sorted.
8119 Else, if the cursor is before the first entry, sort the top-level items.
8120 Else, the children of the entry at point are sorted.
8122 Sorting can be alphabetically, numerically, by date/time as given by
8123 a time stamp, by a property or by priority.
8125 The command prompts for the sorting type unless it has been given to the
8126 function through the SORTING-TYPE argument, which needs to be a character,
8127 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8128 precise meaning of each character:
8130 n Numerically, by converting the beginning of the entry/item to a number.
8131 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8132 t By date/time, either the first active time stamp in the entry, or, if
8133 none exist, by the first inactive one.
8134 s By the scheduled date/time.
8135 d By deadline date/time.
8136 c By creation time, which is assumed to be the first inactive time stamp
8137 at the beginning of a line.
8138 p By priority according to the cookie.
8139 r By the value of a property.
8141 Capital letters will reverse the sort order.
8143 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8144 called with point at the beginning of the record. It must return either
8145 a string or a number that should serve as the sorting key for that record.
8147 Comparing entries ignores case by default. However, with an optional argument
8148 WITH-CASE, the sorting considers case as well."
8149 (interactive "P")
8150 (let ((case-func (if with-case 'identity 'downcase))
8151 start beg end stars re re2
8152 txt what tmp)
8153 ;; Find beginning and end of region to sort
8154 (cond
8155 ((org-region-active-p)
8156 ;; we will sort the region
8157 (setq end (region-end)
8158 what "region")
8159 (goto-char (region-beginning))
8160 (if (not (org-at-heading-p)) (outline-next-heading))
8161 (setq start (point)))
8162 ((or (org-at-heading-p)
8163 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8164 ;; we will sort the children of the current headline
8165 (org-back-to-heading)
8166 (setq start (point)
8167 end (progn (org-end-of-subtree t t)
8168 (or (bolp) (insert "\n"))
8169 (org-back-over-empty-lines)
8170 (point))
8171 what "children")
8172 (goto-char start)
8173 (show-subtree)
8174 (outline-next-heading))
8176 ;; we will sort the top-level entries in this file
8177 (goto-char (point-min))
8178 (or (org-at-heading-p) (outline-next-heading))
8179 (setq start (point))
8180 (goto-char (point-max))
8181 (beginning-of-line 1)
8182 (when (looking-at ".*?\\S-")
8183 ;; File ends in a non-white line
8184 (end-of-line 1)
8185 (insert "\n"))
8186 (setq end (point-max))
8187 (setq what "top-level")
8188 (goto-char start)
8189 (show-all)))
8191 (setq beg (point))
8192 (if (>= beg end) (error "Nothing to sort"))
8194 (looking-at "\\(\\*+\\)")
8195 (setq stars (match-string 1)
8196 re (concat "^" (regexp-quote stars) " +")
8197 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8198 txt (buffer-substring beg end))
8199 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8200 (if (and (not (equal stars "*")) (string-match re2 txt))
8201 (error "Region to sort contains a level above the first entry"))
8203 (unless sorting-type
8204 (message
8205 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8206 [t]ime [s]cheduled [d]eadline [c]reated
8207 A/N/T/S/D/C/P/O/F means reversed:"
8208 what)
8209 (setq sorting-type (read-char-exclusive))
8211 (and (= (downcase sorting-type) ?f)
8212 (setq getkey-func
8213 (org-icompleting-read "Sort using function: "
8214 obarray 'fboundp t nil nil))
8215 (setq getkey-func (intern getkey-func)))
8217 (and (= (downcase sorting-type) ?r)
8218 (setq property
8219 (org-icompleting-read "Property: "
8220 (mapcar 'list (org-buffer-property-keys t))
8221 nil t))))
8223 (message "Sorting entries...")
8225 (save-restriction
8226 (narrow-to-region start end)
8227 (let ((dcst (downcase sorting-type))
8228 (case-fold-search nil)
8229 (now (current-time)))
8230 (sort-subr
8231 (/= dcst sorting-type)
8232 ;; This function moves to the beginning character of the "record" to
8233 ;; be sorted.
8234 (lambda nil
8235 (if (re-search-forward re nil t)
8236 (goto-char (match-beginning 0))
8237 (goto-char (point-max))))
8238 ;; This function moves to the last character of the "record" being
8239 ;; sorted.
8240 (lambda nil
8241 (save-match-data
8242 (condition-case nil
8243 (outline-forward-same-level 1)
8244 (error
8245 (goto-char (point-max))))))
8246 ;; This function returns the value that gets sorted against.
8247 (lambda nil
8248 (cond
8249 ((= dcst ?n)
8250 (if (looking-at org-complex-heading-regexp)
8251 (string-to-number (match-string 4))
8252 nil))
8253 ((= dcst ?a)
8254 (if (looking-at org-complex-heading-regexp)
8255 (funcall case-func (match-string 4))
8256 nil))
8257 ((= dcst ?t)
8258 (let ((end (save-excursion (outline-next-heading) (point))))
8259 (if (or (re-search-forward org-ts-regexp end t)
8260 (re-search-forward org-ts-regexp-both end t))
8261 (org-time-string-to-seconds (match-string 0))
8262 (org-float-time now))))
8263 ((= dcst ?c)
8264 (let ((end (save-excursion (outline-next-heading) (point))))
8265 (if (re-search-forward
8266 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8267 end t)
8268 (org-time-string-to-seconds (match-string 0))
8269 (org-float-time now))))
8270 ((= dcst ?s)
8271 (let ((end (save-excursion (outline-next-heading) (point))))
8272 (if (re-search-forward org-scheduled-time-regexp end t)
8273 (org-time-string-to-seconds (match-string 1))
8274 (org-float-time now))))
8275 ((= dcst ?d)
8276 (let ((end (save-excursion (outline-next-heading) (point))))
8277 (if (re-search-forward org-deadline-time-regexp end t)
8278 (org-time-string-to-seconds (match-string 1))
8279 (org-float-time now))))
8280 ((= dcst ?p)
8281 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8282 (string-to-char (match-string 2))
8283 org-default-priority))
8284 ((= dcst ?r)
8285 (or (org-entry-get nil property) ""))
8286 ((= dcst ?o)
8287 (if (looking-at org-complex-heading-regexp)
8288 (- 9999 (length (member (match-string 2)
8289 org-todo-keywords-1)))))
8290 ((= dcst ?f)
8291 (if getkey-func
8292 (progn
8293 (setq tmp (funcall getkey-func))
8294 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8295 tmp)
8296 (error "Invalid key function `%s'" getkey-func)))
8297 (t (error "Invalid sorting type `%c'" sorting-type))))
8299 (cond
8300 ((= dcst ?a) 'string<)
8301 ((= dcst ?f) compare-func)
8302 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8303 (t nil)))))
8304 (run-hooks 'org-after-sorting-entries-or-items-hook)
8305 (message "Sorting entries...done")))
8307 (defun org-do-sort (table what &optional with-case sorting-type)
8308 "Sort TABLE of WHAT according to SORTING-TYPE.
8309 The user will be prompted for the SORTING-TYPE if the call to this
8310 function does not specify it. WHAT is only for the prompt, to indicate
8311 what is being sorted. The sorting key will be extracted from
8312 the car of the elements of the table.
8313 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8314 (unless sorting-type
8315 (message
8316 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8317 what)
8318 (setq sorting-type (read-char-exclusive)))
8319 (let ((dcst (downcase sorting-type))
8320 extractfun comparefun)
8321 ;; Define the appropriate functions
8322 (cond
8323 ((= dcst ?n)
8324 (setq extractfun 'string-to-number
8325 comparefun (if (= dcst sorting-type) '< '>)))
8326 ((= dcst ?a)
8327 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8328 (lambda(x) (downcase (org-sort-remove-invisible x))))
8329 comparefun (if (= dcst sorting-type)
8330 'string<
8331 (lambda (a b) (and (not (string< a b))
8332 (not (string= a b)))))))
8333 ((= dcst ?t)
8334 (setq extractfun
8335 (lambda (x)
8336 (if (or (string-match org-ts-regexp x)
8337 (string-match org-ts-regexp-both x))
8338 (org-float-time
8339 (org-time-string-to-time (match-string 0 x)))
8341 comparefun (if (= dcst sorting-type) '< '>)))
8342 (t (error "Invalid sorting type `%c'" sorting-type)))
8344 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8345 table)
8346 (lambda (a b) (funcall comparefun (car a) (car b))))))
8349 ;;; The orgstruct minor mode
8351 ;; Define a minor mode which can be used in other modes in order to
8352 ;; integrate the org-mode structure editing commands.
8354 ;; This is really a hack, because the org-mode structure commands use
8355 ;; keys which normally belong to the major mode. Here is how it
8356 ;; works: The minor mode defines all the keys necessary to operate the
8357 ;; structure commands, but wraps the commands into a function which
8358 ;; tests if the cursor is currently at a headline or a plain list
8359 ;; item. If that is the case, the structure command is used,
8360 ;; temporarily setting many Org-mode variables like regular
8361 ;; expressions for filling etc. However, when any of those keys is
8362 ;; used at a different location, function uses `key-binding' to look
8363 ;; up if the key has an associated command in another currently active
8364 ;; keymap (minor modes, major mode, global), and executes that
8365 ;; command. There might be problems if any of the keys is otherwise
8366 ;; used as a prefix key.
8368 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8369 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8370 ;; addresses this by checking explicitly for both bindings.
8372 (defvar orgstruct-mode-map (make-sparse-keymap)
8373 "Keymap for the minor `orgstruct-mode'.")
8375 (defvar org-local-vars nil
8376 "List of local variables, for use by `orgstruct-mode'.")
8378 ;;;###autoload
8379 (define-minor-mode orgstruct-mode
8380 "Toggle the minor mode `orgstruct-mode'.
8381 This mode is for using Org-mode structure commands in other
8382 modes. The following keys behave as if Org-mode were active, if
8383 the cursor is on a headline, or on a plain list item (both as
8384 defined by Org-mode).
8386 M-up Move entry/item up
8387 M-down Move entry/item down
8388 M-left Promote
8389 M-right Demote
8390 M-S-up Move entry/item up
8391 M-S-down Move entry/item down
8392 M-S-left Promote subtree
8393 M-S-right Demote subtree
8394 M-q Fill paragraph and items like in Org-mode
8395 C-c ^ Sort entries
8396 C-c - Cycle list bullet
8397 TAB Cycle item visibility
8398 M-RET Insert new heading/item
8399 S-M-RET Insert new TODO heading / Checkbox item
8400 C-c C-c Set tags / toggle checkbox"
8401 nil " OrgStruct" nil
8402 (org-load-modules-maybe)
8403 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8405 ;;;###autoload
8406 (defun turn-on-orgstruct ()
8407 "Unconditionally turn on `orgstruct-mode'."
8408 (orgstruct-mode 1))
8410 (defvar org-fb-vars nil)
8411 (make-variable-buffer-local 'org-fb-vars)
8412 (defun orgstruct++-mode (&optional arg)
8413 "Toggle `orgstruct-mode', the enhanced version of it.
8414 In addition to setting orgstruct-mode, this also exports all
8415 indentation and autofilling variables from org-mode into the
8416 buffer. It will also recognize item context in multiline items."
8417 (interactive "P")
8418 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8419 (if (< arg 1)
8420 (progn (orgstruct-mode -1)
8421 (mapc (lambda(v)
8422 (org-set-local (car v)
8423 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8424 org-fb-vars))
8425 (orgstruct-mode 1)
8426 (setq org-fb-vars nil)
8427 (let (var val)
8428 (mapc
8429 (lambda (x)
8430 (when (string-match
8431 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8432 (symbol-name (car x)))
8433 (setq var (car x) val (nth 1 x))
8434 (push (list var `(quote ,(eval var))) org-fb-vars)
8435 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8436 org-local-vars)
8437 (org-set-local 'orgstruct-is-++ t))))
8439 (defvar orgstruct-is-++ nil
8440 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8441 (make-variable-buffer-local 'orgstruct-is-++)
8443 ;;;###autoload
8444 (defun turn-on-orgstruct++ ()
8445 "Unconditionally turn on `orgstruct++-mode'."
8446 (orgstruct++-mode 1))
8448 (defun orgstruct-error ()
8449 "Error when there is no default binding for a structure key."
8450 (interactive)
8451 (error "This key has no function outside structure elements"))
8453 (defun orgstruct-setup ()
8454 "Setup orgstruct keymaps."
8455 (let ((nfunc 0)
8456 (bindings
8457 (list
8458 '([(meta up)] org-metaup)
8459 '([(meta down)] org-metadown)
8460 '([(meta left)] org-metaleft)
8461 '([(meta right)] org-metaright)
8462 '([(meta shift up)] org-shiftmetaup)
8463 '([(meta shift down)] org-shiftmetadown)
8464 '([(meta shift left)] org-shiftmetaleft)
8465 '([(meta shift right)] org-shiftmetaright)
8466 '([?\e (up)] org-metaup)
8467 '([?\e (down)] org-metadown)
8468 '([?\e (left)] org-metaleft)
8469 '([?\e (right)] org-metaright)
8470 '([?\e (shift up)] org-shiftmetaup)
8471 '([?\e (shift down)] org-shiftmetadown)
8472 '([?\e (shift left)] org-shiftmetaleft)
8473 '([?\e (shift right)] org-shiftmetaright)
8474 '([(shift up)] org-shiftup)
8475 '([(shift down)] org-shiftdown)
8476 '([(shift left)] org-shiftleft)
8477 '([(shift right)] org-shiftright)
8478 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8479 '("\M-q" fill-paragraph)
8480 '("\C-c^" org-sort)
8481 '("\C-c-" org-cycle-list-bullet)))
8482 elt key fun cmd)
8483 (while (setq elt (pop bindings))
8484 (setq nfunc (1+ nfunc))
8485 (setq key (org-key (car elt))
8486 fun (nth 1 elt)
8487 cmd (orgstruct-make-binding fun nfunc key))
8488 (org-defkey orgstruct-mode-map key cmd))
8490 ;; Special treatment needed for TAB and RET
8491 (org-defkey orgstruct-mode-map [(tab)]
8492 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8493 (org-defkey orgstruct-mode-map "\C-i"
8494 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8496 (org-defkey orgstruct-mode-map "\M-\C-m"
8497 (orgstruct-make-binding 'org-insert-heading 105
8498 "\M-\C-m" [(meta return)]))
8499 (org-defkey orgstruct-mode-map [(meta return)]
8500 (orgstruct-make-binding 'org-insert-heading 106
8501 [(meta return)] "\M-\C-m"))
8503 (org-defkey orgstruct-mode-map [(shift meta return)]
8504 (orgstruct-make-binding 'org-insert-todo-heading 107
8505 [(meta return)] "\M-\C-m"))
8507 (org-defkey orgstruct-mode-map "\e\C-m"
8508 (orgstruct-make-binding 'org-insert-heading 108
8509 "\e\C-m" [?\e (return)]))
8510 (org-defkey orgstruct-mode-map [?\e (return)]
8511 (orgstruct-make-binding 'org-insert-heading 109
8512 [?\e (return)] "\e\C-m"))
8513 (org-defkey orgstruct-mode-map [?\e (shift return)]
8514 (orgstruct-make-binding 'org-insert-todo-heading 110
8515 [?\e (return)] "\e\C-m"))
8517 (unless org-local-vars
8518 (setq org-local-vars (org-get-local-variables)))
8522 (defun orgstruct-make-binding (fun n &rest keys)
8523 "Create a function for binding in the structure minor mode.
8524 FUN is the command to call inside a table. N is used to create a unique
8525 command name. KEYS are keys that should be checked in for a command
8526 to execute outside of tables."
8527 (eval
8528 (list 'defun
8529 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8530 '(arg)
8531 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8532 "Outside of structure, run the binding of `"
8533 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8534 "'.")
8535 '(interactive "p")
8536 (list 'if
8537 `(org-context-p 'headline 'item
8538 (and orgstruct-is-++
8539 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8540 'item-body))
8541 (list 'org-run-like-in-org-mode (list 'quote fun))
8542 (list 'let '(orgstruct-mode)
8543 (list 'call-interactively
8544 (append '(or)
8545 (mapcar (lambda (k)
8546 (list 'key-binding k))
8547 keys)
8548 '('orgstruct-error))))))))
8550 (defun org-context-p (&rest contexts)
8551 "Check if local context is any of CONTEXTS.
8552 Possible values in the list of contexts are `table', `headline', and `item'."
8553 (let ((pos (point)))
8554 (goto-char (point-at-bol))
8555 (prog1 (or (and (memq 'table contexts)
8556 (looking-at "[ \t]*|"))
8557 (and (memq 'headline contexts)
8558 (looking-at org-outline-regexp))
8559 (and (memq 'item contexts)
8560 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8561 (and (memq 'item-body contexts)
8562 (org-in-item-p)))
8563 (goto-char pos))))
8565 (defun org-get-local-variables ()
8566 "Return a list of all local variables in an org-mode buffer."
8567 (let (varlist)
8568 (with-current-buffer (get-buffer-create "*Org tmp*")
8569 (erase-buffer)
8570 (org-mode)
8571 (setq varlist (buffer-local-variables)))
8572 (kill-buffer "*Org tmp*")
8573 (delq nil
8574 (mapcar
8575 (lambda (x)
8576 (setq x
8577 (if (symbolp x)
8578 (list x)
8579 (list (car x) (list 'quote (cdr x)))))
8580 (if (string-match
8581 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8582 (symbol-name (car x)))
8583 x nil))
8584 varlist))))
8586 (defun org-clone-local-variables (from-buffer &optional regexp)
8587 "Clone local variables from FROM-BUFFER.
8588 Optional argument REGEXP selects variables to clone."
8589 (mapc
8590 (lambda (pair)
8591 (and (symbolp (car pair))
8592 (or (null regexp)
8593 (string-match regexp (symbol-name (car pair))))
8594 (set (make-local-variable (car pair))
8595 (cdr pair))))
8596 (buffer-local-variables from-buffer)))
8598 ;;;###autoload
8599 (defun org-run-like-in-org-mode (cmd)
8600 "Run a command, pretending that the current buffer is in Org-mode.
8601 This will temporarily bind local variables that are typically bound in
8602 Org-mode to the values they have in Org-mode, and then interactively
8603 call CMD."
8604 (org-load-modules-maybe)
8605 (unless org-local-vars
8606 (setq org-local-vars (org-get-local-variables)))
8607 (eval (list 'let org-local-vars
8608 (list 'call-interactively (list 'quote cmd)))))
8610 ;;;; Archiving
8612 (defun org-get-category (&optional pos force-refresh)
8613 "Get the category applying to position POS."
8614 (save-match-data
8615 (if force-refresh (org-refresh-category-properties))
8616 (let ((pos (or pos (point))))
8617 (or (get-text-property pos 'org-category)
8618 (progn (org-refresh-category-properties)
8619 (get-text-property pos 'org-category))))))
8621 (defun org-refresh-category-properties ()
8622 "Refresh category text properties in the buffer."
8623 (let ((inhibit-read-only t)
8624 (def-cat (cond
8625 ((null org-category)
8626 (if buffer-file-name
8627 (file-name-sans-extension
8628 (file-name-nondirectory buffer-file-name))
8629 "???"))
8630 ((symbolp org-category) (symbol-name org-category))
8631 (t org-category)))
8632 beg end cat pos optionp)
8633 (org-unmodified
8634 (save-excursion
8635 (save-restriction
8636 (widen)
8637 (goto-char (point-min))
8638 (put-text-property (point) (point-max) 'org-category def-cat)
8639 (while (re-search-forward
8640 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8641 (setq pos (match-end 0)
8642 optionp (equal (char-after (match-beginning 0)) ?#)
8643 cat (org-trim (match-string 2)))
8644 (if optionp
8645 (setq beg (point-at-bol) end (point-max))
8646 (org-back-to-heading t)
8647 (setq beg (point) end (org-end-of-subtree t t)))
8648 (put-text-property beg end 'org-category cat)
8649 (put-text-property beg end 'org-category-position beg)
8650 (goto-char pos)))))))
8653 ;;;; Link Stuff
8655 ;;; Link abbreviations
8657 (defun org-link-expand-abbrev (link)
8658 "Apply replacements as defined in `org-link-abbrev-alist'."
8659 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8660 (let* ((key (match-string 1 link))
8661 (as (or (assoc key org-link-abbrev-alist-local)
8662 (assoc key org-link-abbrev-alist)))
8663 (tag (and (match-end 2) (match-string 3 link)))
8664 rpl)
8665 (if (not as)
8666 link
8667 (setq rpl (cdr as))
8668 (cond
8669 ((symbolp rpl) (funcall rpl tag))
8670 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8671 ((string-match "%h" rpl)
8672 (replace-match (url-hexify-string (or tag "")) t t rpl))
8673 (t (concat rpl tag)))))
8674 link))
8676 ;;; Storing and inserting links
8678 (defvar org-insert-link-history nil
8679 "Minibuffer history for links inserted with `org-insert-link'.")
8681 (defvar org-stored-links nil
8682 "Contains the links stored with `org-store-link'.")
8684 (defvar org-store-link-plist nil
8685 "Plist with info about the most recently link created with `org-store-link'.")
8687 (defvar org-link-protocols nil
8688 "Link protocols added to Org-mode using `org-add-link-type'.")
8690 (defvar org-store-link-functions nil
8691 "List of functions that are called to create and store a link.
8692 Each function will be called in turn until one returns a non-nil
8693 value. Each function should check if it is responsible for creating
8694 this link (for example by looking at the major mode).
8695 If not, it must exit and return nil.
8696 If yes, it should return a non-nil value after a calling
8697 `org-store-link-props' with a list of properties and values.
8698 Special properties are:
8700 :type The link prefix, like \"http\". This must be given.
8701 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8702 This is obligatory as well.
8703 :description Optional default description for the second pair
8704 of brackets in an Org-mode link. The user can still change
8705 this when inserting this link into an Org-mode buffer.
8707 In addition to these, any additional properties can be specified
8708 and then used in remember templates.")
8710 (defun org-add-link-type (type &optional follow export)
8711 "Add TYPE to the list of `org-link-types'.
8712 Re-compute all regular expressions depending on `org-link-types'
8714 FOLLOW and EXPORT are two functions.
8716 FOLLOW should take the link path as the single argument and do whatever
8717 is necessary to follow the link, for example find a file or display
8718 a mail message.
8720 EXPORT should format the link path for export to one of the export formats.
8721 It should be a function accepting three arguments:
8723 path the path of the link, the text after the prefix (like \"http:\")
8724 desc the description of the link, if any, or a description added by
8725 org-export-normalize-links if there is none
8726 format the export format, a symbol like `html' or `latex' or `ascii'..
8728 The function may use the FORMAT information to return different values
8729 depending on the format. The return value will be put literally into
8730 the exported file. If the return value is nil, this means Org should
8731 do what it normally does with links which do not have EXPORT defined.
8733 Org-mode has a built-in default for exporting links. If you are happy with
8734 this default, there is no need to define an export function for the link
8735 type. For a simple example of an export function, see `org-bbdb.el'."
8736 (add-to-list 'org-link-types type t)
8737 (org-make-link-regexps)
8738 (if (assoc type org-link-protocols)
8739 (setcdr (assoc type org-link-protocols) (list follow export))
8740 (push (list type follow export) org-link-protocols)))
8742 (defvar org-agenda-buffer-name)
8744 ;;;###autoload
8745 (defun org-store-link (arg)
8746 "\\<org-mode-map>Store an org-link to the current location.
8747 This link is added to `org-stored-links' and can later be inserted
8748 into an org-buffer with \\[org-insert-link].
8750 For some link types, a prefix arg is interpreted:
8751 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8752 For file links, arg negates `org-context-in-file-links'."
8753 (interactive "P")
8754 (org-load-modules-maybe)
8755 (setq org-store-link-plist nil) ; reset
8756 (org-with-limited-levels
8757 (let (link cpltxt desc description search txt custom-id agenda-link)
8758 (cond
8760 ((run-hook-with-args-until-success 'org-store-link-functions)
8761 (setq link (plist-get org-store-link-plist :link)
8762 desc (or (plist-get org-store-link-plist :description) link)))
8764 ((org-src-edit-buffer-p)
8765 (let (label gc)
8766 (while (or (not label)
8767 (save-excursion
8768 (save-restriction
8769 (widen)
8770 (goto-char (point-min))
8771 (re-search-forward
8772 (regexp-quote (format org-coderef-label-format label))
8773 nil t))))
8774 (when label (message "Label exists already") (sit-for 2))
8775 (setq label (read-string "Code line label: " label)))
8776 (end-of-line 1)
8777 (setq link (format org-coderef-label-format label))
8778 (setq gc (- 79 (length link)))
8779 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8780 (insert link)
8781 (setq link (concat "(" label ")") desc nil)))
8783 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8784 ;; We are in the agenda, link to referenced location
8785 (let ((m (or (get-text-property (point) 'org-hd-marker)
8786 (get-text-property (point) 'org-marker))))
8787 (when m
8788 (org-with-point-at m
8789 (setq agenda-link
8790 (if (org-called-interactively-p 'any)
8791 (call-interactively 'org-store-link)
8792 (org-store-link nil)))))))
8794 ((eq major-mode 'calendar-mode)
8795 (let ((cd (calendar-cursor-to-date)))
8796 (setq link
8797 (format-time-string
8798 (car org-time-stamp-formats)
8799 (apply 'encode-time
8800 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8801 nil nil nil))))
8802 (org-store-link-props :type "calendar" :date cd)))
8804 ((eq major-mode 'w3-mode)
8805 (setq cpltxt (if (and (buffer-name)
8806 (not (string-match "Untitled" (buffer-name))))
8807 (buffer-name)
8808 (url-view-url t))
8809 link (org-make-link (url-view-url t)))
8810 (org-store-link-props :type "w3" :url (url-view-url t)))
8812 ((eq major-mode 'w3m-mode)
8813 (setq cpltxt (or w3m-current-title w3m-current-url)
8814 link (org-make-link w3m-current-url))
8815 (org-store-link-props :type "w3m" :url (url-view-url t)))
8817 ((setq search (run-hook-with-args-until-success
8818 'org-create-file-search-functions))
8819 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8820 "::" search))
8821 (setq cpltxt (or description link)))
8823 ((eq major-mode 'image-mode)
8824 (setq cpltxt (concat "file:"
8825 (abbreviate-file-name buffer-file-name))
8826 link (org-make-link cpltxt))
8827 (org-store-link-props :type "image" :file buffer-file-name))
8829 ((eq major-mode 'dired-mode)
8830 ;; link to the file in the current line
8831 (let ((file (dired-get-filename nil t)))
8832 (setq file (if file
8833 (abbreviate-file-name
8834 (expand-file-name (dired-get-filename nil t)))
8835 ;; otherwise, no file so use current directory.
8836 default-directory))
8837 (setq cpltxt (concat "file:" file)
8838 link (org-make-link cpltxt))))
8840 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8841 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8842 (cond
8843 ((org-in-regexp "<<\\(.*?\\)>>")
8844 (setq cpltxt
8845 (concat "file:"
8846 (abbreviate-file-name
8847 (buffer-file-name (buffer-base-buffer)))
8848 "::" (match-string 1))
8849 link (org-make-link cpltxt)))
8850 ((and (featurep 'org-id)
8851 (or (eq org-link-to-org-use-id t)
8852 (and (eq org-link-to-org-use-id 'create-if-interactive)
8853 (org-called-interactively-p 'any))
8854 (and (eq org-link-to-org-use-id
8855 'create-if-interactive-and-no-custom-id)
8856 (org-called-interactively-p 'any)
8857 (not custom-id))
8858 (and org-link-to-org-use-id
8859 (org-entry-get nil "ID"))))
8860 ;; We can make a link using the ID.
8861 (setq link (condition-case nil
8862 (prog1 (org-id-store-link)
8863 (setq desc (plist-get org-store-link-plist
8864 :description)))
8865 (error
8866 ;; probably before first headline, link to file only
8867 (concat "file:"
8868 (abbreviate-file-name
8869 (buffer-file-name (buffer-base-buffer))))))))
8871 ;; Just link to current headline
8872 (setq cpltxt (concat "file:"
8873 (abbreviate-file-name
8874 (buffer-file-name (buffer-base-buffer)))))
8875 ;; Add a context search string
8876 (when (org-xor org-context-in-file-links arg)
8877 (setq txt (cond
8878 ((org-at-heading-p) nil)
8879 ((org-region-active-p)
8880 (buffer-substring (region-beginning) (region-end)))
8881 (t nil)))
8882 (when (or (null txt) (string-match "\\S-" txt))
8883 (setq cpltxt
8884 (concat cpltxt "::"
8885 (condition-case nil
8886 (org-make-org-heading-search-string txt)
8887 (error "")))
8888 desc (or (nth 4 (ignore-errors
8889 (org-heading-components))) "NONE"))))
8890 (if (string-match "::\\'" cpltxt)
8891 (setq cpltxt (substring cpltxt 0 -2)))
8892 (setq link (org-make-link cpltxt)))))
8894 ((buffer-file-name (buffer-base-buffer))
8895 ;; Just link to this file here.
8896 (setq cpltxt (concat "file:"
8897 (abbreviate-file-name
8898 (buffer-file-name (buffer-base-buffer)))))
8899 ;; Add a context string
8900 (when (org-xor org-context-in-file-links arg)
8901 (setq txt (if (org-region-active-p)
8902 (buffer-substring (region-beginning) (region-end))
8903 (buffer-substring (point-at-bol) (point-at-eol))))
8904 ;; Only use search option if there is some text.
8905 (when (string-match "\\S-" txt)
8906 (setq cpltxt
8907 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8908 desc "NONE")))
8909 (setq link (org-make-link cpltxt)))
8911 ((org-called-interactively-p 'interactive)
8912 (error "Cannot link to a buffer which is not visiting a file"))
8914 (t (setq link nil)))
8916 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8917 (setq link (or link cpltxt)
8918 desc (or desc cpltxt))
8919 (if (equal desc "NONE") (setq desc nil))
8921 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8922 (progn
8923 (setq org-stored-links
8924 (cons (list link desc) org-stored-links))
8925 (message "Stored: %s" (or desc link))
8926 (when custom-id
8927 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8928 "::#" custom-id))
8929 (setq org-stored-links
8930 (cons (list link desc) org-stored-links))))
8931 (or agenda-link (and link (org-make-link-string link desc)))))))
8933 (defun org-store-link-props (&rest plist)
8934 "Store link properties, extract names and addresses."
8935 (let (x adr)
8936 (when (setq x (plist-get plist :from))
8937 (setq adr (mail-extract-address-components x))
8938 (setq plist (plist-put plist :fromname (car adr)))
8939 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8940 (when (setq x (plist-get plist :to))
8941 (setq adr (mail-extract-address-components x))
8942 (setq plist (plist-put plist :toname (car adr)))
8943 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8944 (let ((from (plist-get plist :from))
8945 (to (plist-get plist :to)))
8946 (when (and from to org-from-is-user-regexp)
8947 (setq plist
8948 (plist-put plist :fromto
8949 (if (string-match org-from-is-user-regexp from)
8950 (concat "to %t")
8951 (concat "from %f"))))))
8952 (setq org-store-link-plist plist))
8954 (defun org-add-link-props (&rest plist)
8955 "Add these properties to the link property list."
8956 (let (key value)
8957 (while plist
8958 (setq key (pop plist) value (pop plist))
8959 (setq org-store-link-plist
8960 (plist-put org-store-link-plist key value)))))
8962 (defun org-email-link-description (&optional fmt)
8963 "Return the description part of an email link.
8964 This takes information from `org-store-link-plist' and formats it
8965 according to FMT (default from `org-email-link-description-format')."
8966 (setq fmt (or fmt org-email-link-description-format))
8967 (let* ((p org-store-link-plist)
8968 (to (plist-get p :toaddress))
8969 (from (plist-get p :fromaddress))
8970 (table
8971 (list
8972 (cons "%c" (plist-get p :fromto))
8973 (cons "%F" (plist-get p :from))
8974 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8975 (cons "%T" (plist-get p :to))
8976 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8977 (cons "%s" (plist-get p :subject))
8978 (cons "%d" (plist-get p :date))
8979 (cons "%m" (plist-get p :message-id)))))
8980 (when (string-match "%c" fmt)
8981 ;; Check if the user wrote this message
8982 (if (and org-from-is-user-regexp from to
8983 (save-match-data (string-match org-from-is-user-regexp from)))
8984 (setq fmt (replace-match "to %t" t t fmt))
8985 (setq fmt (replace-match "from %f" t t fmt))))
8986 (org-replace-escapes fmt table)))
8988 (defun org-make-org-heading-search-string (&optional string heading)
8989 "Make search string for STRING or current headline."
8990 (interactive)
8991 (let ((s (or string (org-get-heading)))
8992 (lines org-context-in-file-links))
8993 (unless (and string (not heading))
8994 ;; We are using a headline, clean up garbage in there.
8995 (if (string-match org-todo-regexp s)
8996 (setq s (replace-match "" t t s)))
8997 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8998 (setq s (replace-match "" t t s)))
8999 (setq s (org-trim s))
9000 (if (string-match (concat "^\\(" org-quote-string "\\|"
9001 org-comment-string "\\)") s)
9002 (setq s (replace-match "" t t s)))
9003 (while (string-match org-ts-regexp s)
9004 (setq s (replace-match "" t t s))))
9005 (or string (setq s (concat "*" s))) ; Add * for headlines
9006 (when (and string (integerp lines) (> lines 0))
9007 (let ((slines (org-split-string s "\n")))
9008 (when (< lines (length slines))
9009 (setq s (mapconcat
9010 'identity
9011 (reverse (nthcdr (- (length slines) lines)
9012 (reverse slines))) "\n")))))
9013 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9015 (defun org-make-link (&rest strings)
9016 "Concatenate STRINGS."
9017 (apply 'concat strings))
9019 (defun org-make-link-string (link &optional description)
9020 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9021 (unless (string-match "\\S-" link)
9022 (error "Empty link"))
9023 (when (and description
9024 (stringp description)
9025 (not (string-match "\\S-" description)))
9026 (setq description nil))
9027 (when (stringp description)
9028 ;; Remove brackets from the description, they are fatal.
9029 (while (string-match "\\[" description)
9030 (setq description (replace-match "{" t t description)))
9031 (while (string-match "\\]" description)
9032 (setq description (replace-match "}" t t description))))
9033 (when (equal link description)
9034 ;; No description needed, it is identical
9035 (setq description nil))
9036 (when (and (not description)
9037 (not (string-match (org-image-file-name-regexp) link))
9038 (not (equal link (org-link-escape link))))
9039 (setq description (org-extract-attributes link)))
9040 (setq link
9041 (cond ((string-match (org-image-file-name-regexp) link) link)
9042 ((string-match org-link-types-re link)
9043 (concat (match-string 1 link)
9044 (org-link-escape (substring link (match-end 1)))))
9045 (t (org-link-escape link))))
9046 (concat "[[" link "]"
9047 (if description (concat "[" description "]") "")
9048 "]"))
9050 (defconst org-link-escape-chars
9051 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9052 "List of characters that should be escaped in link.
9053 This is the list that is used for internal purposes.")
9055 (defvar org-url-encoding-use-url-hexify nil)
9057 (defconst org-link-escape-chars-browser
9058 '(?\ )
9059 "List of escapes for characters that are problematic in links.
9060 This is the list that is used before handing over to the browser.")
9062 (defun org-link-escape (text &optional table merge)
9063 "Return percent escaped representation of TEXT.
9064 TEXT is a string with the text to escape.
9065 Optional argument TABLE is a list with characters that should be
9066 escaped. When nil, `org-link-escape-chars' is used.
9067 If optional argument MERGE is set, merge TABLE into
9068 `org-link-escape-chars'."
9069 (if (and org-url-encoding-use-url-hexify (not table))
9070 (url-hexify-string text)
9071 (cond
9072 ((and table merge)
9073 (mapc (lambda (defchr)
9074 (unless (member defchr table)
9075 (setq table (cons defchr table)))) org-link-escape-chars))
9076 ((null table)
9077 (setq table org-link-escape-chars)))
9078 (mapconcat
9079 (lambda (char)
9080 (if (or (member char table)
9081 (< char 32) (= char 37) (> char 126))
9082 (mapconcat (lambda (sequence-element)
9083 (format "%%%.2X" sequence-element))
9084 (or (encode-coding-char char 'utf-8)
9085 (error "Unable to percent escape character: %s"
9086 (char-to-string char))) "")
9087 (char-to-string char))) text "")))
9089 (defun org-link-unescape (str)
9090 "Unhex hexified Unicode strings as returned from the JavaScript function
9091 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9092 (unless (and (null str) (string= "" str))
9093 (let ((pos 0) (case-fold-search t) unhexed)
9094 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9095 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9096 (setq str (replace-match unhexed t t str))
9097 (setq pos (+ pos (length unhexed))))))
9098 str)
9100 (defun org-link-unescape-compound (hex)
9101 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9102 Note: this function also decodes single byte encodings like
9103 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9104 (save-match-data
9105 (let* ((bytes (cdr (split-string hex "%")))
9106 (ret "")
9107 (eat 0)
9108 (sum 0))
9109 (while bytes
9110 (let* ((val (string-to-number (pop bytes) 16))
9111 (shift-xor
9112 (if (= 0 eat)
9113 (cond
9114 ((>= val 252) (cons 6 252))
9115 ((>= val 248) (cons 5 248))
9116 ((>= val 240) (cons 4 240))
9117 ((>= val 224) (cons 3 224))
9118 ((>= val 192) (cons 2 192))
9119 (t (cons 0 0)))
9120 (cons 6 128))))
9121 (if (>= val 192) (setq eat (car shift-xor)))
9122 (setq val (logxor val (cdr shift-xor)))
9123 (setq sum (+ (lsh sum (car shift-xor)) val))
9124 (if (> eat 0) (setq eat (- eat 1)))
9125 (cond
9126 ((= 0 eat) ;multi byte
9127 (setq ret (concat ret (org-char-to-string sum)))
9128 (setq sum 0))
9129 ((not bytes) ; single byte(s)
9130 (setq ret (org-link-unescape-single-byte-sequence hex))))
9131 )) ;; end (while bytes
9132 ret )))
9134 (defun org-link-unescape-single-byte-sequence (hex)
9135 "Unhexify hex-encoded single byte character sequences."
9136 (mapconcat (lambda (byte)
9137 (char-to-string (string-to-number byte 16)))
9138 (cdr (split-string hex "%")) ""))
9140 (defun org-xor (a b)
9141 "Exclusive or."
9142 (if a (not b) b))
9144 (defun org-fixup-message-id-for-http (s)
9145 "Replace special characters in a message id, so it can be used in an http query."
9146 (when (string-match "%" s)
9147 (setq s (mapconcat (lambda (c)
9148 (if (eq c ?%)
9149 "%25"
9150 (char-to-string c)))
9151 s "")))
9152 (while (string-match "<" s)
9153 (setq s (replace-match "%3C" t t s)))
9154 (while (string-match ">" s)
9155 (setq s (replace-match "%3E" t t s)))
9156 (while (string-match "@" s)
9157 (setq s (replace-match "%40" t t s)))
9160 (defun org-link-prettify (link)
9161 "Return a human-readable representation of LINK.
9162 The car of LINK must be a raw link the cdr of LINK must be either
9163 a link description or nil."
9164 (let ((desc (or (cadr link) "<no description>")))
9165 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9166 "[[" (car link) "]]")))
9168 ;;;###autoload
9169 (defun org-insert-link-global ()
9170 "Insert a link like Org-mode does.
9171 This command can be called in any mode to insert a link in Org-mode syntax."
9172 (interactive)
9173 (org-load-modules-maybe)
9174 (org-run-like-in-org-mode 'org-insert-link))
9176 (defun org-insert-link (&optional complete-file link-location default-description)
9177 "Insert a link. At the prompt, enter the link.
9179 Completion can be used to insert any of the link protocol prefixes like
9180 http or ftp in use.
9182 The history can be used to select a link previously stored with
9183 `org-store-link'. When the empty string is entered (i.e. if you just
9184 press RET at the prompt), the link defaults to the most recently
9185 stored link. As SPC triggers completion in the minibuffer, you need to
9186 use M-SPC or C-q SPC to force the insertion of a space character.
9188 You will also be prompted for a description, and if one is given, it will
9189 be displayed in the buffer instead of the link.
9191 If there is already a link at point, this command will allow you to edit link
9192 and description parts.
9194 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9195 be selected using completion. The path to the file will be relative to the
9196 current directory if the file is in the current directory or a subdirectory.
9197 Otherwise, the link will be the absolute path as completed in the minibuffer
9198 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9199 option `org-link-file-path-type'.
9201 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9202 the current directory or below.
9204 With three \\[universal-argument] prefixes, negate the meaning of
9205 `org-keep-stored-link-after-insertion'.
9207 If `org-make-link-description-function' is non-nil, this function will be
9208 called with the link target, and the result will be the default
9209 link description.
9211 If the LINK-LOCATION parameter is non-nil, this value will be
9212 used as the link location instead of reading one interactively.
9214 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9215 be used as the default description."
9216 (interactive "P")
9217 (let* ((wcf (current-window-configuration))
9218 (region (if (org-region-active-p)
9219 (buffer-substring (region-beginning) (region-end))))
9220 (remove (and region (list (region-beginning) (region-end))))
9221 (desc region)
9222 tmphist ; byte-compile incorrectly complains about this
9223 (link link-location)
9224 entry file all-prefixes)
9225 (cond
9226 (link-location) ; specified by arg, just use it.
9227 ((org-in-regexp org-bracket-link-regexp 1)
9228 ;; We do have a link at point, and we are going to edit it.
9229 (setq remove (list (match-beginning 0) (match-end 0)))
9230 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9231 (setq link (read-string "Link: "
9232 (org-link-unescape
9233 (org-match-string-no-properties 1)))))
9234 ((or (org-in-regexp org-angle-link-re)
9235 (org-in-regexp org-plain-link-re))
9236 ;; Convert to bracket link
9237 (setq remove (list (match-beginning 0) (match-end 0))
9238 link (read-string "Link: "
9239 (org-remove-angle-brackets (match-string 0)))))
9240 ((member complete-file '((4) (16)))
9241 ;; Completing read for file names.
9242 (setq link (org-file-complete-link complete-file)))
9244 ;; Read link, with completion for stored links.
9245 (with-output-to-temp-buffer "*Org Links*"
9246 (princ "Insert a link.
9247 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9248 (when org-stored-links
9249 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9250 (princ (mapconcat 'org-link-prettify
9251 (reverse org-stored-links) "\n"))))
9252 (let ((cw (selected-window)))
9253 (select-window (get-buffer-window "*Org Links*" 'visible))
9254 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9255 (unless (pos-visible-in-window-p (point-max))
9256 (org-fit-window-to-buffer))
9257 (and (window-live-p cw) (select-window cw)))
9258 ;; Fake a link history, containing the stored links.
9259 (setq tmphist (append (mapcar 'car org-stored-links)
9260 org-insert-link-history))
9261 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9262 (mapcar 'car org-link-abbrev-alist)
9263 org-link-types))
9264 (unwind-protect
9265 (progn
9266 (setq link
9267 (let ((org-completion-use-ido nil)
9268 (org-completion-use-iswitchb nil))
9269 (org-completing-read
9270 "Link: "
9271 (append
9272 (mapcar (lambda (x) (list (concat x ":")))
9273 all-prefixes)
9274 (mapcar 'car org-stored-links))
9275 nil nil nil
9276 'tmphist
9277 (car (car org-stored-links)))))
9278 (if (not (string-match "\\S-" link))
9279 (error "No link selected"))
9280 (if (or (member link all-prefixes)
9281 (and (equal ":" (substring link -1))
9282 (member (substring link 0 -1) all-prefixes)
9283 (setq link (substring link 0 -1))))
9284 (setq link (org-link-try-special-completion link))))
9285 (set-window-configuration wcf)
9286 (kill-buffer "*Org Links*"))
9287 (setq entry (assoc link org-stored-links))
9288 (or entry (push link org-insert-link-history))
9289 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9290 (not org-keep-stored-link-after-insertion))
9291 (setq org-stored-links (delq (assoc link org-stored-links)
9292 org-stored-links)))
9293 (setq desc (or desc (nth 1 entry)))))
9295 (if (string-match org-plain-link-re link)
9296 ;; URL-like link, normalize the use of angular brackets.
9297 (setq link (org-make-link (org-remove-angle-brackets link))))
9299 ;; Check if we are linking to the current file with a search option
9300 ;; If yes, simplify the link by using only the search option.
9301 (when (and buffer-file-name
9302 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9303 (let* ((path (match-string 1 link))
9304 (case-fold-search nil)
9305 (search (match-string 2 link)))
9306 (save-match-data
9307 (if (equal (file-truename buffer-file-name) (file-truename path))
9308 ;; We are linking to this same file, with a search option
9309 (setq link search)))))
9311 ;; Check if we can/should use a relative path. If yes, simplify the link
9312 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9313 (let* ((type (match-string 1 link))
9314 (path (match-string 2 link))
9315 (origpath path)
9316 (case-fold-search nil))
9317 (cond
9318 ((or (eq org-link-file-path-type 'absolute)
9319 (equal complete-file '(16)))
9320 (setq path (abbreviate-file-name (expand-file-name path))))
9321 ((eq org-link-file-path-type 'noabbrev)
9322 (setq path (expand-file-name path)))
9323 ((eq org-link-file-path-type 'relative)
9324 (setq path (file-relative-name path)))
9326 (save-match-data
9327 (if (string-match (concat "^" (regexp-quote
9328 (expand-file-name
9329 (file-name-as-directory
9330 default-directory))))
9331 (expand-file-name path))
9332 ;; We are linking a file with relative path name.
9333 (setq path (substring (expand-file-name path)
9334 (match-end 0)))
9335 (setq path (abbreviate-file-name (expand-file-name path)))))))
9336 (setq link (concat type path))
9337 (if (equal desc origpath)
9338 (setq desc path))))
9340 (if org-make-link-description-function
9341 (setq desc (funcall org-make-link-description-function link desc))
9342 (if default-description (setq desc default-description)))
9344 (setq desc (read-string "Description: " desc))
9345 (unless (string-match "\\S-" desc) (setq desc nil))
9346 (if remove (apply 'delete-region remove))
9347 (insert (org-make-link-string link desc))))
9349 (defun org-link-try-special-completion (type)
9350 "If there is completion support for link type TYPE, offer it."
9351 (let ((fun (intern (concat "org-" type "-complete-link"))))
9352 (if (functionp fun)
9353 (funcall fun)
9354 (read-string "Link (no completion support): " (concat type ":")))))
9356 (defun org-file-complete-link (&optional arg)
9357 "Create a file link using completion."
9358 (let (file link)
9359 (setq file (read-file-name "File: "))
9360 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9361 (pwd1 (file-name-as-directory (abbreviate-file-name
9362 (expand-file-name ".")))))
9363 (cond
9364 ((equal arg '(16))
9365 (setq link (org-make-link
9366 "file:"
9367 (abbreviate-file-name (expand-file-name file)))))
9368 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9369 (setq link (org-make-link "file:" (match-string 1 file))))
9370 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9371 (expand-file-name file))
9372 (setq link (org-make-link
9373 "file:" (match-string 1 (expand-file-name file)))))
9374 (t (setq link (org-make-link "file:" file)))))
9375 link))
9377 (defun org-completing-read (&rest args)
9378 "Completing-read with SPACE being a normal character."
9379 (let ((enable-recursive-minibuffers t)
9380 (minibuffer-local-completion-map
9381 (copy-keymap minibuffer-local-completion-map)))
9382 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9383 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9384 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9385 (apply 'org-icompleting-read args)))
9387 (defun org-completing-read-no-i (&rest args)
9388 (let (org-completion-use-ido org-completion-use-iswitchb)
9389 (apply 'org-completing-read args)))
9391 (defun org-iswitchb-completing-read (prompt choices &rest args)
9392 "Use iswitch as a completing-read replacement to choose from choices.
9393 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9394 from."
9395 (let* ((iswitchb-use-virtual-buffers nil)
9396 (iswitchb-make-buflist-hook
9397 (lambda ()
9398 (setq iswitchb-temp-buflist choices))))
9399 (iswitchb-read-buffer prompt)))
9401 (defun org-icompleting-read (&rest args)
9402 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9403 (org-without-partial-completion
9404 (if (and org-completion-use-ido
9405 (fboundp 'ido-completing-read)
9406 (boundp 'ido-mode) ido-mode
9407 (listp (second args)))
9408 (let ((ido-enter-matching-directory nil))
9409 (apply 'ido-completing-read (concat (car args))
9410 (if (consp (car (nth 1 args)))
9411 (mapcar 'car (nth 1 args))
9412 (nth 1 args))
9413 (cddr args)))
9414 (if (and org-completion-use-iswitchb
9415 (boundp 'iswitchb-mode) iswitchb-mode
9416 (listp (second args)))
9417 (apply 'org-iswitchb-completing-read (concat (car args))
9418 (if (consp (car (nth 1 args)))
9419 (mapcar 'car (nth 1 args))
9420 (nth 1 args))
9421 (cddr args))
9422 (apply 'completing-read args)))))
9424 (defun org-extract-attributes (s)
9425 "Extract the attributes cookie from a string and set as text property."
9426 (let (a attr (start 0) key value)
9427 (save-match-data
9428 (when (string-match "{{\\([^}]+\\)}}$" s)
9429 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9430 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9431 (setq key (match-string 1 a) value (match-string 2 a)
9432 start (match-end 0)
9433 attr (plist-put attr (intern key) value))))
9434 (org-add-props s nil 'org-attr attr))
9437 (defun org-extract-attributes-from-string (tag)
9438 (let (key value attr)
9439 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9440 (setq key (match-string 1 tag) value (match-string 2 tag)
9441 tag (replace-match "" t t tag)
9442 attr (plist-put attr (intern key) value)))
9443 (cons tag attr)))
9445 (defun org-attributes-to-string (plist)
9446 "Format a property list into an HTML attribute list."
9447 (let ((s "") key value)
9448 (while plist
9449 (setq key (pop plist) value (pop plist))
9450 (and value
9451 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9454 ;;; Opening/following a link
9456 (defvar org-link-search-failed nil)
9458 (defvar org-open-link-functions nil
9459 "Hook for functions finding a plain text link.
9460 These functions must take a single argument, the link content.
9461 They will be called for links that look like [[link text][description]]
9462 when LINK TEXT does not have a protocol like \"http:\" and does not look
9463 like a filename (e.g. \"./blue.png\").
9465 These functions will be called *before* Org attempts to resolve the
9466 link by doing text searches in the current buffer - so if you want a
9467 link \"[[target]]\" to still find \"<<target>>\", your function should
9468 handle this as a special case.
9470 When the function does handle the link, it must return a non-nil value.
9471 If it decides that it is not responsible for this link, it must return
9472 nil to indicate that that Org-mode can continue with other options
9473 like exact and fuzzy text search.")
9475 (defun org-next-link ()
9476 "Move forward to the next link.
9477 If the link is in hidden text, expose it."
9478 (interactive)
9479 (when (and org-link-search-failed (eq this-command last-command))
9480 (goto-char (point-min))
9481 (message "Link search wrapped back to beginning of buffer"))
9482 (setq org-link-search-failed nil)
9483 (let* ((pos (point))
9484 (ct (org-context))
9485 (a (assoc :link ct)))
9486 (if a (goto-char (nth 2 a)))
9487 (if (re-search-forward org-any-link-re nil t)
9488 (progn
9489 (goto-char (match-beginning 0))
9490 (if (outline-invisible-p) (org-show-context)))
9491 (goto-char pos)
9492 (setq org-link-search-failed t)
9493 (error "No further link found"))))
9495 (defun org-previous-link ()
9496 "Move backward to the previous link.
9497 If the link is in hidden text, expose it."
9498 (interactive)
9499 (when (and org-link-search-failed (eq this-command last-command))
9500 (goto-char (point-max))
9501 (message "Link search wrapped back to end of buffer"))
9502 (setq org-link-search-failed nil)
9503 (let* ((pos (point))
9504 (ct (org-context))
9505 (a (assoc :link ct)))
9506 (if a (goto-char (nth 1 a)))
9507 (if (re-search-backward org-any-link-re nil t)
9508 (progn
9509 (goto-char (match-beginning 0))
9510 (if (outline-invisible-p) (org-show-context)))
9511 (goto-char pos)
9512 (setq org-link-search-failed t)
9513 (error "No further link found"))))
9515 (defun org-translate-link (s)
9516 "Translate a link string if a translation function has been defined."
9517 (if (and org-link-translation-function
9518 (fboundp org-link-translation-function)
9519 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9520 (progn
9521 (setq s (funcall org-link-translation-function
9522 (match-string 1 s) (match-string 2 s)))
9523 (concat (car s) ":" (cdr s)))
9526 (defun org-translate-link-from-planner (type path)
9527 "Translate a link from Emacs Planner syntax so that Org can follow it.
9528 This is still an experimental function, your mileage may vary."
9529 (cond
9530 ((member type '("http" "https" "news" "ftp"))
9531 ;; standard Internet links are the same.
9532 nil)
9533 ((and (equal type "irc") (string-match "^//" path))
9534 ;; Planner has two / at the beginning of an irc link, we have 1.
9535 ;; We should have zero, actually....
9536 (setq path (substring path 1)))
9537 ((and (equal type "lisp") (string-match "^/" path))
9538 ;; Planner has a slash, we do not.
9539 (setq type "elisp" path (substring path 1)))
9540 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9541 ;; A typical message link. Planner has the id after the final slash,
9542 ;; we separate it with a hash mark
9543 (setq path (concat (match-string 1 path) "#"
9544 (org-remove-angle-brackets (match-string 2 path)))))
9546 (cons type path))
9548 (defun org-find-file-at-mouse (ev)
9549 "Open file link or URL at mouse."
9550 (interactive "e")
9551 (mouse-set-point ev)
9552 (org-open-at-point 'in-emacs))
9554 (defun org-open-at-mouse (ev)
9555 "Open file link or URL at mouse.
9556 See the docstring of `org-open-file' for details."
9557 (interactive "e")
9558 (mouse-set-point ev)
9559 (if (eq major-mode 'org-agenda-mode)
9560 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9561 (org-open-at-point))
9563 (defvar org-window-config-before-follow-link nil
9564 "The window configuration before following a link.
9565 This is saved in case the need arises to restore it.")
9567 (defvar org-open-link-marker (make-marker)
9568 "Marker pointing to the location where `org-open-at-point; was called.")
9570 ;;;###autoload
9571 (defun org-open-at-point-global ()
9572 "Follow a link like Org-mode does.
9573 This command can be called in any mode to follow a link that has
9574 Org-mode syntax."
9575 (interactive)
9576 (org-run-like-in-org-mode 'org-open-at-point))
9578 ;;;###autoload
9579 (defun org-open-link-from-string (s &optional arg reference-buffer)
9580 "Open a link in the string S, as if it was in Org-mode."
9581 (interactive "sLink: \nP")
9582 (let ((reference-buffer (or reference-buffer (current-buffer))))
9583 (with-temp-buffer
9584 (let ((org-inhibit-startup (not reference-buffer)))
9585 (org-mode)
9586 (insert s)
9587 (goto-char (point-min))
9588 (when reference-buffer
9589 (setq org-link-abbrev-alist-local
9590 (with-current-buffer reference-buffer
9591 org-link-abbrev-alist-local)))
9592 (org-open-at-point arg reference-buffer)))))
9594 (defvar org-open-at-point-functions nil
9595 "Hook that is run when following a link at point.
9597 Functions in this hook must return t if they identify and follow
9598 a link at point. If they don't find anything interesting at point,
9599 they must return nil.")
9601 (defun org-open-at-point (&optional arg reference-buffer)
9602 "Open link at or after point.
9603 If there is no link at point, this function will search forward up to
9604 the end of the current line.
9605 Normally, files will be opened by an appropriate application. If the
9606 optional prefix argument ARG is non-nil, Emacs will visit the file.
9607 With a double prefix argument, try to open outside of Emacs, in the
9608 application the system uses for this file type."
9609 (interactive "P")
9610 ;; if in a code block, then open the block's results
9611 (unless (call-interactively #'org-babel-open-src-block-result)
9612 (org-load-modules-maybe)
9613 (move-marker org-open-link-marker (point))
9614 (setq org-window-config-before-follow-link (current-window-configuration))
9615 (org-remove-occur-highlights nil nil t)
9616 (cond
9617 ((and (org-at-heading-p)
9618 (not (org-at-timestamp-p t))
9619 (not (org-in-regexp
9620 (concat org-plain-link-re "\\|"
9621 org-bracket-link-regexp "\\|"
9622 org-angle-link-re "\\|"
9623 "[ \t]:[^ \t\n]+:[ \t]*$")))
9624 (not (get-text-property (point) 'org-linked-text)))
9625 (or (org-offer-links-in-entry arg)
9626 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9627 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9628 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9629 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9630 (not (org-in-regexp org-bracket-link-regexp)))
9631 (org-footnote-action))
9633 (let (type path link line search (pos (point)))
9634 (catch 'match
9635 (save-excursion
9636 (skip-chars-forward "^]\n\r")
9637 (when (org-in-regexp org-bracket-link-regexp 1)
9638 (setq link (org-extract-attributes
9639 (org-link-unescape (org-match-string-no-properties 1))))
9640 (while (string-match " *\n *" link)
9641 (setq link (replace-match " " t t link)))
9642 (setq link (org-link-expand-abbrev link))
9643 (cond
9644 ((or (file-name-absolute-p link)
9645 (string-match "^\\.\\.?/" link))
9646 (setq type "file" path link))
9647 ((string-match org-link-re-with-space3 link)
9648 (setq type (match-string 1 link) path (match-string 2 link)))
9649 (t (setq type "thisfile" path link)))
9650 (throw 'match t)))
9652 (when (get-text-property (point) 'org-linked-text)
9653 (setq type "thisfile"
9654 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9655 (1+ (point)) (point))
9656 path (buffer-substring
9657 (or (previous-single-property-change pos 'org-linked-text)
9658 (point-min))
9659 (or (next-single-property-change pos 'org-linked-text)
9660 (point-max))))
9661 (throw 'match t))
9663 (save-excursion
9664 (when (or (org-in-regexp org-angle-link-re)
9665 (org-in-regexp org-plain-link-re))
9666 (setq type (match-string 1)
9667 path (org-link-unescape (match-string 2)))
9668 (throw 'match t)))
9669 (save-excursion
9670 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9671 (setq type "tags"
9672 path (match-string 1))
9673 (while (string-match ":" path)
9674 (setq path (replace-match "+" t t path)))
9675 (throw 'match t)))
9676 (when (org-in-regexp "<\\([^><\n]+\\)>")
9677 (setq type "tree-match"
9678 path (match-string 1))
9679 (throw 'match t)))
9680 (unless path
9681 (error "No link found"))
9683 ;; switch back to reference buffer
9684 ;; needed when if called in a temporary buffer through
9685 ;; org-open-link-from-string
9686 (with-current-buffer (or reference-buffer (current-buffer))
9688 ;; Remove any trailing spaces in path
9689 (if (string-match " +\\'" path)
9690 (setq path (replace-match "" t t path)))
9691 (if (and org-link-translation-function
9692 (fboundp org-link-translation-function))
9693 ;; Check if we need to translate the link
9694 (let ((tmp (funcall org-link-translation-function type path)))
9695 (setq type (car tmp) path (cdr tmp))))
9697 (cond
9699 ((assoc type org-link-protocols)
9700 (funcall (nth 1 (assoc type org-link-protocols)) path))
9702 ((equal type "mailto")
9703 (let ((cmd (car org-link-mailto-program))
9704 (args (cdr org-link-mailto-program)) args1
9705 (address path) (subject "") a)
9706 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9707 (setq address (match-string 1 path)
9708 subject (org-link-escape (match-string 2 path))))
9709 (while args
9710 (cond
9711 ((not (stringp (car args))) (push (pop args) args1))
9712 (t (setq a (pop args))
9713 (if (string-match "%a" a)
9714 (setq a (replace-match address t t a)))
9715 (if (string-match "%s" a)
9716 (setq a (replace-match subject t t a)))
9717 (push a args1))))
9718 (apply cmd (nreverse args1))))
9720 ((member type '("http" "https" "ftp" "news"))
9721 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9722 (org-link-escape
9723 path org-link-escape-chars-browser)
9724 path))))
9726 ((string= type "doi")
9727 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9728 (org-link-escape
9729 path org-link-escape-chars-browser)
9730 path))))
9732 ((member type '("message"))
9733 (browse-url (concat type ":" path)))
9735 ((string= type "tags")
9736 (org-tags-view arg path))
9738 ((string= type "tree-match")
9739 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9741 ((string= type "file")
9742 (if (string-match "::\\([0-9]+\\)\\'" path)
9743 (setq line (string-to-number (match-string 1 path))
9744 path (substring path 0 (match-beginning 0)))
9745 (if (string-match "::\\(.+\\)\\'" path)
9746 (setq search (match-string 1 path)
9747 path (substring path 0 (match-beginning 0)))))
9748 (if (string-match "[*?{]" (file-name-nondirectory path))
9749 (dired path)
9750 (org-open-file path arg line search)))
9752 ((string= type "shell")
9753 (let ((cmd path))
9754 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9755 (string-match org-confirm-shell-link-not-regexp cmd))
9756 (not org-confirm-shell-link-function)
9757 (funcall org-confirm-shell-link-function
9758 (format "Execute \"%s\" in shell? "
9759 (org-add-props cmd nil
9760 'face 'org-warning))))
9761 (progn
9762 (message "Executing %s" cmd)
9763 (shell-command cmd))
9764 (error "Abort"))))
9766 ((string= type "elisp")
9767 (let ((cmd path))
9768 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9769 (string-match org-confirm-elisp-link-not-regexp cmd))
9770 (not org-confirm-elisp-link-function)
9771 (funcall org-confirm-elisp-link-function
9772 (format "Execute \"%s\" as elisp? "
9773 (org-add-props cmd nil
9774 'face 'org-warning))))
9775 (message "%s => %s" cmd
9776 (if (equal (string-to-char cmd) ?\()
9777 (eval (read cmd))
9778 (call-interactively (read cmd))))
9779 (error "Abort"))))
9781 ((and (string= type "thisfile")
9782 (run-hook-with-args-until-success
9783 'org-open-link-functions path)))
9785 ((string= type "thisfile")
9786 (if arg
9787 (switch-to-buffer-other-window
9788 (org-get-buffer-for-internal-link (current-buffer)))
9789 (org-mark-ring-push))
9790 (let ((cmd `(org-link-search
9791 ,path
9792 ,(cond ((equal arg '(4)) ''occur)
9793 ((equal arg '(16)) ''org-occur)
9794 (t nil))
9795 ,pos)))
9796 (condition-case nil (let ((org-link-search-inhibit-query t))
9797 (eval cmd))
9798 (error (progn (widen) (eval cmd))))))
9801 (browse-url-at-point)))))))
9802 (move-marker org-open-link-marker nil)
9803 (run-hook-with-args 'org-follow-link-hook)))
9805 (defun org-offer-links-in-entry (&optional nth zero)
9806 "Offer links in the current entry and follow the selected link.
9807 If there is only one link, follow it immediately as well.
9808 If NTH is an integer, immediately pick the NTH link found.
9809 If ZERO is a string, check also this string for a link, and if
9810 there is one, offer it as link number zero."
9811 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9812 "\\(" org-angle-link-re "\\)\\|"
9813 "\\(" org-plain-link-re "\\)"))
9814 (cnt ?0)
9815 (in-emacs (if (integerp nth) nil nth))
9816 have-zero end links link c)
9817 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9818 (push (match-string 0 zero) links)
9819 (setq cnt (1- cnt) have-zero t))
9820 (save-excursion
9821 (org-back-to-heading t)
9822 (setq end (save-excursion (outline-next-heading) (point)))
9823 (while (re-search-forward re end t)
9824 (push (match-string 0) links))
9825 (setq links (org-uniquify (reverse links))))
9827 (cond
9828 ((null links)
9829 (message "No links"))
9830 ((equal (length links) 1)
9831 (setq link (list (car links))))
9832 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9833 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9834 (t ; we have to select a link
9835 (save-excursion
9836 (save-window-excursion
9837 (delete-other-windows)
9838 (with-output-to-temp-buffer "*Select Link*"
9839 (mapc (lambda (l)
9840 (if (not (string-match org-bracket-link-regexp l))
9841 (princ (format "[%c] %s\n" (incf cnt)
9842 (org-remove-angle-brackets l)))
9843 (if (match-end 3)
9844 (princ (format "[%c] %s (%s)\n" (incf cnt)
9845 (match-string 3 l) (match-string 1 l)))
9846 (princ (format "[%c] %s\n" (incf cnt)
9847 (match-string 1 l))))))
9848 links))
9849 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9850 (message "Select link to open, RET to open all:")
9851 (setq c (read-char-exclusive))
9852 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9853 (when (equal c ?q) (error "Abort"))
9854 (if (equal c ?\C-m)
9855 (setq link links)
9856 (setq nth (- c ?0))
9857 (if have-zero (setq nth (1+ nth)))
9858 (unless (and (integerp nth) (>= (length links) nth))
9859 (error "Invalid link selection"))
9860 (setq link (list (nth (1- nth) links))))))
9861 (if link
9862 (let ((buf (current-buffer)))
9863 (dolist (l link)
9864 (org-open-link-from-string l in-emacs buf))
9866 nil)))
9868 ;; Add special file links that specify the way of opening
9870 (org-add-link-type "file+sys" 'org-open-file-with-system)
9871 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9872 (defun org-open-file-with-system (path)
9873 "Open file at PATH using the system way of opening it."
9874 (org-open-file path 'system))
9875 (defun org-open-file-with-emacs (path)
9876 "Open file at PATH in Emacs."
9877 (org-open-file path 'emacs))
9878 (defun org-remove-file-link-modifiers ()
9879 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9880 (goto-char (point-min))
9881 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9882 (org-if-unprotected
9883 (replace-match "file:" t t))))
9884 (eval-after-load "org-exp"
9885 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9886 'org-remove-file-link-modifiers))
9888 ;;;; Time estimates
9890 (defun org-get-effort (&optional pom)
9891 "Get the effort estimate for the current entry."
9892 (org-entry-get pom org-effort-property))
9894 ;;; File search
9896 (defvar org-create-file-search-functions nil
9897 "List of functions to construct the right search string for a file link.
9898 These functions are called in turn with point at the location to
9899 which the link should point.
9901 A function in the hook should first test if it would like to
9902 handle this file type, for example by checking the `major-mode'
9903 or the file extension. If it decides not to handle this file, it
9904 should just return nil to give other functions a chance. If it
9905 does handle the file, it must return the search string to be used
9906 when following the link. The search string will be part of the
9907 file link, given after a double colon, and `org-open-at-point'
9908 will automatically search for it. If special measures must be
9909 taken to make the search successful, another function should be
9910 added to the companion hook `org-execute-file-search-functions',
9911 which see.
9913 A function in this hook may also use `setq' to set the variable
9914 `description' to provide a suggestion for the descriptive text to
9915 be used for this link when it gets inserted into an Org-mode
9916 buffer with \\[org-insert-link].")
9918 (defvar org-execute-file-search-functions nil
9919 "List of functions to execute a file search triggered by a link.
9921 Functions added to this hook must accept a single argument, the
9922 search string that was part of the file link, the part after the
9923 double colon. The function must first check if it would like to
9924 handle this search, for example by checking the `major-mode' or
9925 the file extension. If it decides not to handle this search, it
9926 should just return nil to give other functions a chance. If it
9927 does handle the search, it must return a non-nil value to keep
9928 other functions from trying.
9930 Each function can access the current prefix argument through the
9931 variable `current-prefix-argument'. Note that a single prefix is
9932 used to force opening a link in Emacs, so it may be good to only
9933 use a numeric or double prefix to guide the search function.
9935 In case this is needed, a function in this hook can also restore
9936 the window configuration before `org-open-at-point' was called using:
9938 (set-window-configuration org-window-config-before-follow-link)")
9940 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9941 (defun org-link-search (s &optional type avoid-pos stealth)
9942 "Search for a link search option.
9943 If S is surrounded by forward slashes, it is interpreted as a
9944 regular expression. In org-mode files, this will create an `org-occur'
9945 sparse tree. In ordinary files, `occur' will be used to list matches.
9946 If the current buffer is in `dired-mode', grep will be used to search
9947 in all files. If AVOID-POS is given, ignore matches near that position.
9949 When optional argument STEALTH is non-nil, do not modify
9950 visibility around point, thus ignoring
9951 `org-show-hierarchy-above', `org-show-following-heading' and
9952 `org-show-siblings' variables."
9953 (let ((case-fold-search t)
9954 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9955 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9956 (append '(("") (" ") ("\t") ("\n"))
9957 org-emphasis-alist)
9958 "\\|") "\\)"))
9959 (pos (point))
9960 (pre nil) (post nil)
9961 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9962 (cond
9963 ;; First check if there are any special search functions
9964 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9965 ;; Now try the builtin stuff
9966 ((and (equal (string-to-char s0) ?#)
9967 (> (length s0) 1)
9968 (save-excursion
9969 (goto-char (point-min))
9970 (and
9971 (re-search-forward
9972 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9973 (setq type 'dedicated
9974 pos (match-beginning 0))))
9975 ;; There is an exact target for this
9976 (goto-char pos)
9977 (org-back-to-heading t)))
9978 ((save-excursion
9979 (goto-char (point-min))
9980 (and
9981 (re-search-forward
9982 (concat "<<" (regexp-quote s0) ">>") nil t)
9983 (setq type 'dedicated
9984 pos (match-beginning 0))))
9985 ;; There is an exact target for this
9986 (goto-char pos))
9987 ((save-excursion
9988 (goto-char (point-min))
9989 (and
9990 (re-search-forward
9991 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9992 (setq type 'dedicated pos (match-beginning 0))))
9993 ;; Found an invisible target.
9994 (goto-char pos))
9995 ((save-excursion
9996 (goto-char (point-min))
9997 (and
9998 (re-search-forward
9999 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10000 (setq type 'dedicated pos (match-beginning 0))))
10001 ;; Found an element with a matching #+name affiliated keyword.
10002 (goto-char pos))
10003 ((and (string-match "^(\\(.*\\))$" s0)
10004 (save-excursion
10005 (goto-char (point-min))
10006 (and
10007 (re-search-forward
10008 (concat "[^[]" (regexp-quote
10009 (format org-coderef-label-format
10010 (match-string 1 s0))))
10011 nil t)
10012 (setq type 'dedicated
10013 pos (1+ (match-beginning 0))))))
10014 ;; There is a coderef target for this
10015 (goto-char pos))
10016 ((string-match "^/\\(.*\\)/$" s)
10017 ;; A regular expression
10018 (cond
10019 ((derived-mode-p 'org-mode)
10020 (org-occur (match-string 1 s)))
10021 ;;((eq major-mode 'dired-mode)
10022 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10023 (t (org-do-occur (match-string 1 s)))))
10024 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10025 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10026 (goto-char (point-min))
10027 (cond
10028 ((let (case-fold-search)
10029 (re-search-forward (format org-complex-heading-regexp-format
10030 (regexp-quote s))
10031 nil t))
10032 ;; OK, found a match
10033 (setq type 'dedicated)
10034 (goto-char (match-beginning 0)))
10035 ((and (not org-link-search-inhibit-query)
10036 (eq org-link-search-must-match-exact-headline 'query-to-create)
10037 (y-or-n-p "No match - create this as a new heading? "))
10038 (goto-char (point-max))
10039 (or (bolp) (newline))
10040 (insert "* " s "\n")
10041 (beginning-of-line 0))
10043 (goto-char pos)
10044 (error "No match"))))
10046 ;; A normal search string
10047 (when (equal (string-to-char s) ?*)
10048 ;; Anchor on headlines, post may include tags.
10049 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10050 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10051 s (substring s 1)))
10052 (remove-text-properties
10053 0 (length s)
10054 '(face nil mouse-face nil keymap nil fontified nil) s)
10055 ;; Make a series of regular expressions to find a match
10056 (setq words (org-split-string s "[ \n\r\t]+")
10058 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10059 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10060 "\\)" markers)
10061 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10062 re2a (concat "[ \t\r\n]" re2a_)
10063 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10064 re4 (concat "[^a-zA-Z_]" re4_)
10066 re1 (concat pre re2 post)
10067 re3 (concat pre (if pre re4_ re4) post)
10068 re5 (concat pre ".*" re4)
10069 re2 (concat pre re2)
10070 re2a (concat pre (if pre re2a_ re2a))
10071 re4 (concat pre (if pre re4_ re4))
10072 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10073 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10074 re5 "\\)"
10076 (cond
10077 ((eq type 'org-occur) (org-occur reall))
10078 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10079 (t (goto-char (point-min))
10080 (setq type 'fuzzy)
10081 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10082 (org-search-not-self 1 re1 nil t)
10083 (org-search-not-self 1 re2 nil t)
10084 (org-search-not-self 1 re2a nil t)
10085 (org-search-not-self 1 re3 nil t)
10086 (org-search-not-self 1 re4 nil t)
10087 (org-search-not-self 1 re5 nil t)
10089 (goto-char (match-beginning 1))
10090 (goto-char pos)
10091 (error "No match"))))))
10092 (and (derived-mode-p 'org-mode)
10093 (not stealth)
10094 (org-show-context 'link-search))
10095 type))
10097 (defun org-search-not-self (group &rest args)
10098 "Execute `re-search-forward', but only accept matches that do not
10099 enclose the position of `org-open-link-marker'."
10100 (let ((m org-open-link-marker))
10101 (catch 'exit
10102 (while (apply 're-search-forward args)
10103 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10104 (goto-char (match-end group))
10105 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10106 (> (match-beginning 0) (marker-position m))
10107 (< (match-end 0) (marker-position m)))
10108 (save-match-data
10109 (or (not (org-in-regexp
10110 org-bracket-link-analytic-regexp 1))
10111 (not (match-end 4)) ; no description
10112 (and (<= (match-beginning 4) (point))
10113 (>= (match-end 4) (point))))))
10114 (throw 'exit (point))))))))
10116 (defun org-get-buffer-for-internal-link (buffer)
10117 "Return a buffer to be used for displaying the link target of internal links."
10118 (cond
10119 ((not org-display-internal-link-with-indirect-buffer)
10120 buffer)
10121 ((string-match "(Clone)$" (buffer-name buffer))
10122 (message "Buffer is already a clone, not making another one")
10123 ;; we also do not modify visibility in this case
10124 buffer)
10125 (t ; make a new indirect buffer for displaying the link
10126 (let* ((bn (buffer-name buffer))
10127 (ibn (concat bn "(Clone)"))
10128 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10129 (with-current-buffer ib (org-overview))
10130 ib))))
10132 (defun org-do-occur (regexp &optional cleanup)
10133 "Call the Emacs command `occur'.
10134 If CLEANUP is non-nil, remove the printout of the regular expression
10135 in the *Occur* buffer. This is useful if the regex is long and not useful
10136 to read."
10137 (occur regexp)
10138 (when cleanup
10139 (let ((cwin (selected-window)) win beg end)
10140 (when (setq win (get-buffer-window "*Occur*"))
10141 (select-window win))
10142 (goto-char (point-min))
10143 (when (re-search-forward "match[a-z]+" nil t)
10144 (setq beg (match-end 0))
10145 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10146 (setq end (1- (match-beginning 0)))))
10147 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10148 (goto-char (point-min))
10149 (select-window cwin))))
10151 ;;; The mark ring for links jumps
10153 (defvar org-mark-ring nil
10154 "Mark ring for positions before jumps in Org-mode.")
10155 (defvar org-mark-ring-last-goto nil
10156 "Last position in the mark ring used to go back.")
10157 ;; Fill and close the ring
10158 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10159 (loop for i from 1 to org-mark-ring-length do
10160 (push (make-marker) org-mark-ring))
10161 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10162 org-mark-ring)
10164 (defun org-mark-ring-push (&optional pos buffer)
10165 "Put the current position or POS into the mark ring and rotate it."
10166 (interactive)
10167 (setq pos (or pos (point)))
10168 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10169 (move-marker (car org-mark-ring)
10170 (or pos (point))
10171 (or buffer (current-buffer)))
10172 (message "%s"
10173 (substitute-command-keys
10174 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10176 (defun org-mark-ring-goto (&optional n)
10177 "Jump to the previous position in the mark ring.
10178 With prefix arg N, jump back that many stored positions. When
10179 called several times in succession, walk through the entire ring.
10180 Org-mode commands jumping to a different position in the current file,
10181 or to another Org-mode file, automatically push the old position
10182 onto the ring."
10183 (interactive "p")
10184 (let (p m)
10185 (if (eq last-command this-command)
10186 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10187 (setq p org-mark-ring))
10188 (setq org-mark-ring-last-goto p)
10189 (setq m (car p))
10190 (org-pop-to-buffer-same-window (marker-buffer m))
10191 (goto-char m)
10192 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10194 (defun org-remove-angle-brackets (s)
10195 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10196 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10198 (defun org-add-angle-brackets (s)
10199 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10200 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10202 (defun org-remove-double-quotes (s)
10203 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10204 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10207 ;;; Following specific links
10209 (defun org-follow-timestamp-link ()
10210 (cond
10211 ((org-at-date-range-p t)
10212 (let ((org-agenda-start-on-weekday)
10213 (t1 (match-string 1))
10214 (t2 (match-string 2)))
10215 (setq t1 (time-to-days (org-time-string-to-time t1))
10216 t2 (time-to-days (org-time-string-to-time t2)))
10217 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10218 ((org-at-timestamp-p t)
10219 (org-agenda-list nil (time-to-days (org-time-string-to-time
10220 (substring (match-string 1) 0 10)))
10222 (t (error "This should not happen"))))
10225 ;;; Following file links
10226 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10227 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10228 (declare-function mailcap-mime-info
10229 "mailcap" (string &optional request no-decode))
10230 (defvar org-wait nil)
10231 (defun org-open-file (path &optional in-emacs line search)
10232 "Open the file at PATH.
10233 First, this expands any special file name abbreviations. Then the
10234 configuration variable `org-file-apps' is checked if it contains an
10235 entry for this file type, and if yes, the corresponding command is launched.
10237 If no application is found, Emacs simply visits the file.
10239 With optional prefix argument IN-EMACS, Emacs will visit the file.
10240 With a double \\[universal-argument] \\[universal-argument] \
10241 prefix arg, Org tries to avoid opening in Emacs
10242 and to use an external application to visit the file.
10244 Optional LINE specifies a line to go to, optional SEARCH a string
10245 to search for. If LINE or SEARCH is given, the file will be
10246 opened in Emacs, unless an entry from org-file-apps that makes
10247 use of groups in a regexp matches.
10249 If you want to change the way frames are used when following a
10250 link, please customize `org-link-frame-setup'.
10252 If the file does not exist, an error is thrown."
10253 (let* ((file (if (equal path "")
10254 buffer-file-name
10255 (substitute-in-file-name (expand-file-name path))))
10256 (file-apps (append org-file-apps (org-default-apps)))
10257 (apps (org-remove-if
10258 'org-file-apps-entry-match-against-dlink-p file-apps))
10259 (apps-dlink (org-remove-if-not
10260 'org-file-apps-entry-match-against-dlink-p file-apps))
10261 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10262 (dirp (if remp nil (file-directory-p file)))
10263 (file (if (and dirp org-open-directory-means-index-dot-org)
10264 (concat (file-name-as-directory file) "index.org")
10265 file))
10266 (a-m-a-p (assq 'auto-mode apps))
10267 (dfile (downcase file))
10268 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10269 (link (cond ((and (eq line nil)
10270 (eq search nil))
10271 file)
10272 (line
10273 (concat file "::" (number-to-string line)))
10274 (search
10275 (concat file "::" search))))
10276 (dlink (downcase link))
10277 (old-buffer (current-buffer))
10278 (old-pos (point))
10279 (old-mode major-mode)
10280 ext cmd link-match-data)
10281 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10282 (setq ext (match-string 1 dfile))
10283 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10284 (setq ext (match-string 1 dfile))))
10285 (cond
10286 ((member in-emacs '((16) system))
10287 (setq cmd (cdr (assoc 'system apps))))
10288 (in-emacs (setq cmd 'emacs))
10290 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10291 (and dirp (cdr (assoc 'directory apps)))
10292 ; first, try matching against apps-dlink
10293 ; if we get a match here, store the match data for later
10294 (let ((match (assoc-default dlink apps-dlink
10295 'string-match)))
10296 (if match
10297 (progn (setq link-match-data (match-data))
10298 match)
10299 (progn (setq in-emacs (or in-emacs line search))
10300 nil))) ; if we have no match in apps-dlink,
10301 ; always open the file in emacs if line or search
10302 ; is given (for backwards compatibility)
10303 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10304 'string-match)
10305 (cdr (assoc ext apps))
10306 (cdr (assoc t apps))))))
10307 (when (eq cmd 'system)
10308 (setq cmd (cdr (assoc 'system apps))))
10309 (when (eq cmd 'default)
10310 (setq cmd (cdr (assoc t apps))))
10311 (when (eq cmd 'mailcap)
10312 (require 'mailcap)
10313 (mailcap-parse-mailcaps)
10314 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10315 (command (mailcap-mime-info mime-type)))
10316 (if (stringp command)
10317 (setq cmd command)
10318 (setq cmd 'emacs))))
10319 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10320 (not (file-exists-p file))
10321 (not org-open-non-existing-files))
10322 (error "No such file: %s" file))
10323 (cond
10324 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10325 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10326 (while (string-match "['\"]%s['\"]" cmd)
10327 (setq cmd (replace-match "%s" t t cmd)))
10328 (while (string-match "%s" cmd)
10329 (setq cmd (replace-match
10330 (save-match-data
10331 (shell-quote-argument
10332 (convert-standard-filename file)))
10333 t t cmd)))
10335 ;; Replace "%1", "%2" etc. in command with group matches from regex
10336 (save-match-data
10337 (let ((match-index 1)
10338 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10339 (set-match-data link-match-data)
10340 (while (<= match-index number-of-groups)
10341 (let ((regex (concat "%" (number-to-string match-index)))
10342 (replace-with (match-string match-index dlink)))
10343 (while (string-match regex cmd)
10344 (setq cmd (replace-match replace-with t t cmd))))
10345 (setq match-index (+ match-index 1)))))
10347 (save-window-excursion
10348 (start-process-shell-command cmd nil cmd)
10349 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10351 ((or (stringp cmd)
10352 (eq cmd 'emacs))
10353 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10354 (widen)
10355 (if line (org-goto-line line)
10356 (if search (org-link-search search))))
10357 ((consp cmd)
10358 (let ((file (convert-standard-filename file)))
10359 (save-match-data
10360 (set-match-data link-match-data)
10361 (eval cmd))))
10362 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10363 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10364 (or (not (equal old-buffer (current-buffer)))
10365 (not (equal old-pos (point))))
10366 (org-mark-ring-push old-pos old-buffer))))
10368 (defun org-file-apps-entry-match-against-dlink-p (entry)
10369 "This function returns non-nil if `entry' uses a regular
10370 expression which should be matched against the whole link by
10371 org-open-file.
10373 It assumes that is the case when the entry uses a regular
10374 expression which has at least one grouping construct and the
10375 action is either a lisp form or a command string containing
10376 '%1', i.e. using at least one subexpression match as a
10377 parameter."
10378 (let ((selector (car entry))
10379 (action (cdr entry)))
10380 (if (stringp selector)
10381 (and (> (regexp-opt-depth selector) 0)
10382 (or (and (stringp action)
10383 (string-match "%[0-9]" action))
10384 (consp action)))
10385 nil)))
10387 (defun org-default-apps ()
10388 "Return the default applications for this operating system."
10389 (cond
10390 ((eq system-type 'darwin)
10391 org-file-apps-defaults-macosx)
10392 ((eq system-type 'windows-nt)
10393 org-file-apps-defaults-windowsnt)
10394 (t org-file-apps-defaults-gnu)))
10396 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10397 "Convert extensions to regular expressions in the cars of LIST.
10398 Also, weed out any non-string entries, because the return value is used
10399 only for regexp matching.
10400 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10401 point to the symbol `emacs', indicating that the file should
10402 be opened in Emacs."
10403 (append
10404 (delq nil
10405 (mapcar (lambda (x)
10406 (if (not (stringp (car x)))
10408 (if (string-match "\\W" (car x))
10410 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10411 list))
10412 (if add-auto-mode
10413 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10415 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10416 (defun org-file-remote-p (file)
10417 "Test whether FILE specifies a location on a remote system.
10418 Return non-nil if the location is indeed remote.
10420 For example, the filename \"/user@host:/foo\" specifies a location
10421 on the system \"/user@host:\"."
10422 (cond ((fboundp 'file-remote-p)
10423 (file-remote-p file))
10424 ((fboundp 'tramp-handle-file-remote-p)
10425 (tramp-handle-file-remote-p file))
10426 ((and (boundp 'ange-ftp-name-format)
10427 (string-match (car ange-ftp-name-format) file))
10429 (t nil)))
10432 ;;;; Refiling
10434 (defun org-get-org-file ()
10435 "Read a filename, with default directory `org-directory'."
10436 (let ((default (or org-default-notes-file remember-data-file)))
10437 (read-file-name (format "File name [%s]: " default)
10438 (file-name-as-directory org-directory)
10439 default)))
10441 (defun org-notes-order-reversed-p ()
10442 "Check if the current file should receive notes in reversed order."
10443 (cond
10444 ((not org-reverse-note-order) nil)
10445 ((eq t org-reverse-note-order) t)
10446 ((not (listp org-reverse-note-order)) nil)
10447 (t (catch 'exit
10448 (let ((all org-reverse-note-order)
10449 entry)
10450 (while (setq entry (pop all))
10451 (if (string-match (car entry) buffer-file-name)
10452 (throw 'exit (cdr entry))))
10453 nil)))))
10455 (defvar org-refile-target-table nil
10456 "The list of refile targets, created by `org-refile'.")
10458 (defvar org-agenda-new-buffers nil
10459 "Buffers created to visit agenda files.")
10461 (defvar org-refile-cache nil
10462 "Cache for refile targets.")
10464 (defvar org-refile-markers nil
10465 "All the markers used for caching refile locations.")
10467 (defun org-refile-marker (pos)
10468 "Get a new refile marker, but only if caching is in use."
10469 (if (not org-refile-use-cache)
10471 (let ((m (make-marker)))
10472 (move-marker m pos)
10473 (push m org-refile-markers)
10474 m)))
10476 (defun org-refile-cache-clear ()
10477 "Clear the refile cache and disable all the markers."
10478 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10479 (setq org-refile-markers nil)
10480 (setq org-refile-cache nil)
10481 (message "Refile cache has been cleared"))
10483 (defun org-refile-cache-check-set (set)
10484 "Check if all the markers in the cache still have live buffers."
10485 (let (marker)
10486 (catch 'exit
10487 (while (and set (setq marker (nth 3 (pop set))))
10488 ;; if org-refile-use-outline-path is 'file, marker may be nil
10489 (when (and marker (null (marker-buffer marker)))
10490 (message "not found") (sit-for 3)
10491 (throw 'exit nil)))
10492 t)))
10494 (defun org-refile-cache-put (set &rest identifiers)
10495 "Push the refile targets SET into the cache, under IDENTIFIERS."
10496 (let* ((key (sha1 (prin1-to-string identifiers)))
10497 (entry (assoc key org-refile-cache)))
10498 (if entry
10499 (setcdr entry set)
10500 (push (cons key set) org-refile-cache))))
10502 (defun org-refile-cache-get (&rest identifiers)
10503 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10504 (cond
10505 ((not org-refile-cache) nil)
10506 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10508 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10509 org-refile-cache))))
10510 (and set (org-refile-cache-check-set set) set)))))
10512 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10513 "Produce a table with refile targets."
10514 (let ((case-fold-search nil)
10515 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10516 (entries (or org-refile-targets '((nil . (:level . 1)))))
10517 targets tgs txt re files f desc descre fast-path-p level pos0)
10518 (message "Getting targets...")
10519 (with-current-buffer (or default-buffer (current-buffer))
10520 (while (setq entry (pop entries))
10521 (setq files (car entry) desc (cdr entry))
10522 (setq fast-path-p nil)
10523 (cond
10524 ((null files) (setq files (list (current-buffer))))
10525 ((eq files 'org-agenda-files)
10526 (setq files (org-agenda-files 'unrestricted)))
10527 ((and (symbolp files) (fboundp files))
10528 (setq files (funcall files)))
10529 ((and (symbolp files) (boundp files))
10530 (setq files (symbol-value files))))
10531 (if (stringp files) (setq files (list files)))
10532 (cond
10533 ((eq (car desc) :tag)
10534 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10535 ((eq (car desc) :todo)
10536 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10537 ((eq (car desc) :regexp)
10538 (setq descre (cdr desc)))
10539 ((eq (car desc) :level)
10540 (setq descre (concat "^\\*\\{" (number-to-string
10541 (if org-odd-levels-only
10542 (1- (* 2 (cdr desc)))
10543 (cdr desc)))
10544 "\\}[ \t]")))
10545 ((eq (car desc) :maxlevel)
10546 (setq fast-path-p t)
10547 (setq descre (concat "^\\*\\{1," (number-to-string
10548 (if org-odd-levels-only
10549 (1- (* 2 (cdr desc)))
10550 (cdr desc)))
10551 "\\}[ \t]")))
10552 (t (error "Bad refiling target description %s" desc)))
10553 (while (setq f (pop files))
10554 (with-current-buffer
10555 (if (bufferp f) f (org-get-agenda-file-buffer f))
10557 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10558 (progn
10559 (if (bufferp f) (setq f (buffer-file-name
10560 (buffer-base-buffer f))))
10561 (setq f (and f (expand-file-name f)))
10562 (if (eq org-refile-use-outline-path 'file)
10563 (push (list (file-name-nondirectory f) f nil nil) tgs))
10564 (save-excursion
10565 (save-restriction
10566 (widen)
10567 (goto-char (point-min))
10568 (while (re-search-forward descre nil t)
10569 (goto-char (setq pos0 (point-at-bol)))
10570 (catch 'next
10571 (when org-refile-target-verify-function
10572 (save-match-data
10573 (or (funcall org-refile-target-verify-function)
10574 (throw 'next t))))
10575 (when (and (looking-at org-complex-heading-regexp)
10576 (not (member (match-string 4) excluded-entries))
10577 (match-string 4))
10578 (setq level (org-reduced-level
10579 (- (match-end 1) (match-beginning 1)))
10580 txt (org-link-display-format (match-string 4))
10581 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10582 re (format org-complex-heading-regexp-format
10583 (regexp-quote (match-string 4))))
10584 (when org-refile-use-outline-path
10585 (setq txt (mapconcat
10586 'org-protect-slash
10587 (append
10588 (if (eq org-refile-use-outline-path
10589 'file)
10590 (list (file-name-nondirectory
10591 (buffer-file-name
10592 (buffer-base-buffer))))
10593 (if (eq org-refile-use-outline-path
10594 'full-file-path)
10595 (list (buffer-file-name
10596 (buffer-base-buffer)))))
10597 (org-get-outline-path fast-path-p
10598 level txt)
10599 (list txt))
10600 "/")))
10601 (push (list txt f re (org-refile-marker (point)))
10602 tgs)))
10603 (when (= (point) pos0)
10604 ;; verification function has not moved point
10605 (goto-char (point-at-eol))))))))
10606 (when org-refile-use-cache
10607 (org-refile-cache-put tgs (buffer-file-name) descre))
10608 (setq targets (append tgs targets))
10609 ))))
10610 (message "Getting targets...done")
10611 (nreverse targets)))
10613 (defun org-protect-slash (s)
10614 (while (string-match "/" s)
10615 (setq s (replace-match "\\" t t s)))
10618 (defvar org-olpa (make-vector 20 nil))
10620 (defun org-get-outline-path (&optional fastp level heading)
10621 "Return the outline path to the current entry, as a list.
10623 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10624 routine which makes outline path derivations for an entire file,
10625 avoiding backtracing. Refile target collection makes use of that."
10626 (if fastp
10627 (progn
10628 (if (> level 19)
10629 (error "Outline path failure, more than 19 levels"))
10630 (loop for i from level upto 19 do
10631 (aset org-olpa i nil))
10632 (prog1
10633 (delq nil (append org-olpa nil))
10634 (aset org-olpa level heading)))
10635 (let (rtn case-fold-search)
10636 (save-excursion
10637 (save-restriction
10638 (widen)
10639 (while (org-up-heading-safe)
10640 (when (looking-at org-complex-heading-regexp)
10641 (push (org-match-string-no-properties 4) rtn)))
10642 rtn)))))
10644 (defun org-format-outline-path (path &optional width prefix)
10645 "Format the outline path PATH for display.
10646 Width is the maximum number of characters that is available.
10647 Prefix is a prefix to be included in the returned string,
10648 such as the file name."
10649 (setq width (or width 79))
10650 (if prefix (setq width (- width (length prefix))))
10651 (if (not path)
10652 (or prefix "")
10653 (let* ((nsteps (length path))
10654 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10655 (maxwidth (if (<= total-width width)
10656 10000 ;; everything fits
10657 ;; we need to shorten the level headings
10658 (/ (- width nsteps) nsteps)))
10659 (org-odd-levels-only nil)
10660 (n 0)
10661 (total (1+ (length prefix))))
10662 (setq maxwidth (max maxwidth 10))
10663 (concat prefix
10664 (mapconcat
10665 (lambda (h)
10666 (setq n (1+ n))
10667 (if (and (= n nsteps) (< maxwidth 10000))
10668 (setq maxwidth (- total-width total)))
10669 (if (< (length h) maxwidth)
10670 (progn (setq total (+ total (length h) 1)) h)
10671 (setq h (substring h 0 (- maxwidth 2))
10672 total (+ total maxwidth 1))
10673 (if (string-match "[ \t]+\\'" h)
10674 (setq h (substring h 0 (match-beginning 0))))
10675 (setq h (concat h "..")))
10676 (org-add-props h nil 'face
10677 (nth (% (1- n) org-n-level-faces)
10678 org-level-faces))
10680 path "/")))))
10682 (defun org-display-outline-path (&optional file current)
10683 "Display the current outline path in the echo area."
10684 (interactive "P")
10685 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10686 (case-fold-search nil)
10687 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10688 (if current (setq path (append path
10689 (save-excursion
10690 (org-back-to-heading t)
10691 (if (looking-at org-complex-heading-regexp)
10692 (list (match-string 4)))))))
10693 (message "%s"
10694 (org-format-outline-path
10695 path
10696 (1- (frame-width))
10697 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10699 (defvar org-refile-history nil
10700 "History for refiling operations.")
10702 (defvar org-after-refile-insert-hook nil
10703 "Hook run after `org-refile' has inserted its stuff at the new location.
10704 Note that this is still *before* the stuff will be removed from
10705 the *old* location.")
10707 (defvar org-capture-last-stored-marker)
10708 (defun org-refile (&optional goto default-buffer rfloc)
10709 "Move the entry or entries at point to another heading.
10710 The list of target headings is compiled using the information in
10711 `org-refile-targets', which see.
10713 At the target location, the entry is filed as a subitem of the target
10714 heading. Depending on `org-reverse-note-order', the new subitem will
10715 either be the first or the last subitem.
10717 If there is an active region, all entries in that region will be moved.
10718 However, the region must fulfill the requirement that the first heading
10719 is the first one sets the top-level of the moved text - at most siblings
10720 below it are allowed.
10722 With prefix arg GOTO, the command will only visit the target location
10723 and not actually move anything.
10725 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10726 go to the location where the last refiling operation has put the subtree.
10727 With a prefix argument of `2', refile to the running clock.
10729 RFLOC can be a refile location obtained in a different way.
10731 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10733 If you are using target caching (see `org-refile-use-cache'),
10734 you have to clear the target cache in order to find new targets.
10735 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10736 prefix argument (`C-u C-u C-u C-c C-w')."
10738 (interactive "P")
10739 (if (member goto '(0 (64)))
10740 (org-refile-cache-clear)
10741 (let* ((cbuf (current-buffer))
10742 (regionp (org-region-active-p))
10743 (region-start (and regionp (region-beginning)))
10744 (region-end (and regionp (region-end)))
10745 (region-length (and regionp (- region-end region-start)))
10746 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10747 pos it nbuf file re level reversed)
10748 (setq last-command nil)
10749 (when regionp
10750 (goto-char region-start)
10751 (or (bolp) (goto-char (point-at-bol)))
10752 (setq region-start (point))
10753 (unless (or (org-kill-is-subtree-p
10754 (buffer-substring region-start region-end))
10755 (prog1 org-refile-active-region-within-subtree
10756 (org-toggle-heading)))
10757 (error "The region is not a (sequence of) subtree(s)")))
10758 (if (equal goto '(16))
10759 (org-refile-goto-last-stored)
10760 (when (or
10761 (and (equal goto 2)
10762 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10763 (prog1
10764 (setq it (list (or org-clock-heading "running clock")
10765 (buffer-file-name
10766 (marker-buffer org-clock-hd-marker))
10768 (marker-position org-clock-hd-marker)))
10769 (setq goto nil)))
10770 (setq it (or rfloc
10771 (let (heading-text)
10772 (save-excursion
10773 (unless goto
10774 (org-back-to-heading t)
10775 (setq heading-text
10776 (nth 4 (org-heading-components))))
10777 (org-refile-get-location
10778 (cond (goto "Goto")
10779 (regionp "Refile region to")
10780 (t (concat "Refile subtree \""
10781 heading-text "\" to")))
10782 default-buffer
10783 (and (not (equal '(4) goto))
10784 org-refile-allow-creating-parent-nodes)
10785 goto))))))
10786 (setq file (nth 1 it)
10787 re (nth 2 it)
10788 pos (nth 3 it))
10789 (if (and (not goto)
10791 (equal (buffer-file-name) file)
10792 (if regionp
10793 (and (>= pos region-start)
10794 (<= pos region-end))
10795 (and (>= pos (point))
10796 (< pos (save-excursion
10797 (org-end-of-subtree t t))))))
10798 (error "Cannot refile to position inside the tree or region"))
10800 (setq nbuf (or (find-buffer-visiting file)
10801 (find-file-noselect file)))
10802 (if goto
10803 (progn
10804 (org-pop-to-buffer-same-window nbuf)
10805 (goto-char pos)
10806 (org-show-context 'org-goto))
10807 (if regionp
10808 (progn
10809 (org-kill-new (buffer-substring region-start region-end))
10810 (org-save-markers-in-region region-start region-end))
10811 (org-copy-subtree 1 nil t))
10812 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10813 (find-file-noselect file)))
10814 (setq reversed (org-notes-order-reversed-p))
10815 (save-excursion
10816 (save-restriction
10817 (widen)
10818 (if pos
10819 (progn
10820 (goto-char pos)
10821 (looking-at org-outline-regexp)
10822 (setq level (org-get-valid-level (funcall outline-level) 1))
10823 (goto-char
10824 (if reversed
10825 (or (outline-next-heading) (point-max))
10826 (or (save-excursion (org-get-next-sibling))
10827 (org-end-of-subtree t t)
10828 (point-max)))))
10829 (setq level 1)
10830 (if (not reversed)
10831 (goto-char (point-max))
10832 (goto-char (point-min))
10833 (or (outline-next-heading) (goto-char (point-max)))))
10834 (if (not (bolp)) (newline))
10835 (org-paste-subtree level)
10836 (when org-log-refile
10837 (org-add-log-setup 'refile nil nil 'findpos
10838 org-log-refile)
10839 (unless (eq org-log-refile 'note)
10840 (save-excursion (org-add-log-note))))
10841 (and org-auto-align-tags (org-set-tags nil t))
10842 (bookmark-set "org-refile-last-stored")
10843 ;; If we are refiling for capture, make sure that the
10844 ;; last-capture pointers point here
10845 (when (org-bound-and-true-p org-refile-for-capture)
10846 (bookmark-set "org-capture-last-stored-marker")
10847 (move-marker org-capture-last-stored-marker (point)))
10848 (if (fboundp 'deactivate-mark) (deactivate-mark))
10849 (run-hooks 'org-after-refile-insert-hook))))
10850 (if regionp
10851 (delete-region (point) (+ (point) region-length))
10852 (org-cut-subtree))
10853 (when (featurep 'org-inlinetask)
10854 (org-inlinetask-remove-END-maybe))
10855 (setq org-markers-to-move nil)
10856 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10858 (defun org-refile-goto-last-stored ()
10859 "Go to the location where the last refile was stored."
10860 (interactive)
10861 (bookmark-jump "org-refile-last-stored")
10862 (message "This is the location of the last refile"))
10864 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10865 no-exclude)
10866 "Prompt the user for a refile location, using PROMPT.
10867 PROMPT should not be suffixed with a colon and a space, because
10868 this function appends the default value from
10869 `org-refile-history' automatically, if that is not empty.
10870 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10871 this is used for the GOTO interface."
10872 (let ((org-refile-targets org-refile-targets)
10873 (org-refile-use-outline-path org-refile-use-outline-path)
10874 excluded-entries)
10875 (when (and (derived-mode-p 'org-mode)
10876 (not org-refile-use-cache)
10877 (not no-exclude))
10878 (org-map-tree
10879 (lambda()
10880 (setq excluded-entries
10881 (append excluded-entries (list (org-get-heading t t)))))))
10882 (setq org-refile-target-table
10883 (org-refile-get-targets default-buffer excluded-entries)))
10884 (unless org-refile-target-table
10885 (error "No refile targets"))
10886 (let* ((prompt (concat prompt
10887 (and (car org-refile-history)
10888 (concat " (default " (car org-refile-history) ")"))
10889 ": "))
10890 (cbuf (current-buffer))
10891 (partial-completion-mode nil)
10892 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10893 (cfunc (if (and org-refile-use-outline-path
10894 org-outline-path-complete-in-steps)
10895 'org-olpath-completing-read
10896 'org-icompleting-read))
10897 (extra (if org-refile-use-outline-path "/" ""))
10898 (filename (and cfn (expand-file-name cfn)))
10899 (tbl (mapcar
10900 (lambda (x)
10901 (if (and (not (member org-refile-use-outline-path
10902 '(file full-file-path)))
10903 (not (equal filename (nth 1 x))))
10904 (cons (concat (car x) extra " ("
10905 (file-name-nondirectory (nth 1 x)) ")")
10906 (cdr x))
10907 (cons (concat (car x) extra) (cdr x))))
10908 org-refile-target-table))
10909 (completion-ignore-case t)
10910 pa answ parent-target child parent old-hist)
10911 (setq old-hist org-refile-history)
10912 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10913 nil 'org-refile-history (car org-refile-history)))
10914 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10915 (org-refile-check-position pa)
10916 (if pa
10917 (progn
10918 (when (or (not org-refile-history)
10919 (not (eq old-hist org-refile-history))
10920 (not (equal (car pa) (car org-refile-history))))
10921 (setq org-refile-history
10922 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10923 org-refile-history
10924 (cdr org-refile-history))))
10925 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10926 (pop org-refile-history)))
10928 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10929 (progn
10930 (setq parent (match-string 1 answ)
10931 child (match-string 2 answ))
10932 (setq parent-target (or (assoc parent tbl)
10933 (assoc (concat parent "/") tbl)))
10934 (when (and parent-target
10935 (or (eq new-nodes t)
10936 (and (eq new-nodes 'confirm)
10937 (y-or-n-p (format "Create new node \"%s\"? "
10938 child)))))
10939 (org-refile-new-child parent-target child)))
10940 (error "Invalid target location")))))
10942 (declare-function org-string-nw-p "org-macs.el" (s))
10943 (defun org-refile-check-position (refile-pointer)
10944 "Check if the refile pointer matches the readline to which it points."
10945 (let* ((file (nth 1 refile-pointer))
10946 (re (nth 2 refile-pointer))
10947 (pos (nth 3 refile-pointer))
10948 buffer)
10949 (when (org-string-nw-p re)
10950 (setq buffer (if (markerp pos)
10951 (marker-buffer pos)
10952 (or (find-buffer-visiting file)
10953 (find-file-noselect file))))
10954 (with-current-buffer buffer
10955 (save-excursion
10956 (save-restriction
10957 (widen)
10958 (goto-char pos)
10959 (beginning-of-line 1)
10960 (unless (org-looking-at-p re)
10961 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10963 (defun org-refile-new-child (parent-target child)
10964 "Use refile target PARENT-TARGET to add new CHILD below it."
10965 (unless parent-target
10966 (error "Cannot find parent for new node"))
10967 (let ((file (nth 1 parent-target))
10968 (pos (nth 3 parent-target))
10969 level)
10970 (with-current-buffer (or (find-buffer-visiting file)
10971 (find-file-noselect file))
10972 (save-excursion
10973 (save-restriction
10974 (widen)
10975 (if pos
10976 (goto-char pos)
10977 (goto-char (point-max))
10978 (if (not (bolp)) (newline)))
10979 (when (looking-at org-outline-regexp)
10980 (setq level (funcall outline-level))
10981 (org-end-of-subtree t t))
10982 (org-back-over-empty-lines)
10983 (insert "\n" (make-string
10984 (if pos (org-get-valid-level level 1) 1) ?*)
10985 " " child "\n")
10986 (beginning-of-line 0)
10987 (list (concat (car parent-target) "/" child) file "" (point)))))))
10989 (defun org-olpath-completing-read (prompt collection &rest args)
10990 "Read an outline path like a file name."
10991 (let ((thetable collection)
10992 (org-completion-use-ido nil) ; does not work with ido.
10993 (org-completion-use-iswitchb nil)) ; or iswitchb
10994 (apply
10995 'org-icompleting-read prompt
10996 (lambda (string predicate &optional flag)
10997 (let (rtn r f (l (length string)))
10998 (cond
10999 ((eq flag nil)
11000 ;; try completion
11001 (try-completion string thetable))
11002 ((eq flag t)
11003 ;; all-completions
11004 (setq rtn (all-completions string thetable predicate))
11005 (mapcar
11006 (lambda (x)
11007 (setq r (substring x l))
11008 (if (string-match " ([^)]*)$" x)
11009 (setq f (match-string 0 x))
11010 (setq f ""))
11011 (if (string-match "/" r)
11012 (concat string (substring r 0 (match-end 0)) f)
11014 rtn))
11015 ((eq flag 'lambda)
11016 ;; exact match?
11017 (assoc string thetable)))))
11018 args)))
11020 ;;;; Dynamic blocks
11022 (defun org-find-dblock (name)
11023 "Find the first dynamic block with name NAME in the buffer.
11024 If not found, stay at current position and return nil."
11025 (let (pos)
11026 (save-excursion
11027 (goto-char (point-min))
11028 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
11029 nil t)
11030 (match-beginning 0))))
11031 (if pos (goto-char pos))
11032 pos))
11034 (defconst org-dblock-start-re
11035 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11036 "Matches the start line of a dynamic block, with parameters.")
11038 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
11039 "Matches the end of a dynamic block.")
11041 (defun org-create-dblock (plist)
11042 "Create a dynamic block section, with parameters taken from PLIST.
11043 PLIST must contain a :name entry which is used as name of the block."
11044 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11045 (end-of-line 1)
11046 (newline))
11047 (let ((col (current-column))
11048 (name (plist-get plist :name)))
11049 (insert "#+BEGIN: " name)
11050 (while plist
11051 (if (eq (car plist) :name)
11052 (setq plist (cddr plist))
11053 (insert " " (prin1-to-string (pop plist)))))
11054 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11055 (beginning-of-line -2)))
11057 (defun org-prepare-dblock ()
11058 "Prepare dynamic block for refresh.
11059 This empties the block, puts the cursor at the insert position and returns
11060 the property list including an extra property :name with the block name."
11061 (unless (looking-at org-dblock-start-re)
11062 (error "Not at a dynamic block"))
11063 (let* ((begdel (1+ (match-end 0)))
11064 (name (org-no-properties (match-string 1)))
11065 (params (append (list :name name)
11066 (read (concat "(" (match-string 3) ")")))))
11067 (save-excursion
11068 (beginning-of-line 1)
11069 (skip-chars-forward " \t")
11070 (setq params (plist-put params :indentation-column (current-column))))
11071 (unless (re-search-forward org-dblock-end-re nil t)
11072 (error "Dynamic block not terminated"))
11073 (setq params
11074 (append params
11075 (list :content (buffer-substring
11076 begdel (match-beginning 0)))))
11077 (delete-region begdel (match-beginning 0))
11078 (goto-char begdel)
11079 (open-line 1)
11080 params))
11082 (defun org-map-dblocks (&optional command)
11083 "Apply COMMAND to all dynamic blocks in the current buffer.
11084 If COMMAND is not given, use `org-update-dblock'."
11085 (let ((cmd (or command 'org-update-dblock)))
11086 (save-excursion
11087 (goto-char (point-min))
11088 (while (re-search-forward org-dblock-start-re nil t)
11089 (goto-char (match-beginning 0))
11090 (save-excursion
11091 (condition-case nil
11092 (funcall cmd)
11093 (error (message "Error during update of dynamic block"))))
11094 (unless (re-search-forward org-dblock-end-re nil t)
11095 (error "Dynamic block not terminated"))))))
11097 (defun org-dblock-update (&optional arg)
11098 "User command for updating dynamic blocks.
11099 Update the dynamic block at point. With prefix ARG, update all dynamic
11100 blocks in the buffer."
11101 (interactive "P")
11102 (if arg
11103 (org-update-all-dblocks)
11104 (or (looking-at org-dblock-start-re)
11105 (org-beginning-of-dblock))
11106 (org-update-dblock)))
11108 (defun org-update-dblock ()
11109 "Update the dynamic block at point.
11110 This means to empty the block, parse for parameters and then call
11111 the correct writing function."
11112 (interactive)
11113 (save-window-excursion
11114 (let* ((pos (point))
11115 (line (org-current-line))
11116 (params (org-prepare-dblock))
11117 (name (plist-get params :name))
11118 (indent (plist-get params :indentation-column))
11119 (cmd (intern (concat "org-dblock-write:" name))))
11120 (message "Updating dynamic block `%s' at line %d..." name line)
11121 (funcall cmd params)
11122 (message "Updating dynamic block `%s' at line %d...done" name line)
11123 (goto-char pos)
11124 (when (and indent (> indent 0))
11125 (setq indent (make-string indent ?\ ))
11126 (save-excursion
11127 (org-beginning-of-dblock)
11128 (forward-line 1)
11129 (while (not (looking-at org-dblock-end-re))
11130 (insert indent)
11131 (beginning-of-line 2))
11132 (when (looking-at org-dblock-end-re)
11133 (and (looking-at "[ \t]+")
11134 (replace-match ""))
11135 (insert indent)))))))
11137 (defun org-beginning-of-dblock ()
11138 "Find the beginning of the dynamic block at point.
11139 Error if there is no such block at point."
11140 (let ((pos (point))
11141 beg)
11142 (end-of-line 1)
11143 (if (and (re-search-backward org-dblock-start-re nil t)
11144 (setq beg (match-beginning 0))
11145 (re-search-forward org-dblock-end-re nil t)
11146 (> (match-end 0) pos))
11147 (goto-char beg)
11148 (goto-char pos)
11149 (error "Not in a dynamic block"))))
11151 ;;;###autoload
11152 (defun org-update-all-dblocks ()
11153 "Update all dynamic blocks in the buffer.
11154 This function can be used in a hook."
11155 (interactive)
11156 (when (derived-mode-p 'org-mode)
11157 (org-map-dblocks 'org-update-dblock)))
11160 ;;;; Completion
11162 (defconst org-additional-option-like-keywords
11163 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11164 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11165 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11166 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11167 "BEGIN:" "END:"
11168 "ORGTBL" "TBLFM:" "TBLNAME:"
11169 "BEGIN_EXAMPLE" "END_EXAMPLE"
11170 "BEGIN_QUOTE" "END_QUOTE"
11171 "BEGIN_VERSE" "END_VERSE"
11172 "BEGIN_CENTER" "END_CENTER"
11173 "BEGIN_SRC" "END_SRC"
11174 "BEGIN_RESULT" "END_RESULT"
11175 "NAME:" "RESULTS:"
11176 "HEADER:" "HEADERS:"
11177 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11178 "CAPTION:" "LABEL:"
11179 "SETUPFILE:"
11180 "INCLUDE:"
11181 "BIND:"
11182 "MACRO:"))
11184 (defcustom org-structure-template-alist
11186 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11187 "<src lang=\"?\">\n\n</src>")
11188 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11189 "<example>\n?\n</example>")
11190 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11191 "<quote>\n?\n</quote>")
11192 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11193 "<verse>\n?\n</verse>")
11194 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11195 "<center>\n?\n</center>")
11196 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11197 "<literal style=\"latex\">\n?\n</literal>")
11198 ("L" "#+LaTeX: "
11199 "<literal style=\"latex\">?</literal>")
11200 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11201 "<literal style=\"html\">\n?\n</literal>")
11202 ("H" "#+HTML: "
11203 "<literal style=\"html\">?</literal>")
11204 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11205 ("A" "#+ASCII: ")
11206 ("i" "#+INDEX: ?"
11207 "#+INDEX: ?")
11208 ("I" "#+INCLUDE %file ?"
11209 "<include file=%file markup=\"?\">")
11211 "Structure completion elements.
11212 This is a list of abbreviation keys and values. The value gets inserted
11213 if you type `<' followed by the key and then press the completion key,
11214 usually `M-TAB'. %file will be replaced by a file name after prompting
11215 for the file using completion. The cursor will be placed at the position
11216 of the `?` in the template.
11217 There are two templates for each key, the first uses the original Org syntax,
11218 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11219 the default when the /org-mtags.el/ module has been loaded. See also the
11220 variable `org-mtags-prefer-muse-templates'."
11221 :group 'org-completion
11222 :type '(repeat
11223 (string :tag "Key")
11224 (string :tag "Template")
11225 (string :tag "Muse Template")))
11227 (defun org-try-structure-completion ()
11228 "Try to complete a structure template before point.
11229 This looks for strings like \"<e\" on an otherwise empty line and
11230 expands them."
11231 (let ((l (buffer-substring (point-at-bol) (point)))
11233 (when (and (looking-at "[ \t]*$")
11234 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11235 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11236 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11237 (match-beginning 1)) a)
11238 t)))
11240 (defun org-complete-expand-structure-template (start cell)
11241 "Expand a structure template."
11242 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11243 (rpl (nth (if musep 2 1) cell))
11244 (ind ""))
11245 (delete-region start (point))
11246 (when (string-match "\\`#\\+" rpl)
11247 (cond
11248 ((bolp))
11249 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11250 (setq ind (buffer-substring (point-at-bol) (point))))
11251 (t (newline))))
11252 (setq start (point))
11253 (if (string-match "%file" rpl)
11254 (setq rpl (replace-match
11255 (concat
11256 "\""
11257 (save-match-data
11258 (abbreviate-file-name (read-file-name "Include file: ")))
11259 "\"")
11260 t t rpl)))
11261 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11262 (concat "\n" ind)))
11263 (insert rpl)
11264 (if (re-search-backward "\\?" start t) (delete-char 1))))
11266 ;;;; TODO, DEADLINE, Comments
11268 (defun org-toggle-comment ()
11269 "Change the COMMENT state of an entry."
11270 (interactive)
11271 (save-excursion
11272 (org-back-to-heading)
11273 (let (case-fold-search)
11274 (cond
11275 ((looking-at (format org-heading-keyword-regexp-format
11276 org-comment-string))
11277 (goto-char (match-end 1))
11278 (looking-at (concat " +" org-comment-string))
11279 (replace-match "" t t)
11280 (when (eolp) (insert " ")))
11281 ((looking-at org-outline-regexp)
11282 (goto-char (match-end 0))
11283 (insert org-comment-string " "))))))
11285 (defvar org-last-todo-state-is-todo nil
11286 "This is non-nil when the last TODO state change led to a TODO state.
11287 If the last change removed the TODO tag or switched to DONE, then
11288 this is nil.")
11290 (defvar org-setting-tags nil) ; dynamically skipped
11292 (defvar org-todo-setup-filter-hook nil
11293 "Hook for functions that pre-filter todo specs.
11294 Each function takes a todo spec and returns either nil or the spec
11295 transformed into canonical form." )
11297 (defvar org-todo-get-default-hook nil
11298 "Hook for functions that get a default item for todo.
11299 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11300 nil or a string to be used for the todo mark." )
11302 (defvar org-agenda-headline-snapshot-before-repeat)
11304 (defun org-current-effective-time ()
11305 "Return current time adjusted for `org-extend-today-until' variable"
11306 (let* ((ct (org-current-time))
11307 (dct (decode-time ct))
11308 (ct1
11309 (if (and org-use-effective-time
11310 (< (nth 2 dct) org-extend-today-until))
11311 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11312 ct)))
11313 ct1))
11315 (defun org-todo-yesterday (&optional arg)
11316 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11317 (interactive "P")
11318 (if (eq major-mode 'org-agenda-mode)
11319 (apply 'org-agenda-todo-yesterday arg)
11320 (let* ((hour (third (decode-time
11321 (org-current-time))))
11322 (org-extend-today-until (1+ hour)))
11323 (org-todo arg))))
11325 (defun org-todo (&optional arg)
11326 "Change the TODO state of an item.
11327 The state of an item is given by a keyword at the start of the heading,
11328 like
11329 *** TODO Write paper
11330 *** DONE Call mom
11332 The different keywords are specified in the variable `org-todo-keywords'.
11333 By default the available states are \"TODO\" and \"DONE\".
11334 So for this example: when the item starts with TODO, it is changed to DONE.
11335 When it starts with DONE, the DONE is removed. And when neither TODO nor
11336 DONE are present, add TODO at the beginning of the heading.
11338 With \\[universal-argument] prefix arg, use completion to determine the new \
11339 state.
11340 With numeric prefix arg, switch to that state.
11341 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11342 keywords (nextset).
11343 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11344 With a numeric prefix arg of 0, inhibit note taking for the change.
11346 For calling through lisp, arg is also interpreted in the following way:
11347 'none -> empty state
11348 \"\"(empty string) -> switch to empty state
11349 'done -> switch to DONE
11350 'nextset -> switch to the next set of keywords
11351 'previousset -> switch to the previous set of keywords
11352 \"WAITING\" -> switch to the specified keyword, but only if it
11353 really is a member of `org-todo-keywords'."
11354 (interactive "P")
11355 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11356 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11357 'region-start-level 'region))
11358 org-loop-over-headlines-in-active-region)
11359 (org-map-entries
11360 `(org-todo ,arg)
11361 org-loop-over-headlines-in-active-region
11362 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11363 (if (equal arg '(16)) (setq arg 'nextset))
11364 (let ((org-blocker-hook org-blocker-hook)
11365 (case-fold-search nil))
11366 (when (equal arg '(64))
11367 (setq arg nil org-blocker-hook nil))
11368 (when (and org-blocker-hook
11369 (or org-inhibit-blocking
11370 (org-entry-get nil "NOBLOCKING")))
11371 (setq org-blocker-hook nil))
11372 (save-excursion
11373 (catch 'exit
11374 (org-back-to-heading t)
11375 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11376 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11377 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11378 (let* ((match-data (match-data))
11379 (startpos (point-at-bol))
11380 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11381 (org-log-done org-log-done)
11382 (org-log-repeat org-log-repeat)
11383 (org-todo-log-states org-todo-log-states)
11384 (org-inhibit-logging
11385 (if (equal arg 0)
11386 (progn (setq arg nil) 'note) org-inhibit-logging))
11387 (this (match-string 1))
11388 (hl-pos (match-beginning 0))
11389 (head (org-get-todo-sequence-head this))
11390 (ass (assoc head org-todo-kwd-alist))
11391 (interpret (nth 1 ass))
11392 (done-word (nth 3 ass))
11393 (final-done-word (nth 4 ass))
11394 (org-last-state (or this ""))
11395 (completion-ignore-case t)
11396 (member (member this org-todo-keywords-1))
11397 (tail (cdr member))
11398 (org-state (cond
11399 ((and org-todo-key-trigger
11400 (or (and (equal arg '(4))
11401 (eq org-use-fast-todo-selection 'prefix))
11402 (and (not arg) org-use-fast-todo-selection
11403 (not (eq org-use-fast-todo-selection
11404 'prefix)))))
11405 ;; Use fast selection
11406 (org-fast-todo-selection))
11407 ((and (equal arg '(4))
11408 (or (not org-use-fast-todo-selection)
11409 (not org-todo-key-trigger)))
11410 ;; Read a state with completion
11411 (org-icompleting-read
11412 "State: " (mapcar (lambda(x) (list x))
11413 org-todo-keywords-1)
11414 nil t))
11415 ((eq arg 'right)
11416 (if this
11417 (if tail (car tail) nil)
11418 (car org-todo-keywords-1)))
11419 ((eq arg 'left)
11420 (if (equal member org-todo-keywords-1)
11422 (if this
11423 (nth (- (length org-todo-keywords-1)
11424 (length tail) 2)
11425 org-todo-keywords-1)
11426 (org-last org-todo-keywords-1))))
11427 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11428 (setq arg nil))) ; hack to fall back to cycling
11429 (arg
11430 ;; user or caller requests a specific state
11431 (cond
11432 ((equal arg "") nil)
11433 ((eq arg 'none) nil)
11434 ((eq arg 'done) (or done-word (car org-done-keywords)))
11435 ((eq arg 'nextset)
11436 (or (car (cdr (member head org-todo-heads)))
11437 (car org-todo-heads)))
11438 ((eq arg 'previousset)
11439 (let ((org-todo-heads (reverse org-todo-heads)))
11440 (or (car (cdr (member head org-todo-heads)))
11441 (car org-todo-heads))))
11442 ((car (member arg org-todo-keywords-1)))
11443 ((stringp arg)
11444 (error "State `%s' not valid in this file" arg))
11445 ((nth (1- (prefix-numeric-value arg))
11446 org-todo-keywords-1))))
11447 ((null member) (or head (car org-todo-keywords-1)))
11448 ((equal this final-done-word) nil) ;; -> make empty
11449 ((null tail) nil) ;; -> first entry
11450 ((memq interpret '(type priority))
11451 (if (eq this-command last-command)
11452 (car tail)
11453 (if (> (length tail) 0)
11454 (or done-word (car org-done-keywords))
11455 nil)))
11457 (car tail))))
11458 (org-state (or
11459 (run-hook-with-args-until-success
11460 'org-todo-get-default-hook org-state org-last-state)
11461 org-state))
11462 (next (if org-state (concat " " org-state " ") " "))
11463 (change-plist (list :type 'todo-state-change :from this :to org-state
11464 :position startpos))
11465 dolog now-done-p)
11466 (when org-blocker-hook
11467 (setq org-last-todo-state-is-todo
11468 (not (member this org-done-keywords)))
11469 (unless (save-excursion
11470 (save-match-data
11471 (org-with-wide-buffer
11472 (run-hook-with-args-until-failure
11473 'org-blocker-hook change-plist))))
11474 (if (org-called-interactively-p 'interactive)
11475 (error "TODO state change from %s to %s blocked" this org-state)
11476 ;; fail silently
11477 (message "TODO state change from %s to %s blocked" this org-state)
11478 (throw 'exit nil))))
11479 (store-match-data match-data)
11480 (replace-match next t t)
11481 (unless (pos-visible-in-window-p hl-pos)
11482 (message "TODO state changed to %s" (org-trim next)))
11483 (unless head
11484 (setq head (org-get-todo-sequence-head org-state)
11485 ass (assoc head org-todo-kwd-alist)
11486 interpret (nth 1 ass)
11487 done-word (nth 3 ass)
11488 final-done-word (nth 4 ass)))
11489 (when (memq arg '(nextset previousset))
11490 (message "Keyword-Set %d/%d: %s"
11491 (- (length org-todo-sets) -1
11492 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11493 (length org-todo-sets)
11494 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11495 (setq org-last-todo-state-is-todo
11496 (not (member org-state org-done-keywords)))
11497 (setq now-done-p (and (member org-state org-done-keywords)
11498 (not (member this org-done-keywords))))
11499 (and logging (org-local-logging logging))
11500 (when (and (or org-todo-log-states org-log-done)
11501 (not (eq org-inhibit-logging t))
11502 (not (memq arg '(nextset previousset))))
11503 ;; we need to look at recording a time and note
11504 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11505 (nth 2 (assoc this org-todo-log-states))))
11506 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11507 (setq dolog 'time))
11508 (when (and org-state
11509 (member org-state org-not-done-keywords)
11510 (not (member this org-not-done-keywords)))
11511 ;; This is now a todo state and was not one before
11512 ;; If there was a CLOSED time stamp, get rid of it.
11513 (org-add-planning-info nil nil 'closed))
11514 (when (and now-done-p org-log-done)
11515 ;; It is now done, and it was not done before
11516 (org-add-planning-info 'closed (org-current-effective-time))
11517 (if (and (not dolog) (eq 'note org-log-done))
11518 (org-add-log-setup 'done org-state this 'findpos 'note)))
11519 (when (and org-state dolog)
11520 ;; This is a non-nil state, and we need to log it
11521 (org-add-log-setup 'state org-state this 'findpos dolog)))
11522 ;; Fixup tag positioning
11523 (org-todo-trigger-tag-changes org-state)
11524 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11525 (when org-provide-todo-statistics
11526 (org-update-parent-todo-statistics))
11527 (run-hooks 'org-after-todo-state-change-hook)
11528 (if (and arg (not (member org-state org-done-keywords)))
11529 (setq head (org-get-todo-sequence-head org-state)))
11530 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11531 ;; Do we need to trigger a repeat?
11532 (when now-done-p
11533 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11534 ;; This is for the agenda, take a snapshot of the headline.
11535 (save-match-data
11536 (setq org-agenda-headline-snapshot-before-repeat
11537 (org-get-heading))))
11538 (org-auto-repeat-maybe org-state))
11539 ;; Fixup cursor location if close to the keyword
11540 (if (and (outline-on-heading-p)
11541 (not (bolp))
11542 (save-excursion (beginning-of-line 1)
11543 (looking-at org-todo-line-regexp))
11544 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11545 (progn
11546 (goto-char (or (match-end 2) (match-end 1)))
11547 (and (looking-at " ") (just-one-space))))
11548 (when org-trigger-hook
11549 (save-excursion
11550 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11552 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11553 "Block turning an entry into a TODO, using the hierarchy.
11554 This checks whether the current task should be blocked from state
11555 changes. Such blocking occurs when:
11557 1. The task has children which are not all in a completed state.
11559 2. A task has a parent with the property :ORDERED:, and there
11560 are siblings prior to the current task with incomplete
11561 status.
11563 3. The parent of the task is blocked because it has siblings that should
11564 be done first, or is child of a block grandparent TODO entry."
11566 (if (not org-enforce-todo-dependencies)
11567 t ; if locally turned off don't block
11568 (catch 'dont-block
11569 ;; If this is not a todo state change, or if this entry is already DONE,
11570 ;; do not block
11571 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11572 (member (plist-get change-plist :from)
11573 (cons 'done org-done-keywords))
11574 (member (plist-get change-plist :to)
11575 (cons 'todo org-not-done-keywords))
11576 (not (plist-get change-plist :to)))
11577 (throw 'dont-block t))
11578 ;; If this task has children, and any are undone, it's blocked
11579 (save-excursion
11580 (org-back-to-heading t)
11581 (let ((this-level (funcall outline-level)))
11582 (outline-next-heading)
11583 (let ((child-level (funcall outline-level)))
11584 (while (and (not (eobp))
11585 (> child-level this-level))
11586 ;; this todo has children, check whether they are all
11587 ;; completed
11588 (if (and (not (org-entry-is-done-p))
11589 (org-entry-is-todo-p))
11590 (throw 'dont-block nil))
11591 (outline-next-heading)
11592 (setq child-level (funcall outline-level))))))
11593 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11594 ;; any previous siblings are undone, it's blocked
11595 (save-excursion
11596 (org-back-to-heading t)
11597 (let* ((pos (point))
11598 (parent-pos (and (org-up-heading-safe) (point))))
11599 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11600 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11601 (forward-line 1)
11602 (re-search-forward org-not-done-heading-regexp pos t))
11603 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11604 ;; Search further up the hierarchy, to see if an ancestor is blocked
11605 (while t
11606 (goto-char parent-pos)
11607 (if (not (looking-at org-not-done-heading-regexp))
11608 (throw 'dont-block t)) ; do not block, parent is not a TODO
11609 (setq pos (point))
11610 (setq parent-pos (and (org-up-heading-safe) (point)))
11611 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11612 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11613 (forward-line 1)
11614 (re-search-forward org-not-done-heading-regexp pos t))
11615 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11617 (defcustom org-track-ordered-property-with-tag nil
11618 "Should the ORDERED property also be shown as a tag?
11619 The ORDERED property decides if an entry should require subtasks to be
11620 completed in sequence. Since a property is not very visible, setting
11621 this option means that toggling the ORDERED property with the command
11622 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11623 not relevant for the behavior, but it makes things more visible.
11625 Note that toggling the tag with tags commands will not change the property
11626 and therefore not influence behavior!
11628 This can be t, meaning the tag ORDERED should be used, It can also be a
11629 string to select a different tag for this task."
11630 :group 'org-todo
11631 :type '(choice
11632 (const :tag "No tracking" nil)
11633 (const :tag "Track with ORDERED tag" t)
11634 (string :tag "Use other tag")))
11636 (defun org-toggle-ordered-property ()
11637 "Toggle the ORDERED property of the current entry.
11638 For better visibility, you can track the value of this property with a tag.
11639 See variable `org-track-ordered-property-with-tag'."
11640 (interactive)
11641 (let* ((t1 org-track-ordered-property-with-tag)
11642 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11643 (save-excursion
11644 (org-back-to-heading)
11645 (if (org-entry-get nil "ORDERED")
11646 (progn
11647 (org-delete-property "ORDERED")
11648 (and tag (org-toggle-tag tag 'off))
11649 (message "Subtasks can be completed in arbitrary order"))
11650 (org-entry-put nil "ORDERED" "t")
11651 (and tag (org-toggle-tag tag 'on))
11652 (message "Subtasks must be completed in sequence")))))
11654 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11655 (defun org-block-todo-from-checkboxes (change-plist)
11656 "Block turning an entry into a TODO, using checkboxes.
11657 This checks whether the current task should be blocked from state
11658 changes because there are unchecked boxes in this entry."
11659 (if (not org-enforce-todo-checkbox-dependencies)
11660 t ; if locally turned off don't block
11661 (catch 'dont-block
11662 ;; If this is not a todo state change, or if this entry is already DONE,
11663 ;; do not block
11664 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11665 (member (plist-get change-plist :from)
11666 (cons 'done org-done-keywords))
11667 (member (plist-get change-plist :to)
11668 (cons 'todo org-not-done-keywords))
11669 (not (plist-get change-plist :to)))
11670 (throw 'dont-block t))
11671 ;; If this task has checkboxes that are not checked, it's blocked
11672 (save-excursion
11673 (org-back-to-heading t)
11674 (let ((beg (point)) end)
11675 (outline-next-heading)
11676 (setq end (point))
11677 (goto-char beg)
11678 (if (org-list-search-forward
11679 (concat (org-item-beginning-re)
11680 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11681 "\\[[- ]\\]")
11682 end t)
11683 (progn
11684 (if (boundp 'org-blocked-by-checkboxes)
11685 (setq org-blocked-by-checkboxes t))
11686 (throw 'dont-block nil)))))
11687 t))) ; do not block
11689 (defun org-entry-blocked-p ()
11690 "Is the current entry blocked?"
11691 (if (org-entry-get nil "NOBLOCKING")
11692 nil ;; Never block this entry
11693 (not
11694 (run-hook-with-args-until-failure
11695 'org-blocker-hook
11696 (list :type 'todo-state-change
11697 :position (point)
11698 :from 'todo
11699 :to 'done)))))
11701 (defun org-update-statistics-cookies (all)
11702 "Update the statistics cookie, either from TODO or from checkboxes.
11703 This should be called with the cursor in a line with a statistics cookie."
11704 (interactive "P")
11705 (if all
11706 (progn
11707 (org-update-checkbox-count 'all)
11708 (org-map-entries 'org-update-parent-todo-statistics))
11709 (if (not (org-at-heading-p))
11710 (org-update-checkbox-count)
11711 (let ((pos (move-marker (make-marker) (point)))
11712 end l1 l2)
11713 (ignore-errors (org-back-to-heading t))
11714 (if (not (org-at-heading-p))
11715 (org-update-checkbox-count)
11716 (setq l1 (org-outline-level))
11717 (setq end (save-excursion
11718 (outline-next-heading)
11719 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11720 (point)))
11721 (if (and (save-excursion
11722 (re-search-forward
11723 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11724 (not (save-excursion (re-search-forward
11725 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11726 (org-update-checkbox-count)
11727 (if (and l2 (> l2 l1))
11728 (progn
11729 (goto-char end)
11730 (org-update-parent-todo-statistics))
11731 (goto-char pos)
11732 (beginning-of-line 1)
11733 (while (re-search-forward
11734 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11735 (point-at-eol) t)
11736 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11737 (goto-char pos)
11738 (move-marker pos nil)))))
11740 (defvar org-entry-property-inherited-from) ;; defined below
11741 (defun org-update-parent-todo-statistics ()
11742 "Update any statistics cookie in the parent of the current headline.
11743 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11744 the entire subtree and this will travel up the hierarchy and update
11745 statistics everywhere."
11746 (let* ((prop (save-excursion (org-up-heading-safe)
11747 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11748 (recursive (or (not org-hierarchical-todo-statistics)
11749 (and prop (string-match "\\<recursive\\>" prop))))
11750 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11752 (first t)
11753 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11754 level ltoggle l1 new ndel
11755 (cnt-all 0) (cnt-done 0) is-percent kwd
11756 checkbox-beg ov ovs ove cookie-present)
11757 (catch 'exit
11758 (save-excursion
11759 (beginning-of-line 1)
11760 (setq ltoggle (funcall outline-level))
11761 ;; Three situations are to consider:
11763 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11764 ;; to the top-level ancestor on the headline;
11766 ;; 2. If parent has "recursive" property, repeat up to the
11767 ;; headline setting that property, taking inheritance into
11768 ;; account;
11770 ;; 3. Else, move up to direct parent and proceed only once.
11771 (while (and (setq level (org-up-heading-safe))
11772 (or recursive first)
11773 (>= (point) lim))
11774 (setq first nil cookie-present nil)
11775 (unless (and level
11776 (not (string-match
11777 "\\<checkbox\\>"
11778 (downcase (or (org-entry-get nil "COOKIE_DATA")
11779 "")))))
11780 (throw 'exit nil))
11781 (while (re-search-forward box-re (point-at-eol) t)
11782 (setq cnt-all 0 cnt-done 0 cookie-present t)
11783 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11784 (save-match-data
11785 (unless (outline-next-heading) (throw 'exit nil))
11786 (while (and (looking-at org-complex-heading-regexp)
11787 (> (setq l1 (length (match-string 1))) level))
11788 (setq kwd (and (or recursive (= l1 ltoggle))
11789 (match-string 2)))
11790 (if (or (eq org-provide-todo-statistics 'all-headlines)
11791 (and (listp org-provide-todo-statistics)
11792 (or (member kwd org-provide-todo-statistics)
11793 (member kwd org-done-keywords))))
11794 (setq cnt-all (1+ cnt-all))
11795 (if (eq org-provide-todo-statistics t)
11796 (and kwd (setq cnt-all (1+ cnt-all)))))
11797 (and (member kwd org-done-keywords)
11798 (setq cnt-done (1+ cnt-done)))
11799 (outline-next-heading)))
11800 (setq new
11801 (if is-percent
11802 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11803 (format "[%d/%d]" cnt-done cnt-all))
11804 ndel (- (match-end 0) checkbox-beg))
11805 ;; handle overlays when updating cookie from column view
11806 (when (setq ov (car (overlays-at checkbox-beg)))
11807 (setq ovs (overlay-start ov) ove (overlay-end ov))
11808 (delete-overlay ov))
11809 (goto-char checkbox-beg)
11810 (insert new)
11811 (delete-region (point) (+ (point) ndel))
11812 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11813 (when ov (move-overlay ov ovs ove)))
11814 (when cookie-present
11815 (run-hook-with-args 'org-after-todo-statistics-hook
11816 cnt-done (- cnt-all cnt-done))))))
11817 (run-hooks 'org-todo-statistics-hook)))
11819 (defvar org-after-todo-statistics-hook nil
11820 "Hook that is called after a TODO statistics cookie has been updated.
11821 Each function is called with two arguments: the number of not-done entries
11822 and the number of done entries.
11824 For example, the following function, when added to this hook, will switch
11825 an entry to DONE when all children are done, and back to TODO when new
11826 entries are set to a TODO status. Note that this hook is only called
11827 when there is a statistics cookie in the headline!
11829 (defun org-summary-todo (n-done n-not-done)
11830 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11831 (let (org-log-done org-log-states) ; turn off logging
11832 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11835 (defvar org-todo-statistics-hook nil
11836 "Hook that is run whenever Org thinks TODO statistics should be updated.
11837 This hook runs even if there is no statistics cookie present, in which case
11838 `org-after-todo-statistics-hook' would not run.")
11840 (defun org-todo-trigger-tag-changes (state)
11841 "Apply the changes defined in `org-todo-state-tags-triggers'."
11842 (let ((l org-todo-state-tags-triggers)
11843 changes)
11844 (when (or (not state) (equal state ""))
11845 (setq changes (append changes (cdr (assoc "" l)))))
11846 (when (and (stringp state) (> (length state) 0))
11847 (setq changes (append changes (cdr (assoc state l)))))
11848 (when (member state org-not-done-keywords)
11849 (setq changes (append changes (cdr (assoc 'todo l)))))
11850 (when (member state org-done-keywords)
11851 (setq changes (append changes (cdr (assoc 'done l)))))
11852 (dolist (c changes)
11853 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11855 (defun org-local-logging (value)
11856 "Get logging settings from a property VALUE."
11857 (let* (words w a)
11858 ;; directly set the variables, they are already local.
11859 (setq org-log-done nil
11860 org-log-repeat nil
11861 org-todo-log-states nil)
11862 (setq words (org-split-string value))
11863 (while (setq w (pop words))
11864 (cond
11865 ((setq a (assoc w org-startup-options))
11866 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11867 (set (nth 1 a) (nth 2 a))))
11868 ((setq a (org-extract-log-state-settings w))
11869 (and (member (car a) org-todo-keywords-1)
11870 (push a org-todo-log-states)))))))
11872 (defun org-get-todo-sequence-head (kwd)
11873 "Return the head of the TODO sequence to which KWD belongs.
11874 If KWD is not set, check if there is a text property remembering the
11875 right sequence."
11876 (let (p)
11877 (cond
11878 ((not kwd)
11879 (or (get-text-property (point-at-bol) 'org-todo-head)
11880 (progn
11881 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11882 nil (point-at-eol)))
11883 (get-text-property p 'org-todo-head))))
11884 ((not (member kwd org-todo-keywords-1))
11885 (car org-todo-keywords-1))
11886 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11888 (defun org-fast-todo-selection ()
11889 "Fast TODO keyword selection with single keys.
11890 Returns the new TODO keyword, or nil if no state change should occur."
11891 (let* ((fulltable org-todo-key-alist)
11892 (done-keywords org-done-keywords) ;; needed for the faces.
11893 (maxlen (apply 'max (mapcar
11894 (lambda (x)
11895 (if (stringp (car x)) (string-width (car x)) 0))
11896 fulltable)))
11897 (expert nil)
11898 (fwidth (+ maxlen 3 1 3))
11899 (ncol (/ (- (window-width) 4) fwidth))
11900 tg cnt e c tbl
11901 groups ingroup)
11902 (save-excursion
11903 (save-window-excursion
11904 (if expert
11905 (set-buffer (get-buffer-create " *Org todo*"))
11906 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11907 (erase-buffer)
11908 (org-set-local 'org-done-keywords done-keywords)
11909 (setq tbl fulltable cnt 0)
11910 (while (setq e (pop tbl))
11911 (cond
11912 ((equal e '(:startgroup))
11913 (push '() groups) (setq ingroup t)
11914 (when (not (= cnt 0))
11915 (setq cnt 0)
11916 (insert "\n"))
11917 (insert "{ "))
11918 ((equal e '(:endgroup))
11919 (setq ingroup nil cnt 0)
11920 (insert "}\n"))
11921 ((equal e '(:newline))
11922 (when (not (= cnt 0))
11923 (setq cnt 0)
11924 (insert "\n")
11925 (setq e (car tbl))
11926 (while (equal (car tbl) '(:newline))
11927 (insert "\n")
11928 (setq tbl (cdr tbl)))))
11930 (setq tg (car e) c (cdr e))
11931 (if ingroup (push tg (car groups)))
11932 (setq tg (org-add-props tg nil 'face
11933 (org-get-todo-face tg)))
11934 (if (and (= cnt 0) (not ingroup)) (insert " "))
11935 (insert "[" c "] " tg (make-string
11936 (- fwidth 4 (length tg)) ?\ ))
11937 (when (= (setq cnt (1+ cnt)) ncol)
11938 (insert "\n")
11939 (if ingroup (insert " "))
11940 (setq cnt 0)))))
11941 (insert "\n")
11942 (goto-char (point-min))
11943 (if (not expert) (org-fit-window-to-buffer))
11944 (message "[a-z..]:Set [SPC]:clear")
11945 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11946 (cond
11947 ((or (= c ?\C-g)
11948 (and (= c ?q) (not (rassoc c fulltable))))
11949 (setq quit-flag t))
11950 ((= c ?\ ) nil)
11951 ((setq e (rassoc c fulltable) tg (car e))
11953 (t (setq quit-flag t)))))))
11955 (defun org-entry-is-todo-p ()
11956 (member (org-get-todo-state) org-not-done-keywords))
11958 (defun org-entry-is-done-p ()
11959 (member (org-get-todo-state) org-done-keywords))
11961 (defun org-get-todo-state ()
11962 (save-excursion
11963 (org-back-to-heading t)
11964 (and (looking-at org-todo-line-regexp)
11965 (match-end 2)
11966 (match-string 2))))
11968 (defun org-at-date-range-p (&optional inactive-ok)
11969 "Is the cursor inside a date range?"
11970 (interactive)
11971 (save-excursion
11972 (catch 'exit
11973 (let ((pos (point)))
11974 (skip-chars-backward "^[<\r\n")
11975 (skip-chars-backward "<[")
11976 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11977 (>= (match-end 0) pos)
11978 (throw 'exit t))
11979 (skip-chars-backward "^<[\r\n")
11980 (skip-chars-backward "<[")
11981 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11982 (>= (match-end 0) pos)
11983 (throw 'exit t)))
11984 nil)))
11986 (defun org-get-repeat (&optional tagline)
11987 "Check if there is a deadline/schedule with repeater in this entry."
11988 (save-match-data
11989 (save-excursion
11990 (org-back-to-heading t)
11991 (and (re-search-forward (if tagline
11992 (concat tagline "\\s-*" org-repeat-re)
11993 org-repeat-re)
11994 (org-entry-end-position) t)
11995 (match-string-no-properties 1)))))
11997 (defvar org-last-changed-timestamp)
11998 (defvar org-last-inserted-timestamp)
11999 (defvar org-log-post-message)
12000 (defvar org-log-note-purpose)
12001 (defvar org-log-note-how)
12002 (defvar org-log-note-extra)
12003 (defun org-auto-repeat-maybe (done-word)
12004 "Check if the current headline contains a repeated deadline/schedule.
12005 If yes, set TODO state back to what it was and change the base date
12006 of repeating deadline/scheduled time stamps to new date.
12007 This function is run automatically after each state change to a DONE state."
12008 ;; last-state is dynamically scoped into this function
12009 (let* ((repeat (org-get-repeat))
12010 (aa (assoc org-last-state org-todo-kwd-alist))
12011 (interpret (nth 1 aa))
12012 (head (nth 2 aa))
12013 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12014 (msg "Entry repeats: ")
12015 (org-log-done nil)
12016 (org-todo-log-states nil)
12017 re type n what ts time to-state)
12018 (when repeat
12019 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12020 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12021 org-todo-repeat-to-state))
12022 (unless (and to-state (member to-state org-todo-keywords-1))
12023 (setq to-state (if (eq interpret 'type) org-last-state head)))
12024 (org-todo to-state)
12025 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12026 (org-entry-put nil "LAST_REPEAT" (format-time-string
12027 (org-time-stamp-format t t))))
12028 (when org-log-repeat
12029 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12030 (memq 'org-add-log-note post-command-hook))
12031 ;; OK, we are already setup for some record
12032 (if (eq org-log-repeat 'note)
12033 ;; make sure we take a note, not only a time stamp
12034 (setq org-log-note-how 'note))
12035 ;; Set up for taking a record
12036 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12037 org-last-state
12038 'findpos org-log-repeat)))
12039 (org-back-to-heading t)
12040 (org-add-planning-info nil nil 'closed)
12041 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12042 org-deadline-time-regexp "\\)\\|\\("
12043 org-ts-regexp "\\)"))
12044 (while (re-search-forward
12045 re (save-excursion (outline-next-heading) (point)) t)
12046 (setq type (if (match-end 1) org-scheduled-string
12047 (if (match-end 3) org-deadline-string "Plain:"))
12048 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12049 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12050 (setq n (string-to-number (match-string 2 ts))
12051 what (match-string 3 ts))
12052 (if (equal what "w") (setq n (* n 7) what "d"))
12053 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12054 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12055 ;; Preparation, see if we need to modify the start date for the change
12056 (when (match-end 1)
12057 (setq time (save-match-data (org-time-string-to-time ts)))
12058 (cond
12059 ((equal (match-string 1 ts) ".")
12060 ;; Shift starting date to today
12061 (org-timestamp-change
12062 (- (org-today) (time-to-days time))
12063 'day))
12064 ((equal (match-string 1 ts) "+")
12065 (let ((nshiftmax 10) (nshift 0))
12066 (while (or (= nshift 0)
12067 (<= (time-to-days time)
12068 (time-to-days (current-time))))
12069 (when (= (incf nshift) nshiftmax)
12070 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12071 (error "Abort")))
12072 (org-timestamp-change n (cdr (assoc what whata)))
12073 (org-at-timestamp-p t)
12074 (setq ts (match-string 1))
12075 (setq time (save-match-data (org-time-string-to-time ts)))))
12076 (org-timestamp-change (- n) (cdr (assoc what whata)))
12077 ;; rematch, so that we have everything in place for the real shift
12078 (org-at-timestamp-p t)
12079 (setq ts (match-string 1))
12080 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12081 (org-timestamp-change n (cdr (assoc what whata)))
12082 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12083 (setq org-log-post-message msg)
12084 (message "%s" msg))))
12086 (defun org-show-todo-tree (arg)
12087 "Make a compact tree which shows all headlines marked with TODO.
12088 The tree will show the lines where the regexp matches, and all higher
12089 headlines above the match.
12090 With a \\[universal-argument] prefix, prompt for a regexp to match.
12091 With a numeric prefix N, construct a sparse tree for the Nth element
12092 of `org-todo-keywords-1'."
12093 (interactive "P")
12094 (let ((case-fold-search nil)
12095 (kwd-re
12096 (cond ((null arg) org-not-done-regexp)
12097 ((equal arg '(4))
12098 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12099 (mapcar 'list org-todo-keywords-1))))
12100 (concat "\\("
12101 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12102 "\\)\\>")))
12103 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12104 (regexp-quote (nth (1- (prefix-numeric-value arg))
12105 org-todo-keywords-1)))
12106 (t (error "Invalid prefix argument: %s" arg)))))
12107 (message "%d TODO entries found"
12108 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12110 (defun org-deadline (&optional remove time)
12111 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12112 With argument REMOVE, remove any deadline from the item.
12113 With argument TIME, set the deadline at the corresponding date. TIME
12114 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12115 (interactive "P")
12116 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12117 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12118 'region-start-level 'region))
12119 org-loop-over-headlines-in-active-region)
12120 (org-map-entries
12121 `(org-deadline ',remove ,time)
12122 org-loop-over-headlines-in-active-region
12123 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12124 (let* ((old-date (org-entry-get nil "DEADLINE"))
12125 (repeater (and old-date
12126 (string-match
12127 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12128 old-date)
12129 (match-string 1 old-date))))
12130 (if remove
12131 (progn
12132 (when (and old-date org-log-redeadline)
12133 (org-add-log-setup 'deldeadline nil old-date 'findpos
12134 org-log-redeadline))
12135 (org-remove-timestamp-with-keyword org-deadline-string)
12136 (message "Item no longer has a deadline."))
12137 (org-add-planning-info 'deadline time 'closed)
12138 (when (and old-date org-log-redeadline
12139 (not (equal old-date
12140 (substring org-last-inserted-timestamp 1 -1))))
12141 (org-add-log-setup 'redeadline nil old-date 'findpos
12142 org-log-redeadline))
12143 (when repeater
12144 (save-excursion
12145 (org-back-to-heading t)
12146 (when (re-search-forward (concat org-deadline-string " "
12147 org-last-inserted-timestamp)
12148 (save-excursion
12149 (outline-next-heading) (point)) t)
12150 (goto-char (1- (match-end 0)))
12151 (insert " " repeater)
12152 (setq org-last-inserted-timestamp
12153 (concat (substring org-last-inserted-timestamp 0 -1)
12154 " " repeater
12155 (substring org-last-inserted-timestamp -1))))))
12156 (message "Deadline on %s" org-last-inserted-timestamp)))))
12158 (defun org-schedule (&optional remove time)
12159 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12160 With argument REMOVE, remove any scheduling date from the item.
12161 With argument TIME, scheduled at the corresponding date. TIME can
12162 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12163 (interactive "P")
12164 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12165 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12166 'region-start-level 'region))
12167 org-loop-over-headlines-in-active-region)
12168 (org-map-entries
12169 `(org-schedule ',remove ,time)
12170 org-loop-over-headlines-in-active-region
12171 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12172 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12173 (repeater (and old-date
12174 (string-match
12175 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12176 old-date)
12177 (match-string 1 old-date))))
12178 (if remove
12179 (progn
12180 (when (and old-date org-log-reschedule)
12181 (org-add-log-setup 'delschedule nil old-date 'findpos
12182 org-log-reschedule))
12183 (org-remove-timestamp-with-keyword org-scheduled-string)
12184 (message "Item is no longer scheduled."))
12185 (org-add-planning-info 'scheduled time 'closed)
12186 (when (and old-date org-log-reschedule
12187 (not (equal old-date
12188 (substring org-last-inserted-timestamp 1 -1))))
12189 (org-add-log-setup 'reschedule nil old-date 'findpos
12190 org-log-reschedule))
12191 (when repeater
12192 (save-excursion
12193 (org-back-to-heading t)
12194 (when (re-search-forward (concat org-scheduled-string " "
12195 org-last-inserted-timestamp)
12196 (save-excursion
12197 (outline-next-heading) (point)) t)
12198 (goto-char (1- (match-end 0)))
12199 (insert " " repeater)
12200 (setq org-last-inserted-timestamp
12201 (concat (substring org-last-inserted-timestamp 0 -1)
12202 " " repeater
12203 (substring org-last-inserted-timestamp -1))))))
12204 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12206 (defun org-get-scheduled-time (pom &optional inherit)
12207 "Get the scheduled time as a time tuple, of a format suitable
12208 for calling org-schedule with, or if there is no scheduling,
12209 returns nil."
12210 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12211 (when time
12212 (apply 'encode-time (org-parse-time-string time)))))
12214 (defun org-get-deadline-time (pom &optional inherit)
12215 "Get the deadline as a time tuple, of a format suitable for
12216 calling org-deadline with, or if there is no scheduling, returns
12217 nil."
12218 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12219 (when time
12220 (apply 'encode-time (org-parse-time-string time)))))
12222 (defun org-remove-timestamp-with-keyword (keyword)
12223 "Remove all time stamps with KEYWORD in the current entry."
12224 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12225 beg)
12226 (save-excursion
12227 (org-back-to-heading t)
12228 (setq beg (point))
12229 (outline-next-heading)
12230 (while (re-search-backward re beg t)
12231 (replace-match "")
12232 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12233 (equal (char-before) ?\ ))
12234 (backward-delete-char 1)
12235 (if (string-match "^[ \t]*$" (buffer-substring
12236 (point-at-bol) (point-at-eol)))
12237 (delete-region (point-at-bol)
12238 (min (point-max) (1+ (point-at-eol))))))))))
12240 (defun org-add-planning-info (what &optional time &rest remove)
12241 "Insert new timestamp with keyword in the line directly after the headline.
12242 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12243 If non is given, the user is prompted for a date.
12244 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12245 be removed."
12246 (interactive)
12247 (let (org-time-was-given org-end-time-was-given ts
12248 end default-time default-input)
12250 (catch 'exit
12251 (when (and (memq what '(scheduled deadline))
12252 (or (not time)
12253 (and (stringp time)
12254 (string-match "^[-+]+[0-9]" time))))
12255 ;; Try to get a default date/time from existing timestamp
12256 (save-excursion
12257 (org-back-to-heading t)
12258 (setq end (save-excursion (outline-next-heading) (point)))
12259 (when (re-search-forward (if (eq what 'scheduled)
12260 org-scheduled-time-regexp
12261 org-deadline-time-regexp)
12262 end t)
12263 (setq ts (match-string 1)
12264 default-time
12265 (apply 'encode-time (org-parse-time-string ts))
12266 default-input (and ts (org-get-compact-tod ts))))))
12267 (when what
12268 (setq time
12269 (if (stringp time)
12270 ;; This is a string (relative or absolute), set proper date
12271 (apply 'encode-time
12272 (org-read-date-analyze
12273 time default-time (decode-time default-time)))
12274 ;; If necessary, get the time from the user
12275 (or time (org-read-date nil 'to-time nil nil
12276 default-time default-input)))))
12278 (when (and org-insert-labeled-timestamps-at-point
12279 (member what '(scheduled deadline)))
12280 (insert
12281 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12282 (org-insert-time-stamp time org-time-was-given
12283 nil nil nil (list org-end-time-was-given))
12284 (setq what nil))
12285 (save-excursion
12286 (save-restriction
12287 (let (col list elt ts buffer-invisibility-spec)
12288 (org-back-to-heading t)
12289 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12290 (goto-char (match-end 1))
12291 (setq col (current-column))
12292 (goto-char (match-end 0))
12293 (if (eobp) (insert "\n") (forward-char 1))
12294 (when (and (not what)
12295 (not (looking-at
12296 (concat "[ \t]*"
12297 org-keyword-time-not-clock-regexp))))
12298 ;; Nothing to add, nothing to remove...... :-)
12299 (throw 'exit nil))
12300 (if (and (not (looking-at org-outline-regexp))
12301 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12302 "[^\r\n]*"))
12303 (not (equal (match-string 1) org-clock-string)))
12304 (narrow-to-region (match-beginning 0) (match-end 0))
12305 (insert-before-markers "\n")
12306 (backward-char 1)
12307 (narrow-to-region (point) (point))
12308 (and org-adapt-indentation (org-indent-to-column col)))
12309 ;; Check if we have to remove something.
12310 (setq list (cons what remove))
12311 (while list
12312 (setq elt (pop list))
12313 (when (or (and (eq elt 'scheduled)
12314 (re-search-forward org-scheduled-time-regexp nil t))
12315 (and (eq elt 'deadline)
12316 (re-search-forward org-deadline-time-regexp nil t))
12317 (and (eq elt 'closed)
12318 (re-search-forward org-closed-time-regexp nil t)))
12319 (replace-match "")
12320 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12321 (and (looking-at "[ \t]+") (replace-match ""))
12322 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12323 (when what
12324 (insert
12325 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12326 (cond ((eq what 'scheduled) org-scheduled-string)
12327 ((eq what 'deadline) org-deadline-string)
12328 ((eq what 'closed) org-closed-string))
12329 " ")
12330 (setq ts (org-insert-time-stamp
12331 time
12332 (or org-time-was-given
12333 (and (eq what 'closed) org-log-done-with-time))
12334 (eq what 'closed)
12335 nil nil (list org-end-time-was-given)))
12336 (insert
12337 (if (not (or (bolp) (eq (char-before) ?\ )
12338 (memq (char-after) '(32 10))
12339 (eobp))) " " ""))
12340 (end-of-line 1))
12341 (goto-char (point-min))
12342 (widen)
12343 (if (and (looking-at "[ \t]*\n")
12344 (equal (char-before) ?\n))
12345 (delete-region (1- (point)) (point-at-eol)))
12346 ts))))))
12348 (defvar org-log-note-marker (make-marker))
12349 (defvar org-log-note-purpose nil)
12350 (defvar org-log-note-state nil)
12351 (defvar org-log-note-previous-state nil)
12352 (defvar org-log-note-how nil)
12353 (defvar org-log-note-extra nil)
12354 (defvar org-log-note-window-configuration nil)
12355 (defvar org-log-note-return-to (make-marker))
12356 (defvar org-log-note-effective-time nil
12357 "Remembered current time so that dynamically scoped
12358 `org-extend-today-until' affects tha timestamps in state change
12359 log")
12361 (defvar org-log-post-message nil
12362 "Message to be displayed after a log note has been stored.
12363 The auto-repeater uses this.")
12365 (defun org-add-note ()
12366 "Add a note to the current entry.
12367 This is done in the same way as adding a state change note."
12368 (interactive)
12369 (org-add-log-setup 'note nil nil 'findpos nil))
12371 (defvar org-property-end-re)
12372 (defun org-add-log-setup (&optional purpose state prev-state
12373 findpos how extra)
12374 "Set up the post command hook to take a note.
12375 If this is about to TODO state change, the new state is expected in STATE.
12376 When FINDPOS is non-nil, find the correct position for the note in
12377 the current entry. If not, assume that it can be inserted at point.
12378 HOW is an indicator what kind of note should be created.
12379 EXTRA is additional text that will be inserted into the notes buffer."
12380 (let* ((org-log-into-drawer (org-log-into-drawer))
12381 (drawer (cond ((stringp org-log-into-drawer)
12382 org-log-into-drawer)
12383 (org-log-into-drawer "LOGBOOK")
12384 (t nil))))
12385 (save-restriction
12386 (save-excursion
12387 (when findpos
12388 (org-back-to-heading t)
12389 (narrow-to-region (point) (save-excursion
12390 (outline-next-heading) (point)))
12391 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12392 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12393 "[^\r\n]*\\)?"))
12394 (goto-char (match-end 0))
12395 (cond
12396 (drawer
12397 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12398 nil t)
12399 (progn
12400 (goto-char (match-end 0))
12401 (or org-log-states-order-reversed
12402 (and (re-search-forward org-property-end-re nil t)
12403 (goto-char (1- (match-beginning 0))))))
12404 (insert "\n:" drawer ":\n:END:")
12405 (beginning-of-line 0)
12406 (org-indent-line-function)
12407 (beginning-of-line 2)
12408 (org-indent-line-function)
12409 (end-of-line 0)))
12410 ((and org-log-state-notes-insert-after-drawers
12411 (save-excursion
12412 (forward-line) (looking-at org-drawer-regexp)))
12413 (forward-line)
12414 (while (looking-at org-drawer-regexp)
12415 (goto-char (match-end 0))
12416 (re-search-forward org-property-end-re (point-max) t)
12417 (forward-line))
12418 (forward-line -1)))
12419 (unless org-log-states-order-reversed
12420 (and (= (char-after) ?\n) (forward-char 1))
12421 (org-skip-over-state-notes)
12422 (skip-chars-backward " \t\n\r")))
12423 (move-marker org-log-note-marker (point))
12424 (setq org-log-note-purpose purpose
12425 org-log-note-state state
12426 org-log-note-previous-state prev-state
12427 org-log-note-how how
12428 org-log-note-extra extra
12429 org-log-note-effective-time (org-current-effective-time))
12430 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12432 (defun org-skip-over-state-notes ()
12433 "Skip past the list of State notes in an entry."
12434 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12435 (when (ignore-errors (goto-char (org-in-item-p)))
12436 (let* ((struct (org-list-struct))
12437 (prevs (org-list-prevs-alist struct)))
12438 (while (looking-at "[ \t]*- State")
12439 (goto-char (or (org-list-get-next-item (point) struct prevs)
12440 (org-list-get-item-end (point) struct)))))))
12442 (defun org-add-log-note (&optional purpose)
12443 "Pop up a window for taking a note, and add this note later at point."
12444 (remove-hook 'post-command-hook 'org-add-log-note)
12445 (setq org-log-note-window-configuration (current-window-configuration))
12446 (delete-other-windows)
12447 (move-marker org-log-note-return-to (point))
12448 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12449 (goto-char org-log-note-marker)
12450 (org-switch-to-buffer-other-window "*Org Note*")
12451 (erase-buffer)
12452 (if (memq org-log-note-how '(time state))
12453 (let (current-prefix-arg) (org-store-log-note))
12454 (let ((org-inhibit-startup t)) (org-mode))
12455 (insert (format "# Insert note for %s.
12456 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12457 (cond
12458 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12459 ((eq org-log-note-purpose 'done) "closed todo item")
12460 ((eq org-log-note-purpose 'state)
12461 (format "state change from \"%s\" to \"%s\""
12462 (or org-log-note-previous-state "")
12463 (or org-log-note-state "")))
12464 ((eq org-log-note-purpose 'reschedule)
12465 "rescheduling")
12466 ((eq org-log-note-purpose 'delschedule)
12467 "no longer scheduled")
12468 ((eq org-log-note-purpose 'redeadline)
12469 "changing deadline")
12470 ((eq org-log-note-purpose 'deldeadline)
12471 "removing deadline")
12472 ((eq org-log-note-purpose 'refile)
12473 "refiling")
12474 ((eq org-log-note-purpose 'note)
12475 "this entry")
12476 (t (error "This should not happen")))))
12477 (if org-log-note-extra (insert org-log-note-extra))
12478 (org-set-local 'org-finish-function 'org-store-log-note)
12479 (run-hooks 'org-log-buffer-setup-hook)))
12481 (defvar org-note-abort nil) ; dynamically scoped
12482 (defun org-store-log-note ()
12483 "Finish taking a log note, and insert it to where it belongs."
12484 (let ((txt (buffer-string))
12485 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12486 lines ind bul)
12487 (kill-buffer (current-buffer))
12488 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12489 (setq txt (replace-match "" t t txt)))
12490 (if (string-match "\\s-+\\'" txt)
12491 (setq txt (replace-match "" t t txt)))
12492 (setq lines (org-split-string txt "\n"))
12493 (when (and note (string-match "\\S-" note))
12494 (setq note
12495 (org-replace-escapes
12496 note
12497 (list (cons "%u" (user-login-name))
12498 (cons "%U" user-full-name)
12499 (cons "%t" (format-time-string
12500 (org-time-stamp-format 'long 'inactive)
12501 org-log-note-effective-time))
12502 (cons "%T" (format-time-string
12503 (org-time-stamp-format 'long nil)
12504 org-log-note-effective-time))
12505 (cons "%d" (format-time-string
12506 (org-time-stamp-format nil 'inactive)
12507 org-log-note-effective-time))
12508 (cons "%D" (format-time-string
12509 (org-time-stamp-format nil nil)
12510 org-log-note-effective-time))
12511 (cons "%s" (if org-log-note-state
12512 (concat "\"" org-log-note-state "\"")
12513 ""))
12514 (cons "%S" (if org-log-note-previous-state
12515 (concat "\"" org-log-note-previous-state "\"")
12516 "\"\"")))))
12517 (if lines (setq note (concat note " \\\\")))
12518 (push note lines))
12519 (when (or current-prefix-arg org-note-abort)
12520 (when org-log-into-drawer
12521 (org-remove-empty-drawer-at
12522 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12523 org-log-note-marker))
12524 (setq lines nil))
12525 (when lines
12526 (with-current-buffer (marker-buffer org-log-note-marker)
12527 (save-excursion
12528 (goto-char org-log-note-marker)
12529 (move-marker org-log-note-marker nil)
12530 (end-of-line 1)
12531 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12532 (setq ind (save-excursion
12533 (if (ignore-errors (goto-char (org-in-item-p)))
12534 (let ((struct (org-list-struct)))
12535 (org-list-get-ind
12536 (org-list-get-top-point struct) struct))
12537 (skip-chars-backward " \r\t\n")
12538 (cond
12539 ((and (org-at-heading-p)
12540 org-adapt-indentation)
12541 (1+ (org-current-level)))
12542 ((org-at-heading-p) 0)
12543 (t (org-get-indentation))))))
12544 (setq bul (org-list-bullet-string "-"))
12545 (org-indent-line-to ind)
12546 (insert bul (pop lines))
12547 (let ((ind-body (+ (length bul) ind)))
12548 (while lines
12549 (insert "\n")
12550 (org-indent-line-to ind-body)
12551 (insert (pop lines))))
12552 (message "Note stored")
12553 (org-back-to-heading t)
12554 (org-cycle-hide-drawers 'children)))))
12555 (set-window-configuration org-log-note-window-configuration)
12556 (with-current-buffer (marker-buffer org-log-note-return-to)
12557 (goto-char org-log-note-return-to))
12558 (move-marker org-log-note-return-to nil)
12559 (and org-log-post-message (message "%s" org-log-post-message)))
12561 (defun org-remove-empty-drawer-at (drawer pos)
12562 "Remove an empty drawer DRAWER at position POS.
12563 POS may also be a marker."
12564 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12565 (save-excursion
12566 (save-restriction
12567 (widen)
12568 (goto-char pos)
12569 (if (org-in-regexp
12570 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12571 (replace-match ""))))))
12573 (defun org-sparse-tree (&optional arg)
12574 "Create a sparse tree, prompt for the details.
12575 This command can create sparse trees. You first need to select the type
12576 of match used to create the tree:
12578 t Show all TODO entries.
12579 T Show entries with a specific TODO keyword.
12580 m Show entries selected by a tags/property match.
12581 p Enter a property name and its value (both with completion on existing
12582 names/values) and show entries with that property.
12583 r Show entries matching a regular expression (`/' can be used as well)
12584 d Show deadlines due within `org-deadline-warning-days'.
12585 b Show deadlines and scheduled items before a date.
12586 a Show deadlines and scheduled items after a date."
12587 (interactive "P")
12588 (let (ans kwd value)
12589 (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")
12590 (setq ans (read-char-exclusive))
12591 (cond
12592 ((equal ans ?d)
12593 (call-interactively 'org-check-deadlines))
12594 ((equal ans ?b)
12595 (call-interactively 'org-check-before-date))
12596 ((equal ans ?a)
12597 (call-interactively 'org-check-after-date))
12598 ((equal ans ?D)
12599 (call-interactively 'org-check-dates-range))
12600 ((equal ans ?t)
12601 (org-show-todo-tree nil))
12602 ((equal ans ?T)
12603 (org-show-todo-tree '(4)))
12604 ((member ans '(?T ?m))
12605 (call-interactively 'org-match-sparse-tree))
12606 ((member ans '(?p ?P))
12607 (setq kwd (org-icompleting-read "Property: "
12608 (mapcar 'list (org-buffer-property-keys))))
12609 (setq value (org-icompleting-read "Value: "
12610 (mapcar 'list (org-property-values kwd))))
12611 (unless (string-match "\\`{.*}\\'" value)
12612 (setq value (concat "\"" value "\"")))
12613 (org-match-sparse-tree arg (concat kwd "=" value)))
12614 ((member ans '(?r ?R ?/))
12615 (call-interactively 'org-occur))
12616 (t (error "No such sparse tree command \"%c\"" ans)))))
12618 (defvar org-occur-highlights nil
12619 "List of overlays used for occur matches.")
12620 (make-variable-buffer-local 'org-occur-highlights)
12621 (defvar org-occur-parameters nil
12622 "Parameters of the active org-occur calls.
12623 This is a list, each call to org-occur pushes as cons cell,
12624 containing the regular expression and the callback, onto the list.
12625 The list can contain several entries if `org-occur' has been called
12626 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12627 will only contain one set of parameters. When the highlights are
12628 removed (for example with `C-c C-c', or with the next edit (depending
12629 on `org-remove-highlights-with-change'), this variable is emptied
12630 as well.")
12631 (make-variable-buffer-local 'org-occur-parameters)
12633 (defun org-occur (regexp &optional keep-previous callback)
12634 "Make a compact tree which shows all matches of REGEXP.
12635 The tree will show the lines where the regexp matches, and all higher
12636 headlines above the match. It will also show the heading after the match,
12637 to make sure editing the matching entry is easy.
12638 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12639 call to `org-occur' will be kept, to allow stacking of calls to this
12640 command.
12641 If CALLBACK is non-nil, it is a function which is called to confirm
12642 that the match should indeed be shown."
12643 (interactive "sRegexp: \nP")
12644 (when (equal regexp "")
12645 (error "Regexp cannot be empty"))
12646 (unless keep-previous
12647 (org-remove-occur-highlights nil nil t))
12648 (push (cons regexp callback) org-occur-parameters)
12649 (let ((cnt 0))
12650 (save-excursion
12651 (goto-char (point-min))
12652 (if (or (not keep-previous) ; do not want to keep
12653 (not org-occur-highlights)) ; no previous matches
12654 ;; hide everything
12655 (org-overview))
12656 (while (re-search-forward regexp nil t)
12657 (when (or (not callback)
12658 (save-match-data (funcall callback)))
12659 (setq cnt (1+ cnt))
12660 (when org-highlight-sparse-tree-matches
12661 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12662 (org-show-context 'occur-tree))))
12663 (when org-remove-highlights-with-change
12664 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12665 nil 'local))
12666 (unless org-sparse-tree-open-archived-trees
12667 (org-hide-archived-subtrees (point-min) (point-max)))
12668 (run-hooks 'org-occur-hook)
12669 (if (org-called-interactively-p 'interactive)
12670 (message "%d match(es) for regexp %s" cnt regexp))
12671 cnt))
12673 (defun org-occur-next-match (&optional n reset)
12674 "Function for `next-error-function' to find sparse tree matches.
12675 N is the number of matches to move, when negative move backwards.
12676 RESET is entirely ignored - this function always goes back to the
12677 starting point when no match is found."
12678 (let* ((limit (if (< n 0) (point-min) (point-max)))
12679 (search-func (if (< n 0)
12680 'previous-single-char-property-change
12681 'next-single-char-property-change))
12682 (n (abs n))
12683 (pos (point))
12685 (catch 'exit
12686 (while (setq p1 (funcall search-func (point) 'org-type))
12687 (when (equal p1 limit)
12688 (goto-char pos)
12689 (error "No more matches"))
12690 (when (equal (get-char-property p1 'org-type) 'org-occur)
12691 (setq n (1- n))
12692 (when (= n 0)
12693 (goto-char p1)
12694 (throw 'exit (point))))
12695 (goto-char p1))
12696 (goto-char p1)
12697 (error "No more matches"))))
12699 (defun org-show-context (&optional key)
12700 "Make sure point and context are visible.
12701 How much context is shown depends upon the variables
12702 `org-show-hierarchy-above', `org-show-following-heading',
12703 `org-show-entry-below' and `org-show-siblings'."
12704 (let ((heading-p (org-at-heading-p t))
12705 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12706 (following-p (org-get-alist-option org-show-following-heading key))
12707 (entry-p (org-get-alist-option org-show-entry-below key))
12708 (siblings-p (org-get-alist-option org-show-siblings key)))
12709 (catch 'exit
12710 ;; Show heading or entry text
12711 (if (and heading-p (not entry-p))
12712 (org-flag-heading nil) ; only show the heading
12713 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12714 (org-show-hidden-entry))) ; show entire entry
12715 (when following-p
12716 ;; Show next sibling, or heading below text
12717 (save-excursion
12718 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12719 (org-flag-heading nil))))
12720 (when siblings-p (org-show-siblings))
12721 (when hierarchy-p
12722 ;; show all higher headings, possibly with siblings
12723 (save-excursion
12724 (while (and (condition-case nil
12725 (progn (org-up-heading-all 1) t)
12726 (error nil))
12727 (not (bobp)))
12728 (org-flag-heading nil)
12729 (when siblings-p (org-show-siblings))))))))
12731 (defvar org-reveal-start-hook nil
12732 "Hook run before revealing a location.")
12734 (defun org-reveal (&optional siblings)
12735 "Show current entry, hierarchy above it, and the following headline.
12736 This can be used to show a consistent set of context around locations
12737 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12738 not t for the search context.
12740 With optional argument SIBLINGS, on each level of the hierarchy all
12741 siblings are shown. This repairs the tree structure to what it would
12742 look like when opened with hierarchical calls to `org-cycle'.
12743 With double optional argument \\[universal-argument] \\[universal-argument], \
12744 go to the parent and show the
12745 entire tree."
12746 (interactive "P")
12747 (run-hooks 'org-reveal-start-hook)
12748 (let ((org-show-hierarchy-above t)
12749 (org-show-following-heading t)
12750 (org-show-siblings (if siblings t org-show-siblings)))
12751 (org-show-context nil))
12752 (when (equal siblings '(16))
12753 (save-excursion
12754 (when (org-up-heading-safe)
12755 (org-show-subtree)
12756 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12758 (defun org-highlight-new-match (beg end)
12759 "Highlight from BEG to END and mark the highlight is an occur headline."
12760 (let ((ov (make-overlay beg end)))
12761 (overlay-put ov 'face 'secondary-selection)
12762 (overlay-put ov 'org-type 'org-occur)
12763 (push ov org-occur-highlights)))
12765 (defun org-remove-occur-highlights (&optional beg end noremove)
12766 "Remove the occur highlights from the buffer.
12767 BEG and END are ignored. If NOREMOVE is nil, remove this function
12768 from the `before-change-functions' in the current buffer."
12769 (interactive)
12770 (unless org-inhibit-highlight-removal
12771 (mapc 'delete-overlay org-occur-highlights)
12772 (setq org-occur-highlights nil)
12773 (setq org-occur-parameters nil)
12774 (unless noremove
12775 (remove-hook 'before-change-functions
12776 'org-remove-occur-highlights 'local))))
12778 ;;;; Priorities
12780 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12781 "Regular expression matching the priority indicator.")
12783 (defvar org-remove-priority-next-time nil)
12785 (defun org-priority-up ()
12786 "Increase the priority of the current item."
12787 (interactive)
12788 (org-priority 'up))
12790 (defun org-priority-down ()
12791 "Decrease the priority of the current item."
12792 (interactive)
12793 (org-priority 'down))
12795 (defun org-priority (&optional action)
12796 "Change the priority of an item by ARG.
12797 ACTION can be `set', `up', `down', or a character."
12798 (interactive)
12799 (unless org-enable-priority-commands
12800 (error "Priority commands are disabled"))
12801 (setq action (or action 'set))
12802 (let (current new news have remove)
12803 (save-excursion
12804 (org-back-to-heading t)
12805 (if (looking-at org-priority-regexp)
12806 (setq current (string-to-char (match-string 2))
12807 have t))
12808 (cond
12809 ((eq action 'remove)
12810 (setq remove t new ?\ ))
12811 ((or (eq action 'set)
12812 (if (featurep 'xemacs) (characterp action) (integerp action)))
12813 (if (not (eq action 'set))
12814 (setq new action)
12815 (message "Priority %c-%c, SPC to remove: "
12816 org-highest-priority org-lowest-priority)
12817 (save-match-data
12818 (setq new (read-char-exclusive))))
12819 (if (and (= (upcase org-highest-priority) org-highest-priority)
12820 (= (upcase org-lowest-priority) org-lowest-priority))
12821 (setq new (upcase new)))
12822 (cond ((equal new ?\ ) (setq remove t))
12823 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12824 (error "Priority must be between `%c' and `%c'"
12825 org-highest-priority org-lowest-priority))))
12826 ((eq action 'up)
12827 (setq new (if have
12828 (1- current) ; normal cycling
12829 ;; last priority was empty
12830 (if (eq last-command this-command)
12831 org-lowest-priority ; wrap around empty to lowest
12832 ;; default
12833 (if org-priority-start-cycle-with-default
12834 org-default-priority
12835 (1- org-default-priority))))))
12836 ((eq action 'down)
12837 (setq new (if have
12838 (1+ current) ; normal cycling
12839 ;; last priority was empty
12840 (if (eq last-command this-command)
12841 org-highest-priority ; wrap around empty to highest
12842 ;; default
12843 (if org-priority-start-cycle-with-default
12844 org-default-priority
12845 (1+ org-default-priority))))))
12846 (t (error "Invalid action")))
12847 (if (or (< (upcase new) org-highest-priority)
12848 (> (upcase new) org-lowest-priority))
12849 (if (and (memq action '(up down))
12850 (not have) (not (eq last-command this-command)))
12851 ;; `new' is from default priority
12852 (error
12853 "The default can not be set, see `org-default-priority' why")
12854 ;; normal cycling: `new' is beyond highest/lowest priority
12855 ;; and is wrapped around to the empty priority
12856 (setq remove t)))
12857 (setq news (format "%c" new))
12858 (if have
12859 (if remove
12860 (replace-match "" t t nil 1)
12861 (replace-match news t t nil 2))
12862 (if remove
12863 (error "No priority cookie found in line")
12864 (let ((case-fold-search nil))
12865 (looking-at org-todo-line-regexp))
12866 (if (match-end 2)
12867 (progn
12868 (goto-char (match-end 2))
12869 (insert " [#" news "]"))
12870 (goto-char (match-beginning 3))
12871 (insert "[#" news "] "))))
12872 (org-preserve-lc (org-set-tags nil 'align)))
12873 (if remove
12874 (message "Priority removed")
12875 (message "Priority of current item set to %s" news))))
12877 (defun org-get-priority (s)
12878 "Find priority cookie and return priority."
12879 (if (functionp org-get-priority-function)
12880 (funcall org-get-priority-function)
12881 (save-match-data
12882 (if (not (string-match org-priority-regexp s))
12883 (* 1000 (- org-lowest-priority org-default-priority))
12884 (* 1000 (- org-lowest-priority
12885 (string-to-char (match-string 2 s))))))))
12887 ;;;; Tags
12889 (defvar org-agenda-archives-mode)
12890 (defvar org-map-continue-from nil
12891 "Position from where mapping should continue.
12892 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12894 (defvar org-scanner-tags nil
12895 "The current tag list while the tags scanner is running.")
12896 (defvar org-trust-scanner-tags nil
12897 "Should `org-get-tags-at' use the tags for the scanner.
12898 This is for internal dynamical scoping only.
12899 When this is non-nil, the function `org-get-tags-at' will return the value
12900 of `org-scanner-tags' instead of building the list by itself. This
12901 can lead to large speed-ups when the tags scanner is used in a file with
12902 many entries, and when the list of tags is retrieved, for example to
12903 obtain a list of properties. Building the tags list for each entry in such
12904 a file becomes an N^2 operation - but with this variable set, it scales
12905 as N.")
12907 (defun org-scan-tags (action matcher todo-only &optional start-level)
12908 "Scan headline tags with inheritance and produce output ACTION.
12910 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12911 or `agenda' to produce an entry list for an agenda view. It can also be
12912 a Lisp form or a function that should be called at each matched headline, in
12913 this case the return value is a list of all return values from these calls.
12915 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12916 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12917 only lines with a not-done TODO keyword are included in the output.
12918 This should be the same variable that was scoped into
12919 and set by `org-make-tags-matcher' when it constructed MATCHER.
12921 START-LEVEL can be a string with asterisks, reducing the scope to
12922 headlines matching this string."
12923 (require 'org-agenda)
12924 (let* ((re (concat "^"
12925 (if start-level
12926 ;; Get the correct level to match
12927 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12928 org-outline-regexp)
12929 " *\\(\\<\\("
12930 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12931 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12932 (props (list 'face 'default
12933 'done-face 'org-agenda-done
12934 'undone-face 'default
12935 'mouse-face 'highlight
12936 'org-not-done-regexp org-not-done-regexp
12937 'org-todo-regexp org-todo-regexp
12938 'org-complex-heading-regexp org-complex-heading-regexp
12939 'help-echo
12940 (format "mouse-2 or RET jump to org file %s"
12941 (abbreviate-file-name
12942 (or (buffer-file-name (buffer-base-buffer))
12943 (buffer-name (buffer-base-buffer)))))))
12944 (case-fold-search nil)
12945 (org-map-continue-from nil)
12946 lspos tags tags-list
12947 (tags-alist (list (cons 0 org-file-tags)))
12948 (llast 0) rtn rtn1 level category i txt
12949 todo marker entry priority)
12950 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12951 (setq action (list 'lambda nil action)))
12952 (save-excursion
12953 (goto-char (point-min))
12954 (when (eq action 'sparse-tree)
12955 (org-overview)
12956 (org-remove-occur-highlights))
12957 (while (re-search-forward re nil t)
12958 (setq org-map-continue-from nil)
12959 (catch :skip
12960 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12961 tags (if (match-end 4) (org-match-string-no-properties 4)))
12962 (goto-char (setq lspos (match-beginning 0)))
12963 (setq level (org-reduced-level (funcall outline-level))
12964 category (org-get-category))
12965 (setq i llast llast level)
12966 ;; remove tag lists from same and sublevels
12967 (while (>= i level)
12968 (when (setq entry (assoc i tags-alist))
12969 (setq tags-alist (delete entry tags-alist)))
12970 (setq i (1- i)))
12971 ;; add the next tags
12972 (when tags
12973 (setq tags (org-split-string tags ":")
12974 tags-alist
12975 (cons (cons level tags) tags-alist)))
12976 ;; compile tags for current headline
12977 (setq tags-list
12978 (if org-use-tag-inheritance
12979 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12980 tags)
12981 org-scanner-tags tags-list)
12982 (when org-use-tag-inheritance
12983 (setcdr (car tags-alist)
12984 (mapcar (lambda (x)
12985 (setq x (copy-sequence x))
12986 (org-add-prop-inherited x))
12987 (cdar tags-alist))))
12988 (when (and tags org-use-tag-inheritance
12989 (or (not (eq t org-use-tag-inheritance))
12990 org-tags-exclude-from-inheritance))
12991 ;; selective inheritance, remove uninherited ones
12992 (setcdr (car tags-alist)
12993 (org-remove-uninherited-tags (cdar tags-alist))))
12994 (when (and
12996 ;; eval matcher only when the todo condition is OK
12997 (and (or (not todo-only) (member todo org-not-done-keywords))
12998 (let ((case-fold-search t) (org-trust-scanner-tags t))
12999 (eval matcher)))
13001 ;; Call the skipper, but return t if it does not skip,
13002 ;; so that the `and' form continues evaluating
13003 (progn
13004 (unless (eq action 'sparse-tree) (org-agenda-skip))
13007 ;; Check if timestamps are deselecting this entry
13008 (or (not todo-only)
13009 (and (member todo org-not-done-keywords)
13010 (or (not org-agenda-tags-todo-honor-ignore-options)
13011 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13013 ;; Extra check for the archive tag
13014 ;; FIXME: Does the skipper already do this????
13016 (not (member org-archive-tag tags-list))
13017 ;; we have an archive tag, should we use this anyway?
13018 (or (not org-agenda-skip-archived-trees)
13019 (and (eq action 'agenda) org-agenda-archives-mode))))
13021 ;; select this headline
13023 (cond
13024 ((eq action 'sparse-tree)
13025 (and org-highlight-sparse-tree-matches
13026 (org-get-heading) (match-end 0)
13027 (org-highlight-new-match
13028 (match-beginning 1) (match-end 1)))
13029 (org-show-context 'tags-tree))
13030 ((eq action 'agenda)
13031 (setq txt (org-agenda-format-item
13033 (concat
13034 (if (eq org-tags-match-list-sublevels 'indented)
13035 (make-string (1- level) ?.) "")
13036 (org-get-heading))
13037 category
13038 tags-list)
13039 priority (org-get-priority txt))
13040 (goto-char lspos)
13041 (setq marker (org-agenda-new-marker))
13042 (org-add-props txt props
13043 'org-marker marker 'org-hd-marker marker 'org-category category
13044 'todo-state todo
13045 'priority priority 'type "tagsmatch")
13046 (push txt rtn))
13047 ((functionp action)
13048 (setq org-map-continue-from nil)
13049 (save-excursion
13050 (setq rtn1 (funcall action))
13051 (push rtn1 rtn)))
13052 (t (error "Invalid action")))
13054 ;; if we are to skip sublevels, jump to end of subtree
13055 (unless org-tags-match-list-sublevels
13056 (org-end-of-subtree t)
13057 (backward-char 1))))
13058 ;; Get the correct position from where to continue
13059 (if org-map-continue-from
13060 (goto-char org-map-continue-from)
13061 (and (= (point) lspos) (end-of-line 1)))))
13062 (when (and (eq action 'sparse-tree)
13063 (not org-sparse-tree-open-archived-trees))
13064 (org-hide-archived-subtrees (point-min) (point-max)))
13065 (nreverse rtn)))
13067 (defun org-remove-uninherited-tags (tags)
13068 "Remove all tags that are not inherited from the list TAGS."
13069 (cond
13070 ((eq org-use-tag-inheritance t)
13071 (if org-tags-exclude-from-inheritance
13072 (org-delete-all org-tags-exclude-from-inheritance tags)
13073 tags))
13074 ((not org-use-tag-inheritance) nil)
13075 ((stringp org-use-tag-inheritance)
13076 (delq nil (mapcar
13077 (lambda (x)
13078 (if (and (string-match org-use-tag-inheritance x)
13079 (not (member x org-tags-exclude-from-inheritance)))
13080 x nil))
13081 tags)))
13082 ((listp org-use-tag-inheritance)
13083 (delq nil (mapcar
13084 (lambda (x)
13085 (if (member x org-use-tag-inheritance) x nil))
13086 tags)))))
13088 (defun org-match-sparse-tree (&optional todo-only match)
13089 "Create a sparse tree according to tags string MATCH.
13090 MATCH can contain positive and negative selection of tags, like
13091 \"+WORK+URGENT-WITHBOSS\".
13092 If optional argument TODO-ONLY is non-nil, only select lines that are
13093 also TODO lines."
13094 (interactive "P")
13095 (org-prepare-agenda-buffers (list (current-buffer)))
13096 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13098 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13100 (defvar org-cached-props nil)
13101 (defun org-cached-entry-get (pom property)
13102 (if (or (eq t org-use-property-inheritance)
13103 (and (stringp org-use-property-inheritance)
13104 (string-match org-use-property-inheritance property))
13105 (and (listp org-use-property-inheritance)
13106 (member property org-use-property-inheritance)))
13107 ;; Caching is not possible, check it directly
13108 (org-entry-get pom property 'inherit)
13109 ;; Get all properties, so that we can do complicated checks easily
13110 (cdr (assoc property (or org-cached-props
13111 (setq org-cached-props
13112 (org-entry-properties pom)))))))
13114 (defun org-global-tags-completion-table (&optional files)
13115 "Return the list of all tags in all agenda buffer/files.
13116 Optional FILES argument is a list of files to which can be used
13117 instead of the agenda files."
13118 (save-excursion
13119 (org-uniquify
13120 (delq nil
13121 (apply 'append
13122 (mapcar
13123 (lambda (file)
13124 (set-buffer (find-file-noselect file))
13125 (append (org-get-buffer-tags)
13126 (mapcar (lambda (x) (if (stringp (car-safe x))
13127 (list (car-safe x)) nil))
13128 org-tag-alist)))
13129 (if (and files (car files))
13130 files
13131 (org-agenda-files))))))))
13133 (defun org-make-tags-matcher (match)
13134 "Create the TAGS/TODO matcher form for the selection string MATCH.
13136 The variable `todo-only' is scoped dynamically into this function; it will be
13137 set to t if the matcher restricts matching to TODO entries,
13138 otherwise will not be touched.
13140 Returns a cons of the selection string MATCH and the constructed
13141 lisp form implementing the matcher. The matcher is to be
13142 evaluated at an Org entry, with point on the headline,
13143 and returns t if the entry matches the
13144 selection string MATCH. The returned lisp form references
13145 two variables with information about the entry, which must be
13146 bound around the form's evaluation: todo, the TODO keyword at the
13147 entry (or nil of none); and tags-list, the list of all tags at the
13148 entry including inherited ones. Additionally, the category
13149 of the entry (if any) must be specified as the text property
13150 'org-category on the headline.
13152 See also `org-scan-tags'.
13154 (declare (special todo-only))
13155 (unless (boundp 'todo-only)
13156 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13157 (unless match
13158 ;; Get a new match request, with completion
13159 (let ((org-last-tags-completion-table
13160 (org-global-tags-completion-table)))
13161 (setq match (org-completing-read-no-i
13162 "Match: " 'org-tags-completion-function nil nil nil
13163 'org-tags-history))))
13165 ;; Parse the string and create a lisp form
13166 (let ((match0 match)
13167 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13168 minus tag mm
13169 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13170 orterms term orlist re-p str-p level-p level-op time-p
13171 prop-p pn pv po gv rest)
13172 (if (string-match "/+" match)
13173 ;; match contains also a todo-matching request
13174 (progn
13175 (setq tagsmatch (substring match 0 (match-beginning 0))
13176 todomatch (substring match (match-end 0)))
13177 (if (string-match "^!" todomatch)
13178 (setq todo-only t todomatch (substring todomatch 1)))
13179 (if (string-match "^\\s-*$" todomatch)
13180 (setq todomatch nil)))
13181 ;; only matching tags
13182 (setq tagsmatch match todomatch nil))
13184 ;; Make the tags matcher
13185 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13186 (setq tagsmatcher t)
13187 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13188 (while (setq term (pop orterms))
13189 (while (and (equal (substring term -1) "\\") orterms)
13190 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13191 (while (string-match re term)
13192 (setq rest (substring term (match-end 0))
13193 minus (and (match-end 1)
13194 (equal (match-string 1 term) "-"))
13195 tag (save-match-data (replace-regexp-in-string
13196 "\\\\-" "-"
13197 (match-string 2 term)))
13198 re-p (equal (string-to-char tag) ?{)
13199 level-p (match-end 4)
13200 prop-p (match-end 5)
13201 mm (cond
13202 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13203 (level-p
13204 (setq level-op (org-op-to-function (match-string 3 term)))
13205 `(,level-op level ,(string-to-number
13206 (match-string 4 term))))
13207 (prop-p
13208 (setq pn (match-string 5 term)
13209 po (match-string 6 term)
13210 pv (match-string 7 term)
13211 re-p (equal (string-to-char pv) ?{)
13212 str-p (equal (string-to-char pv) ?\")
13213 time-p (save-match-data
13214 (string-match "^\"[[<].*[]>]\"$" pv))
13215 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13216 (if time-p (setq pv (org-matcher-time pv)))
13217 (setq po (org-op-to-function po (if time-p 'time str-p)))
13218 (cond
13219 ((equal pn "CATEGORY")
13220 (setq gv '(get-text-property (point) 'org-category)))
13221 ((equal pn "TODO")
13222 (setq gv 'todo))
13224 (setq gv `(org-cached-entry-get nil ,pn))))
13225 (if re-p
13226 (if (eq po 'org<>)
13227 `(not (string-match ,pv (or ,gv "")))
13228 `(string-match ,pv (or ,gv "")))
13229 (if str-p
13230 `(,po (or ,gv "") ,pv)
13231 `(,po (string-to-number (or ,gv ""))
13232 ,(string-to-number pv) ))))
13233 (t `(member ,tag tags-list)))
13234 mm (if minus (list 'not mm) mm)
13235 term rest)
13236 (push mm tagsmatcher))
13237 (push (if (> (length tagsmatcher) 1)
13238 (cons 'and tagsmatcher)
13239 (car tagsmatcher))
13240 orlist)
13241 (setq tagsmatcher nil))
13242 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13243 (setq tagsmatcher
13244 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13245 ;; Make the todo matcher
13246 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13247 (setq todomatcher t)
13248 (setq orterms (org-split-string todomatch "|") orlist nil)
13249 (while (setq term (pop orterms))
13250 (while (string-match re term)
13251 (setq minus (and (match-end 1)
13252 (equal (match-string 1 term) "-"))
13253 kwd (match-string 2 term)
13254 re-p (equal (string-to-char kwd) ?{)
13255 term (substring term (match-end 0))
13256 mm (if re-p
13257 `(string-match ,(substring kwd 1 -1) todo)
13258 (list 'equal 'todo kwd))
13259 mm (if minus (list 'not mm) mm))
13260 (push mm todomatcher))
13261 (push (if (> (length todomatcher) 1)
13262 (cons 'and todomatcher)
13263 (car todomatcher))
13264 orlist)
13265 (setq todomatcher nil))
13266 (setq todomatcher (if (> (length orlist) 1)
13267 (cons 'or orlist) (car orlist))))
13269 ;; Return the string and lisp forms of the matcher
13270 (setq matcher (if todomatcher
13271 (list 'and tagsmatcher todomatcher)
13272 tagsmatcher))
13273 (when todo-only
13274 (setq matcher (list 'and '(member todo org-not-done-keywords)
13275 matcher)))
13276 (cons match0 matcher)))
13278 (defun org-op-to-function (op &optional stringp)
13279 "Turn an operator into the appropriate function."
13280 (setq op
13281 (cond
13282 ((equal op "<" ) '(< string< org-time<))
13283 ((equal op ">" ) '(> org-string> org-time>))
13284 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13285 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13286 ((member op '("=" "==")) '(= string= org-time=))
13287 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13288 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13290 (defun org<> (a b) (not (= a b)))
13291 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13292 (defun org-string>= (a b) (not (string< a b)))
13293 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13294 (defun org-string<> (a b) (not (string= a b)))
13295 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13296 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13297 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13298 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13299 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13300 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13301 (defun org-2ft (s)
13302 "Convert S to a floating point time.
13303 If S is already a number, just return it. If it is a string, parse
13304 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13305 (cond
13306 ((numberp s) s)
13307 ((stringp s)
13308 (condition-case nil
13309 (float-time (apply 'encode-time (org-parse-time-string s)))
13310 (error 0.)))
13311 (t 0.)))
13313 (defun org-time-today ()
13314 "Time in seconds today at 0:00.
13315 Returns the float number of seconds since the beginning of the
13316 epoch to the beginning of today (00:00)."
13317 (float-time (apply 'encode-time
13318 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13320 (defun org-matcher-time (s)
13321 "Interpret a time comparison value."
13322 (save-match-data
13323 (cond
13324 ((string= s "<now>") (float-time))
13325 ((string= s "<today>") (org-time-today))
13326 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13327 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13328 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13329 (+ (org-time-today)
13330 (* (string-to-number (match-string 1 s))
13331 (cdr (assoc (match-string 2 s)
13332 '(("d" . 86400.0) ("w" . 604800.0)
13333 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13334 (t (org-2ft s)))))
13336 (defun org-match-any-p (re list)
13337 "Does re match any element of list?"
13338 (setq list (mapcar (lambda (x) (string-match re x)) list))
13339 (delq nil list))
13341 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13342 (defvar org-tags-overlay (make-overlay 1 1))
13343 (org-detach-overlay org-tags-overlay)
13345 (defun org-get-local-tags-at (&optional pos)
13346 "Get a list of tags defined in the current headline."
13347 (org-get-tags-at pos 'local))
13349 (defun org-get-local-tags ()
13350 "Get a list of tags defined in the current headline."
13351 (org-get-tags-at nil 'local))
13353 (defun org-get-tags-at (&optional pos local)
13354 "Get a list of all headline tags applicable at POS.
13355 POS defaults to point. If tags are inherited, the list contains
13356 the targets in the same sequence as the headlines appear, i.e.
13357 the tags of the current headline come last.
13358 When LOCAL is non-nil, only return tags from the current headline,
13359 ignore inherited ones."
13360 (interactive)
13361 (if (and org-trust-scanner-tags
13362 (or (not pos) (equal pos (point)))
13363 (not local))
13364 org-scanner-tags
13365 (let (tags ltags lastpos parent)
13366 (save-excursion
13367 (save-restriction
13368 (widen)
13369 (goto-char (or pos (point)))
13370 (save-match-data
13371 (catch 'done
13372 (condition-case nil
13373 (progn
13374 (org-back-to-heading t)
13375 (while (not (equal lastpos (point)))
13376 (setq lastpos (point))
13377 (when (looking-at
13378 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13379 (setq ltags (org-split-string
13380 (org-match-string-no-properties 1) ":"))
13381 (when parent
13382 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13383 (setq tags (append
13384 (if parent
13385 (org-remove-uninherited-tags ltags)
13386 ltags)
13387 tags)))
13388 (or org-use-tag-inheritance (throw 'done t))
13389 (if local (throw 'done t))
13390 (or (org-up-heading-safe) (error nil))
13391 (setq parent t)))
13392 (error nil)))))
13393 (if local
13394 tags
13395 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13397 (defun org-add-prop-inherited (s)
13398 (add-text-properties 0 (length s) '(inherited t) s)
13401 (defun org-toggle-tag (tag &optional onoff)
13402 "Toggle the tag TAG for the current line.
13403 If ONOFF is `on' or `off', don't toggle but set to this state."
13404 (let (res current)
13405 (save-excursion
13406 (org-back-to-heading t)
13407 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13408 (point-at-eol) t)
13409 (progn
13410 (setq current (match-string 1))
13411 (replace-match ""))
13412 (setq current ""))
13413 (setq current (nreverse (org-split-string current ":")))
13414 (cond
13415 ((eq onoff 'on)
13416 (setq res t)
13417 (or (member tag current) (push tag current)))
13418 ((eq onoff 'off)
13419 (or (not (member tag current)) (setq current (delete tag current))))
13420 (t (if (member tag current)
13421 (setq current (delete tag current))
13422 (setq res t)
13423 (push tag current))))
13424 (end-of-line 1)
13425 (if current
13426 (progn
13427 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13428 (org-set-tags nil t))
13429 (delete-horizontal-space))
13430 (run-hooks 'org-after-tags-change-hook))
13431 res))
13433 (defun org-align-tags-here (to-col)
13434 ;; Assumes that this is a headline
13435 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13436 (beginning-of-line 1)
13437 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13438 (< pos (match-beginning 2)))
13439 (progn
13440 (setq tags-l (- (match-end 2) (match-beginning 2)))
13441 (goto-char (match-beginning 1))
13442 (insert " ")
13443 (delete-region (point) (1+ (match-beginning 2)))
13444 (setq ncol (max (current-column)
13445 (1+ col)
13446 (if (> to-col 0)
13447 to-col
13448 (- (abs to-col) tags-l))))
13449 (setq p (point))
13450 (insert (make-string (- ncol (current-column)) ?\ ))
13451 (setq ncol (current-column))
13452 (when indent-tabs-mode (tabify p (point-at-eol)))
13453 (org-move-to-column (min ncol col) t))
13454 (goto-char pos))))
13456 (defun org-set-tags-command (&optional arg just-align)
13457 "Call the set-tags command for the current entry."
13458 (interactive "P")
13459 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13460 (org-set-tags arg just-align)
13461 (save-excursion
13462 (org-back-to-heading t)
13463 (org-set-tags arg just-align))))
13465 (defun org-set-tags-to (data)
13466 "Set the tags of the current entry to DATA, replacing the current tags.
13467 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13468 If DATA is nil or the empty string, any tags will be removed."
13469 (interactive "sTags: ")
13470 (setq data
13471 (cond
13472 ((eq data nil) "")
13473 ((equal data "") "")
13474 ((stringp data)
13475 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13476 ":"))
13477 ((listp data)
13478 (concat ":" (mapconcat 'identity data ":") ":"))
13479 (t nil)))
13480 (when data
13481 (save-excursion
13482 (org-back-to-heading t)
13483 (when (looking-at org-complex-heading-regexp)
13484 (if (match-end 5)
13485 (progn
13486 (goto-char (match-beginning 5))
13487 (insert data)
13488 (delete-region (point) (point-at-eol))
13489 (org-set-tags nil 'align))
13490 (goto-char (point-at-eol))
13491 (insert " " data)
13492 (org-set-tags nil 'align)))
13493 (beginning-of-line 1)
13494 (if (looking-at ".*?\\([ \t]+\\)$")
13495 (delete-region (match-beginning 1) (match-end 1))))))
13497 (defun org-align-all-tags ()
13498 "Align the tags i all headings."
13499 (interactive)
13500 (save-excursion
13501 (or (ignore-errors (org-back-to-heading t))
13502 (outline-next-heading))
13503 (if (org-at-heading-p)
13504 (org-set-tags t)
13505 (message "No headings"))))
13507 (defvar org-indent-indentation-per-level)
13508 (defun org-set-tags (&optional arg just-align)
13509 "Set the tags for the current headline.
13510 With prefix ARG, realign all tags in headings in the current buffer."
13511 (interactive "P")
13512 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13513 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13514 'region-start-level 'region))
13515 org-loop-over-headlines-in-active-region)
13516 (org-map-entries
13517 ;; We don't use ARG and JUST-ALIGN here these args are not
13518 ;; useful when looping over headlines
13519 `(org-set-tags)
13520 org-loop-over-headlines-in-active-region
13521 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13522 (let* ((re org-outline-regexp-bol)
13523 (current (unless arg (org-get-tags-string)))
13524 (col (current-column))
13525 (org-setting-tags t)
13526 table current-tags inherited-tags ; computed below when needed
13527 tags p0 c0 c1 rpl di tc level)
13528 (if arg
13529 (save-excursion
13530 (goto-char (point-min))
13531 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13532 (while (re-search-forward re nil t)
13533 (org-set-tags nil t)
13534 (end-of-line 1)))
13535 (message "All tags realigned to column %d" org-tags-column))
13536 (if just-align
13537 (setq tags current)
13538 ;; Get a new set of tags from the user
13539 (save-excursion
13540 (setq table (append org-tag-persistent-alist
13541 (or org-tag-alist (org-get-buffer-tags))
13542 (and
13543 org-complete-tags-always-offer-all-agenda-tags
13544 (org-global-tags-completion-table
13545 (org-agenda-files))))
13546 org-last-tags-completion-table table
13547 current-tags (org-split-string current ":")
13548 inherited-tags (nreverse
13549 (nthcdr (length current-tags)
13550 (nreverse (org-get-tags-at))))
13551 tags
13552 (if (or (eq t org-use-fast-tag-selection)
13553 (and org-use-fast-tag-selection
13554 (delq nil (mapcar 'cdr table))))
13555 (org-fast-tag-selection
13556 current-tags inherited-tags table
13557 (if org-fast-tag-selection-include-todo
13558 org-todo-key-alist))
13559 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13560 (org-trim
13561 (org-icompleting-read "Tags: "
13562 'org-tags-completion-function
13563 nil nil current 'org-tags-history))))))
13564 (while (string-match "[-+&]+" tags)
13565 ;; No boolean logic, just a list
13566 (setq tags (replace-match ":" t t tags))))
13568 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13570 (if org-tags-sort-function
13571 (setq tags (mapconcat 'identity
13572 (sort (org-split-string
13573 tags (org-re "[^[:alnum:]_@#%]+"))
13574 org-tags-sort-function) ":")))
13576 (if (string-match "\\`[\t ]*\\'" tags)
13577 (setq tags "")
13578 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13579 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13581 ;; Insert new tags at the correct column
13582 (beginning-of-line 1)
13583 (setq level (or (and (looking-at org-outline-regexp)
13584 (- (match-end 0) (point) 1))
13586 (cond
13587 ((and (equal current "") (equal tags "")))
13588 ((re-search-forward
13589 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13590 (point-at-eol) t)
13591 (if (equal tags "")
13592 (setq rpl "")
13593 (goto-char (match-beginning 0))
13594 (setq c0 (current-column)
13595 ;; compute offset for the case of org-indent-mode active
13596 di (if org-indent-mode
13597 (* (1- org-indent-indentation-per-level) (1- level))
13599 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13600 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13601 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13602 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13603 (replace-match rpl t t)
13604 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13605 tags)
13606 (t (error "Tags alignment failed")))
13607 (org-move-to-column col)
13608 (unless just-align
13609 (run-hooks 'org-after-tags-change-hook))))))
13611 (defun org-change-tag-in-region (beg end tag off)
13612 "Add or remove TAG for each entry in the region.
13613 This works in the agenda, and also in an org-mode buffer."
13614 (interactive
13615 (list (region-beginning) (region-end)
13616 (let ((org-last-tags-completion-table
13617 (if (derived-mode-p 'org-mode)
13618 (org-get-buffer-tags)
13619 (org-global-tags-completion-table))))
13620 (org-icompleting-read
13621 "Tag: " 'org-tags-completion-function nil nil nil
13622 'org-tags-history))
13623 (progn
13624 (message "[s]et or [r]emove? ")
13625 (equal (read-char-exclusive) ?r))))
13626 (if (fboundp 'deactivate-mark) (deactivate-mark))
13627 (let ((agendap (equal major-mode 'org-agenda-mode))
13628 l1 l2 m buf pos newhead (cnt 0))
13629 (goto-char end)
13630 (setq l2 (1- (org-current-line)))
13631 (goto-char beg)
13632 (setq l1 (org-current-line))
13633 (loop for l from l1 to l2 do
13634 (org-goto-line l)
13635 (setq m (get-text-property (point) 'org-hd-marker))
13636 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13637 (and agendap m))
13638 (setq buf (if agendap (marker-buffer m) (current-buffer))
13639 pos (if agendap m (point)))
13640 (with-current-buffer buf
13641 (save-excursion
13642 (save-restriction
13643 (goto-char pos)
13644 (setq cnt (1+ cnt))
13645 (org-toggle-tag tag (if off 'off 'on))
13646 (setq newhead (org-get-heading)))))
13647 (and agendap (org-agenda-change-all-lines newhead m))))
13648 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13650 (defun org-tags-completion-function (string predicate &optional flag)
13651 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13652 (confirm (lambda (x) (stringp (car x)))))
13653 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13654 (setq s1 (match-string 1 string)
13655 s2 (match-string 2 string))
13656 (setq s1 "" s2 string))
13657 (cond
13658 ((eq flag nil)
13659 ;; try completion
13660 (setq rtn (try-completion s2 ctable confirm))
13661 (if (stringp rtn)
13662 (setq rtn
13663 (concat s1 s2 (substring rtn (length s2))
13664 (if (and org-add-colon-after-tag-completion
13665 (assoc rtn ctable))
13666 ":" ""))))
13667 rtn)
13668 ((eq flag t)
13669 ;; all-completions
13670 (all-completions s2 ctable confirm)
13672 ((eq flag 'lambda)
13673 ;; exact match?
13674 (assoc s2 ctable)))
13677 (defun org-fast-tag-insert (kwd tags face &optional end)
13678 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13679 (insert (format "%-12s" (concat kwd ":"))
13680 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13681 (or end "")))
13683 (defun org-fast-tag-show-exit (flag)
13684 (save-excursion
13685 (org-goto-line 3)
13686 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13687 (replace-match ""))
13688 (when flag
13689 (end-of-line 1)
13690 (org-move-to-column (- (window-width) 19) t)
13691 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13693 (defun org-set-current-tags-overlay (current prefix)
13694 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13695 (if (featurep 'xemacs)
13696 (org-overlay-display org-tags-overlay (concat prefix s)
13697 'secondary-selection)
13698 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13699 (org-overlay-display org-tags-overlay (concat prefix s)))))
13701 (defvar org-last-tag-selection-key nil)
13702 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13703 "Fast tag selection with single keys.
13704 CURRENT is the current list of tags in the headline, INHERITED is the
13705 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13706 possibly with grouping information. TODO-TABLE is a similar table with
13707 TODO keywords, should these have keys assigned to them.
13708 If the keys are nil, a-z are automatically assigned.
13709 Returns the new tags string, or nil to not change the current settings."
13710 (let* ((fulltable (append table todo-table))
13711 (maxlen (apply 'max (mapcar
13712 (lambda (x)
13713 (if (stringp (car x)) (string-width (car x)) 0))
13714 fulltable)))
13715 (buf (current-buffer))
13716 (expert (eq org-fast-tag-selection-single-key 'expert))
13717 (buffer-tags nil)
13718 (fwidth (+ maxlen 3 1 3))
13719 (ncol (/ (- (window-width) 4) fwidth))
13720 (i-face 'org-done)
13721 (c-face 'org-todo)
13722 tg cnt e c char c1 c2 ntable tbl rtn
13723 ov-start ov-end ov-prefix
13724 (exit-after-next org-fast-tag-selection-single-key)
13725 (done-keywords org-done-keywords)
13726 groups ingroup)
13727 (save-excursion
13728 (beginning-of-line 1)
13729 (if (looking-at
13730 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13731 (setq ov-start (match-beginning 1)
13732 ov-end (match-end 1)
13733 ov-prefix "")
13734 (setq ov-start (1- (point-at-eol))
13735 ov-end (1+ ov-start))
13736 (skip-chars-forward "^\n\r")
13737 (setq ov-prefix
13738 (concat
13739 (buffer-substring (1- (point)) (point))
13740 (if (> (current-column) org-tags-column)
13742 (make-string (- org-tags-column (current-column)) ?\ ))))))
13743 (move-overlay org-tags-overlay ov-start ov-end)
13744 (save-window-excursion
13745 (if expert
13746 (set-buffer (get-buffer-create " *Org tags*"))
13747 (delete-other-windows)
13748 (split-window-vertically)
13749 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13750 (erase-buffer)
13751 (org-set-local 'org-done-keywords done-keywords)
13752 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13753 (org-fast-tag-insert "Current" current c-face "\n\n")
13754 (org-fast-tag-show-exit exit-after-next)
13755 (org-set-current-tags-overlay current ov-prefix)
13756 (setq tbl fulltable char ?a cnt 0)
13757 (while (setq e (pop tbl))
13758 (cond
13759 ((equal (car e) :startgroup)
13760 (push '() groups) (setq ingroup t)
13761 (when (not (= cnt 0))
13762 (setq cnt 0)
13763 (insert "\n"))
13764 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13765 ((equal (car e) :endgroup)
13766 (setq ingroup nil cnt 0)
13767 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13768 ((equal e '(:newline))
13769 (when (not (= cnt 0))
13770 (setq cnt 0)
13771 (insert "\n")
13772 (setq e (car tbl))
13773 (while (equal (car tbl) '(:newline))
13774 (insert "\n")
13775 (setq tbl (cdr tbl)))))
13777 (setq tg (copy-sequence (car e)) c2 nil)
13778 (if (cdr e)
13779 (setq c (cdr e))
13780 ;; automatically assign a character.
13781 (setq c1 (string-to-char
13782 (downcase (substring
13783 tg (if (= (string-to-char tg) ?@) 1 0)))))
13784 (if (or (rassoc c1 ntable) (rassoc c1 table))
13785 (while (or (rassoc char ntable) (rassoc char table))
13786 (setq char (1+ char)))
13787 (setq c2 c1))
13788 (setq c (or c2 char)))
13789 (if ingroup (push tg (car groups)))
13790 (setq tg (org-add-props tg nil 'face
13791 (cond
13792 ((not (assoc tg table))
13793 (org-get-todo-face tg))
13794 ((member tg current) c-face)
13795 ((member tg inherited) i-face)
13796 (t nil))))
13797 (if (and (= cnt 0) (not ingroup)) (insert " "))
13798 (insert "[" c "] " tg (make-string
13799 (- fwidth 4 (length tg)) ?\ ))
13800 (push (cons tg c) ntable)
13801 (when (= (setq cnt (1+ cnt)) ncol)
13802 (insert "\n")
13803 (if ingroup (insert " "))
13804 (setq cnt 0)))))
13805 (setq ntable (nreverse ntable))
13806 (insert "\n")
13807 (goto-char (point-min))
13808 (if (not expert) (org-fit-window-to-buffer))
13809 (setq rtn
13810 (catch 'exit
13811 (while t
13812 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13813 (if (not groups) "no " "")
13814 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13815 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13816 (setq org-last-tag-selection-key c)
13817 (cond
13818 ((= c ?\r) (throw 'exit t))
13819 ((= c ?!)
13820 (setq groups (not groups))
13821 (goto-char (point-min))
13822 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13823 ((= c ?\C-c)
13824 (if (not expert)
13825 (org-fast-tag-show-exit
13826 (setq exit-after-next (not exit-after-next)))
13827 (setq expert nil)
13828 (delete-other-windows)
13829 (set-window-buffer (split-window-vertically) " *Org tags*")
13830 (org-switch-to-buffer-other-window " *Org tags*")
13831 (org-fit-window-to-buffer)))
13832 ((or (= c ?\C-g)
13833 (and (= c ?q) (not (rassoc c ntable))))
13834 (org-detach-overlay org-tags-overlay)
13835 (setq quit-flag t))
13836 ((= c ?\ )
13837 (setq current nil)
13838 (if exit-after-next (setq exit-after-next 'now)))
13839 ((= c ?\t)
13840 (condition-case nil
13841 (setq tg (org-icompleting-read
13842 "Tag: "
13843 (or buffer-tags
13844 (with-current-buffer buf
13845 (org-get-buffer-tags)))))
13846 (quit (setq tg "")))
13847 (when (string-match "\\S-" tg)
13848 (add-to-list 'buffer-tags (list tg))
13849 (if (member tg current)
13850 (setq current (delete tg current))
13851 (push tg current)))
13852 (if exit-after-next (setq exit-after-next 'now)))
13853 ((setq e (rassoc c todo-table) tg (car e))
13854 (with-current-buffer buf
13855 (save-excursion (org-todo tg)))
13856 (if exit-after-next (setq exit-after-next 'now)))
13857 ((setq e (rassoc c ntable) tg (car e))
13858 (if (member tg current)
13859 (setq current (delete tg current))
13860 (loop for g in groups do
13861 (if (member tg g)
13862 (mapc (lambda (x)
13863 (setq current (delete x current)))
13864 g)))
13865 (push tg current))
13866 (if exit-after-next (setq exit-after-next 'now))))
13868 ;; Create a sorted list
13869 (setq current
13870 (sort current
13871 (lambda (a b)
13872 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13873 (if (eq exit-after-next 'now) (throw 'exit t))
13874 (goto-char (point-min))
13875 (beginning-of-line 2)
13876 (delete-region (point) (point-at-eol))
13877 (org-fast-tag-insert "Current" current c-face)
13878 (org-set-current-tags-overlay current ov-prefix)
13879 (while (re-search-forward
13880 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13881 (setq tg (match-string 1))
13882 (add-text-properties
13883 (match-beginning 1) (match-end 1)
13884 (list 'face
13885 (cond
13886 ((member tg current) c-face)
13887 ((member tg inherited) i-face)
13888 (t (get-text-property (match-beginning 1) 'face))))))
13889 (goto-char (point-min)))))
13890 (org-detach-overlay org-tags-overlay)
13891 (if rtn
13892 (mapconcat 'identity current ":")
13893 nil))))
13895 (defun org-get-tags-string ()
13896 "Get the TAGS string in the current headline."
13897 (unless (org-at-heading-p t)
13898 (error "Not on a heading"))
13899 (save-excursion
13900 (beginning-of-line 1)
13901 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13902 (org-match-string-no-properties 1)
13903 "")))
13905 (defun org-get-tags ()
13906 "Get the list of tags specified in the current headline."
13907 (org-split-string (org-get-tags-string) ":"))
13909 (defun org-get-buffer-tags ()
13910 "Get a table of all tags used in the buffer, for completion."
13911 (let (tags)
13912 (save-excursion
13913 (goto-char (point-min))
13914 (while (re-search-forward
13915 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13916 (when (equal (char-after (point-at-bol 0)) ?*)
13917 (mapc (lambda (x) (add-to-list 'tags x))
13918 (org-split-string (org-match-string-no-properties 1) ":")))))
13919 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13920 (mapcar 'list tags)))
13922 ;;;; The mapping API
13924 ;;;###autoload
13925 (defun org-map-entries (func &optional match scope &rest skip)
13926 "Call FUNC at each headline selected by MATCH in SCOPE.
13928 FUNC is a function or a lisp form. The function will be called without
13929 arguments, with the cursor positioned at the beginning of the headline.
13930 The return values of all calls to the function will be collected and
13931 returned as a list.
13933 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13934 does not need to preserve point. After evaluation, the cursor will be
13935 moved to the end of the line (presumably of the headline of the
13936 processed entry) and search continues from there. Under some
13937 circumstances, this may not produce the wanted results. For example,
13938 if you have removed (e.g. archived) the current (sub)tree it could
13939 mean that the next entry will be skipped entirely. In such cases, you
13940 can specify the position from where search should continue by making
13941 FUNC set the variable `org-map-continue-from' to the desired buffer
13942 position.
13944 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13945 Only headlines that are matched by this query will be considered during
13946 the iteration. When MATCH is nil or t, all headlines will be
13947 visited by the iteration.
13949 SCOPE determines the scope of this command. It can be any of:
13951 nil The current buffer, respecting the restriction if any
13952 tree The subtree started with the entry at point
13953 region The entries within the active region, if any
13954 region-start-level
13955 The entries within the active region, but only those at
13956 the same level than the first one.
13957 file The current buffer, without restriction
13958 file-with-archives
13959 The current buffer, and any archives associated with it
13960 agenda All agenda files
13961 agenda-with-archives
13962 All agenda files with any archive files associated with them
13963 \(file1 file2 ...)
13964 If this is a list, all files in the list will be scanned
13966 The remaining args are treated as settings for the skipping facilities of
13967 the scanner. The following items can be given here:
13969 archive skip trees with the archive tag.
13970 comment skip trees with the COMMENT keyword
13971 function or Emacs Lisp form:
13972 will be used as value for `org-agenda-skip-function', so whenever
13973 the function returns t, FUNC will not be called for that
13974 entry and search will continue from the point where the
13975 function leaves it.
13977 If your function needs to retrieve the tags including inherited tags
13978 at the *current* entry, you can use the value of the variable
13979 `org-scanner-tags' which will be much faster than getting the value
13980 with `org-get-tags-at'. If your function gets properties with
13981 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13982 to t around the call to `org-entry-properties' to get the same speedup.
13983 Note that if your function moves around to retrieve tags and properties at
13984 a *different* entry, you cannot use these techniques."
13985 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13986 (not (org-region-active-p)))
13987 (let* ((org-agenda-archives-mode nil) ; just to make sure
13988 (org-agenda-skip-archived-trees (memq 'archive skip))
13989 (org-agenda-skip-comment-trees (memq 'comment skip))
13990 (org-agenda-skip-function
13991 (car (org-delete-all '(comment archive) skip)))
13992 (org-tags-match-list-sublevels t)
13993 (start-level (eq scope 'region-start-level))
13994 matcher file res
13995 org-todo-keywords-for-agenda
13996 org-done-keywords-for-agenda
13997 org-todo-keyword-alist-for-agenda
13998 org-drawers-for-agenda
13999 org-tag-alist-for-agenda
14000 todo-only)
14002 (cond
14003 ((eq match t) (setq matcher t))
14004 ((eq match nil) (setq matcher t))
14005 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14007 (save-excursion
14008 (save-restriction
14009 (cond ((eq scope 'tree)
14010 (org-back-to-heading t)
14011 (org-narrow-to-subtree)
14012 (setq scope nil))
14013 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14014 (org-region-active-p))
14015 ;; If needed, set start-level to a string like "2"
14016 (when start-level
14017 (save-excursion
14018 (goto-char (region-beginning))
14019 (unless (org-at-heading-p) (outline-next-heading))
14020 (setq start-level (org-current-level))))
14021 (narrow-to-region (region-beginning)
14022 (save-excursion
14023 (goto-char (region-end))
14024 (unless (and (bolp) (org-at-heading-p))
14025 (outline-next-heading))
14026 (point)))
14027 (setq scope nil)))
14029 (if (not scope)
14030 (progn
14031 (org-prepare-agenda-buffers
14032 (list (buffer-file-name (current-buffer))))
14033 (setq res (org-scan-tags func matcher todo-only start-level)))
14034 ;; Get the right scope
14035 (cond
14036 ((and scope (listp scope) (symbolp (car scope)))
14037 (setq scope (eval scope)))
14038 ((eq scope 'agenda)
14039 (setq scope (org-agenda-files t)))
14040 ((eq scope 'agenda-with-archives)
14041 (setq scope (org-agenda-files t))
14042 (setq scope (org-add-archive-files scope)))
14043 ((eq scope 'file)
14044 (setq scope (list (buffer-file-name))))
14045 ((eq scope 'file-with-archives)
14046 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14047 (org-prepare-agenda-buffers scope)
14048 (while (setq file (pop scope))
14049 (with-current-buffer (org-find-base-buffer-visiting file)
14050 (save-excursion
14051 (save-restriction
14052 (widen)
14053 (goto-char (point-min))
14054 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14055 res)))
14057 ;;;; Properties
14059 ;;; Setting and retrieving properties
14061 (defconst org-special-properties
14062 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14063 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
14064 "The special properties valid in Org-mode.
14066 These are properties that are not defined in the property drawer,
14067 but in some other way.")
14069 (defconst org-default-properties
14070 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14071 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14072 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14073 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14074 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14075 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14076 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14077 "Some properties that are used by Org-mode for various purposes.
14078 Being in this list makes sure that they are offered for completion.")
14080 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14081 "Regular expression matching the first line of a property drawer.")
14083 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14084 "Regular expression matching the last line of a property drawer.")
14086 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14087 "Regular expression matching the first line of a property drawer.")
14089 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14090 "Regular expression matching the first line of a property drawer.")
14092 (defconst org-property-drawer-re
14093 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14094 org-property-end-re "\\)\n?")
14095 "Matches an entire property drawer.")
14097 (defconst org-clock-drawer-re
14098 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14099 org-property-end-re "\\)\n?")
14100 "Matches an entire clock drawer.")
14102 (defsubst org-re-property (property)
14103 "Return a regexp matching PROPERTY.
14104 Match group 1 will be set to the value "
14105 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14107 (defun org-property-action ()
14108 "Do an action on properties."
14109 (interactive)
14110 (let (c)
14111 (org-at-property-p)
14112 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14113 (setq c (read-char-exclusive))
14114 (cond
14115 ((equal c ?s)
14116 (call-interactively 'org-set-property))
14117 ((equal c ?d)
14118 (call-interactively 'org-delete-property))
14119 ((equal c ?D)
14120 (call-interactively 'org-delete-property-globally))
14121 ((equal c ?c)
14122 (call-interactively 'org-compute-property-at-point))
14123 (t (error "No such property action %c" c)))))
14125 (defun org-set-effort (&optional value)
14126 "Set the effort property of the current entry.
14127 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14128 allowed value."
14129 (interactive "P")
14130 (if (equal value 0) (setq value 10))
14131 (let* ((completion-ignore-case t)
14132 (prop org-effort-property)
14133 (cur (org-entry-get nil prop))
14134 (allowed (org-property-get-allowed-values nil prop 'table))
14135 (existing (mapcar 'list (org-property-values prop)))
14137 (val (cond
14138 ((stringp value) value)
14139 ((and allowed (integerp value))
14140 (or (car (nth (1- value) allowed))
14141 (car (org-last allowed))))
14142 (allowed
14143 (message "Select 1-9,0, [RET%s]: %s"
14144 (if cur (concat "=" cur) "")
14145 (mapconcat 'car allowed " "))
14146 (setq rpl (read-char-exclusive))
14147 (if (equal rpl ?\r)
14149 (setq rpl (- rpl ?0))
14150 (if (equal rpl 0) (setq rpl 10))
14151 (if (and (> rpl 0) (<= rpl (length allowed)))
14152 (car (nth (1- rpl) allowed))
14153 (org-completing-read "Effort: " allowed nil))))
14155 (let (org-completion-use-ido org-completion-use-iswitchb)
14156 (org-completing-read
14157 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14158 (concat "[" cur "]") "")
14159 ": ")
14160 existing nil nil "" nil cur))))))
14161 (unless (equal (org-entry-get nil prop) val)
14162 (org-entry-put nil prop val))
14163 (message "%s is now %s" prop val)))
14165 (defun org-at-property-p ()
14166 "Is cursor inside a property drawer?"
14167 (save-excursion
14168 (beginning-of-line 1)
14169 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14170 (save-match-data ;; Used by calling procedures
14171 (let ((p (point))
14172 (range (unless (org-before-first-heading-p)
14173 (org-get-property-block))))
14174 (and range (<= (car range) p) (< p (cdr range))))))))
14176 (defun org-get-property-block (&optional beg end force)
14177 "Return the (beg . end) range of the body of the property drawer.
14178 BEG and END can be beginning and end of subtree, if not given
14179 they will be found.
14180 If the drawer does not exist and FORCE is non-nil, create the drawer."
14181 (catch 'exit
14182 (save-excursion
14183 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14184 (end (or end (progn (outline-next-heading) (point)))))
14185 (goto-char beg)
14186 (if (re-search-forward org-property-start-re end t)
14187 (setq beg (1+ (match-end 0)))
14188 (if force
14189 (save-excursion
14190 (org-insert-property-drawer)
14191 (setq end (progn (outline-next-heading) (point))))
14192 (throw 'exit nil))
14193 (goto-char beg)
14194 (if (re-search-forward org-property-start-re end t)
14195 (setq beg (1+ (match-end 0)))))
14196 (if (re-search-forward org-property-end-re end t)
14197 (setq end (match-beginning 0))
14198 (or force (throw 'exit nil))
14199 (goto-char beg)
14200 (setq end beg)
14201 (org-indent-line-function)
14202 (insert ":END:\n"))
14203 (cons beg end)))))
14205 (defun org-entry-properties (&optional pom which specific)
14206 "Get all properties of the entry at point-or-marker POM.
14207 This includes the TODO keyword, the tags, time strings for deadline,
14208 scheduled, and clocking, and any additional properties defined in the
14209 entry. The return value is an alist, keys may occur multiple times
14210 if the property key was used several times.
14211 POM may also be nil, in which case the current entry is used.
14212 If WHICH is nil or `all', get all properties. If WHICH is
14213 `special' or `standard', only get that subclass. If WHICH
14214 is a string only get exactly this property. SPECIFIC can be a string, the
14215 specific property we are interested in. Specifying it can speed
14216 things up because then unnecessary parsing is avoided."
14217 (setq which (or which 'all))
14218 (org-with-point-at pom
14219 (let ((clockstr (substring org-clock-string 0 -1))
14220 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14221 (case-fold-search nil)
14222 beg end range props sum-props key key1 value string clocksum)
14223 (save-excursion
14224 (when (condition-case nil
14225 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14226 (error nil))
14227 (setq beg (point))
14228 (setq sum-props (get-text-property (point) 'org-summaries))
14229 (setq clocksum (get-text-property (point) :org-clock-minutes))
14230 (outline-next-heading)
14231 (setq end (point))
14232 (when (memq which '(all special))
14233 ;; Get the special properties, like TODO and tags
14234 (goto-char beg)
14235 (when (and (or (not specific) (string= specific "TODO"))
14236 (looking-at org-todo-line-regexp) (match-end 2))
14237 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14238 (when (and (or (not specific) (string= specific "PRIORITY"))
14239 (looking-at org-priority-regexp))
14240 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14241 (when (or (not specific) (string= specific "FILE"))
14242 (push (cons "FILE" buffer-file-name) props))
14243 (when (and (or (not specific) (string= specific "TAGS"))
14244 (setq value (org-get-tags-string))
14245 (string-match "\\S-" value))
14246 (push (cons "TAGS" value) props))
14247 (when (and (or (not specific) (string= specific "ALLTAGS"))
14248 (setq value (org-get-tags-at)))
14249 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14250 ":"))
14251 props))
14252 (when (or (not specific) (string= specific "BLOCKED"))
14253 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14254 (when (or (not specific)
14255 (member specific
14256 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14257 "TIMESTAMP" "TIMESTAMP_IA")))
14258 (catch 'match
14259 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14260 (setq key (if (match-end 1)
14261 (substring (org-match-string-no-properties 1)
14262 0 -1))
14263 string (if (equal key clockstr)
14264 (org-no-properties
14265 (org-trim
14266 (buffer-substring
14267 (match-beginning 3) (goto-char
14268 (point-at-eol)))))
14269 (substring (org-match-string-no-properties 3)
14270 1 -1)))
14271 ;; Get the correct property name from the key. This is
14272 ;; necessary if the user has configured time keywords.
14273 (setq key1 (concat key ":"))
14274 (cond
14275 ((not key)
14276 (setq key
14277 (if (= (char-after (match-beginning 3)) ?\[)
14278 "TIMESTAMP_IA" "TIMESTAMP")))
14279 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14280 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14281 ((equal key1 org-closed-string) (setq key "CLOSED"))
14282 ((equal key1 org-clock-string) (setq key "CLOCK")))
14283 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14284 (progn
14285 (push (cons key string) props)
14286 ;; no need to search further if match is found
14287 (throw 'match t))
14288 (when (or (equal key "CLOCK") (not (assoc key props)))
14289 (push (cons key string) props))))))
14292 (when (memq which '(all standard))
14293 ;; Get the standard properties, like :PROP: ...
14294 (setq range (org-get-property-block beg end))
14295 (when range
14296 (goto-char (car range))
14297 (while (re-search-forward
14298 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14299 (cdr range) t)
14300 (setq key (org-match-string-no-properties 1)
14301 value (org-trim (or (org-match-string-no-properties 2) "")))
14302 (unless (member key excluded)
14303 (push (cons key (or value "")) props)))))
14304 (if clocksum
14305 (push (cons "CLOCKSUM"
14306 (org-columns-number-to-string (/ (float clocksum) 60.)
14307 'add_times))
14308 props))
14309 (unless (assoc "CATEGORY" props)
14310 (push (cons "CATEGORY" (org-get-category)) props))
14311 (append sum-props (nreverse props)))))))
14313 (defun org-entry-get (pom property &optional inherit literal-nil)
14314 "Get value of PROPERTY for entry at point-or-marker POM.
14315 If INHERIT is non-nil and the entry does not have the property,
14316 then also check higher levels of the hierarchy.
14317 If INHERIT is the symbol `selective', use inheritance only if the setting
14318 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14319 If the property is present but empty, the return value is the empty string.
14320 If the property is not present at all, nil is returned.
14322 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14323 do not interpret it as the list atom nil. This is used for inheritance
14324 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14325 (org-with-point-at pom
14326 (if (and inherit (if (eq inherit 'selective)
14327 (org-property-inherit-p property)
14329 (org-entry-get-with-inheritance property literal-nil)
14330 (if (member property org-special-properties)
14331 ;; We need a special property. Use `org-entry-properties' to
14332 ;; retrieve it, but specify the wanted property
14333 (cdr (assoc property (org-entry-properties nil 'special property)))
14334 (let ((range (unless (org-before-first-heading-p)
14335 (org-get-property-block)))
14336 (props (list (or (assoc property org-file-properties)
14337 (assoc property org-global-properties)
14338 (assoc property org-global-properties-fixed))))
14339 val)
14340 (flet ((ap (key)
14341 (when (re-search-forward
14342 (org-re-property key) (cdr range) t)
14343 (setq props
14344 (org-update-property-plist
14346 (if (match-end 1)
14347 (org-match-string-no-properties 1) "")
14348 props)))))
14349 (when (and range (goto-char (car range)))
14350 (ap property)
14351 (goto-char (car range))
14352 (while (ap (concat property "+")))
14353 (setq val (cdr (assoc property props)))
14354 (when val (if literal-nil val (org-not-nil val))))))))))
14356 (defun org-property-or-variable-value (var &optional inherit)
14357 "Check if there is a property fixing the value of VAR.
14358 If yes, return this value. If not, return the current value of the variable."
14359 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14360 (if (and prop (stringp prop) (string-match "\\S-" prop))
14361 (read prop)
14362 (symbol-value var))))
14364 (defun org-entry-delete (pom property)
14365 "Delete the property PROPERTY from entry at point-or-marker POM."
14366 (org-with-point-at pom
14367 (if (member property org-special-properties)
14368 nil ; cannot delete these properties.
14369 (let ((range (org-get-property-block)))
14370 (if (and range
14371 (goto-char (car range))
14372 (re-search-forward
14373 (org-re-property property)
14374 (cdr range) t))
14375 (progn
14376 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14378 nil)))))
14380 ;; Multi-values properties are properties that contain multiple values
14381 ;; These values are assumed to be single words, separated by whitespace.
14382 (defun org-entry-add-to-multivalued-property (pom property value)
14383 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14384 (let* ((old (org-entry-get pom property))
14385 (values (and old (org-split-string old "[ \t]"))))
14386 (setq value (org-entry-protect-space value))
14387 (unless (member value values)
14388 (setq values (cons value values))
14389 (org-entry-put pom property
14390 (mapconcat 'identity values " ")))))
14392 (defun org-entry-remove-from-multivalued-property (pom property value)
14393 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14394 (let* ((old (org-entry-get pom property))
14395 (values (and old (org-split-string old "[ \t]"))))
14396 (setq value (org-entry-protect-space value))
14397 (when (member value values)
14398 (setq values (delete value values))
14399 (org-entry-put pom property
14400 (mapconcat 'identity values " ")))))
14402 (defun org-entry-member-in-multivalued-property (pom property value)
14403 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14404 (let* ((old (org-entry-get pom property))
14405 (values (and old (org-split-string old "[ \t]"))))
14406 (setq value (org-entry-protect-space value))
14407 (member value values)))
14409 (defun org-entry-get-multivalued-property (pom property)
14410 "Return a list of values in a multivalued property."
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-put-multivalued-property (pom property &rest values)
14416 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14417 VALUES should be a list of strings. Spaces will be protected."
14418 (org-entry-put pom property
14419 (mapconcat 'org-entry-protect-space values " "))
14420 (let* ((value (org-entry-get pom property))
14421 (values (and value (org-split-string value "[ \t]"))))
14422 (mapcar 'org-entry-restore-space values)))
14424 (defun org-entry-protect-space (s)
14425 "Protect spaces and newline in string S."
14426 (while (string-match " " s)
14427 (setq s (replace-match "%20" t t s)))
14428 (while (string-match "\n" s)
14429 (setq s (replace-match "%0A" t t s)))
14432 (defun org-entry-restore-space (s)
14433 "Restore spaces and newline in string S."
14434 (while (string-match "%20" s)
14435 (setq s (replace-match " " t t s)))
14436 (while (string-match "%0A" s)
14437 (setq s (replace-match "\n" t t s)))
14440 (defvar org-entry-property-inherited-from (make-marker)
14441 "Marker pointing to the entry from where a property was inherited.
14442 Each call to `org-entry-get-with-inheritance' will set this marker to the
14443 location of the entry where the inheritance search matched. If there was
14444 no match, the marker will point nowhere.
14445 Note that also `org-entry-get' calls this function, if the INHERIT flag
14446 is set.")
14448 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14449 "Get entry property, and search higher levels if not present.
14450 The search will stop at the first ancestor which has the property defined.
14451 If the value found is \"nil\", return nil to show that the property
14452 should be considered as undefined (this is the meaning of nil here).
14453 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14454 (move-marker org-entry-property-inherited-from nil)
14455 (let (tmp)
14456 (unless (org-before-first-heading-p)
14457 (save-excursion
14458 (save-restriction
14459 (widen)
14460 (catch 'ex
14461 (while t
14462 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14463 (org-back-to-heading t)
14464 (move-marker org-entry-property-inherited-from (point))
14465 (throw 'ex tmp))
14466 (or (org-up-heading-safe) (throw 'ex nil)))))))
14467 (setq tmp (or tmp
14468 (cdr (assoc property org-file-properties))
14469 (cdr (assoc property org-global-properties))
14470 (cdr (assoc property org-global-properties-fixed))))
14471 (if literal-nil tmp (org-not-nil tmp))))
14473 (defvar org-property-changed-functions nil
14474 "Hook called when the value of a property has changed.
14475 Each hook function should accept two arguments, the name of the property
14476 and the new value.")
14478 (defun org-entry-put (pom property value)
14479 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14480 (org-with-point-at pom
14481 (org-back-to-heading t)
14482 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14483 range)
14484 (cond
14485 ((equal property "TODO")
14486 (when (and (stringp value) (string-match "\\S-" value)
14487 (not (member value org-todo-keywords-1)))
14488 (error "\"%s\" is not a valid TODO state" value))
14489 (if (or (not value)
14490 (not (string-match "\\S-" value)))
14491 (setq value 'none))
14492 (org-todo value)
14493 (org-set-tags nil 'align))
14494 ((equal property "PRIORITY")
14495 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14496 (string-to-char value) ?\ ))
14497 (org-set-tags nil 'align))
14498 ((equal property "SCHEDULED")
14499 (if (re-search-forward org-scheduled-time-regexp end t)
14500 (cond
14501 ((eq value 'earlier) (org-timestamp-change -1 'day))
14502 ((eq value 'later) (org-timestamp-change 1 'day))
14503 (t (call-interactively 'org-schedule)))
14504 (call-interactively 'org-schedule)))
14505 ((equal property "DEADLINE")
14506 (if (re-search-forward org-deadline-time-regexp end t)
14507 (cond
14508 ((eq value 'earlier) (org-timestamp-change -1 'day))
14509 ((eq value 'later) (org-timestamp-change 1 'day))
14510 (t (call-interactively 'org-deadline)))
14511 (call-interactively 'org-deadline)))
14512 ((member property org-special-properties)
14513 (error "The %s property can not yet be set with `org-entry-put'"
14514 property))
14515 (t ; a non-special property
14516 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14517 (setq range (org-get-property-block beg end 'force))
14518 (goto-char (car range))
14519 (if (re-search-forward
14520 (org-re-property property) (cdr range) t)
14521 (progn
14522 (delete-region (match-beginning 0) (match-end 0))
14523 (goto-char (match-beginning 0)))
14524 (goto-char (cdr range))
14525 (insert "\n")
14526 (backward-char 1)
14527 (org-indent-line-function))
14528 (insert ":" property ":")
14529 (and value (insert " " value))
14530 (org-indent-line-function)))))
14531 (run-hook-with-args 'org-property-changed-functions property value)))
14533 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14534 "Get all property keys in the current buffer.
14535 With INCLUDE-SPECIALS, also list the special properties that reflect things
14536 like tags and TODO state.
14537 With INCLUDE-DEFAULTS, also include properties that has special meaning
14538 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14539 and others.
14540 With INCLUDE-COLUMNS, also include property names given in COLUMN
14541 formats in the current buffer."
14542 (let (rtn range cfmt s p)
14543 (save-excursion
14544 (save-restriction
14545 (widen)
14546 (goto-char (point-min))
14547 (while (re-search-forward org-property-start-re nil t)
14548 (setq range (org-get-property-block))
14549 (goto-char (car range))
14550 (while (re-search-forward
14551 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14552 (cdr range) t)
14553 (add-to-list 'rtn (org-match-string-no-properties 1)))
14554 (outline-next-heading))))
14556 (when include-specials
14557 (setq rtn (append org-special-properties rtn)))
14559 (when include-defaults
14560 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14561 (add-to-list 'rtn org-effort-property))
14563 (when include-columns
14564 (save-excursion
14565 (save-restriction
14566 (widen)
14567 (goto-char (point-min))
14568 (while (re-search-forward
14569 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14570 nil t)
14571 (setq cfmt (match-string 2) s 0)
14572 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14573 cfmt s)
14574 (setq s (match-end 0)
14575 p (match-string 1 cfmt))
14576 (unless (or (equal p "ITEM")
14577 (member p org-special-properties))
14578 (add-to-list 'rtn (match-string 1 cfmt))))))))
14580 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14582 (defun org-property-values (key)
14583 "Return a list of all values of property KEY in the current buffer."
14584 (save-excursion
14585 (save-restriction
14586 (widen)
14587 (goto-char (point-min))
14588 (let ((re (org-re-property key))
14589 values)
14590 (while (re-search-forward re nil t)
14591 (add-to-list 'values (org-trim (match-string 1))))
14592 (delete "" values)))))
14594 (defun org-insert-property-drawer ()
14595 "Insert a property drawer into the current entry."
14596 (org-back-to-heading t)
14597 (looking-at org-outline-regexp)
14598 (let ((indent (if org-adapt-indentation
14599 (- (match-end 0) (match-beginning 0))
14601 (beg (point))
14602 (re (concat "^[ \t]*" org-keyword-time-regexp))
14603 end hiddenp)
14604 (outline-next-heading)
14605 (setq end (point))
14606 (goto-char beg)
14607 (while (re-search-forward re end t))
14608 (setq hiddenp (outline-invisible-p))
14609 (end-of-line 1)
14610 (and (equal (char-after) ?\n) (forward-char 1))
14611 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14612 (if (member (match-string 1) '("CLOCK:" ":END:"))
14613 ;; just skip this line
14614 (beginning-of-line 2)
14615 ;; Drawer start, find the end
14616 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14617 (beginning-of-line 1)))
14618 (org-skip-over-state-notes)
14619 (skip-chars-backward " \t\n\r")
14620 (if (eq (char-before) ?*) (forward-char 1))
14621 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14622 (beginning-of-line 0)
14623 (org-indent-to-column indent)
14624 (beginning-of-line 2)
14625 (org-indent-to-column indent)
14626 (beginning-of-line 0)
14627 (if hiddenp
14628 (save-excursion
14629 (org-back-to-heading t)
14630 (hide-entry))
14631 (org-flag-drawer t))))
14633 (defun org-insert-drawer (&optional arg drawer)
14634 "Insert a drawer at point.
14636 Optional argument DRAWER, when non-nil, is a string representing
14637 drawer's name. Otherwise, the user is prompted for a name.
14639 If a region is active, insert the drawer around that region
14640 instead.
14642 Point is left between drawer's boundaries."
14643 (interactive "P")
14644 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14645 "LOGBOOK"))
14646 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14647 ;; internally by Org. They are meant to be inserted
14648 ;; automatically.
14649 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14650 ;; Remove system drawers from list. Note: For some reason,
14651 ;; `org-completing-read' ignores the predicate while
14652 ;; `completing-read' handles it fine.
14653 (drawer (if arg "PROPERTIES"
14654 (or drawer
14655 (completing-read
14656 "Drawer: " org-drawers
14657 (lambda (d) (not (member d system-drawers))))))))
14658 (cond
14659 ;; With C-u, fall back on `org-insert-property-drawer'
14660 (arg (org-insert-property-drawer))
14661 ;; With an active region, insert a drawer at point.
14662 ((not (org-region-active-p))
14663 (progn
14664 (unless (bolp) (insert "\n"))
14665 (insert (format ":%s:\n\n:END:\n" drawer))
14666 (forward-line -2)))
14667 ;; Otherwise, insert the drawer at point
14669 (let ((rbeg (region-beginning))
14670 (rend (copy-marker (region-end))))
14671 (unwind-protect
14672 (progn
14673 (goto-char rbeg)
14674 (beginning-of-line)
14675 (when (save-excursion
14676 (re-search-forward org-outline-regexp-bol rend t))
14677 (error "Drawers cannot contain headlines"))
14678 ;; Position point at the beginning of the first
14679 ;; non-blank line in region. Insert drawer's opening
14680 ;; there, then indent it.
14681 (org-skip-whitespace)
14682 (beginning-of-line)
14683 (insert ":" drawer ":\n")
14684 (forward-line -1)
14685 (indent-for-tab-command)
14686 ;; Move point to the beginning of the first blank line
14687 ;; after the last non-blank line in region. Insert
14688 ;; drawer's closing, then indent it.
14689 (goto-char rend)
14690 (skip-chars-backward " \r\t\n")
14691 (insert "\n:END:")
14692 (indent-for-tab-command)
14693 (unless (eolp) (insert "\n")))
14694 ;; Clear marker, whatever the outcome of insertion is.
14695 (set-marker rend nil)))))))
14697 (defvar org-property-set-functions-alist nil
14698 "Property set function alist.
14699 Each entry should have the following format:
14701 (PROPERTY . READ-FUNCTION)
14703 The read function will be called with the same argument as
14704 `org-completing-read'.")
14706 (defun org-set-property-function (property)
14707 "Get the function that should be used to set PROPERTY.
14708 This is computed according to `org-property-set-functions-alist'."
14709 (or (cdr (assoc property org-property-set-functions-alist))
14710 'org-completing-read))
14712 (defun org-read-property-value (property)
14713 "Read PROPERTY value from user."
14714 (let* ((completion-ignore-case t)
14715 (allowed (org-property-get-allowed-values nil property 'table))
14716 (cur (org-entry-get nil property))
14717 (prompt (concat property " value"
14718 (if (and cur (string-match "\\S-" cur))
14719 (concat " [" cur "]") "") ": "))
14720 (set-function (org-set-property-function property))
14721 (val (if allowed
14722 (funcall set-function prompt allowed nil
14723 (not (get-text-property 0 'org-unrestricted
14724 (caar allowed))))
14725 (let (org-completion-use-ido org-completion-use-iswitchb)
14726 (funcall set-function prompt
14727 (mapcar 'list (org-property-values property))
14728 nil nil "" nil cur)))))
14729 (if (equal val "")
14731 val)))
14733 (defvar org-last-set-property nil)
14734 (defun org-read-property-name ()
14735 "Read a property name."
14736 (let* ((completion-ignore-case t)
14737 (keys (org-buffer-property-keys nil t t))
14738 (default-prop (or (save-excursion
14739 (save-match-data
14740 (beginning-of-line)
14741 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14742 (null (string= (match-string 1) "END"))
14743 (match-string 1))))
14744 org-last-set-property))
14745 (property (org-icompleting-read
14746 (concat "Property"
14747 (if default-prop (concat " [" default-prop "]") "")
14748 ": ")
14749 (mapcar 'list keys)
14750 nil nil nil nil
14751 default-prop
14753 (if (member property keys)
14754 property
14755 (or (cdr (assoc (downcase property)
14756 (mapcar (lambda (x) (cons (downcase x) x))
14757 keys)))
14758 property))))
14760 (defun org-set-property (property value)
14761 "In the current entry, set PROPERTY to VALUE.
14762 When called interactively, this will prompt for a property name, offering
14763 completion on existing and default properties. And then it will prompt
14764 for a value, offering completion either on allowed values (via an inherited
14765 xxx_ALL property) or on existing values in other instances of this property
14766 in the current file."
14767 (interactive (list nil nil))
14768 (let* ((property (or property (org-read-property-name)))
14769 (value (or value (org-read-property-value property)))
14770 (fn (cdr (assoc property org-properties-postprocess-alist))))
14771 (setq org-last-set-property property)
14772 ;; Possibly postprocess the inserted value:
14773 (when fn (setq value (funcall fn value)))
14774 (unless (equal (org-entry-get nil property) value)
14775 (org-entry-put nil property value))))
14777 (defun org-delete-property (property)
14778 "In the current entry, delete PROPERTY."
14779 (interactive
14780 (let* ((completion-ignore-case t)
14781 (prop (org-icompleting-read "Property: "
14782 (org-entry-properties nil 'standard))))
14783 (list prop)))
14784 (message "Property %s %s" property
14785 (if (org-entry-delete nil property)
14786 "deleted"
14787 "was not present in the entry")))
14789 (defun org-delete-property-globally (property)
14790 "Remove PROPERTY globally, from all entries."
14791 (interactive
14792 (let* ((completion-ignore-case t)
14793 (prop (org-icompleting-read
14794 "Globally remove property: "
14795 (mapcar 'list (org-buffer-property-keys)))))
14796 (list prop)))
14797 (save-excursion
14798 (save-restriction
14799 (widen)
14800 (goto-char (point-min))
14801 (let ((cnt 0))
14802 (while (re-search-forward
14803 (org-re-property property)
14804 nil t)
14805 (setq cnt (1+ cnt))
14806 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14807 (message "Property \"%s\" removed from %d entries" property cnt)))))
14809 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14811 (defun org-compute-property-at-point ()
14812 "Compute the property at point.
14813 This looks for an enclosing column format, extracts the operator and
14814 then applies it to the property in the column format's scope."
14815 (interactive)
14816 (unless (org-at-property-p)
14817 (error "Not at a property"))
14818 (let ((prop (org-match-string-no-properties 2)))
14819 (org-columns-get-format-and-top-level)
14820 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14821 (error "No operator defined for property %s" prop))
14822 (org-columns-compute prop)))
14824 (defvar org-property-allowed-value-functions nil
14825 "Hook for functions supplying allowed values for a specific property.
14826 The functions must take a single argument, the name of the property, and
14827 return a flat list of allowed values. If \":ETC\" is one of
14828 the values, this means that these values are intended as defaults for
14829 completion, but that other values should be allowed too.
14830 The functions must return nil if they are not responsible for this
14831 property.")
14833 (defun org-property-get-allowed-values (pom property &optional table)
14834 "Get allowed values for the property PROPERTY.
14835 When TABLE is non-nil, return an alist that can directly be used for
14836 completion."
14837 (let (vals)
14838 (cond
14839 ((equal property "TODO")
14840 (setq vals (org-with-point-at pom
14841 (append org-todo-keywords-1 '("")))))
14842 ((equal property "PRIORITY")
14843 (let ((n org-lowest-priority))
14844 (while (>= n org-highest-priority)
14845 (push (char-to-string n) vals)
14846 (setq n (1- n)))))
14847 ((member property org-special-properties))
14848 ((setq vals (run-hook-with-args-until-success
14849 'org-property-allowed-value-functions property)))
14851 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14852 (when (and vals (string-match "\\S-" vals))
14853 (setq vals (car (read-from-string (concat "(" vals ")"))))
14854 (setq vals (mapcar (lambda (x)
14855 (cond ((stringp x) x)
14856 ((numberp x) (number-to-string x))
14857 ((symbolp x) (symbol-name x))
14858 (t "???")))
14859 vals)))))
14860 (when (member ":ETC" vals)
14861 (setq vals (remove ":ETC" vals))
14862 (org-add-props (car vals) '(org-unrestricted t)))
14863 (if table (mapcar 'list vals) vals)))
14865 (defun org-property-previous-allowed-value (&optional previous)
14866 "Switch to the next allowed value for this property."
14867 (interactive)
14868 (org-property-next-allowed-value t))
14870 (defun org-property-next-allowed-value (&optional previous)
14871 "Switch to the next allowed value for this property."
14872 (interactive)
14873 (unless (org-at-property-p)
14874 (error "Not at a property"))
14875 (let* ((key (match-string 2))
14876 (value (match-string 3))
14877 (allowed (or (org-property-get-allowed-values (point) key)
14878 (and (member value '("[ ]" "[-]" "[X]"))
14879 '("[ ]" "[X]"))))
14880 nval)
14881 (unless allowed
14882 (error "Allowed values for this property have not been defined"))
14883 (if previous (setq allowed (reverse allowed)))
14884 (if (member value allowed)
14885 (setq nval (car (cdr (member value allowed)))))
14886 (setq nval (or nval (car allowed)))
14887 (if (equal nval value)
14888 (error "Only one allowed value for this property"))
14889 (org-at-property-p)
14890 (replace-match (concat " :" key ": " nval) t t)
14891 (org-indent-line-function)
14892 (beginning-of-line 1)
14893 (skip-chars-forward " \t")
14894 (run-hook-with-args 'org-property-changed-functions key nval)))
14896 (defun org-find-olp (path &optional this-buffer)
14897 "Return a marker pointing to the entry at outline path OLP.
14898 If anything goes wrong, throw an error.
14899 You can wrap this call to catch the error like this:
14901 (condition-case msg
14902 (org-mobile-locate-entry (match-string 4))
14903 (error (nth 1 msg)))
14905 The return value will then be either a string with the error message,
14906 or a marker if everything is OK.
14908 If THIS-BUFFER is set, the outline path does not contain a file,
14909 only headings."
14910 (let* ((file (if this-buffer buffer-file-name (pop path)))
14911 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14912 (level 1)
14913 (lmin 1)
14914 (lmax 1)
14915 limit re end found pos heading cnt flevel)
14916 (unless buffer (error "File not found :%s" file))
14917 (with-current-buffer buffer
14918 (save-excursion
14919 (save-restriction
14920 (widen)
14921 (setq limit (point-max))
14922 (goto-char (point-min))
14923 (while (setq heading (pop path))
14924 (setq re (format org-complex-heading-regexp-format
14925 (regexp-quote heading)))
14926 (setq cnt 0 pos (point))
14927 (while (re-search-forward re end t)
14928 (setq level (- (match-end 1) (match-beginning 1)))
14929 (if (and (>= level lmin) (<= level lmax))
14930 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14931 (when (= cnt 0) (error "Heading not found on level %d: %s"
14932 lmax heading))
14933 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14934 lmax heading))
14935 (goto-char found)
14936 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14937 (setq end (save-excursion (org-end-of-subtree t t))))
14938 (when (org-at-heading-p)
14939 (move-marker (make-marker) (point))))))))
14941 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14942 "Find node HEADING in BUFFER.
14943 Return a marker to the heading if it was found, or nil if not.
14944 If POS-ONLY is set, return just the position instead of a marker.
14946 The heading text must match exact, but it may have a TODO keyword,
14947 a priority cookie and tags in the standard locations."
14948 (with-current-buffer (or buffer (current-buffer))
14949 (save-excursion
14950 (save-restriction
14951 (widen)
14952 (goto-char (point-min))
14953 (let (case-fold-search)
14954 (if (re-search-forward
14955 (format org-complex-heading-regexp-format
14956 (regexp-quote heading)) nil t)
14957 (if pos-only
14958 (match-beginning 0)
14959 (move-marker (make-marker) (match-beginning 0)))))))))
14961 (defun org-find-exact-heading-in-directory (heading &optional dir)
14962 "Find Org node headline HEADING in all .org files in directory DIR.
14963 When the target headline is found, return a marker to this location."
14964 (let ((files (directory-files (or dir default-directory)
14965 nil "\\`[^.#].*\\.org\\'"))
14966 file visiting m buffer)
14967 (catch 'found
14968 (while (setq file (pop files))
14969 (message "trying %s" file)
14970 (setq visiting (org-find-base-buffer-visiting file))
14971 (setq buffer (or visiting (find-file-noselect file)))
14972 (setq m (org-find-exact-headline-in-buffer
14973 heading buffer))
14974 (when (and (not m) (not visiting)) (kill-buffer buffer))
14975 (and m (throw 'found m))))))
14977 (defun org-find-entry-with-id (ident)
14978 "Locate the entry that contains the ID property with exact value IDENT.
14979 IDENT can be a string, a symbol or a number, this function will search for
14980 the string representation of it.
14981 Return the position where this entry starts, or nil if there is no such entry."
14982 (interactive "sID: ")
14983 (let ((id (cond
14984 ((stringp ident) ident)
14985 ((symbol-name ident) (symbol-name ident))
14986 ((numberp ident) (number-to-string ident))
14987 (t (error "IDENT %s must be a string, symbol or number" ident))))
14988 (case-fold-search nil))
14989 (save-excursion
14990 (save-restriction
14991 (widen)
14992 (goto-char (point-min))
14993 (when (re-search-forward
14994 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14995 nil t)
14996 (org-back-to-heading t)
14997 (point))))))
14999 ;;;; Timestamps
15001 (defvar org-last-changed-timestamp nil)
15002 (defvar org-last-inserted-timestamp nil
15003 "The last time stamp inserted with `org-insert-time-stamp'.")
15004 (defvar org-time-was-given) ; dynamically scoped parameter
15005 (defvar org-end-time-was-given) ; dynamically scoped parameter
15006 (defvar org-ts-what) ; dynamically scoped parameter
15008 (defun org-time-stamp (arg &optional inactive)
15009 "Prompt for a date/time and insert a time stamp.
15010 If the user specifies a time like HH:MM or if this command is
15011 called with at least one prefix argument, the time stamp contains
15012 the date and the time. Otherwise, only the date is be included.
15014 All parts of a date not specified by the user is filled in from
15015 the current date/time. So if you just press return without
15016 typing anything, the time stamp will represent the current
15017 date/time.
15019 If there is already a timestamp at the cursor, it will be
15020 modified.
15022 With two universal prefix arguments, insert an active timestamp
15023 with the current time without prompting the user."
15024 (interactive "P")
15025 (let* ((ts nil)
15026 (default-time
15027 ;; Default time is either today, or, when entering a range,
15028 ;; the range start.
15029 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15030 (save-excursion
15031 (re-search-backward
15032 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15033 (- (point) 20) t)))
15034 (apply 'encode-time (org-parse-time-string (match-string 1)))
15035 (current-time)))
15036 (default-input (and ts (org-get-compact-tod ts)))
15037 (repeater (save-excursion
15038 (save-match-data
15039 (beginning-of-line)
15040 (when (re-search-forward
15041 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15042 (save-excursion (progn (end-of-line) (point))) t)
15043 (match-string 0)))))
15044 org-time-was-given org-end-time-was-given time)
15045 (cond
15046 ((and (org-at-timestamp-p t)
15047 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15048 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15049 (insert "--")
15050 (setq time (let ((this-command this-command))
15051 (org-read-date arg 'totime nil nil
15052 default-time default-input inactive)))
15053 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15054 ((org-at-timestamp-p t)
15055 (setq time (let ((this-command this-command))
15056 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15057 (when (org-at-timestamp-p t) ; just to get the match data
15058 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15059 (replace-match "")
15060 (setq org-last-changed-timestamp
15061 (org-insert-time-stamp
15062 time (or org-time-was-given arg)
15063 inactive nil nil (list org-end-time-was-given)))
15064 (when repeater (goto-char (1- (point))) (insert " " repeater)
15065 (setq org-last-changed-timestamp
15066 (concat (substring org-last-inserted-timestamp 0 -1)
15067 " " repeater ">"))))
15068 (message "Timestamp updated"))
15069 ((equal arg '(16))
15070 (org-insert-time-stamp (current-time) t))
15072 (setq time (let ((this-command this-command))
15073 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15074 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15075 nil nil (list org-end-time-was-given))))))
15077 ;; FIXME: can we use this for something else, like computing time differences?
15078 (defun org-get-compact-tod (s)
15079 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15080 (let* ((t1 (match-string 1 s))
15081 (h1 (string-to-number (match-string 2 s)))
15082 (m1 (string-to-number (match-string 3 s)))
15083 (t2 (and (match-end 4) (match-string 5 s)))
15084 (h2 (and t2 (string-to-number (match-string 6 s))))
15085 (m2 (and t2 (string-to-number (match-string 7 s))))
15086 dh dm)
15087 (if (not t2)
15089 (setq dh (- h2 h1) dm (- m2 m1))
15090 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15091 (concat t1 "+" (number-to-string dh)
15092 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15094 (defun org-time-stamp-inactive (&optional arg)
15095 "Insert an inactive time stamp.
15096 An inactive time stamp is enclosed in square brackets instead of angle
15097 brackets. It is inactive in the sense that it does not trigger agenda entries,
15098 does not link to the calendar and cannot be changed with the S-cursor keys.
15099 So these are more for recording a certain time/date."
15100 (interactive "P")
15101 (org-time-stamp arg 'inactive))
15103 (defvar org-date-ovl (make-overlay 1 1))
15104 (overlay-put org-date-ovl 'face 'org-date-selected)
15105 (org-detach-overlay org-date-ovl)
15107 (defvar org-ans1) ; dynamically scoped parameter
15108 (defvar org-ans2) ; dynamically scoped parameter
15110 (defvar org-plain-time-of-day-regexp) ; defined below
15112 (defvar org-overriding-default-time nil) ; dynamically scoped
15113 (defvar org-read-date-overlay nil)
15114 (defvar org-dcst nil) ; dynamically scoped
15115 (defvar org-read-date-history nil)
15116 (defvar org-read-date-final-answer nil)
15117 (defvar org-read-date-analyze-futurep nil)
15118 (defvar org-read-date-analyze-forced-year nil)
15119 (defvar org-read-date-inactive)
15121 (defun org-read-date (&optional org-with-time to-time from-string prompt
15122 default-time default-input inactive)
15123 "Read a date, possibly a time, and make things smooth for the user.
15124 The prompt will suggest to enter an ISO date, but you can also enter anything
15125 which will at least partially be understood by `parse-time-string'.
15126 Unrecognized parts of the date will default to the current day, month, year,
15127 hour and minute. If this command is called to replace a timestamp at point,
15128 or to enter the second timestamp of a range, the default time is taken
15129 from the existing stamp. Furthermore, the command prefers the future,
15130 so if you are giving a date where the year is not given, and the day-month
15131 combination is already past in the current year, it will assume you
15132 mean next year. For details, see the manual. A few examples:
15134 3-2-5 --> 2003-02-05
15135 feb 15 --> currentyear-02-15
15136 2/15 --> currentyear-02-15
15137 sep 12 9 --> 2009-09-12
15138 12:45 --> today 12:45
15139 22 sept 0:34 --> currentyear-09-22 0:34
15140 12 --> currentyear-currentmonth-12
15141 Fri --> nearest Friday (today or later)
15142 etc.
15144 Furthermore you can specify a relative date by giving, as the *first* thing
15145 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15146 change in days weeks, months, years.
15147 With a single plus or minus, the date is relative to today. With a double
15148 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15149 +4d --> four days from today
15150 +4 --> same as above
15151 +2w --> two weeks from today
15152 ++5 --> five days from default date
15154 The function understands only English month and weekday abbreviations.
15156 While prompting, a calendar is popped up - you can also select the
15157 date with the mouse (button 1). The calendar shows a period of three
15158 months. To scroll it to other months, use the keys `>' and `<'.
15159 If you don't like the calendar, turn it off with
15160 \(setq org-read-date-popup-calendar nil)
15162 With optional argument TO-TIME, the date will immediately be converted
15163 to an internal time.
15164 With an optional argument WITH-TIME, the prompt will suggest to also
15165 insert a time. Note that when WITH-TIME is not set, you can still
15166 enter a time, and this function will inform the calling routine about
15167 this change. The calling routine may then choose to change the format
15168 used to insert the time stamp into the buffer to include the time.
15169 With optional argument FROM-STRING, read from this string instead from
15170 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15171 the time/date that is used for everything that is not specified by the
15172 user."
15173 (require 'parse-time)
15174 (let* ((org-time-stamp-rounding-minutes
15175 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15176 (org-dcst org-display-custom-times)
15177 (ct (org-current-time))
15178 (org-def (or org-overriding-default-time default-time ct))
15179 (org-defdecode (decode-time org-def))
15180 (dummy (progn
15181 (when (< (nth 2 org-defdecode) org-extend-today-until)
15182 (setcar (nthcdr 2 org-defdecode) -1)
15183 (setcar (nthcdr 1 org-defdecode) 59)
15184 (setq org-def (apply 'encode-time org-defdecode)
15185 org-defdecode (decode-time org-def)))))
15186 (calendar-frame-setup nil)
15187 (calendar-setup nil)
15188 (calendar-move-hook nil)
15189 (calendar-view-diary-initially-flag nil)
15190 (calendar-view-holidays-initially-flag nil)
15191 (timestr (format-time-string
15192 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15193 (prompt (concat (if prompt (concat prompt " ") "")
15194 (format "Date+time [%s]: " timestr)))
15195 ans (org-ans0 "") org-ans1 org-ans2 final)
15197 (cond
15198 (from-string (setq ans from-string))
15199 (org-read-date-popup-calendar
15200 (save-excursion
15201 (save-window-excursion
15202 (calendar)
15203 (org-eval-in-calendar '(setq cursor-type nil) t)
15204 (unwind-protect
15205 (progn
15206 (calendar-forward-day (- (time-to-days org-def)
15207 (calendar-absolute-from-gregorian
15208 (calendar-current-date))))
15209 (org-eval-in-calendar nil t)
15210 (let* ((old-map (current-local-map))
15211 (map (copy-keymap calendar-mode-map))
15212 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15213 (org-defkey map (kbd "RET") 'org-calendar-select)
15214 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15215 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15216 (org-defkey minibuffer-local-map [(meta shift left)]
15217 (lambda () (interactive)
15218 (org-eval-in-calendar '(calendar-backward-month 1))))
15219 (org-defkey minibuffer-local-map [(meta shift right)]
15220 (lambda () (interactive)
15221 (org-eval-in-calendar '(calendar-forward-month 1))))
15222 (org-defkey minibuffer-local-map [(meta shift up)]
15223 (lambda () (interactive)
15224 (org-eval-in-calendar '(calendar-backward-year 1))))
15225 (org-defkey minibuffer-local-map [(meta shift down)]
15226 (lambda () (interactive)
15227 (org-eval-in-calendar '(calendar-forward-year 1))))
15228 (org-defkey minibuffer-local-map [?\e (shift left)]
15229 (lambda () (interactive)
15230 (org-eval-in-calendar '(calendar-backward-month 1))))
15231 (org-defkey minibuffer-local-map [?\e (shift right)]
15232 (lambda () (interactive)
15233 (org-eval-in-calendar '(calendar-forward-month 1))))
15234 (org-defkey minibuffer-local-map [?\e (shift up)]
15235 (lambda () (interactive)
15236 (org-eval-in-calendar '(calendar-backward-year 1))))
15237 (org-defkey minibuffer-local-map [?\e (shift down)]
15238 (lambda () (interactive)
15239 (org-eval-in-calendar '(calendar-forward-year 1))))
15240 (org-defkey minibuffer-local-map [(shift up)]
15241 (lambda () (interactive)
15242 (org-eval-in-calendar '(calendar-backward-week 1))))
15243 (org-defkey minibuffer-local-map [(shift down)]
15244 (lambda () (interactive)
15245 (org-eval-in-calendar '(calendar-forward-week 1))))
15246 (org-defkey minibuffer-local-map [(shift left)]
15247 (lambda () (interactive)
15248 (org-eval-in-calendar '(calendar-backward-day 1))))
15249 (org-defkey minibuffer-local-map [(shift right)]
15250 (lambda () (interactive)
15251 (org-eval-in-calendar '(calendar-forward-day 1))))
15252 (org-defkey minibuffer-local-map ">"
15253 (lambda () (interactive)
15254 (org-eval-in-calendar '(scroll-calendar-left 1))))
15255 (org-defkey minibuffer-local-map "<"
15256 (lambda () (interactive)
15257 (org-eval-in-calendar '(scroll-calendar-right 1))))
15258 (org-defkey minibuffer-local-map "\C-v"
15259 (lambda () (interactive)
15260 (org-eval-in-calendar
15261 '(calendar-scroll-left-three-months 1))))
15262 (org-defkey minibuffer-local-map "\M-v"
15263 (lambda () (interactive)
15264 (org-eval-in-calendar
15265 '(calendar-scroll-right-three-months 1))))
15266 (run-hooks 'org-read-date-minibuffer-setup-hook)
15267 (unwind-protect
15268 (progn
15269 (use-local-map map)
15270 (setq org-read-date-inactive inactive)
15271 (add-hook 'post-command-hook 'org-read-date-display)
15272 (setq org-ans0 (read-string prompt default-input
15273 'org-read-date-history nil))
15274 ;; org-ans0: from prompt
15275 ;; org-ans1: from mouse click
15276 ;; org-ans2: from calendar motion
15277 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15278 (remove-hook 'post-command-hook 'org-read-date-display)
15279 (use-local-map old-map)
15280 (when org-read-date-overlay
15281 (delete-overlay org-read-date-overlay)
15282 (setq org-read-date-overlay nil)))))
15283 (bury-buffer "*Calendar*")))))
15285 (t ; Naked prompt only
15286 (unwind-protect
15287 (setq ans (read-string prompt default-input
15288 'org-read-date-history timestr))
15289 (when org-read-date-overlay
15290 (delete-overlay org-read-date-overlay)
15291 (setq org-read-date-overlay nil)))))
15293 (setq final (org-read-date-analyze ans org-def org-defdecode))
15295 (when org-read-date-analyze-forced-year
15296 (message "Year was forced into %s"
15297 (if org-read-date-force-compatible-dates
15298 "compatible range (1970-2037)"
15299 "range representable on this machine"))
15300 (ding))
15302 ;; One round trip to get rid of 34th of August and stuff like that....
15303 (setq final (decode-time (apply 'encode-time final)))
15305 (setq org-read-date-final-answer ans)
15307 (if to-time
15308 (apply 'encode-time final)
15309 (if (and (boundp 'org-time-was-given) org-time-was-given)
15310 (format "%04d-%02d-%02d %02d:%02d"
15311 (nth 5 final) (nth 4 final) (nth 3 final)
15312 (nth 2 final) (nth 1 final))
15313 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15315 (defvar org-def)
15316 (defvar org-defdecode)
15317 (defvar org-with-time)
15318 (defun org-read-date-display ()
15319 "Display the current date prompt interpretation in the minibuffer."
15320 (when org-read-date-display-live
15321 (when org-read-date-overlay
15322 (delete-overlay org-read-date-overlay))
15323 (when (minibufferp (current-buffer))
15324 (save-excursion
15325 (end-of-line 1)
15326 (while (not (equal (buffer-substring
15327 (max (point-min) (- (point) 4)) (point))
15328 " "))
15329 (insert " ")))
15330 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15331 " " (or org-ans1 org-ans2)))
15332 (org-end-time-was-given nil)
15333 (f (org-read-date-analyze ans org-def org-defdecode))
15334 (fmts (if org-dcst
15335 org-time-stamp-custom-formats
15336 org-time-stamp-formats))
15337 (fmt (if (or org-with-time
15338 (and (boundp 'org-time-was-given) org-time-was-given))
15339 (cdr fmts)
15340 (car fmts)))
15341 (txt (format-time-string fmt (apply 'encode-time f)))
15342 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15343 (txt (concat "=> " txt)))
15344 (when (and org-end-time-was-given
15345 (string-match org-plain-time-of-day-regexp txt))
15346 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15347 org-end-time-was-given
15348 (substring txt (match-end 0)))))
15349 (when org-read-date-analyze-futurep
15350 (setq txt (concat txt " (=>F)")))
15351 (setq org-read-date-overlay
15352 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15353 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15355 (defun org-read-date-analyze (ans org-def org-defdecode)
15356 "Analyze the combined answer of the date prompt."
15357 ;; FIXME: cleanup and comment
15358 (let ((nowdecode (decode-time (current-time)))
15359 delta deltan deltaw deltadef year month day
15360 hour minute second wday pm h2 m2 tl wday1
15361 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15362 (setq org-read-date-analyze-futurep nil
15363 org-read-date-analyze-forced-year nil)
15364 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15365 (setq ans "+0"))
15367 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15368 (setq ans (replace-match "" t t ans)
15369 deltan (car delta)
15370 deltaw (nth 1 delta)
15371 deltadef (nth 2 delta)))
15373 ;; Check if there is an iso week date in there
15374 ;; If yes, store the info and postpone interpreting it until the rest
15375 ;; of the parsing is done
15376 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15377 (setq iso-year (if (match-end 1)
15378 (org-small-year-to-year
15379 (string-to-number (match-string 1 ans))))
15380 iso-weekday (if (match-end 3)
15381 (string-to-number (match-string 3 ans)))
15382 iso-week (string-to-number (match-string 2 ans)))
15383 (setq ans (replace-match "" t t ans)))
15385 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15386 (when (string-match
15387 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15388 (setq year (if (match-end 2)
15389 (string-to-number (match-string 2 ans))
15390 (progn (setq kill-year t)
15391 (string-to-number (format-time-string "%Y"))))
15392 month (string-to-number (match-string 3 ans))
15393 day (string-to-number (match-string 4 ans)))
15394 (if (< year 100) (setq year (+ 2000 year)))
15395 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15396 t nil ans)))
15398 ;; Help matching dotted european dates
15399 (when (string-match
15400 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15401 (setq year (if (match-end 3)
15402 (string-to-number (match-string 3 ans))
15403 (progn (setq kill-year t)
15404 (string-to-number (format-time-string "%Y"))))
15405 day (string-to-number (match-string 1 ans))
15406 month (string-to-number (match-string 2 ans))
15407 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15408 t nil ans)))
15410 ;; Help matching american dates, like 5/30 or 5/30/7
15411 (when (string-match
15412 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15413 (setq year (if (match-end 4)
15414 (string-to-number (match-string 4 ans))
15415 (progn (setq kill-year t)
15416 (string-to-number (format-time-string "%Y"))))
15417 month (string-to-number (match-string 1 ans))
15418 day (string-to-number (match-string 2 ans)))
15419 (if (< year 100) (setq year (+ 2000 year)))
15420 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15421 t nil ans)))
15422 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15423 ;; If there is a time with am/pm, and *no* time without it, we convert
15424 ;; so that matching will be successful.
15425 (loop for i from 1 to 2 do ; twice, for end time as well
15426 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15427 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15428 (setq hour (string-to-number (match-string 1 ans))
15429 minute (if (match-end 3)
15430 (string-to-number (match-string 3 ans))
15432 pm (equal ?p
15433 (string-to-char (downcase (match-string 4 ans)))))
15434 (if (and (= hour 12) (not pm))
15435 (setq hour 0)
15436 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15437 (setq ans (replace-match (format "%02d:%02d" hour minute)
15438 t t ans))))
15440 ;; Check if a time range is given as a duration
15441 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15442 (setq hour (string-to-number (match-string 1 ans))
15443 h2 (+ hour (string-to-number (match-string 3 ans)))
15444 minute (string-to-number (match-string 2 ans))
15445 m2 (+ minute (if (match-end 5) (string-to-number
15446 (match-string 5 ans))0)))
15447 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15448 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15449 t t ans)))
15451 ;; Check if there is a time range
15452 (when (boundp 'org-end-time-was-given)
15453 (setq org-time-was-given nil)
15454 (when (and (string-match org-plain-time-of-day-regexp ans)
15455 (match-end 8))
15456 (setq org-end-time-was-given (match-string 8 ans))
15457 (setq ans (concat (substring ans 0 (match-beginning 7))
15458 (substring ans (match-end 7))))))
15460 (setq tl (parse-time-string ans)
15461 day (or (nth 3 tl) (nth 3 org-defdecode))
15462 month (or (nth 4 tl)
15463 (if (and org-read-date-prefer-future
15464 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15465 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15466 (nth 4 org-defdecode)))
15467 year (or (and (not kill-year) (nth 5 tl))
15468 (if (and org-read-date-prefer-future
15469 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15470 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15471 (nth 5 org-defdecode)))
15472 hour (or (nth 2 tl) (nth 2 org-defdecode))
15473 minute (or (nth 1 tl) (nth 1 org-defdecode))
15474 second (or (nth 0 tl) 0)
15475 wday (nth 6 tl))
15477 (when (and (eq org-read-date-prefer-future 'time)
15478 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15479 (equal day (nth 3 nowdecode))
15480 (equal month (nth 4 nowdecode))
15481 (equal year (nth 5 nowdecode))
15482 (nth 2 tl)
15483 (or (< (nth 2 tl) (nth 2 nowdecode))
15484 (and (= (nth 2 tl) (nth 2 nowdecode))
15485 (nth 1 tl)
15486 (< (nth 1 tl) (nth 1 nowdecode)))))
15487 (setq day (1+ day)
15488 futurep t))
15490 ;; Special date definitions below
15491 (cond
15492 (iso-week
15493 ;; There was an iso week
15494 (require 'cal-iso)
15495 (setq futurep nil)
15496 (setq year (or iso-year year)
15497 day (or iso-weekday wday 1)
15498 wday nil ; to make sure that the trigger below does not match
15499 iso-date (calendar-gregorian-from-absolute
15500 (calendar-absolute-from-iso
15501 (list iso-week day year))))
15502 ; FIXME: Should we also push ISO weeks into the future?
15503 ; (when (and org-read-date-prefer-future
15504 ; (not iso-year)
15505 ; (< (calendar-absolute-from-gregorian iso-date)
15506 ; (time-to-days (current-time))))
15507 ; (setq year (1+ year)
15508 ; iso-date (calendar-gregorian-from-absolute
15509 ; (calendar-absolute-from-iso
15510 ; (list iso-week day year)))))
15511 (setq month (car iso-date)
15512 year (nth 2 iso-date)
15513 day (nth 1 iso-date)))
15514 (deltan
15515 (setq futurep nil)
15516 (unless deltadef
15517 (let ((now (decode-time (current-time))))
15518 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15519 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15520 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15521 ((equal deltaw "m") (setq month (+ month deltan)))
15522 ((equal deltaw "y") (setq year (+ year deltan)))))
15523 ((and wday (not (nth 3 tl)))
15524 (setq futurep nil)
15525 ;; Weekday was given, but no day, so pick that day in the week
15526 ;; on or after the derived date.
15527 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15528 (unless (equal wday wday1)
15529 (setq day (+ day (% (- wday wday1 -7) 7))))))
15530 (if (and (boundp 'org-time-was-given)
15531 (nth 2 tl))
15532 (setq org-time-was-given t))
15533 (if (< year 100) (setq year (+ 2000 year)))
15534 ;; Check of the date is representable
15535 (if org-read-date-force-compatible-dates
15536 (progn
15537 (if (< year 1970)
15538 (setq year 1970 org-read-date-analyze-forced-year t))
15539 (if (> year 2037)
15540 (setq year 2037 org-read-date-analyze-forced-year t)))
15541 (condition-case nil
15542 (ignore (encode-time second minute hour day month year))
15543 (error
15544 (setq year (nth 5 org-defdecode))
15545 (setq org-read-date-analyze-forced-year t))))
15546 (setq org-read-date-analyze-futurep futurep)
15547 (list second minute hour day month year)))
15549 (defvar parse-time-weekdays)
15550 (defun org-read-date-get-relative (s today default)
15551 "Check string S for special relative date string.
15552 TODAY and DEFAULT are internal times, for today and for a default.
15553 Return shift list (N what def-flag)
15554 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15555 N is the number of WHATs to shift.
15556 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15557 the DEFAULT date rather than TODAY."
15558 (require 'parse-time)
15559 (when (and
15560 (string-match
15561 (concat
15562 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15563 "\\([0-9]+\\)?"
15564 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15565 "\\([ \t]\\|$\\)") s)
15566 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15567 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15568 (string-to-char (substring (match-string 1 s) -1))
15569 ?+))
15570 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15571 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15572 (what (if (match-end 3) (match-string 3 s) "d"))
15573 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15574 (date (if rel default today))
15575 (wday (nth 6 (decode-time date)))
15576 delta)
15577 (if wday1
15578 (progn
15579 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15580 (if (= dir ?-) (setq delta (- delta 7)))
15581 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15582 (list delta "d" rel))
15583 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15585 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15586 "Turn a user-specified date into the internal representation.
15587 The internal representation needed by the calendar is (month day year).
15588 This is a wrapper to handle the brain-dead convention in calendar that
15589 user function argument order change dependent on argument order."
15590 (if (boundp 'calendar-date-style)
15591 (cond
15592 ((eq calendar-date-style 'american)
15593 (list arg1 arg2 arg3))
15594 ((eq calendar-date-style 'european)
15595 (list arg2 arg1 arg3))
15596 ((eq calendar-date-style 'iso)
15597 (list arg2 arg3 arg1)))
15598 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15599 (if (org-bound-and-true-p european-calendar-style)
15600 (list arg2 arg1 arg3)
15601 (list arg1 arg2 arg3)))))
15603 (defun org-eval-in-calendar (form &optional keepdate)
15604 "Eval FORM in the calendar window and return to current window.
15605 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15606 otherwise stick to the current value of `org-ans2'."
15607 (let ((sf (selected-frame))
15608 (sw (selected-window)))
15609 (select-window (get-buffer-window "*Calendar*" t))
15610 (eval form)
15611 (when (and (not keepdate) (calendar-cursor-to-date))
15612 (let* ((date (calendar-cursor-to-date))
15613 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15614 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15615 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15616 (select-window sw)
15617 (org-select-frame-set-input-focus sf)))
15619 (defun org-calendar-select ()
15620 "Return to `org-read-date' with the date currently selected.
15621 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15622 (interactive)
15623 (when (calendar-cursor-to-date)
15624 (let* ((date (calendar-cursor-to-date))
15625 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15626 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15627 (if (active-minibuffer-window) (exit-minibuffer))))
15629 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15630 "Insert a date stamp for the date given by the internal TIME.
15631 WITH-HM means use the stamp format that includes the time of the day.
15632 INACTIVE means use square brackets instead of angular ones, so that the
15633 stamp will not contribute to the agenda.
15634 PRE and POST are optional strings to be inserted before and after the
15635 stamp.
15636 The command returns the inserted time stamp."
15637 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15638 stamp)
15639 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15640 (insert-before-markers (or pre ""))
15641 (when (listp extra)
15642 (setq extra (car extra))
15643 (if (and (stringp extra)
15644 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15645 (setq extra (format "-%02d:%02d"
15646 (string-to-number (match-string 1 extra))
15647 (string-to-number (match-string 2 extra))))
15648 (setq extra nil)))
15649 (when extra
15650 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15651 (insert-before-markers (setq stamp (format-time-string fmt time)))
15652 (insert-before-markers (or post ""))
15653 (setq org-last-inserted-timestamp stamp)))
15655 (defun org-toggle-time-stamp-overlays ()
15656 "Toggle the use of custom time stamp formats."
15657 (interactive)
15658 (setq org-display-custom-times (not org-display-custom-times))
15659 (unless org-display-custom-times
15660 (let ((p (point-min)) (bmp (buffer-modified-p)))
15661 (while (setq p (next-single-property-change p 'display))
15662 (if (and (get-text-property p 'display)
15663 (eq (get-text-property p 'face) 'org-date))
15664 (remove-text-properties
15665 p (setq p (next-single-property-change p 'display))
15666 '(display t))))
15667 (set-buffer-modified-p bmp)))
15668 (if (featurep 'xemacs)
15669 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15670 (org-restart-font-lock)
15671 (setq org-table-may-need-update t)
15672 (if org-display-custom-times
15673 (message "Time stamps are overlaid with custom format")
15674 (message "Time stamp overlays removed")))
15676 (defun org-display-custom-time (beg end)
15677 "Overlay modified time stamp format over timestamp between BEG and END."
15678 (let* ((ts (buffer-substring beg end))
15679 t1 w1 with-hm tf time str w2 (off 0))
15680 (save-match-data
15681 (setq t1 (org-parse-time-string ts t))
15682 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15683 (setq off (- (match-end 0) (match-beginning 0)))))
15684 (setq end (- end off))
15685 (setq w1 (- end beg)
15686 with-hm (and (nth 1 t1) (nth 2 t1))
15687 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15688 time (org-fix-decoded-time t1)
15689 str (org-add-props
15690 (format-time-string
15691 (substring tf 1 -1) (apply 'encode-time time))
15692 nil 'mouse-face 'highlight)
15693 w2 (length str))
15694 (if (not (= w2 w1))
15695 (add-text-properties (1+ beg) (+ 2 beg)
15696 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15697 (if (featurep 'xemacs)
15698 (progn
15699 (put-text-property beg end 'invisible t)
15700 (put-text-property beg end 'end-glyph (make-glyph str)))
15701 (put-text-property beg end 'display str))))
15703 (defun org-translate-time (string)
15704 "Translate all timestamps in STRING to custom format.
15705 But do this only if the variable `org-display-custom-times' is set."
15706 (when org-display-custom-times
15707 (save-match-data
15708 (let* ((start 0)
15709 (re org-ts-regexp-both)
15710 t1 with-hm inactive tf time str beg end)
15711 (while (setq start (string-match re string start))
15712 (setq beg (match-beginning 0)
15713 end (match-end 0)
15714 t1 (save-match-data
15715 (org-parse-time-string (substring string beg end) t))
15716 with-hm (and (nth 1 t1) (nth 2 t1))
15717 inactive (equal (substring string beg (1+ beg)) "[")
15718 tf (funcall (if with-hm 'cdr 'car)
15719 org-time-stamp-custom-formats)
15720 time (org-fix-decoded-time t1)
15721 str (format-time-string
15722 (concat
15723 (if inactive "[" "<") (substring tf 1 -1)
15724 (if inactive "]" ">"))
15725 (apply 'encode-time time))
15726 string (replace-match str t t string)
15727 start (+ start (length str)))))))
15728 string)
15730 (defun org-fix-decoded-time (time)
15731 "Set 0 instead of nil for the first 6 elements of time.
15732 Don't touch the rest."
15733 (let ((n 0))
15734 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15736 (defun org-days-to-time (timestamp-string)
15737 "Difference between TIMESTAMP-STRING and now in days."
15738 (- (time-to-days (org-time-string-to-time timestamp-string))
15739 (time-to-days (current-time))))
15741 (defun org-deadline-close (timestamp-string &optional ndays)
15742 "Is the time in TIMESTAMP-STRING close to the current date?"
15743 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15744 (and (< (org-days-to-time timestamp-string) ndays)
15745 (not (org-entry-is-done-p))))
15747 (defun org-get-wdays (ts)
15748 "Get the deadline lead time appropriate for timestring TS."
15749 (cond
15750 ((<= org-deadline-warning-days 0)
15751 ;; 0 or negative, enforce this value no matter what
15752 (- org-deadline-warning-days))
15753 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15754 ;; lead time is specified.
15755 (floor (* (string-to-number (match-string 1 ts))
15756 (cdr (assoc (match-string 2 ts)
15757 '(("d" . 1) ("w" . 7)
15758 ("m" . 30.4) ("y" . 365.25)))))))
15759 ;; go for the default.
15760 (t org-deadline-warning-days)))
15762 (defun org-calendar-select-mouse (ev)
15763 "Return to `org-read-date' with the date currently selected.
15764 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15765 (interactive "e")
15766 (mouse-set-point ev)
15767 (when (calendar-cursor-to-date)
15768 (let* ((date (calendar-cursor-to-date))
15769 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15770 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15771 (if (active-minibuffer-window) (exit-minibuffer))))
15773 (defun org-check-deadlines (ndays)
15774 "Check if there are any deadlines due or past due.
15775 A deadline is considered due if it happens within `org-deadline-warning-days'
15776 days from today's date. If the deadline appears in an entry marked DONE,
15777 it is not shown. The prefix arg NDAYS can be used to test that many
15778 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15779 (interactive "P")
15780 (let* ((org-warn-days
15781 (cond
15782 ((equal ndays '(4)) 100000)
15783 (ndays (prefix-numeric-value ndays))
15784 (t (abs org-deadline-warning-days))))
15785 (case-fold-search nil)
15786 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15787 (callback
15788 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15790 (message "%d deadlines past-due or due within %d days"
15791 (org-occur regexp nil callback)
15792 org-warn-days)))
15794 (defun org-check-before-date (date)
15795 "Check if there are deadlines or scheduled entries before DATE."
15796 (interactive (list (org-read-date)))
15797 (let ((case-fold-search nil)
15798 (regexp (concat "\\<\\(" org-deadline-string
15799 "\\|" org-scheduled-string
15800 "\\) *<\\([^>]+\\)>"))
15801 (callback
15802 (lambda () (time-less-p
15803 (org-time-string-to-time (match-string 2))
15804 (org-time-string-to-time date)))))
15805 (message "%d entries before %s"
15806 (org-occur regexp nil callback) date)))
15808 (defun org-check-after-date (date)
15809 "Check if there are deadlines or scheduled entries after DATE."
15810 (interactive (list (org-read-date)))
15811 (let ((case-fold-search nil)
15812 (regexp (concat "\\<\\(" org-deadline-string
15813 "\\|" org-scheduled-string
15814 "\\) *<\\([^>]+\\)>"))
15815 (callback
15816 (lambda () (not
15817 (time-less-p
15818 (org-time-string-to-time (match-string 2))
15819 (org-time-string-to-time date))))))
15820 (message "%d entries after %s"
15821 (org-occur regexp nil callback) date)))
15823 (defun org-check-dates-range (start-date end-date)
15824 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15825 (interactive (list (org-read-date nil nil nil "Range starts")
15826 (org-read-date nil nil nil "Range end")))
15827 (let ((case-fold-search nil)
15828 (regexp (concat "\\<\\(" org-deadline-string
15829 "\\|" org-scheduled-string
15830 "\\) *<\\([^>]+\\)>"))
15831 (callback
15832 (lambda ()
15833 (let ((match (match-string 2)))
15834 (and
15835 (not (time-less-p
15836 (org-time-string-to-time match)
15837 (org-time-string-to-time start-date)))
15838 (time-less-p
15839 (org-time-string-to-time match)
15840 (org-time-string-to-time end-date)))))))
15841 (message "%d entries between %s and %s"
15842 (org-occur regexp nil callback) start-date end-date)))
15844 (defun org-evaluate-time-range (&optional to-buffer)
15845 "Evaluate a time range by computing the difference between start and end.
15846 Normally the result is just printed in the echo area, but with prefix arg
15847 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15848 If the time range is actually in a table, the result is inserted into the
15849 next column.
15850 For time difference computation, a year is assumed to be exactly 365
15851 days in order to avoid rounding problems."
15852 (interactive "P")
15854 (org-clock-update-time-maybe)
15855 (save-excursion
15856 (unless (org-at-date-range-p t)
15857 (goto-char (point-at-bol))
15858 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15859 (if (not (org-at-date-range-p t))
15860 (error "Not at a time-stamp range, and none found in current line")))
15861 (let* ((ts1 (match-string 1))
15862 (ts2 (match-string 2))
15863 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15864 (match-end (match-end 0))
15865 (time1 (org-time-string-to-time ts1))
15866 (time2 (org-time-string-to-time ts2))
15867 (t1 (org-float-time time1))
15868 (t2 (org-float-time time2))
15869 (diff (abs (- t2 t1)))
15870 (negative (< (- t2 t1) 0))
15871 ;; (ys (floor (* 365 24 60 60)))
15872 (ds (* 24 60 60))
15873 (hs (* 60 60))
15874 (fy "%dy %dd %02d:%02d")
15875 (fy1 "%dy %dd")
15876 (fd "%dd %02d:%02d")
15877 (fd1 "%dd")
15878 (fh "%02d:%02d")
15879 y d h m align)
15880 (if havetime
15881 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15883 d (floor (/ diff ds)) diff (mod diff ds)
15884 h (floor (/ diff hs)) diff (mod diff hs)
15885 m (floor (/ diff 60)))
15886 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15888 d (floor (+ (/ diff ds) 0.5))
15889 h 0 m 0))
15890 (if (not to-buffer)
15891 (message "%s" (org-make-tdiff-string y d h m))
15892 (if (org-at-table-p)
15893 (progn
15894 (goto-char match-end)
15895 (setq align t)
15896 (and (looking-at " *|") (goto-char (match-end 0))))
15897 (goto-char match-end))
15898 (if (looking-at
15899 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15900 (replace-match ""))
15901 (if negative (insert " -"))
15902 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15903 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15904 (insert " " (format fh h m))))
15905 (if align (org-table-align))
15906 (message "Time difference inserted")))))
15908 (defun org-make-tdiff-string (y d h m)
15909 (let ((fmt "")
15910 (l nil))
15911 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15912 l (push y l)))
15913 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15914 l (push d l)))
15915 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15916 l (push h l)))
15917 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15918 l (push m l)))
15919 (apply 'format fmt (nreverse l))))
15921 (defun org-time-string-to-time (s &optional buffer pos)
15922 (condition-case errdata
15923 (apply 'encode-time (org-parse-time-string s))
15924 (error (error "Bad timestamp `%s'%s\nError was: %s"
15925 s (if (not (and buffer pos))
15927 (format " at %d in buffer `%s'" pos buffer))
15928 (cdr errdata)))))
15930 (defun org-time-string-to-seconds (s)
15931 (org-float-time (org-time-string-to-time s)))
15933 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15934 "Convert a time stamp to an absolute day number.
15935 If there is a specifier for a cyclic time stamp, get the closest date to
15936 DAYNR.
15937 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15938 The variable date is bound by the calendar when this is called."
15939 (cond
15940 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15941 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15942 daynr
15943 (+ daynr 1000)))
15944 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
15945 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15946 (time-to-days (current-time))) (match-string 0 s)
15947 prefer show-all))
15948 (t (time-to-days
15949 (condition-case errdata
15950 (apply 'encode-time (org-parse-time-string s))
15951 (error (error "Bad timestamp `%s'%s\nError was: %s"
15952 s (if (not (and buffer pos))
15954 (format " at %d in buffer `%s'" pos buffer))
15955 (cdr errdata))))))))
15957 (defun org-days-to-iso-week (days)
15958 "Return the iso week number."
15959 (require 'cal-iso)
15960 (car (calendar-iso-from-absolute days)))
15962 (defun org-small-year-to-year (year)
15963 "Convert 2-digit years into 4-digit years.
15964 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15965 The year 2000 cannot be abbreviated. Any year larger than 99
15966 is returned unchanged."
15967 (if (< year 38)
15968 (setq year (+ 2000 year))
15969 (if (< year 100)
15970 (setq year (+ 1900 year))))
15971 year)
15973 (defun org-time-from-absolute (d)
15974 "Return the time corresponding to date D.
15975 D may be an absolute day number, or a calendar-type list (month day year)."
15976 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15977 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15979 (defun org-calendar-holiday ()
15980 "List of holidays, for Diary display in Org-mode."
15981 (require 'holidays)
15982 (let ((hl (funcall
15983 (if (fboundp 'calendar-check-holidays)
15984 'calendar-check-holidays 'check-calendar-holidays) date)))
15985 (if hl (mapconcat 'identity hl "; "))))
15987 (defun org-diary-sexp-entry (sexp entry date)
15988 "Process a SEXP diary ENTRY for DATE."
15989 (require 'diary-lib)
15990 (let ((result (if calendar-debug-sexp
15991 (let ((stack-trace-on-error t))
15992 (eval (car (read-from-string sexp))))
15993 (condition-case nil
15994 (eval (car (read-from-string sexp)))
15995 (error
15996 (beep)
15997 (message "Bad sexp at line %d in %s: %s"
15998 (org-current-line)
15999 (buffer-file-name) sexp)
16000 (sleep-for 2))))))
16001 (cond ((stringp result) (split-string result "; "))
16002 ((and (consp result)
16003 (not (consp (cdr result)))
16004 (stringp (cdr result))) (cdr result))
16005 ((and (consp result)
16006 (stringp (car result))) result)
16007 (result entry)
16008 (t nil))))
16010 (defun org-diary-to-ical-string (frombuf)
16011 "Get iCalendar entries from diary entries in buffer FROMBUF.
16012 This uses the icalendar.el library."
16013 (let* ((tmpdir (if (featurep 'xemacs)
16014 (temp-directory)
16015 temporary-file-directory))
16016 (tmpfile (make-temp-name
16017 (expand-file-name "orgics" tmpdir)))
16018 buf rtn b e)
16019 (with-current-buffer frombuf
16020 (icalendar-export-region (point-min) (point-max) tmpfile)
16021 (setq buf (find-buffer-visiting tmpfile))
16022 (set-buffer buf)
16023 (goto-char (point-min))
16024 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16025 (setq b (match-beginning 0)))
16026 (goto-char (point-max))
16027 (if (re-search-backward "^END:VEVENT" nil t)
16028 (setq e (match-end 0)))
16029 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16030 (kill-buffer buf)
16031 (delete-file tmpfile)
16032 rtn))
16034 (defun org-closest-date (start current change prefer show-all)
16035 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16036 When PREFER is `past', return a date that is either CURRENT or past.
16037 When PREFER is `future', return a date that is either CURRENT or future.
16038 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16039 ;; Make the proper lists from the dates
16040 (catch 'exit
16041 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16042 dn dw sday cday n1 n2 n0
16043 d m y y1 y2 date1 date2 nmonths nm ny m2)
16045 (setq start (org-date-to-gregorian start)
16046 current (org-date-to-gregorian
16047 (if show-all
16048 current
16049 (time-to-days (current-time))))
16050 sday (calendar-absolute-from-gregorian start)
16051 cday (calendar-absolute-from-gregorian current))
16053 (if (<= cday sday) (throw 'exit sday))
16055 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16056 (setq dn (string-to-number (match-string 1 change))
16057 dw (cdr (assoc (match-string 2 change) a1)))
16058 (error "Invalid change specifier: %s" change))
16059 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16060 (cond
16061 ((eq dw 'day)
16062 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16063 n2 (+ n1 dn)))
16064 ((eq dw 'year)
16065 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16066 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16067 (setq date1 (list m d y1)
16068 n1 (calendar-absolute-from-gregorian date1)
16069 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16070 n2 (calendar-absolute-from-gregorian date2)))
16071 ((eq dw 'month)
16072 ;; approx number of month between the two dates
16073 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16074 ;; How often does dn fit in there?
16075 (setq d (nth 1 start) m (car start) y (nth 2 start)
16076 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16077 m (+ m nm)
16078 ny (floor (/ m 12))
16079 y (+ y ny)
16080 m (- m (* ny 12)))
16081 (while (> m 12) (setq m (- m 12) y (1+ y)))
16082 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16083 (setq m2 (+ m dn) y2 y)
16084 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16085 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16086 (while (<= n2 cday)
16087 (setq n1 n2 m m2 y y2)
16088 (setq m2 (+ m dn) y2 y)
16089 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16090 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16091 ;; Make sure n1 is the earlier date
16092 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16093 (if show-all
16094 (cond
16095 ((eq prefer 'past) (if (= cday n2) n2 n1))
16096 ((eq prefer 'future) (if (= cday n1) n1 n2))
16097 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16098 (cond
16099 ((eq prefer 'past) (if (= cday n2) n2 n1))
16100 ((eq prefer 'future) (if (= cday n1) n1 n2))
16101 (t (if (= cday n1) n1 n2)))))))
16103 (defun org-date-to-gregorian (date)
16104 "Turn any specification of DATE into a Gregorian date for the calendar."
16105 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16106 ((and (listp date) (= (length date) 3)) date)
16107 ((stringp date)
16108 (setq date (org-parse-time-string date))
16109 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16110 ((listp date)
16111 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16113 (defun org-parse-time-string (s &optional nodefault)
16114 "Parse the standard Org-mode time string.
16115 This should be a lot faster than the normal `parse-time-string'.
16116 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16117 hour and minute fields will be nil if not given."
16118 (if (string-match org-ts-regexp0 s)
16119 (list 0
16120 (if (or (match-beginning 8) (not nodefault))
16121 (string-to-number (or (match-string 8 s) "0")))
16122 (if (or (match-beginning 7) (not nodefault))
16123 (string-to-number (or (match-string 7 s) "0")))
16124 (string-to-number (match-string 4 s))
16125 (string-to-number (match-string 3 s))
16126 (string-to-number (match-string 2 s))
16127 nil nil nil)
16128 (error "Not a standard Org-mode time string: %s" s)))
16130 (defun org-timestamp-up (&optional arg)
16131 "Increase the date item at the cursor by one.
16132 If the cursor is on the year, change the year. If it is on the month,
16133 the day or the time, change that.
16134 With prefix ARG, change by that many units."
16135 (interactive "p")
16136 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16138 (defun org-timestamp-down (&optional arg)
16139 "Decrease the date item at the cursor by one.
16140 If the cursor is on the year, change the year. If it is on the month,
16141 the day or the time, change that.
16142 With prefix ARG, change by that many units."
16143 (interactive "p")
16144 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16146 (defun org-timestamp-up-day (&optional arg)
16147 "Increase the date in the time stamp by one day.
16148 With prefix ARG, change that many days."
16149 (interactive "p")
16150 (if (and (not (org-at-timestamp-p t))
16151 (org-at-heading-p))
16152 (org-todo 'up)
16153 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16155 (defun org-timestamp-down-day (&optional arg)
16156 "Decrease the date in the time stamp by one day.
16157 With prefix ARG, change that many days."
16158 (interactive "p")
16159 (if (and (not (org-at-timestamp-p t))
16160 (org-at-heading-p))
16161 (org-todo 'down)
16162 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16164 (defun org-at-timestamp-p (&optional inactive-ok)
16165 "Determine if the cursor is in or at a timestamp."
16166 (interactive)
16167 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16168 (pos (point))
16169 (ans (or (looking-at tsr)
16170 (save-excursion
16171 (skip-chars-backward "^[<\n\r\t")
16172 (if (> (point) (point-min)) (backward-char 1))
16173 (and (looking-at tsr)
16174 (> (- (match-end 0) pos) -1))))))
16175 (and ans
16176 (boundp 'org-ts-what)
16177 (setq org-ts-what
16178 (cond
16179 ((= pos (match-beginning 0)) 'bracket)
16180 ;; Point is considered to be "on the bracket" whether
16181 ;; it's really on it or right after it.
16182 ((= pos (1- (match-end 0))) 'bracket)
16183 ((= pos (match-end 0)) 'after)
16184 ((org-pos-in-match-range pos 2) 'year)
16185 ((org-pos-in-match-range pos 3) 'month)
16186 ((org-pos-in-match-range pos 7) 'hour)
16187 ((org-pos-in-match-range pos 8) 'minute)
16188 ((or (org-pos-in-match-range pos 4)
16189 (org-pos-in-match-range pos 5)) 'day)
16190 ((and (> pos (or (match-end 8) (match-end 5)))
16191 (< pos (match-end 0)))
16192 (- pos (or (match-end 8) (match-end 5))))
16193 (t 'day))))
16194 ans))
16196 (defun org-toggle-timestamp-type ()
16197 "Toggle the type (<active> or [inactive]) of a time stamp."
16198 (interactive)
16199 (when (org-at-timestamp-p t)
16200 (let ((beg (match-beginning 0)) (end (match-end 0))
16201 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16202 (save-excursion
16203 (goto-char beg)
16204 (while (re-search-forward "[][<>]" end t)
16205 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16206 t t)))
16207 (message "Timestamp is now %sactive"
16208 (if (equal (char-after beg) ?<) "" "in")))))
16210 (defun org-timestamp-change (n &optional what updown)
16211 "Change the date in the time stamp at point.
16212 The date will be changed by N times WHAT. WHAT can be `day', `month',
16213 `year', `minute', `second'. If WHAT is not given, the cursor position
16214 in the timestamp determines what will be changed."
16215 (let ((origin (point)) origin-cat
16216 with-hm inactive
16217 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16218 org-ts-what
16219 extra rem
16220 ts time time0)
16221 (if (not (org-at-timestamp-p t))
16222 (error "Not at a timestamp"))
16223 (if (and (not what) (eq org-ts-what 'bracket))
16224 (org-toggle-timestamp-type)
16225 ;; Point isn't on brackets. Remember the part of the time-stamp
16226 ;; the point was in. Indeed, size of time-stamps may change,
16227 ;; but point must be kept in the same category nonetheless.
16228 (setq origin-cat org-ts-what)
16229 (if (and (not what) (not (eq org-ts-what 'day))
16230 org-display-custom-times
16231 (get-text-property (point) 'display)
16232 (not (get-text-property (1- (point)) 'display)))
16233 (setq org-ts-what 'day))
16234 (setq org-ts-what (or what org-ts-what)
16235 inactive (= (char-after (match-beginning 0)) ?\[)
16236 ts (match-string 0))
16237 (replace-match "")
16238 (if (string-match
16239 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16241 (setq extra (match-string 1 ts)))
16242 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16243 (setq with-hm t))
16244 (setq time0 (org-parse-time-string ts))
16245 (when (and updown
16246 (eq org-ts-what 'minute)
16247 (not current-prefix-arg))
16248 ;; This looks like s-up and s-down. Change by one rounding step.
16249 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16250 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16251 (setcar (cdr time0) (+ (nth 1 time0)
16252 (if (> n 0) (- rem) (- dm rem))))))
16253 (setq time
16254 (encode-time (or (car time0) 0)
16255 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16256 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16257 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16258 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16259 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16260 (nthcdr 6 time0)))
16261 (when (and (member org-ts-what '(hour minute))
16262 extra
16263 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16264 (setq extra (org-modify-ts-extra
16265 extra
16266 (if (eq org-ts-what 'hour) 2 5)
16267 n dm)))
16268 (when (integerp org-ts-what)
16269 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16270 (if (eq what 'calendar)
16271 (let ((cal-date (org-get-date-from-calendar)))
16272 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16273 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16274 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16275 (setcar time0 (or (car time0) 0))
16276 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16277 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16278 (setq time (apply 'encode-time time0))))
16279 ;; Insert the new time-stamp, and ensure point stays in the same
16280 ;; category as before (i.e. not after the last position in that
16281 ;; category).
16282 (let ((pos (point)))
16283 ;; Stay before inserted string. `save-excursion' is of no use.
16284 (setq org-last-changed-timestamp
16285 (org-insert-time-stamp time with-hm inactive nil nil extra))
16286 (goto-char pos))
16287 (save-match-data
16288 (looking-at org-ts-regexp3)
16289 (goto-char (cond
16290 ;; `day' category ends before `hour' if any, or at
16291 ;; the end of the day name.
16292 ((eq origin-cat 'day)
16293 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16294 ((eq origin-cat 'hour) (min (match-end 7) origin))
16295 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16296 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16297 ;; `year' and `month' have both fixed size: point
16298 ;; couldn't have moved into another part.
16299 (t origin))))
16300 ;; Update clock if on a CLOCK line.
16301 (org-clock-update-time-maybe)
16302 ;; Try to recenter the calendar window, if any.
16303 (if (and org-calendar-follow-timestamp-change
16304 (get-buffer-window "*Calendar*" t)
16305 (memq org-ts-what '(day month year)))
16306 (org-recenter-calendar (time-to-days time))))))
16308 (defun org-modify-ts-extra (s pos n dm)
16309 "Change the different parts of the lead-time and repeat fields in timestamp."
16310 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16311 ng h m new rem)
16312 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16313 (cond
16314 ((or (org-pos-in-match-range pos 2)
16315 (org-pos-in-match-range pos 3))
16316 (setq m (string-to-number (match-string 3 s))
16317 h (string-to-number (match-string 2 s)))
16318 (if (org-pos-in-match-range pos 2)
16319 (setq h (+ h n))
16320 (setq n (* dm (org-no-warnings (signum n))))
16321 (when (not (= 0 (setq rem (% m dm))))
16322 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16323 (setq m (+ m n)))
16324 (if (< m 0) (setq m (+ m 60) h (1- h)))
16325 (if (> m 59) (setq m (- m 60) h (1+ h)))
16326 (setq h (min 24 (max 0 h)))
16327 (setq ng 1 new (format "-%02d:%02d" h m)))
16328 ((org-pos-in-match-range pos 6)
16329 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16330 ((org-pos-in-match-range pos 5)
16331 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16333 ((org-pos-in-match-range pos 9)
16334 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16335 ((org-pos-in-match-range pos 8)
16336 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16338 (when ng
16339 (setq s (concat
16340 (substring s 0 (match-beginning ng))
16342 (substring s (match-end ng))))))
16345 (defun org-recenter-calendar (date)
16346 "If the calendar is visible, recenter it to DATE."
16347 (let ((cwin (get-buffer-window "*Calendar*" t)))
16348 (when cwin
16349 (let ((calendar-move-hook nil))
16350 (with-selected-window cwin
16351 (calendar-goto-date (if (listp date) date
16352 (calendar-gregorian-from-absolute date))))))))
16354 (defun org-goto-calendar (&optional arg)
16355 "Go to the Emacs calendar at the current date.
16356 If there is a time stamp in the current line, go to that date.
16357 A prefix ARG can be used to force the current date."
16358 (interactive "P")
16359 (let ((tsr org-ts-regexp) diff
16360 (calendar-move-hook nil)
16361 (calendar-view-holidays-initially-flag nil)
16362 (calendar-view-diary-initially-flag nil))
16363 (if (or (org-at-timestamp-p)
16364 (save-excursion
16365 (beginning-of-line 1)
16366 (looking-at (concat ".*" tsr))))
16367 (let ((d1 (time-to-days (current-time)))
16368 (d2 (time-to-days
16369 (org-time-string-to-time (match-string 1)))))
16370 (setq diff (- d2 d1))))
16371 (calendar)
16372 (calendar-goto-today)
16373 (if (and diff (not arg)) (calendar-forward-day diff))))
16375 (defun org-get-date-from-calendar ()
16376 "Return a list (month day year) of date at point in calendar."
16377 (with-current-buffer "*Calendar*"
16378 (save-match-data
16379 (calendar-cursor-to-date))))
16381 (defun org-date-from-calendar ()
16382 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16383 If there is already a time stamp at the cursor position, update it."
16384 (interactive)
16385 (if (org-at-timestamp-p t)
16386 (org-timestamp-change 0 'calendar)
16387 (let ((cal-date (org-get-date-from-calendar)))
16388 (org-insert-time-stamp
16389 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16391 (defun org-minutes-to-hh:mm-string (m)
16392 "Compute H:MM from a number of minutes."
16393 (let ((h (/ m 60)))
16394 (setq m (- m (* 60 h)))
16395 (format org-time-clocksum-format h m)))
16397 (defun org-hh:mm-string-to-minutes (s)
16398 "Convert a string H:MM to a number of minutes.
16399 If the string is just a number, interpret it as minutes.
16400 In fact, the first hh:mm or number in the string will be taken,
16401 there can be extra stuff in the string.
16402 If no number is found, the return value is 0."
16403 (cond
16404 ((integerp s) s)
16405 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16406 (+ (* (string-to-number (match-string 1 s)) 60)
16407 (string-to-number (match-string 2 s))))
16408 ((string-match "\\([0-9]+\\)" s)
16409 (string-to-number (match-string 1 s)))
16410 (t 0)))
16412 (defcustom org-effort-durations
16413 `(("h" . 60)
16414 ("d" . ,(* 60 8))
16415 ("w" . ,(* 60 8 5))
16416 ("m" . ,(* 60 8 5 4))
16417 ("y" . ,(* 60 8 5 40)))
16418 "Conversion factor to minutes for an effort modifier.
16420 Each entry has the form (MODIFIER . MINUTES).
16422 In an effort string, a number followed by MODIFIER is multiplied
16423 by the specified number of MINUTES to obtain an effort in
16424 minutes.
16426 For example, if the value of this variable is ((\"hours\" . 60)), then an
16427 effort string \"2hours\" is equivalent to 120 minutes."
16428 :group 'org-agenda
16429 :version "24.1"
16430 :type '(alist :key-type (string :tag "Modifier")
16431 :value-type (number :tag "Minutes")))
16433 (defun org-duration-string-to-minutes (s &optional output-to-string)
16434 "Convert a duration string S to minutes.
16436 A bare number is interpreted as minutes, modifiers can be set by
16437 customizing `org-effort-durations' (which see).
16439 Entries containing a colon are interpreted as H:MM by
16440 `org-hh:mm-string-to-minutes'."
16441 (let ((result 0)
16442 (re (concat "\\([0-9.]+\\) *\\("
16443 (regexp-opt (mapcar 'car org-effort-durations))
16444 "\\)")))
16445 (while (string-match re s)
16446 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16447 (string-to-number (match-string 1 s))))
16448 (setq s (replace-match "" nil t s)))
16449 (setq result (floor result))
16450 (incf result (org-hh:mm-string-to-minutes s))
16451 (if output-to-string (number-to-string result) result)))
16453 ;;;; Files
16455 (defun org-save-all-org-buffers ()
16456 "Save all Org-mode buffers without user confirmation."
16457 (interactive)
16458 (message "Saving all Org-mode buffers...")
16459 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16460 (when (featurep 'org-id) (org-id-locations-save))
16461 (message "Saving all Org-mode buffers... done"))
16463 (defun org-revert-all-org-buffers ()
16464 "Revert all Org-mode buffers.
16465 Prompt for confirmation when there are unsaved changes.
16466 Be sure you know what you are doing before letting this function
16467 overwrite your changes.
16469 This function is useful in a setup where one tracks org files
16470 with a version control system, to revert on one machine after pulling
16471 changes from another. I believe the procedure must be like this:
16473 1. M-x org-save-all-org-buffers
16474 2. Pull changes from the other machine, resolve conflicts
16475 3. M-x org-revert-all-org-buffers"
16476 (interactive)
16477 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16478 (error "Abort"))
16479 (save-excursion
16480 (save-window-excursion
16481 (mapc
16482 (lambda (b)
16483 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16484 (with-current-buffer b buffer-file-name))
16485 (org-pop-to-buffer-same-window b)
16486 (revert-buffer t 'no-confirm)))
16487 (buffer-list))
16488 (when (and (featurep 'org-id) org-id-track-globally)
16489 (org-id-locations-load)))))
16491 ;;;; Agenda files
16493 ;;;###autoload
16494 (defun org-switchb (&optional arg)
16495 "Switch between Org buffers.
16496 With one prefix argument, restrict available buffers to files.
16497 With two prefix arguments, restrict available buffers to agenda files.
16499 Defaults to `iswitchb' for buffer name completion.
16500 Set `org-completion-use-ido' to make it use ido instead."
16501 (interactive "P")
16502 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16503 ((equal arg '(16)) (org-buffer-list 'agenda))
16504 (t (org-buffer-list))))
16505 (org-completion-use-iswitchb org-completion-use-iswitchb)
16506 (org-completion-use-ido org-completion-use-ido))
16507 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16508 (setq org-completion-use-iswitchb t))
16509 (org-pop-to-buffer-same-window
16510 (org-icompleting-read "Org buffer: "
16511 (mapcar 'list (mapcar 'buffer-name blist))
16512 nil t))))
16514 ;;; Define some older names previously used for this functionality
16515 ;;;###autoload
16516 (defalias 'org-ido-switchb 'org-switchb)
16517 ;;;###autoload
16518 (defalias 'org-iswitchb 'org-switchb)
16520 (defun org-buffer-list (&optional predicate exclude-tmp)
16521 "Return a list of Org buffers.
16522 PREDICATE can be `export', `files' or `agenda'.
16524 export restrict the list to Export buffers.
16525 files restrict the list to buffers visiting Org files.
16526 agenda restrict the list to buffers visiting agenda files.
16528 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16529 (let* ((bfn nil)
16530 (agenda-files (and (eq predicate 'agenda)
16531 (mapcar 'file-truename (org-agenda-files t))))
16532 (filter
16533 (cond
16534 ((eq predicate 'files)
16535 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16536 ((eq predicate 'export)
16537 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16538 ((eq predicate 'agenda)
16539 (lambda (b)
16540 (with-current-buffer b
16541 (and (derived-mode-p 'org-mode)
16542 (setq bfn (buffer-file-name b))
16543 (member (file-truename bfn) agenda-files)))))
16544 (t (lambda (b) (with-current-buffer b
16545 (or (derived-mode-p 'org-mode)
16546 (string-match "\*Org .*Export"
16547 (buffer-name b)))))))))
16548 (delq nil
16549 (mapcar
16550 (lambda(b)
16551 (if (and (funcall filter b)
16552 (or (not exclude-tmp)
16553 (not (string-match "tmp" (buffer-name b)))))
16555 nil))
16556 (buffer-list)))))
16558 (defun org-agenda-files (&optional unrestricted archives)
16559 "Get the list of agenda files.
16560 Optional UNRESTRICTED means return the full list even if a restriction
16561 is currently in place.
16562 When ARCHIVES is t, include all archive files that are really being
16563 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16564 `org-agenda-archives-mode' is t."
16565 (let ((files
16566 (cond
16567 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16568 ((stringp org-agenda-files) (org-read-agenda-file-list))
16569 ((listp org-agenda-files) org-agenda-files)
16570 (t (error "Invalid value of `org-agenda-files'")))))
16571 (setq files (apply 'append
16572 (mapcar (lambda (f)
16573 (if (file-directory-p f)
16574 (directory-files
16575 f t org-agenda-file-regexp)
16576 (list f)))
16577 files)))
16578 (when org-agenda-skip-unavailable-files
16579 (setq files (delq nil
16580 (mapcar (function
16581 (lambda (file)
16582 (and (file-readable-p file) file)))
16583 files))))
16584 (when (or (eq archives t)
16585 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16586 (setq files (org-add-archive-files files)))
16587 files))
16589 (defun org-agenda-file-p (&optional file)
16590 "Return non-nil, if FILE is an agenda file.
16591 If FILE is omitted, use the file associated with the current
16592 buffer."
16593 (member (or file (buffer-file-name))
16594 (org-agenda-files t)))
16596 (defun org-edit-agenda-file-list ()
16597 "Edit the list of agenda files.
16598 Depending on setup, this either uses customize to edit the variable
16599 `org-agenda-files', or it visits the file that is holding the list. In the
16600 latter case, the buffer is set up in a way that saving it automatically kills
16601 the buffer and restores the previous window configuration."
16602 (interactive)
16603 (if (stringp org-agenda-files)
16604 (let ((cw (current-window-configuration)))
16605 (find-file org-agenda-files)
16606 (org-set-local 'org-window-configuration cw)
16607 (org-add-hook 'after-save-hook
16608 (lambda ()
16609 (set-window-configuration
16610 (prog1 org-window-configuration
16611 (kill-buffer (current-buffer))))
16612 (org-install-agenda-files-menu)
16613 (message "New agenda file list installed"))
16614 nil 'local)
16615 (message "%s" (substitute-command-keys
16616 "Edit list and finish with \\[save-buffer]")))
16617 (customize-variable 'org-agenda-files)))
16619 (defun org-store-new-agenda-file-list (list)
16620 "Set new value for the agenda file list and save it correctly."
16621 (if (stringp org-agenda-files)
16622 (let ((fe (org-read-agenda-file-list t)) b u)
16623 (while (setq b (find-buffer-visiting org-agenda-files))
16624 (kill-buffer b))
16625 (with-temp-file org-agenda-files
16626 (insert
16627 (mapconcat
16628 (lambda (f) ;; Keep un-expanded entries.
16629 (if (setq u (assoc f fe))
16630 (cdr u)
16632 list "\n")
16633 "\n")))
16634 (let ((org-mode-hook nil) (org-inhibit-startup t)
16635 (org-insert-mode-line-in-empty-file nil))
16636 (setq org-agenda-files list)
16637 (customize-save-variable 'org-agenda-files org-agenda-files))))
16639 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16640 "Read the list of agenda files from a file.
16641 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16642 filenames, used by `org-store-new-agenda-file-list' to write back
16643 un-expanded file names."
16644 (when (file-directory-p org-agenda-files)
16645 (error "`org-agenda-files' cannot be a single directory"))
16646 (when (stringp org-agenda-files)
16647 (with-temp-buffer
16648 (insert-file-contents org-agenda-files)
16649 (mapcar
16650 (lambda (f)
16651 (let ((e (expand-file-name (substitute-in-file-name f)
16652 org-directory)))
16653 (if pair-with-expansion
16654 (cons e f)
16655 e)))
16656 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16658 ;;;###autoload
16659 (defun org-cycle-agenda-files ()
16660 "Cycle through the files in `org-agenda-files'.
16661 If the current buffer visits an agenda file, find the next one in the list.
16662 If the current buffer does not, find the first agenda file."
16663 (interactive)
16664 (let* ((fs (org-agenda-files t))
16665 (files (append fs (list (car fs))))
16666 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16667 file)
16668 (unless files (error "No agenda files"))
16669 (catch 'exit
16670 (while (setq file (pop files))
16671 (if (equal (file-truename file) tcf)
16672 (when (car files)
16673 (find-file (car files))
16674 (throw 'exit t))))
16675 (find-file (car fs)))
16676 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16678 (defun org-agenda-file-to-front (&optional to-end)
16679 "Move/add the current file to the top of the agenda file list.
16680 If the file is not present in the list, it is added to the front. If it is
16681 present, it is moved there. With optional argument TO-END, add/move to the
16682 end of the list."
16683 (interactive "P")
16684 (let ((org-agenda-skip-unavailable-files nil)
16685 (file-alist (mapcar (lambda (x)
16686 (cons (file-truename x) x))
16687 (org-agenda-files t)))
16688 (ctf (file-truename buffer-file-name))
16689 x had)
16690 (setq x (assoc ctf file-alist) had x)
16692 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16693 (if to-end
16694 (setq file-alist (append (delq x file-alist) (list x)))
16695 (setq file-alist (cons x (delq x file-alist))))
16696 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16697 (org-install-agenda-files-menu)
16698 (message "File %s to %s of agenda file list"
16699 (if had "moved" "added") (if to-end "end" "front"))))
16701 (defun org-remove-file (&optional file)
16702 "Remove current file from the list of files in variable `org-agenda-files'.
16703 These are the files which are being checked for agenda entries.
16704 Optional argument FILE means use this file instead of the current."
16705 (interactive)
16706 (let* ((org-agenda-skip-unavailable-files nil)
16707 (file (or file buffer-file-name))
16708 (true-file (file-truename file))
16709 (afile (abbreviate-file-name file))
16710 (files (delq nil (mapcar
16711 (lambda (x)
16712 (if (equal true-file
16713 (file-truename x))
16714 nil x))
16715 (org-agenda-files t)))))
16716 (if (not (= (length files) (length (org-agenda-files t))))
16717 (progn
16718 (org-store-new-agenda-file-list files)
16719 (org-install-agenda-files-menu)
16720 (message "Removed file: %s" afile))
16721 (message "File was not in list: %s (not removed)" afile))))
16723 (defun org-file-menu-entry (file)
16724 (vector file (list 'find-file file) t))
16726 (defun org-check-agenda-file (file)
16727 "Make sure FILE exists. If not, ask user what to do."
16728 (when (not (file-exists-p file))
16729 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16730 (abbreviate-file-name file))
16731 (let ((r (downcase (read-char-exclusive))))
16732 (cond
16733 ((equal r ?r)
16734 (org-remove-file file)
16735 (throw 'nextfile t))
16736 (t (error "Abort"))))))
16738 (defun org-get-agenda-file-buffer (file)
16739 "Get a buffer visiting FILE. If the buffer needs to be created, add
16740 it to the list of buffers which might be released later."
16741 (let ((buf (org-find-base-buffer-visiting file)))
16742 (if buf
16743 buf ; just return it
16744 ;; Make a new buffer and remember it
16745 (setq buf (find-file-noselect file))
16746 (if buf (push buf org-agenda-new-buffers))
16747 buf)))
16749 (defun org-release-buffers (blist)
16750 "Release all buffers in list, asking the user for confirmation when needed.
16751 When a buffer is unmodified, it is just killed. When modified, it is saved
16752 \(if the user agrees) and then killed."
16753 (let (buf file)
16754 (while (setq buf (pop blist))
16755 (setq file (buffer-file-name buf))
16756 (when (and (buffer-modified-p buf)
16757 file
16758 (y-or-n-p (format "Save file %s? " file)))
16759 (with-current-buffer buf (save-buffer)))
16760 (kill-buffer buf))))
16762 (defun org-prepare-agenda-buffers (files)
16763 "Create buffers for all agenda files, protect archived trees and comments."
16764 (interactive)
16765 (let ((pa '(:org-archived t))
16766 (pc '(:org-comment t))
16767 (pall '(:org-archived t :org-comment t))
16768 (inhibit-read-only t)
16769 (rea (concat ":" org-archive-tag ":"))
16770 bmp file re)
16771 (save-excursion
16772 (save-restriction
16773 (while (setq file (pop files))
16774 (catch 'nextfile
16775 (if (bufferp file)
16776 (set-buffer file)
16777 (org-check-agenda-file file)
16778 (set-buffer (org-get-agenda-file-buffer file)))
16779 (widen)
16780 (setq bmp (buffer-modified-p))
16781 (org-refresh-category-properties)
16782 (setq org-todo-keywords-for-agenda
16783 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16784 (setq org-done-keywords-for-agenda
16785 (append org-done-keywords-for-agenda org-done-keywords))
16786 (setq org-todo-keyword-alist-for-agenda
16787 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16788 (setq org-drawers-for-agenda
16789 (append org-drawers-for-agenda org-drawers))
16790 (setq org-tag-alist-for-agenda
16791 (append org-tag-alist-for-agenda org-tag-alist))
16793 (save-excursion
16794 (remove-text-properties (point-min) (point-max) pall)
16795 (when org-agenda-skip-archived-trees
16796 (goto-char (point-min))
16797 (while (re-search-forward rea nil t)
16798 (if (org-at-heading-p t)
16799 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16800 (goto-char (point-min))
16801 (setq re (format org-heading-keyword-regexp-format
16802 org-comment-string))
16803 (while (re-search-forward re nil t)
16804 (add-text-properties
16805 (match-beginning 0) (org-end-of-subtree t) pc)))
16806 (set-buffer-modified-p bmp)))))
16807 (setq org-todo-keywords-for-agenda
16808 (org-uniquify org-todo-keywords-for-agenda))
16809 (setq org-todo-keyword-alist-for-agenda
16810 (org-uniquify org-todo-keyword-alist-for-agenda)
16811 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16813 ;;;; Embedded LaTeX
16815 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16816 "Keymap for the minor `org-cdlatex-mode'.")
16818 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16819 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16820 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16821 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16822 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16824 (defvar org-cdlatex-texmathp-advice-is-done nil
16825 "Flag remembering if we have applied the advice to texmathp already.")
16827 (define-minor-mode org-cdlatex-mode
16828 "Toggle the minor `org-cdlatex-mode'.
16829 This mode supports entering LaTeX environment and math in LaTeX fragments
16830 in Org-mode.
16831 \\{org-cdlatex-mode-map}"
16832 nil " OCDL" nil
16833 (when org-cdlatex-mode
16834 (require 'cdlatex)
16835 (run-hooks 'cdlatex-mode-hook)
16836 (cdlatex-compute-tables))
16837 (unless org-cdlatex-texmathp-advice-is-done
16838 (setq org-cdlatex-texmathp-advice-is-done t)
16839 (defadvice texmathp (around org-math-always-on activate)
16840 "Always return t in org-mode buffers.
16841 This is because we want to insert math symbols without dollars even outside
16842 the LaTeX math segments. If Orgmode thinks that point is actually inside
16843 an embedded LaTeX fragment, let texmathp do its job.
16844 \\[org-cdlatex-mode-map]"
16845 (interactive)
16846 (let (p)
16847 (cond
16848 ((not (derived-mode-p 'org-mode)) ad-do-it)
16849 ((eq this-command 'cdlatex-math-symbol)
16850 (setq ad-return-value t
16851 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16853 (let ((p (org-inside-LaTeX-fragment-p)))
16854 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16855 (setq ad-return-value t
16856 texmathp-why '("Org-mode embedded math" . 0))
16857 (if p ad-do-it)))))))))
16859 (defun turn-on-org-cdlatex ()
16860 "Unconditionally turn on `org-cdlatex-mode'."
16861 (org-cdlatex-mode 1))
16863 (defun org-inside-LaTeX-fragment-p ()
16864 "Test if point is inside a LaTeX fragment.
16865 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16866 sequence appearing also before point.
16867 Even though the matchers for math are configurable, this function assumes
16868 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16869 delimiters are skipped when they have been removed by customization.
16870 The return value is nil, or a cons cell with the delimiter and the
16871 position of this delimiter.
16873 This function does a reasonably good job, but can locally be fooled by
16874 for example currency specifications. For example it will assume being in
16875 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16876 fragments that are properly closed, but during editing, we have to live
16877 with the uncertainty caused by missing closing delimiters. This function
16878 looks only before point, not after."
16879 (catch 'exit
16880 (let ((pos (point))
16881 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16882 (lim (progn
16883 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16884 (point)))
16885 dd-on str (start 0) m re)
16886 (goto-char pos)
16887 (when dodollar
16888 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16889 re (nth 1 (assoc "$" org-latex-regexps)))
16890 (while (string-match re str start)
16891 (cond
16892 ((= (match-end 0) (length str))
16893 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16894 ((= (match-end 0) (- (length str) 5))
16895 (throw 'exit nil))
16896 (t (setq start (match-end 0))))))
16897 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16898 (goto-char pos)
16899 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16900 (and (match-beginning 2) (throw 'exit nil))
16901 ;; count $$
16902 (while (re-search-backward "\\$\\$" lim t)
16903 (setq dd-on (not dd-on)))
16904 (goto-char pos)
16905 (if dd-on (cons "$$" m))))))
16907 (defun org-inside-latex-macro-p ()
16908 "Is point inside a LaTeX macro or its arguments?"
16909 (save-match-data
16910 (org-in-regexp
16911 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16913 (defun org-try-cdlatex-tab ()
16914 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16915 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16916 - inside a LaTeX fragment, or
16917 - after the first word in a line, where an abbreviation expansion could
16918 insert a LaTeX environment."
16919 (when org-cdlatex-mode
16920 (cond
16921 ;; Before any word on the line: No expansion possible.
16922 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16923 ;; Just after first word on the line: Expand it. Make sure it
16924 ;; cannot happen on headlines, though.
16925 ((save-excursion
16926 (skip-chars-backward "a-zA-Z0-9*")
16927 (skip-chars-backward " \t")
16928 (and (bolp) (not (org-at-heading-p))))
16929 (cdlatex-tab) t)
16930 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16932 (defun org-cdlatex-underscore-caret (&optional arg)
16933 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16934 Revert to the normal definition outside of these fragments."
16935 (interactive "P")
16936 (if (org-inside-LaTeX-fragment-p)
16937 (call-interactively 'cdlatex-sub-superscript)
16938 (let (org-cdlatex-mode)
16939 (call-interactively (key-binding (vector last-input-event))))))
16941 (defun org-cdlatex-math-modify (&optional arg)
16942 "Execute `cdlatex-math-modify' in LaTeX fragments.
16943 Revert to the normal definition outside of these fragments."
16944 (interactive "P")
16945 (if (org-inside-LaTeX-fragment-p)
16946 (call-interactively 'cdlatex-math-modify)
16947 (let (org-cdlatex-mode)
16948 (call-interactively (key-binding (vector last-input-event))))))
16950 (defvar org-latex-fragment-image-overlays nil
16951 "List of overlays carrying the images of latex fragments.")
16952 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16954 (defun org-remove-latex-fragment-image-overlays ()
16955 "Remove all overlays with LaTeX fragment images in current buffer."
16956 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16957 (setq org-latex-fragment-image-overlays nil))
16959 (defun org-preview-latex-fragment (&optional subtree)
16960 "Preview the LaTeX fragment at point, or all locally or globally.
16961 If the cursor is in a LaTeX fragment, create the image and overlay
16962 it over the source code. If there is no fragment at point, display
16963 all fragments in the current text, from one headline to the next. With
16964 prefix SUBTREE, display all fragments in the current subtree. With a
16965 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16966 the cursor is before the first headline,
16967 display all fragments in the buffer.
16968 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16969 (interactive "P")
16970 (unless buffer-file-name
16971 (error "Can't preview LaTeX fragment in a non-file buffer"))
16972 (org-remove-latex-fragment-image-overlays)
16973 (save-excursion
16974 (save-restriction
16975 (let (beg end at msg)
16976 (cond
16977 ((or (equal subtree '(16))
16978 (not (save-excursion
16979 (re-search-backward org-outline-regexp-bol nil t))))
16980 (setq beg (point-min) end (point-max)
16981 msg "Creating images for buffer...%s"))
16982 ((equal subtree '(4))
16983 (org-back-to-heading)
16984 (setq beg (point) end (org-end-of-subtree t)
16985 msg "Creating images for subtree...%s"))
16987 (if (setq at (org-inside-LaTeX-fragment-p))
16988 (goto-char (max (point-min) (- (cdr at) 2)))
16989 (org-back-to-heading))
16990 (setq beg (point) end (progn (outline-next-heading) (point))
16991 msg (if at "Creating image...%s"
16992 "Creating images for entry...%s"))))
16993 (message msg "")
16994 (narrow-to-region beg end)
16995 (goto-char beg)
16996 (org-format-latex
16997 (concat "ltxpng/" (file-name-sans-extension
16998 (file-name-nondirectory
16999 buffer-file-name)))
17000 default-directory 'overlays msg at 'forbuffer
17001 org-latex-create-formula-image-program)
17002 (message msg "done. Use `C-c C-c' to remove images.")))))
17004 (defvar org-latex-regexps
17005 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17006 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17007 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17008 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17009 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17010 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17011 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17012 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17013 "Regular expressions for matching embedded LaTeX.")
17015 (defvar org-export-have-math nil) ;; dynamic scoping
17016 (defun org-format-latex (prefix &optional dir overlays msg at
17017 forbuffer processing-type)
17018 "Replace LaTeX fragments with links to an image, and produce images.
17019 Some of the options can be changed using the variable
17020 `org-format-latex-options'."
17021 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17022 (let* ((prefixnodir (file-name-nondirectory prefix))
17023 (absprefix (expand-file-name prefix dir))
17024 (todir (file-name-directory absprefix))
17025 (opt org-format-latex-options)
17026 (matchers (plist-get opt :matchers))
17027 (re-list org-latex-regexps)
17028 (org-format-latex-header-extra
17029 (plist-get (org-infile-export-plist) :latex-header-extra))
17030 (cnt 0) txt hash link beg end re e checkdir
17031 executables-checked string
17032 m n block-type block linkfile movefile ov)
17033 ;; Check the different regular expressions
17034 (while (setq e (pop re-list))
17035 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17036 block (if block-type "\n\n" ""))
17037 (when (member m matchers)
17038 (goto-char (point-min))
17039 (while (re-search-forward re nil t)
17040 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17041 (not (get-text-property (match-beginning n)
17042 'org-protected))
17043 (or (not overlays)
17044 (not (eq (get-char-property (match-beginning n)
17045 'org-overlay-type)
17046 'org-latex-overlay))))
17047 (setq org-export-have-math t)
17048 (cond
17049 ((eq processing-type 'verbatim)
17050 ;; Leave the text verbatim, just protect it
17051 (add-text-properties (match-beginning n) (match-end n)
17052 '(org-protected t)))
17053 ((eq processing-type 'mathjax)
17054 ;; Prepare for MathJax processing
17055 (setq string (match-string n))
17056 (if (member m '("$" "$1"))
17057 (save-excursion
17058 (delete-region (match-beginning n) (match-end n))
17059 (goto-char (match-beginning n))
17060 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17061 "\\)")
17062 '(org-protected t))))
17063 (add-text-properties (match-beginning n) (match-end n)
17064 '(org-protected t))))
17065 ((or (eq processing-type 'dvipng)
17066 (eq processing-type 'imagemagick))
17067 ;; Process to an image
17068 (setq txt (match-string n)
17069 beg (match-beginning n) end (match-end n)
17070 cnt (1+ cnt))
17071 (let (print-length print-level) ; make sure full list is printed
17072 (setq hash (sha1 (prin1-to-string
17073 (list org-format-latex-header
17074 org-format-latex-header-extra
17075 org-export-latex-default-packages-alist
17076 org-export-latex-packages-alist
17077 org-format-latex-options
17078 forbuffer txt)))
17079 linkfile (format "%s_%s.png" prefix hash)
17080 movefile (format "%s_%s.png" absprefix hash)))
17081 (setq link (concat block "[[file:" linkfile "]]" block))
17082 (if msg (message msg cnt))
17083 (goto-char beg)
17084 (unless checkdir ; make sure the directory exists
17085 (setq checkdir t)
17086 (or (file-directory-p todir) (make-directory todir t)))
17087 (cond
17088 ((eq processing-type 'dvipng)
17089 (unless executables-checked
17090 (org-check-external-command
17091 "latex" "needed to convert LaTeX fragments to images")
17092 (org-check-external-command
17093 "dvipng" "needed to convert LaTeX fragments to images")
17094 (setq executables-checked t))
17095 (unless (file-exists-p movefile)
17096 (org-create-formula-image-with-dvipng
17097 txt movefile opt forbuffer)))
17098 ((eq processing-type 'imagemagick)
17099 (unless executables-checked
17100 (org-check-external-command
17101 "convert" "you need to install imagemagick")
17102 (setq executables-checked t))
17103 (unless (file-exists-p movefile)
17104 (org-create-formula-image-with-imagemagick
17105 txt movefile opt forbuffer))))
17106 (if overlays
17107 (progn
17108 (mapc (lambda (o)
17109 (if (eq (overlay-get o 'org-overlay-type)
17110 'org-latex-overlay)
17111 (delete-overlay o)))
17112 (overlays-in beg end))
17113 (setq ov (make-overlay beg end))
17114 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17115 (if (featurep 'xemacs)
17116 (progn
17117 (overlay-put ov 'invisible t)
17118 (overlay-put
17119 ov 'end-glyph
17120 (make-glyph (vector 'png :file movefile))))
17121 (overlay-put
17122 ov 'display
17123 (list 'image :type 'png :file movefile :ascent 'center)))
17124 (push ov org-latex-fragment-image-overlays)
17125 (goto-char end))
17126 (delete-region beg end)
17127 (insert (org-add-props link
17128 (list 'org-latex-src
17129 (replace-regexp-in-string
17130 "\"" "" txt)
17131 'org-latex-src-embed-type
17132 (if block-type 'paragraph 'character))))))
17133 ((eq processing-type 'mathml)
17134 ;; Process to MathML
17135 (unless executables-checked
17136 (unless (save-match-data (org-format-latex-mathml-available-p))
17137 (error "LaTeX to MathML converter not configured"))
17138 (setq executables-checked t))
17139 (setq txt (match-string n)
17140 beg (match-beginning n) end (match-end n)
17141 cnt (1+ cnt))
17142 (if msg (message msg cnt))
17143 (goto-char beg)
17144 (delete-region beg end)
17145 (insert (org-format-latex-as-mathml
17146 txt block-type prefix dir)))
17148 (error "Unknown conversion type %s for latex fragments"
17149 processing-type)))))))))
17151 (defun org-create-math-formula (latex-frag &optional mathml-file)
17152 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17153 Use `org-latex-to-mathml-convert-command'. If the conversion is
17154 sucessful, return the portion between \"<math...> </math>\"
17155 elements otherwise return nil. When MATHML-FILE is specified,
17156 write the results in to that file. When invoked as an
17157 interactive command, prompt for LATEX-FRAG, with initial value
17158 set to the current active region and echo the results for user
17159 inspection."
17160 (interactive (list (let ((frag (when (region-active-p)
17161 (buffer-substring-no-properties
17162 (region-beginning) (region-end)))))
17163 (read-string "LaTeX Fragment: " frag nil frag))))
17164 (unless latex-frag (error "Invalid latex-frag"))
17165 (let* ((tmp-in-file (file-relative-name
17166 (make-temp-name (expand-file-name "ltxmathml-in"))))
17167 (ignore (write-region latex-frag nil tmp-in-file))
17168 (tmp-out-file (file-relative-name
17169 (make-temp-name (expand-file-name "ltxmathml-out"))))
17170 (cmd (format-spec
17171 org-latex-to-mathml-convert-command
17172 `((?j . ,(shell-quote-argument
17173 (expand-file-name org-latex-to-mathml-jar-file)))
17174 (?I . ,(shell-quote-argument tmp-in-file))
17175 (?o . ,(shell-quote-argument tmp-out-file)))))
17176 mathml shell-command-output)
17177 (when (org-called-interactively-p 'any)
17178 (unless (org-format-latex-mathml-available-p)
17179 (error "LaTeX to MathML converter not configured")))
17180 (message "Running %s" cmd)
17181 (setq shell-command-output (shell-command-to-string cmd))
17182 (setq mathml
17183 (when (file-readable-p tmp-out-file)
17184 (with-current-buffer (find-file-noselect tmp-out-file t)
17185 (goto-char (point-min))
17186 (when (re-search-forward
17187 (concat
17188 (regexp-quote
17189 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17190 "\\(.\\|\n\\)*"
17191 (regexp-quote "</math>")) nil t)
17192 (prog1 (match-string 0) (kill-buffer))))))
17193 (cond
17194 (mathml
17195 (setq mathml
17196 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17197 (when mathml-file
17198 (write-region mathml nil mathml-file))
17199 (when (org-called-interactively-p 'any)
17200 (message mathml)))
17201 ((message "LaTeX to MathML conversion failed")
17202 (message shell-command-output)))
17203 (delete-file tmp-in-file)
17204 (when (file-exists-p tmp-out-file)
17205 (delete-file tmp-out-file))
17206 mathml))
17208 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17209 prefix &optional dir)
17210 "Use `org-create-math-formula' but check local cache first."
17211 (let* ((absprefix (expand-file-name prefix dir))
17212 (print-length nil) (print-level nil)
17213 (formula-id (concat
17214 "formula-"
17215 (sha1
17216 (prin1-to-string
17217 (list latex-frag
17218 org-latex-to-mathml-convert-command)))))
17219 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17220 (formula-cache-dir (file-name-directory formula-cache)))
17222 (unless (file-directory-p formula-cache-dir)
17223 (make-directory formula-cache-dir t))
17225 (unless (file-exists-p formula-cache)
17226 (org-create-math-formula latex-frag formula-cache))
17228 (if (file-exists-p formula-cache)
17229 ;; Successful conversion. Return the link to MathML file.
17230 (org-add-props
17231 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17232 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17233 'org-latex-src-embed-type (if latex-frag-type
17234 'paragraph 'character)))
17235 ;; Failed conversion. Return the LaTeX fragment verbatim
17236 (add-text-properties
17237 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17238 latex-frag)))
17240 ;; This function borrows from Ganesh Swami's latex2png.el
17241 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17242 "This calls dvipng."
17243 (require 'org-latex)
17244 (let* ((tmpdir (if (featurep 'xemacs)
17245 (temp-directory)
17246 temporary-file-directory))
17247 (texfilebase (make-temp-name
17248 (expand-file-name "orgtex" tmpdir)))
17249 (texfile (concat texfilebase ".tex"))
17250 (dvifile (concat texfilebase ".dvi"))
17251 (pngfile (concat texfilebase ".png"))
17252 (fnh (if (featurep 'xemacs)
17253 (font-height (face-font 'default))
17254 (face-attribute 'default :height nil)))
17255 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17256 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17257 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17258 "Black"))
17259 (bg (or (plist-get options (if buffer :background :html-background))
17260 "Transparent")))
17261 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17262 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17263 (with-temp-file texfile
17264 (insert (org-splice-latex-header
17265 org-format-latex-header
17266 org-export-latex-default-packages-alist
17267 org-export-latex-packages-alist t
17268 org-format-latex-header-extra))
17269 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17270 (require 'org-latex)
17271 (org-export-latex-fix-inputenc))
17272 (let ((dir default-directory))
17273 (condition-case nil
17274 (progn
17275 (cd tmpdir)
17276 (call-process "latex" nil nil nil texfile))
17277 (error nil))
17278 (cd dir))
17279 (if (not (file-exists-p dvifile))
17280 (progn (message "Failed to create dvi file from %s" texfile) nil)
17281 (condition-case nil
17282 (if (featurep 'xemacs)
17283 (call-process "dvipng" nil nil nil
17284 "-fg" fg "-bg" bg
17285 "-T" "tight"
17286 "-o" pngfile
17287 dvifile)
17288 (call-process "dvipng" nil nil nil
17289 "-fg" fg "-bg" bg
17290 "-D" dpi
17291 ;;"-x" scale "-y" scale
17292 "-T" "tight"
17293 "-o" pngfile
17294 dvifile))
17295 (error nil))
17296 (if (not (file-exists-p pngfile))
17297 (if org-format-latex-signal-error
17298 (error "Failed to create png file from %s" texfile)
17299 (message "Failed to create png file from %s" texfile)
17300 nil)
17301 ;; Use the requested file name and clean up
17302 (copy-file pngfile tofile 'replace)
17303 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17304 (if (file-exists-p (concat texfilebase e))
17305 (delete-file (concat texfilebase e))))
17306 pngfile))))
17308 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17309 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17310 "This calls convert, which is included into imagemagick."
17311 (require 'org-latex)
17312 (let* ((tmpdir (if (featurep 'xemacs)
17313 (temp-directory)
17314 temporary-file-directory))
17315 (texfilebase (make-temp-name
17316 (expand-file-name "orgtex" tmpdir)))
17317 (texfile (concat texfilebase ".tex"))
17318 (pdffile (concat texfilebase ".pdf"))
17319 (pngfile (concat texfilebase ".png"))
17320 (fnh (if (featurep 'xemacs)
17321 (font-height (face-font 'default))
17322 (face-attribute 'default :height nil)))
17323 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17324 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17325 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17326 "black"))
17327 (bg (or (plist-get options (if buffer :background :html-background))
17328 "white")))
17329 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17330 (setq fg (org-latex-color-format fg)))
17331 (if (eq bg 'default) (setq bg (org-latex-color :background))
17332 (setq bg (org-latex-color-format
17333 (if (string= bg "Transparent")(setq bg "white")))))
17334 (with-temp-file texfile
17335 (insert (org-splice-latex-header
17336 org-format-latex-header
17337 org-export-latex-default-packages-alist
17338 org-export-latex-packages-alist t
17339 org-format-latex-header-extra))
17340 (insert "\n\\begin{document}\n"
17341 "\\definecolor{fg}{rgb}{" fg "}\n"
17342 "\\definecolor{bg}{rgb}{" bg "}\n"
17343 "\n\\pagecolor{bg}\n"
17344 "\n{\\color{fg}\n"
17345 string
17346 "\n}\n"
17347 "\n\\end{document}\n" )
17348 (require 'org-latex)
17349 (org-export-latex-fix-inputenc))
17350 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17351 (condition-case nil
17352 (progn
17353 (cd tmpdir)
17354 (setq cmds org-latex-to-pdf-process)
17355 (while cmds
17356 (setq latex-frags-cmds (pop cmds))
17357 (if (listp latex-frags-cmds)
17358 (setq cmds nil)
17359 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17360 (while latex-frags-cmds
17361 (setq cmd (pop latex-frags-cmds))
17362 (while (string-match "%b" cmd)
17363 (setq cmd (replace-match
17364 (save-match-data
17365 (shell-quote-argument texfile))
17366 t t cmd)))
17367 (while (string-match "%f" cmd)
17368 (setq cmd (replace-match
17369 (save-match-data
17370 (shell-quote-argument (file-name-nondirectory texfile)))
17371 t t cmd)))
17372 (while (string-match "%o" cmd)
17373 (setq cmd (replace-match
17374 (save-match-data
17375 (shell-quote-argument (file-name-directory texfile)))
17376 t t cmd)))
17377 (setq cmd (split-string cmd))
17378 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17379 (error nil))
17380 (cd dir))
17381 (if (not (file-exists-p pdffile))
17382 (progn (message "Failed to create pdf file from %s" texfile) nil)
17383 (condition-case nil
17384 (if (featurep 'xemacs)
17385 (call-process "convert" nil nil nil
17386 "-density" "96"
17387 "-trim"
17388 "-antialias"
17389 pdffile
17390 "-quality" "100"
17391 ;; "-sharpen" "0x1.0"
17392 pngfile)
17393 (call-process "convert" nil nil nil
17394 "-density" dpi
17395 "-trim"
17396 "-antialias"
17397 pdffile
17398 "-quality" "100"
17399 ; "-sharpen" "0x1.0"
17400 pngfile))
17401 (error nil))
17402 (if (not (file-exists-p pngfile))
17403 (if org-format-latex-signal-error
17404 (error "Failed to create png file from %s" texfile)
17405 (message "Failed to create png file from %s" texfile)
17406 nil)
17407 ;; Use the requested file name and clean up
17408 (copy-file pngfile tofile 'replace)
17409 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17410 (if (file-exists-p (concat texfilebase e))
17411 (delete-file (concat texfilebase e))))
17412 pngfile))))
17414 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17415 "Fill a LaTeX header template TPL.
17416 In the template, the following place holders will be recognized:
17418 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17419 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17420 [PACKAGES] \\usepackage statements for PKG
17421 [NO-PACKAGES] do not include PKG
17422 [EXTRA] the string EXTRA
17423 [NO-EXTRA] do not include EXTRA
17425 For backward compatibility, if both the positive and the negative place
17426 holder is missing, the positive one (without the \"NO-\") will be
17427 assumed to be present at the end of the template.
17428 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17429 EXTRA is a string.
17430 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17431 (let (rpl (end ""))
17432 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17433 (setq rpl (if (or (match-end 1) (not def-pkg))
17434 "" (org-latex-packages-to-string def-pkg snippets-p t))
17435 tpl (replace-match rpl t t tpl))
17436 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17438 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17439 (setq rpl (if (or (match-end 1) (not pkg))
17440 "" (org-latex-packages-to-string pkg snippets-p t))
17441 tpl (replace-match rpl t t tpl))
17442 (if pkg (setq end
17443 (concat end "\n"
17444 (org-latex-packages-to-string pkg snippets-p)))))
17446 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17447 (setq rpl (if (or (match-end 1) (not extra))
17448 "" (concat extra "\n"))
17449 tpl (replace-match rpl t t tpl))
17450 (if (and extra (string-match "\\S-" extra))
17451 (setq end (concat end "\n" extra))))
17453 (if (string-match "\\S-" end)
17454 (concat tpl "\n" end)
17455 tpl)))
17457 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17458 "Turn an alist of packages into a string with the \\usepackage macros."
17459 (setq pkg (mapconcat (lambda(p)
17460 (cond
17461 ((stringp p) p)
17462 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17463 (format "%% Package %s omitted" (cadr p)))
17464 ((equal "" (car p))
17465 (format "\\usepackage{%s}" (cadr p)))
17467 (format "\\usepackage[%s]{%s}"
17468 (car p) (cadr p)))))
17470 "\n"))
17471 (if newline (concat pkg "\n") pkg))
17473 (defun org-dvipng-color (attr)
17474 "Return a RGB color specification for dvipng."
17475 (apply 'format "rgb %s %s %s"
17476 (mapcar 'org-normalize-color
17477 (if (featurep 'xemacs)
17478 (color-rgb-components
17479 (face-property 'default
17480 (cond ((eq attr :foreground) 'foreground)
17481 ((eq attr :background) 'background))))
17482 (color-values (face-attribute 'default attr nil))))))
17484 (defun org-latex-color (attr)
17485 "Return a RGB color for the LaTeX color package."
17486 (apply 'format "%s,%s,%s"
17487 (mapcar 'org-normalize-color
17488 (if (featurep 'xemacs)
17489 (color-rgb-components
17490 (face-property 'default
17491 (cond ((eq attr :foreground) 'foreground)
17492 ((eq attr :background) 'background))))
17493 (color-values (face-attribute 'default attr nil))))))
17495 (defun org-latex-color-format (color-name)
17496 "Convert COLOR-NAME to a RGB color value."
17497 (apply 'format "%s,%s,%s"
17498 (mapcar 'org-normalize-color
17499 (color-values color-name))))
17501 (defun org-normalize-color (value)
17502 "Return string to be used as color value for an RGB component."
17503 (format "%g" (/ value 65535.0)))
17505 ;; Image display
17508 (defvar org-inline-image-overlays nil)
17509 (make-variable-buffer-local 'org-inline-image-overlays)
17511 (defun org-toggle-inline-images (&optional include-linked)
17512 "Toggle the display of inline images.
17513 INCLUDE-LINKED is passed to `org-display-inline-images'."
17514 (interactive "P")
17515 (if org-inline-image-overlays
17516 (progn
17517 (org-remove-inline-images)
17518 (message "Inline image display turned off"))
17519 (org-display-inline-images include-linked)
17520 (if org-inline-image-overlays
17521 (message "%d images displayed inline"
17522 (length org-inline-image-overlays))
17523 (message "No images to display inline"))))
17525 (defun org-display-inline-images (&optional include-linked refresh beg end)
17526 "Display inline images.
17527 Normally only links without a description part are inlined, because this
17528 is how it will work for export. When INCLUDE-LINKED is set, also links
17529 with a description part will be inlined. This can be nice for a quick
17530 look at those images, but it does not reflect what exported files will look
17531 like.
17532 When REFRESH is set, refresh existing images between BEG and END.
17533 This will create new image displays only if necessary.
17534 BEG and END default to the buffer boundaries."
17535 (interactive "P")
17536 (unless refresh
17537 (org-remove-inline-images)
17538 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17539 (save-excursion
17540 (save-restriction
17541 (widen)
17542 (setq beg (or beg (point-min)) end (or end (point-max)))
17543 (goto-char beg)
17544 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17545 (substring (org-image-file-name-regexp) 0 -2)
17546 "\\)\\]" (if include-linked "" "\\]")))
17547 old file ov img)
17548 (while (re-search-forward re end t)
17549 (setq old (get-char-property-and-overlay (match-beginning 1)
17550 'org-image-overlay))
17551 (setq file (expand-file-name
17552 (concat (or (match-string 3) "") (match-string 4))))
17553 (when (file-exists-p file)
17554 (if (and (car-safe old) refresh)
17555 (image-refresh (overlay-get (cdr old) 'display))
17556 (setq img (save-match-data (create-image file)))
17557 (when img
17558 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17559 (overlay-put ov 'display img)
17560 (overlay-put ov 'face 'default)
17561 (overlay-put ov 'org-image-overlay t)
17562 (overlay-put ov 'modification-hooks
17563 (list 'org-display-inline-modification-hook))
17564 (push ov org-inline-image-overlays)))))))))
17566 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17567 "Remove inline-display overlay if a corresponding region is modified."
17568 (let ((inhibit-modification-hooks t))
17569 (when (and ov after)
17570 (delete ov org-inline-image-overlays)
17571 (delete-overlay ov))))
17573 (defun org-remove-inline-images ()
17574 "Remove inline display of images."
17575 (interactive)
17576 (mapc 'delete-overlay org-inline-image-overlays)
17577 (setq org-inline-image-overlays nil))
17579 ;;;; Key bindings
17581 ;; Outline functions from `outline-mode-prefix-map'
17582 ;; that can be remapped in Org:
17583 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17584 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17585 (define-key org-mode-map [remap outline-forward-same-level]
17586 'org-forward-same-level)
17587 (define-key org-mode-map [remap outline-backward-same-level]
17588 'org-backward-same-level)
17589 (define-key org-mode-map [remap show-branches]
17590 'org-kill-note-or-show-branches)
17591 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17592 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17593 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17595 ;; Outline functions from `outline-mode-prefix-map'
17596 ;; that can not be remapped in Org:
17597 ;; - the column "key binding" shows whether the Outline function is still
17598 ;; available in Org mode on the same key that it has been bound to in
17599 ;; Outline mode:
17600 ;; - "overridden": key used for a different functionality in Org mode
17601 ;; - else: key still bound to the same Outline function in Org mode
17602 ;; | Outline function | key binding | Org replacement |
17603 ;; |------------------------------------+-------------+-----------------------|
17604 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17605 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17606 ;; | `show-children' | `C-c C-i' | visibility cycling |
17607 ;; | `hide-subtree' | overridden | visibility cycling |
17608 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17609 ;; | `hide-body' | overridden | no replacement |
17610 ;; | `show-all' | overridden | no replacement |
17611 ;; | `hide-entry' | overridden | visibility cycling |
17612 ;; | `show-entry' | overridden | no replacement |
17613 ;; | `hide-leaves' | overridden | no replacement |
17614 ;; | `hide-sublevels' | overridden | no replacement |
17615 ;; | `hide-other' | overridden | no replacement |
17616 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17617 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17619 ;; Make `C-c C-x' a prefix key
17620 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17622 ;; TAB key with modifiers
17623 (org-defkey org-mode-map "\C-i" 'org-cycle)
17624 (org-defkey org-mode-map [(tab)] 'org-cycle)
17625 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17626 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17627 ;; The following line is necessary under Suse GNU/Linux
17628 (unless (featurep 'xemacs)
17629 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17630 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17631 (define-key org-mode-map [backtab] 'org-shifttab)
17633 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17634 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17635 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17637 ;; Cursor keys with modifiers
17638 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17639 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17640 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17641 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17643 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17644 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17645 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17646 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17648 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17649 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17650 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17651 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17653 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17654 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17655 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17656 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17658 ;; Babel keys
17659 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17660 (mapc (lambda (pair)
17661 (define-key org-babel-map (car pair) (cdr pair)))
17662 org-babel-key-bindings)
17664 ;;; Extra keys for tty access.
17665 ;; We only set them when really needed because otherwise the
17666 ;; menus don't show the simple keys
17668 (when (or org-use-extra-keys
17669 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17670 (not window-system))
17671 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17672 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17673 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17674 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17675 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17676 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17677 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17678 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17679 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17680 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17681 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17682 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17683 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17684 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17685 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17686 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17687 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17688 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17689 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17690 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17691 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17692 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17693 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17694 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17695 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17696 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17697 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17698 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17700 ;; All the other keys
17702 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17703 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17704 (if (boundp 'narrow-map)
17705 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17706 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17707 (if (boundp 'narrow-map)
17708 (org-defkey narrow-map "b" 'org-narrow-to-block)
17709 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17710 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17711 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17712 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17713 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17714 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17715 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17716 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17717 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17718 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17719 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17720 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17721 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17722 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17723 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17724 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17725 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17726 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17727 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17728 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17729 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17730 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17731 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17732 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17733 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17734 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17735 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17736 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17737 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17738 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17739 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17740 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17741 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17742 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17743 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17744 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17745 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17746 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17747 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17748 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17749 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17750 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17751 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17752 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17753 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17754 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17755 (org-defkey org-mode-map "\C-c^" 'org-sort)
17756 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17757 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17758 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17759 (org-defkey org-mode-map "\C-m" 'org-return)
17760 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17761 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17762 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17763 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17764 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17765 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17766 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17767 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17768 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17769 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17770 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17771 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17772 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17773 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17774 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17775 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17776 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17777 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17778 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17779 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17780 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17781 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17782 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17784 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17785 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17786 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17787 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17789 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17790 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17791 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17792 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17793 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17794 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17795 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17796 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17797 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17798 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17799 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17800 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17801 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17802 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17803 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17804 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17805 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17806 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17808 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17809 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17810 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17811 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17812 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17814 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17816 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17818 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17819 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17821 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17824 (when (featurep 'xemacs)
17825 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17828 (defconst org-speed-commands-default
17830 ("Outline Navigation")
17831 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17832 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17833 ("f" . (org-speed-move-safe 'org-forward-same-level))
17834 ("b" . (org-speed-move-safe 'org-backward-same-level))
17835 ("u" . (org-speed-move-safe 'outline-up-heading))
17836 ("j" . org-goto)
17837 ("g" . (org-refile t))
17838 ("Outline Visibility")
17839 ("c" . org-cycle)
17840 ("C" . org-shifttab)
17841 (" " . org-display-outline-path)
17842 (":" . org-columns)
17843 ("Outline Structure Editing")
17844 ("U" . org-shiftmetaup)
17845 ("D" . org-shiftmetadown)
17846 ("r" . org-metaright)
17847 ("l" . org-metaleft)
17848 ("R" . org-shiftmetaright)
17849 ("L" . org-shiftmetaleft)
17850 ("i" . (progn (forward-char 1) (call-interactively
17851 'org-insert-heading-respect-content)))
17852 ("^" . org-sort)
17853 ("w" . org-refile)
17854 ("a" . org-archive-subtree-default-with-confirmation)
17855 ("." . org-mark-subtree)
17856 ("#" . org-toggle-comment)
17857 ("Clock Commands")
17858 ("I" . org-clock-in)
17859 ("O" . org-clock-out)
17860 ("Meta Data Editing")
17861 ("t" . org-todo)
17862 ("0" . (org-priority ?\ ))
17863 ("1" . (org-priority ?A))
17864 ("2" . (org-priority ?B))
17865 ("3" . (org-priority ?C))
17866 (";" . org-set-tags-command)
17867 ("e" . org-set-effort)
17868 ("Agenda Views etc")
17869 ("v" . org-agenda)
17870 ("/" . org-sparse-tree)
17871 ("Misc")
17872 ("o" . org-open-at-point)
17873 ("?" . org-speed-command-help)
17874 ("<" . (org-agenda-set-restriction-lock 'subtree))
17875 (">" . (org-agenda-remove-restriction-lock))
17877 "The default speed commands.")
17879 (defun org-print-speed-command (e)
17880 (if (> (length (car e)) 1)
17881 (progn
17882 (princ "\n")
17883 (princ (car e))
17884 (princ "\n")
17885 (princ (make-string (length (car e)) ?-))
17886 (princ "\n"))
17887 (princ (car e))
17888 (princ " ")
17889 (if (symbolp (cdr e))
17890 (princ (symbol-name (cdr e)))
17891 (prin1 (cdr e)))
17892 (princ "\n")))
17894 (defun org-speed-command-help ()
17895 "Show the available speed commands."
17896 (interactive)
17897 (if (not org-use-speed-commands)
17898 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17899 (with-output-to-temp-buffer "*Help*"
17900 (princ "User-defined Speed commands\n===========================\n")
17901 (mapc 'org-print-speed-command org-speed-commands-user)
17902 (princ "\n")
17903 (princ "Built-in Speed commands\n=======================\n")
17904 (mapc 'org-print-speed-command org-speed-commands-default))
17905 (with-current-buffer "*Help*"
17906 (setq truncate-lines t))))
17908 (defun org-speed-move-safe (cmd)
17909 "Execute CMD, but make sure that the cursor always ends up in a headline.
17910 If not, return to the original position and throw an error."
17911 (interactive)
17912 (let ((pos (point)))
17913 (call-interactively cmd)
17914 (unless (and (bolp) (org-at-heading-p))
17915 (goto-char pos)
17916 (error "Boundary reached while executing %s" cmd))))
17918 (defvar org-self-insert-command-undo-counter 0)
17920 (defvar org-table-auto-blank-field) ; defined in org-table.el
17921 (defvar org-speed-command nil)
17923 (defun org-speed-command-default-hook (keys)
17924 "Hook for activating single-letter speed commands.
17925 `org-speed-commands-default' specifies a minimal command set.
17926 Use `org-speed-commands-user' for further customization."
17927 (when (or (and (bolp) (looking-at org-outline-regexp))
17928 (and (functionp org-use-speed-commands)
17929 (funcall org-use-speed-commands)))
17930 (cdr (assoc keys (append org-speed-commands-user
17931 org-speed-commands-default)))))
17933 (defun org-babel-speed-command-hook (keys)
17934 "Hook for activating single-letter code block commands."
17935 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17936 (cdr (assoc keys org-babel-key-bindings))))
17938 (defcustom org-speed-command-hook
17939 '(org-speed-command-default-hook org-babel-speed-command-hook)
17940 "Hook for activating speed commands at strategic locations.
17941 Hook functions are called in sequence until a valid handler is
17942 found.
17944 Each hook takes a single argument, a user-pressed command key
17945 which is also a `self-insert-command' from the global map.
17947 Within the hook, examine the cursor position and the command key
17948 and return nil or a valid handler as appropriate. Handler could
17949 be one of an interactive command, a function, or a form.
17951 Set `org-use-speed-commands' to non-nil value to enable this
17952 hook. The default setting is `org-speed-command-default-hook'."
17953 :group 'org-structure
17954 :version "24.1"
17955 :type 'hook)
17957 (defun org-self-insert-command (N)
17958 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17959 If the cursor is in a table looking at whitespace, the whitespace is
17960 overwritten, and the table is not marked as requiring realignment."
17961 (interactive "p")
17962 (org-check-before-invisible-edit 'insert)
17963 (cond
17964 ((and org-use-speed-commands
17965 (setq org-speed-command
17966 (run-hook-with-args-until-success
17967 'org-speed-command-hook (this-command-keys))))
17968 (cond
17969 ((commandp org-speed-command)
17970 (setq this-command org-speed-command)
17971 (call-interactively org-speed-command))
17972 ((functionp org-speed-command)
17973 (funcall org-speed-command))
17974 ((and org-speed-command (listp org-speed-command))
17975 (eval org-speed-command))
17976 (t (let (org-use-speed-commands)
17977 (call-interactively 'org-self-insert-command)))))
17978 ((and
17979 (org-table-p)
17980 (progn
17981 ;; check if we blank the field, and if that triggers align
17982 (and (featurep 'org-table) org-table-auto-blank-field
17983 (member last-command
17984 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17985 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17986 ;; got extra space, this field does not determine column width
17987 (let (org-table-may-need-update) (org-table-blank-field))
17988 ;; no extra space, this field may determine column width
17989 (org-table-blank-field)))
17991 (eq N 1)
17992 (looking-at "[^|\n]* |"))
17993 (let (org-table-may-need-update)
17994 (goto-char (1- (match-end 0)))
17995 (backward-delete-char 1)
17996 (goto-char (match-beginning 0))
17997 (self-insert-command N)))
17999 (setq org-table-may-need-update t)
18000 (self-insert-command N)
18001 (org-fix-tags-on-the-fly)
18002 (if org-self-insert-cluster-for-undo
18003 (if (not (eq last-command 'org-self-insert-command))
18004 (setq org-self-insert-command-undo-counter 1)
18005 (if (>= org-self-insert-command-undo-counter 20)
18006 (setq org-self-insert-command-undo-counter 1)
18007 (and (> org-self-insert-command-undo-counter 0)
18008 buffer-undo-list (listp buffer-undo-list)
18009 (not (cadr buffer-undo-list)) ; remove nil entry
18010 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18011 (setq org-self-insert-command-undo-counter
18012 (1+ org-self-insert-command-undo-counter))))))))
18014 (defun org-check-before-invisible-edit (kind)
18015 "Check is editing if kind KIND would be dangerous with invisible text around.
18016 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18017 ;; First, try to get out of here as quickly as possible, to reduce overhead
18018 (if (and org-catch-invisible-edits
18019 (or (not (boundp 'visible-mode)) (not visible-mode))
18020 (or (get-char-property (point) 'invisible)
18021 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18022 ;; OK, we need to take a closer look
18023 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18024 (invisible-before-point (if (bobp) nil (get-char-property
18025 (1- (point)) 'invisible)))
18026 (border-and-ok-direction
18028 ;; Check if we are acting predictably before invisible text
18029 (and invisible-at-point (not invisible-before-point)
18030 (memq kind '(insert delete-backward)))
18031 ;; Check if we are acting predictably after invisible text
18032 ;; This works not well, and I have turned it off. It seems
18033 ;; better to always show and stop after invisible text.
18034 ;; (and (not invisible-at-point) invisible-before-point
18035 ;; (memq kind '(insert delete)))
18038 (when (or (memq invisible-at-point '(outline org-hide-block))
18039 (memq invisible-before-point '(outline org-hide-block)))
18040 (if (eq org-catch-invisible-edits 'error)
18041 (error "Editing in invisible areas is prohibited - make visible first"))
18042 ;; Make the area visible
18043 (save-excursion
18044 (if invisible-before-point
18045 (goto-char (previous-single-char-property-change
18046 (point) 'invisible)))
18047 (org-cycle))
18048 (cond
18049 ((eq org-catch-invisible-edits 'show)
18050 ;; That's it, we do the edit after showing
18051 (message
18052 "Unfolding invisible region around point before editing")
18053 (sit-for 1))
18054 ((and (eq org-catch-invisible-edits 'smart)
18055 border-and-ok-direction)
18056 (message "Unfolding invisible region around point before editing"))
18058 ;; Don't do the edit, make the user repeat it in full visibility
18059 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
18061 (defun org-fix-tags-on-the-fly ()
18062 (when (and (equal (char-after (point-at-bol)) ?*)
18063 (org-at-heading-p))
18064 (org-align-tags-here org-tags-column)))
18066 (defun org-delete-backward-char (N)
18067 "Like `delete-backward-char', insert whitespace at field end in tables.
18068 When deleting backwards, in tables this function will insert whitespace in
18069 front of the next \"|\" separator, to keep the table aligned. The table will
18070 still be marked for re-alignment if the field did fill the entire column,
18071 because, in this case the deletion might narrow the column."
18072 (interactive "p")
18073 (org-check-before-invisible-edit 'delete-backward)
18074 (if (and (org-table-p)
18075 (eq N 1)
18076 (string-match "|" (buffer-substring (point-at-bol) (point)))
18077 (looking-at ".*?|"))
18078 (let ((pos (point))
18079 (noalign (looking-at "[^|\n\r]* |"))
18080 (c org-table-may-need-update))
18081 (backward-delete-char N)
18082 (if (not overwrite-mode)
18083 (progn
18084 (skip-chars-forward "^|")
18085 (insert " ")
18086 (goto-char (1- pos))))
18087 ;; noalign: if there were two spaces at the end, this field
18088 ;; does not determine the width of the column.
18089 (if noalign (setq org-table-may-need-update c)))
18090 (backward-delete-char N)
18091 (org-fix-tags-on-the-fly)))
18093 (defun org-delete-char (N)
18094 "Like `delete-char', but insert whitespace at field end in tables.
18095 When deleting characters, in tables this function will insert whitespace in
18096 front of the next \"|\" separator, to keep the table aligned. The table will
18097 still be marked for re-alignment if the field did fill the entire column,
18098 because, in this case the deletion might narrow the column."
18099 (interactive "p")
18100 (org-check-before-invisible-edit 'delete)
18101 (if (and (org-table-p)
18102 (not (bolp))
18103 (not (= (char-after) ?|))
18104 (eq N 1))
18105 (if (looking-at ".*?|")
18106 (let ((pos (point))
18107 (noalign (looking-at "[^|\n\r]* |"))
18108 (c org-table-may-need-update))
18109 (replace-match (concat
18110 (substring (match-string 0) 1 -1)
18111 " |"))
18112 (goto-char pos)
18113 ;; noalign: if there were two spaces at the end, this field
18114 ;; does not determine the width of the column.
18115 (if noalign (setq org-table-may-need-update c)))
18116 (delete-char N))
18117 (delete-char N)
18118 (org-fix-tags-on-the-fly)))
18120 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18121 (put 'org-self-insert-command 'delete-selection t)
18122 (put 'orgtbl-self-insert-command 'delete-selection t)
18123 (put 'org-delete-char 'delete-selection 'supersede)
18124 (put 'org-delete-backward-char 'delete-selection 'supersede)
18125 (put 'org-yank 'delete-selection 'yank)
18127 ;; Make `flyspell-mode' delay after some commands
18128 (put 'org-self-insert-command 'flyspell-delayed t)
18129 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18130 (put 'org-delete-char 'flyspell-delayed t)
18131 (put 'org-delete-backward-char 'flyspell-delayed t)
18133 ;; Make pabbrev-mode expand after org-mode commands
18134 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18135 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18137 ;; How to do this: Measure non-white length of current string
18138 ;; If equal to column width, we should realign.
18140 (defun org-remap (map &rest commands)
18141 "In MAP, remap the functions given in COMMANDS.
18142 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18143 (let (new old)
18144 (while commands
18145 (setq old (pop commands) new (pop commands))
18146 (if (fboundp 'command-remapping)
18147 (org-defkey map (vector 'remap old) new)
18148 (substitute-key-definition old new map global-map)))))
18150 (when (eq org-enable-table-editor 'optimized)
18151 ;; If the user wants maximum table support, we need to hijack
18152 ;; some standard editing functions
18153 (org-remap org-mode-map
18154 'self-insert-command 'org-self-insert-command
18155 'delete-char 'org-delete-char
18156 'delete-backward-char 'org-delete-backward-char)
18157 (org-defkey org-mode-map "|" 'org-force-self-insert))
18159 (defvar org-ctrl-c-ctrl-c-hook nil
18160 "Hook for functions attaching themselves to `C-c C-c'.
18162 This can be used to add additional functionality to the C-c C-c
18163 key which executes context-dependent commands. This hook is run
18164 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18165 run after the last test.
18167 Each function will be called with no arguments. The function
18168 must check if the context is appropriate for it to act. If yes,
18169 it should do its thing and then return a non-nil value. If the
18170 context is wrong, just do nothing and return nil.")
18172 (defvar org-ctrl-c-ctrl-c-final-hook nil
18173 "Hook for functions attaching themselves to `C-c C-c'.
18175 This can be used to add additional functionality to the C-c C-c
18176 key which executes context-dependent commands. This hook is run
18177 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18178 before the first test.
18180 Each function will be called with no arguments. The function
18181 must check if the context is appropriate for it to act. If yes,
18182 it should do its thing and then return a non-nil value. If the
18183 context is wrong, just do nothing and return nil.")
18185 (defvar org-tab-first-hook nil
18186 "Hook for functions to attach themselves to TAB.
18187 See `org-ctrl-c-ctrl-c-hook' for more information.
18188 This hook runs as the first action when TAB is pressed, even before
18189 `org-cycle' messes around with the `outline-regexp' to cater for
18190 inline tasks and plain list item folding.
18191 If any function in this hook returns t, any other actions that
18192 would have been caused by TAB (such as table field motion or visibility
18193 cycling) will not occur.")
18195 (defvar org-tab-after-check-for-table-hook nil
18196 "Hook for functions to attach themselves to TAB.
18197 See `org-ctrl-c-ctrl-c-hook' for more information.
18198 This hook runs after it has been established that the cursor is not in a
18199 table, but before checking if the cursor is in a headline or if global cycling
18200 should be done.
18201 If any function in this hook returns t, not other actions like visibility
18202 cycling will be done.")
18204 (defvar org-tab-after-check-for-cycling-hook nil
18205 "Hook for functions to attach themselves to TAB.
18206 See `org-ctrl-c-ctrl-c-hook' for more information.
18207 This hook runs after it has been established that not table field motion and
18208 not visibility should be done because of current context. This is probably
18209 the place where a package like yasnippets can hook in.")
18211 (defvar org-tab-before-tab-emulation-hook nil
18212 "Hook for functions to attach themselves to TAB.
18213 See `org-ctrl-c-ctrl-c-hook' for more information.
18214 This hook runs after every other options for TAB have been exhausted, but
18215 before indentation and \t insertion takes place.")
18217 (defvar org-metaleft-hook nil
18218 "Hook for functions attaching themselves to `M-left'.
18219 See `org-ctrl-c-ctrl-c-hook' for more information.")
18220 (defvar org-metaright-hook nil
18221 "Hook for functions attaching themselves to `M-right'.
18222 See `org-ctrl-c-ctrl-c-hook' for more information.")
18223 (defvar org-metaup-hook nil
18224 "Hook for functions attaching themselves to `M-up'.
18225 See `org-ctrl-c-ctrl-c-hook' for more information.")
18226 (defvar org-metadown-hook nil
18227 "Hook for functions attaching themselves to `M-down'.
18228 See `org-ctrl-c-ctrl-c-hook' for more information.")
18229 (defvar org-shiftmetaleft-hook nil
18230 "Hook for functions attaching themselves to `M-S-left'.
18231 See `org-ctrl-c-ctrl-c-hook' for more information.")
18232 (defvar org-shiftmetaright-hook nil
18233 "Hook for functions attaching themselves to `M-S-right'.
18234 See `org-ctrl-c-ctrl-c-hook' for more information.")
18235 (defvar org-shiftmetaup-hook nil
18236 "Hook for functions attaching themselves to `M-S-up'.
18237 See `org-ctrl-c-ctrl-c-hook' for more information.")
18238 (defvar org-shiftmetadown-hook nil
18239 "Hook for functions attaching themselves to `M-S-down'.
18240 See `org-ctrl-c-ctrl-c-hook' for more information.")
18241 (defvar org-metareturn-hook nil
18242 "Hook for functions attaching themselves to `M-RET'.
18243 See `org-ctrl-c-ctrl-c-hook' for more information.")
18244 (defvar org-shiftup-hook nil
18245 "Hook for functions attaching themselves to `S-up'.
18246 See `org-ctrl-c-ctrl-c-hook' for more information.")
18247 (defvar org-shiftup-final-hook nil
18248 "Hook for functions attaching themselves to `S-up'.
18249 This one runs after all other options except shift-select have been excluded.
18250 See `org-ctrl-c-ctrl-c-hook' for more information.")
18251 (defvar org-shiftdown-hook nil
18252 "Hook for functions attaching themselves to `S-down'.
18253 See `org-ctrl-c-ctrl-c-hook' for more information.")
18254 (defvar org-shiftdown-final-hook nil
18255 "Hook for functions attaching themselves to `S-down'.
18256 This one runs after all other options except shift-select have been excluded.
18257 See `org-ctrl-c-ctrl-c-hook' for more information.")
18258 (defvar org-shiftleft-hook nil
18259 "Hook for functions attaching themselves to `S-left'.
18260 See `org-ctrl-c-ctrl-c-hook' for more information.")
18261 (defvar org-shiftleft-final-hook nil
18262 "Hook for functions attaching themselves to `S-left'.
18263 This one runs after all other options except shift-select have been excluded.
18264 See `org-ctrl-c-ctrl-c-hook' for more information.")
18265 (defvar org-shiftright-hook nil
18266 "Hook for functions attaching themselves to `S-right'.
18267 See `org-ctrl-c-ctrl-c-hook' for more information.")
18268 (defvar org-shiftright-final-hook nil
18269 "Hook for functions attaching themselves to `S-right'.
18270 This one runs after all other options except shift-select have been excluded.
18271 See `org-ctrl-c-ctrl-c-hook' for more information.")
18273 (defun org-modifier-cursor-error ()
18274 "Throw an error, a modified cursor command was applied in wrong context."
18275 (error "This command is active in special context like tables, headlines or items"))
18277 (defun org-shiftselect-error ()
18278 "Throw an error because Shift-Cursor command was applied in wrong context."
18279 (if (and (boundp 'shift-select-mode) shift-select-mode)
18280 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18281 (error "This command works only in special context like headlines or timestamps")))
18283 (defun org-call-for-shift-select (cmd)
18284 (let ((this-command-keys-shift-translated t))
18285 (call-interactively cmd)))
18287 (defun org-shifttab (&optional arg)
18288 "Global visibility cycling or move to previous table field.
18289 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18290 on context.
18291 See the individual commands for more information."
18292 (interactive "P")
18293 (cond
18294 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18295 ((integerp arg)
18296 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18297 (message "Content view to level: %d" arg)
18298 (org-content (prefix-numeric-value arg2))
18299 (setq org-cycle-global-status 'overview)))
18300 (t (call-interactively 'org-global-cycle))))
18302 (defun org-shiftmetaleft ()
18303 "Promote subtree or delete table column.
18304 Calls `org-promote-subtree', `org-outdent-item-tree', or
18305 `org-table-delete-column', depending on context. See the
18306 individual commands for more information."
18307 (interactive)
18308 (cond
18309 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18310 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18311 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18312 ((if (not (org-region-active-p)) (org-at-item-p)
18313 (save-excursion (goto-char (region-beginning))
18314 (org-at-item-p)))
18315 (call-interactively 'org-outdent-item-tree))
18316 (t (org-modifier-cursor-error))))
18318 (defun org-shiftmetaright ()
18319 "Demote subtree or insert table column.
18320 Calls `org-demote-subtree', `org-indent-item-tree', or
18321 `org-table-insert-column', depending on context. See the
18322 individual commands for more information."
18323 (interactive)
18324 (cond
18325 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18326 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18327 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18328 ((if (not (org-region-active-p)) (org-at-item-p)
18329 (save-excursion (goto-char (region-beginning))
18330 (org-at-item-p)))
18331 (call-interactively 'org-indent-item-tree))
18332 (t (org-modifier-cursor-error))))
18334 (defun org-shiftmetaup (&optional arg)
18335 "Move subtree up or kill table row.
18336 Calls `org-move-subtree-up' or `org-table-kill-row' or
18337 `org-move-item-up' depending on context. See the individual commands
18338 for more information."
18339 (interactive "P")
18340 (cond
18341 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18342 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18343 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18344 ((org-at-item-p) (call-interactively 'org-move-item-up))
18345 (t (org-modifier-cursor-error))))
18347 (defun org-shiftmetadown (&optional arg)
18348 "Move subtree down or insert table row.
18349 Calls `org-move-subtree-down' or `org-table-insert-row' or
18350 `org-move-item-down', depending on context. See the individual
18351 commands for more information."
18352 (interactive "P")
18353 (cond
18354 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18355 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18356 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18357 ((org-at-item-p) (call-interactively 'org-move-item-down))
18358 (t (org-modifier-cursor-error))))
18360 (defsubst org-hidden-tree-error ()
18361 (error
18362 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18364 (defun org-metaleft (&optional arg)
18365 "Promote heading or move table column to left.
18366 Calls `org-do-promote' or `org-table-move-column', depending on context.
18367 With no specific context, calls the Emacs default `backward-word'.
18368 See the individual commands for more information."
18369 (interactive "P")
18370 (cond
18371 ((run-hook-with-args-until-success 'org-metaleft-hook))
18372 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18373 ((org-with-limited-levels
18374 (or (org-at-heading-p)
18375 (and (org-region-active-p)
18376 (save-excursion
18377 (goto-char (region-beginning))
18378 (org-at-heading-p)))))
18379 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18380 (call-interactively 'org-do-promote))
18381 ;; At an inline task.
18382 ((org-at-heading-p)
18383 (call-interactively 'org-inlinetask-promote))
18384 ((or (org-at-item-p)
18385 (and (org-region-active-p)
18386 (save-excursion
18387 (goto-char (region-beginning))
18388 (org-at-item-p))))
18389 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18390 (call-interactively 'org-outdent-item))
18391 (t (call-interactively 'backward-word))))
18393 (defun org-metaright (&optional arg)
18394 "Demote a subtree, a list item or move table column to right.
18395 In front of a drawer or a block keyword, indent it correctly.
18396 With no specific context, calls the Emacs default `forward-word'.
18397 See the individual commands for more information."
18398 (interactive "P")
18399 (cond
18400 ((run-hook-with-args-until-success 'org-metaright-hook))
18401 ((org-at-table-p) (call-interactively 'org-table-move-column))
18402 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18403 ((org-at-block-p) (call-interactively 'org-indent-block))
18404 ((org-with-limited-levels
18405 (or (org-at-heading-p)
18406 (and (org-region-active-p)
18407 (save-excursion
18408 (goto-char (region-beginning))
18409 (org-at-heading-p)))))
18410 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18411 (call-interactively 'org-do-demote))
18412 ;; At an inline task.
18413 ((org-at-heading-p)
18414 (call-interactively 'org-inlinetask-demote))
18415 ((or (org-at-item-p)
18416 (and (org-region-active-p)
18417 (save-excursion
18418 (goto-char (region-beginning))
18419 (org-at-item-p))))
18420 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18421 (call-interactively 'org-indent-item))
18422 (t (call-interactively 'forward-word))))
18424 (defun org-check-for-hidden (what)
18425 "Check if there are hidden headlines/items in the current visual line.
18426 WHAT can be either `headlines' or `items'. If the current line is
18427 an outline or item heading and it has a folded subtree below it,
18428 this function returns t, nil otherwise."
18429 (let ((re (cond
18430 ((eq what 'headlines) org-outline-regexp-bol)
18431 ((eq what 'items) (org-item-beginning-re))
18432 (t (error "This should not happen"))))
18433 beg end)
18434 (save-excursion
18435 (catch 'exit
18436 (unless (org-region-active-p)
18437 (setq beg (point-at-bol))
18438 (beginning-of-line 2)
18439 (while (and (not (eobp)) ;; this is like `next-line'
18440 (get-char-property (1- (point)) 'invisible))
18441 (beginning-of-line 2))
18442 (setq end (point))
18443 (goto-char beg)
18444 (goto-char (point-at-eol))
18445 (setq end (max end (point)))
18446 (while (re-search-forward re end t)
18447 (if (get-char-property (match-beginning 0) 'invisible)
18448 (throw 'exit t))))
18449 nil))))
18451 (defun org-metaup (&optional arg)
18452 "Move subtree up or move table row up.
18453 Calls `org-move-subtree-up' or `org-table-move-row' or
18454 `org-move-item-up', depending on context. See the individual commands
18455 for more information."
18456 (interactive "P")
18457 (cond
18458 ((run-hook-with-args-until-success 'org-metaup-hook))
18459 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18460 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18461 ((org-at-item-p) (call-interactively 'org-move-item-up))
18462 (t (transpose-lines 1) (beginning-of-line -1))))
18464 (defun org-metadown (&optional arg)
18465 "Move subtree down or move table row down.
18466 Calls `org-move-subtree-down' or `org-table-move-row' or
18467 `org-move-item-down', depending on context. See the individual
18468 commands for more information."
18469 (interactive "P")
18470 (cond
18471 ((run-hook-with-args-until-success 'org-metadown-hook))
18472 ((org-at-table-p) (call-interactively 'org-table-move-row))
18473 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18474 ((org-at-item-p) (call-interactively 'org-move-item-down))
18475 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18477 (defun org-shiftup (&optional arg)
18478 "Increase item in timestamp or increase priority of current headline.
18479 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18480 depending on context. See the individual commands for more information."
18481 (interactive "P")
18482 (cond
18483 ((run-hook-with-args-until-success 'org-shiftup-hook))
18484 ((and org-support-shift-select (org-region-active-p))
18485 (org-call-for-shift-select 'previous-line))
18486 ((org-at-timestamp-p t)
18487 (call-interactively (if org-edit-timestamp-down-means-later
18488 'org-timestamp-down 'org-timestamp-up)))
18489 ((and (not (eq org-support-shift-select 'always))
18490 org-enable-priority-commands
18491 (org-at-heading-p))
18492 (call-interactively 'org-priority-up))
18493 ((and (not org-support-shift-select) (org-at-item-p))
18494 (call-interactively 'org-previous-item))
18495 ((org-clocktable-try-shift 'up arg))
18496 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18497 (org-support-shift-select
18498 (org-call-for-shift-select 'previous-line))
18499 (t (org-shiftselect-error))))
18501 (defun org-shiftdown (&optional arg)
18502 "Decrease item in timestamp or decrease priority of current headline.
18503 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18504 depending on context. See the individual commands for more information."
18505 (interactive "P")
18506 (cond
18507 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18508 ((and org-support-shift-select (org-region-active-p))
18509 (org-call-for-shift-select 'next-line))
18510 ((org-at-timestamp-p t)
18511 (call-interactively (if org-edit-timestamp-down-means-later
18512 'org-timestamp-up 'org-timestamp-down)))
18513 ((and (not (eq org-support-shift-select 'always))
18514 org-enable-priority-commands
18515 (org-at-heading-p))
18516 (call-interactively 'org-priority-down))
18517 ((and (not org-support-shift-select) (org-at-item-p))
18518 (call-interactively 'org-next-item))
18519 ((org-clocktable-try-shift 'down arg))
18520 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18521 (org-support-shift-select
18522 (org-call-for-shift-select 'next-line))
18523 (t (org-shiftselect-error))))
18525 (defun org-shiftright (&optional arg)
18526 "Cycle the thing at point or in the current line, depending on context.
18527 Depending on context, this does one of the following:
18529 - switch a timestamp at point one day into the future
18530 - on a headline, switch to the next TODO keyword.
18531 - on an item, switch entire list to the next bullet type
18532 - on a property line, switch to the next allowed value
18533 - on a clocktable definition line, move time block into the future"
18534 (interactive "P")
18535 (cond
18536 ((run-hook-with-args-until-success 'org-shiftright-hook))
18537 ((and org-support-shift-select (org-region-active-p))
18538 (org-call-for-shift-select 'forward-char))
18539 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18540 ((and (not (eq org-support-shift-select 'always))
18541 (org-at-heading-p))
18542 (let ((org-inhibit-logging
18543 (not org-treat-S-cursor-todo-selection-as-state-change))
18544 (org-inhibit-blocking
18545 (not org-treat-S-cursor-todo-selection-as-state-change)))
18546 (org-call-with-arg 'org-todo 'right)))
18547 ((or (and org-support-shift-select
18548 (not (eq org-support-shift-select 'always))
18549 (org-at-item-bullet-p))
18550 (and (not org-support-shift-select) (org-at-item-p)))
18551 (org-call-with-arg 'org-cycle-list-bullet nil))
18552 ((and (not (eq org-support-shift-select 'always))
18553 (org-at-property-p))
18554 (call-interactively 'org-property-next-allowed-value))
18555 ((org-clocktable-try-shift 'right arg))
18556 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18557 (org-support-shift-select
18558 (org-call-for-shift-select 'forward-char))
18559 (t (org-shiftselect-error))))
18561 (defun org-shiftleft (&optional arg)
18562 "Cycle the thing at point or in the current line, depending on context.
18563 Depending on context, this does one of the following:
18565 - switch a timestamp at point one day into the past
18566 - on a headline, switch to the previous TODO keyword.
18567 - on an item, switch entire list to the previous bullet type
18568 - on a property line, switch to the previous allowed value
18569 - on a clocktable definition line, move time block into the past"
18570 (interactive "P")
18571 (cond
18572 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18573 ((and org-support-shift-select (org-region-active-p))
18574 (org-call-for-shift-select 'backward-char))
18575 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18576 ((and (not (eq org-support-shift-select 'always))
18577 (org-at-heading-p))
18578 (let ((org-inhibit-logging
18579 (not org-treat-S-cursor-todo-selection-as-state-change))
18580 (org-inhibit-blocking
18581 (not org-treat-S-cursor-todo-selection-as-state-change)))
18582 (org-call-with-arg 'org-todo 'left)))
18583 ((or (and org-support-shift-select
18584 (not (eq org-support-shift-select 'always))
18585 (org-at-item-bullet-p))
18586 (and (not org-support-shift-select) (org-at-item-p)))
18587 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18588 ((and (not (eq org-support-shift-select 'always))
18589 (org-at-property-p))
18590 (call-interactively 'org-property-previous-allowed-value))
18591 ((org-clocktable-try-shift 'left arg))
18592 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18593 (org-support-shift-select
18594 (org-call-for-shift-select 'backward-char))
18595 (t (org-shiftselect-error))))
18597 (defun org-shiftcontrolright ()
18598 "Switch to next TODO set."
18599 (interactive)
18600 (cond
18601 ((and org-support-shift-select (org-region-active-p))
18602 (org-call-for-shift-select 'forward-word))
18603 ((and (not (eq org-support-shift-select 'always))
18604 (org-at-heading-p))
18605 (org-call-with-arg 'org-todo 'nextset))
18606 (org-support-shift-select
18607 (org-call-for-shift-select 'forward-word))
18608 (t (org-shiftselect-error))))
18610 (defun org-shiftcontrolleft ()
18611 "Switch to previous TODO set."
18612 (interactive)
18613 (cond
18614 ((and org-support-shift-select (org-region-active-p))
18615 (org-call-for-shift-select 'backward-word))
18616 ((and (not (eq org-support-shift-select 'always))
18617 (org-at-heading-p))
18618 (org-call-with-arg 'org-todo 'previousset))
18619 (org-support-shift-select
18620 (org-call-for-shift-select 'backward-word))
18621 (t (org-shiftselect-error))))
18623 (defun org-shiftcontrolup ()
18624 "Change timestamps synchronously up in CLOCK log lines."
18625 (interactive)
18626 (cond ((and (not org-support-shift-select)
18627 (org-at-clock-log-p)
18628 (org-at-timestamp-p t))
18629 (org-clock-timestamps-up))
18630 (t (org-shiftselect-error))))
18632 (defun org-shiftcontroldown ()
18633 "Change timestamps synchronously down in CLOCK log lines."
18634 (interactive)
18635 (cond ((and (not org-support-shift-select)
18636 (org-at-clock-log-p)
18637 (org-at-timestamp-p t))
18638 (org-clock-timestamps-down))
18639 (t (org-shiftselect-error))))
18641 (defun org-ctrl-c-ret ()
18642 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18643 (interactive)
18644 (cond
18645 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18646 (t (call-interactively 'org-insert-heading))))
18648 (defun org-find-visible ()
18649 (let ((s (point)))
18650 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18651 (get-char-property s 'invisible)))
18653 (defun org-find-invisible ()
18654 (let ((s (point)))
18655 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18656 (not (get-char-property s 'invisible))))
18659 (defun org-copy-visible (beg end)
18660 "Copy the visible parts of the region."
18661 (interactive "r")
18662 (let (snippets s)
18663 (save-excursion
18664 (save-restriction
18665 (narrow-to-region beg end)
18666 (setq s (goto-char (point-min)))
18667 (while (not (= (point) (point-max)))
18668 (goto-char (org-find-invisible))
18669 (push (buffer-substring s (point)) snippets)
18670 (setq s (goto-char (org-find-visible))))))
18671 (kill-new (apply 'concat (nreverse snippets)))))
18673 (defun org-copy-special ()
18674 "Copy region in table or copy current subtree.
18675 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18676 See the individual commands for more information."
18677 (interactive)
18678 (call-interactively
18679 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18681 (defun org-cut-special ()
18682 "Cut region in table or cut current subtree.
18683 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18684 See the individual commands for more information."
18685 (interactive)
18686 (call-interactively
18687 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18689 (defun org-paste-special (arg)
18690 "Paste rectangular region into table, or past subtree relative to level.
18691 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18692 See the individual commands for more information."
18693 (interactive "P")
18694 (if (org-at-table-p)
18695 (org-table-paste-rectangle)
18696 (org-paste-subtree arg)))
18698 (defun org-edit-special (&optional arg)
18699 "Call a special editor for the stuff at point.
18700 When at a table, call the formula editor with `org-table-edit-formulas'.
18701 When at the first line of an src example, call `org-edit-src-code'.
18702 When in an #+include line, visit the include file. Otherwise call
18703 `ffap' to visit the file at point."
18704 (interactive)
18705 ;; possibly prep session before editing source
18706 (when arg
18707 (let* ((info (org-babel-get-src-block-info))
18708 (lang (nth 0 info))
18709 (params (nth 2 info))
18710 (session (cdr (assoc :session params))))
18711 (when (and info session) ;; we are in a source-code block with a session
18712 (funcall
18713 (intern (concat "org-babel-prep-session:" lang)) session params))))
18714 (cond ;; proceed with `org-edit-special'
18715 ((save-excursion
18716 (beginning-of-line 1)
18717 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18718 (find-file (org-trim (match-string 1))))
18719 ((org-edit-src-code))
18720 ((org-edit-fixed-width-region))
18721 ((org-at-table.el-p)
18722 (org-edit-src-code))
18723 ((or (org-at-table-p)
18724 (save-excursion
18725 (beginning-of-line 1)
18726 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18727 (call-interactively 'org-table-edit-formulas))
18728 (t (call-interactively 'ffap))))
18730 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18731 (defun org-ctrl-c-ctrl-c (&optional arg)
18732 "Set tags in headline, or update according to changed information at point.
18734 This command does many different things, depending on context:
18736 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18737 this is what we do.
18739 - If the cursor is on a statistics cookie, update it.
18741 - If the cursor is in a headline, prompt for tags and insert them
18742 into the current line, aligned to `org-tags-column'. When called
18743 with prefix arg, realign all tags in the current buffer.
18745 - If the cursor is in one of the special #+KEYWORD lines, this
18746 triggers scanning the buffer for these lines and updating the
18747 information.
18749 - If the cursor is inside a table, realign the table. This command
18750 works even if the automatic table editor has been turned off.
18752 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18753 the entire table.
18755 - If the cursor is at a footnote reference or definition, jump to
18756 the corresponding definition or references, respectively.
18758 - If the cursor is a the beginning of a dynamic block, update it.
18760 - If the current buffer is a capture buffer, close note and file it.
18762 - If the cursor is on a <<<target>>>, update radio targets and
18763 corresponding links in this buffer.
18765 - If the cursor is on a numbered item in a plain list, renumber the
18766 ordered list.
18768 - If the cursor is on a checkbox, toggle it.
18770 - If the cursor is on a code block, evaluate it. The variable
18771 `org-confirm-babel-evaluate' can be used to control prompting
18772 before code block evaluation, by default every code block
18773 evaluation requires confirmation. Code block evaluation can be
18774 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18775 (interactive "P")
18776 (let ((org-enable-table-editor t))
18777 (cond
18778 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18779 org-occur-highlights
18780 org-latex-fragment-image-overlays)
18781 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18782 (org-remove-occur-highlights)
18783 (org-remove-latex-fragment-image-overlays)
18784 (message "Temporary highlights/overlays removed from current buffer"))
18785 ((and (local-variable-p 'org-finish-function (current-buffer))
18786 (fboundp org-finish-function))
18787 (funcall org-finish-function))
18788 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18789 ((org-in-regexp org-ts-regexp-both)
18790 (org-timestamp-change 0 'day))
18791 ((or (looking-at org-property-start-re)
18792 (org-at-property-p))
18793 (call-interactively 'org-property-action))
18794 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18795 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18796 (or (org-at-heading-p) (org-at-item-p)))
18797 (call-interactively 'org-update-statistics-cookies))
18798 ((org-at-heading-p) (call-interactively 'org-set-tags))
18799 ((org-at-table.el-p)
18800 (message "Use C-c ' to edit table.el tables"))
18801 ((org-at-table-p)
18802 (org-table-maybe-eval-formula)
18803 (if arg
18804 (call-interactively 'org-table-recalculate)
18805 (org-table-maybe-recalculate-line))
18806 (call-interactively 'org-table-align)
18807 (orgtbl-send-table 'maybe))
18808 ((or (org-footnote-at-reference-p)
18809 (org-footnote-at-definition-p))
18810 (call-interactively 'org-footnote-action))
18811 ((org-at-item-checkbox-p)
18812 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18813 ;; list only if at top item.
18814 (let* ((cbox (match-string 1))
18815 (struct (org-list-struct))
18816 (old-struct (copy-tree struct))
18817 (parents (org-list-parents-alist struct))
18818 (orderedp (org-entry-get nil "ORDERED"))
18819 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18820 block-item)
18821 ;; Use a light version of `org-toggle-checkbox' to avoid
18822 ;; computing list structure twice.
18823 (let ((new-box (cond
18824 ((equal arg '(16)) "[-]")
18825 ((equal arg '(4)) nil)
18826 ((equal "[X]" cbox) "[ ]")
18827 (t "[X]"))))
18828 (if (and firstp arg)
18829 ;; If at first item of sub-list, remove check-box from
18830 ;; every item at the same level.
18831 (mapc
18832 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18833 (org-list-get-all-items
18834 (point-at-bol) struct (org-list-prevs-alist struct)))
18835 (org-list-set-checkbox (point-at-bol) struct new-box)))
18836 ;; Replicate `org-list-write-struct', while grabbing a return
18837 ;; value from `org-list-struct-fix-box'.
18838 (org-list-struct-fix-ind struct parents 2)
18839 (org-list-struct-fix-item-end struct)
18840 (let ((prevs (org-list-prevs-alist struct)))
18841 (org-list-struct-fix-bul struct prevs)
18842 (org-list-struct-fix-ind struct parents)
18843 (setq block-item
18844 (org-list-struct-fix-box struct parents prevs orderedp)))
18845 (org-list-struct-apply-struct struct old-struct)
18846 (org-update-checkbox-count-maybe)
18847 (when block-item
18848 (message
18849 "Checkboxes were removed due to unchecked box at line %d"
18850 (org-current-line block-item)))
18851 (when firstp (org-list-send-list 'maybe))))
18852 ((org-at-item-p)
18853 ;; Cursor at an item: repair list. Do checkbox related actions
18854 ;; only if function was called with an argument. Send list only
18855 ;; if at top item.
18856 (let* ((struct (org-list-struct))
18857 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18858 old-struct)
18859 (when arg
18860 (setq old-struct (copy-tree struct))
18861 (if firstp
18862 ;; If at first item of sub-list, add check-box to every
18863 ;; item at the same level.
18864 (mapc
18865 (lambda (pos)
18866 (unless (org-list-get-checkbox pos struct)
18867 (org-list-set-checkbox pos struct "[ ]")))
18868 (org-list-get-all-items
18869 (point-at-bol) struct (org-list-prevs-alist struct)))
18870 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18871 (org-list-write-struct
18872 struct (org-list-parents-alist struct) old-struct)
18873 (when arg (org-update-checkbox-count-maybe))
18874 (when firstp (org-list-send-list 'maybe))))
18875 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18876 ;; Dynamic block
18877 (beginning-of-line 1)
18878 (save-excursion (org-update-dblock)))
18879 ((save-excursion
18880 (let ((case-fold-search t))
18881 (beginning-of-line 1)
18882 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
18883 (cond
18884 ((or (equal (match-string 1) "TBLFM")
18885 (equal (match-string 1) "tblfm"))
18886 ;; Recalculate the table before this line
18887 (save-excursion
18888 (beginning-of-line 1)
18889 (skip-chars-backward " \r\n\t")
18890 (if (org-at-table-p)
18891 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18893 (let ((org-inhibit-startup-visibility-stuff t)
18894 (org-startup-align-all-tables nil))
18895 (when (boundp 'org-table-coordinate-overlays)
18896 (mapc 'delete-overlay org-table-coordinate-overlays)
18897 (setq org-table-coordinate-overlays nil))
18898 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18899 (message "Local setup has been refreshed"))))
18900 ((org-clock-update-time-maybe))
18902 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18903 (error "C-c C-c can do nothing useful at this location"))))))
18905 (defun org-mode-restart ()
18906 "Restart Org-mode, to scan again for special lines.
18907 Also updates the keyword regular expressions."
18908 (interactive)
18909 (org-mode)
18910 (message "Org-mode restarted"))
18912 (defun org-kill-note-or-show-branches ()
18913 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18914 (interactive)
18915 (if (not org-finish-function)
18916 (progn
18917 (hide-subtree)
18918 (call-interactively 'show-branches))
18919 (let ((org-note-abort t))
18920 (funcall org-finish-function))))
18922 (defun org-return (&optional indent)
18923 "Goto next table row or insert a newline.
18924 Calls `org-table-next-row' or `newline', depending on context.
18925 See the individual commands for more information."
18926 (interactive)
18927 (let (org-ts-what)
18928 (cond
18929 ((or (bobp) (org-in-src-block-p))
18930 (if indent (newline-and-indent) (newline)))
18931 ((org-at-table-p)
18932 (org-table-justify-field-maybe)
18933 (call-interactively 'org-table-next-row))
18934 ;; when `newline-and-indent' is called within a list, make sure
18935 ;; text moved stays inside the item.
18936 ((and (org-in-item-p) indent)
18937 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18938 (progn
18939 (save-match-data (newline))
18940 (org-indent-line-to (length (match-string 0))))
18941 (let ((ind (org-get-indentation)))
18942 (newline)
18943 (if (org-looking-back org-list-end-re)
18944 (org-indent-line-function)
18945 (org-indent-line-to ind)))))
18946 ((and org-return-follows-link
18947 (org-at-timestamp-p t)
18948 (not (eq org-ts-what 'after)))
18949 (org-follow-timestamp-link))
18950 ((and org-return-follows-link
18951 (let ((tprop (get-text-property (point) 'face)))
18952 (or (eq tprop 'org-link)
18953 (and (listp tprop) (memq 'org-link tprop)))))
18954 (call-interactively 'org-open-at-point))
18955 ((and (org-at-heading-p)
18956 (looking-at
18957 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18958 (org-show-entry)
18959 (end-of-line 1)
18960 (newline))
18961 (t (if indent (newline-and-indent) (newline))))))
18963 (defun org-return-indent ()
18964 "Goto next table row or insert a newline and indent.
18965 Calls `org-table-next-row' or `newline-and-indent', depending on
18966 context. See the individual commands for more information."
18967 (interactive)
18968 (org-return t))
18970 (defun org-ctrl-c-star ()
18971 "Compute table, or change heading status of lines.
18972 Calls `org-table-recalculate' or `org-toggle-heading',
18973 depending on context."
18974 (interactive)
18975 (cond
18976 ((org-at-table-p)
18977 (call-interactively 'org-table-recalculate))
18979 ;; Convert all lines in region to list items
18980 (call-interactively 'org-toggle-heading))))
18982 (defun org-ctrl-c-minus ()
18983 "Insert separator line in table or modify bullet status of line.
18984 Also turns a plain line or a region of lines into list items.
18985 Calls `org-table-insert-hline', `org-toggle-item', or
18986 `org-cycle-list-bullet', depending on context."
18987 (interactive)
18988 (cond
18989 ((org-at-table-p)
18990 (call-interactively 'org-table-insert-hline))
18991 ((org-region-active-p)
18992 (call-interactively 'org-toggle-item))
18993 ((org-in-item-p)
18994 (call-interactively 'org-cycle-list-bullet))
18996 (call-interactively 'org-toggle-item))))
18998 (defun org-toggle-item (arg)
18999 "Convert headings or normal lines to items, items to normal lines.
19000 If there is no active region, only the current line is considered.
19002 If the first non blank line in the region is an headline, convert
19003 all headlines to items, shifting text accordingly.
19005 If it is an item, convert all items to normal lines.
19007 If it is normal text, change region into an item. With a prefix
19008 argument ARG, change each line in region into an item."
19009 (interactive "P")
19010 (let ((shift-text
19011 (function
19012 ;; Shift text in current section to IND, from point to END.
19013 ;; The function leaves point to END line.
19014 (lambda (ind end)
19015 (let ((min-i 1000) (end (copy-marker end)))
19016 ;; First determine the minimum indentation (MIN-I) of
19017 ;; the text.
19018 (save-excursion
19019 (catch 'exit
19020 (while (< (point) end)
19021 (let ((i (org-get-indentation)))
19022 (cond
19023 ;; Skip blank lines and inline tasks.
19024 ((looking-at "^[ \t]*$"))
19025 ((looking-at org-outline-regexp-bol))
19026 ;; We can't find less than 0 indentation.
19027 ((zerop i) (throw 'exit (setq min-i 0)))
19028 ((< i min-i) (setq min-i i))))
19029 (forward-line))))
19030 ;; Then indent each line so that a line indented to
19031 ;; MIN-I becomes indented to IND. Ignore blank lines
19032 ;; and inline tasks in the process.
19033 (let ((delta (- ind min-i)))
19034 (while (< (point) end)
19035 (unless (or (looking-at "^[ \t]*$")
19036 (looking-at org-outline-regexp-bol))
19037 (org-indent-line-to (+ (org-get-indentation) delta)))
19038 (forward-line)))))))
19039 (skip-blanks
19040 (function
19041 ;; Return beginning of first non-blank line, starting from
19042 ;; line at POS.
19043 (lambda (pos)
19044 (save-excursion
19045 (goto-char pos)
19046 (skip-chars-forward " \r\t\n")
19047 (point-at-bol)))))
19048 beg end)
19049 ;; Determine boundaries of changes.
19050 (if (org-region-active-p)
19051 (setq beg (funcall skip-blanks (region-beginning))
19052 end (copy-marker (region-end)))
19053 (setq beg (funcall skip-blanks (point-at-bol))
19054 end (copy-marker (point-at-eol))))
19055 ;; Depending on the starting line, choose an action on the text
19056 ;; between BEG and END.
19057 (org-with-limited-levels
19058 (save-excursion
19059 (goto-char beg)
19060 (cond
19061 ;; Case 1. Start at an item: de-itemize. Note that it only
19062 ;; happens when a region is active: `org-ctrl-c-minus'
19063 ;; would call `org-cycle-list-bullet' otherwise.
19064 ((org-at-item-p)
19065 (while (< (point) end)
19066 (when (org-at-item-p)
19067 (skip-chars-forward " \t")
19068 (delete-region (point) (match-end 0)))
19069 (forward-line)))
19070 ;; Case 2. Start at an heading: convert to items.
19071 ((org-at-heading-p)
19072 (let* ((bul (org-list-bullet-string "-"))
19073 (bul-len (length bul))
19074 ;; Indentation of the first heading. It should be
19075 ;; relative to the indentation of its parent, if any.
19076 (start-ind (save-excursion
19077 (cond
19078 ((not org-adapt-indentation) 0)
19079 ((not (outline-previous-heading)) 0)
19080 (t (length (match-string 0))))))
19081 ;; Level of first heading. Further headings will be
19082 ;; compared to it to determine hierarchy in the list.
19083 (ref-level (org-reduced-level (org-outline-level))))
19084 (while (< (point) end)
19085 (let* ((level (org-reduced-level (org-outline-level)))
19086 (delta (max 0 (- level ref-level))))
19087 ;; If current headline is less indented than the first
19088 ;; one, set it as reference, in order to preserve
19089 ;; subtrees.
19090 (when (< level ref-level) (setq ref-level level))
19091 (replace-match bul t t)
19092 (org-indent-line-to (+ start-ind (* delta bul-len)))
19093 ;; Ensure all text down to END (or SECTION-END) belongs
19094 ;; to the newly created item.
19095 (let ((section-end (save-excursion
19096 (or (outline-next-heading) (point)))))
19097 (forward-line)
19098 (funcall shift-text
19099 (+ start-ind (* (1+ delta) bul-len))
19100 (min end section-end)))))))
19101 ;; Case 3. Normal line with ARG: turn each non-item line into
19102 ;; an item.
19103 (arg
19104 (while (< (point) end)
19105 (unless (or (org-at-heading-p) (org-at-item-p))
19106 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19107 (replace-match
19108 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19109 (forward-line)))
19110 ;; Case 4. Normal line without ARG: make the first line of
19111 ;; region an item, and shift indentation of others
19112 ;; lines to set them as item's body.
19113 (t (let* ((bul (org-list-bullet-string "-"))
19114 (bul-len (length bul))
19115 (ref-ind (org-get-indentation)))
19116 (skip-chars-forward " \t")
19117 (insert bul)
19118 (forward-line)
19119 (while (< (point) end)
19120 ;; Ensure that lines less indented than first one
19121 ;; still get included in item body.
19122 (funcall shift-text
19123 (+ ref-ind bul-len)
19124 (min end (save-excursion (or (outline-next-heading)
19125 (point)))))
19126 (forward-line)))))))))
19128 (defun org-toggle-heading (&optional nstars)
19129 "Convert headings to normal text, or items or text to headings.
19130 If there is no active region, only the current line is considered.
19132 With a \\[universal-argument] prefix, convert the whole list at
19133 point into heading.
19135 In a region:
19137 - If the first non blank line is an headline, remove the stars
19138 from all headlines in the region.
19140 - If it is a normal line turn each and every normal line (i.e. not an
19141 heading or an item) in the region into a heading.
19143 - If it is a plain list item, turn all plain list items into headings.
19145 When converting a line into a heading, the number of stars is chosen
19146 such that the lines become children of the current entry. However,
19147 when a prefix argument is given, its value determines the number of
19148 stars to add."
19149 (interactive "P")
19150 (let ((skip-blanks
19151 (function
19152 ;; Return beginning of first non-blank line, starting from
19153 ;; line at POS.
19154 (lambda (pos)
19155 (save-excursion
19156 (goto-char pos)
19157 (while (org-at-comment-p) (forward-line))
19158 (skip-chars-forward " \r\t\n")
19159 (point-at-bol)))))
19160 beg end toggled)
19161 ;; Determine boundaries of changes. If a universal prefix has
19162 ;; been given, put the list in a region. If region ends at a bol,
19163 ;; do not consider the last line to be in the region.
19165 (when (and current-prefix-arg (org-at-item-p))
19166 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19167 (org-mark-list))
19169 (if (org-region-active-p)
19170 (setq beg (funcall skip-blanks (region-beginning))
19171 end (copy-marker (save-excursion
19172 (goto-char (region-end))
19173 (if (bolp) (point) (point-at-eol)))))
19174 (setq beg (funcall skip-blanks (point-at-bol))
19175 end (copy-marker (point-at-eol))))
19176 ;; Ensure inline tasks don't count as headings.
19177 (org-with-limited-levels
19178 (save-excursion
19179 (goto-char beg)
19180 (cond
19181 ;; Case 1. Started at an heading: de-star headings.
19182 ((org-at-heading-p)
19183 (while (< (point) end)
19184 (when (org-at-heading-p t)
19185 (looking-at org-outline-regexp) (replace-match "")
19186 (setq toggled t))
19187 (forward-line)))
19188 ;; Case 2. Started at an item: change items into headlines.
19189 ;; One star will be added by `org-list-to-subtree'.
19190 ((org-at-item-p)
19191 (let* ((stars (make-string
19192 (if nstars
19193 ;; subtract the star that will be added again by
19194 ;; `org-list-to-subtree'
19195 (1- (prefix-numeric-value current-prefix-arg))
19196 (or (org-current-level) 0))
19197 ?*))
19198 (add-stars
19199 (cond (nstars "") ; stars from prefix only
19200 ((equal stars "") "") ; before first heading
19201 (org-odd-levels-only "*") ; inside heading, odd
19202 (t "")))) ; inside heading, oddeven
19203 (while (< (point) end)
19204 (when (org-at-item-p)
19205 ;; Pay attention to cases when region ends before list.
19206 (let* ((struct (org-list-struct))
19207 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19208 (save-restriction
19209 (narrow-to-region (point) list-end)
19210 (insert
19211 (org-list-to-subtree
19212 (org-list-parse-list t)
19213 '(:istart (concat stars add-stars (funcall get-stars depth))
19214 :icount (concat stars add-stars (funcall get-stars depth)))))))
19215 (setq toggled t))
19216 (forward-line))))
19217 ;; Case 3. Started at normal text: make every line an heading,
19218 ;; skipping headlines and items.
19219 (t (let* ((stars (make-string
19220 (if nstars
19221 (prefix-numeric-value current-prefix-arg)
19222 (or (org-current-level) 0))
19223 ?*))
19224 (add-stars
19225 (cond (nstars "") ; stars from prefix only
19226 ((equal stars "") "*") ; before first heading
19227 (org-odd-levels-only "**") ; inside heading, odd
19228 (t "*"))) ; inside heading, oddeven
19229 (rpl (concat stars add-stars " ")))
19230 (while (< (point) end)
19231 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19232 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19233 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19234 (forward-line)))))))
19235 (unless toggled (message "Cannot toggle heading from here"))))
19237 (defun org-meta-return (&optional arg)
19238 "Insert a new heading or wrap a region in a table.
19239 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19240 See the individual commands for more information."
19241 (interactive "P")
19242 (cond
19243 ((run-hook-with-args-until-success 'org-metareturn-hook))
19244 ((or (org-at-drawer-p) (org-at-property-p))
19245 (newline-and-indent))
19246 ((org-at-table-p)
19247 (call-interactively 'org-table-wrap-region))
19248 (t (call-interactively 'org-insert-heading))))
19250 ;;; Menu entries
19252 ;; Define the Org-mode menus
19253 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19254 '("Tbl"
19255 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19256 ["Next Field" org-cycle (org-at-table-p)]
19257 ["Previous Field" org-shifttab (org-at-table-p)]
19258 ["Next Row" org-return (org-at-table-p)]
19259 "--"
19260 ["Blank Field" org-table-blank-field (org-at-table-p)]
19261 ["Edit Field" org-table-edit-field (org-at-table-p)]
19262 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19263 "--"
19264 ("Column"
19265 ["Move Column Left" org-metaleft (org-at-table-p)]
19266 ["Move Column Right" org-metaright (org-at-table-p)]
19267 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19268 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19269 ("Row"
19270 ["Move Row Up" org-metaup (org-at-table-p)]
19271 ["Move Row Down" org-metadown (org-at-table-p)]
19272 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19273 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19274 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19275 "--"
19276 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19277 ("Rectangle"
19278 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19279 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19280 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19281 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19282 "--"
19283 ("Calculate"
19284 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19285 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19286 ["Edit Formulas" org-edit-special (org-at-table-p)]
19287 "--"
19288 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19289 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19290 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19291 "--"
19292 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19293 "--"
19294 ["Sum Column/Rectangle" org-table-sum
19295 (or (org-at-table-p) (org-region-active-p))]
19296 ["Which Column?" org-table-current-column (org-at-table-p)])
19297 ["Debug Formulas"
19298 org-table-toggle-formula-debugger
19299 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19300 ["Show Col/Row Numbers"
19301 org-table-toggle-coordinate-overlays
19302 :style toggle
19303 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19304 "--"
19305 ["Create" org-table-create (and (not (org-at-table-p))
19306 org-enable-table-editor)]
19307 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19308 ["Import from File" org-table-import (not (org-at-table-p))]
19309 ["Export to File" org-table-export (org-at-table-p)]
19310 "--"
19311 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19313 (easy-menu-define org-org-menu org-mode-map "Org menu"
19314 '("Org"
19315 ("Show/Hide"
19316 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19317 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19318 ["Sparse Tree..." org-sparse-tree t]
19319 ["Reveal Context" org-reveal t]
19320 ["Show All" show-all t]
19321 "--"
19322 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19323 "--"
19324 ["New Heading" org-insert-heading t]
19325 ("Navigate Headings"
19326 ["Up" outline-up-heading t]
19327 ["Next" outline-next-visible-heading t]
19328 ["Previous" outline-previous-visible-heading t]
19329 ["Next Same Level" outline-forward-same-level t]
19330 ["Previous Same Level" outline-backward-same-level t]
19331 "--"
19332 ["Jump" org-goto t])
19333 ("Edit Structure"
19334 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19335 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19336 "--"
19337 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19338 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19339 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19340 "--"
19341 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19342 "--"
19343 ["Copy visible text" org-copy-visible t]
19344 "--"
19345 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19346 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19347 ["Demote Heading" org-metaright (not (org-at-table-p))]
19348 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19349 "--"
19350 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19351 "--"
19352 ["Convert to odd levels" org-convert-to-odd-levels t]
19353 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19354 ("Editing"
19355 ["Emphasis..." org-emphasize t]
19356 ["Edit Source Example" org-edit-special t]
19357 "--"
19358 ["Footnote new/jump" org-footnote-action t]
19359 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19360 ("Archive"
19361 ["Archive (default method)" org-archive-subtree-default t]
19362 "--"
19363 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19364 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19365 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19367 "--"
19368 ("Hyperlinks"
19369 ["Store Link (Global)" org-store-link t]
19370 ["Find existing link to here" org-occur-link-in-agenda-files t]
19371 ["Insert Link" org-insert-link t]
19372 ["Follow Link" org-open-at-point t]
19373 "--"
19374 ["Next link" org-next-link t]
19375 ["Previous link" org-previous-link t]
19376 "--"
19377 ["Descriptive Links"
19378 org-toggle-link-display
19379 :style radio
19380 :selected org-descriptive-links
19382 ["Literal Links"
19383 org-toggle-link-display
19384 :style radio
19385 :selected (not org-descriptive-links)])
19386 "--"
19387 ("TODO Lists"
19388 ["TODO/DONE/-" org-todo t]
19389 ("Select keyword"
19390 ["Next keyword" org-shiftright (org-at-heading-p)]
19391 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19392 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19393 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19394 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19395 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19396 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19397 "--"
19398 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19399 :selected org-enforce-todo-dependencies :style toggle :active t]
19400 "Settings for tree at point"
19401 ["Do Children sequentially" org-toggle-ordered-property :style radio
19402 :selected (org-entry-get nil "ORDERED")
19403 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19404 ["Do Children parallel" org-toggle-ordered-property :style radio
19405 :selected (not (org-entry-get nil "ORDERED"))
19406 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19407 "--"
19408 ["Set Priority" org-priority t]
19409 ["Priority Up" org-shiftup t]
19410 ["Priority Down" org-shiftdown t]
19411 "--"
19412 ["Get news from all feeds" org-feed-update-all t]
19413 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19414 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19415 ("TAGS and Properties"
19416 ["Set Tags" org-set-tags-command t]
19417 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19418 "--"
19419 ["Set property" org-set-property t]
19420 ["Column view of properties" org-columns t]
19421 ["Insert Column View DBlock" org-insert-columns-dblock t])
19422 ("Dates and Scheduling"
19423 ["Timestamp" org-time-stamp t]
19424 ["Timestamp (inactive)" org-time-stamp-inactive t]
19425 ("Change Date"
19426 ["1 Day Later" org-shiftright t]
19427 ["1 Day Earlier" org-shiftleft t]
19428 ["1 ... Later" org-shiftup t]
19429 ["1 ... Earlier" org-shiftdown t])
19430 ["Compute Time Range" org-evaluate-time-range t]
19431 ["Schedule Item" org-schedule t]
19432 ["Deadline" org-deadline t]
19433 "--"
19434 ["Custom time format" org-toggle-time-stamp-overlays
19435 :style radio :selected org-display-custom-times]
19436 "--"
19437 ["Goto Calendar" org-goto-calendar t]
19438 ["Date from Calendar" org-date-from-calendar t]
19439 "--"
19440 ["Start/Restart Timer" org-timer-start t]
19441 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19442 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19443 ["Insert Timer String" org-timer t]
19444 ["Insert Timer Item" org-timer-item t])
19445 ("Logging work"
19446 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19447 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19448 ["Clock out" org-clock-out t]
19449 ["Clock cancel" org-clock-cancel t]
19450 "--"
19451 ["Mark as default task" org-clock-mark-default-task t]
19452 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19453 ["Goto running clock" org-clock-goto t]
19454 "--"
19455 ["Display times" org-clock-display t]
19456 ["Create clock table" org-clock-report t]
19457 "--"
19458 ["Record DONE time"
19459 (progn (setq org-log-done (not org-log-done))
19460 (message "Switching to %s will %s record a timestamp"
19461 (car org-done-keywords)
19462 (if org-log-done "automatically" "not")))
19463 :style toggle :selected org-log-done])
19464 "--"
19465 ["Agenda Command..." org-agenda t]
19466 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19467 ("File List for Agenda")
19468 ("Special views current file"
19469 ["TODO Tree" org-show-todo-tree t]
19470 ["Check Deadlines" org-check-deadlines t]
19471 ["Timeline" org-timeline t]
19472 ["Tags/Property tree" org-match-sparse-tree t])
19473 "--"
19474 ["Export/Publish..." org-export t]
19475 ("LaTeX"
19476 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19477 :selected org-cdlatex-mode]
19478 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19479 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19480 ["Modify math symbol" org-cdlatex-math-modify
19481 (org-inside-LaTeX-fragment-p)]
19482 ["Insert citation" org-reftex-citation t]
19483 "--"
19484 ["Template for BEAMER" (progn (require 'org-beamer)
19485 (org-insert-beamer-options-template)) t])
19486 "--"
19487 ("MobileOrg"
19488 ["Push Files and Views" org-mobile-push t]
19489 ["Get Captured and Flagged" org-mobile-pull t]
19490 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19491 "--"
19492 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19493 "--"
19494 ("Documentation"
19495 ["Show Version" org-version t]
19496 ["Info Documentation" org-info t])
19497 ("Customize"
19498 ["Browse Org Group" org-customize t]
19499 "--"
19500 ["Expand This Menu" org-create-customize-menu
19501 (fboundp 'customize-menu-create)])
19502 ["Send bug report" org-submit-bug-report t]
19503 "--"
19504 ("Refresh/Reload"
19505 ["Refresh setup current buffer" org-mode-restart t]
19506 ["Reload Org (after update)" org-reload t]
19507 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19510 (defun org-info (&optional node)
19511 "Read documentation for Org-mode in the info system.
19512 With optional NODE, go directly to that node."
19513 (interactive)
19514 (info (format "(org)%s" (or node ""))))
19516 ;;;###autoload
19517 (defun org-submit-bug-report ()
19518 "Submit a bug report on Org-mode via mail.
19520 Don't hesitate to report any problems or inaccurate documentation.
19522 If you don't have setup sending mail from (X)Emacs, please copy the
19523 output buffer into your mail program, as it gives us important
19524 information about your Org-mode version and configuration."
19525 (interactive)
19526 (require 'reporter)
19527 (org-load-modules-maybe)
19528 (org-require-autoloaded-modules)
19529 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19530 (reporter-submit-bug-report
19531 "emacs-orgmode@gnu.org"
19532 (org-version nil 'full)
19533 (let (list)
19534 (save-window-excursion
19535 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19536 (delete-other-windows)
19537 (erase-buffer)
19538 (insert "You are about to submit a bug report to the Org-mode mailing list.
19540 We would like to add your full Org-mode and Outline configuration to the
19541 bug report. This greatly simplifies the work of the maintainer and
19542 other experts on the mailing list.
19544 HOWEVER, some variables you have customized may contain private
19545 information. The names of customers, colleagues, or friends, might
19546 appear in the form of file names, tags, todo states, or search strings.
19547 If you answer yes to the prompt, you might want to check and remove
19548 such private information before sending the email.")
19549 (add-text-properties (point-min) (point-max) '(face org-warning))
19550 (when (yes-or-no-p "Include your Org-mode configuration ")
19551 (mapatoms
19552 (lambda (v)
19553 (and (boundp v)
19554 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19555 (or (and (symbol-value v)
19556 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19557 (and
19558 (get v 'custom-type) (get v 'standard-value)
19559 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19560 (push v list)))))
19561 (kill-buffer (get-buffer "*Warn about privacy*"))
19562 list))
19563 nil nil
19564 "Remember to cover the basics, that is, what you expected to happen and
19565 what in fact did happen. You don't know how to make a good report? See
19567 http://orgmode.org/manual/Feedback.html#Feedback
19569 Your bug report will be posted to the Org-mode mailing list.
19570 ------------------------------------------------------------------------")
19571 (save-excursion
19572 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19573 (replace-match "\\1Bug: \\3 [\\2]")))))
19576 (defun org-install-agenda-files-menu ()
19577 (let ((bl (buffer-list)))
19578 (save-excursion
19579 (while bl
19580 (set-buffer (pop bl))
19581 (if (derived-mode-p 'org-mode) (setq bl nil)))
19582 (when (derived-mode-p 'org-mode)
19583 (easy-menu-change
19584 '("Org") "File List for Agenda"
19585 (append
19586 (list
19587 ["Edit File List" (org-edit-agenda-file-list) t]
19588 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19589 ["Remove Current File from List" org-remove-file t]
19590 ["Cycle through agenda files" org-cycle-agenda-files t]
19591 ["Occur in all agenda files" org-occur-in-agenda-files t]
19592 "--")
19593 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19595 ;;;; Documentation
19597 ;;;###autoload
19598 (defun org-require-autoloaded-modules ()
19599 (interactive)
19600 (mapc 'require
19601 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19602 org-docbook org-exp org-html org-icalendar
19603 org-id org-latex
19604 org-publish org-remember org-table
19605 org-timer org-xoxo)))
19607 ;;;###autoload
19608 (defun org-reload (&optional uncompiled)
19609 "Reload all org lisp files.
19610 With prefix arg UNCOMPILED, load the uncompiled versions."
19611 (interactive "P")
19612 (require 'find-func)
19613 (let* ((file-re "^org\\(-.*\\)?\\.el")
19614 (dir-org (file-name-directory (org-find-library-dir "org")))
19615 (dir-org-contrib (ignore-errors
19616 (file-name-directory
19617 (org-find-library-dir "org-contribdir"))))
19618 (babel-files
19619 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19620 (append (list nil "comint" "eval" "exp" "keys"
19621 "lob" "ref" "table" "tangle")
19622 (delq nil
19623 (mapcar
19624 (lambda (lang)
19625 (when (cdr lang) (symbol-name (car lang))))
19626 org-babel-load-languages)))))
19627 (files
19628 (append babel-files
19629 (and dir-org-contrib
19630 (directory-files dir-org-contrib t file-re))
19631 (directory-files dir-org t file-re)))
19632 (remove-re (concat (if (featurep 'xemacs)
19633 "org-colview" "org-colview-xemacs")
19634 "\\'")))
19635 (setq files (mapcar 'file-name-sans-extension files))
19636 (setq files (mapcar
19637 (lambda (x) (if (string-match remove-re x) nil x))
19638 files))
19639 (setq files (delq nil files))
19640 (mapc
19641 (lambda (f)
19642 (when (featurep (intern (file-name-nondirectory f)))
19643 (if (and (not uncompiled)
19644 (file-exists-p (concat f ".elc")))
19645 (load (concat f ".elc") nil nil 'nosuffix)
19646 (load (concat f ".el") nil nil 'nosuffix))))
19647 files)
19648 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19649 (org-version nil 'full 'message))
19651 ;;;###autoload
19652 (defun org-customize ()
19653 "Call the customize function with org as argument."
19654 (interactive)
19655 (org-load-modules-maybe)
19656 (org-require-autoloaded-modules)
19657 (customize-browse 'org))
19659 (defun org-create-customize-menu ()
19660 "Create a full customization menu for Org-mode, insert it into the menu."
19661 (interactive)
19662 (org-load-modules-maybe)
19663 (org-require-autoloaded-modules)
19664 (if (fboundp 'customize-menu-create)
19665 (progn
19666 (easy-menu-change
19667 '("Org") "Customize"
19668 `(["Browse Org group" org-customize t]
19669 "--"
19670 ,(customize-menu-create 'org)
19671 ["Set" Custom-set t]
19672 ["Save" Custom-save t]
19673 ["Reset to Current" Custom-reset-current t]
19674 ["Reset to Saved" Custom-reset-saved t]
19675 ["Reset to Standard Settings" Custom-reset-standard t]))
19676 (message "\"Org\"-menu now contains full customization menu"))
19677 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19679 ;;;; Miscellaneous stuff
19681 ;;; Generally useful functions
19683 (defun org-get-at-bol (property)
19684 "Get text property PROPERTY at beginning of line."
19685 (get-text-property (point-at-bol) property))
19687 (defun org-find-text-property-in-string (prop s)
19688 "Return the first non-nil value of property PROP in string S."
19689 (or (get-text-property 0 prop s)
19690 (get-text-property (or (next-single-property-change 0 prop s) 0)
19691 prop s)))
19693 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19694 "Display the given MESSAGE as a warning."
19695 (if (fboundp 'display-warning)
19696 (display-warning 'org message
19697 (if (featurep 'xemacs) 'warning :warning))
19698 (let ((buf (get-buffer-create "*Org warnings*")))
19699 (with-current-buffer buf
19700 (goto-char (point-max))
19701 (insert "Warning (Org): " message)
19702 (unless (bolp)
19703 (newline)))
19704 (display-buffer buf)
19705 (sit-for 0))))
19707 (defun org-eval (form)
19708 "Eval FORM and return result."
19709 (condition-case error
19710 (eval form)
19711 (error (format "%%![Error: %s]" error))))
19713 (defun org-in-clocktable-p ()
19714 "Check if the cursor is in a clocktable."
19715 (let ((pos (point)) start)
19716 (save-excursion
19717 (end-of-line 1)
19718 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19719 (setq start (match-beginning 0))
19720 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19721 (>= (match-end 0) pos)
19722 start))))
19724 (defun org-in-commented-line ()
19725 "Is point in a line starting with `#'?"
19726 (equal (char-after (point-at-bol)) ?#))
19728 (defun org-in-indented-comment-line ()
19729 "Is point in a line starting with `#' after some white space?"
19730 (save-excursion
19731 (save-match-data
19732 (goto-char (point-at-bol))
19733 (looking-at "[ \t]*#"))))
19735 (defun org-in-verbatim-emphasis ()
19736 (save-match-data
19737 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19739 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19740 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19741 (if (and marker (marker-buffer marker)
19742 (buffer-live-p (marker-buffer marker)))
19743 (progn
19744 (org-pop-to-buffer-same-window (marker-buffer marker))
19745 (if (or (> marker (point-max)) (< marker (point-min)))
19746 (widen))
19747 (goto-char marker)
19748 (org-show-context 'org-goto))
19749 (if bookmark
19750 (bookmark-jump bookmark)
19751 (error "Cannot find location"))))
19753 (defun org-quote-csv-field (s)
19754 "Quote field for inclusion in CSV material."
19755 (if (string-match "[\",]" s)
19756 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19759 (defun org-force-self-insert (N)
19760 "Needed to enforce self-insert under remapping."
19761 (interactive "p")
19762 (self-insert-command N))
19764 (defun org-string-width (s)
19765 "Compute width of string, ignoring invisible characters.
19766 This ignores character with invisibility property `org-link', and also
19767 characters with property `org-cwidth', because these will become invisible
19768 upon the next fontification round."
19769 (let (b l)
19770 (when (or (eq t buffer-invisibility-spec)
19771 (assq 'org-link buffer-invisibility-spec))
19772 (while (setq b (text-property-any 0 (length s)
19773 'invisible 'org-link s))
19774 (setq s (concat (substring s 0 b)
19775 (substring s (or (next-single-property-change
19776 b 'invisible s) (length s)))))))
19777 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19778 (setq s (concat (substring s 0 b)
19779 (substring s (or (next-single-property-change
19780 b 'org-cwidth s) (length s))))))
19781 (setq l (string-width s) b -1)
19782 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19783 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19786 (defun org-shorten-string (s maxlength)
19787 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19788 If the string is shorter or has length MAXLENGTH, just return the
19789 original string. If it is longer, the functions finds a space in the
19790 string, breaks this string off at that locations and adds three dots
19791 as ellipsis. Including the ellipsis, the string will not be longer
19792 than MAXLENGTH. If finding a good breaking point in the string does
19793 not work, the string is just chopped off in the middle of a word
19794 if necessary."
19795 (if (<= (length s) maxlength)
19797 (let* ((n (max (- maxlength 4) 1))
19798 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19799 (if (string-match re s)
19800 (concat (match-string 1 s) "...")
19801 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19803 (defun org-get-indentation (&optional line)
19804 "Get the indentation of the current line, interpreting tabs.
19805 When LINE is given, assume it represents a line and compute its indentation."
19806 (if line
19807 (if (string-match "^ *" (org-remove-tabs line))
19808 (match-end 0))
19809 (save-excursion
19810 (beginning-of-line 1)
19811 (skip-chars-forward " \t")
19812 (current-column))))
19814 (defun org-get-string-indentation (s)
19815 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19816 (let ((n -1) (i 0) (w tab-width) c)
19817 (catch 'exit
19818 (while (< (setq n (1+ n)) (length s))
19819 (setq c (aref s n))
19820 (cond ((= c ?\ ) (setq i (1+ i)))
19821 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19822 (t (throw 'exit t)))))
19825 (defun org-remove-tabs (s &optional width)
19826 "Replace tabulators in S with spaces.
19827 Assumes that s is a single line, starting in column 0."
19828 (setq width (or width tab-width))
19829 (while (string-match "\t" s)
19830 (setq s (replace-match
19831 (make-string
19832 (- (* width (/ (+ (match-beginning 0) width) width))
19833 (match-beginning 0)) ?\ )
19834 t t s)))
19837 (defun org-fix-indentation (line ind)
19838 "Fix indentation in LINE.
19839 IND is a cons cell with target and minimum indentation.
19840 If the current indentation in LINE is smaller than the minimum,
19841 leave it alone. If it is larger than ind, set it to the target."
19842 (let* ((l (org-remove-tabs line))
19843 (i (org-get-indentation l))
19844 (i1 (car ind)) (i2 (cdr ind)))
19845 (if (>= i i2) (setq l (substring line i2)))
19846 (if (> i1 0)
19847 (concat (make-string i1 ?\ ) l)
19848 l)))
19850 (defun org-remove-indentation (code &optional n)
19851 "Remove the maximum common indentation from the lines in CODE.
19852 N may optionally be the number of spaces to remove."
19853 (with-temp-buffer
19854 (insert code)
19855 (org-do-remove-indentation n)
19856 (buffer-string)))
19858 (defun org-do-remove-indentation (&optional n)
19859 "Remove the maximum common indentation from the buffer."
19860 (untabify (point-min) (point-max))
19861 (let ((min 10000) re)
19862 (if n
19863 (setq min n)
19864 (goto-char (point-min))
19865 (while (re-search-forward "^ *[^ \n]" nil t)
19866 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19867 (unless (or (= min 0) (= min 10000))
19868 (setq re (format "^ \\{%d\\}" min))
19869 (goto-char (point-min))
19870 (while (re-search-forward re nil t)
19871 (replace-match "")
19872 (end-of-line 1))
19873 min)))
19875 (defun org-fill-template (template alist)
19876 "Find each %key of ALIST in TEMPLATE and replace it."
19877 (let ((case-fold-search nil)
19878 entry key value)
19879 (setq alist (sort (copy-sequence alist)
19880 (lambda (a b) (< (length (car a)) (length (car b))))))
19881 (while (setq entry (pop alist))
19882 (setq template
19883 (replace-regexp-in-string
19884 (concat "%" (regexp-quote (car entry)))
19885 (cdr entry) template t t)))
19886 template))
19888 (defun org-base-buffer (buffer)
19889 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19890 (if (not buffer)
19891 buffer
19892 (or (buffer-base-buffer buffer)
19893 buffer)))
19895 (defun org-trim (s)
19896 "Remove whitespace at beginning and end of string."
19897 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19898 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19901 (defun org-wrap (string &optional width lines)
19902 "Wrap string to either a number of lines, or a width in characters.
19903 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19904 that costs. If there is a word longer than WIDTH, the text is actually
19905 wrapped to the length of that word.
19906 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19907 many lines, whatever width that takes.
19908 The return value is a list of lines, without newlines at the end."
19909 (let* ((words (org-split-string string "[ \t\n]+"))
19910 (maxword (apply 'max (mapcar 'org-string-width words)))
19911 w ll)
19912 (cond (width
19913 (org-do-wrap words (max maxword width)))
19914 (lines
19915 (setq w maxword)
19916 (setq ll (org-do-wrap words maxword))
19917 (if (<= (length ll) lines)
19919 (setq ll words)
19920 (while (> (length ll) lines)
19921 (setq w (1+ w))
19922 (setq ll (org-do-wrap words w)))
19923 ll))
19924 (t (error "Cannot wrap this")))))
19926 (defun org-do-wrap (words width)
19927 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19928 (let (lines line)
19929 (while words
19930 (setq line (pop words))
19931 (while (and words (< (+ (length line) (length (car words))) width))
19932 (setq line (concat line " " (pop words))))
19933 (setq lines (push line lines)))
19934 (nreverse lines)))
19936 (defun org-split-string (string &optional separators)
19937 "Splits STRING into substrings at SEPARATORS.
19938 No empty strings are returned if there are matches at the beginning
19939 and end of string."
19940 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19941 (start 0)
19942 notfirst
19943 (list nil))
19944 (while (and (string-match rexp string
19945 (if (and notfirst
19946 (= start (match-beginning 0))
19947 (< start (length string)))
19948 (1+ start) start))
19949 (< (match-beginning 0) (length string)))
19950 (setq notfirst t)
19951 (or (eq (match-beginning 0) 0)
19952 (and (eq (match-beginning 0) (match-end 0))
19953 (eq (match-beginning 0) start))
19954 (setq list
19955 (cons (substring string start (match-beginning 0))
19956 list)))
19957 (setq start (match-end 0)))
19958 (or (eq start (length string))
19959 (setq list
19960 (cons (substring string start)
19961 list)))
19962 (nreverse list)))
19964 (defun org-quote-vert (s)
19965 "Replace \"|\" with \"\\vert\"."
19966 (while (string-match "|" s)
19967 (setq s (replace-match "\\vert" t t s)))
19970 (defun org-uuidgen-p (s)
19971 "Is S an ID created by UUIDGEN?"
19972 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19974 (defun org-in-src-block-p nil
19975 "Whether point is in a code source block."
19976 (let (ov)
19977 (when (setq ov (overlays-at (point)))
19978 (memq 'org-block-background
19979 (overlay-properties
19980 (car ov))))))
19982 (defun org-context ()
19983 "Return a list of contexts of the current cursor position.
19984 If several contexts apply, all are returned.
19985 Each context entry is a list with a symbol naming the context, and
19986 two positions indicating start and end of the context. Possible
19987 contexts are:
19989 :headline anywhere in a headline
19990 :headline-stars on the leading stars in a headline
19991 :todo-keyword on a TODO keyword (including DONE) in a headline
19992 :tags on the TAGS in a headline
19993 :priority on the priority cookie in a headline
19994 :item on the first line of a plain list item
19995 :item-bullet on the bullet/number of a plain list item
19996 :checkbox on the checkbox in a plain list item
19997 :table in an org-mode table
19998 :table-special on a special filed in a table
19999 :table-table in a table.el table
20000 :clocktable in a clocktable
20001 :src-block in a source block
20002 :link on a hyperlink
20003 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20004 :target on a <<target>>
20005 :radio-target on a <<<radio-target>>>
20006 :latex-fragment on a LaTeX fragment
20007 :latex-preview on a LaTeX fragment with overlaid preview image
20009 This function expects the position to be visible because it uses font-lock
20010 faces as a help to recognize the following contexts: :table-special, :link,
20011 and :keyword."
20012 (let* ((f (get-text-property (point) 'face))
20013 (faces (if (listp f) f (list f)))
20014 (case-fold-search t)
20015 (p (point)) clist o)
20016 ;; First the large context
20017 (cond
20018 ((org-at-heading-p t)
20019 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20020 (when (progn
20021 (beginning-of-line 1)
20022 (looking-at org-todo-line-tags-regexp))
20023 (push (org-point-in-group p 1 :headline-stars) clist)
20024 (push (org-point-in-group p 2 :todo-keyword) clist)
20025 (push (org-point-in-group p 4 :tags) clist))
20026 (goto-char p)
20027 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20028 (if (looking-at "\\[#[A-Z0-9]\\]")
20029 (push (org-point-in-group p 0 :priority) clist)))
20031 ((org-at-item-p)
20032 (push (org-point-in-group p 2 :item-bullet) clist)
20033 (push (list :item (point-at-bol)
20034 (save-excursion (org-end-of-item) (point)))
20035 clist)
20036 (and (org-at-item-checkbox-p)
20037 (push (org-point-in-group p 0 :checkbox) clist)))
20039 ((org-at-table-p)
20040 (push (list :table (org-table-begin) (org-table-end)) clist)
20041 (if (memq 'org-formula faces)
20042 (push (list :table-special
20043 (previous-single-property-change p 'face)
20044 (next-single-property-change p 'face)) clist)))
20045 ((org-at-table-p 'any)
20046 (push (list :table-table) clist)))
20047 (goto-char p)
20049 ;; New the "medium" contexts: clocktables, source blocks
20050 (cond ((org-in-clocktable-p)
20051 (push (list :clocktable
20052 (and (or (looking-at "#\\+BEGIN: clocktable")
20053 (search-backward "#+BEGIN: clocktable" nil t))
20054 (match-beginning 0))
20055 (and (re-search-forward "#\\+END:?" nil t)
20056 (match-end 0))) clist))
20057 ((org-in-src-block-p)
20058 (push (list :src-block
20059 (and (or (looking-at "#\\+BEGIN_SRC")
20060 (search-backward "#+BEGIN_SRC" nil t))
20061 (match-beginning 0))
20062 (and (search-forward "#+END_SRC" nil t)
20063 (match-beginning 0))) clist)))
20064 (goto-char p)
20066 ;; Now the small context
20067 (cond
20068 ((org-at-timestamp-p)
20069 (push (org-point-in-group p 0 :timestamp) clist))
20070 ((memq 'org-link faces)
20071 (push (list :link
20072 (previous-single-property-change p 'face)
20073 (next-single-property-change p 'face)) clist))
20074 ((memq 'org-special-keyword faces)
20075 (push (list :keyword
20076 (previous-single-property-change p 'face)
20077 (next-single-property-change p 'face)) clist))
20078 ((org-at-target-p)
20079 (push (org-point-in-group p 0 :target) clist)
20080 (goto-char (1- (match-beginning 0)))
20081 (if (looking-at org-radio-target-regexp)
20082 (push (org-point-in-group p 0 :radio-target) clist))
20083 (goto-char p))
20084 ((setq o (car (delq nil
20085 (mapcar
20086 (lambda (x)
20087 (if (memq x org-latex-fragment-image-overlays) x))
20088 (overlays-at (point))))))
20089 (push (list :latex-fragment
20090 (overlay-start o) (overlay-end o)) clist)
20091 (push (list :latex-preview
20092 (overlay-start o) (overlay-end o)) clist))
20093 ((org-inside-LaTeX-fragment-p)
20094 ;; FIXME: positions wrong.
20095 (push (list :latex-fragment (point) (point)) clist)))
20097 (setq clist (nreverse (delq nil clist)))
20098 clist))
20100 ;; FIXME: Compare with at-regexp-p Do we need both?
20101 (defun org-in-regexp (re &optional nlines visually)
20102 "Check if point is inside a match of regexp.
20103 Normally only the current line is checked, but you can include NLINES extra
20104 lines both before and after point into the search.
20105 If VISUALLY is set, require that the cursor is not after the match but
20106 really on, so that the block visually is on the match."
20107 (catch 'exit
20108 (let ((pos (point))
20109 (eol (point-at-eol (+ 1 (or nlines 0))))
20110 (inc (if visually 1 0)))
20111 (save-excursion
20112 (beginning-of-line (- 1 (or nlines 0)))
20113 (while (re-search-forward re eol t)
20114 (if (and (<= (match-beginning 0) pos)
20115 (>= (+ inc (match-end 0)) pos))
20116 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20118 (defun org-at-regexp-p (regexp)
20119 "Is point inside a match of REGEXP in the current line?"
20120 (catch 'exit
20121 (save-excursion
20122 (let ((pos (point)) (end (point-at-eol)))
20123 (beginning-of-line 1)
20124 (while (re-search-forward regexp end t)
20125 (if (and (<= (match-beginning 0) pos)
20126 (>= (match-end 0) pos))
20127 (throw 'exit t)))
20128 nil))))
20130 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20131 "Non-nil when point is between matches of START-RE and END-RE.
20133 Also return a non-nil value when point is on one of the matches.
20135 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20136 buffer positions. Default values are the positions of headlines
20137 surrounding the point.
20139 The functions returns a cons cell whose car (resp. cdr) is the
20140 position before START-RE (resp. after END-RE)."
20141 (save-match-data
20142 (let ((pos (point))
20143 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20144 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20145 beg end)
20146 (save-excursion
20147 ;; Point is on a block when on START-RE or if START-RE can be
20148 ;; found before it...
20149 (and (or (org-at-regexp-p start-re)
20150 (re-search-backward start-re limit-up t))
20151 (setq beg (match-beginning 0))
20152 ;; ... and END-RE after it...
20153 (goto-char (match-end 0))
20154 (re-search-forward end-re limit-down t)
20155 (> (setq end (match-end 0)) pos)
20156 ;; ... without another START-RE in-between.
20157 (goto-char (match-beginning 0))
20158 (not (re-search-backward start-re (1+ beg) t))
20159 ;; Return value.
20160 (cons beg end))))))
20162 (defun org-in-block-p (names)
20163 "Non-nil when point belongs to a block whose name belongs to NAMES.
20165 NAMES is a list of strings containing names of blocks.
20167 Return first block name matched, or nil. Beware that in case of
20168 nested blocks, the returned name may not belong to the closest
20169 block from point."
20170 (save-match-data
20171 (catch 'exit
20172 (let ((case-fold-search t)
20173 (lim-up (save-excursion (outline-previous-heading)))
20174 (lim-down (save-excursion (outline-next-heading))))
20175 (mapc (lambda (name)
20176 (let ((n (regexp-quote name)))
20177 (when (org-between-regexps-p
20178 (concat "^[ \t]*#\\+begin_" n)
20179 (concat "^[ \t]*#\\+end_" n)
20180 lim-up lim-down)
20181 (throw 'exit n))))
20182 names))
20183 nil)))
20185 (defun org-occur-in-agenda-files (regexp &optional nlines)
20186 "Call `multi-occur' with buffers for all agenda files."
20187 (interactive "sOrg-files matching: \np")
20188 (let* ((files (org-agenda-files))
20189 (tnames (mapcar 'file-truename files))
20190 (extra org-agenda-text-search-extra-files)
20192 (when (eq (car extra) 'agenda-archives)
20193 (setq extra (cdr extra))
20194 (setq files (org-add-archive-files files)))
20195 (while (setq f (pop extra))
20196 (unless (member (file-truename f) tnames)
20197 (add-to-list 'files f 'append)
20198 (add-to-list 'tnames (file-truename f) 'append)))
20199 (multi-occur
20200 (mapcar (lambda (x)
20201 (with-current-buffer
20202 (or (get-file-buffer x) (find-file-noselect x))
20203 (widen)
20204 (current-buffer)))
20205 files)
20206 regexp)))
20208 (if (boundp 'occur-mode-find-occurrence-hook)
20209 ;; Emacs 23
20210 (add-hook 'occur-mode-find-occurrence-hook
20211 (lambda ()
20212 (when (derived-mode-p 'org-mode)
20213 (org-reveal))))
20214 ;; Emacs 22
20215 (defadvice occur-mode-goto-occurrence
20216 (after org-occur-reveal activate)
20217 (and (derived-mode-p 'org-mode) (org-reveal)))
20218 (defadvice occur-mode-goto-occurrence-other-window
20219 (after org-occur-reveal activate)
20220 (and (derived-mode-p 'org-mode) (org-reveal)))
20221 (defadvice occur-mode-display-occurrence
20222 (after org-occur-reveal activate)
20223 (when (derived-mode-p 'org-mode)
20224 (let ((pos (occur-mode-find-occurrence)))
20225 (with-current-buffer (marker-buffer pos)
20226 (save-excursion
20227 (goto-char pos)
20228 (org-reveal)))))))
20230 (defun org-occur-link-in-agenda-files ()
20231 "Create a link and search for it in the agendas.
20232 The link is not stored in `org-stored-links', it is just created
20233 for the search purpose."
20234 (interactive)
20235 (let ((link (condition-case nil
20236 (org-store-link nil)
20237 (error "Unable to create a link to here"))))
20238 (org-occur-in-agenda-files (regexp-quote link))))
20240 (defun org-uniquify (list)
20241 "Remove duplicate elements from LIST."
20242 (let (res)
20243 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20244 res))
20246 (defun org-delete-all (elts list)
20247 "Remove all elements in ELTS from LIST."
20248 (while elts
20249 (setq list (delete (pop elts) list)))
20250 list)
20252 (defun org-count (cl-item cl-seq)
20253 "Count the number of occurrences of ITEM in SEQ.
20254 Taken from `count' in cl-seq.el with all keyword arguments removed."
20255 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20256 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20257 (while (< cl-start cl-end)
20258 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20259 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20260 (setq cl-start (1+ cl-start)))
20261 cl-count))
20263 (defun org-remove-if (predicate seq)
20264 "Remove everything from SEQ that fulfills PREDICATE."
20265 (let (res e)
20266 (while seq
20267 (setq e (pop seq))
20268 (if (not (funcall predicate e)) (push e res)))
20269 (nreverse res)))
20271 (defun org-remove-if-not (predicate seq)
20272 "Remove everything from SEQ that does not fulfill PREDICATE."
20273 (let (res e)
20274 (while seq
20275 (setq e (pop seq))
20276 (if (funcall predicate e) (push e res)))
20277 (nreverse res)))
20279 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20280 "Reduce two-argument FUNCTION across SEQ.
20281 Taken from `reduce' in cl-seq.el with all keyword arguments but
20282 \":initial-value\" removed."
20283 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20284 (cadr (memq :initial-value cl-keys)))
20285 (cl-seq (pop cl-seq))
20286 (t (funcall cl-func)))))
20287 (while cl-seq
20288 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20289 cl-accum))
20291 (defun org-back-over-empty-lines ()
20292 "Move backwards over whitespace, to the beginning of the first empty line.
20293 Returns the number of empty lines passed."
20294 (let ((pos (point)))
20295 (if (cdr (assoc 'heading org-blank-before-new-entry))
20296 (skip-chars-backward " \t\n\r")
20297 (unless (eobp)
20298 (forward-line -1)))
20299 (beginning-of-line 2)
20300 (goto-char (min (point) pos))
20301 (count-lines (point) pos)))
20303 (defun org-skip-whitespace ()
20304 (skip-chars-forward " \t\n\r"))
20306 (defun org-point-in-group (point group &optional context)
20307 "Check if POINT is in match-group GROUP.
20308 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20309 match. If the match group does not exist or point is not inside it,
20310 return nil."
20311 (and (match-beginning group)
20312 (>= point (match-beginning group))
20313 (<= point (match-end group))
20314 (if context
20315 (list context (match-beginning group) (match-end group))
20316 t)))
20318 (defun org-switch-to-buffer-other-window (&rest args)
20319 "Switch to buffer in a second window on the current frame.
20320 In particular, do not allow pop-up frames.
20321 Returns the newly created buffer."
20322 (let (pop-up-frames special-display-buffer-names special-display-regexps
20323 special-display-function)
20324 (apply 'switch-to-buffer-other-window args)))
20326 (defun org-combine-plists (&rest plists)
20327 "Create a single property list from all plists in PLISTS.
20328 The process starts by copying the first list, and then setting properties
20329 from the other lists. Settings in the last list are the most significant
20330 ones and overrule settings in the other lists."
20331 (let ((rtn (copy-sequence (pop plists)))
20332 p v ls)
20333 (while plists
20334 (setq ls (pop plists))
20335 (while ls
20336 (setq p (pop ls) v (pop ls))
20337 (setq rtn (plist-put rtn p v))))
20338 rtn))
20340 (defun org-move-line-down (arg)
20341 "Move the current line down. With prefix argument, move it past ARG lines."
20342 (interactive "p")
20343 (let ((col (current-column))
20344 beg end pos)
20345 (beginning-of-line 1) (setq beg (point))
20346 (beginning-of-line 2) (setq end (point))
20347 (beginning-of-line (+ 1 arg))
20348 (setq pos (move-marker (make-marker) (point)))
20349 (insert (delete-and-extract-region beg end))
20350 (goto-char pos)
20351 (org-move-to-column col)))
20353 (defun org-move-line-up (arg)
20354 "Move the current line up. With prefix argument, move it past ARG lines."
20355 (interactive "p")
20356 (let ((col (current-column))
20357 beg end pos)
20358 (beginning-of-line 1) (setq beg (point))
20359 (beginning-of-line 2) (setq end (point))
20360 (beginning-of-line (- arg))
20361 (setq pos (move-marker (make-marker) (point)))
20362 (insert (delete-and-extract-region beg end))
20363 (goto-char pos)
20364 (org-move-to-column col)))
20366 (defun org-replace-escapes (string table)
20367 "Replace %-escapes in STRING with values in TABLE.
20368 TABLE is an association list with keys like \"%a\" and string values.
20369 The sequences in STRING may contain normal field width and padding information,
20370 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20371 so values can contain further %-escapes if they are define later in TABLE."
20372 (let ((tbl (copy-alist table))
20373 (case-fold-search nil)
20374 (pchg 0)
20375 e re rpl)
20376 (while (setq e (pop tbl))
20377 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20378 (when (and (cdr e) (string-match re (cdr e)))
20379 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20380 (safe "SREF"))
20381 (add-text-properties 0 3 (list 'sref sref) safe)
20382 (setcdr e (replace-match safe t t (cdr e)))))
20383 (while (string-match re string)
20384 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20385 (cdr e)))
20386 (setq string (replace-match rpl t t string))))
20387 (while (setq pchg (next-property-change pchg string))
20388 (let ((sref (get-text-property pchg 'sref string)))
20389 (when (and sref (string-match "SREF" string pchg))
20390 (setq string (replace-match sref t t string)))))
20391 string))
20393 (defun org-sublist (list start end)
20394 "Return a section of LIST, from START to END.
20395 Counting starts at 1."
20396 (let (rtn (c start))
20397 (setq list (nthcdr (1- start) list))
20398 (while (and list (<= c end))
20399 (push (pop list) rtn)
20400 (setq c (1+ c)))
20401 (nreverse rtn)))
20403 (defun org-find-base-buffer-visiting (file)
20404 "Like `find-buffer-visiting' but always return the base buffer and
20405 not an indirect buffer."
20406 (let ((buf (or (get-file-buffer file)
20407 (find-buffer-visiting file))))
20408 (if buf
20409 (or (buffer-base-buffer buf) buf)
20410 nil)))
20412 (defun org-image-file-name-regexp (&optional extensions)
20413 "Return regexp matching the file names of images.
20414 If EXTENSIONS is given, only match these."
20415 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20416 (image-file-name-regexp)
20417 (let ((image-file-name-extensions
20418 (or extensions
20419 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20420 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20421 (concat "\\."
20422 (regexp-opt (nconc (mapcar 'upcase
20423 image-file-name-extensions)
20424 image-file-name-extensions)
20426 "\\'"))))
20428 (defun org-file-image-p (file &optional extensions)
20429 "Return non-nil if FILE is an image."
20430 (save-match-data
20431 (string-match (org-image-file-name-regexp extensions) file)))
20433 (defun org-get-cursor-date ()
20434 "Return the date at cursor in as a time.
20435 This works in the calendar and in the agenda, anywhere else it just
20436 returns the current time."
20437 (let (date day defd)
20438 (cond
20439 ((eq major-mode 'calendar-mode)
20440 (setq date (calendar-cursor-to-date)
20441 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20442 ((eq major-mode 'org-agenda-mode)
20443 (setq day (get-text-property (point) 'day))
20444 (if day
20445 (setq date (calendar-gregorian-from-absolute day)
20446 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20447 (nth 2 date))))))
20448 (or defd (current-time))))
20450 (defvar org-agenda-action-marker (make-marker)
20451 "Marker pointing to the entry for the next agenda action.")
20453 (defun org-mark-entry-for-agenda-action ()
20454 "Mark the current entry as target of an agenda action.
20455 Agenda actions are actions executed from the agenda with the key `k',
20456 which make use of the date at the cursor."
20457 (interactive)
20458 (move-marker org-agenda-action-marker
20459 (save-excursion (org-back-to-heading t) (point))
20460 (current-buffer))
20461 (message
20462 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20464 (defun org-mark-subtree ()
20465 "Mark the current subtree.
20466 This puts point at the start of the current subtree, and mark at the end.
20468 If point is in an inline task, mark that task instead."
20469 (interactive)
20470 (let ((inline-task-p
20471 (and (featurep 'org-inlinetask)
20472 (org-inlinetask-in-task-p)))
20473 (beg))
20474 ;; Get beginning of subtree
20475 (cond
20476 (inline-task-p (org-inlinetask-goto-beginning))
20477 ((org-at-heading-p) (beginning-of-line))
20478 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20479 (setq beg (point))
20480 ;; Get end of it
20481 (if inline-task-p
20482 (org-inlinetask-goto-end)
20483 (org-end-of-subtree))
20484 ;; Mark zone
20485 (push-mark (point) nil t)
20486 (goto-char beg)))
20488 ;;; Paragraph filling stuff.
20489 ;; We want this to be just right, so use the full arsenal.
20491 (defun org-indent-line-function ()
20492 "Indent line depending on context."
20493 (interactive)
20494 (let* ((pos (point))
20495 (itemp (org-at-item-p))
20496 (case-fold-search t)
20497 (org-drawer-regexp (or org-drawer-regexp "\000"))
20498 (inline-task-p (and (featurep 'org-inlinetask)
20499 (org-inlinetask-in-task-p)))
20500 (inline-re (and inline-task-p
20501 (org-inlinetask-outline-regexp)))
20502 column)
20503 (beginning-of-line 1)
20504 (cond
20505 ;; Comments
20506 ((looking-at "# ") (setq column 0))
20507 ;; Headings
20508 ((looking-at org-outline-regexp) (setq column 0))
20509 ;; Included files
20510 ((looking-at "#\\+include:") (setq column 0))
20511 ;; Footnote definition
20512 ((looking-at org-footnote-definition-re) (setq column 0))
20513 ;; Literal examples
20514 ((looking-at "[ \t]*:\\( \\|$\\)")
20515 (setq column (org-get-indentation))) ; do nothing
20516 ;; Lists
20517 ((ignore-errors (goto-char (org-in-item-p)))
20518 (setq column (if itemp
20519 (org-get-indentation)
20520 (org-list-item-body-column (point))))
20521 (goto-char pos))
20522 ;; Drawers
20523 ((and (looking-at "[ \t]*:END:")
20524 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20525 (save-excursion
20526 (goto-char (1- (match-beginning 1)))
20527 (setq column (current-column))))
20528 ;; Special blocks
20529 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20530 (save-excursion
20531 (re-search-backward
20532 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20533 (setq column (org-get-indentation (match-string 0))))
20534 ((and (not (looking-at "[ \t]*#\\+begin_"))
20535 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20536 (save-excursion
20537 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20538 (setq column
20539 (cond ((equal (downcase (match-string 1)) "src")
20540 ;; src blocks: let `org-edit-src-exit' handle them
20541 (org-get-indentation))
20542 ((equal (downcase (match-string 1)) "example")
20543 (max (org-get-indentation)
20544 (org-get-indentation (match-string 0))))
20546 (org-get-indentation (match-string 0))))))
20547 ;; This line has nothing special, look at the previous relevant
20548 ;; line to compute indentation
20550 (beginning-of-line 0)
20551 (while (and (not (bobp))
20552 (not (looking-at org-drawer-regexp))
20553 ;; When point started in an inline task, do not move
20554 ;; above task starting line.
20555 (not (and inline-task-p (looking-at inline-re)))
20556 ;; Skip drawers, blocks, empty lines, verbatim,
20557 ;; comments, tables, footnotes definitions, lists,
20558 ;; inline tasks.
20559 (or (and (looking-at "[ \t]*:END:")
20560 (re-search-backward org-drawer-regexp nil t))
20561 (and (looking-at "[ \t]*#\\+end_")
20562 (re-search-backward "[ \t]*#\\+begin_"nil t))
20563 (looking-at "[ \t]*[\n:#|]")
20564 (looking-at org-footnote-definition-re)
20565 (and (ignore-errors (goto-char (org-in-item-p)))
20566 (goto-char
20567 (org-list-get-top-point (org-list-struct))))
20568 (and (not inline-task-p)
20569 (featurep 'org-inlinetask)
20570 (org-inlinetask-in-task-p)
20571 (or (org-inlinetask-goto-beginning) t))))
20572 (beginning-of-line 0))
20573 (cond
20574 ;; There was an heading above.
20575 ((looking-at "\\*+[ \t]+")
20576 (if (not org-adapt-indentation)
20577 (setq column 0)
20578 (goto-char (match-end 0))
20579 (setq column (current-column))))
20580 ;; A drawer had started and is unfinished
20581 ((looking-at org-drawer-regexp)
20582 (goto-char (1- (match-beginning 1)))
20583 (setq column (current-column)))
20584 ;; Else, nothing noticeable found: get indentation and go on.
20585 (t (setq column (org-get-indentation))))))
20586 ;; Now apply indentation and move cursor accordingly
20587 (goto-char pos)
20588 (if (<= (current-column) (current-indentation))
20589 (org-indent-line-to column)
20590 (save-excursion (org-indent-line-to column)))
20591 ;; Special polishing for properties, see `org-property-format'
20592 (setq column (current-column))
20593 (beginning-of-line 1)
20594 (if (looking-at
20595 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20596 (replace-match (concat (match-string 1)
20597 (format org-property-format
20598 (match-string 2) (match-string 3)))
20599 t t))
20600 (org-move-to-column column)
20601 (when (and orgstruct-is-++ (eq pos (point)))
20602 (org-let org-fb-vars
20603 '(indent-according-to-mode)))))
20605 (defun org-indent-drawer ()
20606 "Indent the drawer at point."
20607 (interactive)
20608 (let ((p (point))
20609 (e (and (save-excursion (re-search-forward ":END:" nil t))
20610 (match-end 0)))
20611 (folded
20612 (save-excursion
20613 (end-of-line)
20614 (when (overlays-at (point))
20615 (member 'invisible (overlay-properties
20616 (car (overlays-at (point)))))))))
20617 (when folded (org-cycle))
20618 (indent-for-tab-command)
20619 (while (and (move-beginning-of-line 2) (< (point) e))
20620 (indent-for-tab-command))
20621 (goto-char p)
20622 (when folded (org-cycle)))
20623 (message "Drawer at point indented"))
20625 (defun org-indent-block ()
20626 "Indent the block at point."
20627 (interactive)
20628 (let ((p (point))
20629 (case-fold-search t)
20630 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20631 (match-end 0)))
20632 (folded
20633 (save-excursion
20634 (end-of-line)
20635 (when (overlays-at (point))
20636 (member 'invisible (overlay-properties
20637 (car (overlays-at (point)))))))))
20638 (when folded (org-cycle))
20639 (indent-for-tab-command)
20640 (while (and (move-beginning-of-line 2) (< (point) e))
20641 (indent-for-tab-command))
20642 (goto-char p)
20643 (when folded (org-cycle)))
20644 (message "Block at point indented"))
20646 ;; For reference, this is the default value of adaptive-fill-regexp
20647 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20648 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20649 "Variable to store copy of `adaptive-fill-regexp'.
20650 Since `adaptive-fill-regexp' is set to never match, we need to
20651 store a backup of its value before entering `org-mode' so that
20652 the functionality can be provided as a fall-back.")
20654 (defun org-set-autofill-regexps ()
20655 (interactive)
20656 ;; In the paragraph separator we include headlines, because filling
20657 ;; text in a line directly attached to a headline would otherwise
20658 ;; fill the headline as well.
20659 (org-set-local 'comment-start-skip "^#+[ \t]*")
20660 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20661 ;; The paragraph starter includes hand-formatted lists.
20662 (org-set-local
20663 'paragraph-start
20664 (concat
20665 "\f" "\\|"
20666 "[ ]*$" "\\|"
20667 org-outline-regexp "\\|"
20668 "[ \t]*#" "\\|"
20669 (org-item-re) "\\|"
20670 "[ \t]*[:|]" "\\|"
20671 "\\$\\$" "\\|"
20672 "\\\\\\(begin\\|end\\|[][]\\)"))
20673 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20674 ;; But only if the user has not turned off tables or fixed-width regions
20675 (org-set-local
20676 'auto-fill-inhibit-regexp
20677 (concat org-outline-regexp
20678 "\\|#\\+"
20679 "\\|[ \t]*" org-keyword-time-regexp
20680 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20681 (concat
20682 "\\|[ \t]*["
20683 (if org-enable-table-editor "|" "")
20684 (if org-enable-fixed-width-editor ":" "")
20685 "]"))))
20686 ;; We use our own fill-paragraph function, to make sure that tables
20687 ;; and fixed-width regions are not wrapped. That function will pass
20688 ;; through to `fill-paragraph' when appropriate.
20689 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20690 ;; Prevent auto-fill from inserting unwanted new items.
20691 (if (boundp 'fill-nobreak-predicate)
20692 (org-set-local
20693 'fill-nobreak-predicate
20694 (org-uniquify
20695 (append fill-nobreak-predicate
20696 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20697 ;; Adaptive filling: To get full control, first make sure that
20698 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20699 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20700 (org-set-local 'org-adaptive-fill-regexp-backup
20701 adaptive-fill-regexp))
20702 (org-set-local 'adaptive-fill-regexp "\000")
20703 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20704 (org-set-local 'adaptive-fill-function
20705 'org-adaptive-fill-function)
20706 (org-set-local
20707 'align-mode-rules-list
20708 '((org-in-buffer-settings
20709 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20710 (modes . '(org-mode))))))
20712 (defun org-fill-item-nobreak-p ()
20713 "Non-nil when a line break at point would insert a new item."
20714 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20716 (defun org-fill-line-break-nobreak-p ()
20717 "Non-nil when a line break at point would create an Org line break."
20718 (save-excursion
20719 (skip-chars-backward "[ \t]")
20720 (skip-chars-backward "\\\\")
20721 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20723 (defun org-fill-paragraph (&optional justify)
20724 "Re-align a table, pass through to fill-paragraph if no table."
20725 (let ((table-p (org-at-table-p))
20726 (table.el-p (org-at-table.el-p))
20727 (itemp (org-in-item-p)))
20728 (cond ((and (equal (char-after (point-at-bol)) ?*)
20729 (save-excursion (goto-char (point-at-bol))
20730 (looking-at org-outline-regexp)))
20731 t) ; skip headlines
20732 (table.el-p t) ; skip table.el tables
20733 (table-p (org-table-align) t) ; align Org tables
20734 (itemp ; align text in items
20735 (let* ((struct (save-excursion (goto-char itemp)
20736 (org-list-struct)))
20737 (parents (org-list-parents-alist struct))
20738 (children (org-list-get-children itemp struct parents))
20739 beg end prev next prefix)
20740 ;; Determine in which part of item point is: before
20741 ;; first child, after last child, between two
20742 ;; sub-lists, or simply in item if there's no child.
20743 (cond
20744 ((not children)
20745 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20746 beg itemp
20747 end (org-list-get-item-end itemp struct)))
20748 ((< (point) (setq next (car children)))
20749 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20750 beg itemp
20751 end next))
20752 ((> (point) (setq prev (car (last children))))
20753 (setq beg (org-list-get-item-end prev struct)
20754 end (org-list-get-item-end itemp struct)
20755 prefix (save-excursion
20756 (goto-char beg)
20757 (skip-chars-forward " \t")
20758 (make-string (current-column) ?\ ))))
20759 (t (catch 'exit
20760 (while (setq next (pop children))
20761 (if (> (point) next)
20762 (setq prev next)
20763 (setq beg (org-list-get-item-end prev struct)
20764 end next
20765 prefix (save-excursion
20766 (goto-char beg)
20767 (skip-chars-forward " \t")
20768 (make-string (current-column) ?\ )))
20769 (throw 'exit nil))))))
20770 ;; Use `fill-paragraph' with buffer narrowed to item
20771 ;; without any child, and with our computed PREFIX.
20772 (flet ((fill-context-prefix (from to &optional flr) prefix))
20773 (save-restriction
20774 (narrow-to-region beg end)
20775 (save-excursion (fill-paragraph justify)))) t))
20776 ;; Special case where point is not in a list but is on
20777 ;; a paragraph adjacent to a list: make sure this paragraph
20778 ;; doesn't get merged with the end of the list by narrowing
20779 ;; buffer first.
20780 ((and (derived-mode-p 'org-mode)
20781 (save-excursion (forward-paragraph -1)
20782 (setq itemp (org-in-item-p))))
20783 (let ((struct (save-excursion (goto-char itemp)
20784 (org-list-struct))))
20785 (save-restriction
20786 (narrow-to-region (org-list-get-bottom-point struct)
20787 (save-excursion (forward-paragraph 1)
20788 (point)))
20789 (fill-paragraph justify) t)))
20790 ;; Don't fill schedule/deadline line before a paragraph
20791 ;; This only makes sense in real org-mode buffers
20792 ((and (eq major-mode 'org-mode)
20793 (save-excursion (forward-paragraph -1)
20794 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20795 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$")))))
20796 (save-restriction
20797 (narrow-to-region (1+ (match-end 0))
20798 (save-excursion (forward-paragraph 1) (point)))
20799 (fill-paragraph justify) t))
20800 ;; Else fall back on fill-paragraph-function as possibly
20801 ;; defined in `org-fb-vars'
20802 (orgstruct-is-++
20803 (org-let org-fb-vars
20804 '(fill-paragraph justify)))
20805 (t nil))))
20807 (defun org-adaptive-fill-function ()
20808 "Return a fill prefix for org-mode files."
20809 (let (itemp)
20810 (save-excursion
20811 (cond
20812 ;; Comment line
20813 ((looking-at "#[ \t]+")
20814 (match-string-no-properties 0))
20815 ;; Plain list item
20816 ((org-at-item-p)
20817 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20818 ;; Point is in a list after `backward-paragraph': original
20819 ;; point wasn't in the list, or filling would have been taken
20820 ;; care of by `org-auto-fill-function', but the list and the
20821 ;; real paragraph are not separated by a blank line. Thus, move
20822 ;; point after the list to go back to real paragraph and
20823 ;; determine fill-prefix.
20824 ((setq itemp (org-in-item-p))
20825 (goto-char itemp)
20826 (let* ((struct (org-list-struct))
20827 (bottom (org-list-get-bottom-point struct)))
20828 (goto-char bottom)
20829 (make-string (org-get-indentation) ?\ )))
20830 ;; Other text
20831 ((looking-at org-adaptive-fill-regexp-backup)
20832 (match-string-no-properties 0))))))
20834 (defun org-auto-fill-function ()
20835 "Auto-fill function."
20836 (unless (and org-src-prevent-auto-filling (org-in-src-block-p))
20837 (let (itemp prefix)
20838 ;; When in a list, compute an appropriate fill-prefix and make
20839 ;; sure it will be used by `do-auto-fill'.
20840 (cond ((setq itemp (org-in-item-p))
20841 (progn
20842 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20843 (flet ((fill-context-prefix (from to &optional flr) prefix))
20844 (do-auto-fill))))
20845 (orgstruct-is-++
20846 (org-let org-fb-vars
20847 '(do-auto-fill)))
20848 (t (do-auto-fill))))))
20850 ;;; Other stuff.
20852 (defun org-toggle-fixed-width-section (arg)
20853 "Toggle the fixed-width export.
20854 If there is no active region, the QUOTE keyword at the current headline is
20855 inserted or removed. When present, it causes the text between this headline
20856 and the next to be exported as fixed-width text, and unmodified.
20857 If there is an active region, this command adds or removes a colon as the
20858 first character of this line. If the first character of a line is a colon,
20859 this line is also exported in fixed-width font."
20860 (interactive "P")
20861 (let* ((cc 0)
20862 (regionp (org-region-active-p))
20863 (beg (if regionp (region-beginning) (point)))
20864 (end (if regionp (region-end)))
20865 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20866 (case-fold-search nil)
20867 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20868 off)
20869 (if regionp
20870 (save-excursion
20871 (goto-char beg)
20872 (setq cc (current-column))
20873 (beginning-of-line 1)
20874 (setq off (looking-at re))
20875 (while (> nlines 0)
20876 (setq nlines (1- nlines))
20877 (beginning-of-line 1)
20878 (cond
20879 (arg
20880 (org-move-to-column cc t)
20881 (insert ": \n")
20882 (forward-line -1))
20883 ((and off (looking-at re))
20884 (replace-match "" t t nil 1))
20885 ((not off) (org-move-to-column cc t) (insert ": ")))
20886 (forward-line 1)))
20887 (save-excursion
20888 (org-back-to-heading)
20889 (cond
20890 ((looking-at (format org-heading-keyword-regexp-format
20891 org-quote-string))
20892 (goto-char (match-end 1))
20893 (looking-at (concat " +" org-quote-string))
20894 (replace-match "" t t)
20895 (when (eolp) (insert " ")))
20896 ((looking-at org-outline-regexp)
20897 (goto-char (match-end 0))
20898 (insert org-quote-string " ")))))))
20900 (defun org-reftex-citation ()
20901 "Use reftex-citation to insert a citation into the buffer.
20902 This looks for a line like
20904 #+BIBLIOGRAPHY: foo plain option:-d
20906 and derives from it that foo.bib is the bibliography file relevant
20907 for this document. It then installs the necessary environment for RefTeX
20908 to work in this buffer and calls `reftex-citation' to insert a citation
20909 into the buffer.
20911 Export of such citations to both LaTeX and HTML is handled by the contributed
20912 package org-exp-bibtex by Taru Karttunen."
20913 (interactive)
20914 (let ((reftex-docstruct-symbol 'rds)
20915 (reftex-cite-format "\\cite{%l}")
20916 rds bib)
20917 (save-excursion
20918 (save-restriction
20919 (widen)
20920 (let ((case-fold-search t)
20921 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20922 (if (not (save-excursion
20923 (or (re-search-forward re nil t)
20924 (re-search-backward re nil t))))
20925 (error "No bibliography defined in file")
20926 (setq bib (concat (match-string 1) ".bib")
20927 rds (list (list 'bib bib)))))))
20928 (call-interactively 'reftex-citation)))
20930 ;;;; Functions extending outline functionality
20932 (defun org-beginning-of-line (&optional arg)
20933 "Go to the beginning of the current line. If that is invisible, continue
20934 to a visible line beginning. This makes the function of C-a more intuitive.
20935 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20936 first attempt, and only move to after the tags when the cursor is already
20937 beyond the end of the headline."
20938 (interactive "P")
20939 (let ((pos (point))
20940 (special (if (consp org-special-ctrl-a/e)
20941 (car org-special-ctrl-a/e)
20942 org-special-ctrl-a/e))
20943 refpos)
20944 (if (org-bound-and-true-p line-move-visual)
20945 (beginning-of-visual-line 1)
20946 (beginning-of-line 1))
20947 (if (and arg (fboundp 'move-beginning-of-line))
20948 (call-interactively 'move-beginning-of-line)
20949 (if (bobp)
20951 (backward-char 1)
20952 (if (org-truely-invisible-p)
20953 (while (and (not (bobp)) (org-truely-invisible-p))
20954 (backward-char 1)
20955 (beginning-of-line 1))
20956 (forward-char 1))))
20957 (when special
20958 (cond
20959 ((and (looking-at org-complex-heading-regexp)
20960 (= (char-after (match-end 1)) ?\ ))
20961 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20962 (point-at-eol)))
20963 (goto-char
20964 (if (eq special t)
20965 (cond ((> pos refpos) refpos)
20966 ((= pos (point)) refpos)
20967 (t (point)))
20968 (cond ((> pos (point)) (point))
20969 ((not (eq last-command this-command)) (point))
20970 (t refpos)))))
20971 ((org-at-item-p)
20972 ;; Being at an item and not looking at an the item means point
20973 ;; was previously moved to beginning of a visual line, which
20974 ;; doesn't contain the item. Therefore, do nothing special,
20975 ;; just stay here.
20976 (when (looking-at org-list-full-item-re)
20977 ;; Set special position at first white space character after
20978 ;; bullet, and check-box, if any.
20979 (let ((after-bullet
20980 (let ((box (match-end 3)))
20981 (if (not box) (match-end 1)
20982 (let ((after (char-after box)))
20983 (if (and after (= after ? )) (1+ box) box))))))
20984 ;; Special case: Move point to special position when
20985 ;; currently after it or at beginning of line.
20986 (if (eq special t)
20987 (when (or (> pos after-bullet) (= (point) pos))
20988 (goto-char after-bullet))
20989 ;; Reversed case: Move point to special position when
20990 ;; point was already at beginning of line and command is
20991 ;; repeated.
20992 (when (and (= (point) pos) (eq last-command this-command))
20993 (goto-char after-bullet))))))))
20994 (org-no-warnings
20995 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20997 (defun org-end-of-line (&optional arg)
20998 "Go to the end of the line.
20999 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21000 first attempt, and only move to after the tags when the cursor is already
21001 beyond the end of the headline."
21002 (interactive "P")
21003 (let ((special (if (consp org-special-ctrl-a/e)
21004 (cdr org-special-ctrl-a/e)
21005 org-special-ctrl-a/e)))
21006 (cond
21007 ((or (not special) arg
21008 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21009 (call-interactively
21010 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21011 ((fboundp 'move-end-of-line) 'move-end-of-line)
21012 (t 'end-of-line))))
21013 ((org-at-heading-p)
21014 (let ((pos (point)))
21015 (beginning-of-line 1)
21016 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21017 (if (eq special t)
21018 (if (or (< pos (match-beginning 1))
21019 (= pos (match-end 0)))
21020 (goto-char (match-beginning 1))
21021 (goto-char (match-end 0)))
21022 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21023 (goto-char (match-end 0))
21024 (goto-char (match-beginning 1))))
21025 (call-interactively (if (fboundp 'move-end-of-line)
21026 'move-end-of-line
21027 'end-of-line)))))
21028 ((org-at-drawer-p)
21029 (move-end-of-line 1)
21030 (when (overlays-at (1- (point))) (backward-char 1)))
21031 ;; At an item: Move before any hidden text.
21032 (t (call-interactively
21033 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21034 ((fboundp 'move-end-of-line) 'move-end-of-line)
21035 (t 'end-of-line)))))
21036 (org-no-warnings
21037 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21039 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21040 (define-key org-mode-map "\C-e" 'org-end-of-line)
21042 (defun org-backward-sentence (&optional arg)
21043 "Go to beginning of sentence, or beginning of table field.
21044 This will call `backward-sentence' or `org-table-beginning-of-field',
21045 depending on context."
21046 (interactive "P")
21047 (cond
21048 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21049 (t (call-interactively 'backward-sentence))))
21051 (defun org-forward-sentence (&optional arg)
21052 "Go to end of sentence, or end of table field.
21053 This will call `forward-sentence' or `org-table-end-of-field',
21054 depending on context."
21055 (interactive "P")
21056 (cond
21057 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21058 (t (call-interactively 'forward-sentence))))
21060 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21061 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21063 (defun org-kill-line (&optional arg)
21064 "Kill line, to tags or end of line."
21065 (interactive "P")
21066 (cond
21067 ((or (not org-special-ctrl-k)
21068 (bolp)
21069 (not (org-at-heading-p)))
21070 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21071 org-ctrl-k-protect-subtree)
21072 (if (or (eq org-ctrl-k-protect-subtree 'error)
21073 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21074 (error "C-k aborted - would kill hidden subtree")))
21075 (call-interactively
21076 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21077 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21078 (kill-region (point) (match-beginning 1))
21079 (org-set-tags nil t))
21080 (t (kill-region (point) (point-at-eol)))))
21082 (define-key org-mode-map "\C-k" 'org-kill-line)
21084 (defun org-yank (&optional arg)
21085 "Yank. If the kill is a subtree, treat it specially.
21086 This command will look at the current kill and check if is a single
21087 subtree, or a series of subtrees[1]. If it passes the test, and if the
21088 cursor is at the beginning of a line or after the stars of a currently
21089 empty headline, then the yank is handled specially. How exactly depends
21090 on the value of the following variables, both set by default.
21092 org-yank-folded-subtrees
21093 When set, the subtree(s) will be folded after insertion, but only
21094 if doing so would now swallow text after the yanked text.
21096 org-yank-adjusted-subtrees
21097 When set, the subtree will be promoted or demoted in order to
21098 fit into the local outline tree structure, which means that the level
21099 will be adjusted so that it becomes the smaller one of the two
21100 *visible* surrounding headings.
21102 Any prefix to this command will cause `yank' to be called directly with
21103 no special treatment. In particular, a simple \\[universal-argument] prefix \
21104 will just
21105 plainly yank the text as it is.
21107 \[1] The test checks if the first non-white line is a heading
21108 and if there are no other headings with fewer stars."
21109 (interactive "P")
21110 (org-yank-generic 'yank arg))
21112 (defun org-yank-generic (command arg)
21113 "Perform some yank-like command.
21115 This function implements the behavior described in the `org-yank'
21116 documentation. However, it has been generalized to work for any
21117 interactive command with similar behavior."
21119 ;; pretend to be command COMMAND
21120 (setq this-command command)
21122 (if arg
21123 (call-interactively command)
21125 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21126 (and (org-kill-is-subtree-p)
21127 (or (bolp)
21128 (and (looking-at "[ \t]*$")
21129 (string-match
21130 "\\`\\*+\\'"
21131 (buffer-substring (point-at-bol) (point)))))))
21132 swallowp)
21133 (cond
21134 ((and subtreep org-yank-folded-subtrees)
21135 (let ((beg (point))
21136 end)
21137 (if (and subtreep org-yank-adjusted-subtrees)
21138 (org-paste-subtree nil nil 'for-yank)
21139 (call-interactively command))
21141 (setq end (point))
21142 (goto-char beg)
21143 (when (and (bolp) subtreep
21144 (not (setq swallowp
21145 (org-yank-folding-would-swallow-text beg end))))
21146 (org-with-limited-levels
21147 (or (looking-at org-outline-regexp)
21148 (re-search-forward org-outline-regexp-bol end t))
21149 (while (and (< (point) end) (looking-at org-outline-regexp))
21150 (hide-subtree)
21151 (org-cycle-show-empty-lines 'folded)
21152 (condition-case nil
21153 (outline-forward-same-level 1)
21154 (error (goto-char end))))))
21155 (when swallowp
21156 (message
21157 "Inserted text not folded because that would swallow text"))
21159 (goto-char end)
21160 (skip-chars-forward " \t\n\r")
21161 (beginning-of-line 1)
21162 (push-mark beg 'nomsg)))
21163 ((and subtreep org-yank-adjusted-subtrees)
21164 (let ((beg (point-at-bol)))
21165 (org-paste-subtree nil nil 'for-yank)
21166 (push-mark beg 'nomsg)))
21168 (call-interactively command))))))
21170 (defun org-yank-folding-would-swallow-text (beg end)
21171 "Would hide-subtree at BEG swallow any text after END?"
21172 (let (level)
21173 (org-with-limited-levels
21174 (save-excursion
21175 (goto-char beg)
21176 (when (or (looking-at org-outline-regexp)
21177 (re-search-forward org-outline-regexp-bol end t))
21178 (setq level (org-outline-level)))
21179 (goto-char end)
21180 (skip-chars-forward " \t\r\n\v\f")
21181 (if (or (eobp)
21182 (and (bolp) (looking-at org-outline-regexp)
21183 (<= (org-outline-level) level)))
21184 nil ; Nothing would be swallowed
21185 t))))) ; something would swallow
21187 (define-key org-mode-map "\C-y" 'org-yank)
21189 (defun org-truely-invisible-p ()
21190 "Check if point is at a character currently not visible.
21191 This version does not only check the character property, but also
21192 `visible-mode'."
21193 ;; Early versions of noutline don't have `outline-invisible-p'.
21194 (if (org-bound-and-true-p visible-mode)
21196 (outline-invisible-p)))
21198 (defun org-invisible-p2 ()
21199 "Check if point is at a character currently not visible."
21200 (save-excursion
21201 (if (and (eolp) (not (bobp))) (backward-char 1))
21202 ;; Early versions of noutline don't have `outline-invisible-p'.
21203 (outline-invisible-p)))
21205 (defun org-back-to-heading (&optional invisible-ok)
21206 "Call `outline-back-to-heading', but provide a better error message."
21207 (condition-case nil
21208 (outline-back-to-heading invisible-ok)
21209 (error (error "Before first headline at position %d in buffer %s"
21210 (point) (current-buffer)))))
21212 (defun org-beginning-of-defun ()
21213 "Go to the beginning of the subtree, i.e. back to the heading."
21214 (org-back-to-heading))
21215 (defun org-end-of-defun ()
21216 "Go to the end of the subtree."
21217 (org-end-of-subtree nil t))
21219 (defun org-before-first-heading-p ()
21220 "Before first heading?"
21221 (save-excursion
21222 (end-of-line)
21223 (null (re-search-backward org-outline-regexp-bol nil t))))
21225 (defun org-at-heading-p (&optional ignored)
21226 (outline-on-heading-p t))
21227 ;; Compatibility alias with Org versions < 7.8.03
21228 (defalias 'org-on-heading-p 'org-at-heading-p)
21230 (defun org-at-comment-p nil
21231 "Is cursor in a line starting with a # character?"
21232 (save-excursion
21233 (beginning-of-line)
21234 (looking-at "^#")))
21236 (defun org-at-drawer-p nil
21237 "Is cursor at a drawer keyword?"
21238 (save-excursion
21239 (move-beginning-of-line 1)
21240 (looking-at org-drawer-regexp)))
21242 (defun org-at-block-p nil
21243 "Is cursor at a block keyword?"
21244 (save-excursion
21245 (move-beginning-of-line 1)
21246 (looking-at org-block-regexp)))
21248 (defun org-point-at-end-of-empty-headline ()
21249 "If point is at the end of an empty headline, return t, else nil.
21250 If the heading only contains a TODO keyword, it is still still considered
21251 empty."
21252 (and (looking-at "[ \t]*$")
21253 (when org-todo-line-regexp
21254 (save-excursion
21255 (beginning-of-line 1)
21256 (let ((case-fold-search nil))
21257 (looking-at org-todo-line-regexp)
21258 (string= (match-string 3) ""))))))
21260 (defun org-at-heading-or-item-p ()
21261 (or (org-at-heading-p) (org-at-item-p)))
21263 (defun org-at-target-p ()
21264 (or (org-in-regexp org-radio-target-regexp)
21265 (org-in-regexp org-target-regexp)))
21266 ;; Compatibility alias with Org versions < 7.8.03
21267 (defalias 'org-on-target-p 'org-at-target-p)
21269 (defun org-up-heading-all (arg)
21270 "Move to the heading line of which the present line is a subheading.
21271 This function considers both visible and invisible heading lines.
21272 With argument, move up ARG levels."
21273 (if (fboundp 'outline-up-heading-all)
21274 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21275 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21277 (defun org-up-heading-safe ()
21278 "Move to the heading line of which the present line is a subheading.
21279 This version will not throw an error. It will return the level of the
21280 headline found, or nil if no higher level is found.
21282 Also, this function will be a lot faster than `outline-up-heading',
21283 because it relies on stars being the outline starters. This can really
21284 make a significant difference in outlines with very many siblings."
21285 (let (start-level re)
21286 (org-back-to-heading t)
21287 (setq start-level (funcall outline-level))
21288 (if (equal start-level 1)
21290 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21291 (if (re-search-backward re nil t)
21292 (funcall outline-level)))))
21294 (defun org-first-sibling-p ()
21295 "Is this heading the first child of its parents?"
21296 (interactive)
21297 (let ((re org-outline-regexp-bol)
21298 level l)
21299 (unless (org-at-heading-p t)
21300 (error "Not at a heading"))
21301 (setq level (funcall outline-level))
21302 (save-excursion
21303 (if (not (re-search-backward re nil t))
21305 (setq l (funcall outline-level))
21306 (< l level)))))
21308 (defun org-goto-sibling (&optional previous)
21309 "Goto the next sibling, even if it is invisible.
21310 When PREVIOUS is set, go to the previous sibling instead. Returns t
21311 when a sibling was found. When none is found, return nil and don't
21312 move point."
21313 (let ((fun (if previous 're-search-backward 're-search-forward))
21314 (pos (point))
21315 (re org-outline-regexp-bol)
21316 level l)
21317 (when (condition-case nil (org-back-to-heading t) (error nil))
21318 (setq level (funcall outline-level))
21319 (catch 'exit
21320 (or previous (forward-char 1))
21321 (while (funcall fun re nil t)
21322 (setq l (funcall outline-level))
21323 (when (< l level) (goto-char pos) (throw 'exit nil))
21324 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21325 (goto-char pos)
21326 nil))))
21328 (defun org-show-siblings ()
21329 "Show all siblings of the current headline."
21330 (save-excursion
21331 (while (org-goto-sibling) (org-flag-heading nil)))
21332 (save-excursion
21333 (while (org-goto-sibling 'previous)
21334 (org-flag-heading nil))))
21336 (defun org-goto-first-child ()
21337 "Goto the first child, even if it is invisible.
21338 Return t when a child was found. Otherwise don't move point and
21339 return nil."
21340 (let (level (pos (point)) (re org-outline-regexp-bol))
21341 (when (condition-case nil (org-back-to-heading t) (error nil))
21342 (setq level (outline-level))
21343 (forward-char 1)
21344 (if (and (re-search-forward re nil t) (> (outline-level) level))
21345 (progn (goto-char (match-beginning 0)) t)
21346 (goto-char pos) nil))))
21348 (defun org-show-hidden-entry ()
21349 "Show an entry where even the heading is hidden."
21350 (save-excursion
21351 (org-show-entry)))
21353 (defun org-flag-heading (flag &optional entry)
21354 "Flag the current heading. FLAG non-nil means make invisible.
21355 When ENTRY is non-nil, show the entire entry."
21356 (save-excursion
21357 (org-back-to-heading t)
21358 ;; Check if we should show the entire entry
21359 (if entry
21360 (progn
21361 (org-show-entry)
21362 (save-excursion
21363 (and (outline-next-heading)
21364 (org-flag-heading nil))))
21365 (outline-flag-region (max (point-min) (1- (point)))
21366 (save-excursion (outline-end-of-heading) (point))
21367 flag))))
21369 (defun org-get-next-sibling ()
21370 "Move to next heading of the same level, and return point.
21371 If there is no such heading, return nil.
21372 This is like outline-next-sibling, but invisible headings are ok."
21373 (let ((level (funcall outline-level)))
21374 (outline-next-heading)
21375 (while (and (not (eobp)) (> (funcall outline-level) level))
21376 (outline-next-heading))
21377 (if (or (eobp) (< (funcall outline-level) level))
21379 (point))))
21381 (defun org-get-last-sibling ()
21382 "Move to previous heading of the same level, and return point.
21383 If there is no such heading, return nil."
21384 (let ((opoint (point))
21385 (level (funcall outline-level)))
21386 (outline-previous-heading)
21387 (when (and (/= (point) opoint) (outline-on-heading-p t))
21388 (while (and (> (funcall outline-level) level)
21389 (not (bobp)))
21390 (outline-previous-heading))
21391 (if (< (funcall outline-level) level)
21393 (point)))))
21395 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21396 ;; This contains an exact copy of the original function, but it uses
21397 ;; `org-back-to-heading', to make it work also in invisible
21398 ;; trees. And is uses an invisible-OK argument.
21399 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21400 ;; Furthermore, when used inside Org, finding the end of a large subtree
21401 ;; with many children and grandchildren etc, this can be much faster
21402 ;; than the outline version.
21403 (org-back-to-heading invisible-OK)
21404 (let ((first t)
21405 (level (funcall outline-level)))
21406 (if (and (derived-mode-p 'org-mode) (< level 1000))
21407 ;; A true heading (not a plain list item), in Org-mode
21408 ;; This means we can easily find the end by looking
21409 ;; only for the right number of stars. Using a regexp to do
21410 ;; this is so much faster than using a Lisp loop.
21411 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21412 (forward-char 1)
21413 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21414 ;; something else, do it the slow way
21415 (while (and (not (eobp))
21416 (or first (> (funcall outline-level) level)))
21417 (setq first nil)
21418 (outline-next-heading)))
21419 (unless to-heading
21420 (if (memq (preceding-char) '(?\n ?\^M))
21421 (progn
21422 ;; Go to end of line before heading
21423 (forward-char -1)
21424 (if (memq (preceding-char) '(?\n ?\^M))
21425 ;; leave blank line before heading
21426 (forward-char -1))))))
21427 (point))
21429 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21430 "Use Org version in org-mode, for dramatic speed-up."
21431 (if (derived-mode-p 'org-mode)
21432 (progn
21433 (org-end-of-subtree nil t)
21434 (unless (eobp) (backward-char 1)))
21435 ad-do-it))
21437 (defun org-end-of-meta-data-and-drawers ()
21438 "Jump to the first text after meta data and drawers in the current entry.
21439 This will move over empty lines, lines with planning time stamps,
21440 clocking lines, and drawers."
21441 (org-back-to-heading t)
21442 (let ((end (save-excursion (outline-next-heading) (point)))
21443 (re (concat "\\(" org-drawer-regexp "\\)"
21444 "\\|" "[ \t]*" org-keyword-time-regexp)))
21445 (forward-line 1)
21446 (while (re-search-forward re end t)
21447 (if (not (match-end 1))
21448 ;; empty or planning line
21449 (forward-line 1)
21450 ;; a drawer, find the end
21451 (re-search-forward "^[ \t]*:END:" end 'move)
21452 (forward-line 1)))
21453 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21454 (point)))
21456 (defun org-forward-same-level (arg &optional invisible-ok)
21457 "Move forward to the arg'th subheading at same level as this one.
21458 Stop at the first and last subheadings of a superior heading.
21459 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21460 it wil also look at invisible ones."
21461 (interactive "p")
21462 (org-back-to-heading invisible-ok)
21463 (org-at-heading-p)
21464 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21465 (re (format "^\\*\\{1,%d\\} " level))
21467 (forward-char 1)
21468 (while (> arg 0)
21469 (while (and (re-search-forward re nil 'move)
21470 (setq l (- (match-end 0) (match-beginning 0) 1))
21471 (= l level)
21472 (not invisible-ok)
21473 (progn (backward-char 1) (outline-invisible-p)))
21474 (if (< l level) (setq arg 1)))
21475 (setq arg (1- arg)))
21476 (beginning-of-line 1)))
21478 (defun org-backward-same-level (arg &optional invisible-ok)
21479 "Move backward to the arg'th subheading at same level as this one.
21480 Stop at the first and last subheadings of a superior heading."
21481 (interactive "p")
21482 (org-back-to-heading)
21483 (org-at-heading-p)
21484 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21485 (re (format "^\\*\\{1,%d\\} " level))
21487 (while (> arg 0)
21488 (while (and (re-search-backward re nil 'move)
21489 (setq l (- (match-end 0) (match-beginning 0) 1))
21490 (= l level)
21491 (not invisible-ok)
21492 (outline-invisible-p))
21493 (if (< l level) (setq arg 1)))
21494 (setq arg (1- arg)))))
21496 (defun org-show-subtree ()
21497 "Show everything after this heading at deeper levels."
21498 (interactive)
21499 (outline-flag-region
21500 (point)
21501 (save-excursion
21502 (org-end-of-subtree t t))
21503 nil))
21505 (defun org-show-entry ()
21506 "Show the body directly following this heading.
21507 Show the heading too, if it is currently invisible."
21508 (interactive)
21509 (save-excursion
21510 (condition-case nil
21511 (progn
21512 (org-back-to-heading t)
21513 (outline-flag-region
21514 (max (point-min) (1- (point)))
21515 (save-excursion
21516 (if (re-search-forward
21517 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21518 (match-beginning 1)
21519 (point-max)))
21520 nil)
21521 (org-cycle-hide-drawers 'children))
21522 (error nil))))
21524 (defun org-make-options-regexp (kwds &optional extra)
21525 "Make a regular expression for keyword lines."
21526 (concat
21528 "#?[ \t]*\\+\\("
21529 (mapconcat 'regexp-quote kwds "\\|")
21530 (if extra (concat "\\|" extra))
21531 "\\):[ \t]*"
21532 "\\(.*\\)"))
21534 ;; Make isearch reveal the necessary context
21535 (defun org-isearch-end ()
21536 "Reveal context after isearch exits."
21537 (when isearch-success ; only if search was successful
21538 (if (featurep 'xemacs)
21539 ;; Under XEmacs, the hook is run in the correct place,
21540 ;; we directly show the context.
21541 (org-show-context 'isearch)
21542 ;; In Emacs the hook runs *before* restoring the overlays.
21543 ;; So we have to use a one-time post-command-hook to do this.
21544 ;; (Emacs 22 has a special variable, see function `org-mode')
21545 (unless (and (boundp 'isearch-mode-end-hook-quit)
21546 isearch-mode-end-hook-quit)
21547 ;; Only when the isearch was not quitted.
21548 (org-add-hook 'post-command-hook 'org-isearch-post-command
21549 'append 'local)))))
21551 (defun org-isearch-post-command ()
21552 "Remove self from hook, and show context."
21553 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21554 (org-show-context 'isearch))
21557 ;;;; Integration with and fixes for other packages
21559 ;;; Imenu support
21561 (defvar org-imenu-markers nil
21562 "All markers currently used by Imenu.")
21563 (make-variable-buffer-local 'org-imenu-markers)
21565 (defun org-imenu-new-marker (&optional pos)
21566 "Return a new marker for use by Imenu, and remember the marker."
21567 (let ((m (make-marker)))
21568 (move-marker m (or pos (point)))
21569 (push m org-imenu-markers)
21572 (defun org-imenu-get-tree ()
21573 "Produce the index for Imenu."
21574 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21575 (setq org-imenu-markers nil)
21576 (let* ((n org-imenu-depth)
21577 (re (concat "^" (org-get-limited-outline-regexp)))
21578 (subs (make-vector (1+ n) nil))
21579 (last-level 0)
21580 m level head)
21581 (save-excursion
21582 (save-restriction
21583 (widen)
21584 (goto-char (point-max))
21585 (while (re-search-backward re nil t)
21586 (setq level (org-reduced-level (funcall outline-level)))
21587 (when (and (<= level n)
21588 (looking-at org-complex-heading-regexp))
21589 (setq head (org-link-display-format
21590 (org-match-string-no-properties 4))
21591 m (org-imenu-new-marker))
21592 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21593 (if (>= level last-level)
21594 (push (cons head m) (aref subs level))
21595 (push (cons head (aref subs (1+ level))) (aref subs level))
21596 (loop for i from (1+ level) to n do (aset subs i nil)))
21597 (setq last-level level)))))
21598 (aref subs 1)))
21600 (eval-after-load "imenu"
21601 '(progn
21602 (add-hook 'imenu-after-jump-hook
21603 (lambda ()
21604 (if (derived-mode-p 'org-mode)
21605 (org-show-context 'org-goto))))))
21607 (defun org-link-display-format (link)
21608 "Replace a link with either the description, or the link target
21609 if no description is present"
21610 (save-match-data
21611 (if (string-match org-bracket-link-analytic-regexp link)
21612 (replace-match (if (match-end 5)
21613 (match-string 5 link)
21614 (concat (match-string 1 link)
21615 (match-string 3 link)))
21616 nil t link)
21617 link)))
21619 (defun org-toggle-link-display ()
21620 "Toggle the literal or descriptive display of links."
21621 (interactive)
21622 (if org-descriptive-links
21623 (progn (org-remove-from-invisibility-spec '(org-link))
21624 (org-restart-font-lock)
21625 (setq org-descriptive-links nil))
21626 (progn (add-to-invisibility-spec '(org-link))
21627 (org-restart-font-lock)
21628 (setq org-descriptive-links t))))
21630 ;; Speedbar support
21632 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21633 "Overlay marking the agenda restriction line in speedbar.")
21634 (overlay-put org-speedbar-restriction-lock-overlay
21635 'face 'org-agenda-restriction-lock)
21636 (overlay-put org-speedbar-restriction-lock-overlay
21637 'help-echo "Agendas are currently limited to this item.")
21638 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21640 (defun org-speedbar-set-agenda-restriction ()
21641 "Restrict future agenda commands to the location at point in speedbar.
21642 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21643 (interactive)
21644 (require 'org-agenda)
21645 (let (p m tp np dir txt)
21646 (cond
21647 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21648 'org-imenu t))
21649 (setq m (get-text-property p 'org-imenu-marker))
21650 (with-current-buffer (marker-buffer m)
21651 (goto-char m)
21652 (org-agenda-set-restriction-lock 'subtree)))
21653 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21654 'speedbar-function 'speedbar-find-file))
21655 (setq tp (previous-single-property-change
21656 (1+ p) 'speedbar-function)
21657 np (next-single-property-change
21658 tp 'speedbar-function)
21659 dir (speedbar-line-directory)
21660 txt (buffer-substring-no-properties (or tp (point-min))
21661 (or np (point-max))))
21662 (with-current-buffer (find-file-noselect
21663 (let ((default-directory dir))
21664 (expand-file-name txt)))
21665 (unless (derived-mode-p 'org-mode)
21666 (error "Cannot restrict to non-Org-mode file"))
21667 (org-agenda-set-restriction-lock 'file)))
21668 (t (error "Don't know how to restrict Org-mode's agenda")))
21669 (move-overlay org-speedbar-restriction-lock-overlay
21670 (point-at-bol) (point-at-eol))
21671 (setq current-prefix-arg nil)
21672 (org-agenda-maybe-redo)))
21674 (eval-after-load "speedbar"
21675 '(progn
21676 (speedbar-add-supported-extension ".org")
21677 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21678 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21679 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21680 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21681 (add-hook 'speedbar-visiting-tag-hook
21682 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
21684 ;;; Fixes and Hacks for problems with other packages
21686 ;; Make flyspell not check words in links, to not mess up our keymap
21687 (defun org-mode-flyspell-verify ()
21688 "Don't let flyspell put overlays at active buttons, or on
21689 {todo,all-time,additional-option-like}-keywords."
21690 (let ((pos (max (1- (point)) (point-min)))
21691 (word (thing-at-point 'word)))
21692 (and (not (get-text-property pos 'keymap))
21693 (not (get-text-property pos 'org-no-flyspell))
21694 (not (member word org-todo-keywords-1))
21695 (not (member word org-all-time-keywords))
21696 (not (member word org-additional-option-like-keywords)))))
21698 (defun org-remove-flyspell-overlays-in (beg end)
21699 "Remove flyspell overlays in region."
21700 (and (org-bound-and-true-p flyspell-mode)
21701 (fboundp 'flyspell-delete-region-overlays)
21702 (flyspell-delete-region-overlays beg end))
21703 (add-text-properties beg end '(org-no-flyspell t)))
21705 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21706 (eval-after-load "bookmark"
21707 '(if (boundp 'bookmark-after-jump-hook)
21708 ;; We can use the hook
21709 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21710 ;; Hook not available, use advice
21711 (defadvice bookmark-jump (after org-make-visible activate)
21712 "Make the position visible."
21713 (org-bookmark-jump-unhide))))
21715 ;; Make sure saveplace shows the location if it was hidden
21716 (eval-after-load "saveplace"
21717 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21718 "Make the position visible."
21719 (org-bookmark-jump-unhide)))
21721 ;; Make sure ecb shows the location if it was hidden
21722 (eval-after-load "ecb"
21723 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21724 "Make hierarchy visible when jumping into location from ECB tree buffer."
21725 (if (derived-mode-p 'org-mode)
21726 (org-show-context))))
21728 (defun org-bookmark-jump-unhide ()
21729 "Unhide the current position, to show the bookmark location."
21730 (and (derived-mode-p 'org-mode)
21731 (or (outline-invisible-p)
21732 (save-excursion (goto-char (max (point-min) (1- (point))))
21733 (outline-invisible-p)))
21734 (org-show-context 'bookmark-jump)))
21736 ;; Make session.el ignore our circular variable
21737 (eval-after-load "session"
21738 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21740 ;;;; Experimental code
21742 (defun org-closed-in-range ()
21743 "Sparse tree of items closed in a certain time range.
21744 Still experimental, may disappear in the future."
21745 (interactive)
21746 ;; Get the time interval from the user.
21747 (let* ((time1 (org-float-time
21748 (org-read-date nil 'to-time nil "Starting date: ")))
21749 (time2 (org-float-time
21750 (org-read-date nil 'to-time nil "End date:")))
21751 ;; callback function
21752 (callback (lambda ()
21753 (let ((time
21754 (org-float-time
21755 (apply 'encode-time
21756 (org-parse-time-string
21757 (match-string 1))))))
21758 ;; check if time in interval
21759 (and (>= time time1) (<= time time2))))))
21760 ;; make tree, check each match with the callback
21761 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21763 ;;;; Finish up
21765 (provide 'org)
21767 (run-hooks 'org-load-hook)
21769 ;;; org.el ends here