org-e-latex: Support for footnote references in an item tag
[org-mode.git] / lisp / org.el
blobb89889dc71125ef085617c3b30b5b2ae48c9f169
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")))))
1847 (defgroup org-refile nil
1848 "Options concerning refiling entries in Org-mode."
1849 :tag "Org Refile"
1850 :group 'org)
1852 (defcustom org-directory "~/org"
1853 "Directory with org files.
1854 This is just a default location to look for Org files. There is no need
1855 at all to put your files into this directory. It is only used in the
1856 following situations:
1858 1. When a remember template specifies a target file that is not an
1859 absolute path. The path will then be interpreted relative to
1860 `org-directory'
1861 2. When a remember note is filed away in an interactive way (when exiting the
1862 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1863 with `org-directory' as the default path."
1864 :group 'org-refile
1865 :group 'org-remember
1866 :type 'directory)
1868 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1869 "Default target for storing notes.
1870 Used as a fall back file for org-remember.el and org-capture.el, for
1871 templates that do not specify a target file."
1872 :group 'org-refile
1873 :group 'org-remember
1874 :type '(choice
1875 (const :tag "Default from remember-data-file" nil)
1876 file))
1878 (defcustom org-goto-interface 'outline
1879 "The default interface to be used for `org-goto'.
1880 Allowed values are:
1881 outline The interface shows an outline of the relevant file
1882 and the correct heading is found by moving through
1883 the outline or by searching with incremental search.
1884 outline-path-completion Headlines in the current buffer are offered via
1885 completion. This is the interface also used by
1886 the refile command."
1887 :group 'org-refile
1888 :type '(choice
1889 (const :tag "Outline" outline)
1890 (const :tag "Outline-path-completion" outline-path-completion)))
1892 (defcustom org-goto-max-level 5
1893 "Maximum target level when running `org-goto' with refile interface."
1894 :group 'org-refile
1895 :type 'integer)
1897 (defcustom org-reverse-note-order nil
1898 "Non-nil means store new notes at the beginning of a file or entry.
1899 When nil, new notes will be filed to the end of a file or entry.
1900 This can also be a list with cons cells of regular expressions that
1901 are matched against file names, and values."
1902 :group 'org-remember
1903 :group 'org-refile
1904 :type '(choice
1905 (const :tag "Reverse always" t)
1906 (const :tag "Reverse never" nil)
1907 (repeat :tag "By file name regexp"
1908 (cons regexp boolean))))
1910 (defcustom org-log-refile nil
1911 "Information to record when a task is refiled.
1913 Possible values are:
1915 nil Don't add anything
1916 time Add a time stamp to the task
1917 note Prompt for a note and add it with template `org-log-note-headings'
1919 This option can also be set with on a per-file-basis with
1921 #+STARTUP: nologrefile
1922 #+STARTUP: logrefile
1923 #+STARTUP: lognoterefile
1925 You can have local logging settings for a subtree by setting the LOGGING
1926 property to one or more of these keywords.
1928 When bulk-refiling from the agenda, the value `note' is forbidden and
1929 will temporarily be changed to `time'."
1930 :group 'org-refile
1931 :group 'org-progress
1932 :version "24.1"
1933 :type '(choice
1934 (const :tag "No logging" nil)
1935 (const :tag "Record timestamp" time)
1936 (const :tag "Record timestamp with note." note)))
1938 (defcustom org-refile-targets nil
1939 "Targets for refiling entries with \\[org-refile].
1940 This is a list of cons cells. Each cell contains:
1941 - a specification of the files to be considered, either a list of files,
1942 or a symbol whose function or variable value will be used to retrieve
1943 a file name or a list of file names. If you use `org-agenda-files' for
1944 that, all agenda files will be scanned for targets. Nil means consider
1945 headings in the current buffer.
1946 - A specification of how to find candidate refile targets. This may be
1947 any of:
1948 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1949 This tag has to be present in all target headlines, inheritance will
1950 not be considered.
1951 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1952 todo keyword.
1953 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1954 headlines that are refiling targets.
1955 - a cons cell (:level . N). Any headline of level N is considered a target.
1956 Note that, when `org-odd-levels-only' is set, level corresponds to
1957 order in hierarchy, not to the number of stars.
1958 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1959 Note that, when `org-odd-levels-only' is set, level corresponds to
1960 order in hierarchy, not to the number of stars.
1962 Each element of this list generates a set of possible targets.
1963 The union of these sets is presented (with completion) to
1964 the user by `org-refile'.
1966 You can set the variable `org-refile-target-verify-function' to a function
1967 to verify each headline found by the simple criteria above.
1969 When this variable is nil, all top-level headlines in the current buffer
1970 are used, equivalent to the value `((nil . (:level . 1))'."
1971 :group 'org-refile
1972 :type '(repeat
1973 (cons
1974 (choice :value org-agenda-files
1975 (const :tag "All agenda files" org-agenda-files)
1976 (const :tag "Current buffer" nil)
1977 (function) (variable) (file))
1978 (choice :tag "Identify target headline by"
1979 (cons :tag "Specific tag" (const :value :tag) (string))
1980 (cons :tag "TODO keyword" (const :value :todo) (string))
1981 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1982 (cons :tag "Level number" (const :value :level) (integer))
1983 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1985 (defcustom org-refile-target-verify-function nil
1986 "Function to verify if the headline at point should be a refile target.
1987 The function will be called without arguments, with point at the
1988 beginning of the headline. It should return t and leave point
1989 where it is if the headline is a valid target for refiling.
1991 If the target should not be selected, the function must return nil.
1992 In addition to this, it may move point to a place from where the search
1993 should be continued. For example, the function may decide that the entire
1994 subtree of the current entry should be excluded and move point to the end
1995 of the subtree."
1996 :group 'org-refile
1997 :type 'function)
1999 (defcustom org-refile-use-cache nil
2000 "Non-nil means cache refile targets to speed up the process.
2001 The cache for a particular file will be updated automatically when
2002 the buffer has been killed, or when any of the marker used for flagging
2003 refile targets no longer points at a live buffer.
2004 If you have added new entries to a buffer that might themselves be targets,
2005 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2006 find that easier, `C-u C-u C-u C-c C-w'."
2007 :group 'org-refile
2008 :version "24.1"
2009 :type 'boolean)
2011 (defcustom org-refile-use-outline-path nil
2012 "Non-nil means provide refile targets as paths.
2013 So a level 3 headline will be available as level1/level2/level3.
2015 When the value is `file', also include the file name (without directory)
2016 into the path. In this case, you can also stop the completion after
2017 the file name, to get entries inserted as top level in the file.
2019 When `full-file-path', include the full file path."
2020 :group 'org-refile
2021 :type '(choice
2022 (const :tag "Not" nil)
2023 (const :tag "Yes" t)
2024 (const :tag "Start with file name" file)
2025 (const :tag "Start with full file path" full-file-path)))
2027 (defcustom org-outline-path-complete-in-steps t
2028 "Non-nil means complete the outline path in hierarchical steps.
2029 When Org-mode uses the refile interface to select an outline path
2030 \(see variable `org-refile-use-outline-path'), the completion of
2031 the path can be done is a single go, or if can be done in steps down
2032 the headline hierarchy. Going in steps is probably the best if you
2033 do not use a special completion package like `ido' or `icicles'.
2034 However, when using these packages, going in one step can be very
2035 fast, while still showing the whole path to the entry."
2036 :group 'org-refile
2037 :type 'boolean)
2039 (defcustom org-refile-allow-creating-parent-nodes nil
2040 "Non-nil means allow to create new nodes as refile targets.
2041 New nodes are then created by adding \"/new node name\" to the completion
2042 of an existing node. When the value of this variable is `confirm',
2043 new node creation must be confirmed by the user (recommended)
2044 When nil, the completion must match an existing entry.
2046 Note that, if the new heading is not seen by the criteria
2047 listed in `org-refile-targets', multiple instances of the same
2048 heading would be created by trying again to file under the new
2049 heading."
2050 :group 'org-refile
2051 :type '(choice
2052 (const :tag "Never" nil)
2053 (const :tag "Always" t)
2054 (const :tag "Prompt for confirmation" confirm)))
2056 (defcustom org-refile-active-region-within-subtree nil
2057 "Non-nil means also refile active region within a subtree.
2059 By default `org-refile' doesn't allow refiling regions if they
2060 don't contain a set of subtrees, but it might be convenient to
2061 do so sometimes: in that case, the first line of the region is
2062 converted to a headline before refiling."
2063 :group 'org-refile
2064 :version "24.1"
2065 :type 'boolean)
2067 (defgroup org-todo nil
2068 "Options concerning TODO items in Org-mode."
2069 :tag "Org TODO"
2070 :group 'org)
2072 (defgroup org-progress nil
2073 "Options concerning Progress logging in Org-mode."
2074 :tag "Org Progress"
2075 :group 'org-time)
2077 (defvar org-todo-interpretation-widgets
2078 '((:tag "Sequence (cycling hits every state)" sequence)
2079 (:tag "Type (cycling directly to DONE)" type))
2080 "The available interpretation symbols for customizing `org-todo-keywords'.
2081 Interested libraries should add to this list.")
2083 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2084 "List of TODO entry keyword sequences and their interpretation.
2085 \\<org-mode-map>This is a list of sequences.
2087 Each sequence starts with a symbol, either `sequence' or `type',
2088 indicating if the keywords should be interpreted as a sequence of
2089 action steps, or as different types of TODO items. The first
2090 keywords are states requiring action - these states will select a headline
2091 for inclusion into the global TODO list Org-mode produces. If one of
2092 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2093 signify that no further action is necessary. If \"|\" is not found,
2094 the last keyword is treated as the only DONE state of the sequence.
2096 The command \\[org-todo] cycles an entry through these states, and one
2097 additional state where no keyword is present. For details about this
2098 cycling, see the manual.
2100 TODO keywords and interpretation can also be set on a per-file basis with
2101 the special #+SEQ_TODO and #+TYP_TODO lines.
2103 Each keyword can optionally specify a character for fast state selection
2104 \(in combination with the variable `org-use-fast-todo-selection')
2105 and specifiers for state change logging, using the same syntax
2106 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2107 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2108 indicates to record a time stamp each time this state is selected.
2110 Each keyword may also specify if a timestamp or a note should be
2111 recorded when entering or leaving the state, by adding additional
2112 characters in the parenthesis after the keyword. This looks like this:
2113 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2114 record only the time of the state change. With X and Y being either
2115 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2116 Y when leaving the state if and only if the *target* state does not
2117 define X. You may omit any of the fast-selection key or X or /Y,
2118 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2120 For backward compatibility, this variable may also be just a list
2121 of keywords - in this case the interpretation (sequence or type) will be
2122 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2123 :group 'org-todo
2124 :group 'org-keywords
2125 :type '(choice
2126 (repeat :tag "Old syntax, just keywords"
2127 (string :tag "Keyword"))
2128 (repeat :tag "New syntax"
2129 (cons
2130 (choice
2131 :tag "Interpretation"
2132 ;;Quick and dirty way to see
2133 ;;`org-todo-interpretations'. This takes the
2134 ;;place of item arguments
2135 :convert-widget
2136 (lambda (widget)
2137 (widget-put widget
2138 :args (mapcar
2139 #'(lambda (x)
2140 (widget-convert
2141 (cons 'const x)))
2142 org-todo-interpretation-widgets))
2143 widget))
2144 (repeat
2145 (string :tag "Keyword"))))))
2147 (defvar org-todo-keywords-1 nil
2148 "All TODO and DONE keywords active in a buffer.")
2149 (make-variable-buffer-local 'org-todo-keywords-1)
2150 (defvar org-todo-keywords-for-agenda nil)
2151 (defvar org-done-keywords-for-agenda nil)
2152 (defvar org-drawers-for-agenda nil)
2153 (defvar org-todo-keyword-alist-for-agenda nil)
2154 (defvar org-tag-alist-for-agenda nil)
2155 (defvar org-agenda-contributing-files nil)
2156 (defvar org-not-done-keywords nil)
2157 (make-variable-buffer-local 'org-not-done-keywords)
2158 (defvar org-done-keywords nil)
2159 (make-variable-buffer-local 'org-done-keywords)
2160 (defvar org-todo-heads nil)
2161 (make-variable-buffer-local 'org-todo-heads)
2162 (defvar org-todo-sets nil)
2163 (make-variable-buffer-local 'org-todo-sets)
2164 (defvar org-todo-log-states nil)
2165 (make-variable-buffer-local 'org-todo-log-states)
2166 (defvar org-todo-kwd-alist nil)
2167 (make-variable-buffer-local 'org-todo-kwd-alist)
2168 (defvar org-todo-key-alist nil)
2169 (make-variable-buffer-local 'org-todo-key-alist)
2170 (defvar org-todo-key-trigger nil)
2171 (make-variable-buffer-local 'org-todo-key-trigger)
2173 (defcustom org-todo-interpretation 'sequence
2174 "Controls how TODO keywords are interpreted.
2175 This variable is in principle obsolete and is only used for
2176 backward compatibility, if the interpretation of todo keywords is
2177 not given already in `org-todo-keywords'. See that variable for
2178 more information."
2179 :group 'org-todo
2180 :group 'org-keywords
2181 :type '(choice (const sequence)
2182 (const type)))
2184 (defcustom org-use-fast-todo-selection t
2185 "Non-nil means use the fast todo selection scheme with C-c C-t.
2186 This variable describes if and under what circumstances the cycling
2187 mechanism for TODO keywords will be replaced by a single-key, direct
2188 selection scheme.
2190 When nil, fast selection is never used.
2192 When the symbol `prefix', it will be used when `org-todo' is called with
2193 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2194 in an agenda buffer.
2196 When t, fast selection is used by default. In this case, the prefix
2197 argument forces cycling instead.
2199 In all cases, the special interface is only used if access keys have actually
2200 been assigned by the user, i.e. if keywords in the configuration are followed
2201 by a letter in parenthesis, like TODO(t)."
2202 :group 'org-todo
2203 :type '(choice
2204 (const :tag "Never" nil)
2205 (const :tag "By default" t)
2206 (const :tag "Only with C-u C-c C-t" prefix)))
2208 (defcustom org-provide-todo-statistics t
2209 "Non-nil means update todo statistics after insert and toggle.
2210 ALL-HEADLINES means update todo statistics by including headlines
2211 with no TODO keyword as well, counting them as not done.
2212 A list of TODO keywords means the same, but skip keywords that are
2213 not in this list.
2215 When this is set, todo statistics is updated in the parent of the
2216 current entry each time a todo state is changed."
2217 :group 'org-todo
2218 :type '(choice
2219 (const :tag "Yes, only for TODO entries" t)
2220 (const :tag "Yes, including all entries" 'all-headlines)
2221 (repeat :tag "Yes, for TODOs in this list"
2222 (string :tag "TODO keyword"))
2223 (other :tag "No TODO statistics" nil)))
2225 (defcustom org-hierarchical-todo-statistics t
2226 "Non-nil means TODO statistics covers just direct children.
2227 When nil, all entries in the subtree are considered.
2228 This has only an effect if `org-provide-todo-statistics' is set.
2229 To set this to nil for only a single subtree, use a COOKIE_DATA
2230 property and include the word \"recursive\" into the value."
2231 :group 'org-todo
2232 :type 'boolean)
2234 (defcustom org-after-todo-state-change-hook nil
2235 "Hook which is run after the state of a TODO item was changed.
2236 The new state (a string with a TODO keyword, or nil) is available in the
2237 Lisp variable `org-state'."
2238 :group 'org-todo
2239 :type 'hook)
2241 (defvar org-blocker-hook nil
2242 "Hook for functions that are allowed to block a state change.
2244 Each function gets as its single argument a property list, see
2245 `org-trigger-hook' for more information about this list.
2247 If any of the functions in this hook returns nil, the state change
2248 is blocked.")
2250 (defvar org-trigger-hook nil
2251 "Hook for functions that are triggered by a state change.
2253 Each function gets as its single argument a property list with at least
2254 the following elements:
2256 (:type type-of-change :position pos-at-entry-start
2257 :from old-state :to new-state)
2259 Depending on the type, more properties may be present.
2261 This mechanism is currently implemented for:
2263 TODO state changes
2264 ------------------
2265 :type todo-state-change
2266 :from previous state (keyword as a string), or nil, or a symbol
2267 'todo' or 'done', to indicate the general type of state.
2268 :to new state, like in :from")
2270 (defcustom org-enforce-todo-dependencies nil
2271 "Non-nil means undone TODO entries will block switching the parent to DONE.
2272 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2273 be blocked if any prior sibling is not yet done.
2274 Finally, if the parent is blocked because of ordered siblings of its own,
2275 the child will also be blocked."
2276 :set (lambda (var val)
2277 (set var val)
2278 (if val
2279 (add-hook 'org-blocker-hook
2280 'org-block-todo-from-children-or-siblings-or-parent)
2281 (remove-hook 'org-blocker-hook
2282 'org-block-todo-from-children-or-siblings-or-parent)))
2283 :group 'org-todo
2284 :type 'boolean)
2286 (defcustom org-enforce-todo-checkbox-dependencies nil
2287 "Non-nil means unchecked boxes will block switching the parent to DONE.
2288 When this is nil, checkboxes have no influence on switching TODO states.
2289 When non-nil, you first need to check off all check boxes before the TODO
2290 entry can be switched to DONE.
2291 This variable needs to be set before org.el is loaded, and you need to
2292 restart Emacs after a change to make the change effective. The only way
2293 to change is while Emacs is running is through the customize interface."
2294 :set (lambda (var val)
2295 (set var val)
2296 (if val
2297 (add-hook 'org-blocker-hook
2298 'org-block-todo-from-checkboxes)
2299 (remove-hook 'org-blocker-hook
2300 'org-block-todo-from-checkboxes)))
2301 :group 'org-todo
2302 :type 'boolean)
2304 (defcustom org-treat-insert-todo-heading-as-state-change nil
2305 "Non-nil means inserting a TODO heading is treated as state change.
2306 So when the command \\[org-insert-todo-heading] is used, state change
2307 logging will apply if appropriate. When nil, the new TODO item will
2308 be inserted directly, and no logging will take place."
2309 :group 'org-todo
2310 :type 'boolean)
2312 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2313 "Non-nil means switching TODO states with S-cursor counts as state change.
2314 This is the default behavior. However, setting this to nil allows a
2315 convenient way to select a TODO state and bypass any logging associated
2316 with that."
2317 :group 'org-todo
2318 :type 'boolean)
2320 (defcustom org-todo-state-tags-triggers nil
2321 "Tag changes that should be triggered by TODO state changes.
2322 This is a list. Each entry is
2324 (state-change (tag . flag) .......)
2326 State-change can be a string with a state, and empty string to indicate the
2327 state that has no TODO keyword, or it can be one of the symbols `todo'
2328 or `done', meaning any not-done or done state, respectively."
2329 :group 'org-todo
2330 :group 'org-tags
2331 :type '(repeat
2332 (cons (choice :tag "When changing to"
2333 (const :tag "Not-done state" todo)
2334 (const :tag "Done state" done)
2335 (string :tag "State"))
2336 (repeat
2337 (cons :tag "Tag action"
2338 (string :tag "Tag")
2339 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2341 (defcustom org-log-done nil
2342 "Information to record when a task moves to the DONE state.
2344 Possible values are:
2346 nil Don't add anything, just change the keyword
2347 time Add a time stamp to the task
2348 note Prompt for a note and add it with template `org-log-note-headings'
2350 This option can also be set with on a per-file-basis with
2352 #+STARTUP: nologdone
2353 #+STARTUP: logdone
2354 #+STARTUP: lognotedone
2356 You can have local logging settings for a subtree by setting the LOGGING
2357 property to one or more of these keywords."
2358 :group 'org-todo
2359 :group 'org-progress
2360 :type '(choice
2361 (const :tag "No logging" nil)
2362 (const :tag "Record CLOSED timestamp" time)
2363 (const :tag "Record CLOSED timestamp with note." note)))
2365 ;; Normalize old uses of org-log-done.
2366 (cond
2367 ((eq org-log-done t) (setq org-log-done 'time))
2368 ((and (listp org-log-done) (memq 'done org-log-done))
2369 (setq org-log-done 'note)))
2371 (defcustom org-log-reschedule nil
2372 "Information to record when the scheduling date of a tasks is modified.
2374 Possible values are:
2376 nil Don't add anything, just change the date
2377 time Add a time stamp to the task
2378 note Prompt for a note and add it with template `org-log-note-headings'
2380 This option can also be set with on a per-file-basis with
2382 #+STARTUP: nologreschedule
2383 #+STARTUP: logreschedule
2384 #+STARTUP: lognotereschedule"
2385 :group 'org-todo
2386 :group 'org-progress
2387 :type '(choice
2388 (const :tag "No logging" nil)
2389 (const :tag "Record timestamp" time)
2390 (const :tag "Record timestamp with note." note)))
2392 (defcustom org-log-redeadline nil
2393 "Information to record when the deadline date of a tasks is modified.
2395 Possible values are:
2397 nil Don't add anything, just change the date
2398 time Add a time stamp to the task
2399 note Prompt for a note and add it with template `org-log-note-headings'
2401 This option can also be set with on a per-file-basis with
2403 #+STARTUP: nologredeadline
2404 #+STARTUP: logredeadline
2405 #+STARTUP: lognoteredeadline
2407 You can have local logging settings for a subtree by setting the LOGGING
2408 property to one or more of these keywords."
2409 :group 'org-todo
2410 :group 'org-progress
2411 :type '(choice
2412 (const :tag "No logging" nil)
2413 (const :tag "Record timestamp" time)
2414 (const :tag "Record timestamp with note." note)))
2416 (defcustom org-log-note-clock-out nil
2417 "Non-nil means record a note when clocking out of an item.
2418 This can also be configured on a per-file basis by adding one of
2419 the following lines anywhere in the buffer:
2421 #+STARTUP: lognoteclock-out
2422 #+STARTUP: nolognoteclock-out"
2423 :group 'org-todo
2424 :group 'org-progress
2425 :type 'boolean)
2427 (defcustom org-log-done-with-time t
2428 "Non-nil means the CLOSED time stamp will contain date and time.
2429 When nil, only the date will be recorded."
2430 :group 'org-progress
2431 :type 'boolean)
2433 (defcustom org-log-note-headings
2434 '((done . "CLOSING NOTE %t")
2435 (state . "State %-12s from %-12S %t")
2436 (note . "Note taken on %t")
2437 (reschedule . "Rescheduled from %S on %t")
2438 (delschedule . "Not scheduled, was %S on %t")
2439 (redeadline . "New deadline from %S on %t")
2440 (deldeadline . "Removed deadline, was %S on %t")
2441 (refile . "Refiled on %t")
2442 (clock-out . ""))
2443 "Headings for notes added to entries.
2444 The value is an alist, with the car being a symbol indicating the note
2445 context, and the cdr is the heading to be used. The heading may also be the
2446 empty string.
2447 %t in the heading will be replaced by a time stamp.
2448 %T will be an active time stamp instead the default inactive one
2449 %d will be replaced by a short-format time stamp.
2450 %D will be replaced by an active short-format time stamp.
2451 %s will be replaced by the new TODO state, in double quotes.
2452 %S will be replaced by the old TODO state, in double quotes.
2453 %u will be replaced by the user name.
2454 %U will be replaced by the full user name.
2456 In fact, it is not a good idea to change the `state' entry, because
2457 agenda log mode depends on the format of these entries."
2458 :group 'org-todo
2459 :group 'org-progress
2460 :type '(list :greedy t
2461 (cons (const :tag "Heading when closing an item" done) string)
2462 (cons (const :tag
2463 "Heading when changing todo state (todo sequence only)"
2464 state) string)
2465 (cons (const :tag "Heading when just taking a note" note) string)
2466 (cons (const :tag "Heading when clocking out" clock-out) string)
2467 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2468 (cons (const :tag "Heading when rescheduling" reschedule) string)
2469 (cons (const :tag "Heading when changing deadline" redeadline) string)
2470 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2471 (cons (const :tag "Heading when refiling" refile) string)))
2473 (unless (assq 'note org-log-note-headings)
2474 (push '(note . "%t") org-log-note-headings))
2476 (defcustom org-log-into-drawer nil
2477 "Non-nil means insert state change notes and time stamps into a drawer.
2478 When nil, state changes notes will be inserted after the headline and
2479 any scheduling and clock lines, but not inside a drawer.
2481 The value of this variable should be the name of the drawer to use.
2482 LOGBOOK is proposed as the default drawer for this purpose, you can
2483 also set this to a string to define the drawer of your choice.
2485 A value of t is also allowed, representing \"LOGBOOK\".
2487 If this variable is set, `org-log-state-notes-insert-after-drawers'
2488 will be ignored.
2490 You can set the property LOG_INTO_DRAWER to overrule this setting for
2491 a subtree."
2492 :group 'org-todo
2493 :group 'org-progress
2494 :type '(choice
2495 (const :tag "Not into a drawer" nil)
2496 (const :tag "LOGBOOK" t)
2497 (string :tag "Other")))
2499 (if (fboundp 'defvaralias)
2500 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2502 (defun org-log-into-drawer ()
2503 "Return the value of `org-log-into-drawer', but let properties overrule.
2504 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2505 used instead of the default value."
2506 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2507 (cond
2508 ((or (not p) (equal p "nil")) org-log-into-drawer)
2509 ((equal p "t") "LOGBOOK")
2510 (t p))))
2512 (defcustom org-log-state-notes-insert-after-drawers nil
2513 "Non-nil means insert state change notes after any drawers in entry.
2514 Only the drawers that *immediately* follow the headline and the
2515 deadline/scheduled line are skipped.
2516 When nil, insert notes right after the heading and perhaps the line
2517 with deadline/scheduling if present.
2519 This variable will have no effect if `org-log-into-drawer' is
2520 set."
2521 :group 'org-todo
2522 :group 'org-progress
2523 :type 'boolean)
2525 (defcustom org-log-states-order-reversed t
2526 "Non-nil means the latest state note will be directly after heading.
2527 When nil, the state change notes will be ordered according to time."
2528 :group 'org-todo
2529 :group 'org-progress
2530 :type 'boolean)
2532 (defcustom org-todo-repeat-to-state nil
2533 "The TODO state to which a repeater should return the repeating task.
2534 By default this is the first task in a TODO sequence, or the previous state
2535 in a TODO_TYP set. But you can specify another task here.
2536 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2537 :group 'org-todo
2538 :version "24.1"
2539 :type '(choice (const :tag "Head of sequence" nil)
2540 (string :tag "Specific state")))
2542 (defcustom org-log-repeat 'time
2543 "Non-nil means record moving through the DONE state when triggering repeat.
2544 An auto-repeating task is immediately switched back to TODO when
2545 marked DONE. If you are not logging state changes (by adding \"@\"
2546 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2547 record a closing note, there will be no record of the task moving
2548 through DONE. This variable forces taking a note anyway.
2550 nil Don't force a record
2551 time Record a time stamp
2552 note Record a note
2554 This option can also be set with on a per-file-basis with
2556 #+STARTUP: logrepeat
2557 #+STARTUP: lognoterepeat
2558 #+STARTUP: nologrepeat
2560 You can have local logging settings for a subtree by setting the LOGGING
2561 property to one or more of these keywords."
2562 :group 'org-todo
2563 :group 'org-progress
2564 :type '(choice
2565 (const :tag "Don't force a record" nil)
2566 (const :tag "Force recording the DONE state" time)
2567 (const :tag "Force recording a note with the DONE state" note)))
2570 (defgroup org-priorities nil
2571 "Priorities in Org-mode."
2572 :tag "Org Priorities"
2573 :group 'org-todo)
2575 (defcustom org-enable-priority-commands t
2576 "Non-nil means priority commands are active.
2577 When nil, these commands will be disabled, so that you never accidentally
2578 set a priority."
2579 :group 'org-priorities
2580 :type 'boolean)
2582 (defcustom org-highest-priority ?A
2583 "The highest priority of TODO items. A character like ?A, ?B etc.
2584 Must have a smaller ASCII number than `org-lowest-priority'."
2585 :group 'org-priorities
2586 :type 'character)
2588 (defcustom org-lowest-priority ?C
2589 "The lowest priority of TODO items. A character like ?A, ?B etc.
2590 Must have a larger ASCII number than `org-highest-priority'."
2591 :group 'org-priorities
2592 :type 'character)
2594 (defcustom org-default-priority ?B
2595 "The default priority of TODO items.
2596 This is the priority an item gets if no explicit priority is given.
2597 When starting to cycle on an empty priority the first step in the cycle
2598 depends on `org-priority-start-cycle-with-default'. The resulting first
2599 step priority must not exceed the range from `org-highest-priority' to
2600 `org-lowest-priority' which means that `org-default-priority' has to be
2601 in this range exclusive or inclusive the range boundaries. Else the
2602 first step refuses to set the default and the second will fall back
2603 to (depending on the command used) the highest or lowest priority."
2604 :group 'org-priorities
2605 :type 'character)
2607 (defcustom org-priority-start-cycle-with-default t
2608 "Non-nil means start with default priority when starting to cycle.
2609 When this is nil, the first step in the cycle will be (depending on the
2610 command used) one higher or lower than the default priority.
2611 See also `org-default-priority'."
2612 :group 'org-priorities
2613 :type 'boolean)
2615 (defcustom org-get-priority-function nil
2616 "Function to extract the priority from a string.
2617 The string is normally the headline. If this is nil Org computes the
2618 priority from the priority cookie like [#A] in the headline. It returns
2619 an integer, increasing by 1000 for each priority level.
2620 The user can set a different function here, which should take a string
2621 as an argument and return the numeric priority."
2622 :group 'org-priorities
2623 :version "24.1"
2624 :type 'function)
2626 (defgroup org-time nil
2627 "Options concerning time stamps and deadlines in Org-mode."
2628 :tag "Org Time"
2629 :group 'org)
2631 (defcustom org-insert-labeled-timestamps-at-point nil
2632 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2633 When nil, these labeled time stamps are forces into the second line of an
2634 entry, just after the headline. When scheduling from the global TODO list,
2635 the time stamp will always be forced into the second line."
2636 :group 'org-time
2637 :type 'boolean)
2639 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2640 "Formats for `format-time-string' which are used for time stamps.
2641 It is not recommended to change this constant.")
2643 (defcustom org-time-stamp-rounding-minutes '(0 5)
2644 "Number of minutes to round time stamps to.
2645 These are two values, the first applies when first creating a time stamp.
2646 The second applies when changing it with the commands `S-up' and `S-down'.
2647 When changing the time stamp, this means that it will change in steps
2648 of N minutes, as given by the second value.
2650 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2651 numbers should be factors of 60, so for example 5, 10, 15.
2653 When this is larger than 1, you can still force an exact time stamp by using
2654 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2655 and by using a prefix arg to `S-up/down' to specify the exact number
2656 of minutes to shift."
2657 :group 'org-time
2658 :get #'(lambda (var) ; Make sure both elements are there
2659 (if (integerp (default-value var))
2660 (list (default-value var) 5)
2661 (default-value var)))
2662 :type '(list
2663 (integer :tag "when inserting times")
2664 (integer :tag "when modifying times")))
2666 ;; Normalize old customizations of this variable.
2667 (when (integerp org-time-stamp-rounding-minutes)
2668 (setq org-time-stamp-rounding-minutes
2669 (list org-time-stamp-rounding-minutes
2670 org-time-stamp-rounding-minutes)))
2672 (defcustom org-display-custom-times nil
2673 "Non-nil means overlay custom formats over all time stamps.
2674 The formats are defined through the variable `org-time-stamp-custom-formats'.
2675 To turn this on on a per-file basis, insert anywhere in the file:
2676 #+STARTUP: customtime"
2677 :group 'org-time
2678 :set 'set-default
2679 :type 'sexp)
2680 (make-variable-buffer-local 'org-display-custom-times)
2682 (defcustom org-time-stamp-custom-formats
2683 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2684 "Custom formats for time stamps. See `format-time-string' for the syntax.
2685 These are overlaid over the default ISO format if the variable
2686 `org-display-custom-times' is set. Time like %H:%M should be at the
2687 end of the second format. The custom formats are also honored by export
2688 commands, if custom time display is turned on at the time of export."
2689 :group 'org-time
2690 :type 'sexp)
2692 (defun org-time-stamp-format (&optional long inactive)
2693 "Get the right format for a time string."
2694 (let ((f (if long (cdr org-time-stamp-formats)
2695 (car org-time-stamp-formats))))
2696 (if inactive
2697 (concat "[" (substring f 1 -1) "]")
2698 f)))
2700 (defcustom org-time-clocksum-format "%d:%02d"
2701 "The format string used when creating CLOCKSUM lines.
2702 This is also used when org-mode generates a time duration."
2703 :group 'org-time
2704 :type 'string)
2706 (defcustom org-time-clocksum-use-fractional nil
2707 "If non-nil, \\[org-clock-display] uses fractional times.
2708 org-mode generates a time duration."
2709 :group 'org-time
2710 :type 'boolean)
2712 (defcustom org-time-clocksum-fractional-format "%.2f"
2713 "The format string used when creating CLOCKSUM lines, or when
2714 org-mode generates a time duration."
2715 :group 'org-time
2716 :type 'string)
2718 (defcustom org-deadline-warning-days 14
2719 "No. of days before expiration during which a deadline becomes active.
2720 This variable governs the display in sparse trees and in the agenda.
2721 When 0 or negative, it means use this number (the absolute value of it)
2722 even if a deadline has a different individual lead time specified.
2724 Custom commands can set this variable in the options section."
2725 :group 'org-time
2726 :group 'org-agenda-daily/weekly
2727 :type 'integer)
2729 (defcustom org-read-date-prefer-future t
2730 "Non-nil means assume future for incomplete date input from user.
2731 This affects the following situations:
2732 1. The user gives a month but not a year.
2733 For example, if it is April and you enter \"feb 2\", this will be read
2734 as Feb 2, *next* year. \"May 5\", however, will be this year.
2735 2. The user gives a day, but no month.
2736 For example, if today is the 15th, and you enter \"3\", Org-mode will
2737 read this as the third of *next* month. However, if you enter \"17\",
2738 it will be considered as *this* month.
2740 If you set this variable to the symbol `time', then also the following
2741 will work:
2743 3. If the user gives a time, but no day. If the time is before now,
2744 to will be interpreted as tomorrow.
2746 Currently none of this works for ISO week specifications.
2748 When this option is nil, the current day, month and year will always be
2749 used as defaults.
2751 See also `org-agenda-jump-prefer-future'."
2752 :group 'org-time
2753 :type '(choice
2754 (const :tag "Never" nil)
2755 (const :tag "Check month and day" t)
2756 (const :tag "Check month, day, and time" time)))
2758 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2759 "Should the agenda jump command prefer the future for incomplete dates?
2760 The default is to do the same as configured in `org-read-date-prefer-future'.
2761 But you can also set a deviating value here.
2762 This may t or nil, or the symbol `org-read-date-prefer-future'."
2763 :group 'org-agenda
2764 :group 'org-time
2765 :version "24.1"
2766 :type '(choice
2767 (const :tag "Use org-read-date-prefer-future"
2768 org-read-date-prefer-future)
2769 (const :tag "Never" nil)
2770 (const :tag "Always" t)))
2772 (defcustom org-read-date-force-compatible-dates t
2773 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2775 Depending on the system Emacs is running on, certain dates cannot
2776 be represented with the type used internally to represent time.
2777 Dates between 1970-1-1 and 2038-1-1 can always be represented
2778 correctly. Some systems allow for earlier dates, some for later,
2779 some for both. One way to find out it to insert any date into an
2780 Org buffer, putting the cursor on the year and hitting S-up and
2781 S-down to test the range.
2783 When this variable is set to t, the date/time prompt will not let
2784 you specify dates outside the 1970-2037 range, so it is certain that
2785 these dates will work in whatever version of Emacs you are
2786 running, and also that you can move a file from one Emacs implementation
2787 to another. WHenever Org is forcing the year for you, it will display
2788 a message and beep.
2790 When this variable is nil, Org will check if the date is
2791 representable in the specific Emacs implementation you are using.
2792 If not, it will force a year, usually the current year, and beep
2793 to remind you. Currently this setting is not recommended because
2794 the likelihood that you will open your Org files in an Emacs that
2795 has limited date range is not negligible.
2797 A workaround for this problem is to use diary sexp dates for time
2798 stamps outside of this range."
2799 :group 'org-time
2800 :version "24.1"
2801 :type 'boolean)
2803 (defcustom org-read-date-display-live t
2804 "Non-nil means display current interpretation of date prompt live.
2805 This display will be in an overlay, in the minibuffer."
2806 :group 'org-time
2807 :type 'boolean)
2809 (defcustom org-read-date-popup-calendar t
2810 "Non-nil means pop up a calendar when prompting for a date.
2811 In the calendar, the date can be selected with mouse-1. However, the
2812 minibuffer will also be active, and you can simply enter the date as well.
2813 When nil, only the minibuffer will be available."
2814 :group 'org-time
2815 :type 'boolean)
2816 (if (fboundp 'defvaralias)
2817 (defvaralias 'org-popup-calendar-for-date-prompt
2818 'org-read-date-popup-calendar))
2820 (defcustom org-read-date-minibuffer-setup-hook nil
2821 "Hook to be used to set up keys for the date/time interface.
2822 Add key definitions to `minibuffer-local-map', which will be a temporary
2823 copy."
2824 :group 'org-time
2825 :type 'hook)
2827 (defcustom org-extend-today-until 0
2828 "The hour when your day really ends. Must be an integer.
2829 This has influence for the following applications:
2830 - When switching the agenda to \"today\". It it is still earlier than
2831 the time given here, the day recognized as TODAY is actually yesterday.
2832 - When a date is read from the user and it is still before the time given
2833 here, the current date and time will be assumed to be yesterday, 23:59.
2834 Also, timestamps inserted in remember templates follow this rule.
2836 IMPORTANT: This is a feature whose implementation is and likely will
2837 remain incomplete. Really, it is only here because past midnight seems to
2838 be the favorite working time of John Wiegley :-)"
2839 :group 'org-time
2840 :type 'integer)
2842 (defcustom org-use-effective-time nil
2843 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2844 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2845 \"effective time\" of any timestamps between midnight and 8am will be
2846 23:59 of the previous day."
2847 :group 'org-time
2848 :version "24.1"
2849 :type 'boolean)
2851 (defcustom org-edit-timestamp-down-means-later nil
2852 "Non-nil means S-down will increase the time in a time stamp.
2853 When nil, S-up will increase."
2854 :group 'org-time
2855 :type 'boolean)
2857 (defcustom org-calendar-follow-timestamp-change t
2858 "Non-nil means make the calendar window follow timestamp changes.
2859 When a timestamp is modified and the calendar window is visible, it will be
2860 moved to the new date."
2861 :group 'org-time
2862 :type 'boolean)
2864 (defgroup org-tags nil
2865 "Options concerning tags in Org-mode."
2866 :tag "Org Tags"
2867 :group 'org)
2869 (defcustom org-tag-alist nil
2870 "List of tags allowed in Org-mode files.
2871 When this list is nil, Org-mode will base TAG input on what is already in the
2872 buffer.
2873 The value of this variable is an alist, the car of each entry must be a
2874 keyword as a string, the cdr may be a character that is used to select
2875 that tag through the fast-tag-selection interface.
2876 See the manual for details."
2877 :group 'org-tags
2878 :type '(repeat
2879 (choice
2880 (cons (string :tag "Tag name")
2881 (character :tag "Access char"))
2882 (list :tag "Start radio group"
2883 (const :startgroup)
2884 (option (string :tag "Group description")))
2885 (list :tag "End radio group"
2886 (const :endgroup)
2887 (option (string :tag "Group description")))
2888 (const :tag "New line" (:newline)))))
2890 (defcustom org-tag-persistent-alist nil
2891 "List of tags that will always appear in all Org-mode files.
2892 This is in addition to any in buffer settings or customizations
2893 of `org-tag-alist'.
2894 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2895 The value of this variable is an alist, the car of each entry must be a
2896 keyword as a string, the cdr may be a character that is used to select
2897 that tag through the fast-tag-selection interface.
2898 See the manual for details.
2899 To disable these tags on a per-file basis, insert anywhere in the file:
2900 #+STARTUP: noptag"
2901 :group 'org-tags
2902 :type '(repeat
2903 (choice
2904 (cons (string :tag "Tag name")
2905 (character :tag "Access char"))
2906 (const :tag "Start radio group" (:startgroup))
2907 (const :tag "End radio group" (:endgroup))
2908 (const :tag "New line" (:newline)))))
2910 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2911 "If non-nil, always offer completion for all tags of all agenda files.
2912 Instead of customizing this variable directly, you might want to
2913 set it locally for capture buffers, because there no list of
2914 tags in that file can be created dynamically (there are none).
2916 (add-hook 'org-capture-mode-hook
2917 (lambda ()
2918 (set (make-local-variable
2919 'org-complete-tags-always-offer-all-agenda-tags)
2920 t)))"
2921 :group 'org-tags
2922 :version "24.1"
2923 :type 'boolean)
2925 (defvar org-file-tags nil
2926 "List of tags that can be inherited by all entries in the file.
2927 The tags will be inherited if the variable `org-use-tag-inheritance'
2928 says they should be.
2929 This variable is populated from #+FILETAGS lines.")
2931 (defcustom org-use-fast-tag-selection 'auto
2932 "Non-nil means use fast tag selection scheme.
2933 This is a special interface to select and deselect tags with single keys.
2934 When nil, fast selection is never used.
2935 When the symbol `auto', fast selection is used if and only if selection
2936 characters for tags have been configured, either through the variable
2937 `org-tag-alist' or through a #+TAGS line in the buffer.
2938 When t, fast selection is always used and selection keys are assigned
2939 automatically if necessary."
2940 :group 'org-tags
2941 :type '(choice
2942 (const :tag "Always" t)
2943 (const :tag "Never" nil)
2944 (const :tag "When selection characters are configured" 'auto)))
2946 (defcustom org-fast-tag-selection-single-key nil
2947 "Non-nil means fast tag selection exits after first change.
2948 When nil, you have to press RET to exit it.
2949 During fast tag selection, you can toggle this flag with `C-c'.
2950 This variable can also have the value `expert'. In this case, the window
2951 displaying the tags menu is not even shown, until you press C-c again."
2952 :group 'org-tags
2953 :type '(choice
2954 (const :tag "No" nil)
2955 (const :tag "Yes" t)
2956 (const :tag "Expert" expert)))
2958 (defvar org-fast-tag-selection-include-todo nil
2959 "Non-nil means fast tags selection interface will also offer TODO states.
2960 This is an undocumented feature, you should not rely on it.")
2962 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2963 "The column to which tags should be indented in a headline.
2964 If this number is positive, it specifies the column. If it is negative,
2965 it means that the tags should be flushright to that column. For example,
2966 -80 works well for a normal 80 character screen.
2967 When 0, place tags directly after headline text, with only one space in
2968 between."
2969 :group 'org-tags
2970 :type 'integer)
2972 (defcustom org-auto-align-tags t
2973 "Non-nil keeps tags aligned when modifying headlines.
2974 Some operations (i.e. demoting) change the length of a headline and
2975 therefore shift the tags around. With this option turned on, after
2976 each such operation the tags are again aligned to `org-tags-column'."
2977 :group 'org-tags
2978 :type 'boolean)
2980 (defcustom org-use-tag-inheritance t
2981 "Non-nil means tags in levels apply also for sublevels.
2982 When nil, only the tags directly given in a specific line apply there.
2983 This may also be a list of tags that should be inherited, or a regexp that
2984 matches tags that should be inherited. Additional control is possible
2985 with the variable `org-tags-exclude-from-inheritance' which gives an
2986 explicit list of tags to be excluded from inheritance., even if the value of
2987 `org-use-tag-inheritance' would select it for inheritance.
2989 If this option is t, a match early-on in a tree can lead to a large
2990 number of matches in the subtree when constructing the agenda or creating
2991 a sparse tree. If you only want to see the first match in a tree during
2992 a search, check out the variable `org-tags-match-list-sublevels'."
2993 :group 'org-tags
2994 :type '(choice
2995 (const :tag "Not" nil)
2996 (const :tag "Always" t)
2997 (repeat :tag "Specific tags" (string :tag "Tag"))
2998 (regexp :tag "Tags matched by regexp")))
3000 (defcustom org-tags-exclude-from-inheritance nil
3001 "List of tags that should never be inherited.
3002 This is a way to exclude a few tags from inheritance. For way to do
3003 the opposite, to actively allow inheritance for selected tags,
3004 see the variable `org-use-tag-inheritance'."
3005 :group 'org-tags
3006 :type '(repeat (string :tag "Tag")))
3008 (defun org-tag-inherit-p (tag)
3009 "Check if TAG is one that should be inherited."
3010 (cond
3011 ((member tag org-tags-exclude-from-inheritance) nil)
3012 ((eq org-use-tag-inheritance t) t)
3013 ((not org-use-tag-inheritance) nil)
3014 ((stringp org-use-tag-inheritance)
3015 (string-match org-use-tag-inheritance tag))
3016 ((listp org-use-tag-inheritance)
3017 (member tag org-use-tag-inheritance))
3018 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3020 (defcustom org-tags-match-list-sublevels t
3021 "Non-nil means list also sublevels of headlines matching a search.
3022 This variable applies to tags/property searches, and also to stuck
3023 projects because this search is based on a tags match as well.
3025 When set to the symbol `indented', sublevels are indented with
3026 leading dots.
3028 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3029 the sublevels of a headline matching a tag search often also match
3030 the same search. Listing all of them can create very long lists.
3031 Setting this variable to nil causes subtrees of a match to be skipped.
3033 This variable is semi-obsolete and probably should always be true. It
3034 is better to limit inheritance to certain tags using the variables
3035 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3036 :group 'org-tags
3037 :type '(choice
3038 (const :tag "No, don't list them" nil)
3039 (const :tag "Yes, do list them" t)
3040 (const :tag "List them, indented with leading dots" indented)))
3042 (defcustom org-tags-sort-function nil
3043 "When set, tags are sorted using this function as a comparator."
3044 :group 'org-tags
3045 :type '(choice
3046 (const :tag "No sorting" nil)
3047 (const :tag "Alphabetical" string<)
3048 (const :tag "Reverse alphabetical" string>)
3049 (function :tag "Custom function" nil)))
3051 (defvar org-tags-history nil
3052 "History of minibuffer reads for tags.")
3053 (defvar org-last-tags-completion-table nil
3054 "The last used completion table for tags.")
3055 (defvar org-after-tags-change-hook nil
3056 "Hook that is run after the tags in a line have changed.")
3058 (defgroup org-properties nil
3059 "Options concerning properties in Org-mode."
3060 :tag "Org Properties"
3061 :group 'org)
3063 (defcustom org-property-format "%-10s %s"
3064 "How property key/value pairs should be formatted by `indent-line'.
3065 When `indent-line' hits a property definition, it will format the line
3066 according to this format, mainly to make sure that the values are
3067 lined-up with respect to each other."
3068 :group 'org-properties
3069 :type 'string)
3071 (defcustom org-properties-postprocess-alist nil
3072 "Alist of properties and functions to adjust inserted values.
3073 Elements of this alist must be of the form
3075 ([string] [function])
3077 where [string] must be a property name and [function] must be a
3078 lambda expression: this lambda expression must take one argument,
3079 the value to adjust, and return the new value as a string.
3081 For example, this element will allow the property \"Remaining\"
3082 to be updated wrt the relation between the \"Effort\" property
3083 and the clock summary:
3085 ((\"Remaining\" (lambda(value)
3086 (let ((clocksum (org-clock-sum-current-item))
3087 (effort (org-duration-string-to-minutes
3088 (org-entry-get (point) \"Effort\"))))
3089 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3090 :group 'org-properties
3091 :version "24.1"
3092 :type '(alist :key-type (string :tag "Property")
3093 :value-type (function :tag "Function")))
3095 (defcustom org-use-property-inheritance nil
3096 "Non-nil means properties apply also for sublevels.
3098 This setting is chiefly used during property searches. Turning it on can
3099 cause significant overhead when doing a search, which is why it is not
3100 on by default.
3102 When nil, only the properties directly given in the current entry count.
3103 When t, every property is inherited. The value may also be a list of
3104 properties that should have inheritance, or a regular expression matching
3105 properties that should be inherited.
3107 However, note that some special properties use inheritance under special
3108 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3109 and the properties ending in \"_ALL\" when they are used as descriptor
3110 for valid values of a property.
3112 Note for programmers:
3113 When querying an entry with `org-entry-get', you can control if inheritance
3114 should be used. By default, `org-entry-get' looks only at the local
3115 properties. You can request inheritance by setting the inherit argument
3116 to t (to force inheritance) or to `selective' (to respect the setting
3117 in this variable)."
3118 :group 'org-properties
3119 :type '(choice
3120 (const :tag "Not" nil)
3121 (const :tag "Always" t)
3122 (repeat :tag "Specific properties" (string :tag "Property"))
3123 (regexp :tag "Properties matched by regexp")))
3125 (defun org-property-inherit-p (property)
3126 "Check if PROPERTY is one that should be inherited."
3127 (cond
3128 ((eq org-use-property-inheritance t) t)
3129 ((not org-use-property-inheritance) nil)
3130 ((stringp org-use-property-inheritance)
3131 (string-match org-use-property-inheritance property))
3132 ((listp org-use-property-inheritance)
3133 (member property org-use-property-inheritance))
3134 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3136 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3137 "The default column format, if no other format has been defined.
3138 This variable can be set on the per-file basis by inserting a line
3140 #+COLUMNS: %25ITEM ....."
3141 :group 'org-properties
3142 :type 'string)
3144 (defcustom org-columns-ellipses ".."
3145 "The ellipses to be used when a field in column view is truncated.
3146 When this is the empty string, as many characters as possible are shown,
3147 but then there will be no visual indication that the field has been truncated.
3148 When this is a string of length N, the last N characters of a truncated
3149 field are replaced by this string. If the column is narrower than the
3150 ellipses string, only part of the ellipses string will be shown."
3151 :group 'org-properties
3152 :type 'string)
3154 (defcustom org-columns-modify-value-for-display-function nil
3155 "Function that modifies values for display in column view.
3156 For example, it can be used to cut out a certain part from a time stamp.
3157 The function must take 2 arguments:
3159 column-title The title of the column (*not* the property name)
3160 value The value that should be modified.
3162 The function should return the value that should be displayed,
3163 or nil if the normal value should be used."
3164 :group 'org-properties
3165 :type 'function)
3167 (defcustom org-effort-property "Effort"
3168 "The property that is being used to keep track of effort estimates.
3169 Effort estimates given in this property need to have the format H:MM."
3170 :group 'org-properties
3171 :group 'org-progress
3172 :type '(string :tag "Property"))
3174 (defconst org-global-properties-fixed
3175 '(("VISIBILITY_ALL" . "folded children content all")
3176 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3177 "List of property/value pairs that can be inherited by any entry.
3179 These are fixed values, for the preset properties. The user variable
3180 that can be used to add to this list is `org-global-properties'.
3182 The entries in this list are cons cells where the car is a property
3183 name and cdr is a string with the value. If the value represents
3184 multiple items like an \"_ALL\" property, separate the items by
3185 spaces.")
3187 (defcustom org-global-properties nil
3188 "List of property/value pairs that can be inherited by any entry.
3190 This list will be combined with the constant `org-global-properties-fixed'.
3192 The entries in this list are cons cells where the car is a property
3193 name and cdr is a string with the value.
3195 You can set buffer-local values for the same purpose in the variable
3196 `org-file-properties' this by adding lines like
3198 #+PROPERTY: NAME VALUE"
3199 :group 'org-properties
3200 :type '(repeat
3201 (cons (string :tag "Property")
3202 (string :tag "Value"))))
3204 (defvar org-file-properties nil
3205 "List of property/value pairs that can be inherited by any entry.
3206 Valid for the current buffer.
3207 This variable is populated from #+PROPERTY lines.")
3208 (make-variable-buffer-local 'org-file-properties)
3210 (defgroup org-agenda nil
3211 "Options concerning agenda views in Org-mode."
3212 :tag "Org Agenda"
3213 :group 'org)
3215 (defvar org-category nil
3216 "Variable used by org files to set a category for agenda display.
3217 Such files should use a file variable to set it, for example
3219 # -*- mode: org; org-category: \"ELisp\"
3221 or contain a special line
3223 #+CATEGORY: ELisp
3225 If the file does not specify a category, then file's base name
3226 is used instead.")
3227 (make-variable-buffer-local 'org-category)
3228 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3230 (defcustom org-agenda-files nil
3231 "The files to be used for agenda display.
3232 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3233 \\[org-remove-file]. You can also use customize to edit the list.
3235 If an entry is a directory, all files in that directory that are matched by
3236 `org-agenda-file-regexp' will be part of the file list.
3238 If the value of the variable is not a list but a single file name, then
3239 the list of agenda files is actually stored and maintained in that file, one
3240 agenda file per line. In this file paths can be given relative to
3241 `org-directory'. Tilde expansion and environment variable substitution
3242 are also made."
3243 :group 'org-agenda
3244 :type '(choice
3245 (repeat :tag "List of files and directories" file)
3246 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3248 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3249 "Regular expression to match files for `org-agenda-files'.
3250 If any element in the list in that variable contains a directory instead
3251 of a normal file, all files in that directory that are matched by this
3252 regular expression will be included."
3253 :group 'org-agenda
3254 :type 'regexp)
3256 (defcustom org-agenda-text-search-extra-files nil
3257 "List of extra files to be searched by text search commands.
3258 These files will be search in addition to the agenda files by the
3259 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3260 Note that these files will only be searched for text search commands,
3261 not for the other agenda views like todo lists, tag searches or the weekly
3262 agenda. This variable is intended to list notes and possibly archive files
3263 that should also be searched by these two commands.
3264 In fact, if the first element in the list is the symbol `agenda-archives',
3265 than all archive files of all agenda files will be added to the search
3266 scope."
3267 :group 'org-agenda
3268 :type '(set :greedy t
3269 (const :tag "Agenda Archives" agenda-archives)
3270 (repeat :inline t (file))))
3272 (if (fboundp 'defvaralias)
3273 (defvaralias 'org-agenda-multi-occur-extra-files
3274 'org-agenda-text-search-extra-files))
3276 (defcustom org-agenda-skip-unavailable-files nil
3277 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3278 A nil value means to remove them, after a query, from the list."
3279 :group 'org-agenda
3280 :type 'boolean)
3282 (defcustom org-calendar-to-agenda-key [?c]
3283 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3284 The command `org-calendar-goto-agenda' will be bound to this key. The
3285 default is the character `c' because then `c' can be used to switch back and
3286 forth between agenda and calendar."
3287 :group 'org-agenda
3288 :type 'sexp)
3290 (defcustom org-calendar-agenda-action-key [?k]
3291 "The key to be installed in `calendar-mode-map' for agenda-action.
3292 The command `org-agenda-action' will be bound to this key. The
3293 default is the character `k' because we use the same key in the agenda."
3294 :group 'org-agenda
3295 :type 'sexp)
3297 (defcustom org-calendar-insert-diary-entry-key [?i]
3298 "The key to be installed in `calendar-mode-map' for adding diary entries.
3299 This option is irrelevant until `org-agenda-diary-file' has been configured
3300 to point to an Org-mode file. When that is the case, the command
3301 `org-agenda-diary-entry' will be bound to the key given here, by default
3302 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3303 if you want to continue doing this, you need to change this to a different
3304 key."
3305 :group 'org-agenda
3306 :type 'sexp)
3308 (defcustom org-agenda-diary-file 'diary-file
3309 "File to which to add new entries with the `i' key in agenda and calendar.
3310 When this is the symbol `diary-file', the functionality in the Emacs
3311 calendar will be used to add entries to the `diary-file'. But when this
3312 points to a file, `org-agenda-diary-entry' will be used instead."
3313 :group 'org-agenda
3314 :type '(choice
3315 (const :tag "The standard Emacs diary file" diary-file)
3316 (file :tag "Special Org file diary entries")))
3318 (eval-after-load "calendar"
3319 '(progn
3320 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3321 'org-calendar-goto-agenda)
3322 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3323 'org-agenda-action)
3324 (add-hook 'calendar-mode-hook
3325 (lambda ()
3326 (unless (eq org-agenda-diary-file 'diary-file)
3327 (define-key calendar-mode-map
3328 org-calendar-insert-diary-entry-key
3329 'org-agenda-diary-entry))))))
3331 (defgroup org-latex nil
3332 "Options for embedding LaTeX code into Org-mode."
3333 :tag "Org LaTeX"
3334 :group 'org)
3336 (defcustom org-format-latex-options
3337 '(:foreground default :background default :scale 1.0
3338 :html-foreground "Black" :html-background "Transparent"
3339 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3340 "Options for creating images from LaTeX fragments.
3341 This is a property list with the following properties:
3342 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3343 `default' means use the foreground of the default face.
3344 :background the background color, or \"Transparent\".
3345 `default' means use the background of the default face.
3346 :scale a scaling factor for the size of the images, to get more pixels
3347 :html-foreground, :html-background, :html-scale
3348 the same numbers for HTML export.
3349 :matchers a list indicating which matchers should be used to
3350 find LaTeX fragments. Valid members of this list are:
3351 \"begin\" find environments
3352 \"$1\" find single characters surrounded by $.$
3353 \"$\" find math expressions surrounded by $...$
3354 \"$$\" find math expressions surrounded by $$....$$
3355 \"\\(\" find math expressions surrounded by \\(...\\)
3356 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3357 :group 'org-latex
3358 :type 'plist)
3360 (defcustom org-format-latex-signal-error t
3361 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3362 When nil, just push out a message."
3363 :group 'org-latex
3364 :version "24.1"
3365 :type 'boolean)
3367 (defcustom org-latex-to-mathml-jar-file nil
3368 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3369 Use this to specify additional executable file say a jar file.
3371 When using MathToWeb as the converter, specify the full-path to
3372 your mathtoweb.jar file."
3373 :group 'org-latex
3374 :version "24.1"
3375 :type '(choice
3376 (const :tag "None" nil)
3377 (file :tag "JAR file" :must-match t)))
3379 (defcustom org-latex-to-mathml-convert-command nil
3380 "Command to convert LaTeX fragments to MathML.
3381 Replace format-specifiers in the command as noted below and use
3382 `shell-command' to convert LaTeX to MathML.
3383 %j: Executable file in fully expanded form as specified by
3384 `org-latex-to-mathml-jar-file'.
3385 %I: Input LaTeX file in fully expanded form
3386 %o: Output MathML file
3387 This command is used by `org-create-math-formula'.
3389 When using MathToWeb as the converter, set this to
3390 \"java -jar %j -unicode -force -df %o %I\"."
3391 :group 'org-latex
3392 :version "24.1"
3393 :type '(choice
3394 (const :tag "None" nil)
3395 (string :tag "\nShell command")))
3397 (defcustom org-latex-create-formula-image-program 'dvipng
3398 "Program to convert LaTeX fragments with.
3400 dvipng Process the LaTeX fragments to dvi file, then convert
3401 dvi files to png files using dvipng.
3402 This will also include processing of non-math environments.
3403 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3404 to convert pdf files to png files"
3405 :group 'org-latex
3406 :version "24.1"
3407 :type '(choice
3408 (const :tag "dvipng" dvipng)
3409 (const :tag "imagemagick" imagemagick)))
3411 (defun org-format-latex-mathml-available-p ()
3412 "Return t if `org-latex-to-mathml-convert-command' is usable."
3413 (save-match-data
3414 (when (and (boundp 'org-latex-to-mathml-convert-command)
3415 org-latex-to-mathml-convert-command)
3416 (let ((executable (car (split-string
3417 org-latex-to-mathml-convert-command))))
3418 (when (executable-find executable)
3419 (if (string-match
3420 "%j" org-latex-to-mathml-convert-command)
3421 (file-readable-p org-latex-to-mathml-jar-file)
3422 t))))))
3424 (defcustom org-format-latex-header "\\documentclass{article}
3425 \\usepackage[usenames]{color}
3426 \\usepackage{amsmath}
3427 \\usepackage[mathscr]{eucal}
3428 \\pagestyle{empty} % do not remove
3429 \[PACKAGES]
3430 \[DEFAULT-PACKAGES]
3431 % The settings below are copied from fullpage.sty
3432 \\setlength{\\textwidth}{\\paperwidth}
3433 \\addtolength{\\textwidth}{-3cm}
3434 \\setlength{\\oddsidemargin}{1.5cm}
3435 \\addtolength{\\oddsidemargin}{-2.54cm}
3436 \\setlength{\\evensidemargin}{\\oddsidemargin}
3437 \\setlength{\\textheight}{\\paperheight}
3438 \\addtolength{\\textheight}{-\\headheight}
3439 \\addtolength{\\textheight}{-\\headsep}
3440 \\addtolength{\\textheight}{-\\footskip}
3441 \\addtolength{\\textheight}{-3cm}
3442 \\setlength{\\topmargin}{1.5cm}
3443 \\addtolength{\\topmargin}{-2.54cm}"
3444 "The document header used for processing LaTeX fragments.
3445 It is imperative that this header make sure that no page number
3446 appears on the page. The package defined in the variables
3447 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3448 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3449 will be appended."
3450 :group 'org-latex
3451 :type 'string)
3453 (defvar org-format-latex-header-extra nil)
3455 (defun org-set-packages-alist (var val)
3456 "Set the packages alist and make sure it has 3 elements per entry."
3457 (set var (mapcar (lambda (x)
3458 (if (and (consp x) (= (length x) 2))
3459 (list (car x) (nth 1 x) t)
3461 val)))
3463 (defun org-get-packages-alist (var)
3465 "Get the packages alist and make sure it has 3 elements per entry."
3466 (mapcar (lambda (x)
3467 (if (and (consp x) (= (length x) 2))
3468 (list (car x) (nth 1 x) t)
3470 (default-value var)))
3472 ;; The following variables are defined here because is it also used
3473 ;; when formatting latex fragments. Originally it was part of the
3474 ;; LaTeX exporter, which is why the name includes "export".
3475 (defcustom org-export-latex-default-packages-alist
3476 '(("AUTO" "inputenc" t)
3477 ("T1" "fontenc" t)
3478 ("" "fixltx2e" nil)
3479 ("" "graphicx" t)
3480 ("" "longtable" nil)
3481 ("" "float" nil)
3482 ("" "wrapfig" nil)
3483 ("" "soul" t)
3484 ("" "textcomp" t)
3485 ("" "marvosym" t)
3486 ("" "wasysym" t)
3487 ("" "latexsym" t)
3488 ("" "amssymb" t)
3489 ("" "hyperref" nil)
3490 "\\tolerance=1000"
3492 "Alist of default packages to be inserted in the header.
3493 Change this only if one of the packages here causes an incompatibility
3494 with another package you are using.
3495 The packages in this list are needed by one part or another of Org-mode
3496 to function properly.
3498 - inputenc, fontenc: for basic font and character selection
3499 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3500 for interpreting the entities in `org-entities'. You can skip some of these
3501 packages if you don't use any of the symbols in it.
3502 - graphicx: for including images
3503 - float, wrapfig: for figure placement
3504 - longtable: for long tables
3505 - hyperref: for cross references
3507 Therefore you should not modify this variable unless you know what you
3508 are doing. The one reason to change it anyway is that you might be loading
3509 some other package that conflicts with one of the default packages.
3510 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3511 If SNIPPET-FLAG is t, the package also needs to be included when
3512 compiling LaTeX snippets into images for inclusion into HTML."
3513 :group 'org-export-latex
3514 :set 'org-set-packages-alist
3515 :get 'org-get-packages-alist
3516 :version "24.1"
3517 :type '(repeat
3518 (choice
3519 (list :tag "options/package pair"
3520 (string :tag "options")
3521 (string :tag "package")
3522 (boolean :tag "Snippet"))
3523 (string :tag "A line of LaTeX"))))
3525 (defcustom org-export-latex-packages-alist nil
3526 "Alist of packages to be inserted in every LaTeX header.
3527 These will be inserted after `org-export-latex-default-packages-alist'.
3528 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3529 SNIPPET-FLAG, when t, indicates that this package is also needed when
3530 turning LaTeX snippets into images for inclusion into HTML.
3531 Make sure that you only list packages here which:
3532 - you want in every file
3533 - do not conflict with the default packages in
3534 `org-export-latex-default-packages-alist'
3535 - do not conflict with the setup in `org-format-latex-header'."
3536 :group 'org-export-latex
3537 :set 'org-set-packages-alist
3538 :get 'org-get-packages-alist
3539 :type '(repeat
3540 (choice
3541 (list :tag "options/package pair"
3542 (string :tag "options")
3543 (string :tag "package")
3544 (boolean :tag "Snippet"))
3545 (string :tag "A line of LaTeX"))))
3548 (defgroup org-appearance nil
3549 "Settings for Org-mode appearance."
3550 :tag "Org Appearance"
3551 :group 'org)
3553 (defcustom org-level-color-stars-only nil
3554 "Non-nil means fontify only the stars in each headline.
3555 When nil, the entire headline is fontified.
3556 Changing it requires restart of `font-lock-mode' to become effective
3557 also in regions already fontified."
3558 :group 'org-appearance
3559 :type 'boolean)
3561 (defcustom org-hide-leading-stars nil
3562 "Non-nil means hide the first N-1 stars in a headline.
3563 This works by using the face `org-hide' for these stars. This
3564 face is white for a light background, and black for a dark
3565 background. You may have to customize the face `org-hide' to
3566 make this work.
3567 Changing it requires restart of `font-lock-mode' to become effective
3568 also in regions already fontified.
3569 You may also set this on a per-file basis by adding one of the following
3570 lines to the buffer:
3572 #+STARTUP: hidestars
3573 #+STARTUP: showstars"
3574 :group 'org-appearance
3575 :type 'boolean)
3577 (defcustom org-hidden-keywords nil
3578 "List of symbols corresponding to keywords to be hidden the org buffer.
3579 For example, a value '(title) for this list will make the document's title
3580 appear in the buffer without the initial #+TITLE: keyword."
3581 :group 'org-appearance
3582 :version "24.1"
3583 :type '(set (const :tag "#+AUTHOR" author)
3584 (const :tag "#+DATE" date)
3585 (const :tag "#+EMAIL" email)
3586 (const :tag "#+TITLE" title)))
3588 (defcustom org-fontify-done-headline nil
3589 "Non-nil means change the face of a headline if it is marked DONE.
3590 Normally, only the TODO/DONE keyword indicates the state of a headline.
3591 When this is non-nil, the headline after the keyword is set to the
3592 `org-headline-done' as an additional indication."
3593 :group 'org-appearance
3594 :type 'boolean)
3596 (defcustom org-fontify-emphasized-text t
3597 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3598 Changing this variable requires a restart of Emacs to take effect."
3599 :group 'org-appearance
3600 :type 'boolean)
3602 (defcustom org-fontify-whole-heading-line nil
3603 "Non-nil means fontify the whole line for headings.
3604 This is useful when setting a background color for the
3605 org-level-* faces."
3606 :group 'org-appearance
3607 :type 'boolean)
3609 (defcustom org-highlight-latex-fragments-and-specials nil
3610 "Non-nil means fontify what is treated specially by the exporters."
3611 :group 'org-appearance
3612 :type 'boolean)
3614 (defcustom org-hide-emphasis-markers nil
3615 "Non-nil mean font-lock should hide the emphasis marker characters."
3616 :group 'org-appearance
3617 :type 'boolean)
3619 (defcustom org-pretty-entities nil
3620 "Non-nil means show entities as UTF8 characters.
3621 When nil, the \\name form remains in the buffer."
3622 :group 'org-appearance
3623 :version "24.1"
3624 :type 'boolean)
3626 (defcustom org-pretty-entities-include-sub-superscripts t
3627 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3628 :group 'org-appearance
3629 :version "24.1"
3630 :type 'boolean)
3632 (defvar org-emph-re nil
3633 "Regular expression for matching emphasis.
3634 After a match, the match groups contain these elements:
3635 0 The match of the full regular expression, including the characters
3636 before and after the proper match
3637 1 The character before the proper match, or empty at beginning of line
3638 2 The proper match, including the leading and trailing markers
3639 3 The leading marker like * or /, indicating the type of highlighting
3640 4 The text between the emphasis markers, not including the markers
3641 5 The character after the match, empty at the end of a line")
3642 (defvar org-verbatim-re nil
3643 "Regular expression for matching verbatim text.")
3644 (defvar org-emphasis-regexp-components) ; defined just below
3645 (defvar org-emphasis-alist) ; defined just below
3646 (defun org-set-emph-re (var val)
3647 "Set variable and compute the emphasis regular expression."
3648 (set var val)
3649 (when (and (boundp 'org-emphasis-alist)
3650 (boundp 'org-emphasis-regexp-components)
3651 org-emphasis-alist org-emphasis-regexp-components)
3652 (let* ((e org-emphasis-regexp-components)
3653 (pre (car e))
3654 (post (nth 1 e))
3655 (border (nth 2 e))
3656 (body (nth 3 e))
3657 (nl (nth 4 e))
3658 (body1 (concat body "*?"))
3659 (markers (mapconcat 'car org-emphasis-alist ""))
3660 (vmarkers (mapconcat
3661 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3662 org-emphasis-alist "")))
3663 ;; make sure special characters appear at the right position in the class
3664 (if (string-match "\\^" markers)
3665 (setq markers (concat (replace-match "" t t markers) "^")))
3666 (if (string-match "-" markers)
3667 (setq markers (concat (replace-match "" t t markers) "-")))
3668 (if (string-match "\\^" vmarkers)
3669 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3670 (if (string-match "-" vmarkers)
3671 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3672 (if (> nl 0)
3673 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3674 (int-to-string nl) "\\}")))
3675 ;; Make the regexp
3676 (setq org-emph-re
3677 (concat "\\([" pre "]\\|^\\)"
3678 "\\("
3679 "\\([" markers "]\\)"
3680 "\\("
3681 "[^" border "]\\|"
3682 "[^" border "]"
3683 body1
3684 "[^" border "]"
3685 "\\)"
3686 "\\3\\)"
3687 "\\([" post "]\\|$\\)"))
3688 (setq org-verbatim-re
3689 (concat "\\([" pre "]\\|^\\)"
3690 "\\("
3691 "\\([" vmarkers "]\\)"
3692 "\\("
3693 "[^" border "]\\|"
3694 "[^" border "]"
3695 body1
3696 "[^" border "]"
3697 "\\)"
3698 "\\3\\)"
3699 "\\([" post "]\\|$\\)")))))
3701 (defcustom org-emphasis-regexp-components
3702 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3703 "Components used to build the regular expression for emphasis.
3704 This is a list with five entries. Terminology: In an emphasis string
3705 like \" *strong word* \", we call the initial space PREMATCH, the final
3706 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3707 and \"trong wor\" is the body. The different components in this variable
3708 specify what is allowed/forbidden in each part:
3710 pre Chars allowed as prematch. Beginning of line will be allowed too.
3711 post Chars allowed as postmatch. End of line will be allowed too.
3712 border The chars *forbidden* as border characters.
3713 body-regexp A regexp like \".\" to match a body character. Don't use
3714 non-shy groups here, and don't allow newline here.
3715 newline The maximum number of newlines allowed in an emphasis exp.
3717 Use customize to modify this, or restart Emacs after changing it."
3718 :group 'org-appearance
3719 :set 'org-set-emph-re
3720 :type '(list
3721 (sexp :tag "Allowed chars in pre ")
3722 (sexp :tag "Allowed chars in post ")
3723 (sexp :tag "Forbidden chars in border ")
3724 (sexp :tag "Regexp for body ")
3725 (integer :tag "number of newlines allowed")
3726 (option (boolean :tag "Please ignore this button"))))
3728 (defcustom org-emphasis-alist
3729 `(("*" bold "<b>" "</b>")
3730 ("/" italic "<i>" "</i>")
3731 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3732 ("=" org-code "<code>" "</code>" verbatim)
3733 ("~" org-verbatim "<code>" "</code>" verbatim)
3734 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3735 "<del>" "</del>")
3737 "Special syntax for emphasized text.
3738 Text starting and ending with a special character will be emphasized, for
3739 example *bold*, _underlined_ and /italic/. This variable sets the marker
3740 characters, the face to be used by font-lock for highlighting in Org-mode
3741 Emacs buffers, and the HTML tags to be used for this.
3742 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3743 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3744 Use customize to modify this, or restart Emacs after changing it."
3745 :group 'org-appearance
3746 :set 'org-set-emph-re
3747 :type '(repeat
3748 (list
3749 (string :tag "Marker character")
3750 (choice
3751 (face :tag "Font-lock-face")
3752 (plist :tag "Face property list"))
3753 (string :tag "HTML start tag")
3754 (string :tag "HTML end tag")
3755 (option (const verbatim)))))
3757 (defvar org-protecting-blocks
3758 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3759 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3760 This is needed for font-lock setup.")
3762 ;;; Miscellaneous options
3764 (defgroup org-completion nil
3765 "Completion in Org-mode."
3766 :tag "Org Completion"
3767 :group 'org)
3769 (defcustom org-completion-use-ido nil
3770 "Non-nil means use ido completion wherever possible.
3771 Note that `ido-mode' must be active for this variable to be relevant.
3772 If you decide to turn this variable on, you might well want to turn off
3773 `org-outline-path-complete-in-steps'.
3774 See also `org-completion-use-iswitchb'."
3775 :group 'org-completion
3776 :type 'boolean)
3778 (defcustom org-completion-use-iswitchb nil
3779 "Non-nil means use iswitchb completion wherever possible.
3780 Note that `iswitchb-mode' must be active for this variable to be relevant.
3781 If you decide to turn this variable on, you might well want to turn off
3782 `org-outline-path-complete-in-steps'.
3783 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3784 :group 'org-completion
3785 :type 'boolean)
3787 (defcustom org-completion-fallback-command 'hippie-expand
3788 "The expansion command called by \\[pcomplete] in normal context.
3789 Normal means, no org-mode-specific context."
3790 :group 'org-completion
3791 :type 'function)
3793 ;;; Functions and variables from their packages
3794 ;; Declared here to avoid compiler warnings
3796 ;; XEmacs only
3797 (defvar outline-mode-menu-heading)
3798 (defvar outline-mode-menu-show)
3799 (defvar outline-mode-menu-hide)
3800 (defvar zmacs-regions) ; XEmacs regions
3802 ;; Emacs only
3803 (defvar mark-active)
3805 ;; Various packages
3806 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3807 (declare-function calendar-forward-day "cal-move" (arg))
3808 (declare-function calendar-goto-date "cal-move" (date))
3809 (declare-function calendar-goto-today "cal-move" ())
3810 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3811 (defvar calc-embedded-close-formula)
3812 (defvar calc-embedded-open-formula)
3813 (declare-function cdlatex-tab "ext:cdlatex" ())
3814 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3815 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3816 (defvar font-lock-unfontify-region-function)
3817 (declare-function iswitchb-read-buffer "iswitchb"
3818 (prompt &optional default require-match start matches-set))
3819 (defvar iswitchb-temp-buflist)
3820 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3821 (defvar org-agenda-tags-todo-honor-ignore-options)
3822 (declare-function org-agenda-skip "org-agenda" ())
3823 (declare-function
3824 org-agenda-format-item "org-agenda"
3825 (extra txt &optional category tags dotime noprefix remove-re habitp))
3826 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3827 (declare-function org-agenda-change-all-lines "org-agenda"
3828 (newhead hdmarker &optional fixface just-this))
3829 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3830 (declare-function org-agenda-maybe-redo "org-agenda" ())
3831 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3832 (beg end))
3833 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3834 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3835 "org-agenda" (&optional end))
3836 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3837 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3838 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3839 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3840 (declare-function org-indent-mode "org-indent" (&optional arg))
3841 (declare-function parse-time-string "parse-time" (string))
3842 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3843 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3844 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3845 (defvar remember-data-file)
3846 (defvar texmathp-why)
3847 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3848 (declare-function table--at-cell-p "table" (position &optional object at-column))
3850 (defvar w3m-current-url)
3851 (defvar w3m-current-title)
3853 (defvar org-latex-regexps)
3855 ;;; Autoload and prepare some org modules
3857 ;; Some table stuff that needs to be defined here, because it is used
3858 ;; by the functions setting up org-mode or checking for table context.
3860 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3861 "Detect an org-type or table-type table.")
3862 (defconst org-table-line-regexp "^[ \t]*|"
3863 "Detect an org-type table line.")
3864 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3865 "Detect an org-type table line.")
3866 (defconst org-table-hline-regexp "^[ \t]*|-"
3867 "Detect an org-type table hline.")
3868 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3869 "Detect a table-type table hline.")
3870 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3871 "Detect the first line outside a table when searching from within it.
3872 This works for both table types.")
3874 ;; Autoload the functions in org-table.el that are needed by functions here.
3876 (eval-and-compile
3877 (org-autoload "org-table"
3878 '(org-table-align org-table-begin org-table-blank-field
3879 org-table-convert org-table-convert-region org-table-copy-down
3880 org-table-copy-region org-table-create
3881 org-table-create-or-convert-from-region
3882 org-table-create-with-table.el org-table-current-dline
3883 org-table-cut-region org-table-delete-column org-table-edit-field
3884 org-table-edit-formulas org-table-end org-table-eval-formula
3885 org-table-export org-table-field-info
3886 org-table-get-stored-formulas org-table-goto-column
3887 org-table-hline-and-move org-table-import org-table-insert-column
3888 org-table-insert-hline org-table-insert-row org-table-iterate
3889 org-table-justify-field-maybe org-table-kill-row
3890 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3891 org-table-move-column org-table-move-column-left
3892 org-table-move-column-right org-table-move-row
3893 org-table-move-row-down org-table-move-row-up
3894 org-table-next-field org-table-next-row org-table-paste-rectangle
3895 org-table-previous-field org-table-recalculate
3896 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3897 org-table-toggle-coordinate-overlays
3898 org-table-toggle-formula-debugger org-table-wrap-region
3899 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3900 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3901 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3903 (defun org-at-table-p (&optional table-type)
3904 "Return t if the cursor is inside an org-type table.
3905 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3906 (if org-enable-table-editor
3907 (save-excursion
3908 (beginning-of-line 1)
3909 (looking-at (if table-type org-table-any-line-regexp
3910 org-table-line-regexp)))
3911 nil))
3912 (defsubst org-table-p () (org-at-table-p))
3914 (defun org-at-table.el-p ()
3915 "Return t if and only if we are at a table.el table."
3916 (and (org-at-table-p 'any)
3917 (save-excursion
3918 (goto-char (org-table-begin 'any))
3919 (looking-at org-table1-hline-regexp))))
3920 (defun org-table-recognize-table.el ()
3921 "If there is a table.el table nearby, recognize it and move into it."
3922 (if org-table-tab-recognizes-table.el
3923 (if (org-at-table.el-p)
3924 (progn
3925 (beginning-of-line 1)
3926 (if (looking-at org-table-dataline-regexp)
3928 (if (looking-at org-table1-hline-regexp)
3929 (progn
3930 (beginning-of-line 2)
3931 (if (looking-at org-table-any-border-regexp)
3932 (beginning-of-line -1)))))
3933 (if (re-search-forward "|" (org-table-end t) t)
3934 (progn
3935 (require 'table)
3936 (if (table--at-cell-p (point))
3938 (message "recognizing table.el table...")
3939 (table-recognize-table)
3940 (message "recognizing table.el table...done")))
3941 (error "This should not happen"))
3943 nil)
3944 nil))
3946 (defun org-at-table-hline-p ()
3947 "Return t if the cursor is inside a hline in a table."
3948 (if org-enable-table-editor
3949 (save-excursion
3950 (beginning-of-line 1)
3951 (looking-at org-table-hline-regexp))
3952 nil))
3954 (defvar org-table-clean-did-remove-column nil)
3956 (defun org-table-map-tables (function &optional quietly)
3957 "Apply FUNCTION to the start of all tables in the buffer."
3958 (save-excursion
3959 (save-restriction
3960 (widen)
3961 (goto-char (point-min))
3962 (while (re-search-forward org-table-any-line-regexp nil t)
3963 (unless quietly
3964 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3965 (beginning-of-line 1)
3966 (when (and (looking-at org-table-line-regexp)
3967 ;; Exclude tables in src/example/verbatim/clocktable blocks
3968 (not (org-in-block-p '("src" "example"))))
3969 (save-excursion (funcall function))
3970 (or (looking-at org-table-line-regexp)
3971 (forward-char 1)))
3972 (re-search-forward org-table-any-border-regexp nil 1))))
3973 (unless quietly (message "Mapping tables: done")))
3975 ;; Declare and autoload functions from org-exp.el & Co
3977 (declare-function org-default-export-plist "org-exp")
3978 (declare-function org-infile-export-plist "org-exp")
3979 (declare-function org-get-current-options "org-exp")
3980 (eval-and-compile
3981 (org-autoload "org-exp"
3982 '(org-export org-export-visible
3983 org-insert-export-options-template
3984 org-table-clean-before-export))
3985 (org-autoload "org-ascii"
3986 '(org-export-as-ascii org-export-ascii-preprocess
3987 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3988 org-export-region-as-ascii))
3989 (org-autoload "org-latex"
3990 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3991 org-replace-region-by-latex org-export-region-as-latex
3992 org-export-as-latex org-export-as-pdf
3993 org-export-as-pdf-and-open))
3994 (org-autoload "org-html"
3995 '(org-export-as-html-and-open
3996 org-export-as-html-batch org-export-as-html-to-buffer
3997 org-replace-region-by-html org-export-region-as-html
3998 org-export-as-html))
3999 (org-autoload "org-docbook"
4000 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4001 org-replace-region-by-docbook org-export-region-as-docbook
4002 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4003 org-export-as-docbook))
4004 (org-autoload "org-icalendar"
4005 '(org-export-icalendar-this-file
4006 org-export-icalendar-all-agenda-files
4007 org-export-icalendar-combine-agenda-files))
4008 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4009 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4011 ;; Declare and autoload functions from org-agenda.el
4013 (eval-and-compile
4014 (org-autoload "org-agenda"
4015 '(org-agenda org-agenda-list org-search-view
4016 org-todo-list org-tags-view org-agenda-list-stuck-projects
4017 org-diary org-agenda-to-appt
4018 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4020 ;; Autoload org-remember
4022 (eval-and-compile
4023 (org-autoload "org-remember"
4024 '(org-remember-insinuate org-remember-annotation
4025 org-remember-apply-template org-remember org-remember-handler)))
4027 (eval-and-compile
4028 (org-autoload "org-capture"
4029 '(org-capture org-capture-insert-template-here
4030 org-capture-import-remember-templates)))
4032 ;; Autoload org-clock.el
4034 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4035 (beg end))
4036 (declare-function org-clock-update-mode-line "org-clock" ())
4037 (declare-function org-resolve-clocks "org-clock"
4038 (&optional also-non-dangling-p prompt last-valid))
4039 (defvar org-clock-start-time)
4040 (defvar org-clock-marker (make-marker)
4041 "Marker recording the last clock-in.")
4042 (defvar org-clock-hd-marker (make-marker)
4043 "Marker recording the last clock-in, but the headline position.")
4044 (defvar org-clock-heading ""
4045 "The heading of the current clock entry.")
4046 (defun org-clock-is-active ()
4047 "Return non-nil if clock is currently running.
4048 The return value is actually the clock marker."
4049 (marker-buffer org-clock-marker))
4051 (eval-and-compile
4052 (org-autoload
4053 "org-clock"
4054 '(org-clock-in org-clock-out org-clock-cancel
4055 org-clock-goto org-clock-sum org-clock-display
4056 org-clock-remove-overlays org-clock-report
4057 org-clocktable-shift org-dblock-write:clocktable
4058 org-get-clocktable org-resolve-clocks)))
4060 (defun org-clock-update-time-maybe ()
4061 "If this is a CLOCK line, update it and return t.
4062 Otherwise, return nil."
4063 (interactive)
4064 (save-excursion
4065 (beginning-of-line 1)
4066 (skip-chars-forward " \t")
4067 (when (looking-at org-clock-string)
4068 (let ((re (concat "[ \t]*" org-clock-string
4069 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4070 "\\([ \t]*=>.*\\)?\\)?"))
4071 ts te h m s neg)
4072 (cond
4073 ((not (looking-at re))
4074 nil)
4075 ((not (match-end 2))
4076 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4077 (> org-clock-marker (point))
4078 (<= org-clock-marker (point-at-eol)))
4079 ;; The clock is running here
4080 (setq org-clock-start-time
4081 (apply 'encode-time
4082 (org-parse-time-string (match-string 1))))
4083 (org-clock-update-mode-line)))
4085 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4086 (end-of-line 1)
4087 (setq ts (match-string 1)
4088 te (match-string 3))
4089 (setq s (- (org-float-time
4090 (apply 'encode-time (org-parse-time-string te)))
4091 (org-float-time
4092 (apply 'encode-time (org-parse-time-string ts))))
4093 neg (< s 0)
4094 s (abs s)
4095 h (floor (/ s 3600))
4096 s (- s (* 3600 h))
4097 m (floor (/ s 60))
4098 s (- s (* 60 s)))
4099 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4100 t))))))
4102 (defun org-check-running-clock ()
4103 "Check if the current buffer contains the running clock.
4104 If yes, offer to stop it and to save the buffer with the changes."
4105 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4106 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4107 (buffer-name))))
4108 (org-clock-out)
4109 (when (y-or-n-p "Save changed buffer?")
4110 (save-buffer))))
4112 (defun org-clocktable-try-shift (dir n)
4113 "Check if this line starts a clock table, if yes, shift the time block."
4114 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4115 (org-clocktable-shift dir n)))
4117 ;; Autoload org-timer.el
4119 (eval-and-compile
4120 (org-autoload
4121 "org-timer"
4122 '(org-timer-start org-timer org-timer-item
4123 org-timer-change-times-in-region
4124 org-timer-set-timer
4125 org-timer-reset-timers
4126 org-timer-show-remaining-time)))
4128 ;; Autoload org-feed.el
4130 (eval-and-compile
4131 (org-autoload
4132 "org-feed"
4133 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4136 ;; Autoload org-indent.el
4138 ;; Define the variable already here, to make sure we have it.
4139 (defvar org-indent-mode nil
4140 "Non-nil if Org-Indent mode is enabled.
4141 Use the command `org-indent-mode' to change this variable.")
4143 (eval-and-compile
4144 (org-autoload
4145 "org-indent"
4146 '(org-indent-mode)))
4148 ;; Autoload org-mobile.el
4150 (eval-and-compile
4151 (org-autoload
4152 "org-mobile"
4153 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4155 ;; Autoload archiving code
4156 ;; The stuff that is needed for cycling and tags has to be defined here.
4158 (defgroup org-archive nil
4159 "Options concerning archiving in Org-mode."
4160 :tag "Org Archive"
4161 :group 'org-structure)
4163 (defcustom org-archive-location "%s_archive::"
4164 "The location where subtrees should be archived.
4166 The value of this variable is a string, consisting of two parts,
4167 separated by a double-colon. The first part is a filename and
4168 the second part is a headline.
4170 When the filename is omitted, archiving happens in the same file.
4171 %s in the filename will be replaced by the current file
4172 name (without the directory part). Archiving to a different file
4173 is useful to keep archived entries from contributing to the
4174 Org-mode Agenda.
4176 The archived entries will be filed as subtrees of the specified
4177 headline. When the headline is omitted, the subtrees are simply
4178 filed away at the end of the file, as top-level entries. Also in
4179 the heading you can use %s to represent the file name, this can be
4180 useful when using the same archive for a number of different files.
4182 Here are a few examples:
4183 \"%s_archive::\"
4184 If the current file is Projects.org, archive in file
4185 Projects.org_archive, as top-level trees. This is the default.
4187 \"::* Archived Tasks\"
4188 Archive in the current file, under the top-level headline
4189 \"* Archived Tasks\".
4191 \"~/org/archive.org::\"
4192 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4194 \"~/org/archive.org::* From %s\"
4195 Archive in file ~/org/archive.org (absolute path), under headlines
4196 \"From FILENAME\" where file name is the current file name.
4198 \"~/org/datetree.org::datetree/* Finished Tasks\"
4199 The \"datetree/\" string is special, signifying to archive
4200 items to the datetree. Items are placed in either the CLOSED
4201 date of the item, or the current date if there is no CLOSED date.
4202 The heading will be a subentry to the current date. There doesn't
4203 need to be a heading, but there always needs to be a slash after
4204 datetree. For example, to store archived items directly in the
4205 datetree, use \"~/org/datetree.org::datetree/\".
4207 \"basement::** Finished Tasks\"
4208 Archive in file ./basement (relative path), as level 3 trees
4209 below the level 2 heading \"** Finished Tasks\".
4211 You may set this option on a per-file basis by adding to the buffer a
4212 line like
4214 #+ARCHIVE: basement::** Finished Tasks
4216 You may also define it locally for a subtree by setting an ARCHIVE property
4217 in the entry. If such a property is found in an entry, or anywhere up
4218 the hierarchy, it will be used."
4219 :group 'org-archive
4220 :type 'string)
4222 (defcustom org-archive-tag "ARCHIVE"
4223 "The tag that marks a subtree as archived.
4224 An archived subtree does not open during visibility cycling, and does
4225 not contribute to the agenda listings.
4226 After changing this, font-lock must be restarted in the relevant buffers to
4227 get the proper fontification."
4228 :group 'org-archive
4229 :group 'org-keywords
4230 :type 'string)
4232 (defcustom org-agenda-skip-archived-trees t
4233 "Non-nil means the agenda will skip any items located in archived trees.
4234 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4235 variable is no longer recommended, you should leave it at the value t.
4236 Instead, use the key `v' to cycle the archives-mode in the agenda."
4237 :group 'org-archive
4238 :group 'org-agenda-skip
4239 :type 'boolean)
4241 (defcustom org-columns-skip-archived-trees t
4242 "Non-nil means ignore archived trees when creating column view."
4243 :group 'org-archive
4244 :group 'org-properties
4245 :type 'boolean)
4247 (defcustom org-cycle-open-archived-trees nil
4248 "Non-nil means `org-cycle' will open archived trees.
4249 An archived tree is a tree marked with the tag ARCHIVE.
4250 When nil, archived trees will stay folded. You can still open them with
4251 normal outline commands like `show-all', but not with the cycling commands."
4252 :group 'org-archive
4253 :group 'org-cycle
4254 :type 'boolean)
4256 (defcustom org-sparse-tree-open-archived-trees nil
4257 "Non-nil means sparse tree construction shows matches in archived trees.
4258 When nil, matches in these trees are highlighted, but the trees are kept in
4259 collapsed state."
4260 :group 'org-archive
4261 :group 'org-sparse-trees
4262 :type 'boolean)
4264 (defun org-cycle-hide-archived-subtrees (state)
4265 "Re-hide all archived subtrees after a visibility state change."
4266 (when (and (not org-cycle-open-archived-trees)
4267 (not (memq state '(overview folded))))
4268 (save-excursion
4269 (let* ((globalp (memq state '(contents all)))
4270 (beg (if globalp (point-min) (point)))
4271 (end (if globalp (point-max) (org-end-of-subtree t))))
4272 (org-hide-archived-subtrees beg end)
4273 (goto-char beg)
4274 (if (looking-at (concat ".*:" org-archive-tag ":"))
4275 (message "%s" (substitute-command-keys
4276 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4278 (defun org-force-cycle-archived ()
4279 "Cycle subtree even if it is archived."
4280 (interactive)
4281 (setq this-command 'org-cycle)
4282 (let ((org-cycle-open-archived-trees t))
4283 (call-interactively 'org-cycle)))
4285 (defun org-hide-archived-subtrees (beg end)
4286 "Re-hide all archived subtrees after a visibility state change."
4287 (save-excursion
4288 (let* ((re (concat ":" org-archive-tag ":")))
4289 (goto-char beg)
4290 (while (re-search-forward re end t)
4291 (when (org-at-heading-p)
4292 (org-flag-subtree t)
4293 (org-end-of-subtree t))))))
4295 (defun org-flag-subtree (flag)
4296 (save-excursion
4297 (org-back-to-heading t)
4298 (outline-end-of-heading)
4299 (outline-flag-region (point)
4300 (progn (org-end-of-subtree t) (point))
4301 flag)))
4303 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4305 (eval-and-compile
4306 (org-autoload "org-archive"
4307 '(org-add-archive-files org-archive-subtree
4308 org-archive-to-archive-sibling org-toggle-archive-tag
4309 org-archive-subtree-default
4310 org-archive-subtree-default-with-confirmation)))
4312 ;; Autoload Column View Code
4314 (declare-function org-columns-number-to-string "org-colview")
4315 (declare-function org-columns-get-format-and-top-level "org-colview")
4316 (declare-function org-columns-compute "org-colview")
4318 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4319 '(org-columns-number-to-string org-columns-get-format-and-top-level
4320 org-columns-compute org-agenda-columns org-columns-remove-overlays
4321 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4323 ;; Autoload ID code
4325 (declare-function org-id-store-link "org-id")
4326 (declare-function org-id-locations-load "org-id")
4327 (declare-function org-id-locations-save "org-id")
4328 (defvar org-id-track-globally)
4329 (org-autoload "org-id"
4330 '(org-id-get-create org-id-new org-id-copy org-id-get
4331 org-id-get-with-outline-path-completion
4332 org-id-get-with-outline-drilling org-id-store-link
4333 org-id-goto org-id-find org-id-store-link))
4335 ;; Autoload Plotting Code
4337 (org-autoload "org-plot"
4338 '(org-plot/gnuplot))
4340 ;;; Variables for pre-computed regular expressions, all buffer local
4342 (defvar org-drawer-regexp nil
4343 "Matches first line of a hidden block.")
4344 (make-variable-buffer-local 'org-drawer-regexp)
4345 (defvar org-todo-regexp nil
4346 "Matches any of the TODO state keywords.")
4347 (make-variable-buffer-local 'org-todo-regexp)
4348 (defvar org-not-done-regexp nil
4349 "Matches any of the TODO state keywords except the last one.")
4350 (make-variable-buffer-local 'org-not-done-regexp)
4351 (defvar org-not-done-heading-regexp nil
4352 "Matches a TODO headline that is not done.")
4353 (make-variable-buffer-local 'org-not-done-regexp)
4354 (defvar org-todo-line-regexp nil
4355 "Matches a headline and puts TODO state into group 2 if present.")
4356 (make-variable-buffer-local 'org-todo-line-regexp)
4357 (defvar org-complex-heading-regexp nil
4358 "Matches a headline and puts everything into groups:
4359 group 1: the stars
4360 group 2: The todo keyword, maybe
4361 group 3: Priority cookie
4362 group 4: True headline
4363 group 5: Tags")
4364 (make-variable-buffer-local 'org-complex-heading-regexp)
4365 (defvar org-complex-heading-regexp-format nil
4366 "Printf format to make regexp to match an exact headline.
4367 This regexp will match the headline of any node which has the
4368 exact headline text that is put into the format, but may have any
4369 TODO state, priority and tags.")
4370 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4371 (defvar org-todo-line-tags-regexp nil
4372 "Matches a headline and puts TODO state into group 2 if present.
4373 Also put tags into group 4 if tags are present.")
4374 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4375 (defvar org-ds-keyword-length 12
4376 "Maximum length of the Deadline and SCHEDULED keywords.")
4377 (make-variable-buffer-local 'org-ds-keyword-length)
4378 (defvar org-deadline-regexp nil
4379 "Matches the DEADLINE keyword.")
4380 (make-variable-buffer-local 'org-deadline-regexp)
4381 (defvar org-deadline-time-regexp nil
4382 "Matches the DEADLINE keyword together with a time stamp.")
4383 (make-variable-buffer-local 'org-deadline-time-regexp)
4384 (defvar org-deadline-line-regexp nil
4385 "Matches the DEADLINE keyword and the rest of the line.")
4386 (make-variable-buffer-local 'org-deadline-line-regexp)
4387 (defvar org-scheduled-regexp nil
4388 "Matches the SCHEDULED keyword.")
4389 (make-variable-buffer-local 'org-scheduled-regexp)
4390 (defvar org-scheduled-time-regexp nil
4391 "Matches the SCHEDULED keyword together with a time stamp.")
4392 (make-variable-buffer-local 'org-scheduled-time-regexp)
4393 (defvar org-closed-time-regexp nil
4394 "Matches the CLOSED keyword together with a time stamp.")
4395 (make-variable-buffer-local 'org-closed-time-regexp)
4397 (defvar org-keyword-time-regexp nil
4398 "Matches any of the 4 keywords, together with the time stamp.")
4399 (make-variable-buffer-local 'org-keyword-time-regexp)
4400 (defvar org-keyword-time-not-clock-regexp nil
4401 "Matches any of the 3 keywords, together with the time stamp.")
4402 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4403 (defvar org-maybe-keyword-time-regexp nil
4404 "Matches a timestamp, possibly preceded by a keyword.")
4405 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4406 (defvar org-planning-or-clock-line-re nil
4407 "Matches a line with planning or clock info.")
4408 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4409 (defvar org-all-time-keywords nil
4410 "List of time keywords.")
4411 (make-variable-buffer-local 'org-all-time-keywords)
4413 (defconst org-plain-time-of-day-regexp
4414 (concat
4415 "\\(\\<[012]?[0-9]"
4416 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4417 "\\(--?"
4418 "\\(\\<[012]?[0-9]"
4419 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4420 "\\)?")
4421 "Regular expression to match a plain time or time range.
4422 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4423 groups carry important information:
4424 0 the full match
4425 1 the first time, range or not
4426 8 the second time, if it is a range.")
4428 (defconst org-plain-time-extension-regexp
4429 (concat
4430 "\\(\\<[012]?[0-9]"
4431 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4432 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4433 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4434 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4435 groups carry important information:
4436 0 the full match
4437 7 hours of duration
4438 9 minutes of duration")
4440 (defconst org-stamp-time-of-day-regexp
4441 (concat
4442 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4443 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4444 "\\(--?"
4445 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4446 "Regular expression to match a timestamp time or time range.
4447 After a match, the following groups carry important information:
4448 0 the full match
4449 1 date plus weekday, for back referencing to make sure both times are on the same day
4450 2 the first time, range or not
4451 4 the second time, if it is a range.")
4453 (defconst org-startup-options
4454 '(("fold" org-startup-folded t)
4455 ("overview" org-startup-folded t)
4456 ("nofold" org-startup-folded nil)
4457 ("showall" org-startup-folded nil)
4458 ("showeverything" org-startup-folded showeverything)
4459 ("content" org-startup-folded content)
4460 ("indent" org-startup-indented t)
4461 ("noindent" org-startup-indented nil)
4462 ("hidestars" org-hide-leading-stars t)
4463 ("showstars" org-hide-leading-stars nil)
4464 ("odd" org-odd-levels-only t)
4465 ("oddeven" org-odd-levels-only nil)
4466 ("align" org-startup-align-all-tables t)
4467 ("noalign" org-startup-align-all-tables nil)
4468 ("inlineimages" org-startup-with-inline-images t)
4469 ("noinlineimages" org-startup-with-inline-images nil)
4470 ("customtime" org-display-custom-times t)
4471 ("logdone" org-log-done time)
4472 ("lognotedone" org-log-done note)
4473 ("nologdone" org-log-done nil)
4474 ("lognoteclock-out" org-log-note-clock-out t)
4475 ("nolognoteclock-out" org-log-note-clock-out nil)
4476 ("logrepeat" org-log-repeat state)
4477 ("lognoterepeat" org-log-repeat note)
4478 ("nologrepeat" org-log-repeat nil)
4479 ("logreschedule" org-log-reschedule time)
4480 ("lognotereschedule" org-log-reschedule note)
4481 ("nologreschedule" org-log-reschedule nil)
4482 ("logredeadline" org-log-redeadline time)
4483 ("lognoteredeadline" org-log-redeadline note)
4484 ("nologredeadline" org-log-redeadline nil)
4485 ("logrefile" org-log-refile time)
4486 ("lognoterefile" org-log-refile note)
4487 ("nologrefile" org-log-refile nil)
4488 ("fninline" org-footnote-define-inline t)
4489 ("nofninline" org-footnote-define-inline nil)
4490 ("fnlocal" org-footnote-section nil)
4491 ("fnauto" org-footnote-auto-label t)
4492 ("fnprompt" org-footnote-auto-label nil)
4493 ("fnconfirm" org-footnote-auto-label confirm)
4494 ("fnplain" org-footnote-auto-label plain)
4495 ("fnadjust" org-footnote-auto-adjust t)
4496 ("nofnadjust" org-footnote-auto-adjust nil)
4497 ("constcgs" constants-unit-system cgs)
4498 ("constSI" constants-unit-system SI)
4499 ("noptag" org-tag-persistent-alist nil)
4500 ("hideblocks" org-hide-block-startup t)
4501 ("nohideblocks" org-hide-block-startup nil)
4502 ("beamer" org-startup-with-beamer-mode t)
4503 ("entitiespretty" org-pretty-entities t)
4504 ("entitiesplain" org-pretty-entities nil))
4505 "Variable associated with STARTUP options for org-mode.
4506 Each element is a list of three items: The startup options as written
4507 in the #+STARTUP line, the corresponding variable, and the value to
4508 set this variable to if the option is found. An optional forth element PUSH
4509 means to push this value onto the list in the variable.")
4511 (defun org-update-property-plist (key val props)
4512 "Update PROPS with KEY and VAL."
4513 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4514 (key (if appending (substring key 0 (- (length key) 1)) key))
4515 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4516 (previous (cdr (assoc key props))))
4517 (if appending
4518 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4519 (cons (cons key val) remainder))))
4521 (defconst org-block-regexp
4522 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4523 "Regular expression for hiding blocks.")
4524 (defconst org-heading-keyword-regexp-format
4525 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4526 "Printf format for a regexp matching an headline with some keyword.
4527 This regexp will match the headline of any node which has the
4528 exact keyword that is put into the format. The keyword isn't in
4529 any group by default, but the stars and the body are.")
4530 (defconst org-heading-keyword-maybe-regexp-format
4531 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4532 "Printf format for a regexp matching an headline, possibly with some keyword.
4533 This regexp can match any headline with the specified keyword, or
4534 without a keyword. The keyword isn't in any group by default,
4535 but the stars and the body are.")
4537 (defun org-set-regexps-and-options ()
4538 "Precompute regular expressions for current buffer."
4539 (when (derived-mode-p 'org-mode)
4540 (org-set-local 'org-todo-kwd-alist nil)
4541 (org-set-local 'org-todo-key-alist nil)
4542 (org-set-local 'org-todo-key-trigger nil)
4543 (org-set-local 'org-todo-keywords-1 nil)
4544 (org-set-local 'org-done-keywords nil)
4545 (org-set-local 'org-todo-heads nil)
4546 (org-set-local 'org-todo-sets nil)
4547 (org-set-local 'org-todo-log-states nil)
4548 (org-set-local 'org-file-properties nil)
4549 (org-set-local 'org-file-tags nil)
4550 (let ((re (org-make-options-regexp
4551 '("CATEGORY" "TODO" "COLUMNS"
4552 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4553 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4554 "OPTIONS")
4555 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4556 (splitre "[ \t]+")
4557 (scripts org-use-sub-superscripts)
4558 kwds kws0 kwsa key log value cat arch tags const links hw dws
4559 tail sep kws1 prio props ftags drawers beamer-p
4560 ext-setup-or-nil setup-contents (start 0))
4561 (save-excursion
4562 (save-restriction
4563 (widen)
4564 (goto-char (point-min))
4565 (while (or (and ext-setup-or-nil
4566 (string-match re ext-setup-or-nil start)
4567 (setq start (match-end 0)))
4568 (and (setq ext-setup-or-nil nil start 0)
4569 (re-search-forward re nil t)))
4570 (setq key (upcase (match-string 1 ext-setup-or-nil))
4571 value (org-match-string-no-properties 2 ext-setup-or-nil))
4572 (if (stringp value) (setq value (org-trim value)))
4573 (cond
4574 ((equal key "CATEGORY")
4575 (setq cat value))
4576 ((member key '("SEQ_TODO" "TODO"))
4577 (push (cons 'sequence (org-split-string value splitre)) kwds))
4578 ((equal key "TYP_TODO")
4579 (push (cons 'type (org-split-string value splitre)) kwds))
4580 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4581 ;; general TODO-like setup
4582 (push (cons (intern (downcase (match-string 1 key)))
4583 (org-split-string value splitre)) kwds))
4584 ((equal key "TAGS")
4585 (setq tags (append tags (if tags '("\\n") nil)
4586 (org-split-string value splitre))))
4587 ((equal key "COLUMNS")
4588 (org-set-local 'org-columns-default-format value))
4589 ((equal key "LINK")
4590 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4591 (push (cons (match-string 1 value)
4592 (org-trim (match-string 2 value)))
4593 links)))
4594 ((equal key "PRIORITIES")
4595 (setq prio (org-split-string value " +")))
4596 ((equal key "PROPERTY")
4597 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4598 (setq props (org-update-property-plist (match-string 1 value)
4599 (match-string 2 value)
4600 props))))
4601 ((equal key "FILETAGS")
4602 (when (string-match "\\S-" value)
4603 (setq ftags
4604 (append
4605 ftags
4606 (apply 'append
4607 (mapcar (lambda (x) (org-split-string x ":"))
4608 (org-split-string value)))))))
4609 ((equal key "DRAWERS")
4610 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4611 ((equal key "CONSTANTS")
4612 (setq const (append const (org-split-string value splitre))))
4613 ((equal key "STARTUP")
4614 (let ((opts (org-split-string value splitre))
4615 l var val)
4616 (while (setq l (pop opts))
4617 (when (setq l (assoc l org-startup-options))
4618 (setq var (nth 1 l) val (nth 2 l))
4619 (if (not (nth 3 l))
4620 (set (make-local-variable var) val)
4621 (if (not (listp (symbol-value var)))
4622 (set (make-local-variable var) nil))
4623 (set (make-local-variable var) (symbol-value var))
4624 (add-to-list var val))))))
4625 ((equal key "ARCHIVE")
4626 (setq arch value)
4627 (remove-text-properties 0 (length arch)
4628 '(face t fontified t) arch))
4629 ((equal key "LATEX_CLASS")
4630 (setq beamer-p (equal value "beamer")))
4631 ((equal key "OPTIONS")
4632 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4633 (setq scripts (read (match-string 2 value)))))
4634 ((equal key "SETUPFILE")
4635 (setq setup-contents (org-file-contents
4636 (expand-file-name
4637 (org-remove-double-quotes value))
4638 'noerror))
4639 (if (not ext-setup-or-nil)
4640 (setq ext-setup-or-nil setup-contents start 0)
4641 (setq ext-setup-or-nil
4642 (concat (substring ext-setup-or-nil 0 start)
4643 "\n" setup-contents "\n"
4644 (substring ext-setup-or-nil start)))))))
4645 ;; search for property blocks
4646 (goto-char (point-min))
4647 (while (re-search-forward org-block-regexp nil t)
4648 (when (equal "PROPERTY" (upcase (match-string 1)))
4649 (setq value (replace-regexp-in-string
4650 "[\n\r]" " " (match-string 4)))
4651 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4652 (setq props (org-update-property-plist (match-string 1 value)
4653 (match-string 2 value)
4654 props)))))))
4655 (org-set-local 'org-use-sub-superscripts scripts)
4656 (when cat
4657 (org-set-local 'org-category (intern cat))
4658 (push (cons "CATEGORY" cat) props))
4659 (when prio
4660 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4661 (setq prio (mapcar 'string-to-char prio))
4662 (org-set-local 'org-highest-priority (nth 0 prio))
4663 (org-set-local 'org-lowest-priority (nth 1 prio))
4664 (org-set-local 'org-default-priority (nth 2 prio)))
4665 (and props (org-set-local 'org-file-properties (nreverse props)))
4666 (and ftags (org-set-local 'org-file-tags
4667 (mapcar 'org-add-prop-inherited ftags)))
4668 (and drawers (org-set-local 'org-drawers drawers))
4669 (and arch (org-set-local 'org-archive-location arch))
4670 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4671 ;; Process the TODO keywords
4672 (unless kwds
4673 ;; Use the global values as if they had been given locally.
4674 (setq kwds (default-value 'org-todo-keywords))
4675 (if (stringp (car kwds))
4676 (setq kwds (list (cons org-todo-interpretation
4677 (default-value 'org-todo-keywords)))))
4678 (setq kwds (reverse kwds)))
4679 (setq kwds (nreverse kwds))
4680 (let (inter kws kw)
4681 (while (setq kws (pop kwds))
4682 (let ((kws (or
4683 (run-hook-with-args-until-success
4684 'org-todo-setup-filter-hook kws)
4685 kws)))
4686 (setq inter (pop kws) sep (member "|" kws)
4687 kws0 (delete "|" (copy-sequence kws))
4688 kwsa nil
4689 kws1 (mapcar
4690 (lambda (x)
4691 ;; 1 2
4692 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4693 (progn
4694 (setq kw (match-string 1 x)
4695 key (and (match-end 2) (match-string 2 x))
4696 log (org-extract-log-state-settings x))
4697 (push (cons kw (and key (string-to-char key))) kwsa)
4698 (and log (push log org-todo-log-states))
4700 (error "Invalid TODO keyword %s" x)))
4701 kws0)
4702 kwsa (if kwsa (append '((:startgroup))
4703 (nreverse kwsa)
4704 '((:endgroup))))
4705 hw (car kws1)
4706 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4707 tail (list inter hw (car dws) (org-last dws))))
4708 (add-to-list 'org-todo-heads hw 'append)
4709 (push kws1 org-todo-sets)
4710 (setq org-done-keywords (append org-done-keywords dws nil))
4711 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4712 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4713 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4714 (setq org-todo-sets (nreverse org-todo-sets)
4715 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4716 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4717 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4718 ;; Process the constants
4719 (when const
4720 (let (e cst)
4721 (while (setq e (pop const))
4722 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4723 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4724 (setq org-table-formula-constants-local cst)))
4726 ;; Process the tags.
4727 (when tags
4728 (let (e tgs)
4729 (while (setq e (pop tags))
4730 (cond
4731 ((equal e "{") (push '(:startgroup) tgs))
4732 ((equal e "}") (push '(:endgroup) tgs))
4733 ((equal e "\\n") (push '(:newline) tgs))
4734 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4735 (push (cons (match-string 1 e)
4736 (string-to-char (match-string 2 e)))
4737 tgs))
4738 (t (push (list e) tgs))))
4739 (org-set-local 'org-tag-alist nil)
4740 (while (setq e (pop tgs))
4741 (or (and (stringp (car e))
4742 (assoc (car e) org-tag-alist))
4743 (push e org-tag-alist)))))
4745 ;; Compute the regular expressions and other local variables.
4746 ;; Using `org-outline-regexp-bol' would complicate them much,
4747 ;; because of the fixed white space at the end of that string.
4748 (if (not org-done-keywords)
4749 (setq org-done-keywords (and org-todo-keywords-1
4750 (list (org-last org-todo-keywords-1)))))
4751 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4752 (length org-scheduled-string)
4753 (length org-clock-string)
4754 (length org-closed-string)))
4755 org-drawer-regexp
4756 (concat "^[ \t]*:\\("
4757 (mapconcat 'regexp-quote org-drawers "\\|")
4758 "\\):[ \t]*$")
4759 org-not-done-keywords
4760 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4761 org-todo-regexp
4762 (concat "\\("
4763 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4764 "\\)")
4765 org-not-done-regexp
4766 (concat "\\("
4767 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4768 "\\)")
4769 org-not-done-heading-regexp
4770 (format org-heading-keyword-regexp-format org-not-done-regexp)
4771 org-todo-line-regexp
4772 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4773 org-complex-heading-regexp
4774 (concat "^\\(\\*+\\)"
4775 "\\(?: +" org-todo-regexp "\\)?"
4776 "\\(?: +\\(\\[#.\\]\\)\\)?"
4777 "\\(?: +\\(.*?\\)\\)?"
4778 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4779 "[ \t]*$")
4780 org-complex-heading-regexp-format
4781 (concat "^\\(\\*+\\)"
4782 "\\(?: +" org-todo-regexp "\\)?"
4783 "\\(?: +\\(\\[#.\\]\\)\\)?"
4784 "\\(?: +"
4785 ;; Stats cookies can be stuck to body.
4786 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4787 "\\(%s\\)"
4788 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4789 "\\)"
4790 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4791 "[ \t]*$")
4792 org-todo-line-tags-regexp
4793 (concat "^\\(\\*+\\)"
4794 "\\(?: +" org-todo-regexp "\\)?"
4795 "\\(?: +\\(.*?\\)\\)?"
4796 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4797 "[ \t]*$")
4798 org-deadline-regexp (concat "\\<" org-deadline-string)
4799 org-deadline-time-regexp
4800 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4801 org-deadline-line-regexp
4802 (concat "\\<\\(" org-deadline-string "\\).*")
4803 org-scheduled-regexp
4804 (concat "\\<" org-scheduled-string)
4805 org-scheduled-time-regexp
4806 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4807 org-closed-time-regexp
4808 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4809 org-keyword-time-regexp
4810 (concat "\\<\\(" org-scheduled-string
4811 "\\|" org-deadline-string
4812 "\\|" org-closed-string
4813 "\\|" org-clock-string "\\)"
4814 " *[[<]\\([^]>]+\\)[]>]")
4815 org-keyword-time-not-clock-regexp
4816 (concat "\\<\\(" org-scheduled-string
4817 "\\|" org-deadline-string
4818 "\\|" org-closed-string
4819 "\\)"
4820 " *[[<]\\([^]>]+\\)[]>]")
4821 org-maybe-keyword-time-regexp
4822 (concat "\\(\\<\\(" org-scheduled-string
4823 "\\|" org-deadline-string
4824 "\\|" org-closed-string
4825 "\\|" org-clock-string "\\)\\)?"
4826 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4827 org-planning-or-clock-line-re
4828 (concat "^[ \t]*\\("
4829 org-scheduled-string "\\|"
4830 org-deadline-string "\\|"
4831 org-closed-string "\\|"
4832 org-clock-string "\\)")
4833 org-all-time-keywords
4834 (mapcar (lambda (w) (substring w 0 -1))
4835 (list org-scheduled-string org-deadline-string
4836 org-clock-string org-closed-string))
4838 (org-compute-latex-and-specials-regexp)
4839 (org-set-font-lock-defaults))))
4841 (defun org-file-contents (file &optional noerror)
4842 "Return the contents of FILE, as a string."
4843 (if (or (not file)
4844 (not (file-readable-p file)))
4845 (if noerror
4846 (progn
4847 (message "Cannot read file \"%s\"" file)
4848 (ding) (sit-for 2)
4850 (error "Cannot read file \"%s\"" file))
4851 (with-temp-buffer
4852 (insert-file-contents file)
4853 (buffer-string))))
4855 (defun org-extract-log-state-settings (x)
4856 "Extract the log state setting from a TODO keyword string.
4857 This will extract info from a string like \"WAIT(w@/!)\"."
4858 (let (kw key log1 log2)
4859 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4860 (setq kw (match-string 1 x)
4861 key (and (match-end 2) (match-string 2 x))
4862 log1 (and (match-end 3) (match-string 3 x))
4863 log2 (and (match-end 4) (match-string 4 x)))
4864 (and (or log1 log2)
4865 (list kw
4866 (and log1 (if (equal log1 "!") 'time 'note))
4867 (and log2 (if (equal log2 "!") 'time 'note)))))))
4869 (defun org-remove-keyword-keys (list)
4870 "Remove a pair of parenthesis at the end of each string in LIST."
4871 (mapcar (lambda (x)
4872 (if (string-match "(.*)$" x)
4873 (substring x 0 (match-beginning 0))
4875 list))
4877 (defun org-assign-fast-keys (alist)
4878 "Assign fast keys to a keyword-key alist.
4879 Respect keys that are already there."
4880 (let (new e (alt ?0))
4881 (while (setq e (pop alist))
4882 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4883 (cdr e)) ;; Key already assigned.
4884 (push e new)
4885 (let ((clist (string-to-list (downcase (car e))))
4886 (used (append new alist)))
4887 (when (= (car clist) ?@)
4888 (pop clist))
4889 (while (and clist (rassoc (car clist) used))
4890 (pop clist))
4891 (unless clist
4892 (while (rassoc alt used)
4893 (incf alt)))
4894 (push (cons (car e) (or (car clist) alt)) new))))
4895 (nreverse new)))
4897 ;;; Some variables used in various places
4899 (defvar org-window-configuration nil
4900 "Used in various places to store a window configuration.")
4901 (defvar org-selected-window nil
4902 "Used in various places to store a window configuration.")
4903 (defvar org-finish-function nil
4904 "Function to be called when `C-c C-c' is used.
4905 This is for getting out of special buffers like remember.")
4908 ;; FIXME: Occasionally check by commenting these, to make sure
4909 ;; no other functions uses these, forgetting to let-bind them.
4910 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4911 (defvar org-last-state)
4912 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4914 ;; Defined somewhere in this file, but used before definition.
4915 (defvar org-entities) ;; defined in org-entities.el
4916 (defvar org-struct-menu)
4917 (defvar org-org-menu)
4918 (defvar org-tbl-menu)
4920 ;;;; Define the Org-mode
4922 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4923 (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"))
4926 ;; We use a before-change function to check if a table might need
4927 ;; an update.
4928 (defvar org-table-may-need-update t
4929 "Indicates that a table might need an update.
4930 This variable is set by `org-before-change-function'.
4931 `org-table-align' sets it back to nil.")
4932 (defun org-before-change-function (beg end)
4933 "Every change indicates that a table might need an update."
4934 (setq org-table-may-need-update t))
4935 (defvar org-mode-map)
4936 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4937 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4938 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4939 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4940 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4941 (defvar org-table-buffer-is-an nil)
4943 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4944 ;; some places -- e.g. see the macro org-with-limited-levels.
4946 ;; In Org buffers, the value of `outline-regexp' is that of
4947 ;; `org-outline-regexp'. The only function still directly relying on
4948 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4949 ;; job when `orgstruct-mode' is active.
4950 (defvar org-outline-regexp "\\*+ "
4951 "Regexp to match Org headlines.")
4952 (defconst org-outline-regexp-bol "^\\*+ "
4953 "Regexp to match Org headlines.
4954 This is similar to `org-outline-regexp' but additionally makes
4955 sure that we are at the beginning of the line.")
4957 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4958 "Matches an headline, putting stars and text into groups.
4959 Stars are put in group 1 and the trimmed body in group 2.")
4961 (defvar bidi-paragraph-direction)
4962 (defvar buffer-face-mode-face)
4964 ;;;###autoload
4965 (define-derived-mode org-mode outline-mode "Org"
4966 "Outline-based notes management and organizer, alias
4967 \"Carsten's outline-mode for keeping track of everything.\"
4969 Org-mode develops organizational tasks around a NOTES file which
4970 contains information about projects as plain text. Org-mode is
4971 implemented on top of outline-mode, which is ideal to keep the content
4972 of large files well structured. It supports ToDo items, deadlines and
4973 time stamps, which magically appear in the diary listing of the Emacs
4974 calendar. Tables are easily created with a built-in table editor.
4975 Plain text URL-like links connect to websites, emails (VM), Usenet
4976 messages (Gnus), BBDB entries, and any files related to the project.
4977 For printing and sharing of notes, an Org-mode file (or a part of it)
4978 can be exported as a structured ASCII or HTML file.
4980 The following commands are available:
4982 \\{org-mode-map}"
4984 ;; Get rid of Outline menus, they are not needed
4985 ;; Need to do this here because define-derived-mode sets up
4986 ;; the keymap so late. Still, it is a waste to call this each time
4987 ;; we switch another buffer into org-mode.
4988 (if (featurep 'xemacs)
4989 (when (boundp 'outline-mode-menu-heading)
4990 ;; Assume this is Greg's port, it uses easymenu
4991 (easy-menu-remove outline-mode-menu-heading)
4992 (easy-menu-remove outline-mode-menu-show)
4993 (easy-menu-remove outline-mode-menu-hide))
4994 (define-key org-mode-map [menu-bar headings] 'undefined)
4995 (define-key org-mode-map [menu-bar hide] 'undefined)
4996 (define-key org-mode-map [menu-bar show] 'undefined))
4998 (org-load-modules-maybe)
4999 (easy-menu-add org-org-menu)
5000 (easy-menu-add org-tbl-menu)
5001 (org-install-agenda-files-menu)
5002 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5003 (add-to-invisibility-spec '(org-cwidth))
5004 (add-to-invisibility-spec '(org-hide-block . t))
5005 (when (featurep 'xemacs)
5006 (org-set-local 'line-move-ignore-invisible t))
5007 (org-set-local 'outline-regexp org-outline-regexp)
5008 (org-set-local 'outline-level 'org-outline-level)
5009 (setq bidi-paragraph-direction 'left-to-right)
5010 (when (and org-ellipsis
5011 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5012 (fboundp 'make-glyph-code))
5013 (unless org-display-table
5014 (setq org-display-table (make-display-table)))
5015 (set-display-table-slot
5016 org-display-table 4
5017 (vconcat (mapcar
5018 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5019 org-ellipsis)))
5020 (if (stringp org-ellipsis) org-ellipsis "..."))))
5021 (setq buffer-display-table org-display-table))
5022 (org-set-regexps-and-options)
5023 (when (and org-tag-faces (not org-tags-special-faces-re))
5024 ;; tag faces set outside customize.... force initialization.
5025 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5026 ;; Calc embedded
5027 (org-set-local 'calc-embedded-open-mode "# ")
5028 (modify-syntax-entry ?@ "w")
5029 (if org-startup-truncated (setq truncate-lines t))
5030 (org-set-local 'font-lock-unfontify-region-function
5031 'org-unfontify-region)
5032 ;; Activate before-change-function
5033 (org-set-local 'org-table-may-need-update t)
5034 (org-add-hook 'before-change-functions 'org-before-change-function nil
5035 'local)
5036 ;; Check for running clock before killing a buffer
5037 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5038 ;; Paragraphs and auto-filling
5039 (org-set-autofill-regexps)
5040 (setq indent-line-function 'org-indent-line-function)
5041 (org-update-radio-target-regexp)
5042 ;; Beginning/end of defun
5043 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5044 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5045 ;; Next error for sparse trees
5046 (org-set-local 'next-error-function 'org-occur-next-match)
5047 ;; Make sure dependence stuff works reliably, even for users who set it
5048 ;; too late :-(
5049 (if org-enforce-todo-dependencies
5050 (add-hook 'org-blocker-hook
5051 'org-block-todo-from-children-or-siblings-or-parent)
5052 (remove-hook 'org-blocker-hook
5053 'org-block-todo-from-children-or-siblings-or-parent))
5054 (if org-enforce-todo-checkbox-dependencies
5055 (add-hook 'org-blocker-hook
5056 'org-block-todo-from-checkboxes)
5057 (remove-hook 'org-blocker-hook
5058 'org-block-todo-from-checkboxes))
5060 ;; Comment characters
5061 (org-set-local 'comment-start "#")
5062 (org-set-local 'comment-padding " ")
5064 ;; Align options lines
5065 (org-set-local
5066 'align-mode-rules-list
5067 '((org-in-buffer-settings
5068 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5069 (modes . '(org-mode)))))
5071 ;; Imenu
5072 (org-set-local 'imenu-create-index-function
5073 'org-imenu-get-tree)
5075 ;; Make isearch reveal context
5076 (if (or (featurep 'xemacs)
5077 (not (boundp 'outline-isearch-open-invisible-function)))
5078 ;; Emacs 21 and XEmacs make use of the hook
5079 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5080 ;; Emacs 22 deals with this through a special variable
5081 (org-set-local 'outline-isearch-open-invisible-function
5082 (lambda (&rest ignore) (org-show-context 'isearch))))
5084 ;; Turn on org-beamer-mode?
5085 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5087 ;; Setup the pcomplete hooks
5088 (set (make-local-variable 'pcomplete-command-completion-function)
5089 'org-pcomplete-initial)
5090 (set (make-local-variable 'pcomplete-command-name-function)
5091 'org-command-at-point)
5092 (set (make-local-variable 'pcomplete-default-completion-function)
5093 'ignore)
5094 (set (make-local-variable 'pcomplete-parse-arguments-function)
5095 'org-parse-arguments)
5096 (set (make-local-variable 'pcomplete-termination-string) "")
5097 (when (>= emacs-major-version 23)
5098 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5100 ;; If empty file that did not turn on org-mode automatically, make it to.
5101 (if (and org-insert-mode-line-in-empty-file
5102 (org-called-interactively-p 'any)
5103 (= (point-min) (point-max)))
5104 (insert "# -*- mode: org -*-\n\n"))
5105 (unless org-inhibit-startup
5106 (when org-startup-align-all-tables
5107 (let ((bmp (buffer-modified-p)))
5108 (org-table-map-tables 'org-table-align 'quietly)
5109 (set-buffer-modified-p bmp)))
5110 (when org-startup-with-inline-images
5111 (org-display-inline-images))
5112 (when org-startup-indented
5113 (require 'org-indent)
5114 (org-indent-mode 1))
5115 (unless org-inhibit-startup-visibility-stuff
5116 (org-set-startup-visibility))))
5118 (when (fboundp 'abbrev-table-put)
5119 (abbrev-table-put org-mode-abbrev-table
5120 :parents (list text-mode-abbrev-table)))
5122 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5124 (defun org-current-time ()
5125 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5126 (if (> (car org-time-stamp-rounding-minutes) 1)
5127 (let ((r (car org-time-stamp-rounding-minutes))
5128 (time (decode-time)))
5129 (apply 'encode-time
5130 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5131 (nthcdr 2 time))))
5132 (current-time)))
5134 (defun org-today ()
5135 "Return today date, considering `org-extend-today-until'."
5136 (time-to-days
5137 (time-subtract (current-time)
5138 (list 0 (* 3600 org-extend-today-until) 0))))
5140 ;;;; Font-Lock stuff, including the activators
5142 (defvar org-mouse-map (make-sparse-keymap))
5143 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5144 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5145 (when org-mouse-1-follows-link
5146 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5147 (when org-tab-follows-link
5148 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5149 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5151 (require 'font-lock)
5153 (defconst org-non-link-chars "]\t\n\r<>")
5154 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5155 "shell" "elisp" "doi" "message"))
5156 (defvar org-link-types-re nil
5157 "Matches a link that has a url-like prefix like \"http:\"")
5158 (defvar org-link-re-with-space nil
5159 "Matches a link with spaces, optional angular brackets around it.")
5160 (defvar org-link-re-with-space2 nil
5161 "Matches a link with spaces, optional angular brackets around it.")
5162 (defvar org-link-re-with-space3 nil
5163 "Matches a link with spaces, only for internal part in bracket links.")
5164 (defvar org-angle-link-re nil
5165 "Matches link with angular brackets, spaces are allowed.")
5166 (defvar org-plain-link-re nil
5167 "Matches plain link, without spaces.")
5168 (defvar org-bracket-link-regexp nil
5169 "Matches a link in double brackets.")
5170 (defvar org-bracket-link-analytic-regexp nil
5171 "Regular expression used to analyze links.
5172 Here is what the match groups contain after a match:
5173 1: http:
5174 2: http
5175 3: path
5176 4: [desc]
5177 5: desc")
5178 (defvar org-bracket-link-analytic-regexp++ nil
5179 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5180 (defvar org-any-link-re nil
5181 "Regular expression matching any link.")
5183 (defcustom org-match-sexp-depth 3
5184 "Number of stacked braces for sub/superscript matching.
5185 This has to be set before loading org.el to be effective."
5186 :group 'org-export-translation ; ??????????????????????????/
5187 :type 'integer)
5189 (defun org-create-multibrace-regexp (left right n)
5190 "Create a regular expression which will match a balanced sexp.
5191 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5192 as single character strings.
5193 The regexp returned will match the entire expression including the
5194 delimiters. It will also define a single group which contains the
5195 match except for the outermost delimiters. The maximum depth of
5196 stacked delimiters is N. Escaping delimiters is not possible."
5197 (let* ((nothing (concat "[^" left right "]*?"))
5198 (or "\\|")
5199 (re nothing)
5200 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5201 (while (> n 1)
5202 (setq n (1- n)
5203 re (concat re or next)
5204 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5205 (concat left "\\(" re "\\)" right)))
5207 (defvar org-match-substring-regexp
5208 (concat
5209 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5210 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5211 "\\|"
5212 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5213 "\\|"
5214 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5215 "The regular expression matching a sub- or superscript.")
5217 (defvar org-match-substring-with-braces-regexp
5218 (concat
5219 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5220 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5221 "\\)")
5222 "The regular expression matching a sub- or superscript, forcing braces.")
5224 (defun org-make-link-regexps ()
5225 "Update the link regular expressions.
5226 This should be called after the variable `org-link-types' has changed."
5227 (setq org-link-types-re
5228 (concat
5229 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5230 org-link-re-with-space
5231 (concat
5232 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5233 "\\([^" org-non-link-chars " ]"
5234 "[^" org-non-link-chars "]*"
5235 "[^" org-non-link-chars " ]\\)>?")
5236 org-link-re-with-space2
5237 (concat
5238 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5239 "\\([^" org-non-link-chars " ]"
5240 "[^\t\n\r]*"
5241 "[^" org-non-link-chars " ]\\)>?")
5242 org-link-re-with-space3
5243 (concat
5244 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5245 "\\([^" org-non-link-chars " ]"
5246 "[^\t\n\r]*\\)")
5247 org-angle-link-re
5248 (concat
5249 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5250 "\\([^" org-non-link-chars " ]"
5251 "[^" org-non-link-chars "]*"
5252 "\\)>")
5253 org-plain-link-re
5254 (concat
5255 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5256 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5257 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5258 org-bracket-link-regexp
5259 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5260 org-bracket-link-analytic-regexp
5261 (concat
5262 "\\[\\["
5263 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5264 "\\([^]]+\\)"
5265 "\\]"
5266 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5267 "\\]")
5268 org-bracket-link-analytic-regexp++
5269 (concat
5270 "\\[\\["
5271 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5272 "\\([^]]+\\)"
5273 "\\]"
5274 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5275 "\\]")
5276 org-any-link-re
5277 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5278 org-angle-link-re "\\)\\|\\("
5279 org-plain-link-re "\\)")))
5281 (org-make-link-regexps)
5283 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5284 "Regular expression for fast time stamp matching.")
5285 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5286 "Regular expression for fast time stamp matching.")
5287 (defconst org-ts-regexp0
5288 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5289 "Regular expression matching time strings for analysis.
5290 This one does not require the space after the date, so it can be used
5291 on a string that terminates immediately after the date.")
5292 (defconst org-ts-regexp1 "\\(\\([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 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5295 "Regular expression matching time stamps, with groups.")
5296 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5297 "Regular expression matching time stamps (also [..]), with groups.")
5298 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5299 "Regular expression matching a time stamp range.")
5300 (defconst org-tr-regexp-both
5301 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5302 "Regular expression matching a time stamp range.")
5303 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5304 org-ts-regexp "\\)?")
5305 "Regular expression matching a time stamp or time stamp range.")
5306 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5307 org-ts-regexp-both "\\)?")
5308 "Regular expression matching a time stamp or time stamp range.
5309 The time stamps may be either active or inactive.")
5311 (defvar org-emph-face nil)
5313 (defun org-do-emphasis-faces (limit)
5314 "Run through the buffer and add overlays to emphasized strings."
5315 (let (rtn a)
5316 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5317 (if (not (= (char-after (match-beginning 3))
5318 (char-after (match-beginning 4))))
5319 (progn
5320 (setq rtn t)
5321 (setq a (assoc (match-string 3) org-emphasis-alist))
5322 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5323 'face
5324 (nth 1 a))
5325 (and (nth 4 a)
5326 (org-remove-flyspell-overlays-in
5327 (match-beginning 0) (match-end 0)))
5328 (add-text-properties (match-beginning 2) (match-end 2)
5329 '(font-lock-multiline t org-emphasis t))
5330 (when org-hide-emphasis-markers
5331 (add-text-properties (match-end 4) (match-beginning 5)
5332 '(invisible org-link))
5333 (add-text-properties (match-beginning 3) (match-end 3)
5334 '(invisible org-link)))))
5335 (backward-char 1))
5336 rtn))
5338 (defun org-emphasize (&optional char)
5339 "Insert or change an emphasis, i.e. a font like bold or italic.
5340 If there is an active region, change that region to a new emphasis.
5341 If there is no region, just insert the marker characters and position
5342 the cursor between them.
5343 CHAR should be either the marker character, or the first character of the
5344 HTML tag associated with that emphasis. If CHAR is a space, the means
5345 to remove the emphasis of the selected region.
5346 If char is not given (for example in an interactive call) it
5347 will be prompted for."
5348 (interactive)
5349 (let ((eal org-emphasis-alist) e det
5350 (erc org-emphasis-regexp-components)
5351 (prompt "")
5352 (string "") beg end move tag c s)
5353 (if (org-region-active-p)
5354 (setq beg (region-beginning) end (region-end)
5355 string (buffer-substring beg end))
5356 (setq move t))
5358 (while (setq e (pop eal))
5359 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5360 c (aref tag 0))
5361 (push (cons c (string-to-char (car e))) det)
5362 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5363 (substring tag 1)))))
5364 (setq det (nreverse det))
5365 (unless char
5366 (message "%s" (concat "Emphasis marker or tag:" prompt))
5367 (setq char (read-char-exclusive)))
5368 (setq char (or (cdr (assoc char det)) char))
5369 (if (equal char ?\ )
5370 (setq s "" move nil)
5371 (unless (assoc (char-to-string char) org-emphasis-alist)
5372 (error "No such emphasis marker: \"%c\"" char))
5373 (setq s (char-to-string char)))
5374 (while (and (> (length string) 1)
5375 (equal (substring string 0 1) (substring string -1))
5376 (assoc (substring string 0 1) org-emphasis-alist))
5377 (setq string (substring string 1 -1)))
5378 (setq string (concat s string s))
5379 (if beg (delete-region beg end))
5380 (unless (or (bolp)
5381 (string-match (concat "[" (nth 0 erc) "\n]")
5382 (char-to-string (char-before (point)))))
5383 (insert " "))
5384 (unless (or (eobp)
5385 (string-match (concat "[" (nth 1 erc) "\n]")
5386 (char-to-string (char-after (point)))))
5387 (insert " ") (backward-char 1))
5388 (insert string)
5389 (and move (backward-char 1))))
5391 (defconst org-nonsticky-props
5392 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5394 (defsubst org-rear-nonsticky-at (pos)
5395 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5397 (defun org-activate-plain-links (limit)
5398 "Run through the buffer and add overlays to links."
5399 (catch 'exit
5400 (let (f)
5401 (if (re-search-forward org-plain-link-re limit t)
5402 (progn
5403 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5404 (setq f (get-text-property (match-beginning 0) 'face))
5405 (if (or (eq f 'org-tag)
5406 (and (listp f) (memq 'org-tag f)))
5408 (add-text-properties (match-beginning 0) (match-end 0)
5409 (list 'mouse-face 'highlight
5410 'face 'org-link
5411 'keymap org-mouse-map))
5412 (org-rear-nonsticky-at (match-end 0)))
5413 t)))))
5415 (defun org-activate-code (limit)
5416 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5417 (progn
5418 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5419 (remove-text-properties (match-beginning 0) (match-end 0)
5420 '(display t invisible t intangible t))
5421 t)))
5423 (defcustom org-src-fontify-natively nil
5424 "When non-nil, fontify code in code blocks."
5425 :type 'boolean
5426 :version "24.1"
5427 :group 'org-appearance
5428 :group 'org-babel)
5430 (defcustom org-src-prevent-auto-filling nil
5431 "When non-nil, prevent auto-filling in src blocks."
5432 :type 'boolean
5433 :version "24.1"
5434 :group 'org-appearance
5435 :group 'org-babel)
5437 (defcustom org-allow-promoting-top-level-subtree nil
5438 "When non-nil, allow promoting a top level subtree.
5439 The leading star of the top level headline will be replaced
5440 by a #."
5441 :type 'boolean
5442 :version "24.1"
5443 :group 'org-appearance)
5445 (defun org-fontify-meta-lines-and-blocks (limit)
5446 (condition-case nil
5447 (org-fontify-meta-lines-and-blocks-1 limit)
5448 (error (message "org-mode fontification error"))))
5450 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5451 "Fontify #+ lines and blocks, in the correct ways."
5452 (let ((case-fold-search t))
5453 (if (re-search-forward
5454 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5455 limit t)
5456 (let ((beg (match-beginning 0))
5457 (block-start (match-end 0))
5458 (block-end nil)
5459 (lang (match-string 7))
5460 (beg1 (line-beginning-position 2))
5461 (dc1 (downcase (match-string 2)))
5462 (dc3 (downcase (match-string 3)))
5463 end end1 quoting block-type ovl)
5464 (cond
5465 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5466 ;; a single line of backend-specific content
5467 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5468 (remove-text-properties (match-beginning 0) (match-end 0)
5469 '(display t invisible t intangible t))
5470 (add-text-properties (match-beginning 1) (match-end 3)
5471 '(font-lock-fontified t face org-meta-line))
5472 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5473 '(font-lock-fontified t face org-block))
5474 ; for backend-specific code
5476 ((and (match-end 4) (equal dc3 "begin"))
5477 ;; Truly a block
5478 (setq block-type (downcase (match-string 5))
5479 quoting (member block-type org-protecting-blocks))
5480 (when (re-search-forward
5481 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5482 nil t) ;; on purpose, we look further than LIMIT
5483 (setq end (min (point-max) (match-end 0))
5484 end1 (min (point-max) (1- (match-beginning 0))))
5485 (setq block-end (match-beginning 0))
5486 (when quoting
5487 (remove-text-properties beg end
5488 '(display t invisible t intangible t)))
5489 (add-text-properties
5490 beg end
5491 '(font-lock-fontified t font-lock-multiline t))
5492 (add-text-properties beg beg1 '(face org-meta-line))
5493 (add-text-properties end1 (min (point-max) (1+ end))
5494 '(face org-meta-line)) ; for end_src
5495 (cond
5496 ((and lang (not (string= lang "")) org-src-fontify-natively)
5497 (org-src-font-lock-fontify-block lang block-start block-end)
5498 ;; remove old background overlays
5499 (mapc (lambda (ov)
5500 (if (eq (overlay-get ov 'face) 'org-block-background)
5501 (delete-overlay ov)))
5502 (overlays-at (/ (+ beg1 block-end) 2)))
5503 ;; add a background overlay
5504 (setq ovl (make-overlay beg1 block-end))
5505 (overlay-put ovl 'face 'org-block-background)
5506 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5507 (quoting
5508 (add-text-properties beg1 (min (point-max) (1+ end1))
5509 '(face org-block))) ; end of source block
5510 ((not org-fontify-quote-and-verse-blocks))
5511 ((string= block-type "quote")
5512 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5513 ((string= block-type "verse")
5514 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5515 (add-text-properties beg beg1 '(face org-block-begin-line))
5516 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5517 '(face org-block-end-line))
5519 ((member dc1 '("title:" "author:" "email:" "date:"))
5520 (add-text-properties
5521 beg (match-end 3)
5522 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5523 '(font-lock-fontified t invisible t)
5524 '(font-lock-fontified t face org-document-info-keyword)))
5525 (add-text-properties
5526 (match-beginning 6) (match-end 6)
5527 (if (string-equal dc1 "title:")
5528 '(font-lock-fontified t face org-document-title)
5529 '(font-lock-fontified t face org-document-info))))
5530 ((not (member (char-after beg) '(?\ ?\t)))
5531 ;; just any other in-buffer setting, but not indented
5532 (add-text-properties
5533 beg (match-end 0)
5534 '(font-lock-fontified t face org-meta-line))
5536 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5537 "orgtbl:" "tblfm:" "tblname:" "results:"
5538 "call:" "header:" "headers:" "name:"))
5539 (and (match-end 4) (equal dc3 "attr")))
5540 (add-text-properties
5541 beg (match-end 0)
5542 '(font-lock-fontified t face org-meta-line))
5544 ((member dc3 '(" " ""))
5545 (add-text-properties
5546 beg (match-end 0)
5547 '(font-lock-fontified t face font-lock-comment-face)))
5548 (t nil))))))
5550 (defun org-strip-protective-commas (beg end)
5551 "Strip protective commas between BEG and END in the current buffer."
5552 (interactive "r")
5553 (save-excursion
5554 (save-match-data
5555 (goto-char beg)
5556 (let ((front-line (save-excursion
5557 (re-search-forward
5558 "[^[:space:]]" end t)
5559 (goto-char (match-beginning 0))
5560 (current-column))))
5561 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5562 (goto-char (match-beginning 1))
5563 (when (= (current-column) front-line)
5564 (replace-match "" nil nil nil 1)))))))
5566 (defun org-activate-angle-links (limit)
5567 "Run through the buffer and add overlays to links."
5568 (if (re-search-forward org-angle-link-re limit t)
5569 (progn
5570 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5571 (add-text-properties (match-beginning 0) (match-end 0)
5572 (list 'mouse-face 'highlight
5573 'keymap org-mouse-map))
5574 (org-rear-nonsticky-at (match-end 0))
5575 t)))
5577 (defun org-activate-footnote-links (limit)
5578 "Run through the buffer and add overlays to footnotes."
5579 (let ((fn (org-footnote-next-reference-or-definition limit)))
5580 (when fn
5581 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5582 (org-remove-flyspell-overlays-in beg end)
5583 (add-text-properties beg end
5584 (list 'mouse-face 'highlight
5585 'keymap org-mouse-map
5586 'help-echo
5587 (if (= (point-at-bol) beg)
5588 "Footnote definition"
5589 "Footnote reference")
5590 'font-lock-fontified t
5591 'font-lock-multiline t
5592 'face 'org-footnote))))))
5594 (defun org-activate-bracket-links (limit)
5595 "Run through the buffer and add overlays to bracketed links."
5596 (if (re-search-forward org-bracket-link-regexp limit t)
5597 (let* ((help (concat "LINK: "
5598 (org-match-string-no-properties 1)))
5599 ;; FIXME: above we should remove the escapes.
5600 ;; but that requires another match, protecting match data,
5601 ;; a lot of overhead for font-lock.
5602 (ip (org-maybe-intangible
5603 (list 'invisible 'org-link
5604 'keymap org-mouse-map 'mouse-face 'highlight
5605 'font-lock-multiline t 'help-echo help)))
5606 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5607 'font-lock-multiline t 'help-echo help)))
5608 ;; We need to remove the invisible property here. Table narrowing
5609 ;; may have made some of this invisible.
5610 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5611 (remove-text-properties (match-beginning 0) (match-end 0)
5612 '(invisible nil))
5613 (if (match-end 3)
5614 (progn
5615 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5616 (org-rear-nonsticky-at (match-beginning 3))
5617 (add-text-properties (match-beginning 3) (match-end 3) vp)
5618 (org-rear-nonsticky-at (match-end 3))
5619 (add-text-properties (match-end 3) (match-end 0) ip)
5620 (org-rear-nonsticky-at (match-end 0)))
5621 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5622 (org-rear-nonsticky-at (match-beginning 1))
5623 (add-text-properties (match-beginning 1) (match-end 1) vp)
5624 (org-rear-nonsticky-at (match-end 1))
5625 (add-text-properties (match-end 1) (match-end 0) ip)
5626 (org-rear-nonsticky-at (match-end 0)))
5627 t)))
5629 (defun org-activate-dates (limit)
5630 "Run through the buffer and add overlays to dates."
5631 (if (re-search-forward org-tsr-regexp-both limit t)
5632 (progn
5633 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5634 (add-text-properties (match-beginning 0) (match-end 0)
5635 (list 'mouse-face 'highlight
5636 'keymap org-mouse-map))
5637 (org-rear-nonsticky-at (match-end 0))
5638 (when org-display-custom-times
5639 (if (match-end 3)
5640 (org-display-custom-time (match-beginning 3) (match-end 3)))
5641 (org-display-custom-time (match-beginning 1) (match-end 1)))
5642 t)))
5644 (defvar org-target-link-regexp nil
5645 "Regular expression matching radio targets in plain text.")
5646 (make-variable-buffer-local 'org-target-link-regexp)
5647 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5648 "Regular expression matching a link target.")
5649 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5650 "Regular expression matching a radio target.")
5651 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5652 "Regular expression matching any target.")
5654 (defun org-activate-target-links (limit)
5655 "Run through the buffer and add overlays to target matches."
5656 (when org-target-link-regexp
5657 (let ((case-fold-search t))
5658 (if (re-search-forward org-target-link-regexp limit t)
5659 (progn
5660 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5661 (add-text-properties (match-beginning 0) (match-end 0)
5662 (list 'mouse-face 'highlight
5663 'keymap org-mouse-map
5664 'help-echo "Radio target link"
5665 'org-linked-text t))
5666 (org-rear-nonsticky-at (match-end 0))
5667 t)))))
5669 (defun org-update-radio-target-regexp ()
5670 "Find all radio targets in this file and update the regular expression."
5671 (interactive)
5672 (when (memq 'radio org-activate-links)
5673 (setq org-target-link-regexp
5674 (org-make-target-link-regexp (org-all-targets 'radio)))
5675 (org-restart-font-lock)))
5677 (defun org-hide-wide-columns (limit)
5678 (let (s e)
5679 (setq s (text-property-any (point) (or limit (point-max))
5680 'org-cwidth t))
5681 (when s
5682 (setq e (next-single-property-change s 'org-cwidth))
5683 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5684 (goto-char e)
5685 t)))
5687 (defvar org-latex-and-specials-regexp nil
5688 "Regular expression for highlighting export special stuff.")
5689 (defvar org-match-substring-regexp)
5690 (defvar org-match-substring-with-braces-regexp)
5692 ;; This should be with the exporter code, but we also use if for font-locking
5693 (defconst org-export-html-special-string-regexps
5694 '(("\\\\-" . "&shy;")
5695 ("---\\([^-]\\)" . "&mdash;\\1")
5696 ("--\\([^-]\\)" . "&ndash;\\1")
5697 ("\\.\\.\\." . "&hellip;"))
5698 "Regular expressions for special string conversion.")
5701 (defun org-compute-latex-and-specials-regexp ()
5702 "Compute regular expression for stuff treated specially by exporters."
5703 (if (not org-highlight-latex-fragments-and-specials)
5704 (org-set-local 'org-latex-and-specials-regexp nil)
5705 (require 'org-exp)
5706 (let*
5707 ((matchers (plist-get org-format-latex-options :matchers))
5708 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5709 org-latex-regexps)))
5710 (org-export-allow-BIND nil)
5711 (options (org-combine-plists (org-default-export-plist)
5712 (org-infile-export-plist)))
5713 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5714 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5715 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5716 (org-export-html-expand (plist-get options :expand-quoted-html))
5717 (org-export-with-special-strings (plist-get options :special-strings))
5718 (re-sub
5719 (cond
5720 ((equal org-export-with-sub-superscripts '{})
5721 (list org-match-substring-with-braces-regexp))
5722 (org-export-with-sub-superscripts
5723 (list org-match-substring-regexp))
5724 (t nil)))
5725 (re-latex
5726 (if org-export-with-LaTeX-fragments
5727 (mapcar (lambda (x) (nth 1 x)) latexs)))
5728 (re-macros
5729 (if org-export-with-TeX-macros
5730 (list (concat "\\\\"
5731 (regexp-opt
5732 (append
5734 (delq nil
5735 (mapcar 'car-safe
5736 (append org-entities-user
5737 org-entities)))
5738 (if (boundp 'org-latex-entities)
5739 (mapcar (lambda (x)
5740 (or (car-safe x) x))
5741 org-latex-entities)
5742 nil))
5743 'words))) ; FIXME
5745 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5746 (re-special (if org-export-with-special-strings
5747 (mapcar (lambda (x) (car x))
5748 org-export-html-special-string-regexps)))
5749 (re-rest
5750 (delq nil
5751 (list
5752 (if org-export-html-expand "@<[^>\n]+>")
5753 ))))
5754 (org-set-local
5755 'org-latex-and-specials-regexp
5756 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5757 re-rest) "\\|")))))
5759 (defun org-do-latex-and-special-faces (limit)
5760 "Run through the buffer and add overlays to links."
5761 (when org-latex-and-specials-regexp
5762 (let (rtn d)
5763 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5764 limit t))
5765 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5766 'face))
5767 '(org-code org-verbatim underline)))
5768 (progn
5769 (setq rtn t
5770 d (cond ((member (char-after (1+ (match-beginning 0)))
5771 '(?_ ?^)) 1)
5772 (t 0)))
5773 (font-lock-prepend-text-property
5774 (+ d (match-beginning 0)) (match-end 0)
5775 'face 'org-latex-and-export-specials)
5776 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5777 '(font-lock-multiline t)))))
5778 rtn)))
5780 (defun org-restart-font-lock ()
5781 "Restart `font-lock-mode', to force refontification."
5782 (when (and (boundp 'font-lock-mode) font-lock-mode)
5783 (font-lock-mode -1)
5784 (font-lock-mode 1)))
5786 (defun org-all-targets (&optional radio)
5787 "Return a list of all targets in this file.
5788 With optional argument RADIO, only find radio targets."
5789 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5790 rtn)
5791 (save-excursion
5792 (goto-char (point-min))
5793 (while (re-search-forward re nil t)
5794 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5795 rtn)))
5797 (defun org-make-target-link-regexp (targets)
5798 "Make regular expression matching all strings in TARGETS.
5799 The regular expression finds the targets also if there is a line break
5800 between words."
5801 (and targets
5802 (concat
5803 "\\<\\("
5804 (mapconcat
5805 (lambda (x)
5806 (setq x (regexp-quote x))
5807 (while (string-match " +" x)
5808 (setq x (replace-match "\\s-+" t t x)))
5810 targets
5811 "\\|")
5812 "\\)\\>")))
5814 (defun org-activate-tags (limit)
5815 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5816 (progn
5817 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5818 (add-text-properties (match-beginning 1) (match-end 1)
5819 (list 'mouse-face 'highlight
5820 'keymap org-mouse-map))
5821 (org-rear-nonsticky-at (match-end 1))
5822 t)))
5824 (defun org-outline-level ()
5825 "Compute the outline level of the heading at point.
5826 This function assumes that the cursor is at the beginning of a line matched
5827 by `outline-regexp'. Otherwise it returns garbage.
5828 If this is called at a normal headline, the level is the number of stars.
5829 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5830 (save-excursion
5831 (looking-at org-outline-regexp)
5832 (1- (- (match-end 0) (match-beginning 0)))))
5834 (defvar org-font-lock-keywords nil)
5836 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5837 "Regular expression matching a property line.")
5839 (defvar org-font-lock-hook nil
5840 "Functions to be called for special font lock stuff.")
5842 (defvar org-font-lock-set-keywords-hook nil
5843 "Functions that can manipulate `org-font-lock-extra-keywords'.
5844 This is called after `org-font-lock-extra-keywords' is defined, but before
5845 it is installed to be used by font lock. This can be useful if something
5846 needs to be inserted at a specific position in the font-lock sequence.")
5848 (defun org-font-lock-hook (limit)
5849 (run-hook-with-args 'org-font-lock-hook limit))
5851 (defun org-set-font-lock-defaults ()
5852 (let* ((em org-fontify-emphasized-text)
5853 (lk org-activate-links)
5854 (org-font-lock-extra-keywords
5855 (list
5856 ;; Call the hook
5857 '(org-font-lock-hook)
5858 ;; Headlines
5859 `(,(if org-fontify-whole-heading-line
5860 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5861 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5862 (1 (org-get-level-face 1))
5863 (2 (org-get-level-face 2))
5864 (3 (org-get-level-face 3)))
5865 ;; Table lines
5866 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5867 (1 'org-table t))
5868 ;; Table internals
5869 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5870 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5871 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5872 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5873 ;; Drawers
5874 (list org-drawer-regexp '(0 'org-special-keyword t))
5875 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5876 ;; Properties
5877 (list org-property-re
5878 '(1 'org-special-keyword t)
5879 '(3 'org-property-value t))
5880 ;; Links
5881 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5882 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5883 (if (memq 'plain lk) '(org-activate-plain-links))
5884 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5885 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5886 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5887 (if (memq 'footnote lk) '(org-activate-footnote-links))
5888 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5889 '(org-hide-wide-columns (0 nil append))
5890 ;; TODO keyword
5891 (list (format org-heading-keyword-regexp-format
5892 org-todo-regexp)
5893 '(2 (org-get-todo-face 2) t))
5894 ;; DONE
5895 (if org-fontify-done-headline
5896 (list (format org-heading-keyword-regexp-format
5897 (concat
5898 "\\(?:"
5899 (mapconcat 'regexp-quote org-done-keywords "\\|")
5900 "\\)"))
5901 '(2 'org-headline-done t))
5902 nil)
5903 ;; Priorities
5904 '(org-font-lock-add-priority-faces)
5905 ;; Tags
5906 '(org-font-lock-add-tag-faces)
5907 ;; Special keywords
5908 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5909 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5910 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5911 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5912 ;; Emphasis
5913 (if em
5914 (if (featurep 'xemacs)
5915 '(org-do-emphasis-faces (0 nil append))
5916 '(org-do-emphasis-faces)))
5917 ;; Checkboxes
5918 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5919 1 'org-checkbox prepend)
5920 (if (cdr (assq 'checkbox org-list-automatic-rules))
5921 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5922 (0 (org-get-checkbox-statistics-face) t)))
5923 ;; Description list items
5924 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5925 1 'org-list-dt prepend)
5926 ;; ARCHIVEd headings
5927 (list (concat
5928 org-outline-regexp-bol
5929 "\\(.*:" org-archive-tag ":.*\\)")
5930 '(1 'org-archived prepend))
5931 ;; Specials
5932 '(org-do-latex-and-special-faces)
5933 '(org-fontify-entities)
5934 '(org-raise-scripts)
5935 ;; Code
5936 '(org-activate-code (1 'org-code t))
5937 ;; COMMENT
5938 (list (format org-heading-keyword-regexp-format
5939 (concat "\\("
5940 org-comment-string "\\|" org-quote-string
5941 "\\)"))
5942 '(2 'org-special-keyword t))
5943 '("^#.*" (0 'font-lock-comment-face t))
5944 ;; Blocks and meta lines
5945 '(org-fontify-meta-lines-and-blocks)
5947 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5948 (run-hooks 'org-font-lock-set-keywords-hook)
5949 ;; Now set the full font-lock-keywords
5950 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5951 (org-set-local 'font-lock-defaults
5952 '(org-font-lock-keywords t nil nil backward-paragraph))
5953 (kill-local-variable 'font-lock-keywords) nil))
5955 (defun org-toggle-pretty-entities ()
5956 "Toggle the composition display of entities as UTF8 characters."
5957 (interactive)
5958 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5959 (org-restart-font-lock)
5960 (if org-pretty-entities
5961 (message "Entities are displayed as UTF8 characters")
5962 (save-restriction
5963 (widen)
5964 (org-decompose-region (point-min) (point-max))
5965 (message "Entities are displayed plain"))))
5967 (defun org-fontify-entities (limit)
5968 "Find an entity to fontify."
5969 (let (ee)
5970 (when org-pretty-entities
5971 (catch 'match
5972 (while (re-search-forward
5973 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5974 limit t)
5975 (if (and (not (org-in-indented-comment-line))
5976 (setq ee (org-entity-get (match-string 1)))
5977 (= (length (nth 6 ee)) 1))
5978 (let*
5979 ((end (if (equal (match-string 2) "{}")
5980 (match-end 2)
5981 (match-end 1))))
5982 (add-text-properties
5983 (match-beginning 0) end
5984 (list 'font-lock-fontified t))
5985 (compose-region (match-beginning 0) end
5986 (nth 6 ee) nil)
5987 (backward-char 1)
5988 (throw 'match t))))
5989 nil))))
5991 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5992 "Fontify string S like in Org-mode."
5993 (with-temp-buffer
5994 (insert s)
5995 (let ((org-odd-levels-only odd-levels))
5996 (org-mode)
5997 (font-lock-fontify-buffer)
5998 (buffer-string))))
6000 (defvar org-m nil)
6001 (defvar org-l nil)
6002 (defvar org-f nil)
6003 (defun org-get-level-face (n)
6004 "Get the right face for match N in font-lock matching of headlines."
6005 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6006 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6007 (if org-cycle-level-faces
6008 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6009 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6010 (cond
6011 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6012 ((eq n 2) org-f)
6013 (t (if org-level-color-stars-only nil org-f))))
6016 (defun org-get-todo-face (kwd)
6017 "Get the right face for a TODO keyword KWD.
6018 If KWD is a number, get the corresponding match group."
6019 (if (numberp kwd) (setq kwd (match-string kwd)))
6020 (or (org-face-from-face-or-color
6021 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6022 (and (member kwd org-done-keywords) 'org-done)
6023 'org-todo))
6025 (defun org-face-from-face-or-color (context inherit face-or-color)
6026 "Create a face list that inherits INHERIT, but sets the foreground color.
6027 When FACE-OR-COLOR is not a string, just return it."
6028 (if (stringp face-or-color)
6029 (list :inherit inherit
6030 (cdr (assoc context org-faces-easy-properties))
6031 face-or-color)
6032 face-or-color))
6034 (defun org-font-lock-add-tag-faces (limit)
6035 "Add the special tag faces."
6036 (when (and org-tag-faces org-tags-special-faces-re)
6037 (while (re-search-forward org-tags-special-faces-re limit t)
6038 (add-text-properties (match-beginning 1) (match-end 1)
6039 (list 'face (org-get-tag-face 1)
6040 'font-lock-fontified t))
6041 (backward-char 1))))
6043 (defun org-font-lock-add-priority-faces (limit)
6044 "Add the special priority faces."
6045 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6046 (when (save-match-data (org-at-heading-p))
6047 (add-text-properties
6048 (match-beginning 0) (match-end 0)
6049 (list 'face (or (org-face-from-face-or-color
6050 'priority 'org-special-keyword
6051 (cdr (assoc (char-after (match-beginning 1))
6052 org-priority-faces)))
6053 'org-special-keyword)
6054 'font-lock-fontified t)))))
6056 (defun org-get-tag-face (kwd)
6057 "Get the right face for a TODO keyword KWD.
6058 If KWD is a number, get the corresponding match group."
6059 (if (numberp kwd) (setq kwd (match-string kwd)))
6060 (or (org-face-from-face-or-color
6061 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6062 'org-tag))
6064 (defun org-unfontify-region (beg end &optional maybe_loudly)
6065 "Remove fontification and activation overlays from links."
6066 (font-lock-default-unfontify-region beg end)
6067 (let* ((buffer-undo-list t)
6068 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6069 (inhibit-modification-hooks t)
6070 deactivate-mark buffer-file-name buffer-file-truename)
6071 (org-decompose-region beg end)
6072 (remove-text-properties beg end
6073 '(mouse-face t keymap t org-linked-text t
6074 invisible t intangible t
6075 org-no-flyspell t org-emphasis t))
6076 (org-remove-font-lock-display-properties beg end)))
6078 (defconst org-script-display '(((raise -0.3) (height 0.7))
6079 ((raise 0.3) (height 0.7))
6080 ((raise -0.5))
6081 ((raise 0.5)))
6082 "Display properties for showing superscripts and subscripts.")
6084 (defun org-remove-font-lock-display-properties (beg end)
6085 "Remove specific display properties that have been added by font lock.
6086 The will remove the raise properties that are used to show superscripts
6087 and subscripts."
6088 (let (next prop)
6089 (while (< beg end)
6090 (setq next (next-single-property-change beg 'display nil end)
6091 prop (get-text-property beg 'display))
6092 (if (member prop org-script-display)
6093 (put-text-property beg next 'display nil))
6094 (setq beg next))))
6096 (defun org-raise-scripts (limit)
6097 "Add raise properties to sub/superscripts."
6098 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6099 (if (re-search-forward
6100 (if (eq org-use-sub-superscripts t)
6101 org-match-substring-regexp
6102 org-match-substring-with-braces-regexp)
6103 limit t)
6104 (let* ((pos (point)) table-p comment-p
6105 (mpos (match-beginning 3))
6106 (emph-p (get-text-property mpos 'org-emphasis))
6107 (link-p (get-text-property mpos 'mouse-face))
6108 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6109 (goto-char (point-at-bol))
6110 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6111 comment-p (org-looking-at-p "[ \t]*#"))
6112 (goto-char pos)
6113 ;; FIXME: Should we go back one character here, for a_b^c
6114 ;; (goto-char (1- pos)) ;????????????????????
6115 (if (or comment-p emph-p link-p keyw-p)
6117 (put-text-property (match-beginning 3) (match-end 0)
6118 'display
6119 (if (equal (char-after (match-beginning 2)) ?^)
6120 (nth (if table-p 3 1) org-script-display)
6121 (nth (if table-p 2 0) org-script-display)))
6122 (add-text-properties (match-beginning 2) (match-end 2)
6123 (list 'invisible t
6124 'org-dwidth t 'org-dwidth-n 1))
6125 (if (and (eq (char-after (match-beginning 3)) ?{)
6126 (eq (char-before (match-end 3)) ?}))
6127 (progn
6128 (add-text-properties
6129 (match-beginning 3) (1+ (match-beginning 3))
6130 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6131 (add-text-properties
6132 (1- (match-end 3)) (match-end 3)
6133 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6134 t)))))
6136 ;;;; Visibility cycling, including org-goto and indirect buffer
6138 ;;; Cycling
6140 (defvar org-cycle-global-status nil)
6141 (make-variable-buffer-local 'org-cycle-global-status)
6142 (defvar org-cycle-subtree-status nil)
6143 (make-variable-buffer-local 'org-cycle-subtree-status)
6145 ;;;###autoload
6147 (defvar org-inlinetask-min-level)
6149 (defun org-cycle (&optional arg)
6150 "TAB-action and visibility cycling for Org-mode.
6152 This is the command invoked in Org-mode by the TAB key. Its main purpose
6153 is outline visibility cycling, but it also invokes other actions
6154 in special contexts.
6156 - When this function is called with a prefix argument, rotate the entire
6157 buffer through 3 states (global cycling)
6158 1. OVERVIEW: Show only top-level headlines.
6159 2. CONTENTS: Show all headlines of all levels, but no body text.
6160 3. SHOW ALL: Show everything.
6161 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6162 determined by the variable `org-startup-folded', and by any VISIBILITY
6163 properties in the buffer.
6164 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6165 including any drawers.
6167 - When inside a table, re-align the table and move to the next field.
6169 - When point is at the beginning of a headline, rotate the subtree started
6170 by this line through 3 different states (local cycling)
6171 1. FOLDED: Only the main headline is shown.
6172 2. CHILDREN: The main headline and the direct children are shown.
6173 From this state, you can move to one of the children
6174 and zoom in further.
6175 3. SUBTREE: Show the entire subtree, including body text.
6176 If there is no subtree, switch directly from CHILDREN to FOLDED.
6178 - When point is at the beginning of an empty headline and the variable
6179 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6180 of the headline by demoting and promoting it to likely levels. This
6181 speeds up creation document structure by pressing TAB once or several
6182 times right after creating a new headline.
6184 - When there is a numeric prefix, go up to a heading with level ARG, do
6185 a `show-subtree' and return to the previous cursor position. If ARG
6186 is negative, go up that many levels.
6188 - When point is not at the beginning of a headline, execute the global
6189 binding for TAB, which is re-indenting the line. See the option
6190 `org-cycle-emulate-tab' for details.
6192 - Special case: if point is at the beginning of the buffer and there is
6193 no headline in line 1, this function will act as if called with prefix arg
6194 (C-u TAB, same as S-TAB) also when called without prefix arg.
6195 But only if also the variable `org-cycle-global-at-bob' is t."
6196 (interactive "P")
6197 (org-load-modules-maybe)
6198 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6199 (and org-cycle-level-after-item/entry-creation
6200 (or (org-cycle-level)
6201 (org-cycle-item-indentation))))
6202 (let* ((limit-level
6203 (or org-cycle-max-level
6204 (and (boundp 'org-inlinetask-min-level)
6205 org-inlinetask-min-level
6206 (1- org-inlinetask-min-level))))
6207 (nstars (and limit-level
6208 (if org-odd-levels-only
6209 (and limit-level (1- (* limit-level 2)))
6210 limit-level)))
6211 (org-outline-regexp
6212 (if (not (derived-mode-p 'org-mode))
6213 outline-regexp
6214 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6215 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6216 (not (looking-at org-outline-regexp))))
6217 (org-cycle-hook
6218 (if bob-special
6219 (delq 'org-optimize-window-after-visibility-change
6220 (copy-sequence org-cycle-hook))
6221 org-cycle-hook))
6222 (pos (point)))
6224 (if (or bob-special (equal arg '(4)))
6225 ;; special case: use global cycling
6226 (setq arg t))
6228 (cond
6230 ((equal arg '(16))
6231 (setq last-command 'dummy)
6232 (org-set-startup-visibility)
6233 (message "Startup visibility, plus VISIBILITY properties"))
6235 ((equal arg '(64))
6236 (show-all)
6237 (message "Entire buffer visible, including drawers"))
6239 ;; Table: enter it or move to the next field.
6240 ((org-at-table-p 'any)
6241 (if (org-at-table.el-p)
6242 (message "Use C-c ' to edit table.el tables")
6243 (if arg (org-table-edit-field t)
6244 (org-table-justify-field-maybe)
6245 (call-interactively 'org-table-next-field))))
6247 ((run-hook-with-args-until-success
6248 'org-tab-after-check-for-table-hook))
6250 ;; Global cycling: delegate to `org-cycle-internal-global'.
6251 ((eq arg t) (org-cycle-internal-global))
6253 ;; Drawers: delegate to `org-flag-drawer'.
6254 ((and org-drawers org-drawer-regexp
6255 (save-excursion
6256 (beginning-of-line 1)
6257 (looking-at org-drawer-regexp)))
6258 (org-flag-drawer ; toggle block visibility
6259 (not (get-char-property (match-end 0) 'invisible))))
6261 ;; Show-subtree, ARG levels up from here.
6262 ((integerp arg)
6263 (save-excursion
6264 (org-back-to-heading)
6265 (outline-up-heading (if (< arg 0) (- arg)
6266 (- (funcall outline-level) arg)))
6267 (org-show-subtree)))
6269 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6270 ((and (featurep 'org-inlinetask)
6271 (org-inlinetask-at-task-p)
6272 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6273 (org-inlinetask-toggle-visibility))
6275 ((org-try-cdlatex-tab))
6277 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6278 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6279 (save-excursion (beginning-of-line 1)
6280 (looking-at org-outline-regexp)))
6281 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6282 (org-cycle-internal-local))
6284 ;; From there: TAB emulation and template completion.
6285 (buffer-read-only (org-back-to-heading))
6287 ((run-hook-with-args-until-success
6288 'org-tab-after-check-for-cycling-hook))
6290 ((org-try-structure-completion))
6292 ((run-hook-with-args-until-success
6293 'org-tab-before-tab-emulation-hook))
6295 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6296 (or (not (bolp))
6297 (not (looking-at org-outline-regexp))))
6298 (call-interactively (global-key-binding "\t")))
6300 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6301 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6302 (or (and (eq org-cycle-emulate-tab 'white)
6303 (= (match-end 0) (point-at-eol)))
6304 (and (eq org-cycle-emulate-tab 'whitestart)
6305 (>= (match-end 0) pos))))
6307 (eq org-cycle-emulate-tab t))
6308 (call-interactively (global-key-binding "\t")))
6310 (t (save-excursion
6311 (org-back-to-heading)
6312 (org-cycle)))))))
6314 (defun org-cycle-internal-global ()
6315 "Do the global cycling action."
6316 ;; Hack to avoid display of messages for .org attachments in Gnus
6317 (let ((ga (string-match "\\*fontification" (buffer-name))))
6318 (cond
6319 ((and (eq last-command this-command)
6320 (eq org-cycle-global-status 'overview))
6321 ;; We just created the overview - now do table of contents
6322 ;; This can be slow in very large buffers, so indicate action
6323 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6324 (unless ga (message "CONTENTS..."))
6325 (org-content)
6326 (unless ga (message "CONTENTS...done"))
6327 (setq org-cycle-global-status 'contents)
6328 (run-hook-with-args 'org-cycle-hook 'contents))
6330 ((and (eq last-command this-command)
6331 (eq org-cycle-global-status 'contents))
6332 ;; We just showed the table of contents - now show everything
6333 (run-hook-with-args 'org-pre-cycle-hook 'all)
6334 (show-all)
6335 (unless ga (message "SHOW ALL"))
6336 (setq org-cycle-global-status 'all)
6337 (run-hook-with-args 'org-cycle-hook 'all))
6340 ;; Default action: go to overview
6341 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6342 (org-overview)
6343 (unless ga (message "OVERVIEW"))
6344 (setq org-cycle-global-status 'overview)
6345 (run-hook-with-args 'org-cycle-hook 'overview)))))
6347 (defun org-cycle-internal-local ()
6348 "Do the local cycling action."
6349 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6350 ;; First, determine end of headline (EOH), end of subtree or item
6351 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6352 (save-excursion
6353 (if (org-at-item-p)
6354 (progn
6355 (beginning-of-line)
6356 (setq struct (org-list-struct))
6357 (setq eoh (point-at-eol))
6358 (setq eos (org-list-get-item-end-before-blank (point) struct))
6359 (setq has-children (org-list-has-child-p (point) struct)))
6360 (org-back-to-heading)
6361 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6362 (setq eos (save-excursion
6363 (org-end-of-subtree t)
6364 (unless (eobp)
6365 (skip-chars-forward " \t\n"))
6366 (if (eobp) (point) (1- (point)))))
6367 (setq has-children
6368 (or (save-excursion
6369 (let ((level (funcall outline-level)))
6370 (outline-next-heading)
6371 (and (org-at-heading-p t)
6372 (> (funcall outline-level) level))))
6373 (save-excursion
6374 (org-list-search-forward (org-item-beginning-re) eos t)))))
6375 ;; Determine end invisible part of buffer (EOL)
6376 (beginning-of-line 2)
6377 ;; XEmacs doesn't have `next-single-char-property-change'
6378 (if (featurep 'xemacs)
6379 (while (and (not (eobp)) ;; this is like `next-line'
6380 (get-char-property (1- (point)) 'invisible))
6381 (beginning-of-line 2))
6382 (while (and (not (eobp)) ;; this is like `next-line'
6383 (get-char-property (1- (point)) 'invisible))
6384 (goto-char (next-single-char-property-change (point) 'invisible))
6385 (and (eolp) (beginning-of-line 2))))
6386 (setq eol (point)))
6387 ;; Find out what to do next and set `this-command'
6388 (cond
6389 ((= eos eoh)
6390 ;; Nothing is hidden behind this heading
6391 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6392 (message "EMPTY ENTRY")
6393 (setq org-cycle-subtree-status nil)
6394 (save-excursion
6395 (goto-char eos)
6396 (outline-next-heading)
6397 (if (outline-invisible-p) (org-flag-heading nil))))
6398 ((and (or (>= eol eos)
6399 (not (string-match "\\S-" (buffer-substring eol eos))))
6400 (or has-children
6401 (not (setq children-skipped
6402 org-cycle-skip-children-state-if-no-children))))
6403 ;; Entire subtree is hidden in one line: children view
6404 (run-hook-with-args 'org-pre-cycle-hook 'children)
6405 (if (org-at-item-p)
6406 (org-list-set-item-visibility (point-at-bol) struct 'children)
6407 (org-show-entry)
6408 (org-with-limited-levels (show-children))
6409 ;; FIXME: This slows down the func way too much.
6410 ;; How keep drawers hidden in subtree anyway?
6411 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6412 ;; (org-cycle-hide-drawers 'subtree))
6414 ;; Fold every list in subtree to top-level items.
6415 (when (eq org-cycle-include-plain-lists 'integrate)
6416 (save-excursion
6417 (org-back-to-heading)
6418 (while (org-list-search-forward (org-item-beginning-re) eos t)
6419 (beginning-of-line 1)
6420 (let* ((struct (org-list-struct))
6421 (prevs (org-list-prevs-alist struct))
6422 (end (org-list-get-bottom-point struct)))
6423 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6424 (org-list-get-all-items (point) struct prevs))
6425 (goto-char end))))))
6426 (message "CHILDREN")
6427 (save-excursion
6428 (goto-char eos)
6429 (outline-next-heading)
6430 (if (outline-invisible-p) (org-flag-heading nil)))
6431 (setq org-cycle-subtree-status 'children)
6432 (run-hook-with-args 'org-cycle-hook 'children))
6433 ((or children-skipped
6434 (and (eq last-command this-command)
6435 (eq org-cycle-subtree-status 'children)))
6436 ;; We just showed the children, or no children are there,
6437 ;; now show everything.
6438 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6439 (outline-flag-region eoh eos nil)
6440 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6441 (setq org-cycle-subtree-status 'subtree)
6442 (run-hook-with-args 'org-cycle-hook 'subtree))
6444 ;; Default action: hide the subtree.
6445 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6446 (outline-flag-region eoh eos t)
6447 (message "FOLDED")
6448 (setq org-cycle-subtree-status 'folded)
6449 (run-hook-with-args 'org-cycle-hook 'folded)))))
6451 ;;;###autoload
6452 (defun org-global-cycle (&optional arg)
6453 "Cycle the global visibility. For details see `org-cycle'.
6454 With \\[universal-argument] prefix arg, switch to startup visibility.
6455 With a numeric prefix, show all headlines up to that level."
6456 (interactive "P")
6457 (let ((org-cycle-include-plain-lists
6458 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6459 (cond
6460 ((integerp arg)
6461 (show-all)
6462 (hide-sublevels arg)
6463 (setq org-cycle-global-status 'contents))
6464 ((equal arg '(4))
6465 (org-set-startup-visibility)
6466 (message "Startup visibility, plus VISIBILITY properties."))
6468 (org-cycle '(4))))))
6470 (defun org-set-startup-visibility ()
6471 "Set the visibility required by startup options and properties."
6472 (cond
6473 ((eq org-startup-folded t)
6474 (org-cycle '(4)))
6475 ((eq org-startup-folded 'content)
6476 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6477 (org-cycle '(4)) (org-cycle '(4)))))
6478 (unless (eq org-startup-folded 'showeverything)
6479 (if org-hide-block-startup (org-hide-block-all))
6480 (org-set-visibility-according-to-property 'no-cleanup)
6481 (org-cycle-hide-archived-subtrees 'all)
6482 (org-cycle-hide-drawers 'all)
6483 (org-cycle-show-empty-lines t)))
6485 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6486 "Switch subtree visibilities according to :VISIBILITY: property."
6487 (interactive)
6488 (let (org-show-entry-below state)
6489 (save-excursion
6490 (goto-char (point-min))
6491 (while (re-search-forward
6492 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6493 nil t)
6494 (setq state (match-string 1))
6495 (save-excursion
6496 (org-back-to-heading t)
6497 (hide-subtree)
6498 (org-reveal)
6499 (cond
6500 ((equal state '("fold" "folded"))
6501 (hide-subtree))
6502 ((equal state "children")
6503 (org-show-hidden-entry)
6504 (show-children))
6505 ((equal state "content")
6506 (save-excursion
6507 (save-restriction
6508 (org-narrow-to-subtree)
6509 (org-content))))
6510 ((member state '("all" "showall"))
6511 (show-subtree)))))
6512 (unless no-cleanup
6513 (org-cycle-hide-archived-subtrees 'all)
6514 (org-cycle-hide-drawers 'all)
6515 (org-cycle-show-empty-lines 'all)))))
6517 ;; This function uses outline-regexp instead of the more fundamental
6518 ;; org-outline-regexp so that org-cycle-global works outside of Org
6519 ;; buffers, where outline-regexp is needed.
6520 (defun org-overview ()
6521 "Switch to overview mode, showing only top-level headlines.
6522 Really, this shows all headlines with level equal or greater than the level
6523 of the first headline in the buffer. This is important, because if the
6524 first headline is not level one, then (hide-sublevels 1) gives confusing
6525 results."
6526 (interactive)
6527 (let ((level (save-excursion
6528 (goto-char (point-min))
6529 (if (re-search-forward (concat "^" outline-regexp) nil t)
6530 (progn
6531 (goto-char (match-beginning 0))
6532 (funcall outline-level))))))
6533 (and level (hide-sublevels level))))
6535 (defun org-content (&optional arg)
6536 "Show all headlines in the buffer, like a table of contents.
6537 With numerical argument N, show content up to level N."
6538 (interactive "P")
6539 (save-excursion
6540 ;; Visit all headings and show their offspring
6541 (and (integerp arg) (org-overview))
6542 (goto-char (point-max))
6543 (catch 'exit
6544 (while (and (progn (condition-case nil
6545 (outline-previous-visible-heading 1)
6546 (error (goto-char (point-min))))
6548 (looking-at org-outline-regexp))
6549 (if (integerp arg)
6550 (show-children (1- arg))
6551 (show-branches))
6552 (if (bobp) (throw 'exit nil))))))
6555 (defun org-optimize-window-after-visibility-change (state)
6556 "Adjust the window after a change in outline visibility.
6557 This function is the default value of the hook `org-cycle-hook'."
6558 (when (get-buffer-window (current-buffer))
6559 (cond
6560 ((eq state 'content) nil)
6561 ((eq state 'all) nil)
6562 ((eq state 'folded) nil)
6563 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6564 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6566 (defun org-remove-empty-overlays-at (pos)
6567 "Remove outline overlays that do not contain non-white stuff."
6568 (mapc
6569 (lambda (o)
6570 (and (eq 'outline (overlay-get o 'invisible))
6571 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6572 (overlay-end o))))
6573 (delete-overlay o)))
6574 (overlays-at pos)))
6576 (defun org-clean-visibility-after-subtree-move ()
6577 "Fix visibility issues after moving a subtree."
6578 ;; First, find a reasonable region to look at:
6579 ;; Start two siblings above, end three below
6580 (let* ((beg (save-excursion
6581 (and (org-get-last-sibling)
6582 (org-get-last-sibling))
6583 (point)))
6584 (end (save-excursion
6585 (and (org-get-next-sibling)
6586 (org-get-next-sibling)
6587 (org-get-next-sibling))
6588 (if (org-at-heading-p)
6589 (point-at-eol)
6590 (point))))
6591 (level (looking-at "\\*+"))
6592 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6593 (save-excursion
6594 (save-restriction
6595 (narrow-to-region beg end)
6596 (when re
6597 ;; Properly fold already folded siblings
6598 (goto-char (point-min))
6599 (while (re-search-forward re nil t)
6600 (if (and (not (outline-invisible-p))
6601 (save-excursion
6602 (goto-char (point-at-eol)) (outline-invisible-p)))
6603 (hide-entry))))
6604 (org-cycle-show-empty-lines 'overview)
6605 (org-cycle-hide-drawers 'overview)))))
6607 (defun org-cycle-show-empty-lines (state)
6608 "Show empty lines above all visible headlines.
6609 The region to be covered depends on STATE when called through
6610 `org-cycle-hook'. Lisp program can use t for STATE to get the
6611 entire buffer covered. Note that an empty line is only shown if there
6612 are at least `org-cycle-separator-lines' empty lines before the headline."
6613 (when (not (= org-cycle-separator-lines 0))
6614 (save-excursion
6615 (let* ((n (abs org-cycle-separator-lines))
6616 (re (cond
6617 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6618 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6619 (t (let ((ns (number-to-string (- n 2))))
6620 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6621 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6622 beg end b e)
6623 (cond
6624 ((memq state '(overview contents t))
6625 (setq beg (point-min) end (point-max)))
6626 ((memq state '(children folded))
6627 (setq beg (point) end (progn (org-end-of-subtree t t)
6628 (beginning-of-line 2)
6629 (point)))))
6630 (when beg
6631 (goto-char beg)
6632 (while (re-search-forward re end t)
6633 (unless (get-char-property (match-end 1) 'invisible)
6634 (setq e (match-end 1))
6635 (if (< org-cycle-separator-lines 0)
6636 (setq b (save-excursion
6637 (goto-char (match-beginning 0))
6638 (org-back-over-empty-lines)
6639 (if (save-excursion
6640 (goto-char (max (point-min) (1- (point))))
6641 (org-at-heading-p))
6642 (1- (point))
6643 (point))))
6644 (setq b (match-beginning 1)))
6645 (outline-flag-region b e nil)))))))
6646 ;; Never hide empty lines at the end of the file.
6647 (save-excursion
6648 (goto-char (point-max))
6649 (outline-previous-heading)
6650 (outline-end-of-heading)
6651 (if (and (looking-at "[ \t\n]+")
6652 (= (match-end 0) (point-max)))
6653 (outline-flag-region (point) (match-end 0) nil))))
6655 (defun org-show-empty-lines-in-parent ()
6656 "Move to the parent and re-show empty lines before visible headlines."
6657 (save-excursion
6658 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6659 (org-cycle-show-empty-lines context))))
6661 (defun org-files-list ()
6662 "Return `org-agenda-files' list, plus all open org-mode files.
6663 This is useful for operations that need to scan all of a user's
6664 open and agenda-wise Org files."
6665 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6666 (dolist (buf (buffer-list))
6667 (with-current-buffer buf
6668 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6669 (let ((file (expand-file-name (buffer-file-name))))
6670 (unless (member file files)
6671 (push file files))))))
6672 files))
6674 (defsubst org-entry-beginning-position ()
6675 "Return the beginning position of the current entry."
6676 (save-excursion (outline-back-to-heading t) (point)))
6678 (defsubst org-entry-end-position ()
6679 "Return the end position of the current entry."
6680 (save-excursion (outline-next-heading) (point)))
6682 (defun org-cycle-hide-drawers (state)
6683 "Re-hide all drawers after a visibility state change."
6684 (when (and (derived-mode-p 'org-mode)
6685 (not (memq state '(overview folded contents))))
6686 (save-excursion
6687 (let* ((globalp (memq state '(contents all)))
6688 (beg (if globalp (point-min) (point)))
6689 (end (if globalp (point-max)
6690 (if (eq state 'children)
6691 (save-excursion (outline-next-heading) (point))
6692 (org-end-of-subtree t)))))
6693 (goto-char beg)
6694 (while (re-search-forward org-drawer-regexp end t)
6695 (org-flag-drawer t))))))
6697 (defun org-flag-drawer (flag)
6698 (save-excursion
6699 (beginning-of-line 1)
6700 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6701 (let ((b (match-end 0)))
6702 (if (re-search-forward
6703 "^[ \t]*:END:"
6704 (save-excursion (outline-next-heading) (point)) t)
6705 (outline-flag-region b (point-at-eol) flag)
6706 (error ":END: line missing at position %s" b))))))
6708 (defun org-subtree-end-visible-p ()
6709 "Is the end of the current subtree visible?"
6710 (pos-visible-in-window-p
6711 (save-excursion (org-end-of-subtree t) (point))))
6713 (defun org-first-headline-recenter (&optional N)
6714 "Move cursor to the first headline and recenter the headline.
6715 Optional argument N means put the headline into the Nth line of the window."
6716 (goto-char (point-min))
6717 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6718 (beginning-of-line)
6719 (recenter (prefix-numeric-value N))))
6721 ;;; Saving and restoring visibility
6723 (defun org-outline-overlay-data (&optional use-markers)
6724 "Return a list of the locations of all outline overlays.
6725 These are overlays with the `invisible' property value `outline'.
6726 The return value is a list of cons cells, with start and stop
6727 positions for each overlay.
6728 If USE-MARKERS is set, return the positions as markers."
6729 (let (beg end)
6730 (save-excursion
6731 (save-restriction
6732 (widen)
6733 (delq nil
6734 (mapcar (lambda (o)
6735 (when (eq (overlay-get o 'invisible) 'outline)
6736 (setq beg (overlay-start o)
6737 end (overlay-end o))
6738 (and beg end (> end beg)
6739 (if use-markers
6740 (cons (move-marker (make-marker) beg)
6741 (move-marker (make-marker) end))
6742 (cons beg end)))))
6743 (overlays-in (point-min) (point-max))))))))
6745 (defun org-set-outline-overlay-data (data)
6746 "Create visibility overlays for all positions in DATA.
6747 DATA should have been made by `org-outline-overlay-data'."
6748 (let (o)
6749 (save-excursion
6750 (save-restriction
6751 (widen)
6752 (show-all)
6753 (mapc (lambda (c)
6754 (outline-flag-region (car c) (cdr c) t))
6755 data)))))
6757 ;;; Folding of blocks
6759 (defvar org-hide-block-overlays nil
6760 "Overlays hiding blocks.")
6761 (make-variable-buffer-local 'org-hide-block-overlays)
6763 (defun org-block-map (function &optional start end)
6764 "Call FUNCTION at the head of all source blocks in the current buffer.
6765 Optional arguments START and END can be used to limit the range."
6766 (let ((start (or start (point-min)))
6767 (end (or end (point-max))))
6768 (save-excursion
6769 (goto-char start)
6770 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6771 (save-excursion
6772 (save-match-data
6773 (goto-char (match-beginning 0))
6774 (funcall function)))))))
6776 (defun org-hide-block-toggle-all ()
6777 "Toggle the visibility of all blocks in the current buffer."
6778 (org-block-map #'org-hide-block-toggle))
6780 (defun org-hide-block-all ()
6781 "Fold all blocks in the current buffer."
6782 (interactive)
6783 (org-show-block-all)
6784 (org-block-map #'org-hide-block-toggle-maybe))
6786 (defun org-show-block-all ()
6787 "Unfold all blocks in the current buffer."
6788 (interactive)
6789 (mapc 'delete-overlay org-hide-block-overlays)
6790 (setq org-hide-block-overlays nil))
6792 (defun org-hide-block-toggle-maybe ()
6793 "Toggle visibility of block at point."
6794 (interactive)
6795 (let ((case-fold-search t))
6796 (if (save-excursion
6797 (beginning-of-line 1)
6798 (looking-at org-block-regexp))
6799 (progn (org-hide-block-toggle)
6800 t) ;; to signal that we took action
6801 nil))) ;; to signal that we did not
6803 (defun org-hide-block-toggle (&optional force)
6804 "Toggle the visibility of the current block."
6805 (interactive)
6806 (save-excursion
6807 (beginning-of-line)
6808 (if (re-search-forward org-block-regexp nil t)
6809 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6810 (end (match-end 0)) ;; end of entire body
6812 (if (memq t (mapcar (lambda (overlay)
6813 (eq (overlay-get overlay 'invisible)
6814 'org-hide-block))
6815 (overlays-at start)))
6816 (if (or (not force) (eq force 'off))
6817 (mapc (lambda (ov)
6818 (when (member ov org-hide-block-overlays)
6819 (setq org-hide-block-overlays
6820 (delq ov org-hide-block-overlays)))
6821 (when (eq (overlay-get ov 'invisible)
6822 'org-hide-block)
6823 (delete-overlay ov)))
6824 (overlays-at start)))
6825 (setq ov (make-overlay start end))
6826 (overlay-put ov 'invisible 'org-hide-block)
6827 ;; make the block accessible to isearch
6828 (overlay-put
6829 ov 'isearch-open-invisible
6830 (lambda (ov)
6831 (when (member ov org-hide-block-overlays)
6832 (setq org-hide-block-overlays
6833 (delq ov org-hide-block-overlays)))
6834 (when (eq (overlay-get ov 'invisible)
6835 'org-hide-block)
6836 (delete-overlay ov))))
6837 (push ov org-hide-block-overlays)))
6838 (error "Not looking at a source block"))))
6840 ;; org-tab-after-check-for-cycling-hook
6841 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6842 ;; Remove overlays when changing major mode
6843 (add-hook 'org-mode-hook
6844 (lambda () (org-add-hook 'change-major-mode-hook
6845 'org-show-block-all 'append 'local)))
6847 ;;; Org-goto
6849 (defvar org-goto-window-configuration nil)
6850 (defvar org-goto-marker nil)
6851 (defvar org-goto-map
6852 (let ((map (make-sparse-keymap)))
6853 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6854 (while (setq cmd (pop cmds))
6855 (substitute-key-definition cmd cmd map global-map)))
6856 (suppress-keymap map)
6857 (org-defkey map "\C-m" 'org-goto-ret)
6858 (org-defkey map [(return)] 'org-goto-ret)
6859 (org-defkey map [(left)] 'org-goto-left)
6860 (org-defkey map [(right)] 'org-goto-right)
6861 (org-defkey map [(control ?g)] 'org-goto-quit)
6862 (org-defkey map "\C-i" 'org-cycle)
6863 (org-defkey map [(tab)] 'org-cycle)
6864 (org-defkey map [(down)] 'outline-next-visible-heading)
6865 (org-defkey map [(up)] 'outline-previous-visible-heading)
6866 (if org-goto-auto-isearch
6867 (if (fboundp 'define-key-after)
6868 (define-key-after map [t] 'org-goto-local-auto-isearch)
6869 nil)
6870 (org-defkey map "q" 'org-goto-quit)
6871 (org-defkey map "n" 'outline-next-visible-heading)
6872 (org-defkey map "p" 'outline-previous-visible-heading)
6873 (org-defkey map "f" 'outline-forward-same-level)
6874 (org-defkey map "b" 'outline-backward-same-level)
6875 (org-defkey map "u" 'outline-up-heading))
6876 (org-defkey map "/" 'org-occur)
6877 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6878 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6879 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6880 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6881 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6882 map))
6884 (defconst org-goto-help
6885 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6886 RET=jump to location [Q]uit and return to previous location
6887 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6889 (defvar org-goto-start-pos) ; dynamically scoped parameter
6891 ;; FIXME: Docstring does not mention both interfaces
6892 (defun org-goto (&optional alternative-interface)
6893 "Look up a different location in the current file, keeping current visibility.
6895 When you want look-up or go to a different location in a
6896 document, the fastest way is often to fold the entire buffer and
6897 then dive into the tree. This method has the disadvantage, that
6898 the previous location will be folded, which may not be what you
6899 want.
6901 This command works around this by showing a copy of the current
6902 buffer in an indirect buffer, in overview mode. You can dive
6903 into the tree in that copy, use org-occur and incremental search
6904 to find a location. When pressing RET or `Q', the command
6905 returns to the original buffer in which the visibility is still
6906 unchanged. After RET it will also jump to the location selected
6907 in the indirect buffer and expose the headline hierarchy above.
6909 With a prefix argument, use the alternative interface: e.g. if
6910 `org-goto-interface' is 'outline use 'outline-path-completion."
6911 (interactive "P")
6912 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6913 (org-refile-use-outline-path t)
6914 (org-refile-target-verify-function nil)
6915 (interface
6916 (if (not alternative-interface)
6917 org-goto-interface
6918 (if (eq org-goto-interface 'outline)
6919 'outline-path-completion
6920 'outline)))
6921 (org-goto-start-pos (point))
6922 (selected-point
6923 (if (eq interface 'outline)
6924 (car (org-get-location (current-buffer) org-goto-help))
6925 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6926 (org-refile-check-position pa)
6927 (nth 3 pa)))))
6928 (if selected-point
6929 (progn
6930 (org-mark-ring-push org-goto-start-pos)
6931 (goto-char selected-point)
6932 (if (or (outline-invisible-p) (org-invisible-p2))
6933 (org-show-context 'org-goto)))
6934 (message "Quit"))))
6936 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6937 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6938 (defvar org-goto-local-auto-isearch-map) ; defined below
6940 (defun org-get-location (buf help)
6941 "Let the user select a location in the Org-mode buffer BUF.
6942 This function uses a recursive edit. It returns the selected position
6943 or nil."
6944 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6945 (isearch-hide-immediately nil)
6946 (isearch-search-fun-function
6947 (lambda () 'org-goto-local-search-headings))
6948 (org-goto-selected-point org-goto-exit-command)
6949 (pop-up-frames nil)
6950 (special-display-buffer-names nil)
6951 (special-display-regexps nil)
6952 (special-display-function nil))
6953 (save-excursion
6954 (save-window-excursion
6955 (delete-other-windows)
6956 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6957 (org-pop-to-buffer-same-window
6958 (condition-case nil
6959 (make-indirect-buffer (current-buffer) "*org-goto*")
6960 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6961 (with-output-to-temp-buffer "*Help*"
6962 (princ help))
6963 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6964 (setq buffer-read-only nil)
6965 (let ((org-startup-truncated t)
6966 (org-startup-folded nil)
6967 (org-startup-align-all-tables nil))
6968 (org-mode)
6969 (org-overview))
6970 (setq buffer-read-only t)
6971 (if (and (boundp 'org-goto-start-pos)
6972 (integer-or-marker-p org-goto-start-pos))
6973 (let ((org-show-hierarchy-above t)
6974 (org-show-siblings t)
6975 (org-show-following-heading t))
6976 (goto-char org-goto-start-pos)
6977 (and (outline-invisible-p) (org-show-context)))
6978 (goto-char (point-min)))
6979 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6980 (message "Select location and press RET")
6981 (use-local-map org-goto-map)
6982 (recursive-edit)
6984 (kill-buffer "*org-goto*")
6985 (cons org-goto-selected-point org-goto-exit-command)))
6987 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6988 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6989 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6990 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6992 (defun org-goto-local-search-headings (string bound noerror)
6993 "Search and make sure that any matches are in headlines."
6994 (catch 'return
6995 (while (if isearch-forward
6996 (search-forward string bound noerror)
6997 (search-backward string bound noerror))
6998 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6999 (and (member :headline context)
7000 (not (member :tags context))))
7001 (throw 'return (point))))))
7003 (defun org-goto-local-auto-isearch ()
7004 "Start isearch."
7005 (interactive)
7006 (goto-char (point-min))
7007 (let ((keys (this-command-keys)))
7008 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7009 (isearch-mode t)
7010 (isearch-process-search-char (string-to-char keys)))))
7012 (defun org-goto-ret (&optional arg)
7013 "Finish `org-goto' by going to the new location."
7014 (interactive "P")
7015 (setq org-goto-selected-point (point)
7016 org-goto-exit-command 'return)
7017 (throw 'exit nil))
7019 (defun org-goto-left ()
7020 "Finish `org-goto' by going to the new location."
7021 (interactive)
7022 (if (org-at-heading-p)
7023 (progn
7024 (beginning-of-line 1)
7025 (setq org-goto-selected-point (point)
7026 org-goto-exit-command 'left)
7027 (throw 'exit nil))
7028 (error "Not on a heading")))
7030 (defun org-goto-right ()
7031 "Finish `org-goto' by going to the new location."
7032 (interactive)
7033 (if (org-at-heading-p)
7034 (progn
7035 (setq org-goto-selected-point (point)
7036 org-goto-exit-command 'right)
7037 (throw 'exit nil))
7038 (error "Not on a heading")))
7040 (defun org-goto-quit ()
7041 "Finish `org-goto' without cursor motion."
7042 (interactive)
7043 (setq org-goto-selected-point nil)
7044 (setq org-goto-exit-command 'quit)
7045 (throw 'exit nil))
7047 ;;; Indirect buffer display of subtrees
7049 (defvar org-indirect-dedicated-frame nil
7050 "This is the frame being used for indirect tree display.")
7051 (defvar org-last-indirect-buffer nil)
7053 (defun org-tree-to-indirect-buffer (&optional arg)
7054 "Create indirect buffer and narrow it to current subtree.
7055 With numerical prefix ARG, go up to this level and then take that tree.
7056 If ARG is negative, go up that many levels.
7057 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7058 indirect buffer previously made with this command, to avoid proliferation of
7059 indirect buffers. However, when you call the command with a \
7060 \\[universal-argument] prefix, or
7061 when `org-indirect-buffer-display' is `new-frame', the last buffer
7062 is kept so that you can work with several indirect buffers at the same time.
7063 If `org-indirect-buffer-display' is `dedicated-frame', the \
7064 \\[universal-argument] prefix also
7065 requests that a new frame be made for the new buffer, so that the dedicated
7066 frame is not changed."
7067 (interactive "P")
7068 (let ((cbuf (current-buffer))
7069 (cwin (selected-window))
7070 (pos (point))
7071 beg end level heading ibuf)
7072 (save-excursion
7073 (org-back-to-heading t)
7074 (when (numberp arg)
7075 (setq level (org-outline-level))
7076 (if (< arg 0) (setq arg (+ level arg)))
7077 (while (> (setq level (org-outline-level)) arg)
7078 (outline-up-heading 1 t)))
7079 (setq beg (point)
7080 heading (org-get-heading))
7081 (org-end-of-subtree t t)
7082 (if (org-at-heading-p) (backward-char 1))
7083 (setq end (point)))
7084 (if (and (buffer-live-p org-last-indirect-buffer)
7085 (not (eq org-indirect-buffer-display 'new-frame))
7086 (not arg))
7087 (kill-buffer org-last-indirect-buffer))
7088 (setq ibuf (org-get-indirect-buffer cbuf)
7089 org-last-indirect-buffer ibuf)
7090 (cond
7091 ((or (eq org-indirect-buffer-display 'new-frame)
7092 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7093 (select-frame (make-frame))
7094 (delete-other-windows)
7095 (org-pop-to-buffer-same-window ibuf)
7096 (org-set-frame-title heading))
7097 ((eq org-indirect-buffer-display 'dedicated-frame)
7098 (raise-frame
7099 (select-frame (or (and org-indirect-dedicated-frame
7100 (frame-live-p org-indirect-dedicated-frame)
7101 org-indirect-dedicated-frame)
7102 (setq org-indirect-dedicated-frame (make-frame)))))
7103 (delete-other-windows)
7104 (org-pop-to-buffer-same-window ibuf)
7105 (org-set-frame-title (concat "Indirect: " heading)))
7106 ((eq org-indirect-buffer-display 'current-window)
7107 (org-pop-to-buffer-same-window ibuf))
7108 ((eq org-indirect-buffer-display 'other-window)
7109 (pop-to-buffer ibuf))
7110 (t (error "Invalid value")))
7111 (if (featurep 'xemacs)
7112 (save-excursion (org-mode) (turn-on-font-lock)))
7113 (narrow-to-region beg end)
7114 (show-all)
7115 (goto-char pos)
7116 (run-hook-with-args 'org-cycle-hook 'all)
7117 (and (window-live-p cwin) (select-window cwin))))
7119 (defun org-get-indirect-buffer (&optional buffer)
7120 (setq buffer (or buffer (current-buffer)))
7121 (let ((n 1) (base (buffer-name buffer)) bname)
7122 (while (buffer-live-p
7123 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7124 (setq n (1+ n)))
7125 (condition-case nil
7126 (make-indirect-buffer buffer bname 'clone)
7127 (error (make-indirect-buffer buffer bname)))))
7129 (defun org-set-frame-title (title)
7130 "Set the title of the current frame to the string TITLE."
7131 ;; FIXME: how to name a single frame in XEmacs???
7132 (unless (featurep 'xemacs)
7133 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7135 ;;;; Structure editing
7137 ;;; Inserting headlines
7139 (defun org-previous-line-empty-p ()
7140 (save-excursion
7141 (and (not (bobp))
7142 (or (beginning-of-line 0) t)
7143 (save-match-data
7144 (looking-at "[ \t]*$")))))
7146 (defun org-insert-heading (&optional force-heading invisible-ok)
7147 "Insert a new heading or item with same depth at point.
7148 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7149 If point is at the beginning of a headline, insert a sibling before the
7150 current headline. If point is not at the beginning, split the line,
7151 create the new headline with the text in the current line after point
7152 \(but see also the variable `org-M-RET-may-split-line').
7154 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7155 This is important for non-interactive uses of the command."
7156 (interactive "P")
7157 (if (or (= (buffer-size) 0)
7158 (and (not (save-excursion
7159 (and (ignore-errors (org-back-to-heading invisible-ok))
7160 (org-at-heading-p))))
7161 (or force-heading (not (org-in-item-p)))))
7162 (progn
7163 (insert "\n* ")
7164 (run-hooks 'org-insert-heading-hook))
7165 (when (or force-heading (not (org-insert-item)))
7166 (let* ((empty-line-p nil)
7167 (level nil)
7168 (on-heading (org-at-heading-p))
7169 (head (save-excursion
7170 (condition-case nil
7171 (progn
7172 (org-back-to-heading invisible-ok)
7173 (when (and (not on-heading)
7174 (featurep 'org-inlinetask)
7175 (integerp org-inlinetask-min-level)
7176 (>= (length (match-string 0))
7177 org-inlinetask-min-level))
7178 ;; Find a heading level before the inline task
7179 (while (and (setq level (org-up-heading-safe))
7180 (>= level org-inlinetask-min-level)))
7181 (if (org-at-heading-p)
7182 (org-back-to-heading invisible-ok)
7183 (error "This should not happen")))
7184 (setq empty-line-p (org-previous-line-empty-p))
7185 (match-string 0))
7186 (error "*"))))
7187 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7188 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7189 pos hide-previous previous-pos)
7190 (cond
7191 ((and (org-at-heading-p) (bolp)
7192 (or (bobp)
7193 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7194 ;; insert before the current line
7195 (open-line (if blank 2 1)))
7196 ((and (bolp)
7197 (not org-insert-heading-respect-content)
7198 (or (bobp)
7199 (save-excursion
7200 (backward-char 1) (not (outline-invisible-p)))))
7201 ;; insert right here
7202 nil)
7204 ;; somewhere in the line
7205 (save-excursion
7206 (setq previous-pos (point-at-bol))
7207 (end-of-line)
7208 (setq hide-previous (outline-invisible-p)))
7209 (and org-insert-heading-respect-content (org-show-subtree))
7210 (let ((split
7211 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7212 (save-excursion
7213 (let ((p (point)))
7214 (goto-char (point-at-bol))
7215 (and (looking-at org-complex-heading-regexp)
7216 (match-beginning 4)
7217 (> p (match-beginning 4)))))))
7218 tags pos)
7219 (cond
7220 (org-insert-heading-respect-content
7221 (org-end-of-subtree nil t)
7222 (when (featurep 'org-inlinetask)
7223 (while (and (not (eobp))
7224 (looking-at "\\(\\*+\\)[ \t]+")
7225 (>= (length (match-string 1))
7226 org-inlinetask-min-level))
7227 (org-end-of-subtree nil t)))
7228 (or (bolp) (newline))
7229 (or (org-previous-line-empty-p)
7230 (and blank (newline)))
7231 (open-line 1))
7232 ((org-at-heading-p)
7233 (when hide-previous
7234 (show-children)
7235 (org-show-entry))
7236 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7237 (setq tags (and (match-end 2) (match-string 2)))
7238 (and (match-end 1)
7239 (delete-region (match-beginning 1) (match-end 1)))
7240 (setq pos (point-at-bol))
7241 (or split (end-of-line 1))
7242 (delete-horizontal-space)
7243 (if (string-match "\\`\\*+\\'"
7244 (buffer-substring (point-at-bol) (point)))
7245 (insert " "))
7246 (newline (if blank 2 1))
7247 (when tags
7248 (save-excursion
7249 (goto-char pos)
7250 (end-of-line 1)
7251 (insert " " tags)
7252 (org-set-tags nil 'align))))
7254 (or split (end-of-line 1))
7255 (newline (if blank 2 1)))))))
7256 (insert head) (just-one-space)
7257 (setq pos (point))
7258 (end-of-line 1)
7259 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7260 (when (and org-insert-heading-respect-content hide-previous)
7261 (save-excursion
7262 (goto-char previous-pos)
7263 (hide-subtree)))
7264 (run-hooks 'org-insert-heading-hook)))))
7266 (defun org-get-heading (&optional no-tags no-todo)
7267 "Return the heading of the current entry, without the stars.
7268 When NO-TAGS is non-nil, don't include tags.
7269 When NO-TODO is non-nil, don't include TODO keywords."
7270 (save-excursion
7271 (org-back-to-heading t)
7272 (cond
7273 ((and no-tags no-todo)
7274 (looking-at org-complex-heading-regexp)
7275 (match-string 4))
7276 (no-tags
7277 (looking-at (concat org-outline-regexp
7278 "\\(.*?\\)"
7279 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7280 (match-string 1))
7281 (no-todo
7282 (looking-at org-todo-line-regexp)
7283 (match-string 3))
7284 (t (looking-at org-heading-regexp)
7285 (match-string 2)))))
7287 (defun org-heading-components ()
7288 "Return the components of the current heading.
7289 This is a list with the following elements:
7290 - the level as an integer
7291 - the reduced level, different if `org-odd-levels-only' is set.
7292 - the TODO keyword, or nil
7293 - the priority character, like ?A, or nil if no priority is given
7294 - the headline text itself, or the tags string if no headline text
7295 - the tags string, or nil."
7296 (save-excursion
7297 (org-back-to-heading t)
7298 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7299 (list (length (match-string 1))
7300 (org-reduced-level (length (match-string 1)))
7301 (org-match-string-no-properties 2)
7302 (and (match-end 3) (aref (match-string 3) 2))
7303 (org-match-string-no-properties 4)
7304 (org-match-string-no-properties 5)))))
7306 (defun org-get-entry ()
7307 "Get the entry text, after heading, entire subtree."
7308 (save-excursion
7309 (org-back-to-heading t)
7310 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7312 (defun org-insert-heading-after-current ()
7313 "Insert a new heading with same level as current, after current subtree."
7314 (interactive)
7315 (org-back-to-heading)
7316 (org-insert-heading)
7317 (org-move-subtree-down)
7318 (end-of-line 1))
7320 (defun org-insert-heading-respect-content ()
7321 (interactive)
7322 (let ((org-insert-heading-respect-content t))
7323 (org-insert-heading t)))
7325 (defun org-insert-todo-heading-respect-content (&optional force-state)
7326 (interactive "P")
7327 (let ((org-insert-heading-respect-content t))
7328 (org-insert-todo-heading force-state t)))
7330 (defun org-insert-todo-heading (arg &optional force-heading)
7331 "Insert a new heading with the same level and TODO state as current heading.
7332 If the heading has no TODO state, or if the state is DONE, use the first
7333 state (TODO by default). Also with prefix arg, force first state."
7334 (interactive "P")
7335 (when (or force-heading (not (org-insert-item 'checkbox)))
7336 (org-insert-heading force-heading)
7337 (save-excursion
7338 (org-back-to-heading)
7339 (outline-previous-heading)
7340 (looking-at org-todo-line-regexp))
7341 (let*
7342 ((new-mark-x
7343 (if (or arg
7344 (not (match-beginning 2))
7345 (member (match-string 2) org-done-keywords))
7346 (car org-todo-keywords-1)
7347 (match-string 2)))
7348 (new-mark
7350 (run-hook-with-args-until-success
7351 'org-todo-get-default-hook new-mark-x nil)
7352 new-mark-x)))
7353 (beginning-of-line 1)
7354 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7355 (if org-treat-insert-todo-heading-as-state-change
7356 (org-todo new-mark)
7357 (insert new-mark " "))))
7358 (when org-provide-todo-statistics
7359 (org-update-parent-todo-statistics))))
7361 (defun org-insert-subheading (arg)
7362 "Insert a new subheading and demote it.
7363 Works for outline headings and for plain lists alike."
7364 (interactive "P")
7365 (org-insert-heading arg)
7366 (cond
7367 ((org-at-heading-p) (org-do-demote))
7368 ((org-at-item-p) (org-indent-item))))
7370 (defun org-insert-todo-subheading (arg)
7371 "Insert a new subheading with TODO keyword or checkbox and demote it.
7372 Works for outline headings and for plain lists alike."
7373 (interactive "P")
7374 (org-insert-todo-heading arg)
7375 (cond
7376 ((org-at-heading-p) (org-do-demote))
7377 ((org-at-item-p) (org-indent-item))))
7379 ;;; Promotion and Demotion
7381 (defvar org-after-demote-entry-hook nil
7382 "Hook run after an entry has been demoted.
7383 The cursor will be at the beginning of the entry.
7384 When a subtree is being demoted, the hook will be called for each node.")
7386 (defvar org-after-promote-entry-hook nil
7387 "Hook run after an entry has been promoted.
7388 The cursor will be at the beginning of the entry.
7389 When a subtree is being promoted, the hook will be called for each node.")
7391 (defun org-promote-subtree ()
7392 "Promote the entire subtree.
7393 See also `org-promote'."
7394 (interactive)
7395 (save-excursion
7396 (org-with-limited-levels (org-map-tree 'org-promote)))
7397 (org-fix-position-after-promote))
7399 (defun org-demote-subtree ()
7400 "Demote the entire subtree. See `org-demote'.
7401 See also `org-promote'."
7402 (interactive)
7403 (save-excursion
7404 (org-with-limited-levels (org-map-tree 'org-demote)))
7405 (org-fix-position-after-promote))
7408 (defun org-do-promote ()
7409 "Promote the current heading higher up the tree.
7410 If the region is active in `transient-mark-mode', promote all headings
7411 in the region."
7412 (interactive)
7413 (save-excursion
7414 (if (org-region-active-p)
7415 (org-map-region 'org-promote (region-beginning) (region-end))
7416 (org-promote)))
7417 (org-fix-position-after-promote))
7419 (defun org-do-demote ()
7420 "Demote the current heading lower down the tree.
7421 If the region is active in `transient-mark-mode', demote all headings
7422 in the region."
7423 (interactive)
7424 (save-excursion
7425 (if (org-region-active-p)
7426 (org-map-region 'org-demote (region-beginning) (region-end))
7427 (org-demote)))
7428 (org-fix-position-after-promote))
7430 (defun org-fix-position-after-promote ()
7431 "Make sure that after pro/demotion cursor position is right."
7432 (let ((pos (point)))
7433 (when (save-excursion
7434 (beginning-of-line 1)
7435 (looking-at org-todo-line-regexp)
7436 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7437 (cond ((eobp) (insert " "))
7438 ((eolp) (insert " "))
7439 ((equal (char-after) ?\ ) (forward-char 1))))))
7441 (defun org-current-level ()
7442 "Return the level of the current entry, or nil if before the first headline.
7443 The level is the number of stars at the beginning of the headline."
7444 (save-excursion
7445 (org-with-limited-levels
7446 (if (ignore-errors (org-back-to-heading t))
7447 (funcall outline-level)))))
7449 (defun org-get-previous-line-level ()
7450 "Return the outline depth of the last headline before the current line.
7451 Returns 0 for the first headline in the buffer, and nil if before the
7452 first headline."
7453 (let ((current-level (org-current-level))
7454 (prev-level (when (> (line-number-at-pos) 1)
7455 (save-excursion
7456 (beginning-of-line 0)
7457 (org-current-level)))))
7458 (cond ((null current-level) nil) ; Before first headline
7459 ((null prev-level) 0) ; At first headline
7460 (prev-level))))
7462 (defun org-reduced-level (l)
7463 "Compute the effective level of a heading.
7464 This takes into account the setting of `org-odd-levels-only'."
7465 (cond
7466 ((zerop l) 0)
7467 (org-odd-levels-only (1+ (floor (/ l 2))))
7468 (t l)))
7470 (defun org-level-increment ()
7471 "Return the number of stars that will be added or removed at a
7472 time to headlines when structure editing, based on the value of
7473 `org-odd-levels-only'."
7474 (if org-odd-levels-only 2 1))
7476 (defun org-get-valid-level (level &optional change)
7477 "Rectify a level change under the influence of `org-odd-levels-only'
7478 LEVEL is a current level, CHANGE is by how much the level should be
7479 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7480 even level numbers will become the next higher odd number."
7481 (if org-odd-levels-only
7482 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7483 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7484 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7485 (max 1 (+ level (or change 0)))))
7487 (if (boundp 'define-obsolete-function-alias)
7488 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7489 (define-obsolete-function-alias 'org-get-legal-level
7490 'org-get-valid-level)
7491 (define-obsolete-function-alias 'org-get-legal-level
7492 'org-get-valid-level "23.1")))
7494 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7495 ;; ̀org-with-limited-levels'
7496 (defun org-promote ()
7497 "Promote the current heading higher up the tree.
7498 If the region is active in `transient-mark-mode', promote all headings
7499 in the region."
7500 (org-back-to-heading t)
7501 (let* ((level (save-match-data (funcall outline-level)))
7502 (after-change-functions (remove 'flyspell-after-change-function
7503 after-change-functions))
7504 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7505 (diff (abs (- level (length up-head) -1))))
7506 (cond ((and (= level 1) org-called-with-limited-levels
7507 org-allow-promoting-top-level-subtree)
7508 (replace-match "# " nil t))
7509 ((= level 1)
7510 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7511 (t (replace-match up-head nil t)))
7512 ;; Fixup tag positioning
7513 (unless (= level 1)
7514 (and org-auto-align-tags (org-set-tags nil t))
7515 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7516 (run-hooks 'org-after-promote-entry-hook)))
7518 (defun org-demote ()
7519 "Demote the current heading lower down the tree.
7520 If the region is active in `transient-mark-mode', demote all headings
7521 in the region."
7522 (org-back-to-heading t)
7523 (let* ((level (save-match-data (funcall outline-level)))
7524 (after-change-functions (remove 'flyspell-after-change-function
7525 after-change-functions))
7526 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7527 (diff (abs (- level (length down-head) -1))))
7528 (replace-match down-head nil t)
7529 ;; Fixup tag positioning
7530 (and org-auto-align-tags (org-set-tags nil t))
7531 (if org-adapt-indentation (org-fixup-indentation diff))
7532 (run-hooks 'org-after-demote-entry-hook)))
7534 (defun org-cycle-level ()
7535 "Cycle the level of an empty headline through possible states.
7536 This goes first to child, then to parent, level, then up the hierarchy.
7537 After top level, it switches back to sibling level."
7538 (interactive)
7539 (let ((org-adapt-indentation nil))
7540 (when (org-point-at-end-of-empty-headline)
7541 (setq this-command 'org-cycle-level) ; Only needed for caching
7542 (let ((cur-level (org-current-level))
7543 (prev-level (org-get-previous-line-level)))
7544 (cond
7545 ;; If first headline in file, promote to top-level.
7546 ((= prev-level 0)
7547 (loop repeat (/ (- cur-level 1) (org-level-increment))
7548 do (org-do-promote)))
7549 ;; If same level as prev, demote one.
7550 ((= prev-level cur-level)
7551 (org-do-demote))
7552 ;; If parent is top-level, promote to top level if not already.
7553 ((= prev-level 1)
7554 (loop repeat (/ (- cur-level 1) (org-level-increment))
7555 do (org-do-promote)))
7556 ;; If top-level, return to prev-level.
7557 ((= cur-level 1)
7558 (loop repeat (/ (- prev-level 1) (org-level-increment))
7559 do (org-do-demote)))
7560 ;; If less than prev-level, promote one.
7561 ((< cur-level prev-level)
7562 (org-do-promote))
7563 ;; If deeper than prev-level, promote until higher than
7564 ;; prev-level.
7565 ((> cur-level prev-level)
7566 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7567 do (org-do-promote))))
7568 t))))
7570 (defun org-map-tree (fun)
7571 "Call FUN for every heading underneath the current one."
7572 (org-back-to-heading)
7573 (let ((level (funcall outline-level)))
7574 (save-excursion
7575 (funcall fun)
7576 (while (and (progn
7577 (outline-next-heading)
7578 (> (funcall outline-level) level))
7579 (not (eobp)))
7580 (funcall fun)))))
7582 (defun org-map-region (fun beg end)
7583 "Call FUN for every heading between BEG and END."
7584 (let ((org-ignore-region t))
7585 (save-excursion
7586 (setq end (copy-marker end))
7587 (goto-char beg)
7588 (if (and (re-search-forward org-outline-regexp-bol nil t)
7589 (< (point) end))
7590 (funcall fun))
7591 (while (and (progn
7592 (outline-next-heading)
7593 (< (point) end))
7594 (not (eobp)))
7595 (funcall fun)))))
7597 (defvar org-property-end-re) ; silence byte-compiler
7598 (defun org-fixup-indentation (diff)
7599 "Change the indentation in the current entry by DIFF.
7600 However, if any line in the current entry has no indentation, or if it
7601 would end up with no indentation after the change, nothing at all is done."
7602 (save-excursion
7603 (let ((end (save-excursion (outline-next-heading)
7604 (point-marker)))
7605 (prohibit (if (> diff 0)
7606 "^\\S-"
7607 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7608 col)
7609 (unless (save-excursion (end-of-line 1)
7610 (re-search-forward prohibit end t))
7611 (while (and (< (point) end)
7612 (re-search-forward "^[ \t]+" end t))
7613 (goto-char (match-end 0))
7614 (setq col (current-column))
7615 (if (< diff 0) (replace-match ""))
7616 (org-indent-to-column (+ diff col))))
7617 (move-marker end nil))))
7619 (defun org-convert-to-odd-levels ()
7620 "Convert an org-mode file with all levels allowed to one with odd levels.
7621 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7622 level 5 etc."
7623 (interactive)
7624 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7625 (let ((outline-level 'org-outline-level)
7626 (org-odd-levels-only nil) n)
7627 (save-excursion
7628 (goto-char (point-min))
7629 (while (re-search-forward "^\\*\\*+ " nil t)
7630 (setq n (- (length (match-string 0)) 2))
7631 (while (>= (setq n (1- n)) 0)
7632 (org-demote))
7633 (end-of-line 1))))))
7635 (defun org-convert-to-oddeven-levels ()
7636 "Convert an org-mode file with only odd levels to one with odd/even levels.
7637 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7638 file contains a section with an even level, conversion would
7639 destroy the structure of the file. An error is signaled in this
7640 case."
7641 (interactive)
7642 (goto-char (point-min))
7643 ;; First check if there are no even levels
7644 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7645 (org-show-context t)
7646 (error "Not all levels are odd in this file. Conversion not possible"))
7647 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7648 (let ((outline-regexp org-outline-regexp)
7649 (outline-level 'org-outline-level)
7650 (org-odd-levels-only nil) n)
7651 (save-excursion
7652 (goto-char (point-min))
7653 (while (re-search-forward "^\\*\\*+ " nil t)
7654 (setq n (/ (1- (length (match-string 0))) 2))
7655 (while (>= (setq n (1- n)) 0)
7656 (org-promote))
7657 (end-of-line 1))))))
7659 (defun org-tr-level (n)
7660 "Make N odd if required."
7661 (if org-odd-levels-only (1+ (/ n 2)) n))
7663 ;;; Vertical tree motion, cutting and pasting of subtrees
7665 (defun org-move-subtree-up (&optional arg)
7666 "Move the current subtree up past ARG headlines of the same level."
7667 (interactive "p")
7668 (org-move-subtree-down (- (prefix-numeric-value arg))))
7670 (defun org-move-subtree-down (&optional arg)
7671 "Move the current subtree down past ARG headlines of the same level."
7672 (interactive "p")
7673 (setq arg (prefix-numeric-value arg))
7674 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7675 'org-get-last-sibling))
7676 (ins-point (make-marker))
7677 (cnt (abs arg))
7678 (col (current-column))
7679 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7680 ;; Select the tree
7681 (org-back-to-heading)
7682 (setq beg0 (point))
7683 (save-excursion
7684 (setq ne-beg (org-back-over-empty-lines))
7685 (setq beg (point)))
7686 (save-match-data
7687 (save-excursion (outline-end-of-heading)
7688 (setq folded (outline-invisible-p)))
7689 (outline-end-of-subtree))
7690 (outline-next-heading)
7691 (setq ne-end (org-back-over-empty-lines))
7692 (setq end (point))
7693 (goto-char beg0)
7694 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7695 ;; include less whitespace
7696 (save-excursion
7697 (goto-char beg)
7698 (forward-line (- ne-beg ne-end))
7699 (setq beg (point))))
7700 ;; Find insertion point, with error handling
7701 (while (> cnt 0)
7702 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7703 (progn (goto-char beg0)
7704 (error "Cannot move past superior level or buffer limit")))
7705 (setq cnt (1- cnt)))
7706 (if (> arg 0)
7707 ;; Moving forward - still need to move over subtree
7708 (progn (org-end-of-subtree t t)
7709 (save-excursion
7710 (org-back-over-empty-lines)
7711 (or (bolp) (newline)))))
7712 (setq ne-ins (org-back-over-empty-lines))
7713 (move-marker ins-point (point))
7714 (setq txt (buffer-substring beg end))
7715 (org-save-markers-in-region beg end)
7716 (delete-region beg end)
7717 (org-remove-empty-overlays-at beg)
7718 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7719 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7720 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7721 (let ((bbb (point)))
7722 (insert-before-markers txt)
7723 (org-reinstall-markers-in-region bbb)
7724 (move-marker ins-point bbb))
7725 (or (bolp) (insert "\n"))
7726 (setq ins-end (point))
7727 (goto-char ins-point)
7728 (org-skip-whitespace)
7729 (when (and (< arg 0)
7730 (org-first-sibling-p)
7731 (> ne-ins ne-beg))
7732 ;; Move whitespace back to beginning
7733 (save-excursion
7734 (goto-char ins-end)
7735 (let ((kill-whole-line t))
7736 (kill-line (- ne-ins ne-beg)) (point)))
7737 (insert (make-string (- ne-ins ne-beg) ?\n)))
7738 (move-marker ins-point nil)
7739 (if folded
7740 (hide-subtree)
7741 (org-show-entry)
7742 (show-children)
7743 (org-cycle-hide-drawers 'children))
7744 (org-clean-visibility-after-subtree-move)
7745 ;; move back to the initial column we were at
7746 (move-to-column col)))
7748 (defvar org-subtree-clip ""
7749 "Clipboard for cut and paste of subtrees.
7750 This is actually only a copy of the kill, because we use the normal kill
7751 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7753 (defvar org-subtree-clip-folded nil
7754 "Was the last copied subtree folded?
7755 This is used to fold the tree back after pasting.")
7757 (defun org-cut-subtree (&optional n)
7758 "Cut the current subtree into the clipboard.
7759 With prefix arg N, cut this many sequential subtrees.
7760 This is a short-hand for marking the subtree and then cutting it."
7761 (interactive "p")
7762 (org-copy-subtree n 'cut))
7764 (defun org-copy-subtree (&optional n cut force-store-markers)
7765 "Cut the current subtree into the clipboard.
7766 With prefix arg N, cut this many sequential subtrees.
7767 This is a short-hand for marking the subtree and then copying it.
7768 If CUT is non-nil, actually cut the subtree.
7769 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7770 of some markers in the region, even if CUT is non-nil. This is
7771 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7772 (interactive "p")
7773 (let (beg end folded (beg0 (point)))
7774 (if (org-called-interactively-p 'any)
7775 (org-back-to-heading nil) ; take what looks like a subtree
7776 (org-back-to-heading t)) ; take what is really there
7777 (org-back-over-empty-lines)
7778 (setq beg (point))
7779 (skip-chars-forward " \t\r\n")
7780 (save-match-data
7781 (save-excursion (outline-end-of-heading)
7782 (setq folded (outline-invisible-p)))
7783 (condition-case nil
7784 (org-forward-same-level (1- n) t)
7785 (error nil))
7786 (org-end-of-subtree t t))
7787 (org-back-over-empty-lines)
7788 (setq end (point))
7789 (goto-char beg0)
7790 (when (> end beg)
7791 (setq org-subtree-clip-folded folded)
7792 (when (or cut force-store-markers)
7793 (org-save-markers-in-region beg end))
7794 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7795 (setq org-subtree-clip (current-kill 0))
7796 (message "%s: Subtree(s) with %d characters"
7797 (if cut "Cut" "Copied")
7798 (length org-subtree-clip)))))
7800 (defun org-paste-subtree (&optional level tree for-yank)
7801 "Paste the clipboard as a subtree, with modification of headline level.
7802 The entire subtree is promoted or demoted in order to match a new headline
7803 level.
7805 If the cursor is at the beginning of a headline, the same level as
7806 that headline is used to paste the tree
7808 If not, the new level is derived from the *visible* headings
7809 before and after the insertion point, and taken to be the inferior headline
7810 level of the two. So if the previous visible heading is level 3 and the
7811 next is level 4 (or vice versa), level 4 will be used for insertion.
7812 This makes sure that the subtree remains an independent subtree and does
7813 not swallow low level entries.
7815 You can also force a different level, either by using a numeric prefix
7816 argument, or by inserting the heading marker by hand. For example, if the
7817 cursor is after \"*****\", then the tree will be shifted to level 5.
7819 If optional TREE is given, use this text instead of the kill ring.
7821 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7822 move back over whitespace before inserting, and move point to the end of
7823 the inserted text when done."
7824 (interactive "P")
7825 (setq tree (or tree (and kill-ring (current-kill 0))))
7826 (unless (org-kill-is-subtree-p tree)
7827 (error "%s"
7828 (substitute-command-keys
7829 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7830 (org-with-limited-levels
7831 (let* ((visp (not (outline-invisible-p)))
7832 (txt tree)
7833 (^re_ "\\(\\*+\\)[ \t]*")
7834 (old-level (if (string-match org-outline-regexp-bol txt)
7835 (- (match-end 0) (match-beginning 0) 1)
7836 -1))
7837 (force-level (cond (level (prefix-numeric-value level))
7838 ((and (looking-at "[ \t]*$")
7839 (string-match
7840 "^\\*+$" (buffer-substring
7841 (point-at-bol) (point))))
7842 (- (match-end 1) (match-beginning 1)))
7843 ((and (bolp)
7844 (looking-at org-outline-regexp))
7845 (- (match-end 0) (point) 1))
7846 (t nil)))
7847 (previous-level (save-excursion
7848 (condition-case nil
7849 (progn
7850 (outline-previous-visible-heading 1)
7851 (if (looking-at ^re_)
7852 (- (match-end 0) (match-beginning 0) 1)
7854 (error 1))))
7855 (next-level (save-excursion
7856 (condition-case nil
7857 (progn
7858 (or (looking-at org-outline-regexp)
7859 (outline-next-visible-heading 1))
7860 (if (looking-at ^re_)
7861 (- (match-end 0) (match-beginning 0) 1)
7863 (error 1))))
7864 (new-level (or force-level (max previous-level next-level)))
7865 (shift (if (or (= old-level -1)
7866 (= new-level -1)
7867 (= old-level new-level))
7869 (- new-level old-level)))
7870 (delta (if (> shift 0) -1 1))
7871 (func (if (> shift 0) 'org-demote 'org-promote))
7872 (org-odd-levels-only nil)
7873 beg end newend)
7874 ;; Remove the forced level indicator
7875 (if force-level
7876 (delete-region (point-at-bol) (point)))
7877 ;; Paste
7878 (beginning-of-line (if (bolp) 1 2))
7879 (unless for-yank (org-back-over-empty-lines))
7880 (setq beg (point))
7881 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7882 (insert-before-markers txt)
7883 (unless (string-match "\n\\'" txt) (insert "\n"))
7884 (setq newend (point))
7885 (org-reinstall-markers-in-region beg)
7886 (setq end (point))
7887 (goto-char beg)
7888 (skip-chars-forward " \t\n\r")
7889 (setq beg (point))
7890 (if (and (outline-invisible-p) visp)
7891 (save-excursion (outline-show-heading)))
7892 ;; Shift if necessary
7893 (unless (= shift 0)
7894 (save-restriction
7895 (narrow-to-region beg end)
7896 (while (not (= shift 0))
7897 (org-map-region func (point-min) (point-max))
7898 (setq shift (+ delta shift)))
7899 (goto-char (point-min))
7900 (setq newend (point-max))))
7901 (when (or (org-called-interactively-p 'interactive) for-yank)
7902 (message "Clipboard pasted as level %d subtree" new-level))
7903 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7904 kill-ring
7905 (eq org-subtree-clip (current-kill 0))
7906 org-subtree-clip-folded)
7907 ;; The tree was folded before it was killed/copied
7908 (hide-subtree))
7909 (and for-yank (goto-char newend)))))
7911 (defun org-kill-is-subtree-p (&optional txt)
7912 "Check if the current kill is an outline subtree, or a set of trees.
7913 Returns nil if kill does not start with a headline, or if the first
7914 headline level is not the largest headline level in the tree.
7915 So this will actually accept several entries of equal levels as well,
7916 which is OK for `org-paste-subtree'.
7917 If optional TXT is given, check this string instead of the current kill."
7918 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7919 (re (org-get-limited-outline-regexp))
7920 (^re (concat "^" re))
7921 (start-level (and kill
7922 (string-match
7923 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7924 kill)
7925 (- (match-end 2) (match-beginning 2) 1)))
7926 (start (1+ (or (match-beginning 2) -1))))
7927 (if (not start-level)
7928 (progn
7929 nil) ;; does not even start with a heading
7930 (catch 'exit
7931 (while (setq start (string-match ^re kill (1+ start)))
7932 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7933 (throw 'exit nil)))
7934 t))))
7936 (defvar org-markers-to-move nil
7937 "Markers that should be moved with a cut-and-paste operation.
7938 Those markers are stored together with their positions relative to
7939 the start of the region.")
7941 (defun org-save-markers-in-region (beg end)
7942 "Check markers in region.
7943 If these markers are between BEG and END, record their position relative
7944 to BEG, so that after moving the block of text, we can put the markers back
7945 into place.
7946 This function gets called just before an entry or tree gets cut from the
7947 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7948 called immediately, to move the markers with the entries."
7949 (setq org-markers-to-move nil)
7950 (when (featurep 'org-clock)
7951 (org-clock-save-markers-for-cut-and-paste beg end))
7952 (when (featurep 'org-agenda)
7953 (org-agenda-save-markers-for-cut-and-paste beg end)))
7955 (defun org-check-and-save-marker (marker beg end)
7956 "Check if MARKER is between BEG and END.
7957 If yes, remember the marker and the distance to BEG."
7958 (when (and (marker-buffer marker)
7959 (equal (marker-buffer marker) (current-buffer)))
7960 (if (and (>= marker beg) (< marker end))
7961 (push (cons marker (- marker beg)) org-markers-to-move))))
7963 (defun org-reinstall-markers-in-region (beg)
7964 "Move all remembered markers to their position relative to BEG."
7965 (mapc (lambda (x)
7966 (move-marker (car x) (+ beg (cdr x))))
7967 org-markers-to-move)
7968 (setq org-markers-to-move nil))
7970 (defun org-narrow-to-subtree ()
7971 "Narrow buffer to the current subtree."
7972 (interactive)
7973 (save-excursion
7974 (save-match-data
7975 (org-with-limited-levels
7976 (narrow-to-region
7977 (progn (org-back-to-heading t) (point))
7978 (progn (org-end-of-subtree t t)
7979 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7980 (point)))))))
7982 (defun org-narrow-to-block ()
7983 "Narrow buffer to the current block."
7984 (interactive)
7985 (let* ((case-fold-search t)
7986 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7987 "^[ \t]*#\\+end_.*")))
7988 (if blockp
7989 (narrow-to-region (car blockp) (cdr blockp))
7990 (error "Not in a block"))))
7992 (eval-when-compile
7993 (defvar org-property-drawer-re))
7995 (defvar org-property-start-re) ;; defined below
7996 (defun org-clone-subtree-with-time-shift (n &optional shift)
7997 "Clone the task (subtree) at point N times.
7998 The clones will be inserted as siblings.
8000 In interactive use, the user will be prompted for the number of
8001 clones to be produced, and for a time SHIFT, which may be a
8002 repeater as used in time stamps, for example `+3d'.
8004 When a valid repeater is given and the entry contains any time
8005 stamps, the clones will become a sequence in time, with time
8006 stamps in the subtree shifted for each clone produced. If SHIFT
8007 is nil or the empty string, time stamps will be left alone. The
8008 ID property of the original subtree is removed.
8010 If the original subtree did contain time stamps with a repeater,
8011 the following will happen:
8012 - the repeater will be removed in each clone
8013 - an additional clone will be produced, with the current, unshifted
8014 date(s) in the entry.
8015 - the original entry will be placed *after* all the clones, with
8016 repeater intact.
8017 - the start days in the repeater in the original entry will be shifted
8018 to past the last clone.
8019 In this way you can spell out a number of instances of a repeating task,
8020 and still retain the repeater to cover future instances of the task."
8021 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8022 (let (beg end template task idprop
8023 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8024 (drawer-re org-drawer-regexp))
8025 (if (not (and (integerp n) (> n 0)))
8026 (error "Invalid number of replications %s" n))
8027 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8028 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8029 shift)))
8030 (error "Invalid shift specification %s" shift))
8031 (when doshift
8032 (setq shift-n (string-to-number (match-string 1 shift))
8033 shift-what (cdr (assoc (match-string 2 shift)
8034 '(("d" . day) ("w" . week)
8035 ("m" . month) ("y" . year))))))
8036 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8037 (setq nmin 1 nmax n)
8038 (org-back-to-heading t)
8039 (setq beg (point))
8040 (setq idprop (org-entry-get nil "ID"))
8041 (org-end-of-subtree t t)
8042 (or (bolp) (insert "\n"))
8043 (setq end (point))
8044 (setq template (buffer-substring beg end))
8045 (when (and doshift
8046 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8047 (delete-region beg end)
8048 (setq end beg)
8049 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8050 (goto-char end)
8051 (loop for n from nmin to nmax do
8052 ;; prepare clone
8053 (with-temp-buffer
8054 (insert template)
8055 (org-mode)
8056 (goto-char (point-min))
8057 (org-show-subtree)
8058 (and idprop (if org-clone-delete-id
8059 (org-entry-delete nil "ID")
8060 (org-id-get-create t)))
8061 (unless (= n 0)
8062 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8063 (kill-whole-line))
8064 (goto-char (point-min))
8065 (while (re-search-forward drawer-re nil t)
8066 (mapc (lambda (d)
8067 (org-remove-empty-drawer-at d (point))) org-drawers)))
8068 (goto-char (point-min))
8069 (when doshift
8070 (while (re-search-forward org-ts-regexp-both nil t)
8071 (org-timestamp-change (* n shift-n) shift-what))
8072 (unless (= n n-no-remove)
8073 (goto-char (point-min))
8074 (while (re-search-forward org-ts-regexp nil t)
8075 (save-excursion
8076 (goto-char (match-beginning 0))
8077 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8078 (delete-region (match-beginning 1) (match-end 1)))))))
8079 (setq task (buffer-string)))
8080 (insert task))
8081 (goto-char beg)))
8083 ;;; Outline Sorting
8085 (defun org-sort (with-case)
8086 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8087 Optional argument WITH-CASE means sort case-sensitively."
8088 (interactive "P")
8089 (cond
8090 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8091 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8093 (org-call-with-arg 'org-sort-entries with-case))))
8095 (defun org-sort-remove-invisible (s)
8096 (remove-text-properties 0 (length s) org-rm-props s)
8097 (while (string-match org-bracket-link-regexp s)
8098 (setq s (replace-match (if (match-end 2)
8099 (match-string 3 s)
8100 (match-string 1 s)) t t s)))
8103 (defvar org-priority-regexp) ; defined later in the file
8105 (defvar org-after-sorting-entries-or-items-hook nil
8106 "Hook that is run after a bunch of entries or items have been sorted.
8107 When children are sorted, the cursor is in the parent line when this
8108 hook gets called. When a region or a plain list is sorted, the cursor
8109 will be in the first entry of the sorted region/list.")
8111 (defun org-sort-entries
8112 (&optional with-case sorting-type getkey-func compare-func property)
8113 "Sort entries on a certain level of an outline tree.
8114 If there is an active region, the entries in the region are sorted.
8115 Else, if the cursor is before the first entry, sort the top-level items.
8116 Else, the children of the entry at point are sorted.
8118 Sorting can be alphabetically, numerically, by date/time as given by
8119 a time stamp, by a property or by priority.
8121 The command prompts for the sorting type unless it has been given to the
8122 function through the SORTING-TYPE argument, which needs to be a character,
8123 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8124 precise meaning of each character:
8126 n Numerically, by converting the beginning of the entry/item to a number.
8127 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8128 t By date/time, either the first active time stamp in the entry, or, if
8129 none exist, by the first inactive one.
8130 s By the scheduled date/time.
8131 d By deadline date/time.
8132 c By creation time, which is assumed to be the first inactive time stamp
8133 at the beginning of a line.
8134 p By priority according to the cookie.
8135 r By the value of a property.
8137 Capital letters will reverse the sort order.
8139 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8140 called with point at the beginning of the record. It must return either
8141 a string or a number that should serve as the sorting key for that record.
8143 Comparing entries ignores case by default. However, with an optional argument
8144 WITH-CASE, the sorting considers case as well."
8145 (interactive "P")
8146 (let ((case-func (if with-case 'identity 'downcase))
8147 start beg end stars re re2
8148 txt what tmp)
8149 ;; Find beginning and end of region to sort
8150 (cond
8151 ((org-region-active-p)
8152 ;; we will sort the region
8153 (setq end (region-end)
8154 what "region")
8155 (goto-char (region-beginning))
8156 (if (not (org-at-heading-p)) (outline-next-heading))
8157 (setq start (point)))
8158 ((or (org-at-heading-p)
8159 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8160 ;; we will sort the children of the current headline
8161 (org-back-to-heading)
8162 (setq start (point)
8163 end (progn (org-end-of-subtree t t)
8164 (or (bolp) (insert "\n"))
8165 (org-back-over-empty-lines)
8166 (point))
8167 what "children")
8168 (goto-char start)
8169 (show-subtree)
8170 (outline-next-heading))
8172 ;; we will sort the top-level entries in this file
8173 (goto-char (point-min))
8174 (or (org-at-heading-p) (outline-next-heading))
8175 (setq start (point))
8176 (goto-char (point-max))
8177 (beginning-of-line 1)
8178 (when (looking-at ".*?\\S-")
8179 ;; File ends in a non-white line
8180 (end-of-line 1)
8181 (insert "\n"))
8182 (setq end (point-max))
8183 (setq what "top-level")
8184 (goto-char start)
8185 (show-all)))
8187 (setq beg (point))
8188 (if (>= beg end) (error "Nothing to sort"))
8190 (looking-at "\\(\\*+\\)")
8191 (setq stars (match-string 1)
8192 re (concat "^" (regexp-quote stars) " +")
8193 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8194 txt (buffer-substring beg end))
8195 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8196 (if (and (not (equal stars "*")) (string-match re2 txt))
8197 (error "Region to sort contains a level above the first entry"))
8199 (unless sorting-type
8200 (message
8201 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8202 [t]ime [s]cheduled [d]eadline [c]reated
8203 A/N/T/S/D/C/P/O/F means reversed:"
8204 what)
8205 (setq sorting-type (read-char-exclusive))
8207 (and (= (downcase sorting-type) ?f)
8208 (setq getkey-func
8209 (org-icompleting-read "Sort using function: "
8210 obarray 'fboundp t nil nil))
8211 (setq getkey-func (intern getkey-func)))
8213 (and (= (downcase sorting-type) ?r)
8214 (setq property
8215 (org-icompleting-read "Property: "
8216 (mapcar 'list (org-buffer-property-keys t))
8217 nil t))))
8219 (message "Sorting entries...")
8221 (save-restriction
8222 (narrow-to-region start end)
8223 (let ((dcst (downcase sorting-type))
8224 (case-fold-search nil)
8225 (now (current-time)))
8226 (sort-subr
8227 (/= dcst sorting-type)
8228 ;; This function moves to the beginning character of the "record" to
8229 ;; be sorted.
8230 (lambda nil
8231 (if (re-search-forward re nil t)
8232 (goto-char (match-beginning 0))
8233 (goto-char (point-max))))
8234 ;; This function moves to the last character of the "record" being
8235 ;; sorted.
8236 (lambda nil
8237 (save-match-data
8238 (condition-case nil
8239 (outline-forward-same-level 1)
8240 (error
8241 (goto-char (point-max))))))
8242 ;; This function returns the value that gets sorted against.
8243 (lambda nil
8244 (cond
8245 ((= dcst ?n)
8246 (if (looking-at org-complex-heading-regexp)
8247 (string-to-number (match-string 4))
8248 nil))
8249 ((= dcst ?a)
8250 (if (looking-at org-complex-heading-regexp)
8251 (funcall case-func (match-string 4))
8252 nil))
8253 ((= dcst ?t)
8254 (let ((end (save-excursion (outline-next-heading) (point))))
8255 (if (or (re-search-forward org-ts-regexp end t)
8256 (re-search-forward org-ts-regexp-both end t))
8257 (org-time-string-to-seconds (match-string 0))
8258 (org-float-time now))))
8259 ((= dcst ?c)
8260 (let ((end (save-excursion (outline-next-heading) (point))))
8261 (if (re-search-forward
8262 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8263 end t)
8264 (org-time-string-to-seconds (match-string 0))
8265 (org-float-time now))))
8266 ((= dcst ?s)
8267 (let ((end (save-excursion (outline-next-heading) (point))))
8268 (if (re-search-forward org-scheduled-time-regexp end t)
8269 (org-time-string-to-seconds (match-string 1))
8270 (org-float-time now))))
8271 ((= dcst ?d)
8272 (let ((end (save-excursion (outline-next-heading) (point))))
8273 (if (re-search-forward org-deadline-time-regexp end t)
8274 (org-time-string-to-seconds (match-string 1))
8275 (org-float-time now))))
8276 ((= dcst ?p)
8277 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8278 (string-to-char (match-string 2))
8279 org-default-priority))
8280 ((= dcst ?r)
8281 (or (org-entry-get nil property) ""))
8282 ((= dcst ?o)
8283 (if (looking-at org-complex-heading-regexp)
8284 (- 9999 (length (member (match-string 2)
8285 org-todo-keywords-1)))))
8286 ((= dcst ?f)
8287 (if getkey-func
8288 (progn
8289 (setq tmp (funcall getkey-func))
8290 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8291 tmp)
8292 (error "Invalid key function `%s'" getkey-func)))
8293 (t (error "Invalid sorting type `%c'" sorting-type))))
8295 (cond
8296 ((= dcst ?a) 'string<)
8297 ((= dcst ?f) compare-func)
8298 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8299 (t nil)))))
8300 (run-hooks 'org-after-sorting-entries-or-items-hook)
8301 (message "Sorting entries...done")))
8303 (defun org-do-sort (table what &optional with-case sorting-type)
8304 "Sort TABLE of WHAT according to SORTING-TYPE.
8305 The user will be prompted for the SORTING-TYPE if the call to this
8306 function does not specify it. WHAT is only for the prompt, to indicate
8307 what is being sorted. The sorting key will be extracted from
8308 the car of the elements of the table.
8309 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8310 (unless sorting-type
8311 (message
8312 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8313 what)
8314 (setq sorting-type (read-char-exclusive)))
8315 (let ((dcst (downcase sorting-type))
8316 extractfun comparefun)
8317 ;; Define the appropriate functions
8318 (cond
8319 ((= dcst ?n)
8320 (setq extractfun 'string-to-number
8321 comparefun (if (= dcst sorting-type) '< '>)))
8322 ((= dcst ?a)
8323 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8324 (lambda(x) (downcase (org-sort-remove-invisible x))))
8325 comparefun (if (= dcst sorting-type)
8326 'string<
8327 (lambda (a b) (and (not (string< a b))
8328 (not (string= a b)))))))
8329 ((= dcst ?t)
8330 (setq extractfun
8331 (lambda (x)
8332 (if (or (string-match org-ts-regexp x)
8333 (string-match org-ts-regexp-both x))
8334 (org-float-time
8335 (org-time-string-to-time (match-string 0 x)))
8337 comparefun (if (= dcst sorting-type) '< '>)))
8338 (t (error "Invalid sorting type `%c'" sorting-type)))
8340 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8341 table)
8342 (lambda (a b) (funcall comparefun (car a) (car b))))))
8345 ;;; The orgstruct minor mode
8347 ;; Define a minor mode which can be used in other modes in order to
8348 ;; integrate the org-mode structure editing commands.
8350 ;; This is really a hack, because the org-mode structure commands use
8351 ;; keys which normally belong to the major mode. Here is how it
8352 ;; works: The minor mode defines all the keys necessary to operate the
8353 ;; structure commands, but wraps the commands into a function which
8354 ;; tests if the cursor is currently at a headline or a plain list
8355 ;; item. If that is the case, the structure command is used,
8356 ;; temporarily setting many Org-mode variables like regular
8357 ;; expressions for filling etc. However, when any of those keys is
8358 ;; used at a different location, function uses `key-binding' to look
8359 ;; up if the key has an associated command in another currently active
8360 ;; keymap (minor modes, major mode, global), and executes that
8361 ;; command. There might be problems if any of the keys is otherwise
8362 ;; used as a prefix key.
8364 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8365 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8366 ;; addresses this by checking explicitly for both bindings.
8368 (defvar orgstruct-mode-map (make-sparse-keymap)
8369 "Keymap for the minor `orgstruct-mode'.")
8371 (defvar org-local-vars nil
8372 "List of local variables, for use by `orgstruct-mode'.")
8374 ;;;###autoload
8375 (define-minor-mode orgstruct-mode
8376 "Toggle the minor mode `orgstruct-mode'.
8377 This mode is for using Org-mode structure commands in other
8378 modes. The following keys behave as if Org-mode were active, if
8379 the cursor is on a headline, or on a plain list item (both as
8380 defined by Org-mode).
8382 M-up Move entry/item up
8383 M-down Move entry/item down
8384 M-left Promote
8385 M-right Demote
8386 M-S-up Move entry/item up
8387 M-S-down Move entry/item down
8388 M-S-left Promote subtree
8389 M-S-right Demote subtree
8390 M-q Fill paragraph and items like in Org-mode
8391 C-c ^ Sort entries
8392 C-c - Cycle list bullet
8393 TAB Cycle item visibility
8394 M-RET Insert new heading/item
8395 S-M-RET Insert new TODO heading / Checkbox item
8396 C-c C-c Set tags / toggle checkbox"
8397 nil " OrgStruct" nil
8398 (org-load-modules-maybe)
8399 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8401 ;;;###autoload
8402 (defun turn-on-orgstruct ()
8403 "Unconditionally turn on `orgstruct-mode'."
8404 (orgstruct-mode 1))
8406 (defvar org-fb-vars nil)
8407 (make-variable-buffer-local 'org-fb-vars)
8408 (defun orgstruct++-mode (&optional arg)
8409 "Toggle `orgstruct-mode', the enhanced version of it.
8410 In addition to setting orgstruct-mode, this also exports all
8411 indentation and autofilling variables from org-mode into the
8412 buffer. It will also recognize item context in multiline items."
8413 (interactive "P")
8414 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8415 (if (< arg 1)
8416 (progn (orgstruct-mode -1)
8417 (mapc (lambda(v)
8418 (org-set-local (car v)
8419 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8420 org-fb-vars))
8421 (orgstruct-mode 1)
8422 (setq org-fb-vars nil)
8423 (let (var val)
8424 (mapc
8425 (lambda (x)
8426 (when (string-match
8427 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8428 (symbol-name (car x)))
8429 (setq var (car x) val (nth 1 x))
8430 (push (list var `(quote ,(eval var))) org-fb-vars)
8431 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8432 org-local-vars)
8433 (org-set-local 'orgstruct-is-++ t))))
8435 (defvar orgstruct-is-++ nil
8436 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8437 (make-variable-buffer-local 'orgstruct-is-++)
8439 ;;;###autoload
8440 (defun turn-on-orgstruct++ ()
8441 "Unconditionally turn on `orgstruct++-mode'."
8442 (orgstruct++-mode 1))
8444 (defun orgstruct-error ()
8445 "Error when there is no default binding for a structure key."
8446 (interactive)
8447 (error "This key has no function outside structure elements"))
8449 (defun orgstruct-setup ()
8450 "Setup orgstruct keymaps."
8451 (let ((nfunc 0)
8452 (bindings
8453 (list
8454 '([(meta up)] org-metaup)
8455 '([(meta down)] org-metadown)
8456 '([(meta left)] org-metaleft)
8457 '([(meta right)] org-metaright)
8458 '([(meta shift up)] org-shiftmetaup)
8459 '([(meta shift down)] org-shiftmetadown)
8460 '([(meta shift left)] org-shiftmetaleft)
8461 '([(meta shift right)] org-shiftmetaright)
8462 '([?\e (up)] org-metaup)
8463 '([?\e (down)] org-metadown)
8464 '([?\e (left)] org-metaleft)
8465 '([?\e (right)] org-metaright)
8466 '([?\e (shift up)] org-shiftmetaup)
8467 '([?\e (shift down)] org-shiftmetadown)
8468 '([?\e (shift left)] org-shiftmetaleft)
8469 '([?\e (shift right)] org-shiftmetaright)
8470 '([(shift up)] org-shiftup)
8471 '([(shift down)] org-shiftdown)
8472 '([(shift left)] org-shiftleft)
8473 '([(shift right)] org-shiftright)
8474 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8475 '("\M-q" fill-paragraph)
8476 '("\C-c^" org-sort)
8477 '("\C-c-" org-cycle-list-bullet)))
8478 elt key fun cmd)
8479 (while (setq elt (pop bindings))
8480 (setq nfunc (1+ nfunc))
8481 (setq key (org-key (car elt))
8482 fun (nth 1 elt)
8483 cmd (orgstruct-make-binding fun nfunc key))
8484 (org-defkey orgstruct-mode-map key cmd))
8486 ;; Special treatment needed for TAB and RET
8487 (org-defkey orgstruct-mode-map [(tab)]
8488 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8489 (org-defkey orgstruct-mode-map "\C-i"
8490 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8492 (org-defkey orgstruct-mode-map "\M-\C-m"
8493 (orgstruct-make-binding 'org-insert-heading 105
8494 "\M-\C-m" [(meta return)]))
8495 (org-defkey orgstruct-mode-map [(meta return)]
8496 (orgstruct-make-binding 'org-insert-heading 106
8497 [(meta return)] "\M-\C-m"))
8499 (org-defkey orgstruct-mode-map [(shift meta return)]
8500 (orgstruct-make-binding 'org-insert-todo-heading 107
8501 [(meta return)] "\M-\C-m"))
8503 (org-defkey orgstruct-mode-map "\e\C-m"
8504 (orgstruct-make-binding 'org-insert-heading 108
8505 "\e\C-m" [?\e (return)]))
8506 (org-defkey orgstruct-mode-map [?\e (return)]
8507 (orgstruct-make-binding 'org-insert-heading 109
8508 [?\e (return)] "\e\C-m"))
8509 (org-defkey orgstruct-mode-map [?\e (shift return)]
8510 (orgstruct-make-binding 'org-insert-todo-heading 110
8511 [?\e (return)] "\e\C-m"))
8513 (unless org-local-vars
8514 (setq org-local-vars (org-get-local-variables)))
8518 (defun orgstruct-make-binding (fun n &rest keys)
8519 "Create a function for binding in the structure minor mode.
8520 FUN is the command to call inside a table. N is used to create a unique
8521 command name. KEYS are keys that should be checked in for a command
8522 to execute outside of tables."
8523 (eval
8524 (list 'defun
8525 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8526 '(arg)
8527 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8528 "Outside of structure, run the binding of `"
8529 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8530 "'.")
8531 '(interactive "p")
8532 (list 'if
8533 `(org-context-p 'headline 'item
8534 (and orgstruct-is-++
8535 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8536 'item-body))
8537 (list 'org-run-like-in-org-mode (list 'quote fun))
8538 (list 'let '(orgstruct-mode)
8539 (list 'call-interactively
8540 (append '(or)
8541 (mapcar (lambda (k)
8542 (list 'key-binding k))
8543 keys)
8544 '('orgstruct-error))))))))
8546 (defun org-context-p (&rest contexts)
8547 "Check if local context is any of CONTEXTS.
8548 Possible values in the list of contexts are `table', `headline', and `item'."
8549 (let ((pos (point)))
8550 (goto-char (point-at-bol))
8551 (prog1 (or (and (memq 'table contexts)
8552 (looking-at "[ \t]*|"))
8553 (and (memq 'headline contexts)
8554 (looking-at org-outline-regexp))
8555 (and (memq 'item contexts)
8556 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8557 (and (memq 'item-body contexts)
8558 (org-in-item-p)))
8559 (goto-char pos))))
8561 (defun org-get-local-variables ()
8562 "Return a list of all local variables in an org-mode buffer."
8563 (let (varlist)
8564 (with-current-buffer (get-buffer-create "*Org tmp*")
8565 (erase-buffer)
8566 (org-mode)
8567 (setq varlist (buffer-local-variables)))
8568 (kill-buffer "*Org tmp*")
8569 (delq nil
8570 (mapcar
8571 (lambda (x)
8572 (setq x
8573 (if (symbolp x)
8574 (list x)
8575 (list (car x) (list 'quote (cdr x)))))
8576 (if (string-match
8577 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8578 (symbol-name (car x)))
8579 x nil))
8580 varlist))))
8582 (defun org-clone-local-variables (from-buffer &optional regexp)
8583 "Clone local variables from FROM-BUFFER.
8584 Optional argument REGEXP selects variables to clone."
8585 (mapc
8586 (lambda (pair)
8587 (and (symbolp (car pair))
8588 (or (null regexp)
8589 (string-match regexp (symbol-name (car pair))))
8590 (set (make-local-variable (car pair))
8591 (cdr pair))))
8592 (buffer-local-variables from-buffer)))
8594 ;;;###autoload
8595 (defun org-run-like-in-org-mode (cmd)
8596 "Run a command, pretending that the current buffer is in Org-mode.
8597 This will temporarily bind local variables that are typically bound in
8598 Org-mode to the values they have in Org-mode, and then interactively
8599 call CMD."
8600 (org-load-modules-maybe)
8601 (unless org-local-vars
8602 (setq org-local-vars (org-get-local-variables)))
8603 (eval (list 'let org-local-vars
8604 (list 'call-interactively (list 'quote cmd)))))
8606 ;;;; Archiving
8608 (defun org-get-category (&optional pos force-refresh)
8609 "Get the category applying to position POS."
8610 (save-match-data
8611 (if force-refresh (org-refresh-category-properties))
8612 (let ((pos (or pos (point))))
8613 (or (get-text-property pos 'org-category)
8614 (progn (org-refresh-category-properties)
8615 (get-text-property pos 'org-category))))))
8617 (defun org-refresh-category-properties ()
8618 "Refresh category text properties in the buffer."
8619 (let ((inhibit-read-only t)
8620 (def-cat (cond
8621 ((null org-category)
8622 (if buffer-file-name
8623 (file-name-sans-extension
8624 (file-name-nondirectory buffer-file-name))
8625 "???"))
8626 ((symbolp org-category) (symbol-name org-category))
8627 (t org-category)))
8628 beg end cat pos optionp)
8629 (org-unmodified
8630 (save-excursion
8631 (save-restriction
8632 (widen)
8633 (goto-char (point-min))
8634 (put-text-property (point) (point-max) 'org-category def-cat)
8635 (while (re-search-forward
8636 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8637 (setq pos (match-end 0)
8638 optionp (equal (char-after (match-beginning 0)) ?#)
8639 cat (org-trim (match-string 2)))
8640 (if optionp
8641 (setq beg (point-at-bol) end (point-max))
8642 (org-back-to-heading t)
8643 (setq beg (point) end (org-end-of-subtree t t)))
8644 (put-text-property beg end 'org-category cat)
8645 (put-text-property beg end 'org-category-position beg)
8646 (goto-char pos)))))))
8649 ;;;; Link Stuff
8651 ;;; Link abbreviations
8653 (defun org-link-expand-abbrev (link)
8654 "Apply replacements as defined in `org-link-abbrev-alist'."
8655 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8656 (let* ((key (match-string 1 link))
8657 (as (or (assoc key org-link-abbrev-alist-local)
8658 (assoc key org-link-abbrev-alist)))
8659 (tag (and (match-end 2) (match-string 3 link)))
8660 rpl)
8661 (if (not as)
8662 link
8663 (setq rpl (cdr as))
8664 (cond
8665 ((symbolp rpl) (funcall rpl tag))
8666 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8667 ((string-match "%h" rpl)
8668 (replace-match (url-hexify-string (or tag "")) t t rpl))
8669 (t (concat rpl tag)))))
8670 link))
8672 ;;; Storing and inserting links
8674 (defvar org-insert-link-history nil
8675 "Minibuffer history for links inserted with `org-insert-link'.")
8677 (defvar org-stored-links nil
8678 "Contains the links stored with `org-store-link'.")
8680 (defvar org-store-link-plist nil
8681 "Plist with info about the most recently link created with `org-store-link'.")
8683 (defvar org-link-protocols nil
8684 "Link protocols added to Org-mode using `org-add-link-type'.")
8686 (defvar org-store-link-functions nil
8687 "List of functions that are called to create and store a link.
8688 Each function will be called in turn until one returns a non-nil
8689 value. Each function should check if it is responsible for creating
8690 this link (for example by looking at the major mode).
8691 If not, it must exit and return nil.
8692 If yes, it should return a non-nil value after a calling
8693 `org-store-link-props' with a list of properties and values.
8694 Special properties are:
8696 :type The link prefix, like \"http\". This must be given.
8697 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8698 This is obligatory as well.
8699 :description Optional default description for the second pair
8700 of brackets in an Org-mode link. The user can still change
8701 this when inserting this link into an Org-mode buffer.
8703 In addition to these, any additional properties can be specified
8704 and then used in remember templates.")
8706 (defun org-add-link-type (type &optional follow export)
8707 "Add TYPE to the list of `org-link-types'.
8708 Re-compute all regular expressions depending on `org-link-types'
8710 FOLLOW and EXPORT are two functions.
8712 FOLLOW should take the link path as the single argument and do whatever
8713 is necessary to follow the link, for example find a file or display
8714 a mail message.
8716 EXPORT should format the link path for export to one of the export formats.
8717 It should be a function accepting three arguments:
8719 path the path of the link, the text after the prefix (like \"http:\")
8720 desc the description of the link, if any, or a description added by
8721 org-export-normalize-links if there is none
8722 format the export format, a symbol like `html' or `latex' or `ascii'..
8724 The function may use the FORMAT information to return different values
8725 depending on the format. The return value will be put literally into
8726 the exported file. If the return value is nil, this means Org should
8727 do what it normally does with links which do not have EXPORT defined.
8729 Org-mode has a built-in default for exporting links. If you are happy with
8730 this default, there is no need to define an export function for the link
8731 type. For a simple example of an export function, see `org-bbdb.el'."
8732 (add-to-list 'org-link-types type t)
8733 (org-make-link-regexps)
8734 (if (assoc type org-link-protocols)
8735 (setcdr (assoc type org-link-protocols) (list follow export))
8736 (push (list type follow export) org-link-protocols)))
8738 (defvar org-agenda-buffer-name)
8740 ;;;###autoload
8741 (defun org-store-link (arg)
8742 "\\<org-mode-map>Store an org-link to the current location.
8743 This link is added to `org-stored-links' and can later be inserted
8744 into an org-buffer with \\[org-insert-link].
8746 For some link types, a prefix arg is interpreted:
8747 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8748 For file links, arg negates `org-context-in-file-links'."
8749 (interactive "P")
8750 (org-load-modules-maybe)
8751 (setq org-store-link-plist nil) ; reset
8752 (org-with-limited-levels
8753 (let (link cpltxt desc description search txt custom-id agenda-link)
8754 (cond
8756 ((run-hook-with-args-until-success 'org-store-link-functions)
8757 (setq link (plist-get org-store-link-plist :link)
8758 desc (or (plist-get org-store-link-plist :description) link)))
8760 ((org-src-edit-buffer-p)
8761 (let (label gc)
8762 (while (or (not label)
8763 (save-excursion
8764 (save-restriction
8765 (widen)
8766 (goto-char (point-min))
8767 (re-search-forward
8768 (regexp-quote (format org-coderef-label-format label))
8769 nil t))))
8770 (when label (message "Label exists already") (sit-for 2))
8771 (setq label (read-string "Code line label: " label)))
8772 (end-of-line 1)
8773 (setq link (format org-coderef-label-format label))
8774 (setq gc (- 79 (length link)))
8775 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8776 (insert link)
8777 (setq link (concat "(" label ")") desc nil)))
8779 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8780 ;; We are in the agenda, link to referenced location
8781 (let ((m (or (get-text-property (point) 'org-hd-marker)
8782 (get-text-property (point) 'org-marker))))
8783 (when m
8784 (org-with-point-at m
8785 (setq agenda-link
8786 (if (org-called-interactively-p 'any)
8787 (call-interactively 'org-store-link)
8788 (org-store-link nil)))))))
8790 ((eq major-mode 'calendar-mode)
8791 (let ((cd (calendar-cursor-to-date)))
8792 (setq link
8793 (format-time-string
8794 (car org-time-stamp-formats)
8795 (apply 'encode-time
8796 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8797 nil nil nil))))
8798 (org-store-link-props :type "calendar" :date cd)))
8800 ((eq major-mode 'w3-mode)
8801 (setq cpltxt (if (and (buffer-name)
8802 (not (string-match "Untitled" (buffer-name))))
8803 (buffer-name)
8804 (url-view-url t))
8805 link (org-make-link (url-view-url t)))
8806 (org-store-link-props :type "w3" :url (url-view-url t)))
8808 ((eq major-mode 'w3m-mode)
8809 (setq cpltxt (or w3m-current-title w3m-current-url)
8810 link (org-make-link w3m-current-url))
8811 (org-store-link-props :type "w3m" :url (url-view-url t)))
8813 ((setq search (run-hook-with-args-until-success
8814 'org-create-file-search-functions))
8815 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8816 "::" search))
8817 (setq cpltxt (or description link)))
8819 ((eq major-mode 'image-mode)
8820 (setq cpltxt (concat "file:"
8821 (abbreviate-file-name buffer-file-name))
8822 link (org-make-link cpltxt))
8823 (org-store-link-props :type "image" :file buffer-file-name))
8825 ((eq major-mode 'dired-mode)
8826 ;; link to the file in the current line
8827 (let ((file (dired-get-filename nil t)))
8828 (setq file (if file
8829 (abbreviate-file-name
8830 (expand-file-name (dired-get-filename nil t)))
8831 ;; otherwise, no file so use current directory.
8832 default-directory))
8833 (setq cpltxt (concat "file:" file)
8834 link (org-make-link cpltxt))))
8836 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8837 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8838 (cond
8839 ((org-in-regexp "<<\\(.*?\\)>>")
8840 (setq cpltxt
8841 (concat "file:"
8842 (abbreviate-file-name
8843 (buffer-file-name (buffer-base-buffer)))
8844 "::" (match-string 1))
8845 link (org-make-link cpltxt)))
8846 ((and (featurep 'org-id)
8847 (or (eq org-link-to-org-use-id t)
8848 (and (eq org-link-to-org-use-id 'create-if-interactive)
8849 (org-called-interactively-p 'any))
8850 (and (eq org-link-to-org-use-id
8851 'create-if-interactive-and-no-custom-id)
8852 (org-called-interactively-p 'any)
8853 (not custom-id))
8854 (and org-link-to-org-use-id
8855 (org-entry-get nil "ID"))))
8856 ;; We can make a link using the ID.
8857 (setq link (condition-case nil
8858 (prog1 (org-id-store-link)
8859 (setq desc (plist-get org-store-link-plist
8860 :description)))
8861 (error
8862 ;; probably before first headline, link to file only
8863 (concat "file:"
8864 (abbreviate-file-name
8865 (buffer-file-name (buffer-base-buffer))))))))
8867 ;; Just link to current headline
8868 (setq cpltxt (concat "file:"
8869 (abbreviate-file-name
8870 (buffer-file-name (buffer-base-buffer)))))
8871 ;; Add a context search string
8872 (when (org-xor org-context-in-file-links arg)
8873 (setq txt (cond
8874 ((org-at-heading-p) nil)
8875 ((org-region-active-p)
8876 (buffer-substring (region-beginning) (region-end)))
8877 (t nil)))
8878 (when (or (null txt) (string-match "\\S-" txt))
8879 (setq cpltxt
8880 (concat cpltxt "::"
8881 (condition-case nil
8882 (org-make-org-heading-search-string txt)
8883 (error "")))
8884 desc (or (nth 4 (ignore-errors
8885 (org-heading-components))) "NONE"))))
8886 (if (string-match "::\\'" cpltxt)
8887 (setq cpltxt (substring cpltxt 0 -2)))
8888 (setq link (org-make-link cpltxt)))))
8890 ((buffer-file-name (buffer-base-buffer))
8891 ;; Just link to this file here.
8892 (setq cpltxt (concat "file:"
8893 (abbreviate-file-name
8894 (buffer-file-name (buffer-base-buffer)))))
8895 ;; Add a context string
8896 (when (org-xor org-context-in-file-links arg)
8897 (setq txt (if (org-region-active-p)
8898 (buffer-substring (region-beginning) (region-end))
8899 (buffer-substring (point-at-bol) (point-at-eol))))
8900 ;; Only use search option if there is some text.
8901 (when (string-match "\\S-" txt)
8902 (setq cpltxt
8903 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8904 desc "NONE")))
8905 (setq link (org-make-link cpltxt)))
8907 ((org-called-interactively-p 'interactive)
8908 (error "Cannot link to a buffer which is not visiting a file"))
8910 (t (setq link nil)))
8912 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8913 (setq link (or link cpltxt)
8914 desc (or desc cpltxt))
8915 (if (equal desc "NONE") (setq desc nil))
8917 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8918 (progn
8919 (setq org-stored-links
8920 (cons (list link desc) org-stored-links))
8921 (message "Stored: %s" (or desc link))
8922 (when custom-id
8923 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8924 "::#" custom-id))
8925 (setq org-stored-links
8926 (cons (list link desc) org-stored-links))))
8927 (or agenda-link (and link (org-make-link-string link desc)))))))
8929 (defun org-store-link-props (&rest plist)
8930 "Store link properties, extract names and addresses."
8931 (let (x adr)
8932 (when (setq x (plist-get plist :from))
8933 (setq adr (mail-extract-address-components x))
8934 (setq plist (plist-put plist :fromname (car adr)))
8935 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8936 (when (setq x (plist-get plist :to))
8937 (setq adr (mail-extract-address-components x))
8938 (setq plist (plist-put plist :toname (car adr)))
8939 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8940 (let ((from (plist-get plist :from))
8941 (to (plist-get plist :to)))
8942 (when (and from to org-from-is-user-regexp)
8943 (setq plist
8944 (plist-put plist :fromto
8945 (if (string-match org-from-is-user-regexp from)
8946 (concat "to %t")
8947 (concat "from %f"))))))
8948 (setq org-store-link-plist plist))
8950 (defun org-add-link-props (&rest plist)
8951 "Add these properties to the link property list."
8952 (let (key value)
8953 (while plist
8954 (setq key (pop plist) value (pop plist))
8955 (setq org-store-link-plist
8956 (plist-put org-store-link-plist key value)))))
8958 (defun org-email-link-description (&optional fmt)
8959 "Return the description part of an email link.
8960 This takes information from `org-store-link-plist' and formats it
8961 according to FMT (default from `org-email-link-description-format')."
8962 (setq fmt (or fmt org-email-link-description-format))
8963 (let* ((p org-store-link-plist)
8964 (to (plist-get p :toaddress))
8965 (from (plist-get p :fromaddress))
8966 (table
8967 (list
8968 (cons "%c" (plist-get p :fromto))
8969 (cons "%F" (plist-get p :from))
8970 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8971 (cons "%T" (plist-get p :to))
8972 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8973 (cons "%s" (plist-get p :subject))
8974 (cons "%d" (plist-get p :date))
8975 (cons "%m" (plist-get p :message-id)))))
8976 (when (string-match "%c" fmt)
8977 ;; Check if the user wrote this message
8978 (if (and org-from-is-user-regexp from to
8979 (save-match-data (string-match org-from-is-user-regexp from)))
8980 (setq fmt (replace-match "to %t" t t fmt))
8981 (setq fmt (replace-match "from %f" t t fmt))))
8982 (org-replace-escapes fmt table)))
8984 (defun org-make-org-heading-search-string (&optional string heading)
8985 "Make search string for STRING or current headline."
8986 (interactive)
8987 (let ((s (or string (org-get-heading)))
8988 (lines org-context-in-file-links))
8989 (unless (and string (not heading))
8990 ;; We are using a headline, clean up garbage in there.
8991 (if (string-match org-todo-regexp s)
8992 (setq s (replace-match "" t t s)))
8993 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8994 (setq s (replace-match "" t t s)))
8995 (setq s (org-trim s))
8996 (if (string-match (concat "^\\(" org-quote-string "\\|"
8997 org-comment-string "\\)") s)
8998 (setq s (replace-match "" t t s)))
8999 (while (string-match org-ts-regexp s)
9000 (setq s (replace-match "" t t s))))
9001 (or string (setq s (concat "*" s))) ; Add * for headlines
9002 (when (and string (integerp lines) (> lines 0))
9003 (let ((slines (org-split-string s "\n")))
9004 (when (< lines (length slines))
9005 (setq s (mapconcat
9006 'identity
9007 (reverse (nthcdr (- (length slines) lines)
9008 (reverse slines))) "\n")))))
9009 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9011 (defun org-make-link (&rest strings)
9012 "Concatenate STRINGS."
9013 (apply 'concat strings))
9015 (defun org-make-link-string (link &optional description)
9016 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9017 (unless (string-match "\\S-" link)
9018 (error "Empty link"))
9019 (when (and description
9020 (stringp description)
9021 (not (string-match "\\S-" description)))
9022 (setq description nil))
9023 (when (stringp description)
9024 ;; Remove brackets from the description, they are fatal.
9025 (while (string-match "\\[" description)
9026 (setq description (replace-match "{" t t description)))
9027 (while (string-match "\\]" description)
9028 (setq description (replace-match "}" t t description))))
9029 (when (equal link description)
9030 ;; No description needed, it is identical
9031 (setq description nil))
9032 (when (and (not description)
9033 (not (string-match (org-image-file-name-regexp) link))
9034 (not (equal link (org-link-escape link))))
9035 (setq description (org-extract-attributes link)))
9036 (setq link
9037 (cond ((string-match (org-image-file-name-regexp) link) link)
9038 ((string-match org-link-types-re link)
9039 (concat (match-string 1 link)
9040 (org-link-escape (substring link (match-end 1)))))
9041 (t (org-link-escape link))))
9042 (concat "[[" link "]"
9043 (if description (concat "[" description "]") "")
9044 "]"))
9046 (defconst org-link-escape-chars
9047 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9048 "List of characters that should be escaped in link.
9049 This is the list that is used for internal purposes.")
9051 (defvar org-url-encoding-use-url-hexify nil)
9053 (defconst org-link-escape-chars-browser
9054 '(?\ )
9055 "List of escapes for characters that are problematic in links.
9056 This is the list that is used before handing over to the browser.")
9058 (defun org-link-escape (text &optional table merge)
9059 "Return percent escaped representation of TEXT.
9060 TEXT is a string with the text to escape.
9061 Optional argument TABLE is a list with characters that should be
9062 escaped. When nil, `org-link-escape-chars' is used.
9063 If optional argument MERGE is set, merge TABLE into
9064 `org-link-escape-chars'."
9065 (if (and org-url-encoding-use-url-hexify (not table))
9066 (url-hexify-string text)
9067 (cond
9068 ((and table merge)
9069 (mapc (lambda (defchr)
9070 (unless (member defchr table)
9071 (setq table (cons defchr table)))) org-link-escape-chars))
9072 ((null table)
9073 (setq table org-link-escape-chars)))
9074 (mapconcat
9075 (lambda (char)
9076 (if (or (member char table)
9077 (< char 32) (= char 37) (> char 126))
9078 (mapconcat (lambda (sequence-element)
9079 (format "%%%.2X" sequence-element))
9080 (or (encode-coding-char char 'utf-8)
9081 (error "Unable to percent escape character: %s"
9082 (char-to-string char))) "")
9083 (char-to-string char))) text "")))
9085 (defun org-link-unescape (str)
9086 "Unhex hexified Unicode strings as returned from the JavaScript function
9087 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9088 (unless (and (null str) (string= "" str))
9089 (let ((pos 0) (case-fold-search t) unhexed)
9090 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9091 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9092 (setq str (replace-match unhexed t t str))
9093 (setq pos (+ pos (length unhexed))))))
9094 str)
9096 (defun org-link-unescape-compound (hex)
9097 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9098 Note: this function also decodes single byte encodings like
9099 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9100 (save-match-data
9101 (let* ((bytes (cdr (split-string hex "%")))
9102 (ret "")
9103 (eat 0)
9104 (sum 0))
9105 (while bytes
9106 (let* ((val (string-to-number (pop bytes) 16))
9107 (shift-xor
9108 (if (= 0 eat)
9109 (cond
9110 ((>= val 252) (cons 6 252))
9111 ((>= val 248) (cons 5 248))
9112 ((>= val 240) (cons 4 240))
9113 ((>= val 224) (cons 3 224))
9114 ((>= val 192) (cons 2 192))
9115 (t (cons 0 0)))
9116 (cons 6 128))))
9117 (if (>= val 192) (setq eat (car shift-xor)))
9118 (setq val (logxor val (cdr shift-xor)))
9119 (setq sum (+ (lsh sum (car shift-xor)) val))
9120 (if (> eat 0) (setq eat (- eat 1)))
9121 (cond
9122 ((= 0 eat) ;multi byte
9123 (setq ret (concat ret (org-char-to-string sum)))
9124 (setq sum 0))
9125 ((not bytes) ; single byte(s)
9126 (setq ret (org-link-unescape-single-byte-sequence hex))))
9127 )) ;; end (while bytes
9128 ret )))
9130 (defun org-link-unescape-single-byte-sequence (hex)
9131 "Unhexify hex-encoded single byte character sequences."
9132 (mapconcat (lambda (byte)
9133 (char-to-string (string-to-number byte 16)))
9134 (cdr (split-string hex "%")) ""))
9136 (defun org-xor (a b)
9137 "Exclusive or."
9138 (if a (not b) b))
9140 (defun org-fixup-message-id-for-http (s)
9141 "Replace special characters in a message id, so it can be used in an http query."
9142 (when (string-match "%" s)
9143 (setq s (mapconcat (lambda (c)
9144 (if (eq c ?%)
9145 "%25"
9146 (char-to-string c)))
9147 s "")))
9148 (while (string-match "<" s)
9149 (setq s (replace-match "%3C" t t s)))
9150 (while (string-match ">" s)
9151 (setq s (replace-match "%3E" t t s)))
9152 (while (string-match "@" s)
9153 (setq s (replace-match "%40" t t s)))
9156 (defun org-link-prettify (link)
9157 "Return a human-readable representation of LINK.
9158 The car of LINK must be a raw link the cdr of LINK must be either
9159 a link description or nil."
9160 (let ((desc (or (cadr link) "<no description>")))
9161 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9162 "[[" (car link) "]]")))
9164 ;;;###autoload
9165 (defun org-insert-link-global ()
9166 "Insert a link like Org-mode does.
9167 This command can be called in any mode to insert a link in Org-mode syntax."
9168 (interactive)
9169 (org-load-modules-maybe)
9170 (org-run-like-in-org-mode 'org-insert-link))
9172 (defun org-insert-link (&optional complete-file link-location default-description)
9173 "Insert a link. At the prompt, enter the link.
9175 Completion can be used to insert any of the link protocol prefixes like
9176 http or ftp in use.
9178 The history can be used to select a link previously stored with
9179 `org-store-link'. When the empty string is entered (i.e. if you just
9180 press RET at the prompt), the link defaults to the most recently
9181 stored link. As SPC triggers completion in the minibuffer, you need to
9182 use M-SPC or C-q SPC to force the insertion of a space character.
9184 You will also be prompted for a description, and if one is given, it will
9185 be displayed in the buffer instead of the link.
9187 If there is already a link at point, this command will allow you to edit link
9188 and description parts.
9190 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9191 be selected using completion. The path to the file will be relative to the
9192 current directory if the file is in the current directory or a subdirectory.
9193 Otherwise, the link will be the absolute path as completed in the minibuffer
9194 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9195 option `org-link-file-path-type'.
9197 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9198 the current directory or below.
9200 With three \\[universal-argument] prefixes, negate the meaning of
9201 `org-keep-stored-link-after-insertion'.
9203 If `org-make-link-description-function' is non-nil, this function will be
9204 called with the link target, and the result will be the default
9205 link description.
9207 If the LINK-LOCATION parameter is non-nil, this value will be
9208 used as the link location instead of reading one interactively.
9210 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9211 be used as the default description."
9212 (interactive "P")
9213 (let* ((wcf (current-window-configuration))
9214 (region (if (org-region-active-p)
9215 (buffer-substring (region-beginning) (region-end))))
9216 (remove (and region (list (region-beginning) (region-end))))
9217 (desc region)
9218 tmphist ; byte-compile incorrectly complains about this
9219 (link link-location)
9220 entry file all-prefixes)
9221 (cond
9222 (link-location) ; specified by arg, just use it.
9223 ((org-in-regexp org-bracket-link-regexp 1)
9224 ;; We do have a link at point, and we are going to edit it.
9225 (setq remove (list (match-beginning 0) (match-end 0)))
9226 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9227 (setq link (read-string "Link: "
9228 (org-link-unescape
9229 (org-match-string-no-properties 1)))))
9230 ((or (org-in-regexp org-angle-link-re)
9231 (org-in-regexp org-plain-link-re))
9232 ;; Convert to bracket link
9233 (setq remove (list (match-beginning 0) (match-end 0))
9234 link (read-string "Link: "
9235 (org-remove-angle-brackets (match-string 0)))))
9236 ((member complete-file '((4) (16)))
9237 ;; Completing read for file names.
9238 (setq link (org-file-complete-link complete-file)))
9240 ;; Read link, with completion for stored links.
9241 (with-output-to-temp-buffer "*Org Links*"
9242 (princ "Insert a link.
9243 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9244 (when org-stored-links
9245 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9246 (princ (mapconcat 'org-link-prettify
9247 (reverse org-stored-links) "\n"))))
9248 (let ((cw (selected-window)))
9249 (select-window (get-buffer-window "*Org Links*" 'visible))
9250 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9251 (unless (pos-visible-in-window-p (point-max))
9252 (org-fit-window-to-buffer))
9253 (and (window-live-p cw) (select-window cw)))
9254 ;; Fake a link history, containing the stored links.
9255 (setq tmphist (append (mapcar 'car org-stored-links)
9256 org-insert-link-history))
9257 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9258 (mapcar 'car org-link-abbrev-alist)
9259 org-link-types))
9260 (unwind-protect
9261 (progn
9262 (setq link
9263 (let ((org-completion-use-ido nil)
9264 (org-completion-use-iswitchb nil))
9265 (org-completing-read
9266 "Link: "
9267 (append
9268 (mapcar (lambda (x) (list (concat x ":")))
9269 all-prefixes)
9270 (mapcar 'car org-stored-links))
9271 nil nil nil
9272 'tmphist
9273 (car (car org-stored-links)))))
9274 (if (not (string-match "\\S-" link))
9275 (error "No link selected"))
9276 (if (or (member link all-prefixes)
9277 (and (equal ":" (substring link -1))
9278 (member (substring link 0 -1) all-prefixes)
9279 (setq link (substring link 0 -1))))
9280 (setq link (org-link-try-special-completion link))))
9281 (set-window-configuration wcf)
9282 (kill-buffer "*Org Links*"))
9283 (setq entry (assoc link org-stored-links))
9284 (or entry (push link org-insert-link-history))
9285 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9286 (not org-keep-stored-link-after-insertion))
9287 (setq org-stored-links (delq (assoc link org-stored-links)
9288 org-stored-links)))
9289 (setq desc (or desc (nth 1 entry)))))
9291 (if (string-match org-plain-link-re link)
9292 ;; URL-like link, normalize the use of angular brackets.
9293 (setq link (org-make-link (org-remove-angle-brackets link))))
9295 ;; Check if we are linking to the current file with a search option
9296 ;; If yes, simplify the link by using only the search option.
9297 (when (and buffer-file-name
9298 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9299 (let* ((path (match-string 1 link))
9300 (case-fold-search nil)
9301 (search (match-string 2 link)))
9302 (save-match-data
9303 (if (equal (file-truename buffer-file-name) (file-truename path))
9304 ;; We are linking to this same file, with a search option
9305 (setq link search)))))
9307 ;; Check if we can/should use a relative path. If yes, simplify the link
9308 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9309 (let* ((type (match-string 1 link))
9310 (path (match-string 2 link))
9311 (origpath path)
9312 (case-fold-search nil))
9313 (cond
9314 ((or (eq org-link-file-path-type 'absolute)
9315 (equal complete-file '(16)))
9316 (setq path (abbreviate-file-name (expand-file-name path))))
9317 ((eq org-link-file-path-type 'noabbrev)
9318 (setq path (expand-file-name path)))
9319 ((eq org-link-file-path-type 'relative)
9320 (setq path (file-relative-name path)))
9322 (save-match-data
9323 (if (string-match (concat "^" (regexp-quote
9324 (expand-file-name
9325 (file-name-as-directory
9326 default-directory))))
9327 (expand-file-name path))
9328 ;; We are linking a file with relative path name.
9329 (setq path (substring (expand-file-name path)
9330 (match-end 0)))
9331 (setq path (abbreviate-file-name (expand-file-name path)))))))
9332 (setq link (concat type path))
9333 (if (equal desc origpath)
9334 (setq desc path))))
9336 (if org-make-link-description-function
9337 (setq desc (funcall org-make-link-description-function link desc))
9338 (if default-description (setq desc default-description)))
9340 (setq desc (read-string "Description: " desc))
9341 (unless (string-match "\\S-" desc) (setq desc nil))
9342 (if remove (apply 'delete-region remove))
9343 (insert (org-make-link-string link desc))))
9345 (defun org-link-try-special-completion (type)
9346 "If there is completion support for link type TYPE, offer it."
9347 (let ((fun (intern (concat "org-" type "-complete-link"))))
9348 (if (functionp fun)
9349 (funcall fun)
9350 (read-string "Link (no completion support): " (concat type ":")))))
9352 (defun org-file-complete-link (&optional arg)
9353 "Create a file link using completion."
9354 (let (file link)
9355 (setq file (read-file-name "File: "))
9356 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9357 (pwd1 (file-name-as-directory (abbreviate-file-name
9358 (expand-file-name ".")))))
9359 (cond
9360 ((equal arg '(16))
9361 (setq link (org-make-link
9362 "file:"
9363 (abbreviate-file-name (expand-file-name file)))))
9364 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9365 (setq link (org-make-link "file:" (match-string 1 file))))
9366 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9367 (expand-file-name file))
9368 (setq link (org-make-link
9369 "file:" (match-string 1 (expand-file-name file)))))
9370 (t (setq link (org-make-link "file:" file)))))
9371 link))
9373 (defun org-completing-read (&rest args)
9374 "Completing-read with SPACE being a normal character."
9375 (let ((enable-recursive-minibuffers t)
9376 (minibuffer-local-completion-map
9377 (copy-keymap minibuffer-local-completion-map)))
9378 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9379 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9380 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9381 (apply 'org-icompleting-read args)))
9383 (defun org-completing-read-no-i (&rest args)
9384 (let (org-completion-use-ido org-completion-use-iswitchb)
9385 (apply 'org-completing-read args)))
9387 (defun org-iswitchb-completing-read (prompt choices &rest args)
9388 "Use iswitch as a completing-read replacement to choose from choices.
9389 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9390 from."
9391 (let* ((iswitchb-use-virtual-buffers nil)
9392 (iswitchb-make-buflist-hook
9393 (lambda ()
9394 (setq iswitchb-temp-buflist choices))))
9395 (iswitchb-read-buffer prompt)))
9397 (defun org-icompleting-read (&rest args)
9398 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9399 (org-without-partial-completion
9400 (if (and org-completion-use-ido
9401 (fboundp 'ido-completing-read)
9402 (boundp 'ido-mode) ido-mode
9403 (listp (second args)))
9404 (let ((ido-enter-matching-directory nil))
9405 (apply 'ido-completing-read (concat (car args))
9406 (if (consp (car (nth 1 args)))
9407 (mapcar 'car (nth 1 args))
9408 (nth 1 args))
9409 (cddr args)))
9410 (if (and org-completion-use-iswitchb
9411 (boundp 'iswitchb-mode) iswitchb-mode
9412 (listp (second args)))
9413 (apply 'org-iswitchb-completing-read (concat (car args))
9414 (if (consp (car (nth 1 args)))
9415 (mapcar 'car (nth 1 args))
9416 (nth 1 args))
9417 (cddr args))
9418 (apply 'completing-read args)))))
9420 (defun org-extract-attributes (s)
9421 "Extract the attributes cookie from a string and set as text property."
9422 (let (a attr (start 0) key value)
9423 (save-match-data
9424 (when (string-match "{{\\([^}]+\\)}}$" s)
9425 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9426 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9427 (setq key (match-string 1 a) value (match-string 2 a)
9428 start (match-end 0)
9429 attr (plist-put attr (intern key) value))))
9430 (org-add-props s nil 'org-attr attr))
9433 (defun org-extract-attributes-from-string (tag)
9434 (let (key value attr)
9435 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9436 (setq key (match-string 1 tag) value (match-string 2 tag)
9437 tag (replace-match "" t t tag)
9438 attr (plist-put attr (intern key) value)))
9439 (cons tag attr)))
9441 (defun org-attributes-to-string (plist)
9442 "Format a property list into an HTML attribute list."
9443 (let ((s "") key value)
9444 (while plist
9445 (setq key (pop plist) value (pop plist))
9446 (and value
9447 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9450 ;;; Opening/following a link
9452 (defvar org-link-search-failed nil)
9454 (defvar org-open-link-functions nil
9455 "Hook for functions finding a plain text link.
9456 These functions must take a single argument, the link content.
9457 They will be called for links that look like [[link text][description]]
9458 when LINK TEXT does not have a protocol like \"http:\" and does not look
9459 like a filename (e.g. \"./blue.png\").
9461 These functions will be called *before* Org attempts to resolve the
9462 link by doing text searches in the current buffer - so if you want a
9463 link \"[[target]]\" to still find \"<<target>>\", your function should
9464 handle this as a special case.
9466 When the function does handle the link, it must return a non-nil value.
9467 If it decides that it is not responsible for this link, it must return
9468 nil to indicate that that Org-mode can continue with other options
9469 like exact and fuzzy text search.")
9471 (defun org-next-link ()
9472 "Move forward to the next link.
9473 If the link is in hidden text, expose it."
9474 (interactive)
9475 (when (and org-link-search-failed (eq this-command last-command))
9476 (goto-char (point-min))
9477 (message "Link search wrapped back to beginning of buffer"))
9478 (setq org-link-search-failed nil)
9479 (let* ((pos (point))
9480 (ct (org-context))
9481 (a (assoc :link ct)))
9482 (if a (goto-char (nth 2 a)))
9483 (if (re-search-forward org-any-link-re nil t)
9484 (progn
9485 (goto-char (match-beginning 0))
9486 (if (outline-invisible-p) (org-show-context)))
9487 (goto-char pos)
9488 (setq org-link-search-failed t)
9489 (error "No further link found"))))
9491 (defun org-previous-link ()
9492 "Move backward to the previous link.
9493 If the link is in hidden text, expose it."
9494 (interactive)
9495 (when (and org-link-search-failed (eq this-command last-command))
9496 (goto-char (point-max))
9497 (message "Link search wrapped back to end of buffer"))
9498 (setq org-link-search-failed nil)
9499 (let* ((pos (point))
9500 (ct (org-context))
9501 (a (assoc :link ct)))
9502 (if a (goto-char (nth 1 a)))
9503 (if (re-search-backward org-any-link-re nil t)
9504 (progn
9505 (goto-char (match-beginning 0))
9506 (if (outline-invisible-p) (org-show-context)))
9507 (goto-char pos)
9508 (setq org-link-search-failed t)
9509 (error "No further link found"))))
9511 (defun org-translate-link (s)
9512 "Translate a link string if a translation function has been defined."
9513 (if (and org-link-translation-function
9514 (fboundp org-link-translation-function)
9515 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9516 (progn
9517 (setq s (funcall org-link-translation-function
9518 (match-string 1 s) (match-string 2 s)))
9519 (concat (car s) ":" (cdr s)))
9522 (defun org-translate-link-from-planner (type path)
9523 "Translate a link from Emacs Planner syntax so that Org can follow it.
9524 This is still an experimental function, your mileage may vary."
9525 (cond
9526 ((member type '("http" "https" "news" "ftp"))
9527 ;; standard Internet links are the same.
9528 nil)
9529 ((and (equal type "irc") (string-match "^//" path))
9530 ;; Planner has two / at the beginning of an irc link, we have 1.
9531 ;; We should have zero, actually....
9532 (setq path (substring path 1)))
9533 ((and (equal type "lisp") (string-match "^/" path))
9534 ;; Planner has a slash, we do not.
9535 (setq type "elisp" path (substring path 1)))
9536 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9537 ;; A typical message link. Planner has the id after the final slash,
9538 ;; we separate it with a hash mark
9539 (setq path (concat (match-string 1 path) "#"
9540 (org-remove-angle-brackets (match-string 2 path)))))
9542 (cons type path))
9544 (defun org-find-file-at-mouse (ev)
9545 "Open file link or URL at mouse."
9546 (interactive "e")
9547 (mouse-set-point ev)
9548 (org-open-at-point 'in-emacs))
9550 (defun org-open-at-mouse (ev)
9551 "Open file link or URL at mouse.
9552 See the docstring of `org-open-file' for details."
9553 (interactive "e")
9554 (mouse-set-point ev)
9555 (if (eq major-mode 'org-agenda-mode)
9556 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9557 (org-open-at-point))
9559 (defvar org-window-config-before-follow-link nil
9560 "The window configuration before following a link.
9561 This is saved in case the need arises to restore it.")
9563 (defvar org-open-link-marker (make-marker)
9564 "Marker pointing to the location where `org-open-at-point; was called.")
9566 ;;;###autoload
9567 (defun org-open-at-point-global ()
9568 "Follow a link like Org-mode does.
9569 This command can be called in any mode to follow a link that has
9570 Org-mode syntax."
9571 (interactive)
9572 (org-run-like-in-org-mode 'org-open-at-point))
9574 ;;;###autoload
9575 (defun org-open-link-from-string (s &optional arg reference-buffer)
9576 "Open a link in the string S, as if it was in Org-mode."
9577 (interactive "sLink: \nP")
9578 (let ((reference-buffer (or reference-buffer (current-buffer))))
9579 (with-temp-buffer
9580 (let ((org-inhibit-startup (not reference-buffer)))
9581 (org-mode)
9582 (insert s)
9583 (goto-char (point-min))
9584 (when reference-buffer
9585 (setq org-link-abbrev-alist-local
9586 (with-current-buffer reference-buffer
9587 org-link-abbrev-alist-local)))
9588 (org-open-at-point arg reference-buffer)))))
9590 (defvar org-open-at-point-functions nil
9591 "Hook that is run when following a link at point.
9593 Functions in this hook must return t if they identify and follow
9594 a link at point. If they don't find anything interesting at point,
9595 they must return nil.")
9597 (defun org-open-at-point (&optional arg reference-buffer)
9598 "Open link at or after point.
9599 If there is no link at point, this function will search forward up to
9600 the end of the current line.
9601 Normally, files will be opened by an appropriate application. If the
9602 optional prefix argument ARG is non-nil, Emacs will visit the file.
9603 With a double prefix argument, try to open outside of Emacs, in the
9604 application the system uses for this file type."
9605 (interactive "P")
9606 ;; if in a code block, then open the block's results
9607 (unless (call-interactively #'org-babel-open-src-block-result)
9608 (org-load-modules-maybe)
9609 (move-marker org-open-link-marker (point))
9610 (setq org-window-config-before-follow-link (current-window-configuration))
9611 (org-remove-occur-highlights nil nil t)
9612 (cond
9613 ((and (org-at-heading-p)
9614 (not (org-at-timestamp-p t))
9615 (not (org-in-regexp
9616 (concat org-plain-link-re "\\|"
9617 org-bracket-link-regexp "\\|"
9618 org-angle-link-re "\\|"
9619 "[ \t]:[^ \t\n]+:[ \t]*$")))
9620 (not (get-text-property (point) 'org-linked-text)))
9621 (or (org-offer-links-in-entry arg)
9622 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9623 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9624 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9625 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9626 (not (org-in-regexp org-bracket-link-regexp)))
9627 (org-footnote-action))
9629 (let (type path link line search (pos (point)))
9630 (catch 'match
9631 (save-excursion
9632 (skip-chars-forward "^]\n\r")
9633 (when (org-in-regexp org-bracket-link-regexp 1)
9634 (setq link (org-extract-attributes
9635 (org-link-unescape (org-match-string-no-properties 1))))
9636 (while (string-match " *\n *" link)
9637 (setq link (replace-match " " t t link)))
9638 (setq link (org-link-expand-abbrev link))
9639 (cond
9640 ((or (file-name-absolute-p link)
9641 (string-match "^\\.\\.?/" link))
9642 (setq type "file" path link))
9643 ((string-match org-link-re-with-space3 link)
9644 (setq type (match-string 1 link) path (match-string 2 link)))
9645 (t (setq type "thisfile" path link)))
9646 (throw 'match t)))
9648 (when (get-text-property (point) 'org-linked-text)
9649 (setq type "thisfile"
9650 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9651 (1+ (point)) (point))
9652 path (buffer-substring
9653 (or (previous-single-property-change pos 'org-linked-text)
9654 (point-min))
9655 (or (next-single-property-change pos 'org-linked-text)
9656 (point-max))))
9657 (throw 'match t))
9659 (save-excursion
9660 (when (or (org-in-regexp org-angle-link-re)
9661 (org-in-regexp org-plain-link-re))
9662 (setq type (match-string 1)
9663 path (org-link-unescape (match-string 2)))
9664 (throw 'match t)))
9665 (save-excursion
9666 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9667 (setq type "tags"
9668 path (match-string 1))
9669 (while (string-match ":" path)
9670 (setq path (replace-match "+" t t path)))
9671 (throw 'match t)))
9672 (when (org-in-regexp "<\\([^><\n]+\\)>")
9673 (setq type "tree-match"
9674 path (match-string 1))
9675 (throw 'match t)))
9676 (unless path
9677 (error "No link found"))
9679 ;; switch back to reference buffer
9680 ;; needed when if called in a temporary buffer through
9681 ;; org-open-link-from-string
9682 (with-current-buffer (or reference-buffer (current-buffer))
9684 ;; Remove any trailing spaces in path
9685 (if (string-match " +\\'" path)
9686 (setq path (replace-match "" t t path)))
9687 (if (and org-link-translation-function
9688 (fboundp org-link-translation-function))
9689 ;; Check if we need to translate the link
9690 (let ((tmp (funcall org-link-translation-function type path)))
9691 (setq type (car tmp) path (cdr tmp))))
9693 (cond
9695 ((assoc type org-link-protocols)
9696 (funcall (nth 1 (assoc type org-link-protocols)) path))
9698 ((equal type "mailto")
9699 (let ((cmd (car org-link-mailto-program))
9700 (args (cdr org-link-mailto-program)) args1
9701 (address path) (subject "") a)
9702 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9703 (setq address (match-string 1 path)
9704 subject (org-link-escape (match-string 2 path))))
9705 (while args
9706 (cond
9707 ((not (stringp (car args))) (push (pop args) args1))
9708 (t (setq a (pop args))
9709 (if (string-match "%a" a)
9710 (setq a (replace-match address t t a)))
9711 (if (string-match "%s" a)
9712 (setq a (replace-match subject t t a)))
9713 (push a args1))))
9714 (apply cmd (nreverse args1))))
9716 ((member type '("http" "https" "ftp" "news"))
9717 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9718 (org-link-escape
9719 path org-link-escape-chars-browser)
9720 path))))
9722 ((string= type "doi")
9723 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9724 (org-link-escape
9725 path org-link-escape-chars-browser)
9726 path))))
9728 ((member type '("message"))
9729 (browse-url (concat type ":" path)))
9731 ((string= type "tags")
9732 (org-tags-view arg path))
9734 ((string= type "tree-match")
9735 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9737 ((string= type "file")
9738 (if (string-match "::\\([0-9]+\\)\\'" path)
9739 (setq line (string-to-number (match-string 1 path))
9740 path (substring path 0 (match-beginning 0)))
9741 (if (string-match "::\\(.+\\)\\'" path)
9742 (setq search (match-string 1 path)
9743 path (substring path 0 (match-beginning 0)))))
9744 (if (string-match "[*?{]" (file-name-nondirectory path))
9745 (dired path)
9746 (org-open-file path arg line search)))
9748 ((string= type "shell")
9749 (let ((cmd path))
9750 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9751 (string-match org-confirm-shell-link-not-regexp cmd))
9752 (not org-confirm-shell-link-function)
9753 (funcall org-confirm-shell-link-function
9754 (format "Execute \"%s\" in shell? "
9755 (org-add-props cmd nil
9756 'face 'org-warning))))
9757 (progn
9758 (message "Executing %s" cmd)
9759 (shell-command cmd))
9760 (error "Abort"))))
9762 ((string= type "elisp")
9763 (let ((cmd path))
9764 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9765 (string-match org-confirm-elisp-link-not-regexp cmd))
9766 (not org-confirm-elisp-link-function)
9767 (funcall org-confirm-elisp-link-function
9768 (format "Execute \"%s\" as elisp? "
9769 (org-add-props cmd nil
9770 'face 'org-warning))))
9771 (message "%s => %s" cmd
9772 (if (equal (string-to-char cmd) ?\()
9773 (eval (read cmd))
9774 (call-interactively (read cmd))))
9775 (error "Abort"))))
9777 ((and (string= type "thisfile")
9778 (run-hook-with-args-until-success
9779 'org-open-link-functions path)))
9781 ((string= type "thisfile")
9782 (if arg
9783 (switch-to-buffer-other-window
9784 (org-get-buffer-for-internal-link (current-buffer)))
9785 (org-mark-ring-push))
9786 (let ((cmd `(org-link-search
9787 ,path
9788 ,(cond ((equal arg '(4)) ''occur)
9789 ((equal arg '(16)) ''org-occur)
9790 (t nil))
9791 ,pos)))
9792 (condition-case nil (let ((org-link-search-inhibit-query t))
9793 (eval cmd))
9794 (error (progn (widen) (eval cmd))))))
9797 (browse-url-at-point)))))))
9798 (move-marker org-open-link-marker nil)
9799 (run-hook-with-args 'org-follow-link-hook)))
9801 (defun org-offer-links-in-entry (&optional nth zero)
9802 "Offer links in the current entry and follow the selected link.
9803 If there is only one link, follow it immediately as well.
9804 If NTH is an integer, immediately pick the NTH link found.
9805 If ZERO is a string, check also this string for a link, and if
9806 there is one, offer it as link number zero."
9807 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9808 "\\(" org-angle-link-re "\\)\\|"
9809 "\\(" org-plain-link-re "\\)"))
9810 (cnt ?0)
9811 (in-emacs (if (integerp nth) nil nth))
9812 have-zero end links link c)
9813 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9814 (push (match-string 0 zero) links)
9815 (setq cnt (1- cnt) have-zero t))
9816 (save-excursion
9817 (org-back-to-heading t)
9818 (setq end (save-excursion (outline-next-heading) (point)))
9819 (while (re-search-forward re end t)
9820 (push (match-string 0) links))
9821 (setq links (org-uniquify (reverse links))))
9823 (cond
9824 ((null links)
9825 (message "No links"))
9826 ((equal (length links) 1)
9827 (setq link (list (car links))))
9828 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9829 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9830 (t ; we have to select a link
9831 (save-excursion
9832 (save-window-excursion
9833 (delete-other-windows)
9834 (with-output-to-temp-buffer "*Select Link*"
9835 (mapc (lambda (l)
9836 (if (not (string-match org-bracket-link-regexp l))
9837 (princ (format "[%c] %s\n" (incf cnt)
9838 (org-remove-angle-brackets l)))
9839 (if (match-end 3)
9840 (princ (format "[%c] %s (%s)\n" (incf cnt)
9841 (match-string 3 l) (match-string 1 l)))
9842 (princ (format "[%c] %s\n" (incf cnt)
9843 (match-string 1 l))))))
9844 links))
9845 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9846 (message "Select link to open, RET to open all:")
9847 (setq c (read-char-exclusive))
9848 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9849 (when (equal c ?q) (error "Abort"))
9850 (if (equal c ?\C-m)
9851 (setq link links)
9852 (setq nth (- c ?0))
9853 (if have-zero (setq nth (1+ nth)))
9854 (unless (and (integerp nth) (>= (length links) nth))
9855 (error "Invalid link selection"))
9856 (setq link (list (nth (1- nth) links))))))
9857 (if link
9858 (let ((buf (current-buffer)))
9859 (dolist (l link)
9860 (org-open-link-from-string l in-emacs buf))
9862 nil)))
9864 ;; Add special file links that specify the way of opening
9866 (org-add-link-type "file+sys" 'org-open-file-with-system)
9867 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9868 (defun org-open-file-with-system (path)
9869 "Open file at PATH using the system way of opening it."
9870 (org-open-file path 'system))
9871 (defun org-open-file-with-emacs (path)
9872 "Open file at PATH in Emacs."
9873 (org-open-file path 'emacs))
9874 (defun org-remove-file-link-modifiers ()
9875 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9876 (goto-char (point-min))
9877 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9878 (org-if-unprotected
9879 (replace-match "file:" t t))))
9880 (eval-after-load "org-exp"
9881 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9882 'org-remove-file-link-modifiers))
9884 ;;;; Time estimates
9886 (defun org-get-effort (&optional pom)
9887 "Get the effort estimate for the current entry."
9888 (org-entry-get pom org-effort-property))
9890 ;;; File search
9892 (defvar org-create-file-search-functions nil
9893 "List of functions to construct the right search string for a file link.
9894 These functions are called in turn with point at the location to
9895 which the link should point.
9897 A function in the hook should first test if it would like to
9898 handle this file type, for example by checking the `major-mode'
9899 or the file extension. If it decides not to handle this file, it
9900 should just return nil to give other functions a chance. If it
9901 does handle the file, it must return the search string to be used
9902 when following the link. The search string will be part of the
9903 file link, given after a double colon, and `org-open-at-point'
9904 will automatically search for it. If special measures must be
9905 taken to make the search successful, another function should be
9906 added to the companion hook `org-execute-file-search-functions',
9907 which see.
9909 A function in this hook may also use `setq' to set the variable
9910 `description' to provide a suggestion for the descriptive text to
9911 be used for this link when it gets inserted into an Org-mode
9912 buffer with \\[org-insert-link].")
9914 (defvar org-execute-file-search-functions nil
9915 "List of functions to execute a file search triggered by a link.
9917 Functions added to this hook must accept a single argument, the
9918 search string that was part of the file link, the part after the
9919 double colon. The function must first check if it would like to
9920 handle this search, for example by checking the `major-mode' or
9921 the file extension. If it decides not to handle this search, it
9922 should just return nil to give other functions a chance. If it
9923 does handle the search, it must return a non-nil value to keep
9924 other functions from trying.
9926 Each function can access the current prefix argument through the
9927 variable `current-prefix-argument'. Note that a single prefix is
9928 used to force opening a link in Emacs, so it may be good to only
9929 use a numeric or double prefix to guide the search function.
9931 In case this is needed, a function in this hook can also restore
9932 the window configuration before `org-open-at-point' was called using:
9934 (set-window-configuration org-window-config-before-follow-link)")
9936 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9937 (defun org-link-search (s &optional type avoid-pos stealth)
9938 "Search for a link search option.
9939 If S is surrounded by forward slashes, it is interpreted as a
9940 regular expression. In org-mode files, this will create an `org-occur'
9941 sparse tree. In ordinary files, `occur' will be used to list matches.
9942 If the current buffer is in `dired-mode', grep will be used to search
9943 in all files. If AVOID-POS is given, ignore matches near that position.
9945 When optional argument STEALTH is non-nil, do not modify
9946 visibility around point, thus ignoring
9947 `org-show-hierarchy-above', `org-show-following-heading' and
9948 `org-show-siblings' variables."
9949 (let ((case-fold-search t)
9950 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9951 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9952 (append '(("") (" ") ("\t") ("\n"))
9953 org-emphasis-alist)
9954 "\\|") "\\)"))
9955 (pos (point))
9956 (pre nil) (post nil)
9957 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9958 (cond
9959 ;; First check if there are any special search functions
9960 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9961 ;; Now try the builtin stuff
9962 ((and (equal (string-to-char s0) ?#)
9963 (> (length s0) 1)
9964 (save-excursion
9965 (goto-char (point-min))
9966 (and
9967 (re-search-forward
9968 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9969 (setq type 'dedicated
9970 pos (match-beginning 0))))
9971 ;; There is an exact target for this
9972 (goto-char pos)
9973 (org-back-to-heading t)))
9974 ((save-excursion
9975 (goto-char (point-min))
9976 (and
9977 (re-search-forward
9978 (concat "<<" (regexp-quote s0) ">>") nil t)
9979 (setq type 'dedicated
9980 pos (match-beginning 0))))
9981 ;; There is an exact target for this
9982 (goto-char pos))
9983 ((save-excursion
9984 (goto-char (point-min))
9985 (and
9986 (re-search-forward
9987 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9988 (setq type 'dedicated pos (match-beginning 0))))
9989 ;; Found an invisible target.
9990 (goto-char pos))
9991 ((save-excursion
9992 (goto-char (point-min))
9993 (and
9994 (re-search-forward
9995 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9996 (setq type 'dedicated pos (match-beginning 0))))
9997 ;; Found an element with a matching #+name affiliated keyword.
9998 (goto-char pos))
9999 ((and (string-match "^(\\(.*\\))$" s0)
10000 (save-excursion
10001 (goto-char (point-min))
10002 (and
10003 (re-search-forward
10004 (concat "[^[]" (regexp-quote
10005 (format org-coderef-label-format
10006 (match-string 1 s0))))
10007 nil t)
10008 (setq type 'dedicated
10009 pos (1+ (match-beginning 0))))))
10010 ;; There is a coderef target for this
10011 (goto-char pos))
10012 ((string-match "^/\\(.*\\)/$" s)
10013 ;; A regular expression
10014 (cond
10015 ((derived-mode-p 'org-mode)
10016 (org-occur (match-string 1 s)))
10017 ;;((eq major-mode 'dired-mode)
10018 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10019 (t (org-do-occur (match-string 1 s)))))
10020 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10021 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10022 (goto-char (point-min))
10023 (cond
10024 ((let (case-fold-search)
10025 (re-search-forward (format org-complex-heading-regexp-format
10026 (regexp-quote s))
10027 nil t))
10028 ;; OK, found a match
10029 (setq type 'dedicated)
10030 (goto-char (match-beginning 0)))
10031 ((and (not org-link-search-inhibit-query)
10032 (eq org-link-search-must-match-exact-headline 'query-to-create)
10033 (y-or-n-p "No match - create this as a new heading? "))
10034 (goto-char (point-max))
10035 (or (bolp) (newline))
10036 (insert "* " s "\n")
10037 (beginning-of-line 0))
10039 (goto-char pos)
10040 (error "No match"))))
10042 ;; A normal search string
10043 (when (equal (string-to-char s) ?*)
10044 ;; Anchor on headlines, post may include tags.
10045 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10046 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10047 s (substring s 1)))
10048 (remove-text-properties
10049 0 (length s)
10050 '(face nil mouse-face nil keymap nil fontified nil) s)
10051 ;; Make a series of regular expressions to find a match
10052 (setq words (org-split-string s "[ \n\r\t]+")
10054 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10055 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10056 "\\)" markers)
10057 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10058 re2a (concat "[ \t\r\n]" re2a_)
10059 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10060 re4 (concat "[^a-zA-Z_]" re4_)
10062 re1 (concat pre re2 post)
10063 re3 (concat pre (if pre re4_ re4) post)
10064 re5 (concat pre ".*" re4)
10065 re2 (concat pre re2)
10066 re2a (concat pre (if pre re2a_ re2a))
10067 re4 (concat pre (if pre re4_ re4))
10068 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10069 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10070 re5 "\\)"
10072 (cond
10073 ((eq type 'org-occur) (org-occur reall))
10074 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10075 (t (goto-char (point-min))
10076 (setq type 'fuzzy)
10077 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10078 (org-search-not-self 1 re1 nil t)
10079 (org-search-not-self 1 re2 nil t)
10080 (org-search-not-self 1 re2a nil t)
10081 (org-search-not-self 1 re3 nil t)
10082 (org-search-not-self 1 re4 nil t)
10083 (org-search-not-self 1 re5 nil t)
10085 (goto-char (match-beginning 1))
10086 (goto-char pos)
10087 (error "No match"))))))
10088 (and (derived-mode-p 'org-mode)
10089 (not stealth)
10090 (org-show-context 'link-search))
10091 type))
10093 (defun org-search-not-self (group &rest args)
10094 "Execute `re-search-forward', but only accept matches that do not
10095 enclose the position of `org-open-link-marker'."
10096 (let ((m org-open-link-marker))
10097 (catch 'exit
10098 (while (apply 're-search-forward args)
10099 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10100 (goto-char (match-end group))
10101 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10102 (> (match-beginning 0) (marker-position m))
10103 (< (match-end 0) (marker-position m)))
10104 (save-match-data
10105 (or (not (org-in-regexp
10106 org-bracket-link-analytic-regexp 1))
10107 (not (match-end 4)) ; no description
10108 (and (<= (match-beginning 4) (point))
10109 (>= (match-end 4) (point))))))
10110 (throw 'exit (point))))))))
10112 (defun org-get-buffer-for-internal-link (buffer)
10113 "Return a buffer to be used for displaying the link target of internal links."
10114 (cond
10115 ((not org-display-internal-link-with-indirect-buffer)
10116 buffer)
10117 ((string-match "(Clone)$" (buffer-name buffer))
10118 (message "Buffer is already a clone, not making another one")
10119 ;; we also do not modify visibility in this case
10120 buffer)
10121 (t ; make a new indirect buffer for displaying the link
10122 (let* ((bn (buffer-name buffer))
10123 (ibn (concat bn "(Clone)"))
10124 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10125 (with-current-buffer ib (org-overview))
10126 ib))))
10128 (defun org-do-occur (regexp &optional cleanup)
10129 "Call the Emacs command `occur'.
10130 If CLEANUP is non-nil, remove the printout of the regular expression
10131 in the *Occur* buffer. This is useful if the regex is long and not useful
10132 to read."
10133 (occur regexp)
10134 (when cleanup
10135 (let ((cwin (selected-window)) win beg end)
10136 (when (setq win (get-buffer-window "*Occur*"))
10137 (select-window win))
10138 (goto-char (point-min))
10139 (when (re-search-forward "match[a-z]+" nil t)
10140 (setq beg (match-end 0))
10141 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10142 (setq end (1- (match-beginning 0)))))
10143 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10144 (goto-char (point-min))
10145 (select-window cwin))))
10147 ;;; The mark ring for links jumps
10149 (defvar org-mark-ring nil
10150 "Mark ring for positions before jumps in Org-mode.")
10151 (defvar org-mark-ring-last-goto nil
10152 "Last position in the mark ring used to go back.")
10153 ;; Fill and close the ring
10154 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10155 (loop for i from 1 to org-mark-ring-length do
10156 (push (make-marker) org-mark-ring))
10157 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10158 org-mark-ring)
10160 (defun org-mark-ring-push (&optional pos buffer)
10161 "Put the current position or POS into the mark ring and rotate it."
10162 (interactive)
10163 (setq pos (or pos (point)))
10164 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10165 (move-marker (car org-mark-ring)
10166 (or pos (point))
10167 (or buffer (current-buffer)))
10168 (message "%s"
10169 (substitute-command-keys
10170 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10172 (defun org-mark-ring-goto (&optional n)
10173 "Jump to the previous position in the mark ring.
10174 With prefix arg N, jump back that many stored positions. When
10175 called several times in succession, walk through the entire ring.
10176 Org-mode commands jumping to a different position in the current file,
10177 or to another Org-mode file, automatically push the old position
10178 onto the ring."
10179 (interactive "p")
10180 (let (p m)
10181 (if (eq last-command this-command)
10182 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10183 (setq p org-mark-ring))
10184 (setq org-mark-ring-last-goto p)
10185 (setq m (car p))
10186 (org-pop-to-buffer-same-window (marker-buffer m))
10187 (goto-char m)
10188 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10190 (defun org-remove-angle-brackets (s)
10191 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10192 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10194 (defun org-add-angle-brackets (s)
10195 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10196 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10198 (defun org-remove-double-quotes (s)
10199 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10200 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10203 ;;; Following specific links
10205 (defun org-follow-timestamp-link ()
10206 (cond
10207 ((org-at-date-range-p t)
10208 (let ((org-agenda-start-on-weekday)
10209 (t1 (match-string 1))
10210 (t2 (match-string 2)))
10211 (setq t1 (time-to-days (org-time-string-to-time t1))
10212 t2 (time-to-days (org-time-string-to-time t2)))
10213 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10214 ((org-at-timestamp-p t)
10215 (org-agenda-list nil (time-to-days (org-time-string-to-time
10216 (substring (match-string 1) 0 10)))
10218 (t (error "This should not happen"))))
10221 ;;; Following file links
10222 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10223 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10224 (declare-function mailcap-mime-info
10225 "mailcap" (string &optional request no-decode))
10226 (defvar org-wait nil)
10227 (defun org-open-file (path &optional in-emacs line search)
10228 "Open the file at PATH.
10229 First, this expands any special file name abbreviations. Then the
10230 configuration variable `org-file-apps' is checked if it contains an
10231 entry for this file type, and if yes, the corresponding command is launched.
10233 If no application is found, Emacs simply visits the file.
10235 With optional prefix argument IN-EMACS, Emacs will visit the file.
10236 With a double \\[universal-argument] \\[universal-argument] \
10237 prefix arg, Org tries to avoid opening in Emacs
10238 and to use an external application to visit the file.
10240 Optional LINE specifies a line to go to, optional SEARCH a string
10241 to search for. If LINE or SEARCH is given, the file will be
10242 opened in Emacs, unless an entry from org-file-apps that makes
10243 use of groups in a regexp matches.
10245 If you want to change the way frames are used when following a
10246 link, please customize `org-link-frame-setup'.
10248 If the file does not exist, an error is thrown."
10249 (let* ((file (if (equal path "")
10250 buffer-file-name
10251 (substitute-in-file-name (expand-file-name path))))
10252 (file-apps (append org-file-apps (org-default-apps)))
10253 (apps (org-remove-if
10254 'org-file-apps-entry-match-against-dlink-p file-apps))
10255 (apps-dlink (org-remove-if-not
10256 'org-file-apps-entry-match-against-dlink-p file-apps))
10257 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10258 (dirp (if remp nil (file-directory-p file)))
10259 (file (if (and dirp org-open-directory-means-index-dot-org)
10260 (concat (file-name-as-directory file) "index.org")
10261 file))
10262 (a-m-a-p (assq 'auto-mode apps))
10263 (dfile (downcase file))
10264 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10265 (link (cond ((and (eq line nil)
10266 (eq search nil))
10267 file)
10268 (line
10269 (concat file "::" (number-to-string line)))
10270 (search
10271 (concat file "::" search))))
10272 (dlink (downcase link))
10273 (old-buffer (current-buffer))
10274 (old-pos (point))
10275 (old-mode major-mode)
10276 ext cmd link-match-data)
10277 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10278 (setq ext (match-string 1 dfile))
10279 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10280 (setq ext (match-string 1 dfile))))
10281 (cond
10282 ((member in-emacs '((16) system))
10283 (setq cmd (cdr (assoc 'system apps))))
10284 (in-emacs (setq cmd 'emacs))
10286 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10287 (and dirp (cdr (assoc 'directory apps)))
10288 ; first, try matching against apps-dlink
10289 ; if we get a match here, store the match data for later
10290 (let ((match (assoc-default dlink apps-dlink
10291 'string-match)))
10292 (if match
10293 (progn (setq link-match-data (match-data))
10294 match)
10295 (progn (setq in-emacs (or in-emacs line search))
10296 nil))) ; if we have no match in apps-dlink,
10297 ; always open the file in emacs if line or search
10298 ; is given (for backwards compatibility)
10299 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10300 'string-match)
10301 (cdr (assoc ext apps))
10302 (cdr (assoc t apps))))))
10303 (when (eq cmd 'system)
10304 (setq cmd (cdr (assoc 'system apps))))
10305 (when (eq cmd 'default)
10306 (setq cmd (cdr (assoc t apps))))
10307 (when (eq cmd 'mailcap)
10308 (require 'mailcap)
10309 (mailcap-parse-mailcaps)
10310 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10311 (command (mailcap-mime-info mime-type)))
10312 (if (stringp command)
10313 (setq cmd command)
10314 (setq cmd 'emacs))))
10315 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10316 (not (file-exists-p file))
10317 (not org-open-non-existing-files))
10318 (error "No such file: %s" file))
10319 (cond
10320 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10321 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10322 (while (string-match "['\"]%s['\"]" cmd)
10323 (setq cmd (replace-match "%s" t t cmd)))
10324 (while (string-match "%s" cmd)
10325 (setq cmd (replace-match
10326 (save-match-data
10327 (shell-quote-argument
10328 (convert-standard-filename file)))
10329 t t cmd)))
10331 ;; Replace "%1", "%2" etc. in command with group matches from regex
10332 (save-match-data
10333 (let ((match-index 1)
10334 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10335 (set-match-data link-match-data)
10336 (while (<= match-index number-of-groups)
10337 (let ((regex (concat "%" (number-to-string match-index)))
10338 (replace-with (match-string match-index dlink)))
10339 (while (string-match regex cmd)
10340 (setq cmd (replace-match replace-with t t cmd))))
10341 (setq match-index (+ match-index 1)))))
10343 (save-window-excursion
10344 (start-process-shell-command cmd nil cmd)
10345 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10347 ((or (stringp cmd)
10348 (eq cmd 'emacs))
10349 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10350 (widen)
10351 (if line (org-goto-line line)
10352 (if search (org-link-search search))))
10353 ((consp cmd)
10354 (let ((file (convert-standard-filename file)))
10355 (save-match-data
10356 (set-match-data link-match-data)
10357 (eval cmd))))
10358 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10359 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10360 (or (not (equal old-buffer (current-buffer)))
10361 (not (equal old-pos (point))))
10362 (org-mark-ring-push old-pos old-buffer))))
10364 (defun org-file-apps-entry-match-against-dlink-p (entry)
10365 "This function returns non-nil if `entry' uses a regular
10366 expression which should be matched against the whole link by
10367 org-open-file.
10369 It assumes that is the case when the entry uses a regular
10370 expression which has at least one grouping construct and the
10371 action is either a lisp form or a command string containing
10372 '%1', i.e. using at least one subexpression match as a
10373 parameter."
10374 (let ((selector (car entry))
10375 (action (cdr entry)))
10376 (if (stringp selector)
10377 (and (> (regexp-opt-depth selector) 0)
10378 (or (and (stringp action)
10379 (string-match "%[0-9]" action))
10380 (consp action)))
10381 nil)))
10383 (defun org-default-apps ()
10384 "Return the default applications for this operating system."
10385 (cond
10386 ((eq system-type 'darwin)
10387 org-file-apps-defaults-macosx)
10388 ((eq system-type 'windows-nt)
10389 org-file-apps-defaults-windowsnt)
10390 (t org-file-apps-defaults-gnu)))
10392 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10393 "Convert extensions to regular expressions in the cars of LIST.
10394 Also, weed out any non-string entries, because the return value is used
10395 only for regexp matching.
10396 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10397 point to the symbol `emacs', indicating that the file should
10398 be opened in Emacs."
10399 (append
10400 (delq nil
10401 (mapcar (lambda (x)
10402 (if (not (stringp (car x)))
10404 (if (string-match "\\W" (car x))
10406 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10407 list))
10408 (if add-auto-mode
10409 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10411 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10412 (defun org-file-remote-p (file)
10413 "Test whether FILE specifies a location on a remote system.
10414 Return non-nil if the location is indeed remote.
10416 For example, the filename \"/user@host:/foo\" specifies a location
10417 on the system \"/user@host:\"."
10418 (cond ((fboundp 'file-remote-p)
10419 (file-remote-p file))
10420 ((fboundp 'tramp-handle-file-remote-p)
10421 (tramp-handle-file-remote-p file))
10422 ((and (boundp 'ange-ftp-name-format)
10423 (string-match (car ange-ftp-name-format) file))
10425 (t nil)))
10428 ;;;; Refiling
10430 (defun org-get-org-file ()
10431 "Read a filename, with default directory `org-directory'."
10432 (let ((default (or org-default-notes-file remember-data-file)))
10433 (read-file-name (format "File name [%s]: " default)
10434 (file-name-as-directory org-directory)
10435 default)))
10437 (defun org-notes-order-reversed-p ()
10438 "Check if the current file should receive notes in reversed order."
10439 (cond
10440 ((not org-reverse-note-order) nil)
10441 ((eq t org-reverse-note-order) t)
10442 ((not (listp org-reverse-note-order)) nil)
10443 (t (catch 'exit
10444 (let ((all org-reverse-note-order)
10445 entry)
10446 (while (setq entry (pop all))
10447 (if (string-match (car entry) buffer-file-name)
10448 (throw 'exit (cdr entry))))
10449 nil)))))
10451 (defvar org-refile-target-table nil
10452 "The list of refile targets, created by `org-refile'.")
10454 (defvar org-agenda-new-buffers nil
10455 "Buffers created to visit agenda files.")
10457 (defvar org-refile-cache nil
10458 "Cache for refile targets.")
10460 (defvar org-refile-markers nil
10461 "All the markers used for caching refile locations.")
10463 (defun org-refile-marker (pos)
10464 "Get a new refile marker, but only if caching is in use."
10465 (if (not org-refile-use-cache)
10467 (let ((m (make-marker)))
10468 (move-marker m pos)
10469 (push m org-refile-markers)
10470 m)))
10472 (defun org-refile-cache-clear ()
10473 "Clear the refile cache and disable all the markers."
10474 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10475 (setq org-refile-markers nil)
10476 (setq org-refile-cache nil)
10477 (message "Refile cache has been cleared"))
10479 (defun org-refile-cache-check-set (set)
10480 "Check if all the markers in the cache still have live buffers."
10481 (let (marker)
10482 (catch 'exit
10483 (while (and set (setq marker (nth 3 (pop set))))
10484 ;; if org-refile-use-outline-path is 'file, marker may be nil
10485 (when (and marker (null (marker-buffer marker)))
10486 (message "not found") (sit-for 3)
10487 (throw 'exit nil)))
10488 t)))
10490 (defun org-refile-cache-put (set &rest identifiers)
10491 "Push the refile targets SET into the cache, under IDENTIFIERS."
10492 (let* ((key (sha1 (prin1-to-string identifiers)))
10493 (entry (assoc key org-refile-cache)))
10494 (if entry
10495 (setcdr entry set)
10496 (push (cons key set) org-refile-cache))))
10498 (defun org-refile-cache-get (&rest identifiers)
10499 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10500 (cond
10501 ((not org-refile-cache) nil)
10502 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10504 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10505 org-refile-cache))))
10506 (and set (org-refile-cache-check-set set) set)))))
10508 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10509 "Produce a table with refile targets."
10510 (let ((case-fold-search nil)
10511 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10512 (entries (or org-refile-targets '((nil . (:level . 1)))))
10513 targets tgs txt re files f desc descre fast-path-p level pos0)
10514 (message "Getting targets...")
10515 (with-current-buffer (or default-buffer (current-buffer))
10516 (while (setq entry (pop entries))
10517 (setq files (car entry) desc (cdr entry))
10518 (setq fast-path-p nil)
10519 (cond
10520 ((null files) (setq files (list (current-buffer))))
10521 ((eq files 'org-agenda-files)
10522 (setq files (org-agenda-files 'unrestricted)))
10523 ((and (symbolp files) (fboundp files))
10524 (setq files (funcall files)))
10525 ((and (symbolp files) (boundp files))
10526 (setq files (symbol-value files))))
10527 (if (stringp files) (setq files (list files)))
10528 (cond
10529 ((eq (car desc) :tag)
10530 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10531 ((eq (car desc) :todo)
10532 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10533 ((eq (car desc) :regexp)
10534 (setq descre (cdr desc)))
10535 ((eq (car desc) :level)
10536 (setq descre (concat "^\\*\\{" (number-to-string
10537 (if org-odd-levels-only
10538 (1- (* 2 (cdr desc)))
10539 (cdr desc)))
10540 "\\}[ \t]")))
10541 ((eq (car desc) :maxlevel)
10542 (setq fast-path-p t)
10543 (setq descre (concat "^\\*\\{1," (number-to-string
10544 (if org-odd-levels-only
10545 (1- (* 2 (cdr desc)))
10546 (cdr desc)))
10547 "\\}[ \t]")))
10548 (t (error "Bad refiling target description %s" desc)))
10549 (while (setq f (pop files))
10550 (with-current-buffer
10551 (if (bufferp f) f (org-get-agenda-file-buffer f))
10553 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10554 (progn
10555 (if (bufferp f) (setq f (buffer-file-name
10556 (buffer-base-buffer f))))
10557 (setq f (and f (expand-file-name f)))
10558 (if (eq org-refile-use-outline-path 'file)
10559 (push (list (file-name-nondirectory f) f nil nil) tgs))
10560 (save-excursion
10561 (save-restriction
10562 (widen)
10563 (goto-char (point-min))
10564 (while (re-search-forward descre nil t)
10565 (goto-char (setq pos0 (point-at-bol)))
10566 (catch 'next
10567 (when org-refile-target-verify-function
10568 (save-match-data
10569 (or (funcall org-refile-target-verify-function)
10570 (throw 'next t))))
10571 (when (and (looking-at org-complex-heading-regexp)
10572 (not (member (match-string 4) excluded-entries))
10573 (match-string 4))
10574 (setq level (org-reduced-level
10575 (- (match-end 1) (match-beginning 1)))
10576 txt (org-link-display-format (match-string 4))
10577 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10578 re (format org-complex-heading-regexp-format
10579 (regexp-quote (match-string 4))))
10580 (when org-refile-use-outline-path
10581 (setq txt (mapconcat
10582 'org-protect-slash
10583 (append
10584 (if (eq org-refile-use-outline-path
10585 'file)
10586 (list (file-name-nondirectory
10587 (buffer-file-name
10588 (buffer-base-buffer))))
10589 (if (eq org-refile-use-outline-path
10590 'full-file-path)
10591 (list (buffer-file-name
10592 (buffer-base-buffer)))))
10593 (org-get-outline-path fast-path-p
10594 level txt)
10595 (list txt))
10596 "/")))
10597 (push (list txt f re (org-refile-marker (point)))
10598 tgs)))
10599 (when (= (point) pos0)
10600 ;; verification function has not moved point
10601 (goto-char (point-at-eol))))))))
10602 (when org-refile-use-cache
10603 (org-refile-cache-put tgs (buffer-file-name) descre))
10604 (setq targets (append tgs targets))
10605 ))))
10606 (message "Getting targets...done")
10607 (nreverse targets)))
10609 (defun org-protect-slash (s)
10610 (while (string-match "/" s)
10611 (setq s (replace-match "\\" t t s)))
10614 (defvar org-olpa (make-vector 20 nil))
10616 (defun org-get-outline-path (&optional fastp level heading)
10617 "Return the outline path to the current entry, as a list.
10619 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10620 routine which makes outline path derivations for an entire file,
10621 avoiding backtracing. Refile target collection makes use of that."
10622 (if fastp
10623 (progn
10624 (if (> level 19)
10625 (error "Outline path failure, more than 19 levels"))
10626 (loop for i from level upto 19 do
10627 (aset org-olpa i nil))
10628 (prog1
10629 (delq nil (append org-olpa nil))
10630 (aset org-olpa level heading)))
10631 (let (rtn case-fold-search)
10632 (save-excursion
10633 (save-restriction
10634 (widen)
10635 (while (org-up-heading-safe)
10636 (when (looking-at org-complex-heading-regexp)
10637 (push (org-match-string-no-properties 4) rtn)))
10638 rtn)))))
10640 (defun org-format-outline-path (path &optional width prefix)
10641 "Format the outline path PATH for display.
10642 Width is the maximum number of characters that is available.
10643 Prefix is a prefix to be included in the returned string,
10644 such as the file name."
10645 (setq width (or width 79))
10646 (if prefix (setq width (- width (length prefix))))
10647 (if (not path)
10648 (or prefix "")
10649 (let* ((nsteps (length path))
10650 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10651 (maxwidth (if (<= total-width width)
10652 10000 ;; everything fits
10653 ;; we need to shorten the level headings
10654 (/ (- width nsteps) nsteps)))
10655 (org-odd-levels-only nil)
10656 (n 0)
10657 (total (1+ (length prefix))))
10658 (setq maxwidth (max maxwidth 10))
10659 (concat prefix
10660 (mapconcat
10661 (lambda (h)
10662 (setq n (1+ n))
10663 (if (and (= n nsteps) (< maxwidth 10000))
10664 (setq maxwidth (- total-width total)))
10665 (if (< (length h) maxwidth)
10666 (progn (setq total (+ total (length h) 1)) h)
10667 (setq h (substring h 0 (- maxwidth 2))
10668 total (+ total maxwidth 1))
10669 (if (string-match "[ \t]+\\'" h)
10670 (setq h (substring h 0 (match-beginning 0))))
10671 (setq h (concat h "..")))
10672 (org-add-props h nil 'face
10673 (nth (% (1- n) org-n-level-faces)
10674 org-level-faces))
10676 path "/")))))
10678 (defun org-display-outline-path (&optional file current)
10679 "Display the current outline path in the echo area."
10680 (interactive "P")
10681 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10682 (case-fold-search nil)
10683 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10684 (if current (setq path (append path
10685 (save-excursion
10686 (org-back-to-heading t)
10687 (if (looking-at org-complex-heading-regexp)
10688 (list (match-string 4)))))))
10689 (message "%s"
10690 (org-format-outline-path
10691 path
10692 (1- (frame-width))
10693 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10695 (defvar org-refile-history nil
10696 "History for refiling operations.")
10698 (defvar org-after-refile-insert-hook nil
10699 "Hook run after `org-refile' has inserted its stuff at the new location.
10700 Note that this is still *before* the stuff will be removed from
10701 the *old* location.")
10703 (defvar org-capture-last-stored-marker)
10704 (defun org-refile (&optional goto default-buffer rfloc)
10705 "Move the entry or entries at point to another heading.
10706 The list of target headings is compiled using the information in
10707 `org-refile-targets', which see.
10709 At the target location, the entry is filed as a subitem of the target
10710 heading. Depending on `org-reverse-note-order', the new subitem will
10711 either be the first or the last subitem.
10713 If there is an active region, all entries in that region will be moved.
10714 However, the region must fulfill the requirement that the first heading
10715 is the first one sets the top-level of the moved text - at most siblings
10716 below it are allowed.
10718 With prefix arg GOTO, the command will only visit the target location
10719 and not actually move anything.
10721 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10722 go to the location where the last refiling operation has put the subtree.
10723 With a prefix argument of `2', refile to the running clock.
10725 RFLOC can be a refile location obtained in a different way.
10727 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10729 If you are using target caching (see `org-refile-use-cache'),
10730 you have to clear the target cache in order to find new targets.
10731 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10732 prefix argument (`C-u C-u C-u C-c C-w')."
10734 (interactive "P")
10735 (if (member goto '(0 (64)))
10736 (org-refile-cache-clear)
10737 (let* ((cbuf (current-buffer))
10738 (regionp (org-region-active-p))
10739 (region-start (and regionp (region-beginning)))
10740 (region-end (and regionp (region-end)))
10741 (region-length (and regionp (- region-end region-start)))
10742 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10743 pos it nbuf file re level reversed)
10744 (setq last-command nil)
10745 (when regionp
10746 (goto-char region-start)
10747 (or (bolp) (goto-char (point-at-bol)))
10748 (setq region-start (point))
10749 (unless (or (org-kill-is-subtree-p
10750 (buffer-substring region-start region-end))
10751 (prog1 org-refile-active-region-within-subtree
10752 (org-toggle-heading)))
10753 (error "The region is not a (sequence of) subtree(s)")))
10754 (if (equal goto '(16))
10755 (org-refile-goto-last-stored)
10756 (when (or
10757 (and (equal goto 2)
10758 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10759 (prog1
10760 (setq it (list (or org-clock-heading "running clock")
10761 (buffer-file-name
10762 (marker-buffer org-clock-hd-marker))
10764 (marker-position org-clock-hd-marker)))
10765 (setq goto nil)))
10766 (setq it (or rfloc
10767 (let (heading-text)
10768 (save-excursion
10769 (unless goto
10770 (org-back-to-heading t)
10771 (setq heading-text
10772 (nth 4 (org-heading-components))))
10773 (org-refile-get-location
10774 (cond (goto "Goto")
10775 (regionp "Refile region to")
10776 (t (concat "Refile subtree \""
10777 heading-text "\" to")))
10778 default-buffer
10779 (and (not (equal '(4) goto))
10780 org-refile-allow-creating-parent-nodes)
10781 goto))))))
10782 (setq file (nth 1 it)
10783 re (nth 2 it)
10784 pos (nth 3 it))
10785 (if (and (not goto)
10787 (equal (buffer-file-name) file)
10788 (if regionp
10789 (and (>= pos region-start)
10790 (<= pos region-end))
10791 (and (>= pos (point))
10792 (< pos (save-excursion
10793 (org-end-of-subtree t t))))))
10794 (error "Cannot refile to position inside the tree or region"))
10796 (setq nbuf (or (find-buffer-visiting file)
10797 (find-file-noselect file)))
10798 (if goto
10799 (progn
10800 (org-pop-to-buffer-same-window nbuf)
10801 (goto-char pos)
10802 (org-show-context 'org-goto))
10803 (if regionp
10804 (progn
10805 (org-kill-new (buffer-substring region-start region-end))
10806 (org-save-markers-in-region region-start region-end))
10807 (org-copy-subtree 1 nil t))
10808 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10809 (find-file-noselect file)))
10810 (setq reversed (org-notes-order-reversed-p))
10811 (save-excursion
10812 (save-restriction
10813 (widen)
10814 (if pos
10815 (progn
10816 (goto-char pos)
10817 (looking-at org-outline-regexp)
10818 (setq level (org-get-valid-level (funcall outline-level) 1))
10819 (goto-char
10820 (if reversed
10821 (or (outline-next-heading) (point-max))
10822 (or (save-excursion (org-get-next-sibling))
10823 (org-end-of-subtree t t)
10824 (point-max)))))
10825 (setq level 1)
10826 (if (not reversed)
10827 (goto-char (point-max))
10828 (goto-char (point-min))
10829 (or (outline-next-heading) (goto-char (point-max)))))
10830 (if (not (bolp)) (newline))
10831 (org-paste-subtree level)
10832 (when org-log-refile
10833 (org-add-log-setup 'refile nil nil 'findpos
10834 org-log-refile)
10835 (unless (eq org-log-refile 'note)
10836 (save-excursion (org-add-log-note))))
10837 (and org-auto-align-tags (org-set-tags nil t))
10838 (bookmark-set "org-refile-last-stored")
10839 ;; If we are refiling for capture, make sure that the
10840 ;; last-capture pointers point here
10841 (when (org-bound-and-true-p org-refile-for-capture)
10842 (bookmark-set "org-capture-last-stored-marker")
10843 (move-marker org-capture-last-stored-marker (point)))
10844 (if (fboundp 'deactivate-mark) (deactivate-mark))
10845 (run-hooks 'org-after-refile-insert-hook))))
10846 (if regionp
10847 (delete-region (point) (+ (point) region-length))
10848 (org-cut-subtree))
10849 (when (featurep 'org-inlinetask)
10850 (org-inlinetask-remove-END-maybe))
10851 (setq org-markers-to-move nil)
10852 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10854 (defun org-refile-goto-last-stored ()
10855 "Go to the location where the last refile was stored."
10856 (interactive)
10857 (bookmark-jump "org-refile-last-stored")
10858 (message "This is the location of the last refile"))
10860 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10861 no-exclude)
10862 "Prompt the user for a refile location, using PROMPT.
10863 PROMPT should not be suffixed with a colon and a space, because
10864 this function appends the default value from
10865 `org-refile-history' automatically, if that is not empty.
10866 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10867 this is used for the GOTO interface."
10868 (let ((org-refile-targets org-refile-targets)
10869 (org-refile-use-outline-path org-refile-use-outline-path)
10870 excluded-entries)
10871 (when (and (derived-mode-p 'org-mode)
10872 (not org-refile-use-cache)
10873 (not no-exclude))
10874 (org-map-tree
10875 (lambda()
10876 (setq excluded-entries
10877 (append excluded-entries (list (org-get-heading t t)))))))
10878 (setq org-refile-target-table
10879 (org-refile-get-targets default-buffer excluded-entries)))
10880 (unless org-refile-target-table
10881 (error "No refile targets"))
10882 (let* ((prompt (concat prompt
10883 (and (car org-refile-history)
10884 (concat " (default " (car org-refile-history) ")"))
10885 ": "))
10886 (cbuf (current-buffer))
10887 (partial-completion-mode nil)
10888 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10889 (cfunc (if (and org-refile-use-outline-path
10890 org-outline-path-complete-in-steps)
10891 'org-olpath-completing-read
10892 'org-icompleting-read))
10893 (extra (if org-refile-use-outline-path "/" ""))
10894 (filename (and cfn (expand-file-name cfn)))
10895 (tbl (mapcar
10896 (lambda (x)
10897 (if (and (not (member org-refile-use-outline-path
10898 '(file full-file-path)))
10899 (not (equal filename (nth 1 x))))
10900 (cons (concat (car x) extra " ("
10901 (file-name-nondirectory (nth 1 x)) ")")
10902 (cdr x))
10903 (cons (concat (car x) extra) (cdr x))))
10904 org-refile-target-table))
10905 (completion-ignore-case t)
10906 pa answ parent-target child parent old-hist)
10907 (setq old-hist org-refile-history)
10908 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10909 nil 'org-refile-history (car org-refile-history)))
10910 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10911 (org-refile-check-position pa)
10912 (if pa
10913 (progn
10914 (when (or (not org-refile-history)
10915 (not (eq old-hist org-refile-history))
10916 (not (equal (car pa) (car org-refile-history))))
10917 (setq org-refile-history
10918 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10919 org-refile-history
10920 (cdr org-refile-history))))
10921 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10922 (pop org-refile-history)))
10924 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10925 (progn
10926 (setq parent (match-string 1 answ)
10927 child (match-string 2 answ))
10928 (setq parent-target (or (assoc parent tbl)
10929 (assoc (concat parent "/") tbl)))
10930 (when (and parent-target
10931 (or (eq new-nodes t)
10932 (and (eq new-nodes 'confirm)
10933 (y-or-n-p (format "Create new node \"%s\"? "
10934 child)))))
10935 (org-refile-new-child parent-target child)))
10936 (error "Invalid target location")))))
10938 (declare-function org-string-nw-p "org-macs.el" (s))
10939 (defun org-refile-check-position (refile-pointer)
10940 "Check if the refile pointer matches the readline to which it points."
10941 (let* ((file (nth 1 refile-pointer))
10942 (re (nth 2 refile-pointer))
10943 (pos (nth 3 refile-pointer))
10944 buffer)
10945 (when (org-string-nw-p re)
10946 (setq buffer (if (markerp pos)
10947 (marker-buffer pos)
10948 (or (find-buffer-visiting file)
10949 (find-file-noselect file))))
10950 (with-current-buffer buffer
10951 (save-excursion
10952 (save-restriction
10953 (widen)
10954 (goto-char pos)
10955 (beginning-of-line 1)
10956 (unless (org-looking-at-p re)
10957 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10959 (defun org-refile-new-child (parent-target child)
10960 "Use refile target PARENT-TARGET to add new CHILD below it."
10961 (unless parent-target
10962 (error "Cannot find parent for new node"))
10963 (let ((file (nth 1 parent-target))
10964 (pos (nth 3 parent-target))
10965 level)
10966 (with-current-buffer (or (find-buffer-visiting file)
10967 (find-file-noselect file))
10968 (save-excursion
10969 (save-restriction
10970 (widen)
10971 (if pos
10972 (goto-char pos)
10973 (goto-char (point-max))
10974 (if (not (bolp)) (newline)))
10975 (when (looking-at org-outline-regexp)
10976 (setq level (funcall outline-level))
10977 (org-end-of-subtree t t))
10978 (org-back-over-empty-lines)
10979 (insert "\n" (make-string
10980 (if pos (org-get-valid-level level 1) 1) ?*)
10981 " " child "\n")
10982 (beginning-of-line 0)
10983 (list (concat (car parent-target) "/" child) file "" (point)))))))
10985 (defun org-olpath-completing-read (prompt collection &rest args)
10986 "Read an outline path like a file name."
10987 (let ((thetable collection)
10988 (org-completion-use-ido nil) ; does not work with ido.
10989 (org-completion-use-iswitchb nil)) ; or iswitchb
10990 (apply
10991 'org-icompleting-read prompt
10992 (lambda (string predicate &optional flag)
10993 (let (rtn r f (l (length string)))
10994 (cond
10995 ((eq flag nil)
10996 ;; try completion
10997 (try-completion string thetable))
10998 ((eq flag t)
10999 ;; all-completions
11000 (setq rtn (all-completions string thetable predicate))
11001 (mapcar
11002 (lambda (x)
11003 (setq r (substring x l))
11004 (if (string-match " ([^)]*)$" x)
11005 (setq f (match-string 0 x))
11006 (setq f ""))
11007 (if (string-match "/" r)
11008 (concat string (substring r 0 (match-end 0)) f)
11010 rtn))
11011 ((eq flag 'lambda)
11012 ;; exact match?
11013 (assoc string thetable)))))
11014 args)))
11016 ;;;; Dynamic blocks
11018 (defun org-find-dblock (name)
11019 "Find the first dynamic block with name NAME in the buffer.
11020 If not found, stay at current position and return nil."
11021 (let (pos)
11022 (save-excursion
11023 (goto-char (point-min))
11024 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
11025 nil t)
11026 (match-beginning 0))))
11027 (if pos (goto-char pos))
11028 pos))
11030 (defconst org-dblock-start-re
11031 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11032 "Matches the start line of a dynamic block, with parameters.")
11034 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
11035 "Matches the end of a dynamic block.")
11037 (defun org-create-dblock (plist)
11038 "Create a dynamic block section, with parameters taken from PLIST.
11039 PLIST must contain a :name entry which is used as name of the block."
11040 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11041 (end-of-line 1)
11042 (newline))
11043 (let ((col (current-column))
11044 (name (plist-get plist :name)))
11045 (insert "#+BEGIN: " name)
11046 (while plist
11047 (if (eq (car plist) :name)
11048 (setq plist (cddr plist))
11049 (insert " " (prin1-to-string (pop plist)))))
11050 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11051 (beginning-of-line -2)))
11053 (defun org-prepare-dblock ()
11054 "Prepare dynamic block for refresh.
11055 This empties the block, puts the cursor at the insert position and returns
11056 the property list including an extra property :name with the block name."
11057 (unless (looking-at org-dblock-start-re)
11058 (error "Not at a dynamic block"))
11059 (let* ((begdel (1+ (match-end 0)))
11060 (name (org-no-properties (match-string 1)))
11061 (params (append (list :name name)
11062 (read (concat "(" (match-string 3) ")")))))
11063 (save-excursion
11064 (beginning-of-line 1)
11065 (skip-chars-forward " \t")
11066 (setq params (plist-put params :indentation-column (current-column))))
11067 (unless (re-search-forward org-dblock-end-re nil t)
11068 (error "Dynamic block not terminated"))
11069 (setq params
11070 (append params
11071 (list :content (buffer-substring
11072 begdel (match-beginning 0)))))
11073 (delete-region begdel (match-beginning 0))
11074 (goto-char begdel)
11075 (open-line 1)
11076 params))
11078 (defun org-map-dblocks (&optional command)
11079 "Apply COMMAND to all dynamic blocks in the current buffer.
11080 If COMMAND is not given, use `org-update-dblock'."
11081 (let ((cmd (or command 'org-update-dblock)))
11082 (save-excursion
11083 (goto-char (point-min))
11084 (while (re-search-forward org-dblock-start-re nil t)
11085 (goto-char (match-beginning 0))
11086 (save-excursion
11087 (condition-case nil
11088 (funcall cmd)
11089 (error (message "Error during update of dynamic block"))))
11090 (unless (re-search-forward org-dblock-end-re nil t)
11091 (error "Dynamic block not terminated"))))))
11093 (defun org-dblock-update (&optional arg)
11094 "User command for updating dynamic blocks.
11095 Update the dynamic block at point. With prefix ARG, update all dynamic
11096 blocks in the buffer."
11097 (interactive "P")
11098 (if arg
11099 (org-update-all-dblocks)
11100 (or (looking-at org-dblock-start-re)
11101 (org-beginning-of-dblock))
11102 (org-update-dblock)))
11104 (defun org-update-dblock ()
11105 "Update the dynamic block at point.
11106 This means to empty the block, parse for parameters and then call
11107 the correct writing function."
11108 (interactive)
11109 (save-window-excursion
11110 (let* ((pos (point))
11111 (line (org-current-line))
11112 (params (org-prepare-dblock))
11113 (name (plist-get params :name))
11114 (indent (plist-get params :indentation-column))
11115 (cmd (intern (concat "org-dblock-write:" name))))
11116 (message "Updating dynamic block `%s' at line %d..." name line)
11117 (funcall cmd params)
11118 (message "Updating dynamic block `%s' at line %d...done" name line)
11119 (goto-char pos)
11120 (when (and indent (> indent 0))
11121 (setq indent (make-string indent ?\ ))
11122 (save-excursion
11123 (org-beginning-of-dblock)
11124 (forward-line 1)
11125 (while (not (looking-at org-dblock-end-re))
11126 (insert indent)
11127 (beginning-of-line 2))
11128 (when (looking-at org-dblock-end-re)
11129 (and (looking-at "[ \t]+")
11130 (replace-match ""))
11131 (insert indent)))))))
11133 (defun org-beginning-of-dblock ()
11134 "Find the beginning of the dynamic block at point.
11135 Error if there is no such block at point."
11136 (let ((pos (point))
11137 beg)
11138 (end-of-line 1)
11139 (if (and (re-search-backward org-dblock-start-re nil t)
11140 (setq beg (match-beginning 0))
11141 (re-search-forward org-dblock-end-re nil t)
11142 (> (match-end 0) pos))
11143 (goto-char beg)
11144 (goto-char pos)
11145 (error "Not in a dynamic block"))))
11147 ;;;###autoload
11148 (defun org-update-all-dblocks ()
11149 "Update all dynamic blocks in the buffer.
11150 This function can be used in a hook."
11151 (interactive)
11152 (when (derived-mode-p 'org-mode)
11153 (org-map-dblocks 'org-update-dblock)))
11156 ;;;; Completion
11158 (defconst org-additional-option-like-keywords
11159 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11160 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11161 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11162 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11163 "BEGIN:" "END:"
11164 "ORGTBL" "TBLFM:" "TBLNAME:"
11165 "BEGIN_EXAMPLE" "END_EXAMPLE"
11166 "BEGIN_QUOTE" "END_QUOTE"
11167 "BEGIN_VERSE" "END_VERSE"
11168 "BEGIN_CENTER" "END_CENTER"
11169 "BEGIN_SRC" "END_SRC"
11170 "BEGIN_RESULT" "END_RESULT"
11171 "NAME:" "RESULTS:"
11172 "HEADER:" "HEADERS:"
11173 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11174 "CAPTION:" "LABEL:"
11175 "SETUPFILE:"
11176 "INCLUDE:"
11177 "BIND:"
11178 "MACRO:"))
11180 (defcustom org-structure-template-alist
11182 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11183 "<src lang=\"?\">\n\n</src>")
11184 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11185 "<example>\n?\n</example>")
11186 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11187 "<quote>\n?\n</quote>")
11188 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11189 "<verse>\n?\n</verse>")
11190 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11191 "<center>\n?\n</center>")
11192 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11193 "<literal style=\"latex\">\n?\n</literal>")
11194 ("L" "#+LaTeX: "
11195 "<literal style=\"latex\">?</literal>")
11196 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11197 "<literal style=\"html\">\n?\n</literal>")
11198 ("H" "#+HTML: "
11199 "<literal style=\"html\">?</literal>")
11200 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11201 ("A" "#+ASCII: ")
11202 ("i" "#+INDEX: ?"
11203 "#+INDEX: ?")
11204 ("I" "#+INCLUDE %file ?"
11205 "<include file=%file markup=\"?\">")
11207 "Structure completion elements.
11208 This is a list of abbreviation keys and values. The value gets inserted
11209 if you type `<' followed by the key and then press the completion key,
11210 usually `M-TAB'. %file will be replaced by a file name after prompting
11211 for the file using completion. The cursor will be placed at the position
11212 of the `?` in the template.
11213 There are two templates for each key, the first uses the original Org syntax,
11214 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11215 the default when the /org-mtags.el/ module has been loaded. See also the
11216 variable `org-mtags-prefer-muse-templates'."
11217 :group 'org-completion
11218 :type '(repeat
11219 (string :tag "Key")
11220 (string :tag "Template")
11221 (string :tag "Muse Template")))
11223 (defun org-try-structure-completion ()
11224 "Try to complete a structure template before point.
11225 This looks for strings like \"<e\" on an otherwise empty line and
11226 expands them."
11227 (let ((l (buffer-substring (point-at-bol) (point)))
11229 (when (and (looking-at "[ \t]*$")
11230 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11231 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11232 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11233 (match-beginning 1)) a)
11234 t)))
11236 (defun org-complete-expand-structure-template (start cell)
11237 "Expand a structure template."
11238 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11239 (rpl (nth (if musep 2 1) cell))
11240 (ind ""))
11241 (delete-region start (point))
11242 (when (string-match "\\`#\\+" rpl)
11243 (cond
11244 ((bolp))
11245 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11246 (setq ind (buffer-substring (point-at-bol) (point))))
11247 (t (newline))))
11248 (setq start (point))
11249 (if (string-match "%file" rpl)
11250 (setq rpl (replace-match
11251 (concat
11252 "\""
11253 (save-match-data
11254 (abbreviate-file-name (read-file-name "Include file: ")))
11255 "\"")
11256 t t rpl)))
11257 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11258 (concat "\n" ind)))
11259 (insert rpl)
11260 (if (re-search-backward "\\?" start t) (delete-char 1))))
11262 ;;;; TODO, DEADLINE, Comments
11264 (defun org-toggle-comment ()
11265 "Change the COMMENT state of an entry."
11266 (interactive)
11267 (save-excursion
11268 (org-back-to-heading)
11269 (let (case-fold-search)
11270 (cond
11271 ((looking-at (format org-heading-keyword-regexp-format
11272 org-comment-string))
11273 (goto-char (match-end 1))
11274 (looking-at (concat " +" org-comment-string))
11275 (replace-match "" t t)
11276 (when (eolp) (insert " ")))
11277 ((looking-at org-outline-regexp)
11278 (goto-char (match-end 0))
11279 (insert org-comment-string " "))))))
11281 (defvar org-last-todo-state-is-todo nil
11282 "This is non-nil when the last TODO state change led to a TODO state.
11283 If the last change removed the TODO tag or switched to DONE, then
11284 this is nil.")
11286 (defvar org-setting-tags nil) ; dynamically skipped
11288 (defvar org-todo-setup-filter-hook nil
11289 "Hook for functions that pre-filter todo specs.
11290 Each function takes a todo spec and returns either nil or the spec
11291 transformed into canonical form." )
11293 (defvar org-todo-get-default-hook nil
11294 "Hook for functions that get a default item for todo.
11295 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11296 nil or a string to be used for the todo mark." )
11298 (defvar org-agenda-headline-snapshot-before-repeat)
11300 (defun org-current-effective-time ()
11301 "Return current time adjusted for `org-extend-today-until' variable"
11302 (let* ((ct (org-current-time))
11303 (dct (decode-time ct))
11304 (ct1
11305 (if (and org-use-effective-time
11306 (< (nth 2 dct) org-extend-today-until))
11307 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11308 ct)))
11309 ct1))
11311 (defun org-todo-yesterday (&optional arg)
11312 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11313 (interactive "P")
11314 (if (eq major-mode 'org-agenda-mode)
11315 (apply 'org-agenda-todo-yesterday arg)
11316 (let* ((hour (third (decode-time
11317 (org-current-time))))
11318 (org-extend-today-until (1+ hour)))
11319 (org-todo arg))))
11321 (defun org-todo (&optional arg)
11322 "Change the TODO state of an item.
11323 The state of an item is given by a keyword at the start of the heading,
11324 like
11325 *** TODO Write paper
11326 *** DONE Call mom
11328 The different keywords are specified in the variable `org-todo-keywords'.
11329 By default the available states are \"TODO\" and \"DONE\".
11330 So for this example: when the item starts with TODO, it is changed to DONE.
11331 When it starts with DONE, the DONE is removed. And when neither TODO nor
11332 DONE are present, add TODO at the beginning of the heading.
11334 With \\[universal-argument] prefix arg, use completion to determine the new \
11335 state.
11336 With numeric prefix arg, switch to that state.
11337 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11338 keywords (nextset).
11339 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11340 With a numeric prefix arg of 0, inhibit note taking for the change.
11342 For calling through lisp, arg is also interpreted in the following way:
11343 'none -> empty state
11344 \"\"(empty string) -> switch to empty state
11345 'done -> switch to DONE
11346 'nextset -> switch to the next set of keywords
11347 'previousset -> switch to the previous set of keywords
11348 \"WAITING\" -> switch to the specified keyword, but only if it
11349 really is a member of `org-todo-keywords'."
11350 (interactive "P")
11351 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11352 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11353 'region-start-level 'region))
11354 org-loop-over-headlines-in-active-region)
11355 (org-map-entries
11356 `(org-todo ,arg)
11357 org-loop-over-headlines-in-active-region
11358 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11359 (if (equal arg '(16)) (setq arg 'nextset))
11360 (let ((org-blocker-hook org-blocker-hook)
11361 (case-fold-search nil))
11362 (when (equal arg '(64))
11363 (setq arg nil org-blocker-hook nil))
11364 (when (and org-blocker-hook
11365 (or org-inhibit-blocking
11366 (org-entry-get nil "NOBLOCKING")))
11367 (setq org-blocker-hook nil))
11368 (save-excursion
11369 (catch 'exit
11370 (org-back-to-heading t)
11371 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11372 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11373 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11374 (let* ((match-data (match-data))
11375 (startpos (point-at-bol))
11376 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11377 (org-log-done org-log-done)
11378 (org-log-repeat org-log-repeat)
11379 (org-todo-log-states org-todo-log-states)
11380 (org-inhibit-logging
11381 (if (equal arg 0)
11382 (progn (setq arg nil) 'note) org-inhibit-logging))
11383 (this (match-string 1))
11384 (hl-pos (match-beginning 0))
11385 (head (org-get-todo-sequence-head this))
11386 (ass (assoc head org-todo-kwd-alist))
11387 (interpret (nth 1 ass))
11388 (done-word (nth 3 ass))
11389 (final-done-word (nth 4 ass))
11390 (org-last-state (or this ""))
11391 (completion-ignore-case t)
11392 (member (member this org-todo-keywords-1))
11393 (tail (cdr member))
11394 (org-state (cond
11395 ((and org-todo-key-trigger
11396 (or (and (equal arg '(4))
11397 (eq org-use-fast-todo-selection 'prefix))
11398 (and (not arg) org-use-fast-todo-selection
11399 (not (eq org-use-fast-todo-selection
11400 'prefix)))))
11401 ;; Use fast selection
11402 (org-fast-todo-selection))
11403 ((and (equal arg '(4))
11404 (or (not org-use-fast-todo-selection)
11405 (not org-todo-key-trigger)))
11406 ;; Read a state with completion
11407 (org-icompleting-read
11408 "State: " (mapcar (lambda(x) (list x))
11409 org-todo-keywords-1)
11410 nil t))
11411 ((eq arg 'right)
11412 (if this
11413 (if tail (car tail) nil)
11414 (car org-todo-keywords-1)))
11415 ((eq arg 'left)
11416 (if (equal member org-todo-keywords-1)
11418 (if this
11419 (nth (- (length org-todo-keywords-1)
11420 (length tail) 2)
11421 org-todo-keywords-1)
11422 (org-last org-todo-keywords-1))))
11423 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11424 (setq arg nil))) ; hack to fall back to cycling
11425 (arg
11426 ;; user or caller requests a specific state
11427 (cond
11428 ((equal arg "") nil)
11429 ((eq arg 'none) nil)
11430 ((eq arg 'done) (or done-word (car org-done-keywords)))
11431 ((eq arg 'nextset)
11432 (or (car (cdr (member head org-todo-heads)))
11433 (car org-todo-heads)))
11434 ((eq arg 'previousset)
11435 (let ((org-todo-heads (reverse org-todo-heads)))
11436 (or (car (cdr (member head org-todo-heads)))
11437 (car org-todo-heads))))
11438 ((car (member arg org-todo-keywords-1)))
11439 ((stringp arg)
11440 (error "State `%s' not valid in this file" arg))
11441 ((nth (1- (prefix-numeric-value arg))
11442 org-todo-keywords-1))))
11443 ((null member) (or head (car org-todo-keywords-1)))
11444 ((equal this final-done-word) nil) ;; -> make empty
11445 ((null tail) nil) ;; -> first entry
11446 ((memq interpret '(type priority))
11447 (if (eq this-command last-command)
11448 (car tail)
11449 (if (> (length tail) 0)
11450 (or done-word (car org-done-keywords))
11451 nil)))
11453 (car tail))))
11454 (org-state (or
11455 (run-hook-with-args-until-success
11456 'org-todo-get-default-hook org-state org-last-state)
11457 org-state))
11458 (next (if org-state (concat " " org-state " ") " "))
11459 (change-plist (list :type 'todo-state-change :from this :to org-state
11460 :position startpos))
11461 dolog now-done-p)
11462 (when org-blocker-hook
11463 (setq org-last-todo-state-is-todo
11464 (not (member this org-done-keywords)))
11465 (unless (save-excursion
11466 (save-match-data
11467 (org-with-wide-buffer
11468 (run-hook-with-args-until-failure
11469 'org-blocker-hook change-plist))))
11470 (if (org-called-interactively-p 'interactive)
11471 (error "TODO state change from %s to %s blocked" this org-state)
11472 ;; fail silently
11473 (message "TODO state change from %s to %s blocked" this org-state)
11474 (throw 'exit nil))))
11475 (store-match-data match-data)
11476 (replace-match next t t)
11477 (unless (pos-visible-in-window-p hl-pos)
11478 (message "TODO state changed to %s" (org-trim next)))
11479 (unless head
11480 (setq head (org-get-todo-sequence-head org-state)
11481 ass (assoc head org-todo-kwd-alist)
11482 interpret (nth 1 ass)
11483 done-word (nth 3 ass)
11484 final-done-word (nth 4 ass)))
11485 (when (memq arg '(nextset previousset))
11486 (message "Keyword-Set %d/%d: %s"
11487 (- (length org-todo-sets) -1
11488 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11489 (length org-todo-sets)
11490 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11491 (setq org-last-todo-state-is-todo
11492 (not (member org-state org-done-keywords)))
11493 (setq now-done-p (and (member org-state org-done-keywords)
11494 (not (member this org-done-keywords))))
11495 (and logging (org-local-logging logging))
11496 (when (and (or org-todo-log-states org-log-done)
11497 (not (eq org-inhibit-logging t))
11498 (not (memq arg '(nextset previousset))))
11499 ;; we need to look at recording a time and note
11500 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11501 (nth 2 (assoc this org-todo-log-states))))
11502 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11503 (setq dolog 'time))
11504 (when (and org-state
11505 (member org-state org-not-done-keywords)
11506 (not (member this org-not-done-keywords)))
11507 ;; This is now a todo state and was not one before
11508 ;; If there was a CLOSED time stamp, get rid of it.
11509 (org-add-planning-info nil nil 'closed))
11510 (when (and now-done-p org-log-done)
11511 ;; It is now done, and it was not done before
11512 (org-add-planning-info 'closed (org-current-effective-time))
11513 (if (and (not dolog) (eq 'note org-log-done))
11514 (org-add-log-setup 'done org-state this 'findpos 'note)))
11515 (when (and org-state dolog)
11516 ;; This is a non-nil state, and we need to log it
11517 (org-add-log-setup 'state org-state this 'findpos dolog)))
11518 ;; Fixup tag positioning
11519 (org-todo-trigger-tag-changes org-state)
11520 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11521 (when org-provide-todo-statistics
11522 (org-update-parent-todo-statistics))
11523 (run-hooks 'org-after-todo-state-change-hook)
11524 (if (and arg (not (member org-state org-done-keywords)))
11525 (setq head (org-get-todo-sequence-head org-state)))
11526 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11527 ;; Do we need to trigger a repeat?
11528 (when now-done-p
11529 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11530 ;; This is for the agenda, take a snapshot of the headline.
11531 (save-match-data
11532 (setq org-agenda-headline-snapshot-before-repeat
11533 (org-get-heading))))
11534 (org-auto-repeat-maybe org-state))
11535 ;; Fixup cursor location if close to the keyword
11536 (if (and (outline-on-heading-p)
11537 (not (bolp))
11538 (save-excursion (beginning-of-line 1)
11539 (looking-at org-todo-line-regexp))
11540 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11541 (progn
11542 (goto-char (or (match-end 2) (match-end 1)))
11543 (and (looking-at " ") (just-one-space))))
11544 (when org-trigger-hook
11545 (save-excursion
11546 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11548 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11549 "Block turning an entry into a TODO, using the hierarchy.
11550 This checks whether the current task should be blocked from state
11551 changes. Such blocking occurs when:
11553 1. The task has children which are not all in a completed state.
11555 2. A task has a parent with the property :ORDERED:, and there
11556 are siblings prior to the current task with incomplete
11557 status.
11559 3. The parent of the task is blocked because it has siblings that should
11560 be done first, or is child of a block grandparent TODO entry."
11562 (if (not org-enforce-todo-dependencies)
11563 t ; if locally turned off don't block
11564 (catch 'dont-block
11565 ;; If this is not a todo state change, or if this entry is already DONE,
11566 ;; do not block
11567 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11568 (member (plist-get change-plist :from)
11569 (cons 'done org-done-keywords))
11570 (member (plist-get change-plist :to)
11571 (cons 'todo org-not-done-keywords))
11572 (not (plist-get change-plist :to)))
11573 (throw 'dont-block t))
11574 ;; If this task has children, and any are undone, it's blocked
11575 (save-excursion
11576 (org-back-to-heading t)
11577 (let ((this-level (funcall outline-level)))
11578 (outline-next-heading)
11579 (let ((child-level (funcall outline-level)))
11580 (while (and (not (eobp))
11581 (> child-level this-level))
11582 ;; this todo has children, check whether they are all
11583 ;; completed
11584 (if (and (not (org-entry-is-done-p))
11585 (org-entry-is-todo-p))
11586 (throw 'dont-block nil))
11587 (outline-next-heading)
11588 (setq child-level (funcall outline-level))))))
11589 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11590 ;; any previous siblings are undone, it's blocked
11591 (save-excursion
11592 (org-back-to-heading t)
11593 (let* ((pos (point))
11594 (parent-pos (and (org-up-heading-safe) (point))))
11595 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11596 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11597 (forward-line 1)
11598 (re-search-forward org-not-done-heading-regexp pos t))
11599 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11600 ;; Search further up the hierarchy, to see if an ancestor is blocked
11601 (while t
11602 (goto-char parent-pos)
11603 (if (not (looking-at org-not-done-heading-regexp))
11604 (throw 'dont-block t)) ; do not block, parent is not a TODO
11605 (setq pos (point))
11606 (setq parent-pos (and (org-up-heading-safe) (point)))
11607 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11608 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11609 (forward-line 1)
11610 (re-search-forward org-not-done-heading-regexp pos t))
11611 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11613 (defcustom org-track-ordered-property-with-tag nil
11614 "Should the ORDERED property also be shown as a tag?
11615 The ORDERED property decides if an entry should require subtasks to be
11616 completed in sequence. Since a property is not very visible, setting
11617 this option means that toggling the ORDERED property with the command
11618 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11619 not relevant for the behavior, but it makes things more visible.
11621 Note that toggling the tag with tags commands will not change the property
11622 and therefore not influence behavior!
11624 This can be t, meaning the tag ORDERED should be used, It can also be a
11625 string to select a different tag for this task."
11626 :group 'org-todo
11627 :type '(choice
11628 (const :tag "No tracking" nil)
11629 (const :tag "Track with ORDERED tag" t)
11630 (string :tag "Use other tag")))
11632 (defun org-toggle-ordered-property ()
11633 "Toggle the ORDERED property of the current entry.
11634 For better visibility, you can track the value of this property with a tag.
11635 See variable `org-track-ordered-property-with-tag'."
11636 (interactive)
11637 (let* ((t1 org-track-ordered-property-with-tag)
11638 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11639 (save-excursion
11640 (org-back-to-heading)
11641 (if (org-entry-get nil "ORDERED")
11642 (progn
11643 (org-delete-property "ORDERED")
11644 (and tag (org-toggle-tag tag 'off))
11645 (message "Subtasks can be completed in arbitrary order"))
11646 (org-entry-put nil "ORDERED" "t")
11647 (and tag (org-toggle-tag tag 'on))
11648 (message "Subtasks must be completed in sequence")))))
11650 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11651 (defun org-block-todo-from-checkboxes (change-plist)
11652 "Block turning an entry into a TODO, using checkboxes.
11653 This checks whether the current task should be blocked from state
11654 changes because there are unchecked boxes in this entry."
11655 (if (not org-enforce-todo-checkbox-dependencies)
11656 t ; if locally turned off don't block
11657 (catch 'dont-block
11658 ;; If this is not a todo state change, or if this entry is already DONE,
11659 ;; do not block
11660 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11661 (member (plist-get change-plist :from)
11662 (cons 'done org-done-keywords))
11663 (member (plist-get change-plist :to)
11664 (cons 'todo org-not-done-keywords))
11665 (not (plist-get change-plist :to)))
11666 (throw 'dont-block t))
11667 ;; If this task has checkboxes that are not checked, it's blocked
11668 (save-excursion
11669 (org-back-to-heading t)
11670 (let ((beg (point)) end)
11671 (outline-next-heading)
11672 (setq end (point))
11673 (goto-char beg)
11674 (if (org-list-search-forward
11675 (concat (org-item-beginning-re)
11676 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11677 "\\[[- ]\\]")
11678 end t)
11679 (progn
11680 (if (boundp 'org-blocked-by-checkboxes)
11681 (setq org-blocked-by-checkboxes t))
11682 (throw 'dont-block nil)))))
11683 t))) ; do not block
11685 (defun org-entry-blocked-p ()
11686 "Is the current entry blocked?"
11687 (if (org-entry-get nil "NOBLOCKING")
11688 nil ;; Never block this entry
11689 (not
11690 (run-hook-with-args-until-failure
11691 'org-blocker-hook
11692 (list :type 'todo-state-change
11693 :position (point)
11694 :from 'todo
11695 :to 'done)))))
11697 (defun org-update-statistics-cookies (all)
11698 "Update the statistics cookie, either from TODO or from checkboxes.
11699 This should be called with the cursor in a line with a statistics cookie."
11700 (interactive "P")
11701 (if all
11702 (progn
11703 (org-update-checkbox-count 'all)
11704 (org-map-entries 'org-update-parent-todo-statistics))
11705 (if (not (org-at-heading-p))
11706 (org-update-checkbox-count)
11707 (let ((pos (move-marker (make-marker) (point)))
11708 end l1 l2)
11709 (ignore-errors (org-back-to-heading t))
11710 (if (not (org-at-heading-p))
11711 (org-update-checkbox-count)
11712 (setq l1 (org-outline-level))
11713 (setq end (save-excursion
11714 (outline-next-heading)
11715 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11716 (point)))
11717 (if (and (save-excursion
11718 (re-search-forward
11719 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11720 (not (save-excursion (re-search-forward
11721 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11722 (org-update-checkbox-count)
11723 (if (and l2 (> l2 l1))
11724 (progn
11725 (goto-char end)
11726 (org-update-parent-todo-statistics))
11727 (goto-char pos)
11728 (beginning-of-line 1)
11729 (while (re-search-forward
11730 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11731 (point-at-eol) t)
11732 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11733 (goto-char pos)
11734 (move-marker pos nil)))))
11736 (defvar org-entry-property-inherited-from) ;; defined below
11737 (defun org-update-parent-todo-statistics ()
11738 "Update any statistics cookie in the parent of the current headline.
11739 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11740 the entire subtree and this will travel up the hierarchy and update
11741 statistics everywhere."
11742 (let* ((prop (save-excursion (org-up-heading-safe)
11743 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11744 (recursive (or (not org-hierarchical-todo-statistics)
11745 (and prop (string-match "\\<recursive\\>" prop))))
11746 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11748 (first t)
11749 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11750 level ltoggle l1 new ndel
11751 (cnt-all 0) (cnt-done 0) is-percent kwd
11752 checkbox-beg ov ovs ove cookie-present)
11753 (catch 'exit
11754 (save-excursion
11755 (beginning-of-line 1)
11756 (setq ltoggle (funcall outline-level))
11757 ;; Three situations are to consider:
11759 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11760 ;; to the top-level ancestor on the headline;
11762 ;; 2. If parent has "recursive" property, repeat up to the
11763 ;; headline setting that property, taking inheritance into
11764 ;; account;
11766 ;; 3. Else, move up to direct parent and proceed only once.
11767 (while (and (setq level (org-up-heading-safe))
11768 (or recursive first)
11769 (>= (point) lim))
11770 (setq first nil cookie-present nil)
11771 (unless (and level
11772 (not (string-match
11773 "\\<checkbox\\>"
11774 (downcase (or (org-entry-get nil "COOKIE_DATA")
11775 "")))))
11776 (throw 'exit nil))
11777 (while (re-search-forward box-re (point-at-eol) t)
11778 (setq cnt-all 0 cnt-done 0 cookie-present t)
11779 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11780 (save-match-data
11781 (unless (outline-next-heading) (throw 'exit nil))
11782 (while (and (looking-at org-complex-heading-regexp)
11783 (> (setq l1 (length (match-string 1))) level))
11784 (setq kwd (and (or recursive (= l1 ltoggle))
11785 (match-string 2)))
11786 (if (or (eq org-provide-todo-statistics 'all-headlines)
11787 (and (listp org-provide-todo-statistics)
11788 (or (member kwd org-provide-todo-statistics)
11789 (member kwd org-done-keywords))))
11790 (setq cnt-all (1+ cnt-all))
11791 (if (eq org-provide-todo-statistics t)
11792 (and kwd (setq cnt-all (1+ cnt-all)))))
11793 (and (member kwd org-done-keywords)
11794 (setq cnt-done (1+ cnt-done)))
11795 (outline-next-heading)))
11796 (setq new
11797 (if is-percent
11798 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11799 (format "[%d/%d]" cnt-done cnt-all))
11800 ndel (- (match-end 0) checkbox-beg))
11801 ;; handle overlays when updating cookie from column view
11802 (when (setq ov (car (overlays-at checkbox-beg)))
11803 (setq ovs (overlay-start ov) ove (overlay-end ov))
11804 (delete-overlay ov))
11805 (goto-char checkbox-beg)
11806 (insert new)
11807 (delete-region (point) (+ (point) ndel))
11808 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11809 (when ov (move-overlay ov ovs ove)))
11810 (when cookie-present
11811 (run-hook-with-args 'org-after-todo-statistics-hook
11812 cnt-done (- cnt-all cnt-done))))))
11813 (run-hooks 'org-todo-statistics-hook)))
11815 (defvar org-after-todo-statistics-hook nil
11816 "Hook that is called after a TODO statistics cookie has been updated.
11817 Each function is called with two arguments: the number of not-done entries
11818 and the number of done entries.
11820 For example, the following function, when added to this hook, will switch
11821 an entry to DONE when all children are done, and back to TODO when new
11822 entries are set to a TODO status. Note that this hook is only called
11823 when there is a statistics cookie in the headline!
11825 (defun org-summary-todo (n-done n-not-done)
11826 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11827 (let (org-log-done org-log-states) ; turn off logging
11828 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11831 (defvar org-todo-statistics-hook nil
11832 "Hook that is run whenever Org thinks TODO statistics should be updated.
11833 This hook runs even if there is no statistics cookie present, in which case
11834 `org-after-todo-statistics-hook' would not run.")
11836 (defun org-todo-trigger-tag-changes (state)
11837 "Apply the changes defined in `org-todo-state-tags-triggers'."
11838 (let ((l org-todo-state-tags-triggers)
11839 changes)
11840 (when (or (not state) (equal state ""))
11841 (setq changes (append changes (cdr (assoc "" l)))))
11842 (when (and (stringp state) (> (length state) 0))
11843 (setq changes (append changes (cdr (assoc state l)))))
11844 (when (member state org-not-done-keywords)
11845 (setq changes (append changes (cdr (assoc 'todo l)))))
11846 (when (member state org-done-keywords)
11847 (setq changes (append changes (cdr (assoc 'done l)))))
11848 (dolist (c changes)
11849 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11851 (defun org-local-logging (value)
11852 "Get logging settings from a property VALUE."
11853 (let* (words w a)
11854 ;; directly set the variables, they are already local.
11855 (setq org-log-done nil
11856 org-log-repeat nil
11857 org-todo-log-states nil)
11858 (setq words (org-split-string value))
11859 (while (setq w (pop words))
11860 (cond
11861 ((setq a (assoc w org-startup-options))
11862 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11863 (set (nth 1 a) (nth 2 a))))
11864 ((setq a (org-extract-log-state-settings w))
11865 (and (member (car a) org-todo-keywords-1)
11866 (push a org-todo-log-states)))))))
11868 (defun org-get-todo-sequence-head (kwd)
11869 "Return the head of the TODO sequence to which KWD belongs.
11870 If KWD is not set, check if there is a text property remembering the
11871 right sequence."
11872 (let (p)
11873 (cond
11874 ((not kwd)
11875 (or (get-text-property (point-at-bol) 'org-todo-head)
11876 (progn
11877 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11878 nil (point-at-eol)))
11879 (get-text-property p 'org-todo-head))))
11880 ((not (member kwd org-todo-keywords-1))
11881 (car org-todo-keywords-1))
11882 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11884 (defun org-fast-todo-selection ()
11885 "Fast TODO keyword selection with single keys.
11886 Returns the new TODO keyword, or nil if no state change should occur."
11887 (let* ((fulltable org-todo-key-alist)
11888 (done-keywords org-done-keywords) ;; needed for the faces.
11889 (maxlen (apply 'max (mapcar
11890 (lambda (x)
11891 (if (stringp (car x)) (string-width (car x)) 0))
11892 fulltable)))
11893 (expert nil)
11894 (fwidth (+ maxlen 3 1 3))
11895 (ncol (/ (- (window-width) 4) fwidth))
11896 tg cnt e c tbl
11897 groups ingroup)
11898 (save-excursion
11899 (save-window-excursion
11900 (if expert
11901 (set-buffer (get-buffer-create " *Org todo*"))
11902 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11903 (erase-buffer)
11904 (org-set-local 'org-done-keywords done-keywords)
11905 (setq tbl fulltable cnt 0)
11906 (while (setq e (pop tbl))
11907 (cond
11908 ((equal e '(:startgroup))
11909 (push '() groups) (setq ingroup t)
11910 (when (not (= cnt 0))
11911 (setq cnt 0)
11912 (insert "\n"))
11913 (insert "{ "))
11914 ((equal e '(:endgroup))
11915 (setq ingroup nil cnt 0)
11916 (insert "}\n"))
11917 ((equal e '(:newline))
11918 (when (not (= cnt 0))
11919 (setq cnt 0)
11920 (insert "\n")
11921 (setq e (car tbl))
11922 (while (equal (car tbl) '(:newline))
11923 (insert "\n")
11924 (setq tbl (cdr tbl)))))
11926 (setq tg (car e) c (cdr e))
11927 (if ingroup (push tg (car groups)))
11928 (setq tg (org-add-props tg nil 'face
11929 (org-get-todo-face tg)))
11930 (if (and (= cnt 0) (not ingroup)) (insert " "))
11931 (insert "[" c "] " tg (make-string
11932 (- fwidth 4 (length tg)) ?\ ))
11933 (when (= (setq cnt (1+ cnt)) ncol)
11934 (insert "\n")
11935 (if ingroup (insert " "))
11936 (setq cnt 0)))))
11937 (insert "\n")
11938 (goto-char (point-min))
11939 (if (not expert) (org-fit-window-to-buffer))
11940 (message "[a-z..]:Set [SPC]:clear")
11941 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11942 (cond
11943 ((or (= c ?\C-g)
11944 (and (= c ?q) (not (rassoc c fulltable))))
11945 (setq quit-flag t))
11946 ((= c ?\ ) nil)
11947 ((setq e (rassoc c fulltable) tg (car e))
11949 (t (setq quit-flag t)))))))
11951 (defun org-entry-is-todo-p ()
11952 (member (org-get-todo-state) org-not-done-keywords))
11954 (defun org-entry-is-done-p ()
11955 (member (org-get-todo-state) org-done-keywords))
11957 (defun org-get-todo-state ()
11958 (save-excursion
11959 (org-back-to-heading t)
11960 (and (looking-at org-todo-line-regexp)
11961 (match-end 2)
11962 (match-string 2))))
11964 (defun org-at-date-range-p (&optional inactive-ok)
11965 "Is the cursor inside a date range?"
11966 (interactive)
11967 (save-excursion
11968 (catch 'exit
11969 (let ((pos (point)))
11970 (skip-chars-backward "^[<\r\n")
11971 (skip-chars-backward "<[")
11972 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11973 (>= (match-end 0) pos)
11974 (throw 'exit t))
11975 (skip-chars-backward "^<[\r\n")
11976 (skip-chars-backward "<[")
11977 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11978 (>= (match-end 0) pos)
11979 (throw 'exit t)))
11980 nil)))
11982 (defun org-get-repeat (&optional tagline)
11983 "Check if there is a deadline/schedule with repeater in this entry."
11984 (save-match-data
11985 (save-excursion
11986 (org-back-to-heading t)
11987 (and (re-search-forward (if tagline
11988 (concat tagline "\\s-*" org-repeat-re)
11989 org-repeat-re)
11990 (org-entry-end-position) t)
11991 (match-string-no-properties 1)))))
11993 (defvar org-last-changed-timestamp)
11994 (defvar org-last-inserted-timestamp)
11995 (defvar org-log-post-message)
11996 (defvar org-log-note-purpose)
11997 (defvar org-log-note-how)
11998 (defvar org-log-note-extra)
11999 (defun org-auto-repeat-maybe (done-word)
12000 "Check if the current headline contains a repeated deadline/schedule.
12001 If yes, set TODO state back to what it was and change the base date
12002 of repeating deadline/scheduled time stamps to new date.
12003 This function is run automatically after each state change to a DONE state."
12004 ;; last-state is dynamically scoped into this function
12005 (let* ((repeat (org-get-repeat))
12006 (aa (assoc org-last-state org-todo-kwd-alist))
12007 (interpret (nth 1 aa))
12008 (head (nth 2 aa))
12009 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12010 (msg "Entry repeats: ")
12011 (org-log-done nil)
12012 (org-todo-log-states nil)
12013 re type n what ts time to-state)
12014 (when repeat
12015 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12016 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12017 org-todo-repeat-to-state))
12018 (unless (and to-state (member to-state org-todo-keywords-1))
12019 (setq to-state (if (eq interpret 'type) org-last-state head)))
12020 (org-todo to-state)
12021 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12022 (org-entry-put nil "LAST_REPEAT" (format-time-string
12023 (org-time-stamp-format t t))))
12024 (when org-log-repeat
12025 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12026 (memq 'org-add-log-note post-command-hook))
12027 ;; OK, we are already setup for some record
12028 (if (eq org-log-repeat 'note)
12029 ;; make sure we take a note, not only a time stamp
12030 (setq org-log-note-how 'note))
12031 ;; Set up for taking a record
12032 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12033 org-last-state
12034 'findpos org-log-repeat)))
12035 (org-back-to-heading t)
12036 (org-add-planning-info nil nil 'closed)
12037 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12038 org-deadline-time-regexp "\\)\\|\\("
12039 org-ts-regexp "\\)"))
12040 (while (re-search-forward
12041 re (save-excursion (outline-next-heading) (point)) t)
12042 (setq type (if (match-end 1) org-scheduled-string
12043 (if (match-end 3) org-deadline-string "Plain:"))
12044 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12045 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12046 (setq n (string-to-number (match-string 2 ts))
12047 what (match-string 3 ts))
12048 (if (equal what "w") (setq n (* n 7) what "d"))
12049 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12050 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12051 ;; Preparation, see if we need to modify the start date for the change
12052 (when (match-end 1)
12053 (setq time (save-match-data (org-time-string-to-time ts)))
12054 (cond
12055 ((equal (match-string 1 ts) ".")
12056 ;; Shift starting date to today
12057 (org-timestamp-change
12058 (- (org-today) (time-to-days time))
12059 'day))
12060 ((equal (match-string 1 ts) "+")
12061 (let ((nshiftmax 10) (nshift 0))
12062 (while (or (= nshift 0)
12063 (<= (time-to-days time)
12064 (time-to-days (current-time))))
12065 (when (= (incf nshift) nshiftmax)
12066 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12067 (error "Abort")))
12068 (org-timestamp-change n (cdr (assoc what whata)))
12069 (org-at-timestamp-p t)
12070 (setq ts (match-string 1))
12071 (setq time (save-match-data (org-time-string-to-time ts)))))
12072 (org-timestamp-change (- n) (cdr (assoc what whata)))
12073 ;; rematch, so that we have everything in place for the real shift
12074 (org-at-timestamp-p t)
12075 (setq ts (match-string 1))
12076 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12077 (org-timestamp-change n (cdr (assoc what whata)))
12078 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12079 (setq org-log-post-message msg)
12080 (message "%s" msg))))
12082 (defun org-show-todo-tree (arg)
12083 "Make a compact tree which shows all headlines marked with TODO.
12084 The tree will show the lines where the regexp matches, and all higher
12085 headlines above the match.
12086 With a \\[universal-argument] prefix, prompt for a regexp to match.
12087 With a numeric prefix N, construct a sparse tree for the Nth element
12088 of `org-todo-keywords-1'."
12089 (interactive "P")
12090 (let ((case-fold-search nil)
12091 (kwd-re
12092 (cond ((null arg) org-not-done-regexp)
12093 ((equal arg '(4))
12094 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12095 (mapcar 'list org-todo-keywords-1))))
12096 (concat "\\("
12097 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12098 "\\)\\>")))
12099 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12100 (regexp-quote (nth (1- (prefix-numeric-value arg))
12101 org-todo-keywords-1)))
12102 (t (error "Invalid prefix argument: %s" arg)))))
12103 (message "%d TODO entries found"
12104 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12106 (defun org-deadline (&optional remove time)
12107 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12108 With argument REMOVE, remove any deadline from the item.
12109 With argument TIME, set the deadline at the corresponding date. TIME
12110 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12111 (interactive "P")
12112 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12113 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12114 'region-start-level 'region))
12115 org-loop-over-headlines-in-active-region)
12116 (org-map-entries
12117 `(org-deadline ',remove ,time)
12118 org-loop-over-headlines-in-active-region
12119 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12120 (let* ((old-date (org-entry-get nil "DEADLINE"))
12121 (repeater (and old-date
12122 (string-match
12123 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12124 old-date)
12125 (match-string 1 old-date))))
12126 (if remove
12127 (progn
12128 (when (and old-date org-log-redeadline)
12129 (org-add-log-setup 'deldeadline nil old-date 'findpos
12130 org-log-redeadline))
12131 (org-remove-timestamp-with-keyword org-deadline-string)
12132 (message "Item no longer has a deadline."))
12133 (org-add-planning-info 'deadline time 'closed)
12134 (when (and old-date org-log-redeadline
12135 (not (equal old-date
12136 (substring org-last-inserted-timestamp 1 -1))))
12137 (org-add-log-setup 'redeadline nil old-date 'findpos
12138 org-log-redeadline))
12139 (when repeater
12140 (save-excursion
12141 (org-back-to-heading t)
12142 (when (re-search-forward (concat org-deadline-string " "
12143 org-last-inserted-timestamp)
12144 (save-excursion
12145 (outline-next-heading) (point)) t)
12146 (goto-char (1- (match-end 0)))
12147 (insert " " repeater)
12148 (setq org-last-inserted-timestamp
12149 (concat (substring org-last-inserted-timestamp 0 -1)
12150 " " repeater
12151 (substring org-last-inserted-timestamp -1))))))
12152 (message "Deadline on %s" org-last-inserted-timestamp)))))
12154 (defun org-schedule (&optional remove time)
12155 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12156 With argument REMOVE, remove any scheduling date from the item.
12157 With argument TIME, scheduled at the corresponding date. TIME can
12158 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12159 (interactive "P")
12160 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12161 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12162 'region-start-level 'region))
12163 org-loop-over-headlines-in-active-region)
12164 (org-map-entries
12165 `(org-schedule ',remove ,time)
12166 org-loop-over-headlines-in-active-region
12167 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12168 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12169 (repeater (and old-date
12170 (string-match
12171 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12172 old-date)
12173 (match-string 1 old-date))))
12174 (if remove
12175 (progn
12176 (when (and old-date org-log-reschedule)
12177 (org-add-log-setup 'delschedule nil old-date 'findpos
12178 org-log-reschedule))
12179 (org-remove-timestamp-with-keyword org-scheduled-string)
12180 (message "Item is no longer scheduled."))
12181 (org-add-planning-info 'scheduled time 'closed)
12182 (when (and old-date org-log-reschedule
12183 (not (equal old-date
12184 (substring org-last-inserted-timestamp 1 -1))))
12185 (org-add-log-setup 'reschedule nil old-date 'findpos
12186 org-log-reschedule))
12187 (when repeater
12188 (save-excursion
12189 (org-back-to-heading t)
12190 (when (re-search-forward (concat org-scheduled-string " "
12191 org-last-inserted-timestamp)
12192 (save-excursion
12193 (outline-next-heading) (point)) t)
12194 (goto-char (1- (match-end 0)))
12195 (insert " " repeater)
12196 (setq org-last-inserted-timestamp
12197 (concat (substring org-last-inserted-timestamp 0 -1)
12198 " " repeater
12199 (substring org-last-inserted-timestamp -1))))))
12200 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12202 (defun org-get-scheduled-time (pom &optional inherit)
12203 "Get the scheduled time as a time tuple, of a format suitable
12204 for calling org-schedule with, or if there is no scheduling,
12205 returns nil."
12206 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12207 (when time
12208 (apply 'encode-time (org-parse-time-string time)))))
12210 (defun org-get-deadline-time (pom &optional inherit)
12211 "Get the deadline as a time tuple, of a format suitable for
12212 calling org-deadline with, or if there is no scheduling, returns
12213 nil."
12214 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12215 (when time
12216 (apply 'encode-time (org-parse-time-string time)))))
12218 (defun org-remove-timestamp-with-keyword (keyword)
12219 "Remove all time stamps with KEYWORD in the current entry."
12220 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12221 beg)
12222 (save-excursion
12223 (org-back-to-heading t)
12224 (setq beg (point))
12225 (outline-next-heading)
12226 (while (re-search-backward re beg t)
12227 (replace-match "")
12228 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12229 (equal (char-before) ?\ ))
12230 (backward-delete-char 1)
12231 (if (string-match "^[ \t]*$" (buffer-substring
12232 (point-at-bol) (point-at-eol)))
12233 (delete-region (point-at-bol)
12234 (min (point-max) (1+ (point-at-eol))))))))))
12236 (defun org-add-planning-info (what &optional time &rest remove)
12237 "Insert new timestamp with keyword in the line directly after the headline.
12238 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12239 If non is given, the user is prompted for a date.
12240 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12241 be removed."
12242 (interactive)
12243 (let (org-time-was-given org-end-time-was-given ts
12244 end default-time default-input)
12246 (catch 'exit
12247 (when (and (memq what '(scheduled deadline))
12248 (or (not time)
12249 (and (stringp time)
12250 (string-match "^[-+]+[0-9]" time))))
12251 ;; Try to get a default date/time from existing timestamp
12252 (save-excursion
12253 (org-back-to-heading t)
12254 (setq end (save-excursion (outline-next-heading) (point)))
12255 (when (re-search-forward (if (eq what 'scheduled)
12256 org-scheduled-time-regexp
12257 org-deadline-time-regexp)
12258 end t)
12259 (setq ts (match-string 1)
12260 default-time
12261 (apply 'encode-time (org-parse-time-string ts))
12262 default-input (and ts (org-get-compact-tod ts))))))
12263 (when what
12264 (setq time
12265 (if (stringp time)
12266 ;; This is a string (relative or absolute), set proper date
12267 (apply 'encode-time
12268 (org-read-date-analyze
12269 time default-time (decode-time default-time)))
12270 ;; If necessary, get the time from the user
12271 (or time (org-read-date nil 'to-time nil nil
12272 default-time default-input)))))
12274 (when (and org-insert-labeled-timestamps-at-point
12275 (member what '(scheduled deadline)))
12276 (insert
12277 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12278 (org-insert-time-stamp time org-time-was-given
12279 nil nil nil (list org-end-time-was-given))
12280 (setq what nil))
12281 (save-excursion
12282 (save-restriction
12283 (let (col list elt ts buffer-invisibility-spec)
12284 (org-back-to-heading t)
12285 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12286 (goto-char (match-end 1))
12287 (setq col (current-column))
12288 (goto-char (match-end 0))
12289 (if (eobp) (insert "\n") (forward-char 1))
12290 (when (and (not what)
12291 (not (looking-at
12292 (concat "[ \t]*"
12293 org-keyword-time-not-clock-regexp))))
12294 ;; Nothing to add, nothing to remove...... :-)
12295 (throw 'exit nil))
12296 (if (and (not (looking-at org-outline-regexp))
12297 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12298 "[^\r\n]*"))
12299 (not (equal (match-string 1) org-clock-string)))
12300 (narrow-to-region (match-beginning 0) (match-end 0))
12301 (insert-before-markers "\n")
12302 (backward-char 1)
12303 (narrow-to-region (point) (point))
12304 (and org-adapt-indentation (org-indent-to-column col)))
12305 ;; Check if we have to remove something.
12306 (setq list (cons what remove))
12307 (while list
12308 (setq elt (pop list))
12309 (when (or (and (eq elt 'scheduled)
12310 (re-search-forward org-scheduled-time-regexp nil t))
12311 (and (eq elt 'deadline)
12312 (re-search-forward org-deadline-time-regexp nil t))
12313 (and (eq elt 'closed)
12314 (re-search-forward org-closed-time-regexp nil t)))
12315 (replace-match "")
12316 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12317 (and (looking-at "[ \t]+") (replace-match ""))
12318 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12319 (when what
12320 (insert
12321 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12322 (cond ((eq what 'scheduled) org-scheduled-string)
12323 ((eq what 'deadline) org-deadline-string)
12324 ((eq what 'closed) org-closed-string))
12325 " ")
12326 (setq ts (org-insert-time-stamp
12327 time
12328 (or org-time-was-given
12329 (and (eq what 'closed) org-log-done-with-time))
12330 (eq what 'closed)
12331 nil nil (list org-end-time-was-given)))
12332 (insert
12333 (if (not (or (bolp) (eq (char-before) ?\ )
12334 (memq (char-after) '(32 10))
12335 (eobp))) " " ""))
12336 (end-of-line 1))
12337 (goto-char (point-min))
12338 (widen)
12339 (if (and (looking-at "[ \t]*\n")
12340 (equal (char-before) ?\n))
12341 (delete-region (1- (point)) (point-at-eol)))
12342 ts))))))
12344 (defvar org-log-note-marker (make-marker))
12345 (defvar org-log-note-purpose nil)
12346 (defvar org-log-note-state nil)
12347 (defvar org-log-note-previous-state nil)
12348 (defvar org-log-note-how nil)
12349 (defvar org-log-note-extra nil)
12350 (defvar org-log-note-window-configuration nil)
12351 (defvar org-log-note-return-to (make-marker))
12352 (defvar org-log-note-effective-time nil
12353 "Remembered current time so that dynamically scoped
12354 `org-extend-today-until' affects tha timestamps in state change
12355 log")
12357 (defvar org-log-post-message nil
12358 "Message to be displayed after a log note has been stored.
12359 The auto-repeater uses this.")
12361 (defun org-add-note ()
12362 "Add a note to the current entry.
12363 This is done in the same way as adding a state change note."
12364 (interactive)
12365 (org-add-log-setup 'note nil nil 'findpos nil))
12367 (defvar org-property-end-re)
12368 (defun org-add-log-setup (&optional purpose state prev-state
12369 findpos how extra)
12370 "Set up the post command hook to take a note.
12371 If this is about to TODO state change, the new state is expected in STATE.
12372 When FINDPOS is non-nil, find the correct position for the note in
12373 the current entry. If not, assume that it can be inserted at point.
12374 HOW is an indicator what kind of note should be created.
12375 EXTRA is additional text that will be inserted into the notes buffer."
12376 (let* ((org-log-into-drawer (org-log-into-drawer))
12377 (drawer (cond ((stringp org-log-into-drawer)
12378 org-log-into-drawer)
12379 (org-log-into-drawer "LOGBOOK")
12380 (t nil))))
12381 (save-restriction
12382 (save-excursion
12383 (when findpos
12384 (org-back-to-heading t)
12385 (narrow-to-region (point) (save-excursion
12386 (outline-next-heading) (point)))
12387 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12388 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12389 "[^\r\n]*\\)?"))
12390 (goto-char (match-end 0))
12391 (cond
12392 (drawer
12393 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12394 nil t)
12395 (progn
12396 (goto-char (match-end 0))
12397 (or org-log-states-order-reversed
12398 (and (re-search-forward org-property-end-re nil t)
12399 (goto-char (1- (match-beginning 0))))))
12400 (insert "\n:" drawer ":\n:END:")
12401 (beginning-of-line 0)
12402 (org-indent-line-function)
12403 (beginning-of-line 2)
12404 (org-indent-line-function)
12405 (end-of-line 0)))
12406 ((and org-log-state-notes-insert-after-drawers
12407 (save-excursion
12408 (forward-line) (looking-at org-drawer-regexp)))
12409 (forward-line)
12410 (while (looking-at org-drawer-regexp)
12411 (goto-char (match-end 0))
12412 (re-search-forward org-property-end-re (point-max) t)
12413 (forward-line))
12414 (forward-line -1)))
12415 (unless org-log-states-order-reversed
12416 (and (= (char-after) ?\n) (forward-char 1))
12417 (org-skip-over-state-notes)
12418 (skip-chars-backward " \t\n\r")))
12419 (move-marker org-log-note-marker (point))
12420 (setq org-log-note-purpose purpose
12421 org-log-note-state state
12422 org-log-note-previous-state prev-state
12423 org-log-note-how how
12424 org-log-note-extra extra
12425 org-log-note-effective-time (org-current-effective-time))
12426 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12428 (defun org-skip-over-state-notes ()
12429 "Skip past the list of State notes in an entry."
12430 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12431 (when (ignore-errors (goto-char (org-in-item-p)))
12432 (let* ((struct (org-list-struct))
12433 (prevs (org-list-prevs-alist struct)))
12434 (while (looking-at "[ \t]*- State")
12435 (goto-char (or (org-list-get-next-item (point) struct prevs)
12436 (org-list-get-item-end (point) struct)))))))
12438 (defun org-add-log-note (&optional purpose)
12439 "Pop up a window for taking a note, and add this note later at point."
12440 (remove-hook 'post-command-hook 'org-add-log-note)
12441 (setq org-log-note-window-configuration (current-window-configuration))
12442 (delete-other-windows)
12443 (move-marker org-log-note-return-to (point))
12444 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12445 (goto-char org-log-note-marker)
12446 (org-switch-to-buffer-other-window "*Org Note*")
12447 (erase-buffer)
12448 (if (memq org-log-note-how '(time state))
12449 (let (current-prefix-arg) (org-store-log-note))
12450 (let ((org-inhibit-startup t)) (org-mode))
12451 (insert (format "# Insert note for %s.
12452 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12453 (cond
12454 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12455 ((eq org-log-note-purpose 'done) "closed todo item")
12456 ((eq org-log-note-purpose 'state)
12457 (format "state change from \"%s\" to \"%s\""
12458 (or org-log-note-previous-state "")
12459 (or org-log-note-state "")))
12460 ((eq org-log-note-purpose 'reschedule)
12461 "rescheduling")
12462 ((eq org-log-note-purpose 'delschedule)
12463 "no longer scheduled")
12464 ((eq org-log-note-purpose 'redeadline)
12465 "changing deadline")
12466 ((eq org-log-note-purpose 'deldeadline)
12467 "removing deadline")
12468 ((eq org-log-note-purpose 'refile)
12469 "refiling")
12470 ((eq org-log-note-purpose 'note)
12471 "this entry")
12472 (t (error "This should not happen")))))
12473 (if org-log-note-extra (insert org-log-note-extra))
12474 (org-set-local 'org-finish-function 'org-store-log-note)
12475 (run-hooks 'org-log-buffer-setup-hook)))
12477 (defvar org-note-abort nil) ; dynamically scoped
12478 (defun org-store-log-note ()
12479 "Finish taking a log note, and insert it to where it belongs."
12480 (let ((txt (buffer-string))
12481 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12482 lines ind bul)
12483 (kill-buffer (current-buffer))
12484 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12485 (setq txt (replace-match "" t t txt)))
12486 (if (string-match "\\s-+\\'" txt)
12487 (setq txt (replace-match "" t t txt)))
12488 (setq lines (org-split-string txt "\n"))
12489 (when (and note (string-match "\\S-" note))
12490 (setq note
12491 (org-replace-escapes
12492 note
12493 (list (cons "%u" (user-login-name))
12494 (cons "%U" user-full-name)
12495 (cons "%t" (format-time-string
12496 (org-time-stamp-format 'long 'inactive)
12497 org-log-note-effective-time))
12498 (cons "%T" (format-time-string
12499 (org-time-stamp-format 'long nil)
12500 org-log-note-effective-time))
12501 (cons "%d" (format-time-string
12502 (org-time-stamp-format nil 'inactive)
12503 org-log-note-effective-time))
12504 (cons "%D" (format-time-string
12505 (org-time-stamp-format nil nil)
12506 org-log-note-effective-time))
12507 (cons "%s" (if org-log-note-state
12508 (concat "\"" org-log-note-state "\"")
12509 ""))
12510 (cons "%S" (if org-log-note-previous-state
12511 (concat "\"" org-log-note-previous-state "\"")
12512 "\"\"")))))
12513 (if lines (setq note (concat note " \\\\")))
12514 (push note lines))
12515 (when (or current-prefix-arg org-note-abort)
12516 (when org-log-into-drawer
12517 (org-remove-empty-drawer-at
12518 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12519 org-log-note-marker))
12520 (setq lines nil))
12521 (when lines
12522 (with-current-buffer (marker-buffer org-log-note-marker)
12523 (save-excursion
12524 (goto-char org-log-note-marker)
12525 (move-marker org-log-note-marker nil)
12526 (end-of-line 1)
12527 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12528 (setq ind (save-excursion
12529 (if (ignore-errors (goto-char (org-in-item-p)))
12530 (let ((struct (org-list-struct)))
12531 (org-list-get-ind
12532 (org-list-get-top-point struct) struct))
12533 (skip-chars-backward " \r\t\n")
12534 (cond
12535 ((and (org-at-heading-p)
12536 org-adapt-indentation)
12537 (1+ (org-current-level)))
12538 ((org-at-heading-p) 0)
12539 (t (org-get-indentation))))))
12540 (setq bul (org-list-bullet-string "-"))
12541 (org-indent-line-to ind)
12542 (insert bul (pop lines))
12543 (let ((ind-body (+ (length bul) ind)))
12544 (while lines
12545 (insert "\n")
12546 (org-indent-line-to ind-body)
12547 (insert (pop lines))))
12548 (message "Note stored")
12549 (org-back-to-heading t)
12550 (org-cycle-hide-drawers 'children)))))
12551 (set-window-configuration org-log-note-window-configuration)
12552 (with-current-buffer (marker-buffer org-log-note-return-to)
12553 (goto-char org-log-note-return-to))
12554 (move-marker org-log-note-return-to nil)
12555 (and org-log-post-message (message "%s" org-log-post-message)))
12557 (defun org-remove-empty-drawer-at (drawer pos)
12558 "Remove an empty drawer DRAWER at position POS.
12559 POS may also be a marker."
12560 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12561 (save-excursion
12562 (save-restriction
12563 (widen)
12564 (goto-char pos)
12565 (if (org-in-regexp
12566 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12567 (replace-match ""))))))
12569 (defun org-sparse-tree (&optional arg)
12570 "Create a sparse tree, prompt for the details.
12571 This command can create sparse trees. You first need to select the type
12572 of match used to create the tree:
12574 t Show all TODO entries.
12575 T Show entries with a specific TODO keyword.
12576 m Show entries selected by a tags/property match.
12577 p Enter a property name and its value (both with completion on existing
12578 names/values) and show entries with that property.
12579 r Show entries matching a regular expression (`/' can be used as well)
12580 d Show deadlines due within `org-deadline-warning-days'.
12581 b Show deadlines and scheduled items before a date.
12582 a Show deadlines and scheduled items after a date."
12583 (interactive "P")
12584 (let (ans kwd value)
12585 (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")
12586 (setq ans (read-char-exclusive))
12587 (cond
12588 ((equal ans ?d)
12589 (call-interactively 'org-check-deadlines))
12590 ((equal ans ?b)
12591 (call-interactively 'org-check-before-date))
12592 ((equal ans ?a)
12593 (call-interactively 'org-check-after-date))
12594 ((equal ans ?D)
12595 (call-interactively 'org-check-dates-range))
12596 ((equal ans ?t)
12597 (org-show-todo-tree nil))
12598 ((equal ans ?T)
12599 (org-show-todo-tree '(4)))
12600 ((member ans '(?T ?m))
12601 (call-interactively 'org-match-sparse-tree))
12602 ((member ans '(?p ?P))
12603 (setq kwd (org-icompleting-read "Property: "
12604 (mapcar 'list (org-buffer-property-keys))))
12605 (setq value (org-icompleting-read "Value: "
12606 (mapcar 'list (org-property-values kwd))))
12607 (unless (string-match "\\`{.*}\\'" value)
12608 (setq value (concat "\"" value "\"")))
12609 (org-match-sparse-tree arg (concat kwd "=" value)))
12610 ((member ans '(?r ?R ?/))
12611 (call-interactively 'org-occur))
12612 (t (error "No such sparse tree command \"%c\"" ans)))))
12614 (defvar org-occur-highlights nil
12615 "List of overlays used for occur matches.")
12616 (make-variable-buffer-local 'org-occur-highlights)
12617 (defvar org-occur-parameters nil
12618 "Parameters of the active org-occur calls.
12619 This is a list, each call to org-occur pushes as cons cell,
12620 containing the regular expression and the callback, onto the list.
12621 The list can contain several entries if `org-occur' has been called
12622 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12623 will only contain one set of parameters. When the highlights are
12624 removed (for example with `C-c C-c', or with the next edit (depending
12625 on `org-remove-highlights-with-change'), this variable is emptied
12626 as well.")
12627 (make-variable-buffer-local 'org-occur-parameters)
12629 (defun org-occur (regexp &optional keep-previous callback)
12630 "Make a compact tree which shows all matches of REGEXP.
12631 The tree will show the lines where the regexp matches, and all higher
12632 headlines above the match. It will also show the heading after the match,
12633 to make sure editing the matching entry is easy.
12634 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12635 call to `org-occur' will be kept, to allow stacking of calls to this
12636 command.
12637 If CALLBACK is non-nil, it is a function which is called to confirm
12638 that the match should indeed be shown."
12639 (interactive "sRegexp: \nP")
12640 (when (equal regexp "")
12641 (error "Regexp cannot be empty"))
12642 (unless keep-previous
12643 (org-remove-occur-highlights nil nil t))
12644 (push (cons regexp callback) org-occur-parameters)
12645 (let ((cnt 0))
12646 (save-excursion
12647 (goto-char (point-min))
12648 (if (or (not keep-previous) ; do not want to keep
12649 (not org-occur-highlights)) ; no previous matches
12650 ;; hide everything
12651 (org-overview))
12652 (while (re-search-forward regexp nil t)
12653 (when (or (not callback)
12654 (save-match-data (funcall callback)))
12655 (setq cnt (1+ cnt))
12656 (when org-highlight-sparse-tree-matches
12657 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12658 (org-show-context 'occur-tree))))
12659 (when org-remove-highlights-with-change
12660 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12661 nil 'local))
12662 (unless org-sparse-tree-open-archived-trees
12663 (org-hide-archived-subtrees (point-min) (point-max)))
12664 (run-hooks 'org-occur-hook)
12665 (if (org-called-interactively-p 'interactive)
12666 (message "%d match(es) for regexp %s" cnt regexp))
12667 cnt))
12669 (defun org-occur-next-match (&optional n reset)
12670 "Function for `next-error-function' to find sparse tree matches.
12671 N is the number of matches to move, when negative move backwards.
12672 RESET is entirely ignored - this function always goes back to the
12673 starting point when no match is found."
12674 (let* ((limit (if (< n 0) (point-min) (point-max)))
12675 (search-func (if (< n 0)
12676 'previous-single-char-property-change
12677 'next-single-char-property-change))
12678 (n (abs n))
12679 (pos (point))
12681 (catch 'exit
12682 (while (setq p1 (funcall search-func (point) 'org-type))
12683 (when (equal p1 limit)
12684 (goto-char pos)
12685 (error "No more matches"))
12686 (when (equal (get-char-property p1 'org-type) 'org-occur)
12687 (setq n (1- n))
12688 (when (= n 0)
12689 (goto-char p1)
12690 (throw 'exit (point))))
12691 (goto-char p1))
12692 (goto-char p1)
12693 (error "No more matches"))))
12695 (defun org-show-context (&optional key)
12696 "Make sure point and context are visible.
12697 How much context is shown depends upon the variables
12698 `org-show-hierarchy-above', `org-show-following-heading',
12699 `org-show-entry-below' and `org-show-siblings'."
12700 (let ((heading-p (org-at-heading-p t))
12701 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12702 (following-p (org-get-alist-option org-show-following-heading key))
12703 (entry-p (org-get-alist-option org-show-entry-below key))
12704 (siblings-p (org-get-alist-option org-show-siblings key)))
12705 (catch 'exit
12706 ;; Show heading or entry text
12707 (if (and heading-p (not entry-p))
12708 (org-flag-heading nil) ; only show the heading
12709 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12710 (org-show-hidden-entry))) ; show entire entry
12711 (when following-p
12712 ;; Show next sibling, or heading below text
12713 (save-excursion
12714 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12715 (org-flag-heading nil))))
12716 (when siblings-p (org-show-siblings))
12717 (when hierarchy-p
12718 ;; show all higher headings, possibly with siblings
12719 (save-excursion
12720 (while (and (condition-case nil
12721 (progn (org-up-heading-all 1) t)
12722 (error nil))
12723 (not (bobp)))
12724 (org-flag-heading nil)
12725 (when siblings-p (org-show-siblings))))))))
12727 (defvar org-reveal-start-hook nil
12728 "Hook run before revealing a location.")
12730 (defun org-reveal (&optional siblings)
12731 "Show current entry, hierarchy above it, and the following headline.
12732 This can be used to show a consistent set of context around locations
12733 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12734 not t for the search context.
12736 With optional argument SIBLINGS, on each level of the hierarchy all
12737 siblings are shown. This repairs the tree structure to what it would
12738 look like when opened with hierarchical calls to `org-cycle'.
12739 With double optional argument \\[universal-argument] \\[universal-argument], \
12740 go to the parent and show the
12741 entire tree."
12742 (interactive "P")
12743 (run-hooks 'org-reveal-start-hook)
12744 (let ((org-show-hierarchy-above t)
12745 (org-show-following-heading t)
12746 (org-show-siblings (if siblings t org-show-siblings)))
12747 (org-show-context nil))
12748 (when (equal siblings '(16))
12749 (save-excursion
12750 (when (org-up-heading-safe)
12751 (org-show-subtree)
12752 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12754 (defun org-highlight-new-match (beg end)
12755 "Highlight from BEG to END and mark the highlight is an occur headline."
12756 (let ((ov (make-overlay beg end)))
12757 (overlay-put ov 'face 'secondary-selection)
12758 (overlay-put ov 'org-type 'org-occur)
12759 (push ov org-occur-highlights)))
12761 (defun org-remove-occur-highlights (&optional beg end noremove)
12762 "Remove the occur highlights from the buffer.
12763 BEG and END are ignored. If NOREMOVE is nil, remove this function
12764 from the `before-change-functions' in the current buffer."
12765 (interactive)
12766 (unless org-inhibit-highlight-removal
12767 (mapc 'delete-overlay org-occur-highlights)
12768 (setq org-occur-highlights nil)
12769 (setq org-occur-parameters nil)
12770 (unless noremove
12771 (remove-hook 'before-change-functions
12772 'org-remove-occur-highlights 'local))))
12774 ;;;; Priorities
12776 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12777 "Regular expression matching the priority indicator.")
12779 (defvar org-remove-priority-next-time nil)
12781 (defun org-priority-up ()
12782 "Increase the priority of the current item."
12783 (interactive)
12784 (org-priority 'up))
12786 (defun org-priority-down ()
12787 "Decrease the priority of the current item."
12788 (interactive)
12789 (org-priority 'down))
12791 (defun org-priority (&optional action)
12792 "Change the priority of an item by ARG.
12793 ACTION can be `set', `up', `down', or a character."
12794 (interactive)
12795 (unless org-enable-priority-commands
12796 (error "Priority commands are disabled"))
12797 (setq action (or action 'set))
12798 (let (current new news have remove)
12799 (save-excursion
12800 (org-back-to-heading t)
12801 (if (looking-at org-priority-regexp)
12802 (setq current (string-to-char (match-string 2))
12803 have t))
12804 (cond
12805 ((eq action 'remove)
12806 (setq remove t new ?\ ))
12807 ((or (eq action 'set)
12808 (if (featurep 'xemacs) (characterp action) (integerp action)))
12809 (if (not (eq action 'set))
12810 (setq new action)
12811 (message "Priority %c-%c, SPC to remove: "
12812 org-highest-priority org-lowest-priority)
12813 (save-match-data
12814 (setq new (read-char-exclusive))))
12815 (if (and (= (upcase org-highest-priority) org-highest-priority)
12816 (= (upcase org-lowest-priority) org-lowest-priority))
12817 (setq new (upcase new)))
12818 (cond ((equal new ?\ ) (setq remove t))
12819 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12820 (error "Priority must be between `%c' and `%c'"
12821 org-highest-priority org-lowest-priority))))
12822 ((eq action 'up)
12823 (setq new (if have
12824 (1- current) ; normal cycling
12825 ;; last priority was empty
12826 (if (eq last-command this-command)
12827 org-lowest-priority ; wrap around empty to lowest
12828 ;; default
12829 (if org-priority-start-cycle-with-default
12830 org-default-priority
12831 (1- org-default-priority))))))
12832 ((eq action 'down)
12833 (setq new (if have
12834 (1+ current) ; normal cycling
12835 ;; last priority was empty
12836 (if (eq last-command this-command)
12837 org-highest-priority ; wrap around empty to highest
12838 ;; default
12839 (if org-priority-start-cycle-with-default
12840 org-default-priority
12841 (1+ org-default-priority))))))
12842 (t (error "Invalid action")))
12843 (if (or (< (upcase new) org-highest-priority)
12844 (> (upcase new) org-lowest-priority))
12845 (if (and (memq action '(up down))
12846 (not have) (not (eq last-command this-command)))
12847 ;; `new' is from default priority
12848 (error
12849 "The default can not be set, see `org-default-priority' why")
12850 ;; normal cycling: `new' is beyond highest/lowest priority
12851 ;; and is wrapped around to the empty priority
12852 (setq remove t)))
12853 (setq news (format "%c" new))
12854 (if have
12855 (if remove
12856 (replace-match "" t t nil 1)
12857 (replace-match news t t nil 2))
12858 (if remove
12859 (error "No priority cookie found in line")
12860 (let ((case-fold-search nil))
12861 (looking-at org-todo-line-regexp))
12862 (if (match-end 2)
12863 (progn
12864 (goto-char (match-end 2))
12865 (insert " [#" news "]"))
12866 (goto-char (match-beginning 3))
12867 (insert "[#" news "] "))))
12868 (org-preserve-lc (org-set-tags nil 'align)))
12869 (if remove
12870 (message "Priority removed")
12871 (message "Priority of current item set to %s" news))))
12873 (defun org-get-priority (s)
12874 "Find priority cookie and return priority."
12875 (if (functionp org-get-priority-function)
12876 (funcall org-get-priority-function)
12877 (save-match-data
12878 (if (not (string-match org-priority-regexp s))
12879 (* 1000 (- org-lowest-priority org-default-priority))
12880 (* 1000 (- org-lowest-priority
12881 (string-to-char (match-string 2 s))))))))
12883 ;;;; Tags
12885 (defvar org-agenda-archives-mode)
12886 (defvar org-map-continue-from nil
12887 "Position from where mapping should continue.
12888 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12890 (defvar org-scanner-tags nil
12891 "The current tag list while the tags scanner is running.")
12892 (defvar org-trust-scanner-tags nil
12893 "Should `org-get-tags-at' use the tags for the scanner.
12894 This is for internal dynamical scoping only.
12895 When this is non-nil, the function `org-get-tags-at' will return the value
12896 of `org-scanner-tags' instead of building the list by itself. This
12897 can lead to large speed-ups when the tags scanner is used in a file with
12898 many entries, and when the list of tags is retrieved, for example to
12899 obtain a list of properties. Building the tags list for each entry in such
12900 a file becomes an N^2 operation - but with this variable set, it scales
12901 as N.")
12903 (defun org-scan-tags (action matcher todo-only &optional start-level)
12904 "Scan headline tags with inheritance and produce output ACTION.
12906 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12907 or `agenda' to produce an entry list for an agenda view. It can also be
12908 a Lisp form or a function that should be called at each matched headline, in
12909 this case the return value is a list of all return values from these calls.
12911 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12912 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12913 only lines with a not-done TODO keyword are included in the output.
12914 This should be the same variable that was scoped into
12915 and set by `org-make-tags-matcher' when it constructed MATCHER.
12917 START-LEVEL can be a string with asterisks, reducing the scope to
12918 headlines matching this string."
12919 (require 'org-agenda)
12920 (let* ((re (concat "^"
12921 (if start-level
12922 ;; Get the correct level to match
12923 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12924 org-outline-regexp)
12925 " *\\(\\<\\("
12926 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12927 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12928 (props (list 'face 'default
12929 'done-face 'org-agenda-done
12930 'undone-face 'default
12931 'mouse-face 'highlight
12932 'org-not-done-regexp org-not-done-regexp
12933 'org-todo-regexp org-todo-regexp
12934 'org-complex-heading-regexp org-complex-heading-regexp
12935 'help-echo
12936 (format "mouse-2 or RET jump to org file %s"
12937 (abbreviate-file-name
12938 (or (buffer-file-name (buffer-base-buffer))
12939 (buffer-name (buffer-base-buffer)))))))
12940 (case-fold-search nil)
12941 (org-map-continue-from nil)
12942 lspos tags tags-list
12943 (tags-alist (list (cons 0 org-file-tags)))
12944 (llast 0) rtn rtn1 level category i txt
12945 todo marker entry priority)
12946 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12947 (setq action (list 'lambda nil action)))
12948 (save-excursion
12949 (goto-char (point-min))
12950 (when (eq action 'sparse-tree)
12951 (org-overview)
12952 (org-remove-occur-highlights))
12953 (while (re-search-forward re nil t)
12954 (setq org-map-continue-from nil)
12955 (catch :skip
12956 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12957 tags (if (match-end 4) (org-match-string-no-properties 4)))
12958 (goto-char (setq lspos (match-beginning 0)))
12959 (setq level (org-reduced-level (funcall outline-level))
12960 category (org-get-category))
12961 (setq i llast llast level)
12962 ;; remove tag lists from same and sublevels
12963 (while (>= i level)
12964 (when (setq entry (assoc i tags-alist))
12965 (setq tags-alist (delete entry tags-alist)))
12966 (setq i (1- i)))
12967 ;; add the next tags
12968 (when tags
12969 (setq tags (org-split-string tags ":")
12970 tags-alist
12971 (cons (cons level tags) tags-alist)))
12972 ;; compile tags for current headline
12973 (setq tags-list
12974 (if org-use-tag-inheritance
12975 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12976 tags)
12977 org-scanner-tags tags-list)
12978 (when org-use-tag-inheritance
12979 (setcdr (car tags-alist)
12980 (mapcar (lambda (x)
12981 (setq x (copy-sequence x))
12982 (org-add-prop-inherited x))
12983 (cdar tags-alist))))
12984 (when (and tags org-use-tag-inheritance
12985 (or (not (eq t org-use-tag-inheritance))
12986 org-tags-exclude-from-inheritance))
12987 ;; selective inheritance, remove uninherited ones
12988 (setcdr (car tags-alist)
12989 (org-remove-uninherited-tags (cdar tags-alist))))
12990 (when (and
12992 ;; eval matcher only when the todo condition is OK
12993 (and (or (not todo-only) (member todo org-not-done-keywords))
12994 (let ((case-fold-search t) (org-trust-scanner-tags t))
12995 (eval matcher)))
12997 ;; Call the skipper, but return t if it does not skip,
12998 ;; so that the `and' form continues evaluating
12999 (progn
13000 (unless (eq action 'sparse-tree) (org-agenda-skip))
13003 ;; Check if timestamps are deselecting this entry
13004 (or (not todo-only)
13005 (and (member todo org-not-done-keywords)
13006 (or (not org-agenda-tags-todo-honor-ignore-options)
13007 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13009 ;; Extra check for the archive tag
13010 ;; FIXME: Does the skipper already do this????
13012 (not (member org-archive-tag tags-list))
13013 ;; we have an archive tag, should we use this anyway?
13014 (or (not org-agenda-skip-archived-trees)
13015 (and (eq action 'agenda) org-agenda-archives-mode))))
13017 ;; select this headline
13019 (cond
13020 ((eq action 'sparse-tree)
13021 (and org-highlight-sparse-tree-matches
13022 (org-get-heading) (match-end 0)
13023 (org-highlight-new-match
13024 (match-beginning 1) (match-end 1)))
13025 (org-show-context 'tags-tree))
13026 ((eq action 'agenda)
13027 (setq txt (org-agenda-format-item
13029 (concat
13030 (if (eq org-tags-match-list-sublevels 'indented)
13031 (make-string (1- level) ?.) "")
13032 (org-get-heading))
13033 category
13034 tags-list)
13035 priority (org-get-priority txt))
13036 (goto-char lspos)
13037 (setq marker (org-agenda-new-marker))
13038 (org-add-props txt props
13039 'org-marker marker 'org-hd-marker marker 'org-category category
13040 'todo-state todo
13041 'priority priority 'type "tagsmatch")
13042 (push txt rtn))
13043 ((functionp action)
13044 (setq org-map-continue-from nil)
13045 (save-excursion
13046 (setq rtn1 (funcall action))
13047 (push rtn1 rtn)))
13048 (t (error "Invalid action")))
13050 ;; if we are to skip sublevels, jump to end of subtree
13051 (unless org-tags-match-list-sublevels
13052 (org-end-of-subtree t)
13053 (backward-char 1))))
13054 ;; Get the correct position from where to continue
13055 (if org-map-continue-from
13056 (goto-char org-map-continue-from)
13057 (and (= (point) lspos) (end-of-line 1)))))
13058 (when (and (eq action 'sparse-tree)
13059 (not org-sparse-tree-open-archived-trees))
13060 (org-hide-archived-subtrees (point-min) (point-max)))
13061 (nreverse rtn)))
13063 (defun org-remove-uninherited-tags (tags)
13064 "Remove all tags that are not inherited from the list TAGS."
13065 (cond
13066 ((eq org-use-tag-inheritance t)
13067 (if org-tags-exclude-from-inheritance
13068 (org-delete-all org-tags-exclude-from-inheritance tags)
13069 tags))
13070 ((not org-use-tag-inheritance) nil)
13071 ((stringp org-use-tag-inheritance)
13072 (delq nil (mapcar
13073 (lambda (x)
13074 (if (and (string-match org-use-tag-inheritance x)
13075 (not (member x org-tags-exclude-from-inheritance)))
13076 x nil))
13077 tags)))
13078 ((listp org-use-tag-inheritance)
13079 (delq nil (mapcar
13080 (lambda (x)
13081 (if (member x org-use-tag-inheritance) x nil))
13082 tags)))))
13084 (defun org-match-sparse-tree (&optional todo-only match)
13085 "Create a sparse tree according to tags string MATCH.
13086 MATCH can contain positive and negative selection of tags, like
13087 \"+WORK+URGENT-WITHBOSS\".
13088 If optional argument TODO-ONLY is non-nil, only select lines that are
13089 also TODO lines."
13090 (interactive "P")
13091 (org-prepare-agenda-buffers (list (current-buffer)))
13092 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13094 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13096 (defvar org-cached-props nil)
13097 (defun org-cached-entry-get (pom property)
13098 (if (or (eq t org-use-property-inheritance)
13099 (and (stringp org-use-property-inheritance)
13100 (string-match org-use-property-inheritance property))
13101 (and (listp org-use-property-inheritance)
13102 (member property org-use-property-inheritance)))
13103 ;; Caching is not possible, check it directly
13104 (org-entry-get pom property 'inherit)
13105 ;; Get all properties, so that we can do complicated checks easily
13106 (cdr (assoc property (or org-cached-props
13107 (setq org-cached-props
13108 (org-entry-properties pom)))))))
13110 (defun org-global-tags-completion-table (&optional files)
13111 "Return the list of all tags in all agenda buffer/files.
13112 Optional FILES argument is a list of files to which can be used
13113 instead of the agenda files."
13114 (save-excursion
13115 (org-uniquify
13116 (delq nil
13117 (apply 'append
13118 (mapcar
13119 (lambda (file)
13120 (set-buffer (find-file-noselect file))
13121 (append (org-get-buffer-tags)
13122 (mapcar (lambda (x) (if (stringp (car-safe x))
13123 (list (car-safe x)) nil))
13124 org-tag-alist)))
13125 (if (and files (car files))
13126 files
13127 (org-agenda-files))))))))
13129 (defun org-make-tags-matcher (match)
13130 "Create the TAGS/TODO matcher form for the selection string MATCH.
13132 The variable `todo-only' is scoped dynamically into this function; it will be
13133 set to t if the matcher restricts matching to TODO entries,
13134 otherwise will not be touched.
13136 Returns a cons of the selection string MATCH and the constructed
13137 lisp form implementing the matcher. The matcher is to be
13138 evaluated at an Org entry, with point on the headline,
13139 and returns t if the entry matches the
13140 selection string MATCH. The returned lisp form references
13141 two variables with information about the entry, which must be
13142 bound around the form's evaluation: todo, the TODO keyword at the
13143 entry (or nil of none); and tags-list, the list of all tags at the
13144 entry including inherited ones. Additionally, the category
13145 of the entry (if any) must be specified as the text property
13146 'org-category on the headline.
13148 See also `org-scan-tags'.
13150 (declare (special todo-only))
13151 (unless (boundp 'todo-only)
13152 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13153 (unless match
13154 ;; Get a new match request, with completion
13155 (let ((org-last-tags-completion-table
13156 (org-global-tags-completion-table)))
13157 (setq match (org-completing-read-no-i
13158 "Match: " 'org-tags-completion-function nil nil nil
13159 'org-tags-history))))
13161 ;; Parse the string and create a lisp form
13162 (let ((match0 match)
13163 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13164 minus tag mm
13165 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13166 orterms term orlist re-p str-p level-p level-op time-p
13167 prop-p pn pv po gv rest)
13168 (if (string-match "/+" match)
13169 ;; match contains also a todo-matching request
13170 (progn
13171 (setq tagsmatch (substring match 0 (match-beginning 0))
13172 todomatch (substring match (match-end 0)))
13173 (if (string-match "^!" todomatch)
13174 (setq todo-only t todomatch (substring todomatch 1)))
13175 (if (string-match "^\\s-*$" todomatch)
13176 (setq todomatch nil)))
13177 ;; only matching tags
13178 (setq tagsmatch match todomatch nil))
13180 ;; Make the tags matcher
13181 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13182 (setq tagsmatcher t)
13183 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13184 (while (setq term (pop orterms))
13185 (while (and (equal (substring term -1) "\\") orterms)
13186 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13187 (while (string-match re term)
13188 (setq rest (substring term (match-end 0))
13189 minus (and (match-end 1)
13190 (equal (match-string 1 term) "-"))
13191 tag (save-match-data (replace-regexp-in-string
13192 "\\\\-" "-"
13193 (match-string 2 term)))
13194 re-p (equal (string-to-char tag) ?{)
13195 level-p (match-end 4)
13196 prop-p (match-end 5)
13197 mm (cond
13198 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13199 (level-p
13200 (setq level-op (org-op-to-function (match-string 3 term)))
13201 `(,level-op level ,(string-to-number
13202 (match-string 4 term))))
13203 (prop-p
13204 (setq pn (match-string 5 term)
13205 po (match-string 6 term)
13206 pv (match-string 7 term)
13207 re-p (equal (string-to-char pv) ?{)
13208 str-p (equal (string-to-char pv) ?\")
13209 time-p (save-match-data
13210 (string-match "^\"[[<].*[]>]\"$" pv))
13211 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13212 (if time-p (setq pv (org-matcher-time pv)))
13213 (setq po (org-op-to-function po (if time-p 'time str-p)))
13214 (cond
13215 ((equal pn "CATEGORY")
13216 (setq gv '(get-text-property (point) 'org-category)))
13217 ((equal pn "TODO")
13218 (setq gv 'todo))
13220 (setq gv `(org-cached-entry-get nil ,pn))))
13221 (if re-p
13222 (if (eq po 'org<>)
13223 `(not (string-match ,pv (or ,gv "")))
13224 `(string-match ,pv (or ,gv "")))
13225 (if str-p
13226 `(,po (or ,gv "") ,pv)
13227 `(,po (string-to-number (or ,gv ""))
13228 ,(string-to-number pv) ))))
13229 (t `(member ,tag tags-list)))
13230 mm (if minus (list 'not mm) mm)
13231 term rest)
13232 (push mm tagsmatcher))
13233 (push (if (> (length tagsmatcher) 1)
13234 (cons 'and tagsmatcher)
13235 (car tagsmatcher))
13236 orlist)
13237 (setq tagsmatcher nil))
13238 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13239 (setq tagsmatcher
13240 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13241 ;; Make the todo matcher
13242 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13243 (setq todomatcher t)
13244 (setq orterms (org-split-string todomatch "|") orlist nil)
13245 (while (setq term (pop orterms))
13246 (while (string-match re term)
13247 (setq minus (and (match-end 1)
13248 (equal (match-string 1 term) "-"))
13249 kwd (match-string 2 term)
13250 re-p (equal (string-to-char kwd) ?{)
13251 term (substring term (match-end 0))
13252 mm (if re-p
13253 `(string-match ,(substring kwd 1 -1) todo)
13254 (list 'equal 'todo kwd))
13255 mm (if minus (list 'not mm) mm))
13256 (push mm todomatcher))
13257 (push (if (> (length todomatcher) 1)
13258 (cons 'and todomatcher)
13259 (car todomatcher))
13260 orlist)
13261 (setq todomatcher nil))
13262 (setq todomatcher (if (> (length orlist) 1)
13263 (cons 'or orlist) (car orlist))))
13265 ;; Return the string and lisp forms of the matcher
13266 (setq matcher (if todomatcher
13267 (list 'and tagsmatcher todomatcher)
13268 tagsmatcher))
13269 (when todo-only
13270 (setq matcher (list 'and '(member todo org-not-done-keywords)
13271 matcher)))
13272 (cons match0 matcher)))
13274 (defun org-op-to-function (op &optional stringp)
13275 "Turn an operator into the appropriate function."
13276 (setq op
13277 (cond
13278 ((equal op "<" ) '(< string< org-time<))
13279 ((equal op ">" ) '(> org-string> org-time>))
13280 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13281 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13282 ((member op '("=" "==")) '(= string= org-time=))
13283 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13284 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13286 (defun org<> (a b) (not (= a b)))
13287 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13288 (defun org-string>= (a b) (not (string< a b)))
13289 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13290 (defun org-string<> (a b) (not (string= a b)))
13291 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13292 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13293 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13294 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> 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) (org<> a b)))
13297 (defun org-2ft (s)
13298 "Convert S to a floating point time.
13299 If S is already a number, just return it. If it is a string, parse
13300 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13301 (cond
13302 ((numberp s) s)
13303 ((stringp s)
13304 (condition-case nil
13305 (float-time (apply 'encode-time (org-parse-time-string s)))
13306 (error 0.)))
13307 (t 0.)))
13309 (defun org-time-today ()
13310 "Time in seconds today at 0:00.
13311 Returns the float number of seconds since the beginning of the
13312 epoch to the beginning of today (00:00)."
13313 (float-time (apply 'encode-time
13314 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13316 (defun org-matcher-time (s)
13317 "Interpret a time comparison value."
13318 (save-match-data
13319 (cond
13320 ((string= s "<now>") (float-time))
13321 ((string= s "<today>") (org-time-today))
13322 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13323 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13324 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13325 (+ (org-time-today)
13326 (* (string-to-number (match-string 1 s))
13327 (cdr (assoc (match-string 2 s)
13328 '(("d" . 86400.0) ("w" . 604800.0)
13329 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13330 (t (org-2ft s)))))
13332 (defun org-match-any-p (re list)
13333 "Does re match any element of list?"
13334 (setq list (mapcar (lambda (x) (string-match re x)) list))
13335 (delq nil list))
13337 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13338 (defvar org-tags-overlay (make-overlay 1 1))
13339 (org-detach-overlay org-tags-overlay)
13341 (defun org-get-local-tags-at (&optional pos)
13342 "Get a list of tags defined in the current headline."
13343 (org-get-tags-at pos 'local))
13345 (defun org-get-local-tags ()
13346 "Get a list of tags defined in the current headline."
13347 (org-get-tags-at nil 'local))
13349 (defun org-get-tags-at (&optional pos local)
13350 "Get a list of all headline tags applicable at POS.
13351 POS defaults to point. If tags are inherited, the list contains
13352 the targets in the same sequence as the headlines appear, i.e.
13353 the tags of the current headline come last.
13354 When LOCAL is non-nil, only return tags from the current headline,
13355 ignore inherited ones."
13356 (interactive)
13357 (if (and org-trust-scanner-tags
13358 (or (not pos) (equal pos (point)))
13359 (not local))
13360 org-scanner-tags
13361 (let (tags ltags lastpos parent)
13362 (save-excursion
13363 (save-restriction
13364 (widen)
13365 (goto-char (or pos (point)))
13366 (save-match-data
13367 (catch 'done
13368 (condition-case nil
13369 (progn
13370 (org-back-to-heading t)
13371 (while (not (equal lastpos (point)))
13372 (setq lastpos (point))
13373 (when (looking-at
13374 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13375 (setq ltags (org-split-string
13376 (org-match-string-no-properties 1) ":"))
13377 (when parent
13378 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13379 (setq tags (append
13380 (if parent
13381 (org-remove-uninherited-tags ltags)
13382 ltags)
13383 tags)))
13384 (or org-use-tag-inheritance (throw 'done t))
13385 (if local (throw 'done t))
13386 (or (org-up-heading-safe) (error nil))
13387 (setq parent t)))
13388 (error nil)))))
13389 (if local
13390 tags
13391 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13393 (defun org-add-prop-inherited (s)
13394 (add-text-properties 0 (length s) '(inherited t) s)
13397 (defun org-toggle-tag (tag &optional onoff)
13398 "Toggle the tag TAG for the current line.
13399 If ONOFF is `on' or `off', don't toggle but set to this state."
13400 (let (res current)
13401 (save-excursion
13402 (org-back-to-heading t)
13403 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13404 (point-at-eol) t)
13405 (progn
13406 (setq current (match-string 1))
13407 (replace-match ""))
13408 (setq current ""))
13409 (setq current (nreverse (org-split-string current ":")))
13410 (cond
13411 ((eq onoff 'on)
13412 (setq res t)
13413 (or (member tag current) (push tag current)))
13414 ((eq onoff 'off)
13415 (or (not (member tag current)) (setq current (delete tag current))))
13416 (t (if (member tag current)
13417 (setq current (delete tag current))
13418 (setq res t)
13419 (push tag current))))
13420 (end-of-line 1)
13421 (if current
13422 (progn
13423 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13424 (org-set-tags nil t))
13425 (delete-horizontal-space))
13426 (run-hooks 'org-after-tags-change-hook))
13427 res))
13429 (defun org-align-tags-here (to-col)
13430 ;; Assumes that this is a headline
13431 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13432 (beginning-of-line 1)
13433 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13434 (< pos (match-beginning 2)))
13435 (progn
13436 (setq tags-l (- (match-end 2) (match-beginning 2)))
13437 (goto-char (match-beginning 1))
13438 (insert " ")
13439 (delete-region (point) (1+ (match-beginning 2)))
13440 (setq ncol (max (current-column)
13441 (1+ col)
13442 (if (> to-col 0)
13443 to-col
13444 (- (abs to-col) tags-l))))
13445 (setq p (point))
13446 (insert (make-string (- ncol (current-column)) ?\ ))
13447 (setq ncol (current-column))
13448 (when indent-tabs-mode (tabify p (point-at-eol)))
13449 (org-move-to-column (min ncol col) t))
13450 (goto-char pos))))
13452 (defun org-set-tags-command (&optional arg just-align)
13453 "Call the set-tags command for the current entry."
13454 (interactive "P")
13455 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13456 (org-set-tags arg just-align)
13457 (save-excursion
13458 (org-back-to-heading t)
13459 (org-set-tags arg just-align))))
13461 (defun org-set-tags-to (data)
13462 "Set the tags of the current entry to DATA, replacing the current tags.
13463 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13464 If DATA is nil or the empty string, any tags will be removed."
13465 (interactive "sTags: ")
13466 (setq data
13467 (cond
13468 ((eq data nil) "")
13469 ((equal data "") "")
13470 ((stringp data)
13471 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13472 ":"))
13473 ((listp data)
13474 (concat ":" (mapconcat 'identity data ":") ":"))
13475 (t nil)))
13476 (when data
13477 (save-excursion
13478 (org-back-to-heading t)
13479 (when (looking-at org-complex-heading-regexp)
13480 (if (match-end 5)
13481 (progn
13482 (goto-char (match-beginning 5))
13483 (insert data)
13484 (delete-region (point) (point-at-eol))
13485 (org-set-tags nil 'align))
13486 (goto-char (point-at-eol))
13487 (insert " " data)
13488 (org-set-tags nil 'align)))
13489 (beginning-of-line 1)
13490 (if (looking-at ".*?\\([ \t]+\\)$")
13491 (delete-region (match-beginning 1) (match-end 1))))))
13493 (defun org-align-all-tags ()
13494 "Align the tags i all headings."
13495 (interactive)
13496 (save-excursion
13497 (or (ignore-errors (org-back-to-heading t))
13498 (outline-next-heading))
13499 (if (org-at-heading-p)
13500 (org-set-tags t)
13501 (message "No headings"))))
13503 (defvar org-indent-indentation-per-level)
13504 (defun org-set-tags (&optional arg just-align)
13505 "Set the tags for the current headline.
13506 With prefix ARG, realign all tags in headings in the current buffer."
13507 (interactive "P")
13508 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13509 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13510 'region-start-level 'region))
13511 org-loop-over-headlines-in-active-region)
13512 (org-map-entries
13513 ;; We don't use ARG and JUST-ALIGN here these args are not
13514 ;; useful when looping over headlines
13515 `(org-set-tags)
13516 org-loop-over-headlines-in-active-region
13517 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13518 (let* ((re org-outline-regexp-bol)
13519 (current (unless arg (org-get-tags-string)))
13520 (col (current-column))
13521 (org-setting-tags t)
13522 table current-tags inherited-tags ; computed below when needed
13523 tags p0 c0 c1 rpl di tc level)
13524 (if arg
13525 (save-excursion
13526 (goto-char (point-min))
13527 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13528 (while (re-search-forward re nil t)
13529 (org-set-tags nil t)
13530 (end-of-line 1)))
13531 (message "All tags realigned to column %d" org-tags-column))
13532 (if just-align
13533 (setq tags current)
13534 ;; Get a new set of tags from the user
13535 (save-excursion
13536 (setq table (append org-tag-persistent-alist
13537 (or org-tag-alist (org-get-buffer-tags))
13538 (and
13539 org-complete-tags-always-offer-all-agenda-tags
13540 (org-global-tags-completion-table
13541 (org-agenda-files))))
13542 org-last-tags-completion-table table
13543 current-tags (org-split-string current ":")
13544 inherited-tags (nreverse
13545 (nthcdr (length current-tags)
13546 (nreverse (org-get-tags-at))))
13547 tags
13548 (if (or (eq t org-use-fast-tag-selection)
13549 (and org-use-fast-tag-selection
13550 (delq nil (mapcar 'cdr table))))
13551 (org-fast-tag-selection
13552 current-tags inherited-tags table
13553 (if org-fast-tag-selection-include-todo
13554 org-todo-key-alist))
13555 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13556 (org-trim
13557 (org-icompleting-read "Tags: "
13558 'org-tags-completion-function
13559 nil nil current 'org-tags-history))))))
13560 (while (string-match "[-+&]+" tags)
13561 ;; No boolean logic, just a list
13562 (setq tags (replace-match ":" t t tags))))
13564 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13566 (if org-tags-sort-function
13567 (setq tags (mapconcat 'identity
13568 (sort (org-split-string
13569 tags (org-re "[^[:alnum:]_@#%]+"))
13570 org-tags-sort-function) ":")))
13572 (if (string-match "\\`[\t ]*\\'" tags)
13573 (setq tags "")
13574 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13575 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13577 ;; Insert new tags at the correct column
13578 (beginning-of-line 1)
13579 (setq level (or (and (looking-at org-outline-regexp)
13580 (- (match-end 0) (point) 1))
13582 (cond
13583 ((and (equal current "") (equal tags "")))
13584 ((re-search-forward
13585 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13586 (point-at-eol) t)
13587 (if (equal tags "")
13588 (setq rpl "")
13589 (goto-char (match-beginning 0))
13590 (setq c0 (current-column)
13591 ;; compute offset for the case of org-indent-mode active
13592 di (if org-indent-mode
13593 (* (1- org-indent-indentation-per-level) (1- level))
13595 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13596 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13597 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13598 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13599 (replace-match rpl t t)
13600 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13601 tags)
13602 (t (error "Tags alignment failed")))
13603 (org-move-to-column col)
13604 (unless just-align
13605 (run-hooks 'org-after-tags-change-hook))))))
13607 (defun org-change-tag-in-region (beg end tag off)
13608 "Add or remove TAG for each entry in the region.
13609 This works in the agenda, and also in an org-mode buffer."
13610 (interactive
13611 (list (region-beginning) (region-end)
13612 (let ((org-last-tags-completion-table
13613 (if (derived-mode-p 'org-mode)
13614 (org-get-buffer-tags)
13615 (org-global-tags-completion-table))))
13616 (org-icompleting-read
13617 "Tag: " 'org-tags-completion-function nil nil nil
13618 'org-tags-history))
13619 (progn
13620 (message "[s]et or [r]emove? ")
13621 (equal (read-char-exclusive) ?r))))
13622 (if (fboundp 'deactivate-mark) (deactivate-mark))
13623 (let ((agendap (equal major-mode 'org-agenda-mode))
13624 l1 l2 m buf pos newhead (cnt 0))
13625 (goto-char end)
13626 (setq l2 (1- (org-current-line)))
13627 (goto-char beg)
13628 (setq l1 (org-current-line))
13629 (loop for l from l1 to l2 do
13630 (org-goto-line l)
13631 (setq m (get-text-property (point) 'org-hd-marker))
13632 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13633 (and agendap m))
13634 (setq buf (if agendap (marker-buffer m) (current-buffer))
13635 pos (if agendap m (point)))
13636 (with-current-buffer buf
13637 (save-excursion
13638 (save-restriction
13639 (goto-char pos)
13640 (setq cnt (1+ cnt))
13641 (org-toggle-tag tag (if off 'off 'on))
13642 (setq newhead (org-get-heading)))))
13643 (and agendap (org-agenda-change-all-lines newhead m))))
13644 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13646 (defun org-tags-completion-function (string predicate &optional flag)
13647 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13648 (confirm (lambda (x) (stringp (car x)))))
13649 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13650 (setq s1 (match-string 1 string)
13651 s2 (match-string 2 string))
13652 (setq s1 "" s2 string))
13653 (cond
13654 ((eq flag nil)
13655 ;; try completion
13656 (setq rtn (try-completion s2 ctable confirm))
13657 (if (stringp rtn)
13658 (setq rtn
13659 (concat s1 s2 (substring rtn (length s2))
13660 (if (and org-add-colon-after-tag-completion
13661 (assoc rtn ctable))
13662 ":" ""))))
13663 rtn)
13664 ((eq flag t)
13665 ;; all-completions
13666 (all-completions s2 ctable confirm)
13668 ((eq flag 'lambda)
13669 ;; exact match?
13670 (assoc s2 ctable)))
13673 (defun org-fast-tag-insert (kwd tags face &optional end)
13674 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13675 (insert (format "%-12s" (concat kwd ":"))
13676 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13677 (or end "")))
13679 (defun org-fast-tag-show-exit (flag)
13680 (save-excursion
13681 (org-goto-line 3)
13682 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13683 (replace-match ""))
13684 (when flag
13685 (end-of-line 1)
13686 (org-move-to-column (- (window-width) 19) t)
13687 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13689 (defun org-set-current-tags-overlay (current prefix)
13690 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13691 (if (featurep 'xemacs)
13692 (org-overlay-display org-tags-overlay (concat prefix s)
13693 'secondary-selection)
13694 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13695 (org-overlay-display org-tags-overlay (concat prefix s)))))
13697 (defvar org-last-tag-selection-key nil)
13698 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13699 "Fast tag selection with single keys.
13700 CURRENT is the current list of tags in the headline, INHERITED is the
13701 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13702 possibly with grouping information. TODO-TABLE is a similar table with
13703 TODO keywords, should these have keys assigned to them.
13704 If the keys are nil, a-z are automatically assigned.
13705 Returns the new tags string, or nil to not change the current settings."
13706 (let* ((fulltable (append table todo-table))
13707 (maxlen (apply 'max (mapcar
13708 (lambda (x)
13709 (if (stringp (car x)) (string-width (car x)) 0))
13710 fulltable)))
13711 (buf (current-buffer))
13712 (expert (eq org-fast-tag-selection-single-key 'expert))
13713 (buffer-tags nil)
13714 (fwidth (+ maxlen 3 1 3))
13715 (ncol (/ (- (window-width) 4) fwidth))
13716 (i-face 'org-done)
13717 (c-face 'org-todo)
13718 tg cnt e c char c1 c2 ntable tbl rtn
13719 ov-start ov-end ov-prefix
13720 (exit-after-next org-fast-tag-selection-single-key)
13721 (done-keywords org-done-keywords)
13722 groups ingroup)
13723 (save-excursion
13724 (beginning-of-line 1)
13725 (if (looking-at
13726 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13727 (setq ov-start (match-beginning 1)
13728 ov-end (match-end 1)
13729 ov-prefix "")
13730 (setq ov-start (1- (point-at-eol))
13731 ov-end (1+ ov-start))
13732 (skip-chars-forward "^\n\r")
13733 (setq ov-prefix
13734 (concat
13735 (buffer-substring (1- (point)) (point))
13736 (if (> (current-column) org-tags-column)
13738 (make-string (- org-tags-column (current-column)) ?\ ))))))
13739 (move-overlay org-tags-overlay ov-start ov-end)
13740 (save-window-excursion
13741 (if expert
13742 (set-buffer (get-buffer-create " *Org tags*"))
13743 (delete-other-windows)
13744 (split-window-vertically)
13745 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13746 (erase-buffer)
13747 (org-set-local 'org-done-keywords done-keywords)
13748 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13749 (org-fast-tag-insert "Current" current c-face "\n\n")
13750 (org-fast-tag-show-exit exit-after-next)
13751 (org-set-current-tags-overlay current ov-prefix)
13752 (setq tbl fulltable char ?a cnt 0)
13753 (while (setq e (pop tbl))
13754 (cond
13755 ((equal (car e) :startgroup)
13756 (push '() groups) (setq ingroup t)
13757 (when (not (= cnt 0))
13758 (setq cnt 0)
13759 (insert "\n"))
13760 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13761 ((equal (car e) :endgroup)
13762 (setq ingroup nil cnt 0)
13763 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13764 ((equal e '(:newline))
13765 (when (not (= cnt 0))
13766 (setq cnt 0)
13767 (insert "\n")
13768 (setq e (car tbl))
13769 (while (equal (car tbl) '(:newline))
13770 (insert "\n")
13771 (setq tbl (cdr tbl)))))
13773 (setq tg (copy-sequence (car e)) c2 nil)
13774 (if (cdr e)
13775 (setq c (cdr e))
13776 ;; automatically assign a character.
13777 (setq c1 (string-to-char
13778 (downcase (substring
13779 tg (if (= (string-to-char tg) ?@) 1 0)))))
13780 (if (or (rassoc c1 ntable) (rassoc c1 table))
13781 (while (or (rassoc char ntable) (rassoc char table))
13782 (setq char (1+ char)))
13783 (setq c2 c1))
13784 (setq c (or c2 char)))
13785 (if ingroup (push tg (car groups)))
13786 (setq tg (org-add-props tg nil 'face
13787 (cond
13788 ((not (assoc tg table))
13789 (org-get-todo-face tg))
13790 ((member tg current) c-face)
13791 ((member tg inherited) i-face)
13792 (t nil))))
13793 (if (and (= cnt 0) (not ingroup)) (insert " "))
13794 (insert "[" c "] " tg (make-string
13795 (- fwidth 4 (length tg)) ?\ ))
13796 (push (cons tg c) ntable)
13797 (when (= (setq cnt (1+ cnt)) ncol)
13798 (insert "\n")
13799 (if ingroup (insert " "))
13800 (setq cnt 0)))))
13801 (setq ntable (nreverse ntable))
13802 (insert "\n")
13803 (goto-char (point-min))
13804 (if (not expert) (org-fit-window-to-buffer))
13805 (setq rtn
13806 (catch 'exit
13807 (while t
13808 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13809 (if (not groups) "no " "")
13810 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13811 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13812 (setq org-last-tag-selection-key c)
13813 (cond
13814 ((= c ?\r) (throw 'exit t))
13815 ((= c ?!)
13816 (setq groups (not groups))
13817 (goto-char (point-min))
13818 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13819 ((= c ?\C-c)
13820 (if (not expert)
13821 (org-fast-tag-show-exit
13822 (setq exit-after-next (not exit-after-next)))
13823 (setq expert nil)
13824 (delete-other-windows)
13825 (set-window-buffer (split-window-vertically) " *Org tags*")
13826 (org-switch-to-buffer-other-window " *Org tags*")
13827 (org-fit-window-to-buffer)))
13828 ((or (= c ?\C-g)
13829 (and (= c ?q) (not (rassoc c ntable))))
13830 (org-detach-overlay org-tags-overlay)
13831 (setq quit-flag t))
13832 ((= c ?\ )
13833 (setq current nil)
13834 (if exit-after-next (setq exit-after-next 'now)))
13835 ((= c ?\t)
13836 (condition-case nil
13837 (setq tg (org-icompleting-read
13838 "Tag: "
13839 (or buffer-tags
13840 (with-current-buffer buf
13841 (org-get-buffer-tags)))))
13842 (quit (setq tg "")))
13843 (when (string-match "\\S-" tg)
13844 (add-to-list 'buffer-tags (list tg))
13845 (if (member tg current)
13846 (setq current (delete tg current))
13847 (push tg current)))
13848 (if exit-after-next (setq exit-after-next 'now)))
13849 ((setq e (rassoc c todo-table) tg (car e))
13850 (with-current-buffer buf
13851 (save-excursion (org-todo tg)))
13852 (if exit-after-next (setq exit-after-next 'now)))
13853 ((setq e (rassoc c ntable) tg (car e))
13854 (if (member tg current)
13855 (setq current (delete tg current))
13856 (loop for g in groups do
13857 (if (member tg g)
13858 (mapc (lambda (x)
13859 (setq current (delete x current)))
13860 g)))
13861 (push tg current))
13862 (if exit-after-next (setq exit-after-next 'now))))
13864 ;; Create a sorted list
13865 (setq current
13866 (sort current
13867 (lambda (a b)
13868 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13869 (if (eq exit-after-next 'now) (throw 'exit t))
13870 (goto-char (point-min))
13871 (beginning-of-line 2)
13872 (delete-region (point) (point-at-eol))
13873 (org-fast-tag-insert "Current" current c-face)
13874 (org-set-current-tags-overlay current ov-prefix)
13875 (while (re-search-forward
13876 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13877 (setq tg (match-string 1))
13878 (add-text-properties
13879 (match-beginning 1) (match-end 1)
13880 (list 'face
13881 (cond
13882 ((member tg current) c-face)
13883 ((member tg inherited) i-face)
13884 (t (get-text-property (match-beginning 1) 'face))))))
13885 (goto-char (point-min)))))
13886 (org-detach-overlay org-tags-overlay)
13887 (if rtn
13888 (mapconcat 'identity current ":")
13889 nil))))
13891 (defun org-get-tags-string ()
13892 "Get the TAGS string in the current headline."
13893 (unless (org-at-heading-p t)
13894 (error "Not on a heading"))
13895 (save-excursion
13896 (beginning-of-line 1)
13897 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13898 (org-match-string-no-properties 1)
13899 "")))
13901 (defun org-get-tags ()
13902 "Get the list of tags specified in the current headline."
13903 (org-split-string (org-get-tags-string) ":"))
13905 (defun org-get-buffer-tags ()
13906 "Get a table of all tags used in the buffer, for completion."
13907 (let (tags)
13908 (save-excursion
13909 (goto-char (point-min))
13910 (while (re-search-forward
13911 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13912 (when (equal (char-after (point-at-bol 0)) ?*)
13913 (mapc (lambda (x) (add-to-list 'tags x))
13914 (org-split-string (org-match-string-no-properties 1) ":")))))
13915 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13916 (mapcar 'list tags)))
13918 ;;;; The mapping API
13920 ;;;###autoload
13921 (defun org-map-entries (func &optional match scope &rest skip)
13922 "Call FUNC at each headline selected by MATCH in SCOPE.
13924 FUNC is a function or a lisp form. The function will be called without
13925 arguments, with the cursor positioned at the beginning of the headline.
13926 The return values of all calls to the function will be collected and
13927 returned as a list.
13929 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13930 does not need to preserve point. After evaluation, the cursor will be
13931 moved to the end of the line (presumably of the headline of the
13932 processed entry) and search continues from there. Under some
13933 circumstances, this may not produce the wanted results. For example,
13934 if you have removed (e.g. archived) the current (sub)tree it could
13935 mean that the next entry will be skipped entirely. In such cases, you
13936 can specify the position from where search should continue by making
13937 FUNC set the variable `org-map-continue-from' to the desired buffer
13938 position.
13940 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13941 Only headlines that are matched by this query will be considered during
13942 the iteration. When MATCH is nil or t, all headlines will be
13943 visited by the iteration.
13945 SCOPE determines the scope of this command. It can be any of:
13947 nil The current buffer, respecting the restriction if any
13948 tree The subtree started with the entry at point
13949 region The entries within the active region, if any
13950 region-start-level
13951 The entries within the active region, but only those at
13952 the same level than the first one.
13953 file The current buffer, without restriction
13954 file-with-archives
13955 The current buffer, and any archives associated with it
13956 agenda All agenda files
13957 agenda-with-archives
13958 All agenda files with any archive files associated with them
13959 \(file1 file2 ...)
13960 If this is a list, all files in the list will be scanned
13962 The remaining args are treated as settings for the skipping facilities of
13963 the scanner. The following items can be given here:
13965 archive skip trees with the archive tag.
13966 comment skip trees with the COMMENT keyword
13967 function or Emacs Lisp form:
13968 will be used as value for `org-agenda-skip-function', so whenever
13969 the function returns t, FUNC will not be called for that
13970 entry and search will continue from the point where the
13971 function leaves it.
13973 If your function needs to retrieve the tags including inherited tags
13974 at the *current* entry, you can use the value of the variable
13975 `org-scanner-tags' which will be much faster than getting the value
13976 with `org-get-tags-at'. If your function gets properties with
13977 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13978 to t around the call to `org-entry-properties' to get the same speedup.
13979 Note that if your function moves around to retrieve tags and properties at
13980 a *different* entry, you cannot use these techniques."
13981 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13982 (not (org-region-active-p)))
13983 (let* ((org-agenda-archives-mode nil) ; just to make sure
13984 (org-agenda-skip-archived-trees (memq 'archive skip))
13985 (org-agenda-skip-comment-trees (memq 'comment skip))
13986 (org-agenda-skip-function
13987 (car (org-delete-all '(comment archive) skip)))
13988 (org-tags-match-list-sublevels t)
13989 (start-level (eq scope 'region-start-level))
13990 matcher file res
13991 org-todo-keywords-for-agenda
13992 org-done-keywords-for-agenda
13993 org-todo-keyword-alist-for-agenda
13994 org-drawers-for-agenda
13995 org-tag-alist-for-agenda
13996 todo-only)
13998 (cond
13999 ((eq match t) (setq matcher t))
14000 ((eq match nil) (setq matcher t))
14001 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14003 (save-excursion
14004 (save-restriction
14005 (cond ((eq scope 'tree)
14006 (org-back-to-heading t)
14007 (org-narrow-to-subtree)
14008 (setq scope nil))
14009 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14010 (org-region-active-p))
14011 ;; If needed, set start-level to a string like "2"
14012 (when start-level
14013 (save-excursion
14014 (goto-char (region-beginning))
14015 (unless (org-at-heading-p) (outline-next-heading))
14016 (setq start-level (org-current-level))))
14017 (narrow-to-region (region-beginning)
14018 (save-excursion
14019 (goto-char (region-end))
14020 (unless (and (bolp) (org-at-heading-p))
14021 (outline-next-heading))
14022 (point)))
14023 (setq scope nil)))
14025 (if (not scope)
14026 (progn
14027 (org-prepare-agenda-buffers
14028 (list (buffer-file-name (current-buffer))))
14029 (setq res (org-scan-tags func matcher todo-only start-level)))
14030 ;; Get the right scope
14031 (cond
14032 ((and scope (listp scope) (symbolp (car scope)))
14033 (setq scope (eval scope)))
14034 ((eq scope 'agenda)
14035 (setq scope (org-agenda-files t)))
14036 ((eq scope 'agenda-with-archives)
14037 (setq scope (org-agenda-files t))
14038 (setq scope (org-add-archive-files scope)))
14039 ((eq scope 'file)
14040 (setq scope (list (buffer-file-name))))
14041 ((eq scope 'file-with-archives)
14042 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14043 (org-prepare-agenda-buffers scope)
14044 (while (setq file (pop scope))
14045 (with-current-buffer (org-find-base-buffer-visiting file)
14046 (save-excursion
14047 (save-restriction
14048 (widen)
14049 (goto-char (point-min))
14050 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14051 res)))
14053 ;;;; Properties
14055 ;;; Setting and retrieving properties
14057 (defconst org-special-properties
14058 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14059 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
14060 "The special properties valid in Org-mode.
14062 These are properties that are not defined in the property drawer,
14063 but in some other way.")
14065 (defconst org-default-properties
14066 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14067 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14068 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14069 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14070 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14071 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14072 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14073 "Some properties that are used by Org-mode for various purposes.
14074 Being in this list makes sure that they are offered for completion.")
14076 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14077 "Regular expression matching the first line of a property drawer.")
14079 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14080 "Regular expression matching the last line of a property drawer.")
14082 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14083 "Regular expression matching the first line of a property drawer.")
14085 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14086 "Regular expression matching the first line of a property drawer.")
14088 (defconst org-property-drawer-re
14089 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14090 org-property-end-re "\\)\n?")
14091 "Matches an entire property drawer.")
14093 (defconst org-clock-drawer-re
14094 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14095 org-property-end-re "\\)\n?")
14096 "Matches an entire clock drawer.")
14098 (defsubst org-re-property (property)
14099 "Return a regexp matching PROPERTY.
14100 Match group 1 will be set to the value "
14101 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14103 (defun org-property-action ()
14104 "Do an action on properties."
14105 (interactive)
14106 (let (c)
14107 (org-at-property-p)
14108 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14109 (setq c (read-char-exclusive))
14110 (cond
14111 ((equal c ?s)
14112 (call-interactively 'org-set-property))
14113 ((equal c ?d)
14114 (call-interactively 'org-delete-property))
14115 ((equal c ?D)
14116 (call-interactively 'org-delete-property-globally))
14117 ((equal c ?c)
14118 (call-interactively 'org-compute-property-at-point))
14119 (t (error "No such property action %c" c)))))
14121 (defun org-set-effort (&optional value)
14122 "Set the effort property of the current entry.
14123 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14124 allowed value."
14125 (interactive "P")
14126 (if (equal value 0) (setq value 10))
14127 (let* ((completion-ignore-case t)
14128 (prop org-effort-property)
14129 (cur (org-entry-get nil prop))
14130 (allowed (org-property-get-allowed-values nil prop 'table))
14131 (existing (mapcar 'list (org-property-values prop)))
14133 (val (cond
14134 ((stringp value) value)
14135 ((and allowed (integerp value))
14136 (or (car (nth (1- value) allowed))
14137 (car (org-last allowed))))
14138 (allowed
14139 (message "Select 1-9,0, [RET%s]: %s"
14140 (if cur (concat "=" cur) "")
14141 (mapconcat 'car allowed " "))
14142 (setq rpl (read-char-exclusive))
14143 (if (equal rpl ?\r)
14145 (setq rpl (- rpl ?0))
14146 (if (equal rpl 0) (setq rpl 10))
14147 (if (and (> rpl 0) (<= rpl (length allowed)))
14148 (car (nth (1- rpl) allowed))
14149 (org-completing-read "Effort: " allowed nil))))
14151 (let (org-completion-use-ido org-completion-use-iswitchb)
14152 (org-completing-read
14153 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14154 (concat "[" cur "]") "")
14155 ": ")
14156 existing nil nil "" nil cur))))))
14157 (unless (equal (org-entry-get nil prop) val)
14158 (org-entry-put nil prop val))
14159 (message "%s is now %s" prop val)))
14161 (defun org-at-property-p ()
14162 "Is cursor inside a property drawer?"
14163 (save-excursion
14164 (beginning-of-line 1)
14165 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14166 (save-match-data ;; Used by calling procedures
14167 (let ((p (point))
14168 (range (unless (org-before-first-heading-p)
14169 (org-get-property-block))))
14170 (and range (<= (car range) p) (< p (cdr range))))))))
14172 (defun org-get-property-block (&optional beg end force)
14173 "Return the (beg . end) range of the body of the property drawer.
14174 BEG and END can be beginning and end of subtree, if not given
14175 they will be found.
14176 If the drawer does not exist and FORCE is non-nil, create the drawer."
14177 (catch 'exit
14178 (save-excursion
14179 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14180 (end (or end (progn (outline-next-heading) (point)))))
14181 (goto-char beg)
14182 (if (re-search-forward org-property-start-re end t)
14183 (setq beg (1+ (match-end 0)))
14184 (if force
14185 (save-excursion
14186 (org-insert-property-drawer)
14187 (setq end (progn (outline-next-heading) (point))))
14188 (throw 'exit nil))
14189 (goto-char beg)
14190 (if (re-search-forward org-property-start-re end t)
14191 (setq beg (1+ (match-end 0)))))
14192 (if (re-search-forward org-property-end-re end t)
14193 (setq end (match-beginning 0))
14194 (or force (throw 'exit nil))
14195 (goto-char beg)
14196 (setq end beg)
14197 (org-indent-line-function)
14198 (insert ":END:\n"))
14199 (cons beg end)))))
14201 (defun org-entry-properties (&optional pom which specific)
14202 "Get all properties of the entry at point-or-marker POM.
14203 This includes the TODO keyword, the tags, time strings for deadline,
14204 scheduled, and clocking, and any additional properties defined in the
14205 entry. The return value is an alist, keys may occur multiple times
14206 if the property key was used several times.
14207 POM may also be nil, in which case the current entry is used.
14208 If WHICH is nil or `all', get all properties. If WHICH is
14209 `special' or `standard', only get that subclass. If WHICH
14210 is a string only get exactly this property. SPECIFIC can be a string, the
14211 specific property we are interested in. Specifying it can speed
14212 things up because then unnecessary parsing is avoided."
14213 (setq which (or which 'all))
14214 (org-with-point-at pom
14215 (let ((clockstr (substring org-clock-string 0 -1))
14216 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14217 (case-fold-search nil)
14218 beg end range props sum-props key key1 value string clocksum)
14219 (save-excursion
14220 (when (condition-case nil
14221 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14222 (error nil))
14223 (setq beg (point))
14224 (setq sum-props (get-text-property (point) 'org-summaries))
14225 (setq clocksum (get-text-property (point) :org-clock-minutes))
14226 (outline-next-heading)
14227 (setq end (point))
14228 (when (memq which '(all special))
14229 ;; Get the special properties, like TODO and tags
14230 (goto-char beg)
14231 (when (and (or (not specific) (string= specific "TODO"))
14232 (looking-at org-todo-line-regexp) (match-end 2))
14233 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14234 (when (and (or (not specific) (string= specific "PRIORITY"))
14235 (looking-at org-priority-regexp))
14236 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14237 (when (or (not specific) (string= specific "FILE"))
14238 (push (cons "FILE" buffer-file-name) props))
14239 (when (and (or (not specific) (string= specific "TAGS"))
14240 (setq value (org-get-tags-string))
14241 (string-match "\\S-" value))
14242 (push (cons "TAGS" value) props))
14243 (when (and (or (not specific) (string= specific "ALLTAGS"))
14244 (setq value (org-get-tags-at)))
14245 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14246 ":"))
14247 props))
14248 (when (or (not specific) (string= specific "BLOCKED"))
14249 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14250 (when (or (not specific)
14251 (member specific
14252 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14253 "TIMESTAMP" "TIMESTAMP_IA")))
14254 (catch 'match
14255 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14256 (setq key (if (match-end 1)
14257 (substring (org-match-string-no-properties 1)
14258 0 -1))
14259 string (if (equal key clockstr)
14260 (org-no-properties
14261 (org-trim
14262 (buffer-substring
14263 (match-beginning 3) (goto-char
14264 (point-at-eol)))))
14265 (substring (org-match-string-no-properties 3)
14266 1 -1)))
14267 ;; Get the correct property name from the key. This is
14268 ;; necessary if the user has configured time keywords.
14269 (setq key1 (concat key ":"))
14270 (cond
14271 ((not key)
14272 (setq key
14273 (if (= (char-after (match-beginning 3)) ?\[)
14274 "TIMESTAMP_IA" "TIMESTAMP")))
14275 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14276 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14277 ((equal key1 org-closed-string) (setq key "CLOSED"))
14278 ((equal key1 org-clock-string) (setq key "CLOCK")))
14279 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14280 (progn
14281 (push (cons key string) props)
14282 ;; no need to search further if match is found
14283 (throw 'match t))
14284 (when (or (equal key "CLOCK") (not (assoc key props)))
14285 (push (cons key string) props))))))
14288 (when (memq which '(all standard))
14289 ;; Get the standard properties, like :PROP: ...
14290 (setq range (org-get-property-block beg end))
14291 (when range
14292 (goto-char (car range))
14293 (while (re-search-forward
14294 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14295 (cdr range) t)
14296 (setq key (org-match-string-no-properties 1)
14297 value (org-trim (or (org-match-string-no-properties 2) "")))
14298 (unless (member key excluded)
14299 (push (cons key (or value "")) props)))))
14300 (if clocksum
14301 (push (cons "CLOCKSUM"
14302 (org-columns-number-to-string (/ (float clocksum) 60.)
14303 'add_times))
14304 props))
14305 (unless (assoc "CATEGORY" props)
14306 (push (cons "CATEGORY" (org-get-category)) props))
14307 (append sum-props (nreverse props)))))))
14309 (defun org-entry-get (pom property &optional inherit literal-nil)
14310 "Get value of PROPERTY for entry at point-or-marker POM.
14311 If INHERIT is non-nil and the entry does not have the property,
14312 then also check higher levels of the hierarchy.
14313 If INHERIT is the symbol `selective', use inheritance only if the setting
14314 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14315 If the property is present but empty, the return value is the empty string.
14316 If the property is not present at all, nil is returned.
14318 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14319 do not interpret it as the list atom nil. This is used for inheritance
14320 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14321 (org-with-point-at pom
14322 (if (and inherit (if (eq inherit 'selective)
14323 (org-property-inherit-p property)
14325 (org-entry-get-with-inheritance property literal-nil)
14326 (if (member property org-special-properties)
14327 ;; We need a special property. Use `org-entry-properties' to
14328 ;; retrieve it, but specify the wanted property
14329 (cdr (assoc property (org-entry-properties nil 'special property)))
14330 (let ((range (unless (org-before-first-heading-p)
14331 (org-get-property-block)))
14332 (props (list (or (assoc property org-file-properties)
14333 (assoc property org-global-properties)
14334 (assoc property org-global-properties-fixed))))
14335 val)
14336 (flet ((ap (key)
14337 (when (re-search-forward
14338 (org-re-property key) (cdr range) t)
14339 (setq props
14340 (org-update-property-plist
14342 (if (match-end 1)
14343 (org-match-string-no-properties 1) "")
14344 props)))))
14345 (when (and range (goto-char (car range)))
14346 (ap property)
14347 (goto-char (car range))
14348 (while (ap (concat property "+")))
14349 (setq val (cdr (assoc property props)))
14350 (when val (if literal-nil val (org-not-nil val))))))))))
14352 (defun org-property-or-variable-value (var &optional inherit)
14353 "Check if there is a property fixing the value of VAR.
14354 If yes, return this value. If not, return the current value of the variable."
14355 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14356 (if (and prop (stringp prop) (string-match "\\S-" prop))
14357 (read prop)
14358 (symbol-value var))))
14360 (defun org-entry-delete (pom property)
14361 "Delete the property PROPERTY from entry at point-or-marker POM."
14362 (org-with-point-at pom
14363 (if (member property org-special-properties)
14364 nil ; cannot delete these properties.
14365 (let ((range (org-get-property-block)))
14366 (if (and range
14367 (goto-char (car range))
14368 (re-search-forward
14369 (org-re-property property)
14370 (cdr range) t))
14371 (progn
14372 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14374 nil)))))
14376 ;; Multi-values properties are properties that contain multiple values
14377 ;; These values are assumed to be single words, separated by whitespace.
14378 (defun org-entry-add-to-multivalued-property (pom property value)
14379 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14380 (let* ((old (org-entry-get pom property))
14381 (values (and old (org-split-string old "[ \t]"))))
14382 (setq value (org-entry-protect-space value))
14383 (unless (member value values)
14384 (setq values (cons value values))
14385 (org-entry-put pom property
14386 (mapconcat 'identity values " ")))))
14388 (defun org-entry-remove-from-multivalued-property (pom property value)
14389 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14390 (let* ((old (org-entry-get pom property))
14391 (values (and old (org-split-string old "[ \t]"))))
14392 (setq value (org-entry-protect-space value))
14393 (when (member value values)
14394 (setq values (delete value values))
14395 (org-entry-put pom property
14396 (mapconcat 'identity values " ")))))
14398 (defun org-entry-member-in-multivalued-property (pom property value)
14399 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14400 (let* ((old (org-entry-get pom property))
14401 (values (and old (org-split-string old "[ \t]"))))
14402 (setq value (org-entry-protect-space value))
14403 (member value values)))
14405 (defun org-entry-get-multivalued-property (pom property)
14406 "Return a list of values in a multivalued property."
14407 (let* ((value (org-entry-get pom property))
14408 (values (and value (org-split-string value "[ \t]"))))
14409 (mapcar 'org-entry-restore-space values)))
14411 (defun org-entry-put-multivalued-property (pom property &rest values)
14412 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14413 VALUES should be a list of strings. Spaces will be protected."
14414 (org-entry-put pom property
14415 (mapconcat 'org-entry-protect-space values " "))
14416 (let* ((value (org-entry-get pom property))
14417 (values (and value (org-split-string value "[ \t]"))))
14418 (mapcar 'org-entry-restore-space values)))
14420 (defun org-entry-protect-space (s)
14421 "Protect spaces and newline in string S."
14422 (while (string-match " " s)
14423 (setq s (replace-match "%20" t t s)))
14424 (while (string-match "\n" s)
14425 (setq s (replace-match "%0A" t t s)))
14428 (defun org-entry-restore-space (s)
14429 "Restore spaces and newline in string S."
14430 (while (string-match "%20" s)
14431 (setq s (replace-match " " t t s)))
14432 (while (string-match "%0A" s)
14433 (setq s (replace-match "\n" t t s)))
14436 (defvar org-entry-property-inherited-from (make-marker)
14437 "Marker pointing to the entry from where a property was inherited.
14438 Each call to `org-entry-get-with-inheritance' will set this marker to the
14439 location of the entry where the inheritance search matched. If there was
14440 no match, the marker will point nowhere.
14441 Note that also `org-entry-get' calls this function, if the INHERIT flag
14442 is set.")
14444 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14445 "Get entry property, and search higher levels if not present.
14446 The search will stop at the first ancestor which has the property defined.
14447 If the value found is \"nil\", return nil to show that the property
14448 should be considered as undefined (this is the meaning of nil here).
14449 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14450 (move-marker org-entry-property-inherited-from nil)
14451 (let (tmp)
14452 (unless (org-before-first-heading-p)
14453 (save-excursion
14454 (save-restriction
14455 (widen)
14456 (catch 'ex
14457 (while t
14458 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14459 (org-back-to-heading t)
14460 (move-marker org-entry-property-inherited-from (point))
14461 (throw 'ex tmp))
14462 (or (org-up-heading-safe) (throw 'ex nil)))))))
14463 (setq tmp (or tmp
14464 (cdr (assoc property org-file-properties))
14465 (cdr (assoc property org-global-properties))
14466 (cdr (assoc property org-global-properties-fixed))))
14467 (if literal-nil tmp (org-not-nil tmp))))
14469 (defvar org-property-changed-functions nil
14470 "Hook called when the value of a property has changed.
14471 Each hook function should accept two arguments, the name of the property
14472 and the new value.")
14474 (defun org-entry-put (pom property value)
14475 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14476 (org-with-point-at pom
14477 (org-back-to-heading t)
14478 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14479 range)
14480 (cond
14481 ((equal property "TODO")
14482 (when (and (stringp value) (string-match "\\S-" value)
14483 (not (member value org-todo-keywords-1)))
14484 (error "\"%s\" is not a valid TODO state" value))
14485 (if (or (not value)
14486 (not (string-match "\\S-" value)))
14487 (setq value 'none))
14488 (org-todo value)
14489 (org-set-tags nil 'align))
14490 ((equal property "PRIORITY")
14491 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14492 (string-to-char value) ?\ ))
14493 (org-set-tags nil 'align))
14494 ((equal property "SCHEDULED")
14495 (if (re-search-forward org-scheduled-time-regexp end t)
14496 (cond
14497 ((eq value 'earlier) (org-timestamp-change -1 'day))
14498 ((eq value 'later) (org-timestamp-change 1 'day))
14499 (t (call-interactively 'org-schedule)))
14500 (call-interactively 'org-schedule)))
14501 ((equal property "DEADLINE")
14502 (if (re-search-forward org-deadline-time-regexp end t)
14503 (cond
14504 ((eq value 'earlier) (org-timestamp-change -1 'day))
14505 ((eq value 'later) (org-timestamp-change 1 'day))
14506 (t (call-interactively 'org-deadline)))
14507 (call-interactively 'org-deadline)))
14508 ((member property org-special-properties)
14509 (error "The %s property can not yet be set with `org-entry-put'"
14510 property))
14511 (t ; a non-special property
14512 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14513 (setq range (org-get-property-block beg end 'force))
14514 (goto-char (car range))
14515 (if (re-search-forward
14516 (org-re-property property) (cdr range) t)
14517 (progn
14518 (delete-region (match-beginning 0) (match-end 0))
14519 (goto-char (match-beginning 0)))
14520 (goto-char (cdr range))
14521 (insert "\n")
14522 (backward-char 1)
14523 (org-indent-line-function))
14524 (insert ":" property ":")
14525 (and value (insert " " value))
14526 (org-indent-line-function)))))
14527 (run-hook-with-args 'org-property-changed-functions property value)))
14529 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14530 "Get all property keys in the current buffer.
14531 With INCLUDE-SPECIALS, also list the special properties that reflect things
14532 like tags and TODO state.
14533 With INCLUDE-DEFAULTS, also include properties that has special meaning
14534 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14535 and others.
14536 With INCLUDE-COLUMNS, also include property names given in COLUMN
14537 formats in the current buffer."
14538 (let (rtn range cfmt s p)
14539 (save-excursion
14540 (save-restriction
14541 (widen)
14542 (goto-char (point-min))
14543 (while (re-search-forward org-property-start-re nil t)
14544 (setq range (org-get-property-block))
14545 (goto-char (car range))
14546 (while (re-search-forward
14547 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14548 (cdr range) t)
14549 (add-to-list 'rtn (org-match-string-no-properties 1)))
14550 (outline-next-heading))))
14552 (when include-specials
14553 (setq rtn (append org-special-properties rtn)))
14555 (when include-defaults
14556 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14557 (add-to-list 'rtn org-effort-property))
14559 (when include-columns
14560 (save-excursion
14561 (save-restriction
14562 (widen)
14563 (goto-char (point-min))
14564 (while (re-search-forward
14565 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14566 nil t)
14567 (setq cfmt (match-string 2) s 0)
14568 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14569 cfmt s)
14570 (setq s (match-end 0)
14571 p (match-string 1 cfmt))
14572 (unless (or (equal p "ITEM")
14573 (member p org-special-properties))
14574 (add-to-list 'rtn (match-string 1 cfmt))))))))
14576 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14578 (defun org-property-values (key)
14579 "Return a list of all values of property KEY in the current buffer."
14580 (save-excursion
14581 (save-restriction
14582 (widen)
14583 (goto-char (point-min))
14584 (let ((re (org-re-property key))
14585 values)
14586 (while (re-search-forward re nil t)
14587 (add-to-list 'values (org-trim (match-string 1))))
14588 (delete "" values)))))
14590 (defun org-insert-property-drawer ()
14591 "Insert a property drawer into the current entry."
14592 (org-back-to-heading t)
14593 (looking-at org-outline-regexp)
14594 (let ((indent (if org-adapt-indentation
14595 (- (match-end 0) (match-beginning 0))
14597 (beg (point))
14598 (re (concat "^[ \t]*" org-keyword-time-regexp))
14599 end hiddenp)
14600 (outline-next-heading)
14601 (setq end (point))
14602 (goto-char beg)
14603 (while (re-search-forward re end t))
14604 (setq hiddenp (outline-invisible-p))
14605 (end-of-line 1)
14606 (and (equal (char-after) ?\n) (forward-char 1))
14607 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14608 (if (member (match-string 1) '("CLOCK:" ":END:"))
14609 ;; just skip this line
14610 (beginning-of-line 2)
14611 ;; Drawer start, find the end
14612 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14613 (beginning-of-line 1)))
14614 (org-skip-over-state-notes)
14615 (skip-chars-backward " \t\n\r")
14616 (if (eq (char-before) ?*) (forward-char 1))
14617 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14618 (beginning-of-line 0)
14619 (org-indent-to-column indent)
14620 (beginning-of-line 2)
14621 (org-indent-to-column indent)
14622 (beginning-of-line 0)
14623 (if hiddenp
14624 (save-excursion
14625 (org-back-to-heading t)
14626 (hide-entry))
14627 (org-flag-drawer t))))
14629 (defun org-insert-drawer (&optional arg drawer)
14630 "Insert a drawer at point.
14632 Optional argument DRAWER, when non-nil, is a string representing
14633 drawer's name. Otherwise, the user is prompted for a name.
14635 If a region is active, insert the drawer around that region
14636 instead.
14638 Point is left between drawer's boundaries."
14639 (interactive "P")
14640 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14641 "LOGBOOK"))
14642 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14643 ;; internally by Org. They are meant to be inserted
14644 ;; automatically.
14645 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14646 ;; Remove system drawers from list. Note: For some reason,
14647 ;; `org-completing-read' ignores the predicate while
14648 ;; `completing-read' handles it fine.
14649 (drawer (if arg "PROPERTIES"
14650 (or drawer
14651 (completing-read
14652 "Drawer: " org-drawers
14653 (lambda (d) (not (member d system-drawers))))))))
14654 (cond
14655 ;; With C-u, fall back on `org-insert-property-drawer'
14656 (arg (org-insert-property-drawer))
14657 ;; With an active region, insert a drawer at point.
14658 ((not (org-region-active-p))
14659 (progn
14660 (unless (bolp) (insert "\n"))
14661 (insert (format ":%s:\n\n:END:\n" drawer))
14662 (forward-line -2)))
14663 ;; Otherwise, insert the drawer at point
14665 (let ((rbeg (region-beginning))
14666 (rend (copy-marker (region-end))))
14667 (unwind-protect
14668 (progn
14669 (goto-char rbeg)
14670 (beginning-of-line)
14671 (when (save-excursion
14672 (re-search-forward org-outline-regexp-bol rend t))
14673 (error "Drawers cannot contain headlines"))
14674 ;; Position point at the beginning of the first
14675 ;; non-blank line in region. Insert drawer's opening
14676 ;; there, then indent it.
14677 (org-skip-whitespace)
14678 (beginning-of-line)
14679 (insert ":" drawer ":\n")
14680 (forward-line -1)
14681 (indent-for-tab-command)
14682 ;; Move point to the beginning of the first blank line
14683 ;; after the last non-blank line in region. Insert
14684 ;; drawer's closing, then indent it.
14685 (goto-char rend)
14686 (skip-chars-backward " \r\t\n")
14687 (insert "\n:END:")
14688 (indent-for-tab-command)
14689 (unless (eolp) (insert "\n")))
14690 ;; Clear marker, whatever the outcome of insertion is.
14691 (set-marker rend nil)))))))
14693 (defvar org-property-set-functions-alist nil
14694 "Property set function alist.
14695 Each entry should have the following format:
14697 (PROPERTY . READ-FUNCTION)
14699 The read function will be called with the same argument as
14700 `org-completing-read'.")
14702 (defun org-set-property-function (property)
14703 "Get the function that should be used to set PROPERTY.
14704 This is computed according to `org-property-set-functions-alist'."
14705 (or (cdr (assoc property org-property-set-functions-alist))
14706 'org-completing-read))
14708 (defun org-read-property-value (property)
14709 "Read PROPERTY value from user."
14710 (let* ((completion-ignore-case t)
14711 (allowed (org-property-get-allowed-values nil property 'table))
14712 (cur (org-entry-get nil property))
14713 (prompt (concat property " value"
14714 (if (and cur (string-match "\\S-" cur))
14715 (concat " [" cur "]") "") ": "))
14716 (set-function (org-set-property-function property))
14717 (val (if allowed
14718 (funcall set-function prompt allowed nil
14719 (not (get-text-property 0 'org-unrestricted
14720 (caar allowed))))
14721 (let (org-completion-use-ido org-completion-use-iswitchb)
14722 (funcall set-function prompt
14723 (mapcar 'list (org-property-values property))
14724 nil nil "" nil cur)))))
14725 (if (equal val "")
14727 val)))
14729 (defvar org-last-set-property nil)
14730 (defun org-read-property-name ()
14731 "Read a property name."
14732 (let* ((completion-ignore-case t)
14733 (keys (org-buffer-property-keys nil t t))
14734 (default-prop (or (save-excursion
14735 (save-match-data
14736 (beginning-of-line)
14737 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14738 (null (string= (match-string 1) "END"))
14739 (match-string 1))))
14740 org-last-set-property))
14741 (property (org-icompleting-read
14742 (concat "Property"
14743 (if default-prop (concat " [" default-prop "]") "")
14744 ": ")
14745 (mapcar 'list keys)
14746 nil nil nil nil
14747 default-prop
14749 (if (member property keys)
14750 property
14751 (or (cdr (assoc (downcase property)
14752 (mapcar (lambda (x) (cons (downcase x) x))
14753 keys)))
14754 property))))
14756 (defun org-set-property (property value)
14757 "In the current entry, set PROPERTY to VALUE.
14758 When called interactively, this will prompt for a property name, offering
14759 completion on existing and default properties. And then it will prompt
14760 for a value, offering completion either on allowed values (via an inherited
14761 xxx_ALL property) or on existing values in other instances of this property
14762 in the current file."
14763 (interactive (list nil nil))
14764 (let* ((property (or property (org-read-property-name)))
14765 (value (or value (org-read-property-value property)))
14766 (fn (cdr (assoc property org-properties-postprocess-alist))))
14767 (setq org-last-set-property property)
14768 ;; Possibly postprocess the inserted value:
14769 (when fn (setq value (funcall fn value)))
14770 (unless (equal (org-entry-get nil property) value)
14771 (org-entry-put nil property value))))
14773 (defun org-delete-property (property)
14774 "In the current entry, delete PROPERTY."
14775 (interactive
14776 (let* ((completion-ignore-case t)
14777 (prop (org-icompleting-read "Property: "
14778 (org-entry-properties nil 'standard))))
14779 (list prop)))
14780 (message "Property %s %s" property
14781 (if (org-entry-delete nil property)
14782 "deleted"
14783 "was not present in the entry")))
14785 (defun org-delete-property-globally (property)
14786 "Remove PROPERTY globally, from all entries."
14787 (interactive
14788 (let* ((completion-ignore-case t)
14789 (prop (org-icompleting-read
14790 "Globally remove property: "
14791 (mapcar 'list (org-buffer-property-keys)))))
14792 (list prop)))
14793 (save-excursion
14794 (save-restriction
14795 (widen)
14796 (goto-char (point-min))
14797 (let ((cnt 0))
14798 (while (re-search-forward
14799 (org-re-property property)
14800 nil t)
14801 (setq cnt (1+ cnt))
14802 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14803 (message "Property \"%s\" removed from %d entries" property cnt)))))
14805 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14807 (defun org-compute-property-at-point ()
14808 "Compute the property at point.
14809 This looks for an enclosing column format, extracts the operator and
14810 then applies it to the property in the column format's scope."
14811 (interactive)
14812 (unless (org-at-property-p)
14813 (error "Not at a property"))
14814 (let ((prop (org-match-string-no-properties 2)))
14815 (org-columns-get-format-and-top-level)
14816 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14817 (error "No operator defined for property %s" prop))
14818 (org-columns-compute prop)))
14820 (defvar org-property-allowed-value-functions nil
14821 "Hook for functions supplying allowed values for a specific property.
14822 The functions must take a single argument, the name of the property, and
14823 return a flat list of allowed values. If \":ETC\" is one of
14824 the values, this means that these values are intended as defaults for
14825 completion, but that other values should be allowed too.
14826 The functions must return nil if they are not responsible for this
14827 property.")
14829 (defun org-property-get-allowed-values (pom property &optional table)
14830 "Get allowed values for the property PROPERTY.
14831 When TABLE is non-nil, return an alist that can directly be used for
14832 completion."
14833 (let (vals)
14834 (cond
14835 ((equal property "TODO")
14836 (setq vals (org-with-point-at pom
14837 (append org-todo-keywords-1 '("")))))
14838 ((equal property "PRIORITY")
14839 (let ((n org-lowest-priority))
14840 (while (>= n org-highest-priority)
14841 (push (char-to-string n) vals)
14842 (setq n (1- n)))))
14843 ((member property org-special-properties))
14844 ((setq vals (run-hook-with-args-until-success
14845 'org-property-allowed-value-functions property)))
14847 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14848 (when (and vals (string-match "\\S-" vals))
14849 (setq vals (car (read-from-string (concat "(" vals ")"))))
14850 (setq vals (mapcar (lambda (x)
14851 (cond ((stringp x) x)
14852 ((numberp x) (number-to-string x))
14853 ((symbolp x) (symbol-name x))
14854 (t "???")))
14855 vals)))))
14856 (when (member ":ETC" vals)
14857 (setq vals (remove ":ETC" vals))
14858 (org-add-props (car vals) '(org-unrestricted t)))
14859 (if table (mapcar 'list vals) vals)))
14861 (defun org-property-previous-allowed-value (&optional previous)
14862 "Switch to the next allowed value for this property."
14863 (interactive)
14864 (org-property-next-allowed-value t))
14866 (defun org-property-next-allowed-value (&optional previous)
14867 "Switch to the next allowed value for this property."
14868 (interactive)
14869 (unless (org-at-property-p)
14870 (error "Not at a property"))
14871 (let* ((key (match-string 2))
14872 (value (match-string 3))
14873 (allowed (or (org-property-get-allowed-values (point) key)
14874 (and (member value '("[ ]" "[-]" "[X]"))
14875 '("[ ]" "[X]"))))
14876 nval)
14877 (unless allowed
14878 (error "Allowed values for this property have not been defined"))
14879 (if previous (setq allowed (reverse allowed)))
14880 (if (member value allowed)
14881 (setq nval (car (cdr (member value allowed)))))
14882 (setq nval (or nval (car allowed)))
14883 (if (equal nval value)
14884 (error "Only one allowed value for this property"))
14885 (org-at-property-p)
14886 (replace-match (concat " :" key ": " nval) t t)
14887 (org-indent-line-function)
14888 (beginning-of-line 1)
14889 (skip-chars-forward " \t")
14890 (run-hook-with-args 'org-property-changed-functions key nval)))
14892 (defun org-find-olp (path &optional this-buffer)
14893 "Return a marker pointing to the entry at outline path OLP.
14894 If anything goes wrong, throw an error.
14895 You can wrap this call to catch the error like this:
14897 (condition-case msg
14898 (org-mobile-locate-entry (match-string 4))
14899 (error (nth 1 msg)))
14901 The return value will then be either a string with the error message,
14902 or a marker if everything is OK.
14904 If THIS-BUFFER is set, the outline path does not contain a file,
14905 only headings."
14906 (let* ((file (if this-buffer buffer-file-name (pop path)))
14907 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14908 (level 1)
14909 (lmin 1)
14910 (lmax 1)
14911 limit re end found pos heading cnt flevel)
14912 (unless buffer (error "File not found :%s" file))
14913 (with-current-buffer buffer
14914 (save-excursion
14915 (save-restriction
14916 (widen)
14917 (setq limit (point-max))
14918 (goto-char (point-min))
14919 (while (setq heading (pop path))
14920 (setq re (format org-complex-heading-regexp-format
14921 (regexp-quote heading)))
14922 (setq cnt 0 pos (point))
14923 (while (re-search-forward re end t)
14924 (setq level (- (match-end 1) (match-beginning 1)))
14925 (if (and (>= level lmin) (<= level lmax))
14926 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14927 (when (= cnt 0) (error "Heading not found on level %d: %s"
14928 lmax heading))
14929 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14930 lmax heading))
14931 (goto-char found)
14932 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14933 (setq end (save-excursion (org-end-of-subtree t t))))
14934 (when (org-at-heading-p)
14935 (move-marker (make-marker) (point))))))))
14937 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14938 "Find node HEADING in BUFFER.
14939 Return a marker to the heading if it was found, or nil if not.
14940 If POS-ONLY is set, return just the position instead of a marker.
14942 The heading text must match exact, but it may have a TODO keyword,
14943 a priority cookie and tags in the standard locations."
14944 (with-current-buffer (or buffer (current-buffer))
14945 (save-excursion
14946 (save-restriction
14947 (widen)
14948 (goto-char (point-min))
14949 (let (case-fold-search)
14950 (if (re-search-forward
14951 (format org-complex-heading-regexp-format
14952 (regexp-quote heading)) nil t)
14953 (if pos-only
14954 (match-beginning 0)
14955 (move-marker (make-marker) (match-beginning 0)))))))))
14957 (defun org-find-exact-heading-in-directory (heading &optional dir)
14958 "Find Org node headline HEADING in all .org files in directory DIR.
14959 When the target headline is found, return a marker to this location."
14960 (let ((files (directory-files (or dir default-directory)
14961 nil "\\`[^.#].*\\.org\\'"))
14962 file visiting m buffer)
14963 (catch 'found
14964 (while (setq file (pop files))
14965 (message "trying %s" file)
14966 (setq visiting (org-find-base-buffer-visiting file))
14967 (setq buffer (or visiting (find-file-noselect file)))
14968 (setq m (org-find-exact-headline-in-buffer
14969 heading buffer))
14970 (when (and (not m) (not visiting)) (kill-buffer buffer))
14971 (and m (throw 'found m))))))
14973 (defun org-find-entry-with-id (ident)
14974 "Locate the entry that contains the ID property with exact value IDENT.
14975 IDENT can be a string, a symbol or a number, this function will search for
14976 the string representation of it.
14977 Return the position where this entry starts, or nil if there is no such entry."
14978 (interactive "sID: ")
14979 (let ((id (cond
14980 ((stringp ident) ident)
14981 ((symbol-name ident) (symbol-name ident))
14982 ((numberp ident) (number-to-string ident))
14983 (t (error "IDENT %s must be a string, symbol or number" ident))))
14984 (case-fold-search nil))
14985 (save-excursion
14986 (save-restriction
14987 (widen)
14988 (goto-char (point-min))
14989 (when (re-search-forward
14990 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14991 nil t)
14992 (org-back-to-heading t)
14993 (point))))))
14995 ;;;; Timestamps
14997 (defvar org-last-changed-timestamp nil)
14998 (defvar org-last-inserted-timestamp nil
14999 "The last time stamp inserted with `org-insert-time-stamp'.")
15000 (defvar org-time-was-given) ; dynamically scoped parameter
15001 (defvar org-end-time-was-given) ; dynamically scoped parameter
15002 (defvar org-ts-what) ; dynamically scoped parameter
15004 (defun org-time-stamp (arg &optional inactive)
15005 "Prompt for a date/time and insert a time stamp.
15006 If the user specifies a time like HH:MM, or if this command is called
15007 with a prefix argument, the time stamp will contain date and time.
15008 Otherwise, only the date will be included. All parts of a date not
15009 specified by the user will be filled in from the current date/time.
15010 So if you press just return without typing anything, the time stamp
15011 will represent the current date/time. If there is already a timestamp
15012 at the cursor, it will be modified."
15013 (interactive "P")
15014 (let* ((ts nil)
15015 (default-time
15016 ;; Default time is either today, or, when entering a range,
15017 ;; the range start.
15018 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15019 (save-excursion
15020 (re-search-backward
15021 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15022 (- (point) 20) t)))
15023 (apply 'encode-time (org-parse-time-string (match-string 1)))
15024 (current-time)))
15025 (default-input (and ts (org-get-compact-tod ts)))
15026 (repeater (save-excursion
15027 (save-match-data
15028 (beginning-of-line)
15029 (when (re-search-forward
15030 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15031 (save-excursion (progn (end-of-line) (point))) t)
15032 (match-string 0)))))
15033 org-time-was-given org-end-time-was-given time)
15034 (cond
15035 ((and (org-at-timestamp-p t)
15036 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15037 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15038 (insert "--")
15039 (setq time (let ((this-command this-command))
15040 (org-read-date arg 'totime nil nil
15041 default-time default-input inactive)))
15042 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15043 ((org-at-timestamp-p t)
15044 (setq time (let ((this-command this-command))
15045 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15046 (when (org-at-timestamp-p t) ; just to get the match data
15047 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15048 (replace-match "")
15049 (setq org-last-changed-timestamp
15050 (org-insert-time-stamp
15051 time (or org-time-was-given arg)
15052 inactive nil nil (list org-end-time-was-given)))
15053 (when repeater (goto-char (1- (point))) (insert " " repeater)
15054 (setq org-last-changed-timestamp
15055 (concat (substring org-last-inserted-timestamp 0 -1)
15056 " " repeater ">"))))
15057 (message "Timestamp updated"))
15059 (setq time (let ((this-command this-command))
15060 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15061 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15062 nil nil (list org-end-time-was-given))))))
15064 ;; FIXME: can we use this for something else, like computing time differences?
15065 (defun org-get-compact-tod (s)
15066 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15067 (let* ((t1 (match-string 1 s))
15068 (h1 (string-to-number (match-string 2 s)))
15069 (m1 (string-to-number (match-string 3 s)))
15070 (t2 (and (match-end 4) (match-string 5 s)))
15071 (h2 (and t2 (string-to-number (match-string 6 s))))
15072 (m2 (and t2 (string-to-number (match-string 7 s))))
15073 dh dm)
15074 (if (not t2)
15076 (setq dh (- h2 h1) dm (- m2 m1))
15077 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15078 (concat t1 "+" (number-to-string dh)
15079 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15081 (defun org-time-stamp-inactive (&optional arg)
15082 "Insert an inactive time stamp.
15083 An inactive time stamp is enclosed in square brackets instead of angle
15084 brackets. It is inactive in the sense that it does not trigger agenda entries,
15085 does not link to the calendar and cannot be changed with the S-cursor keys.
15086 So these are more for recording a certain time/date."
15087 (interactive "P")
15088 (org-time-stamp arg 'inactive))
15090 (defvar org-date-ovl (make-overlay 1 1))
15091 (overlay-put org-date-ovl 'face 'org-date-selected)
15092 (org-detach-overlay org-date-ovl)
15094 (defvar org-ans1) ; dynamically scoped parameter
15095 (defvar org-ans2) ; dynamically scoped parameter
15097 (defvar org-plain-time-of-day-regexp) ; defined below
15099 (defvar org-overriding-default-time nil) ; dynamically scoped
15100 (defvar org-read-date-overlay nil)
15101 (defvar org-dcst nil) ; dynamically scoped
15102 (defvar org-read-date-history nil)
15103 (defvar org-read-date-final-answer nil)
15104 (defvar org-read-date-analyze-futurep nil)
15105 (defvar org-read-date-analyze-forced-year nil)
15106 (defvar org-read-date-inactive)
15108 (defun org-read-date (&optional org-with-time to-time from-string prompt
15109 default-time default-input inactive)
15110 "Read a date, possibly a time, and make things smooth for the user.
15111 The prompt will suggest to enter an ISO date, but you can also enter anything
15112 which will at least partially be understood by `parse-time-string'.
15113 Unrecognized parts of the date will default to the current day, month, year,
15114 hour and minute. If this command is called to replace a timestamp at point,
15115 or to enter the second timestamp of a range, the default time is taken
15116 from the existing stamp. Furthermore, the command prefers the future,
15117 so if you are giving a date where the year is not given, and the day-month
15118 combination is already past in the current year, it will assume you
15119 mean next year. For details, see the manual. A few examples:
15121 3-2-5 --> 2003-02-05
15122 feb 15 --> currentyear-02-15
15123 2/15 --> currentyear-02-15
15124 sep 12 9 --> 2009-09-12
15125 12:45 --> today 12:45
15126 22 sept 0:34 --> currentyear-09-22 0:34
15127 12 --> currentyear-currentmonth-12
15128 Fri --> nearest Friday (today or later)
15129 etc.
15131 Furthermore you can specify a relative date by giving, as the *first* thing
15132 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15133 change in days weeks, months, years.
15134 With a single plus or minus, the date is relative to today. With a double
15135 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15136 +4d --> four days from today
15137 +4 --> same as above
15138 +2w --> two weeks from today
15139 ++5 --> five days from default date
15141 The function understands only English month and weekday abbreviations.
15143 While prompting, a calendar is popped up - you can also select the
15144 date with the mouse (button 1). The calendar shows a period of three
15145 months. To scroll it to other months, use the keys `>' and `<'.
15146 If you don't like the calendar, turn it off with
15147 \(setq org-read-date-popup-calendar nil)
15149 With optional argument TO-TIME, the date will immediately be converted
15150 to an internal time.
15151 With an optional argument WITH-TIME, the prompt will suggest to also
15152 insert a time. Note that when WITH-TIME is not set, you can still
15153 enter a time, and this function will inform the calling routine about
15154 this change. The calling routine may then choose to change the format
15155 used to insert the time stamp into the buffer to include the time.
15156 With optional argument FROM-STRING, read from this string instead from
15157 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15158 the time/date that is used for everything that is not specified by the
15159 user."
15160 (require 'parse-time)
15161 (let* ((org-time-stamp-rounding-minutes
15162 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15163 (org-dcst org-display-custom-times)
15164 (ct (org-current-time))
15165 (org-def (or org-overriding-default-time default-time ct))
15166 (org-defdecode (decode-time org-def))
15167 (dummy (progn
15168 (when (< (nth 2 org-defdecode) org-extend-today-until)
15169 (setcar (nthcdr 2 org-defdecode) -1)
15170 (setcar (nthcdr 1 org-defdecode) 59)
15171 (setq org-def (apply 'encode-time org-defdecode)
15172 org-defdecode (decode-time org-def)))))
15173 (calendar-frame-setup nil)
15174 (calendar-setup nil)
15175 (calendar-move-hook nil)
15176 (calendar-view-diary-initially-flag nil)
15177 (calendar-view-holidays-initially-flag nil)
15178 (timestr (format-time-string
15179 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15180 (prompt (concat (if prompt (concat prompt " ") "")
15181 (format "Date+time [%s]: " timestr)))
15182 ans (org-ans0 "") org-ans1 org-ans2 final)
15184 (cond
15185 (from-string (setq ans from-string))
15186 (org-read-date-popup-calendar
15187 (save-excursion
15188 (save-window-excursion
15189 (calendar)
15190 (org-eval-in-calendar '(setq cursor-type nil) t)
15191 (unwind-protect
15192 (progn
15193 (calendar-forward-day (- (time-to-days org-def)
15194 (calendar-absolute-from-gregorian
15195 (calendar-current-date))))
15196 (org-eval-in-calendar nil t)
15197 (let* ((old-map (current-local-map))
15198 (map (copy-keymap calendar-mode-map))
15199 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15200 (org-defkey map (kbd "RET") 'org-calendar-select)
15201 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15202 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15203 (org-defkey minibuffer-local-map [(meta shift left)]
15204 (lambda () (interactive)
15205 (org-eval-in-calendar '(calendar-backward-month 1))))
15206 (org-defkey minibuffer-local-map [(meta shift right)]
15207 (lambda () (interactive)
15208 (org-eval-in-calendar '(calendar-forward-month 1))))
15209 (org-defkey minibuffer-local-map [(meta shift up)]
15210 (lambda () (interactive)
15211 (org-eval-in-calendar '(calendar-backward-year 1))))
15212 (org-defkey minibuffer-local-map [(meta shift down)]
15213 (lambda () (interactive)
15214 (org-eval-in-calendar '(calendar-forward-year 1))))
15215 (org-defkey minibuffer-local-map [?\e (shift left)]
15216 (lambda () (interactive)
15217 (org-eval-in-calendar '(calendar-backward-month 1))))
15218 (org-defkey minibuffer-local-map [?\e (shift right)]
15219 (lambda () (interactive)
15220 (org-eval-in-calendar '(calendar-forward-month 1))))
15221 (org-defkey minibuffer-local-map [?\e (shift up)]
15222 (lambda () (interactive)
15223 (org-eval-in-calendar '(calendar-backward-year 1))))
15224 (org-defkey minibuffer-local-map [?\e (shift down)]
15225 (lambda () (interactive)
15226 (org-eval-in-calendar '(calendar-forward-year 1))))
15227 (org-defkey minibuffer-local-map [(shift up)]
15228 (lambda () (interactive)
15229 (org-eval-in-calendar '(calendar-backward-week 1))))
15230 (org-defkey minibuffer-local-map [(shift down)]
15231 (lambda () (interactive)
15232 (org-eval-in-calendar '(calendar-forward-week 1))))
15233 (org-defkey minibuffer-local-map [(shift left)]
15234 (lambda () (interactive)
15235 (org-eval-in-calendar '(calendar-backward-day 1))))
15236 (org-defkey minibuffer-local-map [(shift right)]
15237 (lambda () (interactive)
15238 (org-eval-in-calendar '(calendar-forward-day 1))))
15239 (org-defkey minibuffer-local-map ">"
15240 (lambda () (interactive)
15241 (org-eval-in-calendar '(scroll-calendar-left 1))))
15242 (org-defkey minibuffer-local-map "<"
15243 (lambda () (interactive)
15244 (org-eval-in-calendar '(scroll-calendar-right 1))))
15245 (org-defkey minibuffer-local-map "\C-v"
15246 (lambda () (interactive)
15247 (org-eval-in-calendar
15248 '(calendar-scroll-left-three-months 1))))
15249 (org-defkey minibuffer-local-map "\M-v"
15250 (lambda () (interactive)
15251 (org-eval-in-calendar
15252 '(calendar-scroll-right-three-months 1))))
15253 (run-hooks 'org-read-date-minibuffer-setup-hook)
15254 (unwind-protect
15255 (progn
15256 (use-local-map map)
15257 (setq org-read-date-inactive inactive)
15258 (add-hook 'post-command-hook 'org-read-date-display)
15259 (setq org-ans0 (read-string prompt default-input
15260 'org-read-date-history nil))
15261 ;; org-ans0: from prompt
15262 ;; org-ans1: from mouse click
15263 ;; org-ans2: from calendar motion
15264 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15265 (remove-hook 'post-command-hook 'org-read-date-display)
15266 (use-local-map old-map)
15267 (when org-read-date-overlay
15268 (delete-overlay org-read-date-overlay)
15269 (setq org-read-date-overlay nil)))))
15270 (bury-buffer "*Calendar*")))))
15272 (t ; Naked prompt only
15273 (unwind-protect
15274 (setq ans (read-string prompt default-input
15275 'org-read-date-history timestr))
15276 (when org-read-date-overlay
15277 (delete-overlay org-read-date-overlay)
15278 (setq org-read-date-overlay nil)))))
15280 (setq final (org-read-date-analyze ans org-def org-defdecode))
15282 (when org-read-date-analyze-forced-year
15283 (message "Year was forced into %s"
15284 (if org-read-date-force-compatible-dates
15285 "compatible range (1970-2037)"
15286 "range representable on this machine"))
15287 (ding))
15289 ;; One round trip to get rid of 34th of August and stuff like that....
15290 (setq final (decode-time (apply 'encode-time final)))
15292 (setq org-read-date-final-answer ans)
15294 (if to-time
15295 (apply 'encode-time final)
15296 (if (and (boundp 'org-time-was-given) org-time-was-given)
15297 (format "%04d-%02d-%02d %02d:%02d"
15298 (nth 5 final) (nth 4 final) (nth 3 final)
15299 (nth 2 final) (nth 1 final))
15300 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15302 (defvar org-def)
15303 (defvar org-defdecode)
15304 (defvar org-with-time)
15305 (defun org-read-date-display ()
15306 "Display the current date prompt interpretation in the minibuffer."
15307 (when org-read-date-display-live
15308 (when org-read-date-overlay
15309 (delete-overlay org-read-date-overlay))
15310 (when (minibufferp (current-buffer))
15311 (save-excursion
15312 (end-of-line 1)
15313 (while (not (equal (buffer-substring
15314 (max (point-min) (- (point) 4)) (point))
15315 " "))
15316 (insert " ")))
15317 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15318 " " (or org-ans1 org-ans2)))
15319 (org-end-time-was-given nil)
15320 (f (org-read-date-analyze ans org-def org-defdecode))
15321 (fmts (if org-dcst
15322 org-time-stamp-custom-formats
15323 org-time-stamp-formats))
15324 (fmt (if (or org-with-time
15325 (and (boundp 'org-time-was-given) org-time-was-given))
15326 (cdr fmts)
15327 (car fmts)))
15328 (txt (format-time-string fmt (apply 'encode-time f)))
15329 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15330 (txt (concat "=> " txt)))
15331 (when (and org-end-time-was-given
15332 (string-match org-plain-time-of-day-regexp txt))
15333 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15334 org-end-time-was-given
15335 (substring txt (match-end 0)))))
15336 (when org-read-date-analyze-futurep
15337 (setq txt (concat txt " (=>F)")))
15338 (setq org-read-date-overlay
15339 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15340 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15342 (defun org-read-date-analyze (ans org-def org-defdecode)
15343 "Analyze the combined answer of the date prompt."
15344 ;; FIXME: cleanup and comment
15345 (let ((nowdecode (decode-time (current-time)))
15346 delta deltan deltaw deltadef year month day
15347 hour minute second wday pm h2 m2 tl wday1
15348 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15349 (setq org-read-date-analyze-futurep nil
15350 org-read-date-analyze-forced-year nil)
15351 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15352 (setq ans "+0"))
15354 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15355 (setq ans (replace-match "" t t ans)
15356 deltan (car delta)
15357 deltaw (nth 1 delta)
15358 deltadef (nth 2 delta)))
15360 ;; Check if there is an iso week date in there
15361 ;; If yes, store the info and postpone interpreting it until the rest
15362 ;; of the parsing is done
15363 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15364 (setq iso-year (if (match-end 1)
15365 (org-small-year-to-year
15366 (string-to-number (match-string 1 ans))))
15367 iso-weekday (if (match-end 3)
15368 (string-to-number (match-string 3 ans)))
15369 iso-week (string-to-number (match-string 2 ans)))
15370 (setq ans (replace-match "" t t ans)))
15372 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15373 (when (string-match
15374 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15375 (setq year (if (match-end 2)
15376 (string-to-number (match-string 2 ans))
15377 (progn (setq kill-year t)
15378 (string-to-number (format-time-string "%Y"))))
15379 month (string-to-number (match-string 3 ans))
15380 day (string-to-number (match-string 4 ans)))
15381 (if (< year 100) (setq year (+ 2000 year)))
15382 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15383 t nil ans)))
15385 ;; Help matching dotted european dates
15386 (when (string-match
15387 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15388 (setq year (if (match-end 3)
15389 (string-to-number (match-string 3 ans))
15390 (progn (setq kill-year t)
15391 (string-to-number (format-time-string "%Y"))))
15392 day (string-to-number (match-string 1 ans))
15393 month (string-to-number (match-string 2 ans))
15394 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15395 t nil ans)))
15397 ;; Help matching american dates, like 5/30 or 5/30/7
15398 (when (string-match
15399 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15400 (setq year (if (match-end 4)
15401 (string-to-number (match-string 4 ans))
15402 (progn (setq kill-year t)
15403 (string-to-number (format-time-string "%Y"))))
15404 month (string-to-number (match-string 1 ans))
15405 day (string-to-number (match-string 2 ans)))
15406 (if (< year 100) (setq year (+ 2000 year)))
15407 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15408 t nil ans)))
15409 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15410 ;; If there is a time with am/pm, and *no* time without it, we convert
15411 ;; so that matching will be successful.
15412 (loop for i from 1 to 2 do ; twice, for end time as well
15413 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15414 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15415 (setq hour (string-to-number (match-string 1 ans))
15416 minute (if (match-end 3)
15417 (string-to-number (match-string 3 ans))
15419 pm (equal ?p
15420 (string-to-char (downcase (match-string 4 ans)))))
15421 (if (and (= hour 12) (not pm))
15422 (setq hour 0)
15423 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15424 (setq ans (replace-match (format "%02d:%02d" hour minute)
15425 t t ans))))
15427 ;; Check if a time range is given as a duration
15428 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15429 (setq hour (string-to-number (match-string 1 ans))
15430 h2 (+ hour (string-to-number (match-string 3 ans)))
15431 minute (string-to-number (match-string 2 ans))
15432 m2 (+ minute (if (match-end 5) (string-to-number
15433 (match-string 5 ans))0)))
15434 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15435 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15436 t t ans)))
15438 ;; Check if there is a time range
15439 (when (boundp 'org-end-time-was-given)
15440 (setq org-time-was-given nil)
15441 (when (and (string-match org-plain-time-of-day-regexp ans)
15442 (match-end 8))
15443 (setq org-end-time-was-given (match-string 8 ans))
15444 (setq ans (concat (substring ans 0 (match-beginning 7))
15445 (substring ans (match-end 7))))))
15447 (setq tl (parse-time-string ans)
15448 day (or (nth 3 tl) (nth 3 org-defdecode))
15449 month (or (nth 4 tl)
15450 (if (and org-read-date-prefer-future
15451 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15452 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15453 (nth 4 org-defdecode)))
15454 year (or (and (not kill-year) (nth 5 tl))
15455 (if (and org-read-date-prefer-future
15456 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15457 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15458 (nth 5 org-defdecode)))
15459 hour (or (nth 2 tl) (nth 2 org-defdecode))
15460 minute (or (nth 1 tl) (nth 1 org-defdecode))
15461 second (or (nth 0 tl) 0)
15462 wday (nth 6 tl))
15464 (when (and (eq org-read-date-prefer-future 'time)
15465 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15466 (equal day (nth 3 nowdecode))
15467 (equal month (nth 4 nowdecode))
15468 (equal year (nth 5 nowdecode))
15469 (nth 2 tl)
15470 (or (< (nth 2 tl) (nth 2 nowdecode))
15471 (and (= (nth 2 tl) (nth 2 nowdecode))
15472 (nth 1 tl)
15473 (< (nth 1 tl) (nth 1 nowdecode)))))
15474 (setq day (1+ day)
15475 futurep t))
15477 ;; Special date definitions below
15478 (cond
15479 (iso-week
15480 ;; There was an iso week
15481 (require 'cal-iso)
15482 (setq futurep nil)
15483 (setq year (or iso-year year)
15484 day (or iso-weekday wday 1)
15485 wday nil ; to make sure that the trigger below does not match
15486 iso-date (calendar-gregorian-from-absolute
15487 (calendar-absolute-from-iso
15488 (list iso-week day year))))
15489 ; FIXME: Should we also push ISO weeks into the future?
15490 ; (when (and org-read-date-prefer-future
15491 ; (not iso-year)
15492 ; (< (calendar-absolute-from-gregorian iso-date)
15493 ; (time-to-days (current-time))))
15494 ; (setq year (1+ year)
15495 ; iso-date (calendar-gregorian-from-absolute
15496 ; (calendar-absolute-from-iso
15497 ; (list iso-week day year)))))
15498 (setq month (car iso-date)
15499 year (nth 2 iso-date)
15500 day (nth 1 iso-date)))
15501 (deltan
15502 (setq futurep nil)
15503 (unless deltadef
15504 (let ((now (decode-time (current-time))))
15505 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15506 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15507 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15508 ((equal deltaw "m") (setq month (+ month deltan)))
15509 ((equal deltaw "y") (setq year (+ year deltan)))))
15510 ((and wday (not (nth 3 tl)))
15511 (setq futurep nil)
15512 ;; Weekday was given, but no day, so pick that day in the week
15513 ;; on or after the derived date.
15514 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15515 (unless (equal wday wday1)
15516 (setq day (+ day (% (- wday wday1 -7) 7))))))
15517 (if (and (boundp 'org-time-was-given)
15518 (nth 2 tl))
15519 (setq org-time-was-given t))
15520 (if (< year 100) (setq year (+ 2000 year)))
15521 ;; Check of the date is representable
15522 (if org-read-date-force-compatible-dates
15523 (progn
15524 (if (< year 1970)
15525 (setq year 1970 org-read-date-analyze-forced-year t))
15526 (if (> year 2037)
15527 (setq year 2037 org-read-date-analyze-forced-year t)))
15528 (condition-case nil
15529 (ignore (encode-time second minute hour day month year))
15530 (error
15531 (setq year (nth 5 org-defdecode))
15532 (setq org-read-date-analyze-forced-year t))))
15533 (setq org-read-date-analyze-futurep futurep)
15534 (list second minute hour day month year)))
15536 (defvar parse-time-weekdays)
15537 (defun org-read-date-get-relative (s today default)
15538 "Check string S for special relative date string.
15539 TODAY and DEFAULT are internal times, for today and for a default.
15540 Return shift list (N what def-flag)
15541 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15542 N is the number of WHATs to shift.
15543 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15544 the DEFAULT date rather than TODAY."
15545 (require 'parse-time)
15546 (when (and
15547 (string-match
15548 (concat
15549 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15550 "\\([0-9]+\\)?"
15551 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15552 "\\([ \t]\\|$\\)") s)
15553 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15554 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15555 (string-to-char (substring (match-string 1 s) -1))
15556 ?+))
15557 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15558 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15559 (what (if (match-end 3) (match-string 3 s) "d"))
15560 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15561 (date (if rel default today))
15562 (wday (nth 6 (decode-time date)))
15563 delta)
15564 (if wday1
15565 (progn
15566 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15567 (if (= dir ?-) (setq delta (- delta 7)))
15568 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15569 (list delta "d" rel))
15570 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15572 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15573 "Turn a user-specified date into the internal representation.
15574 The internal representation needed by the calendar is (month day year).
15575 This is a wrapper to handle the brain-dead convention in calendar that
15576 user function argument order change dependent on argument order."
15577 (if (boundp 'calendar-date-style)
15578 (cond
15579 ((eq calendar-date-style 'american)
15580 (list arg1 arg2 arg3))
15581 ((eq calendar-date-style 'european)
15582 (list arg2 arg1 arg3))
15583 ((eq calendar-date-style 'iso)
15584 (list arg2 arg3 arg1)))
15585 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15586 (if (org-bound-and-true-p european-calendar-style)
15587 (list arg2 arg1 arg3)
15588 (list arg1 arg2 arg3)))))
15590 (defun org-eval-in-calendar (form &optional keepdate)
15591 "Eval FORM in the calendar window and return to current window.
15592 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15593 otherwise stick to the current value of `org-ans2'."
15594 (let ((sf (selected-frame))
15595 (sw (selected-window)))
15596 (select-window (get-buffer-window "*Calendar*" t))
15597 (eval form)
15598 (when (and (not keepdate) (calendar-cursor-to-date))
15599 (let* ((date (calendar-cursor-to-date))
15600 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15601 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15602 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15603 (select-window sw)
15604 (org-select-frame-set-input-focus sf)))
15606 (defun org-calendar-select ()
15607 "Return to `org-read-date' with the date currently selected.
15608 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15609 (interactive)
15610 (when (calendar-cursor-to-date)
15611 (let* ((date (calendar-cursor-to-date))
15612 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15613 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15614 (if (active-minibuffer-window) (exit-minibuffer))))
15616 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15617 "Insert a date stamp for the date given by the internal TIME.
15618 WITH-HM means use the stamp format that includes the time of the day.
15619 INACTIVE means use square brackets instead of angular ones, so that the
15620 stamp will not contribute to the agenda.
15621 PRE and POST are optional strings to be inserted before and after the
15622 stamp.
15623 The command returns the inserted time stamp."
15624 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15625 stamp)
15626 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15627 (insert-before-markers (or pre ""))
15628 (when (listp extra)
15629 (setq extra (car extra))
15630 (if (and (stringp extra)
15631 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15632 (setq extra (format "-%02d:%02d"
15633 (string-to-number (match-string 1 extra))
15634 (string-to-number (match-string 2 extra))))
15635 (setq extra nil)))
15636 (when extra
15637 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15638 (insert-before-markers (setq stamp (format-time-string fmt time)))
15639 (insert-before-markers (or post ""))
15640 (setq org-last-inserted-timestamp stamp)))
15642 (defun org-toggle-time-stamp-overlays ()
15643 "Toggle the use of custom time stamp formats."
15644 (interactive)
15645 (setq org-display-custom-times (not org-display-custom-times))
15646 (unless org-display-custom-times
15647 (let ((p (point-min)) (bmp (buffer-modified-p)))
15648 (while (setq p (next-single-property-change p 'display))
15649 (if (and (get-text-property p 'display)
15650 (eq (get-text-property p 'face) 'org-date))
15651 (remove-text-properties
15652 p (setq p (next-single-property-change p 'display))
15653 '(display t))))
15654 (set-buffer-modified-p bmp)))
15655 (if (featurep 'xemacs)
15656 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15657 (org-restart-font-lock)
15658 (setq org-table-may-need-update t)
15659 (if org-display-custom-times
15660 (message "Time stamps are overlaid with custom format")
15661 (message "Time stamp overlays removed")))
15663 (defun org-display-custom-time (beg end)
15664 "Overlay modified time stamp format over timestamp between BEG and END."
15665 (let* ((ts (buffer-substring beg end))
15666 t1 w1 with-hm tf time str w2 (off 0))
15667 (save-match-data
15668 (setq t1 (org-parse-time-string ts t))
15669 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15670 (setq off (- (match-end 0) (match-beginning 0)))))
15671 (setq end (- end off))
15672 (setq w1 (- end beg)
15673 with-hm (and (nth 1 t1) (nth 2 t1))
15674 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15675 time (org-fix-decoded-time t1)
15676 str (org-add-props
15677 (format-time-string
15678 (substring tf 1 -1) (apply 'encode-time time))
15679 nil 'mouse-face 'highlight)
15680 w2 (length str))
15681 (if (not (= w2 w1))
15682 (add-text-properties (1+ beg) (+ 2 beg)
15683 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15684 (if (featurep 'xemacs)
15685 (progn
15686 (put-text-property beg end 'invisible t)
15687 (put-text-property beg end 'end-glyph (make-glyph str)))
15688 (put-text-property beg end 'display str))))
15690 (defun org-translate-time (string)
15691 "Translate all timestamps in STRING to custom format.
15692 But do this only if the variable `org-display-custom-times' is set."
15693 (when org-display-custom-times
15694 (save-match-data
15695 (let* ((start 0)
15696 (re org-ts-regexp-both)
15697 t1 with-hm inactive tf time str beg end)
15698 (while (setq start (string-match re string start))
15699 (setq beg (match-beginning 0)
15700 end (match-end 0)
15701 t1 (save-match-data
15702 (org-parse-time-string (substring string beg end) t))
15703 with-hm (and (nth 1 t1) (nth 2 t1))
15704 inactive (equal (substring string beg (1+ beg)) "[")
15705 tf (funcall (if with-hm 'cdr 'car)
15706 org-time-stamp-custom-formats)
15707 time (org-fix-decoded-time t1)
15708 str (format-time-string
15709 (concat
15710 (if inactive "[" "<") (substring tf 1 -1)
15711 (if inactive "]" ">"))
15712 (apply 'encode-time time))
15713 string (replace-match str t t string)
15714 start (+ start (length str)))))))
15715 string)
15717 (defun org-fix-decoded-time (time)
15718 "Set 0 instead of nil for the first 6 elements of time.
15719 Don't touch the rest."
15720 (let ((n 0))
15721 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15723 (defun org-days-to-time (timestamp-string)
15724 "Difference between TIMESTAMP-STRING and now in days."
15725 (- (time-to-days (org-time-string-to-time timestamp-string))
15726 (time-to-days (current-time))))
15728 (defun org-deadline-close (timestamp-string &optional ndays)
15729 "Is the time in TIMESTAMP-STRING close to the current date?"
15730 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15731 (and (< (org-days-to-time timestamp-string) ndays)
15732 (not (org-entry-is-done-p))))
15734 (defun org-get-wdays (ts)
15735 "Get the deadline lead time appropriate for timestring TS."
15736 (cond
15737 ((<= org-deadline-warning-days 0)
15738 ;; 0 or negative, enforce this value no matter what
15739 (- org-deadline-warning-days))
15740 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15741 ;; lead time is specified.
15742 (floor (* (string-to-number (match-string 1 ts))
15743 (cdr (assoc (match-string 2 ts)
15744 '(("d" . 1) ("w" . 7)
15745 ("m" . 30.4) ("y" . 365.25)))))))
15746 ;; go for the default.
15747 (t org-deadline-warning-days)))
15749 (defun org-calendar-select-mouse (ev)
15750 "Return to `org-read-date' with the date currently selected.
15751 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15752 (interactive "e")
15753 (mouse-set-point ev)
15754 (when (calendar-cursor-to-date)
15755 (let* ((date (calendar-cursor-to-date))
15756 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15757 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15758 (if (active-minibuffer-window) (exit-minibuffer))))
15760 (defun org-check-deadlines (ndays)
15761 "Check if there are any deadlines due or past due.
15762 A deadline is considered due if it happens within `org-deadline-warning-days'
15763 days from today's date. If the deadline appears in an entry marked DONE,
15764 it is not shown. The prefix arg NDAYS can be used to test that many
15765 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15766 (interactive "P")
15767 (let* ((org-warn-days
15768 (cond
15769 ((equal ndays '(4)) 100000)
15770 (ndays (prefix-numeric-value ndays))
15771 (t (abs org-deadline-warning-days))))
15772 (case-fold-search nil)
15773 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15774 (callback
15775 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15777 (message "%d deadlines past-due or due within %d days"
15778 (org-occur regexp nil callback)
15779 org-warn-days)))
15781 (defun org-check-before-date (date)
15782 "Check if there are deadlines or scheduled entries before DATE."
15783 (interactive (list (org-read-date)))
15784 (let ((case-fold-search nil)
15785 (regexp (concat "\\<\\(" org-deadline-string
15786 "\\|" org-scheduled-string
15787 "\\) *<\\([^>]+\\)>"))
15788 (callback
15789 (lambda () (time-less-p
15790 (org-time-string-to-time (match-string 2))
15791 (org-time-string-to-time date)))))
15792 (message "%d entries before %s"
15793 (org-occur regexp nil callback) date)))
15795 (defun org-check-after-date (date)
15796 "Check if there are deadlines or scheduled entries after DATE."
15797 (interactive (list (org-read-date)))
15798 (let ((case-fold-search nil)
15799 (regexp (concat "\\<\\(" org-deadline-string
15800 "\\|" org-scheduled-string
15801 "\\) *<\\([^>]+\\)>"))
15802 (callback
15803 (lambda () (not
15804 (time-less-p
15805 (org-time-string-to-time (match-string 2))
15806 (org-time-string-to-time date))))))
15807 (message "%d entries after %s"
15808 (org-occur regexp nil callback) date)))
15810 (defun org-check-dates-range (start-date end-date)
15811 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15812 (interactive (list (org-read-date nil nil nil "Range starts")
15813 (org-read-date nil nil nil "Range end")))
15814 (let ((case-fold-search nil)
15815 (regexp (concat "\\<\\(" org-deadline-string
15816 "\\|" org-scheduled-string
15817 "\\) *<\\([^>]+\\)>"))
15818 (callback
15819 (lambda ()
15820 (let ((match (match-string 2)))
15821 (and
15822 (not (time-less-p
15823 (org-time-string-to-time match)
15824 (org-time-string-to-time start-date)))
15825 (time-less-p
15826 (org-time-string-to-time match)
15827 (org-time-string-to-time end-date)))))))
15828 (message "%d entries between %s and %s"
15829 (org-occur regexp nil callback) start-date end-date)))
15831 (defun org-evaluate-time-range (&optional to-buffer)
15832 "Evaluate a time range by computing the difference between start and end.
15833 Normally the result is just printed in the echo area, but with prefix arg
15834 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15835 If the time range is actually in a table, the result is inserted into the
15836 next column.
15837 For time difference computation, a year is assumed to be exactly 365
15838 days in order to avoid rounding problems."
15839 (interactive "P")
15841 (org-clock-update-time-maybe)
15842 (save-excursion
15843 (unless (org-at-date-range-p t)
15844 (goto-char (point-at-bol))
15845 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15846 (if (not (org-at-date-range-p t))
15847 (error "Not at a time-stamp range, and none found in current line")))
15848 (let* ((ts1 (match-string 1))
15849 (ts2 (match-string 2))
15850 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15851 (match-end (match-end 0))
15852 (time1 (org-time-string-to-time ts1))
15853 (time2 (org-time-string-to-time ts2))
15854 (t1 (org-float-time time1))
15855 (t2 (org-float-time time2))
15856 (diff (abs (- t2 t1)))
15857 (negative (< (- t2 t1) 0))
15858 ;; (ys (floor (* 365 24 60 60)))
15859 (ds (* 24 60 60))
15860 (hs (* 60 60))
15861 (fy "%dy %dd %02d:%02d")
15862 (fy1 "%dy %dd")
15863 (fd "%dd %02d:%02d")
15864 (fd1 "%dd")
15865 (fh "%02d:%02d")
15866 y d h m align)
15867 (if havetime
15868 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15870 d (floor (/ diff ds)) diff (mod diff ds)
15871 h (floor (/ diff hs)) diff (mod diff hs)
15872 m (floor (/ diff 60)))
15873 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15875 d (floor (+ (/ diff ds) 0.5))
15876 h 0 m 0))
15877 (if (not to-buffer)
15878 (message "%s" (org-make-tdiff-string y d h m))
15879 (if (org-at-table-p)
15880 (progn
15881 (goto-char match-end)
15882 (setq align t)
15883 (and (looking-at " *|") (goto-char (match-end 0))))
15884 (goto-char match-end))
15885 (if (looking-at
15886 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15887 (replace-match ""))
15888 (if negative (insert " -"))
15889 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15890 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15891 (insert " " (format fh h m))))
15892 (if align (org-table-align))
15893 (message "Time difference inserted")))))
15895 (defun org-make-tdiff-string (y d h m)
15896 (let ((fmt "")
15897 (l nil))
15898 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15899 l (push y l)))
15900 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15901 l (push d l)))
15902 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15903 l (push h l)))
15904 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15905 l (push m l)))
15906 (apply 'format fmt (nreverse l))))
15908 (defun org-time-string-to-time (s &optional buffer pos)
15909 (condition-case errdata
15910 (apply 'encode-time (org-parse-time-string s))
15911 (error (error "Bad timestamp `%s'%s\nError was: %s"
15912 s (if (not (and buffer pos))
15914 (format " at %d in buffer `%s'" pos buffer))
15915 (cdr errdata)))))
15917 (defun org-time-string-to-seconds (s)
15918 (org-float-time (org-time-string-to-time s)))
15920 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15921 "Convert a time stamp to an absolute day number.
15922 If there is a specifier for a cyclic time stamp, get the closest date to
15923 DAYNR.
15924 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15925 The variable date is bound by the calendar when this is called."
15926 (cond
15927 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15928 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15929 daynr
15930 (+ daynr 1000)))
15931 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
15932 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15933 (time-to-days (current-time))) (match-string 0 s)
15934 prefer show-all))
15935 (t (time-to-days
15936 (condition-case errdata
15937 (apply 'encode-time (org-parse-time-string s))
15938 (error (error "Bad timestamp `%s'%s\nError was: %s"
15939 s (if (not (and buffer pos))
15941 (format " at %d in buffer `%s'" pos buffer))
15942 (cdr errdata))))))))
15944 (defun org-days-to-iso-week (days)
15945 "Return the iso week number."
15946 (require 'cal-iso)
15947 (car (calendar-iso-from-absolute days)))
15949 (defun org-small-year-to-year (year)
15950 "Convert 2-digit years into 4-digit years.
15951 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15952 The year 2000 cannot be abbreviated. Any year larger than 99
15953 is returned unchanged."
15954 (if (< year 38)
15955 (setq year (+ 2000 year))
15956 (if (< year 100)
15957 (setq year (+ 1900 year))))
15958 year)
15960 (defun org-time-from-absolute (d)
15961 "Return the time corresponding to date D.
15962 D may be an absolute day number, or a calendar-type list (month day year)."
15963 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15964 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15966 (defun org-calendar-holiday ()
15967 "List of holidays, for Diary display in Org-mode."
15968 (require 'holidays)
15969 (let ((hl (funcall
15970 (if (fboundp 'calendar-check-holidays)
15971 'calendar-check-holidays 'check-calendar-holidays) date)))
15972 (if hl (mapconcat 'identity hl "; "))))
15974 (defun org-diary-sexp-entry (sexp entry date)
15975 "Process a SEXP diary ENTRY for DATE."
15976 (require 'diary-lib)
15977 (let ((result (if calendar-debug-sexp
15978 (let ((stack-trace-on-error t))
15979 (eval (car (read-from-string sexp))))
15980 (condition-case nil
15981 (eval (car (read-from-string sexp)))
15982 (error
15983 (beep)
15984 (message "Bad sexp at line %d in %s: %s"
15985 (org-current-line)
15986 (buffer-file-name) sexp)
15987 (sleep-for 2))))))
15988 (cond ((stringp result) (split-string result "; "))
15989 ((and (consp result)
15990 (not (consp (cdr result)))
15991 (stringp (cdr result))) (cdr result))
15992 ((and (consp result)
15993 (stringp (car result))) result)
15994 (result entry)
15995 (t nil))))
15997 (defun org-diary-to-ical-string (frombuf)
15998 "Get iCalendar entries from diary entries in buffer FROMBUF.
15999 This uses the icalendar.el library."
16000 (let* ((tmpdir (if (featurep 'xemacs)
16001 (temp-directory)
16002 temporary-file-directory))
16003 (tmpfile (make-temp-name
16004 (expand-file-name "orgics" tmpdir)))
16005 buf rtn b e)
16006 (with-current-buffer frombuf
16007 (icalendar-export-region (point-min) (point-max) tmpfile)
16008 (setq buf (find-buffer-visiting tmpfile))
16009 (set-buffer buf)
16010 (goto-char (point-min))
16011 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16012 (setq b (match-beginning 0)))
16013 (goto-char (point-max))
16014 (if (re-search-backward "^END:VEVENT" nil t)
16015 (setq e (match-end 0)))
16016 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16017 (kill-buffer buf)
16018 (delete-file tmpfile)
16019 rtn))
16021 (defun org-closest-date (start current change prefer show-all)
16022 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16023 When PREFER is `past', return a date that is either CURRENT or past.
16024 When PREFER is `future', return a date that is either CURRENT or future.
16025 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16026 ;; Make the proper lists from the dates
16027 (catch 'exit
16028 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16029 dn dw sday cday n1 n2 n0
16030 d m y y1 y2 date1 date2 nmonths nm ny m2)
16032 (setq start (org-date-to-gregorian start)
16033 current (org-date-to-gregorian
16034 (if show-all
16035 current
16036 (time-to-days (current-time))))
16037 sday (calendar-absolute-from-gregorian start)
16038 cday (calendar-absolute-from-gregorian current))
16040 (if (<= cday sday) (throw 'exit sday))
16042 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16043 (setq dn (string-to-number (match-string 1 change))
16044 dw (cdr (assoc (match-string 2 change) a1)))
16045 (error "Invalid change specifier: %s" change))
16046 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16047 (cond
16048 ((eq dw 'day)
16049 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16050 n2 (+ n1 dn)))
16051 ((eq dw 'year)
16052 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16053 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16054 (setq date1 (list m d y1)
16055 n1 (calendar-absolute-from-gregorian date1)
16056 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16057 n2 (calendar-absolute-from-gregorian date2)))
16058 ((eq dw 'month)
16059 ;; approx number of month between the two dates
16060 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16061 ;; How often does dn fit in there?
16062 (setq d (nth 1 start) m (car start) y (nth 2 start)
16063 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16064 m (+ m nm)
16065 ny (floor (/ m 12))
16066 y (+ y ny)
16067 m (- m (* ny 12)))
16068 (while (> m 12) (setq m (- m 12) y (1+ y)))
16069 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16070 (setq m2 (+ m dn) y2 y)
16071 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16072 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16073 (while (<= n2 cday)
16074 (setq n1 n2 m m2 y y2)
16075 (setq m2 (+ m dn) y2 y)
16076 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16077 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16078 ;; Make sure n1 is the earlier date
16079 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16080 (if show-all
16081 (cond
16082 ((eq prefer 'past) (if (= cday n2) n2 n1))
16083 ((eq prefer 'future) (if (= cday n1) n1 n2))
16084 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16085 (cond
16086 ((eq prefer 'past) (if (= cday n2) n2 n1))
16087 ((eq prefer 'future) (if (= cday n1) n1 n2))
16088 (t (if (= cday n1) n1 n2)))))))
16090 (defun org-date-to-gregorian (date)
16091 "Turn any specification of DATE into a Gregorian date for the calendar."
16092 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16093 ((and (listp date) (= (length date) 3)) date)
16094 ((stringp date)
16095 (setq date (org-parse-time-string date))
16096 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16097 ((listp date)
16098 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16100 (defun org-parse-time-string (s &optional nodefault)
16101 "Parse the standard Org-mode time string.
16102 This should be a lot faster than the normal `parse-time-string'.
16103 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16104 hour and minute fields will be nil if not given."
16105 (if (string-match org-ts-regexp0 s)
16106 (list 0
16107 (if (or (match-beginning 8) (not nodefault))
16108 (string-to-number (or (match-string 8 s) "0")))
16109 (if (or (match-beginning 7) (not nodefault))
16110 (string-to-number (or (match-string 7 s) "0")))
16111 (string-to-number (match-string 4 s))
16112 (string-to-number (match-string 3 s))
16113 (string-to-number (match-string 2 s))
16114 nil nil nil)
16115 (error "Not a standard Org-mode time string: %s" s)))
16117 (defun org-timestamp-up (&optional arg)
16118 "Increase the date item at the cursor by one.
16119 If the cursor is on the year, change the year. If it is on the month,
16120 the day or the time, change that.
16121 With prefix ARG, change by that many units."
16122 (interactive "p")
16123 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16125 (defun org-timestamp-down (&optional arg)
16126 "Decrease the date item at the cursor by one.
16127 If the cursor is on the year, change the year. If it is on the month,
16128 the day or the time, change that.
16129 With prefix ARG, change by that many units."
16130 (interactive "p")
16131 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16133 (defun org-timestamp-up-day (&optional arg)
16134 "Increase the date in the time stamp by one day.
16135 With prefix ARG, change that many days."
16136 (interactive "p")
16137 (if (and (not (org-at-timestamp-p t))
16138 (org-at-heading-p))
16139 (org-todo 'up)
16140 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16142 (defun org-timestamp-down-day (&optional arg)
16143 "Decrease the date in the time stamp by one day.
16144 With prefix ARG, change that many days."
16145 (interactive "p")
16146 (if (and (not (org-at-timestamp-p t))
16147 (org-at-heading-p))
16148 (org-todo 'down)
16149 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16151 (defun org-at-timestamp-p (&optional inactive-ok)
16152 "Determine if the cursor is in or at a timestamp."
16153 (interactive)
16154 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16155 (pos (point))
16156 (ans (or (looking-at tsr)
16157 (save-excursion
16158 (skip-chars-backward "^[<\n\r\t")
16159 (if (> (point) (point-min)) (backward-char 1))
16160 (and (looking-at tsr)
16161 (> (- (match-end 0) pos) -1))))))
16162 (and ans
16163 (boundp 'org-ts-what)
16164 (setq org-ts-what
16165 (cond
16166 ((= pos (match-beginning 0)) 'bracket)
16167 ;; Point is considered to be "on the bracket" whether
16168 ;; it's really on it or right after it.
16169 ((= pos (1- (match-end 0))) 'bracket)
16170 ((= pos (match-end 0)) 'after)
16171 ((org-pos-in-match-range pos 2) 'year)
16172 ((org-pos-in-match-range pos 3) 'month)
16173 ((org-pos-in-match-range pos 7) 'hour)
16174 ((org-pos-in-match-range pos 8) 'minute)
16175 ((or (org-pos-in-match-range pos 4)
16176 (org-pos-in-match-range pos 5)) 'day)
16177 ((and (> pos (or (match-end 8) (match-end 5)))
16178 (< pos (match-end 0)))
16179 (- pos (or (match-end 8) (match-end 5))))
16180 (t 'day))))
16181 ans))
16183 (defun org-toggle-timestamp-type ()
16184 "Toggle the type (<active> or [inactive]) of a time stamp."
16185 (interactive)
16186 (when (org-at-timestamp-p t)
16187 (let ((beg (match-beginning 0)) (end (match-end 0))
16188 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16189 (save-excursion
16190 (goto-char beg)
16191 (while (re-search-forward "[][<>]" end t)
16192 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16193 t t)))
16194 (message "Timestamp is now %sactive"
16195 (if (equal (char-after beg) ?<) "" "in")))))
16197 (defun org-timestamp-change (n &optional what updown)
16198 "Change the date in the time stamp at point.
16199 The date will be changed by N times WHAT. WHAT can be `day', `month',
16200 `year', `minute', `second'. If WHAT is not given, the cursor position
16201 in the timestamp determines what will be changed."
16202 (let ((origin (point)) origin-cat
16203 with-hm inactive
16204 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16205 org-ts-what
16206 extra rem
16207 ts time time0)
16208 (if (not (org-at-timestamp-p t))
16209 (error "Not at a timestamp"))
16210 (if (and (not what) (eq org-ts-what 'bracket))
16211 (org-toggle-timestamp-type)
16212 ;; Point isn't on brackets. Remember the part of the time-stamp
16213 ;; the point was in. Indeed, size of time-stamps may change,
16214 ;; but point must be kept in the same category nonetheless.
16215 (setq origin-cat org-ts-what)
16216 (if (and (not what) (not (eq org-ts-what 'day))
16217 org-display-custom-times
16218 (get-text-property (point) 'display)
16219 (not (get-text-property (1- (point)) 'display)))
16220 (setq org-ts-what 'day))
16221 (setq org-ts-what (or what org-ts-what)
16222 inactive (= (char-after (match-beginning 0)) ?\[)
16223 ts (match-string 0))
16224 (replace-match "")
16225 (if (string-match
16226 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16228 (setq extra (match-string 1 ts)))
16229 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16230 (setq with-hm t))
16231 (setq time0 (org-parse-time-string ts))
16232 (when (and updown
16233 (eq org-ts-what 'minute)
16234 (not current-prefix-arg))
16235 ;; This looks like s-up and s-down. Change by one rounding step.
16236 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16237 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16238 (setcar (cdr time0) (+ (nth 1 time0)
16239 (if (> n 0) (- rem) (- dm rem))))))
16240 (setq time
16241 (encode-time (or (car time0) 0)
16242 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16243 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16244 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16245 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16246 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16247 (nthcdr 6 time0)))
16248 (when (and (member org-ts-what '(hour minute))
16249 extra
16250 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16251 (setq extra (org-modify-ts-extra
16252 extra
16253 (if (eq org-ts-what 'hour) 2 5)
16254 n dm)))
16255 (when (integerp org-ts-what)
16256 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16257 (if (eq what 'calendar)
16258 (let ((cal-date (org-get-date-from-calendar)))
16259 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16260 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16261 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16262 (setcar time0 (or (car time0) 0))
16263 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16264 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16265 (setq time (apply 'encode-time time0))))
16266 ;; Insert the new time-stamp, and ensure point stays in the same
16267 ;; category as before (i.e. not after the last position in that
16268 ;; category).
16269 (let ((pos (point)))
16270 ;; Stay before inserted string. `save-excursion' is of no use.
16271 (setq org-last-changed-timestamp
16272 (org-insert-time-stamp time with-hm inactive nil nil extra))
16273 (goto-char pos))
16274 (save-match-data
16275 (looking-at org-ts-regexp3)
16276 (goto-char (cond
16277 ;; `day' category ends before `hour' if any, or at
16278 ;; the end of the day name.
16279 ((eq origin-cat 'day)
16280 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16281 ((eq origin-cat 'hour) (min (match-end 7) origin))
16282 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16283 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16284 ;; `year' and `month' have both fixed size: point
16285 ;; couldn't have moved into another part.
16286 (t origin))))
16287 ;; Update clock if on a CLOCK line.
16288 (org-clock-update-time-maybe)
16289 ;; Try to recenter the calendar window, if any.
16290 (if (and org-calendar-follow-timestamp-change
16291 (get-buffer-window "*Calendar*" t)
16292 (memq org-ts-what '(day month year)))
16293 (org-recenter-calendar (time-to-days time))))))
16295 (defun org-modify-ts-extra (s pos n dm)
16296 "Change the different parts of the lead-time and repeat fields in timestamp."
16297 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16298 ng h m new rem)
16299 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16300 (cond
16301 ((or (org-pos-in-match-range pos 2)
16302 (org-pos-in-match-range pos 3))
16303 (setq m (string-to-number (match-string 3 s))
16304 h (string-to-number (match-string 2 s)))
16305 (if (org-pos-in-match-range pos 2)
16306 (setq h (+ h n))
16307 (setq n (* dm (org-no-warnings (signum n))))
16308 (when (not (= 0 (setq rem (% m dm))))
16309 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16310 (setq m (+ m n)))
16311 (if (< m 0) (setq m (+ m 60) h (1- h)))
16312 (if (> m 59) (setq m (- m 60) h (1+ h)))
16313 (setq h (min 24 (max 0 h)))
16314 (setq ng 1 new (format "-%02d:%02d" h m)))
16315 ((org-pos-in-match-range pos 6)
16316 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16317 ((org-pos-in-match-range pos 5)
16318 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16320 ((org-pos-in-match-range pos 9)
16321 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16322 ((org-pos-in-match-range pos 8)
16323 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16325 (when ng
16326 (setq s (concat
16327 (substring s 0 (match-beginning ng))
16329 (substring s (match-end ng))))))
16332 (defun org-recenter-calendar (date)
16333 "If the calendar is visible, recenter it to DATE."
16334 (let ((cwin (get-buffer-window "*Calendar*" t)))
16335 (when cwin
16336 (let ((calendar-move-hook nil))
16337 (with-selected-window cwin
16338 (calendar-goto-date (if (listp date) date
16339 (calendar-gregorian-from-absolute date))))))))
16341 (defun org-goto-calendar (&optional arg)
16342 "Go to the Emacs calendar at the current date.
16343 If there is a time stamp in the current line, go to that date.
16344 A prefix ARG can be used to force the current date."
16345 (interactive "P")
16346 (let ((tsr org-ts-regexp) diff
16347 (calendar-move-hook nil)
16348 (calendar-view-holidays-initially-flag nil)
16349 (calendar-view-diary-initially-flag nil))
16350 (if (or (org-at-timestamp-p)
16351 (save-excursion
16352 (beginning-of-line 1)
16353 (looking-at (concat ".*" tsr))))
16354 (let ((d1 (time-to-days (current-time)))
16355 (d2 (time-to-days
16356 (org-time-string-to-time (match-string 1)))))
16357 (setq diff (- d2 d1))))
16358 (calendar)
16359 (calendar-goto-today)
16360 (if (and diff (not arg)) (calendar-forward-day diff))))
16362 (defun org-get-date-from-calendar ()
16363 "Return a list (month day year) of date at point in calendar."
16364 (with-current-buffer "*Calendar*"
16365 (save-match-data
16366 (calendar-cursor-to-date))))
16368 (defun org-date-from-calendar ()
16369 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16370 If there is already a time stamp at the cursor position, update it."
16371 (interactive)
16372 (if (org-at-timestamp-p t)
16373 (org-timestamp-change 0 'calendar)
16374 (let ((cal-date (org-get-date-from-calendar)))
16375 (org-insert-time-stamp
16376 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16378 (defun org-minutes-to-hh:mm-string (m)
16379 "Compute H:MM from a number of minutes."
16380 (let ((h (/ m 60)))
16381 (setq m (- m (* 60 h)))
16382 (format org-time-clocksum-format h m)))
16384 (defun org-hh:mm-string-to-minutes (s)
16385 "Convert a string H:MM to a number of minutes.
16386 If the string is just a number, interpret it as minutes.
16387 In fact, the first hh:mm or number in the string will be taken,
16388 there can be extra stuff in the string.
16389 If no number is found, the return value is 0."
16390 (cond
16391 ((integerp s) s)
16392 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16393 (+ (* (string-to-number (match-string 1 s)) 60)
16394 (string-to-number (match-string 2 s))))
16395 ((string-match "\\([0-9]+\\)" s)
16396 (string-to-number (match-string 1 s)))
16397 (t 0)))
16399 (defcustom org-effort-durations
16400 `(("h" . 60)
16401 ("d" . ,(* 60 8))
16402 ("w" . ,(* 60 8 5))
16403 ("m" . ,(* 60 8 5 4))
16404 ("y" . ,(* 60 8 5 40)))
16405 "Conversion factor to minutes for an effort modifier.
16407 Each entry has the form (MODIFIER . MINUTES).
16409 In an effort string, a number followed by MODIFIER is multiplied
16410 by the specified number of MINUTES to obtain an effort in
16411 minutes.
16413 For example, if the value of this variable is ((\"hours\" . 60)), then an
16414 effort string \"2hours\" is equivalent to 120 minutes."
16415 :group 'org-agenda
16416 :version "24.1"
16417 :type '(alist :key-type (string :tag "Modifier")
16418 :value-type (number :tag "Minutes")))
16420 (defun org-duration-string-to-minutes (s &optional output-to-string)
16421 "Convert a duration string S to minutes.
16423 A bare number is interpreted as minutes, modifiers can be set by
16424 customizing `org-effort-durations' (which see).
16426 Entries containing a colon are interpreted as H:MM by
16427 `org-hh:mm-string-to-minutes'."
16428 (let ((result 0)
16429 (re (concat "\\([0-9.]+\\) *\\("
16430 (regexp-opt (mapcar 'car org-effort-durations))
16431 "\\)")))
16432 (while (string-match re s)
16433 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16434 (string-to-number (match-string 1 s))))
16435 (setq s (replace-match "" nil t s)))
16436 (setq result (floor result))
16437 (incf result (org-hh:mm-string-to-minutes s))
16438 (if output-to-string (number-to-string result) result)))
16440 ;;;; Files
16442 (defun org-save-all-org-buffers ()
16443 "Save all Org-mode buffers without user confirmation."
16444 (interactive)
16445 (message "Saving all Org-mode buffers...")
16446 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16447 (when (featurep 'org-id) (org-id-locations-save))
16448 (message "Saving all Org-mode buffers... done"))
16450 (defun org-revert-all-org-buffers ()
16451 "Revert all Org-mode buffers.
16452 Prompt for confirmation when there are unsaved changes.
16453 Be sure you know what you are doing before letting this function
16454 overwrite your changes.
16456 This function is useful in a setup where one tracks org files
16457 with a version control system, to revert on one machine after pulling
16458 changes from another. I believe the procedure must be like this:
16460 1. M-x org-save-all-org-buffers
16461 2. Pull changes from the other machine, resolve conflicts
16462 3. M-x org-revert-all-org-buffers"
16463 (interactive)
16464 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16465 (error "Abort"))
16466 (save-excursion
16467 (save-window-excursion
16468 (mapc
16469 (lambda (b)
16470 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16471 (with-current-buffer b buffer-file-name))
16472 (org-pop-to-buffer-same-window b)
16473 (revert-buffer t 'no-confirm)))
16474 (buffer-list))
16475 (when (and (featurep 'org-id) org-id-track-globally)
16476 (org-id-locations-load)))))
16478 ;;;; Agenda files
16480 ;;;###autoload
16481 (defun org-switchb (&optional arg)
16482 "Switch between Org buffers.
16483 With one prefix argument, restrict available buffers to files.
16484 With two prefix arguments, restrict available buffers to agenda files.
16486 Defaults to `iswitchb' for buffer name completion.
16487 Set `org-completion-use-ido' to make it use ido instead."
16488 (interactive "P")
16489 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16490 ((equal arg '(16)) (org-buffer-list 'agenda))
16491 (t (org-buffer-list))))
16492 (org-completion-use-iswitchb org-completion-use-iswitchb)
16493 (org-completion-use-ido org-completion-use-ido))
16494 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16495 (setq org-completion-use-iswitchb t))
16496 (org-pop-to-buffer-same-window
16497 (org-icompleting-read "Org buffer: "
16498 (mapcar 'list (mapcar 'buffer-name blist))
16499 nil t))))
16501 ;;; Define some older names previously used for this functionality
16502 ;;;###autoload
16503 (defalias 'org-ido-switchb 'org-switchb)
16504 ;;;###autoload
16505 (defalias 'org-iswitchb 'org-switchb)
16507 (defun org-buffer-list (&optional predicate exclude-tmp)
16508 "Return a list of Org buffers.
16509 PREDICATE can be `export', `files' or `agenda'.
16511 export restrict the list to Export buffers.
16512 files restrict the list to buffers visiting Org files.
16513 agenda restrict the list to buffers visiting agenda files.
16515 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16516 (let* ((bfn nil)
16517 (agenda-files (and (eq predicate 'agenda)
16518 (mapcar 'file-truename (org-agenda-files t))))
16519 (filter
16520 (cond
16521 ((eq predicate 'files)
16522 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16523 ((eq predicate 'export)
16524 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16525 ((eq predicate 'agenda)
16526 (lambda (b)
16527 (with-current-buffer b
16528 (and (derived-mode-p 'org-mode)
16529 (setq bfn (buffer-file-name b))
16530 (member (file-truename bfn) agenda-files)))))
16531 (t (lambda (b) (with-current-buffer b
16532 (or (derived-mode-p 'org-mode)
16533 (string-match "\*Org .*Export"
16534 (buffer-name b)))))))))
16535 (delq nil
16536 (mapcar
16537 (lambda(b)
16538 (if (and (funcall filter b)
16539 (or (not exclude-tmp)
16540 (not (string-match "tmp" (buffer-name b)))))
16542 nil))
16543 (buffer-list)))))
16545 (defun org-agenda-files (&optional unrestricted archives)
16546 "Get the list of agenda files.
16547 Optional UNRESTRICTED means return the full list even if a restriction
16548 is currently in place.
16549 When ARCHIVES is t, include all archive files that are really being
16550 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16551 `org-agenda-archives-mode' is t."
16552 (let ((files
16553 (cond
16554 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16555 ((stringp org-agenda-files) (org-read-agenda-file-list))
16556 ((listp org-agenda-files) org-agenda-files)
16557 (t (error "Invalid value of `org-agenda-files'")))))
16558 (setq files (apply 'append
16559 (mapcar (lambda (f)
16560 (if (file-directory-p f)
16561 (directory-files
16562 f t org-agenda-file-regexp)
16563 (list f)))
16564 files)))
16565 (when org-agenda-skip-unavailable-files
16566 (setq files (delq nil
16567 (mapcar (function
16568 (lambda (file)
16569 (and (file-readable-p file) file)))
16570 files))))
16571 (when (or (eq archives t)
16572 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16573 (setq files (org-add-archive-files files)))
16574 files))
16576 (defun org-agenda-file-p (&optional file)
16577 "Return non-nil, if FILE is an agenda file.
16578 If FILE is omitted, use the file associated with the current
16579 buffer."
16580 (member (or file (buffer-file-name))
16581 (org-agenda-files t)))
16583 (defun org-edit-agenda-file-list ()
16584 "Edit the list of agenda files.
16585 Depending on setup, this either uses customize to edit the variable
16586 `org-agenda-files', or it visits the file that is holding the list. In the
16587 latter case, the buffer is set up in a way that saving it automatically kills
16588 the buffer and restores the previous window configuration."
16589 (interactive)
16590 (if (stringp org-agenda-files)
16591 (let ((cw (current-window-configuration)))
16592 (find-file org-agenda-files)
16593 (org-set-local 'org-window-configuration cw)
16594 (org-add-hook 'after-save-hook
16595 (lambda ()
16596 (set-window-configuration
16597 (prog1 org-window-configuration
16598 (kill-buffer (current-buffer))))
16599 (org-install-agenda-files-menu)
16600 (message "New agenda file list installed"))
16601 nil 'local)
16602 (message "%s" (substitute-command-keys
16603 "Edit list and finish with \\[save-buffer]")))
16604 (customize-variable 'org-agenda-files)))
16606 (defun org-store-new-agenda-file-list (list)
16607 "Set new value for the agenda file list and save it correctly."
16608 (if (stringp org-agenda-files)
16609 (let ((fe (org-read-agenda-file-list t)) b u)
16610 (while (setq b (find-buffer-visiting org-agenda-files))
16611 (kill-buffer b))
16612 (with-temp-file org-agenda-files
16613 (insert
16614 (mapconcat
16615 (lambda (f) ;; Keep un-expanded entries.
16616 (if (setq u (assoc f fe))
16617 (cdr u)
16619 list "\n")
16620 "\n")))
16621 (let ((org-mode-hook nil) (org-inhibit-startup t)
16622 (org-insert-mode-line-in-empty-file nil))
16623 (setq org-agenda-files list)
16624 (customize-save-variable 'org-agenda-files org-agenda-files))))
16626 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16627 "Read the list of agenda files from a file.
16628 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16629 filenames, used by `org-store-new-agenda-file-list' to write back
16630 un-expanded file names."
16631 (when (file-directory-p org-agenda-files)
16632 (error "`org-agenda-files' cannot be a single directory"))
16633 (when (stringp org-agenda-files)
16634 (with-temp-buffer
16635 (insert-file-contents org-agenda-files)
16636 (mapcar
16637 (lambda (f)
16638 (let ((e (expand-file-name (substitute-in-file-name f)
16639 org-directory)))
16640 (if pair-with-expansion
16641 (cons e f)
16642 e)))
16643 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16645 ;;;###autoload
16646 (defun org-cycle-agenda-files ()
16647 "Cycle through the files in `org-agenda-files'.
16648 If the current buffer visits an agenda file, find the next one in the list.
16649 If the current buffer does not, find the first agenda file."
16650 (interactive)
16651 (let* ((fs (org-agenda-files t))
16652 (files (append fs (list (car fs))))
16653 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16654 file)
16655 (unless files (error "No agenda files"))
16656 (catch 'exit
16657 (while (setq file (pop files))
16658 (if (equal (file-truename file) tcf)
16659 (when (car files)
16660 (find-file (car files))
16661 (throw 'exit t))))
16662 (find-file (car fs)))
16663 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16665 (defun org-agenda-file-to-front (&optional to-end)
16666 "Move/add the current file to the top of the agenda file list.
16667 If the file is not present in the list, it is added to the front. If it is
16668 present, it is moved there. With optional argument TO-END, add/move to the
16669 end of the list."
16670 (interactive "P")
16671 (let ((org-agenda-skip-unavailable-files nil)
16672 (file-alist (mapcar (lambda (x)
16673 (cons (file-truename x) x))
16674 (org-agenda-files t)))
16675 (ctf (file-truename buffer-file-name))
16676 x had)
16677 (setq x (assoc ctf file-alist) had x)
16679 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16680 (if to-end
16681 (setq file-alist (append (delq x file-alist) (list x)))
16682 (setq file-alist (cons x (delq x file-alist))))
16683 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16684 (org-install-agenda-files-menu)
16685 (message "File %s to %s of agenda file list"
16686 (if had "moved" "added") (if to-end "end" "front"))))
16688 (defun org-remove-file (&optional file)
16689 "Remove current file from the list of files in variable `org-agenda-files'.
16690 These are the files which are being checked for agenda entries.
16691 Optional argument FILE means use this file instead of the current."
16692 (interactive)
16693 (let* ((org-agenda-skip-unavailable-files nil)
16694 (file (or file buffer-file-name))
16695 (true-file (file-truename file))
16696 (afile (abbreviate-file-name file))
16697 (files (delq nil (mapcar
16698 (lambda (x)
16699 (if (equal true-file
16700 (file-truename x))
16701 nil x))
16702 (org-agenda-files t)))))
16703 (if (not (= (length files) (length (org-agenda-files t))))
16704 (progn
16705 (org-store-new-agenda-file-list files)
16706 (org-install-agenda-files-menu)
16707 (message "Removed file: %s" afile))
16708 (message "File was not in list: %s (not removed)" afile))))
16710 (defun org-file-menu-entry (file)
16711 (vector file (list 'find-file file) t))
16713 (defun org-check-agenda-file (file)
16714 "Make sure FILE exists. If not, ask user what to do."
16715 (when (not (file-exists-p file))
16716 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16717 (abbreviate-file-name file))
16718 (let ((r (downcase (read-char-exclusive))))
16719 (cond
16720 ((equal r ?r)
16721 (org-remove-file file)
16722 (throw 'nextfile t))
16723 (t (error "Abort"))))))
16725 (defun org-get-agenda-file-buffer (file)
16726 "Get a buffer visiting FILE. If the buffer needs to be created, add
16727 it to the list of buffers which might be released later."
16728 (let ((buf (org-find-base-buffer-visiting file)))
16729 (if buf
16730 buf ; just return it
16731 ;; Make a new buffer and remember it
16732 (setq buf (find-file-noselect file))
16733 (if buf (push buf org-agenda-new-buffers))
16734 buf)))
16736 (defun org-release-buffers (blist)
16737 "Release all buffers in list, asking the user for confirmation when needed.
16738 When a buffer is unmodified, it is just killed. When modified, it is saved
16739 \(if the user agrees) and then killed."
16740 (let (buf file)
16741 (while (setq buf (pop blist))
16742 (setq file (buffer-file-name buf))
16743 (when (and (buffer-modified-p buf)
16744 file
16745 (y-or-n-p (format "Save file %s? " file)))
16746 (with-current-buffer buf (save-buffer)))
16747 (kill-buffer buf))))
16749 (defun org-prepare-agenda-buffers (files)
16750 "Create buffers for all agenda files, protect archived trees and comments."
16751 (interactive)
16752 (let ((pa '(:org-archived t))
16753 (pc '(:org-comment t))
16754 (pall '(:org-archived t :org-comment t))
16755 (inhibit-read-only t)
16756 (rea (concat ":" org-archive-tag ":"))
16757 bmp file re)
16758 (save-excursion
16759 (save-restriction
16760 (while (setq file (pop files))
16761 (catch 'nextfile
16762 (if (bufferp file)
16763 (set-buffer file)
16764 (org-check-agenda-file file)
16765 (set-buffer (org-get-agenda-file-buffer file)))
16766 (widen)
16767 (setq bmp (buffer-modified-p))
16768 (org-refresh-category-properties)
16769 (setq org-todo-keywords-for-agenda
16770 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16771 (setq org-done-keywords-for-agenda
16772 (append org-done-keywords-for-agenda org-done-keywords))
16773 (setq org-todo-keyword-alist-for-agenda
16774 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16775 (setq org-drawers-for-agenda
16776 (append org-drawers-for-agenda org-drawers))
16777 (setq org-tag-alist-for-agenda
16778 (append org-tag-alist-for-agenda org-tag-alist))
16780 (save-excursion
16781 (remove-text-properties (point-min) (point-max) pall)
16782 (when org-agenda-skip-archived-trees
16783 (goto-char (point-min))
16784 (while (re-search-forward rea nil t)
16785 (if (org-at-heading-p t)
16786 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16787 (goto-char (point-min))
16788 (setq re (format org-heading-keyword-regexp-format
16789 org-comment-string))
16790 (while (re-search-forward re nil t)
16791 (add-text-properties
16792 (match-beginning 0) (org-end-of-subtree t) pc)))
16793 (set-buffer-modified-p bmp)))))
16794 (setq org-todo-keywords-for-agenda
16795 (org-uniquify org-todo-keywords-for-agenda))
16796 (setq org-todo-keyword-alist-for-agenda
16797 (org-uniquify org-todo-keyword-alist-for-agenda)
16798 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16800 ;;;; Embedded LaTeX
16802 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16803 "Keymap for the minor `org-cdlatex-mode'.")
16805 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16806 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16807 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16808 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16809 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16811 (defvar org-cdlatex-texmathp-advice-is-done nil
16812 "Flag remembering if we have applied the advice to texmathp already.")
16814 (define-minor-mode org-cdlatex-mode
16815 "Toggle the minor `org-cdlatex-mode'.
16816 This mode supports entering LaTeX environment and math in LaTeX fragments
16817 in Org-mode.
16818 \\{org-cdlatex-mode-map}"
16819 nil " OCDL" nil
16820 (when org-cdlatex-mode
16821 (require 'cdlatex)
16822 (run-hooks 'cdlatex-mode-hook)
16823 (cdlatex-compute-tables))
16824 (unless org-cdlatex-texmathp-advice-is-done
16825 (setq org-cdlatex-texmathp-advice-is-done t)
16826 (defadvice texmathp (around org-math-always-on activate)
16827 "Always return t in org-mode buffers.
16828 This is because we want to insert math symbols without dollars even outside
16829 the LaTeX math segments. If Orgmode thinks that point is actually inside
16830 an embedded LaTeX fragment, let texmathp do its job.
16831 \\[org-cdlatex-mode-map]"
16832 (interactive)
16833 (let (p)
16834 (cond
16835 ((not (derived-mode-p 'org-mode)) ad-do-it)
16836 ((eq this-command 'cdlatex-math-symbol)
16837 (setq ad-return-value t
16838 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16840 (let ((p (org-inside-LaTeX-fragment-p)))
16841 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16842 (setq ad-return-value t
16843 texmathp-why '("Org-mode embedded math" . 0))
16844 (if p ad-do-it)))))))))
16846 (defun turn-on-org-cdlatex ()
16847 "Unconditionally turn on `org-cdlatex-mode'."
16848 (org-cdlatex-mode 1))
16850 (defun org-inside-LaTeX-fragment-p ()
16851 "Test if point is inside a LaTeX fragment.
16852 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16853 sequence appearing also before point.
16854 Even though the matchers for math are configurable, this function assumes
16855 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16856 delimiters are skipped when they have been removed by customization.
16857 The return value is nil, or a cons cell with the delimiter and the
16858 position of this delimiter.
16860 This function does a reasonably good job, but can locally be fooled by
16861 for example currency specifications. For example it will assume being in
16862 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16863 fragments that are properly closed, but during editing, we have to live
16864 with the uncertainty caused by missing closing delimiters. This function
16865 looks only before point, not after."
16866 (catch 'exit
16867 (let ((pos (point))
16868 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16869 (lim (progn
16870 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16871 (point)))
16872 dd-on str (start 0) m re)
16873 (goto-char pos)
16874 (when dodollar
16875 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16876 re (nth 1 (assoc "$" org-latex-regexps)))
16877 (while (string-match re str start)
16878 (cond
16879 ((= (match-end 0) (length str))
16880 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16881 ((= (match-end 0) (- (length str) 5))
16882 (throw 'exit nil))
16883 (t (setq start (match-end 0))))))
16884 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16885 (goto-char pos)
16886 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16887 (and (match-beginning 2) (throw 'exit nil))
16888 ;; count $$
16889 (while (re-search-backward "\\$\\$" lim t)
16890 (setq dd-on (not dd-on)))
16891 (goto-char pos)
16892 (if dd-on (cons "$$" m))))))
16894 (defun org-inside-latex-macro-p ()
16895 "Is point inside a LaTeX macro or its arguments?"
16896 (save-match-data
16897 (org-in-regexp
16898 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16900 (defun org-try-cdlatex-tab ()
16901 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16902 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16903 - inside a LaTeX fragment, or
16904 - after the first word in a line, where an abbreviation expansion could
16905 insert a LaTeX environment."
16906 (when org-cdlatex-mode
16907 (cond
16908 ;; Before any word on the line: No expansion possible.
16909 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16910 ;; Just after first word on the line: Expand it. Make sure it
16911 ;; cannot happen on headlines, though.
16912 ((save-excursion
16913 (skip-chars-backward "a-zA-Z0-9*")
16914 (skip-chars-backward " \t")
16915 (and (bolp) (not (org-at-heading-p))))
16916 (cdlatex-tab) t)
16917 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16919 (defun org-cdlatex-underscore-caret (&optional arg)
16920 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16921 Revert to the normal definition outside of these fragments."
16922 (interactive "P")
16923 (if (org-inside-LaTeX-fragment-p)
16924 (call-interactively 'cdlatex-sub-superscript)
16925 (let (org-cdlatex-mode)
16926 (call-interactively (key-binding (vector last-input-event))))))
16928 (defun org-cdlatex-math-modify (&optional arg)
16929 "Execute `cdlatex-math-modify' in LaTeX fragments.
16930 Revert to the normal definition outside of these fragments."
16931 (interactive "P")
16932 (if (org-inside-LaTeX-fragment-p)
16933 (call-interactively 'cdlatex-math-modify)
16934 (let (org-cdlatex-mode)
16935 (call-interactively (key-binding (vector last-input-event))))))
16937 (defvar org-latex-fragment-image-overlays nil
16938 "List of overlays carrying the images of latex fragments.")
16939 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16941 (defun org-remove-latex-fragment-image-overlays ()
16942 "Remove all overlays with LaTeX fragment images in current buffer."
16943 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16944 (setq org-latex-fragment-image-overlays nil))
16946 (defun org-preview-latex-fragment (&optional subtree)
16947 "Preview the LaTeX fragment at point, or all locally or globally.
16948 If the cursor is in a LaTeX fragment, create the image and overlay
16949 it over the source code. If there is no fragment at point, display
16950 all fragments in the current text, from one headline to the next. With
16951 prefix SUBTREE, display all fragments in the current subtree. With a
16952 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16953 the cursor is before the first headline,
16954 display all fragments in the buffer.
16955 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16956 (interactive "P")
16957 (unless buffer-file-name
16958 (error "Can't preview LaTeX fragment in a non-file buffer"))
16959 (org-remove-latex-fragment-image-overlays)
16960 (save-excursion
16961 (save-restriction
16962 (let (beg end at msg)
16963 (cond
16964 ((or (equal subtree '(16))
16965 (not (save-excursion
16966 (re-search-backward org-outline-regexp-bol nil t))))
16967 (setq beg (point-min) end (point-max)
16968 msg "Creating images for buffer...%s"))
16969 ((equal subtree '(4))
16970 (org-back-to-heading)
16971 (setq beg (point) end (org-end-of-subtree t)
16972 msg "Creating images for subtree...%s"))
16974 (if (setq at (org-inside-LaTeX-fragment-p))
16975 (goto-char (max (point-min) (- (cdr at) 2)))
16976 (org-back-to-heading))
16977 (setq beg (point) end (progn (outline-next-heading) (point))
16978 msg (if at "Creating image...%s"
16979 "Creating images for entry...%s"))))
16980 (message msg "")
16981 (narrow-to-region beg end)
16982 (goto-char beg)
16983 (org-format-latex
16984 (concat "ltxpng/" (file-name-sans-extension
16985 (file-name-nondirectory
16986 buffer-file-name)))
16987 default-directory 'overlays msg at 'forbuffer
16988 org-latex-create-formula-image-program)
16989 (message msg "done. Use `C-c C-c' to remove images.")))))
16991 (defvar org-latex-regexps
16992 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16993 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16994 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16995 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16996 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16997 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16998 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16999 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17000 "Regular expressions for matching embedded LaTeX.")
17002 (defvar org-export-have-math nil) ;; dynamic scoping
17003 (defun org-format-latex (prefix &optional dir overlays msg at
17004 forbuffer processing-type)
17005 "Replace LaTeX fragments with links to an image, and produce images.
17006 Some of the options can be changed using the variable
17007 `org-format-latex-options'."
17008 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17009 (let* ((prefixnodir (file-name-nondirectory prefix))
17010 (absprefix (expand-file-name prefix dir))
17011 (todir (file-name-directory absprefix))
17012 (opt org-format-latex-options)
17013 (matchers (plist-get opt :matchers))
17014 (re-list org-latex-regexps)
17015 (org-format-latex-header-extra
17016 (plist-get (org-infile-export-plist) :latex-header-extra))
17017 (cnt 0) txt hash link beg end re e checkdir
17018 executables-checked string
17019 m n block-type block linkfile movefile ov)
17020 ;; Check the different regular expressions
17021 (while (setq e (pop re-list))
17022 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17023 block (if block-type "\n\n" ""))
17024 (when (member m matchers)
17025 (goto-char (point-min))
17026 (while (re-search-forward re nil t)
17027 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17028 (not (get-text-property (match-beginning n)
17029 'org-protected))
17030 (or (not overlays)
17031 (not (eq (get-char-property (match-beginning n)
17032 'org-overlay-type)
17033 'org-latex-overlay))))
17034 (setq org-export-have-math t)
17035 (cond
17036 ((eq processing-type 'verbatim)
17037 ;; Leave the text verbatim, just protect it
17038 (add-text-properties (match-beginning n) (match-end n)
17039 '(org-protected t)))
17040 ((eq processing-type 'mathjax)
17041 ;; Prepare for MathJax processing
17042 (setq string (match-string n))
17043 (if (member m '("$" "$1"))
17044 (save-excursion
17045 (delete-region (match-beginning n) (match-end n))
17046 (goto-char (match-beginning n))
17047 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17048 "\\)")
17049 '(org-protected t))))
17050 (add-text-properties (match-beginning n) (match-end n)
17051 '(org-protected t))))
17052 ((or (eq processing-type 'dvipng)
17053 (eq processing-type 'imagemagick))
17054 ;; Process to an image
17055 (setq txt (match-string n)
17056 beg (match-beginning n) end (match-end n)
17057 cnt (1+ cnt))
17058 (let (print-length print-level) ; make sure full list is printed
17059 (setq hash (sha1 (prin1-to-string
17060 (list org-format-latex-header
17061 org-format-latex-header-extra
17062 org-export-latex-default-packages-alist
17063 org-export-latex-packages-alist
17064 org-format-latex-options
17065 forbuffer txt)))
17066 linkfile (format "%s_%s.png" prefix hash)
17067 movefile (format "%s_%s.png" absprefix hash)))
17068 (setq link (concat block "[[file:" linkfile "]]" block))
17069 (if msg (message msg cnt))
17070 (goto-char beg)
17071 (unless checkdir ; make sure the directory exists
17072 (setq checkdir t)
17073 (or (file-directory-p todir) (make-directory todir t)))
17074 (cond
17075 ((eq processing-type 'dvipng)
17076 (unless executables-checked
17077 (org-check-external-command
17078 "latex" "needed to convert LaTeX fragments to images")
17079 (org-check-external-command
17080 "dvipng" "needed to convert LaTeX fragments to images")
17081 (setq executables-checked t))
17082 (unless (file-exists-p movefile)
17083 (org-create-formula-image-with-dvipng
17084 txt movefile opt forbuffer)))
17085 ((eq processing-type 'imagemagick)
17086 (unless executables-checked
17087 (org-check-external-command
17088 "convert" "you need to install imagemagick")
17089 (setq executables-checked t))
17090 (unless (file-exists-p movefile)
17091 (org-create-formula-image-with-imagemagick
17092 txt movefile opt forbuffer))))
17093 (if overlays
17094 (progn
17095 (mapc (lambda (o)
17096 (if (eq (overlay-get o 'org-overlay-type)
17097 'org-latex-overlay)
17098 (delete-overlay o)))
17099 (overlays-in beg end))
17100 (setq ov (make-overlay beg end))
17101 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17102 (if (featurep 'xemacs)
17103 (progn
17104 (overlay-put ov 'invisible t)
17105 (overlay-put
17106 ov 'end-glyph
17107 (make-glyph (vector 'png :file movefile))))
17108 (overlay-put
17109 ov 'display
17110 (list 'image :type 'png :file movefile :ascent 'center)))
17111 (push ov org-latex-fragment-image-overlays)
17112 (goto-char end))
17113 (delete-region beg end)
17114 (insert (org-add-props link
17115 (list 'org-latex-src
17116 (replace-regexp-in-string
17117 "\"" "" txt)
17118 'org-latex-src-embed-type
17119 (if block-type 'paragraph 'character))))))
17120 ((eq processing-type 'mathml)
17121 ;; Process to MathML
17122 (unless executables-checked
17123 (unless (save-match-data (org-format-latex-mathml-available-p))
17124 (error "LaTeX to MathML converter not configured"))
17125 (setq executables-checked t))
17126 (setq txt (match-string n)
17127 beg (match-beginning n) end (match-end n)
17128 cnt (1+ cnt))
17129 (if msg (message msg cnt))
17130 (goto-char beg)
17131 (delete-region beg end)
17132 (insert (org-format-latex-as-mathml
17133 txt block-type prefix dir)))
17135 (error "Unknown conversion type %s for latex fragments"
17136 processing-type)))))))))
17138 (defun org-create-math-formula (latex-frag &optional mathml-file)
17139 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17140 Use `org-latex-to-mathml-convert-command'. If the conversion is
17141 sucessful, return the portion between \"<math...> </math>\"
17142 elements otherwise return nil. When MATHML-FILE is specified,
17143 write the results in to that file. When invoked as an
17144 interactive command, prompt for LATEX-FRAG, with initial value
17145 set to the current active region and echo the results for user
17146 inspection."
17147 (interactive (list (let ((frag (when (region-active-p)
17148 (buffer-substring-no-properties
17149 (region-beginning) (region-end)))))
17150 (read-string "LaTeX Fragment: " frag nil frag))))
17151 (unless latex-frag (error "Invalid latex-frag"))
17152 (let* ((tmp-in-file (file-relative-name
17153 (make-temp-name (expand-file-name "ltxmathml-in"))))
17154 (ignore (write-region latex-frag nil tmp-in-file))
17155 (tmp-out-file (file-relative-name
17156 (make-temp-name (expand-file-name "ltxmathml-out"))))
17157 (cmd (format-spec
17158 org-latex-to-mathml-convert-command
17159 `((?j . ,(shell-quote-argument
17160 (expand-file-name org-latex-to-mathml-jar-file)))
17161 (?I . ,(shell-quote-argument tmp-in-file))
17162 (?o . ,(shell-quote-argument tmp-out-file)))))
17163 mathml shell-command-output)
17164 (when (org-called-interactively-p 'any)
17165 (unless (org-format-latex-mathml-available-p)
17166 (error "LaTeX to MathML converter not configured")))
17167 (message "Running %s" cmd)
17168 (setq shell-command-output (shell-command-to-string cmd))
17169 (setq mathml
17170 (when (file-readable-p tmp-out-file)
17171 (with-current-buffer (find-file-noselect tmp-out-file t)
17172 (goto-char (point-min))
17173 (when (re-search-forward
17174 (concat
17175 (regexp-quote
17176 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17177 "\\(.\\|\n\\)*"
17178 (regexp-quote "</math>")) nil t)
17179 (prog1 (match-string 0) (kill-buffer))))))
17180 (cond
17181 (mathml
17182 (setq mathml
17183 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17184 (when mathml-file
17185 (write-region mathml nil mathml-file))
17186 (when (org-called-interactively-p 'any)
17187 (message mathml)))
17188 ((message "LaTeX to MathML conversion failed")
17189 (message shell-command-output)))
17190 (delete-file tmp-in-file)
17191 (when (file-exists-p tmp-out-file)
17192 (delete-file tmp-out-file))
17193 mathml))
17195 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17196 prefix &optional dir)
17197 "Use `org-create-math-formula' but check local cache first."
17198 (let* ((absprefix (expand-file-name prefix dir))
17199 (print-length nil) (print-level nil)
17200 (formula-id (concat
17201 "formula-"
17202 (sha1
17203 (prin1-to-string
17204 (list latex-frag
17205 org-latex-to-mathml-convert-command)))))
17206 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17207 (formula-cache-dir (file-name-directory formula-cache)))
17209 (unless (file-directory-p formula-cache-dir)
17210 (make-directory formula-cache-dir t))
17212 (unless (file-exists-p formula-cache)
17213 (org-create-math-formula latex-frag formula-cache))
17215 (if (file-exists-p formula-cache)
17216 ;; Successful conversion. Return the link to MathML file.
17217 (org-add-props
17218 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17219 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17220 'org-latex-src-embed-type (if latex-frag-type
17221 'paragraph 'character)))
17222 ;; Failed conversion. Return the LaTeX fragment verbatim
17223 (add-text-properties
17224 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17225 latex-frag)))
17227 ;; This function borrows from Ganesh Swami's latex2png.el
17228 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17229 "This calls dvipng."
17230 (require 'org-latex)
17231 (let* ((tmpdir (if (featurep 'xemacs)
17232 (temp-directory)
17233 temporary-file-directory))
17234 (texfilebase (make-temp-name
17235 (expand-file-name "orgtex" tmpdir)))
17236 (texfile (concat texfilebase ".tex"))
17237 (dvifile (concat texfilebase ".dvi"))
17238 (pngfile (concat texfilebase ".png"))
17239 (fnh (if (featurep 'xemacs)
17240 (font-height (face-font 'default))
17241 (face-attribute 'default :height nil)))
17242 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17243 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17244 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17245 "Black"))
17246 (bg (or (plist-get options (if buffer :background :html-background))
17247 "Transparent")))
17248 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17249 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17250 (with-temp-file texfile
17251 (insert (org-splice-latex-header
17252 org-format-latex-header
17253 org-export-latex-default-packages-alist
17254 org-export-latex-packages-alist t
17255 org-format-latex-header-extra))
17256 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17257 (require 'org-latex)
17258 (org-export-latex-fix-inputenc))
17259 (let ((dir default-directory))
17260 (condition-case nil
17261 (progn
17262 (cd tmpdir)
17263 (call-process "latex" nil nil nil texfile))
17264 (error nil))
17265 (cd dir))
17266 (if (not (file-exists-p dvifile))
17267 (progn (message "Failed to create dvi file from %s" texfile) nil)
17268 (condition-case nil
17269 (if (featurep 'xemacs)
17270 (call-process "dvipng" nil nil nil
17271 "-fg" fg "-bg" bg
17272 "-T" "tight"
17273 "-o" pngfile
17274 dvifile)
17275 (call-process "dvipng" nil nil nil
17276 "-fg" fg "-bg" bg
17277 "-D" dpi
17278 ;;"-x" scale "-y" scale
17279 "-T" "tight"
17280 "-o" pngfile
17281 dvifile))
17282 (error nil))
17283 (if (not (file-exists-p pngfile))
17284 (if org-format-latex-signal-error
17285 (error "Failed to create png file from %s" texfile)
17286 (message "Failed to create png file from %s" texfile)
17287 nil)
17288 ;; Use the requested file name and clean up
17289 (copy-file pngfile tofile 'replace)
17290 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17291 (if (file-exists-p (concat texfilebase e))
17292 (delete-file (concat texfilebase e))))
17293 pngfile))))
17295 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17296 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17297 "This calls convert, which is included into imagemagick."
17298 (require 'org-latex)
17299 (let* ((tmpdir (if (featurep 'xemacs)
17300 (temp-directory)
17301 temporary-file-directory))
17302 (texfilebase (make-temp-name
17303 (expand-file-name "orgtex" tmpdir)))
17304 (texfile (concat texfilebase ".tex"))
17305 (pdffile (concat texfilebase ".pdf"))
17306 (pngfile (concat texfilebase ".png"))
17307 (fnh (if (featurep 'xemacs)
17308 (font-height (face-font 'default))
17309 (face-attribute 'default :height nil)))
17310 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17311 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17312 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17313 "black"))
17314 (bg (or (plist-get options (if buffer :background :html-background))
17315 "white")))
17316 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17317 (setq fg (org-latex-color-format fg)))
17318 (if (eq bg 'default) (setq bg (org-latex-color :background))
17319 (setq bg (org-latex-color-format
17320 (if (string= bg "Transparent")(setq bg "white")))))
17321 (with-temp-file texfile
17322 (insert (org-splice-latex-header
17323 org-format-latex-header
17324 org-export-latex-default-packages-alist
17325 org-export-latex-packages-alist t
17326 org-format-latex-header-extra))
17327 (insert "\n\\begin{document}\n"
17328 "\\definecolor{fg}{rgb}{" fg "}\n"
17329 "\\definecolor{bg}{rgb}{" bg "}\n"
17330 "\n\\pagecolor{bg}\n"
17331 "\n{\\color{fg}\n"
17332 string
17333 "\n}\n"
17334 "\n\\end{document}\n" )
17335 (require 'org-latex)
17336 (org-export-latex-fix-inputenc))
17337 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17338 (condition-case nil
17339 (progn
17340 (cd tmpdir)
17341 (setq cmds org-latex-to-pdf-process)
17342 (while cmds
17343 (setq latex-frags-cmds (pop cmds))
17344 (if (listp latex-frags-cmds)
17345 (setq cmds nil)
17346 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17347 (while latex-frags-cmds
17348 (setq cmd (pop latex-frags-cmds))
17349 (while (string-match "%b" cmd)
17350 (setq cmd (replace-match
17351 (save-match-data
17352 (shell-quote-argument texfile))
17353 t t cmd)))
17354 (while (string-match "%f" cmd)
17355 (setq cmd (replace-match
17356 (save-match-data
17357 (shell-quote-argument (file-name-nondirectory texfile)))
17358 t t cmd)))
17359 (while (string-match "%o" cmd)
17360 (setq cmd (replace-match
17361 (save-match-data
17362 (shell-quote-argument (file-name-directory texfile)))
17363 t t cmd)))
17364 (setq cmd (split-string cmd))
17365 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17366 (error nil))
17367 (cd dir))
17368 (if (not (file-exists-p pdffile))
17369 (progn (message "Failed to create pdf file from %s" texfile) nil)
17370 (condition-case nil
17371 (if (featurep 'xemacs)
17372 (call-process "convert" nil nil nil
17373 "-density" "96"
17374 "-trim"
17375 "-antialias"
17376 pdffile
17377 "-quality" "100"
17378 ;; "-sharpen" "0x1.0"
17379 pngfile)
17380 (call-process "convert" nil nil nil
17381 "-density" dpi
17382 "-trim"
17383 "-antialias"
17384 pdffile
17385 "-quality" "100"
17386 ; "-sharpen" "0x1.0"
17387 pngfile))
17388 (error nil))
17389 (if (not (file-exists-p pngfile))
17390 (if org-format-latex-signal-error
17391 (error "Failed to create png file from %s" texfile)
17392 (message "Failed to create png file from %s" texfile)
17393 nil)
17394 ;; Use the requested file name and clean up
17395 (copy-file pngfile tofile 'replace)
17396 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17397 (if (file-exists-p (concat texfilebase e))
17398 (delete-file (concat texfilebase e))))
17399 pngfile))))
17401 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17402 "Fill a LaTeX header template TPL.
17403 In the template, the following place holders will be recognized:
17405 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17406 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17407 [PACKAGES] \\usepackage statements for PKG
17408 [NO-PACKAGES] do not include PKG
17409 [EXTRA] the string EXTRA
17410 [NO-EXTRA] do not include EXTRA
17412 For backward compatibility, if both the positive and the negative place
17413 holder is missing, the positive one (without the \"NO-\") will be
17414 assumed to be present at the end of the template.
17415 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17416 EXTRA is a string.
17417 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17418 (let (rpl (end ""))
17419 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17420 (setq rpl (if (or (match-end 1) (not def-pkg))
17421 "" (org-latex-packages-to-string def-pkg snippets-p t))
17422 tpl (replace-match rpl t t tpl))
17423 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17425 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17426 (setq rpl (if (or (match-end 1) (not pkg))
17427 "" (org-latex-packages-to-string pkg snippets-p t))
17428 tpl (replace-match rpl t t tpl))
17429 (if pkg (setq end
17430 (concat end "\n"
17431 (org-latex-packages-to-string pkg snippets-p)))))
17433 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17434 (setq rpl (if (or (match-end 1) (not extra))
17435 "" (concat extra "\n"))
17436 tpl (replace-match rpl t t tpl))
17437 (if (and extra (string-match "\\S-" extra))
17438 (setq end (concat end "\n" extra))))
17440 (if (string-match "\\S-" end)
17441 (concat tpl "\n" end)
17442 tpl)))
17444 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17445 "Turn an alist of packages into a string with the \\usepackage macros."
17446 (setq pkg (mapconcat (lambda(p)
17447 (cond
17448 ((stringp p) p)
17449 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17450 (format "%% Package %s omitted" (cadr p)))
17451 ((equal "" (car p))
17452 (format "\\usepackage{%s}" (cadr p)))
17454 (format "\\usepackage[%s]{%s}"
17455 (car p) (cadr p)))))
17457 "\n"))
17458 (if newline (concat pkg "\n") pkg))
17460 (defun org-dvipng-color (attr)
17461 "Return a RGB color specification for dvipng."
17462 (apply 'format "rgb %s %s %s"
17463 (mapcar 'org-normalize-color
17464 (if (featurep 'xemacs)
17465 (color-rgb-components
17466 (face-property 'default
17467 (cond ((eq attr :foreground) 'foreground)
17468 ((eq attr :background) 'background))))
17469 (color-values (face-attribute 'default attr nil))))))
17471 (defun org-latex-color (attr)
17472 "Return a RGB color for the LaTeX color package."
17473 (apply 'format "%s,%s,%s"
17474 (mapcar 'org-normalize-color
17475 (if (featurep 'xemacs)
17476 (color-rgb-components
17477 (face-property 'default
17478 (cond ((eq attr :foreground) 'foreground)
17479 ((eq attr :background) 'background))))
17480 (color-values (face-attribute 'default attr nil))))))
17482 (defun org-latex-color-format (color-name)
17483 "Convert COLOR-NAME to a RGB color value."
17484 (apply 'format "%s,%s,%s"
17485 (mapcar 'org-normalize-color
17486 (color-values color-name))))
17488 (defun org-normalize-color (value)
17489 "Return string to be used as color value for an RGB component."
17490 (format "%g" (/ value 65535.0)))
17492 ;; Image display
17495 (defvar org-inline-image-overlays nil)
17496 (make-variable-buffer-local 'org-inline-image-overlays)
17498 (defun org-toggle-inline-images (&optional include-linked)
17499 "Toggle the display of inline images.
17500 INCLUDE-LINKED is passed to `org-display-inline-images'."
17501 (interactive "P")
17502 (if org-inline-image-overlays
17503 (progn
17504 (org-remove-inline-images)
17505 (message "Inline image display turned off"))
17506 (org-display-inline-images include-linked)
17507 (if org-inline-image-overlays
17508 (message "%d images displayed inline"
17509 (length org-inline-image-overlays))
17510 (message "No images to display inline"))))
17512 (defun org-display-inline-images (&optional include-linked refresh beg end)
17513 "Display inline images.
17514 Normally only links without a description part are inlined, because this
17515 is how it will work for export. When INCLUDE-LINKED is set, also links
17516 with a description part will be inlined. This can be nice for a quick
17517 look at those images, but it does not reflect what exported files will look
17518 like.
17519 When REFRESH is set, refresh existing images between BEG and END.
17520 This will create new image displays only if necessary.
17521 BEG and END default to the buffer boundaries."
17522 (interactive "P")
17523 (unless refresh
17524 (org-remove-inline-images)
17525 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17526 (save-excursion
17527 (save-restriction
17528 (widen)
17529 (setq beg (or beg (point-min)) end (or end (point-max)))
17530 (goto-char beg)
17531 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17532 (substring (org-image-file-name-regexp) 0 -2)
17533 "\\)\\]" (if include-linked "" "\\]")))
17534 old file ov img)
17535 (while (re-search-forward re end t)
17536 (setq old (get-char-property-and-overlay (match-beginning 1)
17537 'org-image-overlay))
17538 (setq file (expand-file-name
17539 (concat (or (match-string 3) "") (match-string 4))))
17540 (when (file-exists-p file)
17541 (if (and (car-safe old) refresh)
17542 (image-refresh (overlay-get (cdr old) 'display))
17543 (setq img (save-match-data (create-image file)))
17544 (when img
17545 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17546 (overlay-put ov 'display img)
17547 (overlay-put ov 'face 'default)
17548 (overlay-put ov 'org-image-overlay t)
17549 (overlay-put ov 'modification-hooks
17550 (list 'org-display-inline-modification-hook))
17551 (push ov org-inline-image-overlays)))))))))
17553 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17554 "Remove inline-display overlay if a corresponding region is modified."
17555 (let ((inhibit-modification-hooks t))
17556 (when (and ov after)
17557 (delete ov org-inline-image-overlays)
17558 (delete-overlay ov))))
17560 (defun org-remove-inline-images ()
17561 "Remove inline display of images."
17562 (interactive)
17563 (mapc 'delete-overlay org-inline-image-overlays)
17564 (setq org-inline-image-overlays nil))
17566 ;;;; Key bindings
17568 ;; Outline functions from `outline-mode-prefix-map'
17569 ;; that can be remapped in Org:
17570 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17571 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17572 (define-key org-mode-map [remap outline-forward-same-level]
17573 'org-forward-same-level)
17574 (define-key org-mode-map [remap outline-backward-same-level]
17575 'org-backward-same-level)
17576 (define-key org-mode-map [remap show-branches]
17577 'org-kill-note-or-show-branches)
17578 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17579 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17580 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17582 ;; Outline functions from `outline-mode-prefix-map'
17583 ;; that can not be remapped in Org:
17584 ;; - the column "key binding" shows whether the Outline function is still
17585 ;; available in Org mode on the same key that it has been bound to in
17586 ;; Outline mode:
17587 ;; - "overridden": key used for a different functionality in Org mode
17588 ;; - else: key still bound to the same Outline function in Org mode
17589 ;; | Outline function | key binding | Org replacement |
17590 ;; |------------------------------------+-------------+-----------------------|
17591 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17592 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17593 ;; | `show-children' | `C-c C-i' | visibility cycling |
17594 ;; | `hide-subtree' | overridden | visibility cycling |
17595 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17596 ;; | `hide-body' | overridden | no replacement |
17597 ;; | `show-all' | overridden | no replacement |
17598 ;; | `hide-entry' | overridden | visibility cycling |
17599 ;; | `show-entry' | overridden | no replacement |
17600 ;; | `hide-leaves' | overridden | no replacement |
17601 ;; | `hide-sublevels' | overridden | no replacement |
17602 ;; | `hide-other' | overridden | no replacement |
17603 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17604 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17606 ;; Make `C-c C-x' a prefix key
17607 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17609 ;; TAB key with modifiers
17610 (org-defkey org-mode-map "\C-i" 'org-cycle)
17611 (org-defkey org-mode-map [(tab)] 'org-cycle)
17612 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17613 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17614 ;; The following line is necessary under Suse GNU/Linux
17615 (unless (featurep 'xemacs)
17616 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17617 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17618 (define-key org-mode-map [backtab] 'org-shifttab)
17620 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17621 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17622 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17624 ;; Cursor keys with modifiers
17625 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17626 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17627 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17628 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17630 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17631 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17632 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17633 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17635 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17636 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17637 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17638 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17640 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17641 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17642 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17643 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17645 ;; Babel keys
17646 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17647 (mapc (lambda (pair)
17648 (define-key org-babel-map (car pair) (cdr pair)))
17649 org-babel-key-bindings)
17651 ;;; Extra keys for tty access.
17652 ;; We only set them when really needed because otherwise the
17653 ;; menus don't show the simple keys
17655 (when (or org-use-extra-keys
17656 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17657 (not window-system))
17658 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17659 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17660 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17661 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17662 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17663 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17664 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17665 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17666 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17667 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17668 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17669 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17670 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17671 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17672 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17673 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17674 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17675 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17676 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17677 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17678 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17679 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17680 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17681 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17682 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17683 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17684 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17685 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17687 ;; All the other keys
17689 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17690 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17691 (if (boundp 'narrow-map)
17692 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17693 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17694 (if (boundp 'narrow-map)
17695 (org-defkey narrow-map "b" 'org-narrow-to-block)
17696 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17697 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17698 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17699 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17700 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17701 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17702 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17703 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17704 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17705 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17706 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17707 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17708 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17709 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17710 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17711 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17712 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17713 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17714 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17715 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17716 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17717 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17718 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17719 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17720 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17721 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17722 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17723 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17724 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17725 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17726 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17727 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17728 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17729 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17730 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17731 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17732 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17733 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17734 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17735 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17736 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17737 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17738 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17739 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17740 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17741 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17742 (org-defkey org-mode-map "\C-c^" 'org-sort)
17743 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17744 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17745 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17746 (org-defkey org-mode-map "\C-m" 'org-return)
17747 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17748 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17749 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17750 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17751 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17752 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17753 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17754 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17755 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17756 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17757 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17758 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17759 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17760 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17761 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17762 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17763 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17764 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17765 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17766 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17767 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17768 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17769 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17771 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17772 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17773 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17774 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17776 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17777 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17778 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17779 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17780 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17781 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17782 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17783 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17784 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17785 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17786 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17787 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17788 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17789 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17790 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17791 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17792 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17793 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17795 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17796 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17797 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17798 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17799 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17801 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17803 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17805 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17806 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17808 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17811 (when (featurep 'xemacs)
17812 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17815 (defconst org-speed-commands-default
17817 ("Outline Navigation")
17818 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17819 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17820 ("f" . (org-speed-move-safe 'org-forward-same-level))
17821 ("b" . (org-speed-move-safe 'org-backward-same-level))
17822 ("u" . (org-speed-move-safe 'outline-up-heading))
17823 ("j" . org-goto)
17824 ("g" . (org-refile t))
17825 ("Outline Visibility")
17826 ("c" . org-cycle)
17827 ("C" . org-shifttab)
17828 (" " . org-display-outline-path)
17829 ("Outline Structure Editing")
17830 ("U" . org-shiftmetaup)
17831 ("D" . org-shiftmetadown)
17832 ("r" . org-metaright)
17833 ("l" . org-metaleft)
17834 ("R" . org-shiftmetaright)
17835 ("L" . org-shiftmetaleft)
17836 ("i" . (progn (forward-char 1) (call-interactively
17837 'org-insert-heading-respect-content)))
17838 ("^" . org-sort)
17839 ("w" . org-refile)
17840 ("a" . org-archive-subtree-default-with-confirmation)
17841 ("." . org-mark-subtree)
17842 ("Clock Commands")
17843 ("I" . org-clock-in)
17844 ("O" . org-clock-out)
17845 ("Meta Data Editing")
17846 ("t" . org-todo)
17847 ("0" . (org-priority ?\ ))
17848 ("1" . (org-priority ?A))
17849 ("2" . (org-priority ?B))
17850 ("3" . (org-priority ?C))
17851 (";" . org-set-tags-command)
17852 ("e" . org-set-effort)
17853 ("Agenda Views etc")
17854 ("v" . org-agenda)
17855 ("/" . org-sparse-tree)
17856 ("Misc")
17857 ("o" . org-open-at-point)
17858 ("?" . org-speed-command-help)
17859 ("<" . (org-agenda-set-restriction-lock 'subtree))
17860 (">" . (org-agenda-remove-restriction-lock))
17862 "The default speed commands.")
17864 (defun org-print-speed-command (e)
17865 (if (> (length (car e)) 1)
17866 (progn
17867 (princ "\n")
17868 (princ (car e))
17869 (princ "\n")
17870 (princ (make-string (length (car e)) ?-))
17871 (princ "\n"))
17872 (princ (car e))
17873 (princ " ")
17874 (if (symbolp (cdr e))
17875 (princ (symbol-name (cdr e)))
17876 (prin1 (cdr e)))
17877 (princ "\n")))
17879 (defun org-speed-command-help ()
17880 "Show the available speed commands."
17881 (interactive)
17882 (if (not org-use-speed-commands)
17883 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17884 (with-output-to-temp-buffer "*Help*"
17885 (princ "User-defined Speed commands\n===========================\n")
17886 (mapc 'org-print-speed-command org-speed-commands-user)
17887 (princ "\n")
17888 (princ "Built-in Speed commands\n=======================\n")
17889 (mapc 'org-print-speed-command org-speed-commands-default))
17890 (with-current-buffer "*Help*"
17891 (setq truncate-lines t))))
17893 (defun org-speed-move-safe (cmd)
17894 "Execute CMD, but make sure that the cursor always ends up in a headline.
17895 If not, return to the original position and throw an error."
17896 (interactive)
17897 (let ((pos (point)))
17898 (call-interactively cmd)
17899 (unless (and (bolp) (org-at-heading-p))
17900 (goto-char pos)
17901 (error "Boundary reached while executing %s" cmd))))
17903 (defvar org-self-insert-command-undo-counter 0)
17905 (defvar org-table-auto-blank-field) ; defined in org-table.el
17906 (defvar org-speed-command nil)
17908 (defun org-speed-command-default-hook (keys)
17909 "Hook for activating single-letter speed commands.
17910 `org-speed-commands-default' specifies a minimal command set.
17911 Use `org-speed-commands-user' for further customization."
17912 (when (or (and (bolp) (looking-at org-outline-regexp))
17913 (and (functionp org-use-speed-commands)
17914 (funcall org-use-speed-commands)))
17915 (cdr (assoc keys (append org-speed-commands-user
17916 org-speed-commands-default)))))
17918 (defun org-babel-speed-command-hook (keys)
17919 "Hook for activating single-letter code block commands."
17920 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17921 (cdr (assoc keys org-babel-key-bindings))))
17923 (defcustom org-speed-command-hook
17924 '(org-speed-command-default-hook org-babel-speed-command-hook)
17925 "Hook for activating speed commands at strategic locations.
17926 Hook functions are called in sequence until a valid handler is
17927 found.
17929 Each hook takes a single argument, a user-pressed command key
17930 which is also a `self-insert-command' from the global map.
17932 Within the hook, examine the cursor position and the command key
17933 and return nil or a valid handler as appropriate. Handler could
17934 be one of an interactive command, a function, or a form.
17936 Set `org-use-speed-commands' to non-nil value to enable this
17937 hook. The default setting is `org-speed-command-default-hook'."
17938 :group 'org-structure
17939 :version "24.1"
17940 :type 'hook)
17942 (defun org-self-insert-command (N)
17943 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17944 If the cursor is in a table looking at whitespace, the whitespace is
17945 overwritten, and the table is not marked as requiring realignment."
17946 (interactive "p")
17947 (org-check-before-invisible-edit 'insert)
17948 (cond
17949 ((and org-use-speed-commands
17950 (setq org-speed-command
17951 (run-hook-with-args-until-success
17952 'org-speed-command-hook (this-command-keys))))
17953 (cond
17954 ((commandp org-speed-command)
17955 (setq this-command org-speed-command)
17956 (call-interactively org-speed-command))
17957 ((functionp org-speed-command)
17958 (funcall org-speed-command))
17959 ((and org-speed-command (listp org-speed-command))
17960 (eval org-speed-command))
17961 (t (let (org-use-speed-commands)
17962 (call-interactively 'org-self-insert-command)))))
17963 ((and
17964 (org-table-p)
17965 (progn
17966 ;; check if we blank the field, and if that triggers align
17967 (and (featurep 'org-table) org-table-auto-blank-field
17968 (member last-command
17969 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17970 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17971 ;; got extra space, this field does not determine column width
17972 (let (org-table-may-need-update) (org-table-blank-field))
17973 ;; no extra space, this field may determine column width
17974 (org-table-blank-field)))
17976 (eq N 1)
17977 (looking-at "[^|\n]* |"))
17978 (let (org-table-may-need-update)
17979 (goto-char (1- (match-end 0)))
17980 (backward-delete-char 1)
17981 (goto-char (match-beginning 0))
17982 (self-insert-command N)))
17984 (setq org-table-may-need-update t)
17985 (self-insert-command N)
17986 (org-fix-tags-on-the-fly)
17987 (if org-self-insert-cluster-for-undo
17988 (if (not (eq last-command 'org-self-insert-command))
17989 (setq org-self-insert-command-undo-counter 1)
17990 (if (>= org-self-insert-command-undo-counter 20)
17991 (setq org-self-insert-command-undo-counter 1)
17992 (and (> org-self-insert-command-undo-counter 0)
17993 buffer-undo-list (listp buffer-undo-list)
17994 (not (cadr buffer-undo-list)) ; remove nil entry
17995 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17996 (setq org-self-insert-command-undo-counter
17997 (1+ org-self-insert-command-undo-counter))))))))
17999 (defun org-check-before-invisible-edit (kind)
18000 "Check is editing if kind KIND would be dangerous with invisible text around.
18001 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18002 ;; First, try to get out of here as quickly as possible, to reduce overhead
18003 (if (and org-catch-invisible-edits
18004 (or (not (boundp 'visible-mode)) (not visible-mode))
18005 (or (get-char-property (point) 'invisible)
18006 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18007 ;; OK, we need to take a closer look
18008 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18009 (invisible-before-point (if (bobp) nil (get-char-property
18010 (1- (point)) 'invisible)))
18011 (border-and-ok-direction
18013 ;; Check if we are acting predictably before invisible text
18014 (and invisible-at-point (not invisible-before-point)
18015 (memq kind '(insert delete-backward)))
18016 ;; Check if we are acting predictably after invisible text
18017 ;; This works not well, and I have turned it off. It seems
18018 ;; better to always show and stop after invisible text.
18019 ;; (and (not invisible-at-point) invisible-before-point
18020 ;; (memq kind '(insert delete)))
18023 (when (or (memq invisible-at-point '(outline org-hide-block))
18024 (memq invisible-before-point '(outline org-hide-block)))
18025 (if (eq org-catch-invisible-edits 'error)
18026 (error "Editing in invisible areas is prohibited - make visible first"))
18027 ;; Make the area visible
18028 (save-excursion
18029 (if invisible-before-point
18030 (goto-char (previous-single-char-property-change
18031 (point) 'invisible)))
18032 (org-cycle))
18033 (cond
18034 ((eq org-catch-invisible-edits 'show)
18035 ;; That's it, we do the edit after showing
18036 (message
18037 "Unfolding invisible region around point before editing")
18038 (sit-for 1))
18039 ((and (eq org-catch-invisible-edits 'smart)
18040 border-and-ok-direction)
18041 (message "Unfolding invisible region around point before editing"))
18043 ;; Don't do the edit, make the user repeat it in full visibility
18044 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
18046 (defun org-fix-tags-on-the-fly ()
18047 (when (and (equal (char-after (point-at-bol)) ?*)
18048 (org-at-heading-p))
18049 (org-align-tags-here org-tags-column)))
18051 (defun org-delete-backward-char (N)
18052 "Like `delete-backward-char', insert whitespace at field end in tables.
18053 When deleting backwards, in tables this function will insert whitespace in
18054 front of the next \"|\" separator, to keep the table aligned. The table will
18055 still be marked for re-alignment if the field did fill the entire column,
18056 because, in this case the deletion might narrow the column."
18057 (interactive "p")
18058 (org-check-before-invisible-edit 'delete-backward)
18059 (if (and (org-table-p)
18060 (eq N 1)
18061 (string-match "|" (buffer-substring (point-at-bol) (point)))
18062 (looking-at ".*?|"))
18063 (let ((pos (point))
18064 (noalign (looking-at "[^|\n\r]* |"))
18065 (c org-table-may-need-update))
18066 (backward-delete-char N)
18067 (if (not overwrite-mode)
18068 (progn
18069 (skip-chars-forward "^|")
18070 (insert " ")
18071 (goto-char (1- pos))))
18072 ;; noalign: if there were two spaces at the end, this field
18073 ;; does not determine the width of the column.
18074 (if noalign (setq org-table-may-need-update c)))
18075 (backward-delete-char N)
18076 (org-fix-tags-on-the-fly)))
18078 (defun org-delete-char (N)
18079 "Like `delete-char', but insert whitespace at field end in tables.
18080 When deleting characters, in tables this function will insert whitespace in
18081 front of the next \"|\" separator, to keep the table aligned. The table will
18082 still be marked for re-alignment if the field did fill the entire column,
18083 because, in this case the deletion might narrow the column."
18084 (interactive "p")
18085 (org-check-before-invisible-edit 'delete)
18086 (if (and (org-table-p)
18087 (not (bolp))
18088 (not (= (char-after) ?|))
18089 (eq N 1))
18090 (if (looking-at ".*?|")
18091 (let ((pos (point))
18092 (noalign (looking-at "[^|\n\r]* |"))
18093 (c org-table-may-need-update))
18094 (replace-match (concat
18095 (substring (match-string 0) 1 -1)
18096 " |"))
18097 (goto-char pos)
18098 ;; noalign: if there were two spaces at the end, this field
18099 ;; does not determine the width of the column.
18100 (if noalign (setq org-table-may-need-update c)))
18101 (delete-char N))
18102 (delete-char N)
18103 (org-fix-tags-on-the-fly)))
18105 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18106 (put 'org-self-insert-command 'delete-selection t)
18107 (put 'orgtbl-self-insert-command 'delete-selection t)
18108 (put 'org-delete-char 'delete-selection 'supersede)
18109 (put 'org-delete-backward-char 'delete-selection 'supersede)
18110 (put 'org-yank 'delete-selection 'yank)
18112 ;; Make `flyspell-mode' delay after some commands
18113 (put 'org-self-insert-command 'flyspell-delayed t)
18114 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18115 (put 'org-delete-char 'flyspell-delayed t)
18116 (put 'org-delete-backward-char 'flyspell-delayed t)
18118 ;; Make pabbrev-mode expand after org-mode commands
18119 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18120 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18122 ;; How to do this: Measure non-white length of current string
18123 ;; If equal to column width, we should realign.
18125 (defun org-remap (map &rest commands)
18126 "In MAP, remap the functions given in COMMANDS.
18127 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18128 (let (new old)
18129 (while commands
18130 (setq old (pop commands) new (pop commands))
18131 (if (fboundp 'command-remapping)
18132 (org-defkey map (vector 'remap old) new)
18133 (substitute-key-definition old new map global-map)))))
18135 (when (eq org-enable-table-editor 'optimized)
18136 ;; If the user wants maximum table support, we need to hijack
18137 ;; some standard editing functions
18138 (org-remap org-mode-map
18139 'self-insert-command 'org-self-insert-command
18140 'delete-char 'org-delete-char
18141 'delete-backward-char 'org-delete-backward-char)
18142 (org-defkey org-mode-map "|" 'org-force-self-insert))
18144 (defvar org-ctrl-c-ctrl-c-hook nil
18145 "Hook for functions attaching themselves to `C-c C-c'.
18147 This can be used to add additional functionality to the C-c C-c
18148 key which executes context-dependent commands. This hook is run
18149 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18150 run after the last test.
18152 Each function will be called with no arguments. The function
18153 must check if the context is appropriate for it to act. If yes,
18154 it should do its thing and then return a non-nil value. If the
18155 context is wrong, just do nothing and return nil.")
18157 (defvar org-ctrl-c-ctrl-c-final-hook nil
18158 "Hook for functions attaching themselves to `C-c C-c'.
18160 This can be used to add additional functionality to the C-c C-c
18161 key which executes context-dependent commands. This hook is run
18162 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18163 before the first test.
18165 Each function will be called with no arguments. The function
18166 must check if the context is appropriate for it to act. If yes,
18167 it should do its thing and then return a non-nil value. If the
18168 context is wrong, just do nothing and return nil.")
18170 (defvar org-tab-first-hook nil
18171 "Hook for functions to attach themselves to TAB.
18172 See `org-ctrl-c-ctrl-c-hook' for more information.
18173 This hook runs as the first action when TAB is pressed, even before
18174 `org-cycle' messes around with the `outline-regexp' to cater for
18175 inline tasks and plain list item folding.
18176 If any function in this hook returns t, any other actions that
18177 would have been caused by TAB (such as table field motion or visibility
18178 cycling) will not occur.")
18180 (defvar org-tab-after-check-for-table-hook nil
18181 "Hook for functions to attach themselves to TAB.
18182 See `org-ctrl-c-ctrl-c-hook' for more information.
18183 This hook runs after it has been established that the cursor is not in a
18184 table, but before checking if the cursor is in a headline or if global cycling
18185 should be done.
18186 If any function in this hook returns t, not other actions like visibility
18187 cycling will be done.")
18189 (defvar org-tab-after-check-for-cycling-hook nil
18190 "Hook for functions to attach themselves to TAB.
18191 See `org-ctrl-c-ctrl-c-hook' for more information.
18192 This hook runs after it has been established that not table field motion and
18193 not visibility should be done because of current context. This is probably
18194 the place where a package like yasnippets can hook in.")
18196 (defvar org-tab-before-tab-emulation-hook nil
18197 "Hook for functions to attach themselves to TAB.
18198 See `org-ctrl-c-ctrl-c-hook' for more information.
18199 This hook runs after every other options for TAB have been exhausted, but
18200 before indentation and \t insertion takes place.")
18202 (defvar org-metaleft-hook nil
18203 "Hook for functions attaching themselves to `M-left'.
18204 See `org-ctrl-c-ctrl-c-hook' for more information.")
18205 (defvar org-metaright-hook nil
18206 "Hook for functions attaching themselves to `M-right'.
18207 See `org-ctrl-c-ctrl-c-hook' for more information.")
18208 (defvar org-metaup-hook nil
18209 "Hook for functions attaching themselves to `M-up'.
18210 See `org-ctrl-c-ctrl-c-hook' for more information.")
18211 (defvar org-metadown-hook nil
18212 "Hook for functions attaching themselves to `M-down'.
18213 See `org-ctrl-c-ctrl-c-hook' for more information.")
18214 (defvar org-shiftmetaleft-hook nil
18215 "Hook for functions attaching themselves to `M-S-left'.
18216 See `org-ctrl-c-ctrl-c-hook' for more information.")
18217 (defvar org-shiftmetaright-hook nil
18218 "Hook for functions attaching themselves to `M-S-right'.
18219 See `org-ctrl-c-ctrl-c-hook' for more information.")
18220 (defvar org-shiftmetaup-hook nil
18221 "Hook for functions attaching themselves to `M-S-up'.
18222 See `org-ctrl-c-ctrl-c-hook' for more information.")
18223 (defvar org-shiftmetadown-hook nil
18224 "Hook for functions attaching themselves to `M-S-down'.
18225 See `org-ctrl-c-ctrl-c-hook' for more information.")
18226 (defvar org-metareturn-hook nil
18227 "Hook for functions attaching themselves to `M-RET'.
18228 See `org-ctrl-c-ctrl-c-hook' for more information.")
18229 (defvar org-shiftup-hook nil
18230 "Hook for functions attaching themselves to `S-up'.
18231 See `org-ctrl-c-ctrl-c-hook' for more information.")
18232 (defvar org-shiftup-final-hook nil
18233 "Hook for functions attaching themselves to `S-up'.
18234 This one runs after all other options except shift-select have been excluded.
18235 See `org-ctrl-c-ctrl-c-hook' for more information.")
18236 (defvar org-shiftdown-hook nil
18237 "Hook for functions attaching themselves to `S-down'.
18238 See `org-ctrl-c-ctrl-c-hook' for more information.")
18239 (defvar org-shiftdown-final-hook nil
18240 "Hook for functions attaching themselves to `S-down'.
18241 This one runs after all other options except shift-select have been excluded.
18242 See `org-ctrl-c-ctrl-c-hook' for more information.")
18243 (defvar org-shiftleft-hook nil
18244 "Hook for functions attaching themselves to `S-left'.
18245 See `org-ctrl-c-ctrl-c-hook' for more information.")
18246 (defvar org-shiftleft-final-hook nil
18247 "Hook for functions attaching themselves to `S-left'.
18248 This one runs after all other options except shift-select have been excluded.
18249 See `org-ctrl-c-ctrl-c-hook' for more information.")
18250 (defvar org-shiftright-hook nil
18251 "Hook for functions attaching themselves to `S-right'.
18252 See `org-ctrl-c-ctrl-c-hook' for more information.")
18253 (defvar org-shiftright-final-hook nil
18254 "Hook for functions attaching themselves to `S-right'.
18255 This one runs after all other options except shift-select have been excluded.
18256 See `org-ctrl-c-ctrl-c-hook' for more information.")
18258 (defun org-modifier-cursor-error ()
18259 "Throw an error, a modified cursor command was applied in wrong context."
18260 (error "This command is active in special context like tables, headlines or items"))
18262 (defun org-shiftselect-error ()
18263 "Throw an error because Shift-Cursor command was applied in wrong context."
18264 (if (and (boundp 'shift-select-mode) shift-select-mode)
18265 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18266 (error "This command works only in special context like headlines or timestamps")))
18268 (defun org-call-for-shift-select (cmd)
18269 (let ((this-command-keys-shift-translated t))
18270 (call-interactively cmd)))
18272 (defun org-shifttab (&optional arg)
18273 "Global visibility cycling or move to previous table field.
18274 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18275 on context.
18276 See the individual commands for more information."
18277 (interactive "P")
18278 (cond
18279 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18280 ((integerp arg)
18281 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18282 (message "Content view to level: %d" arg)
18283 (org-content (prefix-numeric-value arg2))
18284 (setq org-cycle-global-status 'overview)))
18285 (t (call-interactively 'org-global-cycle))))
18287 (defun org-shiftmetaleft ()
18288 "Promote subtree or delete table column.
18289 Calls `org-promote-subtree', `org-outdent-item-tree', or
18290 `org-table-delete-column', depending on context. See the
18291 individual commands for more information."
18292 (interactive)
18293 (cond
18294 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18295 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18296 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18297 ((if (not (org-region-active-p)) (org-at-item-p)
18298 (save-excursion (goto-char (region-beginning))
18299 (org-at-item-p)))
18300 (call-interactively 'org-outdent-item-tree))
18301 (t (org-modifier-cursor-error))))
18303 (defun org-shiftmetaright ()
18304 "Demote subtree or insert table column.
18305 Calls `org-demote-subtree', `org-indent-item-tree', or
18306 `org-table-insert-column', depending on context. See the
18307 individual commands for more information."
18308 (interactive)
18309 (cond
18310 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18311 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18312 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18313 ((if (not (org-region-active-p)) (org-at-item-p)
18314 (save-excursion (goto-char (region-beginning))
18315 (org-at-item-p)))
18316 (call-interactively 'org-indent-item-tree))
18317 (t (org-modifier-cursor-error))))
18319 (defun org-shiftmetaup (&optional arg)
18320 "Move subtree up or kill table row.
18321 Calls `org-move-subtree-up' or `org-table-kill-row' or
18322 `org-move-item-up' depending on context. See the individual commands
18323 for more information."
18324 (interactive "P")
18325 (cond
18326 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18327 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18328 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18329 ((org-at-item-p) (call-interactively 'org-move-item-up))
18330 (t (org-modifier-cursor-error))))
18332 (defun org-shiftmetadown (&optional arg)
18333 "Move subtree down or insert table row.
18334 Calls `org-move-subtree-down' or `org-table-insert-row' or
18335 `org-move-item-down', depending on context. See the individual
18336 commands for more information."
18337 (interactive "P")
18338 (cond
18339 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18340 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18341 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18342 ((org-at-item-p) (call-interactively 'org-move-item-down))
18343 (t (org-modifier-cursor-error))))
18345 (defsubst org-hidden-tree-error ()
18346 (error
18347 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18349 (defun org-metaleft (&optional arg)
18350 "Promote heading or move table column to left.
18351 Calls `org-do-promote' or `org-table-move-column', depending on context.
18352 With no specific context, calls the Emacs default `backward-word'.
18353 See the individual commands for more information."
18354 (interactive "P")
18355 (cond
18356 ((run-hook-with-args-until-success 'org-metaleft-hook))
18357 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18358 ((org-with-limited-levels
18359 (or (org-at-heading-p)
18360 (and (org-region-active-p)
18361 (save-excursion
18362 (goto-char (region-beginning))
18363 (org-at-heading-p)))))
18364 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18365 (call-interactively 'org-do-promote))
18366 ;; At an inline task.
18367 ((org-at-heading-p)
18368 (call-interactively 'org-inlinetask-promote))
18369 ((or (org-at-item-p)
18370 (and (org-region-active-p)
18371 (save-excursion
18372 (goto-char (region-beginning))
18373 (org-at-item-p))))
18374 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18375 (call-interactively 'org-outdent-item))
18376 (t (call-interactively 'backward-word))))
18378 (defun org-metaright (&optional arg)
18379 "Demote a subtree, a list item or move table column to right.
18380 In front of a drawer or a block keyword, indent it correctly.
18381 With no specific context, calls the Emacs default `forward-word'.
18382 See the individual commands for more information."
18383 (interactive "P")
18384 (cond
18385 ((run-hook-with-args-until-success 'org-metaright-hook))
18386 ((org-at-table-p) (call-interactively 'org-table-move-column))
18387 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18388 ((org-at-block-p) (call-interactively 'org-indent-block))
18389 ((org-with-limited-levels
18390 (or (org-at-heading-p)
18391 (and (org-region-active-p)
18392 (save-excursion
18393 (goto-char (region-beginning))
18394 (org-at-heading-p)))))
18395 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18396 (call-interactively 'org-do-demote))
18397 ;; At an inline task.
18398 ((org-at-heading-p)
18399 (call-interactively 'org-inlinetask-demote))
18400 ((or (org-at-item-p)
18401 (and (org-region-active-p)
18402 (save-excursion
18403 (goto-char (region-beginning))
18404 (org-at-item-p))))
18405 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18406 (call-interactively 'org-indent-item))
18407 (t (call-interactively 'forward-word))))
18409 (defun org-check-for-hidden (what)
18410 "Check if there are hidden headlines/items in the current visual line.
18411 WHAT can be either `headlines' or `items'. If the current line is
18412 an outline or item heading and it has a folded subtree below it,
18413 this function returns t, nil otherwise."
18414 (let ((re (cond
18415 ((eq what 'headlines) org-outline-regexp-bol)
18416 ((eq what 'items) (org-item-beginning-re))
18417 (t (error "This should not happen"))))
18418 beg end)
18419 (save-excursion
18420 (catch 'exit
18421 (unless (org-region-active-p)
18422 (setq beg (point-at-bol))
18423 (beginning-of-line 2)
18424 (while (and (not (eobp)) ;; this is like `next-line'
18425 (get-char-property (1- (point)) 'invisible))
18426 (beginning-of-line 2))
18427 (setq end (point))
18428 (goto-char beg)
18429 (goto-char (point-at-eol))
18430 (setq end (max end (point)))
18431 (while (re-search-forward re end t)
18432 (if (get-char-property (match-beginning 0) 'invisible)
18433 (throw 'exit t))))
18434 nil))))
18436 (defun org-metaup (&optional arg)
18437 "Move subtree up or move table row up.
18438 Calls `org-move-subtree-up' or `org-table-move-row' or
18439 `org-move-item-up', depending on context. See the individual commands
18440 for more information."
18441 (interactive "P")
18442 (cond
18443 ((run-hook-with-args-until-success 'org-metaup-hook))
18444 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18445 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18446 ((org-at-item-p) (call-interactively 'org-move-item-up))
18447 (t (transpose-lines 1) (beginning-of-line -1))))
18449 (defun org-metadown (&optional arg)
18450 "Move subtree down or move table row down.
18451 Calls `org-move-subtree-down' or `org-table-move-row' or
18452 `org-move-item-down', depending on context. See the individual
18453 commands for more information."
18454 (interactive "P")
18455 (cond
18456 ((run-hook-with-args-until-success 'org-metadown-hook))
18457 ((org-at-table-p) (call-interactively 'org-table-move-row))
18458 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18459 ((org-at-item-p) (call-interactively 'org-move-item-down))
18460 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18462 (defun org-shiftup (&optional arg)
18463 "Increase item in timestamp or increase priority of current headline.
18464 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18465 depending on context. See the individual commands for more information."
18466 (interactive "P")
18467 (cond
18468 ((run-hook-with-args-until-success 'org-shiftup-hook))
18469 ((and org-support-shift-select (org-region-active-p))
18470 (org-call-for-shift-select 'previous-line))
18471 ((org-at-timestamp-p t)
18472 (call-interactively (if org-edit-timestamp-down-means-later
18473 'org-timestamp-down 'org-timestamp-up)))
18474 ((and (not (eq org-support-shift-select 'always))
18475 org-enable-priority-commands
18476 (org-at-heading-p))
18477 (call-interactively 'org-priority-up))
18478 ((and (not org-support-shift-select) (org-at-item-p))
18479 (call-interactively 'org-previous-item))
18480 ((org-clocktable-try-shift 'up arg))
18481 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18482 (org-support-shift-select
18483 (org-call-for-shift-select 'previous-line))
18484 (t (org-shiftselect-error))))
18486 (defun org-shiftdown (&optional arg)
18487 "Decrease item in timestamp or decrease priority of current headline.
18488 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18489 depending on context. See the individual commands for more information."
18490 (interactive "P")
18491 (cond
18492 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18493 ((and org-support-shift-select (org-region-active-p))
18494 (org-call-for-shift-select 'next-line))
18495 ((org-at-timestamp-p t)
18496 (call-interactively (if org-edit-timestamp-down-means-later
18497 'org-timestamp-up 'org-timestamp-down)))
18498 ((and (not (eq org-support-shift-select 'always))
18499 org-enable-priority-commands
18500 (org-at-heading-p))
18501 (call-interactively 'org-priority-down))
18502 ((and (not org-support-shift-select) (org-at-item-p))
18503 (call-interactively 'org-next-item))
18504 ((org-clocktable-try-shift 'down arg))
18505 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18506 (org-support-shift-select
18507 (org-call-for-shift-select 'next-line))
18508 (t (org-shiftselect-error))))
18510 (defun org-shiftright (&optional arg)
18511 "Cycle the thing at point or in the current line, depending on context.
18512 Depending on context, this does one of the following:
18514 - switch a timestamp at point one day into the future
18515 - on a headline, switch to the next TODO keyword.
18516 - on an item, switch entire list to the next bullet type
18517 - on a property line, switch to the next allowed value
18518 - on a clocktable definition line, move time block into the future"
18519 (interactive "P")
18520 (cond
18521 ((run-hook-with-args-until-success 'org-shiftright-hook))
18522 ((and org-support-shift-select (org-region-active-p))
18523 (org-call-for-shift-select 'forward-char))
18524 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18525 ((and (not (eq org-support-shift-select 'always))
18526 (org-at-heading-p))
18527 (let ((org-inhibit-logging
18528 (not org-treat-S-cursor-todo-selection-as-state-change))
18529 (org-inhibit-blocking
18530 (not org-treat-S-cursor-todo-selection-as-state-change)))
18531 (org-call-with-arg 'org-todo 'right)))
18532 ((or (and org-support-shift-select
18533 (not (eq org-support-shift-select 'always))
18534 (org-at-item-bullet-p))
18535 (and (not org-support-shift-select) (org-at-item-p)))
18536 (org-call-with-arg 'org-cycle-list-bullet nil))
18537 ((and (not (eq org-support-shift-select 'always))
18538 (org-at-property-p))
18539 (call-interactively 'org-property-next-allowed-value))
18540 ((org-clocktable-try-shift 'right arg))
18541 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18542 (org-support-shift-select
18543 (org-call-for-shift-select 'forward-char))
18544 (t (org-shiftselect-error))))
18546 (defun org-shiftleft (&optional arg)
18547 "Cycle the thing at point or in the current line, depending on context.
18548 Depending on context, this does one of the following:
18550 - switch a timestamp at point one day into the past
18551 - on a headline, switch to the previous TODO keyword.
18552 - on an item, switch entire list to the previous bullet type
18553 - on a property line, switch to the previous allowed value
18554 - on a clocktable definition line, move time block into the past"
18555 (interactive "P")
18556 (cond
18557 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18558 ((and org-support-shift-select (org-region-active-p))
18559 (org-call-for-shift-select 'backward-char))
18560 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18561 ((and (not (eq org-support-shift-select 'always))
18562 (org-at-heading-p))
18563 (let ((org-inhibit-logging
18564 (not org-treat-S-cursor-todo-selection-as-state-change))
18565 (org-inhibit-blocking
18566 (not org-treat-S-cursor-todo-selection-as-state-change)))
18567 (org-call-with-arg 'org-todo 'left)))
18568 ((or (and org-support-shift-select
18569 (not (eq org-support-shift-select 'always))
18570 (org-at-item-bullet-p))
18571 (and (not org-support-shift-select) (org-at-item-p)))
18572 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18573 ((and (not (eq org-support-shift-select 'always))
18574 (org-at-property-p))
18575 (call-interactively 'org-property-previous-allowed-value))
18576 ((org-clocktable-try-shift 'left arg))
18577 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18578 (org-support-shift-select
18579 (org-call-for-shift-select 'backward-char))
18580 (t (org-shiftselect-error))))
18582 (defun org-shiftcontrolright ()
18583 "Switch to next TODO set."
18584 (interactive)
18585 (cond
18586 ((and org-support-shift-select (org-region-active-p))
18587 (org-call-for-shift-select 'forward-word))
18588 ((and (not (eq org-support-shift-select 'always))
18589 (org-at-heading-p))
18590 (org-call-with-arg 'org-todo 'nextset))
18591 (org-support-shift-select
18592 (org-call-for-shift-select 'forward-word))
18593 (t (org-shiftselect-error))))
18595 (defun org-shiftcontrolleft ()
18596 "Switch to previous TODO set."
18597 (interactive)
18598 (cond
18599 ((and org-support-shift-select (org-region-active-p))
18600 (org-call-for-shift-select 'backward-word))
18601 ((and (not (eq org-support-shift-select 'always))
18602 (org-at-heading-p))
18603 (org-call-with-arg 'org-todo 'previousset))
18604 (org-support-shift-select
18605 (org-call-for-shift-select 'backward-word))
18606 (t (org-shiftselect-error))))
18608 (defun org-shiftcontrolup ()
18609 "Change timestamps synchronously up in CLOCK log lines."
18610 (interactive)
18611 (cond ((and (not org-support-shift-select)
18612 (org-at-clock-log-p)
18613 (org-at-timestamp-p t))
18614 (org-clock-timestamps-up))
18615 (t (org-shiftselect-error))))
18617 (defun org-shiftcontroldown ()
18618 "Change timestamps synchronously down in CLOCK log lines."
18619 (interactive)
18620 (cond ((and (not org-support-shift-select)
18621 (org-at-clock-log-p)
18622 (org-at-timestamp-p t))
18623 (org-clock-timestamps-down))
18624 (t (org-shiftselect-error))))
18626 (defun org-ctrl-c-ret ()
18627 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18628 (interactive)
18629 (cond
18630 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18631 (t (call-interactively 'org-insert-heading))))
18633 (defun org-find-visible ()
18634 (let ((s (point)))
18635 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18636 (get-char-property s 'invisible)))
18638 (defun org-find-invisible ()
18639 (let ((s (point)))
18640 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18641 (not (get-char-property s 'invisible))))
18644 (defun org-copy-visible (beg end)
18645 "Copy the visible parts of the region."
18646 (interactive "r")
18647 (let (snippets s)
18648 (save-excursion
18649 (save-restriction
18650 (narrow-to-region beg end)
18651 (setq s (goto-char (point-min)))
18652 (while (not (= (point) (point-max)))
18653 (goto-char (org-find-invisible))
18654 (push (buffer-substring s (point)) snippets)
18655 (setq s (goto-char (org-find-visible))))))
18656 (kill-new (apply 'concat (nreverse snippets)))))
18658 (defun org-copy-special ()
18659 "Copy region in table or copy current subtree.
18660 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18661 See the individual commands for more information."
18662 (interactive)
18663 (call-interactively
18664 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18666 (defun org-cut-special ()
18667 "Cut region in table or cut current subtree.
18668 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18669 See the individual commands for more information."
18670 (interactive)
18671 (call-interactively
18672 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18674 (defun org-paste-special (arg)
18675 "Paste rectangular region into table, or past subtree relative to level.
18676 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18677 See the individual commands for more information."
18678 (interactive "P")
18679 (if (org-at-table-p)
18680 (org-table-paste-rectangle)
18681 (org-paste-subtree arg)))
18683 (defun org-edit-special (&optional arg)
18684 "Call a special editor for the stuff at point.
18685 When at a table, call the formula editor with `org-table-edit-formulas'.
18686 When at the first line of an src example, call `org-edit-src-code'.
18687 When in an #+include line, visit the include file. Otherwise call
18688 `ffap' to visit the file at point."
18689 (interactive)
18690 ;; possibly prep session before editing source
18691 (when arg
18692 (let* ((info (org-babel-get-src-block-info))
18693 (lang (nth 0 info))
18694 (params (nth 2 info))
18695 (session (cdr (assoc :session params))))
18696 (when (and info session) ;; we are in a source-code block with a session
18697 (funcall
18698 (intern (concat "org-babel-prep-session:" lang)) session params))))
18699 (cond ;; proceed with `org-edit-special'
18700 ((save-excursion
18701 (beginning-of-line 1)
18702 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18703 (find-file (org-trim (match-string 1))))
18704 ((org-edit-src-code))
18705 ((org-edit-fixed-width-region))
18706 ((org-at-table.el-p)
18707 (org-edit-src-code))
18708 ((or (org-at-table-p)
18709 (save-excursion
18710 (beginning-of-line 1)
18711 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18712 (call-interactively 'org-table-edit-formulas))
18713 (t (call-interactively 'ffap))))
18715 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18716 (defun org-ctrl-c-ctrl-c (&optional arg)
18717 "Set tags in headline, or update according to changed information at point.
18719 This command does many different things, depending on context:
18721 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18722 this is what we do.
18724 - If the cursor is on a statistics cookie, update it.
18726 - If the cursor is in a headline, prompt for tags and insert them
18727 into the current line, aligned to `org-tags-column'. When called
18728 with prefix arg, realign all tags in the current buffer.
18730 - If the cursor is in one of the special #+KEYWORD lines, this
18731 triggers scanning the buffer for these lines and updating the
18732 information.
18734 - If the cursor is inside a table, realign the table. This command
18735 works even if the automatic table editor has been turned off.
18737 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18738 the entire table.
18740 - If the cursor is at a footnote reference or definition, jump to
18741 the corresponding definition or references, respectively.
18743 - If the cursor is a the beginning of a dynamic block, update it.
18745 - If the current buffer is a capture buffer, close note and file it.
18747 - If the cursor is on a <<<target>>>, update radio targets and
18748 corresponding links in this buffer.
18750 - If the cursor is on a numbered item in a plain list, renumber the
18751 ordered list.
18753 - If the cursor is on a checkbox, toggle it.
18755 - If the cursor is on a code block, evaluate it. The variable
18756 `org-confirm-babel-evaluate' can be used to control prompting
18757 before code block evaluation, by default every code block
18758 evaluation requires confirmation. Code block evaluation can be
18759 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18760 (interactive "P")
18761 (let ((org-enable-table-editor t))
18762 (cond
18763 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18764 org-occur-highlights
18765 org-latex-fragment-image-overlays)
18766 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18767 (org-remove-occur-highlights)
18768 (org-remove-latex-fragment-image-overlays)
18769 (message "Temporary highlights/overlays removed from current buffer"))
18770 ((and (local-variable-p 'org-finish-function (current-buffer))
18771 (fboundp org-finish-function))
18772 (funcall org-finish-function))
18773 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18774 ((org-in-regexp org-ts-regexp-both)
18775 (org-timestamp-change 0 'day))
18776 ((or (looking-at org-property-start-re)
18777 (org-at-property-p))
18778 (call-interactively 'org-property-action))
18779 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18780 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18781 (or (org-at-heading-p) (org-at-item-p)))
18782 (call-interactively 'org-update-statistics-cookies))
18783 ((org-at-heading-p) (call-interactively 'org-set-tags))
18784 ((org-at-table.el-p)
18785 (message "Use C-c ' to edit table.el tables"))
18786 ((org-at-table-p)
18787 (org-table-maybe-eval-formula)
18788 (if arg
18789 (call-interactively 'org-table-recalculate)
18790 (org-table-maybe-recalculate-line))
18791 (call-interactively 'org-table-align)
18792 (orgtbl-send-table 'maybe))
18793 ((or (org-footnote-at-reference-p)
18794 (org-footnote-at-definition-p))
18795 (call-interactively 'org-footnote-action))
18796 ((org-at-item-checkbox-p)
18797 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18798 ;; list only if at top item.
18799 (let* ((cbox (match-string 1))
18800 (struct (org-list-struct))
18801 (old-struct (copy-tree struct))
18802 (parents (org-list-parents-alist struct))
18803 (orderedp (org-entry-get nil "ORDERED"))
18804 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18805 block-item)
18806 ;; Use a light version of `org-toggle-checkbox' to avoid
18807 ;; computing list structure twice.
18808 (let ((new-box (cond
18809 ((equal arg '(16)) "[-]")
18810 ((equal arg '(4)) nil)
18811 ((equal "[X]" cbox) "[ ]")
18812 (t "[X]"))))
18813 (if (and firstp arg)
18814 ;; If at first item of sub-list, remove check-box from
18815 ;; every item at the same level.
18816 (mapc
18817 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18818 (org-list-get-all-items
18819 (point-at-bol) struct (org-list-prevs-alist struct)))
18820 (org-list-set-checkbox (point-at-bol) struct new-box)))
18821 ;; Replicate `org-list-write-struct', while grabbing a return
18822 ;; value from `org-list-struct-fix-box'.
18823 (org-list-struct-fix-ind struct parents 2)
18824 (org-list-struct-fix-item-end struct)
18825 (let ((prevs (org-list-prevs-alist struct)))
18826 (org-list-struct-fix-bul struct prevs)
18827 (org-list-struct-fix-ind struct parents)
18828 (setq block-item
18829 (org-list-struct-fix-box struct parents prevs orderedp)))
18830 (org-list-struct-apply-struct struct old-struct)
18831 (org-update-checkbox-count-maybe)
18832 (when block-item
18833 (message
18834 "Checkboxes were removed due to unchecked box at line %d"
18835 (org-current-line block-item)))
18836 (when firstp (org-list-send-list 'maybe))))
18837 ((org-at-item-p)
18838 ;; Cursor at an item: repair list. Do checkbox related actions
18839 ;; only if function was called with an argument. Send list only
18840 ;; if at top item.
18841 (let* ((struct (org-list-struct))
18842 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18843 old-struct)
18844 (when arg
18845 (setq old-struct (copy-tree struct))
18846 (if firstp
18847 ;; If at first item of sub-list, add check-box to every
18848 ;; item at the same level.
18849 (mapc
18850 (lambda (pos)
18851 (unless (org-list-get-checkbox pos struct)
18852 (org-list-set-checkbox pos struct "[ ]")))
18853 (org-list-get-all-items
18854 (point-at-bol) struct (org-list-prevs-alist struct)))
18855 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18856 (org-list-write-struct
18857 struct (org-list-parents-alist struct) old-struct)
18858 (when arg (org-update-checkbox-count-maybe))
18859 (when firstp (org-list-send-list 'maybe))))
18860 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18861 ;; Dynamic block
18862 (beginning-of-line 1)
18863 (save-excursion (org-update-dblock)))
18864 ((save-excursion
18865 (let ((case-fold-search t))
18866 (beginning-of-line 1)
18867 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
18868 (cond
18869 ((or (equal (match-string 1) "TBLFM")
18870 (equal (match-string 1) "tblfm"))
18871 ;; Recalculate the table before this line
18872 (save-excursion
18873 (beginning-of-line 1)
18874 (skip-chars-backward " \r\n\t")
18875 (if (org-at-table-p)
18876 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18878 (let ((org-inhibit-startup-visibility-stuff t)
18879 (org-startup-align-all-tables nil))
18880 (when (boundp 'org-table-coordinate-overlays)
18881 (mapc 'delete-overlay org-table-coordinate-overlays)
18882 (setq org-table-coordinate-overlays nil))
18883 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18884 (message "Local setup has been refreshed"))))
18885 ((org-clock-update-time-maybe))
18887 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18888 (error "C-c C-c can do nothing useful at this location"))))))
18890 (defun org-mode-restart ()
18891 "Restart Org-mode, to scan again for special lines.
18892 Also updates the keyword regular expressions."
18893 (interactive)
18894 (org-mode)
18895 (message "Org-mode restarted"))
18897 (defun org-kill-note-or-show-branches ()
18898 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18899 (interactive)
18900 (if (not org-finish-function)
18901 (progn
18902 (hide-subtree)
18903 (call-interactively 'show-branches))
18904 (let ((org-note-abort t))
18905 (funcall org-finish-function))))
18907 (defun org-return (&optional indent)
18908 "Goto next table row or insert a newline.
18909 Calls `org-table-next-row' or `newline', depending on context.
18910 See the individual commands for more information."
18911 (interactive)
18912 (let (org-ts-what)
18913 (cond
18914 ((or (bobp) (org-in-src-block-p))
18915 (if indent (newline-and-indent) (newline)))
18916 ((org-at-table-p)
18917 (org-table-justify-field-maybe)
18918 (call-interactively 'org-table-next-row))
18919 ;; when `newline-and-indent' is called within a list, make sure
18920 ;; text moved stays inside the item.
18921 ((and (org-in-item-p) indent)
18922 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18923 (progn
18924 (save-match-data (newline))
18925 (org-indent-line-to (length (match-string 0))))
18926 (let ((ind (org-get-indentation)))
18927 (newline)
18928 (if (org-looking-back org-list-end-re)
18929 (org-indent-line-function)
18930 (org-indent-line-to ind)))))
18931 ((and org-return-follows-link
18932 (org-at-timestamp-p t)
18933 (not (eq org-ts-what 'after)))
18934 (org-follow-timestamp-link))
18935 ((and org-return-follows-link
18936 (let ((tprop (get-text-property (point) 'face)))
18937 (or (eq tprop 'org-link)
18938 (and (listp tprop) (memq 'org-link tprop)))))
18939 (call-interactively 'org-open-at-point))
18940 ((and (org-at-heading-p)
18941 (looking-at
18942 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18943 (org-show-entry)
18944 (end-of-line 1)
18945 (newline))
18946 (t (if indent (newline-and-indent) (newline))))))
18948 (defun org-return-indent ()
18949 "Goto next table row or insert a newline and indent.
18950 Calls `org-table-next-row' or `newline-and-indent', depending on
18951 context. See the individual commands for more information."
18952 (interactive)
18953 (org-return t))
18955 (defun org-ctrl-c-star ()
18956 "Compute table, or change heading status of lines.
18957 Calls `org-table-recalculate' or `org-toggle-heading',
18958 depending on context."
18959 (interactive)
18960 (cond
18961 ((org-at-table-p)
18962 (call-interactively 'org-table-recalculate))
18964 ;; Convert all lines in region to list items
18965 (call-interactively 'org-toggle-heading))))
18967 (defun org-ctrl-c-minus ()
18968 "Insert separator line in table or modify bullet status of line.
18969 Also turns a plain line or a region of lines into list items.
18970 Calls `org-table-insert-hline', `org-toggle-item', or
18971 `org-cycle-list-bullet', depending on context."
18972 (interactive)
18973 (cond
18974 ((org-at-table-p)
18975 (call-interactively 'org-table-insert-hline))
18976 ((org-region-active-p)
18977 (call-interactively 'org-toggle-item))
18978 ((org-in-item-p)
18979 (call-interactively 'org-cycle-list-bullet))
18981 (call-interactively 'org-toggle-item))))
18983 (defun org-toggle-item (arg)
18984 "Convert headings or normal lines to items, items to normal lines.
18985 If there is no active region, only the current line is considered.
18987 If the first non blank line in the region is an headline, convert
18988 all headlines to items, shifting text accordingly.
18990 If it is an item, convert all items to normal lines.
18992 If it is normal text, change region into an item. With a prefix
18993 argument ARG, change each line in region into an item."
18994 (interactive "P")
18995 (let ((shift-text
18996 (function
18997 ;; Shift text in current section to IND, from point to END.
18998 ;; The function leaves point to END line.
18999 (lambda (ind end)
19000 (let ((min-i 1000) (end (copy-marker end)))
19001 ;; First determine the minimum indentation (MIN-I) of
19002 ;; the text.
19003 (save-excursion
19004 (catch 'exit
19005 (while (< (point) end)
19006 (let ((i (org-get-indentation)))
19007 (cond
19008 ;; Skip blank lines and inline tasks.
19009 ((looking-at "^[ \t]*$"))
19010 ((looking-at org-outline-regexp-bol))
19011 ;; We can't find less than 0 indentation.
19012 ((zerop i) (throw 'exit (setq min-i 0)))
19013 ((< i min-i) (setq min-i i))))
19014 (forward-line))))
19015 ;; Then indent each line so that a line indented to
19016 ;; MIN-I becomes indented to IND. Ignore blank lines
19017 ;; and inline tasks in the process.
19018 (let ((delta (- ind min-i)))
19019 (while (< (point) end)
19020 (unless (or (looking-at "^[ \t]*$")
19021 (looking-at org-outline-regexp-bol))
19022 (org-indent-line-to (+ (org-get-indentation) delta)))
19023 (forward-line)))))))
19024 (skip-blanks
19025 (function
19026 ;; Return beginning of first non-blank line, starting from
19027 ;; line at POS.
19028 (lambda (pos)
19029 (save-excursion
19030 (goto-char pos)
19031 (skip-chars-forward " \r\t\n")
19032 (point-at-bol)))))
19033 beg end)
19034 ;; Determine boundaries of changes.
19035 (if (org-region-active-p)
19036 (setq beg (funcall skip-blanks (region-beginning))
19037 end (copy-marker (region-end)))
19038 (setq beg (funcall skip-blanks (point-at-bol))
19039 end (copy-marker (point-at-eol))))
19040 ;; Depending on the starting line, choose an action on the text
19041 ;; between BEG and END.
19042 (org-with-limited-levels
19043 (save-excursion
19044 (goto-char beg)
19045 (cond
19046 ;; Case 1. Start at an item: de-itemize. Note that it only
19047 ;; happens when a region is active: `org-ctrl-c-minus'
19048 ;; would call `org-cycle-list-bullet' otherwise.
19049 ((org-at-item-p)
19050 (while (< (point) end)
19051 (when (org-at-item-p)
19052 (skip-chars-forward " \t")
19053 (delete-region (point) (match-end 0)))
19054 (forward-line)))
19055 ;; Case 2. Start at an heading: convert to items.
19056 ((org-at-heading-p)
19057 (let* ((bul (org-list-bullet-string "-"))
19058 (bul-len (length bul))
19059 ;; Indentation of the first heading. It should be
19060 ;; relative to the indentation of its parent, if any.
19061 (start-ind (save-excursion
19062 (cond
19063 ((not org-adapt-indentation) 0)
19064 ((not (outline-previous-heading)) 0)
19065 (t (length (match-string 0))))))
19066 ;; Level of first heading. Further headings will be
19067 ;; compared to it to determine hierarchy in the list.
19068 (ref-level (org-reduced-level (org-outline-level))))
19069 (while (< (point) end)
19070 (let* ((level (org-reduced-level (org-outline-level)))
19071 (delta (max 0 (- level ref-level))))
19072 ;; If current headline is less indented than the first
19073 ;; one, set it as reference, in order to preserve
19074 ;; subtrees.
19075 (when (< level ref-level) (setq ref-level level))
19076 (replace-match bul t t)
19077 (org-indent-line-to (+ start-ind (* delta bul-len)))
19078 ;; Ensure all text down to END (or SECTION-END) belongs
19079 ;; to the newly created item.
19080 (let ((section-end (save-excursion
19081 (or (outline-next-heading) (point)))))
19082 (forward-line)
19083 (funcall shift-text
19084 (+ start-ind (* (1+ delta) bul-len))
19085 (min end section-end)))))))
19086 ;; Case 3. Normal line with ARG: turn each non-item line into
19087 ;; an item.
19088 (arg
19089 (while (< (point) end)
19090 (unless (or (org-at-heading-p) (org-at-item-p))
19091 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19092 (replace-match
19093 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19094 (forward-line)))
19095 ;; Case 4. Normal line without ARG: make the first line of
19096 ;; region an item, and shift indentation of others
19097 ;; lines to set them as item's body.
19098 (t (let* ((bul (org-list-bullet-string "-"))
19099 (bul-len (length bul))
19100 (ref-ind (org-get-indentation)))
19101 (skip-chars-forward " \t")
19102 (insert bul)
19103 (forward-line)
19104 (while (< (point) end)
19105 ;; Ensure that lines less indented than first one
19106 ;; still get included in item body.
19107 (funcall shift-text
19108 (+ ref-ind bul-len)
19109 (min end (save-excursion (or (outline-next-heading)
19110 (point)))))
19111 (forward-line)))))))))
19113 (defun org-toggle-heading (&optional nstars)
19114 "Convert headings to normal text, or items or text to headings.
19115 If there is no active region, only the current line is considered.
19117 With a \\[universal-argument] prefix, convert the whole list at
19118 point into heading.
19120 In a region:
19122 - If the first non blank line is an headline, remove the stars
19123 from all headlines in the region.
19125 - If it is a normal line turn each and every normal line (i.e. not an
19126 heading or an item) in the region into a heading.
19128 - If it is a plain list item, turn all plain list items into headings.
19130 When converting a line into a heading, the number of stars is chosen
19131 such that the lines become children of the current entry. However,
19132 when a prefix argument is given, its value determines the number of
19133 stars to add."
19134 (interactive "P")
19135 (let ((skip-blanks
19136 (function
19137 ;; Return beginning of first non-blank line, starting from
19138 ;; line at POS.
19139 (lambda (pos)
19140 (save-excursion
19141 (goto-char pos)
19142 (skip-chars-forward " \r\t\n")
19143 (point-at-bol)))))
19144 beg end)
19145 ;; Determine boundaries of changes. If a universal prefix has
19146 ;; been given, put the list in a region. If region ends at a bol,
19147 ;; do not consider the last line to be in the region.
19149 (when (and current-prefix-arg (org-at-item-p))
19150 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19151 (org-mark-list))
19153 (if (org-region-active-p)
19154 (setq beg (funcall skip-blanks (region-beginning))
19155 end (copy-marker (save-excursion
19156 (goto-char (region-end))
19157 (if (bolp) (point) (point-at-eol)))))
19158 (setq beg (funcall skip-blanks (point-at-bol))
19159 end (copy-marker (point-at-eol))))
19160 ;; Ensure inline tasks don't count as headings.
19161 (org-with-limited-levels
19162 (save-excursion
19163 (goto-char beg)
19164 (cond
19165 ;; Case 1. Started at an heading: de-star headings.
19166 ((org-at-heading-p)
19167 (while (< (point) end)
19168 (when (org-at-heading-p t)
19169 (looking-at org-outline-regexp) (replace-match ""))
19170 (forward-line)))
19171 ;; Case 2. Started at an item: change items into headlines.
19172 ;; One star will be added by `org-list-to-subtree'.
19173 ((org-at-item-p)
19174 (let* ((stars (make-string
19175 (if nstars
19176 ;; subtract the star that will be added again by
19177 ;; `org-list-to-subtree'
19178 (1- (prefix-numeric-value current-prefix-arg))
19179 (or (org-current-level) 0))
19180 ?*))
19181 (add-stars
19182 (cond (nstars "") ; stars from prefix only
19183 ((equal stars "") "") ; before first heading
19184 (org-odd-levels-only "*") ; inside heading, odd
19185 (t "")))) ; inside heading, oddeven
19186 (while (< (point) end)
19187 (when (org-at-item-p)
19188 ;; Pay attention to cases when region ends before list.
19189 (let* ((struct (org-list-struct))
19190 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19191 (save-restriction
19192 (narrow-to-region (point) list-end)
19193 (insert
19194 (org-list-to-subtree
19195 (org-list-parse-list t)
19196 '(:istart (concat stars add-stars (funcall get-stars depth))
19197 :icount (concat stars add-stars (funcall get-stars depth))))))))
19198 (forward-line))))
19199 ;; Case 3. Started at normal text: make every line an heading,
19200 ;; skipping headlines and items.
19201 (t (let* ((stars (make-string
19202 (if nstars
19203 (prefix-numeric-value current-prefix-arg)
19204 (or (org-current-level) 0))
19205 ?*))
19206 (add-stars
19207 (cond (nstars "") ; stars from prefix only
19208 ((equal stars "") "*") ; before first heading
19209 (org-odd-levels-only "**") ; inside heading, odd
19210 (t "*"))) ; inside heading, oddeven
19211 (rpl (concat stars add-stars " ")))
19212 (while (< (point) end)
19213 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
19214 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19215 (replace-match (concat rpl (match-string 2))))
19216 (forward-line)))))))))
19218 (defun org-meta-return (&optional arg)
19219 "Insert a new heading or wrap a region in a table.
19220 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19221 See the individual commands for more information."
19222 (interactive "P")
19223 (cond
19224 ((run-hook-with-args-until-success 'org-metareturn-hook))
19225 ((or (org-at-drawer-p) (org-at-property-p))
19226 (newline-and-indent))
19227 ((org-at-table-p)
19228 (call-interactively 'org-table-wrap-region))
19229 (t (call-interactively 'org-insert-heading))))
19231 ;;; Menu entries
19233 ;; Define the Org-mode menus
19234 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19235 '("Tbl"
19236 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19237 ["Next Field" org-cycle (org-at-table-p)]
19238 ["Previous Field" org-shifttab (org-at-table-p)]
19239 ["Next Row" org-return (org-at-table-p)]
19240 "--"
19241 ["Blank Field" org-table-blank-field (org-at-table-p)]
19242 ["Edit Field" org-table-edit-field (org-at-table-p)]
19243 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19244 "--"
19245 ("Column"
19246 ["Move Column Left" org-metaleft (org-at-table-p)]
19247 ["Move Column Right" org-metaright (org-at-table-p)]
19248 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19249 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19250 ("Row"
19251 ["Move Row Up" org-metaup (org-at-table-p)]
19252 ["Move Row Down" org-metadown (org-at-table-p)]
19253 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19254 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19255 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19256 "--"
19257 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19258 ("Rectangle"
19259 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19260 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19261 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19262 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19263 "--"
19264 ("Calculate"
19265 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19266 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19267 ["Edit Formulas" org-edit-special (org-at-table-p)]
19268 "--"
19269 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19270 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19271 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19272 "--"
19273 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19274 "--"
19275 ["Sum Column/Rectangle" org-table-sum
19276 (or (org-at-table-p) (org-region-active-p))]
19277 ["Which Column?" org-table-current-column (org-at-table-p)])
19278 ["Debug Formulas"
19279 org-table-toggle-formula-debugger
19280 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19281 ["Show Col/Row Numbers"
19282 org-table-toggle-coordinate-overlays
19283 :style toggle
19284 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19285 "--"
19286 ["Create" org-table-create (and (not (org-at-table-p))
19287 org-enable-table-editor)]
19288 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19289 ["Import from File" org-table-import (not (org-at-table-p))]
19290 ["Export to File" org-table-export (org-at-table-p)]
19291 "--"
19292 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19294 (easy-menu-define org-org-menu org-mode-map "Org menu"
19295 '("Org"
19296 ("Show/Hide"
19297 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19298 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19299 ["Sparse Tree..." org-sparse-tree t]
19300 ["Reveal Context" org-reveal t]
19301 ["Show All" show-all t]
19302 "--"
19303 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19304 "--"
19305 ["New Heading" org-insert-heading t]
19306 ("Navigate Headings"
19307 ["Up" outline-up-heading t]
19308 ["Next" outline-next-visible-heading t]
19309 ["Previous" outline-previous-visible-heading t]
19310 ["Next Same Level" outline-forward-same-level t]
19311 ["Previous Same Level" outline-backward-same-level t]
19312 "--"
19313 ["Jump" org-goto t])
19314 ("Edit Structure"
19315 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19316 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19317 "--"
19318 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19319 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19320 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19321 "--"
19322 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19323 "--"
19324 ["Copy visible text" org-copy-visible t]
19325 "--"
19326 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19327 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19328 ["Demote Heading" org-metaright (not (org-at-table-p))]
19329 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19330 "--"
19331 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19332 "--"
19333 ["Convert to odd levels" org-convert-to-odd-levels t]
19334 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19335 ("Editing"
19336 ["Emphasis..." org-emphasize t]
19337 ["Edit Source Example" org-edit-special t]
19338 "--"
19339 ["Footnote new/jump" org-footnote-action t]
19340 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19341 ("Archive"
19342 ["Archive (default method)" org-archive-subtree-default t]
19343 "--"
19344 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19345 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19346 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19348 "--"
19349 ("Hyperlinks"
19350 ["Store Link (Global)" org-store-link t]
19351 ["Find existing link to here" org-occur-link-in-agenda-files t]
19352 ["Insert Link" org-insert-link t]
19353 ["Follow Link" org-open-at-point t]
19354 "--"
19355 ["Next link" org-next-link t]
19356 ["Previous link" org-previous-link t]
19357 "--"
19358 ["Descriptive Links"
19359 org-toggle-link-display
19360 :style radio
19361 :selected org-descriptive-links
19363 ["Literal Links"
19364 org-toggle-link-display
19365 :style radio
19366 :selected (not org-descriptive-links)])
19367 "--"
19368 ("TODO Lists"
19369 ["TODO/DONE/-" org-todo t]
19370 ("Select keyword"
19371 ["Next keyword" org-shiftright (org-at-heading-p)]
19372 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19373 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19374 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19375 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19376 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19377 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19378 "--"
19379 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19380 :selected org-enforce-todo-dependencies :style toggle :active t]
19381 "Settings for tree at point"
19382 ["Do Children sequentially" org-toggle-ordered-property :style radio
19383 :selected (org-entry-get nil "ORDERED")
19384 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19385 ["Do Children parallel" org-toggle-ordered-property :style radio
19386 :selected (not (org-entry-get nil "ORDERED"))
19387 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19388 "--"
19389 ["Set Priority" org-priority t]
19390 ["Priority Up" org-shiftup t]
19391 ["Priority Down" org-shiftdown t]
19392 "--"
19393 ["Get news from all feeds" org-feed-update-all t]
19394 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19395 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19396 ("TAGS and Properties"
19397 ["Set Tags" org-set-tags-command t]
19398 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19399 "--"
19400 ["Set property" org-set-property t]
19401 ["Column view of properties" org-columns t]
19402 ["Insert Column View DBlock" org-insert-columns-dblock t])
19403 ("Dates and Scheduling"
19404 ["Timestamp" org-time-stamp t]
19405 ["Timestamp (inactive)" org-time-stamp-inactive t]
19406 ("Change Date"
19407 ["1 Day Later" org-shiftright t]
19408 ["1 Day Earlier" org-shiftleft t]
19409 ["1 ... Later" org-shiftup t]
19410 ["1 ... Earlier" org-shiftdown t])
19411 ["Compute Time Range" org-evaluate-time-range t]
19412 ["Schedule Item" org-schedule t]
19413 ["Deadline" org-deadline t]
19414 "--"
19415 ["Custom time format" org-toggle-time-stamp-overlays
19416 :style radio :selected org-display-custom-times]
19417 "--"
19418 ["Goto Calendar" org-goto-calendar t]
19419 ["Date from Calendar" org-date-from-calendar t]
19420 "--"
19421 ["Start/Restart Timer" org-timer-start t]
19422 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19423 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19424 ["Insert Timer String" org-timer t]
19425 ["Insert Timer Item" org-timer-item t])
19426 ("Logging work"
19427 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19428 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19429 ["Clock out" org-clock-out t]
19430 ["Clock cancel" org-clock-cancel t]
19431 "--"
19432 ["Mark as default task" org-clock-mark-default-task t]
19433 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19434 ["Goto running clock" org-clock-goto t]
19435 "--"
19436 ["Display times" org-clock-display t]
19437 ["Create clock table" org-clock-report t]
19438 "--"
19439 ["Record DONE time"
19440 (progn (setq org-log-done (not org-log-done))
19441 (message "Switching to %s will %s record a timestamp"
19442 (car org-done-keywords)
19443 (if org-log-done "automatically" "not")))
19444 :style toggle :selected org-log-done])
19445 "--"
19446 ["Agenda Command..." org-agenda t]
19447 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19448 ("File List for Agenda")
19449 ("Special views current file"
19450 ["TODO Tree" org-show-todo-tree t]
19451 ["Check Deadlines" org-check-deadlines t]
19452 ["Timeline" org-timeline t]
19453 ["Tags/Property tree" org-match-sparse-tree t])
19454 "--"
19455 ["Export/Publish..." org-export t]
19456 ("LaTeX"
19457 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19458 :selected org-cdlatex-mode]
19459 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19460 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19461 ["Modify math symbol" org-cdlatex-math-modify
19462 (org-inside-LaTeX-fragment-p)]
19463 ["Insert citation" org-reftex-citation t]
19464 "--"
19465 ["Template for BEAMER" (progn (require 'org-beamer)
19466 (org-insert-beamer-options-template)) t])
19467 "--"
19468 ("MobileOrg"
19469 ["Push Files and Views" org-mobile-push t]
19470 ["Get Captured and Flagged" org-mobile-pull t]
19471 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19472 "--"
19473 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19474 "--"
19475 ("Documentation"
19476 ["Show Version" org-version t]
19477 ["Info Documentation" org-info t])
19478 ("Customize"
19479 ["Browse Org Group" org-customize t]
19480 "--"
19481 ["Expand This Menu" org-create-customize-menu
19482 (fboundp 'customize-menu-create)])
19483 ["Send bug report" org-submit-bug-report t]
19484 "--"
19485 ("Refresh/Reload"
19486 ["Refresh setup current buffer" org-mode-restart t]
19487 ["Reload Org (after update)" org-reload t]
19488 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19491 (defun org-info (&optional node)
19492 "Read documentation for Org-mode in the info system.
19493 With optional NODE, go directly to that node."
19494 (interactive)
19495 (info (format "(org)%s" (or node ""))))
19497 ;;;###autoload
19498 (defun org-submit-bug-report ()
19499 "Submit a bug report on Org-mode via mail.
19501 Don't hesitate to report any problems or inaccurate documentation.
19503 If you don't have setup sending mail from (X)Emacs, please copy the
19504 output buffer into your mail program, as it gives us important
19505 information about your Org-mode version and configuration."
19506 (interactive)
19507 (require 'reporter)
19508 (org-load-modules-maybe)
19509 (org-require-autoloaded-modules)
19510 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19511 (reporter-submit-bug-report
19512 "emacs-orgmode@gnu.org"
19513 (org-version nil 'full)
19514 (let (list)
19515 (save-window-excursion
19516 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19517 (delete-other-windows)
19518 (erase-buffer)
19519 (insert "You are about to submit a bug report to the Org-mode mailing list.
19521 We would like to add your full Org-mode and Outline configuration to the
19522 bug report. This greatly simplifies the work of the maintainer and
19523 other experts on the mailing list.
19525 HOWEVER, some variables you have customized may contain private
19526 information. The names of customers, colleagues, or friends, might
19527 appear in the form of file names, tags, todo states, or search strings.
19528 If you answer yes to the prompt, you might want to check and remove
19529 such private information before sending the email.")
19530 (add-text-properties (point-min) (point-max) '(face org-warning))
19531 (when (yes-or-no-p "Include your Org-mode configuration ")
19532 (mapatoms
19533 (lambda (v)
19534 (and (boundp v)
19535 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19536 (or (and (symbol-value v)
19537 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19538 (and
19539 (get v 'custom-type) (get v 'standard-value)
19540 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19541 (push v list)))))
19542 (kill-buffer (get-buffer "*Warn about privacy*"))
19543 list))
19544 nil nil
19545 "Remember to cover the basics, that is, what you expected to happen and
19546 what in fact did happen. You don't know how to make a good report? See
19548 http://orgmode.org/manual/Feedback.html#Feedback
19550 Your bug report will be posted to the Org-mode mailing list.
19551 ------------------------------------------------------------------------")
19552 (save-excursion
19553 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19554 (replace-match "\\1Bug: \\3 [\\2]")))))
19557 (defun org-install-agenda-files-menu ()
19558 (let ((bl (buffer-list)))
19559 (save-excursion
19560 (while bl
19561 (set-buffer (pop bl))
19562 (if (derived-mode-p 'org-mode) (setq bl nil)))
19563 (when (derived-mode-p 'org-mode)
19564 (easy-menu-change
19565 '("Org") "File List for Agenda"
19566 (append
19567 (list
19568 ["Edit File List" (org-edit-agenda-file-list) t]
19569 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19570 ["Remove Current File from List" org-remove-file t]
19571 ["Cycle through agenda files" org-cycle-agenda-files t]
19572 ["Occur in all agenda files" org-occur-in-agenda-files t]
19573 "--")
19574 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19576 ;;;; Documentation
19578 ;;;###autoload
19579 (defun org-require-autoloaded-modules ()
19580 (interactive)
19581 (mapc 'require
19582 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19583 org-docbook org-exp org-html org-icalendar
19584 org-id org-latex
19585 org-publish org-remember org-table
19586 org-timer org-xoxo)))
19588 ;;;###autoload
19589 (defun org-reload (&optional uncompiled)
19590 "Reload all org lisp files.
19591 With prefix arg UNCOMPILED, load the uncompiled versions."
19592 (interactive "P")
19593 (require 'find-func)
19594 (let* ((file-re "^org\\(-.*\\)?\\.el")
19595 (dir-org (file-name-directory (org-find-library-dir "org")))
19596 (dir-org-contrib (ignore-errors
19597 (file-name-directory
19598 (org-find-library-dir "org-contribdir"))))
19599 (babel-files
19600 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19601 (append (list nil "comint" "eval" "exp" "keys"
19602 "lob" "ref" "table" "tangle")
19603 (delq nil
19604 (mapcar
19605 (lambda (lang)
19606 (when (cdr lang) (symbol-name (car lang))))
19607 org-babel-load-languages)))))
19608 (files
19609 (append babel-files
19610 (and dir-org-contrib
19611 (directory-files dir-org-contrib t file-re))
19612 (directory-files dir-org t file-re)))
19613 (remove-re (concat (if (featurep 'xemacs)
19614 "org-colview" "org-colview-xemacs")
19615 "\\'")))
19616 (setq files (mapcar 'file-name-sans-extension files))
19617 (setq files (mapcar
19618 (lambda (x) (if (string-match remove-re x) nil x))
19619 files))
19620 (setq files (delq nil files))
19621 (mapc
19622 (lambda (f)
19623 (when (featurep (intern (file-name-nondirectory f)))
19624 (if (and (not uncompiled)
19625 (file-exists-p (concat f ".elc")))
19626 (load (concat f ".elc") nil nil 'nosuffix)
19627 (load (concat f ".el") nil nil 'nosuffix))))
19628 files)
19629 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19630 (org-version nil 'full 'message))
19632 ;;;###autoload
19633 (defun org-customize ()
19634 "Call the customize function with org as argument."
19635 (interactive)
19636 (org-load-modules-maybe)
19637 (org-require-autoloaded-modules)
19638 (customize-browse 'org))
19640 (defun org-create-customize-menu ()
19641 "Create a full customization menu for Org-mode, insert it into the menu."
19642 (interactive)
19643 (org-load-modules-maybe)
19644 (org-require-autoloaded-modules)
19645 (if (fboundp 'customize-menu-create)
19646 (progn
19647 (easy-menu-change
19648 '("Org") "Customize"
19649 `(["Browse Org group" org-customize t]
19650 "--"
19651 ,(customize-menu-create 'org)
19652 ["Set" Custom-set t]
19653 ["Save" Custom-save t]
19654 ["Reset to Current" Custom-reset-current t]
19655 ["Reset to Saved" Custom-reset-saved t]
19656 ["Reset to Standard Settings" Custom-reset-standard t]))
19657 (message "\"Org\"-menu now contains full customization menu"))
19658 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19660 ;;;; Miscellaneous stuff
19662 ;;; Generally useful functions
19664 (defun org-get-at-bol (property)
19665 "Get text property PROPERTY at beginning of line."
19666 (get-text-property (point-at-bol) property))
19668 (defun org-find-text-property-in-string (prop s)
19669 "Return the first non-nil value of property PROP in string S."
19670 (or (get-text-property 0 prop s)
19671 (get-text-property (or (next-single-property-change 0 prop s) 0)
19672 prop s)))
19674 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19675 "Display the given MESSAGE as a warning."
19676 (if (fboundp 'display-warning)
19677 (display-warning 'org message
19678 (if (featurep 'xemacs) 'warning :warning))
19679 (let ((buf (get-buffer-create "*Org warnings*")))
19680 (with-current-buffer buf
19681 (goto-char (point-max))
19682 (insert "Warning (Org): " message)
19683 (unless (bolp)
19684 (newline)))
19685 (display-buffer buf)
19686 (sit-for 0))))
19688 (defun org-eval (form)
19689 "Eval FORM and return result."
19690 (condition-case error
19691 (eval form)
19692 (error (format "%%![Error: %s]" error))))
19694 (defun org-in-clocktable-p ()
19695 "Check if the cursor is in a clocktable."
19696 (let ((pos (point)) start)
19697 (save-excursion
19698 (end-of-line 1)
19699 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19700 (setq start (match-beginning 0))
19701 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19702 (>= (match-end 0) pos)
19703 start))))
19705 (defun org-in-commented-line ()
19706 "Is point in a line starting with `#'?"
19707 (equal (char-after (point-at-bol)) ?#))
19709 (defun org-in-indented-comment-line ()
19710 "Is point in a line starting with `#' after some white space?"
19711 (save-excursion
19712 (save-match-data
19713 (goto-char (point-at-bol))
19714 (looking-at "[ \t]*#"))))
19716 (defun org-in-verbatim-emphasis ()
19717 (save-match-data
19718 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19720 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19721 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19722 (if (and marker (marker-buffer marker)
19723 (buffer-live-p (marker-buffer marker)))
19724 (progn
19725 (org-pop-to-buffer-same-window (marker-buffer marker))
19726 (if (or (> marker (point-max)) (< marker (point-min)))
19727 (widen))
19728 (goto-char marker)
19729 (org-show-context 'org-goto))
19730 (if bookmark
19731 (bookmark-jump bookmark)
19732 (error "Cannot find location"))))
19734 (defun org-quote-csv-field (s)
19735 "Quote field for inclusion in CSV material."
19736 (if (string-match "[\",]" s)
19737 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19740 (defun org-force-self-insert (N)
19741 "Needed to enforce self-insert under remapping."
19742 (interactive "p")
19743 (self-insert-command N))
19745 (defun org-string-width (s)
19746 "Compute width of string, ignoring invisible characters.
19747 This ignores character with invisibility property `org-link', and also
19748 characters with property `org-cwidth', because these will become invisible
19749 upon the next fontification round."
19750 (let (b l)
19751 (when (or (eq t buffer-invisibility-spec)
19752 (assq 'org-link buffer-invisibility-spec))
19753 (while (setq b (text-property-any 0 (length s)
19754 'invisible 'org-link s))
19755 (setq s (concat (substring s 0 b)
19756 (substring s (or (next-single-property-change
19757 b 'invisible s) (length s)))))))
19758 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19759 (setq s (concat (substring s 0 b)
19760 (substring s (or (next-single-property-change
19761 b 'org-cwidth s) (length s))))))
19762 (setq l (string-width s) b -1)
19763 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19764 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19767 (defun org-shorten-string (s maxlength)
19768 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19769 If the string is shorter or has length MAXLENGTH, just return the
19770 original string. If it is longer, the functions finds a space in the
19771 string, breaks this string off at that locations and adds three dots
19772 as ellipsis. Including the ellipsis, the string will not be longer
19773 than MAXLENGTH. If finding a good breaking point in the string does
19774 not work, the string is just chopped off in the middle of a word
19775 if necessary."
19776 (if (<= (length s) maxlength)
19778 (let* ((n (max (- maxlength 4) 1))
19779 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19780 (if (string-match re s)
19781 (concat (match-string 1 s) "...")
19782 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19784 (defun org-get-indentation (&optional line)
19785 "Get the indentation of the current line, interpreting tabs.
19786 When LINE is given, assume it represents a line and compute its indentation."
19787 (if line
19788 (if (string-match "^ *" (org-remove-tabs line))
19789 (match-end 0))
19790 (save-excursion
19791 (beginning-of-line 1)
19792 (skip-chars-forward " \t")
19793 (current-column))))
19795 (defun org-get-string-indentation (s)
19796 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19797 (let ((n -1) (i 0) (w tab-width) c)
19798 (catch 'exit
19799 (while (< (setq n (1+ n)) (length s))
19800 (setq c (aref s n))
19801 (cond ((= c ?\ ) (setq i (1+ i)))
19802 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19803 (t (throw 'exit t)))))
19806 (defun org-remove-tabs (s &optional width)
19807 "Replace tabulators in S with spaces.
19808 Assumes that s is a single line, starting in column 0."
19809 (setq width (or width tab-width))
19810 (while (string-match "\t" s)
19811 (setq s (replace-match
19812 (make-string
19813 (- (* width (/ (+ (match-beginning 0) width) width))
19814 (match-beginning 0)) ?\ )
19815 t t s)))
19818 (defun org-fix-indentation (line ind)
19819 "Fix indentation in LINE.
19820 IND is a cons cell with target and minimum indentation.
19821 If the current indentation in LINE is smaller than the minimum,
19822 leave it alone. If it is larger than ind, set it to the target."
19823 (let* ((l (org-remove-tabs line))
19824 (i (org-get-indentation l))
19825 (i1 (car ind)) (i2 (cdr ind)))
19826 (if (>= i i2) (setq l (substring line i2)))
19827 (if (> i1 0)
19828 (concat (make-string i1 ?\ ) l)
19829 l)))
19831 (defun org-remove-indentation (code &optional n)
19832 "Remove the maximum common indentation from the lines in CODE.
19833 N may optionally be the number of spaces to remove."
19834 (with-temp-buffer
19835 (insert code)
19836 (org-do-remove-indentation n)
19837 (buffer-string)))
19839 (defun org-do-remove-indentation (&optional n)
19840 "Remove the maximum common indentation from the buffer."
19841 (untabify (point-min) (point-max))
19842 (let ((min 10000) re)
19843 (if n
19844 (setq min n)
19845 (goto-char (point-min))
19846 (while (re-search-forward "^ *[^ \n]" nil t)
19847 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19848 (unless (or (= min 0) (= min 10000))
19849 (setq re (format "^ \\{%d\\}" min))
19850 (goto-char (point-min))
19851 (while (re-search-forward re nil t)
19852 (replace-match "")
19853 (end-of-line 1))
19854 min)))
19856 (defun org-fill-template (template alist)
19857 "Find each %key of ALIST in TEMPLATE and replace it."
19858 (let ((case-fold-search nil)
19859 entry key value)
19860 (setq alist (sort (copy-sequence alist)
19861 (lambda (a b) (< (length (car a)) (length (car b))))))
19862 (while (setq entry (pop alist))
19863 (setq template
19864 (replace-regexp-in-string
19865 (concat "%" (regexp-quote (car entry)))
19866 (cdr entry) template t t)))
19867 template))
19869 (defun org-base-buffer (buffer)
19870 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19871 (if (not buffer)
19872 buffer
19873 (or (buffer-base-buffer buffer)
19874 buffer)))
19876 (defun org-trim (s)
19877 "Remove whitespace at beginning and end of string."
19878 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19879 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19882 (defun org-wrap (string &optional width lines)
19883 "Wrap string to either a number of lines, or a width in characters.
19884 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19885 that costs. If there is a word longer than WIDTH, the text is actually
19886 wrapped to the length of that word.
19887 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19888 many lines, whatever width that takes.
19889 The return value is a list of lines, without newlines at the end."
19890 (let* ((words (org-split-string string "[ \t\n]+"))
19891 (maxword (apply 'max (mapcar 'org-string-width words)))
19892 w ll)
19893 (cond (width
19894 (org-do-wrap words (max maxword width)))
19895 (lines
19896 (setq w maxword)
19897 (setq ll (org-do-wrap words maxword))
19898 (if (<= (length ll) lines)
19900 (setq ll words)
19901 (while (> (length ll) lines)
19902 (setq w (1+ w))
19903 (setq ll (org-do-wrap words w)))
19904 ll))
19905 (t (error "Cannot wrap this")))))
19907 (defun org-do-wrap (words width)
19908 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19909 (let (lines line)
19910 (while words
19911 (setq line (pop words))
19912 (while (and words (< (+ (length line) (length (car words))) width))
19913 (setq line (concat line " " (pop words))))
19914 (setq lines (push line lines)))
19915 (nreverse lines)))
19917 (defun org-split-string (string &optional separators)
19918 "Splits STRING into substrings at SEPARATORS.
19919 No empty strings are returned if there are matches at the beginning
19920 and end of string."
19921 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19922 (start 0)
19923 notfirst
19924 (list nil))
19925 (while (and (string-match rexp string
19926 (if (and notfirst
19927 (= start (match-beginning 0))
19928 (< start (length string)))
19929 (1+ start) start))
19930 (< (match-beginning 0) (length string)))
19931 (setq notfirst t)
19932 (or (eq (match-beginning 0) 0)
19933 (and (eq (match-beginning 0) (match-end 0))
19934 (eq (match-beginning 0) start))
19935 (setq list
19936 (cons (substring string start (match-beginning 0))
19937 list)))
19938 (setq start (match-end 0)))
19939 (or (eq start (length string))
19940 (setq list
19941 (cons (substring string start)
19942 list)))
19943 (nreverse list)))
19945 (defun org-quote-vert (s)
19946 "Replace \"|\" with \"\\vert\"."
19947 (while (string-match "|" s)
19948 (setq s (replace-match "\\vert" t t s)))
19951 (defun org-uuidgen-p (s)
19952 "Is S an ID created by UUIDGEN?"
19953 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19955 (defun org-in-src-block-p nil
19956 "Whether point is in a code source block."
19957 (let (ov)
19958 (when (setq ov (overlays-at (point)))
19959 (memq 'org-block-background
19960 (overlay-properties
19961 (car ov))))))
19963 (defun org-context ()
19964 "Return a list of contexts of the current cursor position.
19965 If several contexts apply, all are returned.
19966 Each context entry is a list with a symbol naming the context, and
19967 two positions indicating start and end of the context. Possible
19968 contexts are:
19970 :headline anywhere in a headline
19971 :headline-stars on the leading stars in a headline
19972 :todo-keyword on a TODO keyword (including DONE) in a headline
19973 :tags on the TAGS in a headline
19974 :priority on the priority cookie in a headline
19975 :item on the first line of a plain list item
19976 :item-bullet on the bullet/number of a plain list item
19977 :checkbox on the checkbox in a plain list item
19978 :table in an org-mode table
19979 :table-special on a special filed in a table
19980 :table-table in a table.el table
19981 :clocktable in a clocktable
19982 :src-block in a source block
19983 :link on a hyperlink
19984 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19985 :target on a <<target>>
19986 :radio-target on a <<<radio-target>>>
19987 :latex-fragment on a LaTeX fragment
19988 :latex-preview on a LaTeX fragment with overlaid preview image
19990 This function expects the position to be visible because it uses font-lock
19991 faces as a help to recognize the following contexts: :table-special, :link,
19992 and :keyword."
19993 (let* ((f (get-text-property (point) 'face))
19994 (faces (if (listp f) f (list f)))
19995 (case-fold-search t)
19996 (p (point)) clist o)
19997 ;; First the large context
19998 (cond
19999 ((org-at-heading-p t)
20000 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20001 (when (progn
20002 (beginning-of-line 1)
20003 (looking-at org-todo-line-tags-regexp))
20004 (push (org-point-in-group p 1 :headline-stars) clist)
20005 (push (org-point-in-group p 2 :todo-keyword) clist)
20006 (push (org-point-in-group p 4 :tags) clist))
20007 (goto-char p)
20008 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20009 (if (looking-at "\\[#[A-Z0-9]\\]")
20010 (push (org-point-in-group p 0 :priority) clist)))
20012 ((org-at-item-p)
20013 (push (org-point-in-group p 2 :item-bullet) clist)
20014 (push (list :item (point-at-bol)
20015 (save-excursion (org-end-of-item) (point)))
20016 clist)
20017 (and (org-at-item-checkbox-p)
20018 (push (org-point-in-group p 0 :checkbox) clist)))
20020 ((org-at-table-p)
20021 (push (list :table (org-table-begin) (org-table-end)) clist)
20022 (if (memq 'org-formula faces)
20023 (push (list :table-special
20024 (previous-single-property-change p 'face)
20025 (next-single-property-change p 'face)) clist)))
20026 ((org-at-table-p 'any)
20027 (push (list :table-table) clist)))
20028 (goto-char p)
20030 ;; New the "medium" contexts: clocktables, source blocks
20031 (cond ((org-in-clocktable-p)
20032 (push (list :clocktable
20033 (and (or (looking-at "#\\+BEGIN: clocktable")
20034 (search-backward "#+BEGIN: clocktable" nil t))
20035 (match-beginning 0))
20036 (and (re-search-forward "#\\+END:?" nil t)
20037 (match-end 0))) clist))
20038 ((org-in-src-block-p)
20039 (push (list :src-block
20040 (and (or (looking-at "#\\+BEGIN_SRC")
20041 (search-backward "#+BEGIN_SRC" nil t))
20042 (match-beginning 0))
20043 (and (search-forward "#+END_SRC" nil t)
20044 (match-beginning 0))) clist)))
20045 (goto-char p)
20047 ;; Now the small context
20048 (cond
20049 ((org-at-timestamp-p)
20050 (push (org-point-in-group p 0 :timestamp) clist))
20051 ((memq 'org-link faces)
20052 (push (list :link
20053 (previous-single-property-change p 'face)
20054 (next-single-property-change p 'face)) clist))
20055 ((memq 'org-special-keyword faces)
20056 (push (list :keyword
20057 (previous-single-property-change p 'face)
20058 (next-single-property-change p 'face)) clist))
20059 ((org-at-target-p)
20060 (push (org-point-in-group p 0 :target) clist)
20061 (goto-char (1- (match-beginning 0)))
20062 (if (looking-at org-radio-target-regexp)
20063 (push (org-point-in-group p 0 :radio-target) clist))
20064 (goto-char p))
20065 ((setq o (car (delq nil
20066 (mapcar
20067 (lambda (x)
20068 (if (memq x org-latex-fragment-image-overlays) x))
20069 (overlays-at (point))))))
20070 (push (list :latex-fragment
20071 (overlay-start o) (overlay-end o)) clist)
20072 (push (list :latex-preview
20073 (overlay-start o) (overlay-end o)) clist))
20074 ((org-inside-LaTeX-fragment-p)
20075 ;; FIXME: positions wrong.
20076 (push (list :latex-fragment (point) (point)) clist)))
20078 (setq clist (nreverse (delq nil clist)))
20079 clist))
20081 ;; FIXME: Compare with at-regexp-p Do we need both?
20082 (defun org-in-regexp (re &optional nlines visually)
20083 "Check if point is inside a match of regexp.
20084 Normally only the current line is checked, but you can include NLINES extra
20085 lines both before and after point into the search.
20086 If VISUALLY is set, require that the cursor is not after the match but
20087 really on, so that the block visually is on the match."
20088 (catch 'exit
20089 (let ((pos (point))
20090 (eol (point-at-eol (+ 1 (or nlines 0))))
20091 (inc (if visually 1 0)))
20092 (save-excursion
20093 (beginning-of-line (- 1 (or nlines 0)))
20094 (while (re-search-forward re eol t)
20095 (if (and (<= (match-beginning 0) pos)
20096 (>= (+ inc (match-end 0)) pos))
20097 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20099 (defun org-at-regexp-p (regexp)
20100 "Is point inside a match of REGEXP in the current line?"
20101 (catch 'exit
20102 (save-excursion
20103 (let ((pos (point)) (end (point-at-eol)))
20104 (beginning-of-line 1)
20105 (while (re-search-forward regexp end t)
20106 (if (and (<= (match-beginning 0) pos)
20107 (>= (match-end 0) pos))
20108 (throw 'exit t)))
20109 nil))))
20111 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20112 "Non-nil when point is between matches of START-RE and END-RE.
20114 Also return a non-nil value when point is on one of the matches.
20116 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20117 buffer positions. Default values are the positions of headlines
20118 surrounding the point.
20120 The functions returns a cons cell whose car (resp. cdr) is the
20121 position before START-RE (resp. after END-RE)."
20122 (save-match-data
20123 (let ((pos (point))
20124 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20125 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20126 beg end)
20127 (save-excursion
20128 ;; Point is on a block when on START-RE or if START-RE can be
20129 ;; found before it...
20130 (and (or (org-at-regexp-p start-re)
20131 (re-search-backward start-re limit-up t))
20132 (setq beg (match-beginning 0))
20133 ;; ... and END-RE after it...
20134 (goto-char (match-end 0))
20135 (re-search-forward end-re limit-down t)
20136 (> (setq end (match-end 0)) pos)
20137 ;; ... without another START-RE in-between.
20138 (goto-char (match-beginning 0))
20139 (not (re-search-backward start-re (1+ beg) t))
20140 ;; Return value.
20141 (cons beg end))))))
20143 (defun org-in-block-p (names)
20144 "Non-nil when point belongs to a block whose name belongs to NAMES.
20146 NAMES is a list of strings containing names of blocks.
20148 Return first block name matched, or nil. Beware that in case of
20149 nested blocks, the returned name may not belong to the closest
20150 block from point."
20151 (save-match-data
20152 (catch 'exit
20153 (let ((case-fold-search t)
20154 (lim-up (save-excursion (outline-previous-heading)))
20155 (lim-down (save-excursion (outline-next-heading))))
20156 (mapc (lambda (name)
20157 (let ((n (regexp-quote name)))
20158 (when (org-between-regexps-p
20159 (concat "^[ \t]*#\\+begin_" n)
20160 (concat "^[ \t]*#\\+end_" n)
20161 lim-up lim-down)
20162 (throw 'exit n))))
20163 names))
20164 nil)))
20166 (defun org-occur-in-agenda-files (regexp &optional nlines)
20167 "Call `multi-occur' with buffers for all agenda files."
20168 (interactive "sOrg-files matching: \np")
20169 (let* ((files (org-agenda-files))
20170 (tnames (mapcar 'file-truename files))
20171 (extra org-agenda-text-search-extra-files)
20173 (when (eq (car extra) 'agenda-archives)
20174 (setq extra (cdr extra))
20175 (setq files (org-add-archive-files files)))
20176 (while (setq f (pop extra))
20177 (unless (member (file-truename f) tnames)
20178 (add-to-list 'files f 'append)
20179 (add-to-list 'tnames (file-truename f) 'append)))
20180 (multi-occur
20181 (mapcar (lambda (x)
20182 (with-current-buffer
20183 (or (get-file-buffer x) (find-file-noselect x))
20184 (widen)
20185 (current-buffer)))
20186 files)
20187 regexp)))
20189 (if (boundp 'occur-mode-find-occurrence-hook)
20190 ;; Emacs 23
20191 (add-hook 'occur-mode-find-occurrence-hook
20192 (lambda ()
20193 (when (derived-mode-p 'org-mode)
20194 (org-reveal))))
20195 ;; Emacs 22
20196 (defadvice occur-mode-goto-occurrence
20197 (after org-occur-reveal activate)
20198 (and (derived-mode-p 'org-mode) (org-reveal)))
20199 (defadvice occur-mode-goto-occurrence-other-window
20200 (after org-occur-reveal activate)
20201 (and (derived-mode-p 'org-mode) (org-reveal)))
20202 (defadvice occur-mode-display-occurrence
20203 (after org-occur-reveal activate)
20204 (when (derived-mode-p 'org-mode)
20205 (let ((pos (occur-mode-find-occurrence)))
20206 (with-current-buffer (marker-buffer pos)
20207 (save-excursion
20208 (goto-char pos)
20209 (org-reveal)))))))
20211 (defun org-occur-link-in-agenda-files ()
20212 "Create a link and search for it in the agendas.
20213 The link is not stored in `org-stored-links', it is just created
20214 for the search purpose."
20215 (interactive)
20216 (let ((link (condition-case nil
20217 (org-store-link nil)
20218 (error "Unable to create a link to here"))))
20219 (org-occur-in-agenda-files (regexp-quote link))))
20221 (defun org-uniquify (list)
20222 "Remove duplicate elements from LIST."
20223 (let (res)
20224 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20225 res))
20227 (defun org-delete-all (elts list)
20228 "Remove all elements in ELTS from LIST."
20229 (while elts
20230 (setq list (delete (pop elts) list)))
20231 list)
20233 (defun org-count (cl-item cl-seq)
20234 "Count the number of occurrences of ITEM in SEQ.
20235 Taken from `count' in cl-seq.el with all keyword arguments removed."
20236 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20237 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20238 (while (< cl-start cl-end)
20239 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20240 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20241 (setq cl-start (1+ cl-start)))
20242 cl-count))
20244 (defun org-remove-if (predicate seq)
20245 "Remove everything from SEQ that fulfills PREDICATE."
20246 (let (res e)
20247 (while seq
20248 (setq e (pop seq))
20249 (if (not (funcall predicate e)) (push e res)))
20250 (nreverse res)))
20252 (defun org-remove-if-not (predicate seq)
20253 "Remove everything from SEQ that does not fulfill PREDICATE."
20254 (let (res e)
20255 (while seq
20256 (setq e (pop seq))
20257 (if (funcall predicate e) (push e res)))
20258 (nreverse res)))
20260 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20261 "Reduce two-argument FUNCTION across SEQ.
20262 Taken from `reduce' in cl-seq.el with all keyword arguments but
20263 \":initial-value\" removed."
20264 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20265 (cadr (memq :initial-value cl-keys)))
20266 (cl-seq (pop cl-seq))
20267 (t (funcall cl-func)))))
20268 (while cl-seq
20269 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20270 cl-accum))
20272 (defun org-back-over-empty-lines ()
20273 "Move backwards over whitespace, to the beginning of the first empty line.
20274 Returns the number of empty lines passed."
20275 (let ((pos (point)))
20276 (if (cdr (assoc 'heading org-blank-before-new-entry))
20277 (skip-chars-backward " \t\n\r")
20278 (unless (eobp)
20279 (forward-line -1)))
20280 (beginning-of-line 2)
20281 (goto-char (min (point) pos))
20282 (count-lines (point) pos)))
20284 (defun org-skip-whitespace ()
20285 (skip-chars-forward " \t\n\r"))
20287 (defun org-point-in-group (point group &optional context)
20288 "Check if POINT is in match-group GROUP.
20289 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20290 match. If the match group does not exist or point is not inside it,
20291 return nil."
20292 (and (match-beginning group)
20293 (>= point (match-beginning group))
20294 (<= point (match-end group))
20295 (if context
20296 (list context (match-beginning group) (match-end group))
20297 t)))
20299 (defun org-switch-to-buffer-other-window (&rest args)
20300 "Switch to buffer in a second window on the current frame.
20301 In particular, do not allow pop-up frames.
20302 Returns the newly created buffer."
20303 (let (pop-up-frames special-display-buffer-names special-display-regexps
20304 special-display-function)
20305 (apply 'switch-to-buffer-other-window args)))
20307 (defun org-combine-plists (&rest plists)
20308 "Create a single property list from all plists in PLISTS.
20309 The process starts by copying the first list, and then setting properties
20310 from the other lists. Settings in the last list are the most significant
20311 ones and overrule settings in the other lists."
20312 (let ((rtn (copy-sequence (pop plists)))
20313 p v ls)
20314 (while plists
20315 (setq ls (pop plists))
20316 (while ls
20317 (setq p (pop ls) v (pop ls))
20318 (setq rtn (plist-put rtn p v))))
20319 rtn))
20321 (defun org-move-line-down (arg)
20322 "Move the current line down. With prefix argument, move it past ARG lines."
20323 (interactive "p")
20324 (let ((col (current-column))
20325 beg end pos)
20326 (beginning-of-line 1) (setq beg (point))
20327 (beginning-of-line 2) (setq end (point))
20328 (beginning-of-line (+ 1 arg))
20329 (setq pos (move-marker (make-marker) (point)))
20330 (insert (delete-and-extract-region beg end))
20331 (goto-char pos)
20332 (org-move-to-column col)))
20334 (defun org-move-line-up (arg)
20335 "Move the current line up. With prefix argument, move it past ARG lines."
20336 (interactive "p")
20337 (let ((col (current-column))
20338 beg end pos)
20339 (beginning-of-line 1) (setq beg (point))
20340 (beginning-of-line 2) (setq end (point))
20341 (beginning-of-line (- arg))
20342 (setq pos (move-marker (make-marker) (point)))
20343 (insert (delete-and-extract-region beg end))
20344 (goto-char pos)
20345 (org-move-to-column col)))
20347 (defun org-replace-escapes (string table)
20348 "Replace %-escapes in STRING with values in TABLE.
20349 TABLE is an association list with keys like \"%a\" and string values.
20350 The sequences in STRING may contain normal field width and padding information,
20351 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20352 so values can contain further %-escapes if they are define later in TABLE."
20353 (let ((tbl (copy-alist table))
20354 (case-fold-search nil)
20355 (pchg 0)
20356 e re rpl)
20357 (while (setq e (pop tbl))
20358 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20359 (when (and (cdr e) (string-match re (cdr e)))
20360 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20361 (safe "SREF"))
20362 (add-text-properties 0 3 (list 'sref sref) safe)
20363 (setcdr e (replace-match safe t t (cdr e)))))
20364 (while (string-match re string)
20365 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20366 (cdr e)))
20367 (setq string (replace-match rpl t t string))))
20368 (while (setq pchg (next-property-change pchg string))
20369 (let ((sref (get-text-property pchg 'sref string)))
20370 (when (and sref (string-match "SREF" string pchg))
20371 (setq string (replace-match sref t t string)))))
20372 string))
20374 (defun org-sublist (list start end)
20375 "Return a section of LIST, from START to END.
20376 Counting starts at 1."
20377 (let (rtn (c start))
20378 (setq list (nthcdr (1- start) list))
20379 (while (and list (<= c end))
20380 (push (pop list) rtn)
20381 (setq c (1+ c)))
20382 (nreverse rtn)))
20384 (defun org-find-base-buffer-visiting (file)
20385 "Like `find-buffer-visiting' but always return the base buffer and
20386 not an indirect buffer."
20387 (let ((buf (or (get-file-buffer file)
20388 (find-buffer-visiting file))))
20389 (if buf
20390 (or (buffer-base-buffer buf) buf)
20391 nil)))
20393 (defun org-image-file-name-regexp (&optional extensions)
20394 "Return regexp matching the file names of images.
20395 If EXTENSIONS is given, only match these."
20396 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20397 (image-file-name-regexp)
20398 (let ((image-file-name-extensions
20399 (or extensions
20400 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20401 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20402 (concat "\\."
20403 (regexp-opt (nconc (mapcar 'upcase
20404 image-file-name-extensions)
20405 image-file-name-extensions)
20407 "\\'"))))
20409 (defun org-file-image-p (file &optional extensions)
20410 "Return non-nil if FILE is an image."
20411 (save-match-data
20412 (string-match (org-image-file-name-regexp extensions) file)))
20414 (defun org-get-cursor-date ()
20415 "Return the date at cursor in as a time.
20416 This works in the calendar and in the agenda, anywhere else it just
20417 returns the current time."
20418 (let (date day defd)
20419 (cond
20420 ((eq major-mode 'calendar-mode)
20421 (setq date (calendar-cursor-to-date)
20422 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20423 ((eq major-mode 'org-agenda-mode)
20424 (setq day (get-text-property (point) 'day))
20425 (if day
20426 (setq date (calendar-gregorian-from-absolute day)
20427 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20428 (nth 2 date))))))
20429 (or defd (current-time))))
20431 (defvar org-agenda-action-marker (make-marker)
20432 "Marker pointing to the entry for the next agenda action.")
20434 (defun org-mark-entry-for-agenda-action ()
20435 "Mark the current entry as target of an agenda action.
20436 Agenda actions are actions executed from the agenda with the key `k',
20437 which make use of the date at the cursor."
20438 (interactive)
20439 (move-marker org-agenda-action-marker
20440 (save-excursion (org-back-to-heading t) (point))
20441 (current-buffer))
20442 (message
20443 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20445 (defun org-mark-subtree ()
20446 "Mark the current subtree.
20447 This puts point at the start of the current subtree, and mark at the end.
20449 If point is in an inline task, mark that task instead."
20450 (interactive)
20451 (let ((inline-task-p
20452 (and (featurep 'org-inlinetask)
20453 (org-inlinetask-in-task-p)))
20454 (beg))
20455 ;; Get beginning of subtree
20456 (cond
20457 (inline-task-p (org-inlinetask-goto-beginning))
20458 ((org-at-heading-p) (beginning-of-line))
20459 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20460 (setq beg (point))
20461 ;; Get end of it
20462 (if inline-task-p
20463 (org-inlinetask-goto-end)
20464 (org-end-of-subtree))
20465 ;; Mark zone
20466 (push-mark (point) nil t)
20467 (goto-char beg)))
20469 ;;; Paragraph filling stuff.
20470 ;; We want this to be just right, so use the full arsenal.
20472 (defun org-indent-line-function ()
20473 "Indent line depending on context."
20474 (interactive)
20475 (let* ((pos (point))
20476 (itemp (org-at-item-p))
20477 (case-fold-search t)
20478 (org-drawer-regexp (or org-drawer-regexp "\000"))
20479 (inline-task-p (and (featurep 'org-inlinetask)
20480 (org-inlinetask-in-task-p)))
20481 (inline-re (and inline-task-p
20482 (org-inlinetask-outline-regexp)))
20483 column)
20484 (beginning-of-line 1)
20485 (cond
20486 ;; Comments
20487 ((looking-at "# ") (setq column 0))
20488 ;; Headings
20489 ((looking-at org-outline-regexp) (setq column 0))
20490 ;; Included files
20491 ((looking-at "#\\+include:") (setq column 0))
20492 ;; Footnote definition
20493 ((looking-at org-footnote-definition-re) (setq column 0))
20494 ;; Literal examples
20495 ((looking-at "[ \t]*:\\( \\|$\\)")
20496 (setq column (org-get-indentation))) ; do nothing
20497 ;; Lists
20498 ((ignore-errors (goto-char (org-in-item-p)))
20499 (setq column (if itemp
20500 (org-get-indentation)
20501 (org-list-item-body-column (point))))
20502 (goto-char pos))
20503 ;; Drawers
20504 ((and (looking-at "[ \t]*:END:")
20505 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20506 (save-excursion
20507 (goto-char (1- (match-beginning 1)))
20508 (setq column (current-column))))
20509 ;; Special blocks
20510 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20511 (save-excursion
20512 (re-search-backward
20513 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20514 (setq column (org-get-indentation (match-string 0))))
20515 ((and (not (looking-at "[ \t]*#\\+begin_"))
20516 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20517 (save-excursion
20518 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20519 (setq column
20520 (cond ((equal (downcase (match-string 1)) "src")
20521 ;; src blocks: let `org-edit-src-exit' handle them
20522 (org-get-indentation))
20523 ((equal (downcase (match-string 1)) "example")
20524 (max (org-get-indentation)
20525 (org-get-indentation (match-string 0))))
20527 (org-get-indentation (match-string 0))))))
20528 ;; This line has nothing special, look at the previous relevant
20529 ;; line to compute indentation
20531 (beginning-of-line 0)
20532 (while (and (not (bobp))
20533 (not (looking-at org-drawer-regexp))
20534 ;; When point started in an inline task, do not move
20535 ;; above task starting line.
20536 (not (and inline-task-p (looking-at inline-re)))
20537 ;; Skip drawers, blocks, empty lines, verbatim,
20538 ;; comments, tables, footnotes definitions, lists,
20539 ;; inline tasks.
20540 (or (and (looking-at "[ \t]*:END:")
20541 (re-search-backward org-drawer-regexp nil t))
20542 (and (looking-at "[ \t]*#\\+end_")
20543 (re-search-backward "[ \t]*#\\+begin_"nil t))
20544 (looking-at "[ \t]*[\n:#|]")
20545 (looking-at org-footnote-definition-re)
20546 (and (ignore-errors (goto-char (org-in-item-p)))
20547 (goto-char
20548 (org-list-get-top-point (org-list-struct))))
20549 (and (not inline-task-p)
20550 (featurep 'org-inlinetask)
20551 (org-inlinetask-in-task-p)
20552 (or (org-inlinetask-goto-beginning) t))))
20553 (beginning-of-line 0))
20554 (cond
20555 ;; There was an heading above.
20556 ((looking-at "\\*+[ \t]+")
20557 (if (not org-adapt-indentation)
20558 (setq column 0)
20559 (goto-char (match-end 0))
20560 (setq column (current-column))))
20561 ;; A drawer had started and is unfinished
20562 ((looking-at org-drawer-regexp)
20563 (goto-char (1- (match-beginning 1)))
20564 (setq column (current-column)))
20565 ;; Else, nothing noticeable found: get indentation and go on.
20566 (t (setq column (org-get-indentation))))))
20567 ;; Now apply indentation and move cursor accordingly
20568 (goto-char pos)
20569 (if (<= (current-column) (current-indentation))
20570 (org-indent-line-to column)
20571 (save-excursion (org-indent-line-to column)))
20572 ;; Special polishing for properties, see `org-property-format'
20573 (setq column (current-column))
20574 (beginning-of-line 1)
20575 (if (looking-at
20576 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20577 (replace-match (concat (match-string 1)
20578 (format org-property-format
20579 (match-string 2) (match-string 3)))
20580 t t))
20581 (org-move-to-column column)
20582 (when (and orgstruct-is-++ (eq pos (point)))
20583 (org-let org-fb-vars
20584 '(indent-according-to-mode)))))
20586 (defun org-indent-drawer ()
20587 "Indent the drawer at point."
20588 (interactive)
20589 (let ((p (point))
20590 (e (and (save-excursion (re-search-forward ":END:" nil t))
20591 (match-end 0)))
20592 (folded
20593 (save-excursion
20594 (end-of-line)
20595 (when (overlays-at (point))
20596 (member 'invisible (overlay-properties
20597 (car (overlays-at (point)))))))))
20598 (when folded (org-cycle))
20599 (indent-for-tab-command)
20600 (while (and (move-beginning-of-line 2) (< (point) e))
20601 (indent-for-tab-command))
20602 (goto-char p)
20603 (when folded (org-cycle)))
20604 (message "Drawer at point indented"))
20606 (defun org-indent-block ()
20607 "Indent the block at point."
20608 (interactive)
20609 (let ((p (point))
20610 (case-fold-search t)
20611 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20612 (match-end 0)))
20613 (folded
20614 (save-excursion
20615 (end-of-line)
20616 (when (overlays-at (point))
20617 (member 'invisible (overlay-properties
20618 (car (overlays-at (point)))))))))
20619 (when folded (org-cycle))
20620 (indent-for-tab-command)
20621 (while (and (move-beginning-of-line 2) (< (point) e))
20622 (indent-for-tab-command))
20623 (goto-char p)
20624 (when folded (org-cycle)))
20625 (message "Block at point indented"))
20627 ;; For reference, this is the default value of adaptive-fill-regexp
20628 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20629 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20630 "Variable to store copy of `adaptive-fill-regexp'.
20631 Since `adaptive-fill-regexp' is set to never match, we need to
20632 store a backup of its value before entering `org-mode' so that
20633 the functionality can be provided as a fall-back.")
20635 (defun org-set-autofill-regexps ()
20636 (interactive)
20637 ;; In the paragraph separator we include headlines, because filling
20638 ;; text in a line directly attached to a headline would otherwise
20639 ;; fill the headline as well.
20640 (org-set-local 'comment-start-skip "^#+[ \t]*")
20641 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20642 ;; The paragraph starter includes hand-formatted lists.
20643 (org-set-local
20644 'paragraph-start
20645 (concat
20646 "\f" "\\|"
20647 "[ ]*$" "\\|"
20648 org-outline-regexp "\\|"
20649 "[ \t]*#" "\\|"
20650 (org-item-re) "\\|"
20651 "[ \t]*[:|]" "\\|"
20652 "\\$\\$" "\\|"
20653 "\\\\\\(begin\\|end\\|[][]\\)"))
20654 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20655 ;; But only if the user has not turned off tables or fixed-width regions
20656 (org-set-local
20657 'auto-fill-inhibit-regexp
20658 (concat org-outline-regexp
20659 "\\|#\\+"
20660 "\\|[ \t]*" org-keyword-time-regexp
20661 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20662 (concat
20663 "\\|[ \t]*["
20664 (if org-enable-table-editor "|" "")
20665 (if org-enable-fixed-width-editor ":" "")
20666 "]"))))
20667 ;; We use our own fill-paragraph function, to make sure that tables
20668 ;; and fixed-width regions are not wrapped. That function will pass
20669 ;; through to `fill-paragraph' when appropriate.
20670 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20671 ;; Prevent auto-fill from inserting unwanted new items.
20672 (if (boundp 'fill-nobreak-predicate)
20673 (org-set-local
20674 'fill-nobreak-predicate
20675 (org-uniquify
20676 (append fill-nobreak-predicate
20677 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20678 ;; Adaptive filling: To get full control, first make sure that
20679 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20680 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20681 (org-set-local 'org-adaptive-fill-regexp-backup
20682 adaptive-fill-regexp))
20683 (org-set-local 'adaptive-fill-regexp "\000")
20684 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20685 (org-set-local 'adaptive-fill-function
20686 'org-adaptive-fill-function)
20687 (org-set-local
20688 'align-mode-rules-list
20689 '((org-in-buffer-settings
20690 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20691 (modes . '(org-mode))))))
20693 (defun org-fill-item-nobreak-p ()
20694 "Non-nil when a line break at point would insert a new item."
20695 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20697 (defun org-fill-line-break-nobreak-p ()
20698 "Non-nil when a line break at point would create an Org line break."
20699 (save-excursion
20700 (skip-chars-backward "[ \t]")
20701 (skip-chars-backward "\\\\")
20702 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20704 (defun org-fill-paragraph (&optional justify)
20705 "Re-align a table, pass through to fill-paragraph if no table."
20706 (let ((table-p (org-at-table-p))
20707 (table.el-p (org-at-table.el-p))
20708 (itemp (org-in-item-p)))
20709 (cond ((and (equal (char-after (point-at-bol)) ?*)
20710 (save-excursion (goto-char (point-at-bol))
20711 (looking-at org-outline-regexp)))
20712 t) ; skip headlines
20713 (table.el-p t) ; skip table.el tables
20714 (table-p (org-table-align) t) ; align Org tables
20715 (itemp ; align text in items
20716 (let* ((struct (save-excursion (goto-char itemp)
20717 (org-list-struct)))
20718 (parents (org-list-parents-alist struct))
20719 (children (org-list-get-children itemp struct parents))
20720 beg end prev next prefix)
20721 ;; Determine in which part of item point is: before
20722 ;; first child, after last child, between two
20723 ;; sub-lists, or simply in item if there's no child.
20724 (cond
20725 ((not children)
20726 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20727 beg itemp
20728 end (org-list-get-item-end itemp struct)))
20729 ((< (point) (setq next (car children)))
20730 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20731 beg itemp
20732 end next))
20733 ((> (point) (setq prev (car (last children))))
20734 (setq beg (org-list-get-item-end prev struct)
20735 end (org-list-get-item-end itemp struct)
20736 prefix (save-excursion
20737 (goto-char beg)
20738 (skip-chars-forward " \t")
20739 (make-string (current-column) ?\ ))))
20740 (t (catch 'exit
20741 (while (setq next (pop children))
20742 (if (> (point) next)
20743 (setq prev next)
20744 (setq beg (org-list-get-item-end prev struct)
20745 end next
20746 prefix (save-excursion
20747 (goto-char beg)
20748 (skip-chars-forward " \t")
20749 (make-string (current-column) ?\ )))
20750 (throw 'exit nil))))))
20751 ;; Use `fill-paragraph' with buffer narrowed to item
20752 ;; without any child, and with our computed PREFIX.
20753 (flet ((fill-context-prefix (from to &optional flr) prefix))
20754 (save-restriction
20755 (narrow-to-region beg end)
20756 (save-excursion (fill-paragraph justify)))) t))
20757 ;; Special case where point is not in a list but is on
20758 ;; a paragraph adjacent to a list: make sure this paragraph
20759 ;; doesn't get merged with the end of the list by narrowing
20760 ;; buffer first.
20761 ((and (derived-mode-p 'org-mode)
20762 (save-excursion (forward-paragraph -1)
20763 (setq itemp (org-in-item-p))))
20764 (let ((struct (save-excursion (goto-char itemp)
20765 (org-list-struct))))
20766 (save-restriction
20767 (narrow-to-region (org-list-get-bottom-point struct)
20768 (save-excursion (forward-paragraph 1)
20769 (point)))
20770 (fill-paragraph justify) t)))
20771 ;; Don't fill schedule/deadline line before a paragraph
20772 ;; This only makes sense in real org-mode buffers
20773 ((and (eq major-mode 'org-mode)
20774 (save-excursion (forward-paragraph -1)
20775 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20776 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$")))))
20777 (save-restriction
20778 (narrow-to-region (1+ (match-end 0))
20779 (save-excursion (forward-paragraph 1) (point)))
20780 (fill-paragraph justify) t))
20781 ;; Else fall back on fill-paragraph-function as possibly
20782 ;; defined in `org-fb-vars'
20783 (orgstruct-is-++
20784 (org-let org-fb-vars
20785 '(fill-paragraph justify)))
20786 (t nil))))
20788 (defun org-adaptive-fill-function ()
20789 "Return a fill prefix for org-mode files."
20790 (let (itemp)
20791 (save-excursion
20792 (cond
20793 ;; Comment line
20794 ((looking-at "#[ \t]+")
20795 (match-string-no-properties 0))
20796 ;; Plain list item
20797 ((org-at-item-p)
20798 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20799 ;; Point is in a list after `backward-paragraph': original
20800 ;; point wasn't in the list, or filling would have been taken
20801 ;; care of by `org-auto-fill-function', but the list and the
20802 ;; real paragraph are not separated by a blank line. Thus, move
20803 ;; point after the list to go back to real paragraph and
20804 ;; determine fill-prefix.
20805 ((setq itemp (org-in-item-p))
20806 (goto-char itemp)
20807 (let* ((struct (org-list-struct))
20808 (bottom (org-list-get-bottom-point struct)))
20809 (goto-char bottom)
20810 (make-string (org-get-indentation) ?\ )))
20811 ;; Other text
20812 ((looking-at org-adaptive-fill-regexp-backup)
20813 (match-string-no-properties 0))))))
20815 (defun org-auto-fill-function ()
20816 "Auto-fill function."
20817 (unless (and org-src-prevent-auto-filling (org-in-src-block-p))
20818 (let (itemp prefix)
20819 ;; When in a list, compute an appropriate fill-prefix and make
20820 ;; sure it will be used by `do-auto-fill'.
20821 (cond ((setq itemp (org-in-item-p))
20822 (progn
20823 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20824 (flet ((fill-context-prefix (from to &optional flr) prefix))
20825 (do-auto-fill))))
20826 (orgstruct-is-++
20827 (org-let org-fb-vars
20828 '(do-auto-fill)))
20829 (t (do-auto-fill))))))
20831 ;;; Other stuff.
20833 (defun org-toggle-fixed-width-section (arg)
20834 "Toggle the fixed-width export.
20835 If there is no active region, the QUOTE keyword at the current headline is
20836 inserted or removed. When present, it causes the text between this headline
20837 and the next to be exported as fixed-width text, and unmodified.
20838 If there is an active region, this command adds or removes a colon as the
20839 first character of this line. If the first character of a line is a colon,
20840 this line is also exported in fixed-width font."
20841 (interactive "P")
20842 (let* ((cc 0)
20843 (regionp (org-region-active-p))
20844 (beg (if regionp (region-beginning) (point)))
20845 (end (if regionp (region-end)))
20846 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20847 (case-fold-search nil)
20848 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20849 off)
20850 (if regionp
20851 (save-excursion
20852 (goto-char beg)
20853 (setq cc (current-column))
20854 (beginning-of-line 1)
20855 (setq off (looking-at re))
20856 (while (> nlines 0)
20857 (setq nlines (1- nlines))
20858 (beginning-of-line 1)
20859 (cond
20860 (arg
20861 (org-move-to-column cc t)
20862 (insert ": \n")
20863 (forward-line -1))
20864 ((and off (looking-at re))
20865 (replace-match "" t t nil 1))
20866 ((not off) (org-move-to-column cc t) (insert ": ")))
20867 (forward-line 1)))
20868 (save-excursion
20869 (org-back-to-heading)
20870 (cond
20871 ((looking-at (format org-heading-keyword-regexp-format
20872 org-quote-string))
20873 (goto-char (match-end 1))
20874 (looking-at (concat " +" org-quote-string))
20875 (replace-match "" t t)
20876 (when (eolp) (insert " ")))
20877 ((looking-at org-outline-regexp)
20878 (goto-char (match-end 0))
20879 (insert org-quote-string " ")))))))
20881 (defun org-reftex-citation ()
20882 "Use reftex-citation to insert a citation into the buffer.
20883 This looks for a line like
20885 #+BIBLIOGRAPHY: foo plain option:-d
20887 and derives from it that foo.bib is the bibliography file relevant
20888 for this document. It then installs the necessary environment for RefTeX
20889 to work in this buffer and calls `reftex-citation' to insert a citation
20890 into the buffer.
20892 Export of such citations to both LaTeX and HTML is handled by the contributed
20893 package org-exp-bibtex by Taru Karttunen."
20894 (interactive)
20895 (let ((reftex-docstruct-symbol 'rds)
20896 (reftex-cite-format "\\cite{%l}")
20897 rds bib)
20898 (save-excursion
20899 (save-restriction
20900 (widen)
20901 (let ((case-fold-search t)
20902 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20903 (if (not (save-excursion
20904 (or (re-search-forward re nil t)
20905 (re-search-backward re nil t))))
20906 (error "No bibliography defined in file")
20907 (setq bib (concat (match-string 1) ".bib")
20908 rds (list (list 'bib bib)))))))
20909 (call-interactively 'reftex-citation)))
20911 ;;;; Functions extending outline functionality
20913 (defun org-beginning-of-line (&optional arg)
20914 "Go to the beginning of the current line. If that is invisible, continue
20915 to a visible line beginning. This makes the function of C-a more intuitive.
20916 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20917 first attempt, and only move to after the tags when the cursor is already
20918 beyond the end of the headline."
20919 (interactive "P")
20920 (let ((pos (point))
20921 (special (if (consp org-special-ctrl-a/e)
20922 (car org-special-ctrl-a/e)
20923 org-special-ctrl-a/e))
20924 refpos)
20925 (if (org-bound-and-true-p line-move-visual)
20926 (beginning-of-visual-line 1)
20927 (beginning-of-line 1))
20928 (if (and arg (fboundp 'move-beginning-of-line))
20929 (call-interactively 'move-beginning-of-line)
20930 (if (bobp)
20932 (backward-char 1)
20933 (if (org-truely-invisible-p)
20934 (while (and (not (bobp)) (org-truely-invisible-p))
20935 (backward-char 1)
20936 (beginning-of-line 1))
20937 (forward-char 1))))
20938 (when special
20939 (cond
20940 ((and (looking-at org-complex-heading-regexp)
20941 (= (char-after (match-end 1)) ?\ ))
20942 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20943 (point-at-eol)))
20944 (goto-char
20945 (if (eq special t)
20946 (cond ((> pos refpos) refpos)
20947 ((= pos (point)) refpos)
20948 (t (point)))
20949 (cond ((> pos (point)) (point))
20950 ((not (eq last-command this-command)) (point))
20951 (t refpos)))))
20952 ((org-at-item-p)
20953 ;; Being at an item and not looking at an the item means point
20954 ;; was previously moved to beginning of a visual line, which
20955 ;; doesn't contain the item. Therefore, do nothing special,
20956 ;; just stay here.
20957 (when (looking-at org-list-full-item-re)
20958 ;; Set special position at first white space character after
20959 ;; bullet, and check-box, if any.
20960 (let ((after-bullet
20961 (let ((box (match-end 3)))
20962 (if (not box) (match-end 1)
20963 (let ((after (char-after box)))
20964 (if (and after (= after ? )) (1+ box) box))))))
20965 ;; Special case: Move point to special position when
20966 ;; currently after it or at beginning of line.
20967 (if (eq special t)
20968 (when (or (> pos after-bullet) (= (point) pos))
20969 (goto-char after-bullet))
20970 ;; Reversed case: Move point to special position when
20971 ;; point was already at beginning of line and command is
20972 ;; repeated.
20973 (when (and (= (point) pos) (eq last-command this-command))
20974 (goto-char after-bullet))))))))
20975 (org-no-warnings
20976 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20978 (defun org-end-of-line (&optional arg)
20979 "Go to the end of the line.
20980 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20981 first attempt, and only move to after the tags when the cursor is already
20982 beyond the end of the headline."
20983 (interactive "P")
20984 (let ((special (if (consp org-special-ctrl-a/e)
20985 (cdr org-special-ctrl-a/e)
20986 org-special-ctrl-a/e)))
20987 (cond
20988 ((or (not special) arg
20989 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20990 (call-interactively
20991 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20992 ((fboundp 'move-end-of-line) 'move-end-of-line)
20993 (t 'end-of-line))))
20994 ((org-at-heading-p)
20995 (let ((pos (point)))
20996 (beginning-of-line 1)
20997 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20998 (if (eq special t)
20999 (if (or (< pos (match-beginning 1))
21000 (= pos (match-end 0)))
21001 (goto-char (match-beginning 1))
21002 (goto-char (match-end 0)))
21003 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21004 (goto-char (match-end 0))
21005 (goto-char (match-beginning 1))))
21006 (call-interactively (if (fboundp 'move-end-of-line)
21007 'move-end-of-line
21008 'end-of-line)))))
21009 ((org-at-drawer-p)
21010 (move-end-of-line 1)
21011 (when (overlays-at (1- (point))) (backward-char 1)))
21012 ;; At an item: Move before any hidden text.
21013 (t (call-interactively
21014 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21015 ((fboundp 'move-end-of-line) 'move-end-of-line)
21016 (t 'end-of-line)))))
21017 (org-no-warnings
21018 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21020 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21021 (define-key org-mode-map "\C-e" 'org-end-of-line)
21023 (defun org-backward-sentence (&optional arg)
21024 "Go to beginning of sentence, or beginning of table field.
21025 This will call `backward-sentence' or `org-table-beginning-of-field',
21026 depending on context."
21027 (interactive "P")
21028 (cond
21029 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21030 (t (call-interactively 'backward-sentence))))
21032 (defun org-forward-sentence (&optional arg)
21033 "Go to end of sentence, or end of table field.
21034 This will call `forward-sentence' or `org-table-end-of-field',
21035 depending on context."
21036 (interactive "P")
21037 (cond
21038 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21039 (t (call-interactively 'forward-sentence))))
21041 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21042 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21044 (defun org-kill-line (&optional arg)
21045 "Kill line, to tags or end of line."
21046 (interactive "P")
21047 (cond
21048 ((or (not org-special-ctrl-k)
21049 (bolp)
21050 (not (org-at-heading-p)))
21051 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21052 org-ctrl-k-protect-subtree)
21053 (if (or (eq org-ctrl-k-protect-subtree 'error)
21054 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21055 (error "C-k aborted - would kill hidden subtree")))
21056 (call-interactively
21057 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21058 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21059 (kill-region (point) (match-beginning 1))
21060 (org-set-tags nil t))
21061 (t (kill-region (point) (point-at-eol)))))
21063 (define-key org-mode-map "\C-k" 'org-kill-line)
21065 (defun org-yank (&optional arg)
21066 "Yank. If the kill is a subtree, treat it specially.
21067 This command will look at the current kill and check if is a single
21068 subtree, or a series of subtrees[1]. If it passes the test, and if the
21069 cursor is at the beginning of a line or after the stars of a currently
21070 empty headline, then the yank is handled specially. How exactly depends
21071 on the value of the following variables, both set by default.
21073 org-yank-folded-subtrees
21074 When set, the subtree(s) will be folded after insertion, but only
21075 if doing so would now swallow text after the yanked text.
21077 org-yank-adjusted-subtrees
21078 When set, the subtree will be promoted or demoted in order to
21079 fit into the local outline tree structure, which means that the level
21080 will be adjusted so that it becomes the smaller one of the two
21081 *visible* surrounding headings.
21083 Any prefix to this command will cause `yank' to be called directly with
21084 no special treatment. In particular, a simple \\[universal-argument] prefix \
21085 will just
21086 plainly yank the text as it is.
21088 \[1] The test checks if the first non-white line is a heading
21089 and if there are no other headings with fewer stars."
21090 (interactive "P")
21091 (org-yank-generic 'yank arg))
21093 (defun org-yank-generic (command arg)
21094 "Perform some yank-like command.
21096 This function implements the behavior described in the `org-yank'
21097 documentation. However, it has been generalized to work for any
21098 interactive command with similar behavior."
21100 ;; pretend to be command COMMAND
21101 (setq this-command command)
21103 (if arg
21104 (call-interactively command)
21106 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21107 (and (org-kill-is-subtree-p)
21108 (or (bolp)
21109 (and (looking-at "[ \t]*$")
21110 (string-match
21111 "\\`\\*+\\'"
21112 (buffer-substring (point-at-bol) (point)))))))
21113 swallowp)
21114 (cond
21115 ((and subtreep org-yank-folded-subtrees)
21116 (let ((beg (point))
21117 end)
21118 (if (and subtreep org-yank-adjusted-subtrees)
21119 (org-paste-subtree nil nil 'for-yank)
21120 (call-interactively command))
21122 (setq end (point))
21123 (goto-char beg)
21124 (when (and (bolp) subtreep
21125 (not (setq swallowp
21126 (org-yank-folding-would-swallow-text beg end))))
21127 (org-with-limited-levels
21128 (or (looking-at org-outline-regexp)
21129 (re-search-forward org-outline-regexp-bol end t))
21130 (while (and (< (point) end) (looking-at org-outline-regexp))
21131 (hide-subtree)
21132 (org-cycle-show-empty-lines 'folded)
21133 (condition-case nil
21134 (outline-forward-same-level 1)
21135 (error (goto-char end))))))
21136 (when swallowp
21137 (message
21138 "Inserted text not folded because that would swallow text"))
21140 (goto-char end)
21141 (skip-chars-forward " \t\n\r")
21142 (beginning-of-line 1)
21143 (push-mark beg 'nomsg)))
21144 ((and subtreep org-yank-adjusted-subtrees)
21145 (let ((beg (point-at-bol)))
21146 (org-paste-subtree nil nil 'for-yank)
21147 (push-mark beg 'nomsg)))
21149 (call-interactively command))))))
21151 (defun org-yank-folding-would-swallow-text (beg end)
21152 "Would hide-subtree at BEG swallow any text after END?"
21153 (let (level)
21154 (org-with-limited-levels
21155 (save-excursion
21156 (goto-char beg)
21157 (when (or (looking-at org-outline-regexp)
21158 (re-search-forward org-outline-regexp-bol end t))
21159 (setq level (org-outline-level)))
21160 (goto-char end)
21161 (skip-chars-forward " \t\r\n\v\f")
21162 (if (or (eobp)
21163 (and (bolp) (looking-at org-outline-regexp)
21164 (<= (org-outline-level) level)))
21165 nil ; Nothing would be swallowed
21166 t))))) ; something would swallow
21168 (define-key org-mode-map "\C-y" 'org-yank)
21170 (defun org-truely-invisible-p ()
21171 "Check if point is at a character currently not visible.
21172 This version does not only check the character property, but also
21173 `visible-mode'."
21174 ;; Early versions of noutline don't have `outline-invisible-p'.
21175 (if (org-bound-and-true-p visible-mode)
21177 (outline-invisible-p)))
21179 (defun org-invisible-p2 ()
21180 "Check if point is at a character currently not visible."
21181 (save-excursion
21182 (if (and (eolp) (not (bobp))) (backward-char 1))
21183 ;; Early versions of noutline don't have `outline-invisible-p'.
21184 (outline-invisible-p)))
21186 (defun org-back-to-heading (&optional invisible-ok)
21187 "Call `outline-back-to-heading', but provide a better error message."
21188 (condition-case nil
21189 (outline-back-to-heading invisible-ok)
21190 (error (error "Before first headline at position %d in buffer %s"
21191 (point) (current-buffer)))))
21193 (defun org-beginning-of-defun ()
21194 "Go to the beginning of the subtree, i.e. back to the heading."
21195 (org-back-to-heading))
21196 (defun org-end-of-defun ()
21197 "Go to the end of the subtree."
21198 (org-end-of-subtree nil t))
21200 (defun org-before-first-heading-p ()
21201 "Before first heading?"
21202 (save-excursion
21203 (end-of-line)
21204 (null (re-search-backward org-outline-regexp-bol nil t))))
21206 (defun org-at-heading-p (&optional ignored)
21207 (outline-on-heading-p t))
21208 ;; Compatibility alias with Org versions < 7.8.03
21209 (defalias 'org-on-heading-p 'org-at-heading-p)
21211 (defun org-at-drawer-p nil
21212 "Is cursor at a drawer keyword?"
21213 (save-excursion
21214 (move-beginning-of-line 1)
21215 (looking-at org-drawer-regexp)))
21217 (defun org-at-block-p nil
21218 "Is cursor at a block keyword?"
21219 (save-excursion
21220 (move-beginning-of-line 1)
21221 (looking-at org-block-regexp)))
21223 (defun org-point-at-end-of-empty-headline ()
21224 "If point is at the end of an empty headline, return t, else nil.
21225 If the heading only contains a TODO keyword, it is still still considered
21226 empty."
21227 (and (looking-at "[ \t]*$")
21228 (when org-todo-line-regexp
21229 (save-excursion
21230 (beginning-of-line 1)
21231 (let ((case-fold-search nil))
21232 (looking-at org-todo-line-regexp)
21233 (string= (match-string 3) ""))))))
21235 (defun org-at-heading-or-item-p ()
21236 (or (org-at-heading-p) (org-at-item-p)))
21238 (defun org-at-target-p ()
21239 (or (org-in-regexp org-radio-target-regexp)
21240 (org-in-regexp org-target-regexp)))
21241 ;; Compatibility alias with Org versions < 7.8.03
21242 (defalias 'org-on-target-p 'org-at-target-p)
21244 (defun org-up-heading-all (arg)
21245 "Move to the heading line of which the present line is a subheading.
21246 This function considers both visible and invisible heading lines.
21247 With argument, move up ARG levels."
21248 (if (fboundp 'outline-up-heading-all)
21249 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21250 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21252 (defun org-up-heading-safe ()
21253 "Move to the heading line of which the present line is a subheading.
21254 This version will not throw an error. It will return the level of the
21255 headline found, or nil if no higher level is found.
21257 Also, this function will be a lot faster than `outline-up-heading',
21258 because it relies on stars being the outline starters. This can really
21259 make a significant difference in outlines with very many siblings."
21260 (let (start-level re)
21261 (org-back-to-heading t)
21262 (setq start-level (funcall outline-level))
21263 (if (equal start-level 1)
21265 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21266 (if (re-search-backward re nil t)
21267 (funcall outline-level)))))
21269 (defun org-first-sibling-p ()
21270 "Is this heading the first child of its parents?"
21271 (interactive)
21272 (let ((re org-outline-regexp-bol)
21273 level l)
21274 (unless (org-at-heading-p t)
21275 (error "Not at a heading"))
21276 (setq level (funcall outline-level))
21277 (save-excursion
21278 (if (not (re-search-backward re nil t))
21280 (setq l (funcall outline-level))
21281 (< l level)))))
21283 (defun org-goto-sibling (&optional previous)
21284 "Goto the next sibling, even if it is invisible.
21285 When PREVIOUS is set, go to the previous sibling instead. Returns t
21286 when a sibling was found. When none is found, return nil and don't
21287 move point."
21288 (let ((fun (if previous 're-search-backward 're-search-forward))
21289 (pos (point))
21290 (re org-outline-regexp-bol)
21291 level l)
21292 (when (condition-case nil (org-back-to-heading t) (error nil))
21293 (setq level (funcall outline-level))
21294 (catch 'exit
21295 (or previous (forward-char 1))
21296 (while (funcall fun re nil t)
21297 (setq l (funcall outline-level))
21298 (when (< l level) (goto-char pos) (throw 'exit nil))
21299 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21300 (goto-char pos)
21301 nil))))
21303 (defun org-show-siblings ()
21304 "Show all siblings of the current headline."
21305 (save-excursion
21306 (while (org-goto-sibling) (org-flag-heading nil)))
21307 (save-excursion
21308 (while (org-goto-sibling 'previous)
21309 (org-flag-heading nil))))
21311 (defun org-goto-first-child ()
21312 "Goto the first child, even if it is invisible.
21313 Return t when a child was found. Otherwise don't move point and
21314 return nil."
21315 (let (level (pos (point)) (re org-outline-regexp-bol))
21316 (when (condition-case nil (org-back-to-heading t) (error nil))
21317 (setq level (outline-level))
21318 (forward-char 1)
21319 (if (and (re-search-forward re nil t) (> (outline-level) level))
21320 (progn (goto-char (match-beginning 0)) t)
21321 (goto-char pos) nil))))
21323 (defun org-show-hidden-entry ()
21324 "Show an entry where even the heading is hidden."
21325 (save-excursion
21326 (org-show-entry)))
21328 (defun org-flag-heading (flag &optional entry)
21329 "Flag the current heading. FLAG non-nil means make invisible.
21330 When ENTRY is non-nil, show the entire entry."
21331 (save-excursion
21332 (org-back-to-heading t)
21333 ;; Check if we should show the entire entry
21334 (if entry
21335 (progn
21336 (org-show-entry)
21337 (save-excursion
21338 (and (outline-next-heading)
21339 (org-flag-heading nil))))
21340 (outline-flag-region (max (point-min) (1- (point)))
21341 (save-excursion (outline-end-of-heading) (point))
21342 flag))))
21344 (defun org-get-next-sibling ()
21345 "Move to next heading of the same level, and return point.
21346 If there is no such heading, return nil.
21347 This is like outline-next-sibling, but invisible headings are ok."
21348 (let ((level (funcall outline-level)))
21349 (outline-next-heading)
21350 (while (and (not (eobp)) (> (funcall outline-level) level))
21351 (outline-next-heading))
21352 (if (or (eobp) (< (funcall outline-level) level))
21354 (point))))
21356 (defun org-get-last-sibling ()
21357 "Move to previous heading of the same level, and return point.
21358 If there is no such heading, return nil."
21359 (let ((opoint (point))
21360 (level (funcall outline-level)))
21361 (outline-previous-heading)
21362 (when (and (/= (point) opoint) (outline-on-heading-p t))
21363 (while (and (> (funcall outline-level) level)
21364 (not (bobp)))
21365 (outline-previous-heading))
21366 (if (< (funcall outline-level) level)
21368 (point)))))
21370 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21371 ;; This contains an exact copy of the original function, but it uses
21372 ;; `org-back-to-heading', to make it work also in invisible
21373 ;; trees. And is uses an invisible-OK argument.
21374 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21375 ;; Furthermore, when used inside Org, finding the end of a large subtree
21376 ;; with many children and grandchildren etc, this can be much faster
21377 ;; than the outline version.
21378 (org-back-to-heading invisible-OK)
21379 (let ((first t)
21380 (level (funcall outline-level)))
21381 (if (and (derived-mode-p 'org-mode) (< level 1000))
21382 ;; A true heading (not a plain list item), in Org-mode
21383 ;; This means we can easily find the end by looking
21384 ;; only for the right number of stars. Using a regexp to do
21385 ;; this is so much faster than using a Lisp loop.
21386 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21387 (forward-char 1)
21388 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21389 ;; something else, do it the slow way
21390 (while (and (not (eobp))
21391 (or first (> (funcall outline-level) level)))
21392 (setq first nil)
21393 (outline-next-heading)))
21394 (unless to-heading
21395 (if (memq (preceding-char) '(?\n ?\^M))
21396 (progn
21397 ;; Go to end of line before heading
21398 (forward-char -1)
21399 (if (memq (preceding-char) '(?\n ?\^M))
21400 ;; leave blank line before heading
21401 (forward-char -1))))))
21402 (point))
21404 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21405 "Use Org version in org-mode, for dramatic speed-up."
21406 (if (derived-mode-p 'org-mode)
21407 (progn
21408 (org-end-of-subtree nil t)
21409 (unless (eobp) (backward-char 1)))
21410 ad-do-it))
21412 (defun org-end-of-meta-data-and-drawers ()
21413 "Jump to the first text after meta data and drawers in the current entry.
21414 This will move over empty lines, lines with planning time stamps,
21415 clocking lines, and drawers."
21416 (org-back-to-heading t)
21417 (let ((end (save-excursion (outline-next-heading) (point)))
21418 (re (concat "\\(" org-drawer-regexp "\\)"
21419 "\\|" "[ \t]*" org-keyword-time-regexp)))
21420 (forward-line 1)
21421 (while (re-search-forward re end t)
21422 (if (not (match-end 1))
21423 ;; empty or planning line
21424 (forward-line 1)
21425 ;; a drawer, find the end
21426 (re-search-forward "^[ \t]*:END:" end 'move)
21427 (forward-line 1)))
21428 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21429 (point)))
21431 (defun org-forward-same-level (arg &optional invisible-ok)
21432 "Move forward to the arg'th subheading at same level as this one.
21433 Stop at the first and last subheadings of a superior heading.
21434 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21435 it wil also look at invisible ones."
21436 (interactive "p")
21437 (org-back-to-heading invisible-ok)
21438 (org-at-heading-p)
21439 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21440 (re (format "^\\*\\{1,%d\\} " level))
21442 (forward-char 1)
21443 (while (> arg 0)
21444 (while (and (re-search-forward re nil 'move)
21445 (setq l (- (match-end 0) (match-beginning 0) 1))
21446 (= l level)
21447 (not invisible-ok)
21448 (progn (backward-char 1) (outline-invisible-p)))
21449 (if (< l level) (setq arg 1)))
21450 (setq arg (1- arg)))
21451 (beginning-of-line 1)))
21453 (defun org-backward-same-level (arg &optional invisible-ok)
21454 "Move backward to the arg'th subheading at same level as this one.
21455 Stop at the first and last subheadings of a superior heading."
21456 (interactive "p")
21457 (org-back-to-heading)
21458 (org-at-heading-p)
21459 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21460 (re (format "^\\*\\{1,%d\\} " level))
21462 (while (> arg 0)
21463 (while (and (re-search-backward re nil 'move)
21464 (setq l (- (match-end 0) (match-beginning 0) 1))
21465 (= l level)
21466 (not invisible-ok)
21467 (outline-invisible-p))
21468 (if (< l level) (setq arg 1)))
21469 (setq arg (1- arg)))))
21471 (defun org-show-subtree ()
21472 "Show everything after this heading at deeper levels."
21473 (interactive)
21474 (outline-flag-region
21475 (point)
21476 (save-excursion
21477 (org-end-of-subtree t t))
21478 nil))
21480 (defun org-show-entry ()
21481 "Show the body directly following this heading.
21482 Show the heading too, if it is currently invisible."
21483 (interactive)
21484 (save-excursion
21485 (condition-case nil
21486 (progn
21487 (org-back-to-heading t)
21488 (outline-flag-region
21489 (max (point-min) (1- (point)))
21490 (save-excursion
21491 (if (re-search-forward
21492 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21493 (match-beginning 1)
21494 (point-max)))
21495 nil)
21496 (org-cycle-hide-drawers 'children))
21497 (error nil))))
21499 (defun org-make-options-regexp (kwds &optional extra)
21500 "Make a regular expression for keyword lines."
21501 (concat
21503 "#?[ \t]*\\+\\("
21504 (mapconcat 'regexp-quote kwds "\\|")
21505 (if extra (concat "\\|" extra))
21506 "\\):[ \t]*"
21507 "\\(.*\\)"))
21509 ;; Make isearch reveal the necessary context
21510 (defun org-isearch-end ()
21511 "Reveal context after isearch exits."
21512 (when isearch-success ; only if search was successful
21513 (if (featurep 'xemacs)
21514 ;; Under XEmacs, the hook is run in the correct place,
21515 ;; we directly show the context.
21516 (org-show-context 'isearch)
21517 ;; In Emacs the hook runs *before* restoring the overlays.
21518 ;; So we have to use a one-time post-command-hook to do this.
21519 ;; (Emacs 22 has a special variable, see function `org-mode')
21520 (unless (and (boundp 'isearch-mode-end-hook-quit)
21521 isearch-mode-end-hook-quit)
21522 ;; Only when the isearch was not quitted.
21523 (org-add-hook 'post-command-hook 'org-isearch-post-command
21524 'append 'local)))))
21526 (defun org-isearch-post-command ()
21527 "Remove self from hook, and show context."
21528 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21529 (org-show-context 'isearch))
21532 ;;;; Integration with and fixes for other packages
21534 ;;; Imenu support
21536 (defvar org-imenu-markers nil
21537 "All markers currently used by Imenu.")
21538 (make-variable-buffer-local 'org-imenu-markers)
21540 (defun org-imenu-new-marker (&optional pos)
21541 "Return a new marker for use by Imenu, and remember the marker."
21542 (let ((m (make-marker)))
21543 (move-marker m (or pos (point)))
21544 (push m org-imenu-markers)
21547 (defun org-imenu-get-tree ()
21548 "Produce the index for Imenu."
21549 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21550 (setq org-imenu-markers nil)
21551 (let* ((n org-imenu-depth)
21552 (re (concat "^" (org-get-limited-outline-regexp)))
21553 (subs (make-vector (1+ n) nil))
21554 (last-level 0)
21555 m level head)
21556 (save-excursion
21557 (save-restriction
21558 (widen)
21559 (goto-char (point-max))
21560 (while (re-search-backward re nil t)
21561 (setq level (org-reduced-level (funcall outline-level)))
21562 (when (and (<= level n)
21563 (looking-at org-complex-heading-regexp))
21564 (setq head (org-link-display-format
21565 (org-match-string-no-properties 4))
21566 m (org-imenu-new-marker))
21567 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21568 (if (>= level last-level)
21569 (push (cons head m) (aref subs level))
21570 (push (cons head (aref subs (1+ level))) (aref subs level))
21571 (loop for i from (1+ level) to n do (aset subs i nil)))
21572 (setq last-level level)))))
21573 (aref subs 1)))
21575 (eval-after-load "imenu"
21576 '(progn
21577 (add-hook 'imenu-after-jump-hook
21578 (lambda ()
21579 (if (derived-mode-p 'org-mode)
21580 (org-show-context 'org-goto))))))
21582 (defun org-link-display-format (link)
21583 "Replace a link with either the description, or the link target
21584 if no description is present"
21585 (save-match-data
21586 (if (string-match org-bracket-link-analytic-regexp link)
21587 (replace-match (if (match-end 5)
21588 (match-string 5 link)
21589 (concat (match-string 1 link)
21590 (match-string 3 link)))
21591 nil t link)
21592 link)))
21594 (defun org-toggle-link-display ()
21595 "Toggle the literal or descriptive display of links."
21596 (interactive)
21597 (if org-descriptive-links
21598 (progn (org-remove-from-invisibility-spec '(org-link))
21599 (org-restart-font-lock)
21600 (setq org-descriptive-links nil))
21601 (progn (add-to-invisibility-spec '(org-link))
21602 (org-restart-font-lock)
21603 (setq org-descriptive-links t))))
21605 ;; Speedbar support
21607 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21608 "Overlay marking the agenda restriction line in speedbar.")
21609 (overlay-put org-speedbar-restriction-lock-overlay
21610 'face 'org-agenda-restriction-lock)
21611 (overlay-put org-speedbar-restriction-lock-overlay
21612 'help-echo "Agendas are currently limited to this item.")
21613 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21615 (defun org-speedbar-set-agenda-restriction ()
21616 "Restrict future agenda commands to the location at point in speedbar.
21617 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21618 (interactive)
21619 (require 'org-agenda)
21620 (let (p m tp np dir txt)
21621 (cond
21622 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21623 'org-imenu t))
21624 (setq m (get-text-property p 'org-imenu-marker))
21625 (with-current-buffer (marker-buffer m)
21626 (goto-char m)
21627 (org-agenda-set-restriction-lock 'subtree)))
21628 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21629 'speedbar-function 'speedbar-find-file))
21630 (setq tp (previous-single-property-change
21631 (1+ p) 'speedbar-function)
21632 np (next-single-property-change
21633 tp 'speedbar-function)
21634 dir (speedbar-line-directory)
21635 txt (buffer-substring-no-properties (or tp (point-min))
21636 (or np (point-max))))
21637 (with-current-buffer (find-file-noselect
21638 (let ((default-directory dir))
21639 (expand-file-name txt)))
21640 (unless (derived-mode-p 'org-mode)
21641 (error "Cannot restrict to non-Org-mode file"))
21642 (org-agenda-set-restriction-lock 'file)))
21643 (t (error "Don't know how to restrict Org-mode's agenda")))
21644 (move-overlay org-speedbar-restriction-lock-overlay
21645 (point-at-bol) (point-at-eol))
21646 (setq current-prefix-arg nil)
21647 (org-agenda-maybe-redo)))
21649 (eval-after-load "speedbar"
21650 '(progn
21651 (speedbar-add-supported-extension ".org")
21652 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21653 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21654 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21655 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21656 (add-hook 'speedbar-visiting-tag-hook
21657 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
21659 ;;; Fixes and Hacks for problems with other packages
21661 ;; Make flyspell not check words in links, to not mess up our keymap
21662 (defun org-mode-flyspell-verify ()
21663 "Don't let flyspell put overlays at active buttons, or on
21664 {todo,all-time,additional-option-like}-keywords."
21665 (let ((pos (max (1- (point)) (point-min)))
21666 (word (thing-at-point 'word)))
21667 (and (not (get-text-property pos 'keymap))
21668 (not (get-text-property pos 'org-no-flyspell))
21669 (not (member word org-todo-keywords-1))
21670 (not (member word org-all-time-keywords))
21671 (not (member word org-additional-option-like-keywords)))))
21673 (defun org-remove-flyspell-overlays-in (beg end)
21674 "Remove flyspell overlays in region."
21675 (and (org-bound-and-true-p flyspell-mode)
21676 (fboundp 'flyspell-delete-region-overlays)
21677 (flyspell-delete-region-overlays beg end))
21678 (add-text-properties beg end '(org-no-flyspell t)))
21680 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21681 (eval-after-load "bookmark"
21682 '(if (boundp 'bookmark-after-jump-hook)
21683 ;; We can use the hook
21684 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21685 ;; Hook not available, use advice
21686 (defadvice bookmark-jump (after org-make-visible activate)
21687 "Make the position visible."
21688 (org-bookmark-jump-unhide))))
21690 ;; Make sure saveplace shows the location if it was hidden
21691 (eval-after-load "saveplace"
21692 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21693 "Make the position visible."
21694 (org-bookmark-jump-unhide)))
21696 ;; Make sure ecb shows the location if it was hidden
21697 (eval-after-load "ecb"
21698 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21699 "Make hierarchy visible when jumping into location from ECB tree buffer."
21700 (if (derived-mode-p 'org-mode)
21701 (org-show-context))))
21703 (defun org-bookmark-jump-unhide ()
21704 "Unhide the current position, to show the bookmark location."
21705 (and (derived-mode-p 'org-mode)
21706 (or (outline-invisible-p)
21707 (save-excursion (goto-char (max (point-min) (1- (point))))
21708 (outline-invisible-p)))
21709 (org-show-context 'bookmark-jump)))
21711 ;; Make session.el ignore our circular variable
21712 (eval-after-load "session"
21713 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21715 ;;;; Experimental code
21717 (defun org-closed-in-range ()
21718 "Sparse tree of items closed in a certain time range.
21719 Still experimental, may disappear in the future."
21720 (interactive)
21721 ;; Get the time interval from the user.
21722 (let* ((time1 (org-float-time
21723 (org-read-date nil 'to-time nil "Starting date: ")))
21724 (time2 (org-float-time
21725 (org-read-date nil 'to-time nil "End date:")))
21726 ;; callback function
21727 (callback (lambda ()
21728 (let ((time
21729 (org-float-time
21730 (apply 'encode-time
21731 (org-parse-time-string
21732 (match-string 1))))))
21733 ;; check if time in interval
21734 (and (>= time time1) (<= time time2))))))
21735 ;; make tree, check each match with the callback
21736 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21738 ;;;; Finish up
21740 (provide 'org)
21742 (run-hooks 'org-load-hook)
21744 ;;; org.el ends here