fix org-reload and add parameters to customize output from org-version
[org-mode.git] / lisp / org.el
blob05f5375f4e47bdfe6de55d6aa8f2ec7130dedaca
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
82 (when (fboundp 'defvaralias)
83 (unless (boundp 'calendar-view-holidays-initially-flag)
84 (defvaralias 'calendar-view-holidays-initially-flag
85 'view-calendar-holidays-initially))
86 (unless (boundp 'calendar-view-diary-initially-flag)
87 (defvaralias 'calendar-view-diary-initially-flag
88 'view-diary-entries-initially))
89 (unless (boundp 'diary-fancy-buffer)
90 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
92 (require 'outline)
93 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
94 ;; Other stuff we need.
95 (require 'time-date)
96 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
97 (require 'easymenu)
98 (require 'overlay)
100 (require 'org-macs)
101 (require 'org-entities)
102 (require 'org-compat)
103 (require 'org-faces)
104 (require 'org-list)
105 (require 'org-pcomplete)
106 (require 'org-src)
107 (require 'org-footnote)
109 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
110 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
111 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
112 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
113 (declare-function org-at-clock-log-p "org-clock" ())
114 (declare-function org-clock-timestamps-up "org-clock" ())
115 (declare-function org-clock-timestamps-down "org-clock" ())
117 ;; babel
118 (require 'ob)
119 (require 'ob-table)
120 (require 'ob-lob)
121 (require 'ob-ref)
122 (require 'ob-tangle)
123 (require 'ob-comint)
124 (require 'ob-keys)
126 ;; load languages based on value of `org-babel-load-languages'
127 (defvar org-babel-load-languages)
128 ;;;###autoload
129 (defun org-babel-do-load-languages (sym value)
130 "Load the languages defined in `org-babel-load-languages'."
131 (set-default sym value)
132 (mapc (lambda (pair)
133 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
134 (if active
135 (progn
136 (require (intern (concat "ob-" lang))))
137 (progn
138 (funcall 'fmakunbound
139 (intern (concat "org-babel-execute:" lang)))
140 (funcall 'fmakunbound
141 (intern (concat "org-babel-expand-body:" lang)))))))
142 org-babel-load-languages))
144 (defcustom org-babel-load-languages '((emacs-lisp . t))
145 "Languages which can be evaluated in Org-mode buffers.
146 This list can be used to load support for any of the languages
147 below, note that each language will depend on a different set of
148 system executables and/or Emacs modes. When a language is
149 \"loaded\", then code blocks in that language can be evaluated
150 with `org-babel-execute-src-block' bound by default to C-c
151 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
152 be set to remove code block evaluation from the C-c C-c
153 keybinding. By default only Emacs Lisp (which has no
154 requirements) is loaded."
155 :group 'org-babel
156 :set 'org-babel-do-load-languages
157 :version "24.1"
158 :type '(alist :tag "Babel Languages"
159 :key-type
160 (choice
161 (const :tag "Awk" awk)
162 (const :tag "C" C)
163 (const :tag "R" R)
164 (const :tag "Asymptote" asymptote)
165 (const :tag "Calc" calc)
166 (const :tag "Clojure" clojure)
167 (const :tag "CSS" css)
168 (const :tag "Ditaa" ditaa)
169 (const :tag "Dot" dot)
170 (const :tag "Emacs Lisp" emacs-lisp)
171 (const :tag "Fortran" fortran)
172 (const :tag "Gnuplot" gnuplot)
173 (const :tag "Haskell" haskell)
174 (const :tag "IO" io)
175 (const :tag "Java" java)
176 (const :tag "Javascript" js)
177 (const :tag "LaTeX" latex)
178 (const :tag "Ledger" ledger)
179 (const :tag "Lilypond" lilypond)
180 (const :tag "Maxima" maxima)
181 (const :tag "Matlab" matlab)
182 (const :tag "Mscgen" mscgen)
183 (const :tag "Ocaml" ocaml)
184 (const :tag "Octave" octave)
185 (const :tag "Org" org)
186 (const :tag "Perl" perl)
187 (const :tag "Pico Lisp" picolisp)
188 (const :tag "PlantUML" plantuml)
189 (const :tag "Python" python)
190 (const :tag "Ruby" ruby)
191 (const :tag "Sass" sass)
192 (const :tag "Scala" scala)
193 (const :tag "Scheme" scheme)
194 (const :tag "Screen" screen)
195 (const :tag "Shell Script" sh)
196 (const :tag "Shen" shen)
197 (const :tag "Sql" sql)
198 (const :tag "Sqlite" sqlite))
199 :value-type (boolean :tag "Activate" :value t)))
201 ;;;; Customization variables
202 (defcustom org-clone-delete-id nil
203 "Remove ID property of clones of a subtree.
204 When non-nil, clones of a subtree don't inherit the ID property.
205 Otherwise they inherit the ID property with a new unique
206 identifier."
207 :type 'boolean
208 :version "24.1"
209 :group 'org-id)
211 ;;; Version
212 (eval-when-compile
213 (defun org-release () "N/A")
214 (defun org-git-version () "N/A !!check installation!!")
215 (and (load (concat (org-find-library-dir "org") "../UTILITIES/org-fixup.el")
216 'noerror 'nomessage 'nosuffix)
217 (org-no-warnings (org-fixup))))
218 ;;;###autoload
219 (defun org-version (&optional here full message)
220 "Show the org-mode version in the echo area.
221 With prefix arg HERE, insert it at point."
222 (interactive "P")
223 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
224 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
225 (org-version (org-release))
226 (git-version (org-git-version))
227 (version (format "Org-mode version %s (%s @ %s)"
228 org-version
229 git-version
230 (if org-install-dir
231 (if (string= org-dir org-install-dir)
232 org-install-dir
233 (concat "mixed installation! " org-install-dir " and " org-dir))
234 "org-install.el can not be found!")))
235 (_version (if full version org-version)))
236 (if (org-called-interactively-p 'interactive)
237 (if here
238 (insert version)
239 (message version))
240 (if message (message _version))
241 _version)))
243 ;;; Compatibility constants
245 ;;; The custom variables
247 (defgroup org nil
248 "Outline-based notes management and organizer."
249 :tag "Org"
250 :group 'outlines
251 :group 'calendar)
253 (defcustom org-mode-hook nil
254 "Mode hook for Org-mode, run after the mode was turned on."
255 :group 'org
256 :type 'hook)
258 (defcustom org-load-hook nil
259 "Hook that is run after org.el has been loaded."
260 :group 'org
261 :type 'hook)
263 (defcustom org-log-buffer-setup-hook nil
264 "Hook that is run after an Org log buffer is created."
265 :group 'org
266 :version "24.1"
267 :type 'hook)
269 (defvar org-modules) ; defined below
270 (defvar org-modules-loaded nil
271 "Have the modules been loaded already?")
273 (defun org-load-modules-maybe (&optional force)
274 "Load all extensions listed in `org-modules'."
275 (when (or force (not org-modules-loaded))
276 (mapc (lambda (ext)
277 (condition-case nil (require ext)
278 (error (message "Problems while trying to load feature `%s'" ext))))
279 org-modules)
280 (setq org-modules-loaded t)))
282 (defun org-set-modules (var value)
283 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
284 (set var value)
285 (when (featurep 'org)
286 (org-load-modules-maybe 'force)))
288 (when (org-bound-and-true-p org-modules)
289 (let ((a (member 'org-infojs org-modules)))
290 (and a (setcar a 'org-jsinfo))))
292 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
293 "Modules that should always be loaded together with org.el.
294 If a description starts with <C>, the file is not part of Emacs
295 and loading it will require that you have downloaded and properly installed
296 the org-mode distribution.
298 You can also use this system to load external packages (i.e. neither Org
299 core modules, nor modules from the CONTRIB directory). Just add symbols
300 to the end of the list. If the package is called org-xyz.el, then you need
301 to add the symbol `xyz', and the package must have a call to
303 (provide 'org-xyz)"
304 :group 'org
305 :set 'org-set-modules
306 :type
307 '(set :greedy t
308 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
309 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
310 (const :tag " crypt: Encryption of subtrees" org-crypt)
311 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
312 (const :tag " docview: Links to doc-view buffers" org-docview)
313 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
314 (const :tag " id: Global IDs for identifying entries" org-id)
315 (const :tag " info: Links to Info nodes" org-info)
316 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
317 (const :tag " habit: Track your consistency with habits" org-habit)
318 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
319 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
320 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
321 (const :tag " mew Links to Mew folders/messages" org-mew)
322 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
323 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
324 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
325 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
326 (const :tag " vm: Links to VM folders/messages" org-vm)
327 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
328 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
329 (const :tag " mouse: Additional mouse support" org-mouse)
330 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
332 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
333 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
334 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
335 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
336 (const :tag "C collector: Collect properties into tables" org-collector)
337 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
338 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
339 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
340 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
341 (const :tag "C eval: Include command output as text" org-eval)
342 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
343 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
344 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
345 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
346 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
348 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
350 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
351 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
352 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
353 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
354 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
355 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
356 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
357 (const :tag "C mtags: Support for muse-like tags" org-mtags)
358 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
359 (const :tag "C registry: A registry for Org-mode links" org-registry)
360 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
361 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
362 (const :tag "C secretary: Team management with org-mode" org-secretary)
363 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
364 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
365 (const :tag "C track: Keep up with Org-mode development" org-track)
366 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
367 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
368 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
370 (defcustom org-support-shift-select nil
371 "Non-nil means make shift-cursor commands select text when possible.
373 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
374 start selecting a region, or enlarge regions started in this way.
375 In Org-mode, in special contexts, these same keys are used for
376 other purposes, important enough to compete with shift selection.
377 Org tries to balance these needs by supporting `shift-select-mode'
378 outside these special contexts, under control of this variable.
380 The default of this variable is nil, to avoid confusing behavior. Shifted
381 cursor keys will then execute Org commands in the following contexts:
382 - on a headline, changing TODO state (left/right) and priority (up/down)
383 - on a time stamp, changing the time
384 - in a plain list item, changing the bullet type
385 - in a property definition line, switching between allowed values
386 - in the BEGIN line of a clock table (changing the time block).
387 Outside these contexts, the commands will throw an error.
389 When this variable is t and the cursor is not in a special
390 context, Org-mode will support shift-selection for making and
391 enlarging regions. To make this more effective, the bullet
392 cycling will no longer happen anywhere in an item line, but only
393 if the cursor is exactly on the bullet.
395 If you set this variable to the symbol `always', then the keys
396 will not be special in headlines, property lines, and item lines,
397 to make shift selection work there as well. If this is what you
398 want, you can use the following alternative commands: `C-c C-t'
399 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
400 can be used to switch TODO sets, `C-c -' to cycle item bullet
401 types, and properties can be edited by hand or in column view.
403 However, when the cursor is on a timestamp, shift-cursor commands
404 will still edit the time stamp - this is just too good to give up.
406 XEmacs user should have this variable set to nil, because
407 `shift-select-mode' is in Emacs 23 or later only."
408 :group 'org
409 :type '(choice
410 (const :tag "Never" nil)
411 (const :tag "When outside special context" t)
412 (const :tag "Everywhere except timestamps" always)))
414 (defcustom org-loop-over-headlines-in-active-region nil
415 "Shall some commands act upon headlines in the active region?
417 When set to `t', some commands will be performed in all headlines
418 within the active region.
420 When set to `start-level', some commands will be performed in all
421 headlines within the active region, provided that these headlines
422 are of the same level than the first one.
424 When set to a string, those commands will be performed on the
425 matching headlines within the active region. Such string must be
426 a tags/property/todo match as it is used in the agenda tags view.
428 The list of commands is: `org-schedule', `org-deadline',
429 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
430 `org-archive-to-archive-sibling'. The archiving commands skip
431 already archived entries."
432 :type '(choice (const :tag "Don't loop" nil)
433 (const :tag "All headlines in active region" t)
434 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
435 (string :tag "Tags/Property/Todo matcher"))
436 :version "24.1"
437 :group 'org-todo
438 :group 'org-archive)
440 (defgroup org-startup nil
441 "Options concerning startup of Org-mode."
442 :tag "Org Startup"
443 :group 'org)
445 (defcustom org-startup-folded t
446 "Non-nil means entering Org-mode will switch to OVERVIEW.
447 This can also be configured on a per-file basis by adding one of
448 the following lines anywhere in the buffer:
450 #+STARTUP: fold (or `overview', this is equivalent)
451 #+STARTUP: nofold (or `showall', this is equivalent)
452 #+STARTUP: content
453 #+STARTUP: showeverything"
454 :group 'org-startup
455 :type '(choice
456 (const :tag "nofold: show all" nil)
457 (const :tag "fold: overview" t)
458 (const :tag "content: all headlines" content)
459 (const :tag "show everything, even drawers" showeverything)))
461 (defcustom org-startup-truncated t
462 "Non-nil means entering Org-mode will set `truncate-lines'.
463 This is useful since some lines containing links can be very long and
464 uninteresting. Also tables look terrible when wrapped."
465 :group 'org-startup
466 :type 'boolean)
468 (defcustom org-startup-indented nil
469 "Non-nil means turn on `org-indent-mode' on startup.
470 This can also be configured on a per-file basis by adding one of
471 the following lines anywhere in the buffer:
473 #+STARTUP: indent
474 #+STARTUP: noindent"
475 :group 'org-structure
476 :type '(choice
477 (const :tag "Not" nil)
478 (const :tag "Globally (slow on startup in large files)" t)))
480 (defcustom org-use-sub-superscripts t
481 "Non-nil means interpret \"_\" and \"^\" for export.
482 When this option is turned on, you can use TeX-like syntax for sub- and
483 superscripts. Several characters after \"_\" or \"^\" will be
484 considered as a single item - so grouping with {} is normally not
485 needed. For example, the following things will be parsed as single
486 sub- or superscripts.
488 10^24 or 10^tau several digits will be considered 1 item.
489 10^-12 or 10^-tau a leading sign with digits or a word
490 x^2-y^3 will be read as x^2 - y^3, because items are
491 terminated by almost any nonword/nondigit char.
492 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
494 Still, ambiguity is possible - so when in doubt use {} to enclose the
495 sub/superscript. If you set this variable to the symbol `{}',
496 the braces are *required* in order to trigger interpretations as
497 sub/superscript. This can be helpful in documents that need \"_\"
498 frequently in plain text.
500 Not all export backends support this, but HTML does.
502 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
503 :group 'org-startup
504 :group 'org-export-translation
505 :version "24.1"
506 :type '(choice
507 (const :tag "Always interpret" t)
508 (const :tag "Only with braces" {})
509 (const :tag "Never interpret" nil)))
511 (if (fboundp 'defvaralias)
512 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
515 (defcustom org-startup-with-beamer-mode nil
516 "Non-nil means turn on `org-beamer-mode' on startup.
517 This can also be configured on a per-file basis by adding one of
518 the following lines anywhere in the buffer:
520 #+STARTUP: beamer"
521 :group 'org-startup
522 :version "24.1"
523 :type 'boolean)
525 (defcustom org-startup-align-all-tables nil
526 "Non-nil means align all tables when visiting a file.
527 This is useful when the column width in tables is forced with <N> cookies
528 in table fields. Such tables will look correct only after the first re-align.
529 This can also be configured on a per-file basis by adding one of
530 the following lines anywhere in the buffer:
531 #+STARTUP: align
532 #+STARTUP: noalign"
533 :group 'org-startup
534 :type 'boolean)
536 (defcustom org-startup-with-inline-images nil
537 "Non-nil means show inline images when loading a new Org file.
538 This can also be configured on a per-file basis by adding one of
539 the following lines anywhere in the buffer:
540 #+STARTUP: inlineimages
541 #+STARTUP: noinlineimages"
542 :group 'org-startup
543 :version "24.1"
544 :type 'boolean)
546 (defcustom org-insert-mode-line-in-empty-file nil
547 "Non-nil means insert the first line setting Org-mode in empty files.
548 When the function `org-mode' is called interactively in an empty file, this
549 normally means that the file name does not automatically trigger Org-mode.
550 To ensure that the file will always be in Org-mode in the future, a
551 line enforcing Org-mode will be inserted into the buffer, if this option
552 has been set."
553 :group 'org-startup
554 :type 'boolean)
556 (defcustom org-replace-disputed-keys nil
557 "Non-nil means use alternative key bindings for some keys.
558 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
559 These keys are also used by other packages like shift-selection-mode'
560 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
561 If you want to use Org-mode together with one of these other modes,
562 or more generally if you would like to move some Org-mode commands to
563 other keys, set this variable and configure the keys with the variable
564 `org-disputed-keys'.
566 This option is only relevant at load-time of Org-mode, and must be set
567 *before* org.el is loaded. Changing it requires a restart of Emacs to
568 become effective."
569 :group 'org-startup
570 :type 'boolean)
572 (defcustom org-use-extra-keys nil
573 "Non-nil means use extra key sequence definitions for certain commands.
574 This happens automatically if you run XEmacs or if `window-system'
575 is nil. This variable lets you do the same manually. You must
576 set it before loading org.
578 Example: on Carbon Emacs 22 running graphically, with an external
579 keyboard on a Powerbook, the default way of setting M-left might
580 not work for either Alt or ESC. Setting this variable will make
581 it work for ESC."
582 :group 'org-startup
583 :type 'boolean)
585 (if (fboundp 'defvaralias)
586 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
588 (defcustom org-disputed-keys
589 '(([(shift up)] . [(meta p)])
590 ([(shift down)] . [(meta n)])
591 ([(shift left)] . [(meta -)])
592 ([(shift right)] . [(meta +)])
593 ([(control shift right)] . [(meta shift +)])
594 ([(control shift left)] . [(meta shift -)]))
595 "Keys for which Org-mode and other modes compete.
596 This is an alist, cars are the default keys, second element specifies
597 the alternative to use when `org-replace-disputed-keys' is t.
599 Keys can be specified in any syntax supported by `define-key'.
600 The value of this option takes effect only at Org-mode's startup,
601 therefore you'll have to restart Emacs to apply it after changing."
602 :group 'org-startup
603 :type 'alist)
605 (defun org-key (key)
606 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
607 Or return the original if not disputed.
608 Also apply the translations defined in `org-xemacs-key-equivalents'."
609 (when org-replace-disputed-keys
610 (let* ((nkey (key-description key))
611 (x (org-find-if (lambda (x)
612 (equal (key-description (car x)) nkey))
613 org-disputed-keys)))
614 (setq key (if x (cdr x) key))))
615 (when (featurep 'xemacs)
616 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
617 key)
619 (defun org-find-if (predicate seq)
620 (catch 'exit
621 (while seq
622 (if (funcall predicate (car seq))
623 (throw 'exit (car seq))
624 (pop seq)))))
626 (defun org-defkey (keymap key def)
627 "Define a key, possibly translated, as returned by `org-key'."
628 (define-key keymap (org-key key) def))
630 (defcustom org-ellipsis nil
631 "The ellipsis to use in the Org-mode outline.
632 When nil, just use the standard three dots. When a string, use that instead,
633 When a face, use the standard 3 dots, but with the specified face.
634 The change affects only Org-mode (which will then use its own display table).
635 Changing this requires executing `M-x org-mode' in a buffer to become
636 effective."
637 :group 'org-startup
638 :type '(choice (const :tag "Default" nil)
639 (face :tag "Face" :value org-warning)
640 (string :tag "String" :value "...#")))
642 (defvar org-display-table nil
643 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
645 (defgroup org-keywords nil
646 "Keywords in Org-mode."
647 :tag "Org Keywords"
648 :group 'org)
650 (defcustom org-deadline-string "DEADLINE:"
651 "String to mark deadline entries.
652 A deadline is this string, followed by a time stamp. Should be a word,
653 terminated by a colon. You can insert a schedule keyword and
654 a timestamp with \\[org-deadline].
655 Changes become only effective after restarting Emacs."
656 :group 'org-keywords
657 :type 'string)
659 (defcustom org-scheduled-string "SCHEDULED:"
660 "String to mark scheduled TODO entries.
661 A schedule is this string, followed by a time stamp. Should be a word,
662 terminated by a colon. You can insert a schedule keyword and
663 a timestamp with \\[org-schedule].
664 Changes become only effective after restarting Emacs."
665 :group 'org-keywords
666 :type 'string)
668 (defcustom org-closed-string "CLOSED:"
669 "String used as the prefix for timestamps logging closing a TODO entry."
670 :group 'org-keywords
671 :type 'string)
673 (defcustom org-clock-string "CLOCK:"
674 "String used as prefix for timestamps clocking work hours on an item."
675 :group 'org-keywords
676 :type 'string)
678 (defcustom org-comment-string "COMMENT"
679 "Entries starting with this keyword will never be exported.
680 An entry can be toggled between COMMENT and normal with
681 \\[org-toggle-comment].
682 Changes become only effective after restarting Emacs."
683 :group 'org-keywords
684 :type 'string)
686 (defcustom org-quote-string "QUOTE"
687 "Entries starting with this keyword will be exported in fixed-width font.
688 Quoting applies only to the text in the entry following the headline, and does
689 not extend beyond the next headline, even if that is lower level.
690 An entry can be toggled between QUOTE and normal with
691 \\[org-toggle-fixed-width-section]."
692 :group 'org-keywords
693 :type 'string)
695 (defconst org-repeat-re
696 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
697 "Regular expression for specifying repeated events.
698 After a match, group 1 contains the repeat expression.")
700 (defgroup org-structure nil
701 "Options concerning the general structure of Org-mode files."
702 :tag "Org Structure"
703 :group 'org)
705 (defgroup org-reveal-location nil
706 "Options about how to make context of a location visible."
707 :tag "Org Reveal Location"
708 :group 'org-structure)
710 (defconst org-context-choice
711 '(choice
712 (const :tag "Always" t)
713 (const :tag "Never" nil)
714 (repeat :greedy t :tag "Individual contexts"
715 (cons
716 (choice :tag "Context"
717 (const agenda)
718 (const org-goto)
719 (const occur-tree)
720 (const tags-tree)
721 (const link-search)
722 (const mark-goto)
723 (const bookmark-jump)
724 (const isearch)
725 (const default))
726 (boolean))))
727 "Contexts for the reveal options.")
729 (defcustom org-show-hierarchy-above '((default . t))
730 "Non-nil means show full hierarchy when revealing a location.
731 Org-mode often shows locations in an org-mode file which might have
732 been invisible before. When this is set, the hierarchy of headings
733 above the exposed location is shown.
734 Turning this off for example for sparse trees makes them very compact.
735 Instead of t, this can also be an alist specifying this option for different
736 contexts. Valid contexts are
737 agenda when exposing an entry from the agenda
738 org-goto when using the command `org-goto' on key C-c C-j
739 occur-tree when using the command `org-occur' on key C-c /
740 tags-tree when constructing a sparse tree based on tags matches
741 link-search when exposing search matches associated with a link
742 mark-goto when exposing the jump goal of a mark
743 bookmark-jump when exposing a bookmark location
744 isearch when exiting from an incremental search
745 default default for all contexts not set explicitly"
746 :group 'org-reveal-location
747 :type org-context-choice)
749 (defcustom org-show-following-heading '((default . nil))
750 "Non-nil means show following heading when revealing a location.
751 Org-mode often shows locations in an org-mode file which might have
752 been invisible before. When this is set, the heading following the
753 match is shown.
754 Turning this off for example for sparse trees makes them very compact,
755 but makes it harder to edit the location of the match. In such a case,
756 use the command \\[org-reveal] to show more context.
757 Instead of t, this can also be an alist specifying this option for different
758 contexts. See `org-show-hierarchy-above' for valid contexts."
759 :group 'org-reveal-location
760 :type org-context-choice)
762 (defcustom org-show-siblings '((default . nil) (isearch t))
763 "Non-nil means show all sibling heading when revealing a location.
764 Org-mode often shows locations in an org-mode file which might have
765 been invisible before. When this is set, the sibling of the current entry
766 heading are all made visible. If `org-show-hierarchy-above' is t,
767 the same happens on each level of the hierarchy above the current entry.
769 By default this is on for the isearch context, off for all other contexts.
770 Turning this off for example for sparse trees makes them very compact,
771 but makes it harder to edit the location of the match. In such a case,
772 use the command \\[org-reveal] to show more context.
773 Instead of t, this can also be an alist specifying this option for different
774 contexts. See `org-show-hierarchy-above' for valid contexts."
775 :group 'org-reveal-location
776 :type org-context-choice)
778 (defcustom org-show-entry-below '((default . nil))
779 "Non-nil means show the entry below a headline when revealing a location.
780 Org-mode often shows locations in an org-mode file which might have
781 been invisible before. When this is set, the text below the headline that is
782 exposed is also shown.
784 By default this is off for all contexts.
785 Instead of t, this can also be an alist specifying this option for different
786 contexts. See `org-show-hierarchy-above' for valid contexts."
787 :group 'org-reveal-location
788 :type org-context-choice)
790 (defcustom org-indirect-buffer-display 'other-window
791 "How should indirect tree buffers be displayed?
792 This applies to indirect buffers created with the commands
793 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
794 Valid values are:
795 current-window Display in the current window
796 other-window Just display in another window.
797 dedicated-frame Create one new frame, and re-use it each time.
798 new-frame Make a new frame each time. Note that in this case
799 previously-made indirect buffers are kept, and you need to
800 kill these buffers yourself."
801 :group 'org-structure
802 :group 'org-agenda-windows
803 :type '(choice
804 (const :tag "In current window" current-window)
805 (const :tag "In current frame, other window" other-window)
806 (const :tag "Each time a new frame" new-frame)
807 (const :tag "One dedicated frame" dedicated-frame)))
809 (defcustom org-use-speed-commands nil
810 "Non-nil means activate single letter commands at beginning of a headline.
811 This may also be a function to test for appropriate locations where speed
812 commands should be active."
813 :group 'org-structure
814 :type '(choice
815 (const :tag "Never" nil)
816 (const :tag "At beginning of headline stars" t)
817 (function)))
819 (defcustom org-speed-commands-user nil
820 "Alist of additional speed commands.
821 This list will be checked before `org-speed-commands-default'
822 when the variable `org-use-speed-commands' is non-nil
823 and when the cursor is at the beginning of a headline.
824 The car if each entry is a string with a single letter, which must
825 be assigned to `self-insert-command' in the global map.
826 The cdr is either a command to be called interactively, a function
827 to be called, or a form to be evaluated.
828 An entry that is just a list with a single string will be interpreted
829 as a descriptive headline that will be added when listing the speed
830 commands in the Help buffer using the `?' speed command."
831 :group 'org-structure
832 :type '(repeat :value ("k" . ignore)
833 (choice :value ("k" . ignore)
834 (list :tag "Descriptive Headline" (string :tag "Headline"))
835 (cons :tag "Letter and Command"
836 (string :tag "Command letter")
837 (choice
838 (function)
839 (sexp))))))
841 (defgroup org-cycle nil
842 "Options concerning visibility cycling in Org-mode."
843 :tag "Org Cycle"
844 :group 'org-structure)
846 (defcustom org-cycle-skip-children-state-if-no-children t
847 "Non-nil means skip CHILDREN state in entries that don't have any."
848 :group 'org-cycle
849 :type 'boolean)
851 (defcustom org-cycle-max-level nil
852 "Maximum level which should still be subject to visibility cycling.
853 Levels higher than this will, for cycling, be treated as text, not a headline.
854 When `org-odd-levels-only' is set, a value of N in this variable actually
855 means 2N-1 stars as the limiting headline.
856 When nil, cycle all levels.
857 Note that the limiting level of cycling is also influenced by
858 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
859 `org-inlinetask-min-level' is, cycling will be limited to levels one less
860 than its value."
861 :group 'org-cycle
862 :type '(choice
863 (const :tag "No limit" nil)
864 (integer :tag "Maximum level")))
866 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
867 "Names of drawers. Drawers are not opened by cycling on the headline above.
868 Drawers only open with a TAB on the drawer line itself. A drawer looks like
869 this:
870 :DRAWERNAME:
871 .....
872 :END:
873 The drawer \"PROPERTIES\" is special for capturing properties through
874 the property API.
876 Drawers can be defined on the per-file basis with a line like:
878 #+DRAWERS: HIDDEN STATE PROPERTIES"
879 :group 'org-structure
880 :group 'org-cycle
881 :type '(repeat (string :tag "Drawer Name")))
883 (defcustom org-hide-block-startup nil
884 "Non-nil means entering Org-mode will fold all blocks.
885 This can also be set in on a per-file basis with
887 #+STARTUP: hideblocks
888 #+STARTUP: showblocks"
889 :group 'org-startup
890 :group 'org-cycle
891 :type 'boolean)
893 (defcustom org-cycle-global-at-bob nil
894 "Cycle globally if cursor is at beginning of buffer and not at a headline.
895 This makes it possible to do global cycling without having to use S-TAB or
896 \\[universal-argument] TAB. For this special case to work, the first line \
897 of the buffer
898 must not be a headline - it may be empty or some other text. When used in
899 this way, `org-cycle-hook' is disables temporarily, to make sure the
900 cursor stays at the beginning of the buffer.
901 When this option is nil, don't do anything special at the beginning
902 of the buffer."
903 :group 'org-cycle
904 :type 'boolean)
906 (defcustom org-cycle-level-after-item/entry-creation t
907 "Non-nil means cycle entry level or item indentation in new empty entries.
909 When the cursor is at the end of an empty headline, i.e with only stars
910 and maybe a TODO keyword, TAB will then switch the entry to become a child,
911 and then all possible ancestor states, before returning to the original state.
912 This makes data entry extremely fast: M-RET to create a new headline,
913 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
915 When the cursor is at the end of an empty plain list item, one TAB will
916 make it a subitem, two or more tabs will back up to make this an item
917 higher up in the item hierarchy."
918 :group 'org-cycle
919 :type 'boolean)
921 (defcustom org-cycle-emulate-tab t
922 "Where should `org-cycle' emulate TAB.
923 nil Never
924 white Only in completely white lines
925 whitestart Only at the beginning of lines, before the first non-white char
926 t Everywhere except in headlines
927 exc-hl-bol Everywhere except at the start of a headline
928 If TAB is used in a place where it does not emulate TAB, the current subtree
929 visibility is cycled."
930 :group 'org-cycle
931 :type '(choice (const :tag "Never" nil)
932 (const :tag "Only in completely white lines" white)
933 (const :tag "Before first char in a line" whitestart)
934 (const :tag "Everywhere except in headlines" t)
935 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
938 (defcustom org-cycle-separator-lines 2
939 "Number of empty lines needed to keep an empty line between collapsed trees.
940 If you leave an empty line between the end of a subtree and the following
941 headline, this empty line is hidden when the subtree is folded.
942 Org-mode will leave (exactly) one empty line visible if the number of
943 empty lines is equal or larger to the number given in this variable.
944 So the default 2 means at least 2 empty lines after the end of a subtree
945 are needed to produce free space between a collapsed subtree and the
946 following headline.
948 If the number is negative, and the number of empty lines is at least -N,
949 all empty lines are shown.
951 Special case: when 0, never leave empty lines in collapsed view."
952 :group 'org-cycle
953 :type 'integer)
954 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
956 (defcustom org-pre-cycle-hook nil
957 "Hook that is run before visibility cycling is happening.
958 The function(s) in this hook must accept a single argument which indicates
959 the new state that will be set right after running this hook. The
960 argument is a symbol. Before a global state change, it can have the values
961 `overview', `content', or `all'. Before a local state change, it can have
962 the values `folded', `children', or `subtree'."
963 :group 'org-cycle
964 :type 'hook)
966 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
967 org-cycle-hide-drawers
968 org-cycle-show-empty-lines
969 org-optimize-window-after-visibility-change)
970 "Hook that is run after `org-cycle' has changed the buffer visibility.
971 The function(s) in this hook must accept a single argument which indicates
972 the new state that was set by the most recent `org-cycle' command. The
973 argument is a symbol. After a global state change, it can have the values
974 `overview', `content', or `all'. After a local state change, it can have
975 the values `folded', `children', or `subtree'."
976 :group 'org-cycle
977 :type 'hook)
979 (defgroup org-edit-structure nil
980 "Options concerning structure editing in Org-mode."
981 :tag "Org Edit Structure"
982 :group 'org-structure)
984 (defcustom org-odd-levels-only nil
985 "Non-nil means skip even levels and only use odd levels for the outline.
986 This has the effect that two stars are being added/taken away in
987 promotion/demotion commands. It also influences how levels are
988 handled by the exporters.
989 Changing it requires restart of `font-lock-mode' to become effective
990 for fontification also in regions already fontified.
991 You may also set this on a per-file basis by adding one of the following
992 lines to the buffer:
994 #+STARTUP: odd
995 #+STARTUP: oddeven"
996 :group 'org-edit-structure
997 :group 'org-appearance
998 :type 'boolean)
1000 (defcustom org-adapt-indentation t
1001 "Non-nil means adapt indentation to outline node level.
1003 When this variable is set, Org assumes that you write outlines by
1004 indenting text in each node to align with the headline (after the stars).
1005 The following issues are influenced by this variable:
1007 - When this is set and the *entire* text in an entry is indented, the
1008 indentation is increased by one space in a demotion command, and
1009 decreased by one in a promotion command. If any line in the entry
1010 body starts with text at column 0, indentation is not changed at all.
1012 - Property drawers and planning information is inserted indented when
1013 this variable s set. When nil, they will not be indented.
1015 - TAB indents a line relative to context. The lines below a headline
1016 will be indented when this variable is set.
1018 Note that this is all about true indentation, by adding and removing
1019 space characters. See also `org-indent.el' which does level-dependent
1020 indentation in a virtual way, i.e. at display time in Emacs."
1021 :group 'org-edit-structure
1022 :type 'boolean)
1024 (defcustom org-special-ctrl-a/e nil
1025 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1027 When t, `C-a' will bring back the cursor to the beginning of the
1028 headline text, i.e. after the stars and after a possible TODO
1029 keyword. In an item, this will be the position after bullet and
1030 check-box, if any. When the cursor is already at that position,
1031 another `C-a' will bring it to the beginning of the line.
1033 `C-e' will jump to the end of the headline, ignoring the presence
1034 of tags in the headline. A second `C-e' will then jump to the
1035 true end of the line, after any tags. This also means that, when
1036 this variable is non-nil, `C-e' also will never jump beyond the
1037 end of the heading of a folded section, i.e. not after the
1038 ellipses.
1040 When set to the symbol `reversed', the first `C-a' or `C-e' works
1041 normally, going to the true line boundary first. Only a directly
1042 following, identical keypress will bring the cursor to the
1043 special positions.
1045 This may also be a cons cell where the behavior for `C-a' and
1046 `C-e' is set separately."
1047 :group 'org-edit-structure
1048 :type '(choice
1049 (const :tag "off" nil)
1050 (const :tag "on: after stars/bullet and before tags first" t)
1051 (const :tag "reversed: true line boundary first" reversed)
1052 (cons :tag "Set C-a and C-e separately"
1053 (choice :tag "Special C-a"
1054 (const :tag "off" nil)
1055 (const :tag "on: after stars/bullet first" t)
1056 (const :tag "reversed: before stars/bullet first" reversed))
1057 (choice :tag "Special C-e"
1058 (const :tag "off" nil)
1059 (const :tag "on: before tags first" t)
1060 (const :tag "reversed: after tags first" reversed)))))
1061 (if (fboundp 'defvaralias)
1062 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1064 (defcustom org-special-ctrl-k nil
1065 "Non-nil means `C-k' will behave specially in headlines.
1066 When nil, `C-k' will call the default `kill-line' command.
1067 When t, the following will happen while the cursor is in the headline:
1069 - When the cursor is at the beginning of a headline, kill the entire
1070 line and possible the folded subtree below the line.
1071 - When in the middle of the headline text, kill the headline up to the tags.
1072 - When after the headline text, kill the tags."
1073 :group 'org-edit-structure
1074 :type 'boolean)
1076 (defcustom org-ctrl-k-protect-subtree nil
1077 "Non-nil means, do not delete a hidden subtree with C-k.
1078 When set to the symbol `error', simply throw an error when C-k is
1079 used to kill (part-of) a headline that has hidden text behind it.
1080 Any other non-nil value will result in a query to the user, if it is
1081 OK to kill that hidden subtree. When nil, kill without remorse."
1082 :group 'org-edit-structure
1083 :version "24.1"
1084 :type '(choice
1085 (const :tag "Do not protect hidden subtrees" nil)
1086 (const :tag "Protect hidden subtrees with a security query" t)
1087 (const :tag "Never kill a hidden subtree with C-k" error)))
1089 (defcustom org-catch-invisible-edits nil
1090 "Check if in invisible region before inserting or deleting a character.
1091 Valid values are:
1093 nil Do not check, so just do invisible edits.
1094 error Throw an error and do nothing.
1095 show Make point visible, and do the requested edit.
1096 show-and-error Make point visible, then throw an error and abort the edit.
1097 smart Make point visible, and do insertion/deletion if it is
1098 adjacent to visible text and the change feels predictable.
1099 Never delete a previously invisible character or add in the
1100 middle or right after an invisible region. Basically, this
1101 allows insertion and backward-delete right before ellipses.
1102 FIXME: maybe in this case we should not even show?"
1103 :group 'org-edit-structure
1104 :version "24.1"
1105 :type '(choice
1106 (const :tag "Do not check" nil)
1107 (const :tag "Throw error when trying to edit" error)
1108 (const :tag "Unhide, but do not do the edit" show-and-error)
1109 (const :tag "Show invisible part and do the edit" show)
1110 (const :tag "Be smart and do the right thing" smart)))
1112 (defcustom org-yank-folded-subtrees t
1113 "Non-nil means when yanking subtrees, fold them.
1114 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1115 it starts with a heading and all other headings in it are either children
1116 or siblings, then fold all the subtrees. However, do this only if no
1117 text after the yank would be swallowed into a folded tree by this action."
1118 :group 'org-edit-structure
1119 :type 'boolean)
1121 (defcustom org-yank-adjusted-subtrees nil
1122 "Non-nil means when yanking subtrees, adjust the level.
1123 With this setting, `org-paste-subtree' is used to insert the subtree, see
1124 this function for details."
1125 :group 'org-edit-structure
1126 :type 'boolean)
1128 (defcustom org-M-RET-may-split-line '((default . t))
1129 "Non-nil means M-RET will split the line at the cursor position.
1130 When nil, it will go to the end of the line before making a
1131 new line.
1132 You may also set this option in a different way for different
1133 contexts. Valid contexts are:
1135 headline when creating a new headline
1136 item when creating a new item
1137 table in a table field
1138 default the value to be used for all contexts not explicitly
1139 customized"
1140 :group 'org-structure
1141 :group 'org-table
1142 :type '(choice
1143 (const :tag "Always" t)
1144 (const :tag "Never" nil)
1145 (repeat :greedy t :tag "Individual contexts"
1146 (cons
1147 (choice :tag "Context"
1148 (const headline)
1149 (const item)
1150 (const table)
1151 (const default))
1152 (boolean)))))
1155 (defcustom org-insert-heading-respect-content nil
1156 "Non-nil means insert new headings after the current subtree.
1157 When nil, the new heading is created directly after the current line.
1158 The commands \\[org-insert-heading-respect-content] and
1159 \\[org-insert-todo-heading-respect-content] turn this variable on
1160 for the duration of the command."
1161 :group 'org-structure
1162 :type 'boolean)
1164 (defcustom org-blank-before-new-entry '((heading . auto)
1165 (plain-list-item . auto))
1166 "Should `org-insert-heading' leave a blank line before new heading/item?
1167 The value is an alist, with `heading' and `plain-list-item' as CAR,
1168 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1169 which case Org will look at the surrounding headings/items and try to
1170 make an intelligent decision whether to insert a blank line or not.
1172 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1173 set, the setting here is ignored and no empty line is inserted, to avoid
1174 breaking the list structure."
1175 :group 'org-edit-structure
1176 :type '(list
1177 (cons (const heading)
1178 (choice (const :tag "Never" nil)
1179 (const :tag "Always" t)
1180 (const :tag "Auto" auto)))
1181 (cons (const plain-list-item)
1182 (choice (const :tag "Never" nil)
1183 (const :tag "Always" t)
1184 (const :tag "Auto" auto)))))
1186 (defcustom org-insert-heading-hook nil
1187 "Hook being run after inserting a new heading."
1188 :group 'org-edit-structure
1189 :type 'hook)
1191 (defcustom org-enable-fixed-width-editor t
1192 "Non-nil means lines starting with \":\" are treated as fixed-width.
1193 This currently only means they are never auto-wrapped.
1194 When nil, such lines will be treated like ordinary lines.
1195 See also the QUOTE keyword."
1196 :group 'org-edit-structure
1197 :type 'boolean)
1199 (defcustom org-goto-auto-isearch t
1200 "Non-nil means typing characters in `org-goto' starts incremental search."
1201 :group 'org-edit-structure
1202 :type 'boolean)
1204 (defgroup org-sparse-trees nil
1205 "Options concerning sparse trees in Org-mode."
1206 :tag "Org Sparse Trees"
1207 :group 'org-structure)
1209 (defcustom org-highlight-sparse-tree-matches t
1210 "Non-nil means highlight all matches that define a sparse tree.
1211 The highlights will automatically disappear the next time the buffer is
1212 changed by an edit command."
1213 :group 'org-sparse-trees
1214 :type 'boolean)
1216 (defcustom org-remove-highlights-with-change t
1217 "Non-nil means any change to the buffer will remove temporary highlights.
1218 Such highlights are created by `org-occur' and `org-clock-display'.
1219 When nil, `C-c C-c needs to be used to get rid of the highlights.
1220 The highlights created by `org-preview-latex-fragment' always need
1221 `C-c C-c' to be removed."
1222 :group 'org-sparse-trees
1223 :group 'org-time
1224 :type 'boolean)
1227 (defcustom org-occur-hook '(org-first-headline-recenter)
1228 "Hook that is run after `org-occur' has constructed a sparse tree.
1229 This can be used to recenter the window to show as much of the structure
1230 as possible."
1231 :group 'org-sparse-trees
1232 :type 'hook)
1234 (defgroup org-imenu-and-speedbar nil
1235 "Options concerning imenu and speedbar in Org-mode."
1236 :tag "Org Imenu and Speedbar"
1237 :group 'org-structure)
1239 (defcustom org-imenu-depth 2
1240 "The maximum level for Imenu access to Org-mode headlines.
1241 This also applied for speedbar access."
1242 :group 'org-imenu-and-speedbar
1243 :type 'integer)
1245 (defgroup org-table nil
1246 "Options concerning tables in Org-mode."
1247 :tag "Org Table"
1248 :group 'org)
1250 (defcustom org-enable-table-editor 'optimized
1251 "Non-nil means lines starting with \"|\" are handled by the table editor.
1252 When nil, such lines will be treated like ordinary lines.
1254 When equal to the symbol `optimized', the table editor will be optimized to
1255 do the following:
1256 - Automatic overwrite mode in front of whitespace in table fields.
1257 This makes the structure of the table stay in tact as long as the edited
1258 field does not exceed the column width.
1259 - Minimize the number of realigns. Normally, the table is aligned each time
1260 TAB or RET are pressed to move to another field. With optimization this
1261 happens only if changes to a field might have changed the column width.
1262 Optimization requires replacing the functions `self-insert-command',
1263 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1264 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1265 very good at guessing when a re-align will be necessary, but you can always
1266 force one with \\[org-ctrl-c-ctrl-c].
1268 If you would like to use the optimized version in Org-mode, but the
1269 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1271 This variable can be used to turn on and off the table editor during a session,
1272 but in order to toggle optimization, a restart is required.
1274 See also the variable `org-table-auto-blank-field'."
1275 :group 'org-table
1276 :type '(choice
1277 (const :tag "off" nil)
1278 (const :tag "on" t)
1279 (const :tag "on, optimized" optimized)))
1281 (defcustom org-self-insert-cluster-for-undo t
1282 "Non-nil means cluster self-insert commands for undo when possible.
1283 If this is set, then, like in the Emacs command loop, 20 consecutive
1284 characters will be undone together.
1285 This is configurable, because there is some impact on typing performance."
1286 :group 'org-table
1287 :type 'boolean)
1289 (defcustom org-table-tab-recognizes-table.el t
1290 "Non-nil means TAB will automatically notice a table.el table.
1291 When it sees such a table, it moves point into it and - if necessary -
1292 calls `table-recognize-table'."
1293 :group 'org-table-editing
1294 :type 'boolean)
1296 (defgroup org-link nil
1297 "Options concerning links in Org-mode."
1298 :tag "Org Link"
1299 :group 'org)
1301 (defvar org-link-abbrev-alist-local nil
1302 "Buffer-local version of `org-link-abbrev-alist', which see.
1303 The value of this is taken from the #+LINK lines.")
1304 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1306 (defcustom org-link-abbrev-alist nil
1307 "Alist of link abbreviations.
1308 The car of each element is a string, to be replaced at the start of a link.
1309 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1310 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1312 [[linkkey:tag][description]]
1314 The 'linkkey' must be a word word, starting with a letter, followed
1315 by letters, numbers, '-' or '_'.
1317 If REPLACE is a string, the tag will simply be appended to create the link.
1318 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1319 the placeholder \"%h\" will cause a url-encoded version of the tag to
1320 be inserted at that point (see the function `url-hexify-string').
1322 REPLACE may also be a function that will be called with the tag as the
1323 only argument to create the link, which should be returned as a string.
1325 See the manual for examples."
1326 :group 'org-link
1327 :type '(repeat
1328 (cons
1329 (string :tag "Protocol")
1330 (choice
1331 (string :tag "Format")
1332 (function)))))
1334 (defcustom org-descriptive-links t
1335 "Non-nil means Org will display descriptive links.
1336 E.g. [[http://orgmode.org][Org website]] will be displayed as
1337 \"Org Website\", hiding the link itself and just displaying its
1338 description. When set to `nil', Org will display the full links
1339 literally.
1341 You can interactively set the value of this variable by calling
1342 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1343 :group 'org-link
1344 :type 'boolean)
1346 (defcustom org-link-file-path-type 'adaptive
1347 "How the path name in file links should be stored.
1348 Valid values are:
1350 relative Relative to the current directory, i.e. the directory of the file
1351 into which the link is being inserted.
1352 absolute Absolute path, if possible with ~ for home directory.
1353 noabbrev Absolute path, no abbreviation of home directory.
1354 adaptive Use relative path for files in the current directory and sub-
1355 directories of it. For other files, use an absolute path."
1356 :group 'org-link
1357 :type '(choice
1358 (const relative)
1359 (const absolute)
1360 (const noabbrev)
1361 (const adaptive)))
1363 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1364 "Types of links that should be activated in Org-mode files.
1365 This is a list of symbols, each leading to the activation of a certain link
1366 type. In principle, it does not hurt to turn on most link types - there may
1367 be a small gain when turning off unused link types. The types are:
1369 bracket The recommended [[link][description]] or [[link]] links with hiding.
1370 angle Links in angular brackets that may contain whitespace like
1371 <bbdb:Carsten Dominik>.
1372 plain Plain links in normal text, no whitespace, like http://google.com.
1373 radio Text that is matched by a radio target, see manual for details.
1374 tag Tag settings in a headline (link to tag search).
1375 date Time stamps (link to calendar).
1376 footnote Footnote labels.
1378 Changing this variable requires a restart of Emacs to become effective."
1379 :group 'org-link
1380 :type '(set :greedy t
1381 (const :tag "Double bracket links" bracket)
1382 (const :tag "Angular bracket links" angle)
1383 (const :tag "Plain text links" plain)
1384 (const :tag "Radio target matches" radio)
1385 (const :tag "Tags" tag)
1386 (const :tag "Timestamps" date)
1387 (const :tag "Footnotes" footnote)))
1389 (defcustom org-make-link-description-function nil
1390 "Function to use to generate link descriptions from links.
1391 If nil the link location will be used. This function must take
1392 two parameters; the first is the link and the second the
1393 description `org-insert-link' has generated, and should return the
1394 description to use."
1395 :group 'org-link
1396 :type 'function)
1398 (defgroup org-link-store nil
1399 "Options concerning storing links in Org-mode."
1400 :tag "Org Store Link"
1401 :group 'org-link)
1403 (defcustom org-email-link-description-format "Email %c: %.30s"
1404 "Format of the description part of a link to an email or usenet message.
1405 The following %-escapes will be replaced by corresponding information:
1407 %F full \"From\" field
1408 %f name, taken from \"From\" field, address if no name
1409 %T full \"To\" field
1410 %t first name in \"To\" field, address if no name
1411 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1412 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1413 %s subject
1414 %d date
1415 %m message-id.
1417 You may use normal field width specification between the % and the letter.
1418 This is for example useful to limit the length of the subject.
1420 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1421 :group 'org-link-store
1422 :type 'string)
1424 (defcustom org-from-is-user-regexp
1425 (let (r1 r2)
1426 (when (and user-mail-address (not (string= user-mail-address "")))
1427 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1428 (when (and user-full-name (not (string= user-full-name "")))
1429 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1430 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1431 "Regexp matched against the \"From:\" header of an email or usenet message.
1432 It should match if the message is from the user him/herself."
1433 :group 'org-link-store
1434 :type 'regexp)
1436 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1437 "Non-nil means storing a link to an Org file will use entry IDs.
1439 Note that before this variable is even considered, org-id must be loaded,
1440 so please customize `org-modules' and turn it on.
1442 The variable can have the following values:
1444 t Create an ID if needed to make a link to the current entry.
1446 create-if-interactive
1447 If `org-store-link' is called directly (interactively, as a user
1448 command), do create an ID to support the link. But when doing the
1449 job for remember, only use the ID if it already exists. The
1450 purpose of this setting is to avoid proliferation of unwanted
1451 IDs, just because you happen to be in an Org file when you
1452 call `org-remember' that automatically and preemptively
1453 creates a link. If you do want to get an ID link in a remember
1454 template to an entry not having an ID, create it first by
1455 explicitly creating a link to it, using `C-c C-l' first.
1457 create-if-interactive-and-no-custom-id
1458 Like create-if-interactive, but do not create an ID if there is
1459 a CUSTOM_ID property defined in the entry. This is the default.
1461 use-existing
1462 Use existing ID, do not create one.
1464 nil Never use an ID to make a link, instead link using a text search for
1465 the headline text."
1466 :group 'org-link-store
1467 :type '(choice
1468 (const :tag "Create ID to make link" t)
1469 (const :tag "Create if storing link interactively"
1470 create-if-interactive)
1471 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1472 create-if-interactive-and-no-custom-id)
1473 (const :tag "Only use existing" use-existing)
1474 (const :tag "Do not use ID to create link" nil)))
1476 (defcustom org-context-in-file-links t
1477 "Non-nil means file links from `org-store-link' contain context.
1478 A search string will be added to the file name with :: as separator and
1479 used to find the context when the link is activated by the command
1480 `org-open-at-point'. When this option is t, the entire active region
1481 will be placed in the search string of the file link. If set to a
1482 positive integer, only the first n lines of context will be stored.
1484 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1485 negates this setting for the duration of the command."
1486 :group 'org-link-store
1487 :type '(choice boolean integer))
1489 (defcustom org-keep-stored-link-after-insertion nil
1490 "Non-nil means keep link in list for entire session.
1492 The command `org-store-link' adds a link pointing to the current
1493 location to an internal list. These links accumulate during a session.
1494 The command `org-insert-link' can be used to insert links into any
1495 Org-mode file (offering completion for all stored links). When this
1496 option is nil, every link which has been inserted once using \\[org-insert-link]
1497 will be removed from the list, to make completing the unused links
1498 more efficient."
1499 :group 'org-link-store
1500 :type 'boolean)
1502 (defgroup org-link-follow nil
1503 "Options concerning following links in Org-mode."
1504 :tag "Org Follow Link"
1505 :group 'org-link)
1507 (defcustom org-link-translation-function nil
1508 "Function to translate links with different syntax to Org syntax.
1509 This can be used to translate links created for example by the Planner
1510 or emacs-wiki packages to Org syntax.
1511 The function must accept two parameters, a TYPE containing the link
1512 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1513 which is everything after the link protocol. It should return a cons
1514 with possibly modified values of type and path.
1515 Org contains a function for this, so if you set this variable to
1516 `org-translate-link-from-planner', you should be able follow many
1517 links created by planner."
1518 :group 'org-link-follow
1519 :type 'function)
1521 (defcustom org-follow-link-hook nil
1522 "Hook that is run after a link has been followed."
1523 :group 'org-link-follow
1524 :type 'hook)
1526 (defcustom org-tab-follows-link nil
1527 "Non-nil means on links TAB will follow the link.
1528 Needs to be set before org.el is loaded.
1529 This really should not be used, it does not make sense, and the
1530 implementation is bad."
1531 :group 'org-link-follow
1532 :type 'boolean)
1534 (defcustom org-return-follows-link nil
1535 "Non-nil means on links RET will follow the link."
1536 :group 'org-link-follow
1537 :type 'boolean)
1539 (defcustom org-mouse-1-follows-link
1540 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1541 "Non-nil means mouse-1 on a link will follow the link.
1542 A longer mouse click will still set point. Does not work on XEmacs.
1543 Needs to be set before org.el is loaded."
1544 :group 'org-link-follow
1545 :type 'boolean)
1547 (defcustom org-mark-ring-length 4
1548 "Number of different positions to be recorded in the ring.
1549 Changing this requires a restart of Emacs to work correctly."
1550 :group 'org-link-follow
1551 :type 'integer)
1553 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1554 "Non-nil means internal links in Org files must exactly match a headline.
1555 When nil, the link search tries to match a phrase with all words
1556 in the search text."
1557 :group 'org-link-follow
1558 :version "24.1"
1559 :type '(choice
1560 (const :tag "Use fuzzy text search" nil)
1561 (const :tag "Match only exact headline" t)
1562 (const :tag "Match exact headline or query to create it"
1563 query-to-create)))
1565 (defcustom org-link-frame-setup
1566 '((vm . vm-visit-folder-other-frame)
1567 (vm-imap . vm-visit-imap-folder-other-frame)
1568 (gnus . org-gnus-no-new-news)
1569 (file . find-file-other-window)
1570 (wl . wl-other-frame))
1571 "Setup the frame configuration for following links.
1572 When following a link with Emacs, it may often be useful to display
1573 this link in another window or frame. This variable can be used to
1574 set this up for the different types of links.
1575 For VM, use any of
1576 `vm-visit-folder'
1577 `vm-visit-folder-other-window'
1578 `vm-visit-folder-other-frame'
1579 For Gnus, use any of
1580 `gnus'
1581 `gnus-other-frame'
1582 `org-gnus-no-new-news'
1583 For FILE, use any of
1584 `find-file'
1585 `find-file-other-window'
1586 `find-file-other-frame'
1587 For Wanderlust use any of
1588 `wl'
1589 `wl-other-frame'
1590 For the calendar, use the variable `calendar-setup'.
1591 For BBDB, it is currently only possible to display the matches in
1592 another window."
1593 :group 'org-link-follow
1594 :type '(list
1595 (cons (const vm)
1596 (choice
1597 (const vm-visit-folder)
1598 (const vm-visit-folder-other-window)
1599 (const vm-visit-folder-other-frame)))
1600 (cons (const gnus)
1601 (choice
1602 (const gnus)
1603 (const gnus-other-frame)
1604 (const org-gnus-no-new-news)))
1605 (cons (const file)
1606 (choice
1607 (const find-file)
1608 (const find-file-other-window)
1609 (const find-file-other-frame)))
1610 (cons (const wl)
1611 (choice
1612 (const wl)
1613 (const wl-other-frame)))))
1615 (defcustom org-display-internal-link-with-indirect-buffer nil
1616 "Non-nil means use indirect buffer to display infile links.
1617 Activating internal links (from one location in a file to another location
1618 in the same file) normally just jumps to the location. When the link is
1619 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1620 is displayed in
1621 another window. When this option is set, the other window actually displays
1622 an indirect buffer clone of the current buffer, to avoid any visibility
1623 changes to the current buffer."
1624 :group 'org-link-follow
1625 :type 'boolean)
1627 (defcustom org-open-non-existing-files nil
1628 "Non-nil means `org-open-file' will open non-existing files.
1629 When nil, an error will be generated.
1630 This variable applies only to external applications because they
1631 might choke on non-existing files. If the link is to a file that
1632 will be opened in Emacs, the variable is ignored."
1633 :group 'org-link-follow
1634 :type 'boolean)
1636 (defcustom org-open-directory-means-index-dot-org nil
1637 "Non-nil means a link to a directory really means to index.org.
1638 When nil, following a directory link will run dired or open a finder/explorer
1639 window on that directory."
1640 :group 'org-link-follow
1641 :type 'boolean)
1643 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1644 "Function and arguments to call for following mailto links.
1645 This is a list with the first element being a Lisp function, and the
1646 remaining elements being arguments to the function. In string arguments,
1647 %a will be replaced by the address, and %s will be replaced by the subject
1648 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1649 :group 'org-link-follow
1650 :type '(choice
1651 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1652 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1653 (const :tag "message-mail" (message-mail "%a" "%s"))
1654 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1656 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1657 "Non-nil means ask for confirmation before executing shell links.
1658 Shell links can be dangerous: just think about a link
1660 [[shell:rm -rf ~/*][Google Search]]
1662 This link would show up in your Org-mode document as \"Google Search\",
1663 but really it would remove your entire home directory.
1664 Therefore we advise against setting this variable to nil.
1665 Just change it to `y-or-n-p' if you want to confirm with a
1666 single keystroke rather than having to type \"yes\"."
1667 :group 'org-link-follow
1668 :type '(choice
1669 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1670 (const :tag "with y-or-n (faster)" y-or-n-p)
1671 (const :tag "no confirmation (dangerous)" nil)))
1672 (put 'org-confirm-shell-link-function
1673 'safe-local-variable
1674 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1676 (defcustom org-confirm-shell-link-not-regexp ""
1677 "A regexp to skip confirmation for shell links."
1678 :group 'org-link-follow
1679 :version "24.1"
1680 :type 'regexp)
1682 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1683 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1684 Elisp links can be dangerous: just think about a link
1686 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1688 This link would show up in your Org-mode document as \"Google Search\",
1689 but really it would remove your entire home directory.
1690 Therefore we advise against setting this variable to nil.
1691 Just change it to `y-or-n-p' if you want to confirm with a
1692 single keystroke rather than having to type \"yes\"."
1693 :group 'org-link-follow
1694 :type '(choice
1695 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1696 (const :tag "with y-or-n (faster)" y-or-n-p)
1697 (const :tag "no confirmation (dangerous)" nil)))
1698 (put 'org-confirm-shell-link-function
1699 'safe-local-variable
1700 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1702 (defcustom org-confirm-elisp-link-not-regexp ""
1703 "A regexp to skip confirmation for Elisp links."
1704 :group 'org-link-follow
1705 :version "24.1"
1706 :type 'regexp)
1708 (defconst org-file-apps-defaults-gnu
1709 '((remote . emacs)
1710 (system . mailcap)
1711 (t . mailcap))
1712 "Default file applications on a UNIX or GNU/Linux system.
1713 See `org-file-apps'.")
1715 (defconst org-file-apps-defaults-macosx
1716 '((remote . emacs)
1717 (t . "open %s")
1718 (system . "open %s")
1719 ("ps.gz" . "gv %s")
1720 ("eps.gz" . "gv %s")
1721 ("dvi" . "xdvi %s")
1722 ("fig" . "xfig %s"))
1723 "Default file applications on a MacOS X system.
1724 The system \"open\" is known as a default, but we use X11 applications
1725 for some files for which the OS does not have a good default.
1726 See `org-file-apps'.")
1728 (defconst org-file-apps-defaults-windowsnt
1729 (list
1730 '(remote . emacs)
1731 (cons t
1732 (list (if (featurep 'xemacs)
1733 'mswindows-shell-execute
1734 'w32-shell-execute)
1735 "open" 'file))
1736 (cons 'system
1737 (list (if (featurep 'xemacs)
1738 'mswindows-shell-execute
1739 'w32-shell-execute)
1740 "open" 'file)))
1741 "Default file applications on a Windows NT system.
1742 The system \"open\" is used for most files.
1743 See `org-file-apps'.")
1745 (defcustom org-file-apps
1747 (auto-mode . emacs)
1748 ("\\.mm\\'" . default)
1749 ("\\.x?html?\\'" . default)
1750 ("\\.pdf\\'" . default)
1752 "External applications for opening `file:path' items in a document.
1753 Org-mode uses system defaults for different file types, but
1754 you can use this variable to set the application for a given file
1755 extension. The entries in this list are cons cells where the car identifies
1756 files and the cdr the corresponding command. Possible values for the
1757 file identifier are
1758 \"string\" A string as a file identifier can be interpreted in different
1759 ways, depending on its contents:
1761 - Alphanumeric characters only:
1762 Match links with this file extension.
1763 Example: (\"pdf\" . \"evince %s\")
1764 to open PDFs with evince.
1766 - Regular expression: Match links where the
1767 filename matches the regexp. If you want to
1768 use groups here, use shy groups.
1770 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1771 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1772 to open *.html and *.xhtml with firefox.
1774 - Regular expression which contains (non-shy) groups:
1775 Match links where the whole link, including \"::\", and
1776 anything after that, matches the regexp.
1777 In a custom command string, %1, %2, etc. are replaced with
1778 the parts of the link that were matched by the groups.
1779 For backwards compatibility, if a command string is given
1780 that does not use any of the group matches, this case is
1781 handled identically to the second one (i.e. match against
1782 file name only).
1783 In a custom lisp form, you can access the group matches with
1784 (match-string n link).
1786 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1787 to open [[file:document.pdf::5]] with evince at page 5.
1789 `directory' Matches a directory
1790 `remote' Matches a remote file, accessible through tramp or efs.
1791 Remote files most likely should be visited through Emacs
1792 because external applications cannot handle such paths.
1793 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1794 so all files Emacs knows how to handle. Using this with
1795 command `emacs' will open most files in Emacs. Beware that this
1796 will also open html files inside Emacs, unless you add
1797 (\"html\" . default) to the list as well.
1798 t Default for files not matched by any of the other options.
1799 `system' The system command to open files, like `open' on Windows
1800 and Mac OS X, and mailcap under GNU/Linux. This is the command
1801 that will be selected if you call `C-c C-o' with a double
1802 \\[universal-argument] \\[universal-argument] prefix.
1804 Possible values for the command are:
1805 `emacs' The file will be visited by the current Emacs process.
1806 `default' Use the default application for this file type, which is the
1807 association for t in the list, most likely in the system-specific
1808 part.
1809 This can be used to overrule an unwanted setting in the
1810 system-specific variable.
1811 `system' Use the system command for opening files, like \"open\".
1812 This command is specified by the entry whose car is `system'.
1813 Most likely, the system-specific version of this variable
1814 does define this command, but you can overrule/replace it
1815 here.
1816 string A command to be executed by a shell; %s will be replaced
1817 by the path to the file.
1818 sexp A Lisp form which will be evaluated. The file path will
1819 be available in the Lisp variable `file'.
1820 For more examples, see the system specific constants
1821 `org-file-apps-defaults-macosx'
1822 `org-file-apps-defaults-windowsnt'
1823 `org-file-apps-defaults-gnu'."
1824 :group 'org-link-follow
1825 :type '(repeat
1826 (cons (choice :value ""
1827 (string :tag "Extension")
1828 (const :tag "System command to open files" system)
1829 (const :tag "Default for unrecognized files" t)
1830 (const :tag "Remote file" remote)
1831 (const :tag "Links to a directory" directory)
1832 (const :tag "Any files that have Emacs modes"
1833 auto-mode))
1834 (choice :value ""
1835 (const :tag "Visit with Emacs" emacs)
1836 (const :tag "Use default" default)
1837 (const :tag "Use the system command" system)
1838 (string :tag "Command")
1839 (sexp :tag "Lisp form")))))
1843 (defgroup org-refile nil
1844 "Options concerning refiling entries in Org-mode."
1845 :tag "Org Refile"
1846 :group 'org)
1848 (defcustom org-directory "~/org"
1849 "Directory with org files.
1850 This is just a default location to look for Org files. There is no need
1851 at all to put your files into this directory. It is only used in the
1852 following situations:
1854 1. When a remember template specifies a target file that is not an
1855 absolute path. The path will then be interpreted relative to
1856 `org-directory'
1857 2. When a remember note is filed away in an interactive way (when exiting the
1858 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1859 with `org-directory' as the default path."
1860 :group 'org-refile
1861 :group 'org-remember
1862 :type 'directory)
1864 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1865 "Default target for storing notes.
1866 Used as a fall back file for org-remember.el and org-capture.el, for
1867 templates that do not specify a target file."
1868 :group 'org-refile
1869 :group 'org-remember
1870 :type '(choice
1871 (const :tag "Default from remember-data-file" nil)
1872 file))
1874 (defcustom org-goto-interface 'outline
1875 "The default interface to be used for `org-goto'.
1876 Allowed values are:
1877 outline The interface shows an outline of the relevant file
1878 and the correct heading is found by moving through
1879 the outline or by searching with incremental search.
1880 outline-path-completion Headlines in the current buffer are offered via
1881 completion. This is the interface also used by
1882 the refile command."
1883 :group 'org-refile
1884 :type '(choice
1885 (const :tag "Outline" outline)
1886 (const :tag "Outline-path-completion" outline-path-completion)))
1888 (defcustom org-goto-max-level 5
1889 "Maximum target level when running `org-goto' with refile interface."
1890 :group 'org-refile
1891 :type 'integer)
1893 (defcustom org-reverse-note-order nil
1894 "Non-nil means store new notes at the beginning of a file or entry.
1895 When nil, new notes will be filed to the end of a file or entry.
1896 This can also be a list with cons cells of regular expressions that
1897 are matched against file names, and values."
1898 :group 'org-remember
1899 :group 'org-refile
1900 :type '(choice
1901 (const :tag "Reverse always" t)
1902 (const :tag "Reverse never" nil)
1903 (repeat :tag "By file name regexp"
1904 (cons regexp boolean))))
1906 (defcustom org-log-refile nil
1907 "Information to record when a task is refiled.
1909 Possible values are:
1911 nil Don't add anything
1912 time Add a time stamp to the task
1913 note Prompt for a note and add it with template `org-log-note-headings'
1915 This option can also be set with on a per-file-basis with
1917 #+STARTUP: nologrefile
1918 #+STARTUP: logrefile
1919 #+STARTUP: lognoterefile
1921 You can have local logging settings for a subtree by setting the LOGGING
1922 property to one or more of these keywords.
1924 When bulk-refiling from the agenda, the value `note' is forbidden and
1925 will temporarily be changed to `time'."
1926 :group 'org-refile
1927 :group 'org-progress
1928 :version "24.1"
1929 :type '(choice
1930 (const :tag "No logging" nil)
1931 (const :tag "Record timestamp" time)
1932 (const :tag "Record timestamp with note." note)))
1934 (defcustom org-refile-targets nil
1935 "Targets for refiling entries with \\[org-refile].
1936 This is a list of cons cells. Each cell contains:
1937 - a specification of the files to be considered, either a list of files,
1938 or a symbol whose function or variable value will be used to retrieve
1939 a file name or a list of file names. If you use `org-agenda-files' for
1940 that, all agenda files will be scanned for targets. Nil means consider
1941 headings in the current buffer.
1942 - A specification of how to find candidate refile targets. This may be
1943 any of:
1944 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1945 This tag has to be present in all target headlines, inheritance will
1946 not be considered.
1947 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1948 todo keyword.
1949 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1950 headlines that are refiling targets.
1951 - a cons cell (:level . N). Any headline of level N is considered a target.
1952 Note that, when `org-odd-levels-only' is set, level corresponds to
1953 order in hierarchy, not to the number of stars.
1954 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1955 Note that, when `org-odd-levels-only' is set, level corresponds to
1956 order in hierarchy, not to the number of stars.
1958 Each element of this list generates a set of possible targets.
1959 The union of these sets is presented (with completion) to
1960 the user by `org-refile'.
1962 You can set the variable `org-refile-target-verify-function' to a function
1963 to verify each headline found by the simple criteria above.
1965 When this variable is nil, all top-level headlines in the current buffer
1966 are used, equivalent to the value `((nil . (:level . 1))'."
1967 :group 'org-refile
1968 :type '(repeat
1969 (cons
1970 (choice :value org-agenda-files
1971 (const :tag "All agenda files" org-agenda-files)
1972 (const :tag "Current buffer" nil)
1973 (function) (variable) (file))
1974 (choice :tag "Identify target headline by"
1975 (cons :tag "Specific tag" (const :value :tag) (string))
1976 (cons :tag "TODO keyword" (const :value :todo) (string))
1977 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1978 (cons :tag "Level number" (const :value :level) (integer))
1979 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1981 (defcustom org-refile-target-verify-function nil
1982 "Function to verify if the headline at point should be a refile target.
1983 The function will be called without arguments, with point at the
1984 beginning of the headline. It should return t and leave point
1985 where it is if the headline is a valid target for refiling.
1987 If the target should not be selected, the function must return nil.
1988 In addition to this, it may move point to a place from where the search
1989 should be continued. For example, the function may decide that the entire
1990 subtree of the current entry should be excluded and move point to the end
1991 of the subtree."
1992 :group 'org-refile
1993 :type 'function)
1995 (defcustom org-refile-use-cache nil
1996 "Non-nil means cache refile targets to speed up the process.
1997 The cache for a particular file will be updated automatically when
1998 the buffer has been killed, or when any of the marker used for flagging
1999 refile targets no longer points at a live buffer.
2000 If you have added new entries to a buffer that might themselves be targets,
2001 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2002 find that easier, `C-u C-u C-u C-c C-w'."
2003 :group 'org-refile
2004 :version "24.1"
2005 :type 'boolean)
2007 (defcustom org-refile-use-outline-path nil
2008 "Non-nil means provide refile targets as paths.
2009 So a level 3 headline will be available as level1/level2/level3.
2011 When the value is `file', also include the file name (without directory)
2012 into the path. In this case, you can also stop the completion after
2013 the file name, to get entries inserted as top level in the file.
2015 When `full-file-path', include the full file path."
2016 :group 'org-refile
2017 :type '(choice
2018 (const :tag "Not" nil)
2019 (const :tag "Yes" t)
2020 (const :tag "Start with file name" file)
2021 (const :tag "Start with full file path" full-file-path)))
2023 (defcustom org-outline-path-complete-in-steps t
2024 "Non-nil means complete the outline path in hierarchical steps.
2025 When Org-mode uses the refile interface to select an outline path
2026 \(see variable `org-refile-use-outline-path'), the completion of
2027 the path can be done is a single go, or if can be done in steps down
2028 the headline hierarchy. Going in steps is probably the best if you
2029 do not use a special completion package like `ido' or `icicles'.
2030 However, when using these packages, going in one step can be very
2031 fast, while still showing the whole path to the entry."
2032 :group 'org-refile
2033 :type 'boolean)
2035 (defcustom org-refile-allow-creating-parent-nodes nil
2036 "Non-nil means allow to create new nodes as refile targets.
2037 New nodes are then created by adding \"/new node name\" to the completion
2038 of an existing node. When the value of this variable is `confirm',
2039 new node creation must be confirmed by the user (recommended)
2040 When nil, the completion must match an existing entry.
2042 Note that, if the new heading is not seen by the criteria
2043 listed in `org-refile-targets', multiple instances of the same
2044 heading would be created by trying again to file under the new
2045 heading."
2046 :group 'org-refile
2047 :type '(choice
2048 (const :tag "Never" nil)
2049 (const :tag "Always" t)
2050 (const :tag "Prompt for confirmation" confirm)))
2052 (defcustom org-refile-active-region-within-subtree nil
2053 "Non-nil means also refile active region within a subtree.
2055 By default `org-refile' doesn't allow refiling regions if they
2056 don't contain a set of subtrees, but it might be convenient to
2057 do so sometimes: in that case, the first line of the region is
2058 converted to a headline before refiling."
2059 :group 'org-refile
2060 :version "24.1"
2061 :type 'boolean)
2063 (defgroup org-todo nil
2064 "Options concerning TODO items in Org-mode."
2065 :tag "Org TODO"
2066 :group 'org)
2068 (defgroup org-progress nil
2069 "Options concerning Progress logging in Org-mode."
2070 :tag "Org Progress"
2071 :group 'org-time)
2073 (defvar org-todo-interpretation-widgets
2074 '((:tag "Sequence (cycling hits every state)" sequence)
2075 (:tag "Type (cycling directly to DONE)" type))
2076 "The available interpretation symbols for customizing `org-todo-keywords'.
2077 Interested libraries should add to this list.")
2079 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2080 "List of TODO entry keyword sequences and their interpretation.
2081 \\<org-mode-map>This is a list of sequences.
2083 Each sequence starts with a symbol, either `sequence' or `type',
2084 indicating if the keywords should be interpreted as a sequence of
2085 action steps, or as different types of TODO items. The first
2086 keywords are states requiring action - these states will select a headline
2087 for inclusion into the global TODO list Org-mode produces. If one of
2088 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2089 signify that no further action is necessary. If \"|\" is not found,
2090 the last keyword is treated as the only DONE state of the sequence.
2092 The command \\[org-todo] cycles an entry through these states, and one
2093 additional state where no keyword is present. For details about this
2094 cycling, see the manual.
2096 TODO keywords and interpretation can also be set on a per-file basis with
2097 the special #+SEQ_TODO and #+TYP_TODO lines.
2099 Each keyword can optionally specify a character for fast state selection
2100 \(in combination with the variable `org-use-fast-todo-selection')
2101 and specifiers for state change logging, using the same syntax
2102 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2103 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2104 indicates to record a time stamp each time this state is selected.
2106 Each keyword may also specify if a timestamp or a note should be
2107 recorded when entering or leaving the state, by adding additional
2108 characters in the parenthesis after the keyword. This looks like this:
2109 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2110 record only the time of the state change. With X and Y being either
2111 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2112 Y when leaving the state if and only if the *target* state does not
2113 define X. You may omit any of the fast-selection key or X or /Y,
2114 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2116 For backward compatibility, this variable may also be just a list
2117 of keywords - in this case the interpretation (sequence or type) will be
2118 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2119 :group 'org-todo
2120 :group 'org-keywords
2121 :type '(choice
2122 (repeat :tag "Old syntax, just keywords"
2123 (string :tag "Keyword"))
2124 (repeat :tag "New syntax"
2125 (cons
2126 (choice
2127 :tag "Interpretation"
2128 ;;Quick and dirty way to see
2129 ;;`org-todo-interpretations'. This takes the
2130 ;;place of item arguments
2131 :convert-widget
2132 (lambda (widget)
2133 (widget-put widget
2134 :args (mapcar
2135 #'(lambda (x)
2136 (widget-convert
2137 (cons 'const x)))
2138 org-todo-interpretation-widgets))
2139 widget))
2140 (repeat
2141 (string :tag "Keyword"))))))
2143 (defvar org-todo-keywords-1 nil
2144 "All TODO and DONE keywords active in a buffer.")
2145 (make-variable-buffer-local 'org-todo-keywords-1)
2146 (defvar org-todo-keywords-for-agenda nil)
2147 (defvar org-done-keywords-for-agenda nil)
2148 (defvar org-drawers-for-agenda nil)
2149 (defvar org-todo-keyword-alist-for-agenda nil)
2150 (defvar org-tag-alist-for-agenda nil)
2151 (defvar org-agenda-contributing-files nil)
2152 (defvar org-not-done-keywords nil)
2153 (make-variable-buffer-local 'org-not-done-keywords)
2154 (defvar org-done-keywords nil)
2155 (make-variable-buffer-local 'org-done-keywords)
2156 (defvar org-todo-heads nil)
2157 (make-variable-buffer-local 'org-todo-heads)
2158 (defvar org-todo-sets nil)
2159 (make-variable-buffer-local 'org-todo-sets)
2160 (defvar org-todo-log-states nil)
2161 (make-variable-buffer-local 'org-todo-log-states)
2162 (defvar org-todo-kwd-alist nil)
2163 (make-variable-buffer-local 'org-todo-kwd-alist)
2164 (defvar org-todo-key-alist nil)
2165 (make-variable-buffer-local 'org-todo-key-alist)
2166 (defvar org-todo-key-trigger nil)
2167 (make-variable-buffer-local 'org-todo-key-trigger)
2169 (defcustom org-todo-interpretation 'sequence
2170 "Controls how TODO keywords are interpreted.
2171 This variable is in principle obsolete and is only used for
2172 backward compatibility, if the interpretation of todo keywords is
2173 not given already in `org-todo-keywords'. See that variable for
2174 more information."
2175 :group 'org-todo
2176 :group 'org-keywords
2177 :type '(choice (const sequence)
2178 (const type)))
2180 (defcustom org-use-fast-todo-selection t
2181 "Non-nil means use the fast todo selection scheme with C-c C-t.
2182 This variable describes if and under what circumstances the cycling
2183 mechanism for TODO keywords will be replaced by a single-key, direct
2184 selection scheme.
2186 When nil, fast selection is never used.
2188 When the symbol `prefix', it will be used when `org-todo' is called with
2189 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2190 in an agenda buffer.
2192 When t, fast selection is used by default. In this case, the prefix
2193 argument forces cycling instead.
2195 In all cases, the special interface is only used if access keys have actually
2196 been assigned by the user, i.e. if keywords in the configuration are followed
2197 by a letter in parenthesis, like TODO(t)."
2198 :group 'org-todo
2199 :type '(choice
2200 (const :tag "Never" nil)
2201 (const :tag "By default" t)
2202 (const :tag "Only with C-u C-c C-t" prefix)))
2204 (defcustom org-provide-todo-statistics t
2205 "Non-nil means update todo statistics after insert and toggle.
2206 ALL-HEADLINES means update todo statistics by including headlines
2207 with no TODO keyword as well, counting them as not done.
2208 A list of TODO keywords means the same, but skip keywords that are
2209 not in this list.
2211 When this is set, todo statistics is updated in the parent of the
2212 current entry each time a todo state is changed."
2213 :group 'org-todo
2214 :type '(choice
2215 (const :tag "Yes, only for TODO entries" t)
2216 (const :tag "Yes, including all entries" 'all-headlines)
2217 (repeat :tag "Yes, for TODOs in this list"
2218 (string :tag "TODO keyword"))
2219 (other :tag "No TODO statistics" nil)))
2221 (defcustom org-hierarchical-todo-statistics t
2222 "Non-nil means TODO statistics covers just direct children.
2223 When nil, all entries in the subtree are considered.
2224 This has only an effect if `org-provide-todo-statistics' is set.
2225 To set this to nil for only a single subtree, use a COOKIE_DATA
2226 property and include the word \"recursive\" into the value."
2227 :group 'org-todo
2228 :type 'boolean)
2230 (defcustom org-after-todo-state-change-hook nil
2231 "Hook which is run after the state of a TODO item was changed.
2232 The new state (a string with a TODO keyword, or nil) is available in the
2233 Lisp variable `org-state'."
2234 :group 'org-todo
2235 :type 'hook)
2237 (defvar org-blocker-hook nil
2238 "Hook for functions that are allowed to block a state change.
2240 Each function gets as its single argument a property list, see
2241 `org-trigger-hook' for more information about this list.
2243 If any of the functions in this hook returns nil, the state change
2244 is blocked.")
2246 (defvar org-trigger-hook nil
2247 "Hook for functions that are triggered by a state change.
2249 Each function gets as its single argument a property list with at least
2250 the following elements:
2252 (:type type-of-change :position pos-at-entry-start
2253 :from old-state :to new-state)
2255 Depending on the type, more properties may be present.
2257 This mechanism is currently implemented for:
2259 TODO state changes
2260 ------------------
2261 :type todo-state-change
2262 :from previous state (keyword as a string), or nil, or a symbol
2263 'todo' or 'done', to indicate the general type of state.
2264 :to new state, like in :from")
2266 (defcustom org-enforce-todo-dependencies nil
2267 "Non-nil means undone TODO entries will block switching the parent to DONE.
2268 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2269 be blocked if any prior sibling is not yet done.
2270 Finally, if the parent is blocked because of ordered siblings of its own,
2271 the child will also be blocked."
2272 :set (lambda (var val)
2273 (set var val)
2274 (if val
2275 (add-hook 'org-blocker-hook
2276 'org-block-todo-from-children-or-siblings-or-parent)
2277 (remove-hook 'org-blocker-hook
2278 'org-block-todo-from-children-or-siblings-or-parent)))
2279 :group 'org-todo
2280 :type 'boolean)
2282 (defcustom org-enforce-todo-checkbox-dependencies nil
2283 "Non-nil means unchecked boxes will block switching the parent to DONE.
2284 When this is nil, checkboxes have no influence on switching TODO states.
2285 When non-nil, you first need to check off all check boxes before the TODO
2286 entry can be switched to DONE.
2287 This variable needs to be set before org.el is loaded, and you need to
2288 restart Emacs after a change to make the change effective. The only way
2289 to change is while Emacs is running is through the customize interface."
2290 :set (lambda (var val)
2291 (set var val)
2292 (if val
2293 (add-hook 'org-blocker-hook
2294 'org-block-todo-from-checkboxes)
2295 (remove-hook 'org-blocker-hook
2296 'org-block-todo-from-checkboxes)))
2297 :group 'org-todo
2298 :type 'boolean)
2300 (defcustom org-treat-insert-todo-heading-as-state-change nil
2301 "Non-nil means inserting a TODO heading is treated as state change.
2302 So when the command \\[org-insert-todo-heading] is used, state change
2303 logging will apply if appropriate. When nil, the new TODO item will
2304 be inserted directly, and no logging will take place."
2305 :group 'org-todo
2306 :type 'boolean)
2308 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2309 "Non-nil means switching TODO states with S-cursor counts as state change.
2310 This is the default behavior. However, setting this to nil allows a
2311 convenient way to select a TODO state and bypass any logging associated
2312 with that."
2313 :group 'org-todo
2314 :type 'boolean)
2316 (defcustom org-todo-state-tags-triggers nil
2317 "Tag changes that should be triggered by TODO state changes.
2318 This is a list. Each entry is
2320 (state-change (tag . flag) .......)
2322 State-change can be a string with a state, and empty string to indicate the
2323 state that has no TODO keyword, or it can be one of the symbols `todo'
2324 or `done', meaning any not-done or done state, respectively."
2325 :group 'org-todo
2326 :group 'org-tags
2327 :type '(repeat
2328 (cons (choice :tag "When changing to"
2329 (const :tag "Not-done state" todo)
2330 (const :tag "Done state" done)
2331 (string :tag "State"))
2332 (repeat
2333 (cons :tag "Tag action"
2334 (string :tag "Tag")
2335 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2337 (defcustom org-log-done nil
2338 "Information to record when a task moves to the DONE state.
2340 Possible values are:
2342 nil Don't add anything, just change the keyword
2343 time Add a time stamp to the task
2344 note Prompt for a note and add it with template `org-log-note-headings'
2346 This option can also be set with on a per-file-basis with
2348 #+STARTUP: nologdone
2349 #+STARTUP: logdone
2350 #+STARTUP: lognotedone
2352 You can have local logging settings for a subtree by setting the LOGGING
2353 property to one or more of these keywords."
2354 :group 'org-todo
2355 :group 'org-progress
2356 :type '(choice
2357 (const :tag "No logging" nil)
2358 (const :tag "Record CLOSED timestamp" time)
2359 (const :tag "Record CLOSED timestamp with note." note)))
2361 ;; Normalize old uses of org-log-done.
2362 (cond
2363 ((eq org-log-done t) (setq org-log-done 'time))
2364 ((and (listp org-log-done) (memq 'done org-log-done))
2365 (setq org-log-done 'note)))
2367 (defcustom org-log-reschedule nil
2368 "Information to record when the scheduling date of a tasks is modified.
2370 Possible values are:
2372 nil Don't add anything, just change the date
2373 time Add a time stamp to the task
2374 note Prompt for a note and add it with template `org-log-note-headings'
2376 This option can also be set with on a per-file-basis with
2378 #+STARTUP: nologreschedule
2379 #+STARTUP: logreschedule
2380 #+STARTUP: lognotereschedule"
2381 :group 'org-todo
2382 :group 'org-progress
2383 :type '(choice
2384 (const :tag "No logging" nil)
2385 (const :tag "Record timestamp" time)
2386 (const :tag "Record timestamp with note." note)))
2388 (defcustom org-log-redeadline nil
2389 "Information to record when the deadline date of a tasks is modified.
2391 Possible values are:
2393 nil Don't add anything, just change the date
2394 time Add a time stamp to the task
2395 note Prompt for a note and add it with template `org-log-note-headings'
2397 This option can also be set with on a per-file-basis with
2399 #+STARTUP: nologredeadline
2400 #+STARTUP: logredeadline
2401 #+STARTUP: lognoteredeadline
2403 You can have local logging settings for a subtree by setting the LOGGING
2404 property to one or more of these keywords."
2405 :group 'org-todo
2406 :group 'org-progress
2407 :type '(choice
2408 (const :tag "No logging" nil)
2409 (const :tag "Record timestamp" time)
2410 (const :tag "Record timestamp with note." note)))
2412 (defcustom org-log-note-clock-out nil
2413 "Non-nil means record a note when clocking out of an item.
2414 This can also be configured on a per-file basis by adding one of
2415 the following lines anywhere in the buffer:
2417 #+STARTUP: lognoteclock-out
2418 #+STARTUP: nolognoteclock-out"
2419 :group 'org-todo
2420 :group 'org-progress
2421 :type 'boolean)
2423 (defcustom org-log-done-with-time t
2424 "Non-nil means the CLOSED time stamp will contain date and time.
2425 When nil, only the date will be recorded."
2426 :group 'org-progress
2427 :type 'boolean)
2429 (defcustom org-log-note-headings
2430 '((done . "CLOSING NOTE %t")
2431 (state . "State %-12s from %-12S %t")
2432 (note . "Note taken on %t")
2433 (reschedule . "Rescheduled from %S on %t")
2434 (delschedule . "Not scheduled, was %S on %t")
2435 (redeadline . "New deadline from %S on %t")
2436 (deldeadline . "Removed deadline, was %S on %t")
2437 (refile . "Refiled on %t")
2438 (clock-out . ""))
2439 "Headings for notes added to entries.
2440 The value is an alist, with the car being a symbol indicating the note
2441 context, and the cdr is the heading to be used. The heading may also be the
2442 empty string.
2443 %t in the heading will be replaced by a time stamp.
2444 %T will be an active time stamp instead the default inactive one
2445 %d will be replaced by a short-format time stamp.
2446 %D will be replaced by an active short-format time stamp.
2447 %s will be replaced by the new TODO state, in double quotes.
2448 %S will be replaced by the old TODO state, in double quotes.
2449 %u will be replaced by the user name.
2450 %U will be replaced by the full user name.
2452 In fact, it is not a good idea to change the `state' entry, because
2453 agenda log mode depends on the format of these entries."
2454 :group 'org-todo
2455 :group 'org-progress
2456 :type '(list :greedy t
2457 (cons (const :tag "Heading when closing an item" done) string)
2458 (cons (const :tag
2459 "Heading when changing todo state (todo sequence only)"
2460 state) string)
2461 (cons (const :tag "Heading when just taking a note" note) string)
2462 (cons (const :tag "Heading when clocking out" clock-out) string)
2463 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2464 (cons (const :tag "Heading when rescheduling" reschedule) string)
2465 (cons (const :tag "Heading when changing deadline" redeadline) string)
2466 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2467 (cons (const :tag "Heading when refiling" refile) string)))
2469 (unless (assq 'note org-log-note-headings)
2470 (push '(note . "%t") org-log-note-headings))
2472 (defcustom org-log-into-drawer nil
2473 "Non-nil means insert state change notes and time stamps into a drawer.
2474 When nil, state changes notes will be inserted after the headline and
2475 any scheduling and clock lines, but not inside a drawer.
2477 The value of this variable should be the name of the drawer to use.
2478 LOGBOOK is proposed as the default drawer for this purpose, you can
2479 also set this to a string to define the drawer of your choice.
2481 A value of t is also allowed, representing \"LOGBOOK\".
2483 If this variable is set, `org-log-state-notes-insert-after-drawers'
2484 will be ignored.
2486 You can set the property LOG_INTO_DRAWER to overrule this setting for
2487 a subtree."
2488 :group 'org-todo
2489 :group 'org-progress
2490 :type '(choice
2491 (const :tag "Not into a drawer" nil)
2492 (const :tag "LOGBOOK" t)
2493 (string :tag "Other")))
2495 (if (fboundp 'defvaralias)
2496 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2498 (defun org-log-into-drawer ()
2499 "Return the value of `org-log-into-drawer', but let properties overrule.
2500 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2501 used instead of the default value."
2502 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2503 (cond
2504 ((or (not p) (equal p "nil")) org-log-into-drawer)
2505 ((equal p "t") "LOGBOOK")
2506 (t p))))
2508 (defcustom org-log-state-notes-insert-after-drawers nil
2509 "Non-nil means insert state change notes after any drawers in entry.
2510 Only the drawers that *immediately* follow the headline and the
2511 deadline/scheduled line are skipped.
2512 When nil, insert notes right after the heading and perhaps the line
2513 with deadline/scheduling if present.
2515 This variable will have no effect if `org-log-into-drawer' is
2516 set."
2517 :group 'org-todo
2518 :group 'org-progress
2519 :type 'boolean)
2521 (defcustom org-log-states-order-reversed t
2522 "Non-nil means the latest state note will be directly after heading.
2523 When nil, the state change notes will be ordered according to time."
2524 :group 'org-todo
2525 :group 'org-progress
2526 :type 'boolean)
2528 (defcustom org-todo-repeat-to-state nil
2529 "The TODO state to which a repeater should return the repeating task.
2530 By default this is the first task in a TODO sequence, or the previous state
2531 in a TODO_TYP set. But you can specify another task here.
2532 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2533 :group 'org-todo
2534 :version "24.1"
2535 :type '(choice (const :tag "Head of sequence" nil)
2536 (string :tag "Specific state")))
2538 (defcustom org-log-repeat 'time
2539 "Non-nil means record moving through the DONE state when triggering repeat.
2540 An auto-repeating task is immediately switched back to TODO when
2541 marked DONE. If you are not logging state changes (by adding \"@\"
2542 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2543 record a closing note, there will be no record of the task moving
2544 through DONE. This variable forces taking a note anyway.
2546 nil Don't force a record
2547 time Record a time stamp
2548 note Record a note
2550 This option can also be set with on a per-file-basis with
2552 #+STARTUP: logrepeat
2553 #+STARTUP: lognoterepeat
2554 #+STARTUP: nologrepeat
2556 You can have local logging settings for a subtree by setting the LOGGING
2557 property to one or more of these keywords."
2558 :group 'org-todo
2559 :group 'org-progress
2560 :type '(choice
2561 (const :tag "Don't force a record" nil)
2562 (const :tag "Force recording the DONE state" time)
2563 (const :tag "Force recording a note with the DONE state" note)))
2566 (defgroup org-priorities nil
2567 "Priorities in Org-mode."
2568 :tag "Org Priorities"
2569 :group 'org-todo)
2571 (defcustom org-enable-priority-commands t
2572 "Non-nil means priority commands are active.
2573 When nil, these commands will be disabled, so that you never accidentally
2574 set a priority."
2575 :group 'org-priorities
2576 :type 'boolean)
2578 (defcustom org-highest-priority ?A
2579 "The highest priority of TODO items. A character like ?A, ?B etc.
2580 Must have a smaller ASCII number than `org-lowest-priority'."
2581 :group 'org-priorities
2582 :type 'character)
2584 (defcustom org-lowest-priority ?C
2585 "The lowest priority of TODO items. A character like ?A, ?B etc.
2586 Must have a larger ASCII number than `org-highest-priority'."
2587 :group 'org-priorities
2588 :type 'character)
2590 (defcustom org-default-priority ?B
2591 "The default priority of TODO items.
2592 This is the priority an item gets if no explicit priority is given.
2593 When starting to cycle on an empty priority the first step in the cycle
2594 depends on `org-priority-start-cycle-with-default'. The resulting first
2595 step priority must not exceed the range from `org-highest-priority' to
2596 `org-lowest-priority' which means that `org-default-priority' has to be
2597 in this range exclusive or inclusive the range boundaries. Else the
2598 first step refuses to set the default and the second will fall back
2599 to (depending on the command used) the highest or lowest priority."
2600 :group 'org-priorities
2601 :type 'character)
2603 (defcustom org-priority-start-cycle-with-default t
2604 "Non-nil means start with default priority when starting to cycle.
2605 When this is nil, the first step in the cycle will be (depending on the
2606 command used) one higher or lower than the default priority.
2607 See also `org-default-priority'."
2608 :group 'org-priorities
2609 :type 'boolean)
2611 (defcustom org-get-priority-function nil
2612 "Function to extract the priority from a string.
2613 The string is normally the headline. If this is nil Org computes the
2614 priority from the priority cookie like [#A] in the headline. It returns
2615 an integer, increasing by 1000 for each priority level.
2616 The user can set a different function here, which should take a string
2617 as an argument and return the numeric priority."
2618 :group 'org-priorities
2619 :version "24.1"
2620 :type 'function)
2622 (defgroup org-time nil
2623 "Options concerning time stamps and deadlines in Org-mode."
2624 :tag "Org Time"
2625 :group 'org)
2627 (defcustom org-insert-labeled-timestamps-at-point nil
2628 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2629 When nil, these labeled time stamps are forces into the second line of an
2630 entry, just after the headline. When scheduling from the global TODO list,
2631 the time stamp will always be forced into the second line."
2632 :group 'org-time
2633 :type 'boolean)
2635 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2636 "Formats for `format-time-string' which are used for time stamps.
2637 It is not recommended to change this constant.")
2639 (defcustom org-time-stamp-rounding-minutes '(0 5)
2640 "Number of minutes to round time stamps to.
2641 These are two values, the first applies when first creating a time stamp.
2642 The second applies when changing it with the commands `S-up' and `S-down'.
2643 When changing the time stamp, this means that it will change in steps
2644 of N minutes, as given by the second value.
2646 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2647 numbers should be factors of 60, so for example 5, 10, 15.
2649 When this is larger than 1, you can still force an exact time stamp by using
2650 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2651 and by using a prefix arg to `S-up/down' to specify the exact number
2652 of minutes to shift."
2653 :group 'org-time
2654 :get #'(lambda (var) ; Make sure both elements are there
2655 (if (integerp (default-value var))
2656 (list (default-value var) 5)
2657 (default-value var)))
2658 :type '(list
2659 (integer :tag "when inserting times")
2660 (integer :tag "when modifying times")))
2662 ;; Normalize old customizations of this variable.
2663 (when (integerp org-time-stamp-rounding-minutes)
2664 (setq org-time-stamp-rounding-minutes
2665 (list org-time-stamp-rounding-minutes
2666 org-time-stamp-rounding-minutes)))
2668 (defcustom org-display-custom-times nil
2669 "Non-nil means overlay custom formats over all time stamps.
2670 The formats are defined through the variable `org-time-stamp-custom-formats'.
2671 To turn this on on a per-file basis, insert anywhere in the file:
2672 #+STARTUP: customtime"
2673 :group 'org-time
2674 :set 'set-default
2675 :type 'sexp)
2676 (make-variable-buffer-local 'org-display-custom-times)
2678 (defcustom org-time-stamp-custom-formats
2679 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2680 "Custom formats for time stamps. See `format-time-string' for the syntax.
2681 These are overlaid over the default ISO format if the variable
2682 `org-display-custom-times' is set. Time like %H:%M should be at the
2683 end of the second format. The custom formats are also honored by export
2684 commands, if custom time display is turned on at the time of export."
2685 :group 'org-time
2686 :type 'sexp)
2688 (defun org-time-stamp-format (&optional long inactive)
2689 "Get the right format for a time string."
2690 (let ((f (if long (cdr org-time-stamp-formats)
2691 (car org-time-stamp-formats))))
2692 (if inactive
2693 (concat "[" (substring f 1 -1) "]")
2694 f)))
2696 (defcustom org-time-clocksum-format "%d:%02d"
2697 "The format string used when creating CLOCKSUM lines.
2698 This is also used when org-mode generates a time duration."
2699 :group 'org-time
2700 :type 'string)
2702 (defcustom org-time-clocksum-use-fractional nil
2703 "If non-nil, \\[org-clock-display] uses fractional times.
2704 org-mode generates a time duration."
2705 :group 'org-time
2706 :type 'boolean)
2708 (defcustom org-time-clocksum-fractional-format "%.2f"
2709 "The format string used when creating CLOCKSUM lines, or when
2710 org-mode generates a time duration."
2711 :group 'org-time
2712 :type 'string)
2714 (defcustom org-deadline-warning-days 14
2715 "No. of days before expiration during which a deadline becomes active.
2716 This variable governs the display in sparse trees and in the agenda.
2717 When 0 or negative, it means use this number (the absolute value of it)
2718 even if a deadline has a different individual lead time specified.
2720 Custom commands can set this variable in the options section."
2721 :group 'org-time
2722 :group 'org-agenda-daily/weekly
2723 :type 'integer)
2725 (defcustom org-read-date-prefer-future t
2726 "Non-nil means assume future for incomplete date input from user.
2727 This affects the following situations:
2728 1. The user gives a month but not a year.
2729 For example, if it is April and you enter \"feb 2\", this will be read
2730 as Feb 2, *next* year. \"May 5\", however, will be this year.
2731 2. The user gives a day, but no month.
2732 For example, if today is the 15th, and you enter \"3\", Org-mode will
2733 read this as the third of *next* month. However, if you enter \"17\",
2734 it will be considered as *this* month.
2736 If you set this variable to the symbol `time', then also the following
2737 will work:
2739 3. If the user gives a time, but no day. If the time is before now,
2740 to will be interpreted as tomorrow.
2742 Currently none of this works for ISO week specifications.
2744 When this option is nil, the current day, month and year will always be
2745 used as defaults.
2747 See also `org-agenda-jump-prefer-future'."
2748 :group 'org-time
2749 :type '(choice
2750 (const :tag "Never" nil)
2751 (const :tag "Check month and day" t)
2752 (const :tag "Check month, day, and time" time)))
2754 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2755 "Should the agenda jump command prefer the future for incomplete dates?
2756 The default is to do the same as configured in `org-read-date-prefer-future'.
2757 But you can also set a deviating value here.
2758 This may t or nil, or the symbol `org-read-date-prefer-future'."
2759 :group 'org-agenda
2760 :group 'org-time
2761 :version "24.1"
2762 :type '(choice
2763 (const :tag "Use org-read-date-prefer-future"
2764 org-read-date-prefer-future)
2765 (const :tag "Never" nil)
2766 (const :tag "Always" t)))
2768 (defcustom org-read-date-force-compatible-dates t
2769 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2771 Depending on the system Emacs is running on, certain dates cannot
2772 be represented with the type used internally to represent time.
2773 Dates between 1970-1-1 and 2038-1-1 can always be represented
2774 correctly. Some systems allow for earlier dates, some for later,
2775 some for both. One way to find out it to insert any date into an
2776 Org buffer, putting the cursor on the year and hitting S-up and
2777 S-down to test the range.
2779 When this variable is set to t, the date/time prompt will not let
2780 you specify dates outside the 1970-2037 range, so it is certain that
2781 these dates will work in whatever version of Emacs you are
2782 running, and also that you can move a file from one Emacs implementation
2783 to another. WHenever Org is forcing the year for you, it will display
2784 a message and beep.
2786 When this variable is nil, Org will check if the date is
2787 representable in the specific Emacs implementation you are using.
2788 If not, it will force a year, usually the current year, and beep
2789 to remind you. Currently this setting is not recommended because
2790 the likelihood that you will open your Org files in an Emacs that
2791 has limited date range is not negligible.
2793 A workaround for this problem is to use diary sexp dates for time
2794 stamps outside of this range."
2795 :group 'org-time
2796 :version "24.1"
2797 :type 'boolean)
2799 (defcustom org-read-date-display-live t
2800 "Non-nil means display current interpretation of date prompt live.
2801 This display will be in an overlay, in the minibuffer."
2802 :group 'org-time
2803 :type 'boolean)
2805 (defcustom org-read-date-popup-calendar t
2806 "Non-nil means pop up a calendar when prompting for a date.
2807 In the calendar, the date can be selected with mouse-1. However, the
2808 minibuffer will also be active, and you can simply enter the date as well.
2809 When nil, only the minibuffer will be available."
2810 :group 'org-time
2811 :type 'boolean)
2812 (if (fboundp 'defvaralias)
2813 (defvaralias 'org-popup-calendar-for-date-prompt
2814 'org-read-date-popup-calendar))
2816 (defcustom org-read-date-minibuffer-setup-hook nil
2817 "Hook to be used to set up keys for the date/time interface.
2818 Add key definitions to `minibuffer-local-map', which will be a temporary
2819 copy."
2820 :group 'org-time
2821 :type 'hook)
2823 (defcustom org-extend-today-until 0
2824 "The hour when your day really ends. Must be an integer.
2825 This has influence for the following applications:
2826 - When switching the agenda to \"today\". It it is still earlier than
2827 the time given here, the day recognized as TODAY is actually yesterday.
2828 - When a date is read from the user and it is still before the time given
2829 here, the current date and time will be assumed to be yesterday, 23:59.
2830 Also, timestamps inserted in remember templates follow this rule.
2832 IMPORTANT: This is a feature whose implementation is and likely will
2833 remain incomplete. Really, it is only here because past midnight seems to
2834 be the favorite working time of John Wiegley :-)"
2835 :group 'org-time
2836 :type 'integer)
2838 (defcustom org-use-effective-time nil
2839 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2840 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2841 \"effective time\" of any timestamps between midnight and 8am will be
2842 23:59 of the previous day."
2843 :group 'org-time
2844 :version "24.1"
2845 :type 'boolean)
2847 (defcustom org-edit-timestamp-down-means-later nil
2848 "Non-nil means S-down will increase the time in a time stamp.
2849 When nil, S-up will increase."
2850 :group 'org-time
2851 :type 'boolean)
2853 (defcustom org-calendar-follow-timestamp-change t
2854 "Non-nil means make the calendar window follow timestamp changes.
2855 When a timestamp is modified and the calendar window is visible, it will be
2856 moved to the new date."
2857 :group 'org-time
2858 :type 'boolean)
2860 (defgroup org-tags nil
2861 "Options concerning tags in Org-mode."
2862 :tag "Org Tags"
2863 :group 'org)
2865 (defcustom org-tag-alist nil
2866 "List of tags allowed in Org-mode files.
2867 When this list is nil, Org-mode will base TAG input on what is already in the
2868 buffer.
2869 The value of this variable is an alist, the car of each entry must be a
2870 keyword as a string, the cdr may be a character that is used to select
2871 that tag through the fast-tag-selection interface.
2872 See the manual for details."
2873 :group 'org-tags
2874 :type '(repeat
2875 (choice
2876 (cons (string :tag "Tag name")
2877 (character :tag "Access char"))
2878 (list :tag "Start radio group"
2879 (const :startgroup)
2880 (option (string :tag "Group description")))
2881 (list :tag "End radio group"
2882 (const :endgroup)
2883 (option (string :tag "Group description")))
2884 (const :tag "New line" (:newline)))))
2886 (defcustom org-tag-persistent-alist nil
2887 "List of tags that will always appear in all Org-mode files.
2888 This is in addition to any in buffer settings or customizations
2889 of `org-tag-alist'.
2890 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2891 The value of this variable is an alist, the car of each entry must be a
2892 keyword as a string, the cdr may be a character that is used to select
2893 that tag through the fast-tag-selection interface.
2894 See the manual for details.
2895 To disable these tags on a per-file basis, insert anywhere in the file:
2896 #+STARTUP: noptag"
2897 :group 'org-tags
2898 :type '(repeat
2899 (choice
2900 (cons (string :tag "Tag name")
2901 (character :tag "Access char"))
2902 (const :tag "Start radio group" (:startgroup))
2903 (const :tag "End radio group" (:endgroup))
2904 (const :tag "New line" (:newline)))))
2906 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2907 "If non-nil, always offer completion for all tags of all agenda files.
2908 Instead of customizing this variable directly, you might want to
2909 set it locally for capture buffers, because there no list of
2910 tags in that file can be created dynamically (there are none).
2912 (add-hook 'org-capture-mode-hook
2913 (lambda ()
2914 (set (make-local-variable
2915 'org-complete-tags-always-offer-all-agenda-tags)
2916 t)))"
2917 :group 'org-tags
2918 :version "24.1"
2919 :type 'boolean)
2921 (defvar org-file-tags nil
2922 "List of tags that can be inherited by all entries in the file.
2923 The tags will be inherited if the variable `org-use-tag-inheritance'
2924 says they should be.
2925 This variable is populated from #+FILETAGS lines.")
2927 (defcustom org-use-fast-tag-selection 'auto
2928 "Non-nil means use fast tag selection scheme.
2929 This is a special interface to select and deselect tags with single keys.
2930 When nil, fast selection is never used.
2931 When the symbol `auto', fast selection is used if and only if selection
2932 characters for tags have been configured, either through the variable
2933 `org-tag-alist' or through a #+TAGS line in the buffer.
2934 When t, fast selection is always used and selection keys are assigned
2935 automatically if necessary."
2936 :group 'org-tags
2937 :type '(choice
2938 (const :tag "Always" t)
2939 (const :tag "Never" nil)
2940 (const :tag "When selection characters are configured" 'auto)))
2942 (defcustom org-fast-tag-selection-single-key nil
2943 "Non-nil means fast tag selection exits after first change.
2944 When nil, you have to press RET to exit it.
2945 During fast tag selection, you can toggle this flag with `C-c'.
2946 This variable can also have the value `expert'. In this case, the window
2947 displaying the tags menu is not even shown, until you press C-c again."
2948 :group 'org-tags
2949 :type '(choice
2950 (const :tag "No" nil)
2951 (const :tag "Yes" t)
2952 (const :tag "Expert" expert)))
2954 (defvar org-fast-tag-selection-include-todo nil
2955 "Non-nil means fast tags selection interface will also offer TODO states.
2956 This is an undocumented feature, you should not rely on it.")
2958 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2959 "The column to which tags should be indented in a headline.
2960 If this number is positive, it specifies the column. If it is negative,
2961 it means that the tags should be flushright to that column. For example,
2962 -80 works well for a normal 80 character screen.
2963 When 0, place tags directly after headline text, with only one space in
2964 between."
2965 :group 'org-tags
2966 :type 'integer)
2968 (defcustom org-auto-align-tags t
2969 "Non-nil keeps tags aligned when modifying headlines.
2970 Some operations (i.e. demoting) change the length of a headline and
2971 therefore shift the tags around. With this option turned on, after
2972 each such operation the tags are again aligned to `org-tags-column'."
2973 :group 'org-tags
2974 :type 'boolean)
2976 (defcustom org-use-tag-inheritance t
2977 "Non-nil means tags in levels apply also for sublevels.
2978 When nil, only the tags directly given in a specific line apply there.
2979 This may also be a list of tags that should be inherited, or a regexp that
2980 matches tags that should be inherited. Additional control is possible
2981 with the variable `org-tags-exclude-from-inheritance' which gives an
2982 explicit list of tags to be excluded from inheritance., even if the value of
2983 `org-use-tag-inheritance' would select it for inheritance.
2985 If this option is t, a match early-on in a tree can lead to a large
2986 number of matches in the subtree when constructing the agenda or creating
2987 a sparse tree. If you only want to see the first match in a tree during
2988 a search, check out the variable `org-tags-match-list-sublevels'."
2989 :group 'org-tags
2990 :type '(choice
2991 (const :tag "Not" nil)
2992 (const :tag "Always" t)
2993 (repeat :tag "Specific tags" (string :tag "Tag"))
2994 (regexp :tag "Tags matched by regexp")))
2996 (defcustom org-tags-exclude-from-inheritance nil
2997 "List of tags that should never be inherited.
2998 This is a way to exclude a few tags from inheritance. For way to do
2999 the opposite, to actively allow inheritance for selected tags,
3000 see the variable `org-use-tag-inheritance'."
3001 :group 'org-tags
3002 :type '(repeat (string :tag "Tag")))
3004 (defun org-tag-inherit-p (tag)
3005 "Check if TAG is one that should be inherited."
3006 (cond
3007 ((member tag org-tags-exclude-from-inheritance) nil)
3008 ((eq org-use-tag-inheritance t) t)
3009 ((not org-use-tag-inheritance) nil)
3010 ((stringp org-use-tag-inheritance)
3011 (string-match org-use-tag-inheritance tag))
3012 ((listp org-use-tag-inheritance)
3013 (member tag org-use-tag-inheritance))
3014 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3016 (defcustom org-tags-match-list-sublevels t
3017 "Non-nil means list also sublevels of headlines matching a search.
3018 This variable applies to tags/property searches, and also to stuck
3019 projects because this search is based on a tags match as well.
3021 When set to the symbol `indented', sublevels are indented with
3022 leading dots.
3024 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3025 the sublevels of a headline matching a tag search often also match
3026 the same search. Listing all of them can create very long lists.
3027 Setting this variable to nil causes subtrees of a match to be skipped.
3029 This variable is semi-obsolete and probably should always be true. It
3030 is better to limit inheritance to certain tags using the variables
3031 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3032 :group 'org-tags
3033 :type '(choice
3034 (const :tag "No, don't list them" nil)
3035 (const :tag "Yes, do list them" t)
3036 (const :tag "List them, indented with leading dots" indented)))
3038 (defcustom org-tags-sort-function nil
3039 "When set, tags are sorted using this function as a comparator."
3040 :group 'org-tags
3041 :type '(choice
3042 (const :tag "No sorting" nil)
3043 (const :tag "Alphabetical" string<)
3044 (const :tag "Reverse alphabetical" string>)
3045 (function :tag "Custom function" nil)))
3047 (defvar org-tags-history nil
3048 "History of minibuffer reads for tags.")
3049 (defvar org-last-tags-completion-table nil
3050 "The last used completion table for tags.")
3051 (defvar org-after-tags-change-hook nil
3052 "Hook that is run after the tags in a line have changed.")
3054 (defgroup org-properties nil
3055 "Options concerning properties in Org-mode."
3056 :tag "Org Properties"
3057 :group 'org)
3059 (defcustom org-property-format "%-10s %s"
3060 "How property key/value pairs should be formatted by `indent-line'.
3061 When `indent-line' hits a property definition, it will format the line
3062 according to this format, mainly to make sure that the values are
3063 lined-up with respect to each other."
3064 :group 'org-properties
3065 :type 'string)
3067 (defcustom org-properties-postprocess-alist nil
3068 "Alist of properties and functions to adjust inserted values.
3069 Elements of this alist must be of the form
3071 ([string] [function])
3073 where [string] must be a property name and [function] must be a
3074 lambda expression: this lambda expression must take one argument,
3075 the value to adjust, and return the new value as a string.
3077 For example, this element will allow the property \"Remaining\"
3078 to be updated wrt the relation between the \"Effort\" property
3079 and the clock summary:
3081 ((\"Remaining\" (lambda(value)
3082 (let ((clocksum (org-clock-sum-current-item))
3083 (effort (org-duration-string-to-minutes
3084 (org-entry-get (point) \"Effort\"))))
3085 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3086 :group 'org-properties
3087 :version "24.1"
3088 :type '(alist :key-type (string :tag "Property")
3089 :value-type (function :tag "Function")))
3091 (defcustom org-use-property-inheritance nil
3092 "Non-nil means properties apply also for sublevels.
3094 This setting is chiefly used during property searches. Turning it on can
3095 cause significant overhead when doing a search, which is why it is not
3096 on by default.
3098 When nil, only the properties directly given in the current entry count.
3099 When t, every property is inherited. The value may also be a list of
3100 properties that should have inheritance, or a regular expression matching
3101 properties that should be inherited.
3103 However, note that some special properties use inheritance under special
3104 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3105 and the properties ending in \"_ALL\" when they are used as descriptor
3106 for valid values of a property.
3108 Note for programmers:
3109 When querying an entry with `org-entry-get', you can control if inheritance
3110 should be used. By default, `org-entry-get' looks only at the local
3111 properties. You can request inheritance by setting the inherit argument
3112 to t (to force inheritance) or to `selective' (to respect the setting
3113 in this variable)."
3114 :group 'org-properties
3115 :type '(choice
3116 (const :tag "Not" nil)
3117 (const :tag "Always" t)
3118 (repeat :tag "Specific properties" (string :tag "Property"))
3119 (regexp :tag "Properties matched by regexp")))
3121 (defun org-property-inherit-p (property)
3122 "Check if PROPERTY is one that should be inherited."
3123 (cond
3124 ((eq org-use-property-inheritance t) t)
3125 ((not org-use-property-inheritance) nil)
3126 ((stringp org-use-property-inheritance)
3127 (string-match org-use-property-inheritance property))
3128 ((listp org-use-property-inheritance)
3129 (member property org-use-property-inheritance))
3130 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3132 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3133 "The default column format, if no other format has been defined.
3134 This variable can be set on the per-file basis by inserting a line
3136 #+COLUMNS: %25ITEM ....."
3137 :group 'org-properties
3138 :type 'string)
3140 (defcustom org-columns-ellipses ".."
3141 "The ellipses to be used when a field in column view is truncated.
3142 When this is the empty string, as many characters as possible are shown,
3143 but then there will be no visual indication that the field has been truncated.
3144 When this is a string of length N, the last N characters of a truncated
3145 field are replaced by this string. If the column is narrower than the
3146 ellipses string, only part of the ellipses string will be shown."
3147 :group 'org-properties
3148 :type 'string)
3150 (defcustom org-columns-modify-value-for-display-function nil
3151 "Function that modifies values for display in column view.
3152 For example, it can be used to cut out a certain part from a time stamp.
3153 The function must take 2 arguments:
3155 column-title The title of the column (*not* the property name)
3156 value The value that should be modified.
3158 The function should return the value that should be displayed,
3159 or nil if the normal value should be used."
3160 :group 'org-properties
3161 :type 'function)
3163 (defcustom org-effort-property "Effort"
3164 "The property that is being used to keep track of effort estimates.
3165 Effort estimates given in this property need to have the format H:MM."
3166 :group 'org-properties
3167 :group 'org-progress
3168 :type '(string :tag "Property"))
3170 (defconst org-global-properties-fixed
3171 '(("VISIBILITY_ALL" . "folded children content all")
3172 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3173 "List of property/value pairs that can be inherited by any entry.
3175 These are fixed values, for the preset properties. The user variable
3176 that can be used to add to this list is `org-global-properties'.
3178 The entries in this list are cons cells where the car is a property
3179 name and cdr is a string with the value. If the value represents
3180 multiple items like an \"_ALL\" property, separate the items by
3181 spaces.")
3183 (defcustom org-global-properties nil
3184 "List of property/value pairs that can be inherited by any entry.
3186 This list will be combined with the constant `org-global-properties-fixed'.
3188 The entries in this list are cons cells where the car is a property
3189 name and cdr is a string with the value.
3191 You can set buffer-local values for the same purpose in the variable
3192 `org-file-properties' this by adding lines like
3194 #+PROPERTY: NAME VALUE"
3195 :group 'org-properties
3196 :type '(repeat
3197 (cons (string :tag "Property")
3198 (string :tag "Value"))))
3200 (defvar org-file-properties nil
3201 "List of property/value pairs that can be inherited by any entry.
3202 Valid for the current buffer.
3203 This variable is populated from #+PROPERTY lines.")
3204 (make-variable-buffer-local 'org-file-properties)
3206 (defgroup org-agenda nil
3207 "Options concerning agenda views in Org-mode."
3208 :tag "Org Agenda"
3209 :group 'org)
3211 (defvar org-category nil
3212 "Variable used by org files to set a category for agenda display.
3213 Such files should use a file variable to set it, for example
3215 # -*- mode: org; org-category: \"ELisp\"
3217 or contain a special line
3219 #+CATEGORY: ELisp
3221 If the file does not specify a category, then file's base name
3222 is used instead.")
3223 (make-variable-buffer-local 'org-category)
3224 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3226 (defcustom org-agenda-files nil
3227 "The files to be used for agenda display.
3228 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3229 \\[org-remove-file]. You can also use customize to edit the list.
3231 If an entry is a directory, all files in that directory that are matched by
3232 `org-agenda-file-regexp' will be part of the file list.
3234 If the value of the variable is not a list but a single file name, then
3235 the list of agenda files is actually stored and maintained in that file, one
3236 agenda file per line. In this file paths can be given relative to
3237 `org-directory'. Tilde expansion and environment variable substitution
3238 are also made."
3239 :group 'org-agenda
3240 :type '(choice
3241 (repeat :tag "List of files and directories" file)
3242 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3244 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3245 "Regular expression to match files for `org-agenda-files'.
3246 If any element in the list in that variable contains a directory instead
3247 of a normal file, all files in that directory that are matched by this
3248 regular expression will be included."
3249 :group 'org-agenda
3250 :type 'regexp)
3252 (defcustom org-agenda-text-search-extra-files nil
3253 "List of extra files to be searched by text search commands.
3254 These files will be search in addition to the agenda files by the
3255 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3256 Note that these files will only be searched for text search commands,
3257 not for the other agenda views like todo lists, tag searches or the weekly
3258 agenda. This variable is intended to list notes and possibly archive files
3259 that should also be searched by these two commands.
3260 In fact, if the first element in the list is the symbol `agenda-archives',
3261 than all archive files of all agenda files will be added to the search
3262 scope."
3263 :group 'org-agenda
3264 :type '(set :greedy t
3265 (const :tag "Agenda Archives" agenda-archives)
3266 (repeat :inline t (file))))
3268 (if (fboundp 'defvaralias)
3269 (defvaralias 'org-agenda-multi-occur-extra-files
3270 'org-agenda-text-search-extra-files))
3272 (defcustom org-agenda-skip-unavailable-files nil
3273 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3274 A nil value means to remove them, after a query, from the list."
3275 :group 'org-agenda
3276 :type 'boolean)
3278 (defcustom org-calendar-to-agenda-key [?c]
3279 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3280 The command `org-calendar-goto-agenda' will be bound to this key. The
3281 default is the character `c' because then `c' can be used to switch back and
3282 forth between agenda and calendar."
3283 :group 'org-agenda
3284 :type 'sexp)
3286 (defcustom org-calendar-agenda-action-key [?k]
3287 "The key to be installed in `calendar-mode-map' for agenda-action.
3288 The command `org-agenda-action' will be bound to this key. The
3289 default is the character `k' because we use the same key in the agenda."
3290 :group 'org-agenda
3291 :type 'sexp)
3293 (defcustom org-calendar-insert-diary-entry-key [?i]
3294 "The key to be installed in `calendar-mode-map' for adding diary entries.
3295 This option is irrelevant until `org-agenda-diary-file' has been configured
3296 to point to an Org-mode file. When that is the case, the command
3297 `org-agenda-diary-entry' will be bound to the key given here, by default
3298 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3299 if you want to continue doing this, you need to change this to a different
3300 key."
3301 :group 'org-agenda
3302 :type 'sexp)
3304 (defcustom org-agenda-diary-file 'diary-file
3305 "File to which to add new entries with the `i' key in agenda and calendar.
3306 When this is the symbol `diary-file', the functionality in the Emacs
3307 calendar will be used to add entries to the `diary-file'. But when this
3308 points to a file, `org-agenda-diary-entry' will be used instead."
3309 :group 'org-agenda
3310 :type '(choice
3311 (const :tag "The standard Emacs diary file" diary-file)
3312 (file :tag "Special Org file diary entries")))
3314 (eval-after-load "calendar"
3315 '(progn
3316 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3317 'org-calendar-goto-agenda)
3318 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3319 'org-agenda-action)
3320 (add-hook 'calendar-mode-hook
3321 (lambda ()
3322 (unless (eq org-agenda-diary-file 'diary-file)
3323 (define-key calendar-mode-map
3324 org-calendar-insert-diary-entry-key
3325 'org-agenda-diary-entry))))))
3327 (defgroup org-latex nil
3328 "Options for embedding LaTeX code into Org-mode."
3329 :tag "Org LaTeX"
3330 :group 'org)
3332 (defcustom org-format-latex-options
3333 '(:foreground default :background default :scale 1.0
3334 :html-foreground "Black" :html-background "Transparent"
3335 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3336 "Options for creating images from LaTeX fragments.
3337 This is a property list with the following properties:
3338 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3339 `default' means use the foreground of the default face.
3340 :background the background color, or \"Transparent\".
3341 `default' means use the background of the default face.
3342 :scale a scaling factor for the size of the images, to get more pixels
3343 :html-foreground, :html-background, :html-scale
3344 the same numbers for HTML export.
3345 :matchers a list indicating which matchers should be used to
3346 find LaTeX fragments. Valid members of this list are:
3347 \"begin\" find environments
3348 \"$1\" find single characters surrounded by $.$
3349 \"$\" find math expressions surrounded by $...$
3350 \"$$\" find math expressions surrounded by $$....$$
3351 \"\\(\" find math expressions surrounded by \\(...\\)
3352 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3353 :group 'org-latex
3354 :type 'plist)
3356 (defcustom org-format-latex-signal-error t
3357 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3358 When nil, just push out a message."
3359 :group 'org-latex
3360 :version "24.1"
3361 :type 'boolean)
3363 (defcustom org-latex-to-mathml-jar-file nil
3364 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3365 Use this to specify additional executable file say a jar file.
3367 When using MathToWeb as the converter, specify the full-path to
3368 your mathtoweb.jar file."
3369 :group 'org-latex
3370 :version "24.1"
3371 :type '(choice
3372 (const :tag "None" nil)
3373 (file :tag "JAR file" :must-match t)))
3375 (defcustom org-latex-to-mathml-convert-command nil
3376 "Command to convert LaTeX fragments to MathML.
3377 Replace format-specifiers in the command as noted below and use
3378 `shell-command' to convert LaTeX to MathML.
3379 %j: Executable file in fully expanded form as specified by
3380 `org-latex-to-mathml-jar-file'.
3381 %I: Input LaTeX file in fully expanded form
3382 %o: Output MathML file
3383 This command is used by `org-create-math-formula'.
3385 When using MathToWeb as the converter, set this to
3386 \"java -jar %j -unicode -force -df %o %I\"."
3387 :group 'org-latex
3388 :version "24.1"
3389 :type '(choice
3390 (const :tag "None" nil)
3391 (string :tag "\nShell command")))
3393 (defcustom org-latex-create-formula-image-program 'dvipng
3394 "Program to convert LaTeX fragments with.
3396 dvipng Process the LaTeX fragments to dvi file, then convert
3397 dvi files to png files using dvipng.
3398 This will also include processing of non-math environments.
3399 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3400 to convert pdf files to png files"
3401 :group 'org-latex
3402 :version "24.1"
3403 :type '(choice
3404 (const :tag "dvipng" dvipng)
3405 (const :tag "imagemagick" imagemagick)))
3407 (defun org-format-latex-mathml-available-p ()
3408 "Return t if `org-latex-to-mathml-convert-command' is usable."
3409 (save-match-data
3410 (when (and (boundp 'org-latex-to-mathml-convert-command)
3411 org-latex-to-mathml-convert-command)
3412 (let ((executable (car (split-string
3413 org-latex-to-mathml-convert-command))))
3414 (when (executable-find executable)
3415 (if (string-match
3416 "%j" org-latex-to-mathml-convert-command)
3417 (file-readable-p org-latex-to-mathml-jar-file)
3418 t))))))
3420 (defcustom org-format-latex-header "\\documentclass{article}
3421 \\usepackage[usenames]{color}
3422 \\usepackage{amsmath}
3423 \\usepackage[mathscr]{eucal}
3424 \\pagestyle{empty} % do not remove
3425 \[PACKAGES]
3426 \[DEFAULT-PACKAGES]
3427 % The settings below are copied from fullpage.sty
3428 \\setlength{\\textwidth}{\\paperwidth}
3429 \\addtolength{\\textwidth}{-3cm}
3430 \\setlength{\\oddsidemargin}{1.5cm}
3431 \\addtolength{\\oddsidemargin}{-2.54cm}
3432 \\setlength{\\evensidemargin}{\\oddsidemargin}
3433 \\setlength{\\textheight}{\\paperheight}
3434 \\addtolength{\\textheight}{-\\headheight}
3435 \\addtolength{\\textheight}{-\\headsep}
3436 \\addtolength{\\textheight}{-\\footskip}
3437 \\addtolength{\\textheight}{-3cm}
3438 \\setlength{\\topmargin}{1.5cm}
3439 \\addtolength{\\topmargin}{-2.54cm}"
3440 "The document header used for processing LaTeX fragments.
3441 It is imperative that this header make sure that no page number
3442 appears on the page. The package defined in the variables
3443 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3444 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3445 will be appended."
3446 :group 'org-latex
3447 :type 'string)
3449 (defvar org-format-latex-header-extra nil)
3451 (defun org-set-packages-alist (var val)
3452 "Set the packages alist and make sure it has 3 elements per entry."
3453 (set var (mapcar (lambda (x)
3454 (if (and (consp x) (= (length x) 2))
3455 (list (car x) (nth 1 x) t)
3457 val)))
3459 (defun org-get-packages-alist (var)
3461 "Get the packages alist and make sure it has 3 elements per entry."
3462 (mapcar (lambda (x)
3463 (if (and (consp x) (= (length x) 2))
3464 (list (car x) (nth 1 x) t)
3466 (default-value var)))
3468 ;; The following variables are defined here because is it also used
3469 ;; when formatting latex fragments. Originally it was part of the
3470 ;; LaTeX exporter, which is why the name includes "export".
3471 (defcustom org-export-latex-default-packages-alist
3472 '(("AUTO" "inputenc" t)
3473 ("T1" "fontenc" t)
3474 ("" "fixltx2e" nil)
3475 ("" "graphicx" t)
3476 ("" "longtable" nil)
3477 ("" "float" nil)
3478 ("" "wrapfig" nil)
3479 ("" "soul" t)
3480 ("" "textcomp" t)
3481 ("" "marvosym" t)
3482 ("" "wasysym" t)
3483 ("" "latexsym" t)
3484 ("" "amssymb" t)
3485 ("" "hyperref" nil)
3486 "\\tolerance=1000"
3488 "Alist of default packages to be inserted in the header.
3489 Change this only if one of the packages here causes an incompatibility
3490 with another package you are using.
3491 The packages in this list are needed by one part or another of Org-mode
3492 to function properly.
3494 - inputenc, fontenc: for basic font and character selection
3495 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3496 for interpreting the entities in `org-entities'. You can skip some of these
3497 packages if you don't use any of the symbols in it.
3498 - graphicx: for including images
3499 - float, wrapfig: for figure placement
3500 - longtable: for long tables
3501 - hyperref: for cross references
3503 Therefore you should not modify this variable unless you know what you
3504 are doing. The one reason to change it anyway is that you might be loading
3505 some other package that conflicts with one of the default packages.
3506 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3507 If SNIPPET-FLAG is t, the package also needs to be included when
3508 compiling LaTeX snippets into images for inclusion into HTML."
3509 :group 'org-export-latex
3510 :set 'org-set-packages-alist
3511 :get 'org-get-packages-alist
3512 :version "24.1"
3513 :type '(repeat
3514 (choice
3515 (list :tag "options/package pair"
3516 (string :tag "options")
3517 (string :tag "package")
3518 (boolean :tag "Snippet"))
3519 (string :tag "A line of LaTeX"))))
3521 (defcustom org-export-latex-packages-alist nil
3522 "Alist of packages to be inserted in every LaTeX header.
3523 These will be inserted after `org-export-latex-default-packages-alist'.
3524 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3525 SNIPPET-FLAG, when t, indicates that this package is also needed when
3526 turning LaTeX snippets into images for inclusion into HTML.
3527 Make sure that you only list packages here which:
3528 - you want in every file
3529 - do not conflict with the default packages in
3530 `org-export-latex-default-packages-alist'
3531 - do not conflict with the setup in `org-format-latex-header'."
3532 :group 'org-export-latex
3533 :set 'org-set-packages-alist
3534 :get 'org-get-packages-alist
3535 :type '(repeat
3536 (choice
3537 (list :tag "options/package pair"
3538 (string :tag "options")
3539 (string :tag "package")
3540 (boolean :tag "Snippet"))
3541 (string :tag "A line of LaTeX"))))
3544 (defgroup org-appearance nil
3545 "Settings for Org-mode appearance."
3546 :tag "Org Appearance"
3547 :group 'org)
3549 (defcustom org-level-color-stars-only nil
3550 "Non-nil means fontify only the stars in each headline.
3551 When nil, the entire headline is fontified.
3552 Changing it requires restart of `font-lock-mode' to become effective
3553 also in regions already fontified."
3554 :group 'org-appearance
3555 :type 'boolean)
3557 (defcustom org-hide-leading-stars nil
3558 "Non-nil means hide the first N-1 stars in a headline.
3559 This works by using the face `org-hide' for these stars. This
3560 face is white for a light background, and black for a dark
3561 background. You may have to customize the face `org-hide' to
3562 make this work.
3563 Changing it requires restart of `font-lock-mode' to become effective
3564 also in regions already fontified.
3565 You may also set this on a per-file basis by adding one of the following
3566 lines to the buffer:
3568 #+STARTUP: hidestars
3569 #+STARTUP: showstars"
3570 :group 'org-appearance
3571 :type 'boolean)
3573 (defcustom org-hidden-keywords nil
3574 "List of symbols corresponding to keywords to be hidden the org buffer.
3575 For example, a value '(title) for this list will make the document's title
3576 appear in the buffer without the initial #+TITLE: keyword."
3577 :group 'org-appearance
3578 :version "24.1"
3579 :type '(set (const :tag "#+AUTHOR" author)
3580 (const :tag "#+DATE" date)
3581 (const :tag "#+EMAIL" email)
3582 (const :tag "#+TITLE" title)))
3584 (defcustom org-fontify-done-headline nil
3585 "Non-nil means change the face of a headline if it is marked DONE.
3586 Normally, only the TODO/DONE keyword indicates the state of a headline.
3587 When this is non-nil, the headline after the keyword is set to the
3588 `org-headline-done' as an additional indication."
3589 :group 'org-appearance
3590 :type 'boolean)
3592 (defcustom org-fontify-emphasized-text t
3593 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3594 Changing this variable requires a restart of Emacs to take effect."
3595 :group 'org-appearance
3596 :type 'boolean)
3598 (defcustom org-fontify-whole-heading-line nil
3599 "Non-nil means fontify the whole line for headings.
3600 This is useful when setting a background color for the
3601 org-level-* faces."
3602 :group 'org-appearance
3603 :type 'boolean)
3605 (defcustom org-highlight-latex-fragments-and-specials nil
3606 "Non-nil means fontify what is treated specially by the exporters."
3607 :group 'org-appearance
3608 :type 'boolean)
3610 (defcustom org-hide-emphasis-markers nil
3611 "Non-nil mean font-lock should hide the emphasis marker characters."
3612 :group 'org-appearance
3613 :type 'boolean)
3615 (defcustom org-pretty-entities nil
3616 "Non-nil means show entities as UTF8 characters.
3617 When nil, the \\name form remains in the buffer."
3618 :group 'org-appearance
3619 :version "24.1"
3620 :type 'boolean)
3622 (defcustom org-pretty-entities-include-sub-superscripts t
3623 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3624 :group 'org-appearance
3625 :version "24.1"
3626 :type 'boolean)
3628 (defvar org-emph-re nil
3629 "Regular expression for matching emphasis.
3630 After a match, the match groups contain these elements:
3631 0 The match of the full regular expression, including the characters
3632 before and after the proper match
3633 1 The character before the proper match, or empty at beginning of line
3634 2 The proper match, including the leading and trailing markers
3635 3 The leading marker like * or /, indicating the type of highlighting
3636 4 The text between the emphasis markers, not including the markers
3637 5 The character after the match, empty at the end of a line")
3638 (defvar org-verbatim-re nil
3639 "Regular expression for matching verbatim text.")
3640 (defvar org-emphasis-regexp-components) ; defined just below
3641 (defvar org-emphasis-alist) ; defined just below
3642 (defun org-set-emph-re (var val)
3643 "Set variable and compute the emphasis regular expression."
3644 (set var val)
3645 (when (and (boundp 'org-emphasis-alist)
3646 (boundp 'org-emphasis-regexp-components)
3647 org-emphasis-alist org-emphasis-regexp-components)
3648 (let* ((e org-emphasis-regexp-components)
3649 (pre (car e))
3650 (post (nth 1 e))
3651 (border (nth 2 e))
3652 (body (nth 3 e))
3653 (nl (nth 4 e))
3654 (body1 (concat body "*?"))
3655 (markers (mapconcat 'car org-emphasis-alist ""))
3656 (vmarkers (mapconcat
3657 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3658 org-emphasis-alist "")))
3659 ;; make sure special characters appear at the right position in the class
3660 (if (string-match "\\^" markers)
3661 (setq markers (concat (replace-match "" t t markers) "^")))
3662 (if (string-match "-" markers)
3663 (setq markers (concat (replace-match "" t t markers) "-")))
3664 (if (string-match "\\^" vmarkers)
3665 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3666 (if (string-match "-" vmarkers)
3667 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3668 (if (> nl 0)
3669 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3670 (int-to-string nl) "\\}")))
3671 ;; Make the regexp
3672 (setq org-emph-re
3673 (concat "\\([" pre "]\\|^\\)"
3674 "\\("
3675 "\\([" markers "]\\)"
3676 "\\("
3677 "[^" border "]\\|"
3678 "[^" border "]"
3679 body1
3680 "[^" border "]"
3681 "\\)"
3682 "\\3\\)"
3683 "\\([" post "]\\|$\\)"))
3684 (setq org-verbatim-re
3685 (concat "\\([" pre "]\\|^\\)"
3686 "\\("
3687 "\\([" vmarkers "]\\)"
3688 "\\("
3689 "[^" border "]\\|"
3690 "[^" border "]"
3691 body1
3692 "[^" border "]"
3693 "\\)"
3694 "\\3\\)"
3695 "\\([" post "]\\|$\\)")))))
3697 (defcustom org-emphasis-regexp-components
3698 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3699 "Components used to build the regular expression for emphasis.
3700 This is a list with five entries. Terminology: In an emphasis string
3701 like \" *strong word* \", we call the initial space PREMATCH, the final
3702 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3703 and \"trong wor\" is the body. The different components in this variable
3704 specify what is allowed/forbidden in each part:
3706 pre Chars allowed as prematch. Beginning of line will be allowed too.
3707 post Chars allowed as postmatch. End of line will be allowed too.
3708 border The chars *forbidden* as border characters.
3709 body-regexp A regexp like \".\" to match a body character. Don't use
3710 non-shy groups here, and don't allow newline here.
3711 newline The maximum number of newlines allowed in an emphasis exp.
3713 Use customize to modify this, or restart Emacs after changing it."
3714 :group 'org-appearance
3715 :set 'org-set-emph-re
3716 :type '(list
3717 (sexp :tag "Allowed chars in pre ")
3718 (sexp :tag "Allowed chars in post ")
3719 (sexp :tag "Forbidden chars in border ")
3720 (sexp :tag "Regexp for body ")
3721 (integer :tag "number of newlines allowed")
3722 (option (boolean :tag "Please ignore this button"))))
3724 (defcustom org-emphasis-alist
3725 `(("*" bold "<b>" "</b>")
3726 ("/" italic "<i>" "</i>")
3727 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3728 ("=" org-code "<code>" "</code>" verbatim)
3729 ("~" org-verbatim "<code>" "</code>" verbatim)
3730 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3731 "<del>" "</del>")
3733 "Special syntax for emphasized text.
3734 Text starting and ending with a special character will be emphasized, for
3735 example *bold*, _underlined_ and /italic/. This variable sets the marker
3736 characters, the face to be used by font-lock for highlighting in Org-mode
3737 Emacs buffers, and the HTML tags to be used for this.
3738 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3739 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3740 Use customize to modify this, or restart Emacs after changing it."
3741 :group 'org-appearance
3742 :set 'org-set-emph-re
3743 :type '(repeat
3744 (list
3745 (string :tag "Marker character")
3746 (choice
3747 (face :tag "Font-lock-face")
3748 (plist :tag "Face property list"))
3749 (string :tag "HTML start tag")
3750 (string :tag "HTML end tag")
3751 (option (const verbatim)))))
3753 (defvar org-protecting-blocks
3754 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3755 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3756 This is needed for font-lock setup.")
3758 ;;; Miscellaneous options
3760 (defgroup org-completion nil
3761 "Completion in Org-mode."
3762 :tag "Org Completion"
3763 :group 'org)
3765 (defcustom org-completion-use-ido nil
3766 "Non-nil means use ido completion wherever possible.
3767 Note that `ido-mode' must be active for this variable to be relevant.
3768 If you decide to turn this variable on, you might well want to turn off
3769 `org-outline-path-complete-in-steps'.
3770 See also `org-completion-use-iswitchb'."
3771 :group 'org-completion
3772 :type 'boolean)
3774 (defcustom org-completion-use-iswitchb nil
3775 "Non-nil means use iswitchb completion wherever possible.
3776 Note that `iswitchb-mode' must be active for this variable to be relevant.
3777 If you decide to turn this variable on, you might well want to turn off
3778 `org-outline-path-complete-in-steps'.
3779 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3780 :group 'org-completion
3781 :type 'boolean)
3783 (defcustom org-completion-fallback-command 'hippie-expand
3784 "The expansion command called by \\[pcomplete] in normal context.
3785 Normal means, no org-mode-specific context."
3786 :group 'org-completion
3787 :type 'function)
3789 ;;; Functions and variables from their packages
3790 ;; Declared here to avoid compiler warnings
3792 ;; XEmacs only
3793 (defvar outline-mode-menu-heading)
3794 (defvar outline-mode-menu-show)
3795 (defvar outline-mode-menu-hide)
3796 (defvar zmacs-regions) ; XEmacs regions
3798 ;; Emacs only
3799 (defvar mark-active)
3801 ;; Various packages
3802 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3803 (declare-function calendar-forward-day "cal-move" (arg))
3804 (declare-function calendar-goto-date "cal-move" (date))
3805 (declare-function calendar-goto-today "cal-move" ())
3806 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3807 (defvar calc-embedded-close-formula)
3808 (defvar calc-embedded-open-formula)
3809 (declare-function cdlatex-tab "ext:cdlatex" ())
3810 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3811 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3812 (defvar font-lock-unfontify-region-function)
3813 (declare-function iswitchb-read-buffer "iswitchb"
3814 (prompt &optional default require-match start matches-set))
3815 (defvar iswitchb-temp-buflist)
3816 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3817 (defvar org-agenda-tags-todo-honor-ignore-options)
3818 (declare-function org-agenda-skip "org-agenda" ())
3819 (declare-function
3820 org-agenda-format-item "org-agenda"
3821 (extra txt &optional category tags dotime noprefix remove-re habitp))
3822 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3823 (declare-function org-agenda-change-all-lines "org-agenda"
3824 (newhead hdmarker &optional fixface just-this))
3825 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3826 (declare-function org-agenda-maybe-redo "org-agenda" ())
3827 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3828 (beg end))
3829 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3830 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3831 "org-agenda" (&optional end))
3832 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3833 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3834 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3835 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3836 (declare-function org-indent-mode "org-indent" (&optional arg))
3837 (declare-function parse-time-string "parse-time" (string))
3838 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3839 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3840 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3841 (defvar remember-data-file)
3842 (defvar texmathp-why)
3843 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3844 (declare-function table--at-cell-p "table" (position &optional object at-column))
3846 (defvar w3m-current-url)
3847 (defvar w3m-current-title)
3849 (defvar org-latex-regexps)
3851 ;;; Autoload and prepare some org modules
3853 ;; Some table stuff that needs to be defined here, because it is used
3854 ;; by the functions setting up org-mode or checking for table context.
3856 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3857 "Detect an org-type or table-type table.")
3858 (defconst org-table-line-regexp "^[ \t]*|"
3859 "Detect an org-type table line.")
3860 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3861 "Detect an org-type table line.")
3862 (defconst org-table-hline-regexp "^[ \t]*|-"
3863 "Detect an org-type table hline.")
3864 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3865 "Detect a table-type table hline.")
3866 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3867 "Detect the first line outside a table when searching from within it.
3868 This works for both table types.")
3870 ;; Autoload the functions in org-table.el that are needed by functions here.
3872 (eval-and-compile
3873 (org-autoload "org-table"
3874 '(org-table-align org-table-begin org-table-blank-field
3875 org-table-convert org-table-convert-region org-table-copy-down
3876 org-table-copy-region org-table-create
3877 org-table-create-or-convert-from-region
3878 org-table-create-with-table.el org-table-current-dline
3879 org-table-cut-region org-table-delete-column org-table-edit-field
3880 org-table-edit-formulas org-table-end org-table-eval-formula
3881 org-table-export org-table-field-info
3882 org-table-get-stored-formulas org-table-goto-column
3883 org-table-hline-and-move org-table-import org-table-insert-column
3884 org-table-insert-hline org-table-insert-row org-table-iterate
3885 org-table-justify-field-maybe org-table-kill-row
3886 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3887 org-table-move-column org-table-move-column-left
3888 org-table-move-column-right org-table-move-row
3889 org-table-move-row-down org-table-move-row-up
3890 org-table-next-field org-table-next-row org-table-paste-rectangle
3891 org-table-previous-field org-table-recalculate
3892 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3893 org-table-toggle-coordinate-overlays
3894 org-table-toggle-formula-debugger org-table-wrap-region
3895 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3896 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3897 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3899 (defun org-at-table-p (&optional table-type)
3900 "Return t if the cursor is inside an org-type table.
3901 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3902 (if org-enable-table-editor
3903 (save-excursion
3904 (beginning-of-line 1)
3905 (looking-at (if table-type org-table-any-line-regexp
3906 org-table-line-regexp)))
3907 nil))
3908 (defsubst org-table-p () (org-at-table-p))
3910 (defun org-at-table.el-p ()
3911 "Return t if and only if we are at a table.el table."
3912 (and (org-at-table-p 'any)
3913 (save-excursion
3914 (goto-char (org-table-begin 'any))
3915 (looking-at org-table1-hline-regexp))))
3916 (defun org-table-recognize-table.el ()
3917 "If there is a table.el table nearby, recognize it and move into it."
3918 (if org-table-tab-recognizes-table.el
3919 (if (org-at-table.el-p)
3920 (progn
3921 (beginning-of-line 1)
3922 (if (looking-at org-table-dataline-regexp)
3924 (if (looking-at org-table1-hline-regexp)
3925 (progn
3926 (beginning-of-line 2)
3927 (if (looking-at org-table-any-border-regexp)
3928 (beginning-of-line -1)))))
3929 (if (re-search-forward "|" (org-table-end t) t)
3930 (progn
3931 (require 'table)
3932 (if (table--at-cell-p (point))
3934 (message "recognizing table.el table...")
3935 (table-recognize-table)
3936 (message "recognizing table.el table...done")))
3937 (error "This should not happen"))
3939 nil)
3940 nil))
3942 (defun org-at-table-hline-p ()
3943 "Return t if the cursor is inside a hline in a table."
3944 (if org-enable-table-editor
3945 (save-excursion
3946 (beginning-of-line 1)
3947 (looking-at org-table-hline-regexp))
3948 nil))
3950 (defvar org-table-clean-did-remove-column nil)
3952 (defun org-table-map-tables (function &optional quietly)
3953 "Apply FUNCTION to the start of all tables in the buffer."
3954 (save-excursion
3955 (save-restriction
3956 (widen)
3957 (goto-char (point-min))
3958 (while (re-search-forward org-table-any-line-regexp nil t)
3959 (unless quietly
3960 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3961 (beginning-of-line 1)
3962 (when (and (looking-at org-table-line-regexp)
3963 ;; Exclude tables in src/example/verbatim/clocktable blocks
3964 (not (org-in-block-p '("src" "example"))))
3965 (save-excursion (funcall function))
3966 (or (looking-at org-table-line-regexp)
3967 (forward-char 1)))
3968 (re-search-forward org-table-any-border-regexp nil 1))))
3969 (unless quietly (message "Mapping tables: done")))
3971 ;; Declare and autoload functions from org-exp.el & Co
3973 (declare-function org-default-export-plist "org-exp")
3974 (declare-function org-infile-export-plist "org-exp")
3975 (declare-function org-get-current-options "org-exp")
3976 (eval-and-compile
3977 (org-autoload "org-exp"
3978 '(org-export org-export-visible
3979 org-insert-export-options-template
3980 org-table-clean-before-export))
3981 (org-autoload "org-ascii"
3982 '(org-export-as-ascii org-export-ascii-preprocess
3983 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3984 org-export-region-as-ascii))
3985 (org-autoload "org-latex"
3986 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3987 org-replace-region-by-latex org-export-region-as-latex
3988 org-export-as-latex org-export-as-pdf
3989 org-export-as-pdf-and-open))
3990 (org-autoload "org-html"
3991 '(org-export-as-html-and-open
3992 org-export-as-html-batch org-export-as-html-to-buffer
3993 org-replace-region-by-html org-export-region-as-html
3994 org-export-as-html))
3995 (org-autoload "org-docbook"
3996 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3997 org-replace-region-by-docbook org-export-region-as-docbook
3998 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3999 org-export-as-docbook))
4000 (org-autoload "org-icalendar"
4001 '(org-export-icalendar-this-file
4002 org-export-icalendar-all-agenda-files
4003 org-export-icalendar-combine-agenda-files))
4004 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4005 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4007 ;; Declare and autoload functions from org-agenda.el
4009 (eval-and-compile
4010 (org-autoload "org-agenda"
4011 '(org-agenda org-agenda-list org-search-view
4012 org-todo-list org-tags-view org-agenda-list-stuck-projects
4013 org-diary org-agenda-to-appt
4014 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4016 ;; Autoload org-remember
4018 (eval-and-compile
4019 (org-autoload "org-remember"
4020 '(org-remember-insinuate org-remember-annotation
4021 org-remember-apply-template org-remember org-remember-handler)))
4023 (eval-and-compile
4024 (org-autoload "org-capture"
4025 '(org-capture org-capture-insert-template-here
4026 org-capture-import-remember-templates)))
4028 ;; Autoload org-clock.el
4030 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4031 (beg end))
4032 (declare-function org-clock-update-mode-line "org-clock" ())
4033 (declare-function org-resolve-clocks "org-clock"
4034 (&optional also-non-dangling-p prompt last-valid))
4035 (defvar org-clock-start-time)
4036 (defvar org-clock-marker (make-marker)
4037 "Marker recording the last clock-in.")
4038 (defvar org-clock-hd-marker (make-marker)
4039 "Marker recording the last clock-in, but the headline position.")
4040 (defvar org-clock-heading ""
4041 "The heading of the current clock entry.")
4042 (defun org-clock-is-active ()
4043 "Return non-nil if clock is currently running.
4044 The return value is actually the clock marker."
4045 (marker-buffer org-clock-marker))
4047 (eval-and-compile
4048 (org-autoload
4049 "org-clock"
4050 '(org-clock-in org-clock-out org-clock-cancel
4051 org-clock-goto org-clock-sum org-clock-display
4052 org-clock-remove-overlays org-clock-report
4053 org-clocktable-shift org-dblock-write:clocktable
4054 org-get-clocktable org-resolve-clocks)))
4056 (defun org-clock-update-time-maybe ()
4057 "If this is a CLOCK line, update it and return t.
4058 Otherwise, return nil."
4059 (interactive)
4060 (save-excursion
4061 (beginning-of-line 1)
4062 (skip-chars-forward " \t")
4063 (when (looking-at org-clock-string)
4064 (let ((re (concat "[ \t]*" org-clock-string
4065 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4066 "\\([ \t]*=>.*\\)?\\)?"))
4067 ts te h m s neg)
4068 (cond
4069 ((not (looking-at re))
4070 nil)
4071 ((not (match-end 2))
4072 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4073 (> org-clock-marker (point))
4074 (<= org-clock-marker (point-at-eol)))
4075 ;; The clock is running here
4076 (setq org-clock-start-time
4077 (apply 'encode-time
4078 (org-parse-time-string (match-string 1))))
4079 (org-clock-update-mode-line)))
4081 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4082 (end-of-line 1)
4083 (setq ts (match-string 1)
4084 te (match-string 3))
4085 (setq s (- (org-float-time
4086 (apply 'encode-time (org-parse-time-string te)))
4087 (org-float-time
4088 (apply 'encode-time (org-parse-time-string ts))))
4089 neg (< s 0)
4090 s (abs s)
4091 h (floor (/ s 3600))
4092 s (- s (* 3600 h))
4093 m (floor (/ s 60))
4094 s (- s (* 60 s)))
4095 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4096 t))))))
4098 (defun org-check-running-clock ()
4099 "Check if the current buffer contains the running clock.
4100 If yes, offer to stop it and to save the buffer with the changes."
4101 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4102 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4103 (buffer-name))))
4104 (org-clock-out)
4105 (when (y-or-n-p "Save changed buffer?")
4106 (save-buffer))))
4108 (defun org-clocktable-try-shift (dir n)
4109 "Check if this line starts a clock table, if yes, shift the time block."
4110 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4111 (org-clocktable-shift dir n)))
4113 ;; Autoload org-timer.el
4115 (eval-and-compile
4116 (org-autoload
4117 "org-timer"
4118 '(org-timer-start org-timer org-timer-item
4119 org-timer-change-times-in-region
4120 org-timer-set-timer
4121 org-timer-reset-timers
4122 org-timer-show-remaining-time)))
4124 ;; Autoload org-feed.el
4126 (eval-and-compile
4127 (org-autoload
4128 "org-feed"
4129 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4132 ;; Autoload org-indent.el
4134 ;; Define the variable already here, to make sure we have it.
4135 (defvar org-indent-mode nil
4136 "Non-nil if Org-Indent mode is enabled.
4137 Use the command `org-indent-mode' to change this variable.")
4139 (eval-and-compile
4140 (org-autoload
4141 "org-indent"
4142 '(org-indent-mode)))
4144 ;; Autoload org-mobile.el
4146 (eval-and-compile
4147 (org-autoload
4148 "org-mobile"
4149 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4151 ;; Autoload archiving code
4152 ;; The stuff that is needed for cycling and tags has to be defined here.
4154 (defgroup org-archive nil
4155 "Options concerning archiving in Org-mode."
4156 :tag "Org Archive"
4157 :group 'org-structure)
4159 (defcustom org-archive-location "%s_archive::"
4160 "The location where subtrees should be archived.
4162 The value of this variable is a string, consisting of two parts,
4163 separated by a double-colon. The first part is a filename and
4164 the second part is a headline.
4166 When the filename is omitted, archiving happens in the same file.
4167 %s in the filename will be replaced by the current file
4168 name (without the directory part). Archiving to a different file
4169 is useful to keep archived entries from contributing to the
4170 Org-mode Agenda.
4172 The archived entries will be filed as subtrees of the specified
4173 headline. When the headline is omitted, the subtrees are simply
4174 filed away at the end of the file, as top-level entries. Also in
4175 the heading you can use %s to represent the file name, this can be
4176 useful when using the same archive for a number of different files.
4178 Here are a few examples:
4179 \"%s_archive::\"
4180 If the current file is Projects.org, archive in file
4181 Projects.org_archive, as top-level trees. This is the default.
4183 \"::* Archived Tasks\"
4184 Archive in the current file, under the top-level headline
4185 \"* Archived Tasks\".
4187 \"~/org/archive.org::\"
4188 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4190 \"~/org/archive.org::* From %s\"
4191 Archive in file ~/org/archive.org (absolute path), under headlines
4192 \"From FILENAME\" where file name is the current file name.
4194 \"~/org/datetree.org::datetree/* Finished Tasks\"
4195 The \"datetree/\" string is special, signifying to archive
4196 items to the datetree. Items are placed in either the CLOSED
4197 date of the item, or the current date if there is no CLOSED date.
4198 The heading will be a subentry to the current date. There doesn't
4199 need to be a heading, but there always needs to be a slash after
4200 datetree. For example, to store archived items directly in the
4201 datetree, use \"~/org/datetree.org::datetree/\".
4203 \"basement::** Finished Tasks\"
4204 Archive in file ./basement (relative path), as level 3 trees
4205 below the level 2 heading \"** Finished Tasks\".
4207 You may set this option on a per-file basis by adding to the buffer a
4208 line like
4210 #+ARCHIVE: basement::** Finished Tasks
4212 You may also define it locally for a subtree by setting an ARCHIVE property
4213 in the entry. If such a property is found in an entry, or anywhere up
4214 the hierarchy, it will be used."
4215 :group 'org-archive
4216 :type 'string)
4218 (defcustom org-archive-tag "ARCHIVE"
4219 "The tag that marks a subtree as archived.
4220 An archived subtree does not open during visibility cycling, and does
4221 not contribute to the agenda listings.
4222 After changing this, font-lock must be restarted in the relevant buffers to
4223 get the proper fontification."
4224 :group 'org-archive
4225 :group 'org-keywords
4226 :type 'string)
4228 (defcustom org-agenda-skip-archived-trees t
4229 "Non-nil means the agenda will skip any items located in archived trees.
4230 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4231 variable is no longer recommended, you should leave it at the value t.
4232 Instead, use the key `v' to cycle the archives-mode in the agenda."
4233 :group 'org-archive
4234 :group 'org-agenda-skip
4235 :type 'boolean)
4237 (defcustom org-columns-skip-archived-trees t
4238 "Non-nil means ignore archived trees when creating column view."
4239 :group 'org-archive
4240 :group 'org-properties
4241 :type 'boolean)
4243 (defcustom org-cycle-open-archived-trees nil
4244 "Non-nil means `org-cycle' will open archived trees.
4245 An archived tree is a tree marked with the tag ARCHIVE.
4246 When nil, archived trees will stay folded. You can still open them with
4247 normal outline commands like `show-all', but not with the cycling commands."
4248 :group 'org-archive
4249 :group 'org-cycle
4250 :type 'boolean)
4252 (defcustom org-sparse-tree-open-archived-trees nil
4253 "Non-nil means sparse tree construction shows matches in archived trees.
4254 When nil, matches in these trees are highlighted, but the trees are kept in
4255 collapsed state."
4256 :group 'org-archive
4257 :group 'org-sparse-trees
4258 :type 'boolean)
4260 (defun org-cycle-hide-archived-subtrees (state)
4261 "Re-hide all archived subtrees after a visibility state change."
4262 (when (and (not org-cycle-open-archived-trees)
4263 (not (memq state '(overview folded))))
4264 (save-excursion
4265 (let* ((globalp (memq state '(contents all)))
4266 (beg (if globalp (point-min) (point)))
4267 (end (if globalp (point-max) (org-end-of-subtree t))))
4268 (org-hide-archived-subtrees beg end)
4269 (goto-char beg)
4270 (if (looking-at (concat ".*:" org-archive-tag ":"))
4271 (message "%s" (substitute-command-keys
4272 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4274 (defun org-force-cycle-archived ()
4275 "Cycle subtree even if it is archived."
4276 (interactive)
4277 (setq this-command 'org-cycle)
4278 (let ((org-cycle-open-archived-trees t))
4279 (call-interactively 'org-cycle)))
4281 (defun org-hide-archived-subtrees (beg end)
4282 "Re-hide all archived subtrees after a visibility state change."
4283 (save-excursion
4284 (let* ((re (concat ":" org-archive-tag ":")))
4285 (goto-char beg)
4286 (while (re-search-forward re end t)
4287 (when (org-at-heading-p)
4288 (org-flag-subtree t)
4289 (org-end-of-subtree t))))))
4291 (defun org-flag-subtree (flag)
4292 (save-excursion
4293 (org-back-to-heading t)
4294 (outline-end-of-heading)
4295 (outline-flag-region (point)
4296 (progn (org-end-of-subtree t) (point))
4297 flag)))
4299 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4301 (eval-and-compile
4302 (org-autoload "org-archive"
4303 '(org-add-archive-files org-archive-subtree
4304 org-archive-to-archive-sibling org-toggle-archive-tag
4305 org-archive-subtree-default
4306 org-archive-subtree-default-with-confirmation)))
4308 ;; Autoload Column View Code
4310 (declare-function org-columns-number-to-string "org-colview")
4311 (declare-function org-columns-get-format-and-top-level "org-colview")
4312 (declare-function org-columns-compute "org-colview")
4314 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4315 '(org-columns-number-to-string org-columns-get-format-and-top-level
4316 org-columns-compute org-agenda-columns org-columns-remove-overlays
4317 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4319 ;; Autoload ID code
4321 (declare-function org-id-store-link "org-id")
4322 (declare-function org-id-locations-load "org-id")
4323 (declare-function org-id-locations-save "org-id")
4324 (defvar org-id-track-globally)
4325 (org-autoload "org-id"
4326 '(org-id-get-create org-id-new org-id-copy org-id-get
4327 org-id-get-with-outline-path-completion
4328 org-id-get-with-outline-drilling org-id-store-link
4329 org-id-goto org-id-find org-id-store-link))
4331 ;; Autoload Plotting Code
4333 (org-autoload "org-plot"
4334 '(org-plot/gnuplot))
4336 ;;; Variables for pre-computed regular expressions, all buffer local
4338 (defvar org-drawer-regexp nil
4339 "Matches first line of a hidden block.")
4340 (make-variable-buffer-local 'org-drawer-regexp)
4341 (defvar org-todo-regexp nil
4342 "Matches any of the TODO state keywords.")
4343 (make-variable-buffer-local 'org-todo-regexp)
4344 (defvar org-not-done-regexp nil
4345 "Matches any of the TODO state keywords except the last one.")
4346 (make-variable-buffer-local 'org-not-done-regexp)
4347 (defvar org-not-done-heading-regexp nil
4348 "Matches a TODO headline that is not done.")
4349 (make-variable-buffer-local 'org-not-done-regexp)
4350 (defvar org-todo-line-regexp nil
4351 "Matches a headline and puts TODO state into group 2 if present.")
4352 (make-variable-buffer-local 'org-todo-line-regexp)
4353 (defvar org-complex-heading-regexp nil
4354 "Matches a headline and puts everything into groups:
4355 group 1: the stars
4356 group 2: The todo keyword, maybe
4357 group 3: Priority cookie
4358 group 4: True headline
4359 group 5: Tags")
4360 (make-variable-buffer-local 'org-complex-heading-regexp)
4361 (defvar org-complex-heading-regexp-format nil
4362 "Printf format to make regexp to match an exact headline.
4363 This regexp will match the headline of any node which has the
4364 exact headline text that is put into the format, but may have any
4365 TODO state, priority and tags.")
4366 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4367 (defvar org-todo-line-tags-regexp nil
4368 "Matches a headline and puts TODO state into group 2 if present.
4369 Also put tags into group 4 if tags are present.")
4370 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4371 (defvar org-ds-keyword-length 12
4372 "Maximum length of the Deadline and SCHEDULED keywords.")
4373 (make-variable-buffer-local 'org-ds-keyword-length)
4374 (defvar org-deadline-regexp nil
4375 "Matches the DEADLINE keyword.")
4376 (make-variable-buffer-local 'org-deadline-regexp)
4377 (defvar org-deadline-time-regexp nil
4378 "Matches the DEADLINE keyword together with a time stamp.")
4379 (make-variable-buffer-local 'org-deadline-time-regexp)
4380 (defvar org-deadline-line-regexp nil
4381 "Matches the DEADLINE keyword and the rest of the line.")
4382 (make-variable-buffer-local 'org-deadline-line-regexp)
4383 (defvar org-scheduled-regexp nil
4384 "Matches the SCHEDULED keyword.")
4385 (make-variable-buffer-local 'org-scheduled-regexp)
4386 (defvar org-scheduled-time-regexp nil
4387 "Matches the SCHEDULED keyword together with a time stamp.")
4388 (make-variable-buffer-local 'org-scheduled-time-regexp)
4389 (defvar org-closed-time-regexp nil
4390 "Matches the CLOSED keyword together with a time stamp.")
4391 (make-variable-buffer-local 'org-closed-time-regexp)
4393 (defvar org-keyword-time-regexp nil
4394 "Matches any of the 4 keywords, together with the time stamp.")
4395 (make-variable-buffer-local 'org-keyword-time-regexp)
4396 (defvar org-keyword-time-not-clock-regexp nil
4397 "Matches any of the 3 keywords, together with the time stamp.")
4398 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4399 (defvar org-maybe-keyword-time-regexp nil
4400 "Matches a timestamp, possibly preceded by a keyword.")
4401 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4402 (defvar org-planning-or-clock-line-re nil
4403 "Matches a line with planning or clock info.")
4404 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4405 (defvar org-all-time-keywords nil
4406 "List of time keywords.")
4407 (make-variable-buffer-local 'org-all-time-keywords)
4409 (defconst org-plain-time-of-day-regexp
4410 (concat
4411 "\\(\\<[012]?[0-9]"
4412 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4413 "\\(--?"
4414 "\\(\\<[012]?[0-9]"
4415 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4416 "\\)?")
4417 "Regular expression to match a plain time or time range.
4418 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4419 groups carry important information:
4420 0 the full match
4421 1 the first time, range or not
4422 8 the second time, if it is a range.")
4424 (defconst org-plain-time-extension-regexp
4425 (concat
4426 "\\(\\<[012]?[0-9]"
4427 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4428 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4429 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4430 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4431 groups carry important information:
4432 0 the full match
4433 7 hours of duration
4434 9 minutes of duration")
4436 (defconst org-stamp-time-of-day-regexp
4437 (concat
4438 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4439 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4440 "\\(--?"
4441 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4442 "Regular expression to match a timestamp time or time range.
4443 After a match, the following groups carry important information:
4444 0 the full match
4445 1 date plus weekday, for back referencing to make sure both times are on the same day
4446 2 the first time, range or not
4447 4 the second time, if it is a range.")
4449 (defconst org-startup-options
4450 '(("fold" org-startup-folded t)
4451 ("overview" org-startup-folded t)
4452 ("nofold" org-startup-folded nil)
4453 ("showall" org-startup-folded nil)
4454 ("showeverything" org-startup-folded showeverything)
4455 ("content" org-startup-folded content)
4456 ("indent" org-startup-indented t)
4457 ("noindent" org-startup-indented nil)
4458 ("hidestars" org-hide-leading-stars t)
4459 ("showstars" org-hide-leading-stars nil)
4460 ("odd" org-odd-levels-only t)
4461 ("oddeven" org-odd-levels-only nil)
4462 ("align" org-startup-align-all-tables t)
4463 ("noalign" org-startup-align-all-tables nil)
4464 ("inlineimages" org-startup-with-inline-images t)
4465 ("noinlineimages" org-startup-with-inline-images nil)
4466 ("customtime" org-display-custom-times t)
4467 ("logdone" org-log-done time)
4468 ("lognotedone" org-log-done note)
4469 ("nologdone" org-log-done nil)
4470 ("lognoteclock-out" org-log-note-clock-out t)
4471 ("nolognoteclock-out" org-log-note-clock-out nil)
4472 ("logrepeat" org-log-repeat state)
4473 ("lognoterepeat" org-log-repeat note)
4474 ("nologrepeat" org-log-repeat nil)
4475 ("logreschedule" org-log-reschedule time)
4476 ("lognotereschedule" org-log-reschedule note)
4477 ("nologreschedule" org-log-reschedule nil)
4478 ("logredeadline" org-log-redeadline time)
4479 ("lognoteredeadline" org-log-redeadline note)
4480 ("nologredeadline" org-log-redeadline nil)
4481 ("logrefile" org-log-refile time)
4482 ("lognoterefile" org-log-refile note)
4483 ("nologrefile" org-log-refile nil)
4484 ("fninline" org-footnote-define-inline t)
4485 ("nofninline" org-footnote-define-inline nil)
4486 ("fnlocal" org-footnote-section nil)
4487 ("fnauto" org-footnote-auto-label t)
4488 ("fnprompt" org-footnote-auto-label nil)
4489 ("fnconfirm" org-footnote-auto-label confirm)
4490 ("fnplain" org-footnote-auto-label plain)
4491 ("fnadjust" org-footnote-auto-adjust t)
4492 ("nofnadjust" org-footnote-auto-adjust nil)
4493 ("constcgs" constants-unit-system cgs)
4494 ("constSI" constants-unit-system SI)
4495 ("noptag" org-tag-persistent-alist nil)
4496 ("hideblocks" org-hide-block-startup t)
4497 ("nohideblocks" org-hide-block-startup nil)
4498 ("beamer" org-startup-with-beamer-mode t)
4499 ("entitiespretty" org-pretty-entities t)
4500 ("entitiesplain" org-pretty-entities nil))
4501 "Variable associated with STARTUP options for org-mode.
4502 Each element is a list of three items: The startup options as written
4503 in the #+STARTUP line, the corresponding variable, and the value to
4504 set this variable to if the option is found. An optional forth element PUSH
4505 means to push this value onto the list in the variable.")
4507 (defun org-update-property-plist (key val props)
4508 "Update PROPS with KEY and VAL."
4509 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4510 (key (if appending (substring key 0 (- (length key) 1)) key))
4511 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4512 (previous (cdr (assoc key props))))
4513 (if appending
4514 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4515 (cons (cons key val) remainder))))
4517 (defconst org-block-regexp
4518 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4519 "Regular expression for hiding blocks.")
4520 (defconst org-heading-keyword-regexp-format
4521 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4522 "Printf format for a regexp matching an headline with some keyword.
4523 This regexp will match the headline of any node which has the
4524 exact keyword that is put into the format. The keyword isn't in
4525 any group by default, but the stars and the body are.")
4526 (defconst org-heading-keyword-maybe-regexp-format
4527 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4528 "Printf format for a regexp matching an headline, possibly with some keyword.
4529 This regexp can match any headline with the specified keyword, or
4530 without a keyword. The keyword isn't in any group by default,
4531 but the stars and the body are.")
4533 (defun org-set-regexps-and-options ()
4534 "Precompute regular expressions for current buffer."
4535 (when (derived-mode-p 'org-mode)
4536 (org-set-local 'org-todo-kwd-alist nil)
4537 (org-set-local 'org-todo-key-alist nil)
4538 (org-set-local 'org-todo-key-trigger nil)
4539 (org-set-local 'org-todo-keywords-1 nil)
4540 (org-set-local 'org-done-keywords nil)
4541 (org-set-local 'org-todo-heads nil)
4542 (org-set-local 'org-todo-sets nil)
4543 (org-set-local 'org-todo-log-states nil)
4544 (org-set-local 'org-file-properties nil)
4545 (org-set-local 'org-file-tags nil)
4546 (let ((re (org-make-options-regexp
4547 '("CATEGORY" "TODO" "COLUMNS"
4548 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4549 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4550 "OPTIONS")
4551 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4552 (splitre "[ \t]+")
4553 (scripts org-use-sub-superscripts)
4554 kwds kws0 kwsa key log value cat arch tags const links hw dws
4555 tail sep kws1 prio props ftags drawers beamer-p
4556 ext-setup-or-nil setup-contents (start 0))
4557 (save-excursion
4558 (save-restriction
4559 (widen)
4560 (goto-char (point-min))
4561 (while (or (and ext-setup-or-nil
4562 (string-match re ext-setup-or-nil start)
4563 (setq start (match-end 0)))
4564 (and (setq ext-setup-or-nil nil start 0)
4565 (re-search-forward re nil t)))
4566 (setq key (upcase (match-string 1 ext-setup-or-nil))
4567 value (org-match-string-no-properties 2 ext-setup-or-nil))
4568 (if (stringp value) (setq value (org-trim value)))
4569 (cond
4570 ((equal key "CATEGORY")
4571 (setq cat value))
4572 ((member key '("SEQ_TODO" "TODO"))
4573 (push (cons 'sequence (org-split-string value splitre)) kwds))
4574 ((equal key "TYP_TODO")
4575 (push (cons 'type (org-split-string value splitre)) kwds))
4576 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4577 ;; general TODO-like setup
4578 (push (cons (intern (downcase (match-string 1 key)))
4579 (org-split-string value splitre)) kwds))
4580 ((equal key "TAGS")
4581 (setq tags (append tags (if tags '("\\n") nil)
4582 (org-split-string value splitre))))
4583 ((equal key "COLUMNS")
4584 (org-set-local 'org-columns-default-format value))
4585 ((equal key "LINK")
4586 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4587 (push (cons (match-string 1 value)
4588 (org-trim (match-string 2 value)))
4589 links)))
4590 ((equal key "PRIORITIES")
4591 (setq prio (org-split-string value " +")))
4592 ((equal key "PROPERTY")
4593 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4594 (setq props (org-update-property-plist (match-string 1 value)
4595 (match-string 2 value)
4596 props))))
4597 ((equal key "FILETAGS")
4598 (when (string-match "\\S-" value)
4599 (setq ftags
4600 (append
4601 ftags
4602 (apply 'append
4603 (mapcar (lambda (x) (org-split-string x ":"))
4604 (org-split-string value)))))))
4605 ((equal key "DRAWERS")
4606 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4607 ((equal key "CONSTANTS")
4608 (setq const (append const (org-split-string value splitre))))
4609 ((equal key "STARTUP")
4610 (let ((opts (org-split-string value splitre))
4611 l var val)
4612 (while (setq l (pop opts))
4613 (when (setq l (assoc l org-startup-options))
4614 (setq var (nth 1 l) val (nth 2 l))
4615 (if (not (nth 3 l))
4616 (set (make-local-variable var) val)
4617 (if (not (listp (symbol-value var)))
4618 (set (make-local-variable var) nil))
4619 (set (make-local-variable var) (symbol-value var))
4620 (add-to-list var val))))))
4621 ((equal key "ARCHIVE")
4622 (setq arch value)
4623 (remove-text-properties 0 (length arch)
4624 '(face t fontified t) arch))
4625 ((equal key "LATEX_CLASS")
4626 (setq beamer-p (equal value "beamer")))
4627 ((equal key "OPTIONS")
4628 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4629 (setq scripts (read (match-string 2 value)))))
4630 ((equal key "SETUPFILE")
4631 (setq setup-contents (org-file-contents
4632 (expand-file-name
4633 (org-remove-double-quotes value))
4634 'noerror))
4635 (if (not ext-setup-or-nil)
4636 (setq ext-setup-or-nil setup-contents start 0)
4637 (setq ext-setup-or-nil
4638 (concat (substring ext-setup-or-nil 0 start)
4639 "\n" setup-contents "\n"
4640 (substring ext-setup-or-nil start)))))))
4641 ;; search for property blocks
4642 (goto-char (point-min))
4643 (while (re-search-forward org-block-regexp nil t)
4644 (when (equal "PROPERTY" (upcase (match-string 1)))
4645 (setq value (replace-regexp-in-string
4646 "[\n\r]" " " (match-string 4)))
4647 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4648 (setq props (org-update-property-plist (match-string 1 value)
4649 (match-string 2 value)
4650 props)))))))
4651 (org-set-local 'org-use-sub-superscripts scripts)
4652 (when cat
4653 (org-set-local 'org-category (intern cat))
4654 (push (cons "CATEGORY" cat) props))
4655 (when prio
4656 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4657 (setq prio (mapcar 'string-to-char prio))
4658 (org-set-local 'org-highest-priority (nth 0 prio))
4659 (org-set-local 'org-lowest-priority (nth 1 prio))
4660 (org-set-local 'org-default-priority (nth 2 prio)))
4661 (and props (org-set-local 'org-file-properties (nreverse props)))
4662 (and ftags (org-set-local 'org-file-tags
4663 (mapcar 'org-add-prop-inherited ftags)))
4664 (and drawers (org-set-local 'org-drawers drawers))
4665 (and arch (org-set-local 'org-archive-location arch))
4666 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4667 ;; Process the TODO keywords
4668 (unless kwds
4669 ;; Use the global values as if they had been given locally.
4670 (setq kwds (default-value 'org-todo-keywords))
4671 (if (stringp (car kwds))
4672 (setq kwds (list (cons org-todo-interpretation
4673 (default-value 'org-todo-keywords)))))
4674 (setq kwds (reverse kwds)))
4675 (setq kwds (nreverse kwds))
4676 (let (inter kws kw)
4677 (while (setq kws (pop kwds))
4678 (let ((kws (or
4679 (run-hook-with-args-until-success
4680 'org-todo-setup-filter-hook kws)
4681 kws)))
4682 (setq inter (pop kws) sep (member "|" kws)
4683 kws0 (delete "|" (copy-sequence kws))
4684 kwsa nil
4685 kws1 (mapcar
4686 (lambda (x)
4687 ;; 1 2
4688 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4689 (progn
4690 (setq kw (match-string 1 x)
4691 key (and (match-end 2) (match-string 2 x))
4692 log (org-extract-log-state-settings x))
4693 (push (cons kw (and key (string-to-char key))) kwsa)
4694 (and log (push log org-todo-log-states))
4696 (error "Invalid TODO keyword %s" x)))
4697 kws0)
4698 kwsa (if kwsa (append '((:startgroup))
4699 (nreverse kwsa)
4700 '((:endgroup))))
4701 hw (car kws1)
4702 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4703 tail (list inter hw (car dws) (org-last dws))))
4704 (add-to-list 'org-todo-heads hw 'append)
4705 (push kws1 org-todo-sets)
4706 (setq org-done-keywords (append org-done-keywords dws nil))
4707 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4708 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4709 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4710 (setq org-todo-sets (nreverse org-todo-sets)
4711 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4712 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4713 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4714 ;; Process the constants
4715 (when const
4716 (let (e cst)
4717 (while (setq e (pop const))
4718 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4719 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4720 (setq org-table-formula-constants-local cst)))
4722 ;; Process the tags.
4723 (when tags
4724 (let (e tgs)
4725 (while (setq e (pop tags))
4726 (cond
4727 ((equal e "{") (push '(:startgroup) tgs))
4728 ((equal e "}") (push '(:endgroup) tgs))
4729 ((equal e "\\n") (push '(:newline) tgs))
4730 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4731 (push (cons (match-string 1 e)
4732 (string-to-char (match-string 2 e)))
4733 tgs))
4734 (t (push (list e) tgs))))
4735 (org-set-local 'org-tag-alist nil)
4736 (while (setq e (pop tgs))
4737 (or (and (stringp (car e))
4738 (assoc (car e) org-tag-alist))
4739 (push e org-tag-alist)))))
4741 ;; Compute the regular expressions and other local variables.
4742 ;; Using `org-outline-regexp-bol' would complicate them much,
4743 ;; because of the fixed white space at the end of that string.
4744 (if (not org-done-keywords)
4745 (setq org-done-keywords (and org-todo-keywords-1
4746 (list (org-last org-todo-keywords-1)))))
4747 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4748 (length org-scheduled-string)
4749 (length org-clock-string)
4750 (length org-closed-string)))
4751 org-drawer-regexp
4752 (concat "^[ \t]*:\\("
4753 (mapconcat 'regexp-quote org-drawers "\\|")
4754 "\\):[ \t]*$")
4755 org-not-done-keywords
4756 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4757 org-todo-regexp
4758 (concat "\\("
4759 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4760 "\\)")
4761 org-not-done-regexp
4762 (concat "\\("
4763 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4764 "\\)")
4765 org-not-done-heading-regexp
4766 (format org-heading-keyword-regexp-format org-not-done-regexp)
4767 org-todo-line-regexp
4768 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4769 org-complex-heading-regexp
4770 (concat "^\\(\\*+\\)"
4771 "\\(?: +" org-todo-regexp "\\)?"
4772 "\\(?: +\\(\\[#.\\]\\)\\)?"
4773 "\\(?: +\\(.*?\\)\\)?"
4774 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4775 "[ \t]*$")
4776 org-complex-heading-regexp-format
4777 (concat "^\\(\\*+\\)"
4778 "\\(?: +" org-todo-regexp "\\)?"
4779 "\\(?: +\\(\\[#.\\]\\)\\)?"
4780 "\\(?: +"
4781 ;; Stats cookies can be stuck to body.
4782 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4783 "\\(%s\\)"
4784 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4785 "\\)"
4786 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4787 "[ \t]*$")
4788 org-todo-line-tags-regexp
4789 (concat "^\\(\\*+\\)"
4790 "\\(?: +" org-todo-regexp "\\)?"
4791 "\\(?: +\\(.*?\\)\\)?"
4792 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4793 "[ \t]*$")
4794 org-deadline-regexp (concat "\\<" org-deadline-string)
4795 org-deadline-time-regexp
4796 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4797 org-deadline-line-regexp
4798 (concat "\\<\\(" org-deadline-string "\\).*")
4799 org-scheduled-regexp
4800 (concat "\\<" org-scheduled-string)
4801 org-scheduled-time-regexp
4802 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4803 org-closed-time-regexp
4804 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4805 org-keyword-time-regexp
4806 (concat "\\<\\(" org-scheduled-string
4807 "\\|" org-deadline-string
4808 "\\|" org-closed-string
4809 "\\|" org-clock-string "\\)"
4810 " *[[<]\\([^]>]+\\)[]>]")
4811 org-keyword-time-not-clock-regexp
4812 (concat "\\<\\(" org-scheduled-string
4813 "\\|" org-deadline-string
4814 "\\|" org-closed-string
4815 "\\)"
4816 " *[[<]\\([^]>]+\\)[]>]")
4817 org-maybe-keyword-time-regexp
4818 (concat "\\(\\<\\(" org-scheduled-string
4819 "\\|" org-deadline-string
4820 "\\|" org-closed-string
4821 "\\|" org-clock-string "\\)\\)?"
4822 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4823 org-planning-or-clock-line-re
4824 (concat "^[ \t]*\\("
4825 org-scheduled-string "\\|"
4826 org-deadline-string "\\|"
4827 org-closed-string "\\|"
4828 org-clock-string "\\)")
4829 org-all-time-keywords
4830 (mapcar (lambda (w) (substring w 0 -1))
4831 (list org-scheduled-string org-deadline-string
4832 org-clock-string org-closed-string))
4834 (org-compute-latex-and-specials-regexp)
4835 (org-set-font-lock-defaults))))
4837 (defun org-file-contents (file &optional noerror)
4838 "Return the contents of FILE, as a string."
4839 (if (or (not file)
4840 (not (file-readable-p file)))
4841 (if noerror
4842 (progn
4843 (message "Cannot read file \"%s\"" file)
4844 (ding) (sit-for 2)
4846 (error "Cannot read file \"%s\"" file))
4847 (with-temp-buffer
4848 (insert-file-contents file)
4849 (buffer-string))))
4851 (defun org-extract-log-state-settings (x)
4852 "Extract the log state setting from a TODO keyword string.
4853 This will extract info from a string like \"WAIT(w@/!)\"."
4854 (let (kw key log1 log2)
4855 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4856 (setq kw (match-string 1 x)
4857 key (and (match-end 2) (match-string 2 x))
4858 log1 (and (match-end 3) (match-string 3 x))
4859 log2 (and (match-end 4) (match-string 4 x)))
4860 (and (or log1 log2)
4861 (list kw
4862 (and log1 (if (equal log1 "!") 'time 'note))
4863 (and log2 (if (equal log2 "!") 'time 'note)))))))
4865 (defun org-remove-keyword-keys (list)
4866 "Remove a pair of parenthesis at the end of each string in LIST."
4867 (mapcar (lambda (x)
4868 (if (string-match "(.*)$" x)
4869 (substring x 0 (match-beginning 0))
4871 list))
4873 (defun org-assign-fast-keys (alist)
4874 "Assign fast keys to a keyword-key alist.
4875 Respect keys that are already there."
4876 (let (new e (alt ?0))
4877 (while (setq e (pop alist))
4878 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4879 (cdr e)) ;; Key already assigned.
4880 (push e new)
4881 (let ((clist (string-to-list (downcase (car e))))
4882 (used (append new alist)))
4883 (when (= (car clist) ?@)
4884 (pop clist))
4885 (while (and clist (rassoc (car clist) used))
4886 (pop clist))
4887 (unless clist
4888 (while (rassoc alt used)
4889 (incf alt)))
4890 (push (cons (car e) (or (car clist) alt)) new))))
4891 (nreverse new)))
4893 ;;; Some variables used in various places
4895 (defvar org-window-configuration nil
4896 "Used in various places to store a window configuration.")
4897 (defvar org-selected-window nil
4898 "Used in various places to store a window configuration.")
4899 (defvar org-finish-function nil
4900 "Function to be called when `C-c C-c' is used.
4901 This is for getting out of special buffers like remember.")
4904 ;; FIXME: Occasionally check by commenting these, to make sure
4905 ;; no other functions uses these, forgetting to let-bind them.
4906 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4907 (defvar org-last-state)
4908 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4910 ;; Defined somewhere in this file, but used before definition.
4911 (defvar org-entities) ;; defined in org-entities.el
4912 (defvar org-struct-menu)
4913 (defvar org-org-menu)
4914 (defvar org-tbl-menu)
4916 ;;;; Define the Org-mode
4918 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4919 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
4922 ;; We use a before-change function to check if a table might need
4923 ;; an update.
4924 (defvar org-table-may-need-update t
4925 "Indicates that a table might need an update.
4926 This variable is set by `org-before-change-function'.
4927 `org-table-align' sets it back to nil.")
4928 (defun org-before-change-function (beg end)
4929 "Every change indicates that a table might need an update."
4930 (setq org-table-may-need-update t))
4931 (defvar org-mode-map)
4932 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4933 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4934 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4935 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4936 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4937 (defvar org-table-buffer-is-an nil)
4939 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4940 ;; some places -- e.g. see the macro org-with-limited-levels.
4942 ;; In Org buffers, the value of `outline-regexp' is that of
4943 ;; `org-outline-regexp'. The only function still directly relying on
4944 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4945 ;; job when `orgstruct-mode' is active.
4946 (defvar org-outline-regexp "\\*+ "
4947 "Regexp to match Org headlines.")
4948 (defconst org-outline-regexp-bol "^\\*+ "
4949 "Regexp to match Org headlines.
4950 This is similar to `org-outline-regexp' but additionally makes
4951 sure that we are at the beginning of the line.")
4953 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4954 "Matches an headline, putting stars and text into groups.
4955 Stars are put in group 1 and the trimmed body in group 2.")
4957 (defvar bidi-paragraph-direction)
4958 (defvar buffer-face-mode-face)
4960 ;;;###autoload
4961 (define-derived-mode org-mode outline-mode "Org"
4962 "Outline-based notes management and organizer, alias
4963 \"Carsten's outline-mode for keeping track of everything.\"
4965 Org-mode develops organizational tasks around a NOTES file which
4966 contains information about projects as plain text. Org-mode is
4967 implemented on top of outline-mode, which is ideal to keep the content
4968 of large files well structured. It supports ToDo items, deadlines and
4969 time stamps, which magically appear in the diary listing of the Emacs
4970 calendar. Tables are easily created with a built-in table editor.
4971 Plain text URL-like links connect to websites, emails (VM), Usenet
4972 messages (Gnus), BBDB entries, and any files related to the project.
4973 For printing and sharing of notes, an Org-mode file (or a part of it)
4974 can be exported as a structured ASCII or HTML file.
4976 The following commands are available:
4978 \\{org-mode-map}"
4980 ;; Get rid of Outline menus, they are not needed
4981 ;; Need to do this here because define-derived-mode sets up
4982 ;; the keymap so late. Still, it is a waste to call this each time
4983 ;; we switch another buffer into org-mode.
4984 (if (featurep 'xemacs)
4985 (when (boundp 'outline-mode-menu-heading)
4986 ;; Assume this is Greg's port, it uses easymenu
4987 (easy-menu-remove outline-mode-menu-heading)
4988 (easy-menu-remove outline-mode-menu-show)
4989 (easy-menu-remove outline-mode-menu-hide))
4990 (define-key org-mode-map [menu-bar headings] 'undefined)
4991 (define-key org-mode-map [menu-bar hide] 'undefined)
4992 (define-key org-mode-map [menu-bar show] 'undefined))
4994 (org-load-modules-maybe)
4995 (easy-menu-add org-org-menu)
4996 (easy-menu-add org-tbl-menu)
4997 (org-install-agenda-files-menu)
4998 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4999 (add-to-invisibility-spec '(org-cwidth))
5000 (add-to-invisibility-spec '(org-hide-block . t))
5001 (when (featurep 'xemacs)
5002 (org-set-local 'line-move-ignore-invisible t))
5003 (org-set-local 'outline-regexp org-outline-regexp)
5004 (org-set-local 'outline-level 'org-outline-level)
5005 (setq bidi-paragraph-direction 'left-to-right)
5006 (when (and org-ellipsis
5007 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5008 (fboundp 'make-glyph-code))
5009 (unless org-display-table
5010 (setq org-display-table (make-display-table)))
5011 (set-display-table-slot
5012 org-display-table 4
5013 (vconcat (mapcar
5014 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5015 org-ellipsis)))
5016 (if (stringp org-ellipsis) org-ellipsis "..."))))
5017 (setq buffer-display-table org-display-table))
5018 (org-set-regexps-and-options)
5019 (when (and org-tag-faces (not org-tags-special-faces-re))
5020 ;; tag faces set outside customize.... force initialization.
5021 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5022 ;; Calc embedded
5023 (org-set-local 'calc-embedded-open-mode "# ")
5024 (modify-syntax-entry ?@ "w")
5025 (if org-startup-truncated (setq truncate-lines t))
5026 (org-set-local 'font-lock-unfontify-region-function
5027 'org-unfontify-region)
5028 ;; Activate before-change-function
5029 (org-set-local 'org-table-may-need-update t)
5030 (org-add-hook 'before-change-functions 'org-before-change-function nil
5031 'local)
5032 ;; Check for running clock before killing a buffer
5033 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5034 ;; Paragraphs and auto-filling
5035 (org-set-autofill-regexps)
5036 (setq indent-line-function 'org-indent-line-function)
5037 (org-update-radio-target-regexp)
5038 ;; Beginning/end of defun
5039 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5040 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5041 ;; Next error for sparse trees
5042 (org-set-local 'next-error-function 'org-occur-next-match)
5043 ;; Make sure dependence stuff works reliably, even for users who set it
5044 ;; too late :-(
5045 (if org-enforce-todo-dependencies
5046 (add-hook 'org-blocker-hook
5047 'org-block-todo-from-children-or-siblings-or-parent)
5048 (remove-hook 'org-blocker-hook
5049 'org-block-todo-from-children-or-siblings-or-parent))
5050 (if org-enforce-todo-checkbox-dependencies
5051 (add-hook 'org-blocker-hook
5052 'org-block-todo-from-checkboxes)
5053 (remove-hook 'org-blocker-hook
5054 'org-block-todo-from-checkboxes))
5056 ;; Comment characters
5057 (org-set-local 'comment-start "#")
5058 (org-set-local 'comment-padding " ")
5060 ;; Align options lines
5061 (org-set-local
5062 'align-mode-rules-list
5063 '((org-in-buffer-settings
5064 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5065 (modes . '(org-mode)))))
5067 ;; Imenu
5068 (org-set-local 'imenu-create-index-function
5069 'org-imenu-get-tree)
5071 ;; Make isearch reveal context
5072 (if (or (featurep 'xemacs)
5073 (not (boundp 'outline-isearch-open-invisible-function)))
5074 ;; Emacs 21 and XEmacs make use of the hook
5075 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5076 ;; Emacs 22 deals with this through a special variable
5077 (org-set-local 'outline-isearch-open-invisible-function
5078 (lambda (&rest ignore) (org-show-context 'isearch))))
5080 ;; Turn on org-beamer-mode?
5081 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5083 ;; Setup the pcomplete hooks
5084 (set (make-local-variable 'pcomplete-command-completion-function)
5085 'org-pcomplete-initial)
5086 (set (make-local-variable 'pcomplete-command-name-function)
5087 'org-command-at-point)
5088 (set (make-local-variable 'pcomplete-default-completion-function)
5089 'ignore)
5090 (set (make-local-variable 'pcomplete-parse-arguments-function)
5091 'org-parse-arguments)
5092 (set (make-local-variable 'pcomplete-termination-string) "")
5093 (when (>= emacs-major-version 23)
5094 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5096 ;; If empty file that did not turn on org-mode automatically, make it to.
5097 (if (and org-insert-mode-line-in-empty-file
5098 (org-called-interactively-p 'any)
5099 (= (point-min) (point-max)))
5100 (insert "# -*- mode: org -*-\n\n"))
5101 (unless org-inhibit-startup
5102 (when org-startup-align-all-tables
5103 (let ((bmp (buffer-modified-p)))
5104 (org-table-map-tables 'org-table-align 'quietly)
5105 (set-buffer-modified-p bmp)))
5106 (when org-startup-with-inline-images
5107 (org-display-inline-images))
5108 (when org-startup-indented
5109 (require 'org-indent)
5110 (org-indent-mode 1))
5111 (unless org-inhibit-startup-visibility-stuff
5112 (org-set-startup-visibility))))
5114 (when (fboundp 'abbrev-table-put)
5115 (abbrev-table-put org-mode-abbrev-table
5116 :parents (list text-mode-abbrev-table)))
5118 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5120 (defun org-current-time ()
5121 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5122 (if (> (car org-time-stamp-rounding-minutes) 1)
5123 (let ((r (car org-time-stamp-rounding-minutes))
5124 (time (decode-time)))
5125 (apply 'encode-time
5126 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5127 (nthcdr 2 time))))
5128 (current-time)))
5130 (defun org-today ()
5131 "Return today date, considering `org-extend-today-until'."
5132 (time-to-days
5133 (time-subtract (current-time)
5134 (list 0 (* 3600 org-extend-today-until) 0))))
5136 ;;;; Font-Lock stuff, including the activators
5138 (defvar org-mouse-map (make-sparse-keymap))
5139 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5140 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5141 (when org-mouse-1-follows-link
5142 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5143 (when org-tab-follows-link
5144 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5145 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5147 (require 'font-lock)
5149 (defconst org-non-link-chars "]\t\n\r<>")
5150 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5151 "shell" "elisp" "doi" "message"))
5152 (defvar org-link-types-re nil
5153 "Matches a link that has a url-like prefix like \"http:\"")
5154 (defvar org-link-re-with-space nil
5155 "Matches a link with spaces, optional angular brackets around it.")
5156 (defvar org-link-re-with-space2 nil
5157 "Matches a link with spaces, optional angular brackets around it.")
5158 (defvar org-link-re-with-space3 nil
5159 "Matches a link with spaces, only for internal part in bracket links.")
5160 (defvar org-angle-link-re nil
5161 "Matches link with angular brackets, spaces are allowed.")
5162 (defvar org-plain-link-re nil
5163 "Matches plain link, without spaces.")
5164 (defvar org-bracket-link-regexp nil
5165 "Matches a link in double brackets.")
5166 (defvar org-bracket-link-analytic-regexp nil
5167 "Regular expression used to analyze links.
5168 Here is what the match groups contain after a match:
5169 1: http:
5170 2: http
5171 3: path
5172 4: [desc]
5173 5: desc")
5174 (defvar org-bracket-link-analytic-regexp++ nil
5175 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5176 (defvar org-any-link-re nil
5177 "Regular expression matching any link.")
5179 (defcustom org-match-sexp-depth 3
5180 "Number of stacked braces for sub/superscript matching.
5181 This has to be set before loading org.el to be effective."
5182 :group 'org-export-translation ; ??????????????????????????/
5183 :type 'integer)
5185 (defun org-create-multibrace-regexp (left right n)
5186 "Create a regular expression which will match a balanced sexp.
5187 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5188 as single character strings.
5189 The regexp returned will match the entire expression including the
5190 delimiters. It will also define a single group which contains the
5191 match except for the outermost delimiters. The maximum depth of
5192 stacked delimiters is N. Escaping delimiters is not possible."
5193 (let* ((nothing (concat "[^" left right "]*?"))
5194 (or "\\|")
5195 (re nothing)
5196 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5197 (while (> n 1)
5198 (setq n (1- n)
5199 re (concat re or next)
5200 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5201 (concat left "\\(" re "\\)" right)))
5203 (defvar org-match-substring-regexp
5204 (concat
5205 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5206 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5207 "\\|"
5208 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5209 "\\|"
5210 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5211 "The regular expression matching a sub- or superscript.")
5213 (defvar org-match-substring-with-braces-regexp
5214 (concat
5215 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5216 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5217 "\\)")
5218 "The regular expression matching a sub- or superscript, forcing braces.")
5220 (defun org-make-link-regexps ()
5221 "Update the link regular expressions.
5222 This should be called after the variable `org-link-types' has changed."
5223 (setq org-link-types-re
5224 (concat
5225 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5226 org-link-re-with-space
5227 (concat
5228 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5229 "\\([^" org-non-link-chars " ]"
5230 "[^" org-non-link-chars "]*"
5231 "[^" org-non-link-chars " ]\\)>?")
5232 org-link-re-with-space2
5233 (concat
5234 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5235 "\\([^" org-non-link-chars " ]"
5236 "[^\t\n\r]*"
5237 "[^" org-non-link-chars " ]\\)>?")
5238 org-link-re-with-space3
5239 (concat
5240 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5241 "\\([^" org-non-link-chars " ]"
5242 "[^\t\n\r]*\\)")
5243 org-angle-link-re
5244 (concat
5245 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5246 "\\([^" org-non-link-chars " ]"
5247 "[^" org-non-link-chars "]*"
5248 "\\)>")
5249 org-plain-link-re
5250 (concat
5251 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5252 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5253 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5254 org-bracket-link-regexp
5255 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5256 org-bracket-link-analytic-regexp
5257 (concat
5258 "\\[\\["
5259 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5260 "\\([^]]+\\)"
5261 "\\]"
5262 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5263 "\\]")
5264 org-bracket-link-analytic-regexp++
5265 (concat
5266 "\\[\\["
5267 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5268 "\\([^]]+\\)"
5269 "\\]"
5270 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5271 "\\]")
5272 org-any-link-re
5273 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5274 org-angle-link-re "\\)\\|\\("
5275 org-plain-link-re "\\)")))
5277 (org-make-link-regexps)
5279 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5280 "Regular expression for fast time stamp matching.")
5281 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5282 "Regular expression for fast time stamp matching.")
5283 (defconst org-ts-regexp0
5284 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5285 "Regular expression matching time strings for analysis.
5286 This one does not require the space after the date, so it can be used
5287 on a string that terminates immediately after the date.")
5288 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5289 "Regular expression matching time strings for analysis.")
5290 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5291 "Regular expression matching time stamps, with groups.")
5292 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5293 "Regular expression matching time stamps (also [..]), with groups.")
5294 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5295 "Regular expression matching a time stamp range.")
5296 (defconst org-tr-regexp-both
5297 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5298 "Regular expression matching a time stamp range.")
5299 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5300 org-ts-regexp "\\)?")
5301 "Regular expression matching a time stamp or time stamp range.")
5302 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5303 org-ts-regexp-both "\\)?")
5304 "Regular expression matching a time stamp or time stamp range.
5305 The time stamps may be either active or inactive.")
5307 (defvar org-emph-face nil)
5309 (defun org-do-emphasis-faces (limit)
5310 "Run through the buffer and add overlays to emphasized strings."
5311 (let (rtn a)
5312 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5313 (if (not (= (char-after (match-beginning 3))
5314 (char-after (match-beginning 4))))
5315 (progn
5316 (setq rtn t)
5317 (setq a (assoc (match-string 3) org-emphasis-alist))
5318 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5319 'face
5320 (nth 1 a))
5321 (and (nth 4 a)
5322 (org-remove-flyspell-overlays-in
5323 (match-beginning 0) (match-end 0)))
5324 (add-text-properties (match-beginning 2) (match-end 2)
5325 '(font-lock-multiline t org-emphasis t))
5326 (when org-hide-emphasis-markers
5327 (add-text-properties (match-end 4) (match-beginning 5)
5328 '(invisible org-link))
5329 (add-text-properties (match-beginning 3) (match-end 3)
5330 '(invisible org-link)))))
5331 (backward-char 1))
5332 rtn))
5334 (defun org-emphasize (&optional char)
5335 "Insert or change an emphasis, i.e. a font like bold or italic.
5336 If there is an active region, change that region to a new emphasis.
5337 If there is no region, just insert the marker characters and position
5338 the cursor between them.
5339 CHAR should be either the marker character, or the first character of the
5340 HTML tag associated with that emphasis. If CHAR is a space, the means
5341 to remove the emphasis of the selected region.
5342 If char is not given (for example in an interactive call) it
5343 will be prompted for."
5344 (interactive)
5345 (let ((eal org-emphasis-alist) e det
5346 (erc org-emphasis-regexp-components)
5347 (prompt "")
5348 (string "") beg end move tag c s)
5349 (if (org-region-active-p)
5350 (setq beg (region-beginning) end (region-end)
5351 string (buffer-substring beg end))
5352 (setq move t))
5354 (while (setq e (pop eal))
5355 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5356 c (aref tag 0))
5357 (push (cons c (string-to-char (car e))) det)
5358 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5359 (substring tag 1)))))
5360 (setq det (nreverse det))
5361 (unless char
5362 (message "%s" (concat "Emphasis marker or tag:" prompt))
5363 (setq char (read-char-exclusive)))
5364 (setq char (or (cdr (assoc char det)) char))
5365 (if (equal char ?\ )
5366 (setq s "" move nil)
5367 (unless (assoc (char-to-string char) org-emphasis-alist)
5368 (error "No such emphasis marker: \"%c\"" char))
5369 (setq s (char-to-string char)))
5370 (while (and (> (length string) 1)
5371 (equal (substring string 0 1) (substring string -1))
5372 (assoc (substring string 0 1) org-emphasis-alist))
5373 (setq string (substring string 1 -1)))
5374 (setq string (concat s string s))
5375 (if beg (delete-region beg end))
5376 (unless (or (bolp)
5377 (string-match (concat "[" (nth 0 erc) "\n]")
5378 (char-to-string (char-before (point)))))
5379 (insert " "))
5380 (unless (or (eobp)
5381 (string-match (concat "[" (nth 1 erc) "\n]")
5382 (char-to-string (char-after (point)))))
5383 (insert " ") (backward-char 1))
5384 (insert string)
5385 (and move (backward-char 1))))
5387 (defconst org-nonsticky-props
5388 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5390 (defsubst org-rear-nonsticky-at (pos)
5391 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5393 (defun org-activate-plain-links (limit)
5394 "Run through the buffer and add overlays to links."
5395 (catch 'exit
5396 (let (f)
5397 (if (re-search-forward org-plain-link-re limit t)
5398 (progn
5399 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5400 (setq f (get-text-property (match-beginning 0) 'face))
5401 (if (or (eq f 'org-tag)
5402 (and (listp f) (memq 'org-tag f)))
5404 (add-text-properties (match-beginning 0) (match-end 0)
5405 (list 'mouse-face 'highlight
5406 'face 'org-link
5407 'keymap org-mouse-map))
5408 (org-rear-nonsticky-at (match-end 0)))
5409 t)))))
5411 (defun org-activate-code (limit)
5412 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5413 (progn
5414 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5415 (remove-text-properties (match-beginning 0) (match-end 0)
5416 '(display t invisible t intangible t))
5417 t)))
5419 (defcustom org-src-fontify-natively nil
5420 "When non-nil, fontify code in code blocks."
5421 :type 'boolean
5422 :version "24.1"
5423 :group 'org-appearance
5424 :group 'org-babel)
5426 (defcustom org-src-prevent-auto-filling nil
5427 "When non-nil, prevent auto-filling in src blocks."
5428 :type 'boolean
5429 :version "24.1"
5430 :group 'org-appearance
5431 :group 'org-babel)
5433 (defcustom org-allow-promoting-top-level-subtree nil
5434 "When non-nil, allow promoting a top level subtree.
5435 The leading star of the top level headline will be replaced
5436 by a #."
5437 :type 'boolean
5438 :version "24.1"
5439 :group 'org-appearance)
5441 (defun org-fontify-meta-lines-and-blocks (limit)
5442 (condition-case nil
5443 (org-fontify-meta-lines-and-blocks-1 limit)
5444 (error (message "org-mode fontification error"))))
5446 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5447 "Fontify #+ lines and blocks, in the correct ways."
5448 (let ((case-fold-search t))
5449 (if (re-search-forward
5450 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5451 limit t)
5452 (let ((beg (match-beginning 0))
5453 (block-start (match-end 0))
5454 (block-end nil)
5455 (lang (match-string 7))
5456 (beg1 (line-beginning-position 2))
5457 (dc1 (downcase (match-string 2)))
5458 (dc3 (downcase (match-string 3)))
5459 end end1 quoting block-type ovl)
5460 (cond
5461 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5462 ;; a single line of backend-specific content
5463 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5464 (remove-text-properties (match-beginning 0) (match-end 0)
5465 '(display t invisible t intangible t))
5466 (add-text-properties (match-beginning 1) (match-end 3)
5467 '(font-lock-fontified t face org-meta-line))
5468 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5469 '(font-lock-fontified t face org-block))
5470 ; for backend-specific code
5472 ((and (match-end 4) (equal dc3 "begin"))
5473 ;; Truly a block
5474 (setq block-type (downcase (match-string 5))
5475 quoting (member block-type org-protecting-blocks))
5476 (when (re-search-forward
5477 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5478 nil t) ;; on purpose, we look further than LIMIT
5479 (setq end (min (point-max) (match-end 0))
5480 end1 (min (point-max) (1- (match-beginning 0))))
5481 (setq block-end (match-beginning 0))
5482 (when quoting
5483 (remove-text-properties beg end
5484 '(display t invisible t intangible t)))
5485 (add-text-properties
5486 beg end
5487 '(font-lock-fontified t font-lock-multiline t))
5488 (add-text-properties beg beg1 '(face org-meta-line))
5489 (add-text-properties end1 (min (point-max) (1+ end))
5490 '(face org-meta-line)) ; for end_src
5491 (cond
5492 ((and lang (not (string= lang "")) org-src-fontify-natively)
5493 (org-src-font-lock-fontify-block lang block-start block-end)
5494 ;; remove old background overlays
5495 (mapc (lambda (ov)
5496 (if (eq (overlay-get ov 'face) 'org-block-background)
5497 (delete-overlay ov)))
5498 (overlays-at (/ (+ beg1 block-end) 2)))
5499 ;; add a background overlay
5500 (setq ovl (make-overlay beg1 block-end))
5501 (overlay-put ovl 'face 'org-block-background)
5502 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5503 (quoting
5504 (add-text-properties beg1 (min (point-max) (1+ end1))
5505 '(face org-block))) ; end of source block
5506 ((not org-fontify-quote-and-verse-blocks))
5507 ((string= block-type "quote")
5508 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5509 ((string= block-type "verse")
5510 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5511 (add-text-properties beg beg1 '(face org-block-begin-line))
5512 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5513 '(face org-block-end-line))
5515 ((member dc1 '("title:" "author:" "email:" "date:"))
5516 (add-text-properties
5517 beg (match-end 3)
5518 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5519 '(font-lock-fontified t invisible t)
5520 '(font-lock-fontified t face org-document-info-keyword)))
5521 (add-text-properties
5522 (match-beginning 6) (match-end 6)
5523 (if (string-equal dc1 "title:")
5524 '(font-lock-fontified t face org-document-title)
5525 '(font-lock-fontified t face org-document-info))))
5526 ((not (member (char-after beg) '(?\ ?\t)))
5527 ;; just any other in-buffer setting, but not indented
5528 (add-text-properties
5529 beg (match-end 0)
5530 '(font-lock-fontified t face org-meta-line))
5532 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5533 "orgtbl:" "tblfm:" "tblname:" "results:"
5534 "call:" "header:" "headers:" "name:"))
5535 (and (match-end 4) (equal dc3 "attr")))
5536 (add-text-properties
5537 beg (match-end 0)
5538 '(font-lock-fontified t face org-meta-line))
5540 ((member dc3 '(" " ""))
5541 (add-text-properties
5542 beg (match-end 0)
5543 '(font-lock-fontified t face font-lock-comment-face)))
5544 (t nil))))))
5546 (defun org-strip-protective-commas (beg end)
5547 "Strip protective commas between BEG and END in the current buffer."
5548 (interactive "r")
5549 (save-excursion
5550 (save-match-data
5551 (goto-char beg)
5552 (let ((front-line (save-excursion
5553 (re-search-forward
5554 "[^[:space:]]" end t)
5555 (goto-char (match-beginning 0))
5556 (current-column))))
5557 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5558 (goto-char (match-beginning 1))
5559 (when (= (current-column) front-line)
5560 (replace-match "" nil nil nil 1)))))))
5562 (defun org-activate-angle-links (limit)
5563 "Run through the buffer and add overlays to links."
5564 (if (re-search-forward org-angle-link-re limit t)
5565 (progn
5566 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5567 (add-text-properties (match-beginning 0) (match-end 0)
5568 (list 'mouse-face 'highlight
5569 'keymap org-mouse-map))
5570 (org-rear-nonsticky-at (match-end 0))
5571 t)))
5573 (defun org-activate-footnote-links (limit)
5574 "Run through the buffer and add overlays to footnotes."
5575 (let ((fn (org-footnote-next-reference-or-definition limit)))
5576 (when fn
5577 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5578 (org-remove-flyspell-overlays-in beg end)
5579 (add-text-properties beg end
5580 (list 'mouse-face 'highlight
5581 'keymap org-mouse-map
5582 'help-echo
5583 (if (= (point-at-bol) beg)
5584 "Footnote definition"
5585 "Footnote reference")
5586 'font-lock-fontified t
5587 'font-lock-multiline t
5588 'face 'org-footnote))))))
5590 (defun org-activate-bracket-links (limit)
5591 "Run through the buffer and add overlays to bracketed links."
5592 (if (re-search-forward org-bracket-link-regexp limit t)
5593 (let* ((help (concat "LINK: "
5594 (org-match-string-no-properties 1)))
5595 ;; FIXME: above we should remove the escapes.
5596 ;; but that requires another match, protecting match data,
5597 ;; a lot of overhead for font-lock.
5598 (ip (org-maybe-intangible
5599 (list 'invisible 'org-link
5600 'keymap org-mouse-map 'mouse-face 'highlight
5601 'font-lock-multiline t 'help-echo help)))
5602 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5603 'font-lock-multiline t 'help-echo help)))
5604 ;; We need to remove the invisible property here. Table narrowing
5605 ;; may have made some of this invisible.
5606 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5607 (remove-text-properties (match-beginning 0) (match-end 0)
5608 '(invisible nil))
5609 (if (match-end 3)
5610 (progn
5611 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5612 (org-rear-nonsticky-at (match-beginning 3))
5613 (add-text-properties (match-beginning 3) (match-end 3) vp)
5614 (org-rear-nonsticky-at (match-end 3))
5615 (add-text-properties (match-end 3) (match-end 0) ip)
5616 (org-rear-nonsticky-at (match-end 0)))
5617 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5618 (org-rear-nonsticky-at (match-beginning 1))
5619 (add-text-properties (match-beginning 1) (match-end 1) vp)
5620 (org-rear-nonsticky-at (match-end 1))
5621 (add-text-properties (match-end 1) (match-end 0) ip)
5622 (org-rear-nonsticky-at (match-end 0)))
5623 t)))
5625 (defun org-activate-dates (limit)
5626 "Run through the buffer and add overlays to dates."
5627 (if (re-search-forward org-tsr-regexp-both limit t)
5628 (progn
5629 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5630 (add-text-properties (match-beginning 0) (match-end 0)
5631 (list 'mouse-face 'highlight
5632 'keymap org-mouse-map))
5633 (org-rear-nonsticky-at (match-end 0))
5634 (when org-display-custom-times
5635 (if (match-end 3)
5636 (org-display-custom-time (match-beginning 3) (match-end 3)))
5637 (org-display-custom-time (match-beginning 1) (match-end 1)))
5638 t)))
5640 (defvar org-target-link-regexp nil
5641 "Regular expression matching radio targets in plain text.")
5642 (make-variable-buffer-local 'org-target-link-regexp)
5643 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5644 "Regular expression matching a link target.")
5645 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5646 "Regular expression matching a radio target.")
5647 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5648 "Regular expression matching any target.")
5650 (defun org-activate-target-links (limit)
5651 "Run through the buffer and add overlays to target matches."
5652 (when org-target-link-regexp
5653 (let ((case-fold-search t))
5654 (if (re-search-forward org-target-link-regexp limit t)
5655 (progn
5656 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5657 (add-text-properties (match-beginning 0) (match-end 0)
5658 (list 'mouse-face 'highlight
5659 'keymap org-mouse-map
5660 'help-echo "Radio target link"
5661 'org-linked-text t))
5662 (org-rear-nonsticky-at (match-end 0))
5663 t)))))
5665 (defun org-update-radio-target-regexp ()
5666 "Find all radio targets in this file and update the regular expression."
5667 (interactive)
5668 (when (memq 'radio org-activate-links)
5669 (setq org-target-link-regexp
5670 (org-make-target-link-regexp (org-all-targets 'radio)))
5671 (org-restart-font-lock)))
5673 (defun org-hide-wide-columns (limit)
5674 (let (s e)
5675 (setq s (text-property-any (point) (or limit (point-max))
5676 'org-cwidth t))
5677 (when s
5678 (setq e (next-single-property-change s 'org-cwidth))
5679 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5680 (goto-char e)
5681 t)))
5683 (defvar org-latex-and-specials-regexp nil
5684 "Regular expression for highlighting export special stuff.")
5685 (defvar org-match-substring-regexp)
5686 (defvar org-match-substring-with-braces-regexp)
5688 ;; This should be with the exporter code, but we also use if for font-locking
5689 (defconst org-export-html-special-string-regexps
5690 '(("\\\\-" . "&shy;")
5691 ("---\\([^-]\\)" . "&mdash;\\1")
5692 ("--\\([^-]\\)" . "&ndash;\\1")
5693 ("\\.\\.\\." . "&hellip;"))
5694 "Regular expressions for special string conversion.")
5697 (defun org-compute-latex-and-specials-regexp ()
5698 "Compute regular expression for stuff treated specially by exporters."
5699 (if (not org-highlight-latex-fragments-and-specials)
5700 (org-set-local 'org-latex-and-specials-regexp nil)
5701 (require 'org-exp)
5702 (let*
5703 ((matchers (plist-get org-format-latex-options :matchers))
5704 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5705 org-latex-regexps)))
5706 (org-export-allow-BIND nil)
5707 (options (org-combine-plists (org-default-export-plist)
5708 (org-infile-export-plist)))
5709 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5710 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5711 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5712 (org-export-html-expand (plist-get options :expand-quoted-html))
5713 (org-export-with-special-strings (plist-get options :special-strings))
5714 (re-sub
5715 (cond
5716 ((equal org-export-with-sub-superscripts '{})
5717 (list org-match-substring-with-braces-regexp))
5718 (org-export-with-sub-superscripts
5719 (list org-match-substring-regexp))
5720 (t nil)))
5721 (re-latex
5722 (if org-export-with-LaTeX-fragments
5723 (mapcar (lambda (x) (nth 1 x)) latexs)))
5724 (re-macros
5725 (if org-export-with-TeX-macros
5726 (list (concat "\\\\"
5727 (regexp-opt
5728 (append
5730 (delq nil
5731 (mapcar 'car-safe
5732 (append org-entities-user
5733 org-entities)))
5734 (if (boundp 'org-latex-entities)
5735 (mapcar (lambda (x)
5736 (or (car-safe x) x))
5737 org-latex-entities)
5738 nil))
5739 'words))) ; FIXME
5741 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5742 (re-special (if org-export-with-special-strings
5743 (mapcar (lambda (x) (car x))
5744 org-export-html-special-string-regexps)))
5745 (re-rest
5746 (delq nil
5747 (list
5748 (if org-export-html-expand "@<[^>\n]+>")
5749 ))))
5750 (org-set-local
5751 'org-latex-and-specials-regexp
5752 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5753 re-rest) "\\|")))))
5755 (defun org-do-latex-and-special-faces (limit)
5756 "Run through the buffer and add overlays to links."
5757 (when org-latex-and-specials-regexp
5758 (let (rtn d)
5759 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5760 limit t))
5761 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5762 'face))
5763 '(org-code org-verbatim underline)))
5764 (progn
5765 (setq rtn t
5766 d (cond ((member (char-after (1+ (match-beginning 0)))
5767 '(?_ ?^)) 1)
5768 (t 0)))
5769 (font-lock-prepend-text-property
5770 (+ d (match-beginning 0)) (match-end 0)
5771 'face 'org-latex-and-export-specials)
5772 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5773 '(font-lock-multiline t)))))
5774 rtn)))
5776 (defun org-restart-font-lock ()
5777 "Restart `font-lock-mode', to force refontification."
5778 (when (and (boundp 'font-lock-mode) font-lock-mode)
5779 (font-lock-mode -1)
5780 (font-lock-mode 1)))
5782 (defun org-all-targets (&optional radio)
5783 "Return a list of all targets in this file.
5784 With optional argument RADIO, only find radio targets."
5785 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5786 rtn)
5787 (save-excursion
5788 (goto-char (point-min))
5789 (while (re-search-forward re nil t)
5790 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5791 rtn)))
5793 (defun org-make-target-link-regexp (targets)
5794 "Make regular expression matching all strings in TARGETS.
5795 The regular expression finds the targets also if there is a line break
5796 between words."
5797 (and targets
5798 (concat
5799 "\\<\\("
5800 (mapconcat
5801 (lambda (x)
5802 (setq x (regexp-quote x))
5803 (while (string-match " +" x)
5804 (setq x (replace-match "\\s-+" t t x)))
5806 targets
5807 "\\|")
5808 "\\)\\>")))
5810 (defun org-activate-tags (limit)
5811 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5812 (progn
5813 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5814 (add-text-properties (match-beginning 1) (match-end 1)
5815 (list 'mouse-face 'highlight
5816 'keymap org-mouse-map))
5817 (org-rear-nonsticky-at (match-end 1))
5818 t)))
5820 (defun org-outline-level ()
5821 "Compute the outline level of the heading at point.
5822 This function assumes that the cursor is at the beginning of a line matched
5823 by `outline-regexp'. Otherwise it returns garbage.
5824 If this is called at a normal headline, the level is the number of stars.
5825 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5826 (save-excursion
5827 (looking-at org-outline-regexp)
5828 (1- (- (match-end 0) (match-beginning 0)))))
5830 (defvar org-font-lock-keywords nil)
5832 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5833 "Regular expression matching a property line.")
5835 (defvar org-font-lock-hook nil
5836 "Functions to be called for special font lock stuff.")
5838 (defvar org-font-lock-set-keywords-hook nil
5839 "Functions that can manipulate `org-font-lock-extra-keywords'.
5840 This is called after `org-font-lock-extra-keywords' is defined, but before
5841 it is installed to be used by font lock. This can be useful if something
5842 needs to be inserted at a specific position in the font-lock sequence.")
5844 (defun org-font-lock-hook (limit)
5845 (run-hook-with-args 'org-font-lock-hook limit))
5847 (defun org-set-font-lock-defaults ()
5848 (let* ((em org-fontify-emphasized-text)
5849 (lk org-activate-links)
5850 (org-font-lock-extra-keywords
5851 (list
5852 ;; Call the hook
5853 '(org-font-lock-hook)
5854 ;; Headlines
5855 `(,(if org-fontify-whole-heading-line
5856 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5857 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5858 (1 (org-get-level-face 1))
5859 (2 (org-get-level-face 2))
5860 (3 (org-get-level-face 3)))
5861 ;; Table lines
5862 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5863 (1 'org-table t))
5864 ;; Table internals
5865 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5866 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5867 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5868 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5869 ;; Drawers
5870 (list org-drawer-regexp '(0 'org-special-keyword t))
5871 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5872 ;; Properties
5873 (list org-property-re
5874 '(1 'org-special-keyword t)
5875 '(3 'org-property-value t))
5876 ;; Links
5877 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5878 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5879 (if (memq 'plain lk) '(org-activate-plain-links))
5880 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5881 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5882 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5883 (if (memq 'footnote lk) '(org-activate-footnote-links))
5884 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5885 '(org-hide-wide-columns (0 nil append))
5886 ;; TODO keyword
5887 (list (format org-heading-keyword-regexp-format
5888 org-todo-regexp)
5889 '(2 (org-get-todo-face 2) t))
5890 ;; DONE
5891 (if org-fontify-done-headline
5892 (list (format org-heading-keyword-regexp-format
5893 (concat
5894 "\\(?:"
5895 (mapconcat 'regexp-quote org-done-keywords "\\|")
5896 "\\)"))
5897 '(2 'org-headline-done t))
5898 nil)
5899 ;; Priorities
5900 '(org-font-lock-add-priority-faces)
5901 ;; Tags
5902 '(org-font-lock-add-tag-faces)
5903 ;; Special keywords
5904 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5905 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5906 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5907 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5908 ;; Emphasis
5909 (if em
5910 (if (featurep 'xemacs)
5911 '(org-do-emphasis-faces (0 nil append))
5912 '(org-do-emphasis-faces)))
5913 ;; Checkboxes
5914 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5915 1 'org-checkbox prepend)
5916 (if (cdr (assq 'checkbox org-list-automatic-rules))
5917 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5918 (0 (org-get-checkbox-statistics-face) t)))
5919 ;; Description list items
5920 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5921 1 'org-list-dt prepend)
5922 ;; ARCHIVEd headings
5923 (list (concat
5924 org-outline-regexp-bol
5925 "\\(.*:" org-archive-tag ":.*\\)")
5926 '(1 'org-archived prepend))
5927 ;; Specials
5928 '(org-do-latex-and-special-faces)
5929 '(org-fontify-entities)
5930 '(org-raise-scripts)
5931 ;; Code
5932 '(org-activate-code (1 'org-code t))
5933 ;; COMMENT
5934 (list (format org-heading-keyword-regexp-format
5935 (concat "\\("
5936 org-comment-string "\\|" org-quote-string
5937 "\\)"))
5938 '(2 'org-special-keyword t))
5939 '("^#.*" (0 'font-lock-comment-face t))
5940 ;; Blocks and meta lines
5941 '(org-fontify-meta-lines-and-blocks)
5943 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5944 (run-hooks 'org-font-lock-set-keywords-hook)
5945 ;; Now set the full font-lock-keywords
5946 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5947 (org-set-local 'font-lock-defaults
5948 '(org-font-lock-keywords t nil nil backward-paragraph))
5949 (kill-local-variable 'font-lock-keywords) nil))
5951 (defun org-toggle-pretty-entities ()
5952 "Toggle the composition display of entities as UTF8 characters."
5953 (interactive)
5954 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5955 (org-restart-font-lock)
5956 (if org-pretty-entities
5957 (message "Entities are displayed as UTF8 characters")
5958 (save-restriction
5959 (widen)
5960 (org-decompose-region (point-min) (point-max))
5961 (message "Entities are displayed plain"))))
5963 (defun org-fontify-entities (limit)
5964 "Find an entity to fontify."
5965 (let (ee)
5966 (when org-pretty-entities
5967 (catch 'match
5968 (while (re-search-forward
5969 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5970 limit t)
5971 (if (and (not (org-in-indented-comment-line))
5972 (setq ee (org-entity-get (match-string 1)))
5973 (= (length (nth 6 ee)) 1))
5974 (let*
5975 ((end (if (equal (match-string 2) "{}")
5976 (match-end 2)
5977 (match-end 1))))
5978 (add-text-properties
5979 (match-beginning 0) end
5980 (list 'font-lock-fontified t))
5981 (compose-region (match-beginning 0) end
5982 (nth 6 ee) nil)
5983 (backward-char 1)
5984 (throw 'match t))))
5985 nil))))
5987 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5988 "Fontify string S like in Org-mode."
5989 (with-temp-buffer
5990 (insert s)
5991 (let ((org-odd-levels-only odd-levels))
5992 (org-mode)
5993 (font-lock-fontify-buffer)
5994 (buffer-string))))
5996 (defvar org-m nil)
5997 (defvar org-l nil)
5998 (defvar org-f nil)
5999 (defun org-get-level-face (n)
6000 "Get the right face for match N in font-lock matching of headlines."
6001 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6002 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6003 (if org-cycle-level-faces
6004 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6005 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6006 (cond
6007 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6008 ((eq n 2) org-f)
6009 (t (if org-level-color-stars-only nil org-f))))
6012 (defun org-get-todo-face (kwd)
6013 "Get the right face for a TODO keyword KWD.
6014 If KWD is a number, get the corresponding match group."
6015 (if (numberp kwd) (setq kwd (match-string kwd)))
6016 (or (org-face-from-face-or-color
6017 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6018 (and (member kwd org-done-keywords) 'org-done)
6019 'org-todo))
6021 (defun org-face-from-face-or-color (context inherit face-or-color)
6022 "Create a face list that inherits INHERIT, but sets the foreground color.
6023 When FACE-OR-COLOR is not a string, just return it."
6024 (if (stringp face-or-color)
6025 (list :inherit inherit
6026 (cdr (assoc context org-faces-easy-properties))
6027 face-or-color)
6028 face-or-color))
6030 (defun org-font-lock-add-tag-faces (limit)
6031 "Add the special tag faces."
6032 (when (and org-tag-faces org-tags-special-faces-re)
6033 (while (re-search-forward org-tags-special-faces-re limit t)
6034 (add-text-properties (match-beginning 1) (match-end 1)
6035 (list 'face (org-get-tag-face 1)
6036 'font-lock-fontified t))
6037 (backward-char 1))))
6039 (defun org-font-lock-add-priority-faces (limit)
6040 "Add the special priority faces."
6041 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6042 (add-text-properties
6043 (match-beginning 0) (match-end 0)
6044 (list 'face (or (org-face-from-face-or-color
6045 'priority 'org-special-keyword
6046 (cdr (assoc (char-after (match-beginning 1))
6047 org-priority-faces)))
6048 'org-special-keyword)
6049 'font-lock-fontified t))))
6051 (defun org-get-tag-face (kwd)
6052 "Get the right face for a TODO keyword KWD.
6053 If KWD is a number, get the corresponding match group."
6054 (if (numberp kwd) (setq kwd (match-string kwd)))
6055 (or (org-face-from-face-or-color
6056 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6057 'org-tag))
6059 (defun org-unfontify-region (beg end &optional maybe_loudly)
6060 "Remove fontification and activation overlays from links."
6061 (font-lock-default-unfontify-region beg end)
6062 (let* ((buffer-undo-list t)
6063 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6064 (inhibit-modification-hooks t)
6065 deactivate-mark buffer-file-name buffer-file-truename)
6066 (org-decompose-region beg end)
6067 (remove-text-properties beg end
6068 '(mouse-face t keymap t org-linked-text t
6069 invisible t intangible t
6070 org-no-flyspell t org-emphasis t))
6071 (org-remove-font-lock-display-properties beg end)))
6073 (defconst org-script-display '(((raise -0.3) (height 0.7))
6074 ((raise 0.3) (height 0.7))
6075 ((raise -0.5))
6076 ((raise 0.5)))
6077 "Display properties for showing superscripts and subscripts.")
6079 (defun org-remove-font-lock-display-properties (beg end)
6080 "Remove specific display properties that have been added by font lock.
6081 The will remove the raise properties that are used to show superscripts
6082 and subscripts."
6083 (let (next prop)
6084 (while (< beg end)
6085 (setq next (next-single-property-change beg 'display nil end)
6086 prop (get-text-property beg 'display))
6087 (if (member prop org-script-display)
6088 (put-text-property beg next 'display nil))
6089 (setq beg next))))
6091 (defun org-raise-scripts (limit)
6092 "Add raise properties to sub/superscripts."
6093 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6094 (if (re-search-forward
6095 (if (eq org-use-sub-superscripts t)
6096 org-match-substring-regexp
6097 org-match-substring-with-braces-regexp)
6098 limit t)
6099 (let* ((pos (point)) table-p comment-p
6100 (mpos (match-beginning 3))
6101 (emph-p (get-text-property mpos 'org-emphasis))
6102 (link-p (get-text-property mpos 'mouse-face))
6103 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6104 (goto-char (point-at-bol))
6105 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6106 comment-p (org-looking-at-p "[ \t]*#"))
6107 (goto-char pos)
6108 ;; FIXME: Should we go back one character here, for a_b^c
6109 ;; (goto-char (1- pos)) ;????????????????????
6110 (if (or comment-p emph-p link-p keyw-p)
6112 (put-text-property (match-beginning 3) (match-end 0)
6113 'display
6114 (if (equal (char-after (match-beginning 2)) ?^)
6115 (nth (if table-p 3 1) org-script-display)
6116 (nth (if table-p 2 0) org-script-display)))
6117 (add-text-properties (match-beginning 2) (match-end 2)
6118 (list 'invisible t
6119 'org-dwidth t 'org-dwidth-n 1))
6120 (if (and (eq (char-after (match-beginning 3)) ?{)
6121 (eq (char-before (match-end 3)) ?}))
6122 (progn
6123 (add-text-properties
6124 (match-beginning 3) (1+ (match-beginning 3))
6125 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6126 (add-text-properties
6127 (1- (match-end 3)) (match-end 3)
6128 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6129 t)))))
6131 ;;;; Visibility cycling, including org-goto and indirect buffer
6133 ;;; Cycling
6135 (defvar org-cycle-global-status nil)
6136 (make-variable-buffer-local 'org-cycle-global-status)
6137 (defvar org-cycle-subtree-status nil)
6138 (make-variable-buffer-local 'org-cycle-subtree-status)
6140 ;;;###autoload
6142 (defvar org-inlinetask-min-level)
6144 (defun org-cycle (&optional arg)
6145 "TAB-action and visibility cycling for Org-mode.
6147 This is the command invoked in Org-mode by the TAB key. Its main purpose
6148 is outline visibility cycling, but it also invokes other actions
6149 in special contexts.
6151 - When this function is called with a prefix argument, rotate the entire
6152 buffer through 3 states (global cycling)
6153 1. OVERVIEW: Show only top-level headlines.
6154 2. CONTENTS: Show all headlines of all levels, but no body text.
6155 3. SHOW ALL: Show everything.
6156 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6157 determined by the variable `org-startup-folded', and by any VISIBILITY
6158 properties in the buffer.
6159 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6160 including any drawers.
6162 - When inside a table, re-align the table and move to the next field.
6164 - When point is at the beginning of a headline, rotate the subtree started
6165 by this line through 3 different states (local cycling)
6166 1. FOLDED: Only the main headline is shown.
6167 2. CHILDREN: The main headline and the direct children are shown.
6168 From this state, you can move to one of the children
6169 and zoom in further.
6170 3. SUBTREE: Show the entire subtree, including body text.
6171 If there is no subtree, switch directly from CHILDREN to FOLDED.
6173 - When point is at the beginning of an empty headline and the variable
6174 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6175 of the headline by demoting and promoting it to likely levels. This
6176 speeds up creation document structure by pressing TAB once or several
6177 times right after creating a new headline.
6179 - When there is a numeric prefix, go up to a heading with level ARG, do
6180 a `show-subtree' and return to the previous cursor position. If ARG
6181 is negative, go up that many levels.
6183 - When point is not at the beginning of a headline, execute the global
6184 binding for TAB, which is re-indenting the line. See the option
6185 `org-cycle-emulate-tab' for details.
6187 - Special case: if point is at the beginning of the buffer and there is
6188 no headline in line 1, this function will act as if called with prefix arg
6189 (C-u TAB, same as S-TAB) also when called without prefix arg.
6190 But only if also the variable `org-cycle-global-at-bob' is t."
6191 (interactive "P")
6192 (org-load-modules-maybe)
6193 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6194 (and org-cycle-level-after-item/entry-creation
6195 (or (org-cycle-level)
6196 (org-cycle-item-indentation))))
6197 (let* ((limit-level
6198 (or org-cycle-max-level
6199 (and (boundp 'org-inlinetask-min-level)
6200 org-inlinetask-min-level
6201 (1- org-inlinetask-min-level))))
6202 (nstars (and limit-level
6203 (if org-odd-levels-only
6204 (and limit-level (1- (* limit-level 2)))
6205 limit-level)))
6206 (org-outline-regexp
6207 (if (not (derived-mode-p 'org-mode))
6208 outline-regexp
6209 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6210 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6211 (not (looking-at org-outline-regexp))))
6212 (org-cycle-hook
6213 (if bob-special
6214 (delq 'org-optimize-window-after-visibility-change
6215 (copy-sequence org-cycle-hook))
6216 org-cycle-hook))
6217 (pos (point)))
6219 (if (or bob-special (equal arg '(4)))
6220 ;; special case: use global cycling
6221 (setq arg t))
6223 (cond
6225 ((equal arg '(16))
6226 (setq last-command 'dummy)
6227 (org-set-startup-visibility)
6228 (message "Startup visibility, plus VISIBILITY properties"))
6230 ((equal arg '(64))
6231 (show-all)
6232 (message "Entire buffer visible, including drawers"))
6234 ;; Table: enter it or move to the next field.
6235 ((org-at-table-p 'any)
6236 (if (org-at-table.el-p)
6237 (message "Use C-c ' to edit table.el tables")
6238 (if arg (org-table-edit-field t)
6239 (org-table-justify-field-maybe)
6240 (call-interactively 'org-table-next-field))))
6242 ((run-hook-with-args-until-success
6243 'org-tab-after-check-for-table-hook))
6245 ;; Global cycling: delegate to `org-cycle-internal-global'.
6246 ((eq arg t) (org-cycle-internal-global))
6248 ;; Drawers: delegate to `org-flag-drawer'.
6249 ((and org-drawers org-drawer-regexp
6250 (save-excursion
6251 (beginning-of-line 1)
6252 (looking-at org-drawer-regexp)))
6253 (org-flag-drawer ; toggle block visibility
6254 (not (get-char-property (match-end 0) 'invisible))))
6256 ;; Show-subtree, ARG levels up from here.
6257 ((integerp arg)
6258 (save-excursion
6259 (org-back-to-heading)
6260 (outline-up-heading (if (< arg 0) (- arg)
6261 (- (funcall outline-level) arg)))
6262 (org-show-subtree)))
6264 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6265 ((and (featurep 'org-inlinetask)
6266 (org-inlinetask-at-task-p)
6267 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6268 (org-inlinetask-toggle-visibility))
6270 ((org-try-cdlatex-tab))
6272 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6273 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6274 (save-excursion (beginning-of-line 1)
6275 (looking-at org-outline-regexp)))
6276 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6277 (org-cycle-internal-local))
6279 ;; From there: TAB emulation and template completion.
6280 (buffer-read-only (org-back-to-heading))
6282 ((run-hook-with-args-until-success
6283 'org-tab-after-check-for-cycling-hook))
6285 ((org-try-structure-completion))
6287 ((run-hook-with-args-until-success
6288 'org-tab-before-tab-emulation-hook))
6290 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6291 (or (not (bolp))
6292 (not (looking-at org-outline-regexp))))
6293 (call-interactively (global-key-binding "\t")))
6295 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6296 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6297 (or (and (eq org-cycle-emulate-tab 'white)
6298 (= (match-end 0) (point-at-eol)))
6299 (and (eq org-cycle-emulate-tab 'whitestart)
6300 (>= (match-end 0) pos))))
6302 (eq org-cycle-emulate-tab t))
6303 (call-interactively (global-key-binding "\t")))
6305 (t (save-excursion
6306 (org-back-to-heading)
6307 (org-cycle)))))))
6309 (defun org-cycle-internal-global ()
6310 "Do the global cycling action."
6311 ;; Hack to avoid display of messages for .org attachments in Gnus
6312 (let ((ga (string-match "\\*fontification" (buffer-name))))
6313 (cond
6314 ((and (eq last-command this-command)
6315 (eq org-cycle-global-status 'overview))
6316 ;; We just created the overview - now do table of contents
6317 ;; This can be slow in very large buffers, so indicate action
6318 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6319 (unless ga (message "CONTENTS..."))
6320 (org-content)
6321 (unless ga (message "CONTENTS...done"))
6322 (setq org-cycle-global-status 'contents)
6323 (run-hook-with-args 'org-cycle-hook 'contents))
6325 ((and (eq last-command this-command)
6326 (eq org-cycle-global-status 'contents))
6327 ;; We just showed the table of contents - now show everything
6328 (run-hook-with-args 'org-pre-cycle-hook 'all)
6329 (show-all)
6330 (unless ga (message "SHOW ALL"))
6331 (setq org-cycle-global-status 'all)
6332 (run-hook-with-args 'org-cycle-hook 'all))
6335 ;; Default action: go to overview
6336 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6337 (org-overview)
6338 (unless ga (message "OVERVIEW"))
6339 (setq org-cycle-global-status 'overview)
6340 (run-hook-with-args 'org-cycle-hook 'overview)))))
6342 (defun org-cycle-internal-local ()
6343 "Do the local cycling action."
6344 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6345 ;; First, determine end of headline (EOH), end of subtree or item
6346 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6347 (save-excursion
6348 (if (org-at-item-p)
6349 (progn
6350 (beginning-of-line)
6351 (setq struct (org-list-struct))
6352 (setq eoh (point-at-eol))
6353 (setq eos (org-list-get-item-end-before-blank (point) struct))
6354 (setq has-children (org-list-has-child-p (point) struct)))
6355 (org-back-to-heading)
6356 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6357 (setq eos (save-excursion
6358 (org-end-of-subtree t)
6359 (unless (eobp)
6360 (skip-chars-forward " \t\n"))
6361 (if (eobp) (point) (1- (point)))))
6362 (setq has-children
6363 (or (save-excursion
6364 (let ((level (funcall outline-level)))
6365 (outline-next-heading)
6366 (and (org-at-heading-p t)
6367 (> (funcall outline-level) level))))
6368 (save-excursion
6369 (org-list-search-forward (org-item-beginning-re) eos t)))))
6370 ;; Determine end invisible part of buffer (EOL)
6371 (beginning-of-line 2)
6372 ;; XEmacs doesn't have `next-single-char-property-change'
6373 (if (featurep 'xemacs)
6374 (while (and (not (eobp)) ;; this is like `next-line'
6375 (get-char-property (1- (point)) 'invisible))
6376 (beginning-of-line 2))
6377 (while (and (not (eobp)) ;; this is like `next-line'
6378 (get-char-property (1- (point)) 'invisible))
6379 (goto-char (next-single-char-property-change (point) 'invisible))
6380 (and (eolp) (beginning-of-line 2))))
6381 (setq eol (point)))
6382 ;; Find out what to do next and set `this-command'
6383 (cond
6384 ((= eos eoh)
6385 ;; Nothing is hidden behind this heading
6386 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6387 (message "EMPTY ENTRY")
6388 (setq org-cycle-subtree-status nil)
6389 (save-excursion
6390 (goto-char eos)
6391 (outline-next-heading)
6392 (if (outline-invisible-p) (org-flag-heading nil))))
6393 ((and (or (>= eol eos)
6394 (not (string-match "\\S-" (buffer-substring eol eos))))
6395 (or has-children
6396 (not (setq children-skipped
6397 org-cycle-skip-children-state-if-no-children))))
6398 ;; Entire subtree is hidden in one line: children view
6399 (run-hook-with-args 'org-pre-cycle-hook 'children)
6400 (if (org-at-item-p)
6401 (org-list-set-item-visibility (point-at-bol) struct 'children)
6402 (org-show-entry)
6403 (org-with-limited-levels (show-children))
6404 ;; FIXME: This slows down the func way too much.
6405 ;; How keep drawers hidden in subtree anyway?
6406 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6407 ;; (org-cycle-hide-drawers 'subtree))
6409 ;; Fold every list in subtree to top-level items.
6410 (when (eq org-cycle-include-plain-lists 'integrate)
6411 (save-excursion
6412 (org-back-to-heading)
6413 (while (org-list-search-forward (org-item-beginning-re) eos t)
6414 (beginning-of-line 1)
6415 (let* ((struct (org-list-struct))
6416 (prevs (org-list-prevs-alist struct))
6417 (end (org-list-get-bottom-point struct)))
6418 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6419 (org-list-get-all-items (point) struct prevs))
6420 (goto-char end))))))
6421 (message "CHILDREN")
6422 (save-excursion
6423 (goto-char eos)
6424 (outline-next-heading)
6425 (if (outline-invisible-p) (org-flag-heading nil)))
6426 (setq org-cycle-subtree-status 'children)
6427 (run-hook-with-args 'org-cycle-hook 'children))
6428 ((or children-skipped
6429 (and (eq last-command this-command)
6430 (eq org-cycle-subtree-status 'children)))
6431 ;; We just showed the children, or no children are there,
6432 ;; now show everything.
6433 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6434 (outline-flag-region eoh eos nil)
6435 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6436 (setq org-cycle-subtree-status 'subtree)
6437 (run-hook-with-args 'org-cycle-hook 'subtree))
6439 ;; Default action: hide the subtree.
6440 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6441 (outline-flag-region eoh eos t)
6442 (message "FOLDED")
6443 (setq org-cycle-subtree-status 'folded)
6444 (run-hook-with-args 'org-cycle-hook 'folded)))))
6446 ;;;###autoload
6447 (defun org-global-cycle (&optional arg)
6448 "Cycle the global visibility. For details see `org-cycle'.
6449 With \\[universal-argument] prefix arg, switch to startup visibility.
6450 With a numeric prefix, show all headlines up to that level."
6451 (interactive "P")
6452 (let ((org-cycle-include-plain-lists
6453 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6454 (cond
6455 ((integerp arg)
6456 (show-all)
6457 (hide-sublevels arg)
6458 (setq org-cycle-global-status 'contents))
6459 ((equal arg '(4))
6460 (org-set-startup-visibility)
6461 (message "Startup visibility, plus VISIBILITY properties."))
6463 (org-cycle '(4))))))
6465 (defun org-set-startup-visibility ()
6466 "Set the visibility required by startup options and properties."
6467 (cond
6468 ((eq org-startup-folded t)
6469 (org-cycle '(4)))
6470 ((eq org-startup-folded 'content)
6471 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6472 (org-cycle '(4)) (org-cycle '(4)))))
6473 (unless (eq org-startup-folded 'showeverything)
6474 (if org-hide-block-startup (org-hide-block-all))
6475 (org-set-visibility-according-to-property 'no-cleanup)
6476 (org-cycle-hide-archived-subtrees 'all)
6477 (org-cycle-hide-drawers 'all)
6478 (org-cycle-show-empty-lines t)))
6480 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6481 "Switch subtree visibilities according to :VISIBILITY: property."
6482 (interactive)
6483 (let (org-show-entry-below state)
6484 (save-excursion
6485 (goto-char (point-min))
6486 (while (re-search-forward
6487 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6488 nil t)
6489 (setq state (match-string 1))
6490 (save-excursion
6491 (org-back-to-heading t)
6492 (hide-subtree)
6493 (org-reveal)
6494 (cond
6495 ((equal state '("fold" "folded"))
6496 (hide-subtree))
6497 ((equal state "children")
6498 (org-show-hidden-entry)
6499 (show-children))
6500 ((equal state "content")
6501 (save-excursion
6502 (save-restriction
6503 (org-narrow-to-subtree)
6504 (org-content))))
6505 ((member state '("all" "showall"))
6506 (show-subtree)))))
6507 (unless no-cleanup
6508 (org-cycle-hide-archived-subtrees 'all)
6509 (org-cycle-hide-drawers 'all)
6510 (org-cycle-show-empty-lines 'all)))))
6512 ;; This function uses outline-regexp instead of the more fundamental
6513 ;; org-outline-regexp so that org-cycle-global works outside of Org
6514 ;; buffers, where outline-regexp is needed.
6515 (defun org-overview ()
6516 "Switch to overview mode, showing only top-level headlines.
6517 Really, this shows all headlines with level equal or greater than the level
6518 of the first headline in the buffer. This is important, because if the
6519 first headline is not level one, then (hide-sublevels 1) gives confusing
6520 results."
6521 (interactive)
6522 (let ((level (save-excursion
6523 (goto-char (point-min))
6524 (if (re-search-forward (concat "^" outline-regexp) nil t)
6525 (progn
6526 (goto-char (match-beginning 0))
6527 (funcall outline-level))))))
6528 (and level (hide-sublevels level))))
6530 (defun org-content (&optional arg)
6531 "Show all headlines in the buffer, like a table of contents.
6532 With numerical argument N, show content up to level N."
6533 (interactive "P")
6534 (save-excursion
6535 ;; Visit all headings and show their offspring
6536 (and (integerp arg) (org-overview))
6537 (goto-char (point-max))
6538 (catch 'exit
6539 (while (and (progn (condition-case nil
6540 (outline-previous-visible-heading 1)
6541 (error (goto-char (point-min))))
6543 (looking-at org-outline-regexp))
6544 (if (integerp arg)
6545 (show-children (1- arg))
6546 (show-branches))
6547 (if (bobp) (throw 'exit nil))))))
6550 (defun org-optimize-window-after-visibility-change (state)
6551 "Adjust the window after a change in outline visibility.
6552 This function is the default value of the hook `org-cycle-hook'."
6553 (when (get-buffer-window (current-buffer))
6554 (cond
6555 ((eq state 'content) nil)
6556 ((eq state 'all) nil)
6557 ((eq state 'folded) nil)
6558 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6559 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6561 (defun org-remove-empty-overlays-at (pos)
6562 "Remove outline overlays that do not contain non-white stuff."
6563 (mapc
6564 (lambda (o)
6565 (and (eq 'outline (overlay-get o 'invisible))
6566 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6567 (overlay-end o))))
6568 (delete-overlay o)))
6569 (overlays-at pos)))
6571 (defun org-clean-visibility-after-subtree-move ()
6572 "Fix visibility issues after moving a subtree."
6573 ;; First, find a reasonable region to look at:
6574 ;; Start two siblings above, end three below
6575 (let* ((beg (save-excursion
6576 (and (org-get-last-sibling)
6577 (org-get-last-sibling))
6578 (point)))
6579 (end (save-excursion
6580 (and (org-get-next-sibling)
6581 (org-get-next-sibling)
6582 (org-get-next-sibling))
6583 (if (org-at-heading-p)
6584 (point-at-eol)
6585 (point))))
6586 (level (looking-at "\\*+"))
6587 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6588 (save-excursion
6589 (save-restriction
6590 (narrow-to-region beg end)
6591 (when re
6592 ;; Properly fold already folded siblings
6593 (goto-char (point-min))
6594 (while (re-search-forward re nil t)
6595 (if (and (not (outline-invisible-p))
6596 (save-excursion
6597 (goto-char (point-at-eol)) (outline-invisible-p)))
6598 (hide-entry))))
6599 (org-cycle-show-empty-lines 'overview)
6600 (org-cycle-hide-drawers 'overview)))))
6602 (defun org-cycle-show-empty-lines (state)
6603 "Show empty lines above all visible headlines.
6604 The region to be covered depends on STATE when called through
6605 `org-cycle-hook'. Lisp program can use t for STATE to get the
6606 entire buffer covered. Note that an empty line is only shown if there
6607 are at least `org-cycle-separator-lines' empty lines before the headline."
6608 (when (not (= org-cycle-separator-lines 0))
6609 (save-excursion
6610 (let* ((n (abs org-cycle-separator-lines))
6611 (re (cond
6612 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6613 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6614 (t (let ((ns (number-to-string (- n 2))))
6615 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6616 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6617 beg end b e)
6618 (cond
6619 ((memq state '(overview contents t))
6620 (setq beg (point-min) end (point-max)))
6621 ((memq state '(children folded))
6622 (setq beg (point) end (progn (org-end-of-subtree t t)
6623 (beginning-of-line 2)
6624 (point)))))
6625 (when beg
6626 (goto-char beg)
6627 (while (re-search-forward re end t)
6628 (unless (get-char-property (match-end 1) 'invisible)
6629 (setq e (match-end 1))
6630 (if (< org-cycle-separator-lines 0)
6631 (setq b (save-excursion
6632 (goto-char (match-beginning 0))
6633 (org-back-over-empty-lines)
6634 (if (save-excursion
6635 (goto-char (max (point-min) (1- (point))))
6636 (org-at-heading-p))
6637 (1- (point))
6638 (point))))
6639 (setq b (match-beginning 1)))
6640 (outline-flag-region b e nil)))))))
6641 ;; Never hide empty lines at the end of the file.
6642 (save-excursion
6643 (goto-char (point-max))
6644 (outline-previous-heading)
6645 (outline-end-of-heading)
6646 (if (and (looking-at "[ \t\n]+")
6647 (= (match-end 0) (point-max)))
6648 (outline-flag-region (point) (match-end 0) nil))))
6650 (defun org-show-empty-lines-in-parent ()
6651 "Move to the parent and re-show empty lines before visible headlines."
6652 (save-excursion
6653 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6654 (org-cycle-show-empty-lines context))))
6656 (defun org-files-list ()
6657 "Return `org-agenda-files' list, plus all open org-mode files.
6658 This is useful for operations that need to scan all of a user's
6659 open and agenda-wise Org files."
6660 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6661 (dolist (buf (buffer-list))
6662 (with-current-buffer buf
6663 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6664 (let ((file (expand-file-name (buffer-file-name))))
6665 (unless (member file files)
6666 (push file files))))))
6667 files))
6669 (defsubst org-entry-beginning-position ()
6670 "Return the beginning position of the current entry."
6671 (save-excursion (outline-back-to-heading t) (point)))
6673 (defsubst org-entry-end-position ()
6674 "Return the end position of the current entry."
6675 (save-excursion (outline-next-heading) (point)))
6677 (defun org-cycle-hide-drawers (state)
6678 "Re-hide all drawers after a visibility state change."
6679 (when (and (derived-mode-p 'org-mode)
6680 (not (memq state '(overview folded contents))))
6681 (save-excursion
6682 (let* ((globalp (memq state '(contents all)))
6683 (beg (if globalp (point-min) (point)))
6684 (end (if globalp (point-max)
6685 (if (eq state 'children)
6686 (save-excursion (outline-next-heading) (point))
6687 (org-end-of-subtree t)))))
6688 (goto-char beg)
6689 (while (re-search-forward org-drawer-regexp end t)
6690 (org-flag-drawer t))))))
6692 (defun org-flag-drawer (flag)
6693 (save-excursion
6694 (beginning-of-line 1)
6695 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6696 (let ((b (match-end 0)))
6697 (if (re-search-forward
6698 "^[ \t]*:END:"
6699 (save-excursion (outline-next-heading) (point)) t)
6700 (outline-flag-region b (point-at-eol) flag)
6701 (error ":END: line missing at position %s" b))))))
6703 (defun org-subtree-end-visible-p ()
6704 "Is the end of the current subtree visible?"
6705 (pos-visible-in-window-p
6706 (save-excursion (org-end-of-subtree t) (point))))
6708 (defun org-first-headline-recenter (&optional N)
6709 "Move cursor to the first headline and recenter the headline.
6710 Optional argument N means put the headline into the Nth line of the window."
6711 (goto-char (point-min))
6712 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6713 (beginning-of-line)
6714 (recenter (prefix-numeric-value N))))
6716 ;;; Saving and restoring visibility
6718 (defun org-outline-overlay-data (&optional use-markers)
6719 "Return a list of the locations of all outline overlays.
6720 These are overlays with the `invisible' property value `outline'.
6721 The return value is a list of cons cells, with start and stop
6722 positions for each overlay.
6723 If USE-MARKERS is set, return the positions as markers."
6724 (let (beg end)
6725 (save-excursion
6726 (save-restriction
6727 (widen)
6728 (delq nil
6729 (mapcar (lambda (o)
6730 (when (eq (overlay-get o 'invisible) 'outline)
6731 (setq beg (overlay-start o)
6732 end (overlay-end o))
6733 (and beg end (> end beg)
6734 (if use-markers
6735 (cons (move-marker (make-marker) beg)
6736 (move-marker (make-marker) end))
6737 (cons beg end)))))
6738 (overlays-in (point-min) (point-max))))))))
6740 (defun org-set-outline-overlay-data (data)
6741 "Create visibility overlays for all positions in DATA.
6742 DATA should have been made by `org-outline-overlay-data'."
6743 (let (o)
6744 (save-excursion
6745 (save-restriction
6746 (widen)
6747 (show-all)
6748 (mapc (lambda (c)
6749 (outline-flag-region (car c) (cdr c) t))
6750 data)))))
6752 ;;; Folding of blocks
6754 (defvar org-hide-block-overlays nil
6755 "Overlays hiding blocks.")
6756 (make-variable-buffer-local 'org-hide-block-overlays)
6758 (defun org-block-map (function &optional start end)
6759 "Call FUNCTION at the head of all source blocks in the current buffer.
6760 Optional arguments START and END can be used to limit the range."
6761 (let ((start (or start (point-min)))
6762 (end (or end (point-max))))
6763 (save-excursion
6764 (goto-char start)
6765 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6766 (save-excursion
6767 (save-match-data
6768 (goto-char (match-beginning 0))
6769 (funcall function)))))))
6771 (defun org-hide-block-toggle-all ()
6772 "Toggle the visibility of all blocks in the current buffer."
6773 (org-block-map #'org-hide-block-toggle))
6775 (defun org-hide-block-all ()
6776 "Fold all blocks in the current buffer."
6777 (interactive)
6778 (org-show-block-all)
6779 (org-block-map #'org-hide-block-toggle-maybe))
6781 (defun org-show-block-all ()
6782 "Unfold all blocks in the current buffer."
6783 (interactive)
6784 (mapc 'delete-overlay org-hide-block-overlays)
6785 (setq org-hide-block-overlays nil))
6787 (defun org-hide-block-toggle-maybe ()
6788 "Toggle visibility of block at point."
6789 (interactive)
6790 (let ((case-fold-search t))
6791 (if (save-excursion
6792 (beginning-of-line 1)
6793 (looking-at org-block-regexp))
6794 (progn (org-hide-block-toggle)
6795 t) ;; to signal that we took action
6796 nil))) ;; to signal that we did not
6798 (defun org-hide-block-toggle (&optional force)
6799 "Toggle the visibility of the current block."
6800 (interactive)
6801 (save-excursion
6802 (beginning-of-line)
6803 (if (re-search-forward org-block-regexp nil t)
6804 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6805 (end (match-end 0)) ;; end of entire body
6807 (if (memq t (mapcar (lambda (overlay)
6808 (eq (overlay-get overlay 'invisible)
6809 'org-hide-block))
6810 (overlays-at start)))
6811 (if (or (not force) (eq force 'off))
6812 (mapc (lambda (ov)
6813 (when (member ov org-hide-block-overlays)
6814 (setq org-hide-block-overlays
6815 (delq ov org-hide-block-overlays)))
6816 (when (eq (overlay-get ov 'invisible)
6817 'org-hide-block)
6818 (delete-overlay ov)))
6819 (overlays-at start)))
6820 (setq ov (make-overlay start end))
6821 (overlay-put ov 'invisible 'org-hide-block)
6822 ;; make the block accessible to isearch
6823 (overlay-put
6824 ov 'isearch-open-invisible
6825 (lambda (ov)
6826 (when (member ov org-hide-block-overlays)
6827 (setq org-hide-block-overlays
6828 (delq ov org-hide-block-overlays)))
6829 (when (eq (overlay-get ov 'invisible)
6830 'org-hide-block)
6831 (delete-overlay ov))))
6832 (push ov org-hide-block-overlays)))
6833 (error "Not looking at a source block"))))
6835 ;; org-tab-after-check-for-cycling-hook
6836 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6837 ;; Remove overlays when changing major mode
6838 (add-hook 'org-mode-hook
6839 (lambda () (org-add-hook 'change-major-mode-hook
6840 'org-show-block-all 'append 'local)))
6842 ;;; Org-goto
6844 (defvar org-goto-window-configuration nil)
6845 (defvar org-goto-marker nil)
6846 (defvar org-goto-map
6847 (let ((map (make-sparse-keymap)))
6848 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6849 (while (setq cmd (pop cmds))
6850 (substitute-key-definition cmd cmd map global-map)))
6851 (suppress-keymap map)
6852 (org-defkey map "\C-m" 'org-goto-ret)
6853 (org-defkey map [(return)] 'org-goto-ret)
6854 (org-defkey map [(left)] 'org-goto-left)
6855 (org-defkey map [(right)] 'org-goto-right)
6856 (org-defkey map [(control ?g)] 'org-goto-quit)
6857 (org-defkey map "\C-i" 'org-cycle)
6858 (org-defkey map [(tab)] 'org-cycle)
6859 (org-defkey map [(down)] 'outline-next-visible-heading)
6860 (org-defkey map [(up)] 'outline-previous-visible-heading)
6861 (if org-goto-auto-isearch
6862 (if (fboundp 'define-key-after)
6863 (define-key-after map [t] 'org-goto-local-auto-isearch)
6864 nil)
6865 (org-defkey map "q" 'org-goto-quit)
6866 (org-defkey map "n" 'outline-next-visible-heading)
6867 (org-defkey map "p" 'outline-previous-visible-heading)
6868 (org-defkey map "f" 'outline-forward-same-level)
6869 (org-defkey map "b" 'outline-backward-same-level)
6870 (org-defkey map "u" 'outline-up-heading))
6871 (org-defkey map "/" 'org-occur)
6872 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6873 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6874 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6875 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6876 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6877 map))
6879 (defconst org-goto-help
6880 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6881 RET=jump to location [Q]uit and return to previous location
6882 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6884 (defvar org-goto-start-pos) ; dynamically scoped parameter
6886 ;; FIXME: Docstring does not mention both interfaces
6887 (defun org-goto (&optional alternative-interface)
6888 "Look up a different location in the current file, keeping current visibility.
6890 When you want look-up or go to a different location in a
6891 document, the fastest way is often to fold the entire buffer and
6892 then dive into the tree. This method has the disadvantage, that
6893 the previous location will be folded, which may not be what you
6894 want.
6896 This command works around this by showing a copy of the current
6897 buffer in an indirect buffer, in overview mode. You can dive
6898 into the tree in that copy, use org-occur and incremental search
6899 to find a location. When pressing RET or `Q', the command
6900 returns to the original buffer in which the visibility is still
6901 unchanged. After RET it will also jump to the location selected
6902 in the indirect buffer and expose the headline hierarchy above.
6904 With a prefix argument, use the alternative interface: e.g. if
6905 `org-goto-interface' is 'outline use 'outline-path-completion."
6906 (interactive "P")
6907 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6908 (org-refile-use-outline-path t)
6909 (org-refile-target-verify-function nil)
6910 (interface
6911 (if (not alternative-interface)
6912 org-goto-interface
6913 (if (eq org-goto-interface 'outline)
6914 'outline-path-completion
6915 'outline)))
6916 (org-goto-start-pos (point))
6917 (selected-point
6918 (if (eq interface 'outline)
6919 (car (org-get-location (current-buffer) org-goto-help))
6920 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6921 (org-refile-check-position pa)
6922 (nth 3 pa)))))
6923 (if selected-point
6924 (progn
6925 (org-mark-ring-push org-goto-start-pos)
6926 (goto-char selected-point)
6927 (if (or (outline-invisible-p) (org-invisible-p2))
6928 (org-show-context 'org-goto)))
6929 (message "Quit"))))
6931 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6932 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6933 (defvar org-goto-local-auto-isearch-map) ; defined below
6935 (defun org-get-location (buf help)
6936 "Let the user select a location in the Org-mode buffer BUF.
6937 This function uses a recursive edit. It returns the selected position
6938 or nil."
6939 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6940 (isearch-hide-immediately nil)
6941 (isearch-search-fun-function
6942 (lambda () 'org-goto-local-search-headings))
6943 (org-goto-selected-point org-goto-exit-command)
6944 (pop-up-frames nil)
6945 (special-display-buffer-names nil)
6946 (special-display-regexps nil)
6947 (special-display-function nil))
6948 (save-excursion
6949 (save-window-excursion
6950 (delete-other-windows)
6951 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6952 (org-pop-to-buffer-same-window
6953 (condition-case nil
6954 (make-indirect-buffer (current-buffer) "*org-goto*")
6955 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6956 (with-output-to-temp-buffer "*Help*"
6957 (princ help))
6958 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6959 (setq buffer-read-only nil)
6960 (let ((org-startup-truncated t)
6961 (org-startup-folded nil)
6962 (org-startup-align-all-tables nil))
6963 (org-mode)
6964 (org-overview))
6965 (setq buffer-read-only t)
6966 (if (and (boundp 'org-goto-start-pos)
6967 (integer-or-marker-p org-goto-start-pos))
6968 (let ((org-show-hierarchy-above t)
6969 (org-show-siblings t)
6970 (org-show-following-heading t))
6971 (goto-char org-goto-start-pos)
6972 (and (outline-invisible-p) (org-show-context)))
6973 (goto-char (point-min)))
6974 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6975 (message "Select location and press RET")
6976 (use-local-map org-goto-map)
6977 (recursive-edit)
6979 (kill-buffer "*org-goto*")
6980 (cons org-goto-selected-point org-goto-exit-command)))
6982 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6983 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6984 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6985 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6987 (defun org-goto-local-search-headings (string bound noerror)
6988 "Search and make sure that any matches are in headlines."
6989 (catch 'return
6990 (while (if isearch-forward
6991 (search-forward string bound noerror)
6992 (search-backward string bound noerror))
6993 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6994 (and (member :headline context)
6995 (not (member :tags context))))
6996 (throw 'return (point))))))
6998 (defun org-goto-local-auto-isearch ()
6999 "Start isearch."
7000 (interactive)
7001 (goto-char (point-min))
7002 (let ((keys (this-command-keys)))
7003 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7004 (isearch-mode t)
7005 (isearch-process-search-char (string-to-char keys)))))
7007 (defun org-goto-ret (&optional arg)
7008 "Finish `org-goto' by going to the new location."
7009 (interactive "P")
7010 (setq org-goto-selected-point (point)
7011 org-goto-exit-command 'return)
7012 (throw 'exit nil))
7014 (defun org-goto-left ()
7015 "Finish `org-goto' by going to the new location."
7016 (interactive)
7017 (if (org-at-heading-p)
7018 (progn
7019 (beginning-of-line 1)
7020 (setq org-goto-selected-point (point)
7021 org-goto-exit-command 'left)
7022 (throw 'exit nil))
7023 (error "Not on a heading")))
7025 (defun org-goto-right ()
7026 "Finish `org-goto' by going to the new location."
7027 (interactive)
7028 (if (org-at-heading-p)
7029 (progn
7030 (setq org-goto-selected-point (point)
7031 org-goto-exit-command 'right)
7032 (throw 'exit nil))
7033 (error "Not on a heading")))
7035 (defun org-goto-quit ()
7036 "Finish `org-goto' without cursor motion."
7037 (interactive)
7038 (setq org-goto-selected-point nil)
7039 (setq org-goto-exit-command 'quit)
7040 (throw 'exit nil))
7042 ;;; Indirect buffer display of subtrees
7044 (defvar org-indirect-dedicated-frame nil
7045 "This is the frame being used for indirect tree display.")
7046 (defvar org-last-indirect-buffer nil)
7048 (defun org-tree-to-indirect-buffer (&optional arg)
7049 "Create indirect buffer and narrow it to current subtree.
7050 With numerical prefix ARG, go up to this level and then take that tree.
7051 If ARG is negative, go up that many levels.
7052 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7053 indirect buffer previously made with this command, to avoid proliferation of
7054 indirect buffers. However, when you call the command with a \
7055 \\[universal-argument] prefix, or
7056 when `org-indirect-buffer-display' is `new-frame', the last buffer
7057 is kept so that you can work with several indirect buffers at the same time.
7058 If `org-indirect-buffer-display' is `dedicated-frame', the \
7059 \\[universal-argument] prefix also
7060 requests that a new frame be made for the new buffer, so that the dedicated
7061 frame is not changed."
7062 (interactive "P")
7063 (let ((cbuf (current-buffer))
7064 (cwin (selected-window))
7065 (pos (point))
7066 beg end level heading ibuf)
7067 (save-excursion
7068 (org-back-to-heading t)
7069 (when (numberp arg)
7070 (setq level (org-outline-level))
7071 (if (< arg 0) (setq arg (+ level arg)))
7072 (while (> (setq level (org-outline-level)) arg)
7073 (outline-up-heading 1 t)))
7074 (setq beg (point)
7075 heading (org-get-heading))
7076 (org-end-of-subtree t t)
7077 (if (org-at-heading-p) (backward-char 1))
7078 (setq end (point)))
7079 (if (and (buffer-live-p org-last-indirect-buffer)
7080 (not (eq org-indirect-buffer-display 'new-frame))
7081 (not arg))
7082 (kill-buffer org-last-indirect-buffer))
7083 (setq ibuf (org-get-indirect-buffer cbuf)
7084 org-last-indirect-buffer ibuf)
7085 (cond
7086 ((or (eq org-indirect-buffer-display 'new-frame)
7087 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7088 (select-frame (make-frame))
7089 (delete-other-windows)
7090 (org-pop-to-buffer-same-window ibuf)
7091 (org-set-frame-title heading))
7092 ((eq org-indirect-buffer-display 'dedicated-frame)
7093 (raise-frame
7094 (select-frame (or (and org-indirect-dedicated-frame
7095 (frame-live-p org-indirect-dedicated-frame)
7096 org-indirect-dedicated-frame)
7097 (setq org-indirect-dedicated-frame (make-frame)))))
7098 (delete-other-windows)
7099 (org-pop-to-buffer-same-window ibuf)
7100 (org-set-frame-title (concat "Indirect: " heading)))
7101 ((eq org-indirect-buffer-display 'current-window)
7102 (org-pop-to-buffer-same-window ibuf))
7103 ((eq org-indirect-buffer-display 'other-window)
7104 (pop-to-buffer ibuf))
7105 (t (error "Invalid value")))
7106 (if (featurep 'xemacs)
7107 (save-excursion (org-mode) (turn-on-font-lock)))
7108 (narrow-to-region beg end)
7109 (show-all)
7110 (goto-char pos)
7111 (run-hook-with-args 'org-cycle-hook 'all)
7112 (and (window-live-p cwin) (select-window cwin))))
7114 (defun org-get-indirect-buffer (&optional buffer)
7115 (setq buffer (or buffer (current-buffer)))
7116 (let ((n 1) (base (buffer-name buffer)) bname)
7117 (while (buffer-live-p
7118 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7119 (setq n (1+ n)))
7120 (condition-case nil
7121 (make-indirect-buffer buffer bname 'clone)
7122 (error (make-indirect-buffer buffer bname)))))
7124 (defun org-set-frame-title (title)
7125 "Set the title of the current frame to the string TITLE."
7126 ;; FIXME: how to name a single frame in XEmacs???
7127 (unless (featurep 'xemacs)
7128 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7130 ;;;; Structure editing
7132 ;;; Inserting headlines
7134 (defun org-previous-line-empty-p ()
7135 (save-excursion
7136 (and (not (bobp))
7137 (or (beginning-of-line 0) t)
7138 (save-match-data
7139 (looking-at "[ \t]*$")))))
7141 (defun org-insert-heading (&optional force-heading invisible-ok)
7142 "Insert a new heading or item with same depth at point.
7143 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7144 If point is at the beginning of a headline, insert a sibling before the
7145 current headline. If point is not at the beginning, split the line,
7146 create the new headline with the text in the current line after point
7147 \(but see also the variable `org-M-RET-may-split-line').
7149 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7150 This is important for non-interactive uses of the command."
7151 (interactive "P")
7152 (if (or (= (buffer-size) 0)
7153 (and (not (save-excursion
7154 (and (ignore-errors (org-back-to-heading invisible-ok))
7155 (org-at-heading-p))))
7156 (or force-heading (not (org-in-item-p)))))
7157 (progn
7158 (insert "\n* ")
7159 (run-hooks 'org-insert-heading-hook))
7160 (when (or force-heading (not (org-insert-item)))
7161 (let* ((empty-line-p nil)
7162 (level nil)
7163 (on-heading (org-at-heading-p))
7164 (head (save-excursion
7165 (condition-case nil
7166 (progn
7167 (org-back-to-heading invisible-ok)
7168 (when (and (not on-heading)
7169 (featurep 'org-inlinetask)
7170 (integerp org-inlinetask-min-level)
7171 (>= (length (match-string 0))
7172 org-inlinetask-min-level))
7173 ;; Find a heading level before the inline task
7174 (while (and (setq level (org-up-heading-safe))
7175 (>= level org-inlinetask-min-level)))
7176 (if (org-at-heading-p)
7177 (org-back-to-heading invisible-ok)
7178 (error "This should not happen")))
7179 (setq empty-line-p (org-previous-line-empty-p))
7180 (match-string 0))
7181 (error "*"))))
7182 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7183 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7184 pos hide-previous previous-pos)
7185 (cond
7186 ((and (org-at-heading-p) (bolp)
7187 (or (bobp)
7188 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7189 ;; insert before the current line
7190 (open-line (if blank 2 1)))
7191 ((and (bolp)
7192 (not org-insert-heading-respect-content)
7193 (or (bobp)
7194 (save-excursion
7195 (backward-char 1) (not (outline-invisible-p)))))
7196 ;; insert right here
7197 nil)
7199 ;; somewhere in the line
7200 (save-excursion
7201 (setq previous-pos (point-at-bol))
7202 (end-of-line)
7203 (setq hide-previous (outline-invisible-p)))
7204 (and org-insert-heading-respect-content (org-show-subtree))
7205 (let ((split
7206 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7207 (save-excursion
7208 (let ((p (point)))
7209 (goto-char (point-at-bol))
7210 (and (looking-at org-complex-heading-regexp)
7211 (match-beginning 4)
7212 (> p (match-beginning 4)))))))
7213 tags pos)
7214 (cond
7215 (org-insert-heading-respect-content
7216 (org-end-of-subtree nil t)
7217 (when (featurep 'org-inlinetask)
7218 (while (and (not (eobp))
7219 (looking-at "\\(\\*+\\)[ \t]+")
7220 (>= (length (match-string 1))
7221 org-inlinetask-min-level))
7222 (org-end-of-subtree nil t)))
7223 (or (bolp) (newline))
7224 (or (org-previous-line-empty-p)
7225 (and blank (newline)))
7226 (open-line 1))
7227 ((org-at-heading-p)
7228 (when hide-previous
7229 (show-children)
7230 (org-show-entry))
7231 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7232 (setq tags (and (match-end 2) (match-string 2)))
7233 (and (match-end 1)
7234 (delete-region (match-beginning 1) (match-end 1)))
7235 (setq pos (point-at-bol))
7236 (or split (end-of-line 1))
7237 (delete-horizontal-space)
7238 (if (string-match "\\`\\*+\\'"
7239 (buffer-substring (point-at-bol) (point)))
7240 (insert " "))
7241 (newline (if blank 2 1))
7242 (when tags
7243 (save-excursion
7244 (goto-char pos)
7245 (end-of-line 1)
7246 (insert " " tags)
7247 (org-set-tags nil 'align))))
7249 (or split (end-of-line 1))
7250 (newline (if blank 2 1)))))))
7251 (insert head) (just-one-space)
7252 (setq pos (point))
7253 (end-of-line 1)
7254 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7255 (when (and org-insert-heading-respect-content hide-previous)
7256 (save-excursion
7257 (goto-char previous-pos)
7258 (hide-subtree)))
7259 (run-hooks 'org-insert-heading-hook)))))
7261 (defun org-get-heading (&optional no-tags no-todo)
7262 "Return the heading of the current entry, without the stars.
7263 When NO-TAGS is non-nil, don't include tags.
7264 When NO-TODO is non-nil, don't include TODO keywords."
7265 (save-excursion
7266 (org-back-to-heading t)
7267 (cond
7268 ((and no-tags no-todo)
7269 (looking-at org-complex-heading-regexp)
7270 (match-string 4))
7271 (no-tags
7272 (looking-at (concat org-outline-regexp
7273 "\\(.*?\\)"
7274 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7275 (match-string 1))
7276 (no-todo
7277 (looking-at org-todo-line-regexp)
7278 (match-string 3))
7279 (t (looking-at org-heading-regexp)
7280 (match-string 2)))))
7282 (defun org-heading-components ()
7283 "Return the components of the current heading.
7284 This is a list with the following elements:
7285 - the level as an integer
7286 - the reduced level, different if `org-odd-levels-only' is set.
7287 - the TODO keyword, or nil
7288 - the priority character, like ?A, or nil if no priority is given
7289 - the headline text itself, or the tags string if no headline text
7290 - the tags string, or nil."
7291 (save-excursion
7292 (org-back-to-heading t)
7293 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7294 (list (length (match-string 1))
7295 (org-reduced-level (length (match-string 1)))
7296 (org-match-string-no-properties 2)
7297 (and (match-end 3) (aref (match-string 3) 2))
7298 (org-match-string-no-properties 4)
7299 (org-match-string-no-properties 5)))))
7301 (defun org-get-entry ()
7302 "Get the entry text, after heading, entire subtree."
7303 (save-excursion
7304 (org-back-to-heading t)
7305 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7307 (defun org-insert-heading-after-current ()
7308 "Insert a new heading with same level as current, after current subtree."
7309 (interactive)
7310 (org-back-to-heading)
7311 (org-insert-heading)
7312 (org-move-subtree-down)
7313 (end-of-line 1))
7315 (defun org-insert-heading-respect-content ()
7316 (interactive)
7317 (let ((org-insert-heading-respect-content t))
7318 (org-insert-heading t)))
7320 (defun org-insert-todo-heading-respect-content (&optional force-state)
7321 (interactive "P")
7322 (let ((org-insert-heading-respect-content t))
7323 (org-insert-todo-heading force-state t)))
7325 (defun org-insert-todo-heading (arg &optional force-heading)
7326 "Insert a new heading with the same level and TODO state as current heading.
7327 If the heading has no TODO state, or if the state is DONE, use the first
7328 state (TODO by default). Also with prefix arg, force first state."
7329 (interactive "P")
7330 (when (or force-heading (not (org-insert-item 'checkbox)))
7331 (org-insert-heading force-heading)
7332 (save-excursion
7333 (org-back-to-heading)
7334 (outline-previous-heading)
7335 (looking-at org-todo-line-regexp))
7336 (let*
7337 ((new-mark-x
7338 (if (or arg
7339 (not (match-beginning 2))
7340 (member (match-string 2) org-done-keywords))
7341 (car org-todo-keywords-1)
7342 (match-string 2)))
7343 (new-mark
7345 (run-hook-with-args-until-success
7346 'org-todo-get-default-hook new-mark-x nil)
7347 new-mark-x)))
7348 (beginning-of-line 1)
7349 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7350 (if org-treat-insert-todo-heading-as-state-change
7351 (org-todo new-mark)
7352 (insert new-mark " "))))
7353 (when org-provide-todo-statistics
7354 (org-update-parent-todo-statistics))))
7356 (defun org-insert-subheading (arg)
7357 "Insert a new subheading and demote it.
7358 Works for outline headings and for plain lists alike."
7359 (interactive "P")
7360 (org-insert-heading arg)
7361 (cond
7362 ((org-at-heading-p) (org-do-demote))
7363 ((org-at-item-p) (org-indent-item))))
7365 (defun org-insert-todo-subheading (arg)
7366 "Insert a new subheading with TODO keyword or checkbox and demote it.
7367 Works for outline headings and for plain lists alike."
7368 (interactive "P")
7369 (org-insert-todo-heading arg)
7370 (cond
7371 ((org-at-heading-p) (org-do-demote))
7372 ((org-at-item-p) (org-indent-item))))
7374 ;;; Promotion and Demotion
7376 (defvar org-after-demote-entry-hook nil
7377 "Hook run after an entry has been demoted.
7378 The cursor will be at the beginning of the entry.
7379 When a subtree is being demoted, the hook will be called for each node.")
7381 (defvar org-after-promote-entry-hook nil
7382 "Hook run after an entry has been promoted.
7383 The cursor will be at the beginning of the entry.
7384 When a subtree is being promoted, the hook will be called for each node.")
7386 (defun org-promote-subtree ()
7387 "Promote the entire subtree.
7388 See also `org-promote'."
7389 (interactive)
7390 (save-excursion
7391 (org-with-limited-levels (org-map-tree 'org-promote)))
7392 (org-fix-position-after-promote))
7394 (defun org-demote-subtree ()
7395 "Demote the entire subtree. See `org-demote'.
7396 See also `org-promote'."
7397 (interactive)
7398 (save-excursion
7399 (org-with-limited-levels (org-map-tree 'org-demote)))
7400 (org-fix-position-after-promote))
7403 (defun org-do-promote ()
7404 "Promote the current heading higher up the tree.
7405 If the region is active in `transient-mark-mode', promote all headings
7406 in the region."
7407 (interactive)
7408 (save-excursion
7409 (if (org-region-active-p)
7410 (org-map-region 'org-promote (region-beginning) (region-end))
7411 (org-promote)))
7412 (org-fix-position-after-promote))
7414 (defun org-do-demote ()
7415 "Demote the current heading lower down the tree.
7416 If the region is active in `transient-mark-mode', demote all headings
7417 in the region."
7418 (interactive)
7419 (save-excursion
7420 (if (org-region-active-p)
7421 (org-map-region 'org-demote (region-beginning) (region-end))
7422 (org-demote)))
7423 (org-fix-position-after-promote))
7425 (defun org-fix-position-after-promote ()
7426 "Make sure that after pro/demotion cursor position is right."
7427 (let ((pos (point)))
7428 (when (save-excursion
7429 (beginning-of-line 1)
7430 (looking-at org-todo-line-regexp)
7431 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7432 (cond ((eobp) (insert " "))
7433 ((eolp) (insert " "))
7434 ((equal (char-after) ?\ ) (forward-char 1))))))
7436 (defun org-current-level ()
7437 "Return the level of the current entry, or nil if before the first headline.
7438 The level is the number of stars at the beginning of the headline."
7439 (save-excursion
7440 (org-with-limited-levels
7441 (if (ignore-errors (org-back-to-heading t))
7442 (funcall outline-level)))))
7444 (defun org-get-previous-line-level ()
7445 "Return the outline depth of the last headline before the current line.
7446 Returns 0 for the first headline in the buffer, and nil if before the
7447 first headline."
7448 (let ((current-level (org-current-level))
7449 (prev-level (when (> (line-number-at-pos) 1)
7450 (save-excursion
7451 (beginning-of-line 0)
7452 (org-current-level)))))
7453 (cond ((null current-level) nil) ; Before first headline
7454 ((null prev-level) 0) ; At first headline
7455 (prev-level))))
7457 (defun org-reduced-level (l)
7458 "Compute the effective level of a heading.
7459 This takes into account the setting of `org-odd-levels-only'."
7460 (cond
7461 ((zerop l) 0)
7462 (org-odd-levels-only (1+ (floor (/ l 2))))
7463 (t l)))
7465 (defun org-level-increment ()
7466 "Return the number of stars that will be added or removed at a
7467 time to headlines when structure editing, based on the value of
7468 `org-odd-levels-only'."
7469 (if org-odd-levels-only 2 1))
7471 (defun org-get-valid-level (level &optional change)
7472 "Rectify a level change under the influence of `org-odd-levels-only'
7473 LEVEL is a current level, CHANGE is by how much the level should be
7474 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7475 even level numbers will become the next higher odd number."
7476 (if org-odd-levels-only
7477 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7478 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7479 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7480 (max 1 (+ level (or change 0)))))
7482 (if (boundp 'define-obsolete-function-alias)
7483 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7484 (define-obsolete-function-alias 'org-get-legal-level
7485 'org-get-valid-level)
7486 (define-obsolete-function-alias 'org-get-legal-level
7487 'org-get-valid-level "23.1")))
7489 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7490 ;; ̀org-with-limited-levels'
7491 (defun org-promote ()
7492 "Promote the current heading higher up the tree.
7493 If the region is active in `transient-mark-mode', promote all headings
7494 in the region."
7495 (org-back-to-heading t)
7496 (let* ((level (save-match-data (funcall outline-level)))
7497 (after-change-functions (remove 'flyspell-after-change-function
7498 after-change-functions))
7499 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7500 (diff (abs (- level (length up-head) -1))))
7501 (cond ((and (= level 1) org-called-with-limited-levels
7502 org-allow-promoting-top-level-subtree)
7503 (replace-match "# " nil t))
7504 ((= level 1)
7505 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7506 (t (replace-match up-head nil t)))
7507 ;; Fixup tag positioning
7508 (unless (= level 1)
7509 (and org-auto-align-tags (org-set-tags nil t))
7510 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7511 (run-hooks 'org-after-promote-entry-hook)))
7513 (defun org-demote ()
7514 "Demote the current heading lower down the tree.
7515 If the region is active in `transient-mark-mode', demote all headings
7516 in the region."
7517 (org-back-to-heading t)
7518 (let* ((level (save-match-data (funcall outline-level)))
7519 (after-change-functions (remove 'flyspell-after-change-function
7520 after-change-functions))
7521 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7522 (diff (abs (- level (length down-head) -1))))
7523 (replace-match down-head nil t)
7524 ;; Fixup tag positioning
7525 (and org-auto-align-tags (org-set-tags nil t))
7526 (if org-adapt-indentation (org-fixup-indentation diff))
7527 (run-hooks 'org-after-demote-entry-hook)))
7529 (defun org-cycle-level ()
7530 "Cycle the level of an empty headline through possible states.
7531 This goes first to child, then to parent, level, then up the hierarchy.
7532 After top level, it switches back to sibling level."
7533 (interactive)
7534 (let ((org-adapt-indentation nil))
7535 (when (org-point-at-end-of-empty-headline)
7536 (setq this-command 'org-cycle-level) ; Only needed for caching
7537 (let ((cur-level (org-current-level))
7538 (prev-level (org-get-previous-line-level)))
7539 (cond
7540 ;; If first headline in file, promote to top-level.
7541 ((= prev-level 0)
7542 (loop repeat (/ (- cur-level 1) (org-level-increment))
7543 do (org-do-promote)))
7544 ;; If same level as prev, demote one.
7545 ((= prev-level cur-level)
7546 (org-do-demote))
7547 ;; If parent is top-level, promote to top level if not already.
7548 ((= prev-level 1)
7549 (loop repeat (/ (- cur-level 1) (org-level-increment))
7550 do (org-do-promote)))
7551 ;; If top-level, return to prev-level.
7552 ((= cur-level 1)
7553 (loop repeat (/ (- prev-level 1) (org-level-increment))
7554 do (org-do-demote)))
7555 ;; If less than prev-level, promote one.
7556 ((< cur-level prev-level)
7557 (org-do-promote))
7558 ;; If deeper than prev-level, promote until higher than
7559 ;; prev-level.
7560 ((> cur-level prev-level)
7561 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7562 do (org-do-promote))))
7563 t))))
7565 (defun org-map-tree (fun)
7566 "Call FUN for every heading underneath the current one."
7567 (org-back-to-heading)
7568 (let ((level (funcall outline-level)))
7569 (save-excursion
7570 (funcall fun)
7571 (while (and (progn
7572 (outline-next-heading)
7573 (> (funcall outline-level) level))
7574 (not (eobp)))
7575 (funcall fun)))))
7577 (defun org-map-region (fun beg end)
7578 "Call FUN for every heading between BEG and END."
7579 (let ((org-ignore-region t))
7580 (save-excursion
7581 (setq end (copy-marker end))
7582 (goto-char beg)
7583 (if (and (re-search-forward org-outline-regexp-bol nil t)
7584 (< (point) end))
7585 (funcall fun))
7586 (while (and (progn
7587 (outline-next-heading)
7588 (< (point) end))
7589 (not (eobp)))
7590 (funcall fun)))))
7592 (defvar org-property-end-re) ; silence byte-compiler
7593 (defun org-fixup-indentation (diff)
7594 "Change the indentation in the current entry by DIFF.
7595 However, if any line in the current entry has no indentation, or if it
7596 would end up with no indentation after the change, nothing at all is done."
7597 (save-excursion
7598 (let ((end (save-excursion (outline-next-heading)
7599 (point-marker)))
7600 (prohibit (if (> diff 0)
7601 "^\\S-"
7602 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7603 col)
7604 (unless (save-excursion (end-of-line 1)
7605 (re-search-forward prohibit end t))
7606 (while (and (< (point) end)
7607 (re-search-forward "^[ \t]+" end t))
7608 (goto-char (match-end 0))
7609 (setq col (current-column))
7610 (if (< diff 0) (replace-match ""))
7611 (org-indent-to-column (+ diff col))))
7612 (move-marker end nil))))
7614 (defun org-convert-to-odd-levels ()
7615 "Convert an org-mode file with all levels allowed to one with odd levels.
7616 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7617 level 5 etc."
7618 (interactive)
7619 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7620 (let ((outline-level 'org-outline-level)
7621 (org-odd-levels-only nil) n)
7622 (save-excursion
7623 (goto-char (point-min))
7624 (while (re-search-forward "^\\*\\*+ " nil t)
7625 (setq n (- (length (match-string 0)) 2))
7626 (while (>= (setq n (1- n)) 0)
7627 (org-demote))
7628 (end-of-line 1))))))
7630 (defun org-convert-to-oddeven-levels ()
7631 "Convert an org-mode file with only odd levels to one with odd/even levels.
7632 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7633 file contains a section with an even level, conversion would
7634 destroy the structure of the file. An error is signaled in this
7635 case."
7636 (interactive)
7637 (goto-char (point-min))
7638 ;; First check if there are no even levels
7639 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7640 (org-show-context t)
7641 (error "Not all levels are odd in this file. Conversion not possible"))
7642 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7643 (let ((outline-regexp org-outline-regexp)
7644 (outline-level 'org-outline-level)
7645 (org-odd-levels-only nil) n)
7646 (save-excursion
7647 (goto-char (point-min))
7648 (while (re-search-forward "^\\*\\*+ " nil t)
7649 (setq n (/ (1- (length (match-string 0))) 2))
7650 (while (>= (setq n (1- n)) 0)
7651 (org-promote))
7652 (end-of-line 1))))))
7654 (defun org-tr-level (n)
7655 "Make N odd if required."
7656 (if org-odd-levels-only (1+ (/ n 2)) n))
7658 ;;; Vertical tree motion, cutting and pasting of subtrees
7660 (defun org-move-subtree-up (&optional arg)
7661 "Move the current subtree up past ARG headlines of the same level."
7662 (interactive "p")
7663 (org-move-subtree-down (- (prefix-numeric-value arg))))
7665 (defun org-move-subtree-down (&optional arg)
7666 "Move the current subtree down past ARG headlines of the same level."
7667 (interactive "p")
7668 (setq arg (prefix-numeric-value arg))
7669 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7670 'org-get-last-sibling))
7671 (ins-point (make-marker))
7672 (cnt (abs arg))
7673 (col (current-column))
7674 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7675 ;; Select the tree
7676 (org-back-to-heading)
7677 (setq beg0 (point))
7678 (save-excursion
7679 (setq ne-beg (org-back-over-empty-lines))
7680 (setq beg (point)))
7681 (save-match-data
7682 (save-excursion (outline-end-of-heading)
7683 (setq folded (outline-invisible-p)))
7684 (outline-end-of-subtree))
7685 (outline-next-heading)
7686 (setq ne-end (org-back-over-empty-lines))
7687 (setq end (point))
7688 (goto-char beg0)
7689 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7690 ;; include less whitespace
7691 (save-excursion
7692 (goto-char beg)
7693 (forward-line (- ne-beg ne-end))
7694 (setq beg (point))))
7695 ;; Find insertion point, with error handling
7696 (while (> cnt 0)
7697 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7698 (progn (goto-char beg0)
7699 (error "Cannot move past superior level or buffer limit")))
7700 (setq cnt (1- cnt)))
7701 (if (> arg 0)
7702 ;; Moving forward - still need to move over subtree
7703 (progn (org-end-of-subtree t t)
7704 (save-excursion
7705 (org-back-over-empty-lines)
7706 (or (bolp) (newline)))))
7707 (setq ne-ins (org-back-over-empty-lines))
7708 (move-marker ins-point (point))
7709 (setq txt (buffer-substring beg end))
7710 (org-save-markers-in-region beg end)
7711 (delete-region beg end)
7712 (org-remove-empty-overlays-at beg)
7713 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7714 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7715 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7716 (let ((bbb (point)))
7717 (insert-before-markers txt)
7718 (org-reinstall-markers-in-region bbb)
7719 (move-marker ins-point bbb))
7720 (or (bolp) (insert "\n"))
7721 (setq ins-end (point))
7722 (goto-char ins-point)
7723 (org-skip-whitespace)
7724 (when (and (< arg 0)
7725 (org-first-sibling-p)
7726 (> ne-ins ne-beg))
7727 ;; Move whitespace back to beginning
7728 (save-excursion
7729 (goto-char ins-end)
7730 (let ((kill-whole-line t))
7731 (kill-line (- ne-ins ne-beg)) (point)))
7732 (insert (make-string (- ne-ins ne-beg) ?\n)))
7733 (move-marker ins-point nil)
7734 (if folded
7735 (hide-subtree)
7736 (org-show-entry)
7737 (show-children)
7738 (org-cycle-hide-drawers 'children))
7739 (org-clean-visibility-after-subtree-move)
7740 ;; move back to the initial column we were at
7741 (move-to-column col)))
7743 (defvar org-subtree-clip ""
7744 "Clipboard for cut and paste of subtrees.
7745 This is actually only a copy of the kill, because we use the normal kill
7746 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7748 (defvar org-subtree-clip-folded nil
7749 "Was the last copied subtree folded?
7750 This is used to fold the tree back after pasting.")
7752 (defun org-cut-subtree (&optional n)
7753 "Cut the current subtree into the clipboard.
7754 With prefix arg N, cut this many sequential subtrees.
7755 This is a short-hand for marking the subtree and then cutting it."
7756 (interactive "p")
7757 (org-copy-subtree n 'cut))
7759 (defun org-copy-subtree (&optional n cut force-store-markers)
7760 "Cut the current subtree into the clipboard.
7761 With prefix arg N, cut this many sequential subtrees.
7762 This is a short-hand for marking the subtree and then copying it.
7763 If CUT is non-nil, actually cut the subtree.
7764 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7765 of some markers in the region, even if CUT is non-nil. This is
7766 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7767 (interactive "p")
7768 (let (beg end folded (beg0 (point)))
7769 (if (org-called-interactively-p 'any)
7770 (org-back-to-heading nil) ; take what looks like a subtree
7771 (org-back-to-heading t)) ; take what is really there
7772 (org-back-over-empty-lines)
7773 (setq beg (point))
7774 (skip-chars-forward " \t\r\n")
7775 (save-match-data
7776 (save-excursion (outline-end-of-heading)
7777 (setq folded (outline-invisible-p)))
7778 (condition-case nil
7779 (org-forward-same-level (1- n) t)
7780 (error nil))
7781 (org-end-of-subtree t t))
7782 (org-back-over-empty-lines)
7783 (setq end (point))
7784 (goto-char beg0)
7785 (when (> end beg)
7786 (setq org-subtree-clip-folded folded)
7787 (when (or cut force-store-markers)
7788 (org-save-markers-in-region beg end))
7789 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7790 (setq org-subtree-clip (current-kill 0))
7791 (message "%s: Subtree(s) with %d characters"
7792 (if cut "Cut" "Copied")
7793 (length org-subtree-clip)))))
7795 (defun org-paste-subtree (&optional level tree for-yank)
7796 "Paste the clipboard as a subtree, with modification of headline level.
7797 The entire subtree is promoted or demoted in order to match a new headline
7798 level.
7800 If the cursor is at the beginning of a headline, the same level as
7801 that headline is used to paste the tree
7803 If not, the new level is derived from the *visible* headings
7804 before and after the insertion point, and taken to be the inferior headline
7805 level of the two. So if the previous visible heading is level 3 and the
7806 next is level 4 (or vice versa), level 4 will be used for insertion.
7807 This makes sure that the subtree remains an independent subtree and does
7808 not swallow low level entries.
7810 You can also force a different level, either by using a numeric prefix
7811 argument, or by inserting the heading marker by hand. For example, if the
7812 cursor is after \"*****\", then the tree will be shifted to level 5.
7814 If optional TREE is given, use this text instead of the kill ring.
7816 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7817 move back over whitespace before inserting, and move point to the end of
7818 the inserted text when done."
7819 (interactive "P")
7820 (setq tree (or tree (and kill-ring (current-kill 0))))
7821 (unless (org-kill-is-subtree-p tree)
7822 (error "%s"
7823 (substitute-command-keys
7824 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7825 (org-with-limited-levels
7826 (let* ((visp (not (outline-invisible-p)))
7827 (txt tree)
7828 (^re_ "\\(\\*+\\)[ \t]*")
7829 (old-level (if (string-match org-outline-regexp-bol txt)
7830 (- (match-end 0) (match-beginning 0) 1)
7831 -1))
7832 (force-level (cond (level (prefix-numeric-value level))
7833 ((and (looking-at "[ \t]*$")
7834 (string-match
7835 "^\\*+$" (buffer-substring
7836 (point-at-bol) (point))))
7837 (- (match-end 1) (match-beginning 1)))
7838 ((and (bolp)
7839 (looking-at org-outline-regexp))
7840 (- (match-end 0) (point) 1))
7841 (t nil)))
7842 (previous-level (save-excursion
7843 (condition-case nil
7844 (progn
7845 (outline-previous-visible-heading 1)
7846 (if (looking-at ^re_)
7847 (- (match-end 0) (match-beginning 0) 1)
7849 (error 1))))
7850 (next-level (save-excursion
7851 (condition-case nil
7852 (progn
7853 (or (looking-at org-outline-regexp)
7854 (outline-next-visible-heading 1))
7855 (if (looking-at ^re_)
7856 (- (match-end 0) (match-beginning 0) 1)
7858 (error 1))))
7859 (new-level (or force-level (max previous-level next-level)))
7860 (shift (if (or (= old-level -1)
7861 (= new-level -1)
7862 (= old-level new-level))
7864 (- new-level old-level)))
7865 (delta (if (> shift 0) -1 1))
7866 (func (if (> shift 0) 'org-demote 'org-promote))
7867 (org-odd-levels-only nil)
7868 beg end newend)
7869 ;; Remove the forced level indicator
7870 (if force-level
7871 (delete-region (point-at-bol) (point)))
7872 ;; Paste
7873 (beginning-of-line (if (bolp) 1 2))
7874 (unless for-yank (org-back-over-empty-lines))
7875 (setq beg (point))
7876 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7877 (insert-before-markers txt)
7878 (unless (string-match "\n\\'" txt) (insert "\n"))
7879 (setq newend (point))
7880 (org-reinstall-markers-in-region beg)
7881 (setq end (point))
7882 (goto-char beg)
7883 (skip-chars-forward " \t\n\r")
7884 (setq beg (point))
7885 (if (and (outline-invisible-p) visp)
7886 (save-excursion (outline-show-heading)))
7887 ;; Shift if necessary
7888 (unless (= shift 0)
7889 (save-restriction
7890 (narrow-to-region beg end)
7891 (while (not (= shift 0))
7892 (org-map-region func (point-min) (point-max))
7893 (setq shift (+ delta shift)))
7894 (goto-char (point-min))
7895 (setq newend (point-max))))
7896 (when (or (org-called-interactively-p 'interactive) for-yank)
7897 (message "Clipboard pasted as level %d subtree" new-level))
7898 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7899 kill-ring
7900 (eq org-subtree-clip (current-kill 0))
7901 org-subtree-clip-folded)
7902 ;; The tree was folded before it was killed/copied
7903 (hide-subtree))
7904 (and for-yank (goto-char newend)))))
7906 (defun org-kill-is-subtree-p (&optional txt)
7907 "Check if the current kill is an outline subtree, or a set of trees.
7908 Returns nil if kill does not start with a headline, or if the first
7909 headline level is not the largest headline level in the tree.
7910 So this will actually accept several entries of equal levels as well,
7911 which is OK for `org-paste-subtree'.
7912 If optional TXT is given, check this string instead of the current kill."
7913 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7914 (re (org-get-limited-outline-regexp))
7915 (^re (concat "^" re))
7916 (start-level (and kill
7917 (string-match
7918 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7919 kill)
7920 (- (match-end 2) (match-beginning 2) 1)))
7921 (start (1+ (or (match-beginning 2) -1))))
7922 (if (not start-level)
7923 (progn
7924 nil) ;; does not even start with a heading
7925 (catch 'exit
7926 (while (setq start (string-match ^re kill (1+ start)))
7927 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7928 (throw 'exit nil)))
7929 t))))
7931 (defvar org-markers-to-move nil
7932 "Markers that should be moved with a cut-and-paste operation.
7933 Those markers are stored together with their positions relative to
7934 the start of the region.")
7936 (defun org-save-markers-in-region (beg end)
7937 "Check markers in region.
7938 If these markers are between BEG and END, record their position relative
7939 to BEG, so that after moving the block of text, we can put the markers back
7940 into place.
7941 This function gets called just before an entry or tree gets cut from the
7942 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7943 called immediately, to move the markers with the entries."
7944 (setq org-markers-to-move nil)
7945 (when (featurep 'org-clock)
7946 (org-clock-save-markers-for-cut-and-paste beg end))
7947 (when (featurep 'org-agenda)
7948 (org-agenda-save-markers-for-cut-and-paste beg end)))
7950 (defun org-check-and-save-marker (marker beg end)
7951 "Check if MARKER is between BEG and END.
7952 If yes, remember the marker and the distance to BEG."
7953 (when (and (marker-buffer marker)
7954 (equal (marker-buffer marker) (current-buffer)))
7955 (if (and (>= marker beg) (< marker end))
7956 (push (cons marker (- marker beg)) org-markers-to-move))))
7958 (defun org-reinstall-markers-in-region (beg)
7959 "Move all remembered markers to their position relative to BEG."
7960 (mapc (lambda (x)
7961 (move-marker (car x) (+ beg (cdr x))))
7962 org-markers-to-move)
7963 (setq org-markers-to-move nil))
7965 (defun org-narrow-to-subtree ()
7966 "Narrow buffer to the current subtree."
7967 (interactive)
7968 (save-excursion
7969 (save-match-data
7970 (org-with-limited-levels
7971 (narrow-to-region
7972 (progn (org-back-to-heading t) (point))
7973 (progn (org-end-of-subtree t t)
7974 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7975 (point)))))))
7977 (defun org-narrow-to-block ()
7978 "Narrow buffer to the current block."
7979 (interactive)
7980 (let* ((case-fold-search t)
7981 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7982 "^[ \t]*#\\+end_.*")))
7983 (if blockp
7984 (narrow-to-region (car blockp) (cdr blockp))
7985 (error "Not in a block"))))
7987 (eval-when-compile
7988 (defvar org-property-drawer-re))
7990 (defvar org-property-start-re) ;; defined below
7991 (defun org-clone-subtree-with-time-shift (n &optional shift)
7992 "Clone the task (subtree) at point N times.
7993 The clones will be inserted as siblings.
7995 In interactive use, the user will be prompted for the number of
7996 clones to be produced, and for a time SHIFT, which may be a
7997 repeater as used in time stamps, for example `+3d'.
7999 When a valid repeater is given and the entry contains any time
8000 stamps, the clones will become a sequence in time, with time
8001 stamps in the subtree shifted for each clone produced. If SHIFT
8002 is nil or the empty string, time stamps will be left alone. The
8003 ID property of the original subtree is removed.
8005 If the original subtree did contain time stamps with a repeater,
8006 the following will happen:
8007 - the repeater will be removed in each clone
8008 - an additional clone will be produced, with the current, unshifted
8009 date(s) in the entry.
8010 - the original entry will be placed *after* all the clones, with
8011 repeater intact.
8012 - the start days in the repeater in the original entry will be shifted
8013 to past the last clone.
8014 In this way you can spell out a number of instances of a repeating task,
8015 and still retain the repeater to cover future instances of the task."
8016 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8017 (let (beg end template task idprop
8018 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8019 (drawer-re org-drawer-regexp))
8020 (if (not (and (integerp n) (> n 0)))
8021 (error "Invalid number of replications %s" n))
8022 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8023 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8024 shift)))
8025 (error "Invalid shift specification %s" shift))
8026 (when doshift
8027 (setq shift-n (string-to-number (match-string 1 shift))
8028 shift-what (cdr (assoc (match-string 2 shift)
8029 '(("d" . day) ("w" . week)
8030 ("m" . month) ("y" . year))))))
8031 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8032 (setq nmin 1 nmax n)
8033 (org-back-to-heading t)
8034 (setq beg (point))
8035 (setq idprop (org-entry-get nil "ID"))
8036 (org-end-of-subtree t t)
8037 (or (bolp) (insert "\n"))
8038 (setq end (point))
8039 (setq template (buffer-substring beg end))
8040 (when (and doshift
8041 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8042 (delete-region beg end)
8043 (setq end beg)
8044 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8045 (goto-char end)
8046 (loop for n from nmin to nmax do
8047 ;; prepare clone
8048 (with-temp-buffer
8049 (insert template)
8050 (org-mode)
8051 (goto-char (point-min))
8052 (org-show-subtree)
8053 (and idprop (if org-clone-delete-id
8054 (org-entry-delete nil "ID")
8055 (org-id-get-create t)))
8056 (unless (= n 0)
8057 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8058 (kill-whole-line))
8059 (goto-char (point-min))
8060 (while (re-search-forward drawer-re nil t)
8061 (mapc (lambda (d)
8062 (org-remove-empty-drawer-at d (point))) org-drawers)))
8063 (goto-char (point-min))
8064 (when doshift
8065 (while (re-search-forward org-ts-regexp-both nil t)
8066 (org-timestamp-change (* n shift-n) shift-what))
8067 (unless (= n n-no-remove)
8068 (goto-char (point-min))
8069 (while (re-search-forward org-ts-regexp nil t)
8070 (save-excursion
8071 (goto-char (match-beginning 0))
8072 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8073 (delete-region (match-beginning 1) (match-end 1)))))))
8074 (setq task (buffer-string)))
8075 (insert task))
8076 (goto-char beg)))
8078 ;;; Outline Sorting
8080 (defun org-sort (with-case)
8081 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8082 Optional argument WITH-CASE means sort case-sensitively."
8083 (interactive "P")
8084 (cond
8085 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8086 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8088 (org-call-with-arg 'org-sort-entries with-case))))
8090 (defun org-sort-remove-invisible (s)
8091 (remove-text-properties 0 (length s) org-rm-props s)
8092 (while (string-match org-bracket-link-regexp s)
8093 (setq s (replace-match (if (match-end 2)
8094 (match-string 3 s)
8095 (match-string 1 s)) t t s)))
8098 (defvar org-priority-regexp) ; defined later in the file
8100 (defvar org-after-sorting-entries-or-items-hook nil
8101 "Hook that is run after a bunch of entries or items have been sorted.
8102 When children are sorted, the cursor is in the parent line when this
8103 hook gets called. When a region or a plain list is sorted, the cursor
8104 will be in the first entry of the sorted region/list.")
8106 (defun org-sort-entries
8107 (&optional with-case sorting-type getkey-func compare-func property)
8108 "Sort entries on a certain level of an outline tree.
8109 If there is an active region, the entries in the region are sorted.
8110 Else, if the cursor is before the first entry, sort the top-level items.
8111 Else, the children of the entry at point are sorted.
8113 Sorting can be alphabetically, numerically, by date/time as given by
8114 a time stamp, by a property or by priority.
8116 The command prompts for the sorting type unless it has been given to the
8117 function through the SORTING-TYPE argument, which needs to be a character,
8118 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8119 precise meaning of each character:
8121 n Numerically, by converting the beginning of the entry/item to a number.
8122 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8123 t By date/time, either the first active time stamp in the entry, or, if
8124 none exist, by the first inactive one.
8125 s By the scheduled date/time.
8126 d By deadline date/time.
8127 c By creation time, which is assumed to be the first inactive time stamp
8128 at the beginning of a line.
8129 p By priority according to the cookie.
8130 r By the value of a property.
8132 Capital letters will reverse the sort order.
8134 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8135 called with point at the beginning of the record. It must return either
8136 a string or a number that should serve as the sorting key for that record.
8138 Comparing entries ignores case by default. However, with an optional argument
8139 WITH-CASE, the sorting considers case as well."
8140 (interactive "P")
8141 (let ((case-func (if with-case 'identity 'downcase))
8142 start beg end stars re re2
8143 txt what tmp)
8144 ;; Find beginning and end of region to sort
8145 (cond
8146 ((org-region-active-p)
8147 ;; we will sort the region
8148 (setq end (region-end)
8149 what "region")
8150 (goto-char (region-beginning))
8151 (if (not (org-at-heading-p)) (outline-next-heading))
8152 (setq start (point)))
8153 ((or (org-at-heading-p)
8154 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8155 ;; we will sort the children of the current headline
8156 (org-back-to-heading)
8157 (setq start (point)
8158 end (progn (org-end-of-subtree t t)
8159 (or (bolp) (insert "\n"))
8160 (org-back-over-empty-lines)
8161 (point))
8162 what "children")
8163 (goto-char start)
8164 (show-subtree)
8165 (outline-next-heading))
8167 ;; we will sort the top-level entries in this file
8168 (goto-char (point-min))
8169 (or (org-at-heading-p) (outline-next-heading))
8170 (setq start (point))
8171 (goto-char (point-max))
8172 (beginning-of-line 1)
8173 (when (looking-at ".*?\\S-")
8174 ;; File ends in a non-white line
8175 (end-of-line 1)
8176 (insert "\n"))
8177 (setq end (point-max))
8178 (setq what "top-level")
8179 (goto-char start)
8180 (show-all)))
8182 (setq beg (point))
8183 (if (>= beg end) (error "Nothing to sort"))
8185 (looking-at "\\(\\*+\\)")
8186 (setq stars (match-string 1)
8187 re (concat "^" (regexp-quote stars) " +")
8188 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8189 txt (buffer-substring beg end))
8190 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8191 (if (and (not (equal stars "*")) (string-match re2 txt))
8192 (error "Region to sort contains a level above the first entry"))
8194 (unless sorting-type
8195 (message
8196 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8197 [t]ime [s]cheduled [d]eadline [c]reated
8198 A/N/T/S/D/C/P/O/F means reversed:"
8199 what)
8200 (setq sorting-type (read-char-exclusive))
8202 (and (= (downcase sorting-type) ?f)
8203 (setq getkey-func
8204 (org-icompleting-read "Sort using function: "
8205 obarray 'fboundp t nil nil))
8206 (setq getkey-func (intern getkey-func)))
8208 (and (= (downcase sorting-type) ?r)
8209 (setq property
8210 (org-icompleting-read "Property: "
8211 (mapcar 'list (org-buffer-property-keys t))
8212 nil t))))
8214 (message "Sorting entries...")
8216 (save-restriction
8217 (narrow-to-region start end)
8218 (let ((dcst (downcase sorting-type))
8219 (case-fold-search nil)
8220 (now (current-time)))
8221 (sort-subr
8222 (/= dcst sorting-type)
8223 ;; This function moves to the beginning character of the "record" to
8224 ;; be sorted.
8225 (lambda nil
8226 (if (re-search-forward re nil t)
8227 (goto-char (match-beginning 0))
8228 (goto-char (point-max))))
8229 ;; This function moves to the last character of the "record" being
8230 ;; sorted.
8231 (lambda nil
8232 (save-match-data
8233 (condition-case nil
8234 (outline-forward-same-level 1)
8235 (error
8236 (goto-char (point-max))))))
8237 ;; This function returns the value that gets sorted against.
8238 (lambda nil
8239 (cond
8240 ((= dcst ?n)
8241 (if (looking-at org-complex-heading-regexp)
8242 (string-to-number (match-string 4))
8243 nil))
8244 ((= dcst ?a)
8245 (if (looking-at org-complex-heading-regexp)
8246 (funcall case-func (match-string 4))
8247 nil))
8248 ((= dcst ?t)
8249 (let ((end (save-excursion (outline-next-heading) (point))))
8250 (if (or (re-search-forward org-ts-regexp end t)
8251 (re-search-forward org-ts-regexp-both end t))
8252 (org-time-string-to-seconds (match-string 0))
8253 (org-float-time now))))
8254 ((= dcst ?c)
8255 (let ((end (save-excursion (outline-next-heading) (point))))
8256 (if (re-search-forward
8257 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8258 end t)
8259 (org-time-string-to-seconds (match-string 0))
8260 (org-float-time now))))
8261 ((= dcst ?s)
8262 (let ((end (save-excursion (outline-next-heading) (point))))
8263 (if (re-search-forward org-scheduled-time-regexp end t)
8264 (org-time-string-to-seconds (match-string 1))
8265 (org-float-time now))))
8266 ((= dcst ?d)
8267 (let ((end (save-excursion (outline-next-heading) (point))))
8268 (if (re-search-forward org-deadline-time-regexp end t)
8269 (org-time-string-to-seconds (match-string 1))
8270 (org-float-time now))))
8271 ((= dcst ?p)
8272 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8273 (string-to-char (match-string 2))
8274 org-default-priority))
8275 ((= dcst ?r)
8276 (or (org-entry-get nil property) ""))
8277 ((= dcst ?o)
8278 (if (looking-at org-complex-heading-regexp)
8279 (- 9999 (length (member (match-string 2)
8280 org-todo-keywords-1)))))
8281 ((= dcst ?f)
8282 (if getkey-func
8283 (progn
8284 (setq tmp (funcall getkey-func))
8285 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8286 tmp)
8287 (error "Invalid key function `%s'" getkey-func)))
8288 (t (error "Invalid sorting type `%c'" sorting-type))))
8290 (cond
8291 ((= dcst ?a) 'string<)
8292 ((= dcst ?f) compare-func)
8293 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8294 (t nil)))))
8295 (run-hooks 'org-after-sorting-entries-or-items-hook)
8296 (message "Sorting entries...done")))
8298 (defun org-do-sort (table what &optional with-case sorting-type)
8299 "Sort TABLE of WHAT according to SORTING-TYPE.
8300 The user will be prompted for the SORTING-TYPE if the call to this
8301 function does not specify it. WHAT is only for the prompt, to indicate
8302 what is being sorted. The sorting key will be extracted from
8303 the car of the elements of the table.
8304 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8305 (unless sorting-type
8306 (message
8307 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8308 what)
8309 (setq sorting-type (read-char-exclusive)))
8310 (let ((dcst (downcase sorting-type))
8311 extractfun comparefun)
8312 ;; Define the appropriate functions
8313 (cond
8314 ((= dcst ?n)
8315 (setq extractfun 'string-to-number
8316 comparefun (if (= dcst sorting-type) '< '>)))
8317 ((= dcst ?a)
8318 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8319 (lambda(x) (downcase (org-sort-remove-invisible x))))
8320 comparefun (if (= dcst sorting-type)
8321 'string<
8322 (lambda (a b) (and (not (string< a b))
8323 (not (string= a b)))))))
8324 ((= dcst ?t)
8325 (setq extractfun
8326 (lambda (x)
8327 (if (or (string-match org-ts-regexp x)
8328 (string-match org-ts-regexp-both x))
8329 (org-float-time
8330 (org-time-string-to-time (match-string 0 x)))
8332 comparefun (if (= dcst sorting-type) '< '>)))
8333 (t (error "Invalid sorting type `%c'" sorting-type)))
8335 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8336 table)
8337 (lambda (a b) (funcall comparefun (car a) (car b))))))
8340 ;;; The orgstruct minor mode
8342 ;; Define a minor mode which can be used in other modes in order to
8343 ;; integrate the org-mode structure editing commands.
8345 ;; This is really a hack, because the org-mode structure commands use
8346 ;; keys which normally belong to the major mode. Here is how it
8347 ;; works: The minor mode defines all the keys necessary to operate the
8348 ;; structure commands, but wraps the commands into a function which
8349 ;; tests if the cursor is currently at a headline or a plain list
8350 ;; item. If that is the case, the structure command is used,
8351 ;; temporarily setting many Org-mode variables like regular
8352 ;; expressions for filling etc. However, when any of those keys is
8353 ;; used at a different location, function uses `key-binding' to look
8354 ;; up if the key has an associated command in another currently active
8355 ;; keymap (minor modes, major mode, global), and executes that
8356 ;; command. There might be problems if any of the keys is otherwise
8357 ;; used as a prefix key.
8359 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8360 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8361 ;; addresses this by checking explicitly for both bindings.
8363 (defvar orgstruct-mode-map (make-sparse-keymap)
8364 "Keymap for the minor `orgstruct-mode'.")
8366 (defvar org-local-vars nil
8367 "List of local variables, for use by `orgstruct-mode'.")
8369 ;;;###autoload
8370 (define-minor-mode orgstruct-mode
8371 "Toggle the minor mode `orgstruct-mode'.
8372 This mode is for using Org-mode structure commands in other
8373 modes. The following keys behave as if Org-mode were active, if
8374 the cursor is on a headline, or on a plain list item (both as
8375 defined by Org-mode).
8377 M-up Move entry/item up
8378 M-down Move entry/item down
8379 M-left Promote
8380 M-right Demote
8381 M-S-up Move entry/item up
8382 M-S-down Move entry/item down
8383 M-S-left Promote subtree
8384 M-S-right Demote subtree
8385 M-q Fill paragraph and items like in Org-mode
8386 C-c ^ Sort entries
8387 C-c - Cycle list bullet
8388 TAB Cycle item visibility
8389 M-RET Insert new heading/item
8390 S-M-RET Insert new TODO heading / Checkbox item
8391 C-c C-c Set tags / toggle checkbox"
8392 nil " OrgStruct" nil
8393 (org-load-modules-maybe)
8394 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8396 ;;;###autoload
8397 (defun turn-on-orgstruct ()
8398 "Unconditionally turn on `orgstruct-mode'."
8399 (orgstruct-mode 1))
8401 (defvar org-fb-vars nil)
8402 (make-variable-buffer-local 'org-fb-vars)
8403 (defun orgstruct++-mode (&optional arg)
8404 "Toggle `orgstruct-mode', the enhanced version of it.
8405 In addition to setting orgstruct-mode, this also exports all
8406 indentation and autofilling variables from org-mode into the
8407 buffer. It will also recognize item context in multiline items."
8408 (interactive "P")
8409 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8410 (if (< arg 1)
8411 (progn (orgstruct-mode -1)
8412 (mapc (lambda(v)
8413 (org-set-local (car v)
8414 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8415 org-fb-vars))
8416 (orgstruct-mode 1)
8417 (setq org-fb-vars nil)
8418 (let (var val)
8419 (mapc
8420 (lambda (x)
8421 (when (string-match
8422 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8423 (symbol-name (car x)))
8424 (setq var (car x) val (nth 1 x))
8425 (push (list var `(quote ,(eval var))) org-fb-vars)
8426 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8427 org-local-vars)
8428 (org-set-local 'orgstruct-is-++ t))))
8430 (defvar orgstruct-is-++ nil
8431 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8432 (make-variable-buffer-local 'orgstruct-is-++)
8434 ;;;###autoload
8435 (defun turn-on-orgstruct++ ()
8436 "Unconditionally turn on `orgstruct++-mode'."
8437 (orgstruct++-mode 1))
8439 (defun orgstruct-error ()
8440 "Error when there is no default binding for a structure key."
8441 (interactive)
8442 (error "This key has no function outside structure elements"))
8444 (defun orgstruct-setup ()
8445 "Setup orgstruct keymaps."
8446 (let ((nfunc 0)
8447 (bindings
8448 (list
8449 '([(meta up)] org-metaup)
8450 '([(meta down)] org-metadown)
8451 '([(meta left)] org-metaleft)
8452 '([(meta right)] org-metaright)
8453 '([(meta shift up)] org-shiftmetaup)
8454 '([(meta shift down)] org-shiftmetadown)
8455 '([(meta shift left)] org-shiftmetaleft)
8456 '([(meta shift right)] org-shiftmetaright)
8457 '([?\e (up)] org-metaup)
8458 '([?\e (down)] org-metadown)
8459 '([?\e (left)] org-metaleft)
8460 '([?\e (right)] org-metaright)
8461 '([?\e (shift up)] org-shiftmetaup)
8462 '([?\e (shift down)] org-shiftmetadown)
8463 '([?\e (shift left)] org-shiftmetaleft)
8464 '([?\e (shift right)] org-shiftmetaright)
8465 '([(shift up)] org-shiftup)
8466 '([(shift down)] org-shiftdown)
8467 '([(shift left)] org-shiftleft)
8468 '([(shift right)] org-shiftright)
8469 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8470 '("\M-q" fill-paragraph)
8471 '("\C-c^" org-sort)
8472 '("\C-c-" org-cycle-list-bullet)))
8473 elt key fun cmd)
8474 (while (setq elt (pop bindings))
8475 (setq nfunc (1+ nfunc))
8476 (setq key (org-key (car elt))
8477 fun (nth 1 elt)
8478 cmd (orgstruct-make-binding fun nfunc key))
8479 (org-defkey orgstruct-mode-map key cmd))
8481 ;; Special treatment needed for TAB and RET
8482 (org-defkey orgstruct-mode-map [(tab)]
8483 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8484 (org-defkey orgstruct-mode-map "\C-i"
8485 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8487 (org-defkey orgstruct-mode-map "\M-\C-m"
8488 (orgstruct-make-binding 'org-insert-heading 105
8489 "\M-\C-m" [(meta return)]))
8490 (org-defkey orgstruct-mode-map [(meta return)]
8491 (orgstruct-make-binding 'org-insert-heading 106
8492 [(meta return)] "\M-\C-m"))
8494 (org-defkey orgstruct-mode-map [(shift meta return)]
8495 (orgstruct-make-binding 'org-insert-todo-heading 107
8496 [(meta return)] "\M-\C-m"))
8498 (org-defkey orgstruct-mode-map "\e\C-m"
8499 (orgstruct-make-binding 'org-insert-heading 108
8500 "\e\C-m" [?\e (return)]))
8501 (org-defkey orgstruct-mode-map [?\e (return)]
8502 (orgstruct-make-binding 'org-insert-heading 109
8503 [?\e (return)] "\e\C-m"))
8504 (org-defkey orgstruct-mode-map [?\e (shift return)]
8505 (orgstruct-make-binding 'org-insert-todo-heading 110
8506 [?\e (return)] "\e\C-m"))
8508 (unless org-local-vars
8509 (setq org-local-vars (org-get-local-variables)))
8513 (defun orgstruct-make-binding (fun n &rest keys)
8514 "Create a function for binding in the structure minor mode.
8515 FUN is the command to call inside a table. N is used to create a unique
8516 command name. KEYS are keys that should be checked in for a command
8517 to execute outside of tables."
8518 (eval
8519 (list 'defun
8520 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8521 '(arg)
8522 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8523 "Outside of structure, run the binding of `"
8524 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8525 "'.")
8526 '(interactive "p")
8527 (list 'if
8528 `(org-context-p 'headline 'item
8529 (and orgstruct-is-++
8530 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8531 'item-body))
8532 (list 'org-run-like-in-org-mode (list 'quote fun))
8533 (list 'let '(orgstruct-mode)
8534 (list 'call-interactively
8535 (append '(or)
8536 (mapcar (lambda (k)
8537 (list 'key-binding k))
8538 keys)
8539 '('orgstruct-error))))))))
8541 (defun org-context-p (&rest contexts)
8542 "Check if local context is any of CONTEXTS.
8543 Possible values in the list of contexts are `table', `headline', and `item'."
8544 (let ((pos (point)))
8545 (goto-char (point-at-bol))
8546 (prog1 (or (and (memq 'table contexts)
8547 (looking-at "[ \t]*|"))
8548 (and (memq 'headline contexts)
8549 (looking-at org-outline-regexp))
8550 (and (memq 'item contexts)
8551 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8552 (and (memq 'item-body contexts)
8553 (org-in-item-p)))
8554 (goto-char pos))))
8556 (defun org-get-local-variables ()
8557 "Return a list of all local variables in an org-mode buffer."
8558 (let (varlist)
8559 (with-current-buffer (get-buffer-create "*Org tmp*")
8560 (erase-buffer)
8561 (org-mode)
8562 (setq varlist (buffer-local-variables)))
8563 (kill-buffer "*Org tmp*")
8564 (delq nil
8565 (mapcar
8566 (lambda (x)
8567 (setq x
8568 (if (symbolp x)
8569 (list x)
8570 (list (car x) (list 'quote (cdr x)))))
8571 (if (string-match
8572 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8573 (symbol-name (car x)))
8574 x nil))
8575 varlist))))
8577 (defun org-clone-local-variables (from-buffer &optional regexp)
8578 "Clone local variables from FROM-BUFFER.
8579 Optional argument REGEXP selects variables to clone."
8580 (mapc
8581 (lambda (pair)
8582 (and (symbolp (car pair))
8583 (or (null regexp)
8584 (string-match regexp (symbol-name (car pair))))
8585 (set (make-local-variable (car pair))
8586 (cdr pair))))
8587 (buffer-local-variables from-buffer)))
8589 ;;;###autoload
8590 (defun org-run-like-in-org-mode (cmd)
8591 "Run a command, pretending that the current buffer is in Org-mode.
8592 This will temporarily bind local variables that are typically bound in
8593 Org-mode to the values they have in Org-mode, and then interactively
8594 call CMD."
8595 (org-load-modules-maybe)
8596 (unless org-local-vars
8597 (setq org-local-vars (org-get-local-variables)))
8598 (eval (list 'let org-local-vars
8599 (list 'call-interactively (list 'quote cmd)))))
8601 ;;;; Archiving
8603 (defun org-get-category (&optional pos force-refresh)
8604 "Get the category applying to position POS."
8605 (save-match-data
8606 (if force-refresh (org-refresh-category-properties))
8607 (let ((pos (or pos (point))))
8608 (or (get-text-property pos 'org-category)
8609 (progn (org-refresh-category-properties)
8610 (get-text-property pos 'org-category))))))
8612 (defun org-refresh-category-properties ()
8613 "Refresh category text properties in the buffer."
8614 (let ((inhibit-read-only t)
8615 (def-cat (cond
8616 ((null org-category)
8617 (if buffer-file-name
8618 (file-name-sans-extension
8619 (file-name-nondirectory buffer-file-name))
8620 "???"))
8621 ((symbolp org-category) (symbol-name org-category))
8622 (t org-category)))
8623 beg end cat pos optionp)
8624 (org-unmodified
8625 (save-excursion
8626 (save-restriction
8627 (widen)
8628 (goto-char (point-min))
8629 (put-text-property (point) (point-max) 'org-category def-cat)
8630 (while (re-search-forward
8631 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8632 (setq pos (match-end 0)
8633 optionp (equal (char-after (match-beginning 0)) ?#)
8634 cat (org-trim (match-string 2)))
8635 (if optionp
8636 (setq beg (point-at-bol) end (point-max))
8637 (org-back-to-heading t)
8638 (setq beg (point) end (org-end-of-subtree t t)))
8639 (put-text-property beg end 'org-category cat)
8640 (put-text-property beg end 'org-category-position beg)
8641 (goto-char pos)))))))
8644 ;;;; Link Stuff
8646 ;;; Link abbreviations
8648 (defun org-link-expand-abbrev (link)
8649 "Apply replacements as defined in `org-link-abbrev-alist'."
8650 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8651 (let* ((key (match-string 1 link))
8652 (as (or (assoc key org-link-abbrev-alist-local)
8653 (assoc key org-link-abbrev-alist)))
8654 (tag (and (match-end 2) (match-string 3 link)))
8655 rpl)
8656 (if (not as)
8657 link
8658 (setq rpl (cdr as))
8659 (cond
8660 ((symbolp rpl) (funcall rpl tag))
8661 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8662 ((string-match "%h" rpl)
8663 (replace-match (url-hexify-string (or tag "")) t t rpl))
8664 (t (concat rpl tag)))))
8665 link))
8667 ;;; Storing and inserting links
8669 (defvar org-insert-link-history nil
8670 "Minibuffer history for links inserted with `org-insert-link'.")
8672 (defvar org-stored-links nil
8673 "Contains the links stored with `org-store-link'.")
8675 (defvar org-store-link-plist nil
8676 "Plist with info about the most recently link created with `org-store-link'.")
8678 (defvar org-link-protocols nil
8679 "Link protocols added to Org-mode using `org-add-link-type'.")
8681 (defvar org-store-link-functions nil
8682 "List of functions that are called to create and store a link.
8683 Each function will be called in turn until one returns a non-nil
8684 value. Each function should check if it is responsible for creating
8685 this link (for example by looking at the major mode).
8686 If not, it must exit and return nil.
8687 If yes, it should return a non-nil value after a calling
8688 `org-store-link-props' with a list of properties and values.
8689 Special properties are:
8691 :type The link prefix, like \"http\". This must be given.
8692 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8693 This is obligatory as well.
8694 :description Optional default description for the second pair
8695 of brackets in an Org-mode link. The user can still change
8696 this when inserting this link into an Org-mode buffer.
8698 In addition to these, any additional properties can be specified
8699 and then used in remember templates.")
8701 (defun org-add-link-type (type &optional follow export)
8702 "Add TYPE to the list of `org-link-types'.
8703 Re-compute all regular expressions depending on `org-link-types'
8705 FOLLOW and EXPORT are two functions.
8707 FOLLOW should take the link path as the single argument and do whatever
8708 is necessary to follow the link, for example find a file or display
8709 a mail message.
8711 EXPORT should format the link path for export to one of the export formats.
8712 It should be a function accepting three arguments:
8714 path the path of the link, the text after the prefix (like \"http:\")
8715 desc the description of the link, if any, or a description added by
8716 org-export-normalize-links if there is none
8717 format the export format, a symbol like `html' or `latex' or `ascii'..
8719 The function may use the FORMAT information to return different values
8720 depending on the format. The return value will be put literally into
8721 the exported file. If the return value is nil, this means Org should
8722 do what it normally does with links which do not have EXPORT defined.
8724 Org-mode has a built-in default for exporting links. If you are happy with
8725 this default, there is no need to define an export function for the link
8726 type. For a simple example of an export function, see `org-bbdb.el'."
8727 (add-to-list 'org-link-types type t)
8728 (org-make-link-regexps)
8729 (if (assoc type org-link-protocols)
8730 (setcdr (assoc type org-link-protocols) (list follow export))
8731 (push (list type follow export) org-link-protocols)))
8733 (defvar org-agenda-buffer-name)
8735 ;;;###autoload
8736 (defun org-store-link (arg)
8737 "\\<org-mode-map>Store an org-link to the current location.
8738 This link is added to `org-stored-links' and can later be inserted
8739 into an org-buffer with \\[org-insert-link].
8741 For some link types, a prefix arg is interpreted:
8742 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8743 For file links, arg negates `org-context-in-file-links'."
8744 (interactive "P")
8745 (org-load-modules-maybe)
8746 (setq org-store-link-plist nil) ; reset
8747 (org-with-limited-levels
8748 (let (link cpltxt desc description search txt custom-id agenda-link)
8749 (cond
8751 ((run-hook-with-args-until-success 'org-store-link-functions)
8752 (setq link (plist-get org-store-link-plist :link)
8753 desc (or (plist-get org-store-link-plist :description) link)))
8755 ((org-src-edit-buffer-p)
8756 (let (label gc)
8757 (while (or (not label)
8758 (save-excursion
8759 (save-restriction
8760 (widen)
8761 (goto-char (point-min))
8762 (re-search-forward
8763 (regexp-quote (format org-coderef-label-format label))
8764 nil t))))
8765 (when label (message "Label exists already") (sit-for 2))
8766 (setq label (read-string "Code line label: " label)))
8767 (end-of-line 1)
8768 (setq link (format org-coderef-label-format label))
8769 (setq gc (- 79 (length link)))
8770 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8771 (insert link)
8772 (setq link (concat "(" label ")") desc nil)))
8774 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8775 ;; We are in the agenda, link to referenced location
8776 (let ((m (or (get-text-property (point) 'org-hd-marker)
8777 (get-text-property (point) 'org-marker))))
8778 (when m
8779 (org-with-point-at m
8780 (setq agenda-link
8781 (if (org-called-interactively-p 'any)
8782 (call-interactively 'org-store-link)
8783 (org-store-link nil)))))))
8785 ((eq major-mode 'calendar-mode)
8786 (let ((cd (calendar-cursor-to-date)))
8787 (setq link
8788 (format-time-string
8789 (car org-time-stamp-formats)
8790 (apply 'encode-time
8791 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8792 nil nil nil))))
8793 (org-store-link-props :type "calendar" :date cd)))
8795 ((eq major-mode 'w3-mode)
8796 (setq cpltxt (if (and (buffer-name)
8797 (not (string-match "Untitled" (buffer-name))))
8798 (buffer-name)
8799 (url-view-url t))
8800 link (org-make-link (url-view-url t)))
8801 (org-store-link-props :type "w3" :url (url-view-url t)))
8803 ((eq major-mode 'w3m-mode)
8804 (setq cpltxt (or w3m-current-title w3m-current-url)
8805 link (org-make-link w3m-current-url))
8806 (org-store-link-props :type "w3m" :url (url-view-url t)))
8808 ((setq search (run-hook-with-args-until-success
8809 'org-create-file-search-functions))
8810 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8811 "::" search))
8812 (setq cpltxt (or description link)))
8814 ((eq major-mode 'image-mode)
8815 (setq cpltxt (concat "file:"
8816 (abbreviate-file-name buffer-file-name))
8817 link (org-make-link cpltxt))
8818 (org-store-link-props :type "image" :file buffer-file-name))
8820 ((eq major-mode 'dired-mode)
8821 ;; link to the file in the current line
8822 (let ((file (dired-get-filename nil t)))
8823 (setq file (if file
8824 (abbreviate-file-name
8825 (expand-file-name (dired-get-filename nil t)))
8826 ;; otherwise, no file so use current directory.
8827 default-directory))
8828 (setq cpltxt (concat "file:" file)
8829 link (org-make-link cpltxt))))
8831 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8832 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8833 (cond
8834 ((org-in-regexp "<<\\(.*?\\)>>")
8835 (setq cpltxt
8836 (concat "file:"
8837 (abbreviate-file-name
8838 (buffer-file-name (buffer-base-buffer)))
8839 "::" (match-string 1))
8840 link (org-make-link cpltxt)))
8841 ((and (featurep 'org-id)
8842 (or (eq org-link-to-org-use-id t)
8843 (and (eq org-link-to-org-use-id 'create-if-interactive)
8844 (org-called-interactively-p 'any))
8845 (and (eq org-link-to-org-use-id
8846 'create-if-interactive-and-no-custom-id)
8847 (org-called-interactively-p 'any)
8848 (not custom-id))
8849 (and org-link-to-org-use-id
8850 (org-entry-get nil "ID"))))
8851 ;; We can make a link using the ID.
8852 (setq link (condition-case nil
8853 (prog1 (org-id-store-link)
8854 (setq desc (plist-get org-store-link-plist
8855 :description)))
8856 (error
8857 ;; probably before first headline, link to file only
8858 (concat "file:"
8859 (abbreviate-file-name
8860 (buffer-file-name (buffer-base-buffer))))))))
8862 ;; Just link to current headline
8863 (setq cpltxt (concat "file:"
8864 (abbreviate-file-name
8865 (buffer-file-name (buffer-base-buffer)))))
8866 ;; Add a context search string
8867 (when (org-xor org-context-in-file-links arg)
8868 (setq txt (cond
8869 ((org-at-heading-p) nil)
8870 ((org-region-active-p)
8871 (buffer-substring (region-beginning) (region-end)))
8872 (t nil)))
8873 (when (or (null txt) (string-match "\\S-" txt))
8874 (setq cpltxt
8875 (concat cpltxt "::"
8876 (condition-case nil
8877 (org-make-org-heading-search-string txt)
8878 (error "")))
8879 desc (or (nth 4 (ignore-errors
8880 (org-heading-components))) "NONE"))))
8881 (if (string-match "::\\'" cpltxt)
8882 (setq cpltxt (substring cpltxt 0 -2)))
8883 (setq link (org-make-link cpltxt)))))
8885 ((buffer-file-name (buffer-base-buffer))
8886 ;; Just link to this file here.
8887 (setq cpltxt (concat "file:"
8888 (abbreviate-file-name
8889 (buffer-file-name (buffer-base-buffer)))))
8890 ;; Add a context string
8891 (when (org-xor org-context-in-file-links arg)
8892 (setq txt (if (org-region-active-p)
8893 (buffer-substring (region-beginning) (region-end))
8894 (buffer-substring (point-at-bol) (point-at-eol))))
8895 ;; Only use search option if there is some text.
8896 (when (string-match "\\S-" txt)
8897 (setq cpltxt
8898 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8899 desc "NONE")))
8900 (setq link (org-make-link cpltxt)))
8902 ((org-called-interactively-p 'interactive)
8903 (error "Cannot link to a buffer which is not visiting a file"))
8905 (t (setq link nil)))
8907 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8908 (setq link (or link cpltxt)
8909 desc (or desc cpltxt))
8910 (if (equal desc "NONE") (setq desc nil))
8912 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8913 (progn
8914 (setq org-stored-links
8915 (cons (list link desc) org-stored-links))
8916 (message "Stored: %s" (or desc link))
8917 (when custom-id
8918 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8919 "::#" custom-id))
8920 (setq org-stored-links
8921 (cons (list link desc) org-stored-links))))
8922 (or agenda-link (and link (org-make-link-string link desc)))))))
8924 (defun org-store-link-props (&rest plist)
8925 "Store link properties, extract names and addresses."
8926 (let (x adr)
8927 (when (setq x (plist-get plist :from))
8928 (setq adr (mail-extract-address-components x))
8929 (setq plist (plist-put plist :fromname (car adr)))
8930 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8931 (when (setq x (plist-get plist :to))
8932 (setq adr (mail-extract-address-components x))
8933 (setq plist (plist-put plist :toname (car adr)))
8934 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8935 (let ((from (plist-get plist :from))
8936 (to (plist-get plist :to)))
8937 (when (and from to org-from-is-user-regexp)
8938 (setq plist
8939 (plist-put plist :fromto
8940 (if (string-match org-from-is-user-regexp from)
8941 (concat "to %t")
8942 (concat "from %f"))))))
8943 (setq org-store-link-plist plist))
8945 (defun org-add-link-props (&rest plist)
8946 "Add these properties to the link property list."
8947 (let (key value)
8948 (while plist
8949 (setq key (pop plist) value (pop plist))
8950 (setq org-store-link-plist
8951 (plist-put org-store-link-plist key value)))))
8953 (defun org-email-link-description (&optional fmt)
8954 "Return the description part of an email link.
8955 This takes information from `org-store-link-plist' and formats it
8956 according to FMT (default from `org-email-link-description-format')."
8957 (setq fmt (or fmt org-email-link-description-format))
8958 (let* ((p org-store-link-plist)
8959 (to (plist-get p :toaddress))
8960 (from (plist-get p :fromaddress))
8961 (table
8962 (list
8963 (cons "%c" (plist-get p :fromto))
8964 (cons "%F" (plist-get p :from))
8965 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8966 (cons "%T" (plist-get p :to))
8967 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8968 (cons "%s" (plist-get p :subject))
8969 (cons "%d" (plist-get p :date))
8970 (cons "%m" (plist-get p :message-id)))))
8971 (when (string-match "%c" fmt)
8972 ;; Check if the user wrote this message
8973 (if (and org-from-is-user-regexp from to
8974 (save-match-data (string-match org-from-is-user-regexp from)))
8975 (setq fmt (replace-match "to %t" t t fmt))
8976 (setq fmt (replace-match "from %f" t t fmt))))
8977 (org-replace-escapes fmt table)))
8979 (defun org-make-org-heading-search-string (&optional string heading)
8980 "Make search string for STRING or current headline."
8981 (interactive)
8982 (let ((s (or string (org-get-heading)))
8983 (lines org-context-in-file-links))
8984 (unless (and string (not heading))
8985 ;; We are using a headline, clean up garbage in there.
8986 (if (string-match org-todo-regexp s)
8987 (setq s (replace-match "" t t s)))
8988 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8989 (setq s (replace-match "" t t s)))
8990 (setq s (org-trim s))
8991 (if (string-match (concat "^\\(" org-quote-string "\\|"
8992 org-comment-string "\\)") s)
8993 (setq s (replace-match "" t t s)))
8994 (while (string-match org-ts-regexp s)
8995 (setq s (replace-match "" t t s))))
8996 (or string (setq s (concat "*" s))) ; Add * for headlines
8997 (when (and string (integerp lines) (> lines 0))
8998 (let ((slines (org-split-string s "\n")))
8999 (when (< lines (length slines))
9000 (setq s (mapconcat
9001 'identity
9002 (reverse (nthcdr (- (length slines) lines)
9003 (reverse slines))) "\n")))))
9004 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9006 (defun org-make-link (&rest strings)
9007 "Concatenate STRINGS."
9008 (apply 'concat strings))
9010 (defun org-make-link-string (link &optional description)
9011 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9012 (unless (string-match "\\S-" link)
9013 (error "Empty link"))
9014 (when (and description
9015 (stringp description)
9016 (not (string-match "\\S-" description)))
9017 (setq description nil))
9018 (when (stringp description)
9019 ;; Remove brackets from the description, they are fatal.
9020 (while (string-match "\\[" description)
9021 (setq description (replace-match "{" t t description)))
9022 (while (string-match "\\]" description)
9023 (setq description (replace-match "}" t t description))))
9024 (when (equal link description)
9025 ;; No description needed, it is identical
9026 (setq description nil))
9027 (when (and (not description)
9028 (not (string-match (org-image-file-name-regexp) link))
9029 (not (equal link (org-link-escape link))))
9030 (setq description (org-extract-attributes link)))
9031 (setq link
9032 (cond ((string-match (org-image-file-name-regexp) link) link)
9033 ((string-match org-link-types-re link)
9034 (concat (match-string 1 link)
9035 (org-link-escape (substring link (match-end 1)))))
9036 (t (org-link-escape link))))
9037 (concat "[[" link "]"
9038 (if description (concat "[" description "]") "")
9039 "]"))
9041 (defconst org-link-escape-chars
9042 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9043 "List of characters that should be escaped in link.
9044 This is the list that is used for internal purposes.")
9046 (defvar org-url-encoding-use-url-hexify nil)
9048 (defconst org-link-escape-chars-browser
9049 '(?\ )
9050 "List of escapes for characters that are problematic in links.
9051 This is the list that is used before handing over to the browser.")
9053 (defun org-link-escape (text &optional table merge)
9054 "Return percent escaped representation of TEXT.
9055 TEXT is a string with the text to escape.
9056 Optional argument TABLE is a list with characters that should be
9057 escaped. When nil, `org-link-escape-chars' is used.
9058 If optional argument MERGE is set, merge TABLE into
9059 `org-link-escape-chars'."
9060 (if (and org-url-encoding-use-url-hexify (not table))
9061 (url-hexify-string text)
9062 (cond
9063 ((and table merge)
9064 (mapc (lambda (defchr)
9065 (unless (member defchr table)
9066 (setq table (cons defchr table)))) org-link-escape-chars))
9067 ((null table)
9068 (setq table org-link-escape-chars)))
9069 (mapconcat
9070 (lambda (char)
9071 (if (or (member char table)
9072 (< char 32) (= char 37) (> char 126))
9073 (mapconcat (lambda (sequence-element)
9074 (format "%%%.2X" sequence-element))
9075 (or (encode-coding-char char 'utf-8)
9076 (error "Unable to percent escape character: %s"
9077 (char-to-string char))) "")
9078 (char-to-string char))) text "")))
9080 (defun org-link-unescape (str)
9081 "Unhex hexified Unicode strings as returned from the JavaScript function
9082 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9083 (unless (and (null str) (string= "" str))
9084 (let ((pos 0) (case-fold-search t) unhexed)
9085 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9086 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9087 (setq str (replace-match unhexed t t str))
9088 (setq pos (+ pos (length unhexed))))))
9089 str)
9091 (defun org-link-unescape-compound (hex)
9092 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9093 Note: this function also decodes single byte encodings like
9094 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9095 (save-match-data
9096 (let* ((bytes (cdr (split-string hex "%")))
9097 (ret "")
9098 (eat 0)
9099 (sum 0))
9100 (while bytes
9101 (let* ((val (string-to-number (pop bytes) 16))
9102 (shift-xor
9103 (if (= 0 eat)
9104 (cond
9105 ((>= val 252) (cons 6 252))
9106 ((>= val 248) (cons 5 248))
9107 ((>= val 240) (cons 4 240))
9108 ((>= val 224) (cons 3 224))
9109 ((>= val 192) (cons 2 192))
9110 (t (cons 0 0)))
9111 (cons 6 128))))
9112 (if (>= val 192) (setq eat (car shift-xor)))
9113 (setq val (logxor val (cdr shift-xor)))
9114 (setq sum (+ (lsh sum (car shift-xor)) val))
9115 (if (> eat 0) (setq eat (- eat 1)))
9116 (cond
9117 ((= 0 eat) ;multi byte
9118 (setq ret (concat ret (org-char-to-string sum)))
9119 (setq sum 0))
9120 ((not bytes) ; single byte(s)
9121 (setq ret (org-link-unescape-single-byte-sequence hex))))
9122 )) ;; end (while bytes
9123 ret )))
9125 (defun org-link-unescape-single-byte-sequence (hex)
9126 "Unhexify hex-encoded single byte character sequences."
9127 (mapconcat (lambda (byte)
9128 (char-to-string (string-to-number byte 16)))
9129 (cdr (split-string hex "%")) ""))
9131 (defun org-xor (a b)
9132 "Exclusive or."
9133 (if a (not b) b))
9135 (defun org-fixup-message-id-for-http (s)
9136 "Replace special characters in a message id, so it can be used in an http query."
9137 (when (string-match "%" s)
9138 (setq s (mapconcat (lambda (c)
9139 (if (eq c ?%)
9140 "%25"
9141 (char-to-string c)))
9142 s "")))
9143 (while (string-match "<" s)
9144 (setq s (replace-match "%3C" t t s)))
9145 (while (string-match ">" s)
9146 (setq s (replace-match "%3E" t t s)))
9147 (while (string-match "@" s)
9148 (setq s (replace-match "%40" t t s)))
9151 (defun org-link-prettify (link)
9152 "Return a human-readable representation of LINK.
9153 The car of LINK must be a raw link the cdr of LINK must be either
9154 a link description or nil."
9155 (let ((desc (or (cadr link) "<no description>")))
9156 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9157 "[[" (car link) "]]")))
9159 ;;;###autoload
9160 (defun org-insert-link-global ()
9161 "Insert a link like Org-mode does.
9162 This command can be called in any mode to insert a link in Org-mode syntax."
9163 (interactive)
9164 (org-load-modules-maybe)
9165 (org-run-like-in-org-mode 'org-insert-link))
9167 (defun org-insert-link (&optional complete-file link-location default-description)
9168 "Insert a link. At the prompt, enter the link.
9170 Completion can be used to insert any of the link protocol prefixes like
9171 http or ftp in use.
9173 The history can be used to select a link previously stored with
9174 `org-store-link'. When the empty string is entered (i.e. if you just
9175 press RET at the prompt), the link defaults to the most recently
9176 stored link. As SPC triggers completion in the minibuffer, you need to
9177 use M-SPC or C-q SPC to force the insertion of a space character.
9179 You will also be prompted for a description, and if one is given, it will
9180 be displayed in the buffer instead of the link.
9182 If there is already a link at point, this command will allow you to edit link
9183 and description parts.
9185 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9186 be selected using completion. The path to the file will be relative to the
9187 current directory if the file is in the current directory or a subdirectory.
9188 Otherwise, the link will be the absolute path as completed in the minibuffer
9189 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9190 option `org-link-file-path-type'.
9192 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9193 the current directory or below.
9195 With three \\[universal-argument] prefixes, negate the meaning of
9196 `org-keep-stored-link-after-insertion'.
9198 If `org-make-link-description-function' is non-nil, this function will be
9199 called with the link target, and the result will be the default
9200 link description.
9202 If the LINK-LOCATION parameter is non-nil, this value will be
9203 used as the link location instead of reading one interactively.
9205 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9206 be used as the default description."
9207 (interactive "P")
9208 (let* ((wcf (current-window-configuration))
9209 (region (if (org-region-active-p)
9210 (buffer-substring (region-beginning) (region-end))))
9211 (remove (and region (list (region-beginning) (region-end))))
9212 (desc region)
9213 tmphist ; byte-compile incorrectly complains about this
9214 (link link-location)
9215 entry file all-prefixes)
9216 (cond
9217 (link-location) ; specified by arg, just use it.
9218 ((org-in-regexp org-bracket-link-regexp 1)
9219 ;; We do have a link at point, and we are going to edit it.
9220 (setq remove (list (match-beginning 0) (match-end 0)))
9221 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9222 (setq link (read-string "Link: "
9223 (org-link-unescape
9224 (org-match-string-no-properties 1)))))
9225 ((or (org-in-regexp org-angle-link-re)
9226 (org-in-regexp org-plain-link-re))
9227 ;; Convert to bracket link
9228 (setq remove (list (match-beginning 0) (match-end 0))
9229 link (read-string "Link: "
9230 (org-remove-angle-brackets (match-string 0)))))
9231 ((member complete-file '((4) (16)))
9232 ;; Completing read for file names.
9233 (setq link (org-file-complete-link complete-file)))
9235 ;; Read link, with completion for stored links.
9236 (with-output-to-temp-buffer "*Org Links*"
9237 (princ "Insert a link.
9238 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9239 (when org-stored-links
9240 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9241 (princ (mapconcat 'org-link-prettify
9242 (reverse org-stored-links) "\n"))))
9243 (let ((cw (selected-window)))
9244 (select-window (get-buffer-window "*Org Links*" 'visible))
9245 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9246 (unless (pos-visible-in-window-p (point-max))
9247 (org-fit-window-to-buffer))
9248 (and (window-live-p cw) (select-window cw)))
9249 ;; Fake a link history, containing the stored links.
9250 (setq tmphist (append (mapcar 'car org-stored-links)
9251 org-insert-link-history))
9252 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9253 (mapcar 'car org-link-abbrev-alist)
9254 org-link-types))
9255 (unwind-protect
9256 (progn
9257 (setq link
9258 (let ((org-completion-use-ido nil)
9259 (org-completion-use-iswitchb nil))
9260 (org-completing-read
9261 "Link: "
9262 (append
9263 (mapcar (lambda (x) (list (concat x ":")))
9264 all-prefixes)
9265 (mapcar 'car org-stored-links))
9266 nil nil nil
9267 'tmphist
9268 (car (car org-stored-links)))))
9269 (if (not (string-match "\\S-" link))
9270 (error "No link selected"))
9271 (if (or (member link all-prefixes)
9272 (and (equal ":" (substring link -1))
9273 (member (substring link 0 -1) all-prefixes)
9274 (setq link (substring link 0 -1))))
9275 (setq link (org-link-try-special-completion link))))
9276 (set-window-configuration wcf)
9277 (kill-buffer "*Org Links*"))
9278 (setq entry (assoc link org-stored-links))
9279 (or entry (push link org-insert-link-history))
9280 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9281 (not org-keep-stored-link-after-insertion))
9282 (setq org-stored-links (delq (assoc link org-stored-links)
9283 org-stored-links)))
9284 (setq desc (or desc (nth 1 entry)))))
9286 (if (string-match org-plain-link-re link)
9287 ;; URL-like link, normalize the use of angular brackets.
9288 (setq link (org-make-link (org-remove-angle-brackets link))))
9290 ;; Check if we are linking to the current file with a search option
9291 ;; If yes, simplify the link by using only the search option.
9292 (when (and buffer-file-name
9293 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9294 (let* ((path (match-string 1 link))
9295 (case-fold-search nil)
9296 (search (match-string 2 link)))
9297 (save-match-data
9298 (if (equal (file-truename buffer-file-name) (file-truename path))
9299 ;; We are linking to this same file, with a search option
9300 (setq link search)))))
9302 ;; Check if we can/should use a relative path. If yes, simplify the link
9303 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9304 (let* ((type (match-string 1 link))
9305 (path (match-string 2 link))
9306 (origpath path)
9307 (case-fold-search nil))
9308 (cond
9309 ((or (eq org-link-file-path-type 'absolute)
9310 (equal complete-file '(16)))
9311 (setq path (abbreviate-file-name (expand-file-name path))))
9312 ((eq org-link-file-path-type 'noabbrev)
9313 (setq path (expand-file-name path)))
9314 ((eq org-link-file-path-type 'relative)
9315 (setq path (file-relative-name path)))
9317 (save-match-data
9318 (if (string-match (concat "^" (regexp-quote
9319 (expand-file-name
9320 (file-name-as-directory
9321 default-directory))))
9322 (expand-file-name path))
9323 ;; We are linking a file with relative path name.
9324 (setq path (substring (expand-file-name path)
9325 (match-end 0)))
9326 (setq path (abbreviate-file-name (expand-file-name path)))))))
9327 (setq link (concat type path))
9328 (if (equal desc origpath)
9329 (setq desc path))))
9331 (if org-make-link-description-function
9332 (setq desc (funcall org-make-link-description-function link desc))
9333 (if default-description (setq desc default-description)))
9335 (setq desc (read-string "Description: " desc))
9336 (unless (string-match "\\S-" desc) (setq desc nil))
9337 (if remove (apply 'delete-region remove))
9338 (insert (org-make-link-string link desc))))
9340 (defun org-link-try-special-completion (type)
9341 "If there is completion support for link type TYPE, offer it."
9342 (let ((fun (intern (concat "org-" type "-complete-link"))))
9343 (if (functionp fun)
9344 (funcall fun)
9345 (read-string "Link (no completion support): " (concat type ":")))))
9347 (defun org-file-complete-link (&optional arg)
9348 "Create a file link using completion."
9349 (let (file link)
9350 (setq file (read-file-name "File: "))
9351 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9352 (pwd1 (file-name-as-directory (abbreviate-file-name
9353 (expand-file-name ".")))))
9354 (cond
9355 ((equal arg '(16))
9356 (setq link (org-make-link
9357 "file:"
9358 (abbreviate-file-name (expand-file-name file)))))
9359 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9360 (setq link (org-make-link "file:" (match-string 1 file))))
9361 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9362 (expand-file-name file))
9363 (setq link (org-make-link
9364 "file:" (match-string 1 (expand-file-name file)))))
9365 (t (setq link (org-make-link "file:" file)))))
9366 link))
9368 (defun org-completing-read (&rest args)
9369 "Completing-read with SPACE being a normal character."
9370 (let ((enable-recursive-minibuffers t)
9371 (minibuffer-local-completion-map
9372 (copy-keymap minibuffer-local-completion-map)))
9373 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9374 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9375 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9376 (apply 'org-icompleting-read args)))
9378 (defun org-completing-read-no-i (&rest args)
9379 (let (org-completion-use-ido org-completion-use-iswitchb)
9380 (apply 'org-completing-read args)))
9382 (defun org-iswitchb-completing-read (prompt choices &rest args)
9383 "Use iswitch as a completing-read replacement to choose from choices.
9384 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9385 from."
9386 (let* ((iswitchb-use-virtual-buffers nil)
9387 (iswitchb-make-buflist-hook
9388 (lambda ()
9389 (setq iswitchb-temp-buflist choices))))
9390 (iswitchb-read-buffer prompt)))
9392 (defun org-icompleting-read (&rest args)
9393 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9394 (org-without-partial-completion
9395 (if (and org-completion-use-ido
9396 (fboundp 'ido-completing-read)
9397 (boundp 'ido-mode) ido-mode
9398 (listp (second args)))
9399 (let ((ido-enter-matching-directory nil))
9400 (apply 'ido-completing-read (concat (car args))
9401 (if (consp (car (nth 1 args)))
9402 (mapcar 'car (nth 1 args))
9403 (nth 1 args))
9404 (cddr args)))
9405 (if (and org-completion-use-iswitchb
9406 (boundp 'iswitchb-mode) iswitchb-mode
9407 (listp (second args)))
9408 (apply 'org-iswitchb-completing-read (concat (car args))
9409 (if (consp (car (nth 1 args)))
9410 (mapcar 'car (nth 1 args))
9411 (nth 1 args))
9412 (cddr args))
9413 (apply 'completing-read args)))))
9415 (defun org-extract-attributes (s)
9416 "Extract the attributes cookie from a string and set as text property."
9417 (let (a attr (start 0) key value)
9418 (save-match-data
9419 (when (string-match "{{\\([^}]+\\)}}$" s)
9420 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9421 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9422 (setq key (match-string 1 a) value (match-string 2 a)
9423 start (match-end 0)
9424 attr (plist-put attr (intern key) value))))
9425 (org-add-props s nil 'org-attr attr))
9428 (defun org-extract-attributes-from-string (tag)
9429 (let (key value attr)
9430 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9431 (setq key (match-string 1 tag) value (match-string 2 tag)
9432 tag (replace-match "" t t tag)
9433 attr (plist-put attr (intern key) value)))
9434 (cons tag attr)))
9436 (defun org-attributes-to-string (plist)
9437 "Format a property list into an HTML attribute list."
9438 (let ((s "") key value)
9439 (while plist
9440 (setq key (pop plist) value (pop plist))
9441 (and value
9442 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9445 ;;; Opening/following a link
9447 (defvar org-link-search-failed nil)
9449 (defvar org-open-link-functions nil
9450 "Hook for functions finding a plain text link.
9451 These functions must take a single argument, the link content.
9452 They will be called for links that look like [[link text][description]]
9453 when LINK TEXT does not have a protocol like \"http:\" and does not look
9454 like a filename (e.g. \"./blue.png\").
9456 These functions will be called *before* Org attempts to resolve the
9457 link by doing text searches in the current buffer - so if you want a
9458 link \"[[target]]\" to still find \"<<target>>\", your function should
9459 handle this as a special case.
9461 When the function does handle the link, it must return a non-nil value.
9462 If it decides that it is not responsible for this link, it must return
9463 nil to indicate that that Org-mode can continue with other options
9464 like exact and fuzzy text search.")
9466 (defun org-next-link ()
9467 "Move forward to the next link.
9468 If the link is in hidden text, expose it."
9469 (interactive)
9470 (when (and org-link-search-failed (eq this-command last-command))
9471 (goto-char (point-min))
9472 (message "Link search wrapped back to beginning of buffer"))
9473 (setq org-link-search-failed nil)
9474 (let* ((pos (point))
9475 (ct (org-context))
9476 (a (assoc :link ct)))
9477 (if a (goto-char (nth 2 a)))
9478 (if (re-search-forward org-any-link-re nil t)
9479 (progn
9480 (goto-char (match-beginning 0))
9481 (if (outline-invisible-p) (org-show-context)))
9482 (goto-char pos)
9483 (setq org-link-search-failed t)
9484 (error "No further link found"))))
9486 (defun org-previous-link ()
9487 "Move backward to the previous link.
9488 If the link is in hidden text, expose it."
9489 (interactive)
9490 (when (and org-link-search-failed (eq this-command last-command))
9491 (goto-char (point-max))
9492 (message "Link search wrapped back to end of buffer"))
9493 (setq org-link-search-failed nil)
9494 (let* ((pos (point))
9495 (ct (org-context))
9496 (a (assoc :link ct)))
9497 (if a (goto-char (nth 1 a)))
9498 (if (re-search-backward org-any-link-re nil t)
9499 (progn
9500 (goto-char (match-beginning 0))
9501 (if (outline-invisible-p) (org-show-context)))
9502 (goto-char pos)
9503 (setq org-link-search-failed t)
9504 (error "No further link found"))))
9506 (defun org-translate-link (s)
9507 "Translate a link string if a translation function has been defined."
9508 (if (and org-link-translation-function
9509 (fboundp org-link-translation-function)
9510 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9511 (progn
9512 (setq s (funcall org-link-translation-function
9513 (match-string 1 s) (match-string 2 s)))
9514 (concat (car s) ":" (cdr s)))
9517 (defun org-translate-link-from-planner (type path)
9518 "Translate a link from Emacs Planner syntax so that Org can follow it.
9519 This is still an experimental function, your mileage may vary."
9520 (cond
9521 ((member type '("http" "https" "news" "ftp"))
9522 ;; standard Internet links are the same.
9523 nil)
9524 ((and (equal type "irc") (string-match "^//" path))
9525 ;; Planner has two / at the beginning of an irc link, we have 1.
9526 ;; We should have zero, actually....
9527 (setq path (substring path 1)))
9528 ((and (equal type "lisp") (string-match "^/" path))
9529 ;; Planner has a slash, we do not.
9530 (setq type "elisp" path (substring path 1)))
9531 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9532 ;; A typical message link. Planner has the id after the final slash,
9533 ;; we separate it with a hash mark
9534 (setq path (concat (match-string 1 path) "#"
9535 (org-remove-angle-brackets (match-string 2 path)))))
9537 (cons type path))
9539 (defun org-find-file-at-mouse (ev)
9540 "Open file link or URL at mouse."
9541 (interactive "e")
9542 (mouse-set-point ev)
9543 (org-open-at-point 'in-emacs))
9545 (defun org-open-at-mouse (ev)
9546 "Open file link or URL at mouse.
9547 See the docstring of `org-open-file' for details."
9548 (interactive "e")
9549 (mouse-set-point ev)
9550 (if (eq major-mode 'org-agenda-mode)
9551 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9552 (org-open-at-point))
9554 (defvar org-window-config-before-follow-link nil
9555 "The window configuration before following a link.
9556 This is saved in case the need arises to restore it.")
9558 (defvar org-open-link-marker (make-marker)
9559 "Marker pointing to the location where `org-open-at-point; was called.")
9561 ;;;###autoload
9562 (defun org-open-at-point-global ()
9563 "Follow a link like Org-mode does.
9564 This command can be called in any mode to follow a link that has
9565 Org-mode syntax."
9566 (interactive)
9567 (org-run-like-in-org-mode 'org-open-at-point))
9569 ;;;###autoload
9570 (defun org-open-link-from-string (s &optional arg reference-buffer)
9571 "Open a link in the string S, as if it was in Org-mode."
9572 (interactive "sLink: \nP")
9573 (let ((reference-buffer (or reference-buffer (current-buffer))))
9574 (with-temp-buffer
9575 (let ((org-inhibit-startup (not reference-buffer)))
9576 (org-mode)
9577 (insert s)
9578 (goto-char (point-min))
9579 (when reference-buffer
9580 (setq org-link-abbrev-alist-local
9581 (with-current-buffer reference-buffer
9582 org-link-abbrev-alist-local)))
9583 (org-open-at-point arg reference-buffer)))))
9585 (defvar org-open-at-point-functions nil
9586 "Hook that is run when following a link at point.
9588 Functions in this hook must return t if they identify and follow
9589 a link at point. If they don't find anything interesting at point,
9590 they must return nil.")
9592 (defun org-open-at-point (&optional arg reference-buffer)
9593 "Open link at or after point.
9594 If there is no link at point, this function will search forward up to
9595 the end of the current line.
9596 Normally, files will be opened by an appropriate application. If the
9597 optional prefix argument ARG is non-nil, Emacs will visit the file.
9598 With a double prefix argument, try to open outside of Emacs, in the
9599 application the system uses for this file type."
9600 (interactive "P")
9601 ;; if in a code block, then open the block's results
9602 (unless (call-interactively #'org-babel-open-src-block-result)
9603 (org-load-modules-maybe)
9604 (move-marker org-open-link-marker (point))
9605 (setq org-window-config-before-follow-link (current-window-configuration))
9606 (org-remove-occur-highlights nil nil t)
9607 (cond
9608 ((and (org-at-heading-p)
9609 (not (org-in-regexp
9610 (concat org-plain-link-re "\\|"
9611 org-bracket-link-regexp "\\|"
9612 org-angle-link-re "\\|"
9613 "[ \t]:[^ \t\n]+:[ \t]*$")))
9614 (not (get-text-property (point) 'org-linked-text)))
9615 (or (org-offer-links-in-entry arg)
9616 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9617 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9618 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9619 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9620 (not (org-in-regexp org-bracket-link-regexp)))
9621 (org-footnote-action))
9623 (let (type path link line search (pos (point)))
9624 (catch 'match
9625 (save-excursion
9626 (skip-chars-forward "^]\n\r")
9627 (when (org-in-regexp org-bracket-link-regexp 1)
9628 (setq link (org-extract-attributes
9629 (org-link-unescape (org-match-string-no-properties 1))))
9630 (while (string-match " *\n *" link)
9631 (setq link (replace-match " " t t link)))
9632 (setq link (org-link-expand-abbrev link))
9633 (cond
9634 ((or (file-name-absolute-p link)
9635 (string-match "^\\.\\.?/" link))
9636 (setq type "file" path link))
9637 ((string-match org-link-re-with-space3 link)
9638 (setq type (match-string 1 link) path (match-string 2 link)))
9639 (t (setq type "thisfile" path link)))
9640 (throw 'match t)))
9642 (when (get-text-property (point) 'org-linked-text)
9643 (setq type "thisfile"
9644 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9645 (1+ (point)) (point))
9646 path (buffer-substring
9647 (or (previous-single-property-change pos 'org-linked-text)
9648 (point-min))
9649 (or (next-single-property-change pos 'org-linked-text)
9650 (point-max))))
9651 (throw 'match t))
9653 (save-excursion
9654 (when (or (org-in-regexp org-angle-link-re)
9655 (org-in-regexp org-plain-link-re))
9656 (setq type (match-string 1)
9657 path (org-link-unescape (match-string 2)))
9658 (throw 'match t)))
9659 (save-excursion
9660 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9661 (setq type "tags"
9662 path (match-string 1))
9663 (while (string-match ":" path)
9664 (setq path (replace-match "+" t t path)))
9665 (throw 'match t)))
9666 (when (org-in-regexp "<\\([^><\n]+\\)>")
9667 (setq type "tree-match"
9668 path (match-string 1))
9669 (throw 'match t)))
9670 (unless path
9671 (error "No link found"))
9673 ;; switch back to reference buffer
9674 ;; needed when if called in a temporary buffer through
9675 ;; org-open-link-from-string
9676 (with-current-buffer (or reference-buffer (current-buffer))
9678 ;; Remove any trailing spaces in path
9679 (if (string-match " +\\'" path)
9680 (setq path (replace-match "" t t path)))
9681 (if (and org-link-translation-function
9682 (fboundp org-link-translation-function))
9683 ;; Check if we need to translate the link
9684 (let ((tmp (funcall org-link-translation-function type path)))
9685 (setq type (car tmp) path (cdr tmp))))
9687 (cond
9689 ((assoc type org-link-protocols)
9690 (funcall (nth 1 (assoc type org-link-protocols)) path))
9692 ((equal type "mailto")
9693 (let ((cmd (car org-link-mailto-program))
9694 (args (cdr org-link-mailto-program)) args1
9695 (address path) (subject "") a)
9696 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9697 (setq address (match-string 1 path)
9698 subject (org-link-escape (match-string 2 path))))
9699 (while args
9700 (cond
9701 ((not (stringp (car args))) (push (pop args) args1))
9702 (t (setq a (pop args))
9703 (if (string-match "%a" a)
9704 (setq a (replace-match address t t a)))
9705 (if (string-match "%s" a)
9706 (setq a (replace-match subject t t a)))
9707 (push a args1))))
9708 (apply cmd (nreverse args1))))
9710 ((member type '("http" "https" "ftp" "news"))
9711 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9712 (org-link-escape
9713 path org-link-escape-chars-browser)
9714 path))))
9716 ((string= type "doi")
9717 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9718 (org-link-escape
9719 path org-link-escape-chars-browser)
9720 path))))
9722 ((member type '("message"))
9723 (browse-url (concat type ":" path)))
9725 ((string= type "tags")
9726 (org-tags-view arg path))
9728 ((string= type "tree-match")
9729 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9731 ((string= type "file")
9732 (if (string-match "::\\([0-9]+\\)\\'" path)
9733 (setq line (string-to-number (match-string 1 path))
9734 path (substring path 0 (match-beginning 0)))
9735 (if (string-match "::\\(.+\\)\\'" path)
9736 (setq search (match-string 1 path)
9737 path (substring path 0 (match-beginning 0)))))
9738 (if (string-match "[*?{]" (file-name-nondirectory path))
9739 (dired path)
9740 (org-open-file path arg line search)))
9742 ((string= type "shell")
9743 (let ((cmd path))
9744 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9745 (string-match org-confirm-shell-link-not-regexp cmd))
9746 (not org-confirm-shell-link-function)
9747 (funcall org-confirm-shell-link-function
9748 (format "Execute \"%s\" in shell? "
9749 (org-add-props cmd nil
9750 'face 'org-warning))))
9751 (progn
9752 (message "Executing %s" cmd)
9753 (shell-command cmd))
9754 (error "Abort"))))
9756 ((string= type "elisp")
9757 (let ((cmd path))
9758 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9759 (string-match org-confirm-elisp-link-not-regexp cmd))
9760 (not org-confirm-elisp-link-function)
9761 (funcall org-confirm-elisp-link-function
9762 (format "Execute \"%s\" as elisp? "
9763 (org-add-props cmd nil
9764 'face 'org-warning))))
9765 (message "%s => %s" cmd
9766 (if (equal (string-to-char cmd) ?\()
9767 (eval (read cmd))
9768 (call-interactively (read cmd))))
9769 (error "Abort"))))
9771 ((and (string= type "thisfile")
9772 (run-hook-with-args-until-success
9773 'org-open-link-functions path)))
9775 ((string= type "thisfile")
9776 (if arg
9777 (switch-to-buffer-other-window
9778 (org-get-buffer-for-internal-link (current-buffer)))
9779 (org-mark-ring-push))
9780 (let ((cmd `(org-link-search
9781 ,path
9782 ,(cond ((equal arg '(4)) ''occur)
9783 ((equal arg '(16)) ''org-occur)
9784 (t nil))
9785 ,pos)))
9786 (condition-case nil (let ((org-link-search-inhibit-query t))
9787 (eval cmd))
9788 (error (progn (widen) (eval cmd))))))
9791 (browse-url-at-point)))))))
9792 (move-marker org-open-link-marker nil)
9793 (run-hook-with-args 'org-follow-link-hook)))
9795 (defun org-offer-links-in-entry (&optional nth zero)
9796 "Offer links in the current entry and follow the selected link.
9797 If there is only one link, follow it immediately as well.
9798 If NTH is an integer, immediately pick the NTH link found.
9799 If ZERO is a string, check also this string for a link, and if
9800 there is one, offer it as link number zero."
9801 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9802 "\\(" org-angle-link-re "\\)\\|"
9803 "\\(" org-plain-link-re "\\)"))
9804 (cnt ?0)
9805 (in-emacs (if (integerp nth) nil nth))
9806 have-zero end links link c)
9807 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9808 (push (match-string 0 zero) links)
9809 (setq cnt (1- cnt) have-zero t))
9810 (save-excursion
9811 (org-back-to-heading t)
9812 (setq end (save-excursion (outline-next-heading) (point)))
9813 (while (re-search-forward re end t)
9814 (push (match-string 0) links))
9815 (setq links (org-uniquify (reverse links))))
9817 (cond
9818 ((null links)
9819 (message "No links"))
9820 ((equal (length links) 1)
9821 (setq link (list (car links))))
9822 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9823 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9824 (t ; we have to select a link
9825 (save-excursion
9826 (save-window-excursion
9827 (delete-other-windows)
9828 (with-output-to-temp-buffer "*Select Link*"
9829 (mapc (lambda (l)
9830 (if (not (string-match org-bracket-link-regexp l))
9831 (princ (format "[%c] %s\n" (incf cnt)
9832 (org-remove-angle-brackets l)))
9833 (if (match-end 3)
9834 (princ (format "[%c] %s (%s)\n" (incf cnt)
9835 (match-string 3 l) (match-string 1 l)))
9836 (princ (format "[%c] %s\n" (incf cnt)
9837 (match-string 1 l))))))
9838 links))
9839 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9840 (message "Select link to open, RET to open all:")
9841 (setq c (read-char-exclusive))
9842 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9843 (when (equal c ?q) (error "Abort"))
9844 (if (equal c ?\C-m)
9845 (setq link links)
9846 (setq nth (- c ?0))
9847 (if have-zero (setq nth (1+ nth)))
9848 (unless (and (integerp nth) (>= (length links) nth))
9849 (error "Invalid link selection"))
9850 (setq link (list (nth (1- nth) links))))))
9851 (if link
9852 (let ((buf (current-buffer)))
9853 (dolist (l link)
9854 (org-open-link-from-string l in-emacs buf))
9856 nil)))
9858 ;; Add special file links that specify the way of opening
9860 (org-add-link-type "file+sys" 'org-open-file-with-system)
9861 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9862 (defun org-open-file-with-system (path)
9863 "Open file at PATH using the system way of opening it."
9864 (org-open-file path 'system))
9865 (defun org-open-file-with-emacs (path)
9866 "Open file at PATH in Emacs."
9867 (org-open-file path 'emacs))
9868 (defun org-remove-file-link-modifiers ()
9869 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9870 (goto-char (point-min))
9871 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9872 (org-if-unprotected
9873 (replace-match "file:" t t))))
9874 (eval-after-load "org-exp"
9875 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9876 'org-remove-file-link-modifiers))
9878 ;;;; Time estimates
9880 (defun org-get-effort (&optional pom)
9881 "Get the effort estimate for the current entry."
9882 (org-entry-get pom org-effort-property))
9884 ;;; File search
9886 (defvar org-create-file-search-functions nil
9887 "List of functions to construct the right search string for a file link.
9888 These functions are called in turn with point at the location to
9889 which the link should point.
9891 A function in the hook should first test if it would like to
9892 handle this file type, for example by checking the `major-mode'
9893 or the file extension. If it decides not to handle this file, it
9894 should just return nil to give other functions a chance. If it
9895 does handle the file, it must return the search string to be used
9896 when following the link. The search string will be part of the
9897 file link, given after a double colon, and `org-open-at-point'
9898 will automatically search for it. If special measures must be
9899 taken to make the search successful, another function should be
9900 added to the companion hook `org-execute-file-search-functions',
9901 which see.
9903 A function in this hook may also use `setq' to set the variable
9904 `description' to provide a suggestion for the descriptive text to
9905 be used for this link when it gets inserted into an Org-mode
9906 buffer with \\[org-insert-link].")
9908 (defvar org-execute-file-search-functions nil
9909 "List of functions to execute a file search triggered by a link.
9911 Functions added to this hook must accept a single argument, the
9912 search string that was part of the file link, the part after the
9913 double colon. The function must first check if it would like to
9914 handle this search, for example by checking the `major-mode' or
9915 the file extension. If it decides not to handle this search, it
9916 should just return nil to give other functions a chance. If it
9917 does handle the search, it must return a non-nil value to keep
9918 other functions from trying.
9920 Each function can access the current prefix argument through the
9921 variable `current-prefix-argument'. Note that a single prefix is
9922 used to force opening a link in Emacs, so it may be good to only
9923 use a numeric or double prefix to guide the search function.
9925 In case this is needed, a function in this hook can also restore
9926 the window configuration before `org-open-at-point' was called using:
9928 (set-window-configuration org-window-config-before-follow-link)")
9930 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9931 (defun org-link-search (s &optional type avoid-pos stealth)
9932 "Search for a link search option.
9933 If S is surrounded by forward slashes, it is interpreted as a
9934 regular expression. In org-mode files, this will create an `org-occur'
9935 sparse tree. In ordinary files, `occur' will be used to list matches.
9936 If the current buffer is in `dired-mode', grep will be used to search
9937 in all files. If AVOID-POS is given, ignore matches near that position.
9939 When optional argument STEALTH is non-nil, do not modify
9940 visibility around point, thus ignoring
9941 `org-show-hierarchy-above', `org-show-following-heading' and
9942 `org-show-siblings' variables."
9943 (let ((case-fold-search t)
9944 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9945 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9946 (append '(("") (" ") ("\t") ("\n"))
9947 org-emphasis-alist)
9948 "\\|") "\\)"))
9949 (pos (point))
9950 (pre nil) (post nil)
9951 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9952 (cond
9953 ;; First check if there are any special search functions
9954 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9955 ;; Now try the builtin stuff
9956 ((and (equal (string-to-char s0) ?#)
9957 (> (length s0) 1)
9958 (save-excursion
9959 (goto-char (point-min))
9960 (and
9961 (re-search-forward
9962 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9963 (setq type 'dedicated
9964 pos (match-beginning 0))))
9965 ;; There is an exact target for this
9966 (goto-char pos)
9967 (org-back-to-heading t)))
9968 ((save-excursion
9969 (goto-char (point-min))
9970 (and
9971 (re-search-forward
9972 (concat "<<" (regexp-quote s0) ">>") nil t)
9973 (setq type 'dedicated
9974 pos (match-beginning 0))))
9975 ;; There is an exact target for this
9976 (goto-char pos))
9977 ((save-excursion
9978 (goto-char (point-min))
9979 (and
9980 (re-search-forward
9981 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9982 (setq type 'dedicated pos (match-beginning 0))))
9983 ;; Found an invisible target.
9984 (goto-char pos))
9985 ((save-excursion
9986 (goto-char (point-min))
9987 (and
9988 (re-search-forward
9989 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9990 (setq type 'dedicated pos (match-beginning 0))))
9991 ;; Found an element with a matching #+name affiliated keyword.
9992 (goto-char pos))
9993 ((and (string-match "^(\\(.*\\))$" s0)
9994 (save-excursion
9995 (goto-char (point-min))
9996 (and
9997 (re-search-forward
9998 (concat "[^[]" (regexp-quote
9999 (format org-coderef-label-format
10000 (match-string 1 s0))))
10001 nil t)
10002 (setq type 'dedicated
10003 pos (1+ (match-beginning 0))))))
10004 ;; There is a coderef target for this
10005 (goto-char pos))
10006 ((string-match "^/\\(.*\\)/$" s)
10007 ;; A regular expression
10008 (cond
10009 ((derived-mode-p 'org-mode)
10010 (org-occur (match-string 1 s)))
10011 ;;((eq major-mode 'dired-mode)
10012 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10013 (t (org-do-occur (match-string 1 s)))))
10014 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10015 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10016 (goto-char (point-min))
10017 (cond
10018 ((let (case-fold-search)
10019 (re-search-forward (format org-complex-heading-regexp-format
10020 (regexp-quote s))
10021 nil t))
10022 ;; OK, found a match
10023 (setq type 'dedicated)
10024 (goto-char (match-beginning 0)))
10025 ((and (not org-link-search-inhibit-query)
10026 (eq org-link-search-must-match-exact-headline 'query-to-create)
10027 (y-or-n-p "No match - create this as a new heading? "))
10028 (goto-char (point-max))
10029 (or (bolp) (newline))
10030 (insert "* " s "\n")
10031 (beginning-of-line 0))
10033 (goto-char pos)
10034 (error "No match"))))
10036 ;; A normal search string
10037 (when (equal (string-to-char s) ?*)
10038 ;; Anchor on headlines, post may include tags.
10039 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10040 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10041 s (substring s 1)))
10042 (remove-text-properties
10043 0 (length s)
10044 '(face nil mouse-face nil keymap nil fontified nil) s)
10045 ;; Make a series of regular expressions to find a match
10046 (setq words (org-split-string s "[ \n\r\t]+")
10048 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10049 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10050 "\\)" markers)
10051 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10052 re2a (concat "[ \t\r\n]" re2a_)
10053 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10054 re4 (concat "[^a-zA-Z_]" re4_)
10056 re1 (concat pre re2 post)
10057 re3 (concat pre (if pre re4_ re4) post)
10058 re5 (concat pre ".*" re4)
10059 re2 (concat pre re2)
10060 re2a (concat pre (if pre re2a_ re2a))
10061 re4 (concat pre (if pre re4_ re4))
10062 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10063 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10064 re5 "\\)"
10066 (cond
10067 ((eq type 'org-occur) (org-occur reall))
10068 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10069 (t (goto-char (point-min))
10070 (setq type 'fuzzy)
10071 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10072 (org-search-not-self 1 re1 nil t)
10073 (org-search-not-self 1 re2 nil t)
10074 (org-search-not-self 1 re2a nil t)
10075 (org-search-not-self 1 re3 nil t)
10076 (org-search-not-self 1 re4 nil t)
10077 (org-search-not-self 1 re5 nil t)
10079 (goto-char (match-beginning 1))
10080 (goto-char pos)
10081 (error "No match"))))))
10082 (and (derived-mode-p 'org-mode)
10083 (not stealth)
10084 (org-show-context 'link-search))
10085 type))
10087 (defun org-search-not-self (group &rest args)
10088 "Execute `re-search-forward', but only accept matches that do not
10089 enclose the position of `org-open-link-marker'."
10090 (let ((m org-open-link-marker))
10091 (catch 'exit
10092 (while (apply 're-search-forward args)
10093 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10094 (goto-char (match-end group))
10095 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10096 (> (match-beginning 0) (marker-position m))
10097 (< (match-end 0) (marker-position m)))
10098 (save-match-data
10099 (or (not (org-in-regexp
10100 org-bracket-link-analytic-regexp 1))
10101 (not (match-end 4)) ; no description
10102 (and (<= (match-beginning 4) (point))
10103 (>= (match-end 4) (point))))))
10104 (throw 'exit (point))))))))
10106 (defun org-get-buffer-for-internal-link (buffer)
10107 "Return a buffer to be used for displaying the link target of internal links."
10108 (cond
10109 ((not org-display-internal-link-with-indirect-buffer)
10110 buffer)
10111 ((string-match "(Clone)$" (buffer-name buffer))
10112 (message "Buffer is already a clone, not making another one")
10113 ;; we also do not modify visibility in this case
10114 buffer)
10115 (t ; make a new indirect buffer for displaying the link
10116 (let* ((bn (buffer-name buffer))
10117 (ibn (concat bn "(Clone)"))
10118 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10119 (with-current-buffer ib (org-overview))
10120 ib))))
10122 (defun org-do-occur (regexp &optional cleanup)
10123 "Call the Emacs command `occur'.
10124 If CLEANUP is non-nil, remove the printout of the regular expression
10125 in the *Occur* buffer. This is useful if the regex is long and not useful
10126 to read."
10127 (occur regexp)
10128 (when cleanup
10129 (let ((cwin (selected-window)) win beg end)
10130 (when (setq win (get-buffer-window "*Occur*"))
10131 (select-window win))
10132 (goto-char (point-min))
10133 (when (re-search-forward "match[a-z]+" nil t)
10134 (setq beg (match-end 0))
10135 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10136 (setq end (1- (match-beginning 0)))))
10137 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10138 (goto-char (point-min))
10139 (select-window cwin))))
10141 ;;; The mark ring for links jumps
10143 (defvar org-mark-ring nil
10144 "Mark ring for positions before jumps in Org-mode.")
10145 (defvar org-mark-ring-last-goto nil
10146 "Last position in the mark ring used to go back.")
10147 ;; Fill and close the ring
10148 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10149 (loop for i from 1 to org-mark-ring-length do
10150 (push (make-marker) org-mark-ring))
10151 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10152 org-mark-ring)
10154 (defun org-mark-ring-push (&optional pos buffer)
10155 "Put the current position or POS into the mark ring and rotate it."
10156 (interactive)
10157 (setq pos (or pos (point)))
10158 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10159 (move-marker (car org-mark-ring)
10160 (or pos (point))
10161 (or buffer (current-buffer)))
10162 (message "%s"
10163 (substitute-command-keys
10164 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10166 (defun org-mark-ring-goto (&optional n)
10167 "Jump to the previous position in the mark ring.
10168 With prefix arg N, jump back that many stored positions. When
10169 called several times in succession, walk through the entire ring.
10170 Org-mode commands jumping to a different position in the current file,
10171 or to another Org-mode file, automatically push the old position
10172 onto the ring."
10173 (interactive "p")
10174 (let (p m)
10175 (if (eq last-command this-command)
10176 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10177 (setq p org-mark-ring))
10178 (setq org-mark-ring-last-goto p)
10179 (setq m (car p))
10180 (org-pop-to-buffer-same-window (marker-buffer m))
10181 (goto-char m)
10182 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10184 (defun org-remove-angle-brackets (s)
10185 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10186 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10188 (defun org-add-angle-brackets (s)
10189 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10190 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10192 (defun org-remove-double-quotes (s)
10193 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10194 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10197 ;;; Following specific links
10199 (defun org-follow-timestamp-link ()
10200 (cond
10201 ((org-at-date-range-p t)
10202 (let ((org-agenda-start-on-weekday)
10203 (t1 (match-string 1))
10204 (t2 (match-string 2)))
10205 (setq t1 (time-to-days (org-time-string-to-time t1))
10206 t2 (time-to-days (org-time-string-to-time t2)))
10207 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10208 ((org-at-timestamp-p t)
10209 (org-agenda-list nil (time-to-days (org-time-string-to-time
10210 (substring (match-string 1) 0 10)))
10212 (t (error "This should not happen"))))
10215 ;;; Following file links
10216 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10217 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10218 (declare-function mailcap-mime-info
10219 "mailcap" (string &optional request no-decode))
10220 (defvar org-wait nil)
10221 (defun org-open-file (path &optional in-emacs line search)
10222 "Open the file at PATH.
10223 First, this expands any special file name abbreviations. Then the
10224 configuration variable `org-file-apps' is checked if it contains an
10225 entry for this file type, and if yes, the corresponding command is launched.
10227 If no application is found, Emacs simply visits the file.
10229 With optional prefix argument IN-EMACS, Emacs will visit the file.
10230 With a double \\[universal-argument] \\[universal-argument] \
10231 prefix arg, Org tries to avoid opening in Emacs
10232 and to use an external application to visit the file.
10234 Optional LINE specifies a line to go to, optional SEARCH a string
10235 to search for. If LINE or SEARCH is given, the file will be
10236 opened in Emacs, unless an entry from org-file-apps that makes
10237 use of groups in a regexp matches.
10239 If you want to change the way frames are used when following a
10240 link, please customize `org-link-frame-setup'.
10242 If the file does not exist, an error is thrown."
10243 (let* ((file (if (equal path "")
10244 buffer-file-name
10245 (substitute-in-file-name (expand-file-name path))))
10246 (file-apps (append org-file-apps (org-default-apps)))
10247 (apps (org-remove-if
10248 'org-file-apps-entry-match-against-dlink-p file-apps))
10249 (apps-dlink (org-remove-if-not
10250 'org-file-apps-entry-match-against-dlink-p file-apps))
10251 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10252 (dirp (if remp nil (file-directory-p file)))
10253 (file (if (and dirp org-open-directory-means-index-dot-org)
10254 (concat (file-name-as-directory file) "index.org")
10255 file))
10256 (a-m-a-p (assq 'auto-mode apps))
10257 (dfile (downcase file))
10258 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10259 (link (cond ((and (eq line nil)
10260 (eq search nil))
10261 file)
10262 (line
10263 (concat file "::" (number-to-string line)))
10264 (search
10265 (concat file "::" search))))
10266 (dlink (downcase link))
10267 (old-buffer (current-buffer))
10268 (old-pos (point))
10269 (old-mode major-mode)
10270 ext cmd link-match-data)
10271 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10272 (setq ext (match-string 1 dfile))
10273 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10274 (setq ext (match-string 1 dfile))))
10275 (cond
10276 ((member in-emacs '((16) system))
10277 (setq cmd (cdr (assoc 'system apps))))
10278 (in-emacs (setq cmd 'emacs))
10280 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10281 (and dirp (cdr (assoc 'directory apps)))
10282 ; first, try matching against apps-dlink
10283 ; if we get a match here, store the match data for later
10284 (let ((match (assoc-default dlink apps-dlink
10285 'string-match)))
10286 (if match
10287 (progn (setq link-match-data (match-data))
10288 match)
10289 (progn (setq in-emacs (or in-emacs line search))
10290 nil))) ; if we have no match in apps-dlink,
10291 ; always open the file in emacs if line or search
10292 ; is given (for backwards compatibility)
10293 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10294 'string-match)
10295 (cdr (assoc ext apps))
10296 (cdr (assoc t apps))))))
10297 (when (eq cmd 'system)
10298 (setq cmd (cdr (assoc 'system apps))))
10299 (when (eq cmd 'default)
10300 (setq cmd (cdr (assoc t apps))))
10301 (when (eq cmd 'mailcap)
10302 (require 'mailcap)
10303 (mailcap-parse-mailcaps)
10304 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10305 (command (mailcap-mime-info mime-type)))
10306 (if (stringp command)
10307 (setq cmd command)
10308 (setq cmd 'emacs))))
10309 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10310 (not (file-exists-p file))
10311 (not org-open-non-existing-files))
10312 (error "No such file: %s" file))
10313 (cond
10314 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10315 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10316 (while (string-match "['\"]%s['\"]" cmd)
10317 (setq cmd (replace-match "%s" t t cmd)))
10318 (while (string-match "%s" cmd)
10319 (setq cmd (replace-match
10320 (save-match-data
10321 (shell-quote-argument
10322 (convert-standard-filename file)))
10323 t t cmd)))
10325 ;; Replace "%1", "%2" etc. in command with group matches from regex
10326 (save-match-data
10327 (let ((match-index 1)
10328 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10329 (set-match-data link-match-data)
10330 (while (<= match-index number-of-groups)
10331 (let ((regex (concat "%" (number-to-string match-index)))
10332 (replace-with (match-string match-index dlink)))
10333 (while (string-match regex cmd)
10334 (setq cmd (replace-match replace-with t t cmd))))
10335 (setq match-index (+ match-index 1)))))
10337 (save-window-excursion
10338 (start-process-shell-command cmd nil cmd)
10339 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10341 ((or (stringp cmd)
10342 (eq cmd 'emacs))
10343 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10344 (widen)
10345 (if line (org-goto-line line)
10346 (if search (org-link-search search))))
10347 ((consp cmd)
10348 (let ((file (convert-standard-filename file)))
10349 (save-match-data
10350 (set-match-data link-match-data)
10351 (eval cmd))))
10352 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10353 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10354 (or (not (equal old-buffer (current-buffer)))
10355 (not (equal old-pos (point))))
10356 (org-mark-ring-push old-pos old-buffer))))
10358 (defun org-file-apps-entry-match-against-dlink-p (entry)
10359 "This function returns non-nil if `entry' uses a regular
10360 expression which should be matched against the whole link by
10361 org-open-file.
10363 It assumes that is the case when the entry uses a regular
10364 expression which has at least one grouping construct and the
10365 action is either a lisp form or a command string containing
10366 '%1', i.e. using at least one subexpression match as a
10367 parameter."
10368 (let ((selector (car entry))
10369 (action (cdr entry)))
10370 (if (stringp selector)
10371 (and (> (regexp-opt-depth selector) 0)
10372 (or (and (stringp action)
10373 (string-match "%[0-9]" action))
10374 (consp action)))
10375 nil)))
10377 (defun org-default-apps ()
10378 "Return the default applications for this operating system."
10379 (cond
10380 ((eq system-type 'darwin)
10381 org-file-apps-defaults-macosx)
10382 ((eq system-type 'windows-nt)
10383 org-file-apps-defaults-windowsnt)
10384 (t org-file-apps-defaults-gnu)))
10386 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10387 "Convert extensions to regular expressions in the cars of LIST.
10388 Also, weed out any non-string entries, because the return value is used
10389 only for regexp matching.
10390 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10391 point to the symbol `emacs', indicating that the file should
10392 be opened in Emacs."
10393 (append
10394 (delq nil
10395 (mapcar (lambda (x)
10396 (if (not (stringp (car x)))
10398 (if (string-match "\\W" (car x))
10400 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10401 list))
10402 (if add-auto-mode
10403 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10405 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10406 (defun org-file-remote-p (file)
10407 "Test whether FILE specifies a location on a remote system.
10408 Return non-nil if the location is indeed remote.
10410 For example, the filename \"/user@host:/foo\" specifies a location
10411 on the system \"/user@host:\"."
10412 (cond ((fboundp 'file-remote-p)
10413 (file-remote-p file))
10414 ((fboundp 'tramp-handle-file-remote-p)
10415 (tramp-handle-file-remote-p file))
10416 ((and (boundp 'ange-ftp-name-format)
10417 (string-match (car ange-ftp-name-format) file))
10419 (t nil)))
10422 ;;;; Refiling
10424 (defun org-get-org-file ()
10425 "Read a filename, with default directory `org-directory'."
10426 (let ((default (or org-default-notes-file remember-data-file)))
10427 (read-file-name (format "File name [%s]: " default)
10428 (file-name-as-directory org-directory)
10429 default)))
10431 (defun org-notes-order-reversed-p ()
10432 "Check if the current file should receive notes in reversed order."
10433 (cond
10434 ((not org-reverse-note-order) nil)
10435 ((eq t org-reverse-note-order) t)
10436 ((not (listp org-reverse-note-order)) nil)
10437 (t (catch 'exit
10438 (let ((all org-reverse-note-order)
10439 entry)
10440 (while (setq entry (pop all))
10441 (if (string-match (car entry) buffer-file-name)
10442 (throw 'exit (cdr entry))))
10443 nil)))))
10445 (defvar org-refile-target-table nil
10446 "The list of refile targets, created by `org-refile'.")
10448 (defvar org-agenda-new-buffers nil
10449 "Buffers created to visit agenda files.")
10451 (defvar org-refile-cache nil
10452 "Cache for refile targets.")
10454 (defvar org-refile-markers nil
10455 "All the markers used for caching refile locations.")
10457 (defun org-refile-marker (pos)
10458 "Get a new refile marker, but only if caching is in use."
10459 (if (not org-refile-use-cache)
10461 (let ((m (make-marker)))
10462 (move-marker m pos)
10463 (push m org-refile-markers)
10464 m)))
10466 (defun org-refile-cache-clear ()
10467 "Clear the refile cache and disable all the markers."
10468 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10469 (setq org-refile-markers nil)
10470 (setq org-refile-cache nil)
10471 (message "Refile cache has been cleared"))
10473 (defun org-refile-cache-check-set (set)
10474 "Check if all the markers in the cache still have live buffers."
10475 (let (marker)
10476 (catch 'exit
10477 (while (and set (setq marker (nth 3 (pop set))))
10478 ;; if org-refile-use-outline-path is 'file, marker may be nil
10479 (when (and marker (null (marker-buffer marker)))
10480 (message "not found") (sit-for 3)
10481 (throw 'exit nil)))
10482 t)))
10484 (defun org-refile-cache-put (set &rest identifiers)
10485 "Push the refile targets SET into the cache, under IDENTIFIERS."
10486 (let* ((key (sha1 (prin1-to-string identifiers)))
10487 (entry (assoc key org-refile-cache)))
10488 (if entry
10489 (setcdr entry set)
10490 (push (cons key set) org-refile-cache))))
10492 (defun org-refile-cache-get (&rest identifiers)
10493 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10494 (cond
10495 ((not org-refile-cache) nil)
10496 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10498 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10499 org-refile-cache))))
10500 (and set (org-refile-cache-check-set set) set)))))
10502 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10503 "Produce a table with refile targets."
10504 (let ((case-fold-search nil)
10505 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10506 (entries (or org-refile-targets '((nil . (:level . 1)))))
10507 targets tgs txt re files f desc descre fast-path-p level pos0)
10508 (message "Getting targets...")
10509 (with-current-buffer (or default-buffer (current-buffer))
10510 (while (setq entry (pop entries))
10511 (setq files (car entry) desc (cdr entry))
10512 (setq fast-path-p nil)
10513 (cond
10514 ((null files) (setq files (list (current-buffer))))
10515 ((eq files 'org-agenda-files)
10516 (setq files (org-agenda-files 'unrestricted)))
10517 ((and (symbolp files) (fboundp files))
10518 (setq files (funcall files)))
10519 ((and (symbolp files) (boundp files))
10520 (setq files (symbol-value files))))
10521 (if (stringp files) (setq files (list files)))
10522 (cond
10523 ((eq (car desc) :tag)
10524 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10525 ((eq (car desc) :todo)
10526 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10527 ((eq (car desc) :regexp)
10528 (setq descre (cdr desc)))
10529 ((eq (car desc) :level)
10530 (setq descre (concat "^\\*\\{" (number-to-string
10531 (if org-odd-levels-only
10532 (1- (* 2 (cdr desc)))
10533 (cdr desc)))
10534 "\\}[ \t]")))
10535 ((eq (car desc) :maxlevel)
10536 (setq fast-path-p t)
10537 (setq descre (concat "^\\*\\{1," (number-to-string
10538 (if org-odd-levels-only
10539 (1- (* 2 (cdr desc)))
10540 (cdr desc)))
10541 "\\}[ \t]")))
10542 (t (error "Bad refiling target description %s" desc)))
10543 (while (setq f (pop files))
10544 (with-current-buffer
10545 (if (bufferp f) f (org-get-agenda-file-buffer f))
10547 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10548 (progn
10549 (if (bufferp f) (setq f (buffer-file-name
10550 (buffer-base-buffer f))))
10551 (setq f (and f (expand-file-name f)))
10552 (if (eq org-refile-use-outline-path 'file)
10553 (push (list (file-name-nondirectory f) f nil nil) tgs))
10554 (save-excursion
10555 (save-restriction
10556 (widen)
10557 (goto-char (point-min))
10558 (while (re-search-forward descre nil t)
10559 (goto-char (setq pos0 (point-at-bol)))
10560 (catch 'next
10561 (when org-refile-target-verify-function
10562 (save-match-data
10563 (or (funcall org-refile-target-verify-function)
10564 (throw 'next t))))
10565 (when (and (looking-at org-complex-heading-regexp)
10566 (not (member (match-string 4) excluded-entries))
10567 (match-string 4))
10568 (setq level (org-reduced-level
10569 (- (match-end 1) (match-beginning 1)))
10570 txt (org-link-display-format (match-string 4))
10571 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10572 re (format org-complex-heading-regexp-format
10573 (regexp-quote (match-string 4))))
10574 (when org-refile-use-outline-path
10575 (setq txt (mapconcat
10576 'org-protect-slash
10577 (append
10578 (if (eq org-refile-use-outline-path
10579 'file)
10580 (list (file-name-nondirectory
10581 (buffer-file-name
10582 (buffer-base-buffer))))
10583 (if (eq org-refile-use-outline-path
10584 'full-file-path)
10585 (list (buffer-file-name
10586 (buffer-base-buffer)))))
10587 (org-get-outline-path fast-path-p
10588 level txt)
10589 (list txt))
10590 "/")))
10591 (push (list txt f re (org-refile-marker (point)))
10592 tgs)))
10593 (when (= (point) pos0)
10594 ;; verification function has not moved point
10595 (goto-char (point-at-eol))))))))
10596 (when org-refile-use-cache
10597 (org-refile-cache-put tgs (buffer-file-name) descre))
10598 (setq targets (append tgs targets))
10599 ))))
10600 (message "Getting targets...done")
10601 (nreverse targets)))
10603 (defun org-protect-slash (s)
10604 (while (string-match "/" s)
10605 (setq s (replace-match "\\" t t s)))
10608 (defvar org-olpa (make-vector 20 nil))
10610 (defun org-get-outline-path (&optional fastp level heading)
10611 "Return the outline path to the current entry, as a list.
10613 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10614 routine which makes outline path derivations for an entire file,
10615 avoiding backtracing. Refile target collection makes use of that."
10616 (if fastp
10617 (progn
10618 (if (> level 19)
10619 (error "Outline path failure, more than 19 levels"))
10620 (loop for i from level upto 19 do
10621 (aset org-olpa i nil))
10622 (prog1
10623 (delq nil (append org-olpa nil))
10624 (aset org-olpa level heading)))
10625 (let (rtn case-fold-search)
10626 (save-excursion
10627 (save-restriction
10628 (widen)
10629 (while (org-up-heading-safe)
10630 (when (looking-at org-complex-heading-regexp)
10631 (push (org-match-string-no-properties 4) rtn)))
10632 rtn)))))
10634 (defun org-format-outline-path (path &optional width prefix)
10635 "Format the outline path PATH for display.
10636 Width is the maximum number of characters that is available.
10637 Prefix is a prefix to be included in the returned string,
10638 such as the file name."
10639 (setq width (or width 79))
10640 (if prefix (setq width (- width (length prefix))))
10641 (if (not path)
10642 (or prefix "")
10643 (let* ((nsteps (length path))
10644 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10645 (maxwidth (if (<= total-width width)
10646 10000 ;; everything fits
10647 ;; we need to shorten the level headings
10648 (/ (- width nsteps) nsteps)))
10649 (org-odd-levels-only nil)
10650 (n 0)
10651 (total (1+ (length prefix))))
10652 (setq maxwidth (max maxwidth 10))
10653 (concat prefix
10654 (mapconcat
10655 (lambda (h)
10656 (setq n (1+ n))
10657 (if (and (= n nsteps) (< maxwidth 10000))
10658 (setq maxwidth (- total-width total)))
10659 (if (< (length h) maxwidth)
10660 (progn (setq total (+ total (length h) 1)) h)
10661 (setq h (substring h 0 (- maxwidth 2))
10662 total (+ total maxwidth 1))
10663 (if (string-match "[ \t]+\\'" h)
10664 (setq h (substring h 0 (match-beginning 0))))
10665 (setq h (concat h "..")))
10666 (org-add-props h nil 'face
10667 (nth (% (1- n) org-n-level-faces)
10668 org-level-faces))
10670 path "/")))))
10672 (defun org-display-outline-path (&optional file current)
10673 "Display the current outline path in the echo area."
10674 (interactive "P")
10675 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10676 (case-fold-search nil)
10677 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10678 (if current (setq path (append path
10679 (save-excursion
10680 (org-back-to-heading t)
10681 (if (looking-at org-complex-heading-regexp)
10682 (list (match-string 4)))))))
10683 (message "%s"
10684 (org-format-outline-path
10685 path
10686 (1- (frame-width))
10687 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10689 (defvar org-refile-history nil
10690 "History for refiling operations.")
10692 (defvar org-after-refile-insert-hook nil
10693 "Hook run after `org-refile' has inserted its stuff at the new location.
10694 Note that this is still *before* the stuff will be removed from
10695 the *old* location.")
10697 (defvar org-capture-last-stored-marker)
10698 (defun org-refile (&optional goto default-buffer rfloc)
10699 "Move the entry or entries at point to another heading.
10700 The list of target headings is compiled using the information in
10701 `org-refile-targets', which see.
10703 At the target location, the entry is filed as a subitem of the target
10704 heading. Depending on `org-reverse-note-order', the new subitem will
10705 either be the first or the last subitem.
10707 If there is an active region, all entries in that region will be moved.
10708 However, the region must fulfill the requirement that the first heading
10709 is the first one sets the top-level of the moved text - at most siblings
10710 below it are allowed.
10712 With prefix arg GOTO, the command will only visit the target location
10713 and not actually move anything.
10715 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10716 go to the location where the last refiling operation has put the subtree.
10717 With a prefix argument of `2', refile to the running clock.
10719 RFLOC can be a refile location obtained in a different way.
10721 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10723 If you are using target caching (see `org-refile-use-cache'),
10724 you have to clear the target cache in order to find new targets.
10725 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10726 prefix argument (`C-u C-u C-u C-c C-w')."
10728 (interactive "P")
10729 (if (member goto '(0 (64)))
10730 (org-refile-cache-clear)
10731 (let* ((cbuf (current-buffer))
10732 (regionp (org-region-active-p))
10733 (region-start (and regionp (region-beginning)))
10734 (region-end (and regionp (region-end)))
10735 (region-length (and regionp (- region-end region-start)))
10736 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10737 pos it nbuf file re level reversed)
10738 (setq last-command nil)
10739 (when regionp
10740 (goto-char region-start)
10741 (or (bolp) (goto-char (point-at-bol)))
10742 (setq region-start (point))
10743 (unless (or (org-kill-is-subtree-p
10744 (buffer-substring region-start region-end))
10745 (prog1 org-refile-active-region-within-subtree
10746 (org-toggle-heading)))
10747 (error "The region is not a (sequence of) subtree(s)")))
10748 (if (equal goto '(16))
10749 (org-refile-goto-last-stored)
10750 (when (or
10751 (and (equal goto 2)
10752 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10753 (prog1
10754 (setq it (list (or org-clock-heading "running clock")
10755 (buffer-file-name
10756 (marker-buffer org-clock-hd-marker))
10758 (marker-position org-clock-hd-marker)))
10759 (setq goto nil)))
10760 (setq it (or rfloc
10761 (let (heading-text)
10762 (save-excursion
10763 (unless goto
10764 (org-back-to-heading t)
10765 (setq heading-text
10766 (nth 4 (org-heading-components))))
10767 (org-refile-get-location
10768 (cond (goto "Goto")
10769 (regionp "Refile region to")
10770 (t (concat "Refile subtree \""
10771 heading-text "\" to")))
10772 default-buffer
10773 (and (not (equal '(4) goto))
10774 org-refile-allow-creating-parent-nodes)
10775 goto))))))
10776 (setq file (nth 1 it)
10777 re (nth 2 it)
10778 pos (nth 3 it))
10779 (if (and (not goto)
10781 (equal (buffer-file-name) file)
10782 (if regionp
10783 (and (>= pos region-start)
10784 (<= pos region-end))
10785 (and (>= pos (point))
10786 (< pos (save-excursion
10787 (org-end-of-subtree t t))))))
10788 (error "Cannot refile to position inside the tree or region"))
10790 (setq nbuf (or (find-buffer-visiting file)
10791 (find-file-noselect file)))
10792 (if goto
10793 (progn
10794 (org-pop-to-buffer-same-window nbuf)
10795 (goto-char pos)
10796 (org-show-context 'org-goto))
10797 (if regionp
10798 (progn
10799 (org-kill-new (buffer-substring region-start region-end))
10800 (org-save-markers-in-region region-start region-end))
10801 (org-copy-subtree 1 nil t))
10802 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10803 (find-file-noselect file)))
10804 (setq reversed (org-notes-order-reversed-p))
10805 (save-excursion
10806 (save-restriction
10807 (widen)
10808 (if pos
10809 (progn
10810 (goto-char pos)
10811 (looking-at org-outline-regexp)
10812 (setq level (org-get-valid-level (funcall outline-level) 1))
10813 (goto-char
10814 (if reversed
10815 (or (outline-next-heading) (point-max))
10816 (or (save-excursion (org-get-next-sibling))
10817 (org-end-of-subtree t t)
10818 (point-max)))))
10819 (setq level 1)
10820 (if (not reversed)
10821 (goto-char (point-max))
10822 (goto-char (point-min))
10823 (or (outline-next-heading) (goto-char (point-max)))))
10824 (if (not (bolp)) (newline))
10825 (org-paste-subtree level)
10826 (when org-log-refile
10827 (org-add-log-setup 'refile nil nil 'findpos
10828 org-log-refile)
10829 (unless (eq org-log-refile 'note)
10830 (save-excursion (org-add-log-note))))
10831 (and org-auto-align-tags (org-set-tags nil t))
10832 (bookmark-set "org-refile-last-stored")
10833 ;; If we are refiling for capture, make sure that the
10834 ;; last-capture pointers point here
10835 (when (org-bound-and-true-p org-refile-for-capture)
10836 (bookmark-set "org-capture-last-stored-marker")
10837 (move-marker org-capture-last-stored-marker (point)))
10838 (if (fboundp 'deactivate-mark) (deactivate-mark))
10839 (run-hooks 'org-after-refile-insert-hook))))
10840 (if regionp
10841 (delete-region (point) (+ (point) region-length))
10842 (org-cut-subtree))
10843 (when (featurep 'org-inlinetask)
10844 (org-inlinetask-remove-END-maybe))
10845 (setq org-markers-to-move nil)
10846 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10848 (defun org-refile-goto-last-stored ()
10849 "Go to the location where the last refile was stored."
10850 (interactive)
10851 (bookmark-jump "org-refile-last-stored")
10852 (message "This is the location of the last refile"))
10854 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10855 no-exclude)
10856 "Prompt the user for a refile location, using PROMPT.
10857 PROMPT should not be suffixed with a colon and a space, because
10858 this function appends the default value from
10859 `org-refile-history' automatically, if that is not empty.
10860 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10861 this is used for the GOTO interface."
10862 (let ((org-refile-targets org-refile-targets)
10863 (org-refile-use-outline-path org-refile-use-outline-path)
10864 excluded-entries)
10865 (when (and (derived-mode-p 'org-mode)
10866 (not org-refile-use-cache)
10867 (not no-exclude))
10868 (org-map-tree
10869 (lambda()
10870 (setq excluded-entries
10871 (append excluded-entries (list (org-get-heading t t)))))))
10872 (setq org-refile-target-table
10873 (org-refile-get-targets default-buffer excluded-entries)))
10874 (unless org-refile-target-table
10875 (error "No refile targets"))
10876 (let* ((prompt (concat prompt
10877 (and (car org-refile-history)
10878 (concat " (default " (car org-refile-history) ")"))
10879 ": "))
10880 (cbuf (current-buffer))
10881 (partial-completion-mode nil)
10882 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10883 (cfunc (if (and org-refile-use-outline-path
10884 org-outline-path-complete-in-steps)
10885 'org-olpath-completing-read
10886 'org-icompleting-read))
10887 (extra (if org-refile-use-outline-path "/" ""))
10888 (filename (and cfn (expand-file-name cfn)))
10889 (tbl (mapcar
10890 (lambda (x)
10891 (if (and (not (member org-refile-use-outline-path
10892 '(file full-file-path)))
10893 (not (equal filename (nth 1 x))))
10894 (cons (concat (car x) extra " ("
10895 (file-name-nondirectory (nth 1 x)) ")")
10896 (cdr x))
10897 (cons (concat (car x) extra) (cdr x))))
10898 org-refile-target-table))
10899 (completion-ignore-case t)
10900 pa answ parent-target child parent old-hist)
10901 (setq old-hist org-refile-history)
10902 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10903 nil 'org-refile-history (car org-refile-history)))
10904 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10905 (org-refile-check-position pa)
10906 (if pa
10907 (progn
10908 (when (or (not org-refile-history)
10909 (not (eq old-hist org-refile-history))
10910 (not (equal (car pa) (car org-refile-history))))
10911 (setq org-refile-history
10912 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10913 org-refile-history
10914 (cdr org-refile-history))))
10915 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10916 (pop org-refile-history)))
10918 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10919 (progn
10920 (setq parent (match-string 1 answ)
10921 child (match-string 2 answ))
10922 (setq parent-target (or (assoc parent tbl)
10923 (assoc (concat parent "/") tbl)))
10924 (when (and parent-target
10925 (or (eq new-nodes t)
10926 (and (eq new-nodes 'confirm)
10927 (y-or-n-p (format "Create new node \"%s\"? "
10928 child)))))
10929 (org-refile-new-child parent-target child)))
10930 (error "Invalid target location")))))
10932 (declare-function org-string-nw-p "org-macs.el" (s))
10933 (defun org-refile-check-position (refile-pointer)
10934 "Check if the refile pointer matches the readline to which it points."
10935 (let* ((file (nth 1 refile-pointer))
10936 (re (nth 2 refile-pointer))
10937 (pos (nth 3 refile-pointer))
10938 buffer)
10939 (when (org-string-nw-p re)
10940 (setq buffer (if (markerp pos)
10941 (marker-buffer pos)
10942 (or (find-buffer-visiting file)
10943 (find-file-noselect file))))
10944 (with-current-buffer buffer
10945 (save-excursion
10946 (save-restriction
10947 (widen)
10948 (goto-char pos)
10949 (beginning-of-line 1)
10950 (unless (org-looking-at-p re)
10951 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10953 (defun org-refile-new-child (parent-target child)
10954 "Use refile target PARENT-TARGET to add new CHILD below it."
10955 (unless parent-target
10956 (error "Cannot find parent for new node"))
10957 (let ((file (nth 1 parent-target))
10958 (pos (nth 3 parent-target))
10959 level)
10960 (with-current-buffer (or (find-buffer-visiting file)
10961 (find-file-noselect file))
10962 (save-excursion
10963 (save-restriction
10964 (widen)
10965 (if pos
10966 (goto-char pos)
10967 (goto-char (point-max))
10968 (if (not (bolp)) (newline)))
10969 (when (looking-at org-outline-regexp)
10970 (setq level (funcall outline-level))
10971 (org-end-of-subtree t t))
10972 (org-back-over-empty-lines)
10973 (insert "\n" (make-string
10974 (if pos (org-get-valid-level level 1) 1) ?*)
10975 " " child "\n")
10976 (beginning-of-line 0)
10977 (list (concat (car parent-target) "/" child) file "" (point)))))))
10979 (defun org-olpath-completing-read (prompt collection &rest args)
10980 "Read an outline path like a file name."
10981 (let ((thetable collection)
10982 (org-completion-use-ido nil) ; does not work with ido.
10983 (org-completion-use-iswitchb nil)) ; or iswitchb
10984 (apply
10985 'org-icompleting-read prompt
10986 (lambda (string predicate &optional flag)
10987 (let (rtn r f (l (length string)))
10988 (cond
10989 ((eq flag nil)
10990 ;; try completion
10991 (try-completion string thetable))
10992 ((eq flag t)
10993 ;; all-completions
10994 (setq rtn (all-completions string thetable predicate))
10995 (mapcar
10996 (lambda (x)
10997 (setq r (substring x l))
10998 (if (string-match " ([^)]*)$" x)
10999 (setq f (match-string 0 x))
11000 (setq f ""))
11001 (if (string-match "/" r)
11002 (concat string (substring r 0 (match-end 0)) f)
11004 rtn))
11005 ((eq flag 'lambda)
11006 ;; exact match?
11007 (assoc string thetable)))))
11008 args)))
11010 ;;;; Dynamic blocks
11012 (defun org-find-dblock (name)
11013 "Find the first dynamic block with name NAME in the buffer.
11014 If not found, stay at current position and return nil."
11015 (let (pos)
11016 (save-excursion
11017 (goto-char (point-min))
11018 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
11019 nil t)
11020 (match-beginning 0))))
11021 (if pos (goto-char pos))
11022 pos))
11024 (defconst org-dblock-start-re
11025 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11026 "Matches the start line of a dynamic block, with parameters.")
11028 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
11029 "Matches the end of a dynamic block.")
11031 (defun org-create-dblock (plist)
11032 "Create a dynamic block section, with parameters taken from PLIST.
11033 PLIST must contain a :name entry which is used as name of the block."
11034 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11035 (end-of-line 1)
11036 (newline))
11037 (let ((col (current-column))
11038 (name (plist-get plist :name)))
11039 (insert "#+BEGIN: " name)
11040 (while plist
11041 (if (eq (car plist) :name)
11042 (setq plist (cddr plist))
11043 (insert " " (prin1-to-string (pop plist)))))
11044 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11045 (beginning-of-line -2)))
11047 (defun org-prepare-dblock ()
11048 "Prepare dynamic block for refresh.
11049 This empties the block, puts the cursor at the insert position and returns
11050 the property list including an extra property :name with the block name."
11051 (unless (looking-at org-dblock-start-re)
11052 (error "Not at a dynamic block"))
11053 (let* ((begdel (1+ (match-end 0)))
11054 (name (org-no-properties (match-string 1)))
11055 (params (append (list :name name)
11056 (read (concat "(" (match-string 3) ")")))))
11057 (save-excursion
11058 (beginning-of-line 1)
11059 (skip-chars-forward " \t")
11060 (setq params (plist-put params :indentation-column (current-column))))
11061 (unless (re-search-forward org-dblock-end-re nil t)
11062 (error "Dynamic block not terminated"))
11063 (setq params
11064 (append params
11065 (list :content (buffer-substring
11066 begdel (match-beginning 0)))))
11067 (delete-region begdel (match-beginning 0))
11068 (goto-char begdel)
11069 (open-line 1)
11070 params))
11072 (defun org-map-dblocks (&optional command)
11073 "Apply COMMAND to all dynamic blocks in the current buffer.
11074 If COMMAND is not given, use `org-update-dblock'."
11075 (let ((cmd (or command 'org-update-dblock)))
11076 (save-excursion
11077 (goto-char (point-min))
11078 (while (re-search-forward org-dblock-start-re nil t)
11079 (goto-char (match-beginning 0))
11080 (save-excursion
11081 (condition-case nil
11082 (funcall cmd)
11083 (error (message "Error during update of dynamic block"))))
11084 (unless (re-search-forward org-dblock-end-re nil t)
11085 (error "Dynamic block not terminated"))))))
11087 (defun org-dblock-update (&optional arg)
11088 "User command for updating dynamic blocks.
11089 Update the dynamic block at point. With prefix ARG, update all dynamic
11090 blocks in the buffer."
11091 (interactive "P")
11092 (if arg
11093 (org-update-all-dblocks)
11094 (or (looking-at org-dblock-start-re)
11095 (org-beginning-of-dblock))
11096 (org-update-dblock)))
11098 (defun org-update-dblock ()
11099 "Update the dynamic block at point.
11100 This means to empty the block, parse for parameters and then call
11101 the correct writing function."
11102 (interactive)
11103 (save-window-excursion
11104 (let* ((pos (point))
11105 (line (org-current-line))
11106 (params (org-prepare-dblock))
11107 (name (plist-get params :name))
11108 (indent (plist-get params :indentation-column))
11109 (cmd (intern (concat "org-dblock-write:" name))))
11110 (message "Updating dynamic block `%s' at line %d..." name line)
11111 (funcall cmd params)
11112 (message "Updating dynamic block `%s' at line %d...done" name line)
11113 (goto-char pos)
11114 (when (and indent (> indent 0))
11115 (setq indent (make-string indent ?\ ))
11116 (save-excursion
11117 (org-beginning-of-dblock)
11118 (forward-line 1)
11119 (while (not (looking-at org-dblock-end-re))
11120 (insert indent)
11121 (beginning-of-line 2))
11122 (when (looking-at org-dblock-end-re)
11123 (and (looking-at "[ \t]+")
11124 (replace-match ""))
11125 (insert indent)))))))
11127 (defun org-beginning-of-dblock ()
11128 "Find the beginning of the dynamic block at point.
11129 Error if there is no such block at point."
11130 (let ((pos (point))
11131 beg)
11132 (end-of-line 1)
11133 (if (and (re-search-backward org-dblock-start-re nil t)
11134 (setq beg (match-beginning 0))
11135 (re-search-forward org-dblock-end-re nil t)
11136 (> (match-end 0) pos))
11137 (goto-char beg)
11138 (goto-char pos)
11139 (error "Not in a dynamic block"))))
11141 ;;;###autoload
11142 (defun org-update-all-dblocks ()
11143 "Update all dynamic blocks in the buffer.
11144 This function can be used in a hook."
11145 (interactive)
11146 (when (derived-mode-p 'org-mode)
11147 (org-map-dblocks 'org-update-dblock)))
11150 ;;;; Completion
11152 (defconst org-additional-option-like-keywords
11153 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11154 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11155 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11156 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11157 "BEGIN:" "END:"
11158 "ORGTBL" "TBLFM:" "TBLNAME:"
11159 "BEGIN_EXAMPLE" "END_EXAMPLE"
11160 "BEGIN_QUOTE" "END_QUOTE"
11161 "BEGIN_VERSE" "END_VERSE"
11162 "BEGIN_CENTER" "END_CENTER"
11163 "BEGIN_SRC" "END_SRC"
11164 "BEGIN_RESULT" "END_RESULT"
11165 "NAME:" "RESULTS:"
11166 "HEADER:" "HEADERS:"
11167 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11168 "CAPTION:" "LABEL:"
11169 "SETUPFILE:"
11170 "INCLUDE:"
11171 "BIND:"
11172 "MACRO:"))
11174 (defcustom org-structure-template-alist
11176 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11177 "<src lang=\"?\">\n\n</src>")
11178 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11179 "<example>\n?\n</example>")
11180 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11181 "<quote>\n?\n</quote>")
11182 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11183 "<verse>\n?\n</verse>")
11184 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11185 "<center>\n?\n</center>")
11186 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11187 "<literal style=\"latex\">\n?\n</literal>")
11188 ("L" "#+LaTeX: "
11189 "<literal style=\"latex\">?</literal>")
11190 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11191 "<literal style=\"html\">\n?\n</literal>")
11192 ("H" "#+HTML: "
11193 "<literal style=\"html\">?</literal>")
11194 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11195 ("A" "#+ASCII: ")
11196 ("i" "#+INDEX: ?"
11197 "#+INDEX: ?")
11198 ("I" "#+INCLUDE %file ?"
11199 "<include file=%file markup=\"?\">")
11201 "Structure completion elements.
11202 This is a list of abbreviation keys and values. The value gets inserted
11203 if you type `<' followed by the key and then press the completion key,
11204 usually `M-TAB'. %file will be replaced by a file name after prompting
11205 for the file using completion. The cursor will be placed at the position
11206 of the `?` in the template.
11207 There are two templates for each key, the first uses the original Org syntax,
11208 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11209 the default when the /org-mtags.el/ module has been loaded. See also the
11210 variable `org-mtags-prefer-muse-templates'."
11211 :group 'org-completion
11212 :type '(repeat
11213 (string :tag "Key")
11214 (string :tag "Template")
11215 (string :tag "Muse Template")))
11217 (defun org-try-structure-completion ()
11218 "Try to complete a structure template before point.
11219 This looks for strings like \"<e\" on an otherwise empty line and
11220 expands them."
11221 (let ((l (buffer-substring (point-at-bol) (point)))
11223 (when (and (looking-at "[ \t]*$")
11224 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11225 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11226 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11227 (match-beginning 1)) a)
11228 t)))
11230 (defun org-complete-expand-structure-template (start cell)
11231 "Expand a structure template."
11232 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11233 (rpl (nth (if musep 2 1) cell))
11234 (ind ""))
11235 (delete-region start (point))
11236 (when (string-match "\\`#\\+" rpl)
11237 (cond
11238 ((bolp))
11239 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11240 (setq ind (buffer-substring (point-at-bol) (point))))
11241 (t (newline))))
11242 (setq start (point))
11243 (if (string-match "%file" rpl)
11244 (setq rpl (replace-match
11245 (concat
11246 "\""
11247 (save-match-data
11248 (abbreviate-file-name (read-file-name "Include file: ")))
11249 "\"")
11250 t t rpl)))
11251 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11252 (concat "\n" ind)))
11253 (insert rpl)
11254 (if (re-search-backward "\\?" start t) (delete-char 1))))
11256 ;;;; TODO, DEADLINE, Comments
11258 (defun org-toggle-comment ()
11259 "Change the COMMENT state of an entry."
11260 (interactive)
11261 (save-excursion
11262 (org-back-to-heading)
11263 (let (case-fold-search)
11264 (cond
11265 ((looking-at (format org-heading-keyword-regexp-format
11266 org-comment-string))
11267 (goto-char (match-end 1))
11268 (looking-at (concat " +" org-comment-string))
11269 (replace-match "" t t)
11270 (when (eolp) (insert " ")))
11271 ((looking-at org-outline-regexp)
11272 (goto-char (match-end 0))
11273 (insert org-comment-string " "))))))
11275 (defvar org-last-todo-state-is-todo nil
11276 "This is non-nil when the last TODO state change led to a TODO state.
11277 If the last change removed the TODO tag or switched to DONE, then
11278 this is nil.")
11280 (defvar org-setting-tags nil) ; dynamically skipped
11282 (defvar org-todo-setup-filter-hook nil
11283 "Hook for functions that pre-filter todo specs.
11284 Each function takes a todo spec and returns either nil or the spec
11285 transformed into canonical form." )
11287 (defvar org-todo-get-default-hook nil
11288 "Hook for functions that get a default item for todo.
11289 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11290 nil or a string to be used for the todo mark." )
11292 (defvar org-agenda-headline-snapshot-before-repeat)
11294 (defun org-current-effective-time ()
11295 "Return current time adjusted for `org-extend-today-until' variable"
11296 (let* ((ct (org-current-time))
11297 (dct (decode-time ct))
11298 (ct1
11299 (if (and org-use-effective-time
11300 (< (nth 2 dct) org-extend-today-until))
11301 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11302 ct)))
11303 ct1))
11305 (defun org-todo-yesterday (&optional arg)
11306 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11307 (interactive "P")
11308 (if (eq major-mode 'org-agenda-mode)
11309 (apply 'org-agenda-todo-yesterday arg)
11310 (let* ((hour (third (decode-time
11311 (org-current-time))))
11312 (org-extend-today-until (1+ hour)))
11313 (org-todo arg))))
11315 (defun org-todo (&optional arg)
11316 "Change the TODO state of an item.
11317 The state of an item is given by a keyword at the start of the heading,
11318 like
11319 *** TODO Write paper
11320 *** DONE Call mom
11322 The different keywords are specified in the variable `org-todo-keywords'.
11323 By default the available states are \"TODO\" and \"DONE\".
11324 So for this example: when the item starts with TODO, it is changed to DONE.
11325 When it starts with DONE, the DONE is removed. And when neither TODO nor
11326 DONE are present, add TODO at the beginning of the heading.
11328 With \\[universal-argument] prefix arg, use completion to determine the new \
11329 state.
11330 With numeric prefix arg, switch to that state.
11331 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11332 keywords (nextset).
11333 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11334 With a numeric prefix arg of 0, inhibit note taking for the change.
11336 For calling through lisp, arg is also interpreted in the following way:
11337 'none -> empty state
11338 \"\"(empty string) -> switch to empty state
11339 'done -> switch to DONE
11340 'nextset -> switch to the next set of keywords
11341 'previousset -> switch to the previous set of keywords
11342 \"WAITING\" -> switch to the specified keyword, but only if it
11343 really is a member of `org-todo-keywords'."
11344 (interactive "P")
11345 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11346 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11347 'region-start-level 'region))
11348 org-loop-over-headlines-in-active-region)
11349 (org-map-entries
11350 `(org-todo ,arg)
11351 org-loop-over-headlines-in-active-region
11352 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11353 (if (equal arg '(16)) (setq arg 'nextset))
11354 (let ((org-blocker-hook org-blocker-hook)
11355 (case-fold-search nil))
11356 (when (equal arg '(64))
11357 (setq arg nil org-blocker-hook nil))
11358 (when (and org-blocker-hook
11359 (or org-inhibit-blocking
11360 (org-entry-get nil "NOBLOCKING")))
11361 (setq org-blocker-hook nil))
11362 (save-excursion
11363 (catch 'exit
11364 (org-back-to-heading t)
11365 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11366 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11367 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11368 (let* ((match-data (match-data))
11369 (startpos (point-at-bol))
11370 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11371 (org-log-done org-log-done)
11372 (org-log-repeat org-log-repeat)
11373 (org-todo-log-states org-todo-log-states)
11374 (org-inhibit-logging
11375 (if (equal arg 0)
11376 (progn (setq arg nil) 'note) org-inhibit-logging))
11377 (this (match-string 1))
11378 (hl-pos (match-beginning 0))
11379 (head (org-get-todo-sequence-head this))
11380 (ass (assoc head org-todo-kwd-alist))
11381 (interpret (nth 1 ass))
11382 (done-word (nth 3 ass))
11383 (final-done-word (nth 4 ass))
11384 (org-last-state (or this ""))
11385 (completion-ignore-case t)
11386 (member (member this org-todo-keywords-1))
11387 (tail (cdr member))
11388 (org-state (cond
11389 ((and org-todo-key-trigger
11390 (or (and (equal arg '(4))
11391 (eq org-use-fast-todo-selection 'prefix))
11392 (and (not arg) org-use-fast-todo-selection
11393 (not (eq org-use-fast-todo-selection
11394 'prefix)))))
11395 ;; Use fast selection
11396 (org-fast-todo-selection))
11397 ((and (equal arg '(4))
11398 (or (not org-use-fast-todo-selection)
11399 (not org-todo-key-trigger)))
11400 ;; Read a state with completion
11401 (org-icompleting-read
11402 "State: " (mapcar (lambda(x) (list x))
11403 org-todo-keywords-1)
11404 nil t))
11405 ((eq arg 'right)
11406 (if this
11407 (if tail (car tail) nil)
11408 (car org-todo-keywords-1)))
11409 ((eq arg 'left)
11410 (if (equal member org-todo-keywords-1)
11412 (if this
11413 (nth (- (length org-todo-keywords-1)
11414 (length tail) 2)
11415 org-todo-keywords-1)
11416 (org-last org-todo-keywords-1))))
11417 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11418 (setq arg nil))) ; hack to fall back to cycling
11419 (arg
11420 ;; user or caller requests a specific state
11421 (cond
11422 ((equal arg "") nil)
11423 ((eq arg 'none) nil)
11424 ((eq arg 'done) (or done-word (car org-done-keywords)))
11425 ((eq arg 'nextset)
11426 (or (car (cdr (member head org-todo-heads)))
11427 (car org-todo-heads)))
11428 ((eq arg 'previousset)
11429 (let ((org-todo-heads (reverse org-todo-heads)))
11430 (or (car (cdr (member head org-todo-heads)))
11431 (car org-todo-heads))))
11432 ((car (member arg org-todo-keywords-1)))
11433 ((stringp arg)
11434 (error "State `%s' not valid in this file" arg))
11435 ((nth (1- (prefix-numeric-value arg))
11436 org-todo-keywords-1))))
11437 ((null member) (or head (car org-todo-keywords-1)))
11438 ((equal this final-done-word) nil) ;; -> make empty
11439 ((null tail) nil) ;; -> first entry
11440 ((memq interpret '(type priority))
11441 (if (eq this-command last-command)
11442 (car tail)
11443 (if (> (length tail) 0)
11444 (or done-word (car org-done-keywords))
11445 nil)))
11447 (car tail))))
11448 (org-state (or
11449 (run-hook-with-args-until-success
11450 'org-todo-get-default-hook org-state org-last-state)
11451 org-state))
11452 (next (if org-state (concat " " org-state " ") " "))
11453 (change-plist (list :type 'todo-state-change :from this :to org-state
11454 :position startpos))
11455 dolog now-done-p)
11456 (when org-blocker-hook
11457 (setq org-last-todo-state-is-todo
11458 (not (member this org-done-keywords)))
11459 (unless (save-excursion
11460 (save-match-data
11461 (org-with-wide-buffer
11462 (run-hook-with-args-until-failure
11463 'org-blocker-hook change-plist))))
11464 (if (org-called-interactively-p 'interactive)
11465 (error "TODO state change from %s to %s blocked" this org-state)
11466 ;; fail silently
11467 (message "TODO state change from %s to %s blocked" this org-state)
11468 (throw 'exit nil))))
11469 (store-match-data match-data)
11470 (replace-match next t t)
11471 (unless (pos-visible-in-window-p hl-pos)
11472 (message "TODO state changed to %s" (org-trim next)))
11473 (unless head
11474 (setq head (org-get-todo-sequence-head org-state)
11475 ass (assoc head org-todo-kwd-alist)
11476 interpret (nth 1 ass)
11477 done-word (nth 3 ass)
11478 final-done-word (nth 4 ass)))
11479 (when (memq arg '(nextset previousset))
11480 (message "Keyword-Set %d/%d: %s"
11481 (- (length org-todo-sets) -1
11482 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11483 (length org-todo-sets)
11484 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11485 (setq org-last-todo-state-is-todo
11486 (not (member org-state org-done-keywords)))
11487 (setq now-done-p (and (member org-state org-done-keywords)
11488 (not (member this org-done-keywords))))
11489 (and logging (org-local-logging logging))
11490 (when (and (or org-todo-log-states org-log-done)
11491 (not (eq org-inhibit-logging t))
11492 (not (memq arg '(nextset previousset))))
11493 ;; we need to look at recording a time and note
11494 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11495 (nth 2 (assoc this org-todo-log-states))))
11496 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11497 (setq dolog 'time))
11498 (when (and org-state
11499 (member org-state org-not-done-keywords)
11500 (not (member this org-not-done-keywords)))
11501 ;; This is now a todo state and was not one before
11502 ;; If there was a CLOSED time stamp, get rid of it.
11503 (org-add-planning-info nil nil 'closed))
11504 (when (and now-done-p org-log-done)
11505 ;; It is now done, and it was not done before
11506 (org-add-planning-info 'closed (org-current-effective-time))
11507 (if (and (not dolog) (eq 'note org-log-done))
11508 (org-add-log-setup 'done org-state this 'findpos 'note)))
11509 (when (and org-state dolog)
11510 ;; This is a non-nil state, and we need to log it
11511 (org-add-log-setup 'state org-state this 'findpos dolog)))
11512 ;; Fixup tag positioning
11513 (org-todo-trigger-tag-changes org-state)
11514 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11515 (when org-provide-todo-statistics
11516 (org-update-parent-todo-statistics))
11517 (run-hooks 'org-after-todo-state-change-hook)
11518 (if (and arg (not (member org-state org-done-keywords)))
11519 (setq head (org-get-todo-sequence-head org-state)))
11520 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11521 ;; Do we need to trigger a repeat?
11522 (when now-done-p
11523 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11524 ;; This is for the agenda, take a snapshot of the headline.
11525 (save-match-data
11526 (setq org-agenda-headline-snapshot-before-repeat
11527 (org-get-heading))))
11528 (org-auto-repeat-maybe org-state))
11529 ;; Fixup cursor location if close to the keyword
11530 (if (and (outline-on-heading-p)
11531 (not (bolp))
11532 (save-excursion (beginning-of-line 1)
11533 (looking-at org-todo-line-regexp))
11534 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11535 (progn
11536 (goto-char (or (match-end 2) (match-end 1)))
11537 (and (looking-at " ") (just-one-space))))
11538 (when org-trigger-hook
11539 (save-excursion
11540 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11542 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11543 "Block turning an entry into a TODO, using the hierarchy.
11544 This checks whether the current task should be blocked from state
11545 changes. Such blocking occurs when:
11547 1. The task has children which are not all in a completed state.
11549 2. A task has a parent with the property :ORDERED:, and there
11550 are siblings prior to the current task with incomplete
11551 status.
11553 3. The parent of the task is blocked because it has siblings that should
11554 be done first, or is child of a block grandparent TODO entry."
11556 (if (not org-enforce-todo-dependencies)
11557 t ; if locally turned off don't block
11558 (catch 'dont-block
11559 ;; If this is not a todo state change, or if this entry is already DONE,
11560 ;; do not block
11561 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11562 (member (plist-get change-plist :from)
11563 (cons 'done org-done-keywords))
11564 (member (plist-get change-plist :to)
11565 (cons 'todo org-not-done-keywords))
11566 (not (plist-get change-plist :to)))
11567 (throw 'dont-block t))
11568 ;; If this task has children, and any are undone, it's blocked
11569 (save-excursion
11570 (org-back-to-heading t)
11571 (let ((this-level (funcall outline-level)))
11572 (outline-next-heading)
11573 (let ((child-level (funcall outline-level)))
11574 (while (and (not (eobp))
11575 (> child-level this-level))
11576 ;; this todo has children, check whether they are all
11577 ;; completed
11578 (if (and (not (org-entry-is-done-p))
11579 (org-entry-is-todo-p))
11580 (throw 'dont-block nil))
11581 (outline-next-heading)
11582 (setq child-level (funcall outline-level))))))
11583 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11584 ;; any previous siblings are undone, it's blocked
11585 (save-excursion
11586 (org-back-to-heading t)
11587 (let* ((pos (point))
11588 (parent-pos (and (org-up-heading-safe) (point))))
11589 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11590 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11591 (forward-line 1)
11592 (re-search-forward org-not-done-heading-regexp pos t))
11593 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11594 ;; Search further up the hierarchy, to see if an ancestor is blocked
11595 (while t
11596 (goto-char parent-pos)
11597 (if (not (looking-at org-not-done-heading-regexp))
11598 (throw 'dont-block t)) ; do not block, parent is not a TODO
11599 (setq pos (point))
11600 (setq parent-pos (and (org-up-heading-safe) (point)))
11601 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11602 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11603 (forward-line 1)
11604 (re-search-forward org-not-done-heading-regexp pos t))
11605 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11607 (defcustom org-track-ordered-property-with-tag nil
11608 "Should the ORDERED property also be shown as a tag?
11609 The ORDERED property decides if an entry should require subtasks to be
11610 completed in sequence. Since a property is not very visible, setting
11611 this option means that toggling the ORDERED property with the command
11612 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11613 not relevant for the behavior, but it makes things more visible.
11615 Note that toggling the tag with tags commands will not change the property
11616 and therefore not influence behavior!
11618 This can be t, meaning the tag ORDERED should be used, It can also be a
11619 string to select a different tag for this task."
11620 :group 'org-todo
11621 :type '(choice
11622 (const :tag "No tracking" nil)
11623 (const :tag "Track with ORDERED tag" t)
11624 (string :tag "Use other tag")))
11626 (defun org-toggle-ordered-property ()
11627 "Toggle the ORDERED property of the current entry.
11628 For better visibility, you can track the value of this property with a tag.
11629 See variable `org-track-ordered-property-with-tag'."
11630 (interactive)
11631 (let* ((t1 org-track-ordered-property-with-tag)
11632 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11633 (save-excursion
11634 (org-back-to-heading)
11635 (if (org-entry-get nil "ORDERED")
11636 (progn
11637 (org-delete-property "ORDERED")
11638 (and tag (org-toggle-tag tag 'off))
11639 (message "Subtasks can be completed in arbitrary order"))
11640 (org-entry-put nil "ORDERED" "t")
11641 (and tag (org-toggle-tag tag 'on))
11642 (message "Subtasks must be completed in sequence")))))
11644 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11645 (defun org-block-todo-from-checkboxes (change-plist)
11646 "Block turning an entry into a TODO, using checkboxes.
11647 This checks whether the current task should be blocked from state
11648 changes because there are unchecked boxes in this entry."
11649 (if (not org-enforce-todo-checkbox-dependencies)
11650 t ; if locally turned off don't block
11651 (catch 'dont-block
11652 ;; If this is not a todo state change, or if this entry is already DONE,
11653 ;; do not block
11654 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11655 (member (plist-get change-plist :from)
11656 (cons 'done org-done-keywords))
11657 (member (plist-get change-plist :to)
11658 (cons 'todo org-not-done-keywords))
11659 (not (plist-get change-plist :to)))
11660 (throw 'dont-block t))
11661 ;; If this task has checkboxes that are not checked, it's blocked
11662 (save-excursion
11663 (org-back-to-heading t)
11664 (let ((beg (point)) end)
11665 (outline-next-heading)
11666 (setq end (point))
11667 (goto-char beg)
11668 (if (org-list-search-forward
11669 (concat (org-item-beginning-re)
11670 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11671 "\\[[- ]\\]")
11672 end t)
11673 (progn
11674 (if (boundp 'org-blocked-by-checkboxes)
11675 (setq org-blocked-by-checkboxes t))
11676 (throw 'dont-block nil)))))
11677 t))) ; do not block
11679 (defun org-entry-blocked-p ()
11680 "Is the current entry blocked?"
11681 (if (org-entry-get nil "NOBLOCKING")
11682 nil ;; Never block this entry
11683 (not
11684 (run-hook-with-args-until-failure
11685 'org-blocker-hook
11686 (list :type 'todo-state-change
11687 :position (point)
11688 :from 'todo
11689 :to 'done)))))
11691 (defun org-update-statistics-cookies (all)
11692 "Update the statistics cookie, either from TODO or from checkboxes.
11693 This should be called with the cursor in a line with a statistics cookie."
11694 (interactive "P")
11695 (if all
11696 (progn
11697 (org-update-checkbox-count 'all)
11698 (org-map-entries 'org-update-parent-todo-statistics))
11699 (if (not (org-at-heading-p))
11700 (org-update-checkbox-count)
11701 (let ((pos (move-marker (make-marker) (point)))
11702 end l1 l2)
11703 (ignore-errors (org-back-to-heading t))
11704 (if (not (org-at-heading-p))
11705 (org-update-checkbox-count)
11706 (setq l1 (org-outline-level))
11707 (setq end (save-excursion
11708 (outline-next-heading)
11709 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11710 (point)))
11711 (if (and (save-excursion
11712 (re-search-forward
11713 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11714 (not (save-excursion (re-search-forward
11715 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11716 (org-update-checkbox-count)
11717 (if (and l2 (> l2 l1))
11718 (progn
11719 (goto-char end)
11720 (org-update-parent-todo-statistics))
11721 (goto-char pos)
11722 (beginning-of-line 1)
11723 (while (re-search-forward
11724 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11725 (point-at-eol) t)
11726 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11727 (goto-char pos)
11728 (move-marker pos nil)))))
11730 (defvar org-entry-property-inherited-from) ;; defined below
11731 (defun org-update-parent-todo-statistics ()
11732 "Update any statistics cookie in the parent of the current headline.
11733 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11734 the entire subtree and this will travel up the hierarchy and update
11735 statistics everywhere."
11736 (let* ((prop (save-excursion (org-up-heading-safe)
11737 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11738 (recursive (or (not org-hierarchical-todo-statistics)
11739 (and prop (string-match "\\<recursive\\>" prop))))
11740 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11742 (first t)
11743 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11744 level ltoggle l1 new ndel
11745 (cnt-all 0) (cnt-done 0) is-percent kwd
11746 checkbox-beg ov ovs ove cookie-present)
11747 (catch 'exit
11748 (save-excursion
11749 (beginning-of-line 1)
11750 (setq ltoggle (funcall outline-level))
11751 ;; Three situations are to consider:
11753 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11754 ;; to the top-level ancestor on the headline;
11756 ;; 2. If parent has "recursive" property, repeat up to the
11757 ;; headline setting that property, taking inheritance into
11758 ;; account;
11760 ;; 3. Else, move up to direct parent and proceed only once.
11761 (while (and (setq level (org-up-heading-safe))
11762 (or recursive first)
11763 (>= (point) lim))
11764 (setq first nil cookie-present nil)
11765 (unless (and level
11766 (not (string-match
11767 "\\<checkbox\\>"
11768 (downcase (or (org-entry-get nil "COOKIE_DATA")
11769 "")))))
11770 (throw 'exit nil))
11771 (while (re-search-forward box-re (point-at-eol) t)
11772 (setq cnt-all 0 cnt-done 0 cookie-present t)
11773 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11774 (save-match-data
11775 (unless (outline-next-heading) (throw 'exit nil))
11776 (while (and (looking-at org-complex-heading-regexp)
11777 (> (setq l1 (length (match-string 1))) level))
11778 (setq kwd (and (or recursive (= l1 ltoggle))
11779 (match-string 2)))
11780 (if (or (eq org-provide-todo-statistics 'all-headlines)
11781 (and (listp org-provide-todo-statistics)
11782 (or (member kwd org-provide-todo-statistics)
11783 (member kwd org-done-keywords))))
11784 (setq cnt-all (1+ cnt-all))
11785 (if (eq org-provide-todo-statistics t)
11786 (and kwd (setq cnt-all (1+ cnt-all)))))
11787 (and (member kwd org-done-keywords)
11788 (setq cnt-done (1+ cnt-done)))
11789 (outline-next-heading)))
11790 (setq new
11791 (if is-percent
11792 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11793 (format "[%d/%d]" cnt-done cnt-all))
11794 ndel (- (match-end 0) checkbox-beg))
11795 ;; handle overlays when updating cookie from column view
11796 (when (setq ov (car (overlays-at checkbox-beg)))
11797 (setq ovs (overlay-start ov) ove (overlay-end ov))
11798 (delete-overlay ov))
11799 (goto-char checkbox-beg)
11800 (insert new)
11801 (delete-region (point) (+ (point) ndel))
11802 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11803 (when ov (move-overlay ov ovs ove)))
11804 (when cookie-present
11805 (run-hook-with-args 'org-after-todo-statistics-hook
11806 cnt-done (- cnt-all cnt-done))))))
11807 (run-hooks 'org-todo-statistics-hook)))
11809 (defvar org-after-todo-statistics-hook nil
11810 "Hook that is called after a TODO statistics cookie has been updated.
11811 Each function is called with two arguments: the number of not-done entries
11812 and the number of done entries.
11814 For example, the following function, when added to this hook, will switch
11815 an entry to DONE when all children are done, and back to TODO when new
11816 entries are set to a TODO status. Note that this hook is only called
11817 when there is a statistics cookie in the headline!
11819 (defun org-summary-todo (n-done n-not-done)
11820 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11821 (let (org-log-done org-log-states) ; turn off logging
11822 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11825 (defvar org-todo-statistics-hook nil
11826 "Hook that is run whenever Org thinks TODO statistics should be updated.
11827 This hook runs even if there is no statistics cookie present, in which case
11828 `org-after-todo-statistics-hook' would not run.")
11830 (defun org-todo-trigger-tag-changes (state)
11831 "Apply the changes defined in `org-todo-state-tags-triggers'."
11832 (let ((l org-todo-state-tags-triggers)
11833 changes)
11834 (when (or (not state) (equal state ""))
11835 (setq changes (append changes (cdr (assoc "" l)))))
11836 (when (and (stringp state) (> (length state) 0))
11837 (setq changes (append changes (cdr (assoc state l)))))
11838 (when (member state org-not-done-keywords)
11839 (setq changes (append changes (cdr (assoc 'todo l)))))
11840 (when (member state org-done-keywords)
11841 (setq changes (append changes (cdr (assoc 'done l)))))
11842 (dolist (c changes)
11843 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11845 (defun org-local-logging (value)
11846 "Get logging settings from a property VALUE."
11847 (let* (words w a)
11848 ;; directly set the variables, they are already local.
11849 (setq org-log-done nil
11850 org-log-repeat nil
11851 org-todo-log-states nil)
11852 (setq words (org-split-string value))
11853 (while (setq w (pop words))
11854 (cond
11855 ((setq a (assoc w org-startup-options))
11856 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11857 (set (nth 1 a) (nth 2 a))))
11858 ((setq a (org-extract-log-state-settings w))
11859 (and (member (car a) org-todo-keywords-1)
11860 (push a org-todo-log-states)))))))
11862 (defun org-get-todo-sequence-head (kwd)
11863 "Return the head of the TODO sequence to which KWD belongs.
11864 If KWD is not set, check if there is a text property remembering the
11865 right sequence."
11866 (let (p)
11867 (cond
11868 ((not kwd)
11869 (or (get-text-property (point-at-bol) 'org-todo-head)
11870 (progn
11871 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11872 nil (point-at-eol)))
11873 (get-text-property p 'org-todo-head))))
11874 ((not (member kwd org-todo-keywords-1))
11875 (car org-todo-keywords-1))
11876 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11878 (defun org-fast-todo-selection ()
11879 "Fast TODO keyword selection with single keys.
11880 Returns the new TODO keyword, or nil if no state change should occur."
11881 (let* ((fulltable org-todo-key-alist)
11882 (done-keywords org-done-keywords) ;; needed for the faces.
11883 (maxlen (apply 'max (mapcar
11884 (lambda (x)
11885 (if (stringp (car x)) (string-width (car x)) 0))
11886 fulltable)))
11887 (expert nil)
11888 (fwidth (+ maxlen 3 1 3))
11889 (ncol (/ (- (window-width) 4) fwidth))
11890 tg cnt e c tbl
11891 groups ingroup)
11892 (save-excursion
11893 (save-window-excursion
11894 (if expert
11895 (set-buffer (get-buffer-create " *Org todo*"))
11896 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11897 (erase-buffer)
11898 (org-set-local 'org-done-keywords done-keywords)
11899 (setq tbl fulltable cnt 0)
11900 (while (setq e (pop tbl))
11901 (cond
11902 ((equal e '(:startgroup))
11903 (push '() groups) (setq ingroup t)
11904 (when (not (= cnt 0))
11905 (setq cnt 0)
11906 (insert "\n"))
11907 (insert "{ "))
11908 ((equal e '(:endgroup))
11909 (setq ingroup nil cnt 0)
11910 (insert "}\n"))
11911 ((equal e '(:newline))
11912 (when (not (= cnt 0))
11913 (setq cnt 0)
11914 (insert "\n")
11915 (setq e (car tbl))
11916 (while (equal (car tbl) '(:newline))
11917 (insert "\n")
11918 (setq tbl (cdr tbl)))))
11920 (setq tg (car e) c (cdr e))
11921 (if ingroup (push tg (car groups)))
11922 (setq tg (org-add-props tg nil 'face
11923 (org-get-todo-face tg)))
11924 (if (and (= cnt 0) (not ingroup)) (insert " "))
11925 (insert "[" c "] " tg (make-string
11926 (- fwidth 4 (length tg)) ?\ ))
11927 (when (= (setq cnt (1+ cnt)) ncol)
11928 (insert "\n")
11929 (if ingroup (insert " "))
11930 (setq cnt 0)))))
11931 (insert "\n")
11932 (goto-char (point-min))
11933 (if (not expert) (org-fit-window-to-buffer))
11934 (message "[a-z..]:Set [SPC]:clear")
11935 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11936 (cond
11937 ((or (= c ?\C-g)
11938 (and (= c ?q) (not (rassoc c fulltable))))
11939 (setq quit-flag t))
11940 ((= c ?\ ) nil)
11941 ((setq e (rassoc c fulltable) tg (car e))
11943 (t (setq quit-flag t)))))))
11945 (defun org-entry-is-todo-p ()
11946 (member (org-get-todo-state) org-not-done-keywords))
11948 (defun org-entry-is-done-p ()
11949 (member (org-get-todo-state) org-done-keywords))
11951 (defun org-get-todo-state ()
11952 (save-excursion
11953 (org-back-to-heading t)
11954 (and (looking-at org-todo-line-regexp)
11955 (match-end 2)
11956 (match-string 2))))
11958 (defun org-at-date-range-p (&optional inactive-ok)
11959 "Is the cursor inside a date range?"
11960 (interactive)
11961 (save-excursion
11962 (catch 'exit
11963 (let ((pos (point)))
11964 (skip-chars-backward "^[<\r\n")
11965 (skip-chars-backward "<[")
11966 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11967 (>= (match-end 0) pos)
11968 (throw 'exit t))
11969 (skip-chars-backward "^<[\r\n")
11970 (skip-chars-backward "<[")
11971 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11972 (>= (match-end 0) pos)
11973 (throw 'exit t)))
11974 nil)))
11976 (defun org-get-repeat (&optional tagline)
11977 "Check if there is a deadline/schedule with repeater in this entry."
11978 (save-match-data
11979 (save-excursion
11980 (org-back-to-heading t)
11981 (and (re-search-forward (if tagline
11982 (concat tagline "\\s-*" org-repeat-re)
11983 org-repeat-re)
11984 (org-entry-end-position) t)
11985 (match-string-no-properties 1)))))
11987 (defvar org-last-changed-timestamp)
11988 (defvar org-last-inserted-timestamp)
11989 (defvar org-log-post-message)
11990 (defvar org-log-note-purpose)
11991 (defvar org-log-note-how)
11992 (defvar org-log-note-extra)
11993 (defun org-auto-repeat-maybe (done-word)
11994 "Check if the current headline contains a repeated deadline/schedule.
11995 If yes, set TODO state back to what it was and change the base date
11996 of repeating deadline/scheduled time stamps to new date.
11997 This function is run automatically after each state change to a DONE state."
11998 ;; last-state is dynamically scoped into this function
11999 (let* ((repeat (org-get-repeat))
12000 (aa (assoc org-last-state org-todo-kwd-alist))
12001 (interpret (nth 1 aa))
12002 (head (nth 2 aa))
12003 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12004 (msg "Entry repeats: ")
12005 (org-log-done nil)
12006 (org-todo-log-states nil)
12007 re type n what ts time to-state)
12008 (when repeat
12009 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12010 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12011 org-todo-repeat-to-state))
12012 (unless (and to-state (member to-state org-todo-keywords-1))
12013 (setq to-state (if (eq interpret 'type) org-last-state head)))
12014 (org-todo to-state)
12015 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12016 (org-entry-put nil "LAST_REPEAT" (format-time-string
12017 (org-time-stamp-format t t))))
12018 (when org-log-repeat
12019 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12020 (memq 'org-add-log-note post-command-hook))
12021 ;; OK, we are already setup for some record
12022 (if (eq org-log-repeat 'note)
12023 ;; make sure we take a note, not only a time stamp
12024 (setq org-log-note-how 'note))
12025 ;; Set up for taking a record
12026 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12027 org-last-state
12028 'findpos org-log-repeat)))
12029 (org-back-to-heading t)
12030 (org-add-planning-info nil nil 'closed)
12031 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12032 org-deadline-time-regexp "\\)\\|\\("
12033 org-ts-regexp "\\)"))
12034 (while (re-search-forward
12035 re (save-excursion (outline-next-heading) (point)) t)
12036 (setq type (if (match-end 1) org-scheduled-string
12037 (if (match-end 3) org-deadline-string "Plain:"))
12038 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12039 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12040 (setq n (string-to-number (match-string 2 ts))
12041 what (match-string 3 ts))
12042 (if (equal what "w") (setq n (* n 7) what "d"))
12043 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12044 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12045 ;; Preparation, see if we need to modify the start date for the change
12046 (when (match-end 1)
12047 (setq time (save-match-data (org-time-string-to-time ts)))
12048 (cond
12049 ((equal (match-string 1 ts) ".")
12050 ;; Shift starting date to today
12051 (org-timestamp-change
12052 (- (org-today) (time-to-days time))
12053 'day))
12054 ((equal (match-string 1 ts) "+")
12055 (let ((nshiftmax 10) (nshift 0))
12056 (while (or (= nshift 0)
12057 (<= (time-to-days time)
12058 (time-to-days (current-time))))
12059 (when (= (incf nshift) nshiftmax)
12060 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12061 (error "Abort")))
12062 (org-timestamp-change n (cdr (assoc what whata)))
12063 (org-at-timestamp-p t)
12064 (setq ts (match-string 1))
12065 (setq time (save-match-data (org-time-string-to-time ts)))))
12066 (org-timestamp-change (- n) (cdr (assoc what whata)))
12067 ;; rematch, so that we have everything in place for the real shift
12068 (org-at-timestamp-p t)
12069 (setq ts (match-string 1))
12070 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12071 (org-timestamp-change n (cdr (assoc what whata)))
12072 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12073 (setq org-log-post-message msg)
12074 (message "%s" msg))))
12076 (defun org-show-todo-tree (arg)
12077 "Make a compact tree which shows all headlines marked with TODO.
12078 The tree will show the lines where the regexp matches, and all higher
12079 headlines above the match.
12080 With a \\[universal-argument] prefix, prompt for a regexp to match.
12081 With a numeric prefix N, construct a sparse tree for the Nth element
12082 of `org-todo-keywords-1'."
12083 (interactive "P")
12084 (let ((case-fold-search nil)
12085 (kwd-re
12086 (cond ((null arg) org-not-done-regexp)
12087 ((equal arg '(4))
12088 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12089 (mapcar 'list org-todo-keywords-1))))
12090 (concat "\\("
12091 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12092 "\\)\\>")))
12093 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12094 (regexp-quote (nth (1- (prefix-numeric-value arg))
12095 org-todo-keywords-1)))
12096 (t (error "Invalid prefix argument: %s" arg)))))
12097 (message "%d TODO entries found"
12098 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12100 (defun org-deadline (&optional remove time)
12101 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12102 With argument REMOVE, remove any deadline from the item.
12103 With argument TIME, set the deadline at the corresponding date. TIME
12104 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12105 (interactive "P")
12106 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12107 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12108 'region-start-level 'region))
12109 org-loop-over-headlines-in-active-region)
12110 (org-map-entries
12111 `(org-deadline ',remove ,time)
12112 org-loop-over-headlines-in-active-region
12113 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12114 (let* ((old-date (org-entry-get nil "DEADLINE"))
12115 (repeater (and old-date
12116 (string-match
12117 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12118 old-date)
12119 (match-string 1 old-date))))
12120 (if remove
12121 (progn
12122 (when (and old-date org-log-redeadline)
12123 (org-add-log-setup 'deldeadline nil old-date 'findpos
12124 org-log-redeadline))
12125 (org-remove-timestamp-with-keyword org-deadline-string)
12126 (message "Item no longer has a deadline."))
12127 (org-add-planning-info 'deadline time 'closed)
12128 (when (and old-date org-log-redeadline
12129 (not (equal old-date
12130 (substring org-last-inserted-timestamp 1 -1))))
12131 (org-add-log-setup 'redeadline nil old-date 'findpos
12132 org-log-redeadline))
12133 (when repeater
12134 (save-excursion
12135 (org-back-to-heading t)
12136 (when (re-search-forward (concat org-deadline-string " "
12137 org-last-inserted-timestamp)
12138 (save-excursion
12139 (outline-next-heading) (point)) t)
12140 (goto-char (1- (match-end 0)))
12141 (insert " " repeater)
12142 (setq org-last-inserted-timestamp
12143 (concat (substring org-last-inserted-timestamp 0 -1)
12144 " " repeater
12145 (substring org-last-inserted-timestamp -1))))))
12146 (message "Deadline on %s" org-last-inserted-timestamp)))))
12148 (defun org-schedule (&optional remove time)
12149 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12150 With argument REMOVE, remove any scheduling date from the item.
12151 With argument TIME, scheduled at the corresponding date. TIME can
12152 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12153 (interactive "P")
12154 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12155 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12156 'region-start-level 'region))
12157 org-loop-over-headlines-in-active-region)
12158 (org-map-entries
12159 `(org-schedule ',remove ,time)
12160 org-loop-over-headlines-in-active-region
12161 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12162 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12163 (repeater (and old-date
12164 (string-match
12165 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12166 old-date)
12167 (match-string 1 old-date))))
12168 (if remove
12169 (progn
12170 (when (and old-date org-log-reschedule)
12171 (org-add-log-setup 'delschedule nil old-date 'findpos
12172 org-log-reschedule))
12173 (org-remove-timestamp-with-keyword org-scheduled-string)
12174 (message "Item is no longer scheduled."))
12175 (org-add-planning-info 'scheduled time 'closed)
12176 (when (and old-date org-log-reschedule
12177 (not (equal old-date
12178 (substring org-last-inserted-timestamp 1 -1))))
12179 (org-add-log-setup 'reschedule nil old-date 'findpos
12180 org-log-reschedule))
12181 (when repeater
12182 (save-excursion
12183 (org-back-to-heading t)
12184 (when (re-search-forward (concat org-scheduled-string " "
12185 org-last-inserted-timestamp)
12186 (save-excursion
12187 (outline-next-heading) (point)) t)
12188 (goto-char (1- (match-end 0)))
12189 (insert " " repeater)
12190 (setq org-last-inserted-timestamp
12191 (concat (substring org-last-inserted-timestamp 0 -1)
12192 " " repeater
12193 (substring org-last-inserted-timestamp -1))))))
12194 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12196 (defun org-get-scheduled-time (pom &optional inherit)
12197 "Get the scheduled time as a time tuple, of a format suitable
12198 for calling org-schedule with, or if there is no scheduling,
12199 returns nil."
12200 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12201 (when time
12202 (apply 'encode-time (org-parse-time-string time)))))
12204 (defun org-get-deadline-time (pom &optional inherit)
12205 "Get the deadline as a time tuple, of a format suitable for
12206 calling org-deadline with, or if there is no scheduling, returns
12207 nil."
12208 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12209 (when time
12210 (apply 'encode-time (org-parse-time-string time)))))
12212 (defun org-remove-timestamp-with-keyword (keyword)
12213 "Remove all time stamps with KEYWORD in the current entry."
12214 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12215 beg)
12216 (save-excursion
12217 (org-back-to-heading t)
12218 (setq beg (point))
12219 (outline-next-heading)
12220 (while (re-search-backward re beg t)
12221 (replace-match "")
12222 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12223 (equal (char-before) ?\ ))
12224 (backward-delete-char 1)
12225 (if (string-match "^[ \t]*$" (buffer-substring
12226 (point-at-bol) (point-at-eol)))
12227 (delete-region (point-at-bol)
12228 (min (point-max) (1+ (point-at-eol))))))))))
12230 (defun org-add-planning-info (what &optional time &rest remove)
12231 "Insert new timestamp with keyword in the line directly after the headline.
12232 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12233 If non is given, the user is prompted for a date.
12234 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12235 be removed."
12236 (interactive)
12237 (let (org-time-was-given org-end-time-was-given ts
12238 end default-time default-input)
12240 (catch 'exit
12241 (when (and (memq what '(scheduled deadline))
12242 (or (not time)
12243 (and (stringp time)
12244 (string-match "^[-+]+[0-9]" time))))
12245 ;; Try to get a default date/time from existing timestamp
12246 (save-excursion
12247 (org-back-to-heading t)
12248 (setq end (save-excursion (outline-next-heading) (point)))
12249 (when (re-search-forward (if (eq what 'scheduled)
12250 org-scheduled-time-regexp
12251 org-deadline-time-regexp)
12252 end t)
12253 (setq ts (match-string 1)
12254 default-time
12255 (apply 'encode-time (org-parse-time-string ts))
12256 default-input (and ts (org-get-compact-tod ts))))))
12257 (when what
12258 (setq time
12259 (if (stringp time)
12260 ;; This is a string (relative or absolute), set proper date
12261 (apply 'encode-time
12262 (org-read-date-analyze
12263 time default-time (decode-time default-time)))
12264 ;; If necessary, get the time from the user
12265 (or time (org-read-date nil 'to-time nil nil
12266 default-time default-input)))))
12268 (when (and org-insert-labeled-timestamps-at-point
12269 (member what '(scheduled deadline)))
12270 (insert
12271 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12272 (org-insert-time-stamp time org-time-was-given
12273 nil nil nil (list org-end-time-was-given))
12274 (setq what nil))
12275 (save-excursion
12276 (save-restriction
12277 (let (col list elt ts buffer-invisibility-spec)
12278 (org-back-to-heading t)
12279 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12280 (goto-char (match-end 1))
12281 (setq col (current-column))
12282 (goto-char (match-end 0))
12283 (if (eobp) (insert "\n") (forward-char 1))
12284 (when (and (not what)
12285 (not (looking-at
12286 (concat "[ \t]*"
12287 org-keyword-time-not-clock-regexp))))
12288 ;; Nothing to add, nothing to remove...... :-)
12289 (throw 'exit nil))
12290 (if (and (not (looking-at org-outline-regexp))
12291 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12292 "[^\r\n]*"))
12293 (not (equal (match-string 1) org-clock-string)))
12294 (narrow-to-region (match-beginning 0) (match-end 0))
12295 (insert-before-markers "\n")
12296 (backward-char 1)
12297 (narrow-to-region (point) (point))
12298 (and org-adapt-indentation (org-indent-to-column col)))
12299 ;; Check if we have to remove something.
12300 (setq list (cons what remove))
12301 (while list
12302 (setq elt (pop list))
12303 (when (or (and (eq elt 'scheduled)
12304 (re-search-forward org-scheduled-time-regexp nil t))
12305 (and (eq elt 'deadline)
12306 (re-search-forward org-deadline-time-regexp nil t))
12307 (and (eq elt 'closed)
12308 (re-search-forward org-closed-time-regexp nil t)))
12309 (replace-match "")
12310 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12311 (and (looking-at "[ \t]+") (replace-match ""))
12312 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12313 (when what
12314 (insert
12315 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12316 (cond ((eq what 'scheduled) org-scheduled-string)
12317 ((eq what 'deadline) org-deadline-string)
12318 ((eq what 'closed) org-closed-string))
12319 " ")
12320 (setq ts (org-insert-time-stamp
12321 time
12322 (or org-time-was-given
12323 (and (eq what 'closed) org-log-done-with-time))
12324 (eq what 'closed)
12325 nil nil (list org-end-time-was-given)))
12326 (insert
12327 (if (not (or (bolp) (eq (char-before) ?\ )
12328 (memq (char-after) '(32 10))
12329 (eobp))) " " ""))
12330 (end-of-line 1))
12331 (goto-char (point-min))
12332 (widen)
12333 (if (and (looking-at "[ \t]*\n")
12334 (equal (char-before) ?\n))
12335 (delete-region (1- (point)) (point-at-eol)))
12336 ts))))))
12338 (defvar org-log-note-marker (make-marker))
12339 (defvar org-log-note-purpose nil)
12340 (defvar org-log-note-state nil)
12341 (defvar org-log-note-previous-state nil)
12342 (defvar org-log-note-how nil)
12343 (defvar org-log-note-extra nil)
12344 (defvar org-log-note-window-configuration nil)
12345 (defvar org-log-note-return-to (make-marker))
12346 (defvar org-log-note-effective-time nil
12347 "Remembered current time so that dynamically scoped
12348 `org-extend-today-until' affects tha timestamps in state change
12349 log")
12351 (defvar org-log-post-message nil
12352 "Message to be displayed after a log note has been stored.
12353 The auto-repeater uses this.")
12355 (defun org-add-note ()
12356 "Add a note to the current entry.
12357 This is done in the same way as adding a state change note."
12358 (interactive)
12359 (org-add-log-setup 'note nil nil 'findpos nil))
12361 (defvar org-property-end-re)
12362 (defun org-add-log-setup (&optional purpose state prev-state
12363 findpos how extra)
12364 "Set up the post command hook to take a note.
12365 If this is about to TODO state change, the new state is expected in STATE.
12366 When FINDPOS is non-nil, find the correct position for the note in
12367 the current entry. If not, assume that it can be inserted at point.
12368 HOW is an indicator what kind of note should be created.
12369 EXTRA is additional text that will be inserted into the notes buffer."
12370 (let* ((org-log-into-drawer (org-log-into-drawer))
12371 (drawer (cond ((stringp org-log-into-drawer)
12372 org-log-into-drawer)
12373 (org-log-into-drawer "LOGBOOK")
12374 (t nil))))
12375 (save-restriction
12376 (save-excursion
12377 (when findpos
12378 (org-back-to-heading t)
12379 (narrow-to-region (point) (save-excursion
12380 (outline-next-heading) (point)))
12381 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12382 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12383 "[^\r\n]*\\)?"))
12384 (goto-char (match-end 0))
12385 (cond
12386 (drawer
12387 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12388 nil t)
12389 (progn
12390 (goto-char (match-end 0))
12391 (or org-log-states-order-reversed
12392 (and (re-search-forward org-property-end-re nil t)
12393 (goto-char (1- (match-beginning 0))))))
12394 (insert "\n:" drawer ":\n:END:")
12395 (beginning-of-line 0)
12396 (org-indent-line-function)
12397 (beginning-of-line 2)
12398 (org-indent-line-function)
12399 (end-of-line 0)))
12400 ((and org-log-state-notes-insert-after-drawers
12401 (save-excursion
12402 (forward-line) (looking-at org-drawer-regexp)))
12403 (forward-line)
12404 (while (looking-at org-drawer-regexp)
12405 (goto-char (match-end 0))
12406 (re-search-forward org-property-end-re (point-max) t)
12407 (forward-line))
12408 (forward-line -1)))
12409 (unless org-log-states-order-reversed
12410 (and (= (char-after) ?\n) (forward-char 1))
12411 (org-skip-over-state-notes)
12412 (skip-chars-backward " \t\n\r")))
12413 (move-marker org-log-note-marker (point))
12414 (setq org-log-note-purpose purpose
12415 org-log-note-state state
12416 org-log-note-previous-state prev-state
12417 org-log-note-how how
12418 org-log-note-extra extra
12419 org-log-note-effective-time (org-current-effective-time))
12420 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12422 (defun org-skip-over-state-notes ()
12423 "Skip past the list of State notes in an entry."
12424 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12425 (when (ignore-errors (goto-char (org-in-item-p)))
12426 (let* ((struct (org-list-struct))
12427 (prevs (org-list-prevs-alist struct)))
12428 (while (looking-at "[ \t]*- State")
12429 (goto-char (or (org-list-get-next-item (point) struct prevs)
12430 (org-list-get-item-end (point) struct)))))))
12432 (defun org-add-log-note (&optional purpose)
12433 "Pop up a window for taking a note, and add this note later at point."
12434 (remove-hook 'post-command-hook 'org-add-log-note)
12435 (setq org-log-note-window-configuration (current-window-configuration))
12436 (delete-other-windows)
12437 (move-marker org-log-note-return-to (point))
12438 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12439 (goto-char org-log-note-marker)
12440 (org-switch-to-buffer-other-window "*Org Note*")
12441 (erase-buffer)
12442 (if (memq org-log-note-how '(time state))
12443 (let (current-prefix-arg) (org-store-log-note))
12444 (let ((org-inhibit-startup t)) (org-mode))
12445 (insert (format "# Insert note for %s.
12446 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12447 (cond
12448 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12449 ((eq org-log-note-purpose 'done) "closed todo item")
12450 ((eq org-log-note-purpose 'state)
12451 (format "state change from \"%s\" to \"%s\""
12452 (or org-log-note-previous-state "")
12453 (or org-log-note-state "")))
12454 ((eq org-log-note-purpose 'reschedule)
12455 "rescheduling")
12456 ((eq org-log-note-purpose 'delschedule)
12457 "no longer scheduled")
12458 ((eq org-log-note-purpose 'redeadline)
12459 "changing deadline")
12460 ((eq org-log-note-purpose 'deldeadline)
12461 "removing deadline")
12462 ((eq org-log-note-purpose 'refile)
12463 "refiling")
12464 ((eq org-log-note-purpose 'note)
12465 "this entry")
12466 (t (error "This should not happen")))))
12467 (if org-log-note-extra (insert org-log-note-extra))
12468 (org-set-local 'org-finish-function 'org-store-log-note)
12469 (run-hooks 'org-log-buffer-setup-hook)))
12471 (defvar org-note-abort nil) ; dynamically scoped
12472 (defun org-store-log-note ()
12473 "Finish taking a log note, and insert it to where it belongs."
12474 (let ((txt (buffer-string))
12475 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12476 lines ind bul)
12477 (kill-buffer (current-buffer))
12478 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12479 (setq txt (replace-match "" t t txt)))
12480 (if (string-match "\\s-+\\'" txt)
12481 (setq txt (replace-match "" t t txt)))
12482 (setq lines (org-split-string txt "\n"))
12483 (when (and note (string-match "\\S-" note))
12484 (setq note
12485 (org-replace-escapes
12486 note
12487 (list (cons "%u" (user-login-name))
12488 (cons "%U" user-full-name)
12489 (cons "%t" (format-time-string
12490 (org-time-stamp-format 'long 'inactive)
12491 org-log-note-effective-time))
12492 (cons "%T" (format-time-string
12493 (org-time-stamp-format 'long nil)
12494 org-log-note-effective-time))
12495 (cons "%d" (format-time-string
12496 (org-time-stamp-format nil 'inactive)
12497 org-log-note-effective-time))
12498 (cons "%D" (format-time-string
12499 (org-time-stamp-format nil nil)
12500 org-log-note-effective-time))
12501 (cons "%s" (if org-log-note-state
12502 (concat "\"" org-log-note-state "\"")
12503 ""))
12504 (cons "%S" (if org-log-note-previous-state
12505 (concat "\"" org-log-note-previous-state "\"")
12506 "\"\"")))))
12507 (if lines (setq note (concat note " \\\\")))
12508 (push note lines))
12509 (when (or current-prefix-arg org-note-abort)
12510 (when org-log-into-drawer
12511 (org-remove-empty-drawer-at
12512 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12513 org-log-note-marker))
12514 (setq lines nil))
12515 (when lines
12516 (with-current-buffer (marker-buffer org-log-note-marker)
12517 (save-excursion
12518 (goto-char org-log-note-marker)
12519 (move-marker org-log-note-marker nil)
12520 (end-of-line 1)
12521 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12522 (setq ind (save-excursion
12523 (if (ignore-errors (goto-char (org-in-item-p)))
12524 (let ((struct (org-list-struct)))
12525 (org-list-get-ind
12526 (org-list-get-top-point struct) struct))
12527 (skip-chars-backward " \r\t\n")
12528 (cond
12529 ((and (org-at-heading-p)
12530 org-adapt-indentation)
12531 (1+ (org-current-level)))
12532 ((org-at-heading-p) 0)
12533 (t (org-get-indentation))))))
12534 (setq bul (org-list-bullet-string "-"))
12535 (org-indent-line-to ind)
12536 (insert bul (pop lines))
12537 (let ((ind-body (+ (length bul) ind)))
12538 (while lines
12539 (insert "\n")
12540 (org-indent-line-to ind-body)
12541 (insert (pop lines))))
12542 (message "Note stored")
12543 (org-back-to-heading t)
12544 (org-cycle-hide-drawers 'children)))))
12545 (set-window-configuration org-log-note-window-configuration)
12546 (with-current-buffer (marker-buffer org-log-note-return-to)
12547 (goto-char org-log-note-return-to))
12548 (move-marker org-log-note-return-to nil)
12549 (and org-log-post-message (message "%s" org-log-post-message)))
12551 (defun org-remove-empty-drawer-at (drawer pos)
12552 "Remove an empty drawer DRAWER at position POS.
12553 POS may also be a marker."
12554 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12555 (save-excursion
12556 (save-restriction
12557 (widen)
12558 (goto-char pos)
12559 (if (org-in-regexp
12560 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12561 (replace-match ""))))))
12563 (defun org-sparse-tree (&optional arg)
12564 "Create a sparse tree, prompt for the details.
12565 This command can create sparse trees. You first need to select the type
12566 of match used to create the tree:
12568 t Show all TODO entries.
12569 T Show entries with a specific TODO keyword.
12570 m Show entries selected by a tags/property match.
12571 p Enter a property name and its value (both with completion on existing
12572 names/values) and show entries with that property.
12573 r Show entries matching a regular expression (`/' can be used as well)
12574 d Show deadlines due within `org-deadline-warning-days'.
12575 b Show deadlines and scheduled items before a date.
12576 a Show deadlines and scheduled items after a date."
12577 (interactive "P")
12578 (let (ans kwd value)
12579 (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")
12580 (setq ans (read-char-exclusive))
12581 (cond
12582 ((equal ans ?d)
12583 (call-interactively 'org-check-deadlines))
12584 ((equal ans ?b)
12585 (call-interactively 'org-check-before-date))
12586 ((equal ans ?a)
12587 (call-interactively 'org-check-after-date))
12588 ((equal ans ?D)
12589 (call-interactively 'org-check-dates-range))
12590 ((equal ans ?t)
12591 (org-show-todo-tree nil))
12592 ((equal ans ?T)
12593 (org-show-todo-tree '(4)))
12594 ((member ans '(?T ?m))
12595 (call-interactively 'org-match-sparse-tree))
12596 ((member ans '(?p ?P))
12597 (setq kwd (org-icompleting-read "Property: "
12598 (mapcar 'list (org-buffer-property-keys))))
12599 (setq value (org-icompleting-read "Value: "
12600 (mapcar 'list (org-property-values kwd))))
12601 (unless (string-match "\\`{.*}\\'" value)
12602 (setq value (concat "\"" value "\"")))
12603 (org-match-sparse-tree arg (concat kwd "=" value)))
12604 ((member ans '(?r ?R ?/))
12605 (call-interactively 'org-occur))
12606 (t (error "No such sparse tree command \"%c\"" ans)))))
12608 (defvar org-occur-highlights nil
12609 "List of overlays used for occur matches.")
12610 (make-variable-buffer-local 'org-occur-highlights)
12611 (defvar org-occur-parameters nil
12612 "Parameters of the active org-occur calls.
12613 This is a list, each call to org-occur pushes as cons cell,
12614 containing the regular expression and the callback, onto the list.
12615 The list can contain several entries if `org-occur' has been called
12616 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12617 will only contain one set of parameters. When the highlights are
12618 removed (for example with `C-c C-c', or with the next edit (depending
12619 on `org-remove-highlights-with-change'), this variable is emptied
12620 as well.")
12621 (make-variable-buffer-local 'org-occur-parameters)
12623 (defun org-occur (regexp &optional keep-previous callback)
12624 "Make a compact tree which shows all matches of REGEXP.
12625 The tree will show the lines where the regexp matches, and all higher
12626 headlines above the match. It will also show the heading after the match,
12627 to make sure editing the matching entry is easy.
12628 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12629 call to `org-occur' will be kept, to allow stacking of calls to this
12630 command.
12631 If CALLBACK is non-nil, it is a function which is called to confirm
12632 that the match should indeed be shown."
12633 (interactive "sRegexp: \nP")
12634 (when (equal regexp "")
12635 (error "Regexp cannot be empty"))
12636 (unless keep-previous
12637 (org-remove-occur-highlights nil nil t))
12638 (push (cons regexp callback) org-occur-parameters)
12639 (let ((cnt 0))
12640 (save-excursion
12641 (goto-char (point-min))
12642 (if (or (not keep-previous) ; do not want to keep
12643 (not org-occur-highlights)) ; no previous matches
12644 ;; hide everything
12645 (org-overview))
12646 (while (re-search-forward regexp nil t)
12647 (when (or (not callback)
12648 (save-match-data (funcall callback)))
12649 (setq cnt (1+ cnt))
12650 (when org-highlight-sparse-tree-matches
12651 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12652 (org-show-context 'occur-tree))))
12653 (when org-remove-highlights-with-change
12654 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12655 nil 'local))
12656 (unless org-sparse-tree-open-archived-trees
12657 (org-hide-archived-subtrees (point-min) (point-max)))
12658 (run-hooks 'org-occur-hook)
12659 (if (org-called-interactively-p 'interactive)
12660 (message "%d match(es) for regexp %s" cnt regexp))
12661 cnt))
12663 (defun org-occur-next-match (&optional n reset)
12664 "Function for `next-error-function' to find sparse tree matches.
12665 N is the number of matches to move, when negative move backwards.
12666 RESET is entirely ignored - this function always goes back to the
12667 starting point when no match is found."
12668 (let* ((limit (if (< n 0) (point-min) (point-max)))
12669 (search-func (if (< n 0)
12670 'previous-single-char-property-change
12671 'next-single-char-property-change))
12672 (n (abs n))
12673 (pos (point))
12675 (catch 'exit
12676 (while (setq p1 (funcall search-func (point) 'org-type))
12677 (when (equal p1 limit)
12678 (goto-char pos)
12679 (error "No more matches"))
12680 (when (equal (get-char-property p1 'org-type) 'org-occur)
12681 (setq n (1- n))
12682 (when (= n 0)
12683 (goto-char p1)
12684 (throw 'exit (point))))
12685 (goto-char p1))
12686 (goto-char p1)
12687 (error "No more matches"))))
12689 (defun org-show-context (&optional key)
12690 "Make sure point and context are visible.
12691 How much context is shown depends upon the variables
12692 `org-show-hierarchy-above', `org-show-following-heading',
12693 `org-show-entry-below' and `org-show-siblings'."
12694 (let ((heading-p (org-at-heading-p t))
12695 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12696 (following-p (org-get-alist-option org-show-following-heading key))
12697 (entry-p (org-get-alist-option org-show-entry-below key))
12698 (siblings-p (org-get-alist-option org-show-siblings key)))
12699 (catch 'exit
12700 ;; Show heading or entry text
12701 (if (and heading-p (not entry-p))
12702 (org-flag-heading nil) ; only show the heading
12703 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12704 (org-show-hidden-entry))) ; show entire entry
12705 (when following-p
12706 ;; Show next sibling, or heading below text
12707 (save-excursion
12708 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12709 (org-flag-heading nil))))
12710 (when siblings-p (org-show-siblings))
12711 (when hierarchy-p
12712 ;; show all higher headings, possibly with siblings
12713 (save-excursion
12714 (while (and (condition-case nil
12715 (progn (org-up-heading-all 1) t)
12716 (error nil))
12717 (not (bobp)))
12718 (org-flag-heading nil)
12719 (when siblings-p (org-show-siblings))))))))
12721 (defvar org-reveal-start-hook nil
12722 "Hook run before revealing a location.")
12724 (defun org-reveal (&optional siblings)
12725 "Show current entry, hierarchy above it, and the following headline.
12726 This can be used to show a consistent set of context around locations
12727 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12728 not t for the search context.
12730 With optional argument SIBLINGS, on each level of the hierarchy all
12731 siblings are shown. This repairs the tree structure to what it would
12732 look like when opened with hierarchical calls to `org-cycle'.
12733 With double optional argument \\[universal-argument] \\[universal-argument], \
12734 go to the parent and show the
12735 entire tree."
12736 (interactive "P")
12737 (run-hooks 'org-reveal-start-hook)
12738 (let ((org-show-hierarchy-above t)
12739 (org-show-following-heading t)
12740 (org-show-siblings (if siblings t org-show-siblings)))
12741 (org-show-context nil))
12742 (when (equal siblings '(16))
12743 (save-excursion
12744 (when (org-up-heading-safe)
12745 (org-show-subtree)
12746 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12748 (defun org-highlight-new-match (beg end)
12749 "Highlight from BEG to END and mark the highlight is an occur headline."
12750 (let ((ov (make-overlay beg end)))
12751 (overlay-put ov 'face 'secondary-selection)
12752 (overlay-put ov 'org-type 'org-occur)
12753 (push ov org-occur-highlights)))
12755 (defun org-remove-occur-highlights (&optional beg end noremove)
12756 "Remove the occur highlights from the buffer.
12757 BEG and END are ignored. If NOREMOVE is nil, remove this function
12758 from the `before-change-functions' in the current buffer."
12759 (interactive)
12760 (unless org-inhibit-highlight-removal
12761 (mapc 'delete-overlay org-occur-highlights)
12762 (setq org-occur-highlights nil)
12763 (setq org-occur-parameters nil)
12764 (unless noremove
12765 (remove-hook 'before-change-functions
12766 'org-remove-occur-highlights 'local))))
12768 ;;;; Priorities
12770 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12771 "Regular expression matching the priority indicator.")
12773 (defvar org-remove-priority-next-time nil)
12775 (defun org-priority-up ()
12776 "Increase the priority of the current item."
12777 (interactive)
12778 (org-priority 'up))
12780 (defun org-priority-down ()
12781 "Decrease the priority of the current item."
12782 (interactive)
12783 (org-priority 'down))
12785 (defun org-priority (&optional action)
12786 "Change the priority of an item by ARG.
12787 ACTION can be `set', `up', `down', or a character."
12788 (interactive)
12789 (unless org-enable-priority-commands
12790 (error "Priority commands are disabled"))
12791 (setq action (or action 'set))
12792 (let (current new news have remove)
12793 (save-excursion
12794 (org-back-to-heading t)
12795 (if (looking-at org-priority-regexp)
12796 (setq current (string-to-char (match-string 2))
12797 have t))
12798 (cond
12799 ((eq action 'remove)
12800 (setq remove t new ?\ ))
12801 ((or (eq action 'set)
12802 (if (featurep 'xemacs) (characterp action) (integerp action)))
12803 (if (not (eq action 'set))
12804 (setq new action)
12805 (message "Priority %c-%c, SPC to remove: "
12806 org-highest-priority org-lowest-priority)
12807 (save-match-data
12808 (setq new (read-char-exclusive))))
12809 (if (and (= (upcase org-highest-priority) org-highest-priority)
12810 (= (upcase org-lowest-priority) org-lowest-priority))
12811 (setq new (upcase new)))
12812 (cond ((equal new ?\ ) (setq remove t))
12813 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12814 (error "Priority must be between `%c' and `%c'"
12815 org-highest-priority org-lowest-priority))))
12816 ((eq action 'up)
12817 (setq new (if have
12818 (1- current) ; normal cycling
12819 ;; last priority was empty
12820 (if (eq last-command this-command)
12821 org-lowest-priority ; wrap around empty to lowest
12822 ;; default
12823 (if org-priority-start-cycle-with-default
12824 org-default-priority
12825 (1- org-default-priority))))))
12826 ((eq action 'down)
12827 (setq new (if have
12828 (1+ current) ; normal cycling
12829 ;; last priority was empty
12830 (if (eq last-command this-command)
12831 org-highest-priority ; wrap around empty to highest
12832 ;; default
12833 (if org-priority-start-cycle-with-default
12834 org-default-priority
12835 (1+ org-default-priority))))))
12836 (t (error "Invalid action")))
12837 (if (or (< (upcase new) org-highest-priority)
12838 (> (upcase new) org-lowest-priority))
12839 (if (and (memq action '(up down))
12840 (not have) (not (eq last-command this-command)))
12841 ;; `new' is from default priority
12842 (error
12843 "The default can not be set, see `org-default-priority' why")
12844 ;; normal cycling: `new' is beyond highest/lowest priority
12845 ;; and is wrapped around to the empty priority
12846 (setq remove t)))
12847 (setq news (format "%c" new))
12848 (if have
12849 (if remove
12850 (replace-match "" t t nil 1)
12851 (replace-match news t t nil 2))
12852 (if remove
12853 (error "No priority cookie found in line")
12854 (let ((case-fold-search nil))
12855 (looking-at org-todo-line-regexp))
12856 (if (match-end 2)
12857 (progn
12858 (goto-char (match-end 2))
12859 (insert " [#" news "]"))
12860 (goto-char (match-beginning 3))
12861 (insert "[#" news "] "))))
12862 (org-preserve-lc (org-set-tags nil 'align)))
12863 (if remove
12864 (message "Priority removed")
12865 (message "Priority of current item set to %s" news))))
12867 (defun org-get-priority (s)
12868 "Find priority cookie and return priority."
12869 (if (functionp org-get-priority-function)
12870 (funcall org-get-priority-function)
12871 (save-match-data
12872 (if (not (string-match org-priority-regexp s))
12873 (* 1000 (- org-lowest-priority org-default-priority))
12874 (* 1000 (- org-lowest-priority
12875 (string-to-char (match-string 2 s))))))))
12877 ;;;; Tags
12879 (defvar org-agenda-archives-mode)
12880 (defvar org-map-continue-from nil
12881 "Position from where mapping should continue.
12882 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12884 (defvar org-scanner-tags nil
12885 "The current tag list while the tags scanner is running.")
12886 (defvar org-trust-scanner-tags nil
12887 "Should `org-get-tags-at' use the tags for the scanner.
12888 This is for internal dynamical scoping only.
12889 When this is non-nil, the function `org-get-tags-at' will return the value
12890 of `org-scanner-tags' instead of building the list by itself. This
12891 can lead to large speed-ups when the tags scanner is used in a file with
12892 many entries, and when the list of tags is retrieved, for example to
12893 obtain a list of properties. Building the tags list for each entry in such
12894 a file becomes an N^2 operation - but with this variable set, it scales
12895 as N.")
12897 (defun org-scan-tags (action matcher todo-only &optional start-level)
12898 "Scan headline tags with inheritance and produce output ACTION.
12900 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12901 or `agenda' to produce an entry list for an agenda view. It can also be
12902 a Lisp form or a function that should be called at each matched headline, in
12903 this case the return value is a list of all return values from these calls.
12905 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12906 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12907 only lines with a not-done TODO keyword are included in the output.
12908 This should be the same variable that was scoped into
12909 and set by `org-make-tags-matcher' when it constructed MATCHER.
12911 START-LEVEL can be a string with asterisks, reducing the scope to
12912 headlines matching this string."
12913 (require 'org-agenda)
12914 (let* ((re (concat "^"
12915 (if start-level
12916 ;; Get the correct level to match
12917 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12918 org-outline-regexp)
12919 " *\\(\\<\\("
12920 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12921 (org-re
12922 (if todo-only
12923 "\\>\\)\\)[ \t]+\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"
12924 "\\>\\)\\)? *\\([^ ].*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))))
12925 (props (list 'face 'default
12926 'done-face 'org-agenda-done
12927 'undone-face 'default
12928 'mouse-face 'highlight
12929 'org-not-done-regexp org-not-done-regexp
12930 'org-todo-regexp org-todo-regexp
12931 'org-complex-heading-regexp org-complex-heading-regexp
12932 'help-echo
12933 (format "mouse-2 or RET jump to org file %s"
12934 (abbreviate-file-name
12935 (or (buffer-file-name (buffer-base-buffer))
12936 (buffer-name (buffer-base-buffer)))))))
12937 (case-fold-search nil)
12938 (org-map-continue-from nil)
12939 lspos tags tags-list
12940 (tags-alist (list (cons 0 org-file-tags)))
12941 (llast 0) rtn rtn1 level category i txt
12942 todo marker entry priority)
12943 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12944 (setq action (list 'lambda nil action)))
12945 (save-excursion
12946 (goto-char (point-min))
12947 (when (eq action 'sparse-tree)
12948 (org-overview)
12949 (org-remove-occur-highlights))
12950 (while (re-search-forward re nil t)
12951 (setq org-map-continue-from nil)
12952 (catch :skip
12953 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12954 tags (if (match-end 4) (org-match-string-no-properties 4)))
12955 (goto-char (setq lspos (match-beginning 0)))
12956 (setq level (org-reduced-level (funcall outline-level))
12957 category (org-get-category))
12958 (setq i llast llast level)
12959 ;; remove tag lists from same and sublevels
12960 (while (>= i level)
12961 (when (setq entry (assoc i tags-alist))
12962 (setq tags-alist (delete entry tags-alist)))
12963 (setq i (1- i)))
12964 ;; add the next tags
12965 (when tags
12966 (setq tags (org-split-string tags ":")
12967 tags-alist
12968 (cons (cons level tags) tags-alist)))
12969 ;; compile tags for current headline
12970 (setq tags-list
12971 (if org-use-tag-inheritance
12972 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12973 tags)
12974 org-scanner-tags tags-list)
12975 (when org-use-tag-inheritance
12976 (setcdr (car tags-alist)
12977 (mapcar (lambda (x)
12978 (setq x (copy-sequence x))
12979 (org-add-prop-inherited x))
12980 (cdar tags-alist))))
12981 (when (and tags org-use-tag-inheritance
12982 (or (not (eq t org-use-tag-inheritance))
12983 org-tags-exclude-from-inheritance))
12984 ;; selective inheritance, remove uninherited ones
12985 (setcdr (car tags-alist)
12986 (org-remove-uninherited-tags (cdar tags-alist))))
12987 (when (and
12989 ;; eval matcher only when the todo condition is OK
12990 (and (or (not todo-only) (member todo org-not-done-keywords))
12991 (let ((case-fold-search t) (org-trust-scanner-tags t))
12992 (eval matcher)))
12994 ;; Call the skipper, but return t if it does not skip,
12995 ;; so that the `and' form continues evaluating
12996 (progn
12997 (unless (eq action 'sparse-tree) (org-agenda-skip))
13000 ;; Check if timestamps are deselecting this entry
13001 (or (not todo-only)
13002 (and (member todo org-not-done-keywords)
13003 (or (not org-agenda-tags-todo-honor-ignore-options)
13004 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13006 ;; Extra check for the archive tag
13007 ;; FIXME: Does the skipper already do this????
13009 (not (member org-archive-tag tags-list))
13010 ;; we have an archive tag, should we use this anyway?
13011 (or (not org-agenda-skip-archived-trees)
13012 (and (eq action 'agenda) org-agenda-archives-mode))))
13014 ;; select this headline
13016 (cond
13017 ((eq action 'sparse-tree)
13018 (and org-highlight-sparse-tree-matches
13019 (org-get-heading) (match-end 0)
13020 (org-highlight-new-match
13021 (match-beginning 1) (match-end 1)))
13022 (org-show-context 'tags-tree))
13023 ((eq action 'agenda)
13024 (setq txt (org-agenda-format-item
13026 (concat
13027 (if (eq org-tags-match-list-sublevels 'indented)
13028 (make-string (1- level) ?.) "")
13029 (org-get-heading))
13030 category
13031 tags-list)
13032 priority (org-get-priority txt))
13033 (goto-char lspos)
13034 (setq marker (org-agenda-new-marker))
13035 (org-add-props txt props
13036 'org-marker marker 'org-hd-marker marker 'org-category category
13037 'todo-state todo
13038 'priority priority 'type "tagsmatch")
13039 (push txt rtn))
13040 ((functionp action)
13041 (setq org-map-continue-from nil)
13042 (save-excursion
13043 (setq rtn1 (funcall action))
13044 (push rtn1 rtn)))
13045 (t (error "Invalid action")))
13047 ;; if we are to skip sublevels, jump to end of subtree
13048 (unless org-tags-match-list-sublevels
13049 (org-end-of-subtree t)
13050 (backward-char 1))))
13051 ;; Get the correct position from where to continue
13052 (if org-map-continue-from
13053 (goto-char org-map-continue-from)
13054 (and (= (point) lspos) (end-of-line 1)))))
13055 (when (and (eq action 'sparse-tree)
13056 (not org-sparse-tree-open-archived-trees))
13057 (org-hide-archived-subtrees (point-min) (point-max)))
13058 (nreverse rtn)))
13060 (defun org-remove-uninherited-tags (tags)
13061 "Remove all tags that are not inherited from the list TAGS."
13062 (cond
13063 ((eq org-use-tag-inheritance t)
13064 (if org-tags-exclude-from-inheritance
13065 (org-delete-all org-tags-exclude-from-inheritance tags)
13066 tags))
13067 ((not org-use-tag-inheritance) nil)
13068 ((stringp org-use-tag-inheritance)
13069 (delq nil (mapcar
13070 (lambda (x)
13071 (if (and (string-match org-use-tag-inheritance x)
13072 (not (member x org-tags-exclude-from-inheritance)))
13073 x nil))
13074 tags)))
13075 ((listp org-use-tag-inheritance)
13076 (delq nil (mapcar
13077 (lambda (x)
13078 (if (member x org-use-tag-inheritance) x nil))
13079 tags)))))
13081 (defun org-match-sparse-tree (&optional todo-only match)
13082 "Create a sparse tree according to tags string MATCH.
13083 MATCH can contain positive and negative selection of tags, like
13084 \"+WORK+URGENT-WITHBOSS\".
13085 If optional argument TODO-ONLY is non-nil, only select lines that are
13086 also TODO lines."
13087 (interactive "P")
13088 (org-prepare-agenda-buffers (list (current-buffer)))
13089 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13091 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13093 (defvar org-cached-props nil)
13094 (defun org-cached-entry-get (pom property)
13095 (if (or (eq t org-use-property-inheritance)
13096 (and (stringp org-use-property-inheritance)
13097 (string-match org-use-property-inheritance property))
13098 (and (listp org-use-property-inheritance)
13099 (member property org-use-property-inheritance)))
13100 ;; Caching is not possible, check it directly
13101 (org-entry-get pom property 'inherit)
13102 ;; Get all properties, so that we can do complicated checks easily
13103 (cdr (assoc property (or org-cached-props
13104 (setq org-cached-props
13105 (org-entry-properties pom)))))))
13107 (defun org-global-tags-completion-table (&optional files)
13108 "Return the list of all tags in all agenda buffer/files.
13109 Optional FILES argument is a list of files to which can be used
13110 instead of the agenda files."
13111 (save-excursion
13112 (org-uniquify
13113 (delq nil
13114 (apply 'append
13115 (mapcar
13116 (lambda (file)
13117 (set-buffer (find-file-noselect file))
13118 (append (org-get-buffer-tags)
13119 (mapcar (lambda (x) (if (stringp (car-safe x))
13120 (list (car-safe x)) nil))
13121 org-tag-alist)))
13122 (if (and files (car files))
13123 files
13124 (org-agenda-files))))))))
13126 (defun org-make-tags-matcher (match)
13127 "Create the TAGS/TODO matcher form for the selection string MATCH.
13129 The variable `todo-only' is scoped dynamically into this function; it will be
13130 set to t if the matcher restricts matching to TODO entries,
13131 otherwise will not be touched.
13133 Returns a cons of the selection string MATCH and the constructed
13134 lisp form implementing the matcher. The matcher is to be
13135 evaluated at an Org entry, with point on the headline,
13136 and returns t if the entry matches the
13137 selection string MATCH. The returned lisp form references
13138 two variables with information about the entry, which must be
13139 bound around the form's evaluation: todo, the TODO keyword at the
13140 entry (or nil of none); and tags-list, the list of all tags at the
13141 entry including inherited ones. Additionally, the category
13142 of the entry (if any) must be specified as the text property
13143 'org-category on the headline.
13145 See also `org-scan-tags'.
13147 (declare (special todo-only))
13148 (unless (boundp 'todo-only)
13149 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13150 (unless match
13151 ;; Get a new match request, with completion
13152 (let ((org-last-tags-completion-table
13153 (org-global-tags-completion-table)))
13154 (setq match (org-completing-read-no-i
13155 "Match: " 'org-tags-completion-function nil nil nil
13156 'org-tags-history))))
13158 ;; Parse the string and create a lisp form
13159 (let ((match0 match)
13160 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13161 minus tag mm
13162 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13163 orterms term orlist re-p str-p level-p level-op time-p
13164 prop-p pn pv po gv rest)
13165 (if (string-match "/+" match)
13166 ;; match contains also a todo-matching request
13167 (progn
13168 (setq tagsmatch (substring match 0 (match-beginning 0))
13169 todomatch (substring match (match-end 0)))
13170 (if (string-match "^!" todomatch)
13171 (setq todo-only t todomatch (substring todomatch 1)))
13172 (if (string-match "^\\s-*$" todomatch)
13173 (setq todomatch nil)))
13174 ;; only matching tags
13175 (setq tagsmatch match todomatch nil))
13177 ;; Make the tags matcher
13178 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13179 (setq tagsmatcher t)
13180 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13181 (while (setq term (pop orterms))
13182 (while (and (equal (substring term -1) "\\") orterms)
13183 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13184 (while (string-match re term)
13185 (setq rest (substring term (match-end 0))
13186 minus (and (match-end 1)
13187 (equal (match-string 1 term) "-"))
13188 tag (save-match-data (replace-regexp-in-string
13189 "\\\\-" "-"
13190 (match-string 2 term)))
13191 re-p (equal (string-to-char tag) ?{)
13192 level-p (match-end 4)
13193 prop-p (match-end 5)
13194 mm (cond
13195 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13196 (level-p
13197 (setq level-op (org-op-to-function (match-string 3 term)))
13198 `(,level-op level ,(string-to-number
13199 (match-string 4 term))))
13200 (prop-p
13201 (setq pn (match-string 5 term)
13202 po (match-string 6 term)
13203 pv (match-string 7 term)
13204 re-p (equal (string-to-char pv) ?{)
13205 str-p (equal (string-to-char pv) ?\")
13206 time-p (save-match-data
13207 (string-match "^\"[[<].*[]>]\"$" pv))
13208 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13209 (if time-p (setq pv (org-matcher-time pv)))
13210 (setq po (org-op-to-function po (if time-p 'time str-p)))
13211 (cond
13212 ((equal pn "CATEGORY")
13213 (setq gv '(get-text-property (point) 'org-category)))
13214 ((equal pn "TODO")
13215 (setq gv 'todo))
13217 (setq gv `(org-cached-entry-get nil ,pn))))
13218 (if re-p
13219 (if (eq po 'org<>)
13220 `(not (string-match ,pv (or ,gv "")))
13221 `(string-match ,pv (or ,gv "")))
13222 (if str-p
13223 `(,po (or ,gv "") ,pv)
13224 `(,po (string-to-number (or ,gv ""))
13225 ,(string-to-number pv) ))))
13226 (t `(member ,tag tags-list)))
13227 mm (if minus (list 'not mm) mm)
13228 term rest)
13229 (push mm tagsmatcher))
13230 (push (if (> (length tagsmatcher) 1)
13231 (cons 'and tagsmatcher)
13232 (car tagsmatcher))
13233 orlist)
13234 (setq tagsmatcher nil))
13235 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13236 (setq tagsmatcher
13237 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13238 ;; Make the todo matcher
13239 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13240 (setq todomatcher t)
13241 (setq orterms (org-split-string todomatch "|") orlist nil)
13242 (while (setq term (pop orterms))
13243 (while (string-match re term)
13244 (setq minus (and (match-end 1)
13245 (equal (match-string 1 term) "-"))
13246 kwd (match-string 2 term)
13247 re-p (equal (string-to-char kwd) ?{)
13248 term (substring term (match-end 0))
13249 mm (if re-p
13250 `(string-match ,(substring kwd 1 -1) todo)
13251 (list 'equal 'todo kwd))
13252 mm (if minus (list 'not mm) mm))
13253 (push mm todomatcher))
13254 (push (if (> (length todomatcher) 1)
13255 (cons 'and todomatcher)
13256 (car todomatcher))
13257 orlist)
13258 (setq todomatcher nil))
13259 (setq todomatcher (if (> (length orlist) 1)
13260 (cons 'or orlist) (car orlist))))
13262 ;; Return the string and lisp forms of the matcher
13263 (setq matcher (if todomatcher
13264 (list 'and tagsmatcher todomatcher)
13265 tagsmatcher))
13266 (when todo-only
13267 (setq matcher (list 'and '(member todo org-not-done-keywords)
13268 matcher)))
13269 (cons match0 matcher)))
13271 (defun org-op-to-function (op &optional stringp)
13272 "Turn an operator into the appropriate function."
13273 (setq op
13274 (cond
13275 ((equal op "<" ) '(< string< org-time<))
13276 ((equal op ">" ) '(> org-string> org-time>))
13277 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13278 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13279 ((member op '("=" "==")) '(= string= org-time=))
13280 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13281 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13283 (defun org<> (a b) (not (= a b)))
13284 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13285 (defun org-string>= (a b) (not (string< a b)))
13286 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13287 (defun org-string<> (a b) (not (string= a b)))
13288 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13289 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13290 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13291 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> 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) (org<> a b)))
13294 (defun org-2ft (s)
13295 "Convert S to a floating point time.
13296 If S is already a number, just return it. If it is a string, parse
13297 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13298 (cond
13299 ((numberp s) s)
13300 ((stringp s)
13301 (condition-case nil
13302 (float-time (apply 'encode-time (org-parse-time-string s)))
13303 (error 0.)))
13304 (t 0.)))
13306 (defun org-time-today ()
13307 "Time in seconds today at 0:00.
13308 Returns the float number of seconds since the beginning of the
13309 epoch to the beginning of today (00:00)."
13310 (float-time (apply 'encode-time
13311 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13313 (defun org-matcher-time (s)
13314 "Interpret a time comparison value."
13315 (save-match-data
13316 (cond
13317 ((string= s "<now>") (float-time))
13318 ((string= s "<today>") (org-time-today))
13319 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13320 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13321 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13322 (+ (org-time-today)
13323 (* (string-to-number (match-string 1 s))
13324 (cdr (assoc (match-string 2 s)
13325 '(("d" . 86400.0) ("w" . 604800.0)
13326 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13327 (t (org-2ft s)))))
13329 (defun org-match-any-p (re list)
13330 "Does re match any element of list?"
13331 (setq list (mapcar (lambda (x) (string-match re x)) list))
13332 (delq nil list))
13334 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13335 (defvar org-tags-overlay (make-overlay 1 1))
13336 (org-detach-overlay org-tags-overlay)
13338 (defun org-get-local-tags-at (&optional pos)
13339 "Get a list of tags defined in the current headline."
13340 (org-get-tags-at pos 'local))
13342 (defun org-get-local-tags ()
13343 "Get a list of tags defined in the current headline."
13344 (org-get-tags-at nil 'local))
13346 (defun org-get-tags-at (&optional pos local)
13347 "Get a list of all headline tags applicable at POS.
13348 POS defaults to point. If tags are inherited, the list contains
13349 the targets in the same sequence as the headlines appear, i.e.
13350 the tags of the current headline come last.
13351 When LOCAL is non-nil, only return tags from the current headline,
13352 ignore inherited ones."
13353 (interactive)
13354 (if (and org-trust-scanner-tags
13355 (or (not pos) (equal pos (point)))
13356 (not local))
13357 org-scanner-tags
13358 (let (tags ltags lastpos parent)
13359 (save-excursion
13360 (save-restriction
13361 (widen)
13362 (goto-char (or pos (point)))
13363 (save-match-data
13364 (catch 'done
13365 (condition-case nil
13366 (progn
13367 (org-back-to-heading t)
13368 (while (not (equal lastpos (point)))
13369 (setq lastpos (point))
13370 (when (looking-at
13371 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13372 (setq ltags (org-split-string
13373 (org-match-string-no-properties 1) ":"))
13374 (when parent
13375 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13376 (setq tags (append
13377 (if parent
13378 (org-remove-uninherited-tags ltags)
13379 ltags)
13380 tags)))
13381 (or org-use-tag-inheritance (throw 'done t))
13382 (if local (throw 'done t))
13383 (or (org-up-heading-safe) (error nil))
13384 (setq parent t)))
13385 (error nil)))))
13386 (if local
13387 tags
13388 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13390 (defun org-add-prop-inherited (s)
13391 (add-text-properties 0 (length s) '(inherited t) s)
13394 (defun org-toggle-tag (tag &optional onoff)
13395 "Toggle the tag TAG for the current line.
13396 If ONOFF is `on' or `off', don't toggle but set to this state."
13397 (let (res current)
13398 (save-excursion
13399 (org-back-to-heading t)
13400 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13401 (point-at-eol) t)
13402 (progn
13403 (setq current (match-string 1))
13404 (replace-match ""))
13405 (setq current ""))
13406 (setq current (nreverse (org-split-string current ":")))
13407 (cond
13408 ((eq onoff 'on)
13409 (setq res t)
13410 (or (member tag current) (push tag current)))
13411 ((eq onoff 'off)
13412 (or (not (member tag current)) (setq current (delete tag current))))
13413 (t (if (member tag current)
13414 (setq current (delete tag current))
13415 (setq res t)
13416 (push tag current))))
13417 (end-of-line 1)
13418 (if current
13419 (progn
13420 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13421 (org-set-tags nil t))
13422 (delete-horizontal-space))
13423 (run-hooks 'org-after-tags-change-hook))
13424 res))
13426 (defun org-align-tags-here (to-col)
13427 ;; Assumes that this is a headline
13428 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13429 (beginning-of-line 1)
13430 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13431 (< pos (match-beginning 2)))
13432 (progn
13433 (setq tags-l (- (match-end 2) (match-beginning 2)))
13434 (goto-char (match-beginning 1))
13435 (insert " ")
13436 (delete-region (point) (1+ (match-beginning 2)))
13437 (setq ncol (max (current-column)
13438 (1+ col)
13439 (if (> to-col 0)
13440 to-col
13441 (- (abs to-col) tags-l))))
13442 (setq p (point))
13443 (insert (make-string (- ncol (current-column)) ?\ ))
13444 (setq ncol (current-column))
13445 (when indent-tabs-mode (tabify p (point-at-eol)))
13446 (org-move-to-column (min ncol col) t))
13447 (goto-char pos))))
13449 (defun org-set-tags-command (&optional arg just-align)
13450 "Call the set-tags command for the current entry."
13451 (interactive "P")
13452 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13453 (org-set-tags arg just-align)
13454 (save-excursion
13455 (org-back-to-heading t)
13456 (org-set-tags arg just-align))))
13458 (defun org-set-tags-to (data)
13459 "Set the tags of the current entry to DATA, replacing the current tags.
13460 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13461 If DATA is nil or the empty string, any tags will be removed."
13462 (interactive "sTags: ")
13463 (setq data
13464 (cond
13465 ((eq data nil) "")
13466 ((equal data "") "")
13467 ((stringp data)
13468 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13469 ":"))
13470 ((listp data)
13471 (concat ":" (mapconcat 'identity data ":") ":"))
13472 (t nil)))
13473 (when data
13474 (save-excursion
13475 (org-back-to-heading t)
13476 (when (looking-at org-complex-heading-regexp)
13477 (if (match-end 5)
13478 (progn
13479 (goto-char (match-beginning 5))
13480 (insert data)
13481 (delete-region (point) (point-at-eol))
13482 (org-set-tags nil 'align))
13483 (goto-char (point-at-eol))
13484 (insert " " data)
13485 (org-set-tags nil 'align)))
13486 (beginning-of-line 1)
13487 (if (looking-at ".*?\\([ \t]+\\)$")
13488 (delete-region (match-beginning 1) (match-end 1))))))
13490 (defun org-align-all-tags ()
13491 "Align the tags i all headings."
13492 (interactive)
13493 (save-excursion
13494 (or (ignore-errors (org-back-to-heading t))
13495 (outline-next-heading))
13496 (if (org-at-heading-p)
13497 (org-set-tags t)
13498 (message "No headings"))))
13500 (defvar org-indent-indentation-per-level)
13501 (defun org-set-tags (&optional arg just-align)
13502 "Set the tags for the current headline.
13503 With prefix ARG, realign all tags in headings in the current buffer."
13504 (interactive "P")
13505 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13506 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13507 'region-start-level 'region))
13508 org-loop-over-headlines-in-active-region)
13509 (org-map-entries
13510 ;; We don't use ARG and JUST-ALIGN here these args are not
13511 ;; useful when looping over headlines
13512 `(org-set-tags)
13513 org-loop-over-headlines-in-active-region
13514 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13515 (let* ((re org-outline-regexp-bol)
13516 (current (unless arg (org-get-tags-string)))
13517 (col (current-column))
13518 (org-setting-tags t)
13519 table current-tags inherited-tags ; computed below when needed
13520 tags p0 c0 c1 rpl di tc level)
13521 (if arg
13522 (save-excursion
13523 (goto-char (point-min))
13524 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13525 (while (re-search-forward re nil t)
13526 (org-set-tags nil t)
13527 (end-of-line 1)))
13528 (message "All tags realigned to column %d" org-tags-column))
13529 (if just-align
13530 (setq tags current)
13531 ;; Get a new set of tags from the user
13532 (save-excursion
13533 (setq table (append org-tag-persistent-alist
13534 (or org-tag-alist (org-get-buffer-tags))
13535 (and
13536 org-complete-tags-always-offer-all-agenda-tags
13537 (org-global-tags-completion-table
13538 (org-agenda-files))))
13539 org-last-tags-completion-table table
13540 current-tags (org-split-string current ":")
13541 inherited-tags (nreverse
13542 (nthcdr (length current-tags)
13543 (nreverse (org-get-tags-at))))
13544 tags
13545 (if (or (eq t org-use-fast-tag-selection)
13546 (and org-use-fast-tag-selection
13547 (delq nil (mapcar 'cdr table))))
13548 (org-fast-tag-selection
13549 current-tags inherited-tags table
13550 (if org-fast-tag-selection-include-todo
13551 org-todo-key-alist))
13552 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13553 (org-trim
13554 (org-icompleting-read "Tags: "
13555 'org-tags-completion-function
13556 nil nil current 'org-tags-history))))))
13557 (while (string-match "[-+&]+" tags)
13558 ;; No boolean logic, just a list
13559 (setq tags (replace-match ":" t t tags))))
13561 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13563 (if org-tags-sort-function
13564 (setq tags (mapconcat 'identity
13565 (sort (org-split-string
13566 tags (org-re "[^[:alnum:]_@#%]+"))
13567 org-tags-sort-function) ":")))
13569 (if (string-match "\\`[\t ]*\\'" tags)
13570 (setq tags "")
13571 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13572 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13574 ;; Insert new tags at the correct column
13575 (beginning-of-line 1)
13576 (setq level (or (and (looking-at org-outline-regexp)
13577 (- (match-end 0) (point) 1))
13579 (cond
13580 ((and (equal current "") (equal tags "")))
13581 ((re-search-forward
13582 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13583 (point-at-eol) t)
13584 (if (equal tags "")
13585 (setq rpl "")
13586 (goto-char (match-beginning 0))
13587 (setq c0 (current-column)
13588 ;; compute offset for the case of org-indent-mode active
13589 di (if org-indent-mode
13590 (* (1- org-indent-indentation-per-level) (1- level))
13592 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13593 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13594 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13595 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13596 (replace-match rpl t t)
13597 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13598 tags)
13599 (t (error "Tags alignment failed")))
13600 (org-move-to-column col)
13601 (unless just-align
13602 (run-hooks 'org-after-tags-change-hook))))))
13604 (defun org-change-tag-in-region (beg end tag off)
13605 "Add or remove TAG for each entry in the region.
13606 This works in the agenda, and also in an org-mode buffer."
13607 (interactive
13608 (list (region-beginning) (region-end)
13609 (let ((org-last-tags-completion-table
13610 (if (derived-mode-p 'org-mode)
13611 (org-get-buffer-tags)
13612 (org-global-tags-completion-table))))
13613 (org-icompleting-read
13614 "Tag: " 'org-tags-completion-function nil nil nil
13615 'org-tags-history))
13616 (progn
13617 (message "[s]et or [r]emove? ")
13618 (equal (read-char-exclusive) ?r))))
13619 (if (fboundp 'deactivate-mark) (deactivate-mark))
13620 (let ((agendap (equal major-mode 'org-agenda-mode))
13621 l1 l2 m buf pos newhead (cnt 0))
13622 (goto-char end)
13623 (setq l2 (1- (org-current-line)))
13624 (goto-char beg)
13625 (setq l1 (org-current-line))
13626 (loop for l from l1 to l2 do
13627 (org-goto-line l)
13628 (setq m (get-text-property (point) 'org-hd-marker))
13629 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13630 (and agendap m))
13631 (setq buf (if agendap (marker-buffer m) (current-buffer))
13632 pos (if agendap m (point)))
13633 (with-current-buffer buf
13634 (save-excursion
13635 (save-restriction
13636 (goto-char pos)
13637 (setq cnt (1+ cnt))
13638 (org-toggle-tag tag (if off 'off 'on))
13639 (setq newhead (org-get-heading)))))
13640 (and agendap (org-agenda-change-all-lines newhead m))))
13641 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13643 (defun org-tags-completion-function (string predicate &optional flag)
13644 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13645 (confirm (lambda (x) (stringp (car x)))))
13646 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13647 (setq s1 (match-string 1 string)
13648 s2 (match-string 2 string))
13649 (setq s1 "" s2 string))
13650 (cond
13651 ((eq flag nil)
13652 ;; try completion
13653 (setq rtn (try-completion s2 ctable confirm))
13654 (if (stringp rtn)
13655 (setq rtn
13656 (concat s1 s2 (substring rtn (length s2))
13657 (if (and org-add-colon-after-tag-completion
13658 (assoc rtn ctable))
13659 ":" ""))))
13660 rtn)
13661 ((eq flag t)
13662 ;; all-completions
13663 (all-completions s2 ctable confirm)
13665 ((eq flag 'lambda)
13666 ;; exact match?
13667 (assoc s2 ctable)))
13670 (defun org-fast-tag-insert (kwd tags face &optional end)
13671 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13672 (insert (format "%-12s" (concat kwd ":"))
13673 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13674 (or end "")))
13676 (defun org-fast-tag-show-exit (flag)
13677 (save-excursion
13678 (org-goto-line 3)
13679 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13680 (replace-match ""))
13681 (when flag
13682 (end-of-line 1)
13683 (org-move-to-column (- (window-width) 19) t)
13684 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13686 (defun org-set-current-tags-overlay (current prefix)
13687 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13688 (if (featurep 'xemacs)
13689 (org-overlay-display org-tags-overlay (concat prefix s)
13690 'secondary-selection)
13691 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13692 (org-overlay-display org-tags-overlay (concat prefix s)))))
13694 (defvar org-last-tag-selection-key nil)
13695 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13696 "Fast tag selection with single keys.
13697 CURRENT is the current list of tags in the headline, INHERITED is the
13698 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13699 possibly with grouping information. TODO-TABLE is a similar table with
13700 TODO keywords, should these have keys assigned to them.
13701 If the keys are nil, a-z are automatically assigned.
13702 Returns the new tags string, or nil to not change the current settings."
13703 (let* ((fulltable (append table todo-table))
13704 (maxlen (apply 'max (mapcar
13705 (lambda (x)
13706 (if (stringp (car x)) (string-width (car x)) 0))
13707 fulltable)))
13708 (buf (current-buffer))
13709 (expert (eq org-fast-tag-selection-single-key 'expert))
13710 (buffer-tags nil)
13711 (fwidth (+ maxlen 3 1 3))
13712 (ncol (/ (- (window-width) 4) fwidth))
13713 (i-face 'org-done)
13714 (c-face 'org-todo)
13715 tg cnt e c char c1 c2 ntable tbl rtn
13716 ov-start ov-end ov-prefix
13717 (exit-after-next org-fast-tag-selection-single-key)
13718 (done-keywords org-done-keywords)
13719 groups ingroup)
13720 (save-excursion
13721 (beginning-of-line 1)
13722 (if (looking-at
13723 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13724 (setq ov-start (match-beginning 1)
13725 ov-end (match-end 1)
13726 ov-prefix "")
13727 (setq ov-start (1- (point-at-eol))
13728 ov-end (1+ ov-start))
13729 (skip-chars-forward "^\n\r")
13730 (setq ov-prefix
13731 (concat
13732 (buffer-substring (1- (point)) (point))
13733 (if (> (current-column) org-tags-column)
13735 (make-string (- org-tags-column (current-column)) ?\ ))))))
13736 (move-overlay org-tags-overlay ov-start ov-end)
13737 (save-window-excursion
13738 (if expert
13739 (set-buffer (get-buffer-create " *Org tags*"))
13740 (delete-other-windows)
13741 (split-window-vertically)
13742 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13743 (erase-buffer)
13744 (org-set-local 'org-done-keywords done-keywords)
13745 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13746 (org-fast-tag-insert "Current" current c-face "\n\n")
13747 (org-fast-tag-show-exit exit-after-next)
13748 (org-set-current-tags-overlay current ov-prefix)
13749 (setq tbl fulltable char ?a cnt 0)
13750 (while (setq e (pop tbl))
13751 (cond
13752 ((equal (car e) :startgroup)
13753 (push '() groups) (setq ingroup t)
13754 (when (not (= cnt 0))
13755 (setq cnt 0)
13756 (insert "\n"))
13757 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13758 ((equal (car e) :endgroup)
13759 (setq ingroup nil cnt 0)
13760 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13761 ((equal e '(:newline))
13762 (when (not (= cnt 0))
13763 (setq cnt 0)
13764 (insert "\n")
13765 (setq e (car tbl))
13766 (while (equal (car tbl) '(:newline))
13767 (insert "\n")
13768 (setq tbl (cdr tbl)))))
13770 (setq tg (copy-sequence (car e)) c2 nil)
13771 (if (cdr e)
13772 (setq c (cdr e))
13773 ;; automatically assign a character.
13774 (setq c1 (string-to-char
13775 (downcase (substring
13776 tg (if (= (string-to-char tg) ?@) 1 0)))))
13777 (if (or (rassoc c1 ntable) (rassoc c1 table))
13778 (while (or (rassoc char ntable) (rassoc char table))
13779 (setq char (1+ char)))
13780 (setq c2 c1))
13781 (setq c (or c2 char)))
13782 (if ingroup (push tg (car groups)))
13783 (setq tg (org-add-props tg nil 'face
13784 (cond
13785 ((not (assoc tg table))
13786 (org-get-todo-face tg))
13787 ((member tg current) c-face)
13788 ((member tg inherited) i-face)
13789 (t nil))))
13790 (if (and (= cnt 0) (not ingroup)) (insert " "))
13791 (insert "[" c "] " tg (make-string
13792 (- fwidth 4 (length tg)) ?\ ))
13793 (push (cons tg c) ntable)
13794 (when (= (setq cnt (1+ cnt)) ncol)
13795 (insert "\n")
13796 (if ingroup (insert " "))
13797 (setq cnt 0)))))
13798 (setq ntable (nreverse ntable))
13799 (insert "\n")
13800 (goto-char (point-min))
13801 (if (not expert) (org-fit-window-to-buffer))
13802 (setq rtn
13803 (catch 'exit
13804 (while t
13805 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13806 (if (not groups) "no " "")
13807 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13808 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13809 (setq org-last-tag-selection-key c)
13810 (cond
13811 ((= c ?\r) (throw 'exit t))
13812 ((= c ?!)
13813 (setq groups (not groups))
13814 (goto-char (point-min))
13815 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13816 ((= c ?\C-c)
13817 (if (not expert)
13818 (org-fast-tag-show-exit
13819 (setq exit-after-next (not exit-after-next)))
13820 (setq expert nil)
13821 (delete-other-windows)
13822 (set-window-buffer (split-window-vertically) " *Org tags*")
13823 (org-switch-to-buffer-other-window " *Org tags*")
13824 (org-fit-window-to-buffer)))
13825 ((or (= c ?\C-g)
13826 (and (= c ?q) (not (rassoc c ntable))))
13827 (org-detach-overlay org-tags-overlay)
13828 (setq quit-flag t))
13829 ((= c ?\ )
13830 (setq current nil)
13831 (if exit-after-next (setq exit-after-next 'now)))
13832 ((= c ?\t)
13833 (condition-case nil
13834 (setq tg (org-icompleting-read
13835 "Tag: "
13836 (or buffer-tags
13837 (with-current-buffer buf
13838 (org-get-buffer-tags)))))
13839 (quit (setq tg "")))
13840 (when (string-match "\\S-" tg)
13841 (add-to-list 'buffer-tags (list tg))
13842 (if (member tg current)
13843 (setq current (delete tg current))
13844 (push tg current)))
13845 (if exit-after-next (setq exit-after-next 'now)))
13846 ((setq e (rassoc c todo-table) tg (car e))
13847 (with-current-buffer buf
13848 (save-excursion (org-todo tg)))
13849 (if exit-after-next (setq exit-after-next 'now)))
13850 ((setq e (rassoc c ntable) tg (car e))
13851 (if (member tg current)
13852 (setq current (delete tg current))
13853 (loop for g in groups do
13854 (if (member tg g)
13855 (mapc (lambda (x)
13856 (setq current (delete x current)))
13857 g)))
13858 (push tg current))
13859 (if exit-after-next (setq exit-after-next 'now))))
13861 ;; Create a sorted list
13862 (setq current
13863 (sort current
13864 (lambda (a b)
13865 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13866 (if (eq exit-after-next 'now) (throw 'exit t))
13867 (goto-char (point-min))
13868 (beginning-of-line 2)
13869 (delete-region (point) (point-at-eol))
13870 (org-fast-tag-insert "Current" current c-face)
13871 (org-set-current-tags-overlay current ov-prefix)
13872 (while (re-search-forward
13873 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13874 (setq tg (match-string 1))
13875 (add-text-properties
13876 (match-beginning 1) (match-end 1)
13877 (list 'face
13878 (cond
13879 ((member tg current) c-face)
13880 ((member tg inherited) i-face)
13881 (t (get-text-property (match-beginning 1) 'face))))))
13882 (goto-char (point-min)))))
13883 (org-detach-overlay org-tags-overlay)
13884 (if rtn
13885 (mapconcat 'identity current ":")
13886 nil))))
13888 (defun org-get-tags-string ()
13889 "Get the TAGS string in the current headline."
13890 (unless (org-at-heading-p t)
13891 (error "Not on a heading"))
13892 (save-excursion
13893 (beginning-of-line 1)
13894 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13895 (org-match-string-no-properties 1)
13896 "")))
13898 (defun org-get-tags ()
13899 "Get the list of tags specified in the current headline."
13900 (org-split-string (org-get-tags-string) ":"))
13902 (defun org-get-buffer-tags ()
13903 "Get a table of all tags used in the buffer, for completion."
13904 (let (tags)
13905 (save-excursion
13906 (goto-char (point-min))
13907 (while (re-search-forward
13908 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13909 (when (equal (char-after (point-at-bol 0)) ?*)
13910 (mapc (lambda (x) (add-to-list 'tags x))
13911 (org-split-string (org-match-string-no-properties 1) ":")))))
13912 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13913 (mapcar 'list tags)))
13915 ;;;; The mapping API
13917 ;;;###autoload
13918 (defun org-map-entries (func &optional match scope &rest skip)
13919 "Call FUNC at each headline selected by MATCH in SCOPE.
13921 FUNC is a function or a lisp form. The function will be called without
13922 arguments, with the cursor positioned at the beginning of the headline.
13923 The return values of all calls to the function will be collected and
13924 returned as a list.
13926 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13927 does not need to preserve point. After evaluation, the cursor will be
13928 moved to the end of the line (presumably of the headline of the
13929 processed entry) and search continues from there. Under some
13930 circumstances, this may not produce the wanted results. For example,
13931 if you have removed (e.g. archived) the current (sub)tree it could
13932 mean that the next entry will be skipped entirely. In such cases, you
13933 can specify the position from where search should continue by making
13934 FUNC set the variable `org-map-continue-from' to the desired buffer
13935 position.
13937 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13938 Only headlines that are matched by this query will be considered during
13939 the iteration. When MATCH is nil or t, all headlines will be
13940 visited by the iteration.
13942 SCOPE determines the scope of this command. It can be any of:
13944 nil The current buffer, respecting the restriction if any
13945 tree The subtree started with the entry at point
13946 region The entries within the active region, if any
13947 region-start-level
13948 The entries within the active region, but only those at
13949 the same level than the first one.
13950 file The current buffer, without restriction
13951 file-with-archives
13952 The current buffer, and any archives associated with it
13953 agenda All agenda files
13954 agenda-with-archives
13955 All agenda files with any archive files associated with them
13956 \(file1 file2 ...)
13957 If this is a list, all files in the list will be scanned
13959 The remaining args are treated as settings for the skipping facilities of
13960 the scanner. The following items can be given here:
13962 archive skip trees with the archive tag.
13963 comment skip trees with the COMMENT keyword
13964 function or Emacs Lisp form:
13965 will be used as value for `org-agenda-skip-function', so whenever
13966 the function returns t, FUNC will not be called for that
13967 entry and search will continue from the point where the
13968 function leaves it.
13970 If your function needs to retrieve the tags including inherited tags
13971 at the *current* entry, you can use the value of the variable
13972 `org-scanner-tags' which will be much faster than getting the value
13973 with `org-get-tags-at'. If your function gets properties with
13974 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13975 to t around the call to `org-entry-properties' to get the same speedup.
13976 Note that if your function moves around to retrieve tags and properties at
13977 a *different* entry, you cannot use these techniques."
13978 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13979 (not (org-region-active-p)))
13980 (let* ((org-agenda-archives-mode nil) ; just to make sure
13981 (org-agenda-skip-archived-trees (memq 'archive skip))
13982 (org-agenda-skip-comment-trees (memq 'comment skip))
13983 (org-agenda-skip-function
13984 (car (org-delete-all '(comment archive) skip)))
13985 (org-tags-match-list-sublevels t)
13986 (start-level (eq scope 'region-start-level))
13987 matcher file res
13988 org-todo-keywords-for-agenda
13989 org-done-keywords-for-agenda
13990 org-todo-keyword-alist-for-agenda
13991 org-drawers-for-agenda
13992 org-tag-alist-for-agenda
13993 todo-only)
13995 (cond
13996 ((eq match t) (setq matcher t))
13997 ((eq match nil) (setq matcher t))
13998 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14000 (save-excursion
14001 (save-restriction
14002 (cond ((eq scope 'tree)
14003 (org-back-to-heading t)
14004 (org-narrow-to-subtree)
14005 (setq scope nil))
14006 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14007 (org-region-active-p))
14008 ;; If needed, set start-level to a string like "2"
14009 (when start-level
14010 (save-excursion
14011 (goto-char (region-beginning))
14012 (unless (org-at-heading-p) (outline-next-heading))
14013 (setq start-level (org-current-level))))
14014 (narrow-to-region (region-beginning)
14015 (save-excursion
14016 (goto-char (region-end))
14017 (unless (and (bolp) (org-at-heading-p))
14018 (outline-next-heading))
14019 (point)))
14020 (setq scope nil)))
14022 (if (not scope)
14023 (progn
14024 (org-prepare-agenda-buffers
14025 (list (buffer-file-name (current-buffer))))
14026 (setq res (org-scan-tags func matcher todo-only start-level)))
14027 ;; Get the right scope
14028 (cond
14029 ((and scope (listp scope) (symbolp (car scope)))
14030 (setq scope (eval scope)))
14031 ((eq scope 'agenda)
14032 (setq scope (org-agenda-files t)))
14033 ((eq scope 'agenda-with-archives)
14034 (setq scope (org-agenda-files t))
14035 (setq scope (org-add-archive-files scope)))
14036 ((eq scope 'file)
14037 (setq scope (list (buffer-file-name))))
14038 ((eq scope 'file-with-archives)
14039 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14040 (org-prepare-agenda-buffers scope)
14041 (while (setq file (pop scope))
14042 (with-current-buffer (org-find-base-buffer-visiting file)
14043 (save-excursion
14044 (save-restriction
14045 (widen)
14046 (goto-char (point-min))
14047 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14048 res)))
14050 ;;;; Properties
14052 ;;; Setting and retrieving properties
14054 (defconst org-special-properties
14055 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14056 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
14057 "The special properties valid in Org-mode.
14059 These are properties that are not defined in the property drawer,
14060 but in some other way.")
14062 (defconst org-default-properties
14063 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14064 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14065 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14066 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14067 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14068 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14069 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14070 "Some properties that are used by Org-mode for various purposes.
14071 Being in this list makes sure that they are offered for completion.")
14073 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14074 "Regular expression matching the first line of a property drawer.")
14076 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14077 "Regular expression matching the last line of a property drawer.")
14079 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14080 "Regular expression matching the first line of a property drawer.")
14082 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14083 "Regular expression matching the first line of a property drawer.")
14085 (defconst org-property-drawer-re
14086 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14087 org-property-end-re "\\)\n?")
14088 "Matches an entire property drawer.")
14090 (defconst org-clock-drawer-re
14091 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14092 org-property-end-re "\\)\n?")
14093 "Matches an entire clock drawer.")
14095 (defsubst org-re-property (property)
14096 "Return a regexp matching PROPERTY.
14097 Match group 1 will be set to the value "
14098 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14100 (defun org-property-action ()
14101 "Do an action on properties."
14102 (interactive)
14103 (let (c)
14104 (org-at-property-p)
14105 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14106 (setq c (read-char-exclusive))
14107 (cond
14108 ((equal c ?s)
14109 (call-interactively 'org-set-property))
14110 ((equal c ?d)
14111 (call-interactively 'org-delete-property))
14112 ((equal c ?D)
14113 (call-interactively 'org-delete-property-globally))
14114 ((equal c ?c)
14115 (call-interactively 'org-compute-property-at-point))
14116 (t (error "No such property action %c" c)))))
14118 (defun org-set-effort (&optional value)
14119 "Set the effort property of the current entry.
14120 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14121 allowed value."
14122 (interactive "P")
14123 (if (equal value 0) (setq value 10))
14124 (let* ((completion-ignore-case t)
14125 (prop org-effort-property)
14126 (cur (org-entry-get nil prop))
14127 (allowed (org-property-get-allowed-values nil prop 'table))
14128 (existing (mapcar 'list (org-property-values prop)))
14130 (val (cond
14131 ((stringp value) value)
14132 ((and allowed (integerp value))
14133 (or (car (nth (1- value) allowed))
14134 (car (org-last allowed))))
14135 (allowed
14136 (message "Select 1-9,0, [RET%s]: %s"
14137 (if cur (concat "=" cur) "")
14138 (mapconcat 'car allowed " "))
14139 (setq rpl (read-char-exclusive))
14140 (if (equal rpl ?\r)
14142 (setq rpl (- rpl ?0))
14143 (if (equal rpl 0) (setq rpl 10))
14144 (if (and (> rpl 0) (<= rpl (length allowed)))
14145 (car (nth (1- rpl) allowed))
14146 (org-completing-read "Effort: " allowed nil))))
14148 (let (org-completion-use-ido org-completion-use-iswitchb)
14149 (org-completing-read
14150 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14151 (concat "[" cur "]") "")
14152 ": ")
14153 existing nil nil "" nil cur))))))
14154 (unless (equal (org-entry-get nil prop) val)
14155 (org-entry-put nil prop val))
14156 (message "%s is now %s" prop val)))
14158 (defun org-at-property-p ()
14159 "Is cursor inside a property drawer?"
14160 (save-excursion
14161 (beginning-of-line 1)
14162 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14163 (save-match-data ;; Used by calling procedures
14164 (let ((p (point))
14165 (range (unless (org-before-first-heading-p)
14166 (org-get-property-block))))
14167 (and range (<= (car range) p) (< p (cdr range))))))))
14169 (defun org-get-property-block (&optional beg end force)
14170 "Return the (beg . end) range of the body of the property drawer.
14171 BEG and END can be beginning and end of subtree, if not given
14172 they will be found.
14173 If the drawer does not exist and FORCE is non-nil, create the drawer."
14174 (catch 'exit
14175 (save-excursion
14176 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14177 (end (or end (progn (outline-next-heading) (point)))))
14178 (goto-char beg)
14179 (if (re-search-forward org-property-start-re end t)
14180 (setq beg (1+ (match-end 0)))
14181 (if force
14182 (save-excursion
14183 (org-insert-property-drawer)
14184 (setq end (progn (outline-next-heading) (point))))
14185 (throw 'exit nil))
14186 (goto-char beg)
14187 (if (re-search-forward org-property-start-re end t)
14188 (setq beg (1+ (match-end 0)))))
14189 (if (re-search-forward org-property-end-re end t)
14190 (setq end (match-beginning 0))
14191 (or force (throw 'exit nil))
14192 (goto-char beg)
14193 (setq end beg)
14194 (org-indent-line-function)
14195 (insert ":END:\n"))
14196 (cons beg end)))))
14198 (defun org-entry-properties (&optional pom which specific)
14199 "Get all properties of the entry at point-or-marker POM.
14200 This includes the TODO keyword, the tags, time strings for deadline,
14201 scheduled, and clocking, and any additional properties defined in the
14202 entry. The return value is an alist, keys may occur multiple times
14203 if the property key was used several times.
14204 POM may also be nil, in which case the current entry is used.
14205 If WHICH is nil or `all', get all properties. If WHICH is
14206 `special' or `standard', only get that subclass. If WHICH
14207 is a string only get exactly this property. SPECIFIC can be a string, the
14208 specific property we are interested in. Specifying it can speed
14209 things up because then unnecessary parsing is avoided."
14210 (setq which (or which 'all))
14211 (org-with-point-at pom
14212 (let ((clockstr (substring org-clock-string 0 -1))
14213 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14214 (case-fold-search nil)
14215 beg end range props sum-props key key1 value string clocksum)
14216 (save-excursion
14217 (when (condition-case nil
14218 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14219 (error nil))
14220 (setq beg (point))
14221 (setq sum-props (get-text-property (point) 'org-summaries))
14222 (setq clocksum (get-text-property (point) :org-clock-minutes))
14223 (outline-next-heading)
14224 (setq end (point))
14225 (when (memq which '(all special))
14226 ;; Get the special properties, like TODO and tags
14227 (goto-char beg)
14228 (when (and (or (not specific) (string= specific "TODO"))
14229 (looking-at org-todo-line-regexp) (match-end 2))
14230 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14231 (when (and (or (not specific) (string= specific "PRIORITY"))
14232 (looking-at org-priority-regexp))
14233 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14234 (when (or (not specific) (string= specific "FILE"))
14235 (push (cons "FILE" buffer-file-name) props))
14236 (when (and (or (not specific) (string= specific "TAGS"))
14237 (setq value (org-get-tags-string))
14238 (string-match "\\S-" value))
14239 (push (cons "TAGS" value) props))
14240 (when (and (or (not specific) (string= specific "ALLTAGS"))
14241 (setq value (org-get-tags-at)))
14242 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14243 ":"))
14244 props))
14245 (when (or (not specific) (string= specific "BLOCKED"))
14246 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14247 (when (or (not specific)
14248 (member specific
14249 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14250 "TIMESTAMP" "TIMESTAMP_IA")))
14251 (catch 'match
14252 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14253 (setq key (if (match-end 1)
14254 (substring (org-match-string-no-properties 1)
14255 0 -1))
14256 string (if (equal key clockstr)
14257 (org-no-properties
14258 (org-trim
14259 (buffer-substring
14260 (match-beginning 3) (goto-char
14261 (point-at-eol)))))
14262 (substring (org-match-string-no-properties 3)
14263 1 -1)))
14264 ;; Get the correct property name from the key. This is
14265 ;; necessary if the user has configured time keywords.
14266 (setq key1 (concat key ":"))
14267 (cond
14268 ((not key)
14269 (setq key
14270 (if (= (char-after (match-beginning 3)) ?\[)
14271 "TIMESTAMP_IA" "TIMESTAMP")))
14272 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14273 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14274 ((equal key1 org-closed-string) (setq key "CLOSED"))
14275 ((equal key1 org-clock-string) (setq key "CLOCK")))
14276 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14277 (progn
14278 (push (cons key string) props)
14279 ;; no need to search further if match is found
14280 (throw 'match t))
14281 (when (or (equal key "CLOCK") (not (assoc key props)))
14282 (push (cons key string) props))))))
14285 (when (memq which '(all standard))
14286 ;; Get the standard properties, like :PROP: ...
14287 (setq range (org-get-property-block beg end))
14288 (when range
14289 (goto-char (car range))
14290 (while (re-search-forward
14291 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14292 (cdr range) t)
14293 (setq key (org-match-string-no-properties 1)
14294 value (org-trim (or (org-match-string-no-properties 2) "")))
14295 (unless (member key excluded)
14296 (push (cons key (or value "")) props)))))
14297 (if clocksum
14298 (push (cons "CLOCKSUM"
14299 (org-columns-number-to-string (/ (float clocksum) 60.)
14300 'add_times))
14301 props))
14302 (unless (assoc "CATEGORY" props)
14303 (push (cons "CATEGORY" (org-get-category)) props))
14304 (append sum-props (nreverse props)))))))
14306 (defun org-entry-get (pom property &optional inherit literal-nil)
14307 "Get value of PROPERTY for entry at point-or-marker POM.
14308 If INHERIT is non-nil and the entry does not have the property,
14309 then also check higher levels of the hierarchy.
14310 If INHERIT is the symbol `selective', use inheritance only if the setting
14311 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14312 If the property is present but empty, the return value is the empty string.
14313 If the property is not present at all, nil is returned.
14315 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14316 do not interpret it as the list atom nil. This is used for inheritance
14317 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14318 (org-with-point-at pom
14319 (if (and inherit (if (eq inherit 'selective)
14320 (org-property-inherit-p property)
14322 (org-entry-get-with-inheritance property literal-nil)
14323 (if (member property org-special-properties)
14324 ;; We need a special property. Use `org-entry-properties' to
14325 ;; retrieve it, but specify the wanted property
14326 (cdr (assoc property (org-entry-properties nil 'special property)))
14327 (let ((range (unless (org-before-first-heading-p)
14328 (org-get-property-block)))
14329 (props (list (or (assoc property org-file-properties)
14330 (assoc property org-global-properties)
14331 (assoc property org-global-properties-fixed))))
14332 val)
14333 (flet ((ap (key)
14334 (when (re-search-forward
14335 (org-re-property key) (cdr range) t)
14336 (setq props
14337 (org-update-property-plist
14339 (if (match-end 1)
14340 (org-match-string-no-properties 1) "")
14341 props)))))
14342 (when (and range (goto-char (car range)))
14343 (ap property)
14344 (goto-char (car range))
14345 (while (ap (concat property "+")))
14346 (setq val (cdr (assoc property props)))
14347 (when val (if literal-nil val (org-not-nil val))))))))))
14349 (defun org-property-or-variable-value (var &optional inherit)
14350 "Check if there is a property fixing the value of VAR.
14351 If yes, return this value. If not, return the current value of the variable."
14352 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14353 (if (and prop (stringp prop) (string-match "\\S-" prop))
14354 (read prop)
14355 (symbol-value var))))
14357 (defun org-entry-delete (pom property)
14358 "Delete the property PROPERTY from entry at point-or-marker POM."
14359 (org-with-point-at pom
14360 (if (member property org-special-properties)
14361 nil ; cannot delete these properties.
14362 (let ((range (org-get-property-block)))
14363 (if (and range
14364 (goto-char (car range))
14365 (re-search-forward
14366 (org-re-property property)
14367 (cdr range) t))
14368 (progn
14369 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14371 nil)))))
14373 ;; Multi-values properties are properties that contain multiple values
14374 ;; These values are assumed to be single words, separated by whitespace.
14375 (defun org-entry-add-to-multivalued-property (pom property value)
14376 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14377 (let* ((old (org-entry-get pom property))
14378 (values (and old (org-split-string old "[ \t]"))))
14379 (setq value (org-entry-protect-space value))
14380 (unless (member value values)
14381 (setq values (cons value values))
14382 (org-entry-put pom property
14383 (mapconcat 'identity values " ")))))
14385 (defun org-entry-remove-from-multivalued-property (pom property value)
14386 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14387 (let* ((old (org-entry-get pom property))
14388 (values (and old (org-split-string old "[ \t]"))))
14389 (setq value (org-entry-protect-space value))
14390 (when (member value values)
14391 (setq values (delete value values))
14392 (org-entry-put pom property
14393 (mapconcat 'identity values " ")))))
14395 (defun org-entry-member-in-multivalued-property (pom property value)
14396 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14397 (let* ((old (org-entry-get pom property))
14398 (values (and old (org-split-string old "[ \t]"))))
14399 (setq value (org-entry-protect-space value))
14400 (member value values)))
14402 (defun org-entry-get-multivalued-property (pom property)
14403 "Return a list of values in a multivalued property."
14404 (let* ((value (org-entry-get pom property))
14405 (values (and value (org-split-string value "[ \t]"))))
14406 (mapcar 'org-entry-restore-space values)))
14408 (defun org-entry-put-multivalued-property (pom property &rest values)
14409 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14410 VALUES should be a list of strings. Spaces will be protected."
14411 (org-entry-put pom property
14412 (mapconcat 'org-entry-protect-space values " "))
14413 (let* ((value (org-entry-get pom property))
14414 (values (and value (org-split-string value "[ \t]"))))
14415 (mapcar 'org-entry-restore-space values)))
14417 (defun org-entry-protect-space (s)
14418 "Protect spaces and newline in string S."
14419 (while (string-match " " s)
14420 (setq s (replace-match "%20" t t s)))
14421 (while (string-match "\n" s)
14422 (setq s (replace-match "%0A" t t s)))
14425 (defun org-entry-restore-space (s)
14426 "Restore spaces and newline in string S."
14427 (while (string-match "%20" s)
14428 (setq s (replace-match " " t t s)))
14429 (while (string-match "%0A" s)
14430 (setq s (replace-match "\n" t t s)))
14433 (defvar org-entry-property-inherited-from (make-marker)
14434 "Marker pointing to the entry from where a property was inherited.
14435 Each call to `org-entry-get-with-inheritance' will set this marker to the
14436 location of the entry where the inheritance search matched. If there was
14437 no match, the marker will point nowhere.
14438 Note that also `org-entry-get' calls this function, if the INHERIT flag
14439 is set.")
14441 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14442 "Get entry property, and search higher levels if not present.
14443 The search will stop at the first ancestor which has the property defined.
14444 If the value found is \"nil\", return nil to show that the property
14445 should be considered as undefined (this is the meaning of nil here).
14446 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14447 (move-marker org-entry-property-inherited-from nil)
14448 (let (tmp)
14449 (unless (org-before-first-heading-p)
14450 (save-excursion
14451 (save-restriction
14452 (widen)
14453 (catch 'ex
14454 (while t
14455 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14456 (org-back-to-heading t)
14457 (move-marker org-entry-property-inherited-from (point))
14458 (throw 'ex tmp))
14459 (or (org-up-heading-safe) (throw 'ex nil)))))))
14460 (setq tmp (or tmp
14461 (cdr (assoc property org-file-properties))
14462 (cdr (assoc property org-global-properties))
14463 (cdr (assoc property org-global-properties-fixed))))
14464 (if literal-nil tmp (org-not-nil tmp))))
14466 (defvar org-property-changed-functions nil
14467 "Hook called when the value of a property has changed.
14468 Each hook function should accept two arguments, the name of the property
14469 and the new value.")
14471 (defun org-entry-put (pom property value)
14472 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14473 (org-with-point-at pom
14474 (org-back-to-heading t)
14475 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14476 range)
14477 (cond
14478 ((equal property "TODO")
14479 (when (and (stringp value) (string-match "\\S-" value)
14480 (not (member value org-todo-keywords-1)))
14481 (error "\"%s\" is not a valid TODO state" value))
14482 (if (or (not value)
14483 (not (string-match "\\S-" value)))
14484 (setq value 'none))
14485 (org-todo value)
14486 (org-set-tags nil 'align))
14487 ((equal property "PRIORITY")
14488 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14489 (string-to-char value) ?\ ))
14490 (org-set-tags nil 'align))
14491 ((equal property "SCHEDULED")
14492 (if (re-search-forward org-scheduled-time-regexp end t)
14493 (cond
14494 ((eq value 'earlier) (org-timestamp-change -1 'day))
14495 ((eq value 'later) (org-timestamp-change 1 'day))
14496 (t (call-interactively 'org-schedule)))
14497 (call-interactively 'org-schedule)))
14498 ((equal property "DEADLINE")
14499 (if (re-search-forward org-deadline-time-regexp end t)
14500 (cond
14501 ((eq value 'earlier) (org-timestamp-change -1 'day))
14502 ((eq value 'later) (org-timestamp-change 1 'day))
14503 (t (call-interactively 'org-deadline)))
14504 (call-interactively 'org-deadline)))
14505 ((member property org-special-properties)
14506 (error "The %s property can not yet be set with `org-entry-put'"
14507 property))
14508 (t ; a non-special property
14509 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14510 (setq range (org-get-property-block beg end 'force))
14511 (goto-char (car range))
14512 (if (re-search-forward
14513 (org-re-property property) (cdr range) t)
14514 (progn
14515 (delete-region (match-beginning 0) (match-end 0))
14516 (goto-char (match-beginning 0)))
14517 (goto-char (cdr range))
14518 (insert "\n")
14519 (backward-char 1)
14520 (org-indent-line-function))
14521 (insert ":" property ":")
14522 (and value (insert " " value))
14523 (org-indent-line-function)))))
14524 (run-hook-with-args 'org-property-changed-functions property value)))
14526 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14527 "Get all property keys in the current buffer.
14528 With INCLUDE-SPECIALS, also list the special properties that reflect things
14529 like tags and TODO state.
14530 With INCLUDE-DEFAULTS, also include properties that has special meaning
14531 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14532 and others.
14533 With INCLUDE-COLUMNS, also include property names given in COLUMN
14534 formats in the current buffer."
14535 (let (rtn range cfmt s p)
14536 (save-excursion
14537 (save-restriction
14538 (widen)
14539 (goto-char (point-min))
14540 (while (re-search-forward org-property-start-re nil t)
14541 (setq range (org-get-property-block))
14542 (goto-char (car range))
14543 (while (re-search-forward
14544 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14545 (cdr range) t)
14546 (add-to-list 'rtn (org-match-string-no-properties 1)))
14547 (outline-next-heading))))
14549 (when include-specials
14550 (setq rtn (append org-special-properties rtn)))
14552 (when include-defaults
14553 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14554 (add-to-list 'rtn org-effort-property))
14556 (when include-columns
14557 (save-excursion
14558 (save-restriction
14559 (widen)
14560 (goto-char (point-min))
14561 (while (re-search-forward
14562 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14563 nil t)
14564 (setq cfmt (match-string 2) s 0)
14565 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14566 cfmt s)
14567 (setq s (match-end 0)
14568 p (match-string 1 cfmt))
14569 (unless (or (equal p "ITEM")
14570 (member p org-special-properties))
14571 (add-to-list 'rtn (match-string 1 cfmt))))))))
14573 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14575 (defun org-property-values (key)
14576 "Return a list of all values of property KEY in the current buffer."
14577 (save-excursion
14578 (save-restriction
14579 (widen)
14580 (goto-char (point-min))
14581 (let ((re (org-re-property key))
14582 values)
14583 (while (re-search-forward re nil t)
14584 (add-to-list 'values (org-trim (match-string 1))))
14585 (delete "" values)))))
14587 (defun org-insert-property-drawer ()
14588 "Insert a property drawer into the current entry."
14589 (org-back-to-heading t)
14590 (looking-at org-outline-regexp)
14591 (let ((indent (if org-adapt-indentation
14592 (- (match-end 0) (match-beginning 0))
14594 (beg (point))
14595 (re (concat "^[ \t]*" org-keyword-time-regexp))
14596 end hiddenp)
14597 (outline-next-heading)
14598 (setq end (point))
14599 (goto-char beg)
14600 (while (re-search-forward re end t))
14601 (setq hiddenp (outline-invisible-p))
14602 (end-of-line 1)
14603 (and (equal (char-after) ?\n) (forward-char 1))
14604 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14605 (if (member (match-string 1) '("CLOCK:" ":END:"))
14606 ;; just skip this line
14607 (beginning-of-line 2)
14608 ;; Drawer start, find the end
14609 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14610 (beginning-of-line 1)))
14611 (org-skip-over-state-notes)
14612 (skip-chars-backward " \t\n\r")
14613 (if (eq (char-before) ?*) (forward-char 1))
14614 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14615 (beginning-of-line 0)
14616 (org-indent-to-column indent)
14617 (beginning-of-line 2)
14618 (org-indent-to-column indent)
14619 (beginning-of-line 0)
14620 (if hiddenp
14621 (save-excursion
14622 (org-back-to-heading t)
14623 (hide-entry))
14624 (org-flag-drawer t))))
14626 (defun org-insert-drawer (&optional arg drawer)
14627 "Insert a drawer at point.
14629 Optional argument DRAWER, when non-nil, is a string representing
14630 drawer's name. Otherwise, the user is prompted for a name.
14632 If a region is active, insert the drawer around that region
14633 instead.
14635 Point is left between drawer's boundaries."
14636 (interactive "P")
14637 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14638 "LOGBOOK"))
14639 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14640 ;; internally by Org. They are meant to be inserted
14641 ;; automatically.
14642 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14643 ;; Remove system drawers from list. Note: For some reason,
14644 ;; `org-completing-read' ignores the predicate while
14645 ;; `completing-read' handles it fine.
14646 (drawer (if arg "PROPERTIES"
14647 (or drawer
14648 (completing-read
14649 "Drawer: " org-drawers
14650 (lambda (d) (not (member d system-drawers))))))))
14651 (cond
14652 ;; With C-u, fall back on `org-insert-property-drawer'
14653 (arg (org-insert-property-drawer))
14654 ;; With an active region, insert a drawer at point.
14655 ((not (org-region-active-p))
14656 (progn
14657 (unless (bolp) (insert "\n"))
14658 (insert (format ":%s:\n\n:END:\n" drawer))
14659 (forward-line -2)))
14660 ;; Otherwise, insert the drawer at point
14662 (let ((rbeg (region-beginning))
14663 (rend (copy-marker (region-end))))
14664 (unwind-protect
14665 (progn
14666 (goto-char rbeg)
14667 (beginning-of-line)
14668 (when (save-excursion
14669 (re-search-forward org-outline-regexp-bol rend t))
14670 (error "Drawers cannot contain headlines"))
14671 ;; Position point at the beginning of the first
14672 ;; non-blank line in region. Insert drawer's opening
14673 ;; there, then indent it.
14674 (org-skip-whitespace)
14675 (beginning-of-line)
14676 (insert ":" drawer ":\n")
14677 (forward-line -1)
14678 (indent-for-tab-command)
14679 ;; Move point to the beginning of the first blank line
14680 ;; after the last non-blank line in region. Insert
14681 ;; drawer's closing, then indent it.
14682 (goto-char rend)
14683 (skip-chars-backward " \r\t\n")
14684 (insert "\n:END:")
14685 (indent-for-tab-command)
14686 (unless (eolp) (insert "\n")))
14687 ;; Clear marker, whatever the outcome of insertion is.
14688 (set-marker rend nil)))))))
14690 (defvar org-property-set-functions-alist nil
14691 "Property set function alist.
14692 Each entry should have the following format:
14694 (PROPERTY . READ-FUNCTION)
14696 The read function will be called with the same argument as
14697 `org-completing-read'.")
14699 (defun org-set-property-function (property)
14700 "Get the function that should be used to set PROPERTY.
14701 This is computed according to `org-property-set-functions-alist'."
14702 (or (cdr (assoc property org-property-set-functions-alist))
14703 'org-completing-read))
14705 (defun org-read-property-value (property)
14706 "Read PROPERTY value from user."
14707 (let* ((completion-ignore-case t)
14708 (allowed (org-property-get-allowed-values nil property 'table))
14709 (cur (org-entry-get nil property))
14710 (prompt (concat property " value"
14711 (if (and cur (string-match "\\S-" cur))
14712 (concat " [" cur "]") "") ": "))
14713 (set-function (org-set-property-function property))
14714 (val (if allowed
14715 (funcall set-function prompt allowed nil
14716 (not (get-text-property 0 'org-unrestricted
14717 (caar allowed))))
14718 (let (org-completion-use-ido org-completion-use-iswitchb)
14719 (funcall set-function prompt
14720 (mapcar 'list (org-property-values property))
14721 nil nil "" nil cur)))))
14722 (if (equal val "")
14724 val)))
14726 (defvar org-last-set-property nil)
14727 (defun org-read-property-name ()
14728 "Read a property name."
14729 (let* ((completion-ignore-case t)
14730 (keys (org-buffer-property-keys nil t t))
14731 (default-prop (or (save-excursion
14732 (save-match-data
14733 (beginning-of-line)
14734 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14735 (null (string= (match-string 1) "END"))
14736 (match-string 1))))
14737 org-last-set-property))
14738 (property (org-icompleting-read
14739 (concat "Property"
14740 (if default-prop (concat " [" default-prop "]") "")
14741 ": ")
14742 (mapcar 'list keys)
14743 nil nil nil nil
14744 default-prop
14746 (if (member property keys)
14747 property
14748 (or (cdr (assoc (downcase property)
14749 (mapcar (lambda (x) (cons (downcase x) x))
14750 keys)))
14751 property))))
14753 (defun org-set-property (property value)
14754 "In the current entry, set PROPERTY to VALUE.
14755 When called interactively, this will prompt for a property name, offering
14756 completion on existing and default properties. And then it will prompt
14757 for a value, offering completion either on allowed values (via an inherited
14758 xxx_ALL property) or on existing values in other instances of this property
14759 in the current file."
14760 (interactive (list nil nil))
14761 (let* ((property (or property (org-read-property-name)))
14762 (value (or value (org-read-property-value property)))
14763 (fn (cdr (assoc property org-properties-postprocess-alist))))
14764 (setq org-last-set-property property)
14765 ;; Possibly postprocess the inserted value:
14766 (when fn (setq value (funcall fn value)))
14767 (unless (equal (org-entry-get nil property) value)
14768 (org-entry-put nil property value))))
14770 (defun org-delete-property (property)
14771 "In the current entry, delete PROPERTY."
14772 (interactive
14773 (let* ((completion-ignore-case t)
14774 (prop (org-icompleting-read "Property: "
14775 (org-entry-properties nil 'standard))))
14776 (list prop)))
14777 (message "Property %s %s" property
14778 (if (org-entry-delete nil property)
14779 "deleted"
14780 "was not present in the entry")))
14782 (defun org-delete-property-globally (property)
14783 "Remove PROPERTY globally, from all entries."
14784 (interactive
14785 (let* ((completion-ignore-case t)
14786 (prop (org-icompleting-read
14787 "Globally remove property: "
14788 (mapcar 'list (org-buffer-property-keys)))))
14789 (list prop)))
14790 (save-excursion
14791 (save-restriction
14792 (widen)
14793 (goto-char (point-min))
14794 (let ((cnt 0))
14795 (while (re-search-forward
14796 (org-re-property property)
14797 nil t)
14798 (setq cnt (1+ cnt))
14799 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14800 (message "Property \"%s\" removed from %d entries" property cnt)))))
14802 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14804 (defun org-compute-property-at-point ()
14805 "Compute the property at point.
14806 This looks for an enclosing column format, extracts the operator and
14807 then applies it to the property in the column format's scope."
14808 (interactive)
14809 (unless (org-at-property-p)
14810 (error "Not at a property"))
14811 (let ((prop (org-match-string-no-properties 2)))
14812 (org-columns-get-format-and-top-level)
14813 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14814 (error "No operator defined for property %s" prop))
14815 (org-columns-compute prop)))
14817 (defvar org-property-allowed-value-functions nil
14818 "Hook for functions supplying allowed values for a specific property.
14819 The functions must take a single argument, the name of the property, and
14820 return a flat list of allowed values. If \":ETC\" is one of
14821 the values, this means that these values are intended as defaults for
14822 completion, but that other values should be allowed too.
14823 The functions must return nil if they are not responsible for this
14824 property.")
14826 (defun org-property-get-allowed-values (pom property &optional table)
14827 "Get allowed values for the property PROPERTY.
14828 When TABLE is non-nil, return an alist that can directly be used for
14829 completion."
14830 (let (vals)
14831 (cond
14832 ((equal property "TODO")
14833 (setq vals (org-with-point-at pom
14834 (append org-todo-keywords-1 '("")))))
14835 ((equal property "PRIORITY")
14836 (let ((n org-lowest-priority))
14837 (while (>= n org-highest-priority)
14838 (push (char-to-string n) vals)
14839 (setq n (1- n)))))
14840 ((member property org-special-properties))
14841 ((setq vals (run-hook-with-args-until-success
14842 'org-property-allowed-value-functions property)))
14844 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14845 (when (and vals (string-match "\\S-" vals))
14846 (setq vals (car (read-from-string (concat "(" vals ")"))))
14847 (setq vals (mapcar (lambda (x)
14848 (cond ((stringp x) x)
14849 ((numberp x) (number-to-string x))
14850 ((symbolp x) (symbol-name x))
14851 (t "???")))
14852 vals)))))
14853 (when (member ":ETC" vals)
14854 (setq vals (remove ":ETC" vals))
14855 (org-add-props (car vals) '(org-unrestricted t)))
14856 (if table (mapcar 'list vals) vals)))
14858 (defun org-property-previous-allowed-value (&optional previous)
14859 "Switch to the next allowed value for this property."
14860 (interactive)
14861 (org-property-next-allowed-value t))
14863 (defun org-property-next-allowed-value (&optional previous)
14864 "Switch to the next allowed value for this property."
14865 (interactive)
14866 (unless (org-at-property-p)
14867 (error "Not at a property"))
14868 (let* ((key (match-string 2))
14869 (value (match-string 3))
14870 (allowed (or (org-property-get-allowed-values (point) key)
14871 (and (member value '("[ ]" "[-]" "[X]"))
14872 '("[ ]" "[X]"))))
14873 nval)
14874 (unless allowed
14875 (error "Allowed values for this property have not been defined"))
14876 (if previous (setq allowed (reverse allowed)))
14877 (if (member value allowed)
14878 (setq nval (car (cdr (member value allowed)))))
14879 (setq nval (or nval (car allowed)))
14880 (if (equal nval value)
14881 (error "Only one allowed value for this property"))
14882 (org-at-property-p)
14883 (replace-match (concat " :" key ": " nval) t t)
14884 (org-indent-line-function)
14885 (beginning-of-line 1)
14886 (skip-chars-forward " \t")
14887 (run-hook-with-args 'org-property-changed-functions key nval)))
14889 (defun org-find-olp (path &optional this-buffer)
14890 "Return a marker pointing to the entry at outline path OLP.
14891 If anything goes wrong, throw an error.
14892 You can wrap this call to catch the error like this:
14894 (condition-case msg
14895 (org-mobile-locate-entry (match-string 4))
14896 (error (nth 1 msg)))
14898 The return value will then be either a string with the error message,
14899 or a marker if everything is OK.
14901 If THIS-BUFFER is set, the outline path does not contain a file,
14902 only headings."
14903 (let* ((file (if this-buffer buffer-file-name (pop path)))
14904 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14905 (level 1)
14906 (lmin 1)
14907 (lmax 1)
14908 limit re end found pos heading cnt flevel)
14909 (unless buffer (error "File not found :%s" file))
14910 (with-current-buffer buffer
14911 (save-excursion
14912 (save-restriction
14913 (widen)
14914 (setq limit (point-max))
14915 (goto-char (point-min))
14916 (while (setq heading (pop path))
14917 (setq re (format org-complex-heading-regexp-format
14918 (regexp-quote heading)))
14919 (setq cnt 0 pos (point))
14920 (while (re-search-forward re end t)
14921 (setq level (- (match-end 1) (match-beginning 1)))
14922 (if (and (>= level lmin) (<= level lmax))
14923 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14924 (when (= cnt 0) (error "Heading not found on level %d: %s"
14925 lmax heading))
14926 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14927 lmax heading))
14928 (goto-char found)
14929 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14930 (setq end (save-excursion (org-end-of-subtree t t))))
14931 (when (org-at-heading-p)
14932 (move-marker (make-marker) (point))))))))
14934 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14935 "Find node HEADING in BUFFER.
14936 Return a marker to the heading if it was found, or nil if not.
14937 If POS-ONLY is set, return just the position instead of a marker.
14939 The heading text must match exact, but it may have a TODO keyword,
14940 a priority cookie and tags in the standard locations."
14941 (with-current-buffer (or buffer (current-buffer))
14942 (save-excursion
14943 (save-restriction
14944 (widen)
14945 (goto-char (point-min))
14946 (let (case-fold-search)
14947 (if (re-search-forward
14948 (format org-complex-heading-regexp-format
14949 (regexp-quote heading)) nil t)
14950 (if pos-only
14951 (match-beginning 0)
14952 (move-marker (make-marker) (match-beginning 0)))))))))
14954 (defun org-find-exact-heading-in-directory (heading &optional dir)
14955 "Find Org node headline HEADING in all .org files in directory DIR.
14956 When the target headline is found, return a marker to this location."
14957 (let ((files (directory-files (or dir default-directory)
14958 nil "\\`[^.#].*\\.org\\'"))
14959 file visiting m buffer)
14960 (catch 'found
14961 (while (setq file (pop files))
14962 (message "trying %s" file)
14963 (setq visiting (org-find-base-buffer-visiting file))
14964 (setq buffer (or visiting (find-file-noselect file)))
14965 (setq m (org-find-exact-headline-in-buffer
14966 heading buffer))
14967 (when (and (not m) (not visiting)) (kill-buffer buffer))
14968 (and m (throw 'found m))))))
14970 (defun org-find-entry-with-id (ident)
14971 "Locate the entry that contains the ID property with exact value IDENT.
14972 IDENT can be a string, a symbol or a number, this function will search for
14973 the string representation of it.
14974 Return the position where this entry starts, or nil if there is no such entry."
14975 (interactive "sID: ")
14976 (let ((id (cond
14977 ((stringp ident) ident)
14978 ((symbol-name ident) (symbol-name ident))
14979 ((numberp ident) (number-to-string ident))
14980 (t (error "IDENT %s must be a string, symbol or number" ident))))
14981 (case-fold-search nil))
14982 (save-excursion
14983 (save-restriction
14984 (widen)
14985 (goto-char (point-min))
14986 (when (re-search-forward
14987 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14988 nil t)
14989 (org-back-to-heading t)
14990 (point))))))
14992 ;;;; Timestamps
14994 (defvar org-last-changed-timestamp nil)
14995 (defvar org-last-inserted-timestamp nil
14996 "The last time stamp inserted with `org-insert-time-stamp'.")
14997 (defvar org-time-was-given) ; dynamically scoped parameter
14998 (defvar org-end-time-was-given) ; dynamically scoped parameter
14999 (defvar org-ts-what) ; dynamically scoped parameter
15001 (defun org-time-stamp (arg &optional inactive)
15002 "Prompt for a date/time and insert a time stamp.
15003 If the user specifies a time like HH:MM, or if this command is called
15004 with a prefix argument, the time stamp will contain date and time.
15005 Otherwise, only the date will be included. All parts of a date not
15006 specified by the user will be filled in from the current date/time.
15007 So if you press just return without typing anything, the time stamp
15008 will represent the current date/time. If there is already a timestamp
15009 at the cursor, it will be modified."
15010 (interactive "P")
15011 (let* ((ts nil)
15012 (default-time
15013 ;; Default time is either today, or, when entering a range,
15014 ;; the range start.
15015 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15016 (save-excursion
15017 (re-search-backward
15018 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15019 (- (point) 20) t)))
15020 (apply 'encode-time (org-parse-time-string (match-string 1)))
15021 (current-time)))
15022 (default-input (and ts (org-get-compact-tod ts)))
15023 (repeater (save-excursion
15024 (save-match-data
15025 (beginning-of-line)
15026 (when (re-search-forward
15027 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15028 (save-excursion (progn (end-of-line) (point))) t)
15029 (match-string 0)))))
15030 org-time-was-given org-end-time-was-given time)
15031 (cond
15032 ((and (org-at-timestamp-p t)
15033 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15034 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15035 (insert "--")
15036 (setq time (let ((this-command this-command))
15037 (org-read-date arg 'totime nil nil
15038 default-time default-input inactive)))
15039 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15040 ((org-at-timestamp-p t)
15041 (setq time (let ((this-command this-command))
15042 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15043 (when (org-at-timestamp-p t) ; just to get the match data
15044 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15045 (replace-match "")
15046 (setq org-last-changed-timestamp
15047 (org-insert-time-stamp
15048 time (or org-time-was-given arg)
15049 inactive nil nil (list org-end-time-was-given)))
15050 (when repeater (goto-char (1- (point))) (insert " " repeater)
15051 (setq org-last-changed-timestamp
15052 (concat (substring org-last-inserted-timestamp 0 -1)
15053 " " repeater ">"))))
15054 (message "Timestamp updated"))
15056 (setq time (let ((this-command this-command))
15057 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15058 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15059 nil nil (list org-end-time-was-given))))))
15061 ;; FIXME: can we use this for something else, like computing time differences?
15062 (defun org-get-compact-tod (s)
15063 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15064 (let* ((t1 (match-string 1 s))
15065 (h1 (string-to-number (match-string 2 s)))
15066 (m1 (string-to-number (match-string 3 s)))
15067 (t2 (and (match-end 4) (match-string 5 s)))
15068 (h2 (and t2 (string-to-number (match-string 6 s))))
15069 (m2 (and t2 (string-to-number (match-string 7 s))))
15070 dh dm)
15071 (if (not t2)
15073 (setq dh (- h2 h1) dm (- m2 m1))
15074 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15075 (concat t1 "+" (number-to-string dh)
15076 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15078 (defun org-time-stamp-inactive (&optional arg)
15079 "Insert an inactive time stamp.
15080 An inactive time stamp is enclosed in square brackets instead of angle
15081 brackets. It is inactive in the sense that it does not trigger agenda entries,
15082 does not link to the calendar and cannot be changed with the S-cursor keys.
15083 So these are more for recording a certain time/date."
15084 (interactive "P")
15085 (org-time-stamp arg 'inactive))
15087 (defvar org-date-ovl (make-overlay 1 1))
15088 (overlay-put org-date-ovl 'face 'org-date-selected)
15089 (org-detach-overlay org-date-ovl)
15091 (defvar org-ans1) ; dynamically scoped parameter
15092 (defvar org-ans2) ; dynamically scoped parameter
15094 (defvar org-plain-time-of-day-regexp) ; defined below
15096 (defvar org-overriding-default-time nil) ; dynamically scoped
15097 (defvar org-read-date-overlay nil)
15098 (defvar org-dcst nil) ; dynamically scoped
15099 (defvar org-read-date-history nil)
15100 (defvar org-read-date-final-answer nil)
15101 (defvar org-read-date-analyze-futurep nil)
15102 (defvar org-read-date-analyze-forced-year nil)
15103 (defvar org-read-date-inactive)
15105 (defun org-read-date (&optional org-with-time to-time from-string prompt
15106 default-time default-input inactive)
15107 "Read a date, possibly a time, and make things smooth for the user.
15108 The prompt will suggest to enter an ISO date, but you can also enter anything
15109 which will at least partially be understood by `parse-time-string'.
15110 Unrecognized parts of the date will default to the current day, month, year,
15111 hour and minute. If this command is called to replace a timestamp at point,
15112 or to enter the second timestamp of a range, the default time is taken
15113 from the existing stamp. Furthermore, the command prefers the future,
15114 so if you are giving a date where the year is not given, and the day-month
15115 combination is already past in the current year, it will assume you
15116 mean next year. For details, see the manual. A few examples:
15118 3-2-5 --> 2003-02-05
15119 feb 15 --> currentyear-02-15
15120 2/15 --> currentyear-02-15
15121 sep 12 9 --> 2009-09-12
15122 12:45 --> today 12:45
15123 22 sept 0:34 --> currentyear-09-22 0:34
15124 12 --> currentyear-currentmonth-12
15125 Fri --> nearest Friday (today or later)
15126 etc.
15128 Furthermore you can specify a relative date by giving, as the *first* thing
15129 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15130 change in days weeks, months, years.
15131 With a single plus or minus, the date is relative to today. With a double
15132 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15133 +4d --> four days from today
15134 +4 --> same as above
15135 +2w --> two weeks from today
15136 ++5 --> five days from default date
15138 The function understands only English month and weekday abbreviations.
15140 While prompting, a calendar is popped up - you can also select the
15141 date with the mouse (button 1). The calendar shows a period of three
15142 months. To scroll it to other months, use the keys `>' and `<'.
15143 If you don't like the calendar, turn it off with
15144 \(setq org-read-date-popup-calendar nil)
15146 With optional argument TO-TIME, the date will immediately be converted
15147 to an internal time.
15148 With an optional argument WITH-TIME, the prompt will suggest to also
15149 insert a time. Note that when WITH-TIME is not set, you can still
15150 enter a time, and this function will inform the calling routine about
15151 this change. The calling routine may then choose to change the format
15152 used to insert the time stamp into the buffer to include the time.
15153 With optional argument FROM-STRING, read from this string instead from
15154 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15155 the time/date that is used for everything that is not specified by the
15156 user."
15157 (require 'parse-time)
15158 (let* ((org-time-stamp-rounding-minutes
15159 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15160 (org-dcst org-display-custom-times)
15161 (ct (org-current-time))
15162 (org-def (or org-overriding-default-time default-time ct))
15163 (org-defdecode (decode-time org-def))
15164 (dummy (progn
15165 (when (< (nth 2 org-defdecode) org-extend-today-until)
15166 (setcar (nthcdr 2 org-defdecode) -1)
15167 (setcar (nthcdr 1 org-defdecode) 59)
15168 (setq org-def (apply 'encode-time org-defdecode)
15169 org-defdecode (decode-time org-def)))))
15170 (calendar-frame-setup nil)
15171 (calendar-setup nil)
15172 (calendar-move-hook nil)
15173 (calendar-view-diary-initially-flag nil)
15174 (calendar-view-holidays-initially-flag nil)
15175 (timestr (format-time-string
15176 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15177 (prompt (concat (if prompt (concat prompt " ") "")
15178 (format "Date+time [%s]: " timestr)))
15179 ans (org-ans0 "") org-ans1 org-ans2 final)
15181 (cond
15182 (from-string (setq ans from-string))
15183 (org-read-date-popup-calendar
15184 (save-excursion
15185 (save-window-excursion
15186 (calendar)
15187 (org-eval-in-calendar '(setq cursor-type nil) t)
15188 (unwind-protect
15189 (progn
15190 (calendar-forward-day (- (time-to-days org-def)
15191 (calendar-absolute-from-gregorian
15192 (calendar-current-date))))
15193 (org-eval-in-calendar nil t)
15194 (let* ((old-map (current-local-map))
15195 (map (copy-keymap calendar-mode-map))
15196 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15197 (org-defkey map (kbd "RET") 'org-calendar-select)
15198 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15199 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15200 (org-defkey minibuffer-local-map [(meta shift left)]
15201 (lambda () (interactive)
15202 (org-eval-in-calendar '(calendar-backward-month 1))))
15203 (org-defkey minibuffer-local-map [(meta shift right)]
15204 (lambda () (interactive)
15205 (org-eval-in-calendar '(calendar-forward-month 1))))
15206 (org-defkey minibuffer-local-map [(meta shift up)]
15207 (lambda () (interactive)
15208 (org-eval-in-calendar '(calendar-backward-year 1))))
15209 (org-defkey minibuffer-local-map [(meta shift down)]
15210 (lambda () (interactive)
15211 (org-eval-in-calendar '(calendar-forward-year 1))))
15212 (org-defkey minibuffer-local-map [?\e (shift left)]
15213 (lambda () (interactive)
15214 (org-eval-in-calendar '(calendar-backward-month 1))))
15215 (org-defkey minibuffer-local-map [?\e (shift right)]
15216 (lambda () (interactive)
15217 (org-eval-in-calendar '(calendar-forward-month 1))))
15218 (org-defkey minibuffer-local-map [?\e (shift up)]
15219 (lambda () (interactive)
15220 (org-eval-in-calendar '(calendar-backward-year 1))))
15221 (org-defkey minibuffer-local-map [?\e (shift down)]
15222 (lambda () (interactive)
15223 (org-eval-in-calendar '(calendar-forward-year 1))))
15224 (org-defkey minibuffer-local-map [(shift up)]
15225 (lambda () (interactive)
15226 (org-eval-in-calendar '(calendar-backward-week 1))))
15227 (org-defkey minibuffer-local-map [(shift down)]
15228 (lambda () (interactive)
15229 (org-eval-in-calendar '(calendar-forward-week 1))))
15230 (org-defkey minibuffer-local-map [(shift left)]
15231 (lambda () (interactive)
15232 (org-eval-in-calendar '(calendar-backward-day 1))))
15233 (org-defkey minibuffer-local-map [(shift right)]
15234 (lambda () (interactive)
15235 (org-eval-in-calendar '(calendar-forward-day 1))))
15236 (org-defkey minibuffer-local-map ">"
15237 (lambda () (interactive)
15238 (org-eval-in-calendar '(scroll-calendar-left 1))))
15239 (org-defkey minibuffer-local-map "<"
15240 (lambda () (interactive)
15241 (org-eval-in-calendar '(scroll-calendar-right 1))))
15242 (org-defkey minibuffer-local-map "\C-v"
15243 (lambda () (interactive)
15244 (org-eval-in-calendar
15245 '(calendar-scroll-left-three-months 1))))
15246 (org-defkey minibuffer-local-map "\M-v"
15247 (lambda () (interactive)
15248 (org-eval-in-calendar
15249 '(calendar-scroll-right-three-months 1))))
15250 (run-hooks 'org-read-date-minibuffer-setup-hook)
15251 (unwind-protect
15252 (progn
15253 (use-local-map map)
15254 (setq org-read-date-inactive inactive)
15255 (add-hook 'post-command-hook 'org-read-date-display)
15256 (setq org-ans0 (read-string prompt default-input
15257 'org-read-date-history nil))
15258 ;; org-ans0: from prompt
15259 ;; org-ans1: from mouse click
15260 ;; org-ans2: from calendar motion
15261 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15262 (remove-hook 'post-command-hook 'org-read-date-display)
15263 (use-local-map old-map)
15264 (when org-read-date-overlay
15265 (delete-overlay org-read-date-overlay)
15266 (setq org-read-date-overlay nil)))))
15267 (bury-buffer "*Calendar*")))))
15269 (t ; Naked prompt only
15270 (unwind-protect
15271 (setq ans (read-string prompt default-input
15272 'org-read-date-history timestr))
15273 (when org-read-date-overlay
15274 (delete-overlay org-read-date-overlay)
15275 (setq org-read-date-overlay nil)))))
15277 (setq final (org-read-date-analyze ans org-def org-defdecode))
15279 (when org-read-date-analyze-forced-year
15280 (message "Year was forced into %s"
15281 (if org-read-date-force-compatible-dates
15282 "compatible range (1970-2037)"
15283 "range representable on this machine"))
15284 (ding))
15286 ;; One round trip to get rid of 34th of August and stuff like that....
15287 (setq final (decode-time (apply 'encode-time final)))
15289 (setq org-read-date-final-answer ans)
15291 (if to-time
15292 (apply 'encode-time final)
15293 (if (and (boundp 'org-time-was-given) org-time-was-given)
15294 (format "%04d-%02d-%02d %02d:%02d"
15295 (nth 5 final) (nth 4 final) (nth 3 final)
15296 (nth 2 final) (nth 1 final))
15297 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15299 (defvar org-def)
15300 (defvar org-defdecode)
15301 (defvar org-with-time)
15302 (defun org-read-date-display ()
15303 "Display the current date prompt interpretation in the minibuffer."
15304 (when org-read-date-display-live
15305 (when org-read-date-overlay
15306 (delete-overlay org-read-date-overlay))
15307 (when (minibufferp (current-buffer))
15308 (save-excursion
15309 (end-of-line 1)
15310 (while (not (equal (buffer-substring
15311 (max (point-min) (- (point) 4)) (point))
15312 " "))
15313 (insert " ")))
15314 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15315 " " (or org-ans1 org-ans2)))
15316 (org-end-time-was-given nil)
15317 (f (org-read-date-analyze ans org-def org-defdecode))
15318 (fmts (if org-dcst
15319 org-time-stamp-custom-formats
15320 org-time-stamp-formats))
15321 (fmt (if (or org-with-time
15322 (and (boundp 'org-time-was-given) org-time-was-given))
15323 (cdr fmts)
15324 (car fmts)))
15325 (txt (format-time-string fmt (apply 'encode-time f)))
15326 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15327 (txt (concat "=> " txt)))
15328 (when (and org-end-time-was-given
15329 (string-match org-plain-time-of-day-regexp txt))
15330 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15331 org-end-time-was-given
15332 (substring txt (match-end 0)))))
15333 (when org-read-date-analyze-futurep
15334 (setq txt (concat txt " (=>F)")))
15335 (setq org-read-date-overlay
15336 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15337 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15339 (defun org-read-date-analyze (ans org-def org-defdecode)
15340 "Analyze the combined answer of the date prompt."
15341 ;; FIXME: cleanup and comment
15342 (let ((nowdecode (decode-time (current-time)))
15343 delta deltan deltaw deltadef year month day
15344 hour minute second wday pm h2 m2 tl wday1
15345 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15346 (setq org-read-date-analyze-futurep nil
15347 org-read-date-analyze-forced-year nil)
15348 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15349 (setq ans "+0"))
15351 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15352 (setq ans (replace-match "" t t ans)
15353 deltan (car delta)
15354 deltaw (nth 1 delta)
15355 deltadef (nth 2 delta)))
15357 ;; Check if there is an iso week date in there
15358 ;; If yes, store the info and postpone interpreting it until the rest
15359 ;; of the parsing is done
15360 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15361 (setq iso-year (if (match-end 1)
15362 (org-small-year-to-year
15363 (string-to-number (match-string 1 ans))))
15364 iso-weekday (if (match-end 3)
15365 (string-to-number (match-string 3 ans)))
15366 iso-week (string-to-number (match-string 2 ans)))
15367 (setq ans (replace-match "" t t ans)))
15369 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15370 (when (string-match
15371 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15372 (setq year (if (match-end 2)
15373 (string-to-number (match-string 2 ans))
15374 (progn (setq kill-year t)
15375 (string-to-number (format-time-string "%Y"))))
15376 month (string-to-number (match-string 3 ans))
15377 day (string-to-number (match-string 4 ans)))
15378 (if (< year 100) (setq year (+ 2000 year)))
15379 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15380 t nil ans)))
15382 ;; Help matching dotted european dates
15383 (when (string-match
15384 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15385 (setq year (if (match-end 3)
15386 (string-to-number (match-string 3 ans))
15387 (progn (setq kill-year t)
15388 (string-to-number (format-time-string "%Y"))))
15389 day (string-to-number (match-string 1 ans))
15390 month (string-to-number (match-string 2 ans))
15391 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15392 t nil ans)))
15394 ;; Help matching american dates, like 5/30 or 5/30/7
15395 (when (string-match
15396 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15397 (setq year (if (match-end 4)
15398 (string-to-number (match-string 4 ans))
15399 (progn (setq kill-year t)
15400 (string-to-number (format-time-string "%Y"))))
15401 month (string-to-number (match-string 1 ans))
15402 day (string-to-number (match-string 2 ans)))
15403 (if (< year 100) (setq year (+ 2000 year)))
15404 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15405 t nil ans)))
15406 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15407 ;; If there is a time with am/pm, and *no* time without it, we convert
15408 ;; so that matching will be successful.
15409 (loop for i from 1 to 2 do ; twice, for end time as well
15410 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15411 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15412 (setq hour (string-to-number (match-string 1 ans))
15413 minute (if (match-end 3)
15414 (string-to-number (match-string 3 ans))
15416 pm (equal ?p
15417 (string-to-char (downcase (match-string 4 ans)))))
15418 (if (and (= hour 12) (not pm))
15419 (setq hour 0)
15420 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15421 (setq ans (replace-match (format "%02d:%02d" hour minute)
15422 t t ans))))
15424 ;; Check if a time range is given as a duration
15425 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15426 (setq hour (string-to-number (match-string 1 ans))
15427 h2 (+ hour (string-to-number (match-string 3 ans)))
15428 minute (string-to-number (match-string 2 ans))
15429 m2 (+ minute (if (match-end 5) (string-to-number
15430 (match-string 5 ans))0)))
15431 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15432 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15433 t t ans)))
15435 ;; Check if there is a time range
15436 (when (boundp 'org-end-time-was-given)
15437 (setq org-time-was-given nil)
15438 (when (and (string-match org-plain-time-of-day-regexp ans)
15439 (match-end 8))
15440 (setq org-end-time-was-given (match-string 8 ans))
15441 (setq ans (concat (substring ans 0 (match-beginning 7))
15442 (substring ans (match-end 7))))))
15444 (setq tl (parse-time-string ans)
15445 day (or (nth 3 tl) (nth 3 org-defdecode))
15446 month (or (nth 4 tl)
15447 (if (and org-read-date-prefer-future
15448 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15449 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15450 (nth 4 org-defdecode)))
15451 year (or (and (not kill-year) (nth 5 tl))
15452 (if (and org-read-date-prefer-future
15453 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15454 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15455 (nth 5 org-defdecode)))
15456 hour (or (nth 2 tl) (nth 2 org-defdecode))
15457 minute (or (nth 1 tl) (nth 1 org-defdecode))
15458 second (or (nth 0 tl) 0)
15459 wday (nth 6 tl))
15461 (when (and (eq org-read-date-prefer-future 'time)
15462 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15463 (equal day (nth 3 nowdecode))
15464 (equal month (nth 4 nowdecode))
15465 (equal year (nth 5 nowdecode))
15466 (nth 2 tl)
15467 (or (< (nth 2 tl) (nth 2 nowdecode))
15468 (and (= (nth 2 tl) (nth 2 nowdecode))
15469 (nth 1 tl)
15470 (< (nth 1 tl) (nth 1 nowdecode)))))
15471 (setq day (1+ day)
15472 futurep t))
15474 ;; Special date definitions below
15475 (cond
15476 (iso-week
15477 ;; There was an iso week
15478 (require 'cal-iso)
15479 (setq futurep nil)
15480 (setq year (or iso-year year)
15481 day (or iso-weekday wday 1)
15482 wday nil ; to make sure that the trigger below does not match
15483 iso-date (calendar-gregorian-from-absolute
15484 (calendar-absolute-from-iso
15485 (list iso-week day year))))
15486 ; FIXME: Should we also push ISO weeks into the future?
15487 ; (when (and org-read-date-prefer-future
15488 ; (not iso-year)
15489 ; (< (calendar-absolute-from-gregorian iso-date)
15490 ; (time-to-days (current-time))))
15491 ; (setq year (1+ year)
15492 ; iso-date (calendar-gregorian-from-absolute
15493 ; (calendar-absolute-from-iso
15494 ; (list iso-week day year)))))
15495 (setq month (car iso-date)
15496 year (nth 2 iso-date)
15497 day (nth 1 iso-date)))
15498 (deltan
15499 (setq futurep nil)
15500 (unless deltadef
15501 (let ((now (decode-time (current-time))))
15502 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15503 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15504 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15505 ((equal deltaw "m") (setq month (+ month deltan)))
15506 ((equal deltaw "y") (setq year (+ year deltan)))))
15507 ((and wday (not (nth 3 tl)))
15508 (setq futurep nil)
15509 ;; Weekday was given, but no day, so pick that day in the week
15510 ;; on or after the derived date.
15511 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15512 (unless (equal wday wday1)
15513 (setq day (+ day (% (- wday wday1 -7) 7))))))
15514 (if (and (boundp 'org-time-was-given)
15515 (nth 2 tl))
15516 (setq org-time-was-given t))
15517 (if (< year 100) (setq year (+ 2000 year)))
15518 ;; Check of the date is representable
15519 (if org-read-date-force-compatible-dates
15520 (progn
15521 (if (< year 1970)
15522 (setq year 1970 org-read-date-analyze-forced-year t))
15523 (if (> year 2037)
15524 (setq year 2037 org-read-date-analyze-forced-year t)))
15525 (condition-case nil
15526 (ignore (encode-time second minute hour day month year))
15527 (error
15528 (setq year (nth 5 org-defdecode))
15529 (setq org-read-date-analyze-forced-year t))))
15530 (setq org-read-date-analyze-futurep futurep)
15531 (list second minute hour day month year)))
15533 (defvar parse-time-weekdays)
15534 (defun org-read-date-get-relative (s today default)
15535 "Check string S for special relative date string.
15536 TODAY and DEFAULT are internal times, for today and for a default.
15537 Return shift list (N what def-flag)
15538 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15539 N is the number of WHATs to shift.
15540 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15541 the DEFAULT date rather than TODAY."
15542 (require 'parse-time)
15543 (when (and
15544 (string-match
15545 (concat
15546 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15547 "\\([0-9]+\\)?"
15548 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15549 "\\([ \t]\\|$\\)") s)
15550 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15551 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15552 (string-to-char (substring (match-string 1 s) -1))
15553 ?+))
15554 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15555 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15556 (what (if (match-end 3) (match-string 3 s) "d"))
15557 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15558 (date (if rel default today))
15559 (wday (nth 6 (decode-time date)))
15560 delta)
15561 (if wday1
15562 (progn
15563 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15564 (if (= dir ?-) (setq delta (- delta 7)))
15565 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15566 (list delta "d" rel))
15567 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15569 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15570 "Turn a user-specified date into the internal representation.
15571 The internal representation needed by the calendar is (month day year).
15572 This is a wrapper to handle the brain-dead convention in calendar that
15573 user function argument order change dependent on argument order."
15574 (if (boundp 'calendar-date-style)
15575 (cond
15576 ((eq calendar-date-style 'american)
15577 (list arg1 arg2 arg3))
15578 ((eq calendar-date-style 'european)
15579 (list arg2 arg1 arg3))
15580 ((eq calendar-date-style 'iso)
15581 (list arg2 arg3 arg1)))
15582 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15583 (if (org-bound-and-true-p european-calendar-style)
15584 (list arg2 arg1 arg3)
15585 (list arg1 arg2 arg3)))))
15587 (defun org-eval-in-calendar (form &optional keepdate)
15588 "Eval FORM in the calendar window and return to current window.
15589 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15590 otherwise stick to the current value of `org-ans2'."
15591 (let ((sf (selected-frame))
15592 (sw (selected-window)))
15593 (select-window (get-buffer-window "*Calendar*" t))
15594 (eval form)
15595 (when (and (not keepdate) (calendar-cursor-to-date))
15596 (let* ((date (calendar-cursor-to-date))
15597 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15598 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15599 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15600 (select-window sw)
15601 (org-select-frame-set-input-focus sf)))
15603 (defun org-calendar-select ()
15604 "Return to `org-read-date' with the date currently selected.
15605 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15606 (interactive)
15607 (when (calendar-cursor-to-date)
15608 (let* ((date (calendar-cursor-to-date))
15609 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15610 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15611 (if (active-minibuffer-window) (exit-minibuffer))))
15613 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15614 "Insert a date stamp for the date given by the internal TIME.
15615 WITH-HM means use the stamp format that includes the time of the day.
15616 INACTIVE means use square brackets instead of angular ones, so that the
15617 stamp will not contribute to the agenda.
15618 PRE and POST are optional strings to be inserted before and after the
15619 stamp.
15620 The command returns the inserted time stamp."
15621 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15622 stamp)
15623 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15624 (insert-before-markers (or pre ""))
15625 (when (listp extra)
15626 (setq extra (car extra))
15627 (if (and (stringp extra)
15628 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15629 (setq extra (format "-%02d:%02d"
15630 (string-to-number (match-string 1 extra))
15631 (string-to-number (match-string 2 extra))))
15632 (setq extra nil)))
15633 (when extra
15634 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15635 (insert-before-markers (setq stamp (format-time-string fmt time)))
15636 (insert-before-markers (or post ""))
15637 (setq org-last-inserted-timestamp stamp)))
15639 (defun org-toggle-time-stamp-overlays ()
15640 "Toggle the use of custom time stamp formats."
15641 (interactive)
15642 (setq org-display-custom-times (not org-display-custom-times))
15643 (unless org-display-custom-times
15644 (let ((p (point-min)) (bmp (buffer-modified-p)))
15645 (while (setq p (next-single-property-change p 'display))
15646 (if (and (get-text-property p 'display)
15647 (eq (get-text-property p 'face) 'org-date))
15648 (remove-text-properties
15649 p (setq p (next-single-property-change p 'display))
15650 '(display t))))
15651 (set-buffer-modified-p bmp)))
15652 (if (featurep 'xemacs)
15653 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15654 (org-restart-font-lock)
15655 (setq org-table-may-need-update t)
15656 (if org-display-custom-times
15657 (message "Time stamps are overlaid with custom format")
15658 (message "Time stamp overlays removed")))
15660 (defun org-display-custom-time (beg end)
15661 "Overlay modified time stamp format over timestamp between BEG and END."
15662 (let* ((ts (buffer-substring beg end))
15663 t1 w1 with-hm tf time str w2 (off 0))
15664 (save-match-data
15665 (setq t1 (org-parse-time-string ts t))
15666 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15667 (setq off (- (match-end 0) (match-beginning 0)))))
15668 (setq end (- end off))
15669 (setq w1 (- end beg)
15670 with-hm (and (nth 1 t1) (nth 2 t1))
15671 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15672 time (org-fix-decoded-time t1)
15673 str (org-add-props
15674 (format-time-string
15675 (substring tf 1 -1) (apply 'encode-time time))
15676 nil 'mouse-face 'highlight)
15677 w2 (length str))
15678 (if (not (= w2 w1))
15679 (add-text-properties (1+ beg) (+ 2 beg)
15680 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15681 (if (featurep 'xemacs)
15682 (progn
15683 (put-text-property beg end 'invisible t)
15684 (put-text-property beg end 'end-glyph (make-glyph str)))
15685 (put-text-property beg end 'display str))))
15687 (defun org-translate-time (string)
15688 "Translate all timestamps in STRING to custom format.
15689 But do this only if the variable `org-display-custom-times' is set."
15690 (when org-display-custom-times
15691 (save-match-data
15692 (let* ((start 0)
15693 (re org-ts-regexp-both)
15694 t1 with-hm inactive tf time str beg end)
15695 (while (setq start (string-match re string start))
15696 (setq beg (match-beginning 0)
15697 end (match-end 0)
15698 t1 (save-match-data
15699 (org-parse-time-string (substring string beg end) t))
15700 with-hm (and (nth 1 t1) (nth 2 t1))
15701 inactive (equal (substring string beg (1+ beg)) "[")
15702 tf (funcall (if with-hm 'cdr 'car)
15703 org-time-stamp-custom-formats)
15704 time (org-fix-decoded-time t1)
15705 str (format-time-string
15706 (concat
15707 (if inactive "[" "<") (substring tf 1 -1)
15708 (if inactive "]" ">"))
15709 (apply 'encode-time time))
15710 string (replace-match str t t string)
15711 start (+ start (length str)))))))
15712 string)
15714 (defun org-fix-decoded-time (time)
15715 "Set 0 instead of nil for the first 6 elements of time.
15716 Don't touch the rest."
15717 (let ((n 0))
15718 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15720 (defun org-days-to-time (timestamp-string)
15721 "Difference between TIMESTAMP-STRING and now in days."
15722 (- (time-to-days (org-time-string-to-time timestamp-string))
15723 (time-to-days (current-time))))
15725 (defun org-deadline-close (timestamp-string &optional ndays)
15726 "Is the time in TIMESTAMP-STRING close to the current date?"
15727 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15728 (and (< (org-days-to-time timestamp-string) ndays)
15729 (not (org-entry-is-done-p))))
15731 (defun org-get-wdays (ts)
15732 "Get the deadline lead time appropriate for timestring TS."
15733 (cond
15734 ((<= org-deadline-warning-days 0)
15735 ;; 0 or negative, enforce this value no matter what
15736 (- org-deadline-warning-days))
15737 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15738 ;; lead time is specified.
15739 (floor (* (string-to-number (match-string 1 ts))
15740 (cdr (assoc (match-string 2 ts)
15741 '(("d" . 1) ("w" . 7)
15742 ("m" . 30.4) ("y" . 365.25)))))))
15743 ;; go for the default.
15744 (t org-deadline-warning-days)))
15746 (defun org-calendar-select-mouse (ev)
15747 "Return to `org-read-date' with the date currently selected.
15748 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15749 (interactive "e")
15750 (mouse-set-point ev)
15751 (when (calendar-cursor-to-date)
15752 (let* ((date (calendar-cursor-to-date))
15753 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15754 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15755 (if (active-minibuffer-window) (exit-minibuffer))))
15757 (defun org-check-deadlines (ndays)
15758 "Check if there are any deadlines due or past due.
15759 A deadline is considered due if it happens within `org-deadline-warning-days'
15760 days from today's date. If the deadline appears in an entry marked DONE,
15761 it is not shown. The prefix arg NDAYS can be used to test that many
15762 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15763 (interactive "P")
15764 (let* ((org-warn-days
15765 (cond
15766 ((equal ndays '(4)) 100000)
15767 (ndays (prefix-numeric-value ndays))
15768 (t (abs org-deadline-warning-days))))
15769 (case-fold-search nil)
15770 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15771 (callback
15772 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15774 (message "%d deadlines past-due or due within %d days"
15775 (org-occur regexp nil callback)
15776 org-warn-days)))
15778 (defun org-check-before-date (date)
15779 "Check if there are deadlines or scheduled entries before DATE."
15780 (interactive (list (org-read-date)))
15781 (let ((case-fold-search nil)
15782 (regexp (concat "\\<\\(" org-deadline-string
15783 "\\|" org-scheduled-string
15784 "\\) *<\\([^>]+\\)>"))
15785 (callback
15786 (lambda () (time-less-p
15787 (org-time-string-to-time (match-string 2))
15788 (org-time-string-to-time date)))))
15789 (message "%d entries before %s"
15790 (org-occur regexp nil callback) date)))
15792 (defun org-check-after-date (date)
15793 "Check if there are deadlines or scheduled entries after DATE."
15794 (interactive (list (org-read-date)))
15795 (let ((case-fold-search nil)
15796 (regexp (concat "\\<\\(" org-deadline-string
15797 "\\|" org-scheduled-string
15798 "\\) *<\\([^>]+\\)>"))
15799 (callback
15800 (lambda () (not
15801 (time-less-p
15802 (org-time-string-to-time (match-string 2))
15803 (org-time-string-to-time date))))))
15804 (message "%d entries after %s"
15805 (org-occur regexp nil callback) date)))
15807 (defun org-check-dates-range (start-date end-date)
15808 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15809 (interactive (list (org-read-date nil nil nil "Range starts")
15810 (org-read-date nil nil nil "Range end")))
15811 (let ((case-fold-search nil)
15812 (regexp (concat "\\<\\(" org-deadline-string
15813 "\\|" org-scheduled-string
15814 "\\) *<\\([^>]+\\)>"))
15815 (callback
15816 (lambda ()
15817 (let ((match (match-string 2)))
15818 (and
15819 (not (time-less-p
15820 (org-time-string-to-time match)
15821 (org-time-string-to-time start-date)))
15822 (time-less-p
15823 (org-time-string-to-time match)
15824 (org-time-string-to-time end-date)))))))
15825 (message "%d entries between %s and %s"
15826 (org-occur regexp nil callback) start-date end-date)))
15828 (defun org-evaluate-time-range (&optional to-buffer)
15829 "Evaluate a time range by computing the difference between start and end.
15830 Normally the result is just printed in the echo area, but with prefix arg
15831 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15832 If the time range is actually in a table, the result is inserted into the
15833 next column.
15834 For time difference computation, a year is assumed to be exactly 365
15835 days in order to avoid rounding problems."
15836 (interactive "P")
15838 (org-clock-update-time-maybe)
15839 (save-excursion
15840 (unless (org-at-date-range-p t)
15841 (goto-char (point-at-bol))
15842 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15843 (if (not (org-at-date-range-p t))
15844 (error "Not at a time-stamp range, and none found in current line")))
15845 (let* ((ts1 (match-string 1))
15846 (ts2 (match-string 2))
15847 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15848 (match-end (match-end 0))
15849 (time1 (org-time-string-to-time ts1))
15850 (time2 (org-time-string-to-time ts2))
15851 (t1 (org-float-time time1))
15852 (t2 (org-float-time time2))
15853 (diff (abs (- t2 t1)))
15854 (negative (< (- t2 t1) 0))
15855 ;; (ys (floor (* 365 24 60 60)))
15856 (ds (* 24 60 60))
15857 (hs (* 60 60))
15858 (fy "%dy %dd %02d:%02d")
15859 (fy1 "%dy %dd")
15860 (fd "%dd %02d:%02d")
15861 (fd1 "%dd")
15862 (fh "%02d:%02d")
15863 y d h m align)
15864 (if havetime
15865 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15867 d (floor (/ diff ds)) diff (mod diff ds)
15868 h (floor (/ diff hs)) diff (mod diff hs)
15869 m (floor (/ diff 60)))
15870 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15872 d (floor (+ (/ diff ds) 0.5))
15873 h 0 m 0))
15874 (if (not to-buffer)
15875 (message "%s" (org-make-tdiff-string y d h m))
15876 (if (org-at-table-p)
15877 (progn
15878 (goto-char match-end)
15879 (setq align t)
15880 (and (looking-at " *|") (goto-char (match-end 0))))
15881 (goto-char match-end))
15882 (if (looking-at
15883 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15884 (replace-match ""))
15885 (if negative (insert " -"))
15886 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15887 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15888 (insert " " (format fh h m))))
15889 (if align (org-table-align))
15890 (message "Time difference inserted")))))
15892 (defun org-make-tdiff-string (y d h m)
15893 (let ((fmt "")
15894 (l nil))
15895 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15896 l (push y l)))
15897 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15898 l (push d l)))
15899 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15900 l (push h l)))
15901 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15902 l (push m l)))
15903 (apply 'format fmt (nreverse l))))
15905 (defun org-time-string-to-time (s &optional buffer pos)
15906 (condition-case errdata
15907 (apply 'encode-time (org-parse-time-string s))
15908 (error (error "Bad timestamp `%s'%s\nError was: %s"
15909 s (if (not (and buffer pos))
15911 (format " at %d in buffer `%s'" pos buffer))
15912 (cdr errdata)))))
15914 (defun org-time-string-to-seconds (s)
15915 (org-float-time (org-time-string-to-time s)))
15917 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15918 "Convert a time stamp to an absolute day number.
15919 If there is a specifier for a cyclic time stamp, get the closest date to
15920 DAYNR.
15921 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15922 The variable date is bound by the calendar when this is called."
15923 (cond
15924 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15925 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15926 daynr
15927 (+ daynr 1000)))
15928 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
15929 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15930 (time-to-days (current-time))) (match-string 0 s)
15931 prefer show-all))
15932 (t (time-to-days
15933 (condition-case errdata
15934 (apply 'encode-time (org-parse-time-string s))
15935 (error (error "Bad timestamp `%s'%s\nError was: %s"
15936 s (if (not (and buffer pos))
15938 (format " at %d in buffer `%s'" pos buffer))
15939 (cdr errdata))))))))
15941 (defun org-days-to-iso-week (days)
15942 "Return the iso week number."
15943 (require 'cal-iso)
15944 (car (calendar-iso-from-absolute days)))
15946 (defun org-small-year-to-year (year)
15947 "Convert 2-digit years into 4-digit years.
15948 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15949 The year 2000 cannot be abbreviated. Any year larger than 99
15950 is returned unchanged."
15951 (if (< year 38)
15952 (setq year (+ 2000 year))
15953 (if (< year 100)
15954 (setq year (+ 1900 year))))
15955 year)
15957 (defun org-time-from-absolute (d)
15958 "Return the time corresponding to date D.
15959 D may be an absolute day number, or a calendar-type list (month day year)."
15960 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15961 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15963 (defun org-calendar-holiday ()
15964 "List of holidays, for Diary display in Org-mode."
15965 (require 'holidays)
15966 (let ((hl (funcall
15967 (if (fboundp 'calendar-check-holidays)
15968 'calendar-check-holidays 'check-calendar-holidays) date)))
15969 (if hl (mapconcat 'identity hl "; "))))
15971 (defun org-diary-sexp-entry (sexp entry date)
15972 "Process a SEXP diary ENTRY for DATE."
15973 (require 'diary-lib)
15974 (let ((result (if calendar-debug-sexp
15975 (let ((stack-trace-on-error t))
15976 (eval (car (read-from-string sexp))))
15977 (condition-case nil
15978 (eval (car (read-from-string sexp)))
15979 (error
15980 (beep)
15981 (message "Bad sexp at line %d in %s: %s"
15982 (org-current-line)
15983 (buffer-file-name) sexp)
15984 (sleep-for 2))))))
15985 (cond ((stringp result) (split-string result "; "))
15986 ((and (consp result)
15987 (not (consp (cdr result)))
15988 (stringp (cdr result))) (cdr result))
15989 ((and (consp result)
15990 (stringp (car result))) result)
15991 (result entry)
15992 (t nil))))
15994 (defun org-diary-to-ical-string (frombuf)
15995 "Get iCalendar entries from diary entries in buffer FROMBUF.
15996 This uses the icalendar.el library."
15997 (let* ((tmpdir (if (featurep 'xemacs)
15998 (temp-directory)
15999 temporary-file-directory))
16000 (tmpfile (make-temp-name
16001 (expand-file-name "orgics" tmpdir)))
16002 buf rtn b e)
16003 (with-current-buffer frombuf
16004 (icalendar-export-region (point-min) (point-max) tmpfile)
16005 (setq buf (find-buffer-visiting tmpfile))
16006 (set-buffer buf)
16007 (goto-char (point-min))
16008 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16009 (setq b (match-beginning 0)))
16010 (goto-char (point-max))
16011 (if (re-search-backward "^END:VEVENT" nil t)
16012 (setq e (match-end 0)))
16013 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16014 (kill-buffer buf)
16015 (delete-file tmpfile)
16016 rtn))
16018 (defun org-closest-date (start current change prefer show-all)
16019 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16020 When PREFER is `past', return a date that is either CURRENT or past.
16021 When PREFER is `future', return a date that is either CURRENT or future.
16022 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16023 ;; Make the proper lists from the dates
16024 (catch 'exit
16025 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16026 dn dw sday cday n1 n2 n0
16027 d m y y1 y2 date1 date2 nmonths nm ny m2)
16029 (setq start (org-date-to-gregorian start)
16030 current (org-date-to-gregorian
16031 (if show-all
16032 current
16033 (time-to-days (current-time))))
16034 sday (calendar-absolute-from-gregorian start)
16035 cday (calendar-absolute-from-gregorian current))
16037 (if (<= cday sday) (throw 'exit sday))
16039 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16040 (setq dn (string-to-number (match-string 1 change))
16041 dw (cdr (assoc (match-string 2 change) a1)))
16042 (error "Invalid change specifier: %s" change))
16043 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16044 (cond
16045 ((eq dw 'day)
16046 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16047 n2 (+ n1 dn)))
16048 ((eq dw 'year)
16049 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16050 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16051 (setq date1 (list m d y1)
16052 n1 (calendar-absolute-from-gregorian date1)
16053 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16054 n2 (calendar-absolute-from-gregorian date2)))
16055 ((eq dw 'month)
16056 ;; approx number of month between the two dates
16057 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16058 ;; How often does dn fit in there?
16059 (setq d (nth 1 start) m (car start) y (nth 2 start)
16060 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16061 m (+ m nm)
16062 ny (floor (/ m 12))
16063 y (+ y ny)
16064 m (- m (* ny 12)))
16065 (while (> m 12) (setq m (- m 12) y (1+ y)))
16066 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16067 (setq m2 (+ m dn) y2 y)
16068 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16069 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16070 (while (<= n2 cday)
16071 (setq n1 n2 m m2 y y2)
16072 (setq m2 (+ m dn) y2 y)
16073 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16074 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16075 ;; Make sure n1 is the earlier date
16076 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16077 (if show-all
16078 (cond
16079 ((eq prefer 'past) (if (= cday n2) n2 n1))
16080 ((eq prefer 'future) (if (= cday n1) n1 n2))
16081 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16082 (cond
16083 ((eq prefer 'past) (if (= cday n2) n2 n1))
16084 ((eq prefer 'future) (if (= cday n1) n1 n2))
16085 (t (if (= cday n1) n1 n2)))))))
16087 (defun org-date-to-gregorian (date)
16088 "Turn any specification of DATE into a Gregorian date for the calendar."
16089 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16090 ((and (listp date) (= (length date) 3)) date)
16091 ((stringp date)
16092 (setq date (org-parse-time-string date))
16093 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16094 ((listp date)
16095 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16097 (defun org-parse-time-string (s &optional nodefault)
16098 "Parse the standard Org-mode time string.
16099 This should be a lot faster than the normal `parse-time-string'.
16100 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16101 hour and minute fields will be nil if not given."
16102 (if (string-match org-ts-regexp0 s)
16103 (list 0
16104 (if (or (match-beginning 8) (not nodefault))
16105 (string-to-number (or (match-string 8 s) "0")))
16106 (if (or (match-beginning 7) (not nodefault))
16107 (string-to-number (or (match-string 7 s) "0")))
16108 (string-to-number (match-string 4 s))
16109 (string-to-number (match-string 3 s))
16110 (string-to-number (match-string 2 s))
16111 nil nil nil)
16112 (error "Not a standard Org-mode time string: %s" s)))
16114 (defun org-timestamp-up (&optional arg)
16115 "Increase the date item at the cursor by one.
16116 If the cursor is on the year, change the year. If it is on the month,
16117 the day or the time, change that.
16118 With prefix ARG, change by that many units."
16119 (interactive "p")
16120 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16122 (defun org-timestamp-down (&optional arg)
16123 "Decrease the date item at the cursor by one.
16124 If the cursor is on the year, change the year. If it is on the month,
16125 the day or the time, change that.
16126 With prefix ARG, change by that many units."
16127 (interactive "p")
16128 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16130 (defun org-timestamp-up-day (&optional arg)
16131 "Increase the date in the time stamp by one day.
16132 With prefix ARG, change that many days."
16133 (interactive "p")
16134 (if (and (not (org-at-timestamp-p t))
16135 (org-at-heading-p))
16136 (org-todo 'up)
16137 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16139 (defun org-timestamp-down-day (&optional arg)
16140 "Decrease the date in the time stamp by one day.
16141 With prefix ARG, change that many days."
16142 (interactive "p")
16143 (if (and (not (org-at-timestamp-p t))
16144 (org-at-heading-p))
16145 (org-todo 'down)
16146 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16148 (defun org-at-timestamp-p (&optional inactive-ok)
16149 "Determine if the cursor is in or at a timestamp."
16150 (interactive)
16151 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16152 (pos (point))
16153 (ans (or (looking-at tsr)
16154 (save-excursion
16155 (skip-chars-backward "^[<\n\r\t")
16156 (if (> (point) (point-min)) (backward-char 1))
16157 (and (looking-at tsr)
16158 (> (- (match-end 0) pos) -1))))))
16159 (and ans
16160 (boundp 'org-ts-what)
16161 (setq org-ts-what
16162 (cond
16163 ((= pos (match-beginning 0)) 'bracket)
16164 ;; Point is considered to be "on the bracket" whether
16165 ;; it's really on it or right after it.
16166 ((or (= pos (1- (match-end 0)))
16167 (= pos (match-end 0))) 'bracket)
16168 ((org-pos-in-match-range pos 2) 'year)
16169 ((org-pos-in-match-range pos 3) 'month)
16170 ((org-pos-in-match-range pos 7) 'hour)
16171 ((org-pos-in-match-range pos 8) 'minute)
16172 ((or (org-pos-in-match-range pos 4)
16173 (org-pos-in-match-range pos 5)) 'day)
16174 ((and (> pos (or (match-end 8) (match-end 5)))
16175 (< pos (match-end 0)))
16176 (- pos (or (match-end 8) (match-end 5))))
16177 (t 'day))))
16178 ans))
16180 (defun org-toggle-timestamp-type ()
16181 "Toggle the type (<active> or [inactive]) of a time stamp."
16182 (interactive)
16183 (when (org-at-timestamp-p t)
16184 (let ((beg (match-beginning 0)) (end (match-end 0))
16185 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16186 (save-excursion
16187 (goto-char beg)
16188 (while (re-search-forward "[][<>]" end t)
16189 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16190 t t)))
16191 (message "Timestamp is now %sactive"
16192 (if (equal (char-after beg) ?<) "" "in")))))
16194 (defun org-timestamp-change (n &optional what updown)
16195 "Change the date in the time stamp at point.
16196 The date will be changed by N times WHAT. WHAT can be `day', `month',
16197 `year', `minute', `second'. If WHAT is not given, the cursor position
16198 in the timestamp determines what will be changed."
16199 (let ((origin (point)) origin-cat
16200 with-hm inactive
16201 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16202 org-ts-what
16203 extra rem
16204 ts time time0)
16205 (if (not (org-at-timestamp-p t))
16206 (error "Not at a timestamp"))
16207 (if (and (not what) (eq org-ts-what 'bracket))
16208 (org-toggle-timestamp-type)
16209 ;; Point isn't on brackets. Remember the part of the time-stamp
16210 ;; the point was in. Indeed, size of time-stamps may change,
16211 ;; but point must be kept in the same category nonetheless.
16212 (setq origin-cat org-ts-what)
16213 (if (and (not what) (not (eq org-ts-what 'day))
16214 org-display-custom-times
16215 (get-text-property (point) 'display)
16216 (not (get-text-property (1- (point)) 'display)))
16217 (setq org-ts-what 'day))
16218 (setq org-ts-what (or what org-ts-what)
16219 inactive (= (char-after (match-beginning 0)) ?\[)
16220 ts (match-string 0))
16221 (replace-match "")
16222 (if (string-match
16223 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16225 (setq extra (match-string 1 ts)))
16226 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16227 (setq with-hm t))
16228 (setq time0 (org-parse-time-string ts))
16229 (when (and updown
16230 (eq org-ts-what 'minute)
16231 (not current-prefix-arg))
16232 ;; This looks like s-up and s-down. Change by one rounding step.
16233 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16234 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16235 (setcar (cdr time0) (+ (nth 1 time0)
16236 (if (> n 0) (- rem) (- dm rem))))))
16237 (setq time
16238 (encode-time (or (car time0) 0)
16239 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16240 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16241 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16242 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16243 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16244 (nthcdr 6 time0)))
16245 (when (and (member org-ts-what '(hour minute))
16246 extra
16247 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16248 (setq extra (org-modify-ts-extra
16249 extra
16250 (if (eq org-ts-what 'hour) 2 5)
16251 n dm)))
16252 (when (integerp org-ts-what)
16253 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16254 (if (eq what 'calendar)
16255 (let ((cal-date (org-get-date-from-calendar)))
16256 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16257 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16258 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16259 (setcar time0 (or (car time0) 0))
16260 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16261 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16262 (setq time (apply 'encode-time time0))))
16263 ;; Insert the new time-stamp, and ensure point stays in the same
16264 ;; category as before (i.e. not after the last position in that
16265 ;; category).
16266 (let ((pos (point)))
16267 ;; Stay before inserted string. `save-excursion' is of no use.
16268 (setq org-last-changed-timestamp
16269 (org-insert-time-stamp time with-hm inactive nil nil extra))
16270 (goto-char pos))
16271 (save-match-data
16272 (looking-at org-ts-regexp3)
16273 (goto-char (cond
16274 ;; `day' category ends before `hour' if any, or at
16275 ;; the end of the day name.
16276 ((eq origin-cat 'day)
16277 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16278 ((eq origin-cat 'hour) (min (match-end 7) origin))
16279 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16280 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16281 ;; `year' and `month' have both fixed size: point
16282 ;; couldn't have moved into another part.
16283 (t origin))))
16284 ;; Update clock if on a CLOCK line.
16285 (org-clock-update-time-maybe)
16286 ;; Try to recenter the calendar window, if any.
16287 (if (and org-calendar-follow-timestamp-change
16288 (get-buffer-window "*Calendar*" t)
16289 (memq org-ts-what '(day month year)))
16290 (org-recenter-calendar (time-to-days time))))))
16292 (defun org-modify-ts-extra (s pos n dm)
16293 "Change the different parts of the lead-time and repeat fields in timestamp."
16294 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16295 ng h m new rem)
16296 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16297 (cond
16298 ((or (org-pos-in-match-range pos 2)
16299 (org-pos-in-match-range pos 3))
16300 (setq m (string-to-number (match-string 3 s))
16301 h (string-to-number (match-string 2 s)))
16302 (if (org-pos-in-match-range pos 2)
16303 (setq h (+ h n))
16304 (setq n (* dm (org-no-warnings (signum n))))
16305 (when (not (= 0 (setq rem (% m dm))))
16306 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16307 (setq m (+ m n)))
16308 (if (< m 0) (setq m (+ m 60) h (1- h)))
16309 (if (> m 59) (setq m (- m 60) h (1+ h)))
16310 (setq h (min 24 (max 0 h)))
16311 (setq ng 1 new (format "-%02d:%02d" h m)))
16312 ((org-pos-in-match-range pos 6)
16313 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16314 ((org-pos-in-match-range pos 5)
16315 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16317 ((org-pos-in-match-range pos 9)
16318 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16319 ((org-pos-in-match-range pos 8)
16320 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16322 (when ng
16323 (setq s (concat
16324 (substring s 0 (match-beginning ng))
16326 (substring s (match-end ng))))))
16329 (defun org-recenter-calendar (date)
16330 "If the calendar is visible, recenter it to DATE."
16331 (let ((cwin (get-buffer-window "*Calendar*" t)))
16332 (when cwin
16333 (let ((calendar-move-hook nil))
16334 (with-selected-window cwin
16335 (calendar-goto-date (if (listp date) date
16336 (calendar-gregorian-from-absolute date))))))))
16338 (defun org-goto-calendar (&optional arg)
16339 "Go to the Emacs calendar at the current date.
16340 If there is a time stamp in the current line, go to that date.
16341 A prefix ARG can be used to force the current date."
16342 (interactive "P")
16343 (let ((tsr org-ts-regexp) diff
16344 (calendar-move-hook nil)
16345 (calendar-view-holidays-initially-flag nil)
16346 (calendar-view-diary-initially-flag nil))
16347 (if (or (org-at-timestamp-p)
16348 (save-excursion
16349 (beginning-of-line 1)
16350 (looking-at (concat ".*" tsr))))
16351 (let ((d1 (time-to-days (current-time)))
16352 (d2 (time-to-days
16353 (org-time-string-to-time (match-string 1)))))
16354 (setq diff (- d2 d1))))
16355 (calendar)
16356 (calendar-goto-today)
16357 (if (and diff (not arg)) (calendar-forward-day diff))))
16359 (defun org-get-date-from-calendar ()
16360 "Return a list (month day year) of date at point in calendar."
16361 (with-current-buffer "*Calendar*"
16362 (save-match-data
16363 (calendar-cursor-to-date))))
16365 (defun org-date-from-calendar ()
16366 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16367 If there is already a time stamp at the cursor position, update it."
16368 (interactive)
16369 (if (org-at-timestamp-p t)
16370 (org-timestamp-change 0 'calendar)
16371 (let ((cal-date (org-get-date-from-calendar)))
16372 (org-insert-time-stamp
16373 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16375 (defun org-minutes-to-hh:mm-string (m)
16376 "Compute H:MM from a number of minutes."
16377 (let ((h (/ m 60)))
16378 (setq m (- m (* 60 h)))
16379 (format org-time-clocksum-format h m)))
16381 (defun org-hh:mm-string-to-minutes (s)
16382 "Convert a string H:MM to a number of minutes.
16383 If the string is just a number, interpret it as minutes.
16384 In fact, the first hh:mm or number in the string will be taken,
16385 there can be extra stuff in the string.
16386 If no number is found, the return value is 0."
16387 (cond
16388 ((integerp s) s)
16389 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16390 (+ (* (string-to-number (match-string 1 s)) 60)
16391 (string-to-number (match-string 2 s))))
16392 ((string-match "\\([0-9]+\\)" s)
16393 (string-to-number (match-string 1 s)))
16394 (t 0)))
16396 (defcustom org-effort-durations
16397 `(("h" . 60)
16398 ("d" . ,(* 60 8))
16399 ("w" . ,(* 60 8 5))
16400 ("m" . ,(* 60 8 5 4))
16401 ("y" . ,(* 60 8 5 40)))
16402 "Conversion factor to minutes for an effort modifier.
16404 Each entry has the form (MODIFIER . MINUTES).
16406 In an effort string, a number followed by MODIFIER is multiplied
16407 by the specified number of MINUTES to obtain an effort in
16408 minutes.
16410 For example, if the value of this variable is ((\"hours\" . 60)), then an
16411 effort string \"2hours\" is equivalent to 120 minutes."
16412 :group 'org-agenda
16413 :version "24.1"
16414 :type '(alist :key-type (string :tag "Modifier")
16415 :value-type (number :tag "Minutes")))
16417 (defun org-duration-string-to-minutes (s &optional output-to-string)
16418 "Convert a duration string S to minutes.
16420 A bare number is interpreted as minutes, modifiers can be set by
16421 customizing `org-effort-durations' (which see).
16423 Entries containing a colon are interpreted as H:MM by
16424 `org-hh:mm-string-to-minutes'."
16425 (let ((result 0)
16426 (re (concat "\\([0-9.]+\\) *\\("
16427 (regexp-opt (mapcar 'car org-effort-durations))
16428 "\\)")))
16429 (while (string-match re s)
16430 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16431 (string-to-number (match-string 1 s))))
16432 (setq s (replace-match "" nil t s)))
16433 (setq result (floor result))
16434 (incf result (org-hh:mm-string-to-minutes s))
16435 (if output-to-string (number-to-string result) result)))
16437 ;;;; Files
16439 (defun org-save-all-org-buffers ()
16440 "Save all Org-mode buffers without user confirmation."
16441 (interactive)
16442 (message "Saving all Org-mode buffers...")
16443 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16444 (when (featurep 'org-id) (org-id-locations-save))
16445 (message "Saving all Org-mode buffers... done"))
16447 (defun org-revert-all-org-buffers ()
16448 "Revert all Org-mode buffers.
16449 Prompt for confirmation when there are unsaved changes.
16450 Be sure you know what you are doing before letting this function
16451 overwrite your changes.
16453 This function is useful in a setup where one tracks org files
16454 with a version control system, to revert on one machine after pulling
16455 changes from another. I believe the procedure must be like this:
16457 1. M-x org-save-all-org-buffers
16458 2. Pull changes from the other machine, resolve conflicts
16459 3. M-x org-revert-all-org-buffers"
16460 (interactive)
16461 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16462 (error "Abort"))
16463 (save-excursion
16464 (save-window-excursion
16465 (mapc
16466 (lambda (b)
16467 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16468 (with-current-buffer b buffer-file-name))
16469 (org-pop-to-buffer-same-window b)
16470 (revert-buffer t 'no-confirm)))
16471 (buffer-list))
16472 (when (and (featurep 'org-id) org-id-track-globally)
16473 (org-id-locations-load)))))
16475 ;;;; Agenda files
16477 ;;;###autoload
16478 (defun org-switchb (&optional arg)
16479 "Switch between Org buffers.
16480 With one prefix argument, restrict available buffers to files.
16481 With two prefix arguments, restrict available buffers to agenda files.
16483 Defaults to `iswitchb' for buffer name completion.
16484 Set `org-completion-use-ido' to make it use ido instead."
16485 (interactive "P")
16486 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16487 ((equal arg '(16)) (org-buffer-list 'agenda))
16488 (t (org-buffer-list))))
16489 (org-completion-use-iswitchb org-completion-use-iswitchb)
16490 (org-completion-use-ido org-completion-use-ido))
16491 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16492 (setq org-completion-use-iswitchb t))
16493 (org-pop-to-buffer-same-window
16494 (org-icompleting-read "Org buffer: "
16495 (mapcar 'list (mapcar 'buffer-name blist))
16496 nil t))))
16498 ;;; Define some older names previously used for this functionality
16499 ;;;###autoload
16500 (defalias 'org-ido-switchb 'org-switchb)
16501 ;;;###autoload
16502 (defalias 'org-iswitchb 'org-switchb)
16504 (defun org-buffer-list (&optional predicate exclude-tmp)
16505 "Return a list of Org buffers.
16506 PREDICATE can be `export', `files' or `agenda'.
16508 export restrict the list to Export buffers.
16509 files restrict the list to buffers visiting Org files.
16510 agenda restrict the list to buffers visiting agenda files.
16512 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16513 (let* ((bfn nil)
16514 (agenda-files (and (eq predicate 'agenda)
16515 (mapcar 'file-truename (org-agenda-files t))))
16516 (filter
16517 (cond
16518 ((eq predicate 'files)
16519 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16520 ((eq predicate 'export)
16521 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16522 ((eq predicate 'agenda)
16523 (lambda (b)
16524 (with-current-buffer b
16525 (and (derived-mode-p 'org-mode)
16526 (setq bfn (buffer-file-name b))
16527 (member (file-truename bfn) agenda-files)))))
16528 (t (lambda (b) (with-current-buffer b
16529 (or (derived-mode-p 'org-mode)
16530 (string-match "\*Org .*Export"
16531 (buffer-name b)))))))))
16532 (delq nil
16533 (mapcar
16534 (lambda(b)
16535 (if (and (funcall filter b)
16536 (or (not exclude-tmp)
16537 (not (string-match "tmp" (buffer-name b)))))
16539 nil))
16540 (buffer-list)))))
16542 (defun org-agenda-files (&optional unrestricted archives)
16543 "Get the list of agenda files.
16544 Optional UNRESTRICTED means return the full list even if a restriction
16545 is currently in place.
16546 When ARCHIVES is t, include all archive files that are really being
16547 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16548 `org-agenda-archives-mode' is t."
16549 (let ((files
16550 (cond
16551 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16552 ((stringp org-agenda-files) (org-read-agenda-file-list))
16553 ((listp org-agenda-files) org-agenda-files)
16554 (t (error "Invalid value of `org-agenda-files'")))))
16555 (setq files (apply 'append
16556 (mapcar (lambda (f)
16557 (if (file-directory-p f)
16558 (directory-files
16559 f t org-agenda-file-regexp)
16560 (list f)))
16561 files)))
16562 (when org-agenda-skip-unavailable-files
16563 (setq files (delq nil
16564 (mapcar (function
16565 (lambda (file)
16566 (and (file-readable-p file) file)))
16567 files))))
16568 (when (or (eq archives t)
16569 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16570 (setq files (org-add-archive-files files)))
16571 files))
16573 (defun org-agenda-file-p (&optional file)
16574 "Return non-nil, if FILE is an agenda file.
16575 If FILE is omitted, use the file associated with the current
16576 buffer."
16577 (member (or file (buffer-file-name))
16578 (org-agenda-files t)))
16580 (defun org-edit-agenda-file-list ()
16581 "Edit the list of agenda files.
16582 Depending on setup, this either uses customize to edit the variable
16583 `org-agenda-files', or it visits the file that is holding the list. In the
16584 latter case, the buffer is set up in a way that saving it automatically kills
16585 the buffer and restores the previous window configuration."
16586 (interactive)
16587 (if (stringp org-agenda-files)
16588 (let ((cw (current-window-configuration)))
16589 (find-file org-agenda-files)
16590 (org-set-local 'org-window-configuration cw)
16591 (org-add-hook 'after-save-hook
16592 (lambda ()
16593 (set-window-configuration
16594 (prog1 org-window-configuration
16595 (kill-buffer (current-buffer))))
16596 (org-install-agenda-files-menu)
16597 (message "New agenda file list installed"))
16598 nil 'local)
16599 (message "%s" (substitute-command-keys
16600 "Edit list and finish with \\[save-buffer]")))
16601 (customize-variable 'org-agenda-files)))
16603 (defun org-store-new-agenda-file-list (list)
16604 "Set new value for the agenda file list and save it correctly."
16605 (if (stringp org-agenda-files)
16606 (let ((fe (org-read-agenda-file-list t)) b u)
16607 (while (setq b (find-buffer-visiting org-agenda-files))
16608 (kill-buffer b))
16609 (with-temp-file org-agenda-files
16610 (insert
16611 (mapconcat
16612 (lambda (f) ;; Keep un-expanded entries.
16613 (if (setq u (assoc f fe))
16614 (cdr u)
16616 list "\n")
16617 "\n")))
16618 (let ((org-mode-hook nil) (org-inhibit-startup t)
16619 (org-insert-mode-line-in-empty-file nil))
16620 (setq org-agenda-files list)
16621 (customize-save-variable 'org-agenda-files org-agenda-files))))
16623 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16624 "Read the list of agenda files from a file.
16625 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16626 filenames, used by `org-store-new-agenda-file-list' to write back
16627 un-expanded file names."
16628 (when (file-directory-p org-agenda-files)
16629 (error "`org-agenda-files' cannot be a single directory"))
16630 (when (stringp org-agenda-files)
16631 (with-temp-buffer
16632 (insert-file-contents org-agenda-files)
16633 (mapcar
16634 (lambda (f)
16635 (let ((e (expand-file-name (substitute-in-file-name f)
16636 org-directory)))
16637 (if pair-with-expansion
16638 (cons e f)
16639 e)))
16640 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16642 ;;;###autoload
16643 (defun org-cycle-agenda-files ()
16644 "Cycle through the files in `org-agenda-files'.
16645 If the current buffer visits an agenda file, find the next one in the list.
16646 If the current buffer does not, find the first agenda file."
16647 (interactive)
16648 (let* ((fs (org-agenda-files t))
16649 (files (append fs (list (car fs))))
16650 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16651 file)
16652 (unless files (error "No agenda files"))
16653 (catch 'exit
16654 (while (setq file (pop files))
16655 (if (equal (file-truename file) tcf)
16656 (when (car files)
16657 (find-file (car files))
16658 (throw 'exit t))))
16659 (find-file (car fs)))
16660 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16662 (defun org-agenda-file-to-front (&optional to-end)
16663 "Move/add the current file to the top of the agenda file list.
16664 If the file is not present in the list, it is added to the front. If it is
16665 present, it is moved there. With optional argument TO-END, add/move to the
16666 end of the list."
16667 (interactive "P")
16668 (let ((org-agenda-skip-unavailable-files nil)
16669 (file-alist (mapcar (lambda (x)
16670 (cons (file-truename x) x))
16671 (org-agenda-files t)))
16672 (ctf (file-truename buffer-file-name))
16673 x had)
16674 (setq x (assoc ctf file-alist) had x)
16676 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16677 (if to-end
16678 (setq file-alist (append (delq x file-alist) (list x)))
16679 (setq file-alist (cons x (delq x file-alist))))
16680 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16681 (org-install-agenda-files-menu)
16682 (message "File %s to %s of agenda file list"
16683 (if had "moved" "added") (if to-end "end" "front"))))
16685 (defun org-remove-file (&optional file)
16686 "Remove current file from the list of files in variable `org-agenda-files'.
16687 These are the files which are being checked for agenda entries.
16688 Optional argument FILE means use this file instead of the current."
16689 (interactive)
16690 (let* ((org-agenda-skip-unavailable-files nil)
16691 (file (or file buffer-file-name))
16692 (true-file (file-truename file))
16693 (afile (abbreviate-file-name file))
16694 (files (delq nil (mapcar
16695 (lambda (x)
16696 (if (equal true-file
16697 (file-truename x))
16698 nil x))
16699 (org-agenda-files t)))))
16700 (if (not (= (length files) (length (org-agenda-files t))))
16701 (progn
16702 (org-store-new-agenda-file-list files)
16703 (org-install-agenda-files-menu)
16704 (message "Removed file: %s" afile))
16705 (message "File was not in list: %s (not removed)" afile))))
16707 (defun org-file-menu-entry (file)
16708 (vector file (list 'find-file file) t))
16710 (defun org-check-agenda-file (file)
16711 "Make sure FILE exists. If not, ask user what to do."
16712 (when (not (file-exists-p file))
16713 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16714 (abbreviate-file-name file))
16715 (let ((r (downcase (read-char-exclusive))))
16716 (cond
16717 ((equal r ?r)
16718 (org-remove-file file)
16719 (throw 'nextfile t))
16720 (t (error "Abort"))))))
16722 (defun org-get-agenda-file-buffer (file)
16723 "Get a buffer visiting FILE. If the buffer needs to be created, add
16724 it to the list of buffers which might be released later."
16725 (let ((buf (org-find-base-buffer-visiting file)))
16726 (if buf
16727 buf ; just return it
16728 ;; Make a new buffer and remember it
16729 (setq buf (find-file-noselect file))
16730 (if buf (push buf org-agenda-new-buffers))
16731 buf)))
16733 (defun org-release-buffers (blist)
16734 "Release all buffers in list, asking the user for confirmation when needed.
16735 When a buffer is unmodified, it is just killed. When modified, it is saved
16736 \(if the user agrees) and then killed."
16737 (let (buf file)
16738 (while (setq buf (pop blist))
16739 (setq file (buffer-file-name buf))
16740 (when (and (buffer-modified-p buf)
16741 file
16742 (y-or-n-p (format "Save file %s? " file)))
16743 (with-current-buffer buf (save-buffer)))
16744 (kill-buffer buf))))
16746 (defun org-prepare-agenda-buffers (files)
16747 "Create buffers for all agenda files, protect archived trees and comments."
16748 (interactive)
16749 (let ((pa '(:org-archived t))
16750 (pc '(:org-comment t))
16751 (pall '(:org-archived t :org-comment t))
16752 (inhibit-read-only t)
16753 (rea (concat ":" org-archive-tag ":"))
16754 bmp file re)
16755 (save-excursion
16756 (save-restriction
16757 (while (setq file (pop files))
16758 (catch 'nextfile
16759 (if (bufferp file)
16760 (set-buffer file)
16761 (org-check-agenda-file file)
16762 (set-buffer (org-get-agenda-file-buffer file)))
16763 (widen)
16764 (setq bmp (buffer-modified-p))
16765 (org-refresh-category-properties)
16766 (setq org-todo-keywords-for-agenda
16767 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16768 (setq org-done-keywords-for-agenda
16769 (append org-done-keywords-for-agenda org-done-keywords))
16770 (setq org-todo-keyword-alist-for-agenda
16771 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16772 (setq org-drawers-for-agenda
16773 (append org-drawers-for-agenda org-drawers))
16774 (setq org-tag-alist-for-agenda
16775 (append org-tag-alist-for-agenda org-tag-alist))
16777 (save-excursion
16778 (remove-text-properties (point-min) (point-max) pall)
16779 (when org-agenda-skip-archived-trees
16780 (goto-char (point-min))
16781 (while (re-search-forward rea nil t)
16782 (if (org-at-heading-p t)
16783 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16784 (goto-char (point-min))
16785 (setq re (format org-heading-keyword-regexp-format
16786 org-comment-string))
16787 (while (re-search-forward re nil t)
16788 (add-text-properties
16789 (match-beginning 0) (org-end-of-subtree t) pc)))
16790 (set-buffer-modified-p bmp)))))
16791 (setq org-todo-keywords-for-agenda
16792 (org-uniquify org-todo-keywords-for-agenda))
16793 (setq org-todo-keyword-alist-for-agenda
16794 (org-uniquify org-todo-keyword-alist-for-agenda)
16795 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16797 ;;;; Embedded LaTeX
16799 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16800 "Keymap for the minor `org-cdlatex-mode'.")
16802 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16803 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16804 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16805 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16806 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16808 (defvar org-cdlatex-texmathp-advice-is-done nil
16809 "Flag remembering if we have applied the advice to texmathp already.")
16811 (define-minor-mode org-cdlatex-mode
16812 "Toggle the minor `org-cdlatex-mode'.
16813 This mode supports entering LaTeX environment and math in LaTeX fragments
16814 in Org-mode.
16815 \\{org-cdlatex-mode-map}"
16816 nil " OCDL" nil
16817 (when org-cdlatex-mode
16818 (require 'cdlatex)
16819 (run-hooks 'cdlatex-mode-hook)
16820 (cdlatex-compute-tables))
16821 (unless org-cdlatex-texmathp-advice-is-done
16822 (setq org-cdlatex-texmathp-advice-is-done t)
16823 (defadvice texmathp (around org-math-always-on activate)
16824 "Always return t in org-mode buffers.
16825 This is because we want to insert math symbols without dollars even outside
16826 the LaTeX math segments. If Orgmode thinks that point is actually inside
16827 an embedded LaTeX fragment, let texmathp do its job.
16828 \\[org-cdlatex-mode-map]"
16829 (interactive)
16830 (let (p)
16831 (cond
16832 ((not (derived-mode-p 'org-mode)) ad-do-it)
16833 ((eq this-command 'cdlatex-math-symbol)
16834 (setq ad-return-value t
16835 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16837 (let ((p (org-inside-LaTeX-fragment-p)))
16838 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16839 (setq ad-return-value t
16840 texmathp-why '("Org-mode embedded math" . 0))
16841 (if p ad-do-it)))))))))
16843 (defun turn-on-org-cdlatex ()
16844 "Unconditionally turn on `org-cdlatex-mode'."
16845 (org-cdlatex-mode 1))
16847 (defun org-inside-LaTeX-fragment-p ()
16848 "Test if point is inside a LaTeX fragment.
16849 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16850 sequence appearing also before point.
16851 Even though the matchers for math are configurable, this function assumes
16852 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16853 delimiters are skipped when they have been removed by customization.
16854 The return value is nil, or a cons cell with the delimiter and the
16855 position of this delimiter.
16857 This function does a reasonably good job, but can locally be fooled by
16858 for example currency specifications. For example it will assume being in
16859 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16860 fragments that are properly closed, but during editing, we have to live
16861 with the uncertainty caused by missing closing delimiters. This function
16862 looks only before point, not after."
16863 (catch 'exit
16864 (let ((pos (point))
16865 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16866 (lim (progn
16867 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16868 (point)))
16869 dd-on str (start 0) m re)
16870 (goto-char pos)
16871 (when dodollar
16872 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16873 re (nth 1 (assoc "$" org-latex-regexps)))
16874 (while (string-match re str start)
16875 (cond
16876 ((= (match-end 0) (length str))
16877 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16878 ((= (match-end 0) (- (length str) 5))
16879 (throw 'exit nil))
16880 (t (setq start (match-end 0))))))
16881 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16882 (goto-char pos)
16883 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16884 (and (match-beginning 2) (throw 'exit nil))
16885 ;; count $$
16886 (while (re-search-backward "\\$\\$" lim t)
16887 (setq dd-on (not dd-on)))
16888 (goto-char pos)
16889 (if dd-on (cons "$$" m))))))
16891 (defun org-inside-latex-macro-p ()
16892 "Is point inside a LaTeX macro or its arguments?"
16893 (save-match-data
16894 (org-in-regexp
16895 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16897 (defun org-try-cdlatex-tab ()
16898 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16899 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16900 - inside a LaTeX fragment, or
16901 - after the first word in a line, where an abbreviation expansion could
16902 insert a LaTeX environment."
16903 (when org-cdlatex-mode
16904 (cond
16905 ;; Before any word on the line: No expansion possible.
16906 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16907 ;; Just after first word on the line: Expand it. Make sure it
16908 ;; cannot happen on headlines, though.
16909 ((save-excursion
16910 (skip-chars-backward "a-zA-Z0-9*")
16911 (skip-chars-backward " \t")
16912 (and (bolp) (not (org-at-heading-p))))
16913 (cdlatex-tab) t)
16914 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16916 (defun org-cdlatex-underscore-caret (&optional arg)
16917 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16918 Revert to the normal definition outside of these fragments."
16919 (interactive "P")
16920 (if (org-inside-LaTeX-fragment-p)
16921 (call-interactively 'cdlatex-sub-superscript)
16922 (let (org-cdlatex-mode)
16923 (call-interactively (key-binding (vector last-input-event))))))
16925 (defun org-cdlatex-math-modify (&optional arg)
16926 "Execute `cdlatex-math-modify' in LaTeX fragments.
16927 Revert to the normal definition outside of these fragments."
16928 (interactive "P")
16929 (if (org-inside-LaTeX-fragment-p)
16930 (call-interactively 'cdlatex-math-modify)
16931 (let (org-cdlatex-mode)
16932 (call-interactively (key-binding (vector last-input-event))))))
16934 (defvar org-latex-fragment-image-overlays nil
16935 "List of overlays carrying the images of latex fragments.")
16936 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16938 (defun org-remove-latex-fragment-image-overlays ()
16939 "Remove all overlays with LaTeX fragment images in current buffer."
16940 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16941 (setq org-latex-fragment-image-overlays nil))
16943 (defun org-preview-latex-fragment (&optional subtree)
16944 "Preview the LaTeX fragment at point, or all locally or globally.
16945 If the cursor is in a LaTeX fragment, create the image and overlay
16946 it over the source code. If there is no fragment at point, display
16947 all fragments in the current text, from one headline to the next. With
16948 prefix SUBTREE, display all fragments in the current subtree. With a
16949 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16950 the cursor is before the first headline,
16951 display all fragments in the buffer.
16952 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16953 (interactive "P")
16954 (unless buffer-file-name
16955 (error "Can't preview LaTeX fragment in a non-file buffer"))
16956 (org-remove-latex-fragment-image-overlays)
16957 (save-excursion
16958 (save-restriction
16959 (let (beg end at msg)
16960 (cond
16961 ((or (equal subtree '(16))
16962 (not (save-excursion
16963 (re-search-backward org-outline-regexp-bol nil t))))
16964 (setq beg (point-min) end (point-max)
16965 msg "Creating images for buffer...%s"))
16966 ((equal subtree '(4))
16967 (org-back-to-heading)
16968 (setq beg (point) end (org-end-of-subtree t)
16969 msg "Creating images for subtree...%s"))
16971 (if (setq at (org-inside-LaTeX-fragment-p))
16972 (goto-char (max (point-min) (- (cdr at) 2)))
16973 (org-back-to-heading))
16974 (setq beg (point) end (progn (outline-next-heading) (point))
16975 msg (if at "Creating image...%s"
16976 "Creating images for entry...%s"))))
16977 (message msg "")
16978 (narrow-to-region beg end)
16979 (goto-char beg)
16980 (org-format-latex
16981 (concat "ltxpng/" (file-name-sans-extension
16982 (file-name-nondirectory
16983 buffer-file-name)))
16984 default-directory 'overlays msg at 'forbuffer
16985 org-latex-create-formula-image-program)
16986 (message msg "done. Use `C-c C-c' to remove images.")))))
16988 (defvar org-latex-regexps
16989 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16990 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16991 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16992 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16993 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16994 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16995 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16996 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16997 "Regular expressions for matching embedded LaTeX.")
16999 (defvar org-export-have-math nil) ;; dynamic scoping
17000 (defun org-format-latex (prefix &optional dir overlays msg at
17001 forbuffer processing-type)
17002 "Replace LaTeX fragments with links to an image, and produce images.
17003 Some of the options can be changed using the variable
17004 `org-format-latex-options'."
17005 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17006 (let* ((prefixnodir (file-name-nondirectory prefix))
17007 (absprefix (expand-file-name prefix dir))
17008 (todir (file-name-directory absprefix))
17009 (opt org-format-latex-options)
17010 (matchers (plist-get opt :matchers))
17011 (re-list org-latex-regexps)
17012 (org-format-latex-header-extra
17013 (plist-get (org-infile-export-plist) :latex-header-extra))
17014 (cnt 0) txt hash link beg end re e checkdir
17015 executables-checked string
17016 m n block-type block linkfile movefile ov)
17017 ;; Check the different regular expressions
17018 (while (setq e (pop re-list))
17019 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17020 block (if block-type "\n\n" ""))
17021 (when (member m matchers)
17022 (goto-char (point-min))
17023 (while (re-search-forward re nil t)
17024 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17025 (not (get-text-property (match-beginning n)
17026 'org-protected))
17027 (or (not overlays)
17028 (not (eq (get-char-property (match-beginning n)
17029 'org-overlay-type)
17030 'org-latex-overlay))))
17031 (setq org-export-have-math t)
17032 (cond
17033 ((eq processing-type 'verbatim)
17034 ;; Leave the text verbatim, just protect it
17035 (add-text-properties (match-beginning n) (match-end n)
17036 '(org-protected t)))
17037 ((eq processing-type 'mathjax)
17038 ;; Prepare for MathJax processing
17039 (setq string (match-string n))
17040 (if (member m '("$" "$1"))
17041 (save-excursion
17042 (delete-region (match-beginning n) (match-end n))
17043 (goto-char (match-beginning n))
17044 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17045 "\\)")
17046 '(org-protected t))))
17047 (add-text-properties (match-beginning n) (match-end n)
17048 '(org-protected t))))
17049 ((or (eq processing-type 'dvipng)
17050 (eq processing-type 'imagemagick))
17051 ;; Process to an image
17052 (setq txt (match-string n)
17053 beg (match-beginning n) end (match-end n)
17054 cnt (1+ cnt))
17055 (let (print-length print-level) ; make sure full list is printed
17056 (setq hash (sha1 (prin1-to-string
17057 (list org-format-latex-header
17058 org-format-latex-header-extra
17059 org-export-latex-default-packages-alist
17060 org-export-latex-packages-alist
17061 org-format-latex-options
17062 forbuffer txt)))
17063 linkfile (format "%s_%s.png" prefix hash)
17064 movefile (format "%s_%s.png" absprefix hash)))
17065 (setq link (concat block "[[file:" linkfile "]]" block))
17066 (if msg (message msg cnt))
17067 (goto-char beg)
17068 (unless checkdir ; make sure the directory exists
17069 (setq checkdir t)
17070 (or (file-directory-p todir) (make-directory todir t)))
17071 (cond
17072 ((eq processing-type 'dvipng)
17073 (unless executables-checked
17074 (org-check-external-command
17075 "latex" "needed to convert LaTeX fragments to images")
17076 (org-check-external-command
17077 "dvipng" "needed to convert LaTeX fragments to images")
17078 (setq executables-checked t))
17079 (unless (file-exists-p movefile)
17080 (org-create-formula-image-with-dvipng
17081 txt movefile opt forbuffer)))
17082 ((eq processing-type 'imagemagick)
17083 (unless executables-checked
17084 (org-check-external-command
17085 "convert" "you need to install imagemagick")
17086 (setq executables-checked t))
17087 (unless (file-exists-p movefile)
17088 (org-create-formula-image-with-imagemagick
17089 txt movefile opt forbuffer))))
17090 (if overlays
17091 (progn
17092 (mapc (lambda (o)
17093 (if (eq (overlay-get o 'org-overlay-type)
17094 'org-latex-overlay)
17095 (delete-overlay o)))
17096 (overlays-in beg end))
17097 (setq ov (make-overlay beg end))
17098 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17099 (if (featurep 'xemacs)
17100 (progn
17101 (overlay-put ov 'invisible t)
17102 (overlay-put
17103 ov 'end-glyph
17104 (make-glyph (vector 'png :file movefile))))
17105 (overlay-put
17106 ov 'display
17107 (list 'image :type 'png :file movefile :ascent 'center)))
17108 (push ov org-latex-fragment-image-overlays)
17109 (goto-char end))
17110 (delete-region beg end)
17111 (insert (org-add-props link
17112 (list 'org-latex-src
17113 (replace-regexp-in-string
17114 "\"" "" txt)
17115 'org-latex-src-embed-type
17116 (if block-type 'paragraph 'character))))))
17117 ((eq processing-type 'mathml)
17118 ;; Process to MathML
17119 (unless executables-checked
17120 (unless (save-match-data (org-format-latex-mathml-available-p))
17121 (error "LaTeX to MathML converter not configured"))
17122 (setq executables-checked t))
17123 (setq txt (match-string n)
17124 beg (match-beginning n) end (match-end n)
17125 cnt (1+ cnt))
17126 (if msg (message msg cnt))
17127 (goto-char beg)
17128 (delete-region beg end)
17129 (insert (org-format-latex-as-mathml
17130 txt block-type prefix dir)))
17132 (error "Unknown conversion type %s for latex fragments"
17133 processing-type)))))))))
17135 (defun org-create-math-formula (latex-frag &optional mathml-file)
17136 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17137 Use `org-latex-to-mathml-convert-command'. If the conversion is
17138 sucessful, return the portion between \"<math...> </math>\"
17139 elements otherwise return nil. When MATHML-FILE is specified,
17140 write the results in to that file. When invoked as an
17141 interactive command, prompt for LATEX-FRAG, with initial value
17142 set to the current active region and echo the results for user
17143 inspection."
17144 (interactive (list (let ((frag (when (region-active-p)
17145 (buffer-substring-no-properties
17146 (region-beginning) (region-end)))))
17147 (read-string "LaTeX Fragment: " frag nil frag))))
17148 (unless latex-frag (error "Invalid latex-frag"))
17149 (let* ((tmp-in-file (file-relative-name
17150 (make-temp-name (expand-file-name "ltxmathml-in"))))
17151 (ignore (write-region latex-frag nil tmp-in-file))
17152 (tmp-out-file (file-relative-name
17153 (make-temp-name (expand-file-name "ltxmathml-out"))))
17154 (cmd (format-spec
17155 org-latex-to-mathml-convert-command
17156 `((?j . ,(shell-quote-argument
17157 (expand-file-name org-latex-to-mathml-jar-file)))
17158 (?I . ,(shell-quote-argument tmp-in-file))
17159 (?o . ,(shell-quote-argument tmp-out-file)))))
17160 mathml shell-command-output)
17161 (when (org-called-interactively-p 'any)
17162 (unless (org-format-latex-mathml-available-p)
17163 (error "LaTeX to MathML converter not configured")))
17164 (message "Running %s" cmd)
17165 (setq shell-command-output (shell-command-to-string cmd))
17166 (setq mathml
17167 (when (file-readable-p tmp-out-file)
17168 (with-current-buffer (find-file-noselect tmp-out-file t)
17169 (goto-char (point-min))
17170 (when (re-search-forward
17171 (concat
17172 (regexp-quote
17173 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17174 "\\(.\\|\n\\)*"
17175 (regexp-quote "</math>")) nil t)
17176 (prog1 (match-string 0) (kill-buffer))))))
17177 (cond
17178 (mathml
17179 (setq mathml
17180 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17181 (when mathml-file
17182 (write-region mathml nil mathml-file))
17183 (when (org-called-interactively-p 'any)
17184 (message mathml)))
17185 ((message "LaTeX to MathML conversion failed")
17186 (message shell-command-output)))
17187 (delete-file tmp-in-file)
17188 (when (file-exists-p tmp-out-file)
17189 (delete-file tmp-out-file))
17190 mathml))
17192 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17193 prefix &optional dir)
17194 "Use `org-create-math-formula' but check local cache first."
17195 (let* ((absprefix (expand-file-name prefix dir))
17196 (print-length nil) (print-level nil)
17197 (formula-id (concat
17198 "formula-"
17199 (sha1
17200 (prin1-to-string
17201 (list latex-frag
17202 org-latex-to-mathml-convert-command)))))
17203 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17204 (formula-cache-dir (file-name-directory formula-cache)))
17206 (unless (file-directory-p formula-cache-dir)
17207 (make-directory formula-cache-dir t))
17209 (unless (file-exists-p formula-cache)
17210 (org-create-math-formula latex-frag formula-cache))
17212 (if (file-exists-p formula-cache)
17213 ;; Successful conversion. Return the link to MathML file.
17214 (org-add-props
17215 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17216 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17217 'org-latex-src-embed-type (if latex-frag-type
17218 'paragraph 'character)))
17219 ;; Failed conversion. Return the LaTeX fragment verbatim
17220 (add-text-properties
17221 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17222 latex-frag)))
17224 ;; This function borrows from Ganesh Swami's latex2png.el
17225 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17226 "This calls dvipng."
17227 (require 'org-latex)
17228 (let* ((tmpdir (if (featurep 'xemacs)
17229 (temp-directory)
17230 temporary-file-directory))
17231 (texfilebase (make-temp-name
17232 (expand-file-name "orgtex" tmpdir)))
17233 (texfile (concat texfilebase ".tex"))
17234 (dvifile (concat texfilebase ".dvi"))
17235 (pngfile (concat texfilebase ".png"))
17236 (fnh (if (featurep 'xemacs)
17237 (font-height (face-font 'default))
17238 (face-attribute 'default :height nil)))
17239 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17240 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17241 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17242 "Black"))
17243 (bg (or (plist-get options (if buffer :background :html-background))
17244 "Transparent")))
17245 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17246 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17247 (with-temp-file texfile
17248 (insert (org-splice-latex-header
17249 org-format-latex-header
17250 org-export-latex-default-packages-alist
17251 org-export-latex-packages-alist t
17252 org-format-latex-header-extra))
17253 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17254 (require 'org-latex)
17255 (org-export-latex-fix-inputenc))
17256 (let ((dir default-directory))
17257 (condition-case nil
17258 (progn
17259 (cd tmpdir)
17260 (call-process "latex" nil nil nil texfile))
17261 (error nil))
17262 (cd dir))
17263 (if (not (file-exists-p dvifile))
17264 (progn (message "Failed to create dvi file from %s" texfile) nil)
17265 (condition-case nil
17266 (if (featurep 'xemacs)
17267 (call-process "dvipng" nil nil nil
17268 "-fg" fg "-bg" bg
17269 "-T" "tight"
17270 "-o" pngfile
17271 dvifile)
17272 (call-process "dvipng" nil nil nil
17273 "-fg" fg "-bg" bg
17274 "-D" dpi
17275 ;;"-x" scale "-y" scale
17276 "-T" "tight"
17277 "-o" pngfile
17278 dvifile))
17279 (error nil))
17280 (if (not (file-exists-p pngfile))
17281 (if org-format-latex-signal-error
17282 (error "Failed to create png file from %s" texfile)
17283 (message "Failed to create png file from %s" texfile)
17284 nil)
17285 ;; Use the requested file name and clean up
17286 (copy-file pngfile tofile 'replace)
17287 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17288 (if (file-exists-p (concat texfilebase e))
17289 (delete-file (concat texfilebase e))))
17290 pngfile))))
17292 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17293 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17294 "This calls convert, which is included into imagemagick."
17295 (require 'org-latex)
17296 (let* ((tmpdir (if (featurep 'xemacs)
17297 (temp-directory)
17298 temporary-file-directory))
17299 (texfilebase (make-temp-name
17300 (expand-file-name "orgtex" tmpdir)))
17301 (texfile (concat texfilebase ".tex"))
17302 (pdffile (concat texfilebase ".pdf"))
17303 (pngfile (concat texfilebase ".png"))
17304 (fnh (if (featurep 'xemacs)
17305 (font-height (face-font 'default))
17306 (face-attribute 'default :height nil)))
17307 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17308 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17309 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17310 "black"))
17311 (bg (or (plist-get options (if buffer :background :html-background))
17312 "white")))
17313 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17314 (setq fg (org-latex-color-format fg)))
17315 (if (eq bg 'default) (setq bg (org-latex-color :background))
17316 (setq bg (org-latex-color-format
17317 (if (string= bg "Transparent")(setq bg "white")))))
17318 (with-temp-file texfile
17319 (insert (org-splice-latex-header
17320 org-format-latex-header
17321 org-export-latex-default-packages-alist
17322 org-export-latex-packages-alist t
17323 org-format-latex-header-extra))
17324 (insert "\n\\begin{document}\n"
17325 "\\definecolor{fg}{rgb}{" fg "}\n"
17326 "\\definecolor{bg}{rgb}{" bg "}\n"
17327 "\n\\pagecolor{bg}\n"
17328 "\n{\\color{fg}\n"
17329 string
17330 "\n}\n"
17331 "\n\\end{document}\n" )
17332 (require 'org-latex)
17333 (org-export-latex-fix-inputenc))
17334 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17335 (condition-case nil
17336 (progn
17337 (cd tmpdir)
17338 (setq cmds org-latex-to-pdf-process)
17339 (while cmds
17340 (setq latex-frags-cmds (pop cmds))
17341 (if (listp latex-frags-cmds)
17342 (setq cmds nil)
17343 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17344 (while latex-frags-cmds
17345 (setq cmd (pop latex-frags-cmds))
17346 (while (string-match "%b" cmd)
17347 (setq cmd (replace-match
17348 (save-match-data
17349 (shell-quote-argument texfile))
17350 t t cmd)))
17351 (while (string-match "%f" cmd)
17352 (setq cmd (replace-match
17353 (save-match-data
17354 (shell-quote-argument (file-name-nondirectory texfile)))
17355 t t cmd)))
17356 (while (string-match "%o" cmd)
17357 (setq cmd (replace-match
17358 (save-match-data
17359 (shell-quote-argument (file-name-directory texfile)))
17360 t t cmd)))
17361 (setq cmd (split-string cmd))
17362 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17363 (error nil))
17364 (cd dir))
17365 (if (not (file-exists-p pdffile))
17366 (progn (message "Failed to create pdf file from %s" texfile) nil)
17367 (condition-case nil
17368 (if (featurep 'xemacs)
17369 (call-process "convert" nil nil nil
17370 "-density" "96"
17371 "-trim"
17372 "-antialias"
17373 pdffile
17374 "-quality" "100"
17375 ;; "-sharpen" "0x1.0"
17376 pngfile)
17377 (call-process "convert" nil nil nil
17378 "-density" dpi
17379 "-trim"
17380 "-antialias"
17381 pdffile
17382 "-quality" "100"
17383 ; "-sharpen" "0x1.0"
17384 pngfile))
17385 (error nil))
17386 (if (not (file-exists-p pngfile))
17387 (if org-format-latex-signal-error
17388 (error "Failed to create png file from %s" texfile)
17389 (message "Failed to create png file from %s" texfile)
17390 nil)
17391 ;; Use the requested file name and clean up
17392 (copy-file pngfile tofile 'replace)
17393 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17394 (if (file-exists-p (concat texfilebase e))
17395 (delete-file (concat texfilebase e))))
17396 pngfile))))
17398 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17399 "Fill a LaTeX header template TPL.
17400 In the template, the following place holders will be recognized:
17402 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17403 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17404 [PACKAGES] \\usepackage statements for PKG
17405 [NO-PACKAGES] do not include PKG
17406 [EXTRA] the string EXTRA
17407 [NO-EXTRA] do not include EXTRA
17409 For backward compatibility, if both the positive and the negative place
17410 holder is missing, the positive one (without the \"NO-\") will be
17411 assumed to be present at the end of the template.
17412 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17413 EXTRA is a string.
17414 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17415 (let (rpl (end ""))
17416 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17417 (setq rpl (if (or (match-end 1) (not def-pkg))
17418 "" (org-latex-packages-to-string def-pkg snippets-p t))
17419 tpl (replace-match rpl t t tpl))
17420 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17422 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17423 (setq rpl (if (or (match-end 1) (not pkg))
17424 "" (org-latex-packages-to-string pkg snippets-p t))
17425 tpl (replace-match rpl t t tpl))
17426 (if pkg (setq end
17427 (concat end "\n"
17428 (org-latex-packages-to-string pkg snippets-p)))))
17430 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17431 (setq rpl (if (or (match-end 1) (not extra))
17432 "" (concat extra "\n"))
17433 tpl (replace-match rpl t t tpl))
17434 (if (and extra (string-match "\\S-" extra))
17435 (setq end (concat end "\n" extra))))
17437 (if (string-match "\\S-" end)
17438 (concat tpl "\n" end)
17439 tpl)))
17441 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17442 "Turn an alist of packages into a string with the \\usepackage macros."
17443 (setq pkg (mapconcat (lambda(p)
17444 (cond
17445 ((stringp p) p)
17446 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17447 (format "%% Package %s omitted" (cadr p)))
17448 ((equal "" (car p))
17449 (format "\\usepackage{%s}" (cadr p)))
17451 (format "\\usepackage[%s]{%s}"
17452 (car p) (cadr p)))))
17454 "\n"))
17455 (if newline (concat pkg "\n") pkg))
17457 (defun org-dvipng-color (attr)
17458 "Return a RGB color specification for dvipng."
17459 (apply 'format "rgb %s %s %s"
17460 (mapcar 'org-normalize-color
17461 (if (featurep 'xemacs)
17462 (color-rgb-components
17463 (face-property 'default
17464 (cond ((eq attr :foreground) 'foreground)
17465 ((eq attr :background) 'background))))
17466 (color-values (face-attribute 'default attr nil))))))
17468 (defun org-latex-color (attr)
17469 "Return a RGB color for the LaTeX color package."
17470 (apply 'format "%s,%s,%s"
17471 (mapcar 'org-normalize-color
17472 (if (featurep 'xemacs)
17473 (color-rgb-components
17474 (face-property 'default
17475 (cond ((eq attr :foreground) 'foreground)
17476 ((eq attr :background) 'background))))
17477 (color-values (face-attribute 'default attr nil))))))
17479 (defun org-latex-color-format (color-name)
17480 "Convert COLOR-NAME to a RGB color value."
17481 (apply 'format "%s,%s,%s"
17482 (mapcar 'org-normalize-color
17483 (color-values color-name))))
17485 (defun org-normalize-color (value)
17486 "Return string to be used as color value for an RGB component."
17487 (format "%g" (/ value 65535.0)))
17489 ;; Image display
17492 (defvar org-inline-image-overlays nil)
17493 (make-variable-buffer-local 'org-inline-image-overlays)
17495 (defun org-toggle-inline-images (&optional include-linked)
17496 "Toggle the display of inline images.
17497 INCLUDE-LINKED is passed to `org-display-inline-images'."
17498 (interactive "P")
17499 (if org-inline-image-overlays
17500 (progn
17501 (org-remove-inline-images)
17502 (message "Inline image display turned off"))
17503 (org-display-inline-images include-linked)
17504 (if org-inline-image-overlays
17505 (message "%d images displayed inline"
17506 (length org-inline-image-overlays))
17507 (message "No images to display inline"))))
17509 (defun org-display-inline-images (&optional include-linked refresh beg end)
17510 "Display inline images.
17511 Normally only links without a description part are inlined, because this
17512 is how it will work for export. When INCLUDE-LINKED is set, also links
17513 with a description part will be inlined. This can be nice for a quick
17514 look at those images, but it does not reflect what exported files will look
17515 like.
17516 When REFRESH is set, refresh existing images between BEG and END.
17517 This will create new image displays only if necessary.
17518 BEG and END default to the buffer boundaries."
17519 (interactive "P")
17520 (unless refresh
17521 (org-remove-inline-images)
17522 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17523 (save-excursion
17524 (save-restriction
17525 (widen)
17526 (setq beg (or beg (point-min)) end (or end (point-max)))
17527 (goto-char beg)
17528 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17529 (substring (org-image-file-name-regexp) 0 -2)
17530 "\\)\\]" (if include-linked "" "\\]")))
17531 old file ov img)
17532 (while (re-search-forward re end t)
17533 (setq old (get-char-property-and-overlay (match-beginning 1)
17534 'org-image-overlay))
17535 (setq file (expand-file-name
17536 (concat (or (match-string 3) "") (match-string 4))))
17537 (when (file-exists-p file)
17538 (if (and (car-safe old) refresh)
17539 (image-refresh (overlay-get (cdr old) 'display))
17540 (setq img (save-match-data (create-image file)))
17541 (when img
17542 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17543 (overlay-put ov 'display img)
17544 (overlay-put ov 'face 'default)
17545 (overlay-put ov 'org-image-overlay t)
17546 (overlay-put ov 'modification-hooks
17547 (list 'org-display-inline-modification-hook))
17548 (push ov org-inline-image-overlays)))))))))
17550 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17551 "Remove inline-display overlay if a corresponding region is modified."
17552 (let ((inhibit-modification-hooks t))
17553 (when (and ov after)
17554 (delete ov org-inline-image-overlays)
17555 (delete-overlay ov))))
17557 (defun org-remove-inline-images ()
17558 "Remove inline display of images."
17559 (interactive)
17560 (mapc 'delete-overlay org-inline-image-overlays)
17561 (setq org-inline-image-overlays nil))
17563 ;;;; Key bindings
17565 ;; Outline functions from `outline-mode-prefix-map'
17566 ;; that can be remapped in Org:
17567 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17568 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17569 (define-key org-mode-map [remap outline-forward-same-level]
17570 'org-forward-same-level)
17571 (define-key org-mode-map [remap outline-backward-same-level]
17572 'org-backward-same-level)
17573 (define-key org-mode-map [remap show-branches]
17574 'org-kill-note-or-show-branches)
17575 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17576 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17577 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17579 ;; Outline functions from `outline-mode-prefix-map'
17580 ;; that can not be remapped in Org:
17581 ;; - the column "key binding" shows whether the Outline function is still
17582 ;; available in Org mode on the same key that it has been bound to in
17583 ;; Outline mode:
17584 ;; - "overridden": key used for a different functionality in Org mode
17585 ;; - else: key still bound to the same Outline function in Org mode
17586 ;; | Outline function | key binding | Org replacement |
17587 ;; |------------------------------------+-------------+-----------------------|
17588 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17589 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17590 ;; | `show-children' | `C-c C-i' | visibility cycling |
17591 ;; | `hide-subtree' | overridden | visibility cycling |
17592 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17593 ;; | `hide-body' | overridden | no replacement |
17594 ;; | `show-all' | overridden | no replacement |
17595 ;; | `hide-entry' | overridden | visibility cycling |
17596 ;; | `show-entry' | overridden | no replacement |
17597 ;; | `hide-leaves' | overridden | no replacement |
17598 ;; | `hide-sublevels' | overridden | no replacement |
17599 ;; | `hide-other' | overridden | no replacement |
17600 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17601 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17603 ;; Make `C-c C-x' a prefix key
17604 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17606 ;; TAB key with modifiers
17607 (org-defkey org-mode-map "\C-i" 'org-cycle)
17608 (org-defkey org-mode-map [(tab)] 'org-cycle)
17609 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17610 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17611 ;; The following line is necessary under Suse GNU/Linux
17612 (unless (featurep 'xemacs)
17613 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17614 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17615 (define-key org-mode-map [backtab] 'org-shifttab)
17617 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17618 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17619 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17621 ;; Cursor keys with modifiers
17622 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17623 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17624 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17625 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17627 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17628 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17629 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17630 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17632 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17633 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17634 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17635 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17637 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17638 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17639 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17640 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17642 ;; Babel keys
17643 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17644 (mapc (lambda (pair)
17645 (define-key org-babel-map (car pair) (cdr pair)))
17646 org-babel-key-bindings)
17648 ;;; Extra keys for tty access.
17649 ;; We only set them when really needed because otherwise the
17650 ;; menus don't show the simple keys
17652 (when (or org-use-extra-keys
17653 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17654 (not window-system))
17655 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17656 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17657 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17658 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17659 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17660 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17661 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17662 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17663 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17664 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17665 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17666 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17667 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17668 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17669 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17670 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17671 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17672 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17673 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17674 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17675 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17676 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17677 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17678 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17679 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17680 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17681 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17682 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17684 ;; All the other keys
17686 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17687 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17688 (if (boundp 'narrow-map)
17689 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17690 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17691 (if (boundp 'narrow-map)
17692 (org-defkey narrow-map "b" 'org-narrow-to-block)
17693 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17694 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17695 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17696 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17697 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17698 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17699 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17700 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17701 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17702 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17703 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17704 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17705 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17706 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17707 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17708 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17709 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17710 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17711 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17712 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17713 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17714 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17715 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17716 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17717 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17718 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17719 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17720 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17721 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17722 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17723 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17724 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17725 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17726 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17727 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17728 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17729 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17730 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17731 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17732 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17733 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17734 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17735 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17736 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17737 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17738 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17739 (org-defkey org-mode-map "\C-c^" 'org-sort)
17740 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17741 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17742 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17743 (org-defkey org-mode-map "\C-m" 'org-return)
17744 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17745 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17746 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17747 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17748 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17749 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17750 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17751 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17752 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17753 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17754 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17755 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17756 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17757 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17758 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17759 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17760 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17761 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17762 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17763 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17764 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17765 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17766 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17768 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17769 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17770 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17771 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17773 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17774 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17775 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17776 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17777 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17778 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17779 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17780 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17781 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17782 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17783 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17784 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17785 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17786 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17787 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17788 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17789 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17790 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17792 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17793 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17794 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17795 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17796 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17798 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17800 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17802 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17803 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17805 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17808 (when (featurep 'xemacs)
17809 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17812 (defconst org-speed-commands-default
17814 ("Outline Navigation")
17815 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17816 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17817 ("f" . (org-speed-move-safe 'org-forward-same-level))
17818 ("b" . (org-speed-move-safe 'org-backward-same-level))
17819 ("u" . (org-speed-move-safe 'outline-up-heading))
17820 ("j" . org-goto)
17821 ("g" . (org-refile t))
17822 ("Outline Visibility")
17823 ("c" . org-cycle)
17824 ("C" . org-shifttab)
17825 (" " . org-display-outline-path)
17826 ("Outline Structure Editing")
17827 ("U" . org-shiftmetaup)
17828 ("D" . org-shiftmetadown)
17829 ("r" . org-metaright)
17830 ("l" . org-metaleft)
17831 ("R" . org-shiftmetaright)
17832 ("L" . org-shiftmetaleft)
17833 ("i" . (progn (forward-char 1) (call-interactively
17834 'org-insert-heading-respect-content)))
17835 ("^" . org-sort)
17836 ("w" . org-refile)
17837 ("a" . org-archive-subtree-default-with-confirmation)
17838 ("." . org-mark-subtree)
17839 ("Clock Commands")
17840 ("I" . org-clock-in)
17841 ("O" . org-clock-out)
17842 ("Meta Data Editing")
17843 ("t" . org-todo)
17844 ("0" . (org-priority ?\ ))
17845 ("1" . (org-priority ?A))
17846 ("2" . (org-priority ?B))
17847 ("3" . (org-priority ?C))
17848 (";" . org-set-tags-command)
17849 ("e" . org-set-effort)
17850 ("Agenda Views etc")
17851 ("v" . org-agenda)
17852 ("/" . org-sparse-tree)
17853 ("Misc")
17854 ("o" . org-open-at-point)
17855 ("?" . org-speed-command-help)
17856 ("<" . (org-agenda-set-restriction-lock 'subtree))
17857 (">" . (org-agenda-remove-restriction-lock))
17859 "The default speed commands.")
17861 (defun org-print-speed-command (e)
17862 (if (> (length (car e)) 1)
17863 (progn
17864 (princ "\n")
17865 (princ (car e))
17866 (princ "\n")
17867 (princ (make-string (length (car e)) ?-))
17868 (princ "\n"))
17869 (princ (car e))
17870 (princ " ")
17871 (if (symbolp (cdr e))
17872 (princ (symbol-name (cdr e)))
17873 (prin1 (cdr e)))
17874 (princ "\n")))
17876 (defun org-speed-command-help ()
17877 "Show the available speed commands."
17878 (interactive)
17879 (if (not org-use-speed-commands)
17880 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17881 (with-output-to-temp-buffer "*Help*"
17882 (princ "User-defined Speed commands\n===========================\n")
17883 (mapc 'org-print-speed-command org-speed-commands-user)
17884 (princ "\n")
17885 (princ "Built-in Speed commands\n=======================\n")
17886 (mapc 'org-print-speed-command org-speed-commands-default))
17887 (with-current-buffer "*Help*"
17888 (setq truncate-lines t))))
17890 (defun org-speed-move-safe (cmd)
17891 "Execute CMD, but make sure that the cursor always ends up in a headline.
17892 If not, return to the original position and throw an error."
17893 (interactive)
17894 (let ((pos (point)))
17895 (call-interactively cmd)
17896 (unless (and (bolp) (org-at-heading-p))
17897 (goto-char pos)
17898 (error "Boundary reached while executing %s" cmd))))
17900 (defvar org-self-insert-command-undo-counter 0)
17902 (defvar org-table-auto-blank-field) ; defined in org-table.el
17903 (defvar org-speed-command nil)
17905 (defun org-speed-command-default-hook (keys)
17906 "Hook for activating single-letter speed commands.
17907 `org-speed-commands-default' specifies a minimal command set.
17908 Use `org-speed-commands-user' for further customization."
17909 (when (or (and (bolp) (looking-at org-outline-regexp))
17910 (and (functionp org-use-speed-commands)
17911 (funcall org-use-speed-commands)))
17912 (cdr (assoc keys (append org-speed-commands-user
17913 org-speed-commands-default)))))
17915 (defun org-babel-speed-command-hook (keys)
17916 "Hook for activating single-letter code block commands."
17917 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17918 (cdr (assoc keys org-babel-key-bindings))))
17920 (defcustom org-speed-command-hook
17921 '(org-speed-command-default-hook org-babel-speed-command-hook)
17922 "Hook for activating speed commands at strategic locations.
17923 Hook functions are called in sequence until a valid handler is
17924 found.
17926 Each hook takes a single argument, a user-pressed command key
17927 which is also a `self-insert-command' from the global map.
17929 Within the hook, examine the cursor position and the command key
17930 and return nil or a valid handler as appropriate. Handler could
17931 be one of an interactive command, a function, or a form.
17933 Set `org-use-speed-commands' to non-nil value to enable this
17934 hook. The default setting is `org-speed-command-default-hook'."
17935 :group 'org-structure
17936 :version "24.1"
17937 :type 'hook)
17939 (defun org-self-insert-command (N)
17940 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17941 If the cursor is in a table looking at whitespace, the whitespace is
17942 overwritten, and the table is not marked as requiring realignment."
17943 (interactive "p")
17944 (org-check-before-invisible-edit 'insert)
17945 (cond
17946 ((and org-use-speed-commands
17947 (setq org-speed-command
17948 (run-hook-with-args-until-success
17949 'org-speed-command-hook (this-command-keys))))
17950 (cond
17951 ((commandp org-speed-command)
17952 (setq this-command org-speed-command)
17953 (call-interactively org-speed-command))
17954 ((functionp org-speed-command)
17955 (funcall org-speed-command))
17956 ((and org-speed-command (listp org-speed-command))
17957 (eval org-speed-command))
17958 (t (let (org-use-speed-commands)
17959 (call-interactively 'org-self-insert-command)))))
17960 ((and
17961 (org-table-p)
17962 (progn
17963 ;; check if we blank the field, and if that triggers align
17964 (and (featurep 'org-table) org-table-auto-blank-field
17965 (member last-command
17966 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17967 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17968 ;; got extra space, this field does not determine column width
17969 (let (org-table-may-need-update) (org-table-blank-field))
17970 ;; no extra space, this field may determine column width
17971 (org-table-blank-field)))
17973 (eq N 1)
17974 (looking-at "[^|\n]* |"))
17975 (let (org-table-may-need-update)
17976 (goto-char (1- (match-end 0)))
17977 (backward-delete-char 1)
17978 (goto-char (match-beginning 0))
17979 (self-insert-command N)))
17981 (setq org-table-may-need-update t)
17982 (self-insert-command N)
17983 (org-fix-tags-on-the-fly)
17984 (if org-self-insert-cluster-for-undo
17985 (if (not (eq last-command 'org-self-insert-command))
17986 (setq org-self-insert-command-undo-counter 1)
17987 (if (>= org-self-insert-command-undo-counter 20)
17988 (setq org-self-insert-command-undo-counter 1)
17989 (and (> org-self-insert-command-undo-counter 0)
17990 buffer-undo-list (listp buffer-undo-list)
17991 (not (cadr buffer-undo-list)) ; remove nil entry
17992 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17993 (setq org-self-insert-command-undo-counter
17994 (1+ org-self-insert-command-undo-counter))))))))
17996 (defun org-check-before-invisible-edit (kind)
17997 "Check is editing if kind KIND would be dangerous with invisible text around.
17998 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17999 ;; First, try to get out of here as quickly as possible, to reduce overhead
18000 (if (and org-catch-invisible-edits
18001 (or (not (boundp 'visible-mode)) (not visible-mode))
18002 (or (get-char-property (point) 'invisible)
18003 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18004 ;; OK, we need to take a closer look
18005 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18006 (invisible-before-point (if (bobp) nil (get-char-property
18007 (1- (point)) 'invisible)))
18008 (border-and-ok-direction
18010 ;; Check if we are acting predictably before invisible text
18011 (and invisible-at-point (not invisible-before-point)
18012 (memq kind '(insert delete-backward)))
18013 ;; Check if we are acting predictably after invisible text
18014 ;; This works not well, and I have turned it off. It seems
18015 ;; better to always show and stop after invisible text.
18016 ;; (and (not invisible-at-point) invisible-before-point
18017 ;; (memq kind '(insert delete)))
18020 (when (or (memq invisible-at-point '(outline org-hide-block))
18021 (memq invisible-before-point '(outline org-hide-block)))
18022 (if (eq org-catch-invisible-edits 'error)
18023 (error "Editing in invisible areas is prohibited - make visible first"))
18024 ;; Make the area visible
18025 (save-excursion
18026 (if invisible-before-point
18027 (goto-char (previous-single-char-property-change
18028 (point) 'invisible)))
18029 (org-cycle))
18030 (cond
18031 ((eq org-catch-invisible-edits 'show)
18032 ;; That's it, we do the edit after showing
18033 (message
18034 "Unfolding invisible region around point before editing")
18035 (sit-for 1))
18036 ((and (eq org-catch-invisible-edits 'smart)
18037 border-and-ok-direction)
18038 (message "Unfolding invisible region around point before editing"))
18040 ;; Don't do the edit, make the user repeat it in full visibility
18041 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
18043 (defun org-fix-tags-on-the-fly ()
18044 (when (and (equal (char-after (point-at-bol)) ?*)
18045 (org-at-heading-p))
18046 (org-align-tags-here org-tags-column)))
18048 (defun org-delete-backward-char (N)
18049 "Like `delete-backward-char', insert whitespace at field end in tables.
18050 When deleting backwards, in tables this function will insert whitespace in
18051 front of the next \"|\" separator, to keep the table aligned. The table will
18052 still be marked for re-alignment if the field did fill the entire column,
18053 because, in this case the deletion might narrow the column."
18054 (interactive "p")
18055 (org-check-before-invisible-edit 'delete-backward)
18056 (if (and (org-table-p)
18057 (eq N 1)
18058 (string-match "|" (buffer-substring (point-at-bol) (point)))
18059 (looking-at ".*?|"))
18060 (let ((pos (point))
18061 (noalign (looking-at "[^|\n\r]* |"))
18062 (c org-table-may-need-update))
18063 (backward-delete-char N)
18064 (if (not overwrite-mode)
18065 (progn
18066 (skip-chars-forward "^|")
18067 (insert " ")
18068 (goto-char (1- pos))))
18069 ;; noalign: if there were two spaces at the end, this field
18070 ;; does not determine the width of the column.
18071 (if noalign (setq org-table-may-need-update c)))
18072 (backward-delete-char N)
18073 (org-fix-tags-on-the-fly)))
18075 (defun org-delete-char (N)
18076 "Like `delete-char', but insert whitespace at field end in tables.
18077 When deleting characters, in tables this function will insert whitespace in
18078 front of the next \"|\" separator, to keep the table aligned. The table will
18079 still be marked for re-alignment if the field did fill the entire column,
18080 because, in this case the deletion might narrow the column."
18081 (interactive "p")
18082 (org-check-before-invisible-edit 'delete)
18083 (if (and (org-table-p)
18084 (not (bolp))
18085 (not (= (char-after) ?|))
18086 (eq N 1))
18087 (if (looking-at ".*?|")
18088 (let ((pos (point))
18089 (noalign (looking-at "[^|\n\r]* |"))
18090 (c org-table-may-need-update))
18091 (replace-match (concat
18092 (substring (match-string 0) 1 -1)
18093 " |"))
18094 (goto-char pos)
18095 ;; noalign: if there were two spaces at the end, this field
18096 ;; does not determine the width of the column.
18097 (if noalign (setq org-table-may-need-update c)))
18098 (delete-char N))
18099 (delete-char N)
18100 (org-fix-tags-on-the-fly)))
18102 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18103 (put 'org-self-insert-command 'delete-selection t)
18104 (put 'orgtbl-self-insert-command 'delete-selection t)
18105 (put 'org-delete-char 'delete-selection 'supersede)
18106 (put 'org-delete-backward-char 'delete-selection 'supersede)
18107 (put 'org-yank 'delete-selection 'yank)
18109 ;; Make `flyspell-mode' delay after some commands
18110 (put 'org-self-insert-command 'flyspell-delayed t)
18111 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18112 (put 'org-delete-char 'flyspell-delayed t)
18113 (put 'org-delete-backward-char 'flyspell-delayed t)
18115 ;; Make pabbrev-mode expand after org-mode commands
18116 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18117 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18119 ;; How to do this: Measure non-white length of current string
18120 ;; If equal to column width, we should realign.
18122 (defun org-remap (map &rest commands)
18123 "In MAP, remap the functions given in COMMANDS.
18124 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18125 (let (new old)
18126 (while commands
18127 (setq old (pop commands) new (pop commands))
18128 (if (fboundp 'command-remapping)
18129 (org-defkey map (vector 'remap old) new)
18130 (substitute-key-definition old new map global-map)))))
18132 (when (eq org-enable-table-editor 'optimized)
18133 ;; If the user wants maximum table support, we need to hijack
18134 ;; some standard editing functions
18135 (org-remap org-mode-map
18136 'self-insert-command 'org-self-insert-command
18137 'delete-char 'org-delete-char
18138 'delete-backward-char 'org-delete-backward-char)
18139 (org-defkey org-mode-map "|" 'org-force-self-insert))
18141 (defvar org-ctrl-c-ctrl-c-hook nil
18142 "Hook for functions attaching themselves to `C-c C-c'.
18144 This can be used to add additional functionality to the C-c C-c
18145 key which executes context-dependent commands. This hook is run
18146 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18147 run after the last test.
18149 Each function will be called with no arguments. The function
18150 must check if the context is appropriate for it to act. If yes,
18151 it should do its thing and then return a non-nil value. If the
18152 context is wrong, just do nothing and return nil.")
18154 (defvar org-ctrl-c-ctrl-c-final-hook nil
18155 "Hook for functions attaching themselves to `C-c C-c'.
18157 This can be used to add additional functionality to the C-c C-c
18158 key which executes context-dependent commands. This hook is run
18159 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18160 before the first test.
18162 Each function will be called with no arguments. The function
18163 must check if the context is appropriate for it to act. If yes,
18164 it should do its thing and then return a non-nil value. If the
18165 context is wrong, just do nothing and return nil.")
18167 (defvar org-tab-first-hook nil
18168 "Hook for functions to attach themselves to TAB.
18169 See `org-ctrl-c-ctrl-c-hook' for more information.
18170 This hook runs as the first action when TAB is pressed, even before
18171 `org-cycle' messes around with the `outline-regexp' to cater for
18172 inline tasks and plain list item folding.
18173 If any function in this hook returns t, any other actions that
18174 would have been caused by TAB (such as table field motion or visibility
18175 cycling) will not occur.")
18177 (defvar org-tab-after-check-for-table-hook nil
18178 "Hook for functions to attach themselves to TAB.
18179 See `org-ctrl-c-ctrl-c-hook' for more information.
18180 This hook runs after it has been established that the cursor is not in a
18181 table, but before checking if the cursor is in a headline or if global cycling
18182 should be done.
18183 If any function in this hook returns t, not other actions like visibility
18184 cycling will be done.")
18186 (defvar org-tab-after-check-for-cycling-hook nil
18187 "Hook for functions to attach themselves to TAB.
18188 See `org-ctrl-c-ctrl-c-hook' for more information.
18189 This hook runs after it has been established that not table field motion and
18190 not visibility should be done because of current context. This is probably
18191 the place where a package like yasnippets can hook in.")
18193 (defvar org-tab-before-tab-emulation-hook nil
18194 "Hook for functions to attach themselves to TAB.
18195 See `org-ctrl-c-ctrl-c-hook' for more information.
18196 This hook runs after every other options for TAB have been exhausted, but
18197 before indentation and \t insertion takes place.")
18199 (defvar org-metaleft-hook nil
18200 "Hook for functions attaching themselves to `M-left'.
18201 See `org-ctrl-c-ctrl-c-hook' for more information.")
18202 (defvar org-metaright-hook nil
18203 "Hook for functions attaching themselves to `M-right'.
18204 See `org-ctrl-c-ctrl-c-hook' for more information.")
18205 (defvar org-metaup-hook nil
18206 "Hook for functions attaching themselves to `M-up'.
18207 See `org-ctrl-c-ctrl-c-hook' for more information.")
18208 (defvar org-metadown-hook nil
18209 "Hook for functions attaching themselves to `M-down'.
18210 See `org-ctrl-c-ctrl-c-hook' for more information.")
18211 (defvar org-shiftmetaleft-hook nil
18212 "Hook for functions attaching themselves to `M-S-left'.
18213 See `org-ctrl-c-ctrl-c-hook' for more information.")
18214 (defvar org-shiftmetaright-hook nil
18215 "Hook for functions attaching themselves to `M-S-right'.
18216 See `org-ctrl-c-ctrl-c-hook' for more information.")
18217 (defvar org-shiftmetaup-hook nil
18218 "Hook for functions attaching themselves to `M-S-up'.
18219 See `org-ctrl-c-ctrl-c-hook' for more information.")
18220 (defvar org-shiftmetadown-hook nil
18221 "Hook for functions attaching themselves to `M-S-down'.
18222 See `org-ctrl-c-ctrl-c-hook' for more information.")
18223 (defvar org-metareturn-hook nil
18224 "Hook for functions attaching themselves to `M-RET'.
18225 See `org-ctrl-c-ctrl-c-hook' for more information.")
18226 (defvar org-shiftup-hook nil
18227 "Hook for functions attaching themselves to `S-up'.
18228 See `org-ctrl-c-ctrl-c-hook' for more information.")
18229 (defvar org-shiftup-final-hook nil
18230 "Hook for functions attaching themselves to `S-up'.
18231 This one runs after all other options except shift-select have been excluded.
18232 See `org-ctrl-c-ctrl-c-hook' for more information.")
18233 (defvar org-shiftdown-hook nil
18234 "Hook for functions attaching themselves to `S-down'.
18235 See `org-ctrl-c-ctrl-c-hook' for more information.")
18236 (defvar org-shiftdown-final-hook nil
18237 "Hook for functions attaching themselves to `S-down'.
18238 This one runs after all other options except shift-select have been excluded.
18239 See `org-ctrl-c-ctrl-c-hook' for more information.")
18240 (defvar org-shiftleft-hook nil
18241 "Hook for functions attaching themselves to `S-left'.
18242 See `org-ctrl-c-ctrl-c-hook' for more information.")
18243 (defvar org-shiftleft-final-hook nil
18244 "Hook for functions attaching themselves to `S-left'.
18245 This one runs after all other options except shift-select have been excluded.
18246 See `org-ctrl-c-ctrl-c-hook' for more information.")
18247 (defvar org-shiftright-hook nil
18248 "Hook for functions attaching themselves to `S-right'.
18249 See `org-ctrl-c-ctrl-c-hook' for more information.")
18250 (defvar org-shiftright-final-hook nil
18251 "Hook for functions attaching themselves to `S-right'.
18252 This one runs after all other options except shift-select have been excluded.
18253 See `org-ctrl-c-ctrl-c-hook' for more information.")
18255 (defun org-modifier-cursor-error ()
18256 "Throw an error, a modified cursor command was applied in wrong context."
18257 (error "This command is active in special context like tables, headlines or items"))
18259 (defun org-shiftselect-error ()
18260 "Throw an error because Shift-Cursor command was applied in wrong context."
18261 (if (and (boundp 'shift-select-mode) shift-select-mode)
18262 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18263 (error "This command works only in special context like headlines or timestamps")))
18265 (defun org-call-for-shift-select (cmd)
18266 (let ((this-command-keys-shift-translated t))
18267 (call-interactively cmd)))
18269 (defun org-shifttab (&optional arg)
18270 "Global visibility cycling or move to previous table field.
18271 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18272 on context.
18273 See the individual commands for more information."
18274 (interactive "P")
18275 (cond
18276 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18277 ((integerp arg)
18278 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18279 (message "Content view to level: %d" arg)
18280 (org-content (prefix-numeric-value arg2))
18281 (setq org-cycle-global-status 'overview)))
18282 (t (call-interactively 'org-global-cycle))))
18284 (defun org-shiftmetaleft ()
18285 "Promote subtree or delete table column.
18286 Calls `org-promote-subtree', `org-outdent-item-tree', or
18287 `org-table-delete-column', depending on context. See the
18288 individual commands for more information."
18289 (interactive)
18290 (cond
18291 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18292 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18293 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18294 ((if (not (org-region-active-p)) (org-at-item-p)
18295 (save-excursion (goto-char (region-beginning))
18296 (org-at-item-p)))
18297 (call-interactively 'org-outdent-item-tree))
18298 (t (org-modifier-cursor-error))))
18300 (defun org-shiftmetaright ()
18301 "Demote subtree or insert table column.
18302 Calls `org-demote-subtree', `org-indent-item-tree', or
18303 `org-table-insert-column', depending on context. See the
18304 individual commands for more information."
18305 (interactive)
18306 (cond
18307 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18308 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18309 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18310 ((if (not (org-region-active-p)) (org-at-item-p)
18311 (save-excursion (goto-char (region-beginning))
18312 (org-at-item-p)))
18313 (call-interactively 'org-indent-item-tree))
18314 (t (org-modifier-cursor-error))))
18316 (defun org-shiftmetaup (&optional arg)
18317 "Move subtree up or kill table row.
18318 Calls `org-move-subtree-up' or `org-table-kill-row' or
18319 `org-move-item-up' depending on context. See the individual commands
18320 for more information."
18321 (interactive "P")
18322 (cond
18323 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18324 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18325 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18326 ((org-at-item-p) (call-interactively 'org-move-item-up))
18327 (t (org-modifier-cursor-error))))
18329 (defun org-shiftmetadown (&optional arg)
18330 "Move subtree down or insert table row.
18331 Calls `org-move-subtree-down' or `org-table-insert-row' or
18332 `org-move-item-down', depending on context. See the individual
18333 commands for more information."
18334 (interactive "P")
18335 (cond
18336 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18337 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18338 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18339 ((org-at-item-p) (call-interactively 'org-move-item-down))
18340 (t (org-modifier-cursor-error))))
18342 (defsubst org-hidden-tree-error ()
18343 (error
18344 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18346 (defun org-metaleft (&optional arg)
18347 "Promote heading or move table column to left.
18348 Calls `org-do-promote' or `org-table-move-column', depending on context.
18349 With no specific context, calls the Emacs default `backward-word'.
18350 See the individual commands for more information."
18351 (interactive "P")
18352 (cond
18353 ((run-hook-with-args-until-success 'org-metaleft-hook))
18354 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18355 ((org-with-limited-levels
18356 (or (org-at-heading-p)
18357 (and (org-region-active-p)
18358 (save-excursion
18359 (goto-char (region-beginning))
18360 (org-at-heading-p)))))
18361 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18362 (call-interactively 'org-do-promote))
18363 ;; At an inline task.
18364 ((org-at-heading-p)
18365 (call-interactively 'org-inlinetask-promote))
18366 ((or (org-at-item-p)
18367 (and (org-region-active-p)
18368 (save-excursion
18369 (goto-char (region-beginning))
18370 (org-at-item-p))))
18371 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18372 (call-interactively 'org-outdent-item))
18373 (t (call-interactively 'backward-word))))
18375 (defun org-metaright (&optional arg)
18376 "Demote a subtree, a list item or move table column to right.
18377 In front of a drawer or a block keyword, indent it correctly.
18378 With no specific context, calls the Emacs default `forward-word'.
18379 See the individual commands for more information."
18380 (interactive "P")
18381 (cond
18382 ((run-hook-with-args-until-success 'org-metaright-hook))
18383 ((org-at-table-p) (call-interactively 'org-table-move-column))
18384 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18385 ((org-at-block-p) (call-interactively 'org-indent-block))
18386 ((org-with-limited-levels
18387 (or (org-at-heading-p)
18388 (and (org-region-active-p)
18389 (save-excursion
18390 (goto-char (region-beginning))
18391 (org-at-heading-p)))))
18392 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18393 (call-interactively 'org-do-demote))
18394 ;; At an inline task.
18395 ((org-at-heading-p)
18396 (call-interactively 'org-inlinetask-demote))
18397 ((or (org-at-item-p)
18398 (and (org-region-active-p)
18399 (save-excursion
18400 (goto-char (region-beginning))
18401 (org-at-item-p))))
18402 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18403 (call-interactively 'org-indent-item))
18404 (t (call-interactively 'forward-word))))
18406 (defun org-check-for-hidden (what)
18407 "Check if there are hidden headlines/items in the current visual line.
18408 WHAT can be either `headlines' or `items'. If the current line is
18409 an outline or item heading and it has a folded subtree below it,
18410 this function returns t, nil otherwise."
18411 (let ((re (cond
18412 ((eq what 'headlines) org-outline-regexp-bol)
18413 ((eq what 'items) (org-item-beginning-re))
18414 (t (error "This should not happen"))))
18415 beg end)
18416 (save-excursion
18417 (catch 'exit
18418 (unless (org-region-active-p)
18419 (setq beg (point-at-bol))
18420 (beginning-of-line 2)
18421 (while (and (not (eobp)) ;; this is like `next-line'
18422 (get-char-property (1- (point)) 'invisible))
18423 (beginning-of-line 2))
18424 (setq end (point))
18425 (goto-char beg)
18426 (goto-char (point-at-eol))
18427 (setq end (max end (point)))
18428 (while (re-search-forward re end t)
18429 (if (get-char-property (match-beginning 0) 'invisible)
18430 (throw 'exit t))))
18431 nil))))
18433 (defun org-metaup (&optional arg)
18434 "Move subtree up or move table row up.
18435 Calls `org-move-subtree-up' or `org-table-move-row' or
18436 `org-move-item-up', depending on context. See the individual commands
18437 for more information."
18438 (interactive "P")
18439 (cond
18440 ((run-hook-with-args-until-success 'org-metaup-hook))
18441 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18442 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18443 ((org-at-item-p) (call-interactively 'org-move-item-up))
18444 (t (transpose-lines 1) (beginning-of-line -1))))
18446 (defun org-metadown (&optional arg)
18447 "Move subtree down or move table row down.
18448 Calls `org-move-subtree-down' or `org-table-move-row' or
18449 `org-move-item-down', depending on context. See the individual
18450 commands for more information."
18451 (interactive "P")
18452 (cond
18453 ((run-hook-with-args-until-success 'org-metadown-hook))
18454 ((org-at-table-p) (call-interactively 'org-table-move-row))
18455 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18456 ((org-at-item-p) (call-interactively 'org-move-item-down))
18457 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18459 (defun org-shiftup (&optional arg)
18460 "Increase item in timestamp or increase priority of current headline.
18461 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18462 depending on context. See the individual commands for more information."
18463 (interactive "P")
18464 (cond
18465 ((run-hook-with-args-until-success 'org-shiftup-hook))
18466 ((and org-support-shift-select (org-region-active-p))
18467 (org-call-for-shift-select 'previous-line))
18468 ((org-at-timestamp-p t)
18469 (call-interactively (if org-edit-timestamp-down-means-later
18470 'org-timestamp-down 'org-timestamp-up)))
18471 ((and (not (eq org-support-shift-select 'always))
18472 org-enable-priority-commands
18473 (org-at-heading-p))
18474 (call-interactively 'org-priority-up))
18475 ((and (not org-support-shift-select) (org-at-item-p))
18476 (call-interactively 'org-previous-item))
18477 ((org-clocktable-try-shift 'up arg))
18478 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18479 (org-support-shift-select
18480 (org-call-for-shift-select 'previous-line))
18481 (t (org-shiftselect-error))))
18483 (defun org-shiftdown (&optional arg)
18484 "Decrease item in timestamp or decrease priority of current headline.
18485 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18486 depending on context. See the individual commands for more information."
18487 (interactive "P")
18488 (cond
18489 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18490 ((and org-support-shift-select (org-region-active-p))
18491 (org-call-for-shift-select 'next-line))
18492 ((org-at-timestamp-p t)
18493 (call-interactively (if org-edit-timestamp-down-means-later
18494 'org-timestamp-up 'org-timestamp-down)))
18495 ((and (not (eq org-support-shift-select 'always))
18496 org-enable-priority-commands
18497 (org-at-heading-p))
18498 (call-interactively 'org-priority-down))
18499 ((and (not org-support-shift-select) (org-at-item-p))
18500 (call-interactively 'org-next-item))
18501 ((org-clocktable-try-shift 'down arg))
18502 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18503 (org-support-shift-select
18504 (org-call-for-shift-select 'next-line))
18505 (t (org-shiftselect-error))))
18507 (defun org-shiftright (&optional arg)
18508 "Cycle the thing at point or in the current line, depending on context.
18509 Depending on context, this does one of the following:
18511 - switch a timestamp at point one day into the future
18512 - on a headline, switch to the next TODO keyword.
18513 - on an item, switch entire list to the next bullet type
18514 - on a property line, switch to the next allowed value
18515 - on a clocktable definition line, move time block into the future"
18516 (interactive "P")
18517 (cond
18518 ((run-hook-with-args-until-success 'org-shiftright-hook))
18519 ((and org-support-shift-select (org-region-active-p))
18520 (org-call-for-shift-select 'forward-char))
18521 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18522 ((and (not (eq org-support-shift-select 'always))
18523 (org-at-heading-p))
18524 (let ((org-inhibit-logging
18525 (not org-treat-S-cursor-todo-selection-as-state-change))
18526 (org-inhibit-blocking
18527 (not org-treat-S-cursor-todo-selection-as-state-change)))
18528 (org-call-with-arg 'org-todo 'right)))
18529 ((or (and org-support-shift-select
18530 (not (eq org-support-shift-select 'always))
18531 (org-at-item-bullet-p))
18532 (and (not org-support-shift-select) (org-at-item-p)))
18533 (org-call-with-arg 'org-cycle-list-bullet nil))
18534 ((and (not (eq org-support-shift-select 'always))
18535 (org-at-property-p))
18536 (call-interactively 'org-property-next-allowed-value))
18537 ((org-clocktable-try-shift 'right arg))
18538 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18539 (org-support-shift-select
18540 (org-call-for-shift-select 'forward-char))
18541 (t (org-shiftselect-error))))
18543 (defun org-shiftleft (&optional arg)
18544 "Cycle the thing at point or in the current line, depending on context.
18545 Depending on context, this does one of the following:
18547 - switch a timestamp at point one day into the past
18548 - on a headline, switch to the previous TODO keyword.
18549 - on an item, switch entire list to the previous bullet type
18550 - on a property line, switch to the previous allowed value
18551 - on a clocktable definition line, move time block into the past"
18552 (interactive "P")
18553 (cond
18554 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18555 ((and org-support-shift-select (org-region-active-p))
18556 (org-call-for-shift-select 'backward-char))
18557 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18558 ((and (not (eq org-support-shift-select 'always))
18559 (org-at-heading-p))
18560 (let ((org-inhibit-logging
18561 (not org-treat-S-cursor-todo-selection-as-state-change))
18562 (org-inhibit-blocking
18563 (not org-treat-S-cursor-todo-selection-as-state-change)))
18564 (org-call-with-arg 'org-todo 'left)))
18565 ((or (and org-support-shift-select
18566 (not (eq org-support-shift-select 'always))
18567 (org-at-item-bullet-p))
18568 (and (not org-support-shift-select) (org-at-item-p)))
18569 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18570 ((and (not (eq org-support-shift-select 'always))
18571 (org-at-property-p))
18572 (call-interactively 'org-property-previous-allowed-value))
18573 ((org-clocktable-try-shift 'left arg))
18574 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18575 (org-support-shift-select
18576 (org-call-for-shift-select 'backward-char))
18577 (t (org-shiftselect-error))))
18579 (defun org-shiftcontrolright ()
18580 "Switch to next TODO set."
18581 (interactive)
18582 (cond
18583 ((and org-support-shift-select (org-region-active-p))
18584 (org-call-for-shift-select 'forward-word))
18585 ((and (not (eq org-support-shift-select 'always))
18586 (org-at-heading-p))
18587 (org-call-with-arg 'org-todo 'nextset))
18588 (org-support-shift-select
18589 (org-call-for-shift-select 'forward-word))
18590 (t (org-shiftselect-error))))
18592 (defun org-shiftcontrolleft ()
18593 "Switch to previous TODO set."
18594 (interactive)
18595 (cond
18596 ((and org-support-shift-select (org-region-active-p))
18597 (org-call-for-shift-select 'backward-word))
18598 ((and (not (eq org-support-shift-select 'always))
18599 (org-at-heading-p))
18600 (org-call-with-arg 'org-todo 'previousset))
18601 (org-support-shift-select
18602 (org-call-for-shift-select 'backward-word))
18603 (t (org-shiftselect-error))))
18605 (defun org-shiftcontrolup ()
18606 "Change timestamps synchronously up in CLOCK log lines."
18607 (interactive)
18608 (cond ((and (not org-support-shift-select)
18609 (org-at-clock-log-p)
18610 (org-at-timestamp-p t))
18611 (org-clock-timestamps-up))
18612 (t (org-shiftselect-error))))
18614 (defun org-shiftcontroldown ()
18615 "Change timestamps synchronously down in CLOCK log lines."
18616 (interactive)
18617 (cond ((and (not org-support-shift-select)
18618 (org-at-clock-log-p)
18619 (org-at-timestamp-p t))
18620 (org-clock-timestamps-down))
18621 (t (org-shiftselect-error))))
18623 (defun org-ctrl-c-ret ()
18624 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18625 (interactive)
18626 (cond
18627 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18628 (t (call-interactively 'org-insert-heading))))
18630 (defun org-find-visible ()
18631 (let ((s (point)))
18632 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18633 (get-char-property s 'invisible)))
18635 (defun org-find-invisible ()
18636 (let ((s (point)))
18637 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18638 (not (get-char-property s 'invisible))))
18641 (defun org-copy-visible (beg end)
18642 "Copy the visible parts of the region."
18643 (interactive "r")
18644 (let (snippets s)
18645 (save-excursion
18646 (save-restriction
18647 (narrow-to-region beg end)
18648 (setq s (goto-char (point-min)))
18649 (while (not (= (point) (point-max)))
18650 (goto-char (org-find-invisible))
18651 (push (buffer-substring s (point)) snippets)
18652 (setq s (goto-char (org-find-visible))))))
18653 (kill-new (apply 'concat (nreverse snippets)))))
18655 (defun org-copy-special ()
18656 "Copy region in table or copy current subtree.
18657 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18658 See the individual commands for more information."
18659 (interactive)
18660 (call-interactively
18661 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18663 (defun org-cut-special ()
18664 "Cut region in table or cut current subtree.
18665 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18666 See the individual commands for more information."
18667 (interactive)
18668 (call-interactively
18669 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18671 (defun org-paste-special (arg)
18672 "Paste rectangular region into table, or past subtree relative to level.
18673 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18674 See the individual commands for more information."
18675 (interactive "P")
18676 (if (org-at-table-p)
18677 (org-table-paste-rectangle)
18678 (org-paste-subtree arg)))
18680 (defun org-edit-special (&optional arg)
18681 "Call a special editor for the stuff at point.
18682 When at a table, call the formula editor with `org-table-edit-formulas'.
18683 When at the first line of an src example, call `org-edit-src-code'.
18684 When in an #+include line, visit the include file. Otherwise call
18685 `ffap' to visit the file at point."
18686 (interactive)
18687 ;; possibly prep session before editing source
18688 (when arg
18689 (let* ((info (org-babel-get-src-block-info))
18690 (lang (nth 0 info))
18691 (params (nth 2 info))
18692 (session (cdr (assoc :session params))))
18693 (when (and info session) ;; we are in a source-code block with a session
18694 (funcall
18695 (intern (concat "org-babel-prep-session:" lang)) session params))))
18696 (cond ;; proceed with `org-edit-special'
18697 ((save-excursion
18698 (beginning-of-line 1)
18699 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18700 (find-file (org-trim (match-string 1))))
18701 ((org-edit-src-code))
18702 ((org-edit-fixed-width-region))
18703 ((org-at-table.el-p)
18704 (org-edit-src-code))
18705 ((or (org-at-table-p)
18706 (save-excursion
18707 (beginning-of-line 1)
18708 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18709 (call-interactively 'org-table-edit-formulas))
18710 (t (call-interactively 'ffap))))
18712 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18713 (defun org-ctrl-c-ctrl-c (&optional arg)
18714 "Set tags in headline, or update according to changed information at point.
18716 This command does many different things, depending on context:
18718 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18719 this is what we do.
18721 - If the cursor is on a statistics cookie, update it.
18723 - If the cursor is in a headline, prompt for tags and insert them
18724 into the current line, aligned to `org-tags-column'. When called
18725 with prefix arg, realign all tags in the current buffer.
18727 - If the cursor is in one of the special #+KEYWORD lines, this
18728 triggers scanning the buffer for these lines and updating the
18729 information.
18731 - If the cursor is inside a table, realign the table. This command
18732 works even if the automatic table editor has been turned off.
18734 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18735 the entire table.
18737 - If the cursor is at a footnote reference or definition, jump to
18738 the corresponding definition or references, respectively.
18740 - If the cursor is a the beginning of a dynamic block, update it.
18742 - If the current buffer is a capture buffer, close note and file it.
18744 - If the cursor is on a <<<target>>>, update radio targets and
18745 corresponding links in this buffer.
18747 - If the cursor is on a numbered item in a plain list, renumber the
18748 ordered list.
18750 - If the cursor is on a checkbox, toggle it.
18752 - If the cursor is on a code block, evaluate it. The variable
18753 `org-confirm-babel-evaluate' can be used to control prompting
18754 before code block evaluation, by default every code block
18755 evaluation requires confirmation. Code block evaluation can be
18756 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18757 (interactive "P")
18758 (let ((org-enable-table-editor t))
18759 (cond
18760 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18761 org-occur-highlights
18762 org-latex-fragment-image-overlays)
18763 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18764 (org-remove-occur-highlights)
18765 (org-remove-latex-fragment-image-overlays)
18766 (message "Temporary highlights/overlays removed from current buffer"))
18767 ((and (local-variable-p 'org-finish-function (current-buffer))
18768 (fboundp org-finish-function))
18769 (funcall org-finish-function))
18770 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18771 ((org-in-regexp org-ts-regexp-both)
18772 (org-timestamp-change 0 'day))
18773 ((or (looking-at org-property-start-re)
18774 (org-at-property-p))
18775 (call-interactively 'org-property-action))
18776 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18777 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18778 (or (org-at-heading-p) (org-at-item-p)))
18779 (call-interactively 'org-update-statistics-cookies))
18780 ((org-at-heading-p) (call-interactively 'org-set-tags))
18781 ((org-at-table.el-p)
18782 (message "Use C-c ' to edit table.el tables"))
18783 ((org-at-table-p)
18784 (org-table-maybe-eval-formula)
18785 (if arg
18786 (call-interactively 'org-table-recalculate)
18787 (org-table-maybe-recalculate-line))
18788 (call-interactively 'org-table-align)
18789 (orgtbl-send-table 'maybe))
18790 ((or (org-footnote-at-reference-p)
18791 (org-footnote-at-definition-p))
18792 (call-interactively 'org-footnote-action))
18793 ((org-at-item-checkbox-p)
18794 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18795 ;; list only if at top item.
18796 (let* ((cbox (match-string 1))
18797 (struct (org-list-struct))
18798 (old-struct (copy-tree struct))
18799 (parents (org-list-parents-alist struct))
18800 (orderedp (org-entry-get nil "ORDERED"))
18801 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18802 block-item)
18803 ;; Use a light version of `org-toggle-checkbox' to avoid
18804 ;; computing list structure twice.
18805 (let ((new-box (cond
18806 ((equal arg '(16)) "[-]")
18807 ((equal arg '(4)) nil)
18808 ((equal "[X]" cbox) "[ ]")
18809 (t "[X]"))))
18810 (if (and firstp arg)
18811 ;; If at first item of sub-list, remove check-box from
18812 ;; every item at the same level.
18813 (mapc
18814 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18815 (org-list-get-all-items
18816 (point-at-bol) struct (org-list-prevs-alist struct)))
18817 (org-list-set-checkbox (point-at-bol) struct new-box)))
18818 ;; Replicate `org-list-write-struct', while grabbing a return
18819 ;; value from `org-list-struct-fix-box'.
18820 (org-list-struct-fix-ind struct parents 2)
18821 (org-list-struct-fix-item-end struct)
18822 (let ((prevs (org-list-prevs-alist struct)))
18823 (org-list-struct-fix-bul struct prevs)
18824 (org-list-struct-fix-ind struct parents)
18825 (setq block-item
18826 (org-list-struct-fix-box struct parents prevs orderedp)))
18827 (org-list-struct-apply-struct struct old-struct)
18828 (org-update-checkbox-count-maybe)
18829 (when block-item
18830 (message
18831 "Checkboxes were removed due to unchecked box at line %d"
18832 (org-current-line block-item)))
18833 (when firstp (org-list-send-list 'maybe))))
18834 ((org-at-item-p)
18835 ;; Cursor at an item: repair list. Do checkbox related actions
18836 ;; only if function was called with an argument. Send list only
18837 ;; if at top item.
18838 (let* ((struct (org-list-struct))
18839 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18840 old-struct)
18841 (when arg
18842 (setq old-struct (copy-tree struct))
18843 (if firstp
18844 ;; If at first item of sub-list, add check-box to every
18845 ;; item at the same level.
18846 (mapc
18847 (lambda (pos)
18848 (unless (org-list-get-checkbox pos struct)
18849 (org-list-set-checkbox pos struct "[ ]")))
18850 (org-list-get-all-items
18851 (point-at-bol) struct (org-list-prevs-alist struct)))
18852 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18853 (org-list-write-struct
18854 struct (org-list-parents-alist struct) old-struct)
18855 (when arg (org-update-checkbox-count-maybe))
18856 (when firstp (org-list-send-list 'maybe))))
18857 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18858 ;; Dynamic block
18859 (beginning-of-line 1)
18860 (save-excursion (org-update-dblock)))
18861 ((save-excursion
18862 (let ((case-fold-search t))
18863 (beginning-of-line 1)
18864 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
18865 (cond
18866 ((or (equal (match-string 1) "TBLFM")
18867 (equal (match-string 1) "tblfm"))
18868 ;; Recalculate the table before this line
18869 (save-excursion
18870 (beginning-of-line 1)
18871 (skip-chars-backward " \r\n\t")
18872 (if (org-at-table-p)
18873 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18875 (let ((org-inhibit-startup-visibility-stuff t)
18876 (org-startup-align-all-tables nil))
18877 (when (boundp 'org-table-coordinate-overlays)
18878 (mapc 'delete-overlay org-table-coordinate-overlays)
18879 (setq org-table-coordinate-overlays nil))
18880 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18881 (message "Local setup has been refreshed"))))
18882 ((org-clock-update-time-maybe))
18884 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18885 (error "C-c C-c can do nothing useful at this location"))))))
18887 (defun org-mode-restart ()
18888 "Restart Org-mode, to scan again for special lines.
18889 Also updates the keyword regular expressions."
18890 (interactive)
18891 (org-mode)
18892 (message "Org-mode restarted"))
18894 (defun org-kill-note-or-show-branches ()
18895 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18896 (interactive)
18897 (if (not org-finish-function)
18898 (progn
18899 (hide-subtree)
18900 (call-interactively 'show-branches))
18901 (let ((org-note-abort t))
18902 (funcall org-finish-function))))
18904 (defun org-return (&optional indent)
18905 "Goto next table row or insert a newline.
18906 Calls `org-table-next-row' or `newline', depending on context.
18907 See the individual commands for more information."
18908 (interactive)
18909 (cond
18910 ((or (bobp) (org-in-src-block-p))
18911 (if indent (newline-and-indent) (newline)))
18912 ((org-at-table-p)
18913 (org-table-justify-field-maybe)
18914 (call-interactively 'org-table-next-row))
18915 ;; when `newline-and-indent' is called within a list, make sure
18916 ;; text moved stays inside the item.
18917 ((and (org-in-item-p) indent)
18918 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18919 (progn
18920 (save-match-data (newline))
18921 (org-indent-line-to (length (match-string 0))))
18922 (let ((ind (org-get-indentation)))
18923 (newline)
18924 (if (org-looking-back org-list-end-re)
18925 (org-indent-line-function)
18926 (org-indent-line-to ind)))))
18927 ((and org-return-follows-link
18928 (let ((tprop (get-text-property (point) 'face)))
18929 (or (eq tprop 'org-link)
18930 (and (listp tprop) (memq 'org-link tprop)))))
18931 (call-interactively 'org-open-at-point))
18932 ((and (org-at-heading-p)
18933 (looking-at
18934 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18935 (org-show-entry)
18936 (end-of-line 1)
18937 (newline))
18938 (t (if indent (newline-and-indent) (newline)))))
18940 (defun org-return-indent ()
18941 "Goto next table row or insert a newline and indent.
18942 Calls `org-table-next-row' or `newline-and-indent', depending on
18943 context. See the individual commands for more information."
18944 (interactive)
18945 (org-return t))
18947 (defun org-ctrl-c-star ()
18948 "Compute table, or change heading status of lines.
18949 Calls `org-table-recalculate' or `org-toggle-heading',
18950 depending on context."
18951 (interactive)
18952 (cond
18953 ((org-at-table-p)
18954 (call-interactively 'org-table-recalculate))
18956 ;; Convert all lines in region to list items
18957 (call-interactively 'org-toggle-heading))))
18959 (defun org-ctrl-c-minus ()
18960 "Insert separator line in table or modify bullet status of line.
18961 Also turns a plain line or a region of lines into list items.
18962 Calls `org-table-insert-hline', `org-toggle-item', or
18963 `org-cycle-list-bullet', depending on context."
18964 (interactive)
18965 (cond
18966 ((org-at-table-p)
18967 (call-interactively 'org-table-insert-hline))
18968 ((org-region-active-p)
18969 (call-interactively 'org-toggle-item))
18970 ((org-in-item-p)
18971 (call-interactively 'org-cycle-list-bullet))
18973 (call-interactively 'org-toggle-item))))
18975 (defun org-toggle-item (arg)
18976 "Convert headings or normal lines to items, items to normal lines.
18977 If there is no active region, only the current line is considered.
18979 If the first non blank line in the region is an headline, convert
18980 all headlines to items, shifting text accordingly.
18982 If it is an item, convert all items to normal lines.
18984 If it is normal text, change region into an item. With a prefix
18985 argument ARG, change each line in region into an item."
18986 (interactive "P")
18987 (let ((shift-text
18988 (function
18989 ;; Shift text in current section to IND, from point to END.
18990 ;; The function leaves point to END line.
18991 (lambda (ind end)
18992 (let ((min-i 1000) (end (copy-marker end)))
18993 ;; First determine the minimum indentation (MIN-I) of
18994 ;; the text.
18995 (save-excursion
18996 (catch 'exit
18997 (while (< (point) end)
18998 (let ((i (org-get-indentation)))
18999 (cond
19000 ;; Skip blank lines and inline tasks.
19001 ((looking-at "^[ \t]*$"))
19002 ((looking-at org-outline-regexp-bol))
19003 ;; We can't find less than 0 indentation.
19004 ((zerop i) (throw 'exit (setq min-i 0)))
19005 ((< i min-i) (setq min-i i))))
19006 (forward-line))))
19007 ;; Then indent each line so that a line indented to
19008 ;; MIN-I becomes indented to IND. Ignore blank lines
19009 ;; and inline tasks in the process.
19010 (let ((delta (- ind min-i)))
19011 (while (< (point) end)
19012 (unless (or (looking-at "^[ \t]*$")
19013 (looking-at org-outline-regexp-bol))
19014 (org-indent-line-to (+ (org-get-indentation) delta)))
19015 (forward-line)))))))
19016 (skip-blanks
19017 (function
19018 ;; Return beginning of first non-blank line, starting from
19019 ;; line at POS.
19020 (lambda (pos)
19021 (save-excursion
19022 (goto-char pos)
19023 (skip-chars-forward " \r\t\n")
19024 (point-at-bol)))))
19025 beg end)
19026 ;; Determine boundaries of changes.
19027 (if (org-region-active-p)
19028 (setq beg (funcall skip-blanks (region-beginning))
19029 end (copy-marker (region-end)))
19030 (setq beg (funcall skip-blanks (point-at-bol))
19031 end (copy-marker (point-at-eol))))
19032 ;; Depending on the starting line, choose an action on the text
19033 ;; between BEG and END.
19034 (org-with-limited-levels
19035 (save-excursion
19036 (goto-char beg)
19037 (cond
19038 ;; Case 1. Start at an item: de-itemize. Note that it only
19039 ;; happens when a region is active: `org-ctrl-c-minus'
19040 ;; would call `org-cycle-list-bullet' otherwise.
19041 ((org-at-item-p)
19042 (while (< (point) end)
19043 (when (org-at-item-p)
19044 (skip-chars-forward " \t")
19045 (delete-region (point) (match-end 0)))
19046 (forward-line)))
19047 ;; Case 2. Start at an heading: convert to items.
19048 ((org-at-heading-p)
19049 (let* ((bul (org-list-bullet-string "-"))
19050 (bul-len (length bul))
19051 ;; Indentation of the first heading. It should be
19052 ;; relative to the indentation of its parent, if any.
19053 (start-ind (save-excursion
19054 (cond
19055 ((not org-adapt-indentation) 0)
19056 ((not (outline-previous-heading)) 0)
19057 (t (length (match-string 0))))))
19058 ;; Level of first heading. Further headings will be
19059 ;; compared to it to determine hierarchy in the list.
19060 (ref-level (org-reduced-level (org-outline-level))))
19061 (while (< (point) end)
19062 (let* ((level (org-reduced-level (org-outline-level)))
19063 (delta (max 0 (- level ref-level))))
19064 ;; If current headline is less indented than the first
19065 ;; one, set it as reference, in order to preserve
19066 ;; subtrees.
19067 (when (< level ref-level) (setq ref-level level))
19068 (replace-match bul t t)
19069 (org-indent-line-to (+ start-ind (* delta bul-len)))
19070 ;; Ensure all text down to END (or SECTION-END) belongs
19071 ;; to the newly created item.
19072 (let ((section-end (save-excursion
19073 (or (outline-next-heading) (point)))))
19074 (forward-line)
19075 (funcall shift-text
19076 (+ start-ind (* (1+ delta) bul-len))
19077 (min end section-end)))))))
19078 ;; Case 3. Normal line with ARG: turn each non-item line into
19079 ;; an item.
19080 (arg
19081 (while (< (point) end)
19082 (unless (or (org-at-heading-p) (org-at-item-p))
19083 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19084 (replace-match
19085 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19086 (forward-line)))
19087 ;; Case 4. Normal line without ARG: make the first line of
19088 ;; region an item, and shift indentation of others
19089 ;; lines to set them as item's body.
19090 (t (let* ((bul (org-list-bullet-string "-"))
19091 (bul-len (length bul))
19092 (ref-ind (org-get-indentation)))
19093 (skip-chars-forward " \t")
19094 (insert bul)
19095 (forward-line)
19096 (while (< (point) end)
19097 ;; Ensure that lines less indented than first one
19098 ;; still get included in item body.
19099 (funcall shift-text
19100 (+ ref-ind bul-len)
19101 (min end (save-excursion (or (outline-next-heading)
19102 (point)))))
19103 (forward-line)))))))))
19105 (defun org-toggle-heading (&optional nstars)
19106 "Convert headings to normal text, or items or text to headings.
19107 If there is no active region, only the current line is considered.
19109 With a \\[universal-argument] prefix, convert the whole list at
19110 point into heading.
19112 In a region:
19114 - If the first non blank line is an headline, remove the stars
19115 from all headlines in the region.
19117 - If it is a normal line turn each and every normal line (i.e. not an
19118 heading or an item) in the region into a heading.
19120 - If it is a plain list item, turn all plain list items into headings.
19122 When converting a line into a heading, the number of stars is chosen
19123 such that the lines become children of the current entry. However,
19124 when a prefix argument is given, its value determines the number of
19125 stars to add."
19126 (interactive "P")
19127 (let ((skip-blanks
19128 (function
19129 ;; Return beginning of first non-blank line, starting from
19130 ;; line at POS.
19131 (lambda (pos)
19132 (save-excursion
19133 (goto-char pos)
19134 (skip-chars-forward " \r\t\n")
19135 (point-at-bol)))))
19136 beg end)
19137 ;; Determine boundaries of changes. If a universal prefix has
19138 ;; been given, put the list in a region. If region ends at a bol,
19139 ;; do not consider the last line to be in the region.
19141 (when (and current-prefix-arg (org-at-item-p))
19142 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19143 (org-mark-list))
19145 (if (org-region-active-p)
19146 (setq beg (funcall skip-blanks (region-beginning))
19147 end (copy-marker (save-excursion
19148 (goto-char (region-end))
19149 (if (bolp) (point) (point-at-eol)))))
19150 (setq beg (funcall skip-blanks (point-at-bol))
19151 end (copy-marker (point-at-eol))))
19152 ;; Ensure inline tasks don't count as headings.
19153 (org-with-limited-levels
19154 (save-excursion
19155 (goto-char beg)
19156 (cond
19157 ;; Case 1. Started at an heading: de-star headings.
19158 ((org-at-heading-p)
19159 (while (< (point) end)
19160 (when (org-at-heading-p t)
19161 (looking-at org-outline-regexp) (replace-match ""))
19162 (forward-line)))
19163 ;; Case 2. Started at an item: change items into headlines.
19164 ;; One star will be added by `org-list-to-subtree'.
19165 ((org-at-item-p)
19166 (let* ((stars (make-string
19167 (if nstars
19168 ;; subtract the star that will be added again by
19169 ;; `org-list-to-subtree'
19170 (1- (prefix-numeric-value current-prefix-arg))
19171 (or (org-current-level) 0))
19172 ?*))
19173 (add-stars
19174 (cond (nstars "") ; stars from prefix only
19175 ((equal stars "") "") ; before first heading
19176 (org-odd-levels-only "*") ; inside heading, odd
19177 (t "")))) ; inside heading, oddeven
19178 (while (< (point) end)
19179 (when (org-at-item-p)
19180 ;; Pay attention to cases when region ends before list.
19181 (let* ((struct (org-list-struct))
19182 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19183 (save-restriction
19184 (narrow-to-region (point) list-end)
19185 (insert
19186 (org-list-to-subtree
19187 (org-list-parse-list t)
19188 '(:istart (concat stars add-stars (funcall get-stars depth))
19189 :icount (concat stars add-stars (funcall get-stars depth))))))))
19190 (forward-line))))
19191 ;; Case 3. Started at normal text: make every line an heading,
19192 ;; skipping headlines and items.
19193 (t (let* ((stars (make-string
19194 (if nstars
19195 (prefix-numeric-value current-prefix-arg)
19196 (or (org-current-level) 0))
19197 ?*))
19198 (add-stars
19199 (cond (nstars "") ; stars from prefix only
19200 ((equal stars "") "*") ; before first heading
19201 (org-odd-levels-only "**") ; inside heading, odd
19202 (t "*"))) ; inside heading, oddeven
19203 (rpl (concat stars add-stars " ")))
19204 (while (< (point) end)
19205 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
19206 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19207 (replace-match (concat rpl (match-string 2))))
19208 (forward-line)))))))))
19210 (defun org-meta-return (&optional arg)
19211 "Insert a new heading or wrap a region in a table.
19212 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19213 See the individual commands for more information."
19214 (interactive "P")
19215 (cond
19216 ((run-hook-with-args-until-success 'org-metareturn-hook))
19217 ((or (org-at-drawer-p) (org-at-property-p))
19218 (newline-and-indent))
19219 ((org-at-table-p)
19220 (call-interactively 'org-table-wrap-region))
19221 (t (call-interactively 'org-insert-heading))))
19223 ;;; Menu entries
19225 ;; Define the Org-mode menus
19226 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19227 '("Tbl"
19228 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19229 ["Next Field" org-cycle (org-at-table-p)]
19230 ["Previous Field" org-shifttab (org-at-table-p)]
19231 ["Next Row" org-return (org-at-table-p)]
19232 "--"
19233 ["Blank Field" org-table-blank-field (org-at-table-p)]
19234 ["Edit Field" org-table-edit-field (org-at-table-p)]
19235 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19236 "--"
19237 ("Column"
19238 ["Move Column Left" org-metaleft (org-at-table-p)]
19239 ["Move Column Right" org-metaright (org-at-table-p)]
19240 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19241 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19242 ("Row"
19243 ["Move Row Up" org-metaup (org-at-table-p)]
19244 ["Move Row Down" org-metadown (org-at-table-p)]
19245 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19246 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19247 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19248 "--"
19249 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19250 ("Rectangle"
19251 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19252 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19253 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19254 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19255 "--"
19256 ("Calculate"
19257 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19258 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19259 ["Edit Formulas" org-edit-special (org-at-table-p)]
19260 "--"
19261 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19262 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19263 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19264 "--"
19265 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19266 "--"
19267 ["Sum Column/Rectangle" org-table-sum
19268 (or (org-at-table-p) (org-region-active-p))]
19269 ["Which Column?" org-table-current-column (org-at-table-p)])
19270 ["Debug Formulas"
19271 org-table-toggle-formula-debugger
19272 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19273 ["Show Col/Row Numbers"
19274 org-table-toggle-coordinate-overlays
19275 :style toggle
19276 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19277 "--"
19278 ["Create" org-table-create (and (not (org-at-table-p))
19279 org-enable-table-editor)]
19280 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19281 ["Import from File" org-table-import (not (org-at-table-p))]
19282 ["Export to File" org-table-export (org-at-table-p)]
19283 "--"
19284 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19286 (easy-menu-define org-org-menu org-mode-map "Org menu"
19287 '("Org"
19288 ("Show/Hide"
19289 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19290 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19291 ["Sparse Tree..." org-sparse-tree t]
19292 ["Reveal Context" org-reveal t]
19293 ["Show All" show-all t]
19294 "--"
19295 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19296 "--"
19297 ["New Heading" org-insert-heading t]
19298 ("Navigate Headings"
19299 ["Up" outline-up-heading t]
19300 ["Next" outline-next-visible-heading t]
19301 ["Previous" outline-previous-visible-heading t]
19302 ["Next Same Level" outline-forward-same-level t]
19303 ["Previous Same Level" outline-backward-same-level t]
19304 "--"
19305 ["Jump" org-goto t])
19306 ("Edit Structure"
19307 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19308 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19309 "--"
19310 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19311 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19312 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19313 "--"
19314 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19315 "--"
19316 ["Copy visible text" org-copy-visible t]
19317 "--"
19318 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19319 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19320 ["Demote Heading" org-metaright (not (org-at-table-p))]
19321 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19322 "--"
19323 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19324 "--"
19325 ["Convert to odd levels" org-convert-to-odd-levels t]
19326 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19327 ("Editing"
19328 ["Emphasis..." org-emphasize t]
19329 ["Edit Source Example" org-edit-special t]
19330 "--"
19331 ["Footnote new/jump" org-footnote-action t]
19332 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19333 ("Archive"
19334 ["Archive (default method)" org-archive-subtree-default t]
19335 "--"
19336 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19337 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19338 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19340 "--"
19341 ("Hyperlinks"
19342 ["Store Link (Global)" org-store-link t]
19343 ["Find existing link to here" org-occur-link-in-agenda-files t]
19344 ["Insert Link" org-insert-link t]
19345 ["Follow Link" org-open-at-point t]
19346 "--"
19347 ["Next link" org-next-link t]
19348 ["Previous link" org-previous-link t]
19349 "--"
19350 ["Descriptive Links"
19351 org-toggle-link-display
19352 :style radio
19353 :selected org-descriptive-links
19355 ["Literal Links"
19356 org-toggle-link-display
19357 :style radio
19358 :selected (not org-descriptive-links)])
19359 "--"
19360 ("TODO Lists"
19361 ["TODO/DONE/-" org-todo t]
19362 ("Select keyword"
19363 ["Next keyword" org-shiftright (org-at-heading-p)]
19364 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19365 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19366 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19367 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19368 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19369 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19370 "--"
19371 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19372 :selected org-enforce-todo-dependencies :style toggle :active t]
19373 "Settings for tree at point"
19374 ["Do Children sequentially" org-toggle-ordered-property :style radio
19375 :selected (org-entry-get nil "ORDERED")
19376 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19377 ["Do Children parallel" org-toggle-ordered-property :style radio
19378 :selected (not (org-entry-get nil "ORDERED"))
19379 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19380 "--"
19381 ["Set Priority" org-priority t]
19382 ["Priority Up" org-shiftup t]
19383 ["Priority Down" org-shiftdown t]
19384 "--"
19385 ["Get news from all feeds" org-feed-update-all t]
19386 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19387 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19388 ("TAGS and Properties"
19389 ["Set Tags" org-set-tags-command t]
19390 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19391 "--"
19392 ["Set property" org-set-property t]
19393 ["Column view of properties" org-columns t]
19394 ["Insert Column View DBlock" org-insert-columns-dblock t])
19395 ("Dates and Scheduling"
19396 ["Timestamp" org-time-stamp t]
19397 ["Timestamp (inactive)" org-time-stamp-inactive t]
19398 ("Change Date"
19399 ["1 Day Later" org-shiftright t]
19400 ["1 Day Earlier" org-shiftleft t]
19401 ["1 ... Later" org-shiftup t]
19402 ["1 ... Earlier" org-shiftdown t])
19403 ["Compute Time Range" org-evaluate-time-range t]
19404 ["Schedule Item" org-schedule t]
19405 ["Deadline" org-deadline t]
19406 "--"
19407 ["Custom time format" org-toggle-time-stamp-overlays
19408 :style radio :selected org-display-custom-times]
19409 "--"
19410 ["Goto Calendar" org-goto-calendar t]
19411 ["Date from Calendar" org-date-from-calendar t]
19412 "--"
19413 ["Start/Restart Timer" org-timer-start t]
19414 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19415 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19416 ["Insert Timer String" org-timer t]
19417 ["Insert Timer Item" org-timer-item t])
19418 ("Logging work"
19419 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19420 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19421 ["Clock out" org-clock-out t]
19422 ["Clock cancel" org-clock-cancel t]
19423 "--"
19424 ["Mark as default task" org-clock-mark-default-task t]
19425 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19426 ["Goto running clock" org-clock-goto t]
19427 "--"
19428 ["Display times" org-clock-display t]
19429 ["Create clock table" org-clock-report t]
19430 "--"
19431 ["Record DONE time"
19432 (progn (setq org-log-done (not org-log-done))
19433 (message "Switching to %s will %s record a timestamp"
19434 (car org-done-keywords)
19435 (if org-log-done "automatically" "not")))
19436 :style toggle :selected org-log-done])
19437 "--"
19438 ["Agenda Command..." org-agenda t]
19439 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19440 ("File List for Agenda")
19441 ("Special views current file"
19442 ["TODO Tree" org-show-todo-tree t]
19443 ["Check Deadlines" org-check-deadlines t]
19444 ["Timeline" org-timeline t]
19445 ["Tags/Property tree" org-match-sparse-tree t])
19446 "--"
19447 ["Export/Publish..." org-export t]
19448 ("LaTeX"
19449 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19450 :selected org-cdlatex-mode]
19451 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19452 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19453 ["Modify math symbol" org-cdlatex-math-modify
19454 (org-inside-LaTeX-fragment-p)]
19455 ["Insert citation" org-reftex-citation t]
19456 "--"
19457 ["Template for BEAMER" (progn (require 'org-beamer)
19458 (org-insert-beamer-options-template)) t])
19459 "--"
19460 ("MobileOrg"
19461 ["Push Files and Views" org-mobile-push t]
19462 ["Get Captured and Flagged" org-mobile-pull t]
19463 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19464 "--"
19465 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19466 "--"
19467 ("Documentation"
19468 ["Show Version" org-version t]
19469 ["Info Documentation" org-info t])
19470 ("Customize"
19471 ["Browse Org Group" org-customize t]
19472 "--"
19473 ["Expand This Menu" org-create-customize-menu
19474 (fboundp 'customize-menu-create)])
19475 ["Send bug report" org-submit-bug-report t]
19476 "--"
19477 ("Refresh/Reload"
19478 ["Refresh setup current buffer" org-mode-restart t]
19479 ["Reload Org (after update)" org-reload t]
19480 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19483 (defun org-info (&optional node)
19484 "Read documentation for Org-mode in the info system.
19485 With optional NODE, go directly to that node."
19486 (interactive)
19487 (info (format "(org)%s" (or node ""))))
19489 ;;;###autoload
19490 (defun org-submit-bug-report ()
19491 "Submit a bug report on Org-mode via mail.
19493 Don't hesitate to report any problems or inaccurate documentation.
19495 If you don't have setup sending mail from (X)Emacs, please copy the
19496 output buffer into your mail program, as it gives us important
19497 information about your Org-mode version and configuration."
19498 (interactive)
19499 (require 'reporter)
19500 (org-load-modules-maybe)
19501 (org-require-autoloaded-modules)
19502 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19503 (reporter-submit-bug-report
19504 "emacs-orgmode@gnu.org"
19505 (org-version nil 'full)
19506 (let (list)
19507 (save-window-excursion
19508 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19509 (delete-other-windows)
19510 (erase-buffer)
19511 (insert "You are about to submit a bug report to the Org-mode mailing list.
19513 We would like to add your full Org-mode and Outline configuration to the
19514 bug report. This greatly simplifies the work of the maintainer and
19515 other experts on the mailing list.
19517 HOWEVER, some variables you have customized may contain private
19518 information. The names of customers, colleagues, or friends, might
19519 appear in the form of file names, tags, todo states, or search strings.
19520 If you answer yes to the prompt, you might want to check and remove
19521 such private information before sending the email.")
19522 (add-text-properties (point-min) (point-max) '(face org-warning))
19523 (when (yes-or-no-p "Include your Org-mode configuration ")
19524 (mapatoms
19525 (lambda (v)
19526 (and (boundp v)
19527 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19528 (or (and (symbol-value v)
19529 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19530 (and
19531 (get v 'custom-type) (get v 'standard-value)
19532 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19533 (push v list)))))
19534 (kill-buffer (get-buffer "*Warn about privacy*"))
19535 list))
19536 nil nil
19537 "Remember to cover the basics, that is, what you expected to happen and
19538 what in fact did happen. You don't know how to make a good report? See
19540 http://orgmode.org/manual/Feedback.html#Feedback
19542 Your bug report will be posted to the Org-mode mailing list.
19543 ------------------------------------------------------------------------")
19544 (save-excursion
19545 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19546 (replace-match "\\1Bug: \\3 [\\2]")))))
19549 (defun org-install-agenda-files-menu ()
19550 (let ((bl (buffer-list)))
19551 (save-excursion
19552 (while bl
19553 (set-buffer (pop bl))
19554 (if (derived-mode-p 'org-mode) (setq bl nil)))
19555 (when (derived-mode-p 'org-mode)
19556 (easy-menu-change
19557 '("Org") "File List for Agenda"
19558 (append
19559 (list
19560 ["Edit File List" (org-edit-agenda-file-list) t]
19561 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19562 ["Remove Current File from List" org-remove-file t]
19563 ["Cycle through agenda files" org-cycle-agenda-files t]
19564 ["Occur in all agenda files" org-occur-in-agenda-files t]
19565 "--")
19566 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19568 ;;;; Documentation
19570 ;;;###autoload
19571 (defun org-require-autoloaded-modules ()
19572 (interactive)
19573 (mapc 'require
19574 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19575 org-docbook org-exp org-html org-icalendar
19576 org-id org-latex
19577 org-publish org-remember org-table
19578 org-timer org-xoxo)))
19580 ;;;###autoload
19581 (defun org-reload (&optional uncompiled)
19582 "Reload all org lisp files.
19583 With prefix arg UNCOMPILED, load the uncompiled versions."
19584 (interactive "P")
19585 (require 'find-func)
19586 (let* ((file-re "^org\\(-.*\\)?\\.el")
19587 (dir-org (file-name-directory (org-find-library-dir "org")))
19588 (dir-org-contrib (ignore-errors
19589 (file-name-directory
19590 (org-find-library-dir "org-contribdir"))))
19591 (babel-files
19592 (mapcar (lambda (el) (concat (concat dir-org "ob") (when el (format "-%s" el)) ".el"))
19593 (append (list nil "comint" "eval" "exp" "keys"
19594 "lob" "ref" "table" "tangle")
19595 (delq nil
19596 (mapcar
19597 (lambda (lang)
19598 (when (cdr lang) (symbol-name (car lang))))
19599 org-babel-load-languages)))))
19600 (files
19601 (append babel-files
19602 (and dir-org-contrib
19603 (directory-files dir-org-contrib t file-re))
19604 (directory-files dir-org t file-re)))
19605 (remove-re (concat (if (featurep 'xemacs)
19606 "org-colview" "org-colview-xemacs")
19607 "\\'")))
19608 (setq files (mapcar 'file-name-sans-extension files))
19609 (setq files (mapcar
19610 (lambda (x) (if (string-match remove-re x) nil x))
19611 files))
19612 (setq files (delq nil files))
19613 (mapc
19614 (lambda (f)
19615 (when (featurep (intern (file-name-nondirectory f)))
19616 (if (and (not uncompiled)
19617 (file-exists-p (concat f ".elc")))
19618 (load (concat f ".elc") nil nil 'nosuffix)
19619 (load (concat f ".el") nil nil 'nosuffix))))
19620 files)
19621 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19622 (org-version nil 'full 'message))
19624 ;;;###autoload
19625 (defun org-customize ()
19626 "Call the customize function with org as argument."
19627 (interactive)
19628 (org-load-modules-maybe)
19629 (org-require-autoloaded-modules)
19630 (customize-browse 'org))
19632 (defun org-create-customize-menu ()
19633 "Create a full customization menu for Org-mode, insert it into the menu."
19634 (interactive)
19635 (org-load-modules-maybe)
19636 (org-require-autoloaded-modules)
19637 (if (fboundp 'customize-menu-create)
19638 (progn
19639 (easy-menu-change
19640 '("Org") "Customize"
19641 `(["Browse Org group" org-customize t]
19642 "--"
19643 ,(customize-menu-create 'org)
19644 ["Set" Custom-set t]
19645 ["Save" Custom-save t]
19646 ["Reset to Current" Custom-reset-current t]
19647 ["Reset to Saved" Custom-reset-saved t]
19648 ["Reset to Standard Settings" Custom-reset-standard t]))
19649 (message "\"Org\"-menu now contains full customization menu"))
19650 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19652 ;;;; Miscellaneous stuff
19654 ;;; Generally useful functions
19656 (defun org-get-at-bol (property)
19657 "Get text property PROPERTY at beginning of line."
19658 (get-text-property (point-at-bol) property))
19660 (defun org-find-text-property-in-string (prop s)
19661 "Return the first non-nil value of property PROP in string S."
19662 (or (get-text-property 0 prop s)
19663 (get-text-property (or (next-single-property-change 0 prop s) 0)
19664 prop s)))
19666 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19667 "Display the given MESSAGE as a warning."
19668 (if (fboundp 'display-warning)
19669 (display-warning 'org message
19670 (if (featurep 'xemacs) 'warning :warning))
19671 (let ((buf (get-buffer-create "*Org warnings*")))
19672 (with-current-buffer buf
19673 (goto-char (point-max))
19674 (insert "Warning (Org): " message)
19675 (unless (bolp)
19676 (newline)))
19677 (display-buffer buf)
19678 (sit-for 0))))
19680 (defun org-eval (form)
19681 "Eval FORM and return result."
19682 (condition-case error
19683 (eval form)
19684 (error (format "%%![Error: %s]" error))))
19686 (defun org-in-clocktable-p ()
19687 "Check if the cursor is in a clocktable."
19688 (let ((pos (point)) start)
19689 (save-excursion
19690 (end-of-line 1)
19691 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19692 (setq start (match-beginning 0))
19693 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19694 (>= (match-end 0) pos)
19695 start))))
19697 (defun org-in-commented-line ()
19698 "Is point in a line starting with `#'?"
19699 (equal (char-after (point-at-bol)) ?#))
19701 (defun org-in-indented-comment-line ()
19702 "Is point in a line starting with `#' after some white space?"
19703 (save-excursion
19704 (save-match-data
19705 (goto-char (point-at-bol))
19706 (looking-at "[ \t]*#"))))
19708 (defun org-in-verbatim-emphasis ()
19709 (save-match-data
19710 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19712 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19713 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19714 (if (and marker (marker-buffer marker)
19715 (buffer-live-p (marker-buffer marker)))
19716 (progn
19717 (org-pop-to-buffer-same-window (marker-buffer marker))
19718 (if (or (> marker (point-max)) (< marker (point-min)))
19719 (widen))
19720 (goto-char marker)
19721 (org-show-context 'org-goto))
19722 (if bookmark
19723 (bookmark-jump bookmark)
19724 (error "Cannot find location"))))
19726 (defun org-quote-csv-field (s)
19727 "Quote field for inclusion in CSV material."
19728 (if (string-match "[\",]" s)
19729 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19732 (defun org-force-self-insert (N)
19733 "Needed to enforce self-insert under remapping."
19734 (interactive "p")
19735 (self-insert-command N))
19737 (defun org-string-width (s)
19738 "Compute width of string, ignoring invisible characters.
19739 This ignores character with invisibility property `org-link', and also
19740 characters with property `org-cwidth', because these will become invisible
19741 upon the next fontification round."
19742 (let (b l)
19743 (when (or (eq t buffer-invisibility-spec)
19744 (assq 'org-link buffer-invisibility-spec))
19745 (while (setq b (text-property-any 0 (length s)
19746 'invisible 'org-link s))
19747 (setq s (concat (substring s 0 b)
19748 (substring s (or (next-single-property-change
19749 b 'invisible s) (length s)))))))
19750 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19751 (setq s (concat (substring s 0 b)
19752 (substring s (or (next-single-property-change
19753 b 'org-cwidth s) (length s))))))
19754 (setq l (string-width s) b -1)
19755 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19756 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19759 (defun org-shorten-string (s maxlength)
19760 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19761 If the string is shorter or has length MAXLENGTH, just return the
19762 original string. If it is longer, the functions finds a space in the
19763 string, breaks this string off at that locations and adds three dots
19764 as ellipsis. Including the ellipsis, the string will not be longer
19765 than MAXLENGTH. If finding a good breaking point in the string does
19766 not work, the string is just chopped off in the middle of a word
19767 if necessary."
19768 (if (<= (length s) maxlength)
19770 (let* ((n (max (- maxlength 4) 1))
19771 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19772 (if (string-match re s)
19773 (concat (match-string 1 s) "...")
19774 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19776 (defun org-get-indentation (&optional line)
19777 "Get the indentation of the current line, interpreting tabs.
19778 When LINE is given, assume it represents a line and compute its indentation."
19779 (if line
19780 (if (string-match "^ *" (org-remove-tabs line))
19781 (match-end 0))
19782 (save-excursion
19783 (beginning-of-line 1)
19784 (skip-chars-forward " \t")
19785 (current-column))))
19787 (defun org-get-string-indentation (s)
19788 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19789 (let ((n -1) (i 0) (w tab-width) c)
19790 (catch 'exit
19791 (while (< (setq n (1+ n)) (length s))
19792 (setq c (aref s n))
19793 (cond ((= c ?\ ) (setq i (1+ i)))
19794 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19795 (t (throw 'exit t)))))
19798 (defun org-remove-tabs (s &optional width)
19799 "Replace tabulators in S with spaces.
19800 Assumes that s is a single line, starting in column 0."
19801 (setq width (or width tab-width))
19802 (while (string-match "\t" s)
19803 (setq s (replace-match
19804 (make-string
19805 (- (* width (/ (+ (match-beginning 0) width) width))
19806 (match-beginning 0)) ?\ )
19807 t t s)))
19810 (defun org-fix-indentation (line ind)
19811 "Fix indentation in LINE.
19812 IND is a cons cell with target and minimum indentation.
19813 If the current indentation in LINE is smaller than the minimum,
19814 leave it alone. If it is larger than ind, set it to the target."
19815 (let* ((l (org-remove-tabs line))
19816 (i (org-get-indentation l))
19817 (i1 (car ind)) (i2 (cdr ind)))
19818 (if (>= i i2) (setq l (substring line i2)))
19819 (if (> i1 0)
19820 (concat (make-string i1 ?\ ) l)
19821 l)))
19823 (defun org-remove-indentation (code &optional n)
19824 "Remove the maximum common indentation from the lines in CODE.
19825 N may optionally be the number of spaces to remove."
19826 (with-temp-buffer
19827 (insert code)
19828 (org-do-remove-indentation n)
19829 (buffer-string)))
19831 (defun org-do-remove-indentation (&optional n)
19832 "Remove the maximum common indentation from the buffer."
19833 (untabify (point-min) (point-max))
19834 (let ((min 10000) re)
19835 (if n
19836 (setq min n)
19837 (goto-char (point-min))
19838 (while (re-search-forward "^ *[^ \n]" nil t)
19839 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19840 (unless (or (= min 0) (= min 10000))
19841 (setq re (format "^ \\{%d\\}" min))
19842 (goto-char (point-min))
19843 (while (re-search-forward re nil t)
19844 (replace-match "")
19845 (end-of-line 1))
19846 min)))
19848 (defun org-fill-template (template alist)
19849 "Find each %key of ALIST in TEMPLATE and replace it."
19850 (let ((case-fold-search nil)
19851 entry key value)
19852 (setq alist (sort (copy-sequence alist)
19853 (lambda (a b) (< (length (car a)) (length (car b))))))
19854 (while (setq entry (pop alist))
19855 (setq template
19856 (replace-regexp-in-string
19857 (concat "%" (regexp-quote (car entry)))
19858 (cdr entry) template t t)))
19859 template))
19861 (defun org-base-buffer (buffer)
19862 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19863 (if (not buffer)
19864 buffer
19865 (or (buffer-base-buffer buffer)
19866 buffer)))
19868 (defun org-trim (s)
19869 "Remove whitespace at beginning and end of string."
19870 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19871 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19874 (defun org-wrap (string &optional width lines)
19875 "Wrap string to either a number of lines, or a width in characters.
19876 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19877 that costs. If there is a word longer than WIDTH, the text is actually
19878 wrapped to the length of that word.
19879 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19880 many lines, whatever width that takes.
19881 The return value is a list of lines, without newlines at the end."
19882 (let* ((words (org-split-string string "[ \t\n]+"))
19883 (maxword (apply 'max (mapcar 'org-string-width words)))
19884 w ll)
19885 (cond (width
19886 (org-do-wrap words (max maxword width)))
19887 (lines
19888 (setq w maxword)
19889 (setq ll (org-do-wrap words maxword))
19890 (if (<= (length ll) lines)
19892 (setq ll words)
19893 (while (> (length ll) lines)
19894 (setq w (1+ w))
19895 (setq ll (org-do-wrap words w)))
19896 ll))
19897 (t (error "Cannot wrap this")))))
19899 (defun org-do-wrap (words width)
19900 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19901 (let (lines line)
19902 (while words
19903 (setq line (pop words))
19904 (while (and words (< (+ (length line) (length (car words))) width))
19905 (setq line (concat line " " (pop words))))
19906 (setq lines (push line lines)))
19907 (nreverse lines)))
19909 (defun org-split-string (string &optional separators)
19910 "Splits STRING into substrings at SEPARATORS.
19911 No empty strings are returned if there are matches at the beginning
19912 and end of string."
19913 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19914 (start 0)
19915 notfirst
19916 (list nil))
19917 (while (and (string-match rexp string
19918 (if (and notfirst
19919 (= start (match-beginning 0))
19920 (< start (length string)))
19921 (1+ start) start))
19922 (< (match-beginning 0) (length string)))
19923 (setq notfirst t)
19924 (or (eq (match-beginning 0) 0)
19925 (and (eq (match-beginning 0) (match-end 0))
19926 (eq (match-beginning 0) start))
19927 (setq list
19928 (cons (substring string start (match-beginning 0))
19929 list)))
19930 (setq start (match-end 0)))
19931 (or (eq start (length string))
19932 (setq list
19933 (cons (substring string start)
19934 list)))
19935 (nreverse list)))
19937 (defun org-quote-vert (s)
19938 "Replace \"|\" with \"\\vert\"."
19939 (while (string-match "|" s)
19940 (setq s (replace-match "\\vert" t t s)))
19943 (defun org-uuidgen-p (s)
19944 "Is S an ID created by UUIDGEN?"
19945 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19947 (defun org-in-src-block-p nil
19948 "Whether point is in a code source block."
19949 (let (ov)
19950 (when (setq ov (overlays-at (point)))
19951 (memq 'org-block-background
19952 (overlay-properties
19953 (car ov))))))
19955 (defun org-context ()
19956 "Return a list of contexts of the current cursor position.
19957 If several contexts apply, all are returned.
19958 Each context entry is a list with a symbol naming the context, and
19959 two positions indicating start and end of the context. Possible
19960 contexts are:
19962 :headline anywhere in a headline
19963 :headline-stars on the leading stars in a headline
19964 :todo-keyword on a TODO keyword (including DONE) in a headline
19965 :tags on the TAGS in a headline
19966 :priority on the priority cookie in a headline
19967 :item on the first line of a plain list item
19968 :item-bullet on the bullet/number of a plain list item
19969 :checkbox on the checkbox in a plain list item
19970 :table in an org-mode table
19971 :table-special on a special filed in a table
19972 :table-table in a table.el table
19973 :clocktable in a clocktable
19974 :src-block in a source block
19975 :link on a hyperlink
19976 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19977 :target on a <<target>>
19978 :radio-target on a <<<radio-target>>>
19979 :latex-fragment on a LaTeX fragment
19980 :latex-preview on a LaTeX fragment with overlaid preview image
19982 This function expects the position to be visible because it uses font-lock
19983 faces as a help to recognize the following contexts: :table-special, :link,
19984 and :keyword."
19985 (let* ((f (get-text-property (point) 'face))
19986 (faces (if (listp f) f (list f)))
19987 (case-fold-search t)
19988 (p (point)) clist o)
19989 ;; First the large context
19990 (cond
19991 ((org-at-heading-p t)
19992 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19993 (when (progn
19994 (beginning-of-line 1)
19995 (looking-at org-todo-line-tags-regexp))
19996 (push (org-point-in-group p 1 :headline-stars) clist)
19997 (push (org-point-in-group p 2 :todo-keyword) clist)
19998 (push (org-point-in-group p 4 :tags) clist))
19999 (goto-char p)
20000 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20001 (if (looking-at "\\[#[A-Z0-9]\\]")
20002 (push (org-point-in-group p 0 :priority) clist)))
20004 ((org-at-item-p)
20005 (push (org-point-in-group p 2 :item-bullet) clist)
20006 (push (list :item (point-at-bol)
20007 (save-excursion (org-end-of-item) (point)))
20008 clist)
20009 (and (org-at-item-checkbox-p)
20010 (push (org-point-in-group p 0 :checkbox) clist)))
20012 ((org-at-table-p)
20013 (push (list :table (org-table-begin) (org-table-end)) clist)
20014 (if (memq 'org-formula faces)
20015 (push (list :table-special
20016 (previous-single-property-change p 'face)
20017 (next-single-property-change p 'face)) clist)))
20018 ((org-at-table-p 'any)
20019 (push (list :table-table) clist)))
20020 (goto-char p)
20022 ;; New the "medium" contexts: clocktables, source blocks
20023 (cond ((org-in-clocktable-p)
20024 (push (list :clocktable
20025 (and (or (looking-at "#\\+BEGIN: clocktable")
20026 (search-backward "#+BEGIN: clocktable" nil t))
20027 (match-beginning 0))
20028 (and (re-search-forward "#\\+END:?" nil t)
20029 (match-end 0))) clist))
20030 ((org-in-src-block-p)
20031 (push (list :src-block
20032 (and (or (looking-at "#\\+BEGIN_SRC")
20033 (search-backward "#+BEGIN_SRC" nil t))
20034 (match-beginning 0))
20035 (and (search-forward "#+END_SRC" nil t)
20036 (match-beginning 0))) clist)))
20037 (goto-char p)
20039 ;; Now the small context
20040 (cond
20041 ((org-at-timestamp-p)
20042 (push (org-point-in-group p 0 :timestamp) clist))
20043 ((memq 'org-link faces)
20044 (push (list :link
20045 (previous-single-property-change p 'face)
20046 (next-single-property-change p 'face)) clist))
20047 ((memq 'org-special-keyword faces)
20048 (push (list :keyword
20049 (previous-single-property-change p 'face)
20050 (next-single-property-change p 'face)) clist))
20051 ((org-at-target-p)
20052 (push (org-point-in-group p 0 :target) clist)
20053 (goto-char (1- (match-beginning 0)))
20054 (if (looking-at org-radio-target-regexp)
20055 (push (org-point-in-group p 0 :radio-target) clist))
20056 (goto-char p))
20057 ((setq o (car (delq nil
20058 (mapcar
20059 (lambda (x)
20060 (if (memq x org-latex-fragment-image-overlays) x))
20061 (overlays-at (point))))))
20062 (push (list :latex-fragment
20063 (overlay-start o) (overlay-end o)) clist)
20064 (push (list :latex-preview
20065 (overlay-start o) (overlay-end o)) clist))
20066 ((org-inside-LaTeX-fragment-p)
20067 ;; FIXME: positions wrong.
20068 (push (list :latex-fragment (point) (point)) clist)))
20070 (setq clist (nreverse (delq nil clist)))
20071 clist))
20073 ;; FIXME: Compare with at-regexp-p Do we need both?
20074 (defun org-in-regexp (re &optional nlines visually)
20075 "Check if point is inside a match of regexp.
20076 Normally only the current line is checked, but you can include NLINES extra
20077 lines both before and after point into the search.
20078 If VISUALLY is set, require that the cursor is not after the match but
20079 really on, so that the block visually is on the match."
20080 (catch 'exit
20081 (let ((pos (point))
20082 (eol (point-at-eol (+ 1 (or nlines 0))))
20083 (inc (if visually 1 0)))
20084 (save-excursion
20085 (beginning-of-line (- 1 (or nlines 0)))
20086 (while (re-search-forward re eol t)
20087 (if (and (<= (match-beginning 0) pos)
20088 (>= (+ inc (match-end 0)) pos))
20089 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20091 (defun org-at-regexp-p (regexp)
20092 "Is point inside a match of REGEXP in the current line?"
20093 (catch 'exit
20094 (save-excursion
20095 (let ((pos (point)) (end (point-at-eol)))
20096 (beginning-of-line 1)
20097 (while (re-search-forward regexp end t)
20098 (if (and (<= (match-beginning 0) pos)
20099 (>= (match-end 0) pos))
20100 (throw 'exit t)))
20101 nil))))
20103 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20104 "Non-nil when point is between matches of START-RE and END-RE.
20106 Also return a non-nil value when point is on one of the matches.
20108 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20109 buffer positions. Default values are the positions of headlines
20110 surrounding the point.
20112 The functions returns a cons cell whose car (resp. cdr) is the
20113 position before START-RE (resp. after END-RE)."
20114 (save-match-data
20115 (let ((pos (point))
20116 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20117 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20118 beg end)
20119 (save-excursion
20120 ;; Point is on a block when on START-RE or if START-RE can be
20121 ;; found before it...
20122 (and (or (org-at-regexp-p start-re)
20123 (re-search-backward start-re limit-up t))
20124 (setq beg (match-beginning 0))
20125 ;; ... and END-RE after it...
20126 (goto-char (match-end 0))
20127 (re-search-forward end-re limit-down t)
20128 (> (setq end (match-end 0)) pos)
20129 ;; ... without another START-RE in-between.
20130 (goto-char (match-beginning 0))
20131 (not (re-search-backward start-re (1+ beg) t))
20132 ;; Return value.
20133 (cons beg end))))))
20135 (defun org-in-block-p (names)
20136 "Non-nil when point belongs to a block whose name belongs to NAMES.
20138 NAMES is a list of strings containing names of blocks.
20140 Return first block name matched, or nil. Beware that in case of
20141 nested blocks, the returned name may not belong to the closest
20142 block from point."
20143 (save-match-data
20144 (catch 'exit
20145 (let ((case-fold-search t)
20146 (lim-up (save-excursion (outline-previous-heading)))
20147 (lim-down (save-excursion (outline-next-heading))))
20148 (mapc (lambda (name)
20149 (let ((n (regexp-quote name)))
20150 (when (org-between-regexps-p
20151 (concat "^[ \t]*#\\+begin_" n)
20152 (concat "^[ \t]*#\\+end_" n)
20153 lim-up lim-down)
20154 (throw 'exit n))))
20155 names))
20156 nil)))
20158 (defun org-occur-in-agenda-files (regexp &optional nlines)
20159 "Call `multi-occur' with buffers for all agenda files."
20160 (interactive "sOrg-files matching: \np")
20161 (let* ((files (org-agenda-files))
20162 (tnames (mapcar 'file-truename files))
20163 (extra org-agenda-text-search-extra-files)
20165 (when (eq (car extra) 'agenda-archives)
20166 (setq extra (cdr extra))
20167 (setq files (org-add-archive-files files)))
20168 (while (setq f (pop extra))
20169 (unless (member (file-truename f) tnames)
20170 (add-to-list 'files f 'append)
20171 (add-to-list 'tnames (file-truename f) 'append)))
20172 (multi-occur
20173 (mapcar (lambda (x)
20174 (with-current-buffer
20175 (or (get-file-buffer x) (find-file-noselect x))
20176 (widen)
20177 (current-buffer)))
20178 files)
20179 regexp)))
20181 (if (boundp 'occur-mode-find-occurrence-hook)
20182 ;; Emacs 23
20183 (add-hook 'occur-mode-find-occurrence-hook
20184 (lambda ()
20185 (when (derived-mode-p 'org-mode)
20186 (org-reveal))))
20187 ;; Emacs 22
20188 (defadvice occur-mode-goto-occurrence
20189 (after org-occur-reveal activate)
20190 (and (derived-mode-p 'org-mode) (org-reveal)))
20191 (defadvice occur-mode-goto-occurrence-other-window
20192 (after org-occur-reveal activate)
20193 (and (derived-mode-p 'org-mode) (org-reveal)))
20194 (defadvice occur-mode-display-occurrence
20195 (after org-occur-reveal activate)
20196 (when (derived-mode-p 'org-mode)
20197 (let ((pos (occur-mode-find-occurrence)))
20198 (with-current-buffer (marker-buffer pos)
20199 (save-excursion
20200 (goto-char pos)
20201 (org-reveal)))))))
20203 (defun org-occur-link-in-agenda-files ()
20204 "Create a link and search for it in the agendas.
20205 The link is not stored in `org-stored-links', it is just created
20206 for the search purpose."
20207 (interactive)
20208 (let ((link (condition-case nil
20209 (org-store-link nil)
20210 (error "Unable to create a link to here"))))
20211 (org-occur-in-agenda-files (regexp-quote link))))
20213 (defun org-uniquify (list)
20214 "Remove duplicate elements from LIST."
20215 (let (res)
20216 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20217 res))
20219 (defun org-delete-all (elts list)
20220 "Remove all elements in ELTS from LIST."
20221 (while elts
20222 (setq list (delete (pop elts) list)))
20223 list)
20225 (defun org-count (cl-item cl-seq)
20226 "Count the number of occurrences of ITEM in SEQ.
20227 Taken from `count' in cl-seq.el with all keyword arguments removed."
20228 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20229 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20230 (while (< cl-start cl-end)
20231 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20232 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20233 (setq cl-start (1+ cl-start)))
20234 cl-count))
20236 (defun org-remove-if (predicate seq)
20237 "Remove everything from SEQ that fulfills PREDICATE."
20238 (let (res e)
20239 (while seq
20240 (setq e (pop seq))
20241 (if (not (funcall predicate e)) (push e res)))
20242 (nreverse res)))
20244 (defun org-remove-if-not (predicate seq)
20245 "Remove everything from SEQ that does not fulfill PREDICATE."
20246 (let (res e)
20247 (while seq
20248 (setq e (pop seq))
20249 (if (funcall predicate e) (push e res)))
20250 (nreverse res)))
20252 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20253 "Reduce two-argument FUNCTION across SEQ.
20254 Taken from `reduce' in cl-seq.el with all keyword arguments but
20255 \":initial-value\" removed."
20256 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20257 (cadr (memq :initial-value cl-keys)))
20258 (cl-seq (pop cl-seq))
20259 (t (funcall cl-func)))))
20260 (while cl-seq
20261 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20262 cl-accum))
20264 (defun org-back-over-empty-lines ()
20265 "Move backwards over whitespace, to the beginning of the first empty line.
20266 Returns the number of empty lines passed."
20267 (let ((pos (point)))
20268 (if (cdr (assoc 'heading org-blank-before-new-entry))
20269 (skip-chars-backward " \t\n\r")
20270 (unless (eobp)
20271 (forward-line -1)))
20272 (beginning-of-line 2)
20273 (goto-char (min (point) pos))
20274 (count-lines (point) pos)))
20276 (defun org-skip-whitespace ()
20277 (skip-chars-forward " \t\n\r"))
20279 (defun org-point-in-group (point group &optional context)
20280 "Check if POINT is in match-group GROUP.
20281 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20282 match. If the match group does not exist or point is not inside it,
20283 return nil."
20284 (and (match-beginning group)
20285 (>= point (match-beginning group))
20286 (<= point (match-end group))
20287 (if context
20288 (list context (match-beginning group) (match-end group))
20289 t)))
20291 (defun org-switch-to-buffer-other-window (&rest args)
20292 "Switch to buffer in a second window on the current frame.
20293 In particular, do not allow pop-up frames.
20294 Returns the newly created buffer."
20295 (let (pop-up-frames special-display-buffer-names special-display-regexps
20296 special-display-function)
20297 (apply 'switch-to-buffer-other-window args)))
20299 (defun org-combine-plists (&rest plists)
20300 "Create a single property list from all plists in PLISTS.
20301 The process starts by copying the first list, and then setting properties
20302 from the other lists. Settings in the last list are the most significant
20303 ones and overrule settings in the other lists."
20304 (let ((rtn (copy-sequence (pop plists)))
20305 p v ls)
20306 (while plists
20307 (setq ls (pop plists))
20308 (while ls
20309 (setq p (pop ls) v (pop ls))
20310 (setq rtn (plist-put rtn p v))))
20311 rtn))
20313 (defun org-move-line-down (arg)
20314 "Move the current line down. With prefix argument, move it past ARG lines."
20315 (interactive "p")
20316 (let ((col (current-column))
20317 beg end pos)
20318 (beginning-of-line 1) (setq beg (point))
20319 (beginning-of-line 2) (setq end (point))
20320 (beginning-of-line (+ 1 arg))
20321 (setq pos (move-marker (make-marker) (point)))
20322 (insert (delete-and-extract-region beg end))
20323 (goto-char pos)
20324 (org-move-to-column col)))
20326 (defun org-move-line-up (arg)
20327 "Move the current line up. With prefix argument, move it past ARG lines."
20328 (interactive "p")
20329 (let ((col (current-column))
20330 beg end pos)
20331 (beginning-of-line 1) (setq beg (point))
20332 (beginning-of-line 2) (setq end (point))
20333 (beginning-of-line (- arg))
20334 (setq pos (move-marker (make-marker) (point)))
20335 (insert (delete-and-extract-region beg end))
20336 (goto-char pos)
20337 (org-move-to-column col)))
20339 (defun org-replace-escapes (string table)
20340 "Replace %-escapes in STRING with values in TABLE.
20341 TABLE is an association list with keys like \"%a\" and string values.
20342 The sequences in STRING may contain normal field width and padding information,
20343 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20344 so values can contain further %-escapes if they are define later in TABLE."
20345 (let ((tbl (copy-alist table))
20346 (case-fold-search nil)
20347 (pchg 0)
20348 e re rpl)
20349 (while (setq e (pop tbl))
20350 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20351 (when (and (cdr e) (string-match re (cdr e)))
20352 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20353 (safe "SREF"))
20354 (add-text-properties 0 3 (list 'sref sref) safe)
20355 (setcdr e (replace-match safe t t (cdr e)))))
20356 (while (string-match re string)
20357 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20358 (cdr e)))
20359 (setq string (replace-match rpl t t string))))
20360 (while (setq pchg (next-property-change pchg string))
20361 (let ((sref (get-text-property pchg 'sref string)))
20362 (when (and sref (string-match "SREF" string pchg))
20363 (setq string (replace-match sref t t string)))))
20364 string))
20366 (defun org-sublist (list start end)
20367 "Return a section of LIST, from START to END.
20368 Counting starts at 1."
20369 (let (rtn (c start))
20370 (setq list (nthcdr (1- start) list))
20371 (while (and list (<= c end))
20372 (push (pop list) rtn)
20373 (setq c (1+ c)))
20374 (nreverse rtn)))
20376 (defun org-find-base-buffer-visiting (file)
20377 "Like `find-buffer-visiting' but always return the base buffer and
20378 not an indirect buffer."
20379 (let ((buf (or (get-file-buffer file)
20380 (find-buffer-visiting file))))
20381 (if buf
20382 (or (buffer-base-buffer buf) buf)
20383 nil)))
20385 (defun org-image-file-name-regexp (&optional extensions)
20386 "Return regexp matching the file names of images.
20387 If EXTENSIONS is given, only match these."
20388 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20389 (image-file-name-regexp)
20390 (let ((image-file-name-extensions
20391 (or extensions
20392 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20393 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20394 (concat "\\."
20395 (regexp-opt (nconc (mapcar 'upcase
20396 image-file-name-extensions)
20397 image-file-name-extensions)
20399 "\\'"))))
20401 (defun org-file-image-p (file &optional extensions)
20402 "Return non-nil if FILE is an image."
20403 (save-match-data
20404 (string-match (org-image-file-name-regexp extensions) file)))
20406 (defun org-get-cursor-date ()
20407 "Return the date at cursor in as a time.
20408 This works in the calendar and in the agenda, anywhere else it just
20409 returns the current time."
20410 (let (date day defd)
20411 (cond
20412 ((eq major-mode 'calendar-mode)
20413 (setq date (calendar-cursor-to-date)
20414 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20415 ((eq major-mode 'org-agenda-mode)
20416 (setq day (get-text-property (point) 'day))
20417 (if day
20418 (setq date (calendar-gregorian-from-absolute day)
20419 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20420 (nth 2 date))))))
20421 (or defd (current-time))))
20423 (defvar org-agenda-action-marker (make-marker)
20424 "Marker pointing to the entry for the next agenda action.")
20426 (defun org-mark-entry-for-agenda-action ()
20427 "Mark the current entry as target of an agenda action.
20428 Agenda actions are actions executed from the agenda with the key `k',
20429 which make use of the date at the cursor."
20430 (interactive)
20431 (move-marker org-agenda-action-marker
20432 (save-excursion (org-back-to-heading t) (point))
20433 (current-buffer))
20434 (message
20435 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20437 (defun org-mark-subtree ()
20438 "Mark the current subtree.
20439 This puts point at the start of the current subtree, and mark at the end.
20441 If point is in an inline task, mark that task instead."
20442 (interactive)
20443 (let ((inline-task-p
20444 (and (featurep 'org-inlinetask)
20445 (org-inlinetask-in-task-p)))
20446 (beg))
20447 ;; Get beginning of subtree
20448 (cond
20449 (inline-task-p (org-inlinetask-goto-beginning))
20450 ((org-at-heading-p) (beginning-of-line))
20451 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20452 (setq beg (point))
20453 ;; Get end of it
20454 (if inline-task-p
20455 (org-inlinetask-goto-end)
20456 (org-end-of-subtree))
20457 ;; Mark zone
20458 (push-mark (point) nil t)
20459 (goto-char beg)))
20461 ;;; Paragraph filling stuff.
20462 ;; We want this to be just right, so use the full arsenal.
20464 (defun org-indent-line-function ()
20465 "Indent line depending on context."
20466 (interactive)
20467 (let* ((pos (point))
20468 (itemp (org-at-item-p))
20469 (case-fold-search t)
20470 (org-drawer-regexp (or org-drawer-regexp "\000"))
20471 (inline-task-p (and (featurep 'org-inlinetask)
20472 (org-inlinetask-in-task-p)))
20473 (inline-re (and inline-task-p
20474 (org-inlinetask-outline-regexp)))
20475 column)
20476 (beginning-of-line 1)
20477 (cond
20478 ;; Comments
20479 ((looking-at "# ") (setq column 0))
20480 ;; Headings
20481 ((looking-at org-outline-regexp) (setq column 0))
20482 ;; Included files
20483 ((looking-at "#\\+include:") (setq column 0))
20484 ;; Footnote definition
20485 ((looking-at org-footnote-definition-re) (setq column 0))
20486 ;; Literal examples
20487 ((looking-at "[ \t]*:\\( \\|$\\)")
20488 (setq column (org-get-indentation))) ; do nothing
20489 ;; Lists
20490 ((ignore-errors (goto-char (org-in-item-p)))
20491 (setq column (if itemp
20492 (org-get-indentation)
20493 (org-list-item-body-column (point))))
20494 (goto-char pos))
20495 ;; Drawers
20496 ((and (looking-at "[ \t]*:END:")
20497 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20498 (save-excursion
20499 (goto-char (1- (match-beginning 1)))
20500 (setq column (current-column))))
20501 ;; Special blocks
20502 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20503 (save-excursion
20504 (re-search-backward
20505 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20506 (setq column (org-get-indentation (match-string 0))))
20507 ((and (not (looking-at "[ \t]*#\\+begin_"))
20508 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20509 (save-excursion
20510 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20511 (setq column
20512 (cond ((equal (downcase (match-string 1)) "src")
20513 ;; src blocks: let `org-edit-src-exit' handle them
20514 (org-get-indentation))
20515 ((equal (downcase (match-string 1)) "example")
20516 (max (org-get-indentation)
20517 (org-get-indentation (match-string 0))))
20519 (org-get-indentation (match-string 0))))))
20520 ;; This line has nothing special, look at the previous relevant
20521 ;; line to compute indentation
20523 (beginning-of-line 0)
20524 (while (and (not (bobp))
20525 (not (looking-at org-drawer-regexp))
20526 ;; When point started in an inline task, do not move
20527 ;; above task starting line.
20528 (not (and inline-task-p (looking-at inline-re)))
20529 ;; Skip drawers, blocks, empty lines, verbatim,
20530 ;; comments, tables, footnotes definitions, lists,
20531 ;; inline tasks.
20532 (or (and (looking-at "[ \t]*:END:")
20533 (re-search-backward org-drawer-regexp nil t))
20534 (and (looking-at "[ \t]*#\\+end_")
20535 (re-search-backward "[ \t]*#\\+begin_"nil t))
20536 (looking-at "[ \t]*[\n:#|]")
20537 (looking-at org-footnote-definition-re)
20538 (and (ignore-errors (goto-char (org-in-item-p)))
20539 (goto-char
20540 (org-list-get-top-point (org-list-struct))))
20541 (and (not inline-task-p)
20542 (featurep 'org-inlinetask)
20543 (org-inlinetask-in-task-p)
20544 (or (org-inlinetask-goto-beginning) t))))
20545 (beginning-of-line 0))
20546 (cond
20547 ;; There was an heading above.
20548 ((looking-at "\\*+[ \t]+")
20549 (if (not org-adapt-indentation)
20550 (setq column 0)
20551 (goto-char (match-end 0))
20552 (setq column (current-column))))
20553 ;; A drawer had started and is unfinished
20554 ((looking-at org-drawer-regexp)
20555 (goto-char (1- (match-beginning 1)))
20556 (setq column (current-column)))
20557 ;; Else, nothing noticeable found: get indentation and go on.
20558 (t (setq column (org-get-indentation))))))
20559 ;; Now apply indentation and move cursor accordingly
20560 (goto-char pos)
20561 (if (<= (current-column) (current-indentation))
20562 (org-indent-line-to column)
20563 (save-excursion (org-indent-line-to column)))
20564 ;; Special polishing for properties, see `org-property-format'
20565 (setq column (current-column))
20566 (beginning-of-line 1)
20567 (if (looking-at
20568 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20569 (replace-match (concat (match-string 1)
20570 (format org-property-format
20571 (match-string 2) (match-string 3)))
20572 t t))
20573 (org-move-to-column column)
20574 (when (and orgstruct-is-++ (eq pos (point)))
20575 (org-let org-fb-vars
20576 '(indent-according-to-mode)))))
20578 (defun org-indent-drawer ()
20579 "Indent the drawer at point."
20580 (interactive)
20581 (let ((p (point))
20582 (e (and (save-excursion (re-search-forward ":END:" nil t))
20583 (match-end 0)))
20584 (folded
20585 (save-excursion
20586 (end-of-line)
20587 (when (overlays-at (point))
20588 (member 'invisible (overlay-properties
20589 (car (overlays-at (point)))))))))
20590 (when folded (org-cycle))
20591 (indent-for-tab-command)
20592 (while (and (move-beginning-of-line 2) (< (point) e))
20593 (indent-for-tab-command))
20594 (goto-char p)
20595 (when folded (org-cycle)))
20596 (message "Drawer at point indented"))
20598 (defun org-indent-block ()
20599 "Indent the block at point."
20600 (interactive)
20601 (let ((p (point))
20602 (case-fold-search t)
20603 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20604 (match-end 0)))
20605 (folded
20606 (save-excursion
20607 (end-of-line)
20608 (when (overlays-at (point))
20609 (member 'invisible (overlay-properties
20610 (car (overlays-at (point)))))))))
20611 (when folded (org-cycle))
20612 (indent-for-tab-command)
20613 (while (and (move-beginning-of-line 2) (< (point) e))
20614 (indent-for-tab-command))
20615 (goto-char p)
20616 (when folded (org-cycle)))
20617 (message "Block at point indented"))
20619 ;; For reference, this is the default value of adaptive-fill-regexp
20620 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20621 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20622 "Variable to store copy of `adaptive-fill-regexp'.
20623 Since `adaptive-fill-regexp' is set to never match, we need to
20624 store a backup of its value before entering `org-mode' so that
20625 the functionality can be provided as a fall-back.")
20627 (defun org-set-autofill-regexps ()
20628 (interactive)
20629 ;; In the paragraph separator we include headlines, because filling
20630 ;; text in a line directly attached to a headline would otherwise
20631 ;; fill the headline as well.
20632 (org-set-local 'comment-start-skip "^#+[ \t]*")
20633 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20634 ;; The paragraph starter includes hand-formatted lists.
20635 (org-set-local
20636 'paragraph-start
20637 (concat
20638 "\f" "\\|"
20639 "[ ]*$" "\\|"
20640 org-outline-regexp "\\|"
20641 "[ \t]*#" "\\|"
20642 (org-item-re) "\\|"
20643 "[ \t]*[:|]" "\\|"
20644 "\\$\\$" "\\|"
20645 "\\\\\\(begin\\|end\\|[][]\\)"))
20646 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20647 ;; But only if the user has not turned off tables or fixed-width regions
20648 (org-set-local
20649 'auto-fill-inhibit-regexp
20650 (concat org-outline-regexp
20651 "\\|#\\+"
20652 "\\|[ \t]*" org-keyword-time-regexp
20653 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20654 (concat
20655 "\\|[ \t]*["
20656 (if org-enable-table-editor "|" "")
20657 (if org-enable-fixed-width-editor ":" "")
20658 "]"))))
20659 ;; We use our own fill-paragraph function, to make sure that tables
20660 ;; and fixed-width regions are not wrapped. That function will pass
20661 ;; through to `fill-paragraph' when appropriate.
20662 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20663 ;; Prevent auto-fill from inserting unwanted new items.
20664 (if (boundp 'fill-nobreak-predicate)
20665 (org-set-local
20666 'fill-nobreak-predicate
20667 (org-uniquify
20668 (append fill-nobreak-predicate
20669 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20670 ;; Adaptive filling: To get full control, first make sure that
20671 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20672 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20673 (org-set-local 'org-adaptive-fill-regexp-backup
20674 adaptive-fill-regexp))
20675 (org-set-local 'adaptive-fill-regexp "\000")
20676 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20677 (org-set-local 'adaptive-fill-function
20678 'org-adaptive-fill-function)
20679 (org-set-local
20680 'align-mode-rules-list
20681 '((org-in-buffer-settings
20682 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20683 (modes . '(org-mode))))))
20685 (defun org-fill-item-nobreak-p ()
20686 "Non-nil when a line break at point would insert a new item."
20687 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20689 (defun org-fill-line-break-nobreak-p ()
20690 "Non-nil when a line break at point would create an Org line break."
20691 (save-excursion
20692 (skip-chars-backward "[ \t]")
20693 (skip-chars-backward "\\\\")
20694 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20696 (defun org-fill-paragraph (&optional justify)
20697 "Re-align a table, pass through to fill-paragraph if no table."
20698 (let ((table-p (org-at-table-p))
20699 (table.el-p (org-at-table.el-p))
20700 (itemp (org-in-item-p)))
20701 (cond ((and (equal (char-after (point-at-bol)) ?*)
20702 (save-excursion (goto-char (point-at-bol))
20703 (looking-at org-outline-regexp)))
20704 t) ; skip headlines
20705 (table.el-p t) ; skip table.el tables
20706 (table-p (org-table-align) t) ; align Org tables
20707 (itemp ; align text in items
20708 (let* ((struct (save-excursion (goto-char itemp)
20709 (org-list-struct)))
20710 (parents (org-list-parents-alist struct))
20711 (children (org-list-get-children itemp struct parents))
20712 beg end prev next prefix)
20713 ;; Determine in which part of item point is: before
20714 ;; first child, after last child, between two
20715 ;; sub-lists, or simply in item if there's no child.
20716 (cond
20717 ((not children)
20718 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20719 beg itemp
20720 end (org-list-get-item-end itemp struct)))
20721 ((< (point) (setq next (car children)))
20722 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20723 beg itemp
20724 end next))
20725 ((> (point) (setq prev (car (last children))))
20726 (setq beg (org-list-get-item-end prev struct)
20727 end (org-list-get-item-end itemp struct)
20728 prefix (save-excursion
20729 (goto-char beg)
20730 (skip-chars-forward " \t")
20731 (make-string (current-column) ?\ ))))
20732 (t (catch 'exit
20733 (while (setq next (pop children))
20734 (if (> (point) next)
20735 (setq prev next)
20736 (setq beg (org-list-get-item-end prev struct)
20737 end next
20738 prefix (save-excursion
20739 (goto-char beg)
20740 (skip-chars-forward " \t")
20741 (make-string (current-column) ?\ )))
20742 (throw 'exit nil))))))
20743 ;; Use `fill-paragraph' with buffer narrowed to item
20744 ;; without any child, and with our computed PREFIX.
20745 (flet ((fill-context-prefix (from to &optional flr) prefix))
20746 (save-restriction
20747 (narrow-to-region beg end)
20748 (save-excursion (fill-paragraph justify)))) t))
20749 ;; Special case where point is not in a list but is on
20750 ;; a paragraph adjacent to a list: make sure this paragraph
20751 ;; doesn't get merged with the end of the list by narrowing
20752 ;; buffer first.
20753 ((and (derived-mode-p 'org-mode)
20754 (save-excursion (forward-paragraph -1)
20755 (setq itemp (org-in-item-p))))
20756 (let ((struct (save-excursion (goto-char itemp)
20757 (org-list-struct))))
20758 (save-restriction
20759 (narrow-to-region (org-list-get-bottom-point struct)
20760 (save-excursion (forward-paragraph 1)
20761 (point)))
20762 (fill-paragraph justify) t)))
20763 ;; Don't fill schedule/deadline line before a paragraph
20764 ;; This only makes sense in real org-mode buffers
20765 ((and (eq major-mode 'org-mode)
20766 (save-excursion (forward-paragraph -1)
20767 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20768 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$")))))
20769 (save-restriction
20770 (narrow-to-region (1+ (match-end 0))
20771 (save-excursion (forward-paragraph 1) (point)))
20772 (fill-paragraph justify) t))
20773 ;; Else fall back on fill-paragraph-function as possibly
20774 ;; defined in `org-fb-vars'
20775 (orgstruct-is-++
20776 (org-let org-fb-vars
20777 '(fill-paragraph justify)))
20778 (t nil))))
20780 (defun org-adaptive-fill-function ()
20781 "Return a fill prefix for org-mode files."
20782 (let (itemp)
20783 (save-excursion
20784 (cond
20785 ;; Comment line
20786 ((looking-at "#[ \t]+")
20787 (match-string-no-properties 0))
20788 ;; Plain list item
20789 ((org-at-item-p)
20790 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20791 ;; Point is in a list after `backward-paragraph': original
20792 ;; point wasn't in the list, or filling would have been taken
20793 ;; care of by `org-auto-fill-function', but the list and the
20794 ;; real paragraph are not separated by a blank line. Thus, move
20795 ;; point after the list to go back to real paragraph and
20796 ;; determine fill-prefix.
20797 ((setq itemp (org-in-item-p))
20798 (goto-char itemp)
20799 (let* ((struct (org-list-struct))
20800 (bottom (org-list-get-bottom-point struct)))
20801 (goto-char bottom)
20802 (make-string (org-get-indentation) ?\ )))
20803 ;; Other text
20804 ((looking-at org-adaptive-fill-regexp-backup)
20805 (match-string-no-properties 0))))))
20807 (defun org-auto-fill-function ()
20808 "Auto-fill function."
20809 (unless (and org-src-prevent-auto-filling (org-in-src-block-p))
20810 (let (itemp prefix)
20811 ;; When in a list, compute an appropriate fill-prefix and make
20812 ;; sure it will be used by `do-auto-fill'.
20813 (cond ((setq itemp (org-in-item-p))
20814 (progn
20815 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20816 (flet ((fill-context-prefix (from to &optional flr) prefix))
20817 (do-auto-fill))))
20818 (orgstruct-is-++
20819 (org-let org-fb-vars
20820 '(do-auto-fill)))
20821 (t (do-auto-fill))))))
20823 ;;; Other stuff.
20825 (defun org-toggle-fixed-width-section (arg)
20826 "Toggle the fixed-width export.
20827 If there is no active region, the QUOTE keyword at the current headline is
20828 inserted or removed. When present, it causes the text between this headline
20829 and the next to be exported as fixed-width text, and unmodified.
20830 If there is an active region, this command adds or removes a colon as the
20831 first character of this line. If the first character of a line is a colon,
20832 this line is also exported in fixed-width font."
20833 (interactive "P")
20834 (let* ((cc 0)
20835 (regionp (org-region-active-p))
20836 (beg (if regionp (region-beginning) (point)))
20837 (end (if regionp (region-end)))
20838 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20839 (case-fold-search nil)
20840 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20841 off)
20842 (if regionp
20843 (save-excursion
20844 (goto-char beg)
20845 (setq cc (current-column))
20846 (beginning-of-line 1)
20847 (setq off (looking-at re))
20848 (while (> nlines 0)
20849 (setq nlines (1- nlines))
20850 (beginning-of-line 1)
20851 (cond
20852 (arg
20853 (org-move-to-column cc t)
20854 (insert ": \n")
20855 (forward-line -1))
20856 ((and off (looking-at re))
20857 (replace-match "" t t nil 1))
20858 ((not off) (org-move-to-column cc t) (insert ": ")))
20859 (forward-line 1)))
20860 (save-excursion
20861 (org-back-to-heading)
20862 (cond
20863 ((looking-at (format org-heading-keyword-regexp-format
20864 org-quote-string))
20865 (goto-char (match-end 1))
20866 (looking-at (concat " +" org-quote-string))
20867 (replace-match "" t t)
20868 (when (eolp) (insert " ")))
20869 ((looking-at org-outline-regexp)
20870 (goto-char (match-end 0))
20871 (insert org-quote-string " ")))))))
20873 (defun org-reftex-citation ()
20874 "Use reftex-citation to insert a citation into the buffer.
20875 This looks for a line like
20877 #+BIBLIOGRAPHY: foo plain option:-d
20879 and derives from it that foo.bib is the bibliography file relevant
20880 for this document. It then installs the necessary environment for RefTeX
20881 to work in this buffer and calls `reftex-citation' to insert a citation
20882 into the buffer.
20884 Export of such citations to both LaTeX and HTML is handled by the contributed
20885 package org-exp-bibtex by Taru Karttunen."
20886 (interactive)
20887 (let ((reftex-docstruct-symbol 'rds)
20888 (reftex-cite-format "\\cite{%l}")
20889 rds bib)
20890 (save-excursion
20891 (save-restriction
20892 (widen)
20893 (let ((case-fold-search t)
20894 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20895 (if (not (save-excursion
20896 (or (re-search-forward re nil t)
20897 (re-search-backward re nil t))))
20898 (error "No bibliography defined in file")
20899 (setq bib (concat (match-string 1) ".bib")
20900 rds (list (list 'bib bib)))))))
20901 (call-interactively 'reftex-citation)))
20903 ;;;; Functions extending outline functionality
20905 (defun org-beginning-of-line (&optional arg)
20906 "Go to the beginning of the current line. If that is invisible, continue
20907 to a visible line beginning. This makes the function of C-a more intuitive.
20908 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20909 first attempt, and only move to after the tags when the cursor is already
20910 beyond the end of the headline."
20911 (interactive "P")
20912 (let ((pos (point))
20913 (special (if (consp org-special-ctrl-a/e)
20914 (car org-special-ctrl-a/e)
20915 org-special-ctrl-a/e))
20916 refpos)
20917 (if (org-bound-and-true-p line-move-visual)
20918 (beginning-of-visual-line 1)
20919 (beginning-of-line 1))
20920 (if (and arg (fboundp 'move-beginning-of-line))
20921 (call-interactively 'move-beginning-of-line)
20922 (if (bobp)
20924 (backward-char 1)
20925 (if (org-truely-invisible-p)
20926 (while (and (not (bobp)) (org-truely-invisible-p))
20927 (backward-char 1)
20928 (beginning-of-line 1))
20929 (forward-char 1))))
20930 (when special
20931 (cond
20932 ((and (looking-at org-complex-heading-regexp)
20933 (= (char-after (match-end 1)) ?\ ))
20934 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20935 (point-at-eol)))
20936 (goto-char
20937 (if (eq special t)
20938 (cond ((> pos refpos) refpos)
20939 ((= pos (point)) refpos)
20940 (t (point)))
20941 (cond ((> pos (point)) (point))
20942 ((not (eq last-command this-command)) (point))
20943 (t refpos)))))
20944 ((org-at-item-p)
20945 ;; Being at an item and not looking at an the item means point
20946 ;; was previously moved to beginning of a visual line, which
20947 ;; doesn't contain the item. Therefore, do nothing special,
20948 ;; just stay here.
20949 (when (looking-at org-list-full-item-re)
20950 ;; Set special position at first white space character after
20951 ;; bullet, and check-box, if any.
20952 (let ((after-bullet
20953 (let ((box (match-end 3)))
20954 (if (not box) (match-end 1)
20955 (let ((after (char-after box)))
20956 (if (and after (= after ? )) (1+ box) box))))))
20957 ;; Special case: Move point to special position when
20958 ;; currently after it or at beginning of line.
20959 (if (eq special t)
20960 (when (or (> pos after-bullet) (= (point) pos))
20961 (goto-char after-bullet))
20962 ;; Reversed case: Move point to special position when
20963 ;; point was already at beginning of line and command is
20964 ;; repeated.
20965 (when (and (= (point) pos) (eq last-command this-command))
20966 (goto-char after-bullet))))))))
20967 (org-no-warnings
20968 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20970 (defun org-end-of-line (&optional arg)
20971 "Go to the end of the line.
20972 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20973 first attempt, and only move to after the tags when the cursor is already
20974 beyond the end of the headline."
20975 (interactive "P")
20976 (let ((special (if (consp org-special-ctrl-a/e)
20977 (cdr org-special-ctrl-a/e)
20978 org-special-ctrl-a/e)))
20979 (cond
20980 ((or (not special) arg
20981 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20982 (call-interactively
20983 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20984 ((fboundp 'move-end-of-line) 'move-end-of-line)
20985 (t 'end-of-line))))
20986 ((org-at-heading-p)
20987 (let ((pos (point)))
20988 (beginning-of-line 1)
20989 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20990 (if (eq special t)
20991 (if (or (< pos (match-beginning 1))
20992 (= pos (match-end 0)))
20993 (goto-char (match-beginning 1))
20994 (goto-char (match-end 0)))
20995 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20996 (goto-char (match-end 0))
20997 (goto-char (match-beginning 1))))
20998 (call-interactively (if (fboundp 'move-end-of-line)
20999 'move-end-of-line
21000 'end-of-line)))))
21001 ((org-at-drawer-p)
21002 (move-end-of-line 1)
21003 (when (overlays-at (1- (point))) (backward-char 1)))
21004 ;; At an item: Move before any hidden text.
21005 (t (call-interactively
21006 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21007 ((fboundp 'move-end-of-line) 'move-end-of-line)
21008 (t 'end-of-line)))))
21009 (org-no-warnings
21010 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21012 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21013 (define-key org-mode-map "\C-e" 'org-end-of-line)
21015 (defun org-backward-sentence (&optional arg)
21016 "Go to beginning of sentence, or beginning of table field.
21017 This will call `backward-sentence' or `org-table-beginning-of-field',
21018 depending on context."
21019 (interactive "P")
21020 (cond
21021 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21022 (t (call-interactively 'backward-sentence))))
21024 (defun org-forward-sentence (&optional arg)
21025 "Go to end of sentence, or end of table field.
21026 This will call `forward-sentence' or `org-table-end-of-field',
21027 depending on context."
21028 (interactive "P")
21029 (cond
21030 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21031 (t (call-interactively 'forward-sentence))))
21033 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21034 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21036 (defun org-kill-line (&optional arg)
21037 "Kill line, to tags or end of line."
21038 (interactive "P")
21039 (cond
21040 ((or (not org-special-ctrl-k)
21041 (bolp)
21042 (not (org-at-heading-p)))
21043 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21044 org-ctrl-k-protect-subtree)
21045 (if (or (eq org-ctrl-k-protect-subtree 'error)
21046 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21047 (error "C-k aborted - would kill hidden subtree")))
21048 (call-interactively
21049 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21050 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21051 (kill-region (point) (match-beginning 1))
21052 (org-set-tags nil t))
21053 (t (kill-region (point) (point-at-eol)))))
21055 (define-key org-mode-map "\C-k" 'org-kill-line)
21057 (defun org-yank (&optional arg)
21058 "Yank. If the kill is a subtree, treat it specially.
21059 This command will look at the current kill and check if is a single
21060 subtree, or a series of subtrees[1]. If it passes the test, and if the
21061 cursor is at the beginning of a line or after the stars of a currently
21062 empty headline, then the yank is handled specially. How exactly depends
21063 on the value of the following variables, both set by default.
21065 org-yank-folded-subtrees
21066 When set, the subtree(s) will be folded after insertion, but only
21067 if doing so would now swallow text after the yanked text.
21069 org-yank-adjusted-subtrees
21070 When set, the subtree will be promoted or demoted in order to
21071 fit into the local outline tree structure, which means that the level
21072 will be adjusted so that it becomes the smaller one of the two
21073 *visible* surrounding headings.
21075 Any prefix to this command will cause `yank' to be called directly with
21076 no special treatment. In particular, a simple \\[universal-argument] prefix \
21077 will just
21078 plainly yank the text as it is.
21080 \[1] The test checks if the first non-white line is a heading
21081 and if there are no other headings with fewer stars."
21082 (interactive "P")
21083 (org-yank-generic 'yank arg))
21085 (defun org-yank-generic (command arg)
21086 "Perform some yank-like command.
21088 This function implements the behavior described in the `org-yank'
21089 documentation. However, it has been generalized to work for any
21090 interactive command with similar behavior."
21092 ;; pretend to be command COMMAND
21093 (setq this-command command)
21095 (if arg
21096 (call-interactively command)
21098 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21099 (and (org-kill-is-subtree-p)
21100 (or (bolp)
21101 (and (looking-at "[ \t]*$")
21102 (string-match
21103 "\\`\\*+\\'"
21104 (buffer-substring (point-at-bol) (point)))))))
21105 swallowp)
21106 (cond
21107 ((and subtreep org-yank-folded-subtrees)
21108 (let ((beg (point))
21109 end)
21110 (if (and subtreep org-yank-adjusted-subtrees)
21111 (org-paste-subtree nil nil 'for-yank)
21112 (call-interactively command))
21114 (setq end (point))
21115 (goto-char beg)
21116 (when (and (bolp) subtreep
21117 (not (setq swallowp
21118 (org-yank-folding-would-swallow-text beg end))))
21119 (org-with-limited-levels
21120 (or (looking-at org-outline-regexp)
21121 (re-search-forward org-outline-regexp-bol end t))
21122 (while (and (< (point) end) (looking-at org-outline-regexp))
21123 (hide-subtree)
21124 (org-cycle-show-empty-lines 'folded)
21125 (condition-case nil
21126 (outline-forward-same-level 1)
21127 (error (goto-char end))))))
21128 (when swallowp
21129 (message
21130 "Inserted text not folded because that would swallow text"))
21132 (goto-char end)
21133 (skip-chars-forward " \t\n\r")
21134 (beginning-of-line 1)
21135 (push-mark beg 'nomsg)))
21136 ((and subtreep org-yank-adjusted-subtrees)
21137 (let ((beg (point-at-bol)))
21138 (org-paste-subtree nil nil 'for-yank)
21139 (push-mark beg 'nomsg)))
21141 (call-interactively command))))))
21143 (defun org-yank-folding-would-swallow-text (beg end)
21144 "Would hide-subtree at BEG swallow any text after END?"
21145 (let (level)
21146 (org-with-limited-levels
21147 (save-excursion
21148 (goto-char beg)
21149 (when (or (looking-at org-outline-regexp)
21150 (re-search-forward org-outline-regexp-bol end t))
21151 (setq level (org-outline-level)))
21152 (goto-char end)
21153 (skip-chars-forward " \t\r\n\v\f")
21154 (if (or (eobp)
21155 (and (bolp) (looking-at org-outline-regexp)
21156 (<= (org-outline-level) level)))
21157 nil ; Nothing would be swallowed
21158 t))))) ; something would swallow
21160 (define-key org-mode-map "\C-y" 'org-yank)
21162 (defun org-truely-invisible-p ()
21163 "Check if point is at a character currently not visible.
21164 This version does not only check the character property, but also
21165 `visible-mode'."
21166 ;; Early versions of noutline don't have `outline-invisible-p'.
21167 (if (org-bound-and-true-p visible-mode)
21169 (outline-invisible-p)))
21171 (defun org-invisible-p2 ()
21172 "Check if point is at a character currently not visible."
21173 (save-excursion
21174 (if (and (eolp) (not (bobp))) (backward-char 1))
21175 ;; Early versions of noutline don't have `outline-invisible-p'.
21176 (outline-invisible-p)))
21178 (defun org-back-to-heading (&optional invisible-ok)
21179 "Call `outline-back-to-heading', but provide a better error message."
21180 (condition-case nil
21181 (outline-back-to-heading invisible-ok)
21182 (error (error "Before first headline at position %d in buffer %s"
21183 (point) (current-buffer)))))
21185 (defun org-beginning-of-defun ()
21186 "Go to the beginning of the subtree, i.e. back to the heading."
21187 (org-back-to-heading))
21188 (defun org-end-of-defun ()
21189 "Go to the end of the subtree."
21190 (org-end-of-subtree nil t))
21192 (defun org-before-first-heading-p ()
21193 "Before first heading?"
21194 (save-excursion
21195 (end-of-line)
21196 (null (re-search-backward org-outline-regexp-bol nil t))))
21198 (defun org-at-heading-p (&optional ignored)
21199 (outline-on-heading-p t))
21200 ;; Compatibility alias with Org versions < 7.8.03
21201 (defalias 'org-on-heading-p 'org-at-heading-p)
21203 (defun org-at-drawer-p nil
21204 "Is cursor at a drawer keyword?"
21205 (save-excursion
21206 (move-beginning-of-line 1)
21207 (looking-at org-drawer-regexp)))
21209 (defun org-at-block-p nil
21210 "Is cursor at a block keyword?"
21211 (save-excursion
21212 (move-beginning-of-line 1)
21213 (looking-at org-block-regexp)))
21215 (defun org-point-at-end-of-empty-headline ()
21216 "If point is at the end of an empty headline, return t, else nil.
21217 If the heading only contains a TODO keyword, it is still still considered
21218 empty."
21219 (and (looking-at "[ \t]*$")
21220 (when org-todo-line-regexp
21221 (save-excursion
21222 (beginning-of-line 1)
21223 (let ((case-fold-search nil))
21224 (looking-at org-todo-line-regexp)
21225 (string= (match-string 3) ""))))))
21227 (defun org-at-heading-or-item-p ()
21228 (or (org-at-heading-p) (org-at-item-p)))
21230 (defun org-at-target-p ()
21231 (or (org-in-regexp org-radio-target-regexp)
21232 (org-in-regexp org-target-regexp)))
21233 ;; Compatibility alias with Org versions < 7.8.03
21234 (defalias 'org-on-target-p 'org-at-target-p)
21236 (defun org-up-heading-all (arg)
21237 "Move to the heading line of which the present line is a subheading.
21238 This function considers both visible and invisible heading lines.
21239 With argument, move up ARG levels."
21240 (if (fboundp 'outline-up-heading-all)
21241 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21242 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21244 (defun org-up-heading-safe ()
21245 "Move to the heading line of which the present line is a subheading.
21246 This version will not throw an error. It will return the level of the
21247 headline found, or nil if no higher level is found.
21249 Also, this function will be a lot faster than `outline-up-heading',
21250 because it relies on stars being the outline starters. This can really
21251 make a significant difference in outlines with very many siblings."
21252 (let (start-level re)
21253 (org-back-to-heading t)
21254 (setq start-level (funcall outline-level))
21255 (if (equal start-level 1)
21257 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21258 (if (re-search-backward re nil t)
21259 (funcall outline-level)))))
21261 (defun org-first-sibling-p ()
21262 "Is this heading the first child of its parents?"
21263 (interactive)
21264 (let ((re org-outline-regexp-bol)
21265 level l)
21266 (unless (org-at-heading-p t)
21267 (error "Not at a heading"))
21268 (setq level (funcall outline-level))
21269 (save-excursion
21270 (if (not (re-search-backward re nil t))
21272 (setq l (funcall outline-level))
21273 (< l level)))))
21275 (defun org-goto-sibling (&optional previous)
21276 "Goto the next sibling, even if it is invisible.
21277 When PREVIOUS is set, go to the previous sibling instead. Returns t
21278 when a sibling was found. When none is found, return nil and don't
21279 move point."
21280 (let ((fun (if previous 're-search-backward 're-search-forward))
21281 (pos (point))
21282 (re org-outline-regexp-bol)
21283 level l)
21284 (when (condition-case nil (org-back-to-heading t) (error nil))
21285 (setq level (funcall outline-level))
21286 (catch 'exit
21287 (or previous (forward-char 1))
21288 (while (funcall fun re nil t)
21289 (setq l (funcall outline-level))
21290 (when (< l level) (goto-char pos) (throw 'exit nil))
21291 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21292 (goto-char pos)
21293 nil))))
21295 (defun org-show-siblings ()
21296 "Show all siblings of the current headline."
21297 (save-excursion
21298 (while (org-goto-sibling) (org-flag-heading nil)))
21299 (save-excursion
21300 (while (org-goto-sibling 'previous)
21301 (org-flag-heading nil))))
21303 (defun org-goto-first-child ()
21304 "Goto the first child, even if it is invisible.
21305 Return t when a child was found. Otherwise don't move point and
21306 return nil."
21307 (let (level (pos (point)) (re org-outline-regexp-bol))
21308 (when (condition-case nil (org-back-to-heading t) (error nil))
21309 (setq level (outline-level))
21310 (forward-char 1)
21311 (if (and (re-search-forward re nil t) (> (outline-level) level))
21312 (progn (goto-char (match-beginning 0)) t)
21313 (goto-char pos) nil))))
21315 (defun org-show-hidden-entry ()
21316 "Show an entry where even the heading is hidden."
21317 (save-excursion
21318 (org-show-entry)))
21320 (defun org-flag-heading (flag &optional entry)
21321 "Flag the current heading. FLAG non-nil means make invisible.
21322 When ENTRY is non-nil, show the entire entry."
21323 (save-excursion
21324 (org-back-to-heading t)
21325 ;; Check if we should show the entire entry
21326 (if entry
21327 (progn
21328 (org-show-entry)
21329 (save-excursion
21330 (and (outline-next-heading)
21331 (org-flag-heading nil))))
21332 (outline-flag-region (max (point-min) (1- (point)))
21333 (save-excursion (outline-end-of-heading) (point))
21334 flag))))
21336 (defun org-get-next-sibling ()
21337 "Move to next heading of the same level, and return point.
21338 If there is no such heading, return nil.
21339 This is like outline-next-sibling, but invisible headings are ok."
21340 (let ((level (funcall outline-level)))
21341 (outline-next-heading)
21342 (while (and (not (eobp)) (> (funcall outline-level) level))
21343 (outline-next-heading))
21344 (if (or (eobp) (< (funcall outline-level) level))
21346 (point))))
21348 (defun org-get-last-sibling ()
21349 "Move to previous heading of the same level, and return point.
21350 If there is no such heading, return nil."
21351 (let ((opoint (point))
21352 (level (funcall outline-level)))
21353 (outline-previous-heading)
21354 (when (and (/= (point) opoint) (outline-on-heading-p t))
21355 (while (and (> (funcall outline-level) level)
21356 (not (bobp)))
21357 (outline-previous-heading))
21358 (if (< (funcall outline-level) level)
21360 (point)))))
21362 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21363 ;; This contains an exact copy of the original function, but it uses
21364 ;; `org-back-to-heading', to make it work also in invisible
21365 ;; trees. And is uses an invisible-OK argument.
21366 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21367 ;; Furthermore, when used inside Org, finding the end of a large subtree
21368 ;; with many children and grandchildren etc, this can be much faster
21369 ;; than the outline version.
21370 (org-back-to-heading invisible-OK)
21371 (let ((first t)
21372 (level (funcall outline-level)))
21373 (if (and (derived-mode-p 'org-mode) (< level 1000))
21374 ;; A true heading (not a plain list item), in Org-mode
21375 ;; This means we can easily find the end by looking
21376 ;; only for the right number of stars. Using a regexp to do
21377 ;; this is so much faster than using a Lisp loop.
21378 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21379 (forward-char 1)
21380 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21381 ;; something else, do it the slow way
21382 (while (and (not (eobp))
21383 (or first (> (funcall outline-level) level)))
21384 (setq first nil)
21385 (outline-next-heading)))
21386 (unless to-heading
21387 (if (memq (preceding-char) '(?\n ?\^M))
21388 (progn
21389 ;; Go to end of line before heading
21390 (forward-char -1)
21391 (if (memq (preceding-char) '(?\n ?\^M))
21392 ;; leave blank line before heading
21393 (forward-char -1))))))
21394 (point))
21396 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21397 "Use Org version in org-mode, for dramatic speed-up."
21398 (if (derived-mode-p 'org-mode)
21399 (progn
21400 (org-end-of-subtree nil t)
21401 (unless (eobp) (backward-char 1)))
21402 ad-do-it))
21404 (defun org-end-of-meta-data-and-drawers ()
21405 "Jump to the first text after meta data and drawers in the current entry.
21406 This will move over empty lines, lines with planning time stamps,
21407 clocking lines, and drawers."
21408 (org-back-to-heading t)
21409 (let ((end (save-excursion (outline-next-heading) (point)))
21410 (re (concat "\\(" org-drawer-regexp "\\)"
21411 "\\|" "[ \t]*" org-keyword-time-regexp)))
21412 (forward-line 1)
21413 (while (re-search-forward re end t)
21414 (if (not (match-end 1))
21415 ;; empty or planning line
21416 (forward-line 1)
21417 ;; a drawer, find the end
21418 (re-search-forward "^[ \t]*:END:" end 'move)
21419 (forward-line 1)))
21420 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21421 (point)))
21423 (defun org-forward-same-level (arg &optional invisible-ok)
21424 "Move forward to the arg'th subheading at same level as this one.
21425 Stop at the first and last subheadings of a superior heading.
21426 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21427 it wil also look at invisible ones."
21428 (interactive "p")
21429 (org-back-to-heading invisible-ok)
21430 (org-at-heading-p)
21431 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21432 (re (format "^\\*\\{1,%d\\} " level))
21434 (forward-char 1)
21435 (while (> arg 0)
21436 (while (and (re-search-forward re nil 'move)
21437 (setq l (- (match-end 0) (match-beginning 0) 1))
21438 (= l level)
21439 (not invisible-ok)
21440 (progn (backward-char 1) (outline-invisible-p)))
21441 (if (< l level) (setq arg 1)))
21442 (setq arg (1- arg)))
21443 (beginning-of-line 1)))
21445 (defun org-backward-same-level (arg &optional invisible-ok)
21446 "Move backward to the arg'th subheading at same level as this one.
21447 Stop at the first and last subheadings of a superior heading."
21448 (interactive "p")
21449 (org-back-to-heading)
21450 (org-at-heading-p)
21451 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21452 (re (format "^\\*\\{1,%d\\} " level))
21454 (while (> arg 0)
21455 (while (and (re-search-backward re nil 'move)
21456 (setq l (- (match-end 0) (match-beginning 0) 1))
21457 (= l level)
21458 (not invisible-ok)
21459 (outline-invisible-p))
21460 (if (< l level) (setq arg 1)))
21461 (setq arg (1- arg)))))
21463 (defun org-show-subtree ()
21464 "Show everything after this heading at deeper levels."
21465 (interactive)
21466 (outline-flag-region
21467 (point)
21468 (save-excursion
21469 (org-end-of-subtree t t))
21470 nil))
21472 (defun org-show-entry ()
21473 "Show the body directly following this heading.
21474 Show the heading too, if it is currently invisible."
21475 (interactive)
21476 (save-excursion
21477 (condition-case nil
21478 (progn
21479 (org-back-to-heading t)
21480 (outline-flag-region
21481 (max (point-min) (1- (point)))
21482 (save-excursion
21483 (if (re-search-forward
21484 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21485 (match-beginning 1)
21486 (point-max)))
21487 nil)
21488 (org-cycle-hide-drawers 'children))
21489 (error nil))))
21491 (defun org-make-options-regexp (kwds &optional extra)
21492 "Make a regular expression for keyword lines."
21493 (concat
21495 "#?[ \t]*\\+\\("
21496 (mapconcat 'regexp-quote kwds "\\|")
21497 (if extra (concat "\\|" extra))
21498 "\\):[ \t]*"
21499 "\\(.*\\)"))
21501 ;; Make isearch reveal the necessary context
21502 (defun org-isearch-end ()
21503 "Reveal context after isearch exits."
21504 (when isearch-success ; only if search was successful
21505 (if (featurep 'xemacs)
21506 ;; Under XEmacs, the hook is run in the correct place,
21507 ;; we directly show the context.
21508 (org-show-context 'isearch)
21509 ;; In Emacs the hook runs *before* restoring the overlays.
21510 ;; So we have to use a one-time post-command-hook to do this.
21511 ;; (Emacs 22 has a special variable, see function `org-mode')
21512 (unless (and (boundp 'isearch-mode-end-hook-quit)
21513 isearch-mode-end-hook-quit)
21514 ;; Only when the isearch was not quitted.
21515 (org-add-hook 'post-command-hook 'org-isearch-post-command
21516 'append 'local)))))
21518 (defun org-isearch-post-command ()
21519 "Remove self from hook, and show context."
21520 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21521 (org-show-context 'isearch))
21524 ;;;; Integration with and fixes for other packages
21526 ;;; Imenu support
21528 (defvar org-imenu-markers nil
21529 "All markers currently used by Imenu.")
21530 (make-variable-buffer-local 'org-imenu-markers)
21532 (defun org-imenu-new-marker (&optional pos)
21533 "Return a new marker for use by Imenu, and remember the marker."
21534 (let ((m (make-marker)))
21535 (move-marker m (or pos (point)))
21536 (push m org-imenu-markers)
21539 (defun org-imenu-get-tree ()
21540 "Produce the index for Imenu."
21541 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21542 (setq org-imenu-markers nil)
21543 (let* ((n org-imenu-depth)
21544 (re (concat "^" (org-get-limited-outline-regexp)))
21545 (subs (make-vector (1+ n) nil))
21546 (last-level 0)
21547 m level head)
21548 (save-excursion
21549 (save-restriction
21550 (widen)
21551 (goto-char (point-max))
21552 (while (re-search-backward re nil t)
21553 (setq level (org-reduced-level (funcall outline-level)))
21554 (when (and (<= level n)
21555 (looking-at org-complex-heading-regexp))
21556 (setq head (org-link-display-format
21557 (org-match-string-no-properties 4))
21558 m (org-imenu-new-marker))
21559 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21560 (if (>= level last-level)
21561 (push (cons head m) (aref subs level))
21562 (push (cons head (aref subs (1+ level))) (aref subs level))
21563 (loop for i from (1+ level) to n do (aset subs i nil)))
21564 (setq last-level level)))))
21565 (aref subs 1)))
21567 (eval-after-load "imenu"
21568 '(progn
21569 (add-hook 'imenu-after-jump-hook
21570 (lambda ()
21571 (if (derived-mode-p 'org-mode)
21572 (org-show-context 'org-goto))))))
21574 (defun org-link-display-format (link)
21575 "Replace a link with either the description, or the link target
21576 if no description is present"
21577 (save-match-data
21578 (if (string-match org-bracket-link-analytic-regexp link)
21579 (replace-match (if (match-end 5)
21580 (match-string 5 link)
21581 (concat (match-string 1 link)
21582 (match-string 3 link)))
21583 nil t link)
21584 link)))
21586 (defun org-toggle-link-display ()
21587 "Toggle the literal or descriptive display of links."
21588 (interactive)
21589 (if org-descriptive-links
21590 (progn (org-remove-from-invisibility-spec '(org-link))
21591 (org-restart-font-lock)
21592 (setq org-descriptive-links nil))
21593 (progn (add-to-invisibility-spec '(org-link))
21594 (org-restart-font-lock)
21595 (setq org-descriptive-links t))))
21597 ;; Speedbar support
21599 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21600 "Overlay marking the agenda restriction line in speedbar.")
21601 (overlay-put org-speedbar-restriction-lock-overlay
21602 'face 'org-agenda-restriction-lock)
21603 (overlay-put org-speedbar-restriction-lock-overlay
21604 'help-echo "Agendas are currently limited to this item.")
21605 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21607 (defun org-speedbar-set-agenda-restriction ()
21608 "Restrict future agenda commands to the location at point in speedbar.
21609 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21610 (interactive)
21611 (require 'org-agenda)
21612 (let (p m tp np dir txt)
21613 (cond
21614 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21615 'org-imenu t))
21616 (setq m (get-text-property p 'org-imenu-marker))
21617 (with-current-buffer (marker-buffer m)
21618 (goto-char m)
21619 (org-agenda-set-restriction-lock 'subtree)))
21620 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21621 'speedbar-function 'speedbar-find-file))
21622 (setq tp (previous-single-property-change
21623 (1+ p) 'speedbar-function)
21624 np (next-single-property-change
21625 tp 'speedbar-function)
21626 dir (speedbar-line-directory)
21627 txt (buffer-substring-no-properties (or tp (point-min))
21628 (or np (point-max))))
21629 (with-current-buffer (find-file-noselect
21630 (let ((default-directory dir))
21631 (expand-file-name txt)))
21632 (unless (derived-mode-p 'org-mode)
21633 (error "Cannot restrict to non-Org-mode file"))
21634 (org-agenda-set-restriction-lock 'file)))
21635 (t (error "Don't know how to restrict Org-mode's agenda")))
21636 (move-overlay org-speedbar-restriction-lock-overlay
21637 (point-at-bol) (point-at-eol))
21638 (setq current-prefix-arg nil)
21639 (org-agenda-maybe-redo)))
21641 (eval-after-load "speedbar"
21642 '(progn
21643 (speedbar-add-supported-extension ".org")
21644 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21645 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21646 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21647 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21648 (add-hook 'speedbar-visiting-tag-hook
21649 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
21651 ;;; Fixes and Hacks for problems with other packages
21653 ;; Make flyspell not check words in links, to not mess up our keymap
21654 (defun org-mode-flyspell-verify ()
21655 "Don't let flyspell put overlays at active buttons, or on
21656 {todo,all-time,additional-option-like}-keywords."
21657 (let ((pos (max (1- (point)) (point-min)))
21658 (word (thing-at-point 'word)))
21659 (and (not (get-text-property pos 'keymap))
21660 (not (get-text-property pos 'org-no-flyspell))
21661 (not (member word org-todo-keywords-1))
21662 (not (member word org-all-time-keywords))
21663 (not (member word org-additional-option-like-keywords)))))
21665 (defun org-remove-flyspell-overlays-in (beg end)
21666 "Remove flyspell overlays in region."
21667 (and (org-bound-and-true-p flyspell-mode)
21668 (fboundp 'flyspell-delete-region-overlays)
21669 (flyspell-delete-region-overlays beg end))
21670 (add-text-properties beg end '(org-no-flyspell t)))
21672 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21673 (eval-after-load "bookmark"
21674 '(if (boundp 'bookmark-after-jump-hook)
21675 ;; We can use the hook
21676 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21677 ;; Hook not available, use advice
21678 (defadvice bookmark-jump (after org-make-visible activate)
21679 "Make the position visible."
21680 (org-bookmark-jump-unhide))))
21682 ;; Make sure saveplace shows the location if it was hidden
21683 (eval-after-load "saveplace"
21684 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21685 "Make the position visible."
21686 (org-bookmark-jump-unhide)))
21688 ;; Make sure ecb shows the location if it was hidden
21689 (eval-after-load "ecb"
21690 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21691 "Make hierarchy visible when jumping into location from ECB tree buffer."
21692 (if (derived-mode-p 'org-mode)
21693 (org-show-context))))
21695 (defun org-bookmark-jump-unhide ()
21696 "Unhide the current position, to show the bookmark location."
21697 (and (derived-mode-p 'org-mode)
21698 (or (outline-invisible-p)
21699 (save-excursion (goto-char (max (point-min) (1- (point))))
21700 (outline-invisible-p)))
21701 (org-show-context 'bookmark-jump)))
21703 ;; Make session.el ignore our circular variable
21704 (eval-after-load "session"
21705 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21707 ;;;; Experimental code
21709 (defun org-closed-in-range ()
21710 "Sparse tree of items closed in a certain time range.
21711 Still experimental, may disappear in the future."
21712 (interactive)
21713 ;; Get the time interval from the user.
21714 (let* ((time1 (org-float-time
21715 (org-read-date nil 'to-time nil "Starting date: ")))
21716 (time2 (org-float-time
21717 (org-read-date nil 'to-time nil "End date:")))
21718 ;; callback function
21719 (callback (lambda ()
21720 (let ((time
21721 (org-float-time
21722 (apply 'encode-time
21723 (org-parse-time-string
21724 (match-string 1))))))
21725 ;; check if time in interval
21726 (and (>= time time1) (<= time time2))))))
21727 ;; make tree, check each match with the callback
21728 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21730 ;;;; Finish up
21732 (provide 'org)
21734 (run-hooks 'org-load-hook)
21736 ;;; org.el ends here