org-element: Handle special cases in setter functions
[org-mode.git] / lisp / org.el
blob3ad80cb194a4c6c2a81611fdec975ba1c68633f1
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 ;; fallback definitions if everything goes wrong
213 (defun org-release () "N/A")
214 (defun org-git-version () "N/A !!check installation!!")
215 ;; re-define them with something sensible if possible
216 (when (eval-when-compile
217 (require 'org-fixup
218 (concat (org-find-library-dir "org") "../UTILITIES/org-fixup.el")
219 'noerror))
220 (org-fixup))
221 ;;;###autoload
222 (defun org-version (&optional here full message)
223 "Show the org-mode version in the echo area.
224 With prefix arg HERE, insert it at point."
225 (interactive "P")
226 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
227 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
228 (org-trash (or
229 (and (fboundp 'org-release) (fboundp 'org-git-version))
230 (load (concat org-dir "org-version.el")
231 'noerror 'nomessage 'nosuffix)))
232 (org-version (org-release))
233 (git-version (org-git-version))
234 (version (format "Org-mode version %s (%s @ %s)"
235 org-version
236 git-version
237 (if org-install-dir
238 (if (string= org-dir org-install-dir)
239 org-install-dir
240 (concat "mixed installation! " org-install-dir " and " org-dir))
241 "org-install.el can not be found!")))
242 (_version (if full version org-version)))
243 (if (org-called-interactively-p 'interactive)
244 (if here
245 (insert version)
246 (message version))
247 (if message (message _version))
248 _version)))
250 ;;; Compatibility constants
252 ;;; The custom variables
254 (defgroup org nil
255 "Outline-based notes management and organizer."
256 :tag "Org"
257 :group 'outlines
258 :group 'calendar)
260 (defcustom org-mode-hook nil
261 "Mode hook for Org-mode, run after the mode was turned on."
262 :group 'org
263 :type 'hook)
265 (defcustom org-load-hook nil
266 "Hook that is run after org.el has been loaded."
267 :group 'org
268 :type 'hook)
270 (defcustom org-log-buffer-setup-hook nil
271 "Hook that is run after an Org log buffer is created."
272 :group 'org
273 :version "24.1"
274 :type 'hook)
276 (defvar org-modules) ; defined below
277 (defvar org-modules-loaded nil
278 "Have the modules been loaded already?")
280 (defun org-load-modules-maybe (&optional force)
281 "Load all extensions listed in `org-modules'."
282 (when (or force (not org-modules-loaded))
283 (mapc (lambda (ext)
284 (condition-case nil (require ext)
285 (error (message "Problems while trying to load feature `%s'" ext))))
286 org-modules)
287 (setq org-modules-loaded t)))
289 (defun org-set-modules (var value)
290 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
291 (set var value)
292 (when (featurep 'org)
293 (org-load-modules-maybe 'force)))
295 (when (org-bound-and-true-p org-modules)
296 (let ((a (member 'org-infojs org-modules)))
297 (and a (setcar a 'org-jsinfo))))
299 (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)
300 "Modules that should always be loaded together with org.el.
301 If a description starts with <C>, the file is not part of Emacs
302 and loading it will require that you have downloaded and properly installed
303 the org-mode distribution.
305 You can also use this system to load external packages (i.e. neither Org
306 core modules, nor modules from the CONTRIB directory). Just add symbols
307 to the end of the list. If the package is called org-xyz.el, then you need
308 to add the symbol `xyz', and the package must have a call to
310 (provide 'org-xyz)"
311 :group 'org
312 :set 'org-set-modules
313 :type
314 '(set :greedy t
315 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
316 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
317 (const :tag " crypt: Encryption of subtrees" org-crypt)
318 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
319 (const :tag " docview: Links to doc-view buffers" org-docview)
320 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
321 (const :tag " id: Global IDs for identifying entries" org-id)
322 (const :tag " info: Links to Info nodes" org-info)
323 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
324 (const :tag " habit: Track your consistency with habits" org-habit)
325 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
326 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
327 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
328 (const :tag " mew Links to Mew folders/messages" org-mew)
329 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
330 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
331 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
332 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
333 (const :tag " vm: Links to VM folders/messages" org-vm)
334 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
335 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
336 (const :tag " mouse: Additional mouse support" org-mouse)
337 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
339 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
340 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
341 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
342 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
343 (const :tag "C collector: Collect properties into tables" org-collector)
344 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
345 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
346 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
347 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
348 (const :tag "C eval: Include command output as text" org-eval)
349 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
350 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
351 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
352 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
353 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
355 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
357 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
358 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
359 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
360 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
361 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
362 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
363 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
364 (const :tag "C mtags: Support for muse-like tags" org-mtags)
365 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
366 (const :tag "C registry: A registry for Org-mode links" org-registry)
367 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
368 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
369 (const :tag "C secretary: Team management with org-mode" org-secretary)
370 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
371 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
372 (const :tag "C track: Keep up with Org-mode development" org-track)
373 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
374 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
375 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
377 (defcustom org-support-shift-select nil
378 "Non-nil means make shift-cursor commands select text when possible.
380 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
381 start selecting a region, or enlarge regions started in this way.
382 In Org-mode, in special contexts, these same keys are used for
383 other purposes, important enough to compete with shift selection.
384 Org tries to balance these needs by supporting `shift-select-mode'
385 outside these special contexts, under control of this variable.
387 The default of this variable is nil, to avoid confusing behavior. Shifted
388 cursor keys will then execute Org commands in the following contexts:
389 - on a headline, changing TODO state (left/right) and priority (up/down)
390 - on a time stamp, changing the time
391 - in a plain list item, changing the bullet type
392 - in a property definition line, switching between allowed values
393 - in the BEGIN line of a clock table (changing the time block).
394 Outside these contexts, the commands will throw an error.
396 When this variable is t and the cursor is not in a special
397 context, Org-mode will support shift-selection for making and
398 enlarging regions. To make this more effective, the bullet
399 cycling will no longer happen anywhere in an item line, but only
400 if the cursor is exactly on the bullet.
402 If you set this variable to the symbol `always', then the keys
403 will not be special in headlines, property lines, and item lines,
404 to make shift selection work there as well. If this is what you
405 want, you can use the following alternative commands: `C-c C-t'
406 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
407 can be used to switch TODO sets, `C-c -' to cycle item bullet
408 types, and properties can be edited by hand or in column view.
410 However, when the cursor is on a timestamp, shift-cursor commands
411 will still edit the time stamp - this is just too good to give up.
413 XEmacs user should have this variable set to nil, because
414 `shift-select-mode' is in Emacs 23 or later only."
415 :group 'org
416 :type '(choice
417 (const :tag "Never" nil)
418 (const :tag "When outside special context" t)
419 (const :tag "Everywhere except timestamps" always)))
421 (defcustom org-loop-over-headlines-in-active-region nil
422 "Shall some commands act upon headlines in the active region?
424 When set to `t', some commands will be performed in all headlines
425 within the active region.
427 When set to `start-level', some commands will be performed in all
428 headlines within the active region, provided that these headlines
429 are of the same level than the first one.
431 When set to a string, those commands will be performed on the
432 matching headlines within the active region. Such string must be
433 a tags/property/todo match as it is used in the agenda tags view.
435 The list of commands is: `org-schedule', `org-deadline',
436 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
437 `org-archive-to-archive-sibling'. The archiving commands skip
438 already archived entries."
439 :type '(choice (const :tag "Don't loop" nil)
440 (const :tag "All headlines in active region" t)
441 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
442 (string :tag "Tags/Property/Todo matcher"))
443 :version "24.1"
444 :group 'org-todo
445 :group 'org-archive)
447 (defgroup org-startup nil
448 "Options concerning startup of Org-mode."
449 :tag "Org Startup"
450 :group 'org)
452 (defcustom org-startup-folded t
453 "Non-nil means entering Org-mode will switch to OVERVIEW.
454 This can also be configured on a per-file basis by adding one of
455 the following lines anywhere in the buffer:
457 #+STARTUP: fold (or `overview', this is equivalent)
458 #+STARTUP: nofold (or `showall', this is equivalent)
459 #+STARTUP: content
460 #+STARTUP: showeverything"
461 :group 'org-startup
462 :type '(choice
463 (const :tag "nofold: show all" nil)
464 (const :tag "fold: overview" t)
465 (const :tag "content: all headlines" content)
466 (const :tag "show everything, even drawers" showeverything)))
468 (defcustom org-startup-truncated t
469 "Non-nil means entering Org-mode will set `truncate-lines'.
470 This is useful since some lines containing links can be very long and
471 uninteresting. Also tables look terrible when wrapped."
472 :group 'org-startup
473 :type 'boolean)
475 (defcustom org-startup-indented nil
476 "Non-nil means turn on `org-indent-mode' on startup.
477 This can also be configured on a per-file basis by adding one of
478 the following lines anywhere in the buffer:
480 #+STARTUP: indent
481 #+STARTUP: noindent"
482 :group 'org-structure
483 :type '(choice
484 (const :tag "Not" nil)
485 (const :tag "Globally (slow on startup in large files)" t)))
487 (defcustom org-use-sub-superscripts t
488 "Non-nil means interpret \"_\" and \"^\" for export.
489 When this option is turned on, you can use TeX-like syntax for sub- and
490 superscripts. Several characters after \"_\" or \"^\" will be
491 considered as a single item - so grouping with {} is normally not
492 needed. For example, the following things will be parsed as single
493 sub- or superscripts.
495 10^24 or 10^tau several digits will be considered 1 item.
496 10^-12 or 10^-tau a leading sign with digits or a word
497 x^2-y^3 will be read as x^2 - y^3, because items are
498 terminated by almost any nonword/nondigit char.
499 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
501 Still, ambiguity is possible - so when in doubt use {} to enclose the
502 sub/superscript. If you set this variable to the symbol `{}',
503 the braces are *required* in order to trigger interpretations as
504 sub/superscript. This can be helpful in documents that need \"_\"
505 frequently in plain text.
507 Not all export backends support this, but HTML does.
509 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
510 :group 'org-startup
511 :group 'org-export-translation
512 :version "24.1"
513 :type '(choice
514 (const :tag "Always interpret" t)
515 (const :tag "Only with braces" {})
516 (const :tag "Never interpret" nil)))
518 (if (fboundp 'defvaralias)
519 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
522 (defcustom org-startup-with-beamer-mode nil
523 "Non-nil means turn on `org-beamer-mode' on startup.
524 This can also be configured on a per-file basis by adding one of
525 the following lines anywhere in the buffer:
527 #+STARTUP: beamer"
528 :group 'org-startup
529 :version "24.1"
530 :type 'boolean)
532 (defcustom org-startup-align-all-tables nil
533 "Non-nil means align all tables when visiting a file.
534 This is useful when the column width in tables is forced with <N> cookies
535 in table fields. Such tables will look correct only after the first re-align.
536 This can also be configured on a per-file basis by adding one of
537 the following lines anywhere in the buffer:
538 #+STARTUP: align
539 #+STARTUP: noalign"
540 :group 'org-startup
541 :type 'boolean)
543 (defcustom org-startup-with-inline-images nil
544 "Non-nil means show inline images when loading a new Org file.
545 This can also be configured on a per-file basis by adding one of
546 the following lines anywhere in the buffer:
547 #+STARTUP: inlineimages
548 #+STARTUP: noinlineimages"
549 :group 'org-startup
550 :version "24.1"
551 :type 'boolean)
553 (defcustom org-insert-mode-line-in-empty-file nil
554 "Non-nil means insert the first line setting Org-mode in empty files.
555 When the function `org-mode' is called interactively in an empty file, this
556 normally means that the file name does not automatically trigger Org-mode.
557 To ensure that the file will always be in Org-mode in the future, a
558 line enforcing Org-mode will be inserted into the buffer, if this option
559 has been set."
560 :group 'org-startup
561 :type 'boolean)
563 (defcustom org-replace-disputed-keys nil
564 "Non-nil means use alternative key bindings for some keys.
565 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
566 These keys are also used by other packages like shift-selection-mode'
567 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
568 If you want to use Org-mode together with one of these other modes,
569 or more generally if you would like to move some Org-mode commands to
570 other keys, set this variable and configure the keys with the variable
571 `org-disputed-keys'.
573 This option is only relevant at load-time of Org-mode, and must be set
574 *before* org.el is loaded. Changing it requires a restart of Emacs to
575 become effective."
576 :group 'org-startup
577 :type 'boolean)
579 (defcustom org-use-extra-keys nil
580 "Non-nil means use extra key sequence definitions for certain commands.
581 This happens automatically if you run XEmacs or if `window-system'
582 is nil. This variable lets you do the same manually. You must
583 set it before loading org.
585 Example: on Carbon Emacs 22 running graphically, with an external
586 keyboard on a Powerbook, the default way of setting M-left might
587 not work for either Alt or ESC. Setting this variable will make
588 it work for ESC."
589 :group 'org-startup
590 :type 'boolean)
592 (if (fboundp 'defvaralias)
593 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
595 (defcustom org-disputed-keys
596 '(([(shift up)] . [(meta p)])
597 ([(shift down)] . [(meta n)])
598 ([(shift left)] . [(meta -)])
599 ([(shift right)] . [(meta +)])
600 ([(control shift right)] . [(meta shift +)])
601 ([(control shift left)] . [(meta shift -)]))
602 "Keys for which Org-mode and other modes compete.
603 This is an alist, cars are the default keys, second element specifies
604 the alternative to use when `org-replace-disputed-keys' is t.
606 Keys can be specified in any syntax supported by `define-key'.
607 The value of this option takes effect only at Org-mode's startup,
608 therefore you'll have to restart Emacs to apply it after changing."
609 :group 'org-startup
610 :type 'alist)
612 (defun org-key (key)
613 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
614 Or return the original if not disputed.
615 Also apply the translations defined in `org-xemacs-key-equivalents'."
616 (when org-replace-disputed-keys
617 (let* ((nkey (key-description key))
618 (x (org-find-if (lambda (x)
619 (equal (key-description (car x)) nkey))
620 org-disputed-keys)))
621 (setq key (if x (cdr x) key))))
622 (when (featurep 'xemacs)
623 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
624 key)
626 (defun org-find-if (predicate seq)
627 (catch 'exit
628 (while seq
629 (if (funcall predicate (car seq))
630 (throw 'exit (car seq))
631 (pop seq)))))
633 (defun org-defkey (keymap key def)
634 "Define a key, possibly translated, as returned by `org-key'."
635 (define-key keymap (org-key key) def))
637 (defcustom org-ellipsis nil
638 "The ellipsis to use in the Org-mode outline.
639 When nil, just use the standard three dots. When a string, use that instead,
640 When a face, use the standard 3 dots, but with the specified face.
641 The change affects only Org-mode (which will then use its own display table).
642 Changing this requires executing `M-x org-mode' in a buffer to become
643 effective."
644 :group 'org-startup
645 :type '(choice (const :tag "Default" nil)
646 (face :tag "Face" :value org-warning)
647 (string :tag "String" :value "...#")))
649 (defvar org-display-table nil
650 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
652 (defgroup org-keywords nil
653 "Keywords in Org-mode."
654 :tag "Org Keywords"
655 :group 'org)
657 (defcustom org-deadline-string "DEADLINE:"
658 "String to mark deadline entries.
659 A deadline is this string, followed by a time stamp. Should be a word,
660 terminated by a colon. You can insert a schedule keyword and
661 a timestamp with \\[org-deadline].
662 Changes become only effective after restarting Emacs."
663 :group 'org-keywords
664 :type 'string)
666 (defcustom org-scheduled-string "SCHEDULED:"
667 "String to mark scheduled TODO entries.
668 A schedule is this string, followed by a time stamp. Should be a word,
669 terminated by a colon. You can insert a schedule keyword and
670 a timestamp with \\[org-schedule].
671 Changes become only effective after restarting Emacs."
672 :group 'org-keywords
673 :type 'string)
675 (defcustom org-closed-string "CLOSED:"
676 "String used as the prefix for timestamps logging closing a TODO entry."
677 :group 'org-keywords
678 :type 'string)
680 (defcustom org-clock-string "CLOCK:"
681 "String used as prefix for timestamps clocking work hours on an item."
682 :group 'org-keywords
683 :type 'string)
685 (defcustom org-comment-string "COMMENT"
686 "Entries starting with this keyword will never be exported.
687 An entry can be toggled between COMMENT and normal with
688 \\[org-toggle-comment].
689 Changes become only effective after restarting Emacs."
690 :group 'org-keywords
691 :type 'string)
693 (defcustom org-quote-string "QUOTE"
694 "Entries starting with this keyword will be exported in fixed-width font.
695 Quoting applies only to the text in the entry following the headline, and does
696 not extend beyond the next headline, even if that is lower level.
697 An entry can be toggled between QUOTE and normal with
698 \\[org-toggle-fixed-width-section]."
699 :group 'org-keywords
700 :type 'string)
702 (defconst org-repeat-re
703 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
704 "Regular expression for specifying repeated events.
705 After a match, group 1 contains the repeat expression.")
707 (defgroup org-structure nil
708 "Options concerning the general structure of Org-mode files."
709 :tag "Org Structure"
710 :group 'org)
712 (defgroup org-reveal-location nil
713 "Options about how to make context of a location visible."
714 :tag "Org Reveal Location"
715 :group 'org-structure)
717 (defconst org-context-choice
718 '(choice
719 (const :tag "Always" t)
720 (const :tag "Never" nil)
721 (repeat :greedy t :tag "Individual contexts"
722 (cons
723 (choice :tag "Context"
724 (const agenda)
725 (const org-goto)
726 (const occur-tree)
727 (const tags-tree)
728 (const link-search)
729 (const mark-goto)
730 (const bookmark-jump)
731 (const isearch)
732 (const default))
733 (boolean))))
734 "Contexts for the reveal options.")
736 (defcustom org-show-hierarchy-above '((default . t))
737 "Non-nil means show full hierarchy when revealing a location.
738 Org-mode often shows locations in an org-mode file which might have
739 been invisible before. When this is set, the hierarchy of headings
740 above the exposed location is shown.
741 Turning this off for example for sparse trees makes them very compact.
742 Instead of t, this can also be an alist specifying this option for different
743 contexts. Valid contexts are
744 agenda when exposing an entry from the agenda
745 org-goto when using the command `org-goto' on key C-c C-j
746 occur-tree when using the command `org-occur' on key C-c /
747 tags-tree when constructing a sparse tree based on tags matches
748 link-search when exposing search matches associated with a link
749 mark-goto when exposing the jump goal of a mark
750 bookmark-jump when exposing a bookmark location
751 isearch when exiting from an incremental search
752 default default for all contexts not set explicitly"
753 :group 'org-reveal-location
754 :type org-context-choice)
756 (defcustom org-show-following-heading '((default . nil))
757 "Non-nil means show following heading when revealing a location.
758 Org-mode often shows locations in an org-mode file which might have
759 been invisible before. When this is set, the heading following the
760 match is shown.
761 Turning this off for example for sparse trees makes them very compact,
762 but makes it harder to edit the location of the match. In such a case,
763 use the command \\[org-reveal] to show more context.
764 Instead of t, this can also be an alist specifying this option for different
765 contexts. See `org-show-hierarchy-above' for valid contexts."
766 :group 'org-reveal-location
767 :type org-context-choice)
769 (defcustom org-show-siblings '((default . nil) (isearch t))
770 "Non-nil means show all sibling heading when revealing a location.
771 Org-mode often shows locations in an org-mode file which might have
772 been invisible before. When this is set, the sibling of the current entry
773 heading are all made visible. If `org-show-hierarchy-above' is t,
774 the same happens on each level of the hierarchy above the current entry.
776 By default this is on for the isearch context, off for all other contexts.
777 Turning this off for example for sparse trees makes them very compact,
778 but makes it harder to edit the location of the match. In such a case,
779 use the command \\[org-reveal] to show more context.
780 Instead of t, this can also be an alist specifying this option for different
781 contexts. See `org-show-hierarchy-above' for valid contexts."
782 :group 'org-reveal-location
783 :type org-context-choice)
785 (defcustom org-show-entry-below '((default . nil))
786 "Non-nil means show the entry below a headline when revealing a location.
787 Org-mode often shows locations in an org-mode file which might have
788 been invisible before. When this is set, the text below the headline that is
789 exposed is also shown.
791 By default this is off for all contexts.
792 Instead of t, this can also be an alist specifying this option for different
793 contexts. See `org-show-hierarchy-above' for valid contexts."
794 :group 'org-reveal-location
795 :type org-context-choice)
797 (defcustom org-indirect-buffer-display 'other-window
798 "How should indirect tree buffers be displayed?
799 This applies to indirect buffers created with the commands
800 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
801 Valid values are:
802 current-window Display in the current window
803 other-window Just display in another window.
804 dedicated-frame Create one new frame, and re-use it each time.
805 new-frame Make a new frame each time. Note that in this case
806 previously-made indirect buffers are kept, and you need to
807 kill these buffers yourself."
808 :group 'org-structure
809 :group 'org-agenda-windows
810 :type '(choice
811 (const :tag "In current window" current-window)
812 (const :tag "In current frame, other window" other-window)
813 (const :tag "Each time a new frame" new-frame)
814 (const :tag "One dedicated frame" dedicated-frame)))
816 (defcustom org-use-speed-commands nil
817 "Non-nil means activate single letter commands at beginning of a headline.
818 This may also be a function to test for appropriate locations where speed
819 commands should be active."
820 :group 'org-structure
821 :type '(choice
822 (const :tag "Never" nil)
823 (const :tag "At beginning of headline stars" t)
824 (function)))
826 (defcustom org-speed-commands-user nil
827 "Alist of additional speed commands.
828 This list will be checked before `org-speed-commands-default'
829 when the variable `org-use-speed-commands' is non-nil
830 and when the cursor is at the beginning of a headline.
831 The car if each entry is a string with a single letter, which must
832 be assigned to `self-insert-command' in the global map.
833 The cdr is either a command to be called interactively, a function
834 to be called, or a form to be evaluated.
835 An entry that is just a list with a single string will be interpreted
836 as a descriptive headline that will be added when listing the speed
837 commands in the Help buffer using the `?' speed command."
838 :group 'org-structure
839 :type '(repeat :value ("k" . ignore)
840 (choice :value ("k" . ignore)
841 (list :tag "Descriptive Headline" (string :tag "Headline"))
842 (cons :tag "Letter and Command"
843 (string :tag "Command letter")
844 (choice
845 (function)
846 (sexp))))))
848 (defgroup org-cycle nil
849 "Options concerning visibility cycling in Org-mode."
850 :tag "Org Cycle"
851 :group 'org-structure)
853 (defcustom org-cycle-skip-children-state-if-no-children t
854 "Non-nil means skip CHILDREN state in entries that don't have any."
855 :group 'org-cycle
856 :type 'boolean)
858 (defcustom org-cycle-max-level nil
859 "Maximum level which should still be subject to visibility cycling.
860 Levels higher than this will, for cycling, be treated as text, not a headline.
861 When `org-odd-levels-only' is set, a value of N in this variable actually
862 means 2N-1 stars as the limiting headline.
863 When nil, cycle all levels.
864 Note that the limiting level of cycling is also influenced by
865 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
866 `org-inlinetask-min-level' is, cycling will be limited to levels one less
867 than its value."
868 :group 'org-cycle
869 :type '(choice
870 (const :tag "No limit" nil)
871 (integer :tag "Maximum level")))
873 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
874 "Names of drawers. Drawers are not opened by cycling on the headline above.
875 Drawers only open with a TAB on the drawer line itself. A drawer looks like
876 this:
877 :DRAWERNAME:
878 .....
879 :END:
880 The drawer \"PROPERTIES\" is special for capturing properties through
881 the property API.
883 Drawers can be defined on the per-file basis with a line like:
885 #+DRAWERS: HIDDEN STATE PROPERTIES"
886 :group 'org-structure
887 :group 'org-cycle
888 :type '(repeat (string :tag "Drawer Name")))
890 (defcustom org-hide-block-startup nil
891 "Non-nil means entering Org-mode will fold all blocks.
892 This can also be set in on a per-file basis with
894 #+STARTUP: hideblocks
895 #+STARTUP: showblocks"
896 :group 'org-startup
897 :group 'org-cycle
898 :type 'boolean)
900 (defcustom org-cycle-global-at-bob nil
901 "Cycle globally if cursor is at beginning of buffer and not at a headline.
902 This makes it possible to do global cycling without having to use S-TAB or
903 \\[universal-argument] TAB. For this special case to work, the first line \
904 of the buffer
905 must not be a headline - it may be empty or some other text. When used in
906 this way, `org-cycle-hook' is disables temporarily, to make sure the
907 cursor stays at the beginning of the buffer.
908 When this option is nil, don't do anything special at the beginning
909 of the buffer."
910 :group 'org-cycle
911 :type 'boolean)
913 (defcustom org-cycle-level-after-item/entry-creation t
914 "Non-nil means cycle entry level or item indentation in new empty entries.
916 When the cursor is at the end of an empty headline, i.e with only stars
917 and maybe a TODO keyword, TAB will then switch the entry to become a child,
918 and then all possible ancestor states, before returning to the original state.
919 This makes data entry extremely fast: M-RET to create a new headline,
920 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
922 When the cursor is at the end of an empty plain list item, one TAB will
923 make it a subitem, two or more tabs will back up to make this an item
924 higher up in the item hierarchy."
925 :group 'org-cycle
926 :type 'boolean)
928 (defcustom org-cycle-emulate-tab t
929 "Where should `org-cycle' emulate TAB.
930 nil Never
931 white Only in completely white lines
932 whitestart Only at the beginning of lines, before the first non-white char
933 t Everywhere except in headlines
934 exc-hl-bol Everywhere except at the start of a headline
935 If TAB is used in a place where it does not emulate TAB, the current subtree
936 visibility is cycled."
937 :group 'org-cycle
938 :type '(choice (const :tag "Never" nil)
939 (const :tag "Only in completely white lines" white)
940 (const :tag "Before first char in a line" whitestart)
941 (const :tag "Everywhere except in headlines" t)
942 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
945 (defcustom org-cycle-separator-lines 2
946 "Number of empty lines needed to keep an empty line between collapsed trees.
947 If you leave an empty line between the end of a subtree and the following
948 headline, this empty line is hidden when the subtree is folded.
949 Org-mode will leave (exactly) one empty line visible if the number of
950 empty lines is equal or larger to the number given in this variable.
951 So the default 2 means at least 2 empty lines after the end of a subtree
952 are needed to produce free space between a collapsed subtree and the
953 following headline.
955 If the number is negative, and the number of empty lines is at least -N,
956 all empty lines are shown.
958 Special case: when 0, never leave empty lines in collapsed view."
959 :group 'org-cycle
960 :type 'integer)
961 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
963 (defcustom org-pre-cycle-hook nil
964 "Hook that is run before visibility cycling is happening.
965 The function(s) in this hook must accept a single argument which indicates
966 the new state that will be set right after running this hook. The
967 argument is a symbol. Before a global state change, it can have the values
968 `overview', `content', or `all'. Before a local state change, it can have
969 the values `folded', `children', or `subtree'."
970 :group 'org-cycle
971 :type 'hook)
973 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
974 org-cycle-hide-drawers
975 org-cycle-show-empty-lines
976 org-optimize-window-after-visibility-change)
977 "Hook that is run after `org-cycle' has changed the buffer visibility.
978 The function(s) in this hook must accept a single argument which indicates
979 the new state that was set by the most recent `org-cycle' command. The
980 argument is a symbol. After a global state change, it can have the values
981 `overview', `content', or `all'. After a local state change, it can have
982 the values `folded', `children', or `subtree'."
983 :group 'org-cycle
984 :type 'hook)
986 (defgroup org-edit-structure nil
987 "Options concerning structure editing in Org-mode."
988 :tag "Org Edit Structure"
989 :group 'org-structure)
991 (defcustom org-odd-levels-only nil
992 "Non-nil means skip even levels and only use odd levels for the outline.
993 This has the effect that two stars are being added/taken away in
994 promotion/demotion commands. It also influences how levels are
995 handled by the exporters.
996 Changing it requires restart of `font-lock-mode' to become effective
997 for fontification also in regions already fontified.
998 You may also set this on a per-file basis by adding one of the following
999 lines to the buffer:
1001 #+STARTUP: odd
1002 #+STARTUP: oddeven"
1003 :group 'org-edit-structure
1004 :group 'org-appearance
1005 :type 'boolean)
1007 (defcustom org-adapt-indentation t
1008 "Non-nil means adapt indentation to outline node level.
1010 When this variable is set, Org assumes that you write outlines by
1011 indenting text in each node to align with the headline (after the stars).
1012 The following issues are influenced by this variable:
1014 - When this is set and the *entire* text in an entry is indented, the
1015 indentation is increased by one space in a demotion command, and
1016 decreased by one in a promotion command. If any line in the entry
1017 body starts with text at column 0, indentation is not changed at all.
1019 - Property drawers and planning information is inserted indented when
1020 this variable s set. When nil, they will not be indented.
1022 - TAB indents a line relative to context. The lines below a headline
1023 will be indented when this variable is set.
1025 Note that this is all about true indentation, by adding and removing
1026 space characters. See also `org-indent.el' which does level-dependent
1027 indentation in a virtual way, i.e. at display time in Emacs."
1028 :group 'org-edit-structure
1029 :type 'boolean)
1031 (defcustom org-special-ctrl-a/e nil
1032 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1034 When t, `C-a' will bring back the cursor to the beginning of the
1035 headline text, i.e. after the stars and after a possible TODO
1036 keyword. In an item, this will be the position after bullet and
1037 check-box, if any. When the cursor is already at that position,
1038 another `C-a' will bring it to the beginning of the line.
1040 `C-e' will jump to the end of the headline, ignoring the presence
1041 of tags in the headline. A second `C-e' will then jump to the
1042 true end of the line, after any tags. This also means that, when
1043 this variable is non-nil, `C-e' also will never jump beyond the
1044 end of the heading of a folded section, i.e. not after the
1045 ellipses.
1047 When set to the symbol `reversed', the first `C-a' or `C-e' works
1048 normally, going to the true line boundary first. Only a directly
1049 following, identical keypress will bring the cursor to the
1050 special positions.
1052 This may also be a cons cell where the behavior for `C-a' and
1053 `C-e' is set separately."
1054 :group 'org-edit-structure
1055 :type '(choice
1056 (const :tag "off" nil)
1057 (const :tag "on: after stars/bullet and before tags first" t)
1058 (const :tag "reversed: true line boundary first" reversed)
1059 (cons :tag "Set C-a and C-e separately"
1060 (choice :tag "Special C-a"
1061 (const :tag "off" nil)
1062 (const :tag "on: after stars/bullet first" t)
1063 (const :tag "reversed: before stars/bullet first" reversed))
1064 (choice :tag "Special C-e"
1065 (const :tag "off" nil)
1066 (const :tag "on: before tags first" t)
1067 (const :tag "reversed: after tags first" reversed)))))
1068 (if (fboundp 'defvaralias)
1069 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1071 (defcustom org-special-ctrl-k nil
1072 "Non-nil means `C-k' will behave specially in headlines.
1073 When nil, `C-k' will call the default `kill-line' command.
1074 When t, the following will happen while the cursor is in the headline:
1076 - When the cursor is at the beginning of a headline, kill the entire
1077 line and possible the folded subtree below the line.
1078 - When in the middle of the headline text, kill the headline up to the tags.
1079 - When after the headline text, kill the tags."
1080 :group 'org-edit-structure
1081 :type 'boolean)
1083 (defcustom org-ctrl-k-protect-subtree nil
1084 "Non-nil means, do not delete a hidden subtree with C-k.
1085 When set to the symbol `error', simply throw an error when C-k is
1086 used to kill (part-of) a headline that has hidden text behind it.
1087 Any other non-nil value will result in a query to the user, if it is
1088 OK to kill that hidden subtree. When nil, kill without remorse."
1089 :group 'org-edit-structure
1090 :version "24.1"
1091 :type '(choice
1092 (const :tag "Do not protect hidden subtrees" nil)
1093 (const :tag "Protect hidden subtrees with a security query" t)
1094 (const :tag "Never kill a hidden subtree with C-k" error)))
1096 (defcustom org-catch-invisible-edits nil
1097 "Check if in invisible region before inserting or deleting a character.
1098 Valid values are:
1100 nil Do not check, so just do invisible edits.
1101 error Throw an error and do nothing.
1102 show Make point visible, and do the requested edit.
1103 show-and-error Make point visible, then throw an error and abort the edit.
1104 smart Make point visible, and do insertion/deletion if it is
1105 adjacent to visible text and the change feels predictable.
1106 Never delete a previously invisible character or add in the
1107 middle or right after an invisible region. Basically, this
1108 allows insertion and backward-delete right before ellipses.
1109 FIXME: maybe in this case we should not even show?"
1110 :group 'org-edit-structure
1111 :version "24.1"
1112 :type '(choice
1113 (const :tag "Do not check" nil)
1114 (const :tag "Throw error when trying to edit" error)
1115 (const :tag "Unhide, but do not do the edit" show-and-error)
1116 (const :tag "Show invisible part and do the edit" show)
1117 (const :tag "Be smart and do the right thing" smart)))
1119 (defcustom org-yank-folded-subtrees t
1120 "Non-nil means when yanking subtrees, fold them.
1121 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1122 it starts with a heading and all other headings in it are either children
1123 or siblings, then fold all the subtrees. However, do this only if no
1124 text after the yank would be swallowed into a folded tree by this action."
1125 :group 'org-edit-structure
1126 :type 'boolean)
1128 (defcustom org-yank-adjusted-subtrees nil
1129 "Non-nil means when yanking subtrees, adjust the level.
1130 With this setting, `org-paste-subtree' is used to insert the subtree, see
1131 this function for details."
1132 :group 'org-edit-structure
1133 :type 'boolean)
1135 (defcustom org-M-RET-may-split-line '((default . t))
1136 "Non-nil means M-RET will split the line at the cursor position.
1137 When nil, it will go to the end of the line before making a
1138 new line.
1139 You may also set this option in a different way for different
1140 contexts. Valid contexts are:
1142 headline when creating a new headline
1143 item when creating a new item
1144 table in a table field
1145 default the value to be used for all contexts not explicitly
1146 customized"
1147 :group 'org-structure
1148 :group 'org-table
1149 :type '(choice
1150 (const :tag "Always" t)
1151 (const :tag "Never" nil)
1152 (repeat :greedy t :tag "Individual contexts"
1153 (cons
1154 (choice :tag "Context"
1155 (const headline)
1156 (const item)
1157 (const table)
1158 (const default))
1159 (boolean)))))
1162 (defcustom org-insert-heading-respect-content nil
1163 "Non-nil means insert new headings after the current subtree.
1164 When nil, the new heading is created directly after the current line.
1165 The commands \\[org-insert-heading-respect-content] and
1166 \\[org-insert-todo-heading-respect-content] turn this variable on
1167 for the duration of the command."
1168 :group 'org-structure
1169 :type 'boolean)
1171 (defcustom org-blank-before-new-entry '((heading . auto)
1172 (plain-list-item . auto))
1173 "Should `org-insert-heading' leave a blank line before new heading/item?
1174 The value is an alist, with `heading' and `plain-list-item' as CAR,
1175 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1176 which case Org will look at the surrounding headings/items and try to
1177 make an intelligent decision whether to insert a blank line or not.
1179 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1180 set, the setting here is ignored and no empty line is inserted, to avoid
1181 breaking the list structure."
1182 :group 'org-edit-structure
1183 :type '(list
1184 (cons (const heading)
1185 (choice (const :tag "Never" nil)
1186 (const :tag "Always" t)
1187 (const :tag "Auto" auto)))
1188 (cons (const plain-list-item)
1189 (choice (const :tag "Never" nil)
1190 (const :tag "Always" t)
1191 (const :tag "Auto" auto)))))
1193 (defcustom org-insert-heading-hook nil
1194 "Hook being run after inserting a new heading."
1195 :group 'org-edit-structure
1196 :type 'hook)
1198 (defcustom org-enable-fixed-width-editor t
1199 "Non-nil means lines starting with \":\" are treated as fixed-width.
1200 This currently only means they are never auto-wrapped.
1201 When nil, such lines will be treated like ordinary lines.
1202 See also the QUOTE keyword."
1203 :group 'org-edit-structure
1204 :type 'boolean)
1206 (defcustom org-goto-auto-isearch t
1207 "Non-nil means typing characters in `org-goto' starts incremental search."
1208 :group 'org-edit-structure
1209 :type 'boolean)
1211 (defgroup org-sparse-trees nil
1212 "Options concerning sparse trees in Org-mode."
1213 :tag "Org Sparse Trees"
1214 :group 'org-structure)
1216 (defcustom org-highlight-sparse-tree-matches t
1217 "Non-nil means highlight all matches that define a sparse tree.
1218 The highlights will automatically disappear the next time the buffer is
1219 changed by an edit command."
1220 :group 'org-sparse-trees
1221 :type 'boolean)
1223 (defcustom org-remove-highlights-with-change t
1224 "Non-nil means any change to the buffer will remove temporary highlights.
1225 Such highlights are created by `org-occur' and `org-clock-display'.
1226 When nil, `C-c C-c needs to be used to get rid of the highlights.
1227 The highlights created by `org-preview-latex-fragment' always need
1228 `C-c C-c' to be removed."
1229 :group 'org-sparse-trees
1230 :group 'org-time
1231 :type 'boolean)
1234 (defcustom org-occur-hook '(org-first-headline-recenter)
1235 "Hook that is run after `org-occur' has constructed a sparse tree.
1236 This can be used to recenter the window to show as much of the structure
1237 as possible."
1238 :group 'org-sparse-trees
1239 :type 'hook)
1241 (defgroup org-imenu-and-speedbar nil
1242 "Options concerning imenu and speedbar in Org-mode."
1243 :tag "Org Imenu and Speedbar"
1244 :group 'org-structure)
1246 (defcustom org-imenu-depth 2
1247 "The maximum level for Imenu access to Org-mode headlines.
1248 This also applied for speedbar access."
1249 :group 'org-imenu-and-speedbar
1250 :type 'integer)
1252 (defgroup org-table nil
1253 "Options concerning tables in Org-mode."
1254 :tag "Org Table"
1255 :group 'org)
1257 (defcustom org-enable-table-editor 'optimized
1258 "Non-nil means lines starting with \"|\" are handled by the table editor.
1259 When nil, such lines will be treated like ordinary lines.
1261 When equal to the symbol `optimized', the table editor will be optimized to
1262 do the following:
1263 - Automatic overwrite mode in front of whitespace in table fields.
1264 This makes the structure of the table stay in tact as long as the edited
1265 field does not exceed the column width.
1266 - Minimize the number of realigns. Normally, the table is aligned each time
1267 TAB or RET are pressed to move to another field. With optimization this
1268 happens only if changes to a field might have changed the column width.
1269 Optimization requires replacing the functions `self-insert-command',
1270 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1271 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1272 very good at guessing when a re-align will be necessary, but you can always
1273 force one with \\[org-ctrl-c-ctrl-c].
1275 If you would like to use the optimized version in Org-mode, but the
1276 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1278 This variable can be used to turn on and off the table editor during a session,
1279 but in order to toggle optimization, a restart is required.
1281 See also the variable `org-table-auto-blank-field'."
1282 :group 'org-table
1283 :type '(choice
1284 (const :tag "off" nil)
1285 (const :tag "on" t)
1286 (const :tag "on, optimized" optimized)))
1288 (defcustom org-self-insert-cluster-for-undo t
1289 "Non-nil means cluster self-insert commands for undo when possible.
1290 If this is set, then, like in the Emacs command loop, 20 consecutive
1291 characters will be undone together.
1292 This is configurable, because there is some impact on typing performance."
1293 :group 'org-table
1294 :type 'boolean)
1296 (defcustom org-table-tab-recognizes-table.el t
1297 "Non-nil means TAB will automatically notice a table.el table.
1298 When it sees such a table, it moves point into it and - if necessary -
1299 calls `table-recognize-table'."
1300 :group 'org-table-editing
1301 :type 'boolean)
1303 (defgroup org-link nil
1304 "Options concerning links in Org-mode."
1305 :tag "Org Link"
1306 :group 'org)
1308 (defvar org-link-abbrev-alist-local nil
1309 "Buffer-local version of `org-link-abbrev-alist', which see.
1310 The value of this is taken from the #+LINK lines.")
1311 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1313 (defcustom org-link-abbrev-alist nil
1314 "Alist of link abbreviations.
1315 The car of each element is a string, to be replaced at the start of a link.
1316 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1317 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1319 [[linkkey:tag][description]]
1321 The 'linkkey' must be a word word, starting with a letter, followed
1322 by letters, numbers, '-' or '_'.
1324 If REPLACE is a string, the tag will simply be appended to create the link.
1325 If the string contains \"%s\", the tag will be inserted there. If the string
1326 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1327 at that point (see the function `url-hexify-string'). If the string contains
1328 the specifier \"%(my-function)\", then the custom function `my-function' will
1329 be invoked: this function takes the tag as its only argument and must return
1330 a string.
1332 REPLACE may also be a function that will be called with the tag as the
1333 only argument to create the link, which should be returned as a string.
1335 See the manual for examples."
1336 :group 'org-link
1337 :type '(repeat
1338 (cons
1339 (string :tag "Protocol")
1340 (choice
1341 (string :tag "Format")
1342 (function)))))
1344 (defcustom org-descriptive-links t
1345 "Non-nil means Org will display descriptive links.
1346 E.g. [[http://orgmode.org][Org website]] will be displayed as
1347 \"Org Website\", hiding the link itself and just displaying its
1348 description. When set to `nil', Org will display the full links
1349 literally.
1351 You can interactively set the value of this variable by calling
1352 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1353 :group 'org-link
1354 :type 'boolean)
1356 (defcustom org-link-file-path-type 'adaptive
1357 "How the path name in file links should be stored.
1358 Valid values are:
1360 relative Relative to the current directory, i.e. the directory of the file
1361 into which the link is being inserted.
1362 absolute Absolute path, if possible with ~ for home directory.
1363 noabbrev Absolute path, no abbreviation of home directory.
1364 adaptive Use relative path for files in the current directory and sub-
1365 directories of it. For other files, use an absolute path."
1366 :group 'org-link
1367 :type '(choice
1368 (const relative)
1369 (const absolute)
1370 (const noabbrev)
1371 (const adaptive)))
1373 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1374 "Types of links that should be activated in Org-mode files.
1375 This is a list of symbols, each leading to the activation of a certain link
1376 type. In principle, it does not hurt to turn on most link types - there may
1377 be a small gain when turning off unused link types. The types are:
1379 bracket The recommended [[link][description]] or [[link]] links with hiding.
1380 angle Links in angular brackets that may contain whitespace like
1381 <bbdb:Carsten Dominik>.
1382 plain Plain links in normal text, no whitespace, like http://google.com.
1383 radio Text that is matched by a radio target, see manual for details.
1384 tag Tag settings in a headline (link to tag search).
1385 date Time stamps (link to calendar).
1386 footnote Footnote labels.
1388 Changing this variable requires a restart of Emacs to become effective."
1389 :group 'org-link
1390 :type '(set :greedy t
1391 (const :tag "Double bracket links" bracket)
1392 (const :tag "Angular bracket links" angle)
1393 (const :tag "Plain text links" plain)
1394 (const :tag "Radio target matches" radio)
1395 (const :tag "Tags" tag)
1396 (const :tag "Timestamps" date)
1397 (const :tag "Footnotes" footnote)))
1399 (defcustom org-make-link-description-function nil
1400 "Function to use to generate link descriptions from links.
1401 If nil the link location will be used. This function must take
1402 two parameters; the first is the link and the second the
1403 description `org-insert-link' has generated, and should return the
1404 description to use."
1405 :group 'org-link
1406 :type 'function)
1408 (defgroup org-link-store nil
1409 "Options concerning storing links in Org-mode."
1410 :tag "Org Store Link"
1411 :group 'org-link)
1413 (defcustom org-email-link-description-format "Email %c: %.30s"
1414 "Format of the description part of a link to an email or usenet message.
1415 The following %-escapes will be replaced by corresponding information:
1417 %F full \"From\" field
1418 %f name, taken from \"From\" field, address if no name
1419 %T full \"To\" field
1420 %t first name in \"To\" field, address if no name
1421 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1422 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1423 %s subject
1424 %d date
1425 %m message-id.
1427 You may use normal field width specification between the % and the letter.
1428 This is for example useful to limit the length of the subject.
1430 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1431 :group 'org-link-store
1432 :type 'string)
1434 (defcustom org-from-is-user-regexp
1435 (let (r1 r2)
1436 (when (and user-mail-address (not (string= user-mail-address "")))
1437 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1438 (when (and user-full-name (not (string= user-full-name "")))
1439 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1440 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1441 "Regexp matched against the \"From:\" header of an email or usenet message.
1442 It should match if the message is from the user him/herself."
1443 :group 'org-link-store
1444 :type 'regexp)
1446 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1447 "Non-nil means storing a link to an Org file will use entry IDs.
1449 Note that before this variable is even considered, org-id must be loaded,
1450 so please customize `org-modules' and turn it on.
1452 The variable can have the following values:
1454 t Create an ID if needed to make a link to the current entry.
1456 create-if-interactive
1457 If `org-store-link' is called directly (interactively, as a user
1458 command), do create an ID to support the link. But when doing the
1459 job for remember, only use the ID if it already exists. The
1460 purpose of this setting is to avoid proliferation of unwanted
1461 IDs, just because you happen to be in an Org file when you
1462 call `org-remember' that automatically and preemptively
1463 creates a link. If you do want to get an ID link in a remember
1464 template to an entry not having an ID, create it first by
1465 explicitly creating a link to it, using `C-c C-l' first.
1467 create-if-interactive-and-no-custom-id
1468 Like create-if-interactive, but do not create an ID if there is
1469 a CUSTOM_ID property defined in the entry. This is the default.
1471 use-existing
1472 Use existing ID, do not create one.
1474 nil Never use an ID to make a link, instead link using a text search for
1475 the headline text."
1476 :group 'org-link-store
1477 :type '(choice
1478 (const :tag "Create ID to make link" t)
1479 (const :tag "Create if storing link interactively"
1480 create-if-interactive)
1481 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1482 create-if-interactive-and-no-custom-id)
1483 (const :tag "Only use existing" use-existing)
1484 (const :tag "Do not use ID to create link" nil)))
1486 (defcustom org-context-in-file-links t
1487 "Non-nil means file links from `org-store-link' contain context.
1488 A search string will be added to the file name with :: as separator and
1489 used to find the context when the link is activated by the command
1490 `org-open-at-point'. When this option is t, the entire active region
1491 will be placed in the search string of the file link. If set to a
1492 positive integer, only the first n lines of context will be stored.
1494 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1495 negates this setting for the duration of the command."
1496 :group 'org-link-store
1497 :type '(choice boolean integer))
1499 (defcustom org-keep-stored-link-after-insertion nil
1500 "Non-nil means keep link in list for entire session.
1502 The command `org-store-link' adds a link pointing to the current
1503 location to an internal list. These links accumulate during a session.
1504 The command `org-insert-link' can be used to insert links into any
1505 Org-mode file (offering completion for all stored links). When this
1506 option is nil, every link which has been inserted once using \\[org-insert-link]
1507 will be removed from the list, to make completing the unused links
1508 more efficient."
1509 :group 'org-link-store
1510 :type 'boolean)
1512 (defgroup org-link-follow nil
1513 "Options concerning following links in Org-mode."
1514 :tag "Org Follow Link"
1515 :group 'org-link)
1517 (defcustom org-link-translation-function nil
1518 "Function to translate links with different syntax to Org syntax.
1519 This can be used to translate links created for example by the Planner
1520 or emacs-wiki packages to Org syntax.
1521 The function must accept two parameters, a TYPE containing the link
1522 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1523 which is everything after the link protocol. It should return a cons
1524 with possibly modified values of type and path.
1525 Org contains a function for this, so if you set this variable to
1526 `org-translate-link-from-planner', you should be able follow many
1527 links created by planner."
1528 :group 'org-link-follow
1529 :type 'function)
1531 (defcustom org-follow-link-hook nil
1532 "Hook that is run after a link has been followed."
1533 :group 'org-link-follow
1534 :type 'hook)
1536 (defcustom org-tab-follows-link nil
1537 "Non-nil means on links TAB will follow the link.
1538 Needs to be set before org.el is loaded.
1539 This really should not be used, it does not make sense, and the
1540 implementation is bad."
1541 :group 'org-link-follow
1542 :type 'boolean)
1544 (defcustom org-return-follows-link nil
1545 "Non-nil means on links RET will follow the link."
1546 :group 'org-link-follow
1547 :type 'boolean)
1549 (defcustom org-mouse-1-follows-link
1550 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1551 "Non-nil means mouse-1 on a link will follow the link.
1552 A longer mouse click will still set point. Does not work on XEmacs.
1553 Needs to be set before org.el is loaded."
1554 :group 'org-link-follow
1555 :type 'boolean)
1557 (defcustom org-mark-ring-length 4
1558 "Number of different positions to be recorded in the ring.
1559 Changing this requires a restart of Emacs to work correctly."
1560 :group 'org-link-follow
1561 :type 'integer)
1563 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1564 "Non-nil means internal links in Org files must exactly match a headline.
1565 When nil, the link search tries to match a phrase with all words
1566 in the search text."
1567 :group 'org-link-follow
1568 :version "24.1"
1569 :type '(choice
1570 (const :tag "Use fuzzy text search" nil)
1571 (const :tag "Match only exact headline" t)
1572 (const :tag "Match exact headline or query to create it"
1573 query-to-create)))
1575 (defcustom org-link-frame-setup
1576 '((vm . vm-visit-folder-other-frame)
1577 (vm-imap . vm-visit-imap-folder-other-frame)
1578 (gnus . org-gnus-no-new-news)
1579 (file . find-file-other-window)
1580 (wl . wl-other-frame))
1581 "Setup the frame configuration for following links.
1582 When following a link with Emacs, it may often be useful to display
1583 this link in another window or frame. This variable can be used to
1584 set this up for the different types of links.
1585 For VM, use any of
1586 `vm-visit-folder'
1587 `vm-visit-folder-other-window'
1588 `vm-visit-folder-other-frame'
1589 For Gnus, use any of
1590 `gnus'
1591 `gnus-other-frame'
1592 `org-gnus-no-new-news'
1593 For FILE, use any of
1594 `find-file'
1595 `find-file-other-window'
1596 `find-file-other-frame'
1597 For Wanderlust use any of
1598 `wl'
1599 `wl-other-frame'
1600 For the calendar, use the variable `calendar-setup'.
1601 For BBDB, it is currently only possible to display the matches in
1602 another window."
1603 :group 'org-link-follow
1604 :type '(list
1605 (cons (const vm)
1606 (choice
1607 (const vm-visit-folder)
1608 (const vm-visit-folder-other-window)
1609 (const vm-visit-folder-other-frame)))
1610 (cons (const gnus)
1611 (choice
1612 (const gnus)
1613 (const gnus-other-frame)
1614 (const org-gnus-no-new-news)))
1615 (cons (const file)
1616 (choice
1617 (const find-file)
1618 (const find-file-other-window)
1619 (const find-file-other-frame)))
1620 (cons (const wl)
1621 (choice
1622 (const wl)
1623 (const wl-other-frame)))))
1625 (defcustom org-display-internal-link-with-indirect-buffer nil
1626 "Non-nil means use indirect buffer to display infile links.
1627 Activating internal links (from one location in a file to another location
1628 in the same file) normally just jumps to the location. When the link is
1629 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1630 is displayed in
1631 another window. When this option is set, the other window actually displays
1632 an indirect buffer clone of the current buffer, to avoid any visibility
1633 changes to the current buffer."
1634 :group 'org-link-follow
1635 :type 'boolean)
1637 (defcustom org-open-non-existing-files nil
1638 "Non-nil means `org-open-file' will open non-existing files.
1639 When nil, an error will be generated.
1640 This variable applies only to external applications because they
1641 might choke on non-existing files. If the link is to a file that
1642 will be opened in Emacs, the variable is ignored."
1643 :group 'org-link-follow
1644 :type 'boolean)
1646 (defcustom org-open-directory-means-index-dot-org nil
1647 "Non-nil means a link to a directory really means to index.org.
1648 When nil, following a directory link will run dired or open a finder/explorer
1649 window on that directory."
1650 :group 'org-link-follow
1651 :type 'boolean)
1653 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1654 "Function and arguments to call for following mailto links.
1655 This is a list with the first element being a Lisp function, and the
1656 remaining elements being arguments to the function. In string arguments,
1657 %a will be replaced by the address, and %s will be replaced by the subject
1658 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1659 :group 'org-link-follow
1660 :type '(choice
1661 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1662 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1663 (const :tag "message-mail" (message-mail "%a" "%s"))
1664 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1666 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1667 "Non-nil means ask for confirmation before executing shell links.
1668 Shell links can be dangerous: just think about a link
1670 [[shell:rm -rf ~/*][Google Search]]
1672 This link would show up in your Org-mode document as \"Google Search\",
1673 but really it would remove your entire home directory.
1674 Therefore we advise against setting this variable to nil.
1675 Just change it to `y-or-n-p' if you want to confirm with a
1676 single keystroke rather than having to type \"yes\"."
1677 :group 'org-link-follow
1678 :type '(choice
1679 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1680 (const :tag "with y-or-n (faster)" y-or-n-p)
1681 (const :tag "no confirmation (dangerous)" nil)))
1682 (put 'org-confirm-shell-link-function
1683 'safe-local-variable
1684 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1686 (defcustom org-confirm-shell-link-not-regexp ""
1687 "A regexp to skip confirmation for shell links."
1688 :group 'org-link-follow
1689 :version "24.1"
1690 :type 'regexp)
1692 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1693 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1694 Elisp links can be dangerous: just think about a link
1696 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1698 This link would show up in your Org-mode document as \"Google Search\",
1699 but really it would remove your entire home directory.
1700 Therefore we advise against setting this variable to nil.
1701 Just change it to `y-or-n-p' if you want to confirm with a
1702 single keystroke rather than having to type \"yes\"."
1703 :group 'org-link-follow
1704 :type '(choice
1705 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1706 (const :tag "with y-or-n (faster)" y-or-n-p)
1707 (const :tag "no confirmation (dangerous)" nil)))
1708 (put 'org-confirm-shell-link-function
1709 'safe-local-variable
1710 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1712 (defcustom org-confirm-elisp-link-not-regexp ""
1713 "A regexp to skip confirmation for Elisp links."
1714 :group 'org-link-follow
1715 :version "24.1"
1716 :type 'regexp)
1718 (defconst org-file-apps-defaults-gnu
1719 '((remote . emacs)
1720 (system . mailcap)
1721 (t . mailcap))
1722 "Default file applications on a UNIX or GNU/Linux system.
1723 See `org-file-apps'.")
1725 (defconst org-file-apps-defaults-macosx
1726 '((remote . emacs)
1727 (t . "open %s")
1728 (system . "open %s")
1729 ("ps.gz" . "gv %s")
1730 ("eps.gz" . "gv %s")
1731 ("dvi" . "xdvi %s")
1732 ("fig" . "xfig %s"))
1733 "Default file applications on a MacOS X system.
1734 The system \"open\" is known as a default, but we use X11 applications
1735 for some files for which the OS does not have a good default.
1736 See `org-file-apps'.")
1738 (defconst org-file-apps-defaults-windowsnt
1739 (list
1740 '(remote . emacs)
1741 (cons t
1742 (list (if (featurep 'xemacs)
1743 'mswindows-shell-execute
1744 'w32-shell-execute)
1745 "open" 'file))
1746 (cons 'system
1747 (list (if (featurep 'xemacs)
1748 'mswindows-shell-execute
1749 'w32-shell-execute)
1750 "open" 'file)))
1751 "Default file applications on a Windows NT system.
1752 The system \"open\" is used for most files.
1753 See `org-file-apps'.")
1755 (defcustom org-file-apps
1757 (auto-mode . emacs)
1758 ("\\.mm\\'" . default)
1759 ("\\.x?html?\\'" . default)
1760 ("\\.pdf\\'" . default)
1762 "External applications for opening `file:path' items in a document.
1763 Org-mode uses system defaults for different file types, but
1764 you can use this variable to set the application for a given file
1765 extension. The entries in this list are cons cells where the car identifies
1766 files and the cdr the corresponding command. Possible values for the
1767 file identifier are
1768 \"string\" A string as a file identifier can be interpreted in different
1769 ways, depending on its contents:
1771 - Alphanumeric characters only:
1772 Match links with this file extension.
1773 Example: (\"pdf\" . \"evince %s\")
1774 to open PDFs with evince.
1776 - Regular expression: Match links where the
1777 filename matches the regexp. If you want to
1778 use groups here, use shy groups.
1780 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1781 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1782 to open *.html and *.xhtml with firefox.
1784 - Regular expression which contains (non-shy) groups:
1785 Match links where the whole link, including \"::\", and
1786 anything after that, matches the regexp.
1787 In a custom command string, %1, %2, etc. are replaced with
1788 the parts of the link that were matched by the groups.
1789 For backwards compatibility, if a command string is given
1790 that does not use any of the group matches, this case is
1791 handled identically to the second one (i.e. match against
1792 file name only).
1793 In a custom lisp form, you can access the group matches with
1794 (match-string n link).
1796 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1797 to open [[file:document.pdf::5]] with evince at page 5.
1799 `directory' Matches a directory
1800 `remote' Matches a remote file, accessible through tramp or efs.
1801 Remote files most likely should be visited through Emacs
1802 because external applications cannot handle such paths.
1803 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1804 so all files Emacs knows how to handle. Using this with
1805 command `emacs' will open most files in Emacs. Beware that this
1806 will also open html files inside Emacs, unless you add
1807 (\"html\" . default) to the list as well.
1808 t Default for files not matched by any of the other options.
1809 `system' The system command to open files, like `open' on Windows
1810 and Mac OS X, and mailcap under GNU/Linux. This is the command
1811 that will be selected if you call `C-c C-o' with a double
1812 \\[universal-argument] \\[universal-argument] prefix.
1814 Possible values for the command are:
1815 `emacs' The file will be visited by the current Emacs process.
1816 `default' Use the default application for this file type, which is the
1817 association for t in the list, most likely in the system-specific
1818 part.
1819 This can be used to overrule an unwanted setting in the
1820 system-specific variable.
1821 `system' Use the system command for opening files, like \"open\".
1822 This command is specified by the entry whose car is `system'.
1823 Most likely, the system-specific version of this variable
1824 does define this command, but you can overrule/replace it
1825 here.
1826 string A command to be executed by a shell; %s will be replaced
1827 by the path to the file.
1828 sexp A Lisp form which will be evaluated. The file path will
1829 be available in the Lisp variable `file'.
1830 For more examples, see the system specific constants
1831 `org-file-apps-defaults-macosx'
1832 `org-file-apps-defaults-windowsnt'
1833 `org-file-apps-defaults-gnu'."
1834 :group 'org-link-follow
1835 :type '(repeat
1836 (cons (choice :value ""
1837 (string :tag "Extension")
1838 (const :tag "System command to open files" system)
1839 (const :tag "Default for unrecognized files" t)
1840 (const :tag "Remote file" remote)
1841 (const :tag "Links to a directory" directory)
1842 (const :tag "Any files that have Emacs modes"
1843 auto-mode))
1844 (choice :value ""
1845 (const :tag "Visit with Emacs" emacs)
1846 (const :tag "Use default" default)
1847 (const :tag "Use the system command" system)
1848 (string :tag "Command")
1849 (sexp :tag "Lisp form")))))
1851 (defcustom org-doi-server-url "http://dx.doi.org/"
1852 "The URL of the DOI server."
1853 :type 'string
1854 :version "24.2"
1855 :group 'org-link-follow)
1857 (defgroup org-refile nil
1858 "Options concerning refiling entries in Org-mode."
1859 :tag "Org Refile"
1860 :group 'org)
1862 (defcustom org-directory "~/org"
1863 "Directory with org files.
1864 This is just a default location to look for Org files. There is no need
1865 at all to put your files into this directory. It is only used in the
1866 following situations:
1868 1. When a remember template specifies a target file that is not an
1869 absolute path. The path will then be interpreted relative to
1870 `org-directory'
1871 2. When a remember note is filed away in an interactive way (when exiting the
1872 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1873 with `org-directory' as the default path."
1874 :group 'org-refile
1875 :group 'org-remember
1876 :type 'directory)
1878 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1879 "Default target for storing notes.
1880 Used as a fall back file for org-remember.el and org-capture.el, for
1881 templates that do not specify a target file."
1882 :group 'org-refile
1883 :group 'org-remember
1884 :type '(choice
1885 (const :tag "Default from remember-data-file" nil)
1886 file))
1888 (defcustom org-goto-interface 'outline
1889 "The default interface to be used for `org-goto'.
1890 Allowed values are:
1891 outline The interface shows an outline of the relevant file
1892 and the correct heading is found by moving through
1893 the outline or by searching with incremental search.
1894 outline-path-completion Headlines in the current buffer are offered via
1895 completion. This is the interface also used by
1896 the refile command."
1897 :group 'org-refile
1898 :type '(choice
1899 (const :tag "Outline" outline)
1900 (const :tag "Outline-path-completion" outline-path-completion)))
1902 (defcustom org-goto-max-level 5
1903 "Maximum target level when running `org-goto' with refile interface."
1904 :group 'org-refile
1905 :type 'integer)
1907 (defcustom org-reverse-note-order nil
1908 "Non-nil means store new notes at the beginning of a file or entry.
1909 When nil, new notes will be filed to the end of a file or entry.
1910 This can also be a list with cons cells of regular expressions that
1911 are matched against file names, and values."
1912 :group 'org-remember
1913 :group 'org-refile
1914 :type '(choice
1915 (const :tag "Reverse always" t)
1916 (const :tag "Reverse never" nil)
1917 (repeat :tag "By file name regexp"
1918 (cons regexp boolean))))
1920 (defcustom org-log-refile nil
1921 "Information to record when a task is refiled.
1923 Possible values are:
1925 nil Don't add anything
1926 time Add a time stamp to the task
1927 note Prompt for a note and add it with template `org-log-note-headings'
1929 This option can also be set with on a per-file-basis with
1931 #+STARTUP: nologrefile
1932 #+STARTUP: logrefile
1933 #+STARTUP: lognoterefile
1935 You can have local logging settings for a subtree by setting the LOGGING
1936 property to one or more of these keywords.
1938 When bulk-refiling from the agenda, the value `note' is forbidden and
1939 will temporarily be changed to `time'."
1940 :group 'org-refile
1941 :group 'org-progress
1942 :version "24.1"
1943 :type '(choice
1944 (const :tag "No logging" nil)
1945 (const :tag "Record timestamp" time)
1946 (const :tag "Record timestamp with note." note)))
1948 (defcustom org-refile-targets nil
1949 "Targets for refiling entries with \\[org-refile].
1950 This is a list of cons cells. Each cell contains:
1951 - a specification of the files to be considered, either a list of files,
1952 or a symbol whose function or variable value will be used to retrieve
1953 a file name or a list of file names. If you use `org-agenda-files' for
1954 that, all agenda files will be scanned for targets. Nil means consider
1955 headings in the current buffer.
1956 - A specification of how to find candidate refile targets. This may be
1957 any of:
1958 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1959 This tag has to be present in all target headlines, inheritance will
1960 not be considered.
1961 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1962 todo keyword.
1963 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1964 headlines that are refiling targets.
1965 - a cons cell (:level . N). Any headline of level N is considered a target.
1966 Note that, when `org-odd-levels-only' is set, level corresponds to
1967 order in hierarchy, not to the number of stars.
1968 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1969 Note that, when `org-odd-levels-only' is set, level corresponds to
1970 order in hierarchy, not to the number of stars.
1972 Each element of this list generates a set of possible targets.
1973 The union of these sets is presented (with completion) to
1974 the user by `org-refile'.
1976 You can set the variable `org-refile-target-verify-function' to a function
1977 to verify each headline found by the simple criteria above.
1979 When this variable is nil, all top-level headlines in the current buffer
1980 are used, equivalent to the value `((nil . (:level . 1))'."
1981 :group 'org-refile
1982 :type '(repeat
1983 (cons
1984 (choice :value org-agenda-files
1985 (const :tag "All agenda files" org-agenda-files)
1986 (const :tag "Current buffer" nil)
1987 (function) (variable) (file))
1988 (choice :tag "Identify target headline by"
1989 (cons :tag "Specific tag" (const :value :tag) (string))
1990 (cons :tag "TODO keyword" (const :value :todo) (string))
1991 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1992 (cons :tag "Level number" (const :value :level) (integer))
1993 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1995 (defcustom org-refile-target-verify-function nil
1996 "Function to verify if the headline at point should be a refile target.
1997 The function will be called without arguments, with point at the
1998 beginning of the headline. It should return t and leave point
1999 where it is if the headline is a valid target for refiling.
2001 If the target should not be selected, the function must return nil.
2002 In addition to this, it may move point to a place from where the search
2003 should be continued. For example, the function may decide that the entire
2004 subtree of the current entry should be excluded and move point to the end
2005 of the subtree."
2006 :group 'org-refile
2007 :type 'function)
2009 (defcustom org-refile-use-cache nil
2010 "Non-nil means cache refile targets to speed up the process.
2011 The cache for a particular file will be updated automatically when
2012 the buffer has been killed, or when any of the marker used for flagging
2013 refile targets no longer points at a live buffer.
2014 If you have added new entries to a buffer that might themselves be targets,
2015 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2016 find that easier, `C-u C-u C-u C-c C-w'."
2017 :group 'org-refile
2018 :version "24.1"
2019 :type 'boolean)
2021 (defcustom org-refile-use-outline-path nil
2022 "Non-nil means provide refile targets as paths.
2023 So a level 3 headline will be available as level1/level2/level3.
2025 When the value is `file', also include the file name (without directory)
2026 into the path. In this case, you can also stop the completion after
2027 the file name, to get entries inserted as top level in the file.
2029 When `full-file-path', include the full file path."
2030 :group 'org-refile
2031 :type '(choice
2032 (const :tag "Not" nil)
2033 (const :tag "Yes" t)
2034 (const :tag "Start with file name" file)
2035 (const :tag "Start with full file path" full-file-path)))
2037 (defcustom org-outline-path-complete-in-steps t
2038 "Non-nil means complete the outline path in hierarchical steps.
2039 When Org-mode uses the refile interface to select an outline path
2040 \(see variable `org-refile-use-outline-path'), the completion of
2041 the path can be done is a single go, or if can be done in steps down
2042 the headline hierarchy. Going in steps is probably the best if you
2043 do not use a special completion package like `ido' or `icicles'.
2044 However, when using these packages, going in one step can be very
2045 fast, while still showing the whole path to the entry."
2046 :group 'org-refile
2047 :type 'boolean)
2049 (defcustom org-refile-allow-creating-parent-nodes nil
2050 "Non-nil means allow to create new nodes as refile targets.
2051 New nodes are then created by adding \"/new node name\" to the completion
2052 of an existing node. When the value of this variable is `confirm',
2053 new node creation must be confirmed by the user (recommended)
2054 When nil, the completion must match an existing entry.
2056 Note that, if the new heading is not seen by the criteria
2057 listed in `org-refile-targets', multiple instances of the same
2058 heading would be created by trying again to file under the new
2059 heading."
2060 :group 'org-refile
2061 :type '(choice
2062 (const :tag "Never" nil)
2063 (const :tag "Always" t)
2064 (const :tag "Prompt for confirmation" confirm)))
2066 (defcustom org-refile-active-region-within-subtree nil
2067 "Non-nil means also refile active region within a subtree.
2069 By default `org-refile' doesn't allow refiling regions if they
2070 don't contain a set of subtrees, but it might be convenient to
2071 do so sometimes: in that case, the first line of the region is
2072 converted to a headline before refiling."
2073 :group 'org-refile
2074 :version "24.1"
2075 :type 'boolean)
2077 (defgroup org-todo nil
2078 "Options concerning TODO items in Org-mode."
2079 :tag "Org TODO"
2080 :group 'org)
2082 (defgroup org-progress nil
2083 "Options concerning Progress logging in Org-mode."
2084 :tag "Org Progress"
2085 :group 'org-time)
2087 (defvar org-todo-interpretation-widgets
2088 '((:tag "Sequence (cycling hits every state)" sequence)
2089 (:tag "Type (cycling directly to DONE)" type))
2090 "The available interpretation symbols for customizing `org-todo-keywords'.
2091 Interested libraries should add to this list.")
2093 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2094 "List of TODO entry keyword sequences and their interpretation.
2095 \\<org-mode-map>This is a list of sequences.
2097 Each sequence starts with a symbol, either `sequence' or `type',
2098 indicating if the keywords should be interpreted as a sequence of
2099 action steps, or as different types of TODO items. The first
2100 keywords are states requiring action - these states will select a headline
2101 for inclusion into the global TODO list Org-mode produces. If one of
2102 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2103 signify that no further action is necessary. If \"|\" is not found,
2104 the last keyword is treated as the only DONE state of the sequence.
2106 The command \\[org-todo] cycles an entry through these states, and one
2107 additional state where no keyword is present. For details about this
2108 cycling, see the manual.
2110 TODO keywords and interpretation can also be set on a per-file basis with
2111 the special #+SEQ_TODO and #+TYP_TODO lines.
2113 Each keyword can optionally specify a letter for fast state selection
2114 \(in combination with the variable `org-use-fast-todo-selection')
2115 and specifiers for state change logging, using the same syntax that
2116 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2117 the WAIT state can be selected with the \"w\" letter. \"WAIT(w!)\"
2118 indicates to record a time stamp each time this state is selected.
2120 Each keyword may also specify if a timestamp or a note should be
2121 recorded when entering or leaving the state, by adding additional
2122 characters in the parenthesis after the keyword. This looks like this:
2123 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2124 record only the time of the state change. With X and Y being either
2125 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2126 Y when leaving the state if and only if the *target* state does not
2127 define X. You may omit any of the fast-selection key or X or /Y,
2128 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2130 For backward compatibility, this variable may also be just a list
2131 of keywords. In this case the interpretation (sequence or type) will be
2132 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2133 :group 'org-todo
2134 :group 'org-keywords
2135 :type '(choice
2136 (repeat :tag "Old syntax, just keywords"
2137 (string :tag "Keyword"))
2138 (repeat :tag "New syntax"
2139 (cons
2140 (choice
2141 :tag "Interpretation"
2142 ;;Quick and dirty way to see
2143 ;;`org-todo-interpretations'. This takes the
2144 ;;place of item arguments
2145 :convert-widget
2146 (lambda (widget)
2147 (widget-put widget
2148 :args (mapcar
2149 #'(lambda (x)
2150 (widget-convert
2151 (cons 'const x)))
2152 org-todo-interpretation-widgets))
2153 widget))
2154 (repeat
2155 (string :tag "Keyword"))))))
2157 (defvar org-todo-keywords-1 nil
2158 "All TODO and DONE keywords active in a buffer.")
2159 (make-variable-buffer-local 'org-todo-keywords-1)
2160 (defvar org-todo-keywords-for-agenda nil)
2161 (defvar org-done-keywords-for-agenda nil)
2162 (defvar org-drawers-for-agenda nil)
2163 (defvar org-todo-keyword-alist-for-agenda nil)
2164 (defvar org-tag-alist-for-agenda nil)
2165 (defvar org-agenda-contributing-files nil)
2166 (defvar org-not-done-keywords nil)
2167 (make-variable-buffer-local 'org-not-done-keywords)
2168 (defvar org-done-keywords nil)
2169 (make-variable-buffer-local 'org-done-keywords)
2170 (defvar org-todo-heads nil)
2171 (make-variable-buffer-local 'org-todo-heads)
2172 (defvar org-todo-sets nil)
2173 (make-variable-buffer-local 'org-todo-sets)
2174 (defvar org-todo-log-states nil)
2175 (make-variable-buffer-local 'org-todo-log-states)
2176 (defvar org-todo-kwd-alist nil)
2177 (make-variable-buffer-local 'org-todo-kwd-alist)
2178 (defvar org-todo-key-alist nil)
2179 (make-variable-buffer-local 'org-todo-key-alist)
2180 (defvar org-todo-key-trigger nil)
2181 (make-variable-buffer-local 'org-todo-key-trigger)
2183 (defcustom org-todo-interpretation 'sequence
2184 "Controls how TODO keywords are interpreted.
2185 This variable is in principle obsolete and is only used for
2186 backward compatibility, if the interpretation of todo keywords is
2187 not given already in `org-todo-keywords'. See that variable for
2188 more information."
2189 :group 'org-todo
2190 :group 'org-keywords
2191 :type '(choice (const sequence)
2192 (const type)))
2194 (defcustom org-use-fast-todo-selection t
2195 "Non-nil means use the fast todo selection scheme with C-c C-t.
2196 This variable describes if and under what circumstances the cycling
2197 mechanism for TODO keywords will be replaced by a single-key, direct
2198 selection scheme.
2200 When nil, fast selection is never used.
2202 When the symbol `prefix', it will be used when `org-todo' is called
2203 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2204 `C-u t' in an agenda buffer.
2206 When t, fast selection is used by default. In this case, the prefix
2207 argument forces cycling instead.
2209 In all cases, the special interface is only used if access keys have
2210 actually been assigned by the user, i.e. if keywords in the configuration
2211 are followed by a letter in parenthesis, like TODO(t)."
2212 :group 'org-todo
2213 :type '(choice
2214 (const :tag "Never" nil)
2215 (const :tag "By default" t)
2216 (const :tag "Only with C-u C-c C-t" prefix)))
2218 (defcustom org-provide-todo-statistics t
2219 "Non-nil means update todo statistics after insert and toggle.
2220 ALL-HEADLINES means update todo statistics by including headlines
2221 with no TODO keyword as well, counting them as not done.
2222 A list of TODO keywords means the same, but skip keywords that are
2223 not in this list.
2225 When this is set, todo statistics is updated in the parent of the
2226 current entry each time a todo state is changed."
2227 :group 'org-todo
2228 :type '(choice
2229 (const :tag "Yes, only for TODO entries" t)
2230 (const :tag "Yes, including all entries" 'all-headlines)
2231 (repeat :tag "Yes, for TODOs in this list"
2232 (string :tag "TODO keyword"))
2233 (other :tag "No TODO statistics" nil)))
2235 (defcustom org-hierarchical-todo-statistics t
2236 "Non-nil means TODO statistics covers just direct children.
2237 When nil, all entries in the subtree are considered.
2238 This has only an effect if `org-provide-todo-statistics' is set.
2239 To set this to nil for only a single subtree, use a COOKIE_DATA
2240 property and include the word \"recursive\" into the value."
2241 :group 'org-todo
2242 :type 'boolean)
2244 (defcustom org-after-todo-state-change-hook nil
2245 "Hook which is run after the state of a TODO item was changed.
2246 The new state (a string with a TODO keyword, or nil) is available in the
2247 Lisp variable `org-state'."
2248 :group 'org-todo
2249 :type 'hook)
2251 (defvar org-blocker-hook nil
2252 "Hook for functions that are allowed to block a state change.
2254 Each function gets as its single argument a property list, see
2255 `org-trigger-hook' for more information about this list.
2257 If any of the functions in this hook returns nil, the state change
2258 is blocked.")
2260 (defvar org-trigger-hook nil
2261 "Hook for functions that are triggered by a state change.
2263 Each function gets as its single argument a property list with at least
2264 the following elements:
2266 (:type type-of-change :position pos-at-entry-start
2267 :from old-state :to new-state)
2269 Depending on the type, more properties may be present.
2271 This mechanism is currently implemented for:
2273 TODO state changes
2274 ------------------
2275 :type todo-state-change
2276 :from previous state (keyword as a string), or nil, or a symbol
2277 'todo' or 'done', to indicate the general type of state.
2278 :to new state, like in :from")
2280 (defcustom org-enforce-todo-dependencies nil
2281 "Non-nil means undone TODO entries will block switching the parent to DONE.
2282 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2283 be blocked if any prior sibling is not yet done.
2284 Finally, if the parent is blocked because of ordered siblings of its own,
2285 the child will also be blocked."
2286 :set (lambda (var val)
2287 (set var val)
2288 (if val
2289 (add-hook 'org-blocker-hook
2290 'org-block-todo-from-children-or-siblings-or-parent)
2291 (remove-hook 'org-blocker-hook
2292 'org-block-todo-from-children-or-siblings-or-parent)))
2293 :group 'org-todo
2294 :type 'boolean)
2296 (defcustom org-enforce-todo-checkbox-dependencies nil
2297 "Non-nil means unchecked boxes will block switching the parent to DONE.
2298 When this is nil, checkboxes have no influence on switching TODO states.
2299 When non-nil, you first need to check off all check boxes before the TODO
2300 entry can be switched to DONE.
2301 This variable needs to be set before org.el is loaded, and you need to
2302 restart Emacs after a change to make the change effective. The only way
2303 to change is while Emacs is running is through the customize interface."
2304 :set (lambda (var val)
2305 (set var val)
2306 (if val
2307 (add-hook 'org-blocker-hook
2308 'org-block-todo-from-checkboxes)
2309 (remove-hook 'org-blocker-hook
2310 'org-block-todo-from-checkboxes)))
2311 :group 'org-todo
2312 :type 'boolean)
2314 (defcustom org-treat-insert-todo-heading-as-state-change nil
2315 "Non-nil means inserting a TODO heading is treated as state change.
2316 So when the command \\[org-insert-todo-heading] is used, state change
2317 logging will apply if appropriate. When nil, the new TODO item will
2318 be inserted directly, and no logging will take place."
2319 :group 'org-todo
2320 :type 'boolean)
2322 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2323 "Non-nil means switching TODO states with S-cursor counts as state change.
2324 This is the default behavior. However, setting this to nil allows a
2325 convenient way to select a TODO state and bypass any logging associated
2326 with that."
2327 :group 'org-todo
2328 :type 'boolean)
2330 (defcustom org-todo-state-tags-triggers nil
2331 "Tag changes that should be triggered by TODO state changes.
2332 This is a list. Each entry is
2334 (state-change (tag . flag) .......)
2336 State-change can be a string with a state, and empty string to indicate the
2337 state that has no TODO keyword, or it can be one of the symbols `todo'
2338 or `done', meaning any not-done or done state, respectively."
2339 :group 'org-todo
2340 :group 'org-tags
2341 :type '(repeat
2342 (cons (choice :tag "When changing to"
2343 (const :tag "Not-done state" todo)
2344 (const :tag "Done state" done)
2345 (string :tag "State"))
2346 (repeat
2347 (cons :tag "Tag action"
2348 (string :tag "Tag")
2349 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2351 (defcustom org-log-done nil
2352 "Information to record when a task moves to the DONE state.
2354 Possible values are:
2356 nil Don't add anything, just change the keyword
2357 time Add a time stamp to the task
2358 note Prompt for a note and add it with template `org-log-note-headings'
2360 This option can also be set with on a per-file-basis with
2362 #+STARTUP: nologdone
2363 #+STARTUP: logdone
2364 #+STARTUP: lognotedone
2366 You can have local logging settings for a subtree by setting the LOGGING
2367 property to one or more of these keywords."
2368 :group 'org-todo
2369 :group 'org-progress
2370 :type '(choice
2371 (const :tag "No logging" nil)
2372 (const :tag "Record CLOSED timestamp" time)
2373 (const :tag "Record CLOSED timestamp with note." note)))
2375 ;; Normalize old uses of org-log-done.
2376 (cond
2377 ((eq org-log-done t) (setq org-log-done 'time))
2378 ((and (listp org-log-done) (memq 'done org-log-done))
2379 (setq org-log-done 'note)))
2381 (defcustom org-log-reschedule nil
2382 "Information to record when the scheduling date of a tasks is modified.
2384 Possible values are:
2386 nil Don't add anything, just change the date
2387 time Add a time stamp to the task
2388 note Prompt for a note and add it with template `org-log-note-headings'
2390 This option can also be set with on a per-file-basis with
2392 #+STARTUP: nologreschedule
2393 #+STARTUP: logreschedule
2394 #+STARTUP: lognotereschedule"
2395 :group 'org-todo
2396 :group 'org-progress
2397 :type '(choice
2398 (const :tag "No logging" nil)
2399 (const :tag "Record timestamp" time)
2400 (const :tag "Record timestamp with note." note)))
2402 (defcustom org-log-redeadline nil
2403 "Information to record when the deadline date of a tasks is modified.
2405 Possible values are:
2407 nil Don't add anything, just change the date
2408 time Add a time stamp to the task
2409 note Prompt for a note and add it with template `org-log-note-headings'
2411 This option can also be set with on a per-file-basis with
2413 #+STARTUP: nologredeadline
2414 #+STARTUP: logredeadline
2415 #+STARTUP: lognoteredeadline
2417 You can have local logging settings for a subtree by setting the LOGGING
2418 property to one or more of these keywords."
2419 :group 'org-todo
2420 :group 'org-progress
2421 :type '(choice
2422 (const :tag "No logging" nil)
2423 (const :tag "Record timestamp" time)
2424 (const :tag "Record timestamp with note." note)))
2426 (defcustom org-log-note-clock-out nil
2427 "Non-nil means record a note when clocking out of an item.
2428 This can also be configured on a per-file basis by adding one of
2429 the following lines anywhere in the buffer:
2431 #+STARTUP: lognoteclock-out
2432 #+STARTUP: nolognoteclock-out"
2433 :group 'org-todo
2434 :group 'org-progress
2435 :type 'boolean)
2437 (defcustom org-log-done-with-time t
2438 "Non-nil means the CLOSED time stamp will contain date and time.
2439 When nil, only the date will be recorded."
2440 :group 'org-progress
2441 :type 'boolean)
2443 (defcustom org-log-note-headings
2444 '((done . "CLOSING NOTE %t")
2445 (state . "State %-12s from %-12S %t")
2446 (note . "Note taken on %t")
2447 (reschedule . "Rescheduled from %S on %t")
2448 (delschedule . "Not scheduled, was %S on %t")
2449 (redeadline . "New deadline from %S on %t")
2450 (deldeadline . "Removed deadline, was %S on %t")
2451 (refile . "Refiled on %t")
2452 (clock-out . ""))
2453 "Headings for notes added to entries.
2454 The value is an alist, with the car being a symbol indicating the note
2455 context, and the cdr is the heading to be used. The heading may also be the
2456 empty string.
2457 %t in the heading will be replaced by a time stamp.
2458 %T will be an active time stamp instead the default inactive one
2459 %d will be replaced by a short-format time stamp.
2460 %D will be replaced by an active short-format time stamp.
2461 %s will be replaced by the new TODO state, in double quotes.
2462 %S will be replaced by the old TODO state, in double quotes.
2463 %u will be replaced by the user name.
2464 %U will be replaced by the full user name.
2466 In fact, it is not a good idea to change the `state' entry, because
2467 agenda log mode depends on the format of these entries."
2468 :group 'org-todo
2469 :group 'org-progress
2470 :type '(list :greedy t
2471 (cons (const :tag "Heading when closing an item" done) string)
2472 (cons (const :tag
2473 "Heading when changing todo state (todo sequence only)"
2474 state) string)
2475 (cons (const :tag "Heading when just taking a note" note) string)
2476 (cons (const :tag "Heading when clocking out" clock-out) string)
2477 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2478 (cons (const :tag "Heading when rescheduling" reschedule) string)
2479 (cons (const :tag "Heading when changing deadline" redeadline) string)
2480 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2481 (cons (const :tag "Heading when refiling" refile) string)))
2483 (unless (assq 'note org-log-note-headings)
2484 (push '(note . "%t") org-log-note-headings))
2486 (defcustom org-log-into-drawer nil
2487 "Non-nil means insert state change notes and time stamps into a drawer.
2488 When nil, state changes notes will be inserted after the headline and
2489 any scheduling and clock lines, but not inside a drawer.
2491 The value of this variable should be the name of the drawer to use.
2492 LOGBOOK is proposed as the default drawer for this purpose, you can
2493 also set this to a string to define the drawer of your choice.
2495 A value of t is also allowed, representing \"LOGBOOK\".
2497 If this variable is set, `org-log-state-notes-insert-after-drawers'
2498 will be ignored.
2500 You can set the property LOG_INTO_DRAWER to overrule this setting for
2501 a subtree."
2502 :group 'org-todo
2503 :group 'org-progress
2504 :type '(choice
2505 (const :tag "Not into a drawer" nil)
2506 (const :tag "LOGBOOK" t)
2507 (string :tag "Other")))
2509 (if (fboundp 'defvaralias)
2510 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2512 (defun org-log-into-drawer ()
2513 "Return the value of `org-log-into-drawer', but let properties overrule.
2514 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2515 used instead of the default value."
2516 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2517 (cond
2518 ((or (not p) (equal p "nil")) org-log-into-drawer)
2519 ((equal p "t") "LOGBOOK")
2520 (t p))))
2522 (defcustom org-log-state-notes-insert-after-drawers nil
2523 "Non-nil means insert state change notes after any drawers in entry.
2524 Only the drawers that *immediately* follow the headline and the
2525 deadline/scheduled line are skipped.
2526 When nil, insert notes right after the heading and perhaps the line
2527 with deadline/scheduling if present.
2529 This variable will have no effect if `org-log-into-drawer' is
2530 set."
2531 :group 'org-todo
2532 :group 'org-progress
2533 :type 'boolean)
2535 (defcustom org-log-states-order-reversed t
2536 "Non-nil means the latest state note will be directly after heading.
2537 When nil, the state change notes will be ordered according to time."
2538 :group 'org-todo
2539 :group 'org-progress
2540 :type 'boolean)
2542 (defcustom org-todo-repeat-to-state nil
2543 "The TODO state to which a repeater should return the repeating task.
2544 By default this is the first task in a TODO sequence, or the previous state
2545 in a TODO_TYP set. But you can specify another task here.
2546 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2547 :group 'org-todo
2548 :version "24.1"
2549 :type '(choice (const :tag "Head of sequence" nil)
2550 (string :tag "Specific state")))
2552 (defcustom org-log-repeat 'time
2553 "Non-nil means record moving through the DONE state when triggering repeat.
2554 An auto-repeating task is immediately switched back to TODO when
2555 marked DONE. If you are not logging state changes (by adding \"@\"
2556 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2557 record a closing note, there will be no record of the task moving
2558 through DONE. This variable forces taking a note anyway.
2560 nil Don't force a record
2561 time Record a time stamp
2562 note Record a note
2564 This option can also be set with on a per-file-basis with
2566 #+STARTUP: logrepeat
2567 #+STARTUP: lognoterepeat
2568 #+STARTUP: nologrepeat
2570 You can have local logging settings for a subtree by setting the LOGGING
2571 property to one or more of these keywords."
2572 :group 'org-todo
2573 :group 'org-progress
2574 :type '(choice
2575 (const :tag "Don't force a record" nil)
2576 (const :tag "Force recording the DONE state" time)
2577 (const :tag "Force recording a note with the DONE state" note)))
2580 (defgroup org-priorities nil
2581 "Priorities in Org-mode."
2582 :tag "Org Priorities"
2583 :group 'org-todo)
2585 (defcustom org-enable-priority-commands t
2586 "Non-nil means priority commands are active.
2587 When nil, these commands will be disabled, so that you never accidentally
2588 set a priority."
2589 :group 'org-priorities
2590 :type 'boolean)
2592 (defcustom org-highest-priority ?A
2593 "The highest priority of TODO items. A character like ?A, ?B etc.
2594 Must have a smaller ASCII number than `org-lowest-priority'."
2595 :group 'org-priorities
2596 :type 'character)
2598 (defcustom org-lowest-priority ?C
2599 "The lowest priority of TODO items. A character like ?A, ?B etc.
2600 Must have a larger ASCII number than `org-highest-priority'."
2601 :group 'org-priorities
2602 :type 'character)
2604 (defcustom org-default-priority ?B
2605 "The default priority of TODO items.
2606 This is the priority an item gets if no explicit priority is given.
2607 When starting to cycle on an empty priority the first step in the cycle
2608 depends on `org-priority-start-cycle-with-default'. The resulting first
2609 step priority must not exceed the range from `org-highest-priority' to
2610 `org-lowest-priority' which means that `org-default-priority' has to be
2611 in this range exclusive or inclusive the range boundaries. Else the
2612 first step refuses to set the default and the second will fall back
2613 to (depending on the command used) the highest or lowest priority."
2614 :group 'org-priorities
2615 :type 'character)
2617 (defcustom org-priority-start-cycle-with-default t
2618 "Non-nil means start with default priority when starting to cycle.
2619 When this is nil, the first step in the cycle will be (depending on the
2620 command used) one higher or lower than the default priority.
2621 See also `org-default-priority'."
2622 :group 'org-priorities
2623 :type 'boolean)
2625 (defcustom org-get-priority-function nil
2626 "Function to extract the priority from a string.
2627 The string is normally the headline. If this is nil Org computes the
2628 priority from the priority cookie like [#A] in the headline. It returns
2629 an integer, increasing by 1000 for each priority level.
2630 The user can set a different function here, which should take a string
2631 as an argument and return the numeric priority."
2632 :group 'org-priorities
2633 :version "24.1"
2634 :type 'function)
2636 (defgroup org-time nil
2637 "Options concerning time stamps and deadlines in Org-mode."
2638 :tag "Org Time"
2639 :group 'org)
2641 (defcustom org-insert-labeled-timestamps-at-point nil
2642 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2643 When nil, these labeled time stamps are forces into the second line of an
2644 entry, just after the headline. When scheduling from the global TODO list,
2645 the time stamp will always be forced into the second line."
2646 :group 'org-time
2647 :type 'boolean)
2649 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2650 "Formats for `format-time-string' which are used for time stamps.
2651 It is not recommended to change this constant.")
2653 (defcustom org-time-stamp-rounding-minutes '(0 5)
2654 "Number of minutes to round time stamps to.
2655 These are two values, the first applies when first creating a time stamp.
2656 The second applies when changing it with the commands `S-up' and `S-down'.
2657 When changing the time stamp, this means that it will change in steps
2658 of N minutes, as given by the second value.
2660 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2661 numbers should be factors of 60, so for example 5, 10, 15.
2663 When this is larger than 1, you can still force an exact time stamp by using
2664 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2665 and by using a prefix arg to `S-up/down' to specify the exact number
2666 of minutes to shift."
2667 :group 'org-time
2668 :get #'(lambda (var) ; Make sure both elements are there
2669 (if (integerp (default-value var))
2670 (list (default-value var) 5)
2671 (default-value var)))
2672 :type '(list
2673 (integer :tag "when inserting times")
2674 (integer :tag "when modifying times")))
2676 ;; Normalize old customizations of this variable.
2677 (when (integerp org-time-stamp-rounding-minutes)
2678 (setq org-time-stamp-rounding-minutes
2679 (list org-time-stamp-rounding-minutes
2680 org-time-stamp-rounding-minutes)))
2682 (defcustom org-display-custom-times nil
2683 "Non-nil means overlay custom formats over all time stamps.
2684 The formats are defined through the variable `org-time-stamp-custom-formats'.
2685 To turn this on on a per-file basis, insert anywhere in the file:
2686 #+STARTUP: customtime"
2687 :group 'org-time
2688 :set 'set-default
2689 :type 'sexp)
2690 (make-variable-buffer-local 'org-display-custom-times)
2692 (defcustom org-time-stamp-custom-formats
2693 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2694 "Custom formats for time stamps. See `format-time-string' for the syntax.
2695 These are overlaid over the default ISO format if the variable
2696 `org-display-custom-times' is set. Time like %H:%M should be at the
2697 end of the second format. The custom formats are also honored by export
2698 commands, if custom time display is turned on at the time of export."
2699 :group 'org-time
2700 :type 'sexp)
2702 (defun org-time-stamp-format (&optional long inactive)
2703 "Get the right format for a time string."
2704 (let ((f (if long (cdr org-time-stamp-formats)
2705 (car org-time-stamp-formats))))
2706 (if inactive
2707 (concat "[" (substring f 1 -1) "]")
2708 f)))
2710 (defcustom org-time-clocksum-format "%d:%02d"
2711 "The format string used when creating CLOCKSUM lines.
2712 This is also used when org-mode generates a time duration."
2713 :group 'org-time
2714 :type 'string)
2716 (defcustom org-time-clocksum-use-fractional nil
2717 "If non-nil, \\[org-clock-display] uses fractional times.
2718 org-mode generates a time duration."
2719 :group 'org-time
2720 :type 'boolean)
2722 (defcustom org-time-clocksum-fractional-format "%.2f"
2723 "The format string used when creating CLOCKSUM lines, or when
2724 org-mode generates a time duration."
2725 :group 'org-time
2726 :type 'string)
2728 (defcustom org-deadline-warning-days 14
2729 "No. of days before expiration during which a deadline becomes active.
2730 This variable governs the display in sparse trees and in the agenda.
2731 When 0 or negative, it means use this number (the absolute value of it)
2732 even if a deadline has a different individual lead time specified.
2734 Custom commands can set this variable in the options section."
2735 :group 'org-time
2736 :group 'org-agenda-daily/weekly
2737 :type 'integer)
2739 (defcustom org-read-date-prefer-future t
2740 "Non-nil means assume future for incomplete date input from user.
2741 This affects the following situations:
2742 1. The user gives a month but not a year.
2743 For example, if it is April and you enter \"feb 2\", this will be read
2744 as Feb 2, *next* year. \"May 5\", however, will be this year.
2745 2. The user gives a day, but no month.
2746 For example, if today is the 15th, and you enter \"3\", Org-mode will
2747 read this as the third of *next* month. However, if you enter \"17\",
2748 it will be considered as *this* month.
2750 If you set this variable to the symbol `time', then also the following
2751 will work:
2753 3. If the user gives a time, but no day. If the time is before now,
2754 to will be interpreted as tomorrow.
2756 Currently none of this works for ISO week specifications.
2758 When this option is nil, the current day, month and year will always be
2759 used as defaults.
2761 See also `org-agenda-jump-prefer-future'."
2762 :group 'org-time
2763 :type '(choice
2764 (const :tag "Never" nil)
2765 (const :tag "Check month and day" t)
2766 (const :tag "Check month, day, and time" time)))
2768 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2769 "Should the agenda jump command prefer the future for incomplete dates?
2770 The default is to do the same as configured in `org-read-date-prefer-future'.
2771 But you can also set a deviating value here.
2772 This may t or nil, or the symbol `org-read-date-prefer-future'."
2773 :group 'org-agenda
2774 :group 'org-time
2775 :version "24.1"
2776 :type '(choice
2777 (const :tag "Use org-read-date-prefer-future"
2778 org-read-date-prefer-future)
2779 (const :tag "Never" nil)
2780 (const :tag "Always" t)))
2782 (defcustom org-read-date-force-compatible-dates t
2783 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2785 Depending on the system Emacs is running on, certain dates cannot
2786 be represented with the type used internally to represent time.
2787 Dates between 1970-1-1 and 2038-1-1 can always be represented
2788 correctly. Some systems allow for earlier dates, some for later,
2789 some for both. One way to find out it to insert any date into an
2790 Org buffer, putting the cursor on the year and hitting S-up and
2791 S-down to test the range.
2793 When this variable is set to t, the date/time prompt will not let
2794 you specify dates outside the 1970-2037 range, so it is certain that
2795 these dates will work in whatever version of Emacs you are
2796 running, and also that you can move a file from one Emacs implementation
2797 to another. WHenever Org is forcing the year for you, it will display
2798 a message and beep.
2800 When this variable is nil, Org will check if the date is
2801 representable in the specific Emacs implementation you are using.
2802 If not, it will force a year, usually the current year, and beep
2803 to remind you. Currently this setting is not recommended because
2804 the likelihood that you will open your Org files in an Emacs that
2805 has limited date range is not negligible.
2807 A workaround for this problem is to use diary sexp dates for time
2808 stamps outside of this range."
2809 :group 'org-time
2810 :version "24.1"
2811 :type 'boolean)
2813 (defcustom org-read-date-display-live t
2814 "Non-nil means display current interpretation of date prompt live.
2815 This display will be in an overlay, in the minibuffer."
2816 :group 'org-time
2817 :type 'boolean)
2819 (defcustom org-read-date-popup-calendar t
2820 "Non-nil means pop up a calendar when prompting for a date.
2821 In the calendar, the date can be selected with mouse-1. However, the
2822 minibuffer will also be active, and you can simply enter the date as well.
2823 When nil, only the minibuffer will be available."
2824 :group 'org-time
2825 :type 'boolean)
2826 (if (fboundp 'defvaralias)
2827 (defvaralias 'org-popup-calendar-for-date-prompt
2828 'org-read-date-popup-calendar))
2830 (defcustom org-read-date-minibuffer-setup-hook nil
2831 "Hook to be used to set up keys for the date/time interface.
2832 Add key definitions to `minibuffer-local-map', which will be a temporary
2833 copy."
2834 :group 'org-time
2835 :type 'hook)
2837 (defcustom org-extend-today-until 0
2838 "The hour when your day really ends. Must be an integer.
2839 This has influence for the following applications:
2840 - When switching the agenda to \"today\". It it is still earlier than
2841 the time given here, the day recognized as TODAY is actually yesterday.
2842 - When a date is read from the user and it is still before the time given
2843 here, the current date and time will be assumed to be yesterday, 23:59.
2844 Also, timestamps inserted in remember templates follow this rule.
2846 IMPORTANT: This is a feature whose implementation is and likely will
2847 remain incomplete. Really, it is only here because past midnight seems to
2848 be the favorite working time of John Wiegley :-)"
2849 :group 'org-time
2850 :type 'integer)
2852 (defcustom org-use-effective-time nil
2853 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2854 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2855 \"effective time\" of any timestamps between midnight and 8am will be
2856 23:59 of the previous day."
2857 :group 'org-time
2858 :version "24.1"
2859 :type 'boolean)
2861 (defcustom org-edit-timestamp-down-means-later nil
2862 "Non-nil means S-down will increase the time in a time stamp.
2863 When nil, S-up will increase."
2864 :group 'org-time
2865 :type 'boolean)
2867 (defcustom org-calendar-follow-timestamp-change t
2868 "Non-nil means make the calendar window follow timestamp changes.
2869 When a timestamp is modified and the calendar window is visible, it will be
2870 moved to the new date."
2871 :group 'org-time
2872 :type 'boolean)
2874 (defgroup org-tags nil
2875 "Options concerning tags in Org-mode."
2876 :tag "Org Tags"
2877 :group 'org)
2879 (defcustom org-tag-alist nil
2880 "List of tags allowed in Org-mode files.
2881 When this list is nil, Org-mode will base TAG input on what is already in the
2882 buffer.
2883 The value of this variable is an alist, the car of each entry must be a
2884 keyword as a string, the cdr may be a character that is used to select
2885 that tag through the fast-tag-selection interface.
2886 See the manual for details."
2887 :group 'org-tags
2888 :type '(repeat
2889 (choice
2890 (cons (string :tag "Tag name")
2891 (character :tag "Access char"))
2892 (list :tag "Start radio group"
2893 (const :startgroup)
2894 (option (string :tag "Group description")))
2895 (list :tag "End radio group"
2896 (const :endgroup)
2897 (option (string :tag "Group description")))
2898 (const :tag "New line" (:newline)))))
2900 (defcustom org-tag-persistent-alist nil
2901 "List of tags that will always appear in all Org-mode files.
2902 This is in addition to any in buffer settings or customizations
2903 of `org-tag-alist'.
2904 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2905 The value of this variable is an alist, the car of each entry must be a
2906 keyword as a string, the cdr may be a character that is used to select
2907 that tag through the fast-tag-selection interface.
2908 See the manual for details.
2909 To disable these tags on a per-file basis, insert anywhere in the file:
2910 #+STARTUP: noptag"
2911 :group 'org-tags
2912 :type '(repeat
2913 (choice
2914 (cons (string :tag "Tag name")
2915 (character :tag "Access char"))
2916 (const :tag "Start radio group" (:startgroup))
2917 (const :tag "End radio group" (:endgroup))
2918 (const :tag "New line" (:newline)))))
2920 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2921 "If non-nil, always offer completion for all tags of all agenda files.
2922 Instead of customizing this variable directly, you might want to
2923 set it locally for capture buffers, because there no list of
2924 tags in that file can be created dynamically (there are none).
2926 (add-hook 'org-capture-mode-hook
2927 (lambda ()
2928 (set (make-local-variable
2929 'org-complete-tags-always-offer-all-agenda-tags)
2930 t)))"
2931 :group 'org-tags
2932 :version "24.1"
2933 :type 'boolean)
2935 (defvar org-file-tags nil
2936 "List of tags that can be inherited by all entries in the file.
2937 The tags will be inherited if the variable `org-use-tag-inheritance'
2938 says they should be.
2939 This variable is populated from #+FILETAGS lines.")
2941 (defcustom org-use-fast-tag-selection 'auto
2942 "Non-nil means use fast tag selection scheme.
2943 This is a special interface to select and deselect tags with single keys.
2944 When nil, fast selection is never used.
2945 When the symbol `auto', fast selection is used if and only if selection
2946 characters for tags have been configured, either through the variable
2947 `org-tag-alist' or through a #+TAGS line in the buffer.
2948 When t, fast selection is always used and selection keys are assigned
2949 automatically if necessary."
2950 :group 'org-tags
2951 :type '(choice
2952 (const :tag "Always" t)
2953 (const :tag "Never" nil)
2954 (const :tag "When selection characters are configured" 'auto)))
2956 (defcustom org-fast-tag-selection-single-key nil
2957 "Non-nil means fast tag selection exits after first change.
2958 When nil, you have to press RET to exit it.
2959 During fast tag selection, you can toggle this flag with `C-c'.
2960 This variable can also have the value `expert'. In this case, the window
2961 displaying the tags menu is not even shown, until you press C-c again."
2962 :group 'org-tags
2963 :type '(choice
2964 (const :tag "No" nil)
2965 (const :tag "Yes" t)
2966 (const :tag "Expert" expert)))
2968 (defvar org-fast-tag-selection-include-todo nil
2969 "Non-nil means fast tags selection interface will also offer TODO states.
2970 This is an undocumented feature, you should not rely on it.")
2972 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2973 "The column to which tags should be indented in a headline.
2974 If this number is positive, it specifies the column. If it is negative,
2975 it means that the tags should be flushright to that column. For example,
2976 -80 works well for a normal 80 character screen.
2977 When 0, place tags directly after headline text, with only one space in
2978 between."
2979 :group 'org-tags
2980 :type 'integer)
2982 (defcustom org-auto-align-tags t
2983 "Non-nil keeps tags aligned when modifying headlines.
2984 Some operations (i.e. demoting) change the length of a headline and
2985 therefore shift the tags around. With this option turned on, after
2986 each such operation the tags are again aligned to `org-tags-column'."
2987 :group 'org-tags
2988 :type 'boolean)
2990 (defcustom org-use-tag-inheritance t
2991 "Non-nil means tags in levels apply also for sublevels.
2992 When nil, only the tags directly given in a specific line apply there.
2993 This may also be a list of tags that should be inherited, or a regexp that
2994 matches tags that should be inherited. Additional control is possible
2995 with the variable `org-tags-exclude-from-inheritance' which gives an
2996 explicit list of tags to be excluded from inheritance., even if the value of
2997 `org-use-tag-inheritance' would select it for inheritance.
2999 If this option is t, a match early-on in a tree can lead to a large
3000 number of matches in the subtree when constructing the agenda or creating
3001 a sparse tree. If you only want to see the first match in a tree during
3002 a search, check out the variable `org-tags-match-list-sublevels'."
3003 :group 'org-tags
3004 :type '(choice
3005 (const :tag "Not" nil)
3006 (const :tag "Always" t)
3007 (repeat :tag "Specific tags" (string :tag "Tag"))
3008 (regexp :tag "Tags matched by regexp")))
3010 (defcustom org-tags-exclude-from-inheritance nil
3011 "List of tags that should never be inherited.
3012 This is a way to exclude a few tags from inheritance. For way to do
3013 the opposite, to actively allow inheritance for selected tags,
3014 see the variable `org-use-tag-inheritance'."
3015 :group 'org-tags
3016 :type '(repeat (string :tag "Tag")))
3018 (defun org-tag-inherit-p (tag)
3019 "Check if TAG is one that should be inherited."
3020 (cond
3021 ((member tag org-tags-exclude-from-inheritance) nil)
3022 ((eq org-use-tag-inheritance t) t)
3023 ((not org-use-tag-inheritance) nil)
3024 ((stringp org-use-tag-inheritance)
3025 (string-match org-use-tag-inheritance tag))
3026 ((listp org-use-tag-inheritance)
3027 (member tag org-use-tag-inheritance))
3028 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3030 (defcustom org-tags-match-list-sublevels t
3031 "Non-nil means list also sublevels of headlines matching a search.
3032 This variable applies to tags/property searches, and also to stuck
3033 projects because this search is based on a tags match as well.
3035 When set to the symbol `indented', sublevels are indented with
3036 leading dots.
3038 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3039 the sublevels of a headline matching a tag search often also match
3040 the same search. Listing all of them can create very long lists.
3041 Setting this variable to nil causes subtrees of a match to be skipped.
3043 This variable is semi-obsolete and probably should always be true. It
3044 is better to limit inheritance to certain tags using the variables
3045 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3046 :group 'org-tags
3047 :type '(choice
3048 (const :tag "No, don't list them" nil)
3049 (const :tag "Yes, do list them" t)
3050 (const :tag "List them, indented with leading dots" indented)))
3052 (defcustom org-tags-sort-function nil
3053 "When set, tags are sorted using this function as a comparator."
3054 :group 'org-tags
3055 :type '(choice
3056 (const :tag "No sorting" nil)
3057 (const :tag "Alphabetical" string<)
3058 (const :tag "Reverse alphabetical" string>)
3059 (function :tag "Custom function" nil)))
3061 (defvar org-tags-history nil
3062 "History of minibuffer reads for tags.")
3063 (defvar org-last-tags-completion-table nil
3064 "The last used completion table for tags.")
3065 (defvar org-after-tags-change-hook nil
3066 "Hook that is run after the tags in a line have changed.")
3068 (defgroup org-properties nil
3069 "Options concerning properties in Org-mode."
3070 :tag "Org Properties"
3071 :group 'org)
3073 (defcustom org-property-format "%-10s %s"
3074 "How property key/value pairs should be formatted by `indent-line'.
3075 When `indent-line' hits a property definition, it will format the line
3076 according to this format, mainly to make sure that the values are
3077 lined-up with respect to each other."
3078 :group 'org-properties
3079 :type 'string)
3081 (defcustom org-properties-postprocess-alist nil
3082 "Alist of properties and functions to adjust inserted values.
3083 Elements of this alist must be of the form
3085 ([string] [function])
3087 where [string] must be a property name and [function] must be a
3088 lambda expression: this lambda expression must take one argument,
3089 the value to adjust, and return the new value as a string.
3091 For example, this element will allow the property \"Remaining\"
3092 to be updated wrt the relation between the \"Effort\" property
3093 and the clock summary:
3095 ((\"Remaining\" (lambda(value)
3096 (let ((clocksum (org-clock-sum-current-item))
3097 (effort (org-duration-string-to-minutes
3098 (org-entry-get (point) \"Effort\"))))
3099 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3100 :group 'org-properties
3101 :version "24.1"
3102 :type '(alist :key-type (string :tag "Property")
3103 :value-type (function :tag "Function")))
3105 (defcustom org-use-property-inheritance nil
3106 "Non-nil means properties apply also for sublevels.
3108 This setting is chiefly used during property searches. Turning it on can
3109 cause significant overhead when doing a search, which is why it is not
3110 on by default.
3112 When nil, only the properties directly given in the current entry count.
3113 When t, every property is inherited. The value may also be a list of
3114 properties that should have inheritance, or a regular expression matching
3115 properties that should be inherited.
3117 However, note that some special properties use inheritance under special
3118 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3119 and the properties ending in \"_ALL\" when they are used as descriptor
3120 for valid values of a property.
3122 Note for programmers:
3123 When querying an entry with `org-entry-get', you can control if inheritance
3124 should be used. By default, `org-entry-get' looks only at the local
3125 properties. You can request inheritance by setting the inherit argument
3126 to t (to force inheritance) or to `selective' (to respect the setting
3127 in this variable)."
3128 :group 'org-properties
3129 :type '(choice
3130 (const :tag "Not" nil)
3131 (const :tag "Always" t)
3132 (repeat :tag "Specific properties" (string :tag "Property"))
3133 (regexp :tag "Properties matched by regexp")))
3135 (defun org-property-inherit-p (property)
3136 "Check if PROPERTY is one that should be inherited."
3137 (cond
3138 ((eq org-use-property-inheritance t) t)
3139 ((not org-use-property-inheritance) nil)
3140 ((stringp org-use-property-inheritance)
3141 (string-match org-use-property-inheritance property))
3142 ((listp org-use-property-inheritance)
3143 (member property org-use-property-inheritance))
3144 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3146 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3147 "The default column format, if no other format has been defined.
3148 This variable can be set on the per-file basis by inserting a line
3150 #+COLUMNS: %25ITEM ....."
3151 :group 'org-properties
3152 :type 'string)
3154 (defcustom org-columns-ellipses ".."
3155 "The ellipses to be used when a field in column view is truncated.
3156 When this is the empty string, as many characters as possible are shown,
3157 but then there will be no visual indication that the field has been truncated.
3158 When this is a string of length N, the last N characters of a truncated
3159 field are replaced by this string. If the column is narrower than the
3160 ellipses string, only part of the ellipses string will be shown."
3161 :group 'org-properties
3162 :type 'string)
3164 (defcustom org-columns-modify-value-for-display-function nil
3165 "Function that modifies values for display in column view.
3166 For example, it can be used to cut out a certain part from a time stamp.
3167 The function must take 2 arguments:
3169 column-title The title of the column (*not* the property name)
3170 value The value that should be modified.
3172 The function should return the value that should be displayed,
3173 or nil if the normal value should be used."
3174 :group 'org-properties
3175 :type 'function)
3177 (defcustom org-effort-property "Effort"
3178 "The property that is being used to keep track of effort estimates.
3179 Effort estimates given in this property need to have the format H:MM."
3180 :group 'org-properties
3181 :group 'org-progress
3182 :type '(string :tag "Property"))
3184 (defconst org-global-properties-fixed
3185 '(("VISIBILITY_ALL" . "folded children content all")
3186 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3187 "List of property/value pairs that can be inherited by any entry.
3189 These are fixed values, for the preset properties. The user variable
3190 that can be used to add to this list is `org-global-properties'.
3192 The entries in this list are cons cells where the car is a property
3193 name and cdr is a string with the value. If the value represents
3194 multiple items like an \"_ALL\" property, separate the items by
3195 spaces.")
3197 (defcustom org-global-properties nil
3198 "List of property/value pairs that can be inherited by any entry.
3200 This list will be combined with the constant `org-global-properties-fixed'.
3202 The entries in this list are cons cells where the car is a property
3203 name and cdr is a string with the value.
3205 You can set buffer-local values for the same purpose in the variable
3206 `org-file-properties' this by adding lines like
3208 #+PROPERTY: NAME VALUE"
3209 :group 'org-properties
3210 :type '(repeat
3211 (cons (string :tag "Property")
3212 (string :tag "Value"))))
3214 (defvar org-file-properties nil
3215 "List of property/value pairs that can be inherited by any entry.
3216 Valid for the current buffer.
3217 This variable is populated from #+PROPERTY lines.")
3218 (make-variable-buffer-local 'org-file-properties)
3220 (defgroup org-agenda nil
3221 "Options concerning agenda views in Org-mode."
3222 :tag "Org Agenda"
3223 :group 'org)
3225 (defvar org-category nil
3226 "Variable used by org files to set a category for agenda display.
3227 Such files should use a file variable to set it, for example
3229 # -*- mode: org; org-category: \"ELisp\"
3231 or contain a special line
3233 #+CATEGORY: ELisp
3235 If the file does not specify a category, then file's base name
3236 is used instead.")
3237 (make-variable-buffer-local 'org-category)
3238 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3240 (defcustom org-agenda-files nil
3241 "The files to be used for agenda display.
3242 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3243 \\[org-remove-file]. You can also use customize to edit the list.
3245 If an entry is a directory, all files in that directory that are matched by
3246 `org-agenda-file-regexp' will be part of the file list.
3248 If the value of the variable is not a list but a single file name, then
3249 the list of agenda files is actually stored and maintained in that file, one
3250 agenda file per line. In this file paths can be given relative to
3251 `org-directory'. Tilde expansion and environment variable substitution
3252 are also made."
3253 :group 'org-agenda
3254 :type '(choice
3255 (repeat :tag "List of files and directories" file)
3256 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3258 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3259 "Regular expression to match files for `org-agenda-files'.
3260 If any element in the list in that variable contains a directory instead
3261 of a normal file, all files in that directory that are matched by this
3262 regular expression will be included."
3263 :group 'org-agenda
3264 :type 'regexp)
3266 (defcustom org-agenda-text-search-extra-files nil
3267 "List of extra files to be searched by text search commands.
3268 These files will be search in addition to the agenda files by the
3269 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3270 Note that these files will only be searched for text search commands,
3271 not for the other agenda views like todo lists, tag searches or the weekly
3272 agenda. This variable is intended to list notes and possibly archive files
3273 that should also be searched by these two commands.
3274 In fact, if the first element in the list is the symbol `agenda-archives',
3275 than all archive files of all agenda files will be added to the search
3276 scope."
3277 :group 'org-agenda
3278 :type '(set :greedy t
3279 (const :tag "Agenda Archives" agenda-archives)
3280 (repeat :inline t (file))))
3282 (if (fboundp 'defvaralias)
3283 (defvaralias 'org-agenda-multi-occur-extra-files
3284 'org-agenda-text-search-extra-files))
3286 (defcustom org-agenda-skip-unavailable-files nil
3287 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3288 A nil value means to remove them, after a query, from the list."
3289 :group 'org-agenda
3290 :type 'boolean)
3292 (defcustom org-calendar-to-agenda-key [?c]
3293 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3294 The command `org-calendar-goto-agenda' will be bound to this key. The
3295 default is the character `c' because then `c' can be used to switch back and
3296 forth between agenda and calendar."
3297 :group 'org-agenda
3298 :type 'sexp)
3300 (defcustom org-calendar-agenda-action-key [?k]
3301 "The key to be installed in `calendar-mode-map' for agenda-action.
3302 The command `org-agenda-action' will be bound to this key. The
3303 default is the character `k' because we use the same key in the agenda."
3304 :group 'org-agenda
3305 :type 'sexp)
3307 (defcustom org-calendar-insert-diary-entry-key [?i]
3308 "The key to be installed in `calendar-mode-map' for adding diary entries.
3309 This option is irrelevant until `org-agenda-diary-file' has been configured
3310 to point to an Org-mode file. When that is the case, the command
3311 `org-agenda-diary-entry' will be bound to the key given here, by default
3312 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3313 if you want to continue doing this, you need to change this to a different
3314 key."
3315 :group 'org-agenda
3316 :type 'sexp)
3318 (defcustom org-agenda-diary-file 'diary-file
3319 "File to which to add new entries with the `i' key in agenda and calendar.
3320 When this is the symbol `diary-file', the functionality in the Emacs
3321 calendar will be used to add entries to the `diary-file'. But when this
3322 points to a file, `org-agenda-diary-entry' will be used instead."
3323 :group 'org-agenda
3324 :type '(choice
3325 (const :tag "The standard Emacs diary file" diary-file)
3326 (file :tag "Special Org file diary entries")))
3328 (eval-after-load "calendar"
3329 '(progn
3330 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3331 'org-calendar-goto-agenda)
3332 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3333 'org-agenda-action)
3334 (add-hook 'calendar-mode-hook
3335 (lambda ()
3336 (unless (eq org-agenda-diary-file 'diary-file)
3337 (define-key calendar-mode-map
3338 org-calendar-insert-diary-entry-key
3339 'org-agenda-diary-entry))))))
3341 (defgroup org-latex nil
3342 "Options for embedding LaTeX code into Org-mode."
3343 :tag "Org LaTeX"
3344 :group 'org)
3346 (defcustom org-format-latex-options
3347 '(:foreground default :background default :scale 1.0
3348 :html-foreground "Black" :html-background "Transparent"
3349 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3350 "Options for creating images from LaTeX fragments.
3351 This is a property list with the following properties:
3352 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3353 `default' means use the foreground of the default face.
3354 :background the background color, or \"Transparent\".
3355 `default' means use the background of the default face.
3356 :scale a scaling factor for the size of the images, to get more pixels
3357 :html-foreground, :html-background, :html-scale
3358 the same numbers for HTML export.
3359 :matchers a list indicating which matchers should be used to
3360 find LaTeX fragments. Valid members of this list are:
3361 \"begin\" find environments
3362 \"$1\" find single characters surrounded by $.$
3363 \"$\" find math expressions surrounded by $...$
3364 \"$$\" find math expressions surrounded by $$....$$
3365 \"\\(\" find math expressions surrounded by \\(...\\)
3366 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3367 :group 'org-latex
3368 :type 'plist)
3370 (defcustom org-format-latex-signal-error t
3371 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3372 When nil, just push out a message."
3373 :group 'org-latex
3374 :version "24.1"
3375 :type 'boolean)
3377 (defcustom org-latex-to-mathml-jar-file nil
3378 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3379 Use this to specify additional executable file say a jar file.
3381 When using MathToWeb as the converter, specify the full-path to
3382 your mathtoweb.jar file."
3383 :group 'org-latex
3384 :version "24.1"
3385 :type '(choice
3386 (const :tag "None" nil)
3387 (file :tag "JAR file" :must-match t)))
3389 (defcustom org-latex-to-mathml-convert-command nil
3390 "Command to convert LaTeX fragments to MathML.
3391 Replace format-specifiers in the command as noted below and use
3392 `shell-command' to convert LaTeX to MathML.
3393 %j: Executable file in fully expanded form as specified by
3394 `org-latex-to-mathml-jar-file'.
3395 %I: Input LaTeX file in fully expanded form
3396 %o: Output MathML file
3397 This command is used by `org-create-math-formula'.
3399 When using MathToWeb as the converter, set this to
3400 \"java -jar %j -unicode -force -df %o %I\"."
3401 :group 'org-latex
3402 :version "24.1"
3403 :type '(choice
3404 (const :tag "None" nil)
3405 (string :tag "\nShell command")))
3407 (defcustom org-latex-create-formula-image-program 'dvipng
3408 "Program to convert LaTeX fragments with.
3410 dvipng Process the LaTeX fragments to dvi file, then convert
3411 dvi files to png files using dvipng.
3412 This will also include processing of non-math environments.
3413 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3414 to convert pdf files to png files"
3415 :group 'org-latex
3416 :version "24.1"
3417 :type '(choice
3418 (const :tag "dvipng" dvipng)
3419 (const :tag "imagemagick" imagemagick)))
3421 (defun org-format-latex-mathml-available-p ()
3422 "Return t if `org-latex-to-mathml-convert-command' is usable."
3423 (save-match-data
3424 (when (and (boundp 'org-latex-to-mathml-convert-command)
3425 org-latex-to-mathml-convert-command)
3426 (let ((executable (car (split-string
3427 org-latex-to-mathml-convert-command))))
3428 (when (executable-find executable)
3429 (if (string-match
3430 "%j" org-latex-to-mathml-convert-command)
3431 (file-readable-p org-latex-to-mathml-jar-file)
3432 t))))))
3434 (defcustom org-format-latex-header "\\documentclass{article}
3435 \\usepackage[usenames]{color}
3436 \\usepackage{amsmath}
3437 \\usepackage[mathscr]{eucal}
3438 \\pagestyle{empty} % do not remove
3439 \[PACKAGES]
3440 \[DEFAULT-PACKAGES]
3441 % The settings below are copied from fullpage.sty
3442 \\setlength{\\textwidth}{\\paperwidth}
3443 \\addtolength{\\textwidth}{-3cm}
3444 \\setlength{\\oddsidemargin}{1.5cm}
3445 \\addtolength{\\oddsidemargin}{-2.54cm}
3446 \\setlength{\\evensidemargin}{\\oddsidemargin}
3447 \\setlength{\\textheight}{\\paperheight}
3448 \\addtolength{\\textheight}{-\\headheight}
3449 \\addtolength{\\textheight}{-\\headsep}
3450 \\addtolength{\\textheight}{-\\footskip}
3451 \\addtolength{\\textheight}{-3cm}
3452 \\setlength{\\topmargin}{1.5cm}
3453 \\addtolength{\\topmargin}{-2.54cm}"
3454 "The document header used for processing LaTeX fragments.
3455 It is imperative that this header make sure that no page number
3456 appears on the page. The package defined in the variables
3457 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3458 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3459 will be appended."
3460 :group 'org-latex
3461 :type 'string)
3463 (defvar org-format-latex-header-extra nil)
3465 (defun org-set-packages-alist (var val)
3466 "Set the packages alist and make sure it has 3 elements per entry."
3467 (set var (mapcar (lambda (x)
3468 (if (and (consp x) (= (length x) 2))
3469 (list (car x) (nth 1 x) t)
3471 val)))
3473 (defun org-get-packages-alist (var)
3475 "Get the packages alist and make sure it has 3 elements per entry."
3476 (mapcar (lambda (x)
3477 (if (and (consp x) (= (length x) 2))
3478 (list (car x) (nth 1 x) t)
3480 (default-value var)))
3482 ;; The following variables are defined here because is it also used
3483 ;; when formatting latex fragments. Originally it was part of the
3484 ;; LaTeX exporter, which is why the name includes "export".
3485 (defcustom org-export-latex-default-packages-alist
3486 '(("AUTO" "inputenc" t)
3487 ("T1" "fontenc" t)
3488 ("" "fixltx2e" nil)
3489 ("" "graphicx" t)
3490 ("" "longtable" nil)
3491 ("" "float" nil)
3492 ("" "wrapfig" nil)
3493 ("" "soul" t)
3494 ("" "textcomp" t)
3495 ("" "marvosym" t)
3496 ("" "wasysym" t)
3497 ("" "latexsym" t)
3498 ("" "amssymb" t)
3499 ("" "hyperref" nil)
3500 "\\tolerance=1000"
3502 "Alist of default packages to be inserted in the header.
3503 Change this only if one of the packages here causes an incompatibility
3504 with another package you are using.
3505 The packages in this list are needed by one part or another of Org-mode
3506 to function properly.
3508 - inputenc, fontenc: for basic font and character selection
3509 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3510 for interpreting the entities in `org-entities'. You can skip some of these
3511 packages if you don't use any of the symbols in it.
3512 - graphicx: for including images
3513 - float, wrapfig: for figure placement
3514 - longtable: for long tables
3515 - hyperref: for cross references
3517 Therefore you should not modify this variable unless you know what you
3518 are doing. The one reason to change it anyway is that you might be loading
3519 some other package that conflicts with one of the default packages.
3520 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3521 If SNIPPET-FLAG is t, the package also needs to be included when
3522 compiling LaTeX snippets into images for inclusion into HTML."
3523 :group 'org-export-latex
3524 :set 'org-set-packages-alist
3525 :get 'org-get-packages-alist
3526 :version "24.1"
3527 :type '(repeat
3528 (choice
3529 (list :tag "options/package pair"
3530 (string :tag "options")
3531 (string :tag "package")
3532 (boolean :tag "Snippet"))
3533 (string :tag "A line of LaTeX"))))
3535 (defcustom org-export-latex-packages-alist nil
3536 "Alist of packages to be inserted in every LaTeX header.
3537 These will be inserted after `org-export-latex-default-packages-alist'.
3538 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3539 SNIPPET-FLAG, when t, indicates that this package is also needed when
3540 turning LaTeX snippets into images for inclusion into HTML.
3541 Make sure that you only list packages here which:
3542 - you want in every file
3543 - do not conflict with the default packages in
3544 `org-export-latex-default-packages-alist'
3545 - do not conflict with the setup in `org-format-latex-header'."
3546 :group 'org-export-latex
3547 :set 'org-set-packages-alist
3548 :get 'org-get-packages-alist
3549 :type '(repeat
3550 (choice
3551 (list :tag "options/package pair"
3552 (string :tag "options")
3553 (string :tag "package")
3554 (boolean :tag "Snippet"))
3555 (string :tag "A line of LaTeX"))))
3558 (defgroup org-appearance nil
3559 "Settings for Org-mode appearance."
3560 :tag "Org Appearance"
3561 :group 'org)
3563 (defcustom org-level-color-stars-only nil
3564 "Non-nil means fontify only the stars in each headline.
3565 When nil, the entire headline is fontified.
3566 Changing it requires restart of `font-lock-mode' to become effective
3567 also in regions already fontified."
3568 :group 'org-appearance
3569 :type 'boolean)
3571 (defcustom org-hide-leading-stars nil
3572 "Non-nil means hide the first N-1 stars in a headline.
3573 This works by using the face `org-hide' for these stars. This
3574 face is white for a light background, and black for a dark
3575 background. You may have to customize the face `org-hide' to
3576 make this work.
3577 Changing it requires restart of `font-lock-mode' to become effective
3578 also in regions already fontified.
3579 You may also set this on a per-file basis by adding one of the following
3580 lines to the buffer:
3582 #+STARTUP: hidestars
3583 #+STARTUP: showstars"
3584 :group 'org-appearance
3585 :type 'boolean)
3587 (defcustom org-hidden-keywords nil
3588 "List of symbols corresponding to keywords to be hidden the org buffer.
3589 For example, a value '(title) for this list will make the document's title
3590 appear in the buffer without the initial #+TITLE: keyword."
3591 :group 'org-appearance
3592 :version "24.1"
3593 :type '(set (const :tag "#+AUTHOR" author)
3594 (const :tag "#+DATE" date)
3595 (const :tag "#+EMAIL" email)
3596 (const :tag "#+TITLE" title)))
3598 (defcustom org-fontify-done-headline nil
3599 "Non-nil means change the face of a headline if it is marked DONE.
3600 Normally, only the TODO/DONE keyword indicates the state of a headline.
3601 When this is non-nil, the headline after the keyword is set to the
3602 `org-headline-done' as an additional indication."
3603 :group 'org-appearance
3604 :type 'boolean)
3606 (defcustom org-fontify-emphasized-text t
3607 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3608 Changing this variable requires a restart of Emacs to take effect."
3609 :group 'org-appearance
3610 :type 'boolean)
3612 (defcustom org-fontify-whole-heading-line nil
3613 "Non-nil means fontify the whole line for headings.
3614 This is useful when setting a background color for the
3615 org-level-* faces."
3616 :group 'org-appearance
3617 :type 'boolean)
3619 (defcustom org-highlight-latex-fragments-and-specials nil
3620 "Non-nil means fontify what is treated specially by the exporters."
3621 :group 'org-appearance
3622 :type 'boolean)
3624 (defcustom org-hide-emphasis-markers nil
3625 "Non-nil mean font-lock should hide the emphasis marker characters."
3626 :group 'org-appearance
3627 :type 'boolean)
3629 (defcustom org-pretty-entities nil
3630 "Non-nil means show entities as UTF8 characters.
3631 When nil, the \\name form remains in the buffer."
3632 :group 'org-appearance
3633 :version "24.1"
3634 :type 'boolean)
3636 (defcustom org-pretty-entities-include-sub-superscripts t
3637 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3638 :group 'org-appearance
3639 :version "24.1"
3640 :type 'boolean)
3642 (defvar org-emph-re nil
3643 "Regular expression for matching emphasis.
3644 After a match, the match groups contain these elements:
3645 0 The match of the full regular expression, including the characters
3646 before and after the proper match
3647 1 The character before the proper match, or empty at beginning of line
3648 2 The proper match, including the leading and trailing markers
3649 3 The leading marker like * or /, indicating the type of highlighting
3650 4 The text between the emphasis markers, not including the markers
3651 5 The character after the match, empty at the end of a line")
3652 (defvar org-verbatim-re nil
3653 "Regular expression for matching verbatim text.")
3654 (defvar org-emphasis-regexp-components) ; defined just below
3655 (defvar org-emphasis-alist) ; defined just below
3656 (defun org-set-emph-re (var val)
3657 "Set variable and compute the emphasis regular expression."
3658 (set var val)
3659 (when (and (boundp 'org-emphasis-alist)
3660 (boundp 'org-emphasis-regexp-components)
3661 org-emphasis-alist org-emphasis-regexp-components)
3662 (let* ((e org-emphasis-regexp-components)
3663 (pre (car e))
3664 (post (nth 1 e))
3665 (border (nth 2 e))
3666 (body (nth 3 e))
3667 (nl (nth 4 e))
3668 (body1 (concat body "*?"))
3669 (markers (mapconcat 'car org-emphasis-alist ""))
3670 (vmarkers (mapconcat
3671 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3672 org-emphasis-alist "")))
3673 ;; make sure special characters appear at the right position in the class
3674 (if (string-match "\\^" markers)
3675 (setq markers (concat (replace-match "" t t markers) "^")))
3676 (if (string-match "-" markers)
3677 (setq markers (concat (replace-match "" t t markers) "-")))
3678 (if (string-match "\\^" vmarkers)
3679 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3680 (if (string-match "-" vmarkers)
3681 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3682 (if (> nl 0)
3683 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3684 (int-to-string nl) "\\}")))
3685 ;; Make the regexp
3686 (setq org-emph-re
3687 (concat "\\([" pre "]\\|^\\)"
3688 "\\("
3689 "\\([" markers "]\\)"
3690 "\\("
3691 "[^" border "]\\|"
3692 "[^" border "]"
3693 body1
3694 "[^" border "]"
3695 "\\)"
3696 "\\3\\)"
3697 "\\([" post "]\\|$\\)"))
3698 (setq org-verbatim-re
3699 (concat "\\([" pre "]\\|^\\)"
3700 "\\("
3701 "\\([" vmarkers "]\\)"
3702 "\\("
3703 "[^" border "]\\|"
3704 "[^" border "]"
3705 body1
3706 "[^" border "]"
3707 "\\)"
3708 "\\3\\)"
3709 "\\([" post "]\\|$\\)")))))
3711 (defcustom org-emphasis-regexp-components
3712 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3713 "Components used to build the regular expression for emphasis.
3714 This is a list with five entries. Terminology: In an emphasis string
3715 like \" *strong word* \", we call the initial space PREMATCH, the final
3716 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3717 and \"trong wor\" is the body. The different components in this variable
3718 specify what is allowed/forbidden in each part:
3720 pre Chars allowed as prematch. Beginning of line will be allowed too.
3721 post Chars allowed as postmatch. End of line will be allowed too.
3722 border The chars *forbidden* as border characters.
3723 body-regexp A regexp like \".\" to match a body character. Don't use
3724 non-shy groups here, and don't allow newline here.
3725 newline The maximum number of newlines allowed in an emphasis exp.
3727 Use customize to modify this, or restart Emacs after changing it."
3728 :group 'org-appearance
3729 :set 'org-set-emph-re
3730 :type '(list
3731 (sexp :tag "Allowed chars in pre ")
3732 (sexp :tag "Allowed chars in post ")
3733 (sexp :tag "Forbidden chars in border ")
3734 (sexp :tag "Regexp for body ")
3735 (integer :tag "number of newlines allowed")
3736 (option (boolean :tag "Please ignore this button"))))
3738 (defcustom org-emphasis-alist
3739 `(("*" bold "<b>" "</b>")
3740 ("/" italic "<i>" "</i>")
3741 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3742 ("=" org-code "<code>" "</code>" verbatim)
3743 ("~" org-verbatim "<code>" "</code>" verbatim)
3744 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3745 "<del>" "</del>")
3747 "Special syntax for emphasized text.
3748 Text starting and ending with a special character will be emphasized, for
3749 example *bold*, _underlined_ and /italic/. This variable sets the marker
3750 characters, the face to be used by font-lock for highlighting in Org-mode
3751 Emacs buffers, and the HTML tags to be used for this.
3752 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3753 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3754 Use customize to modify this, or restart Emacs after changing it."
3755 :group 'org-appearance
3756 :set 'org-set-emph-re
3757 :type '(repeat
3758 (list
3759 (string :tag "Marker character")
3760 (choice
3761 (face :tag "Font-lock-face")
3762 (plist :tag "Face property list"))
3763 (string :tag "HTML start tag")
3764 (string :tag "HTML end tag")
3765 (option (const verbatim)))))
3767 (defvar org-protecting-blocks
3768 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3769 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3770 This is needed for font-lock setup.")
3772 ;;; Miscellaneous options
3774 (defgroup org-completion nil
3775 "Completion in Org-mode."
3776 :tag "Org Completion"
3777 :group 'org)
3779 (defcustom org-completion-use-ido nil
3780 "Non-nil means use ido completion wherever possible.
3781 Note that `ido-mode' must be active for this variable to be relevant.
3782 If you decide to turn this variable on, you might well want to turn off
3783 `org-outline-path-complete-in-steps'.
3784 See also `org-completion-use-iswitchb'."
3785 :group 'org-completion
3786 :type 'boolean)
3788 (defcustom org-completion-use-iswitchb nil
3789 "Non-nil means use iswitchb completion wherever possible.
3790 Note that `iswitchb-mode' must be active for this variable to be relevant.
3791 If you decide to turn this variable on, you might well want to turn off
3792 `org-outline-path-complete-in-steps'.
3793 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3794 :group 'org-completion
3795 :type 'boolean)
3797 (defcustom org-completion-fallback-command 'hippie-expand
3798 "The expansion command called by \\[pcomplete] in normal context.
3799 Normal means, no org-mode-specific context."
3800 :group 'org-completion
3801 :type 'function)
3803 ;;; Functions and variables from their packages
3804 ;; Declared here to avoid compiler warnings
3806 ;; XEmacs only
3807 (defvar outline-mode-menu-heading)
3808 (defvar outline-mode-menu-show)
3809 (defvar outline-mode-menu-hide)
3810 (defvar zmacs-regions) ; XEmacs regions
3812 ;; Emacs only
3813 (defvar mark-active)
3815 ;; Various packages
3816 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3817 (declare-function calendar-forward-day "cal-move" (arg))
3818 (declare-function calendar-goto-date "cal-move" (date))
3819 (declare-function calendar-goto-today "cal-move" ())
3820 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3821 (defvar calc-embedded-close-formula)
3822 (defvar calc-embedded-open-formula)
3823 (declare-function cdlatex-tab "ext:cdlatex" ())
3824 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3825 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3826 (defvar font-lock-unfontify-region-function)
3827 (declare-function iswitchb-read-buffer "iswitchb"
3828 (prompt &optional default require-match start matches-set))
3829 (defvar iswitchb-temp-buflist)
3830 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3831 (defvar org-agenda-tags-todo-honor-ignore-options)
3832 (declare-function org-agenda-skip "org-agenda" ())
3833 (declare-function
3834 org-agenda-format-item "org-agenda"
3835 (extra txt &optional category tags dotime noprefix remove-re habitp))
3836 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3837 (declare-function org-agenda-change-all-lines "org-agenda"
3838 (newhead hdmarker &optional fixface just-this))
3839 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3840 (declare-function org-agenda-maybe-redo "org-agenda" ())
3841 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3842 (beg end))
3843 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3844 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3845 "org-agenda" (&optional end))
3846 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3847 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3848 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3849 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3850 (declare-function org-indent-mode "org-indent" (&optional arg))
3851 (declare-function parse-time-string "parse-time" (string))
3852 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3853 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3854 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3855 (defvar remember-data-file)
3856 (defvar texmathp-why)
3857 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3858 (declare-function table--at-cell-p "table" (position &optional object at-column))
3860 (defvar w3m-current-url)
3861 (defvar w3m-current-title)
3863 (defvar org-latex-regexps)
3865 ;;; Autoload and prepare some org modules
3867 ;; Some table stuff that needs to be defined here, because it is used
3868 ;; by the functions setting up org-mode or checking for table context.
3870 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3871 "Detect an org-type or table-type table.")
3872 (defconst org-table-line-regexp "^[ \t]*|"
3873 "Detect an org-type table line.")
3874 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3875 "Detect an org-type table line.")
3876 (defconst org-table-hline-regexp "^[ \t]*|-"
3877 "Detect an org-type table hline.")
3878 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3879 "Detect a table-type table hline.")
3880 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3881 "Detect the first line outside a table when searching from within it.
3882 This works for both table types.")
3884 ;; Autoload the functions in org-table.el that are needed by functions here.
3886 (eval-and-compile
3887 (org-autoload "org-table"
3888 '(org-table-align org-table-begin org-table-blank-field
3889 org-table-convert org-table-convert-region org-table-copy-down
3890 org-table-copy-region org-table-create
3891 org-table-create-or-convert-from-region
3892 org-table-create-with-table.el org-table-current-dline
3893 org-table-cut-region org-table-delete-column org-table-edit-field
3894 org-table-edit-formulas org-table-end org-table-eval-formula
3895 org-table-export org-table-field-info
3896 org-table-get-stored-formulas org-table-goto-column
3897 org-table-hline-and-move org-table-import org-table-insert-column
3898 org-table-insert-hline org-table-insert-row org-table-iterate
3899 org-table-justify-field-maybe org-table-kill-row
3900 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3901 org-table-move-column org-table-move-column-left
3902 org-table-move-column-right org-table-move-row
3903 org-table-move-row-down org-table-move-row-up
3904 org-table-next-field org-table-next-row org-table-paste-rectangle
3905 org-table-previous-field org-table-recalculate
3906 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3907 org-table-toggle-coordinate-overlays
3908 org-table-toggle-formula-debugger org-table-wrap-region
3909 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3910 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3911 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3913 (defun org-at-table-p (&optional table-type)
3914 "Return t if the cursor is inside an org-type table.
3915 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3916 (if org-enable-table-editor
3917 (save-excursion
3918 (beginning-of-line 1)
3919 (looking-at (if table-type org-table-any-line-regexp
3920 org-table-line-regexp)))
3921 nil))
3922 (defsubst org-table-p () (org-at-table-p))
3924 (defun org-at-table.el-p ()
3925 "Return t if and only if we are at a table.el table."
3926 (and (org-at-table-p 'any)
3927 (save-excursion
3928 (goto-char (org-table-begin 'any))
3929 (looking-at org-table1-hline-regexp))))
3930 (defun org-table-recognize-table.el ()
3931 "If there is a table.el table nearby, recognize it and move into it."
3932 (if org-table-tab-recognizes-table.el
3933 (if (org-at-table.el-p)
3934 (progn
3935 (beginning-of-line 1)
3936 (if (looking-at org-table-dataline-regexp)
3938 (if (looking-at org-table1-hline-regexp)
3939 (progn
3940 (beginning-of-line 2)
3941 (if (looking-at org-table-any-border-regexp)
3942 (beginning-of-line -1)))))
3943 (if (re-search-forward "|" (org-table-end t) t)
3944 (progn
3945 (require 'table)
3946 (if (table--at-cell-p (point))
3948 (message "recognizing table.el table...")
3949 (table-recognize-table)
3950 (message "recognizing table.el table...done")))
3951 (error "This should not happen"))
3953 nil)
3954 nil))
3956 (defun org-at-table-hline-p ()
3957 "Return t if the cursor is inside a hline in a table."
3958 (if org-enable-table-editor
3959 (save-excursion
3960 (beginning-of-line 1)
3961 (looking-at org-table-hline-regexp))
3962 nil))
3964 (defvar org-table-clean-did-remove-column nil)
3966 (defun org-table-map-tables (function &optional quietly)
3967 "Apply FUNCTION to the start of all tables in the buffer."
3968 (save-excursion
3969 (save-restriction
3970 (widen)
3971 (goto-char (point-min))
3972 (while (re-search-forward org-table-any-line-regexp nil t)
3973 (unless quietly
3974 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3975 (beginning-of-line 1)
3976 (when (and (looking-at org-table-line-regexp)
3977 ;; Exclude tables in src/example/verbatim/clocktable blocks
3978 (not (org-in-block-p '("src" "example"))))
3979 (save-excursion (funcall function))
3980 (or (looking-at org-table-line-regexp)
3981 (forward-char 1)))
3982 (re-search-forward org-table-any-border-regexp nil 1))))
3983 (unless quietly (message "Mapping tables: done")))
3985 ;; Declare and autoload functions from org-exp.el & Co
3987 (declare-function org-default-export-plist "org-exp")
3988 (declare-function org-infile-export-plist "org-exp")
3989 (declare-function org-get-current-options "org-exp")
3990 (eval-and-compile
3991 (org-autoload "org-exp"
3992 '(org-export org-export-visible
3993 org-insert-export-options-template
3994 org-table-clean-before-export))
3995 (org-autoload "org-ascii"
3996 '(org-export-as-ascii org-export-ascii-preprocess
3997 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3998 org-export-region-as-ascii))
3999 (org-autoload "org-latex"
4000 '(org-export-as-latex-batch org-export-as-latex-to-buffer
4001 org-replace-region-by-latex org-export-region-as-latex
4002 org-export-as-latex org-export-as-pdf
4003 org-export-as-pdf-and-open))
4004 (org-autoload "org-html"
4005 '(org-export-as-html-and-open
4006 org-export-as-html-batch org-export-as-html-to-buffer
4007 org-replace-region-by-html org-export-region-as-html
4008 org-export-as-html))
4009 (org-autoload "org-docbook"
4010 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4011 org-replace-region-by-docbook org-export-region-as-docbook
4012 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4013 org-export-as-docbook))
4014 (org-autoload "org-icalendar"
4015 '(org-export-icalendar-this-file
4016 org-export-icalendar-all-agenda-files
4017 org-export-icalendar-combine-agenda-files))
4018 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4019 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4021 ;; Declare and autoload functions from org-agenda.el
4023 (eval-and-compile
4024 (org-autoload "org-agenda"
4025 '(org-agenda org-agenda-list org-search-view
4026 org-todo-list org-tags-view org-agenda-list-stuck-projects
4027 org-diary org-agenda-to-appt
4028 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4030 ;; Autoload org-remember
4032 (eval-and-compile
4033 (org-autoload "org-remember"
4034 '(org-remember-insinuate org-remember-annotation
4035 org-remember-apply-template org-remember org-remember-handler)))
4037 (eval-and-compile
4038 (org-autoload "org-capture"
4039 '(org-capture org-capture-insert-template-here
4040 org-capture-import-remember-templates)))
4042 ;; Autoload org-clock.el
4044 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4045 (beg end))
4046 (declare-function org-clock-update-mode-line "org-clock" ())
4047 (declare-function org-resolve-clocks "org-clock"
4048 (&optional also-non-dangling-p prompt last-valid))
4049 (defvar org-clock-start-time)
4050 (defvar org-clock-marker (make-marker)
4051 "Marker recording the last clock-in.")
4052 (defvar org-clock-hd-marker (make-marker)
4053 "Marker recording the last clock-in, but the headline position.")
4054 (defvar org-clock-heading ""
4055 "The heading of the current clock entry.")
4056 (defun org-clock-is-active ()
4057 "Return non-nil if clock is currently running.
4058 The return value is actually the clock marker."
4059 (marker-buffer org-clock-marker))
4061 (eval-and-compile
4062 (org-autoload
4063 "org-clock"
4064 '(org-clock-in org-clock-out org-clock-cancel
4065 org-clock-goto org-clock-sum org-clock-display
4066 org-clock-remove-overlays org-clock-report
4067 org-clocktable-shift org-dblock-write:clocktable
4068 org-get-clocktable org-resolve-clocks)))
4070 (defun org-clock-update-time-maybe ()
4071 "If this is a CLOCK line, update it and return t.
4072 Otherwise, return nil."
4073 (interactive)
4074 (save-excursion
4075 (beginning-of-line 1)
4076 (skip-chars-forward " \t")
4077 (when (looking-at org-clock-string)
4078 (let ((re (concat "[ \t]*" org-clock-string
4079 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4080 "\\([ \t]*=>.*\\)?\\)?"))
4081 ts te h m s neg)
4082 (cond
4083 ((not (looking-at re))
4084 nil)
4085 ((not (match-end 2))
4086 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4087 (> org-clock-marker (point))
4088 (<= org-clock-marker (point-at-eol)))
4089 ;; The clock is running here
4090 (setq org-clock-start-time
4091 (apply 'encode-time
4092 (org-parse-time-string (match-string 1))))
4093 (org-clock-update-mode-line)))
4095 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4096 (end-of-line 1)
4097 (setq ts (match-string 1)
4098 te (match-string 3))
4099 (setq s (- (org-float-time
4100 (apply 'encode-time (org-parse-time-string te)))
4101 (org-float-time
4102 (apply 'encode-time (org-parse-time-string ts))))
4103 neg (< s 0)
4104 s (abs s)
4105 h (floor (/ s 3600))
4106 s (- s (* 3600 h))
4107 m (floor (/ s 60))
4108 s (- s (* 60 s)))
4109 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4110 t))))))
4112 (defun org-check-running-clock ()
4113 "Check if the current buffer contains the running clock.
4114 If yes, offer to stop it and to save the buffer with the changes."
4115 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4116 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4117 (buffer-name))))
4118 (org-clock-out)
4119 (when (y-or-n-p "Save changed buffer?")
4120 (save-buffer))))
4122 (defun org-clocktable-try-shift (dir n)
4123 "Check if this line starts a clock table, if yes, shift the time block."
4124 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4125 (org-clocktable-shift dir n)))
4127 ;; Autoload org-timer.el
4129 (eval-and-compile
4130 (org-autoload
4131 "org-timer"
4132 '(org-timer-start org-timer org-timer-item
4133 org-timer-change-times-in-region
4134 org-timer-set-timer
4135 org-timer-reset-timers
4136 org-timer-show-remaining-time)))
4138 ;; Autoload org-feed.el
4140 (eval-and-compile
4141 (org-autoload
4142 "org-feed"
4143 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4146 ;; Autoload org-indent.el
4148 ;; Define the variable already here, to make sure we have it.
4149 (defvar org-indent-mode nil
4150 "Non-nil if Org-Indent mode is enabled.
4151 Use the command `org-indent-mode' to change this variable.")
4153 (eval-and-compile
4154 (org-autoload
4155 "org-indent"
4156 '(org-indent-mode)))
4158 ;; Autoload org-mobile.el
4160 (eval-and-compile
4161 (org-autoload
4162 "org-mobile"
4163 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4165 ;; Autoload archiving code
4166 ;; The stuff that is needed for cycling and tags has to be defined here.
4168 (defgroup org-archive nil
4169 "Options concerning archiving in Org-mode."
4170 :tag "Org Archive"
4171 :group 'org-structure)
4173 (defcustom org-archive-location "%s_archive::"
4174 "The location where subtrees should be archived.
4176 The value of this variable is a string, consisting of two parts,
4177 separated by a double-colon. The first part is a filename and
4178 the second part is a headline.
4180 When the filename is omitted, archiving happens in the same file.
4181 %s in the filename will be replaced by the current file
4182 name (without the directory part). Archiving to a different file
4183 is useful to keep archived entries from contributing to the
4184 Org-mode Agenda.
4186 The archived entries will be filed as subtrees of the specified
4187 headline. When the headline is omitted, the subtrees are simply
4188 filed away at the end of the file, as top-level entries. Also in
4189 the heading you can use %s to represent the file name, this can be
4190 useful when using the same archive for a number of different files.
4192 Here are a few examples:
4193 \"%s_archive::\"
4194 If the current file is Projects.org, archive in file
4195 Projects.org_archive, as top-level trees. This is the default.
4197 \"::* Archived Tasks\"
4198 Archive in the current file, under the top-level headline
4199 \"* Archived Tasks\".
4201 \"~/org/archive.org::\"
4202 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4204 \"~/org/archive.org::* From %s\"
4205 Archive in file ~/org/archive.org (absolute path), under headlines
4206 \"From FILENAME\" where file name is the current file name.
4208 \"~/org/datetree.org::datetree/* Finished Tasks\"
4209 The \"datetree/\" string is special, signifying to archive
4210 items to the datetree. Items are placed in either the CLOSED
4211 date of the item, or the current date if there is no CLOSED date.
4212 The heading will be a subentry to the current date. There doesn't
4213 need to be a heading, but there always needs to be a slash after
4214 datetree. For example, to store archived items directly in the
4215 datetree, use \"~/org/datetree.org::datetree/\".
4217 \"basement::** Finished Tasks\"
4218 Archive in file ./basement (relative path), as level 3 trees
4219 below the level 2 heading \"** Finished Tasks\".
4221 You may set this option on a per-file basis by adding to the buffer a
4222 line like
4224 #+ARCHIVE: basement::** Finished Tasks
4226 You may also define it locally for a subtree by setting an ARCHIVE property
4227 in the entry. If such a property is found in an entry, or anywhere up
4228 the hierarchy, it will be used."
4229 :group 'org-archive
4230 :type 'string)
4232 (defcustom org-archive-tag "ARCHIVE"
4233 "The tag that marks a subtree as archived.
4234 An archived subtree does not open during visibility cycling, and does
4235 not contribute to the agenda listings.
4236 After changing this, font-lock must be restarted in the relevant buffers to
4237 get the proper fontification."
4238 :group 'org-archive
4239 :group 'org-keywords
4240 :type 'string)
4242 (defcustom org-agenda-skip-archived-trees t
4243 "Non-nil means the agenda will skip any items located in archived trees.
4244 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4245 variable is no longer recommended, you should leave it at the value t.
4246 Instead, use the key `v' to cycle the archives-mode in the agenda."
4247 :group 'org-archive
4248 :group 'org-agenda-skip
4249 :type 'boolean)
4251 (defcustom org-columns-skip-archived-trees t
4252 "Non-nil means ignore archived trees when creating column view."
4253 :group 'org-archive
4254 :group 'org-properties
4255 :type 'boolean)
4257 (defcustom org-cycle-open-archived-trees nil
4258 "Non-nil means `org-cycle' will open archived trees.
4259 An archived tree is a tree marked with the tag ARCHIVE.
4260 When nil, archived trees will stay folded. You can still open them with
4261 normal outline commands like `show-all', but not with the cycling commands."
4262 :group 'org-archive
4263 :group 'org-cycle
4264 :type 'boolean)
4266 (defcustom org-sparse-tree-open-archived-trees nil
4267 "Non-nil means sparse tree construction shows matches in archived trees.
4268 When nil, matches in these trees are highlighted, but the trees are kept in
4269 collapsed state."
4270 :group 'org-archive
4271 :group 'org-sparse-trees
4272 :type 'boolean)
4274 (defun org-cycle-hide-archived-subtrees (state)
4275 "Re-hide all archived subtrees after a visibility state change."
4276 (when (and (not org-cycle-open-archived-trees)
4277 (not (memq state '(overview folded))))
4278 (save-excursion
4279 (let* ((globalp (memq state '(contents all)))
4280 (beg (if globalp (point-min) (point)))
4281 (end (if globalp (point-max) (org-end-of-subtree t))))
4282 (org-hide-archived-subtrees beg end)
4283 (goto-char beg)
4284 (if (looking-at (concat ".*:" org-archive-tag ":"))
4285 (message "%s" (substitute-command-keys
4286 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4288 (defun org-force-cycle-archived ()
4289 "Cycle subtree even if it is archived."
4290 (interactive)
4291 (setq this-command 'org-cycle)
4292 (let ((org-cycle-open-archived-trees t))
4293 (call-interactively 'org-cycle)))
4295 (defun org-hide-archived-subtrees (beg end)
4296 "Re-hide all archived subtrees after a visibility state change."
4297 (save-excursion
4298 (let* ((re (concat ":" org-archive-tag ":")))
4299 (goto-char beg)
4300 (while (re-search-forward re end t)
4301 (when (org-at-heading-p)
4302 (org-flag-subtree t)
4303 (org-end-of-subtree t))))))
4305 (defun org-flag-subtree (flag)
4306 (save-excursion
4307 (org-back-to-heading t)
4308 (outline-end-of-heading)
4309 (outline-flag-region (point)
4310 (progn (org-end-of-subtree t) (point))
4311 flag)))
4313 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4315 (eval-and-compile
4316 (org-autoload "org-archive"
4317 '(org-add-archive-files org-archive-subtree
4318 org-archive-to-archive-sibling org-toggle-archive-tag
4319 org-archive-subtree-default
4320 org-archive-subtree-default-with-confirmation)))
4322 ;; Autoload Column View Code
4324 (declare-function org-columns-number-to-string "org-colview")
4325 (declare-function org-columns-get-format-and-top-level "org-colview")
4326 (declare-function org-columns-compute "org-colview")
4328 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4329 '(org-columns-number-to-string org-columns-get-format-and-top-level
4330 org-columns-compute org-agenda-columns org-columns-remove-overlays
4331 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4333 ;; Autoload ID code
4335 (declare-function org-id-store-link "org-id")
4336 (declare-function org-id-locations-load "org-id")
4337 (declare-function org-id-locations-save "org-id")
4338 (defvar org-id-track-globally)
4339 (org-autoload "org-id"
4340 '(org-id-get-create org-id-new org-id-copy org-id-get
4341 org-id-get-with-outline-path-completion
4342 org-id-get-with-outline-drilling org-id-store-link
4343 org-id-goto org-id-find org-id-store-link))
4345 ;; Autoload Plotting Code
4347 (org-autoload "org-plot"
4348 '(org-plot/gnuplot))
4350 ;;; Variables for pre-computed regular expressions, all buffer local
4352 (defvar org-drawer-regexp nil
4353 "Matches first line of a hidden block.")
4354 (make-variable-buffer-local 'org-drawer-regexp)
4355 (defvar org-todo-regexp nil
4356 "Matches any of the TODO state keywords.")
4357 (make-variable-buffer-local 'org-todo-regexp)
4358 (defvar org-not-done-regexp nil
4359 "Matches any of the TODO state keywords except the last one.")
4360 (make-variable-buffer-local 'org-not-done-regexp)
4361 (defvar org-not-done-heading-regexp nil
4362 "Matches a TODO headline that is not done.")
4363 (make-variable-buffer-local 'org-not-done-regexp)
4364 (defvar org-todo-line-regexp nil
4365 "Matches a headline and puts TODO state into group 2 if present.")
4366 (make-variable-buffer-local 'org-todo-line-regexp)
4367 (defvar org-complex-heading-regexp nil
4368 "Matches a headline and puts everything into groups:
4369 group 1: the stars
4370 group 2: The todo keyword, maybe
4371 group 3: Priority cookie
4372 group 4: True headline
4373 group 5: Tags")
4374 (make-variable-buffer-local 'org-complex-heading-regexp)
4375 (defvar org-complex-heading-regexp-format nil
4376 "Printf format to make regexp to match an exact headline.
4377 This regexp will match the headline of any node which has the
4378 exact headline text that is put into the format, but may have any
4379 TODO state, priority and tags.")
4380 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4381 (defvar org-todo-line-tags-regexp nil
4382 "Matches a headline and puts TODO state into group 2 if present.
4383 Also put tags into group 4 if tags are present.")
4384 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4385 (defvar org-ds-keyword-length 12
4386 "Maximum length of the Deadline and SCHEDULED keywords.")
4387 (make-variable-buffer-local 'org-ds-keyword-length)
4388 (defvar org-deadline-regexp nil
4389 "Matches the DEADLINE keyword.")
4390 (make-variable-buffer-local 'org-deadline-regexp)
4391 (defvar org-deadline-time-regexp nil
4392 "Matches the DEADLINE keyword together with a time stamp.")
4393 (make-variable-buffer-local 'org-deadline-time-regexp)
4394 (defvar org-deadline-line-regexp nil
4395 "Matches the DEADLINE keyword and the rest of the line.")
4396 (make-variable-buffer-local 'org-deadline-line-regexp)
4397 (defvar org-scheduled-regexp nil
4398 "Matches the SCHEDULED keyword.")
4399 (make-variable-buffer-local 'org-scheduled-regexp)
4400 (defvar org-scheduled-time-regexp nil
4401 "Matches the SCHEDULED keyword together with a time stamp.")
4402 (make-variable-buffer-local 'org-scheduled-time-regexp)
4403 (defvar org-closed-time-regexp nil
4404 "Matches the CLOSED keyword together with a time stamp.")
4405 (make-variable-buffer-local 'org-closed-time-regexp)
4407 (defvar org-keyword-time-regexp nil
4408 "Matches any of the 4 keywords, together with the time stamp.")
4409 (make-variable-buffer-local 'org-keyword-time-regexp)
4410 (defvar org-keyword-time-not-clock-regexp nil
4411 "Matches any of the 3 keywords, together with the time stamp.")
4412 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4413 (defvar org-maybe-keyword-time-regexp nil
4414 "Matches a timestamp, possibly preceded by a keyword.")
4415 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4416 (defvar org-planning-or-clock-line-re nil
4417 "Matches a line with planning or clock info.")
4418 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4419 (defvar org-all-time-keywords nil
4420 "List of time keywords.")
4421 (make-variable-buffer-local 'org-all-time-keywords)
4423 (defconst org-plain-time-of-day-regexp
4424 (concat
4425 "\\(\\<[012]?[0-9]"
4426 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4427 "\\(--?"
4428 "\\(\\<[012]?[0-9]"
4429 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4430 "\\)?")
4431 "Regular expression to match a plain time or time range.
4432 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4433 groups carry important information:
4434 0 the full match
4435 1 the first time, range or not
4436 8 the second time, if it is a range.")
4438 (defconst org-plain-time-extension-regexp
4439 (concat
4440 "\\(\\<[012]?[0-9]"
4441 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4442 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4443 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4444 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4445 groups carry important information:
4446 0 the full match
4447 7 hours of duration
4448 9 minutes of duration")
4450 (defconst org-stamp-time-of-day-regexp
4451 (concat
4452 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4453 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4454 "\\(--?"
4455 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4456 "Regular expression to match a timestamp time or time range.
4457 After a match, the following groups carry important information:
4458 0 the full match
4459 1 date plus weekday, for back referencing to make sure both times are on the same day
4460 2 the first time, range or not
4461 4 the second time, if it is a range.")
4463 (defconst org-startup-options
4464 '(("fold" org-startup-folded t)
4465 ("overview" org-startup-folded t)
4466 ("nofold" org-startup-folded nil)
4467 ("showall" org-startup-folded nil)
4468 ("showeverything" org-startup-folded showeverything)
4469 ("content" org-startup-folded content)
4470 ("indent" org-startup-indented t)
4471 ("noindent" org-startup-indented nil)
4472 ("hidestars" org-hide-leading-stars t)
4473 ("showstars" org-hide-leading-stars nil)
4474 ("odd" org-odd-levels-only t)
4475 ("oddeven" org-odd-levels-only nil)
4476 ("align" org-startup-align-all-tables t)
4477 ("noalign" org-startup-align-all-tables nil)
4478 ("inlineimages" org-startup-with-inline-images t)
4479 ("noinlineimages" org-startup-with-inline-images nil)
4480 ("customtime" org-display-custom-times t)
4481 ("logdone" org-log-done time)
4482 ("lognotedone" org-log-done note)
4483 ("nologdone" org-log-done nil)
4484 ("lognoteclock-out" org-log-note-clock-out t)
4485 ("nolognoteclock-out" org-log-note-clock-out nil)
4486 ("logrepeat" org-log-repeat state)
4487 ("lognoterepeat" org-log-repeat note)
4488 ("nologrepeat" org-log-repeat nil)
4489 ("logreschedule" org-log-reschedule time)
4490 ("lognotereschedule" org-log-reschedule note)
4491 ("nologreschedule" org-log-reschedule nil)
4492 ("logredeadline" org-log-redeadline time)
4493 ("lognoteredeadline" org-log-redeadline note)
4494 ("nologredeadline" org-log-redeadline nil)
4495 ("logrefile" org-log-refile time)
4496 ("lognoterefile" org-log-refile note)
4497 ("nologrefile" org-log-refile nil)
4498 ("fninline" org-footnote-define-inline t)
4499 ("nofninline" org-footnote-define-inline nil)
4500 ("fnlocal" org-footnote-section nil)
4501 ("fnauto" org-footnote-auto-label t)
4502 ("fnprompt" org-footnote-auto-label nil)
4503 ("fnconfirm" org-footnote-auto-label confirm)
4504 ("fnplain" org-footnote-auto-label plain)
4505 ("fnadjust" org-footnote-auto-adjust t)
4506 ("nofnadjust" org-footnote-auto-adjust nil)
4507 ("constcgs" constants-unit-system cgs)
4508 ("constSI" constants-unit-system SI)
4509 ("noptag" org-tag-persistent-alist nil)
4510 ("hideblocks" org-hide-block-startup t)
4511 ("nohideblocks" org-hide-block-startup nil)
4512 ("beamer" org-startup-with-beamer-mode t)
4513 ("entitiespretty" org-pretty-entities t)
4514 ("entitiesplain" org-pretty-entities nil))
4515 "Variable associated with STARTUP options for org-mode.
4516 Each element is a list of three items: the startup options (as written
4517 in the #+STARTUP line), the corresponding variable, and the value to set
4518 this variable to if the option is found. An optional forth element PUSH
4519 means to push this value onto the list in the variable.")
4521 (defun org-update-property-plist (key val props)
4522 "Update PROPS with KEY and VAL."
4523 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4524 (key (if appending (substring key 0 (- (length key) 1)) key))
4525 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4526 (previous (cdr (assoc key props))))
4527 (if appending
4528 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4529 (cons (cons key val) remainder))))
4531 (defconst org-block-regexp
4532 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4533 "Regular expression for hiding blocks.")
4534 (defconst org-heading-keyword-regexp-format
4535 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4536 "Printf format for a regexp matching an headline with some keyword.
4537 This regexp will match the headline of any node which has the
4538 exact keyword that is put into the format. The keyword isn't in
4539 any group by default, but the stars and the body are.")
4540 (defconst org-heading-keyword-maybe-regexp-format
4541 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4542 "Printf format for a regexp matching an headline, possibly with some keyword.
4543 This regexp can match any headline with the specified keyword, or
4544 without a keyword. The keyword isn't in any group by default,
4545 but the stars and the body are.")
4547 (defun org-set-regexps-and-options ()
4548 "Precompute regular expressions for current buffer."
4549 (when (derived-mode-p 'org-mode)
4550 (org-set-local 'org-todo-kwd-alist nil)
4551 (org-set-local 'org-todo-key-alist nil)
4552 (org-set-local 'org-todo-key-trigger nil)
4553 (org-set-local 'org-todo-keywords-1 nil)
4554 (org-set-local 'org-done-keywords nil)
4555 (org-set-local 'org-todo-heads nil)
4556 (org-set-local 'org-todo-sets nil)
4557 (org-set-local 'org-todo-log-states nil)
4558 (org-set-local 'org-file-properties nil)
4559 (org-set-local 'org-file-tags nil)
4560 (let ((re (org-make-options-regexp
4561 '("CATEGORY" "TODO" "COLUMNS"
4562 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4563 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4564 "OPTIONS")
4565 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4566 (splitre "[ \t]+")
4567 (scripts org-use-sub-superscripts)
4568 kwds kws0 kwsa key log value cat arch tags const links hw dws
4569 tail sep kws1 prio props ftags drawers beamer-p
4570 ext-setup-or-nil setup-contents (start 0))
4571 (save-excursion
4572 (save-restriction
4573 (widen)
4574 (goto-char (point-min))
4575 (while (or (and ext-setup-or-nil
4576 (string-match re ext-setup-or-nil start)
4577 (setq start (match-end 0)))
4578 (and (setq ext-setup-or-nil nil start 0)
4579 (re-search-forward re nil t)))
4580 (setq key (upcase (match-string 1 ext-setup-or-nil))
4581 value (org-match-string-no-properties 2 ext-setup-or-nil))
4582 (if (stringp value) (setq value (org-trim value)))
4583 (cond
4584 ((equal key "CATEGORY")
4585 (setq cat value))
4586 ((member key '("SEQ_TODO" "TODO"))
4587 (push (cons 'sequence (org-split-string value splitre)) kwds))
4588 ((equal key "TYP_TODO")
4589 (push (cons 'type (org-split-string value splitre)) kwds))
4590 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4591 ;; general TODO-like setup
4592 (push (cons (intern (downcase (match-string 1 key)))
4593 (org-split-string value splitre)) kwds))
4594 ((equal key "TAGS")
4595 (setq tags (append tags (if tags '("\\n") nil)
4596 (org-split-string value splitre))))
4597 ((equal key "COLUMNS")
4598 (org-set-local 'org-columns-default-format value))
4599 ((equal key "LINK")
4600 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4601 (push (cons (match-string 1 value)
4602 (org-trim (match-string 2 value)))
4603 links)))
4604 ((equal key "PRIORITIES")
4605 (setq prio (org-split-string value " +")))
4606 ((equal key "PROPERTY")
4607 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4608 (setq props (org-update-property-plist (match-string 1 value)
4609 (match-string 2 value)
4610 props))))
4611 ((equal key "FILETAGS")
4612 (when (string-match "\\S-" value)
4613 (setq ftags
4614 (append
4615 ftags
4616 (apply 'append
4617 (mapcar (lambda (x) (org-split-string x ":"))
4618 (org-split-string value)))))))
4619 ((equal key "DRAWERS")
4620 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4621 ((equal key "CONSTANTS")
4622 (setq const (append const (org-split-string value splitre))))
4623 ((equal key "STARTUP")
4624 (let ((opts (org-split-string value splitre))
4625 l var val)
4626 (while (setq l (pop opts))
4627 (when (setq l (assoc l org-startup-options))
4628 (setq var (nth 1 l) val (nth 2 l))
4629 (if (not (nth 3 l))
4630 (set (make-local-variable var) val)
4631 (if (not (listp (symbol-value var)))
4632 (set (make-local-variable var) nil))
4633 (set (make-local-variable var) (symbol-value var))
4634 (add-to-list var val))))))
4635 ((equal key "ARCHIVE")
4636 (setq arch value)
4637 (remove-text-properties 0 (length arch)
4638 '(face t fontified t) arch))
4639 ((equal key "LATEX_CLASS")
4640 (setq beamer-p (equal value "beamer")))
4641 ((equal key "OPTIONS")
4642 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4643 (setq scripts (read (match-string 2 value)))))
4644 ((equal key "SETUPFILE")
4645 (setq setup-contents (org-file-contents
4646 (expand-file-name
4647 (org-remove-double-quotes value))
4648 'noerror))
4649 (if (not ext-setup-or-nil)
4650 (setq ext-setup-or-nil setup-contents start 0)
4651 (setq ext-setup-or-nil
4652 (concat (substring ext-setup-or-nil 0 start)
4653 "\n" setup-contents "\n"
4654 (substring ext-setup-or-nil start)))))))
4655 ;; search for property blocks
4656 (goto-char (point-min))
4657 (while (re-search-forward org-block-regexp nil t)
4658 (when (equal "PROPERTY" (upcase (match-string 1)))
4659 (setq value (replace-regexp-in-string
4660 "[\n\r]" " " (match-string 4)))
4661 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4662 (setq props (org-update-property-plist (match-string 1 value)
4663 (match-string 2 value)
4664 props)))))))
4665 (org-set-local 'org-use-sub-superscripts scripts)
4666 (when cat
4667 (org-set-local 'org-category (intern cat))
4668 (push (cons "CATEGORY" cat) props))
4669 (when prio
4670 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4671 (setq prio (mapcar 'string-to-char prio))
4672 (org-set-local 'org-highest-priority (nth 0 prio))
4673 (org-set-local 'org-lowest-priority (nth 1 prio))
4674 (org-set-local 'org-default-priority (nth 2 prio)))
4675 (and props (org-set-local 'org-file-properties (nreverse props)))
4676 (and ftags (org-set-local 'org-file-tags
4677 (mapcar 'org-add-prop-inherited ftags)))
4678 (and drawers (org-set-local 'org-drawers drawers))
4679 (and arch (org-set-local 'org-archive-location arch))
4680 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4681 ;; Process the TODO keywords
4682 (unless kwds
4683 ;; Use the global values as if they had been given locally.
4684 (setq kwds (default-value 'org-todo-keywords))
4685 (if (stringp (car kwds))
4686 (setq kwds (list (cons org-todo-interpretation
4687 (default-value 'org-todo-keywords)))))
4688 (setq kwds (reverse kwds)))
4689 (setq kwds (nreverse kwds))
4690 (let (inter kws kw)
4691 (while (setq kws (pop kwds))
4692 (let ((kws (or
4693 (run-hook-with-args-until-success
4694 'org-todo-setup-filter-hook kws)
4695 kws)))
4696 (setq inter (pop kws) sep (member "|" kws)
4697 kws0 (delete "|" (copy-sequence kws))
4698 kwsa nil
4699 kws1 (mapcar
4700 (lambda (x)
4701 ;; 1 2
4702 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4703 (progn
4704 (setq kw (match-string 1 x)
4705 key (and (match-end 2) (match-string 2 x))
4706 log (org-extract-log-state-settings x))
4707 (push (cons kw (and key (string-to-char key))) kwsa)
4708 (and log (push log org-todo-log-states))
4710 (error "Invalid TODO keyword %s" x)))
4711 kws0)
4712 kwsa (if kwsa (append '((:startgroup))
4713 (nreverse kwsa)
4714 '((:endgroup))))
4715 hw (car kws1)
4716 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4717 tail (list inter hw (car dws) (org-last dws))))
4718 (add-to-list 'org-todo-heads hw 'append)
4719 (push kws1 org-todo-sets)
4720 (setq org-done-keywords (append org-done-keywords dws nil))
4721 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4722 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4723 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4724 (setq org-todo-sets (nreverse org-todo-sets)
4725 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4726 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4727 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4728 ;; Process the constants
4729 (when const
4730 (let (e cst)
4731 (while (setq e (pop const))
4732 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4733 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4734 (setq org-table-formula-constants-local cst)))
4736 ;; Process the tags.
4737 (when tags
4738 (let (e tgs)
4739 (while (setq e (pop tags))
4740 (cond
4741 ((equal e "{") (push '(:startgroup) tgs))
4742 ((equal e "}") (push '(:endgroup) tgs))
4743 ((equal e "\\n") (push '(:newline) tgs))
4744 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4745 (push (cons (match-string 1 e)
4746 (string-to-char (match-string 2 e)))
4747 tgs))
4748 (t (push (list e) tgs))))
4749 (org-set-local 'org-tag-alist nil)
4750 (while (setq e (pop tgs))
4751 (or (and (stringp (car e))
4752 (assoc (car e) org-tag-alist))
4753 (push e org-tag-alist)))))
4755 ;; Compute the regular expressions and other local variables.
4756 ;; Using `org-outline-regexp-bol' would complicate them much,
4757 ;; because of the fixed white space at the end of that string.
4758 (if (not org-done-keywords)
4759 (setq org-done-keywords (and org-todo-keywords-1
4760 (list (org-last org-todo-keywords-1)))))
4761 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4762 (length org-scheduled-string)
4763 (length org-clock-string)
4764 (length org-closed-string)))
4765 org-drawer-regexp
4766 (concat "^[ \t]*:\\("
4767 (mapconcat 'regexp-quote org-drawers "\\|")
4768 "\\):[ \t]*$")
4769 org-not-done-keywords
4770 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4771 org-todo-regexp
4772 (concat "\\("
4773 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4774 "\\)")
4775 org-not-done-regexp
4776 (concat "\\("
4777 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4778 "\\)")
4779 org-not-done-heading-regexp
4780 (format org-heading-keyword-regexp-format org-not-done-regexp)
4781 org-todo-line-regexp
4782 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4783 org-complex-heading-regexp
4784 (concat "^\\(\\*+\\)"
4785 "\\(?: +" org-todo-regexp "\\)?"
4786 "\\(?: +\\(\\[#.\\]\\)\\)?"
4787 "\\(?: +\\(.*?\\)\\)?"
4788 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4789 "[ \t]*$")
4790 org-complex-heading-regexp-format
4791 (concat "^\\(\\*+\\)"
4792 "\\(?: +" org-todo-regexp "\\)?"
4793 "\\(?: +\\(\\[#.\\]\\)\\)?"
4794 "\\(?: +"
4795 ;; Stats cookies can be stuck to body.
4796 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4797 "\\(%s\\)"
4798 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4799 "\\)"
4800 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4801 "[ \t]*$")
4802 org-todo-line-tags-regexp
4803 (concat "^\\(\\*+\\)"
4804 "\\(?: +" org-todo-regexp "\\)?"
4805 "\\(?: +\\(.*?\\)\\)?"
4806 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4807 "[ \t]*$")
4808 org-deadline-regexp (concat "\\<" org-deadline-string)
4809 org-deadline-time-regexp
4810 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4811 org-deadline-line-regexp
4812 (concat "\\<\\(" org-deadline-string "\\).*")
4813 org-scheduled-regexp
4814 (concat "\\<" org-scheduled-string)
4815 org-scheduled-time-regexp
4816 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4817 org-closed-time-regexp
4818 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4819 org-keyword-time-regexp
4820 (concat "\\<\\(" org-scheduled-string
4821 "\\|" org-deadline-string
4822 "\\|" org-closed-string
4823 "\\|" org-clock-string "\\)"
4824 " *[[<]\\([^]>]+\\)[]>]")
4825 org-keyword-time-not-clock-regexp
4826 (concat "\\<\\(" org-scheduled-string
4827 "\\|" org-deadline-string
4828 "\\|" org-closed-string
4829 "\\)"
4830 " *[[<]\\([^]>]+\\)[]>]")
4831 org-maybe-keyword-time-regexp
4832 (concat "\\(\\<\\(" org-scheduled-string
4833 "\\|" org-deadline-string
4834 "\\|" org-closed-string
4835 "\\|" org-clock-string "\\)\\)?"
4836 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4837 org-planning-or-clock-line-re
4838 (concat "^[ \t]*\\("
4839 org-scheduled-string "\\|"
4840 org-deadline-string "\\|"
4841 org-closed-string "\\|"
4842 org-clock-string "\\)")
4843 org-all-time-keywords
4844 (mapcar (lambda (w) (substring w 0 -1))
4845 (list org-scheduled-string org-deadline-string
4846 org-clock-string org-closed-string))
4848 (org-compute-latex-and-specials-regexp)
4849 (org-set-font-lock-defaults))))
4851 (defun org-file-contents (file &optional noerror)
4852 "Return the contents of FILE, as a string."
4853 (if (or (not file)
4854 (not (file-readable-p file)))
4855 (if noerror
4856 (progn
4857 (message "Cannot read file \"%s\"" file)
4858 (ding) (sit-for 2)
4860 (error "Cannot read file \"%s\"" file))
4861 (with-temp-buffer
4862 (insert-file-contents file)
4863 (buffer-string))))
4865 (defun org-extract-log-state-settings (x)
4866 "Extract the log state setting from a TODO keyword string.
4867 This will extract info from a string like \"WAIT(w@/!)\"."
4868 (let (kw key log1 log2)
4869 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4870 (setq kw (match-string 1 x)
4871 key (and (match-end 2) (match-string 2 x))
4872 log1 (and (match-end 3) (match-string 3 x))
4873 log2 (and (match-end 4) (match-string 4 x)))
4874 (and (or log1 log2)
4875 (list kw
4876 (and log1 (if (equal log1 "!") 'time 'note))
4877 (and log2 (if (equal log2 "!") 'time 'note)))))))
4879 (defun org-remove-keyword-keys (list)
4880 "Remove a pair of parenthesis at the end of each string in LIST."
4881 (mapcar (lambda (x)
4882 (if (string-match "(.*)$" x)
4883 (substring x 0 (match-beginning 0))
4885 list))
4887 (defun org-assign-fast-keys (alist)
4888 "Assign fast keys to a keyword-key alist.
4889 Respect keys that are already there."
4890 (let (new e (alt ?0))
4891 (while (setq e (pop alist))
4892 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4893 (cdr e)) ;; Key already assigned.
4894 (push e new)
4895 (let ((clist (string-to-list (downcase (car e))))
4896 (used (append new alist)))
4897 (when (= (car clist) ?@)
4898 (pop clist))
4899 (while (and clist (rassoc (car clist) used))
4900 (pop clist))
4901 (unless clist
4902 (while (rassoc alt used)
4903 (incf alt)))
4904 (push (cons (car e) (or (car clist) alt)) new))))
4905 (nreverse new)))
4907 ;;; Some variables used in various places
4909 (defvar org-window-configuration nil
4910 "Used in various places to store a window configuration.")
4911 (defvar org-selected-window nil
4912 "Used in various places to store a window configuration.")
4913 (defvar org-finish-function nil
4914 "Function to be called when `C-c C-c' is used.
4915 This is for getting out of special buffers like remember.")
4918 ;; FIXME: Occasionally check by commenting these, to make sure
4919 ;; no other functions uses these, forgetting to let-bind them.
4920 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4921 (defvar org-last-state)
4922 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4924 ;; Defined somewhere in this file, but used before definition.
4925 (defvar org-entities) ;; defined in org-entities.el
4926 (defvar org-struct-menu)
4927 (defvar org-org-menu)
4928 (defvar org-tbl-menu)
4930 ;;;; Define the Org-mode
4932 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4933 (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"))
4936 ;; We use a before-change function to check if a table might need
4937 ;; an update.
4938 (defvar org-table-may-need-update t
4939 "Indicates that a table might need an update.
4940 This variable is set by `org-before-change-function'.
4941 `org-table-align' sets it back to nil.")
4942 (defun org-before-change-function (beg end)
4943 "Every change indicates that a table might need an update."
4944 (setq org-table-may-need-update t))
4945 (defvar org-mode-map)
4946 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4947 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4948 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4949 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4950 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4951 (defvar org-table-buffer-is-an nil)
4953 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4954 ;; some places -- e.g. see the macro org-with-limited-levels.
4956 ;; In Org buffers, the value of `outline-regexp' is that of
4957 ;; `org-outline-regexp'. The only function still directly relying on
4958 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4959 ;; job when `orgstruct-mode' is active.
4960 (defvar org-outline-regexp "\\*+ "
4961 "Regexp to match Org headlines.")
4962 (defconst org-outline-regexp-bol "^\\*+ "
4963 "Regexp to match Org headlines.
4964 This is similar to `org-outline-regexp' but additionally makes
4965 sure that we are at the beginning of the line.")
4967 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4968 "Matches an headline, putting stars and text into groups.
4969 Stars are put in group 1 and the trimmed body in group 2.")
4971 (defvar bidi-paragraph-direction)
4972 (defvar buffer-face-mode-face)
4974 ;;;###autoload
4975 (define-derived-mode org-mode outline-mode "Org"
4976 "Outline-based notes management and organizer, alias
4977 \"Carsten's outline-mode for keeping track of everything.\"
4979 Org-mode develops organizational tasks around a NOTES file which
4980 contains information about projects as plain text. Org-mode is
4981 implemented on top of outline-mode, which is ideal to keep the content
4982 of large files well structured. It supports ToDo items, deadlines and
4983 time stamps, which magically appear in the diary listing of the Emacs
4984 calendar. Tables are easily created with a built-in table editor.
4985 Plain text URL-like links connect to websites, emails (VM), Usenet
4986 messages (Gnus), BBDB entries, and any files related to the project.
4987 For printing and sharing of notes, an Org-mode file (or a part of it)
4988 can be exported as a structured ASCII or HTML file.
4990 The following commands are available:
4992 \\{org-mode-map}"
4994 ;; Get rid of Outline menus, they are not needed
4995 ;; Need to do this here because define-derived-mode sets up
4996 ;; the keymap so late. Still, it is a waste to call this each time
4997 ;; we switch another buffer into org-mode.
4998 (if (featurep 'xemacs)
4999 (when (boundp 'outline-mode-menu-heading)
5000 ;; Assume this is Greg's port, it uses easymenu
5001 (easy-menu-remove outline-mode-menu-heading)
5002 (easy-menu-remove outline-mode-menu-show)
5003 (easy-menu-remove outline-mode-menu-hide))
5004 (define-key org-mode-map [menu-bar headings] 'undefined)
5005 (define-key org-mode-map [menu-bar hide] 'undefined)
5006 (define-key org-mode-map [menu-bar show] 'undefined))
5008 (org-load-modules-maybe)
5009 (easy-menu-add org-org-menu)
5010 (easy-menu-add org-tbl-menu)
5011 (org-install-agenda-files-menu)
5012 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5013 (add-to-invisibility-spec '(org-cwidth))
5014 (add-to-invisibility-spec '(org-hide-block . t))
5015 (when (featurep 'xemacs)
5016 (org-set-local 'line-move-ignore-invisible t))
5017 (org-set-local 'outline-regexp org-outline-regexp)
5018 (org-set-local 'outline-level 'org-outline-level)
5019 (setq bidi-paragraph-direction 'left-to-right)
5020 (when (and org-ellipsis
5021 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5022 (fboundp 'make-glyph-code))
5023 (unless org-display-table
5024 (setq org-display-table (make-display-table)))
5025 (set-display-table-slot
5026 org-display-table 4
5027 (vconcat (mapcar
5028 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5029 org-ellipsis)))
5030 (if (stringp org-ellipsis) org-ellipsis "..."))))
5031 (setq buffer-display-table org-display-table))
5032 (org-set-regexps-and-options)
5033 (when (and org-tag-faces (not org-tags-special-faces-re))
5034 ;; tag faces set outside customize.... force initialization.
5035 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5036 ;; Calc embedded
5037 (org-set-local 'calc-embedded-open-mode "# ")
5038 (modify-syntax-entry ?@ "w")
5039 (if org-startup-truncated (setq truncate-lines t))
5040 (org-set-local 'font-lock-unfontify-region-function
5041 'org-unfontify-region)
5042 ;; Activate before-change-function
5043 (org-set-local 'org-table-may-need-update t)
5044 (org-add-hook 'before-change-functions 'org-before-change-function nil
5045 'local)
5046 ;; Check for running clock before killing a buffer
5047 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5048 ;; Paragraphs and auto-filling
5049 (org-set-autofill-regexps)
5050 (org-set-local 'indent-line-function 'org-indent-line)
5051 (org-set-local 'indent-region-function 'org-indent-region)
5052 (org-update-radio-target-regexp)
5053 ;; Beginning/end of defun
5054 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5055 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5056 ;; Next error for sparse trees
5057 (org-set-local 'next-error-function 'org-occur-next-match)
5058 ;; Make sure dependence stuff works reliably, even for users who set it
5059 ;; too late :-(
5060 (if org-enforce-todo-dependencies
5061 (add-hook 'org-blocker-hook
5062 'org-block-todo-from-children-or-siblings-or-parent)
5063 (remove-hook 'org-blocker-hook
5064 'org-block-todo-from-children-or-siblings-or-parent))
5065 (if org-enforce-todo-checkbox-dependencies
5066 (add-hook 'org-blocker-hook
5067 'org-block-todo-from-checkboxes)
5068 (remove-hook 'org-blocker-hook
5069 'org-block-todo-from-checkboxes))
5071 ;; Comment characters
5072 (org-set-local 'comment-start "#")
5073 (org-set-local 'comment-padding " ")
5075 ;; Align options lines
5076 (org-set-local
5077 'align-mode-rules-list
5078 '((org-in-buffer-settings
5079 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5080 (modes . '(org-mode)))))
5082 ;; Imenu
5083 (org-set-local 'imenu-create-index-function
5084 'org-imenu-get-tree)
5086 ;; Make isearch reveal context
5087 (if (or (featurep 'xemacs)
5088 (not (boundp 'outline-isearch-open-invisible-function)))
5089 ;; Emacs 21 and XEmacs make use of the hook
5090 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5091 ;; Emacs 22 deals with this through a special variable
5092 (org-set-local 'outline-isearch-open-invisible-function
5093 (lambda (&rest ignore) (org-show-context 'isearch))))
5095 ;; Turn on org-beamer-mode?
5096 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5098 ;; Setup the pcomplete hooks
5099 (set (make-local-variable 'pcomplete-command-completion-function)
5100 'org-pcomplete-initial)
5101 (set (make-local-variable 'pcomplete-command-name-function)
5102 'org-command-at-point)
5103 (set (make-local-variable 'pcomplete-default-completion-function)
5104 'ignore)
5105 (set (make-local-variable 'pcomplete-parse-arguments-function)
5106 'org-parse-arguments)
5107 (set (make-local-variable 'pcomplete-termination-string) "")
5108 (when (>= emacs-major-version 23)
5109 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5111 ;; If empty file that did not turn on org-mode automatically, make it to.
5112 (if (and org-insert-mode-line-in-empty-file
5113 (org-called-interactively-p 'any)
5114 (= (point-min) (point-max)))
5115 (insert "# -*- mode: org -*-\n\n"))
5116 (unless org-inhibit-startup
5117 (when org-startup-align-all-tables
5118 (let ((bmp (buffer-modified-p)))
5119 (org-table-map-tables 'org-table-align 'quietly)
5120 (set-buffer-modified-p bmp)))
5121 (when org-startup-with-inline-images
5122 (org-display-inline-images))
5123 (when org-startup-indented
5124 (require 'org-indent)
5125 (org-indent-mode 1))
5126 (unless org-inhibit-startup-visibility-stuff
5127 (org-set-startup-visibility))))
5129 (when (fboundp 'abbrev-table-put)
5130 (abbrev-table-put org-mode-abbrev-table
5131 :parents (list text-mode-abbrev-table)))
5133 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5135 (defun org-current-time ()
5136 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5137 (if (> (car org-time-stamp-rounding-minutes) 1)
5138 (let ((r (car org-time-stamp-rounding-minutes))
5139 (time (decode-time)))
5140 (apply 'encode-time
5141 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5142 (nthcdr 2 time))))
5143 (current-time)))
5145 (defun org-today ()
5146 "Return today date, considering `org-extend-today-until'."
5147 (time-to-days
5148 (time-subtract (current-time)
5149 (list 0 (* 3600 org-extend-today-until) 0))))
5151 ;;;; Font-Lock stuff, including the activators
5153 (defvar org-mouse-map (make-sparse-keymap))
5154 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5155 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5156 (when org-mouse-1-follows-link
5157 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5158 (when org-tab-follows-link
5159 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5160 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5162 (require 'font-lock)
5164 (defconst org-non-link-chars "]\t\n\r<>")
5165 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5166 "shell" "elisp" "doi" "message"))
5167 (defvar org-link-types-re nil
5168 "Matches a link that has a url-like prefix like \"http:\"")
5169 (defvar org-link-re-with-space nil
5170 "Matches a link with spaces, optional angular brackets around it.")
5171 (defvar org-link-re-with-space2 nil
5172 "Matches a link with spaces, optional angular brackets around it.")
5173 (defvar org-link-re-with-space3 nil
5174 "Matches a link with spaces, only for internal part in bracket links.")
5175 (defvar org-angle-link-re nil
5176 "Matches link with angular brackets, spaces are allowed.")
5177 (defvar org-plain-link-re nil
5178 "Matches plain link, without spaces.")
5179 (defvar org-bracket-link-regexp nil
5180 "Matches a link in double brackets.")
5181 (defvar org-bracket-link-analytic-regexp nil
5182 "Regular expression used to analyze links.
5183 Here is what the match groups contain after a match:
5184 1: http:
5185 2: http
5186 3: path
5187 4: [desc]
5188 5: desc")
5189 (defvar org-bracket-link-analytic-regexp++ nil
5190 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5191 (defvar org-any-link-re nil
5192 "Regular expression matching any link.")
5194 (defcustom org-match-sexp-depth 3
5195 "Number of stacked braces for sub/superscript matching.
5196 This has to be set before loading org.el to be effective."
5197 :group 'org-export-translation ; ??????????????????????????/
5198 :type 'integer)
5200 (defun org-create-multibrace-regexp (left right n)
5201 "Create a regular expression which will match a balanced sexp.
5202 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5203 as single character strings.
5204 The regexp returned will match the entire expression including the
5205 delimiters. It will also define a single group which contains the
5206 match except for the outermost delimiters. The maximum depth of
5207 stacked delimiters is N. Escaping delimiters is not possible."
5208 (let* ((nothing (concat "[^" left right "]*?"))
5209 (or "\\|")
5210 (re nothing)
5211 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5212 (while (> n 1)
5213 (setq n (1- n)
5214 re (concat re or next)
5215 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5216 (concat left "\\(" re "\\)" right)))
5218 (defvar org-match-substring-regexp
5219 (concat
5220 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5221 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5222 "\\|"
5223 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5224 "\\|"
5225 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5226 "The regular expression matching a sub- or superscript.")
5228 (defvar org-match-substring-with-braces-regexp
5229 (concat
5230 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5231 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5232 "\\)")
5233 "The regular expression matching a sub- or superscript, forcing braces.")
5235 (defun org-make-link-regexps ()
5236 "Update the link regular expressions.
5237 This should be called after the variable `org-link-types' has changed."
5238 (setq org-link-types-re
5239 (concat
5240 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5241 org-link-re-with-space
5242 (concat
5243 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5244 "\\([^" org-non-link-chars " ]"
5245 "[^" org-non-link-chars "]*"
5246 "[^" org-non-link-chars " ]\\)>?")
5247 org-link-re-with-space2
5248 (concat
5249 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5250 "\\([^" org-non-link-chars " ]"
5251 "[^\t\n\r]*"
5252 "[^" org-non-link-chars " ]\\)>?")
5253 org-link-re-with-space3
5254 (concat
5255 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5256 "\\([^" org-non-link-chars " ]"
5257 "[^\t\n\r]*\\)")
5258 org-angle-link-re
5259 (concat
5260 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5261 "\\([^" org-non-link-chars " ]"
5262 "[^" org-non-link-chars "]*"
5263 "\\)>")
5264 org-plain-link-re
5265 (concat
5266 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5267 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5268 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5269 org-bracket-link-regexp
5270 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5271 org-bracket-link-analytic-regexp
5272 (concat
5273 "\\[\\["
5274 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5275 "\\([^]]+\\)"
5276 "\\]"
5277 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5278 "\\]")
5279 org-bracket-link-analytic-regexp++
5280 (concat
5281 "\\[\\["
5282 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5283 "\\([^]]+\\)"
5284 "\\]"
5285 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5286 "\\]")
5287 org-any-link-re
5288 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5289 org-angle-link-re "\\)\\|\\("
5290 org-plain-link-re "\\)")))
5292 (org-make-link-regexps)
5294 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5295 "Regular expression for fast time stamp matching.")
5296 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5297 "Regular expression for fast time stamp matching.")
5298 (defconst org-ts-regexp0
5299 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5300 "Regular expression matching time strings for analysis.
5301 This one does not require the space after the date, so it can be used
5302 on a string that terminates immediately after the date.")
5303 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5304 "Regular expression matching time strings for analysis.")
5305 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5306 "Regular expression matching time stamps, with groups.")
5307 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5308 "Regular expression matching time stamps (also [..]), with groups.")
5309 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5310 "Regular expression matching a time stamp range.")
5311 (defconst org-tr-regexp-both
5312 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5313 "Regular expression matching a time stamp range.")
5314 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5315 org-ts-regexp "\\)?")
5316 "Regular expression matching a time stamp or time stamp range.")
5317 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5318 org-ts-regexp-both "\\)?")
5319 "Regular expression matching a time stamp or time stamp range.
5320 The time stamps may be either active or inactive.")
5322 (defvar org-emph-face nil)
5324 (defun org-do-emphasis-faces (limit)
5325 "Run through the buffer and add overlays to emphasized strings."
5326 (let (rtn a)
5327 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5328 (if (not (= (char-after (match-beginning 3))
5329 (char-after (match-beginning 4))))
5330 (progn
5331 (setq rtn t)
5332 (setq a (assoc (match-string 3) org-emphasis-alist))
5333 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5334 'face
5335 (nth 1 a))
5336 (and (nth 4 a)
5337 (org-remove-flyspell-overlays-in
5338 (match-beginning 0) (match-end 0)))
5339 (add-text-properties (match-beginning 2) (match-end 2)
5340 '(font-lock-multiline t org-emphasis t))
5341 (when org-hide-emphasis-markers
5342 (add-text-properties (match-end 4) (match-beginning 5)
5343 '(invisible org-link))
5344 (add-text-properties (match-beginning 3) (match-end 3)
5345 '(invisible org-link)))))
5346 (backward-char 1))
5347 rtn))
5349 (defun org-emphasize (&optional char)
5350 "Insert or change an emphasis, i.e. a font like bold or italic.
5351 If there is an active region, change that region to a new emphasis.
5352 If there is no region, just insert the marker characters and position
5353 the cursor between them.
5354 CHAR should be either the marker character, or the first character of the
5355 HTML tag associated with that emphasis. If CHAR is a space, the means
5356 to remove the emphasis of the selected region.
5357 If char is not given (for example in an interactive call) it
5358 will be prompted for."
5359 (interactive)
5360 (let ((eal org-emphasis-alist) e det
5361 (erc org-emphasis-regexp-components)
5362 (prompt "")
5363 (string "") beg end move tag c s)
5364 (if (org-region-active-p)
5365 (setq beg (region-beginning) end (region-end)
5366 string (buffer-substring beg end))
5367 (setq move t))
5369 (while (setq e (pop eal))
5370 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5371 c (aref tag 0))
5372 (push (cons c (string-to-char (car e))) det)
5373 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5374 (substring tag 1)))))
5375 (setq det (nreverse det))
5376 (unless char
5377 (message "%s" (concat "Emphasis marker or tag:" prompt))
5378 (setq char (read-char-exclusive)))
5379 (setq char (or (cdr (assoc char det)) char))
5380 (if (equal char ?\ )
5381 (setq s "" move nil)
5382 (unless (assoc (char-to-string char) org-emphasis-alist)
5383 (error "No such emphasis marker: \"%c\"" char))
5384 (setq s (char-to-string char)))
5385 (while (and (> (length string) 1)
5386 (equal (substring string 0 1) (substring string -1))
5387 (assoc (substring string 0 1) org-emphasis-alist))
5388 (setq string (substring string 1 -1)))
5389 (setq string (concat s string s))
5390 (if beg (delete-region beg end))
5391 (unless (or (bolp)
5392 (string-match (concat "[" (nth 0 erc) "\n]")
5393 (char-to-string (char-before (point)))))
5394 (insert " "))
5395 (unless (or (eobp)
5396 (string-match (concat "[" (nth 1 erc) "\n]")
5397 (char-to-string (char-after (point)))))
5398 (insert " ") (backward-char 1))
5399 (insert string)
5400 (and move (backward-char 1))))
5402 (defconst org-nonsticky-props
5403 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5405 (defsubst org-rear-nonsticky-at (pos)
5406 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5408 (defun org-activate-plain-links (limit)
5409 "Run through the buffer and add overlays to links."
5410 (catch 'exit
5411 (let (f)
5412 (if (re-search-forward org-plain-link-re limit t)
5413 (progn
5414 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5415 (setq f (get-text-property (match-beginning 0) 'face))
5416 (if (or (eq f 'org-tag)
5417 (and (listp f) (memq 'org-tag f)))
5419 (add-text-properties (match-beginning 0) (match-end 0)
5420 (list 'mouse-face 'highlight
5421 'face 'org-link
5422 'keymap org-mouse-map))
5423 (org-rear-nonsticky-at (match-end 0)))
5424 t)))))
5426 (defun org-activate-code (limit)
5427 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5428 (progn
5429 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5430 (remove-text-properties (match-beginning 0) (match-end 0)
5431 '(display t invisible t intangible t))
5432 t)))
5434 (defcustom org-src-fontify-natively nil
5435 "When non-nil, fontify code in code blocks."
5436 :type 'boolean
5437 :version "24.1"
5438 :group 'org-appearance
5439 :group 'org-babel)
5441 (defcustom org-src-prevent-auto-filling nil
5442 "When non-nil, prevent auto-filling in src blocks."
5443 :type 'boolean
5444 :version "24.1"
5445 :group 'org-appearance
5446 :group 'org-babel)
5448 (defcustom org-allow-promoting-top-level-subtree nil
5449 "When non-nil, allow promoting a top level subtree.
5450 The leading star of the top level headline will be replaced
5451 by a #."
5452 :type 'boolean
5453 :version "24.1"
5454 :group 'org-appearance)
5456 (defun org-fontify-meta-lines-and-blocks (limit)
5457 (condition-case nil
5458 (org-fontify-meta-lines-and-blocks-1 limit)
5459 (error (message "org-mode fontification error"))))
5461 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5462 "Fontify #+ lines and blocks, in the correct ways."
5463 (let ((case-fold-search t))
5464 (if (re-search-forward
5465 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5466 limit t)
5467 (let ((beg (match-beginning 0))
5468 (block-start (match-end 0))
5469 (block-end nil)
5470 (lang (match-string 7))
5471 (beg1 (line-beginning-position 2))
5472 (dc1 (downcase (match-string 2)))
5473 (dc3 (downcase (match-string 3)))
5474 end end1 quoting block-type ovl)
5475 (cond
5476 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5477 ;; a single line of backend-specific content
5478 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5479 (remove-text-properties (match-beginning 0) (match-end 0)
5480 '(display t invisible t intangible t))
5481 (add-text-properties (match-beginning 1) (match-end 3)
5482 '(font-lock-fontified t face org-meta-line))
5483 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5484 '(font-lock-fontified t face org-block))
5485 ; for backend-specific code
5487 ((and (match-end 4) (equal dc3 "begin"))
5488 ;; Truly a block
5489 (setq block-type (downcase (match-string 5))
5490 quoting (member block-type org-protecting-blocks))
5491 (when (re-search-forward
5492 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5493 nil t) ;; on purpose, we look further than LIMIT
5494 (setq end (min (point-max) (match-end 0))
5495 end1 (min (point-max) (1- (match-beginning 0))))
5496 (setq block-end (match-beginning 0))
5497 (when quoting
5498 (remove-text-properties beg end
5499 '(display t invisible t intangible t)))
5500 (add-text-properties
5501 beg end
5502 '(font-lock-fontified t font-lock-multiline t))
5503 (add-text-properties beg beg1 '(face org-meta-line))
5504 (add-text-properties end1 (min (point-max) (1+ end))
5505 '(face org-meta-line)) ; for end_src
5506 (cond
5507 ((and lang (not (string= lang "")) org-src-fontify-natively)
5508 (org-src-font-lock-fontify-block lang block-start block-end)
5509 ;; remove old background overlays
5510 (mapc (lambda (ov)
5511 (if (eq (overlay-get ov 'face) 'org-block-background)
5512 (delete-overlay ov)))
5513 (overlays-at (/ (+ beg1 block-end) 2)))
5514 ;; add a background overlay
5515 (setq ovl (make-overlay beg1 block-end))
5516 (overlay-put ovl 'face 'org-block-background)
5517 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5518 (quoting
5519 (add-text-properties beg1 (min (point-max) (1+ end1))
5520 '(face org-block))) ; end of source block
5521 ((not org-fontify-quote-and-verse-blocks))
5522 ((string= block-type "quote")
5523 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5524 ((string= block-type "verse")
5525 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5526 (add-text-properties beg beg1 '(face org-block-begin-line))
5527 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5528 '(face org-block-end-line))
5530 ((member dc1 '("title:" "author:" "email:" "date:"))
5531 (add-text-properties
5532 beg (match-end 3)
5533 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5534 '(font-lock-fontified t invisible t)
5535 '(font-lock-fontified t face org-document-info-keyword)))
5536 (add-text-properties
5537 (match-beginning 6) (match-end 6)
5538 (if (string-equal dc1 "title:")
5539 '(font-lock-fontified t face org-document-title)
5540 '(font-lock-fontified t face org-document-info))))
5541 ((not (member (char-after beg) '(?\ ?\t)))
5542 ;; just any other in-buffer setting, but not indented
5543 (add-text-properties
5544 beg (match-end 0)
5545 '(font-lock-fontified t face org-meta-line))
5547 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5548 "orgtbl:" "tblfm:" "tblname:" "results:"
5549 "call:" "header:" "headers:" "name:"))
5550 (and (match-end 4) (equal dc3 "attr")))
5551 (add-text-properties
5552 beg (match-end 0)
5553 '(font-lock-fontified t face org-meta-line))
5555 ((member dc3 '(" " ""))
5556 (add-text-properties
5557 beg (match-end 0)
5558 '(font-lock-fontified t face font-lock-comment-face)))
5559 (t nil))))))
5561 (defun org-strip-protective-commas (beg end)
5562 "Strip protective commas between BEG and END in the current buffer."
5563 (interactive "r")
5564 (save-excursion
5565 (save-match-data
5566 (goto-char beg)
5567 (let ((front-line (save-excursion
5568 (re-search-forward
5569 "[^[:space:]]" end t)
5570 (goto-char (match-beginning 0))
5571 (current-column))))
5572 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5573 (goto-char (match-beginning 1))
5574 (when (= (current-column) front-line)
5575 (replace-match "" nil nil nil 1)))))))
5577 (defun org-activate-angle-links (limit)
5578 "Run through the buffer and add overlays to links."
5579 (if (re-search-forward org-angle-link-re limit t)
5580 (progn
5581 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5582 (add-text-properties (match-beginning 0) (match-end 0)
5583 (list 'mouse-face 'highlight
5584 'keymap org-mouse-map))
5585 (org-rear-nonsticky-at (match-end 0))
5586 t)))
5588 (defun org-activate-footnote-links (limit)
5589 "Run through the buffer and add overlays to footnotes."
5590 (let ((fn (org-footnote-next-reference-or-definition limit)))
5591 (when fn
5592 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5593 (org-remove-flyspell-overlays-in beg end)
5594 (add-text-properties beg end
5595 (list 'mouse-face 'highlight
5596 'keymap org-mouse-map
5597 'help-echo
5598 (if (= (point-at-bol) beg)
5599 "Footnote definition"
5600 "Footnote reference")
5601 'font-lock-fontified t
5602 'font-lock-multiline t
5603 'face 'org-footnote))))))
5605 (defun org-activate-bracket-links (limit)
5606 "Run through the buffer and add overlays to bracketed links."
5607 (if (re-search-forward org-bracket-link-regexp limit t)
5608 (let* ((help (concat "LINK: "
5609 (org-match-string-no-properties 1)))
5610 ;; FIXME: above we should remove the escapes.
5611 ;; but that requires another match, protecting match data,
5612 ;; a lot of overhead for font-lock.
5613 (ip (org-maybe-intangible
5614 (list 'invisible 'org-link
5615 'keymap org-mouse-map 'mouse-face 'highlight
5616 'font-lock-multiline t 'help-echo help)))
5617 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5618 'font-lock-multiline t 'help-echo help)))
5619 ;; We need to remove the invisible property here. Table narrowing
5620 ;; may have made some of this invisible.
5621 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5622 (remove-text-properties (match-beginning 0) (match-end 0)
5623 '(invisible nil))
5624 (if (match-end 3)
5625 (progn
5626 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5627 (org-rear-nonsticky-at (match-beginning 3))
5628 (add-text-properties (match-beginning 3) (match-end 3) vp)
5629 (org-rear-nonsticky-at (match-end 3))
5630 (add-text-properties (match-end 3) (match-end 0) ip)
5631 (org-rear-nonsticky-at (match-end 0)))
5632 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5633 (org-rear-nonsticky-at (match-beginning 1))
5634 (add-text-properties (match-beginning 1) (match-end 1) vp)
5635 (org-rear-nonsticky-at (match-end 1))
5636 (add-text-properties (match-end 1) (match-end 0) ip)
5637 (org-rear-nonsticky-at (match-end 0)))
5638 t)))
5640 (defun org-activate-dates (limit)
5641 "Run through the buffer and add overlays to dates."
5642 (if (re-search-forward org-tsr-regexp-both limit t)
5643 (progn
5644 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5645 (add-text-properties (match-beginning 0) (match-end 0)
5646 (list 'mouse-face 'highlight
5647 'keymap org-mouse-map))
5648 (org-rear-nonsticky-at (match-end 0))
5649 (when org-display-custom-times
5650 (if (match-end 3)
5651 (org-display-custom-time (match-beginning 3) (match-end 3)))
5652 (org-display-custom-time (match-beginning 1) (match-end 1)))
5653 t)))
5655 (defvar org-target-link-regexp nil
5656 "Regular expression matching radio targets in plain text.")
5657 (make-variable-buffer-local 'org-target-link-regexp)
5658 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5659 "Regular expression matching a link target.")
5660 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5661 "Regular expression matching a radio target.")
5662 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5663 "Regular expression matching any target.")
5665 (defun org-activate-target-links (limit)
5666 "Run through the buffer and add overlays to target matches."
5667 (when org-target-link-regexp
5668 (let ((case-fold-search t))
5669 (if (re-search-forward org-target-link-regexp limit t)
5670 (progn
5671 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5672 (add-text-properties (match-beginning 0) (match-end 0)
5673 (list 'mouse-face 'highlight
5674 'keymap org-mouse-map
5675 'help-echo "Radio target link"
5676 'org-linked-text t))
5677 (org-rear-nonsticky-at (match-end 0))
5678 t)))))
5680 (defun org-update-radio-target-regexp ()
5681 "Find all radio targets in this file and update the regular expression."
5682 (interactive)
5683 (when (memq 'radio org-activate-links)
5684 (setq org-target-link-regexp
5685 (org-make-target-link-regexp (org-all-targets 'radio)))
5686 (org-restart-font-lock)))
5688 (defun org-hide-wide-columns (limit)
5689 (let (s e)
5690 (setq s (text-property-any (point) (or limit (point-max))
5691 'org-cwidth t))
5692 (when s
5693 (setq e (next-single-property-change s 'org-cwidth))
5694 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5695 (goto-char e)
5696 t)))
5698 (defvar org-latex-and-specials-regexp nil
5699 "Regular expression for highlighting export special stuff.")
5700 (defvar org-match-substring-regexp)
5701 (defvar org-match-substring-with-braces-regexp)
5703 ;; This should be with the exporter code, but we also use if for font-locking
5704 (defconst org-export-html-special-string-regexps
5705 '(("\\\\-" . "&shy;")
5706 ("---\\([^-]\\)" . "&mdash;\\1")
5707 ("--\\([^-]\\)" . "&ndash;\\1")
5708 ("\\.\\.\\." . "&hellip;"))
5709 "Regular expressions for special string conversion.")
5712 (defun org-compute-latex-and-specials-regexp ()
5713 "Compute regular expression for stuff treated specially by exporters."
5714 (if (not org-highlight-latex-fragments-and-specials)
5715 (org-set-local 'org-latex-and-specials-regexp nil)
5716 (require 'org-exp)
5717 (let*
5718 ((matchers (plist-get org-format-latex-options :matchers))
5719 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5720 org-latex-regexps)))
5721 (org-export-allow-BIND nil)
5722 (options (org-combine-plists (org-default-export-plist)
5723 (org-infile-export-plist)))
5724 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5725 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5726 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5727 (org-export-html-expand (plist-get options :expand-quoted-html))
5728 (org-export-with-special-strings (plist-get options :special-strings))
5729 (re-sub
5730 (cond
5731 ((equal org-export-with-sub-superscripts '{})
5732 (list org-match-substring-with-braces-regexp))
5733 (org-export-with-sub-superscripts
5734 (list org-match-substring-regexp))
5735 (t nil)))
5736 (re-latex
5737 (if org-export-with-LaTeX-fragments
5738 (mapcar (lambda (x) (nth 1 x)) latexs)))
5739 (re-macros
5740 (if org-export-with-TeX-macros
5741 (list (concat "\\\\"
5742 (regexp-opt
5743 (append
5745 (delq nil
5746 (mapcar 'car-safe
5747 (append org-entities-user
5748 org-entities)))
5749 (if (boundp 'org-latex-entities)
5750 (mapcar (lambda (x)
5751 (or (car-safe x) x))
5752 org-latex-entities)
5753 nil))
5754 'words))) ; FIXME
5756 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5757 (re-special (if org-export-with-special-strings
5758 (mapcar (lambda (x) (car x))
5759 org-export-html-special-string-regexps)))
5760 (re-rest
5761 (delq nil
5762 (list
5763 (if org-export-html-expand "@<[^>\n]+>")
5764 ))))
5765 (org-set-local
5766 'org-latex-and-specials-regexp
5767 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5768 re-rest) "\\|")))))
5770 (defun org-do-latex-and-special-faces (limit)
5771 "Run through the buffer and add overlays to links."
5772 (when org-latex-and-specials-regexp
5773 (let (rtn d)
5774 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5775 limit t))
5776 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5777 'face))
5778 '(org-code org-verbatim underline)))
5779 (progn
5780 (setq rtn t
5781 d (cond ((member (char-after (1+ (match-beginning 0)))
5782 '(?_ ?^)) 1)
5783 (t 0)))
5784 (font-lock-prepend-text-property
5785 (+ d (match-beginning 0)) (match-end 0)
5786 'face 'org-latex-and-export-specials)
5787 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5788 '(font-lock-multiline t)))))
5789 rtn)))
5791 (defun org-restart-font-lock ()
5792 "Restart `font-lock-mode', to force refontification."
5793 (when (and (boundp 'font-lock-mode) font-lock-mode)
5794 (font-lock-mode -1)
5795 (font-lock-mode 1)))
5797 (defun org-all-targets (&optional radio)
5798 "Return a list of all targets in this file.
5799 With optional argument RADIO, only find radio targets."
5800 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5801 rtn)
5802 (save-excursion
5803 (goto-char (point-min))
5804 (while (re-search-forward re nil t)
5805 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5806 rtn)))
5808 (defun org-make-target-link-regexp (targets)
5809 "Make regular expression matching all strings in TARGETS.
5810 The regular expression finds the targets also if there is a line break
5811 between words."
5812 (and targets
5813 (concat
5814 "\\<\\("
5815 (mapconcat
5816 (lambda (x)
5817 (setq x (regexp-quote x))
5818 (while (string-match " +" x)
5819 (setq x (replace-match "\\s-+" t t x)))
5821 targets
5822 "\\|")
5823 "\\)\\>")))
5825 (defun org-activate-tags (limit)
5826 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5827 (progn
5828 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5829 (add-text-properties (match-beginning 1) (match-end 1)
5830 (list 'mouse-face 'highlight
5831 'keymap org-mouse-map))
5832 (org-rear-nonsticky-at (match-end 1))
5833 t)))
5835 (defun org-outline-level ()
5836 "Compute the outline level of the heading at point.
5837 This function assumes that the cursor is at the beginning of a line matched
5838 by `outline-regexp'. Otherwise it returns garbage.
5839 If this is called at a normal headline, the level is the number of stars.
5840 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5841 (save-excursion
5842 (looking-at org-outline-regexp)
5843 (1- (- (match-end 0) (match-beginning 0)))))
5845 (defvar org-font-lock-keywords nil)
5847 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5848 "Regular expression matching a property line.")
5850 (defvar org-font-lock-hook nil
5851 "Functions to be called for special font lock stuff.")
5853 (defvar org-font-lock-set-keywords-hook nil
5854 "Functions that can manipulate `org-font-lock-extra-keywords'.
5855 This is called after `org-font-lock-extra-keywords' is defined, but before
5856 it is installed to be used by font lock. This can be useful if something
5857 needs to be inserted at a specific position in the font-lock sequence.")
5859 (defun org-font-lock-hook (limit)
5860 (run-hook-with-args 'org-font-lock-hook limit))
5862 (defun org-set-font-lock-defaults ()
5863 (let* ((em org-fontify-emphasized-text)
5864 (lk org-activate-links)
5865 (org-font-lock-extra-keywords
5866 (list
5867 ;; Call the hook
5868 '(org-font-lock-hook)
5869 ;; Headlines
5870 `(,(if org-fontify-whole-heading-line
5871 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5872 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5873 (1 (org-get-level-face 1))
5874 (2 (org-get-level-face 2))
5875 (3 (org-get-level-face 3)))
5876 ;; Table lines
5877 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5878 (1 'org-table t))
5879 ;; Table internals
5880 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5881 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5882 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5883 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5884 ;; Drawers
5885 (list org-drawer-regexp '(0 'org-special-keyword t))
5886 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5887 ;; Properties
5888 (list org-property-re
5889 '(1 'org-special-keyword t)
5890 '(3 'org-property-value t))
5891 ;; Links
5892 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5893 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5894 (if (memq 'plain lk) '(org-activate-plain-links))
5895 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5896 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5897 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5898 (if (memq 'footnote lk) '(org-activate-footnote-links))
5899 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5900 '(org-hide-wide-columns (0 nil append))
5901 ;; TODO keyword
5902 (list (format org-heading-keyword-regexp-format
5903 org-todo-regexp)
5904 '(2 (org-get-todo-face 2) t))
5905 ;; DONE
5906 (if org-fontify-done-headline
5907 (list (format org-heading-keyword-regexp-format
5908 (concat
5909 "\\(?:"
5910 (mapconcat 'regexp-quote org-done-keywords "\\|")
5911 "\\)"))
5912 '(2 'org-headline-done t))
5913 nil)
5914 ;; Priorities
5915 '(org-font-lock-add-priority-faces)
5916 ;; Tags
5917 '(org-font-lock-add-tag-faces)
5918 ;; Special keywords
5919 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5920 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5921 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5922 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5923 ;; Emphasis
5924 (if em
5925 (if (featurep 'xemacs)
5926 '(org-do-emphasis-faces (0 nil append))
5927 '(org-do-emphasis-faces)))
5928 ;; Checkboxes
5929 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5930 1 'org-checkbox prepend)
5931 (if (cdr (assq 'checkbox org-list-automatic-rules))
5932 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5933 (0 (org-get-checkbox-statistics-face) t)))
5934 ;; Description list items
5935 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5936 1 'org-list-dt prepend)
5937 ;; ARCHIVEd headings
5938 (list (concat
5939 org-outline-regexp-bol
5940 "\\(.*:" org-archive-tag ":.*\\)")
5941 '(1 'org-archived prepend))
5942 ;; Specials
5943 '(org-do-latex-and-special-faces)
5944 '(org-fontify-entities)
5945 '(org-raise-scripts)
5946 ;; Code
5947 '(org-activate-code (1 'org-code t))
5948 ;; COMMENT
5949 (list (format org-heading-keyword-regexp-format
5950 (concat "\\("
5951 org-comment-string "\\|" org-quote-string
5952 "\\)"))
5953 '(2 'org-special-keyword t))
5954 '("^#.*" (0 'font-lock-comment-face t))
5955 ;; Blocks and meta lines
5956 '(org-fontify-meta-lines-and-blocks)
5958 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5959 (run-hooks 'org-font-lock-set-keywords-hook)
5960 ;; Now set the full font-lock-keywords
5961 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5962 (org-set-local 'font-lock-defaults
5963 '(org-font-lock-keywords t nil nil backward-paragraph))
5964 (kill-local-variable 'font-lock-keywords) nil))
5966 (defun org-toggle-pretty-entities ()
5967 "Toggle the composition display of entities as UTF8 characters."
5968 (interactive)
5969 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5970 (org-restart-font-lock)
5971 (if org-pretty-entities
5972 (message "Entities are displayed as UTF8 characters")
5973 (save-restriction
5974 (widen)
5975 (org-decompose-region (point-min) (point-max))
5976 (message "Entities are displayed plain"))))
5978 (defun org-fontify-entities (limit)
5979 "Find an entity to fontify."
5980 (let (ee)
5981 (when org-pretty-entities
5982 (catch 'match
5983 (while (re-search-forward
5984 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5985 limit t)
5986 (if (and (not (org-in-indented-comment-line))
5987 (setq ee (org-entity-get (match-string 1)))
5988 (= (length (nth 6 ee)) 1))
5989 (let*
5990 ((end (if (equal (match-string 2) "{}")
5991 (match-end 2)
5992 (match-end 1))))
5993 (add-text-properties
5994 (match-beginning 0) end
5995 (list 'font-lock-fontified t))
5996 (compose-region (match-beginning 0) end
5997 (nth 6 ee) nil)
5998 (backward-char 1)
5999 (throw 'match t))))
6000 nil))))
6002 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6003 "Fontify string S like in Org-mode."
6004 (with-temp-buffer
6005 (insert s)
6006 (let ((org-odd-levels-only odd-levels))
6007 (org-mode)
6008 (font-lock-fontify-buffer)
6009 (buffer-string))))
6011 (defvar org-m nil)
6012 (defvar org-l nil)
6013 (defvar org-f nil)
6014 (defun org-get-level-face (n)
6015 "Get the right face for match N in font-lock matching of headlines."
6016 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6017 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6018 (if org-cycle-level-faces
6019 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6020 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6021 (cond
6022 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6023 ((eq n 2) org-f)
6024 (t (if org-level-color-stars-only nil org-f))))
6027 (defun org-get-todo-face (kwd)
6028 "Get the right face for a TODO keyword KWD.
6029 If KWD is a number, get the corresponding match group."
6030 (if (numberp kwd) (setq kwd (match-string kwd)))
6031 (or (org-face-from-face-or-color
6032 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6033 (and (member kwd org-done-keywords) 'org-done)
6034 'org-todo))
6036 (defun org-face-from-face-or-color (context inherit face-or-color)
6037 "Create a face list that inherits INHERIT, but sets the foreground color.
6038 When FACE-OR-COLOR is not a string, just return it."
6039 (if (stringp face-or-color)
6040 (list :inherit inherit
6041 (cdr (assoc context org-faces-easy-properties))
6042 face-or-color)
6043 face-or-color))
6045 (defun org-font-lock-add-tag-faces (limit)
6046 "Add the special tag faces."
6047 (when (and org-tag-faces org-tags-special-faces-re)
6048 (while (re-search-forward org-tags-special-faces-re limit t)
6049 (add-text-properties (match-beginning 1) (match-end 1)
6050 (list 'face (org-get-tag-face 1)
6051 'font-lock-fontified t))
6052 (backward-char 1))))
6054 (defun org-font-lock-add-priority-faces (limit)
6055 "Add the special priority faces."
6056 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6057 (when (save-match-data (org-at-heading-p))
6058 (add-text-properties
6059 (match-beginning 0) (match-end 0)
6060 (list 'face (or (org-face-from-face-or-color
6061 'priority 'org-special-keyword
6062 (cdr (assoc (char-after (match-beginning 1))
6063 org-priority-faces)))
6064 'org-special-keyword)
6065 'font-lock-fontified t)))))
6067 (defun org-get-tag-face (kwd)
6068 "Get the right face for a TODO keyword KWD.
6069 If KWD is a number, get the corresponding match group."
6070 (if (numberp kwd) (setq kwd (match-string kwd)))
6071 (or (org-face-from-face-or-color
6072 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6073 'org-tag))
6075 (defun org-unfontify-region (beg end &optional maybe_loudly)
6076 "Remove fontification and activation overlays from links."
6077 (font-lock-default-unfontify-region beg end)
6078 (let* ((buffer-undo-list t)
6079 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6080 (inhibit-modification-hooks t)
6081 deactivate-mark buffer-file-name buffer-file-truename)
6082 (org-decompose-region beg end)
6083 (remove-text-properties beg end
6084 '(mouse-face t keymap t org-linked-text t
6085 invisible t intangible t
6086 org-no-flyspell t org-emphasis t))
6087 (org-remove-font-lock-display-properties beg end)))
6089 (defconst org-script-display '(((raise -0.3) (height 0.7))
6090 ((raise 0.3) (height 0.7))
6091 ((raise -0.5))
6092 ((raise 0.5)))
6093 "Display properties for showing superscripts and subscripts.")
6095 (defun org-remove-font-lock-display-properties (beg end)
6096 "Remove specific display properties that have been added by font lock.
6097 The will remove the raise properties that are used to show superscripts
6098 and subscripts."
6099 (let (next prop)
6100 (while (< beg end)
6101 (setq next (next-single-property-change beg 'display nil end)
6102 prop (get-text-property beg 'display))
6103 (if (member prop org-script-display)
6104 (put-text-property beg next 'display nil))
6105 (setq beg next))))
6107 (defun org-raise-scripts (limit)
6108 "Add raise properties to sub/superscripts."
6109 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6110 (if (re-search-forward
6111 (if (eq org-use-sub-superscripts t)
6112 org-match-substring-regexp
6113 org-match-substring-with-braces-regexp)
6114 limit t)
6115 (let* ((pos (point)) table-p comment-p
6116 (mpos (match-beginning 3))
6117 (emph-p (get-text-property mpos 'org-emphasis))
6118 (link-p (get-text-property mpos 'mouse-face))
6119 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6120 (goto-char (point-at-bol))
6121 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6122 comment-p (org-looking-at-p "[ \t]*#"))
6123 (goto-char pos)
6124 ;; FIXME: Should we go back one character here, for a_b^c
6125 ;; (goto-char (1- pos)) ;????????????????????
6126 (if (or comment-p emph-p link-p keyw-p)
6128 (put-text-property (match-beginning 3) (match-end 0)
6129 'display
6130 (if (equal (char-after (match-beginning 2)) ?^)
6131 (nth (if table-p 3 1) org-script-display)
6132 (nth (if table-p 2 0) org-script-display)))
6133 (add-text-properties (match-beginning 2) (match-end 2)
6134 (list 'invisible t
6135 'org-dwidth t 'org-dwidth-n 1))
6136 (if (and (eq (char-after (match-beginning 3)) ?{)
6137 (eq (char-before (match-end 3)) ?}))
6138 (progn
6139 (add-text-properties
6140 (match-beginning 3) (1+ (match-beginning 3))
6141 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6142 (add-text-properties
6143 (1- (match-end 3)) (match-end 3)
6144 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6145 t)))))
6147 ;;;; Visibility cycling, including org-goto and indirect buffer
6149 ;;; Cycling
6151 (defvar org-cycle-global-status nil)
6152 (make-variable-buffer-local 'org-cycle-global-status)
6153 (defvar org-cycle-subtree-status nil)
6154 (make-variable-buffer-local 'org-cycle-subtree-status)
6156 ;;;###autoload
6158 (defvar org-inlinetask-min-level)
6160 (defun org-cycle (&optional arg)
6161 "TAB-action and visibility cycling for Org-mode.
6163 This is the command invoked in Org-mode by the TAB key. Its main purpose
6164 is outline visibility cycling, but it also invokes other actions
6165 in special contexts.
6167 - When this function is called with a prefix argument, rotate the entire
6168 buffer through 3 states (global cycling)
6169 1. OVERVIEW: Show only top-level headlines.
6170 2. CONTENTS: Show all headlines of all levels, but no body text.
6171 3. SHOW ALL: Show everything.
6172 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6173 determined by the variable `org-startup-folded', and by any VISIBILITY
6174 properties in the buffer.
6175 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6176 including any drawers.
6178 - When inside a table, re-align the table and move to the next field.
6180 - When point is at the beginning of a headline, rotate the subtree started
6181 by this line through 3 different states (local cycling)
6182 1. FOLDED: Only the main headline is shown.
6183 2. CHILDREN: The main headline and the direct children are shown.
6184 From this state, you can move to one of the children
6185 and zoom in further.
6186 3. SUBTREE: Show the entire subtree, including body text.
6187 If there is no subtree, switch directly from CHILDREN to FOLDED.
6189 - When point is at the beginning of an empty headline and the variable
6190 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6191 of the headline by demoting and promoting it to likely levels. This
6192 speeds up creation document structure by pressing TAB once or several
6193 times right after creating a new headline.
6195 - When there is a numeric prefix, go up to a heading with level ARG, do
6196 a `show-subtree' and return to the previous cursor position. If ARG
6197 is negative, go up that many levels.
6199 - When point is not at the beginning of a headline, execute the global
6200 binding for TAB, which is re-indenting the line. See the option
6201 `org-cycle-emulate-tab' for details.
6203 - Special case: if point is at the beginning of the buffer and there is
6204 no headline in line 1, this function will act as if called with prefix arg
6205 (C-u TAB, same as S-TAB) also when called without prefix arg.
6206 But only if also the variable `org-cycle-global-at-bob' is t."
6207 (interactive "P")
6208 (org-load-modules-maybe)
6209 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6210 (and org-cycle-level-after-item/entry-creation
6211 (or (org-cycle-level)
6212 (org-cycle-item-indentation))))
6213 (let* ((limit-level
6214 (or org-cycle-max-level
6215 (and (boundp 'org-inlinetask-min-level)
6216 org-inlinetask-min-level
6217 (1- org-inlinetask-min-level))))
6218 (nstars (and limit-level
6219 (if org-odd-levels-only
6220 (and limit-level (1- (* limit-level 2)))
6221 limit-level)))
6222 (org-outline-regexp
6223 (if (not (derived-mode-p 'org-mode))
6224 outline-regexp
6225 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6226 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6227 (not (looking-at org-outline-regexp))))
6228 (org-cycle-hook
6229 (if bob-special
6230 (delq 'org-optimize-window-after-visibility-change
6231 (copy-sequence org-cycle-hook))
6232 org-cycle-hook))
6233 (pos (point)))
6235 (if (or bob-special (equal arg '(4)))
6236 ;; special case: use global cycling
6237 (setq arg t))
6239 (cond
6241 ((equal arg '(16))
6242 (setq last-command 'dummy)
6243 (org-set-startup-visibility)
6244 (message "Startup visibility, plus VISIBILITY properties"))
6246 ((equal arg '(64))
6247 (show-all)
6248 (message "Entire buffer visible, including drawers"))
6250 ;; Table: enter it or move to the next field.
6251 ((org-at-table-p 'any)
6252 (if (org-at-table.el-p)
6253 (message "Use C-c ' to edit table.el tables")
6254 (if arg (org-table-edit-field t)
6255 (org-table-justify-field-maybe)
6256 (call-interactively 'org-table-next-field))))
6258 ((run-hook-with-args-until-success
6259 'org-tab-after-check-for-table-hook))
6261 ;; Global cycling: delegate to `org-cycle-internal-global'.
6262 ((eq arg t) (org-cycle-internal-global))
6264 ;; Drawers: delegate to `org-flag-drawer'.
6265 ((and org-drawers org-drawer-regexp
6266 (save-excursion
6267 (beginning-of-line 1)
6268 (looking-at org-drawer-regexp)))
6269 (org-flag-drawer ; toggle block visibility
6270 (not (get-char-property (match-end 0) 'invisible))))
6272 ;; Show-subtree, ARG levels up from here.
6273 ((integerp arg)
6274 (save-excursion
6275 (org-back-to-heading)
6276 (outline-up-heading (if (< arg 0) (- arg)
6277 (- (funcall outline-level) arg)))
6278 (org-show-subtree)))
6280 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6281 ((and (featurep 'org-inlinetask)
6282 (org-inlinetask-at-task-p)
6283 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6284 (org-inlinetask-toggle-visibility))
6286 ((org-try-cdlatex-tab))
6288 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6289 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6290 (save-excursion (beginning-of-line 1)
6291 (looking-at org-outline-regexp)))
6292 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6293 (org-cycle-internal-local))
6295 ;; From there: TAB emulation and template completion.
6296 (buffer-read-only (org-back-to-heading))
6298 ((run-hook-with-args-until-success
6299 'org-tab-after-check-for-cycling-hook))
6301 ((org-try-structure-completion))
6303 ((run-hook-with-args-until-success
6304 'org-tab-before-tab-emulation-hook))
6306 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6307 (or (not (bolp))
6308 (not (looking-at org-outline-regexp))))
6309 (call-interactively (global-key-binding "\t")))
6311 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6312 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6313 (or (and (eq org-cycle-emulate-tab 'white)
6314 (= (match-end 0) (point-at-eol)))
6315 (and (eq org-cycle-emulate-tab 'whitestart)
6316 (>= (match-end 0) pos))))
6318 (eq org-cycle-emulate-tab t))
6319 (call-interactively (global-key-binding "\t")))
6321 (t (save-excursion
6322 (org-back-to-heading)
6323 (org-cycle)))))))
6325 (defun org-cycle-internal-global ()
6326 "Do the global cycling action."
6327 ;; Hack to avoid display of messages for .org attachments in Gnus
6328 (let ((ga (string-match "\\*fontification" (buffer-name))))
6329 (cond
6330 ((and (eq last-command this-command)
6331 (eq org-cycle-global-status 'overview))
6332 ;; We just created the overview - now do table of contents
6333 ;; This can be slow in very large buffers, so indicate action
6334 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6335 (unless ga (message "CONTENTS..."))
6336 (org-content)
6337 (unless ga (message "CONTENTS...done"))
6338 (setq org-cycle-global-status 'contents)
6339 (run-hook-with-args 'org-cycle-hook 'contents))
6341 ((and (eq last-command this-command)
6342 (eq org-cycle-global-status 'contents))
6343 ;; We just showed the table of contents - now show everything
6344 (run-hook-with-args 'org-pre-cycle-hook 'all)
6345 (show-all)
6346 (unless ga (message "SHOW ALL"))
6347 (setq org-cycle-global-status 'all)
6348 (run-hook-with-args 'org-cycle-hook 'all))
6351 ;; Default action: go to overview
6352 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6353 (org-overview)
6354 (unless ga (message "OVERVIEW"))
6355 (setq org-cycle-global-status 'overview)
6356 (run-hook-with-args 'org-cycle-hook 'overview)))))
6358 (defun org-cycle-internal-local ()
6359 "Do the local cycling action."
6360 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6361 ;; First, determine end of headline (EOH), end of subtree or item
6362 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6363 (save-excursion
6364 (if (org-at-item-p)
6365 (progn
6366 (beginning-of-line)
6367 (setq struct (org-list-struct))
6368 (setq eoh (point-at-eol))
6369 (setq eos (org-list-get-item-end-before-blank (point) struct))
6370 (setq has-children (org-list-has-child-p (point) struct)))
6371 (org-back-to-heading)
6372 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6373 (setq eos (save-excursion
6374 (org-end-of-subtree t)
6375 (unless (eobp)
6376 (skip-chars-forward " \t\n"))
6377 (if (eobp) (point) (1- (point)))))
6378 (setq has-children
6379 (or (save-excursion
6380 (let ((level (funcall outline-level)))
6381 (outline-next-heading)
6382 (and (org-at-heading-p t)
6383 (> (funcall outline-level) level))))
6384 (save-excursion
6385 (org-list-search-forward (org-item-beginning-re) eos t)))))
6386 ;; Determine end invisible part of buffer (EOL)
6387 (beginning-of-line 2)
6388 ;; XEmacs doesn't have `next-single-char-property-change'
6389 (if (featurep 'xemacs)
6390 (while (and (not (eobp)) ;; this is like `next-line'
6391 (get-char-property (1- (point)) 'invisible))
6392 (beginning-of-line 2))
6393 (while (and (not (eobp)) ;; this is like `next-line'
6394 (get-char-property (1- (point)) 'invisible))
6395 (goto-char (next-single-char-property-change (point) 'invisible))
6396 (and (eolp) (beginning-of-line 2))))
6397 (setq eol (point)))
6398 ;; Find out what to do next and set `this-command'
6399 (cond
6400 ((= eos eoh)
6401 ;; Nothing is hidden behind this heading
6402 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6403 (message "EMPTY ENTRY")
6404 (setq org-cycle-subtree-status nil)
6405 (save-excursion
6406 (goto-char eos)
6407 (outline-next-heading)
6408 (if (outline-invisible-p) (org-flag-heading nil))))
6409 ((and (or (>= eol eos)
6410 (not (string-match "\\S-" (buffer-substring eol eos))))
6411 (or has-children
6412 (not (setq children-skipped
6413 org-cycle-skip-children-state-if-no-children))))
6414 ;; Entire subtree is hidden in one line: children view
6415 (run-hook-with-args 'org-pre-cycle-hook 'children)
6416 (if (org-at-item-p)
6417 (org-list-set-item-visibility (point-at-bol) struct 'children)
6418 (org-show-entry)
6419 (org-with-limited-levels (show-children))
6420 ;; FIXME: This slows down the func way too much.
6421 ;; How keep drawers hidden in subtree anyway?
6422 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6423 ;; (org-cycle-hide-drawers 'subtree))
6425 ;; Fold every list in subtree to top-level items.
6426 (when (eq org-cycle-include-plain-lists 'integrate)
6427 (save-excursion
6428 (org-back-to-heading)
6429 (while (org-list-search-forward (org-item-beginning-re) eos t)
6430 (beginning-of-line 1)
6431 (let* ((struct (org-list-struct))
6432 (prevs (org-list-prevs-alist struct))
6433 (end (org-list-get-bottom-point struct)))
6434 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6435 (org-list-get-all-items (point) struct prevs))
6436 (goto-char end))))))
6437 (message "CHILDREN")
6438 (save-excursion
6439 (goto-char eos)
6440 (outline-next-heading)
6441 (if (outline-invisible-p) (org-flag-heading nil)))
6442 (setq org-cycle-subtree-status 'children)
6443 (run-hook-with-args 'org-cycle-hook 'children))
6444 ((or children-skipped
6445 (and (eq last-command this-command)
6446 (eq org-cycle-subtree-status 'children)))
6447 ;; We just showed the children, or no children are there,
6448 ;; now show everything.
6449 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6450 (outline-flag-region eoh eos nil)
6451 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6452 (setq org-cycle-subtree-status 'subtree)
6453 (run-hook-with-args 'org-cycle-hook 'subtree))
6455 ;; Default action: hide the subtree.
6456 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6457 (outline-flag-region eoh eos t)
6458 (message "FOLDED")
6459 (setq org-cycle-subtree-status 'folded)
6460 (run-hook-with-args 'org-cycle-hook 'folded)))))
6462 ;;;###autoload
6463 (defun org-global-cycle (&optional arg)
6464 "Cycle the global visibility. For details see `org-cycle'.
6465 With \\[universal-argument] prefix arg, switch to startup visibility.
6466 With a numeric prefix, show all headlines up to that level."
6467 (interactive "P")
6468 (let ((org-cycle-include-plain-lists
6469 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6470 (cond
6471 ((integerp arg)
6472 (show-all)
6473 (hide-sublevels arg)
6474 (setq org-cycle-global-status 'contents))
6475 ((equal arg '(4))
6476 (org-set-startup-visibility)
6477 (message "Startup visibility, plus VISIBILITY properties."))
6479 (org-cycle '(4))))))
6481 (defun org-set-startup-visibility ()
6482 "Set the visibility required by startup options and properties."
6483 (cond
6484 ((eq org-startup-folded t)
6485 (org-cycle '(4)))
6486 ((eq org-startup-folded 'content)
6487 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6488 (org-cycle '(4)) (org-cycle '(4)))))
6489 (unless (eq org-startup-folded 'showeverything)
6490 (if org-hide-block-startup (org-hide-block-all))
6491 (org-set-visibility-according-to-property 'no-cleanup)
6492 (org-cycle-hide-archived-subtrees 'all)
6493 (org-cycle-hide-drawers 'all)
6494 (org-cycle-show-empty-lines t)))
6496 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6497 "Switch subtree visibilities according to :VISIBILITY: property."
6498 (interactive)
6499 (let (org-show-entry-below state)
6500 (save-excursion
6501 (goto-char (point-min))
6502 (while (re-search-forward
6503 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6504 nil t)
6505 (setq state (match-string 1))
6506 (save-excursion
6507 (org-back-to-heading t)
6508 (hide-subtree)
6509 (org-reveal)
6510 (cond
6511 ((equal state '("fold" "folded"))
6512 (hide-subtree))
6513 ((equal state "children")
6514 (org-show-hidden-entry)
6515 (show-children))
6516 ((equal state "content")
6517 (save-excursion
6518 (save-restriction
6519 (org-narrow-to-subtree)
6520 (org-content))))
6521 ((member state '("all" "showall"))
6522 (show-subtree)))))
6523 (unless no-cleanup
6524 (org-cycle-hide-archived-subtrees 'all)
6525 (org-cycle-hide-drawers 'all)
6526 (org-cycle-show-empty-lines 'all)))))
6528 ;; This function uses outline-regexp instead of the more fundamental
6529 ;; org-outline-regexp so that org-cycle-global works outside of Org
6530 ;; buffers, where outline-regexp is needed.
6531 (defun org-overview ()
6532 "Switch to overview mode, showing only top-level headlines.
6533 Really, this shows all headlines with level equal or greater than the level
6534 of the first headline in the buffer. This is important, because if the
6535 first headline is not level one, then (hide-sublevels 1) gives confusing
6536 results."
6537 (interactive)
6538 (let ((level (save-excursion
6539 (goto-char (point-min))
6540 (if (re-search-forward (concat "^" outline-regexp) nil t)
6541 (progn
6542 (goto-char (match-beginning 0))
6543 (funcall outline-level))))))
6544 (and level (hide-sublevels level))))
6546 (defun org-content (&optional arg)
6547 "Show all headlines in the buffer, like a table of contents.
6548 With numerical argument N, show content up to level N."
6549 (interactive "P")
6550 (save-excursion
6551 ;; Visit all headings and show their offspring
6552 (and (integerp arg) (org-overview))
6553 (goto-char (point-max))
6554 (catch 'exit
6555 (while (and (progn (condition-case nil
6556 (outline-previous-visible-heading 1)
6557 (error (goto-char (point-min))))
6559 (looking-at org-outline-regexp))
6560 (if (integerp arg)
6561 (show-children (1- arg))
6562 (show-branches))
6563 (if (bobp) (throw 'exit nil))))))
6566 (defun org-optimize-window-after-visibility-change (state)
6567 "Adjust the window after a change in outline visibility.
6568 This function is the default value of the hook `org-cycle-hook'."
6569 (when (get-buffer-window (current-buffer))
6570 (cond
6571 ((eq state 'content) nil)
6572 ((eq state 'all) nil)
6573 ((eq state 'folded) nil)
6574 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6575 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6577 (defun org-remove-empty-overlays-at (pos)
6578 "Remove outline overlays that do not contain non-white stuff."
6579 (mapc
6580 (lambda (o)
6581 (and (eq 'outline (overlay-get o 'invisible))
6582 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6583 (overlay-end o))))
6584 (delete-overlay o)))
6585 (overlays-at pos)))
6587 (defun org-clean-visibility-after-subtree-move ()
6588 "Fix visibility issues after moving a subtree."
6589 ;; First, find a reasonable region to look at:
6590 ;; Start two siblings above, end three below
6591 (let* ((beg (save-excursion
6592 (and (org-get-last-sibling)
6593 (org-get-last-sibling))
6594 (point)))
6595 (end (save-excursion
6596 (and (org-get-next-sibling)
6597 (org-get-next-sibling)
6598 (org-get-next-sibling))
6599 (if (org-at-heading-p)
6600 (point-at-eol)
6601 (point))))
6602 (level (looking-at "\\*+"))
6603 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6604 (save-excursion
6605 (save-restriction
6606 (narrow-to-region beg end)
6607 (when re
6608 ;; Properly fold already folded siblings
6609 (goto-char (point-min))
6610 (while (re-search-forward re nil t)
6611 (if (and (not (outline-invisible-p))
6612 (save-excursion
6613 (goto-char (point-at-eol)) (outline-invisible-p)))
6614 (hide-entry))))
6615 (org-cycle-show-empty-lines 'overview)
6616 (org-cycle-hide-drawers 'overview)))))
6618 (defun org-cycle-show-empty-lines (state)
6619 "Show empty lines above all visible headlines.
6620 The region to be covered depends on STATE when called through
6621 `org-cycle-hook'. Lisp program can use t for STATE to get the
6622 entire buffer covered. Note that an empty line is only shown if there
6623 are at least `org-cycle-separator-lines' empty lines before the headline."
6624 (when (not (= org-cycle-separator-lines 0))
6625 (save-excursion
6626 (let* ((n (abs org-cycle-separator-lines))
6627 (re (cond
6628 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6629 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6630 (t (let ((ns (number-to-string (- n 2))))
6631 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6632 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6633 beg end b e)
6634 (cond
6635 ((memq state '(overview contents t))
6636 (setq beg (point-min) end (point-max)))
6637 ((memq state '(children folded))
6638 (setq beg (point) end (progn (org-end-of-subtree t t)
6639 (beginning-of-line 2)
6640 (point)))))
6641 (when beg
6642 (goto-char beg)
6643 (while (re-search-forward re end t)
6644 (unless (get-char-property (match-end 1) 'invisible)
6645 (setq e (match-end 1))
6646 (if (< org-cycle-separator-lines 0)
6647 (setq b (save-excursion
6648 (goto-char (match-beginning 0))
6649 (org-back-over-empty-lines)
6650 (if (save-excursion
6651 (goto-char (max (point-min) (1- (point))))
6652 (org-at-heading-p))
6653 (1- (point))
6654 (point))))
6655 (setq b (match-beginning 1)))
6656 (outline-flag-region b e nil)))))))
6657 ;; Never hide empty lines at the end of the file.
6658 (save-excursion
6659 (goto-char (point-max))
6660 (outline-previous-heading)
6661 (outline-end-of-heading)
6662 (if (and (looking-at "[ \t\n]+")
6663 (= (match-end 0) (point-max)))
6664 (outline-flag-region (point) (match-end 0) nil))))
6666 (defun org-show-empty-lines-in-parent ()
6667 "Move to the parent and re-show empty lines before visible headlines."
6668 (save-excursion
6669 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6670 (org-cycle-show-empty-lines context))))
6672 (defun org-files-list ()
6673 "Return `org-agenda-files' list, plus all open org-mode files.
6674 This is useful for operations that need to scan all of a user's
6675 open and agenda-wise Org files."
6676 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6677 (dolist (buf (buffer-list))
6678 (with-current-buffer buf
6679 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6680 (let ((file (expand-file-name (buffer-file-name))))
6681 (unless (member file files)
6682 (push file files))))))
6683 files))
6685 (defsubst org-entry-beginning-position ()
6686 "Return the beginning position of the current entry."
6687 (save-excursion (outline-back-to-heading t) (point)))
6689 (defsubst org-entry-end-position ()
6690 "Return the end position of the current entry."
6691 (save-excursion (outline-next-heading) (point)))
6693 (defun org-cycle-hide-drawers (state)
6694 "Re-hide all drawers after a visibility state change."
6695 (when (and (derived-mode-p 'org-mode)
6696 (not (memq state '(overview folded contents))))
6697 (save-excursion
6698 (let* ((globalp (memq state '(contents all)))
6699 (beg (if globalp (point-min) (point)))
6700 (end (if globalp (point-max)
6701 (if (eq state 'children)
6702 (save-excursion (outline-next-heading) (point))
6703 (org-end-of-subtree t)))))
6704 (goto-char beg)
6705 (while (re-search-forward org-drawer-regexp end t)
6706 (org-flag-drawer t))))))
6708 (defun org-flag-drawer (flag)
6709 "When FLAG is non-nil, hide the drawer we are within.
6710 Otherwise make it visible."
6711 (save-excursion
6712 (beginning-of-line 1)
6713 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6714 (let ((b (match-end 0)))
6715 (if (re-search-forward
6716 "^[ \t]*:END:"
6717 (save-excursion (outline-next-heading) (point)) t)
6718 (outline-flag-region b (point-at-eol) flag)
6719 (error ":END: line missing at position %s" b))))))
6721 (defun org-subtree-end-visible-p ()
6722 "Is the end of the current subtree visible?"
6723 (pos-visible-in-window-p
6724 (save-excursion (org-end-of-subtree t) (point))))
6726 (defun org-first-headline-recenter (&optional N)
6727 "Move cursor to the first headline and recenter the headline.
6728 Optional argument N means put the headline into the Nth line of the window."
6729 (goto-char (point-min))
6730 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6731 (beginning-of-line)
6732 (recenter (prefix-numeric-value N))))
6734 ;;; Saving and restoring visibility
6736 (defun org-outline-overlay-data (&optional use-markers)
6737 "Return a list of the locations of all outline overlays.
6738 These are overlays with the `invisible' property value `outline'.
6739 The return value is a list of cons cells, with start and stop
6740 positions for each overlay.
6741 If USE-MARKERS is set, return the positions as markers."
6742 (let (beg end)
6743 (save-excursion
6744 (save-restriction
6745 (widen)
6746 (delq nil
6747 (mapcar (lambda (o)
6748 (when (eq (overlay-get o 'invisible) 'outline)
6749 (setq beg (overlay-start o)
6750 end (overlay-end o))
6751 (and beg end (> end beg)
6752 (if use-markers
6753 (cons (move-marker (make-marker) beg)
6754 (move-marker (make-marker) end))
6755 (cons beg end)))))
6756 (overlays-in (point-min) (point-max))))))))
6758 (defun org-set-outline-overlay-data (data)
6759 "Create visibility overlays for all positions in DATA.
6760 DATA should have been made by `org-outline-overlay-data'."
6761 (let (o)
6762 (save-excursion
6763 (save-restriction
6764 (widen)
6765 (show-all)
6766 (mapc (lambda (c)
6767 (outline-flag-region (car c) (cdr c) t))
6768 data)))))
6770 ;;; Folding of blocks
6772 (defvar org-hide-block-overlays nil
6773 "Overlays hiding blocks.")
6774 (make-variable-buffer-local 'org-hide-block-overlays)
6776 (defun org-block-map (function &optional start end)
6777 "Call FUNCTION at the head of all source blocks in the current buffer.
6778 Optional arguments START and END can be used to limit the range."
6779 (let ((start (or start (point-min)))
6780 (end (or end (point-max))))
6781 (save-excursion
6782 (goto-char start)
6783 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6784 (save-excursion
6785 (save-match-data
6786 (goto-char (match-beginning 0))
6787 (funcall function)))))))
6789 (defun org-hide-block-toggle-all ()
6790 "Toggle the visibility of all blocks in the current buffer."
6791 (org-block-map #'org-hide-block-toggle))
6793 (defun org-hide-block-all ()
6794 "Fold all blocks in the current buffer."
6795 (interactive)
6796 (org-show-block-all)
6797 (org-block-map #'org-hide-block-toggle-maybe))
6799 (defun org-show-block-all ()
6800 "Unfold all blocks in the current buffer."
6801 (interactive)
6802 (mapc 'delete-overlay org-hide-block-overlays)
6803 (setq org-hide-block-overlays nil))
6805 (defun org-hide-block-toggle-maybe ()
6806 "Toggle visibility of block at point."
6807 (interactive)
6808 (let ((case-fold-search t))
6809 (if (save-excursion
6810 (beginning-of-line 1)
6811 (looking-at org-block-regexp))
6812 (progn (org-hide-block-toggle)
6813 t) ;; to signal that we took action
6814 nil))) ;; to signal that we did not
6816 (defun org-hide-block-toggle (&optional force)
6817 "Toggle the visibility of the current block."
6818 (interactive)
6819 (save-excursion
6820 (beginning-of-line)
6821 (if (re-search-forward org-block-regexp nil t)
6822 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6823 (end (match-end 0)) ;; end of entire body
6825 (if (memq t (mapcar (lambda (overlay)
6826 (eq (overlay-get overlay 'invisible)
6827 'org-hide-block))
6828 (overlays-at start)))
6829 (if (or (not force) (eq force 'off))
6830 (mapc (lambda (ov)
6831 (when (member ov org-hide-block-overlays)
6832 (setq org-hide-block-overlays
6833 (delq ov org-hide-block-overlays)))
6834 (when (eq (overlay-get ov 'invisible)
6835 'org-hide-block)
6836 (delete-overlay ov)))
6837 (overlays-at start)))
6838 (setq ov (make-overlay start end))
6839 (overlay-put ov 'invisible 'org-hide-block)
6840 ;; make the block accessible to isearch
6841 (overlay-put
6842 ov 'isearch-open-invisible
6843 (lambda (ov)
6844 (when (member ov org-hide-block-overlays)
6845 (setq org-hide-block-overlays
6846 (delq ov org-hide-block-overlays)))
6847 (when (eq (overlay-get ov 'invisible)
6848 'org-hide-block)
6849 (delete-overlay ov))))
6850 (push ov org-hide-block-overlays)))
6851 (error "Not looking at a source block"))))
6853 ;; org-tab-after-check-for-cycling-hook
6854 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6855 ;; Remove overlays when changing major mode
6856 (add-hook 'org-mode-hook
6857 (lambda () (org-add-hook 'change-major-mode-hook
6858 'org-show-block-all 'append 'local)))
6860 ;;; Org-goto
6862 (defvar org-goto-window-configuration nil)
6863 (defvar org-goto-marker nil)
6864 (defvar org-goto-map
6865 (let ((map (make-sparse-keymap)))
6866 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6867 (while (setq cmd (pop cmds))
6868 (substitute-key-definition cmd cmd map global-map)))
6869 (suppress-keymap map)
6870 (org-defkey map "\C-m" 'org-goto-ret)
6871 (org-defkey map [(return)] 'org-goto-ret)
6872 (org-defkey map [(left)] 'org-goto-left)
6873 (org-defkey map [(right)] 'org-goto-right)
6874 (org-defkey map [(control ?g)] 'org-goto-quit)
6875 (org-defkey map "\C-i" 'org-cycle)
6876 (org-defkey map [(tab)] 'org-cycle)
6877 (org-defkey map [(down)] 'outline-next-visible-heading)
6878 (org-defkey map [(up)] 'outline-previous-visible-heading)
6879 (if org-goto-auto-isearch
6880 (if (fboundp 'define-key-after)
6881 (define-key-after map [t] 'org-goto-local-auto-isearch)
6882 nil)
6883 (org-defkey map "q" 'org-goto-quit)
6884 (org-defkey map "n" 'outline-next-visible-heading)
6885 (org-defkey map "p" 'outline-previous-visible-heading)
6886 (org-defkey map "f" 'outline-forward-same-level)
6887 (org-defkey map "b" 'outline-backward-same-level)
6888 (org-defkey map "u" 'outline-up-heading))
6889 (org-defkey map "/" 'org-occur)
6890 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6891 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6892 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6893 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6894 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6895 map))
6897 (defconst org-goto-help
6898 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6899 RET=jump to location [Q]uit and return to previous location
6900 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6902 (defvar org-goto-start-pos) ; dynamically scoped parameter
6904 ;; FIXME: Docstring does not mention both interfaces
6905 (defun org-goto (&optional alternative-interface)
6906 "Look up a different location in the current file, keeping current visibility.
6908 When you want look-up or go to a different location in a
6909 document, the fastest way is often to fold the entire buffer and
6910 then dive into the tree. This method has the disadvantage, that
6911 the previous location will be folded, which may not be what you
6912 want.
6914 This command works around this by showing a copy of the current
6915 buffer in an indirect buffer, in overview mode. You can dive
6916 into the tree in that copy, use org-occur and incremental search
6917 to find a location. When pressing RET or `Q', the command
6918 returns to the original buffer in which the visibility is still
6919 unchanged. After RET it will also jump to the location selected
6920 in the indirect buffer and expose the headline hierarchy above.
6922 With a prefix argument, use the alternative interface: e.g. if
6923 `org-goto-interface' is 'outline use 'outline-path-completion."
6924 (interactive "P")
6925 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6926 (org-refile-use-outline-path t)
6927 (org-refile-target-verify-function nil)
6928 (interface
6929 (if (not alternative-interface)
6930 org-goto-interface
6931 (if (eq org-goto-interface 'outline)
6932 'outline-path-completion
6933 'outline)))
6934 (org-goto-start-pos (point))
6935 (selected-point
6936 (if (eq interface 'outline)
6937 (car (org-get-location (current-buffer) org-goto-help))
6938 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6939 (org-refile-check-position pa)
6940 (nth 3 pa)))))
6941 (if selected-point
6942 (progn
6943 (org-mark-ring-push org-goto-start-pos)
6944 (goto-char selected-point)
6945 (if (or (outline-invisible-p) (org-invisible-p2))
6946 (org-show-context 'org-goto)))
6947 (message "Quit"))))
6949 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6950 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6951 (defvar org-goto-local-auto-isearch-map) ; defined below
6953 (defun org-get-location (buf help)
6954 "Let the user select a location in the Org-mode buffer BUF.
6955 This function uses a recursive edit. It returns the selected position
6956 or nil."
6957 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6958 (isearch-hide-immediately nil)
6959 (isearch-search-fun-function
6960 (lambda () 'org-goto-local-search-headings))
6961 (org-goto-selected-point org-goto-exit-command)
6962 (pop-up-frames nil)
6963 (special-display-buffer-names nil)
6964 (special-display-regexps nil)
6965 (special-display-function nil))
6966 (save-excursion
6967 (save-window-excursion
6968 (delete-other-windows)
6969 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6970 (org-pop-to-buffer-same-window
6971 (condition-case nil
6972 (make-indirect-buffer (current-buffer) "*org-goto*")
6973 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6974 (with-output-to-temp-buffer "*Help*"
6975 (princ help))
6976 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6977 (setq buffer-read-only nil)
6978 (let ((org-startup-truncated t)
6979 (org-startup-folded nil)
6980 (org-startup-align-all-tables nil))
6981 (org-mode)
6982 (org-overview))
6983 (setq buffer-read-only t)
6984 (if (and (boundp 'org-goto-start-pos)
6985 (integer-or-marker-p org-goto-start-pos))
6986 (let ((org-show-hierarchy-above t)
6987 (org-show-siblings t)
6988 (org-show-following-heading t))
6989 (goto-char org-goto-start-pos)
6990 (and (outline-invisible-p) (org-show-context)))
6991 (goto-char (point-min)))
6992 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6993 (message "Select location and press RET")
6994 (use-local-map org-goto-map)
6995 (recursive-edit)
6997 (kill-buffer "*org-goto*")
6998 (cons org-goto-selected-point org-goto-exit-command)))
7000 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7001 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7002 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7003 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7005 (defun org-goto-local-search-headings (string bound noerror)
7006 "Search and make sure that any matches are in headlines."
7007 (catch 'return
7008 (while (if isearch-forward
7009 (search-forward string bound noerror)
7010 (search-backward string bound noerror))
7011 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7012 (and (member :headline context)
7013 (not (member :tags context))))
7014 (throw 'return (point))))))
7016 (defun org-goto-local-auto-isearch ()
7017 "Start isearch."
7018 (interactive)
7019 (goto-char (point-min))
7020 (let ((keys (this-command-keys)))
7021 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7022 (isearch-mode t)
7023 (isearch-process-search-char (string-to-char keys)))))
7025 (defun org-goto-ret (&optional arg)
7026 "Finish `org-goto' by going to the new location."
7027 (interactive "P")
7028 (setq org-goto-selected-point (point)
7029 org-goto-exit-command 'return)
7030 (throw 'exit nil))
7032 (defun org-goto-left ()
7033 "Finish `org-goto' by going to the new location."
7034 (interactive)
7035 (if (org-at-heading-p)
7036 (progn
7037 (beginning-of-line 1)
7038 (setq org-goto-selected-point (point)
7039 org-goto-exit-command 'left)
7040 (throw 'exit nil))
7041 (error "Not on a heading")))
7043 (defun org-goto-right ()
7044 "Finish `org-goto' by going to the new location."
7045 (interactive)
7046 (if (org-at-heading-p)
7047 (progn
7048 (setq org-goto-selected-point (point)
7049 org-goto-exit-command 'right)
7050 (throw 'exit nil))
7051 (error "Not on a heading")))
7053 (defun org-goto-quit ()
7054 "Finish `org-goto' without cursor motion."
7055 (interactive)
7056 (setq org-goto-selected-point nil)
7057 (setq org-goto-exit-command 'quit)
7058 (throw 'exit nil))
7060 ;;; Indirect buffer display of subtrees
7062 (defvar org-indirect-dedicated-frame nil
7063 "This is the frame being used for indirect tree display.")
7064 (defvar org-last-indirect-buffer nil)
7066 (defun org-tree-to-indirect-buffer (&optional arg)
7067 "Create indirect buffer and narrow it to current subtree.
7068 With numerical prefix ARG, go up to this level and then take that tree.
7069 If ARG is negative, go up that many levels.
7070 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7071 indirect buffer previously made with this command, to avoid proliferation of
7072 indirect buffers. However, when you call the command with a \
7073 \\[universal-argument] prefix, or
7074 when `org-indirect-buffer-display' is `new-frame', the last buffer
7075 is kept so that you can work with several indirect buffers at the same time.
7076 If `org-indirect-buffer-display' is `dedicated-frame', the \
7077 \\[universal-argument] prefix also
7078 requests that a new frame be made for the new buffer, so that the dedicated
7079 frame is not changed."
7080 (interactive "P")
7081 (let ((cbuf (current-buffer))
7082 (cwin (selected-window))
7083 (pos (point))
7084 beg end level heading ibuf)
7085 (save-excursion
7086 (org-back-to-heading t)
7087 (when (numberp arg)
7088 (setq level (org-outline-level))
7089 (if (< arg 0) (setq arg (+ level arg)))
7090 (while (> (setq level (org-outline-level)) arg)
7091 (outline-up-heading 1 t)))
7092 (setq beg (point)
7093 heading (org-get-heading))
7094 (org-end-of-subtree t t)
7095 (if (org-at-heading-p) (backward-char 1))
7096 (setq end (point)))
7097 (if (and (buffer-live-p org-last-indirect-buffer)
7098 (not (eq org-indirect-buffer-display 'new-frame))
7099 (not arg))
7100 (kill-buffer org-last-indirect-buffer))
7101 (setq ibuf (org-get-indirect-buffer cbuf)
7102 org-last-indirect-buffer ibuf)
7103 (cond
7104 ((or (eq org-indirect-buffer-display 'new-frame)
7105 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7106 (select-frame (make-frame))
7107 (delete-other-windows)
7108 (org-pop-to-buffer-same-window ibuf)
7109 (org-set-frame-title heading))
7110 ((eq org-indirect-buffer-display 'dedicated-frame)
7111 (raise-frame
7112 (select-frame (or (and org-indirect-dedicated-frame
7113 (frame-live-p org-indirect-dedicated-frame)
7114 org-indirect-dedicated-frame)
7115 (setq org-indirect-dedicated-frame (make-frame)))))
7116 (delete-other-windows)
7117 (org-pop-to-buffer-same-window ibuf)
7118 (org-set-frame-title (concat "Indirect: " heading)))
7119 ((eq org-indirect-buffer-display 'current-window)
7120 (org-pop-to-buffer-same-window ibuf))
7121 ((eq org-indirect-buffer-display 'other-window)
7122 (pop-to-buffer ibuf))
7123 (t (error "Invalid value")))
7124 (if (featurep 'xemacs)
7125 (save-excursion (org-mode) (turn-on-font-lock)))
7126 (narrow-to-region beg end)
7127 (show-all)
7128 (goto-char pos)
7129 (run-hook-with-args 'org-cycle-hook 'all)
7130 (and (window-live-p cwin) (select-window cwin))))
7132 (defun org-get-indirect-buffer (&optional buffer)
7133 (setq buffer (or buffer (current-buffer)))
7134 (let ((n 1) (base (buffer-name buffer)) bname)
7135 (while (buffer-live-p
7136 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7137 (setq n (1+ n)))
7138 (condition-case nil
7139 (make-indirect-buffer buffer bname 'clone)
7140 (error (make-indirect-buffer buffer bname)))))
7142 (defun org-set-frame-title (title)
7143 "Set the title of the current frame to the string TITLE."
7144 ;; FIXME: how to name a single frame in XEmacs???
7145 (unless (featurep 'xemacs)
7146 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7148 ;;;; Structure editing
7150 ;;; Inserting headlines
7152 (defun org-previous-line-empty-p ()
7153 (save-excursion
7154 (and (not (bobp))
7155 (or (beginning-of-line 0) t)
7156 (save-match-data
7157 (looking-at "[ \t]*$")))))
7159 (defun org-insert-heading (&optional force-heading invisible-ok)
7160 "Insert a new heading or item with same depth at point.
7161 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7162 If point is at the beginning of a headline, insert a sibling before the
7163 current headline. If point is not at the beginning, split the line,
7164 create the new headline with the text in the current line after point
7165 \(but see also the variable `org-M-RET-may-split-line').
7167 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7168 This is important for non-interactive uses of the command."
7169 (interactive "P")
7170 (if (or (= (buffer-size) 0)
7171 (and (not (save-excursion
7172 (and (ignore-errors (org-back-to-heading invisible-ok))
7173 (org-at-heading-p))))
7174 (or force-heading (not (org-in-item-p)))))
7175 (progn
7176 (insert "\n* ")
7177 (run-hooks 'org-insert-heading-hook))
7178 (when (or force-heading (not (org-insert-item)))
7179 (let* ((empty-line-p nil)
7180 (level nil)
7181 (on-heading (org-at-heading-p))
7182 (head (save-excursion
7183 (condition-case nil
7184 (progn
7185 (org-back-to-heading invisible-ok)
7186 (when (and (not on-heading)
7187 (featurep 'org-inlinetask)
7188 (integerp org-inlinetask-min-level)
7189 (>= (length (match-string 0))
7190 org-inlinetask-min-level))
7191 ;; Find a heading level before the inline task
7192 (while (and (setq level (org-up-heading-safe))
7193 (>= level org-inlinetask-min-level)))
7194 (if (org-at-heading-p)
7195 (org-back-to-heading invisible-ok)
7196 (error "This should not happen")))
7197 (setq empty-line-p (org-previous-line-empty-p))
7198 (match-string 0))
7199 (error "*"))))
7200 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7201 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7202 pos hide-previous previous-pos)
7203 (cond
7204 ((and (org-at-heading-p) (bolp)
7205 (or (bobp)
7206 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7207 ;; insert before the current line
7208 (open-line (if blank 2 1)))
7209 ((and (bolp)
7210 (not org-insert-heading-respect-content)
7211 (or (bobp)
7212 (save-excursion
7213 (backward-char 1) (not (outline-invisible-p)))))
7214 ;; insert right here
7215 nil)
7217 ;; somewhere in the line
7218 (save-excursion
7219 (setq previous-pos (point-at-bol))
7220 (end-of-line)
7221 (setq hide-previous (outline-invisible-p)))
7222 (and org-insert-heading-respect-content (org-show-subtree))
7223 (let ((split
7224 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7225 (save-excursion
7226 (let ((p (point)))
7227 (goto-char (point-at-bol))
7228 (and (looking-at org-complex-heading-regexp)
7229 (match-beginning 4)
7230 (> p (match-beginning 4)))))))
7231 tags pos)
7232 (cond
7233 (org-insert-heading-respect-content
7234 (org-end-of-subtree nil t)
7235 (when (featurep 'org-inlinetask)
7236 (while (and (not (eobp))
7237 (looking-at "\\(\\*+\\)[ \t]+")
7238 (>= (length (match-string 1))
7239 org-inlinetask-min-level))
7240 (org-end-of-subtree nil t)))
7241 (or (bolp) (newline))
7242 (or (org-previous-line-empty-p)
7243 (and blank (newline)))
7244 (open-line 1))
7245 ((org-at-heading-p)
7246 (when hide-previous
7247 (show-children)
7248 (org-show-entry))
7249 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7250 (setq tags (and (match-end 2) (match-string 2)))
7251 (and (match-end 1)
7252 (delete-region (match-beginning 1) (match-end 1)))
7253 (setq pos (point-at-bol))
7254 (or split (end-of-line 1))
7255 (delete-horizontal-space)
7256 (if (string-match "\\`\\*+\\'"
7257 (buffer-substring (point-at-bol) (point)))
7258 (insert " "))
7259 (newline (if blank 2 1))
7260 (when tags
7261 (save-excursion
7262 (goto-char pos)
7263 (end-of-line 1)
7264 (insert " " tags)
7265 (org-set-tags nil 'align))))
7267 (or split (end-of-line 1))
7268 (newline (if blank 2 1)))))))
7269 (insert head) (just-one-space)
7270 (setq pos (point))
7271 (end-of-line 1)
7272 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7273 (when (and org-insert-heading-respect-content hide-previous)
7274 (save-excursion
7275 (goto-char previous-pos)
7276 (hide-subtree)))
7277 (run-hooks 'org-insert-heading-hook)))))
7279 (defun org-get-heading (&optional no-tags no-todo)
7280 "Return the heading of the current entry, without the stars.
7281 When NO-TAGS is non-nil, don't include tags.
7282 When NO-TODO is non-nil, don't include TODO keywords."
7283 (save-excursion
7284 (org-back-to-heading t)
7285 (cond
7286 ((and no-tags no-todo)
7287 (looking-at org-complex-heading-regexp)
7288 (match-string 4))
7289 (no-tags
7290 (looking-at (concat org-outline-regexp
7291 "\\(.*?\\)"
7292 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7293 (match-string 1))
7294 (no-todo
7295 (looking-at org-todo-line-regexp)
7296 (match-string 3))
7297 (t (looking-at org-heading-regexp)
7298 (match-string 2)))))
7300 (defun org-heading-components ()
7301 "Return the components of the current heading.
7302 This is a list with the following elements:
7303 - the level as an integer
7304 - the reduced level, different if `org-odd-levels-only' is set.
7305 - the TODO keyword, or nil
7306 - the priority character, like ?A, or nil if no priority is given
7307 - the headline text itself, or the tags string if no headline text
7308 - the tags string, or nil."
7309 (save-excursion
7310 (org-back-to-heading t)
7311 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7312 (list (length (match-string 1))
7313 (org-reduced-level (length (match-string 1)))
7314 (org-match-string-no-properties 2)
7315 (and (match-end 3) (aref (match-string 3) 2))
7316 (org-match-string-no-properties 4)
7317 (org-match-string-no-properties 5)))))
7319 (defun org-get-entry ()
7320 "Get the entry text, after heading, entire subtree."
7321 (save-excursion
7322 (org-back-to-heading t)
7323 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7325 (defun org-insert-heading-after-current ()
7326 "Insert a new heading with same level as current, after current subtree."
7327 (interactive)
7328 (org-back-to-heading)
7329 (org-insert-heading)
7330 (org-move-subtree-down)
7331 (end-of-line 1))
7333 (defun org-insert-heading-respect-content ()
7334 (interactive)
7335 (let ((org-insert-heading-respect-content t))
7336 (org-insert-heading t)))
7338 (defun org-insert-todo-heading-respect-content (&optional force-state)
7339 (interactive "P")
7340 (let ((org-insert-heading-respect-content t))
7341 (org-insert-todo-heading force-state t)))
7343 (defun org-insert-todo-heading (arg &optional force-heading)
7344 "Insert a new heading with the same level and TODO state as current heading.
7345 If the heading has no TODO state, or if the state is DONE, use the first
7346 state (TODO by default). Also with prefix arg, force first state."
7347 (interactive "P")
7348 (when (or force-heading (not (org-insert-item 'checkbox)))
7349 (org-insert-heading force-heading)
7350 (save-excursion
7351 (org-back-to-heading)
7352 (outline-previous-heading)
7353 (looking-at org-todo-line-regexp))
7354 (let*
7355 ((new-mark-x
7356 (if (or arg
7357 (not (match-beginning 2))
7358 (member (match-string 2) org-done-keywords))
7359 (car org-todo-keywords-1)
7360 (match-string 2)))
7361 (new-mark
7363 (run-hook-with-args-until-success
7364 'org-todo-get-default-hook new-mark-x nil)
7365 new-mark-x)))
7366 (beginning-of-line 1)
7367 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7368 (if org-treat-insert-todo-heading-as-state-change
7369 (org-todo new-mark)
7370 (insert new-mark " "))))
7371 (when org-provide-todo-statistics
7372 (org-update-parent-todo-statistics))))
7374 (defun org-insert-subheading (arg)
7375 "Insert a new subheading and demote it.
7376 Works for outline headings and for plain lists alike."
7377 (interactive "P")
7378 (org-insert-heading arg)
7379 (cond
7380 ((org-at-heading-p) (org-do-demote))
7381 ((org-at-item-p) (org-indent-item))))
7383 (defun org-insert-todo-subheading (arg)
7384 "Insert a new subheading with TODO keyword or checkbox and demote it.
7385 Works for outline headings and for plain lists alike."
7386 (interactive "P")
7387 (org-insert-todo-heading arg)
7388 (cond
7389 ((org-at-heading-p) (org-do-demote))
7390 ((org-at-item-p) (org-indent-item))))
7392 ;;; Promotion and Demotion
7394 (defvar org-after-demote-entry-hook nil
7395 "Hook run after an entry has been demoted.
7396 The cursor will be at the beginning of the entry.
7397 When a subtree is being demoted, the hook will be called for each node.")
7399 (defvar org-after-promote-entry-hook nil
7400 "Hook run after an entry has been promoted.
7401 The cursor will be at the beginning of the entry.
7402 When a subtree is being promoted, the hook will be called for each node.")
7404 (defun org-promote-subtree ()
7405 "Promote the entire subtree.
7406 See also `org-promote'."
7407 (interactive)
7408 (save-excursion
7409 (org-with-limited-levels (org-map-tree 'org-promote)))
7410 (org-fix-position-after-promote))
7412 (defun org-demote-subtree ()
7413 "Demote the entire subtree. See `org-demote'.
7414 See also `org-promote'."
7415 (interactive)
7416 (save-excursion
7417 (org-with-limited-levels (org-map-tree 'org-demote)))
7418 (org-fix-position-after-promote))
7421 (defun org-do-promote ()
7422 "Promote the current heading higher up the tree.
7423 If the region is active in `transient-mark-mode', promote all headings
7424 in the region."
7425 (interactive)
7426 (save-excursion
7427 (if (org-region-active-p)
7428 (org-map-region 'org-promote (region-beginning) (region-end))
7429 (org-promote)))
7430 (org-fix-position-after-promote))
7432 (defun org-do-demote ()
7433 "Demote the current heading lower down the tree.
7434 If the region is active in `transient-mark-mode', demote all headings
7435 in the region."
7436 (interactive)
7437 (save-excursion
7438 (if (org-region-active-p)
7439 (org-map-region 'org-demote (region-beginning) (region-end))
7440 (org-demote)))
7441 (org-fix-position-after-promote))
7443 (defun org-fix-position-after-promote ()
7444 "Make sure that after pro/demotion cursor position is right."
7445 (let ((pos (point)))
7446 (when (save-excursion
7447 (beginning-of-line 1)
7448 (looking-at org-todo-line-regexp)
7449 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7450 (cond ((eobp) (insert " "))
7451 ((eolp) (insert " "))
7452 ((equal (char-after) ?\ ) (forward-char 1))))))
7454 (defun org-current-level ()
7455 "Return the level of the current entry, or nil if before the first headline.
7456 The level is the number of stars at the beginning of the headline."
7457 (save-excursion
7458 (org-with-limited-levels
7459 (if (ignore-errors (org-back-to-heading t))
7460 (funcall outline-level)))))
7462 (defun org-get-previous-line-level ()
7463 "Return the outline depth of the last headline before the current line.
7464 Returns 0 for the first headline in the buffer, and nil if before the
7465 first headline."
7466 (let ((current-level (org-current-level))
7467 (prev-level (when (> (line-number-at-pos) 1)
7468 (save-excursion
7469 (beginning-of-line 0)
7470 (org-current-level)))))
7471 (cond ((null current-level) nil) ; Before first headline
7472 ((null prev-level) 0) ; At first headline
7473 (prev-level))))
7475 (defun org-reduced-level (l)
7476 "Compute the effective level of a heading.
7477 This takes into account the setting of `org-odd-levels-only'."
7478 (cond
7479 ((zerop l) 0)
7480 (org-odd-levels-only (1+ (floor (/ l 2))))
7481 (t l)))
7483 (defun org-level-increment ()
7484 "Return the number of stars that will be added or removed at a
7485 time to headlines when structure editing, based on the value of
7486 `org-odd-levels-only'."
7487 (if org-odd-levels-only 2 1))
7489 (defun org-get-valid-level (level &optional change)
7490 "Rectify a level change under the influence of `org-odd-levels-only'
7491 LEVEL is a current level, CHANGE is by how much the level should be
7492 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7493 even level numbers will become the next higher odd number."
7494 (if org-odd-levels-only
7495 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7496 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7497 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7498 (max 1 (+ level (or change 0)))))
7500 (if (boundp 'define-obsolete-function-alias)
7501 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7502 (define-obsolete-function-alias 'org-get-legal-level
7503 'org-get-valid-level)
7504 (define-obsolete-function-alias 'org-get-legal-level
7505 'org-get-valid-level "23.1")))
7507 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7508 ;; ̀org-with-limited-levels'
7509 (defun org-promote ()
7510 "Promote the current heading higher up the tree.
7511 If the region is active in `transient-mark-mode', promote all headings
7512 in the region."
7513 (org-back-to-heading t)
7514 (let* ((level (save-match-data (funcall outline-level)))
7515 (after-change-functions (remove 'flyspell-after-change-function
7516 after-change-functions))
7517 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7518 (diff (abs (- level (length up-head) -1))))
7519 (cond ((and (= level 1) org-called-with-limited-levels
7520 org-allow-promoting-top-level-subtree)
7521 (replace-match "# " nil t))
7522 ((= level 1)
7523 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7524 (t (replace-match up-head nil t)))
7525 ;; Fixup tag positioning
7526 (unless (= level 1)
7527 (and org-auto-align-tags (org-set-tags nil t))
7528 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7529 (run-hooks 'org-after-promote-entry-hook)))
7531 (defun org-demote ()
7532 "Demote the current heading lower down the tree.
7533 If the region is active in `transient-mark-mode', demote all headings
7534 in the region."
7535 (org-back-to-heading t)
7536 (let* ((level (save-match-data (funcall outline-level)))
7537 (after-change-functions (remove 'flyspell-after-change-function
7538 after-change-functions))
7539 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7540 (diff (abs (- level (length down-head) -1))))
7541 (replace-match down-head nil t)
7542 ;; Fixup tag positioning
7543 (and org-auto-align-tags (org-set-tags nil t))
7544 (if org-adapt-indentation (org-fixup-indentation diff))
7545 (run-hooks 'org-after-demote-entry-hook)))
7547 (defun org-cycle-level ()
7548 "Cycle the level of an empty headline through possible states.
7549 This goes first to child, then to parent, level, then up the hierarchy.
7550 After top level, it switches back to sibling level."
7551 (interactive)
7552 (let ((org-adapt-indentation nil))
7553 (when (org-point-at-end-of-empty-headline)
7554 (setq this-command 'org-cycle-level) ; Only needed for caching
7555 (let ((cur-level (org-current-level))
7556 (prev-level (org-get-previous-line-level)))
7557 (cond
7558 ;; If first headline in file, promote to top-level.
7559 ((= prev-level 0)
7560 (loop repeat (/ (- cur-level 1) (org-level-increment))
7561 do (org-do-promote)))
7562 ;; If same level as prev, demote one.
7563 ((= prev-level cur-level)
7564 (org-do-demote))
7565 ;; If parent is top-level, promote to top level if not already.
7566 ((= prev-level 1)
7567 (loop repeat (/ (- cur-level 1) (org-level-increment))
7568 do (org-do-promote)))
7569 ;; If top-level, return to prev-level.
7570 ((= cur-level 1)
7571 (loop repeat (/ (- prev-level 1) (org-level-increment))
7572 do (org-do-demote)))
7573 ;; If less than prev-level, promote one.
7574 ((< cur-level prev-level)
7575 (org-do-promote))
7576 ;; If deeper than prev-level, promote until higher than
7577 ;; prev-level.
7578 ((> cur-level prev-level)
7579 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7580 do (org-do-promote))))
7581 t))))
7583 (defun org-map-tree (fun)
7584 "Call FUN for every heading underneath the current one."
7585 (org-back-to-heading)
7586 (let ((level (funcall outline-level)))
7587 (save-excursion
7588 (funcall fun)
7589 (while (and (progn
7590 (outline-next-heading)
7591 (> (funcall outline-level) level))
7592 (not (eobp)))
7593 (funcall fun)))))
7595 (defun org-map-region (fun beg end)
7596 "Call FUN for every heading between BEG and END."
7597 (let ((org-ignore-region t))
7598 (save-excursion
7599 (setq end (copy-marker end))
7600 (goto-char beg)
7601 (if (and (re-search-forward org-outline-regexp-bol nil t)
7602 (< (point) end))
7603 (funcall fun))
7604 (while (and (progn
7605 (outline-next-heading)
7606 (< (point) end))
7607 (not (eobp)))
7608 (funcall fun)))))
7610 (defvar org-property-end-re) ; silence byte-compiler
7611 (defun org-fixup-indentation (diff)
7612 "Change the indentation in the current entry by DIFF.
7613 However, if any line in the current entry has no indentation, or if it
7614 would end up with no indentation after the change, nothing at all is done."
7615 (save-excursion
7616 (let ((end (save-excursion (outline-next-heading)
7617 (point-marker)))
7618 (prohibit (if (> diff 0)
7619 "^\\S-"
7620 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7621 col)
7622 (unless (save-excursion (end-of-line 1)
7623 (re-search-forward prohibit end t))
7624 (while (and (< (point) end)
7625 (re-search-forward "^[ \t]+" end t))
7626 (goto-char (match-end 0))
7627 (setq col (current-column))
7628 (if (< diff 0) (replace-match ""))
7629 (org-indent-to-column (+ diff col))))
7630 (move-marker end nil))))
7632 (defun org-convert-to-odd-levels ()
7633 "Convert an org-mode file with all levels allowed to one with odd levels.
7634 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7635 level 5 etc."
7636 (interactive)
7637 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7638 (let ((outline-level 'org-outline-level)
7639 (org-odd-levels-only nil) n)
7640 (save-excursion
7641 (goto-char (point-min))
7642 (while (re-search-forward "^\\*\\*+ " nil t)
7643 (setq n (- (length (match-string 0)) 2))
7644 (while (>= (setq n (1- n)) 0)
7645 (org-demote))
7646 (end-of-line 1))))))
7648 (defun org-convert-to-oddeven-levels ()
7649 "Convert an org-mode file with only odd levels to one with odd/even levels.
7650 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7651 file contains a section with an even level, conversion would
7652 destroy the structure of the file. An error is signaled in this
7653 case."
7654 (interactive)
7655 (goto-char (point-min))
7656 ;; First check if there are no even levels
7657 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7658 (org-show-context t)
7659 (error "Not all levels are odd in this file. Conversion not possible"))
7660 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7661 (let ((outline-regexp org-outline-regexp)
7662 (outline-level 'org-outline-level)
7663 (org-odd-levels-only nil) n)
7664 (save-excursion
7665 (goto-char (point-min))
7666 (while (re-search-forward "^\\*\\*+ " nil t)
7667 (setq n (/ (1- (length (match-string 0))) 2))
7668 (while (>= (setq n (1- n)) 0)
7669 (org-promote))
7670 (end-of-line 1))))))
7672 (defun org-tr-level (n)
7673 "Make N odd if required."
7674 (if org-odd-levels-only (1+ (/ n 2)) n))
7676 ;;; Vertical tree motion, cutting and pasting of subtrees
7678 (defun org-move-subtree-up (&optional arg)
7679 "Move the current subtree up past ARG headlines of the same level."
7680 (interactive "p")
7681 (org-move-subtree-down (- (prefix-numeric-value arg))))
7683 (defun org-move-subtree-down (&optional arg)
7684 "Move the current subtree down past ARG headlines of the same level."
7685 (interactive "p")
7686 (setq arg (prefix-numeric-value arg))
7687 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7688 'org-get-last-sibling))
7689 (ins-point (make-marker))
7690 (cnt (abs arg))
7691 (col (current-column))
7692 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7693 ;; Select the tree
7694 (org-back-to-heading)
7695 (setq beg0 (point))
7696 (save-excursion
7697 (setq ne-beg (org-back-over-empty-lines))
7698 (setq beg (point)))
7699 (save-match-data
7700 (save-excursion (outline-end-of-heading)
7701 (setq folded (outline-invisible-p)))
7702 (outline-end-of-subtree))
7703 (outline-next-heading)
7704 (setq ne-end (org-back-over-empty-lines))
7705 (setq end (point))
7706 (goto-char beg0)
7707 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7708 ;; include less whitespace
7709 (save-excursion
7710 (goto-char beg)
7711 (forward-line (- ne-beg ne-end))
7712 (setq beg (point))))
7713 ;; Find insertion point, with error handling
7714 (while (> cnt 0)
7715 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7716 (progn (goto-char beg0)
7717 (error "Cannot move past superior level or buffer limit")))
7718 (setq cnt (1- cnt)))
7719 (if (> arg 0)
7720 ;; Moving forward - still need to move over subtree
7721 (progn (org-end-of-subtree t t)
7722 (save-excursion
7723 (org-back-over-empty-lines)
7724 (or (bolp) (newline)))))
7725 (setq ne-ins (org-back-over-empty-lines))
7726 (move-marker ins-point (point))
7727 (setq txt (buffer-substring beg end))
7728 (org-save-markers-in-region beg end)
7729 (delete-region beg end)
7730 (org-remove-empty-overlays-at beg)
7731 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7732 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7733 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7734 (let ((bbb (point)))
7735 (insert-before-markers txt)
7736 (org-reinstall-markers-in-region bbb)
7737 (move-marker ins-point bbb))
7738 (or (bolp) (insert "\n"))
7739 (setq ins-end (point))
7740 (goto-char ins-point)
7741 (org-skip-whitespace)
7742 (when (and (< arg 0)
7743 (org-first-sibling-p)
7744 (> ne-ins ne-beg))
7745 ;; Move whitespace back to beginning
7746 (save-excursion
7747 (goto-char ins-end)
7748 (let ((kill-whole-line t))
7749 (kill-line (- ne-ins ne-beg)) (point)))
7750 (insert (make-string (- ne-ins ne-beg) ?\n)))
7751 (move-marker ins-point nil)
7752 (if folded
7753 (hide-subtree)
7754 (org-show-entry)
7755 (show-children)
7756 (org-cycle-hide-drawers 'children))
7757 (org-clean-visibility-after-subtree-move)
7758 ;; move back to the initial column we were at
7759 (move-to-column col)))
7761 (defvar org-subtree-clip ""
7762 "Clipboard for cut and paste of subtrees.
7763 This is actually only a copy of the kill, because we use the normal kill
7764 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7766 (defvar org-subtree-clip-folded nil
7767 "Was the last copied subtree folded?
7768 This is used to fold the tree back after pasting.")
7770 (defun org-cut-subtree (&optional n)
7771 "Cut the current subtree into the clipboard.
7772 With prefix arg N, cut this many sequential subtrees.
7773 This is a short-hand for marking the subtree and then cutting it."
7774 (interactive "p")
7775 (org-copy-subtree n 'cut))
7777 (defun org-copy-subtree (&optional n cut force-store-markers)
7778 "Cut the current subtree into the clipboard.
7779 With prefix arg N, cut this many sequential subtrees.
7780 This is a short-hand for marking the subtree and then copying it.
7781 If CUT is non-nil, actually cut the subtree.
7782 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7783 of some markers in the region, even if CUT is non-nil. This is
7784 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7785 (interactive "p")
7786 (let (beg end folded (beg0 (point)))
7787 (if (org-called-interactively-p 'any)
7788 (org-back-to-heading nil) ; take what looks like a subtree
7789 (org-back-to-heading t)) ; take what is really there
7790 (org-back-over-empty-lines)
7791 (setq beg (point))
7792 (skip-chars-forward " \t\r\n")
7793 (save-match-data
7794 (save-excursion (outline-end-of-heading)
7795 (setq folded (outline-invisible-p)))
7796 (condition-case nil
7797 (org-forward-same-level (1- n) t)
7798 (error nil))
7799 (org-end-of-subtree t t))
7800 (org-back-over-empty-lines)
7801 (setq end (point))
7802 (goto-char beg0)
7803 (when (> end beg)
7804 (setq org-subtree-clip-folded folded)
7805 (when (or cut force-store-markers)
7806 (org-save-markers-in-region beg end))
7807 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7808 (setq org-subtree-clip (current-kill 0))
7809 (message "%s: Subtree(s) with %d characters"
7810 (if cut "Cut" "Copied")
7811 (length org-subtree-clip)))))
7813 (defun org-paste-subtree (&optional level tree for-yank)
7814 "Paste the clipboard as a subtree, with modification of headline level.
7815 The entire subtree is promoted or demoted in order to match a new headline
7816 level.
7818 If the cursor is at the beginning of a headline, the same level as
7819 that headline is used to paste the tree
7821 If not, the new level is derived from the *visible* headings
7822 before and after the insertion point, and taken to be the inferior headline
7823 level of the two. So if the previous visible heading is level 3 and the
7824 next is level 4 (or vice versa), level 4 will be used for insertion.
7825 This makes sure that the subtree remains an independent subtree and does
7826 not swallow low level entries.
7828 You can also force a different level, either by using a numeric prefix
7829 argument, or by inserting the heading marker by hand. For example, if the
7830 cursor is after \"*****\", then the tree will be shifted to level 5.
7832 If optional TREE is given, use this text instead of the kill ring.
7834 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7835 move back over whitespace before inserting, and move point to the end of
7836 the inserted text when done."
7837 (interactive "P")
7838 (setq tree (or tree (and kill-ring (current-kill 0))))
7839 (unless (org-kill-is-subtree-p tree)
7840 (error "%s"
7841 (substitute-command-keys
7842 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7843 (org-with-limited-levels
7844 (let* ((visp (not (outline-invisible-p)))
7845 (txt tree)
7846 (^re_ "\\(\\*+\\)[ \t]*")
7847 (old-level (if (string-match org-outline-regexp-bol txt)
7848 (- (match-end 0) (match-beginning 0) 1)
7849 -1))
7850 (force-level (cond (level (prefix-numeric-value level))
7851 ((and (looking-at "[ \t]*$")
7852 (string-match
7853 "^\\*+$" (buffer-substring
7854 (point-at-bol) (point))))
7855 (- (match-end 1) (match-beginning 1)))
7856 ((and (bolp)
7857 (looking-at org-outline-regexp))
7858 (- (match-end 0) (point) 1))
7859 (t nil)))
7860 (previous-level (save-excursion
7861 (condition-case nil
7862 (progn
7863 (outline-previous-visible-heading 1)
7864 (if (looking-at ^re_)
7865 (- (match-end 0) (match-beginning 0) 1)
7867 (error 1))))
7868 (next-level (save-excursion
7869 (condition-case nil
7870 (progn
7871 (or (looking-at org-outline-regexp)
7872 (outline-next-visible-heading 1))
7873 (if (looking-at ^re_)
7874 (- (match-end 0) (match-beginning 0) 1)
7876 (error 1))))
7877 (new-level (or force-level (max previous-level next-level)))
7878 (shift (if (or (= old-level -1)
7879 (= new-level -1)
7880 (= old-level new-level))
7882 (- new-level old-level)))
7883 (delta (if (> shift 0) -1 1))
7884 (func (if (> shift 0) 'org-demote 'org-promote))
7885 (org-odd-levels-only nil)
7886 beg end newend)
7887 ;; Remove the forced level indicator
7888 (if force-level
7889 (delete-region (point-at-bol) (point)))
7890 ;; Paste
7891 (beginning-of-line (if (bolp) 1 2))
7892 (unless for-yank (org-back-over-empty-lines))
7893 (setq beg (point))
7894 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7895 (insert-before-markers txt)
7896 (unless (string-match "\n\\'" txt) (insert "\n"))
7897 (setq newend (point))
7898 (org-reinstall-markers-in-region beg)
7899 (setq end (point))
7900 (goto-char beg)
7901 (skip-chars-forward " \t\n\r")
7902 (setq beg (point))
7903 (if (and (outline-invisible-p) visp)
7904 (save-excursion (outline-show-heading)))
7905 ;; Shift if necessary
7906 (unless (= shift 0)
7907 (save-restriction
7908 (narrow-to-region beg end)
7909 (while (not (= shift 0))
7910 (org-map-region func (point-min) (point-max))
7911 (setq shift (+ delta shift)))
7912 (goto-char (point-min))
7913 (setq newend (point-max))))
7914 (when (or (org-called-interactively-p 'interactive) for-yank)
7915 (message "Clipboard pasted as level %d subtree" new-level))
7916 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7917 kill-ring
7918 (eq org-subtree-clip (current-kill 0))
7919 org-subtree-clip-folded)
7920 ;; The tree was folded before it was killed/copied
7921 (hide-subtree))
7922 (and for-yank (goto-char newend)))))
7924 (defun org-kill-is-subtree-p (&optional txt)
7925 "Check if the current kill is an outline subtree, or a set of trees.
7926 Returns nil if kill does not start with a headline, or if the first
7927 headline level is not the largest headline level in the tree.
7928 So this will actually accept several entries of equal levels as well,
7929 which is OK for `org-paste-subtree'.
7930 If optional TXT is given, check this string instead of the current kill."
7931 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7932 (re (org-get-limited-outline-regexp))
7933 (^re (concat "^" re))
7934 (start-level (and kill
7935 (string-match
7936 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7937 kill)
7938 (- (match-end 2) (match-beginning 2) 1)))
7939 (start (1+ (or (match-beginning 2) -1))))
7940 (if (not start-level)
7941 (progn
7942 nil) ;; does not even start with a heading
7943 (catch 'exit
7944 (while (setq start (string-match ^re kill (1+ start)))
7945 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7946 (throw 'exit nil)))
7947 t))))
7949 (defvar org-markers-to-move nil
7950 "Markers that should be moved with a cut-and-paste operation.
7951 Those markers are stored together with their positions relative to
7952 the start of the region.")
7954 (defun org-save-markers-in-region (beg end)
7955 "Check markers in region.
7956 If these markers are between BEG and END, record their position relative
7957 to BEG, so that after moving the block of text, we can put the markers back
7958 into place.
7959 This function gets called just before an entry or tree gets cut from the
7960 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7961 called immediately, to move the markers with the entries."
7962 (setq org-markers-to-move nil)
7963 (when (featurep 'org-clock)
7964 (org-clock-save-markers-for-cut-and-paste beg end))
7965 (when (featurep 'org-agenda)
7966 (org-agenda-save-markers-for-cut-and-paste beg end)))
7968 (defun org-check-and-save-marker (marker beg end)
7969 "Check if MARKER is between BEG and END.
7970 If yes, remember the marker and the distance to BEG."
7971 (when (and (marker-buffer marker)
7972 (equal (marker-buffer marker) (current-buffer)))
7973 (if (and (>= marker beg) (< marker end))
7974 (push (cons marker (- marker beg)) org-markers-to-move))))
7976 (defun org-reinstall-markers-in-region (beg)
7977 "Move all remembered markers to their position relative to BEG."
7978 (mapc (lambda (x)
7979 (move-marker (car x) (+ beg (cdr x))))
7980 org-markers-to-move)
7981 (setq org-markers-to-move nil))
7983 (defun org-narrow-to-subtree ()
7984 "Narrow buffer to the current subtree."
7985 (interactive)
7986 (save-excursion
7987 (save-match-data
7988 (org-with-limited-levels
7989 (narrow-to-region
7990 (progn (org-back-to-heading t) (point))
7991 (progn (org-end-of-subtree t t)
7992 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7993 (point)))))))
7995 (defun org-narrow-to-block ()
7996 "Narrow buffer to the current block."
7997 (interactive)
7998 (let* ((case-fold-search t)
7999 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8000 "^[ \t]*#\\+end_.*")))
8001 (if blockp
8002 (narrow-to-region (car blockp) (cdr blockp))
8003 (error "Not in a block"))))
8005 (eval-when-compile
8006 (defvar org-property-drawer-re))
8008 (defvar org-property-start-re) ;; defined below
8009 (defun org-clone-subtree-with-time-shift (n &optional shift)
8010 "Clone the task (subtree) at point N times.
8011 The clones will be inserted as siblings.
8013 In interactive use, the user will be prompted for the number of
8014 clones to be produced, and for a time SHIFT, which may be a
8015 repeater as used in time stamps, for example `+3d'.
8017 When a valid repeater is given and the entry contains any time
8018 stamps, the clones will become a sequence in time, with time
8019 stamps in the subtree shifted for each clone produced. If SHIFT
8020 is nil or the empty string, time stamps will be left alone. The
8021 ID property of the original subtree is removed.
8023 If the original subtree did contain time stamps with a repeater,
8024 the following will happen:
8025 - the repeater will be removed in each clone
8026 - an additional clone will be produced, with the current, unshifted
8027 date(s) in the entry.
8028 - the original entry will be placed *after* all the clones, with
8029 repeater intact.
8030 - the start days in the repeater in the original entry will be shifted
8031 to past the last clone.
8032 In this way you can spell out a number of instances of a repeating task,
8033 and still retain the repeater to cover future instances of the task."
8034 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8035 (let (beg end template task idprop
8036 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8037 (drawer-re org-drawer-regexp))
8038 (if (not (and (integerp n) (> n 0)))
8039 (error "Invalid number of replications %s" n))
8040 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8041 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8042 shift)))
8043 (error "Invalid shift specification %s" shift))
8044 (when doshift
8045 (setq shift-n (string-to-number (match-string 1 shift))
8046 shift-what (cdr (assoc (match-string 2 shift)
8047 '(("d" . day) ("w" . week)
8048 ("m" . month) ("y" . year))))))
8049 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8050 (setq nmin 1 nmax n)
8051 (org-back-to-heading t)
8052 (setq beg (point))
8053 (setq idprop (org-entry-get nil "ID"))
8054 (org-end-of-subtree t t)
8055 (or (bolp) (insert "\n"))
8056 (setq end (point))
8057 (setq template (buffer-substring beg end))
8058 (when (and doshift
8059 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8060 (delete-region beg end)
8061 (setq end beg)
8062 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8063 (goto-char end)
8064 (loop for n from nmin to nmax do
8065 ;; prepare clone
8066 (with-temp-buffer
8067 (insert template)
8068 (org-mode)
8069 (goto-char (point-min))
8070 (org-show-subtree)
8071 (and idprop (if org-clone-delete-id
8072 (org-entry-delete nil "ID")
8073 (org-id-get-create t)))
8074 (unless (= n 0)
8075 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8076 (kill-whole-line))
8077 (goto-char (point-min))
8078 (while (re-search-forward drawer-re nil t)
8079 (mapc (lambda (d)
8080 (org-remove-empty-drawer-at d (point))) org-drawers)))
8081 (goto-char (point-min))
8082 (when doshift
8083 (while (re-search-forward org-ts-regexp-both nil t)
8084 (org-timestamp-change (* n shift-n) shift-what))
8085 (unless (= n n-no-remove)
8086 (goto-char (point-min))
8087 (while (re-search-forward org-ts-regexp nil t)
8088 (save-excursion
8089 (goto-char (match-beginning 0))
8090 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8091 (delete-region (match-beginning 1) (match-end 1)))))))
8092 (setq task (buffer-string)))
8093 (insert task))
8094 (goto-char beg)))
8096 ;;; Outline Sorting
8098 (defun org-sort (with-case)
8099 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8100 Optional argument WITH-CASE means sort case-sensitively."
8101 (interactive "P")
8102 (cond
8103 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8104 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8106 (org-call-with-arg 'org-sort-entries with-case))))
8108 (defun org-sort-remove-invisible (s)
8109 (remove-text-properties 0 (length s) org-rm-props s)
8110 (while (string-match org-bracket-link-regexp s)
8111 (setq s (replace-match (if (match-end 2)
8112 (match-string 3 s)
8113 (match-string 1 s)) t t s)))
8116 (defvar org-priority-regexp) ; defined later in the file
8118 (defvar org-after-sorting-entries-or-items-hook nil
8119 "Hook that is run after a bunch of entries or items have been sorted.
8120 When children are sorted, the cursor is in the parent line when this
8121 hook gets called. When a region or a plain list is sorted, the cursor
8122 will be in the first entry of the sorted region/list.")
8124 (defun org-sort-entries
8125 (&optional with-case sorting-type getkey-func compare-func property)
8126 "Sort entries on a certain level of an outline tree.
8127 If there is an active region, the entries in the region are sorted.
8128 Else, if the cursor is before the first entry, sort the top-level items.
8129 Else, the children of the entry at point are sorted.
8131 Sorting can be alphabetically, numerically, by date/time as given by
8132 a time stamp, by a property or by priority.
8134 The command prompts for the sorting type unless it has been given to the
8135 function through the SORTING-TYPE argument, which needs to be a character,
8136 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8137 precise meaning of each character:
8139 n Numerically, by converting the beginning of the entry/item to a number.
8140 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8141 t By date/time, either the first active time stamp in the entry, or, if
8142 none exist, by the first inactive one.
8143 s By the scheduled date/time.
8144 d By deadline date/time.
8145 c By creation time, which is assumed to be the first inactive time stamp
8146 at the beginning of a line.
8147 p By priority according to the cookie.
8148 r By the value of a property.
8150 Capital letters will reverse the sort order.
8152 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8153 called with point at the beginning of the record. It must return either
8154 a string or a number that should serve as the sorting key for that record.
8156 Comparing entries ignores case by default. However, with an optional argument
8157 WITH-CASE, the sorting considers case as well."
8158 (interactive "P")
8159 (let ((case-func (if with-case 'identity 'downcase))
8160 start beg end stars re re2
8161 txt what tmp)
8162 ;; Find beginning and end of region to sort
8163 (cond
8164 ((org-region-active-p)
8165 ;; we will sort the region
8166 (setq end (region-end)
8167 what "region")
8168 (goto-char (region-beginning))
8169 (if (not (org-at-heading-p)) (outline-next-heading))
8170 (setq start (point)))
8171 ((or (org-at-heading-p)
8172 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8173 ;; we will sort the children of the current headline
8174 (org-back-to-heading)
8175 (setq start (point)
8176 end (progn (org-end-of-subtree t t)
8177 (or (bolp) (insert "\n"))
8178 (org-back-over-empty-lines)
8179 (point))
8180 what "children")
8181 (goto-char start)
8182 (show-subtree)
8183 (outline-next-heading))
8185 ;; we will sort the top-level entries in this file
8186 (goto-char (point-min))
8187 (or (org-at-heading-p) (outline-next-heading))
8188 (setq start (point))
8189 (goto-char (point-max))
8190 (beginning-of-line 1)
8191 (when (looking-at ".*?\\S-")
8192 ;; File ends in a non-white line
8193 (end-of-line 1)
8194 (insert "\n"))
8195 (setq end (point-max))
8196 (setq what "top-level")
8197 (goto-char start)
8198 (show-all)))
8200 (setq beg (point))
8201 (if (>= beg end) (error "Nothing to sort"))
8203 (looking-at "\\(\\*+\\)")
8204 (setq stars (match-string 1)
8205 re (concat "^" (regexp-quote stars) " +")
8206 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8207 txt (buffer-substring beg end))
8208 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8209 (if (and (not (equal stars "*")) (string-match re2 txt))
8210 (error "Region to sort contains a level above the first entry"))
8212 (unless sorting-type
8213 (message
8214 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8215 [t]ime [s]cheduled [d]eadline [c]reated
8216 A/N/T/S/D/C/P/O/F means reversed:"
8217 what)
8218 (setq sorting-type (read-char-exclusive))
8220 (and (= (downcase sorting-type) ?f)
8221 (setq getkey-func
8222 (org-icompleting-read "Sort using function: "
8223 obarray 'fboundp t nil nil))
8224 (setq getkey-func (intern getkey-func)))
8226 (and (= (downcase sorting-type) ?r)
8227 (setq property
8228 (org-icompleting-read "Property: "
8229 (mapcar 'list (org-buffer-property-keys t))
8230 nil t))))
8232 (message "Sorting entries...")
8234 (save-restriction
8235 (narrow-to-region start end)
8236 (let ((dcst (downcase sorting-type))
8237 (case-fold-search nil)
8238 (now (current-time)))
8239 (sort-subr
8240 (/= dcst sorting-type)
8241 ;; This function moves to the beginning character of the "record" to
8242 ;; be sorted.
8243 (lambda nil
8244 (if (re-search-forward re nil t)
8245 (goto-char (match-beginning 0))
8246 (goto-char (point-max))))
8247 ;; This function moves to the last character of the "record" being
8248 ;; sorted.
8249 (lambda nil
8250 (save-match-data
8251 (condition-case nil
8252 (outline-forward-same-level 1)
8253 (error
8254 (goto-char (point-max))))))
8255 ;; This function returns the value that gets sorted against.
8256 (lambda nil
8257 (cond
8258 ((= dcst ?n)
8259 (if (looking-at org-complex-heading-regexp)
8260 (string-to-number (match-string 4))
8261 nil))
8262 ((= dcst ?a)
8263 (if (looking-at org-complex-heading-regexp)
8264 (funcall case-func (match-string 4))
8265 nil))
8266 ((= dcst ?t)
8267 (let ((end (save-excursion (outline-next-heading) (point))))
8268 (if (or (re-search-forward org-ts-regexp end t)
8269 (re-search-forward org-ts-regexp-both end t))
8270 (org-time-string-to-seconds (match-string 0))
8271 (org-float-time now))))
8272 ((= dcst ?c)
8273 (let ((end (save-excursion (outline-next-heading) (point))))
8274 (if (re-search-forward
8275 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8276 end t)
8277 (org-time-string-to-seconds (match-string 0))
8278 (org-float-time now))))
8279 ((= dcst ?s)
8280 (let ((end (save-excursion (outline-next-heading) (point))))
8281 (if (re-search-forward org-scheduled-time-regexp end t)
8282 (org-time-string-to-seconds (match-string 1))
8283 (org-float-time now))))
8284 ((= dcst ?d)
8285 (let ((end (save-excursion (outline-next-heading) (point))))
8286 (if (re-search-forward org-deadline-time-regexp end t)
8287 (org-time-string-to-seconds (match-string 1))
8288 (org-float-time now))))
8289 ((= dcst ?p)
8290 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8291 (string-to-char (match-string 2))
8292 org-default-priority))
8293 ((= dcst ?r)
8294 (or (org-entry-get nil property) ""))
8295 ((= dcst ?o)
8296 (if (looking-at org-complex-heading-regexp)
8297 (- 9999 (length (member (match-string 2)
8298 org-todo-keywords-1)))))
8299 ((= dcst ?f)
8300 (if getkey-func
8301 (progn
8302 (setq tmp (funcall getkey-func))
8303 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8304 tmp)
8305 (error "Invalid key function `%s'" getkey-func)))
8306 (t (error "Invalid sorting type `%c'" sorting-type))))
8308 (cond
8309 ((= dcst ?a) 'string<)
8310 ((= dcst ?f) compare-func)
8311 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8312 (t nil)))))
8313 (run-hooks 'org-after-sorting-entries-or-items-hook)
8314 (message "Sorting entries...done")))
8316 (defun org-do-sort (table what &optional with-case sorting-type)
8317 "Sort TABLE of WHAT according to SORTING-TYPE.
8318 The user will be prompted for the SORTING-TYPE if the call to this
8319 function does not specify it. WHAT is only for the prompt, to indicate
8320 what is being sorted. The sorting key will be extracted from
8321 the car of the elements of the table.
8322 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8323 (unless sorting-type
8324 (message
8325 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8326 what)
8327 (setq sorting-type (read-char-exclusive)))
8328 (let ((dcst (downcase sorting-type))
8329 extractfun comparefun)
8330 ;; Define the appropriate functions
8331 (cond
8332 ((= dcst ?n)
8333 (setq extractfun 'string-to-number
8334 comparefun (if (= dcst sorting-type) '< '>)))
8335 ((= dcst ?a)
8336 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8337 (lambda(x) (downcase (org-sort-remove-invisible x))))
8338 comparefun (if (= dcst sorting-type)
8339 'string<
8340 (lambda (a b) (and (not (string< a b))
8341 (not (string= a b)))))))
8342 ((= dcst ?t)
8343 (setq extractfun
8344 (lambda (x)
8345 (if (or (string-match org-ts-regexp x)
8346 (string-match org-ts-regexp-both x))
8347 (org-float-time
8348 (org-time-string-to-time (match-string 0 x)))
8350 comparefun (if (= dcst sorting-type) '< '>)))
8351 (t (error "Invalid sorting type `%c'" sorting-type)))
8353 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8354 table)
8355 (lambda (a b) (funcall comparefun (car a) (car b))))))
8358 ;;; The orgstruct minor mode
8360 ;; Define a minor mode which can be used in other modes in order to
8361 ;; integrate the org-mode structure editing commands.
8363 ;; This is really a hack, because the org-mode structure commands use
8364 ;; keys which normally belong to the major mode. Here is how it
8365 ;; works: The minor mode defines all the keys necessary to operate the
8366 ;; structure commands, but wraps the commands into a function which
8367 ;; tests if the cursor is currently at a headline or a plain list
8368 ;; item. If that is the case, the structure command is used,
8369 ;; temporarily setting many Org-mode variables like regular
8370 ;; expressions for filling etc. However, when any of those keys is
8371 ;; used at a different location, function uses `key-binding' to look
8372 ;; up if the key has an associated command in another currently active
8373 ;; keymap (minor modes, major mode, global), and executes that
8374 ;; command. There might be problems if any of the keys is otherwise
8375 ;; used as a prefix key.
8377 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8378 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8379 ;; addresses this by checking explicitly for both bindings.
8381 (defvar orgstruct-mode-map (make-sparse-keymap)
8382 "Keymap for the minor `orgstruct-mode'.")
8384 (defvar org-local-vars nil
8385 "List of local variables, for use by `orgstruct-mode'.")
8387 ;;;###autoload
8388 (define-minor-mode orgstruct-mode
8389 "Toggle the minor mode `orgstruct-mode'.
8390 This mode is for using Org-mode structure commands in other
8391 modes. The following keys behave as if Org-mode were active, if
8392 the cursor is on a headline, or on a plain list item (both as
8393 defined by Org-mode).
8395 M-up Move entry/item up
8396 M-down Move entry/item down
8397 M-left Promote
8398 M-right Demote
8399 M-S-up Move entry/item up
8400 M-S-down Move entry/item down
8401 M-S-left Promote subtree
8402 M-S-right Demote subtree
8403 M-q Fill paragraph and items like in Org-mode
8404 C-c ^ Sort entries
8405 C-c - Cycle list bullet
8406 TAB Cycle item visibility
8407 M-RET Insert new heading/item
8408 S-M-RET Insert new TODO heading / Checkbox item
8409 C-c C-c Set tags / toggle checkbox"
8410 nil " OrgStruct" nil
8411 (org-load-modules-maybe)
8412 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8414 ;;;###autoload
8415 (defun turn-on-orgstruct ()
8416 "Unconditionally turn on `orgstruct-mode'."
8417 (orgstruct-mode 1))
8419 (defvar org-fb-vars nil)
8420 (make-variable-buffer-local 'org-fb-vars)
8421 (defun orgstruct++-mode (&optional arg)
8422 "Toggle `orgstruct-mode', the enhanced version of it.
8423 In addition to setting orgstruct-mode, this also exports all
8424 indentation and autofilling variables from org-mode into the
8425 buffer. It will also recognize item context in multiline items."
8426 (interactive "P")
8427 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8428 (if (< arg 1)
8429 (progn (orgstruct-mode -1)
8430 (mapc (lambda(v)
8431 (org-set-local (car v)
8432 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8433 org-fb-vars))
8434 (orgstruct-mode 1)
8435 (setq org-fb-vars nil)
8436 (let (var val)
8437 (mapc
8438 (lambda (x)
8439 (when (string-match
8440 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8441 (symbol-name (car x)))
8442 (setq var (car x) val (nth 1 x))
8443 (push (list var `(quote ,(eval var))) org-fb-vars)
8444 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8445 org-local-vars)
8446 (org-set-local 'orgstruct-is-++ t))))
8448 (defvar orgstruct-is-++ nil
8449 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8450 (make-variable-buffer-local 'orgstruct-is-++)
8452 ;;;###autoload
8453 (defun turn-on-orgstruct++ ()
8454 "Unconditionally turn on `orgstruct++-mode'."
8455 (orgstruct++-mode 1))
8457 (defun orgstruct-error ()
8458 "Error when there is no default binding for a structure key."
8459 (interactive)
8460 (error "This key has no function outside structure elements"))
8462 (defun orgstruct-setup ()
8463 "Setup orgstruct keymaps."
8464 (let ((nfunc 0)
8465 (bindings
8466 (list
8467 '([(meta up)] org-metaup)
8468 '([(meta down)] org-metadown)
8469 '([(meta left)] org-metaleft)
8470 '([(meta right)] org-metaright)
8471 '([(meta shift up)] org-shiftmetaup)
8472 '([(meta shift down)] org-shiftmetadown)
8473 '([(meta shift left)] org-shiftmetaleft)
8474 '([(meta shift right)] org-shiftmetaright)
8475 '([?\e (up)] org-metaup)
8476 '([?\e (down)] org-metadown)
8477 '([?\e (left)] org-metaleft)
8478 '([?\e (right)] org-metaright)
8479 '([?\e (shift up)] org-shiftmetaup)
8480 '([?\e (shift down)] org-shiftmetadown)
8481 '([?\e (shift left)] org-shiftmetaleft)
8482 '([?\e (shift right)] org-shiftmetaright)
8483 '([(shift up)] org-shiftup)
8484 '([(shift down)] org-shiftdown)
8485 '([(shift left)] org-shiftleft)
8486 '([(shift right)] org-shiftright)
8487 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8488 '("\M-q" fill-paragraph)
8489 '("\C-c^" org-sort)
8490 '("\C-c-" org-cycle-list-bullet)))
8491 elt key fun cmd)
8492 (while (setq elt (pop bindings))
8493 (setq nfunc (1+ nfunc))
8494 (setq key (org-key (car elt))
8495 fun (nth 1 elt)
8496 cmd (orgstruct-make-binding fun nfunc key))
8497 (org-defkey orgstruct-mode-map key cmd))
8499 ;; Special treatment needed for TAB and RET
8500 (org-defkey orgstruct-mode-map [(tab)]
8501 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8502 (org-defkey orgstruct-mode-map "\C-i"
8503 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8505 (org-defkey orgstruct-mode-map "\M-\C-m"
8506 (orgstruct-make-binding 'org-insert-heading 105
8507 "\M-\C-m" [(meta return)]))
8508 (org-defkey orgstruct-mode-map [(meta return)]
8509 (orgstruct-make-binding 'org-insert-heading 106
8510 [(meta return)] "\M-\C-m"))
8512 (org-defkey orgstruct-mode-map [(shift meta return)]
8513 (orgstruct-make-binding 'org-insert-todo-heading 107
8514 [(meta return)] "\M-\C-m"))
8516 (org-defkey orgstruct-mode-map "\e\C-m"
8517 (orgstruct-make-binding 'org-insert-heading 108
8518 "\e\C-m" [?\e (return)]))
8519 (org-defkey orgstruct-mode-map [?\e (return)]
8520 (orgstruct-make-binding 'org-insert-heading 109
8521 [?\e (return)] "\e\C-m"))
8522 (org-defkey orgstruct-mode-map [?\e (shift return)]
8523 (orgstruct-make-binding 'org-insert-todo-heading 110
8524 [?\e (return)] "\e\C-m"))
8526 (unless org-local-vars
8527 (setq org-local-vars (org-get-local-variables)))
8531 (defun orgstruct-make-binding (fun n &rest keys)
8532 "Create a function for binding in the structure minor mode.
8533 FUN is the command to call inside a table. N is used to create a unique
8534 command name. KEYS are keys that should be checked in for a command
8535 to execute outside of tables."
8536 (eval
8537 (list 'defun
8538 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8539 '(arg)
8540 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8541 "Outside of structure, run the binding of `"
8542 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8543 "'.")
8544 '(interactive "p")
8545 (list 'if
8546 `(org-context-p 'headline 'item
8547 (and orgstruct-is-++
8548 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8549 'item-body))
8550 (list 'org-run-like-in-org-mode (list 'quote fun))
8551 (list 'let '(orgstruct-mode)
8552 (list 'call-interactively
8553 (append '(or)
8554 (mapcar (lambda (k)
8555 (list 'key-binding k))
8556 keys)
8557 '('orgstruct-error))))))))
8559 (defun org-context-p (&rest contexts)
8560 "Check if local context is any of CONTEXTS.
8561 Possible values in the list of contexts are `table', `headline', and `item'."
8562 (let ((pos (point)))
8563 (goto-char (point-at-bol))
8564 (prog1 (or (and (memq 'table contexts)
8565 (looking-at "[ \t]*|"))
8566 (and (memq 'headline contexts)
8567 (looking-at org-outline-regexp))
8568 (and (memq 'item contexts)
8569 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8570 (and (memq 'item-body contexts)
8571 (org-in-item-p)))
8572 (goto-char pos))))
8574 (defun org-get-local-variables ()
8575 "Return a list of all local variables in an org-mode buffer."
8576 (let (varlist)
8577 (with-current-buffer (get-buffer-create "*Org tmp*")
8578 (erase-buffer)
8579 (org-mode)
8580 (setq varlist (buffer-local-variables)))
8581 (kill-buffer "*Org tmp*")
8582 (delq nil
8583 (mapcar
8584 (lambda (x)
8585 (setq x
8586 (if (symbolp x)
8587 (list x)
8588 (list (car x) (list 'quote (cdr x)))))
8589 (if (string-match
8590 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8591 (symbol-name (car x)))
8592 x nil))
8593 varlist))))
8595 (defun org-clone-local-variables (from-buffer &optional regexp)
8596 "Clone local variables from FROM-BUFFER.
8597 Optional argument REGEXP selects variables to clone."
8598 (mapc
8599 (lambda (pair)
8600 (and (symbolp (car pair))
8601 (or (null regexp)
8602 (string-match regexp (symbol-name (car pair))))
8603 (set (make-local-variable (car pair))
8604 (cdr pair))))
8605 (buffer-local-variables from-buffer)))
8607 ;;;###autoload
8608 (defun org-run-like-in-org-mode (cmd)
8609 "Run a command, pretending that the current buffer is in Org-mode.
8610 This will temporarily bind local variables that are typically bound in
8611 Org-mode to the values they have in Org-mode, and then interactively
8612 call CMD."
8613 (org-load-modules-maybe)
8614 (unless org-local-vars
8615 (setq org-local-vars (org-get-local-variables)))
8616 (eval (list 'let org-local-vars
8617 (list 'call-interactively (list 'quote cmd)))))
8619 ;;;; Archiving
8621 (defun org-get-category (&optional pos force-refresh)
8622 "Get the category applying to position POS."
8623 (save-match-data
8624 (if force-refresh (org-refresh-category-properties))
8625 (let ((pos (or pos (point))))
8626 (or (get-text-property pos 'org-category)
8627 (progn (org-refresh-category-properties)
8628 (get-text-property pos 'org-category))))))
8630 (defun org-refresh-category-properties ()
8631 "Refresh category text properties in the buffer."
8632 (let ((inhibit-read-only t)
8633 (def-cat (cond
8634 ((null org-category)
8635 (if buffer-file-name
8636 (file-name-sans-extension
8637 (file-name-nondirectory buffer-file-name))
8638 "???"))
8639 ((symbolp org-category) (symbol-name org-category))
8640 (t org-category)))
8641 beg end cat pos optionp)
8642 (org-unmodified
8643 (save-excursion
8644 (save-restriction
8645 (widen)
8646 (goto-char (point-min))
8647 (put-text-property (point) (point-max) 'org-category def-cat)
8648 (while (re-search-forward
8649 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8650 (setq pos (match-end 0)
8651 optionp (equal (char-after (match-beginning 0)) ?#)
8652 cat (org-trim (match-string 2)))
8653 (if optionp
8654 (setq beg (point-at-bol) end (point-max))
8655 (org-back-to-heading t)
8656 (setq beg (point) end (org-end-of-subtree t t)))
8657 (put-text-property beg end 'org-category cat)
8658 (put-text-property beg end 'org-category-position beg)
8659 (goto-char pos)))))))
8662 ;;;; Link Stuff
8664 ;;; Link abbreviations
8666 (defun org-link-expand-abbrev (link)
8667 "Apply replacements as defined in `org-link-abbrev-alist'."
8668 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8669 (let* ((key (match-string 1 link))
8670 (as (or (assoc key org-link-abbrev-alist-local)
8671 (assoc key org-link-abbrev-alist)))
8672 (tag (and (match-end 2) (match-string 3 link)))
8673 rpl)
8674 (if (not as)
8675 link
8676 (setq rpl (cdr as))
8677 (cond
8678 ((symbolp rpl) (funcall rpl tag))
8679 ((string-match "%(\\([^)]+\\))" rpl)
8680 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8681 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8682 ((string-match "%h" rpl)
8683 (replace-match (url-hexify-string (or tag "")) t t rpl))
8684 (t (concat rpl tag)))))
8685 link))
8687 ;;; Storing and inserting links
8689 (defvar org-insert-link-history nil
8690 "Minibuffer history for links inserted with `org-insert-link'.")
8692 (defvar org-stored-links nil
8693 "Contains the links stored with `org-store-link'.")
8695 (defvar org-store-link-plist nil
8696 "Plist with info about the most recently link created with `org-store-link'.")
8698 (defvar org-link-protocols nil
8699 "Link protocols added to Org-mode using `org-add-link-type'.")
8701 (defvar org-store-link-functions nil
8702 "List of functions that are called to create and store a link.
8703 Each function will be called in turn until one returns a non-nil
8704 value. Each function should check if it is responsible for creating
8705 this link (for example by looking at the major mode).
8706 If not, it must exit and return nil.
8707 If yes, it should return a non-nil value after a calling
8708 `org-store-link-props' with a list of properties and values.
8709 Special properties are:
8711 :type The link prefix, like \"http\". This must be given.
8712 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8713 This is obligatory as well.
8714 :description Optional default description for the second pair
8715 of brackets in an Org-mode link. The user can still change
8716 this when inserting this link into an Org-mode buffer.
8718 In addition to these, any additional properties can be specified
8719 and then used in remember templates.")
8721 (defun org-add-link-type (type &optional follow export)
8722 "Add TYPE to the list of `org-link-types'.
8723 Re-compute all regular expressions depending on `org-link-types'
8725 FOLLOW and EXPORT are two functions.
8727 FOLLOW should take the link path as the single argument and do whatever
8728 is necessary to follow the link, for example find a file or display
8729 a mail message.
8731 EXPORT should format the link path for export to one of the export formats.
8732 It should be a function accepting three arguments:
8734 path the path of the link, the text after the prefix (like \"http:\")
8735 desc the description of the link, if any, or a description added by
8736 org-export-normalize-links if there is none
8737 format the export format, a symbol like `html' or `latex' or `ascii'..
8739 The function may use the FORMAT information to return different values
8740 depending on the format. The return value will be put literally into
8741 the exported file. If the return value is nil, this means Org should
8742 do what it normally does with links which do not have EXPORT defined.
8744 Org-mode has a built-in default for exporting links. If you are happy with
8745 this default, there is no need to define an export function for the link
8746 type. For a simple example of an export function, see `org-bbdb.el'."
8747 (add-to-list 'org-link-types type t)
8748 (org-make-link-regexps)
8749 (if (assoc type org-link-protocols)
8750 (setcdr (assoc type org-link-protocols) (list follow export))
8751 (push (list type follow export) org-link-protocols)))
8753 (defvar org-agenda-buffer-name)
8755 ;;;###autoload
8756 (defun org-store-link (arg)
8757 "\\<org-mode-map>Store an org-link to the current location.
8758 This link is added to `org-stored-links' and can later be inserted
8759 into an org-buffer with \\[org-insert-link].
8761 For some link types, a prefix arg is interpreted:
8762 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8763 For file links, arg negates `org-context-in-file-links'."
8764 (interactive "P")
8765 (org-load-modules-maybe)
8766 (setq org-store-link-plist nil) ; reset
8767 (org-with-limited-levels
8768 (let (link cpltxt desc description search txt custom-id agenda-link)
8769 (cond
8771 ((run-hook-with-args-until-success 'org-store-link-functions)
8772 (setq link (plist-get org-store-link-plist :link)
8773 desc (or (plist-get org-store-link-plist :description) link)))
8775 ((org-src-edit-buffer-p)
8776 (let (label gc)
8777 (while (or (not label)
8778 (save-excursion
8779 (save-restriction
8780 (widen)
8781 (goto-char (point-min))
8782 (re-search-forward
8783 (regexp-quote (format org-coderef-label-format label))
8784 nil t))))
8785 (when label (message "Label exists already") (sit-for 2))
8786 (setq label (read-string "Code line label: " label)))
8787 (end-of-line 1)
8788 (setq link (format org-coderef-label-format label))
8789 (setq gc (- 79 (length link)))
8790 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8791 (insert link)
8792 (setq link (concat "(" label ")") desc nil)))
8794 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8795 ;; We are in the agenda, link to referenced location
8796 (let ((m (or (get-text-property (point) 'org-hd-marker)
8797 (get-text-property (point) 'org-marker))))
8798 (when m
8799 (org-with-point-at m
8800 (setq agenda-link
8801 (if (org-called-interactively-p 'any)
8802 (call-interactively 'org-store-link)
8803 (org-store-link nil)))))))
8805 ((eq major-mode 'calendar-mode)
8806 (let ((cd (calendar-cursor-to-date)))
8807 (setq link
8808 (format-time-string
8809 (car org-time-stamp-formats)
8810 (apply 'encode-time
8811 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8812 nil nil nil))))
8813 (org-store-link-props :type "calendar" :date cd)))
8815 ((eq major-mode 'w3-mode)
8816 (setq cpltxt (if (and (buffer-name)
8817 (not (string-match "Untitled" (buffer-name))))
8818 (buffer-name)
8819 (url-view-url t))
8820 link (org-make-link (url-view-url t)))
8821 (org-store-link-props :type "w3" :url (url-view-url t)))
8823 ((eq major-mode 'w3m-mode)
8824 (setq cpltxt (or w3m-current-title w3m-current-url)
8825 link (org-make-link w3m-current-url))
8826 (org-store-link-props :type "w3m" :url (url-view-url t)))
8828 ((setq search (run-hook-with-args-until-success
8829 'org-create-file-search-functions))
8830 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8831 "::" search))
8832 (setq cpltxt (or description link)))
8834 ((eq major-mode 'image-mode)
8835 (setq cpltxt (concat "file:"
8836 (abbreviate-file-name buffer-file-name))
8837 link (org-make-link cpltxt))
8838 (org-store-link-props :type "image" :file buffer-file-name))
8840 ((eq major-mode 'dired-mode)
8841 ;; link to the file in the current line
8842 (let ((file (dired-get-filename nil t)))
8843 (setq file (if file
8844 (abbreviate-file-name
8845 (expand-file-name (dired-get-filename nil t)))
8846 ;; otherwise, no file so use current directory.
8847 default-directory))
8848 (setq cpltxt (concat "file:" file)
8849 link (org-make-link cpltxt))))
8851 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8852 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8853 (cond
8854 ((org-in-regexp "<<\\(.*?\\)>>")
8855 (setq cpltxt
8856 (concat "file:"
8857 (abbreviate-file-name
8858 (buffer-file-name (buffer-base-buffer)))
8859 "::" (match-string 1))
8860 link (org-make-link cpltxt)))
8861 ((and (featurep 'org-id)
8862 (or (eq org-link-to-org-use-id t)
8863 (and (eq org-link-to-org-use-id 'create-if-interactive)
8864 (org-called-interactively-p 'any))
8865 (and (eq org-link-to-org-use-id
8866 'create-if-interactive-and-no-custom-id)
8867 (org-called-interactively-p 'any)
8868 (not custom-id))
8869 (and org-link-to-org-use-id
8870 (org-entry-get nil "ID"))))
8871 ;; We can make a link using the ID.
8872 (setq link (condition-case nil
8873 (prog1 (org-id-store-link)
8874 (setq desc (plist-get org-store-link-plist
8875 :description)))
8876 (error
8877 ;; probably before first headline, link to file only
8878 (concat "file:"
8879 (abbreviate-file-name
8880 (buffer-file-name (buffer-base-buffer))))))))
8882 ;; Just link to current headline
8883 (setq cpltxt (concat "file:"
8884 (abbreviate-file-name
8885 (buffer-file-name (buffer-base-buffer)))))
8886 ;; Add a context search string
8887 (when (org-xor org-context-in-file-links arg)
8888 (setq txt (cond
8889 ((org-at-heading-p) nil)
8890 ((org-region-active-p)
8891 (buffer-substring (region-beginning) (region-end)))
8892 (t nil)))
8893 (when (or (null txt) (string-match "\\S-" txt))
8894 (setq cpltxt
8895 (concat cpltxt "::"
8896 (condition-case nil
8897 (org-make-org-heading-search-string txt)
8898 (error "")))
8899 desc (or (nth 4 (ignore-errors
8900 (org-heading-components))) "NONE"))))
8901 (if (string-match "::\\'" cpltxt)
8902 (setq cpltxt (substring cpltxt 0 -2)))
8903 (setq link (org-make-link cpltxt)))))
8905 ((buffer-file-name (buffer-base-buffer))
8906 ;; Just link to this file here.
8907 (setq cpltxt (concat "file:"
8908 (abbreviate-file-name
8909 (buffer-file-name (buffer-base-buffer)))))
8910 ;; Add a context string
8911 (when (org-xor org-context-in-file-links arg)
8912 (setq txt (if (org-region-active-p)
8913 (buffer-substring (region-beginning) (region-end))
8914 (buffer-substring (point-at-bol) (point-at-eol))))
8915 ;; Only use search option if there is some text.
8916 (when (string-match "\\S-" txt)
8917 (setq cpltxt
8918 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8919 desc "NONE")))
8920 (setq link (org-make-link cpltxt)))
8922 ((org-called-interactively-p 'interactive)
8923 (error "Cannot link to a buffer which is not visiting a file"))
8925 (t (setq link nil)))
8927 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8928 (setq link (or link cpltxt)
8929 desc (or desc cpltxt))
8930 (if (equal desc "NONE") (setq desc nil))
8932 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8933 (progn
8934 (setq org-stored-links
8935 (cons (list link desc) org-stored-links))
8936 (message "Stored: %s" (or desc link))
8937 (when custom-id
8938 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8939 "::#" custom-id))
8940 (setq org-stored-links
8941 (cons (list link desc) org-stored-links))))
8942 (or agenda-link (and link (org-make-link-string link desc)))))))
8944 (defun org-store-link-props (&rest plist)
8945 "Store link properties, extract names and addresses."
8946 (let (x adr)
8947 (when (setq x (plist-get plist :from))
8948 (setq adr (mail-extract-address-components x))
8949 (setq plist (plist-put plist :fromname (car adr)))
8950 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8951 (when (setq x (plist-get plist :to))
8952 (setq adr (mail-extract-address-components x))
8953 (setq plist (plist-put plist :toname (car adr)))
8954 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8955 (let ((from (plist-get plist :from))
8956 (to (plist-get plist :to)))
8957 (when (and from to org-from-is-user-regexp)
8958 (setq plist
8959 (plist-put plist :fromto
8960 (if (string-match org-from-is-user-regexp from)
8961 (concat "to %t")
8962 (concat "from %f"))))))
8963 (setq org-store-link-plist plist))
8965 (defun org-add-link-props (&rest plist)
8966 "Add these properties to the link property list."
8967 (let (key value)
8968 (while plist
8969 (setq key (pop plist) value (pop plist))
8970 (setq org-store-link-plist
8971 (plist-put org-store-link-plist key value)))))
8973 (defun org-email-link-description (&optional fmt)
8974 "Return the description part of an email link.
8975 This takes information from `org-store-link-plist' and formats it
8976 according to FMT (default from `org-email-link-description-format')."
8977 (setq fmt (or fmt org-email-link-description-format))
8978 (let* ((p org-store-link-plist)
8979 (to (plist-get p :toaddress))
8980 (from (plist-get p :fromaddress))
8981 (table
8982 (list
8983 (cons "%c" (plist-get p :fromto))
8984 (cons "%F" (plist-get p :from))
8985 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8986 (cons "%T" (plist-get p :to))
8987 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8988 (cons "%s" (plist-get p :subject))
8989 (cons "%d" (plist-get p :date))
8990 (cons "%m" (plist-get p :message-id)))))
8991 (when (string-match "%c" fmt)
8992 ;; Check if the user wrote this message
8993 (if (and org-from-is-user-regexp from to
8994 (save-match-data (string-match org-from-is-user-regexp from)))
8995 (setq fmt (replace-match "to %t" t t fmt))
8996 (setq fmt (replace-match "from %f" t t fmt))))
8997 (org-replace-escapes fmt table)))
8999 (defun org-make-org-heading-search-string (&optional string heading)
9000 "Make search string for STRING or current headline."
9001 (interactive)
9002 (let ((s (or string (org-get-heading)))
9003 (lines org-context-in-file-links))
9004 (unless (and string (not heading))
9005 ;; We are using a headline, clean up garbage in there.
9006 (if (string-match org-todo-regexp s)
9007 (setq s (replace-match "" t t s)))
9008 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9009 (setq s (replace-match "" t t s)))
9010 (setq s (org-trim s))
9011 (if (string-match (concat "^\\(" org-quote-string "\\|"
9012 org-comment-string "\\)") s)
9013 (setq s (replace-match "" t t s)))
9014 (while (string-match org-ts-regexp s)
9015 (setq s (replace-match "" t t s))))
9016 (or string (setq s (concat "*" s))) ; Add * for headlines
9017 (when (and string (integerp lines) (> lines 0))
9018 (let ((slines (org-split-string s "\n")))
9019 (when (< lines (length slines))
9020 (setq s (mapconcat
9021 'identity
9022 (reverse (nthcdr (- (length slines) lines)
9023 (reverse slines))) "\n")))))
9024 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9026 (defun org-make-link (&rest strings)
9027 "Concatenate STRINGS."
9028 (apply 'concat strings))
9030 (defun org-make-link-string (link &optional description)
9031 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9032 (unless (string-match "\\S-" link)
9033 (error "Empty link"))
9034 (when (and description
9035 (stringp description)
9036 (not (string-match "\\S-" description)))
9037 (setq description nil))
9038 (when (stringp description)
9039 ;; Remove brackets from the description, they are fatal.
9040 (while (string-match "\\[" description)
9041 (setq description (replace-match "{" t t description)))
9042 (while (string-match "\\]" description)
9043 (setq description (replace-match "}" t t description))))
9044 (when (equal link description)
9045 ;; No description needed, it is identical
9046 (setq description nil))
9047 (when (and (not description)
9048 (not (string-match (org-image-file-name-regexp) link))
9049 (not (equal link (org-link-escape link))))
9050 (setq description (org-extract-attributes link)))
9051 (setq link
9052 (cond ((string-match (org-image-file-name-regexp) link) link)
9053 ((string-match org-link-types-re link)
9054 (concat (match-string 1 link)
9055 (org-link-escape (substring link (match-end 1)))))
9056 (t (org-link-escape link))))
9057 (concat "[[" link "]"
9058 (if description (concat "[" description "]") "")
9059 "]"))
9061 (defconst org-link-escape-chars
9062 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9063 "List of characters that should be escaped in link.
9064 This is the list that is used for internal purposes.")
9066 (defvar org-url-encoding-use-url-hexify nil)
9068 (defconst org-link-escape-chars-browser
9069 '(?\ )
9070 "List of escapes for characters that are problematic in links.
9071 This is the list that is used before handing over to the browser.")
9073 (defun org-link-escape (text &optional table merge)
9074 "Return percent escaped representation of TEXT.
9075 TEXT is a string with the text to escape.
9076 Optional argument TABLE is a list with characters that should be
9077 escaped. When nil, `org-link-escape-chars' is used.
9078 If optional argument MERGE is set, merge TABLE into
9079 `org-link-escape-chars'."
9080 (if (and org-url-encoding-use-url-hexify (not table))
9081 (url-hexify-string text)
9082 (cond
9083 ((and table merge)
9084 (mapc (lambda (defchr)
9085 (unless (member defchr table)
9086 (setq table (cons defchr table)))) org-link-escape-chars))
9087 ((null table)
9088 (setq table org-link-escape-chars)))
9089 (mapconcat
9090 (lambda (char)
9091 (if (or (member char table)
9092 (< char 32) (= char 37) (> char 126))
9093 (mapconcat (lambda (sequence-element)
9094 (format "%%%.2X" sequence-element))
9095 (or (encode-coding-char char 'utf-8)
9096 (error "Unable to percent escape character: %s"
9097 (char-to-string char))) "")
9098 (char-to-string char))) text "")))
9100 (defun org-link-unescape (str)
9101 "Unhex hexified Unicode strings as returned from the JavaScript function
9102 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9103 (unless (and (null str) (string= "" str))
9104 (let ((pos 0) (case-fold-search t) unhexed)
9105 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9106 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9107 (setq str (replace-match unhexed t t str))
9108 (setq pos (+ pos (length unhexed))))))
9109 str)
9111 (defun org-link-unescape-compound (hex)
9112 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9113 Note: this function also decodes single byte encodings like
9114 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9115 (save-match-data
9116 (let* ((bytes (cdr (split-string hex "%")))
9117 (ret "")
9118 (eat 0)
9119 (sum 0))
9120 (while bytes
9121 (let* ((val (string-to-number (pop bytes) 16))
9122 (shift-xor
9123 (if (= 0 eat)
9124 (cond
9125 ((>= val 252) (cons 6 252))
9126 ((>= val 248) (cons 5 248))
9127 ((>= val 240) (cons 4 240))
9128 ((>= val 224) (cons 3 224))
9129 ((>= val 192) (cons 2 192))
9130 (t (cons 0 0)))
9131 (cons 6 128))))
9132 (if (>= val 192) (setq eat (car shift-xor)))
9133 (setq val (logxor val (cdr shift-xor)))
9134 (setq sum (+ (lsh sum (car shift-xor)) val))
9135 (if (> eat 0) (setq eat (- eat 1)))
9136 (cond
9137 ((= 0 eat) ;multi byte
9138 (setq ret (concat ret (org-char-to-string sum)))
9139 (setq sum 0))
9140 ((not bytes) ; single byte(s)
9141 (setq ret (org-link-unescape-single-byte-sequence hex))))
9142 )) ;; end (while bytes
9143 ret )))
9145 (defun org-link-unescape-single-byte-sequence (hex)
9146 "Unhexify hex-encoded single byte character sequences."
9147 (mapconcat (lambda (byte)
9148 (char-to-string (string-to-number byte 16)))
9149 (cdr (split-string hex "%")) ""))
9151 (defun org-xor (a b)
9152 "Exclusive or."
9153 (if a (not b) b))
9155 (defun org-fixup-message-id-for-http (s)
9156 "Replace special characters in a message id, so it can be used in an http query."
9157 (when (string-match "%" s)
9158 (setq s (mapconcat (lambda (c)
9159 (if (eq c ?%)
9160 "%25"
9161 (char-to-string c)))
9162 s "")))
9163 (while (string-match "<" s)
9164 (setq s (replace-match "%3C" t t s)))
9165 (while (string-match ">" s)
9166 (setq s (replace-match "%3E" t t s)))
9167 (while (string-match "@" s)
9168 (setq s (replace-match "%40" t t s)))
9171 (defun org-link-prettify (link)
9172 "Return a human-readable representation of LINK.
9173 The car of LINK must be a raw link the cdr of LINK must be either
9174 a link description or nil."
9175 (let ((desc (or (cadr link) "<no description>")))
9176 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9177 "[[" (car link) "]]")))
9179 ;;;###autoload
9180 (defun org-insert-link-global ()
9181 "Insert a link like Org-mode does.
9182 This command can be called in any mode to insert a link in Org-mode syntax."
9183 (interactive)
9184 (org-load-modules-maybe)
9185 (org-run-like-in-org-mode 'org-insert-link))
9187 (defun org-insert-link (&optional complete-file link-location default-description)
9188 "Insert a link. At the prompt, enter the link.
9190 Completion can be used to insert any of the link protocol prefixes like
9191 http or ftp in use.
9193 The history can be used to select a link previously stored with
9194 `org-store-link'. When the empty string is entered (i.e. if you just
9195 press RET at the prompt), the link defaults to the most recently
9196 stored link. As SPC triggers completion in the minibuffer, you need to
9197 use M-SPC or C-q SPC to force the insertion of a space character.
9199 You will also be prompted for a description, and if one is given, it will
9200 be displayed in the buffer instead of the link.
9202 If there is already a link at point, this command will allow you to edit link
9203 and description parts.
9205 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9206 be selected using completion. The path to the file will be relative to the
9207 current directory if the file is in the current directory or a subdirectory.
9208 Otherwise, the link will be the absolute path as completed in the minibuffer
9209 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9210 option `org-link-file-path-type'.
9212 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9213 the current directory or below.
9215 With three \\[universal-argument] prefixes, negate the meaning of
9216 `org-keep-stored-link-after-insertion'.
9218 If `org-make-link-description-function' is non-nil, this function will be
9219 called with the link target, and the result will be the default
9220 link description.
9222 If the LINK-LOCATION parameter is non-nil, this value will be
9223 used as the link location instead of reading one interactively.
9225 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9226 be used as the default description."
9227 (interactive "P")
9228 (let* ((wcf (current-window-configuration))
9229 (region (if (org-region-active-p)
9230 (buffer-substring (region-beginning) (region-end))))
9231 (remove (and region (list (region-beginning) (region-end))))
9232 (desc region)
9233 tmphist ; byte-compile incorrectly complains about this
9234 (link link-location)
9235 entry file all-prefixes)
9236 (cond
9237 (link-location) ; specified by arg, just use it.
9238 ((org-in-regexp org-bracket-link-regexp 1)
9239 ;; We do have a link at point, and we are going to edit it.
9240 (setq remove (list (match-beginning 0) (match-end 0)))
9241 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9242 (setq link (read-string "Link: "
9243 (org-link-unescape
9244 (org-match-string-no-properties 1)))))
9245 ((or (org-in-regexp org-angle-link-re)
9246 (org-in-regexp org-plain-link-re))
9247 ;; Convert to bracket link
9248 (setq remove (list (match-beginning 0) (match-end 0))
9249 link (read-string "Link: "
9250 (org-remove-angle-brackets (match-string 0)))))
9251 ((member complete-file '((4) (16)))
9252 ;; Completing read for file names.
9253 (setq link (org-file-complete-link complete-file)))
9255 ;; Read link, with completion for stored links.
9256 (with-output-to-temp-buffer "*Org Links*"
9257 (princ "Insert a link.
9258 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9259 (when org-stored-links
9260 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9261 (princ (mapconcat 'org-link-prettify
9262 (reverse org-stored-links) "\n"))))
9263 (let ((cw (selected-window)))
9264 (select-window (get-buffer-window "*Org Links*" 'visible))
9265 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9266 (unless (pos-visible-in-window-p (point-max))
9267 (org-fit-window-to-buffer))
9268 (and (window-live-p cw) (select-window cw)))
9269 ;; Fake a link history, containing the stored links.
9270 (setq tmphist (append (mapcar 'car org-stored-links)
9271 org-insert-link-history))
9272 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9273 (mapcar 'car org-link-abbrev-alist)
9274 org-link-types))
9275 (unwind-protect
9276 (progn
9277 (setq link
9278 (let ((org-completion-use-ido nil)
9279 (org-completion-use-iswitchb nil))
9280 (org-completing-read
9281 "Link: "
9282 (append
9283 (mapcar (lambda (x) (list (concat x ":")))
9284 all-prefixes)
9285 (mapcar 'car org-stored-links))
9286 nil nil nil
9287 'tmphist
9288 (car (car org-stored-links)))))
9289 (if (not (string-match "\\S-" link))
9290 (error "No link selected"))
9291 (if (or (member link all-prefixes)
9292 (and (equal ":" (substring link -1))
9293 (member (substring link 0 -1) all-prefixes)
9294 (setq link (substring link 0 -1))))
9295 (setq link (org-link-try-special-completion link))))
9296 (set-window-configuration wcf)
9297 (kill-buffer "*Org Links*"))
9298 (setq entry (assoc link org-stored-links))
9299 (or entry (push link org-insert-link-history))
9300 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9301 (not org-keep-stored-link-after-insertion))
9302 (setq org-stored-links (delq (assoc link org-stored-links)
9303 org-stored-links)))
9304 (setq desc (or desc (nth 1 entry)))))
9306 (if (string-match org-plain-link-re link)
9307 ;; URL-like link, normalize the use of angular brackets.
9308 (setq link (org-make-link (org-remove-angle-brackets link))))
9310 ;; Check if we are linking to the current file with a search option
9311 ;; If yes, simplify the link by using only the search option.
9312 (when (and buffer-file-name
9313 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9314 (let* ((path (match-string 1 link))
9315 (case-fold-search nil)
9316 (search (match-string 2 link)))
9317 (save-match-data
9318 (if (equal (file-truename buffer-file-name) (file-truename path))
9319 ;; We are linking to this same file, with a search option
9320 (setq link search)))))
9322 ;; Check if we can/should use a relative path. If yes, simplify the link
9323 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9324 (let* ((type (match-string 1 link))
9325 (path (match-string 2 link))
9326 (origpath path)
9327 (case-fold-search nil))
9328 (cond
9329 ((or (eq org-link-file-path-type 'absolute)
9330 (equal complete-file '(16)))
9331 (setq path (abbreviate-file-name (expand-file-name path))))
9332 ((eq org-link-file-path-type 'noabbrev)
9333 (setq path (expand-file-name path)))
9334 ((eq org-link-file-path-type 'relative)
9335 (setq path (file-relative-name path)))
9337 (save-match-data
9338 (if (string-match (concat "^" (regexp-quote
9339 (expand-file-name
9340 (file-name-as-directory
9341 default-directory))))
9342 (expand-file-name path))
9343 ;; We are linking a file with relative path name.
9344 (setq path (substring (expand-file-name path)
9345 (match-end 0)))
9346 (setq path (abbreviate-file-name (expand-file-name path)))))))
9347 (setq link (concat type path))
9348 (if (equal desc origpath)
9349 (setq desc path))))
9351 (if org-make-link-description-function
9352 (setq desc (funcall org-make-link-description-function link desc))
9353 (if default-description (setq desc default-description)))
9355 (setq desc (read-string "Description: " desc))
9356 (unless (string-match "\\S-" desc) (setq desc nil))
9357 (if remove (apply 'delete-region remove))
9358 (insert (org-make-link-string link desc))))
9360 (defun org-link-try-special-completion (type)
9361 "If there is completion support for link type TYPE, offer it."
9362 (let ((fun (intern (concat "org-" type "-complete-link"))))
9363 (if (functionp fun)
9364 (funcall fun)
9365 (read-string "Link (no completion support): " (concat type ":")))))
9367 (defun org-file-complete-link (&optional arg)
9368 "Create a file link using completion."
9369 (let (file link)
9370 (setq file (read-file-name "File: "))
9371 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9372 (pwd1 (file-name-as-directory (abbreviate-file-name
9373 (expand-file-name ".")))))
9374 (cond
9375 ((equal arg '(16))
9376 (setq link (org-make-link
9377 "file:"
9378 (abbreviate-file-name (expand-file-name file)))))
9379 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9380 (setq link (org-make-link "file:" (match-string 1 file))))
9381 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9382 (expand-file-name file))
9383 (setq link (org-make-link
9384 "file:" (match-string 1 (expand-file-name file)))))
9385 (t (setq link (org-make-link "file:" file)))))
9386 link))
9388 (defun org-completing-read (&rest args)
9389 "Completing-read with SPACE being a normal character."
9390 (let ((enable-recursive-minibuffers t)
9391 (minibuffer-local-completion-map
9392 (copy-keymap minibuffer-local-completion-map)))
9393 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9394 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9395 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9396 (apply 'org-icompleting-read args)))
9398 (defun org-completing-read-no-i (&rest args)
9399 (let (org-completion-use-ido org-completion-use-iswitchb)
9400 (apply 'org-completing-read args)))
9402 (defun org-iswitchb-completing-read (prompt choices &rest args)
9403 "Use iswitch as a completing-read replacement to choose from choices.
9404 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9405 from."
9406 (let* ((iswitchb-use-virtual-buffers nil)
9407 (iswitchb-make-buflist-hook
9408 (lambda ()
9409 (setq iswitchb-temp-buflist choices))))
9410 (iswitchb-read-buffer prompt)))
9412 (defun org-icompleting-read (&rest args)
9413 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9414 (org-without-partial-completion
9415 (if (and org-completion-use-ido
9416 (fboundp 'ido-completing-read)
9417 (boundp 'ido-mode) ido-mode
9418 (listp (second args)))
9419 (let ((ido-enter-matching-directory nil))
9420 (apply 'ido-completing-read (concat (car args))
9421 (if (consp (car (nth 1 args)))
9422 (mapcar 'car (nth 1 args))
9423 (nth 1 args))
9424 (cddr args)))
9425 (if (and org-completion-use-iswitchb
9426 (boundp 'iswitchb-mode) iswitchb-mode
9427 (listp (second args)))
9428 (apply 'org-iswitchb-completing-read (concat (car args))
9429 (if (consp (car (nth 1 args)))
9430 (mapcar 'car (nth 1 args))
9431 (nth 1 args))
9432 (cddr args))
9433 (apply 'completing-read args)))))
9435 (defun org-extract-attributes (s)
9436 "Extract the attributes cookie from a string and set as text property."
9437 (let (a attr (start 0) key value)
9438 (save-match-data
9439 (when (string-match "{{\\([^}]+\\)}}$" s)
9440 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9441 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9442 (setq key (match-string 1 a) value (match-string 2 a)
9443 start (match-end 0)
9444 attr (plist-put attr (intern key) value))))
9445 (org-add-props s nil 'org-attr attr))
9448 (defun org-extract-attributes-from-string (tag)
9449 (let (key value attr)
9450 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9451 (setq key (match-string 1 tag) value (match-string 2 tag)
9452 tag (replace-match "" t t tag)
9453 attr (plist-put attr (intern key) value)))
9454 (cons tag attr)))
9456 (defun org-attributes-to-string (plist)
9457 "Format a property list into an HTML attribute list."
9458 (let ((s "") key value)
9459 (while plist
9460 (setq key (pop plist) value (pop plist))
9461 (and value
9462 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9465 ;;; Opening/following a link
9467 (defvar org-link-search-failed nil)
9469 (defvar org-open-link-functions nil
9470 "Hook for functions finding a plain text link.
9471 These functions must take a single argument, the link content.
9472 They will be called for links that look like [[link text][description]]
9473 when LINK TEXT does not have a protocol like \"http:\" and does not look
9474 like a filename (e.g. \"./blue.png\").
9476 These functions will be called *before* Org attempts to resolve the
9477 link by doing text searches in the current buffer - so if you want a
9478 link \"[[target]]\" to still find \"<<target>>\", your function should
9479 handle this as a special case.
9481 When the function does handle the link, it must return a non-nil value.
9482 If it decides that it is not responsible for this link, it must return
9483 nil to indicate that that Org-mode can continue with other options
9484 like exact and fuzzy text search.")
9486 (defun org-next-link ()
9487 "Move forward to the next 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-min))
9492 (message "Link search wrapped back to beginning 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 2 a)))
9498 (if (re-search-forward 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-previous-link ()
9507 "Move backward to the previous link.
9508 If the link is in hidden text, expose it."
9509 (interactive)
9510 (when (and org-link-search-failed (eq this-command last-command))
9511 (goto-char (point-max))
9512 (message "Link search wrapped back to end of buffer"))
9513 (setq org-link-search-failed nil)
9514 (let* ((pos (point))
9515 (ct (org-context))
9516 (a (assoc :link ct)))
9517 (if a (goto-char (nth 1 a)))
9518 (if (re-search-backward org-any-link-re nil t)
9519 (progn
9520 (goto-char (match-beginning 0))
9521 (if (outline-invisible-p) (org-show-context)))
9522 (goto-char pos)
9523 (setq org-link-search-failed t)
9524 (error "No further link found"))))
9526 (defun org-translate-link (s)
9527 "Translate a link string if a translation function has been defined."
9528 (if (and org-link-translation-function
9529 (fboundp org-link-translation-function)
9530 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9531 (progn
9532 (setq s (funcall org-link-translation-function
9533 (match-string 1 s) (match-string 2 s)))
9534 (concat (car s) ":" (cdr s)))
9537 (defun org-translate-link-from-planner (type path)
9538 "Translate a link from Emacs Planner syntax so that Org can follow it.
9539 This is still an experimental function, your mileage may vary."
9540 (cond
9541 ((member type '("http" "https" "news" "ftp"))
9542 ;; standard Internet links are the same.
9543 nil)
9544 ((and (equal type "irc") (string-match "^//" path))
9545 ;; Planner has two / at the beginning of an irc link, we have 1.
9546 ;; We should have zero, actually....
9547 (setq path (substring path 1)))
9548 ((and (equal type "lisp") (string-match "^/" path))
9549 ;; Planner has a slash, we do not.
9550 (setq type "elisp" path (substring path 1)))
9551 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9552 ;; A typical message link. Planner has the id after the final slash,
9553 ;; we separate it with a hash mark
9554 (setq path (concat (match-string 1 path) "#"
9555 (org-remove-angle-brackets (match-string 2 path)))))
9557 (cons type path))
9559 (defun org-find-file-at-mouse (ev)
9560 "Open file link or URL at mouse."
9561 (interactive "e")
9562 (mouse-set-point ev)
9563 (org-open-at-point 'in-emacs))
9565 (defun org-open-at-mouse (ev)
9566 "Open file link or URL at mouse.
9567 See the docstring of `org-open-file' for details."
9568 (interactive "e")
9569 (mouse-set-point ev)
9570 (if (eq major-mode 'org-agenda-mode)
9571 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9572 (org-open-at-point))
9574 (defvar org-window-config-before-follow-link nil
9575 "The window configuration before following a link.
9576 This is saved in case the need arises to restore it.")
9578 (defvar org-open-link-marker (make-marker)
9579 "Marker pointing to the location where `org-open-at-point; was called.")
9581 ;;;###autoload
9582 (defun org-open-at-point-global ()
9583 "Follow a link like Org-mode does.
9584 This command can be called in any mode to follow a link that has
9585 Org-mode syntax."
9586 (interactive)
9587 (org-run-like-in-org-mode 'org-open-at-point))
9589 ;;;###autoload
9590 (defun org-open-link-from-string (s &optional arg reference-buffer)
9591 "Open a link in the string S, as if it was in Org-mode."
9592 (interactive "sLink: \nP")
9593 (let ((reference-buffer (or reference-buffer (current-buffer))))
9594 (with-temp-buffer
9595 (let ((org-inhibit-startup (not reference-buffer)))
9596 (org-mode)
9597 (insert s)
9598 (goto-char (point-min))
9599 (when reference-buffer
9600 (setq org-link-abbrev-alist-local
9601 (with-current-buffer reference-buffer
9602 org-link-abbrev-alist-local)))
9603 (org-open-at-point arg reference-buffer)))))
9605 (defvar org-open-at-point-functions nil
9606 "Hook that is run when following a link at point.
9608 Functions in this hook must return t if they identify and follow
9609 a link at point. If they don't find anything interesting at point,
9610 they must return nil.")
9612 (defun org-open-at-point (&optional arg reference-buffer)
9613 "Open link at or after point.
9614 If there is no link at point, this function will search forward up to
9615 the end of the current line.
9616 Normally, files will be opened by an appropriate application. If the
9617 optional prefix argument ARG is non-nil, Emacs will visit the file.
9618 With a double prefix argument, try to open outside of Emacs, in the
9619 application the system uses for this file type."
9620 (interactive "P")
9621 ;; if in a code block, then open the block's results
9622 (unless (call-interactively #'org-babel-open-src-block-result)
9623 (org-load-modules-maybe)
9624 (move-marker org-open-link-marker (point))
9625 (setq org-window-config-before-follow-link (current-window-configuration))
9626 (org-remove-occur-highlights nil nil t)
9627 (cond
9628 ((and (org-at-heading-p)
9629 (not (org-at-timestamp-p t))
9630 (not (org-in-regexp
9631 (concat org-plain-link-re "\\|"
9632 org-bracket-link-regexp "\\|"
9633 org-angle-link-re "\\|"
9634 "[ \t]:[^ \t\n]+:[ \t]*$")))
9635 (not (get-text-property (point) 'org-linked-text)))
9636 (or (org-offer-links-in-entry arg)
9637 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9638 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9639 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9640 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9641 (not (org-in-regexp org-bracket-link-regexp)))
9642 (org-footnote-action))
9644 (let (type path link line search (pos (point)))
9645 (catch 'match
9646 (save-excursion
9647 (skip-chars-forward "^]\n\r")
9648 (when (org-in-regexp org-bracket-link-regexp 1)
9649 (setq link (org-extract-attributes
9650 (org-link-unescape (org-match-string-no-properties 1))))
9651 (while (string-match " *\n *" link)
9652 (setq link (replace-match " " t t link)))
9653 (setq link (org-link-expand-abbrev link))
9654 (cond
9655 ((or (file-name-absolute-p link)
9656 (string-match "^\\.\\.?/" link))
9657 (setq type "file" path link))
9658 ((string-match org-link-re-with-space3 link)
9659 (setq type (match-string 1 link) path (match-string 2 link)))
9660 (t (setq type "thisfile" path link)))
9661 (throw 'match t)))
9663 (when (get-text-property (point) 'org-linked-text)
9664 (setq type "thisfile"
9665 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9666 (1+ (point)) (point))
9667 path (buffer-substring
9668 (or (previous-single-property-change pos 'org-linked-text)
9669 (point-min))
9670 (or (next-single-property-change pos 'org-linked-text)
9671 (point-max))))
9672 (throw 'match t))
9674 (save-excursion
9675 (when (or (org-in-regexp org-angle-link-re)
9676 (org-in-regexp org-plain-link-re))
9677 (setq type (match-string 1)
9678 path (org-link-unescape (match-string 2)))
9679 (throw 'match t)))
9680 (save-excursion
9681 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9682 (setq type "tags"
9683 path (match-string 1))
9684 (while (string-match ":" path)
9685 (setq path (replace-match "+" t t path)))
9686 (throw 'match t)))
9687 (when (org-in-regexp "<\\([^><\n]+\\)>")
9688 (setq type "tree-match"
9689 path (match-string 1))
9690 (throw 'match t)))
9691 (unless path
9692 (error "No link found"))
9694 ;; switch back to reference buffer
9695 ;; needed when if called in a temporary buffer through
9696 ;; org-open-link-from-string
9697 (with-current-buffer (or reference-buffer (current-buffer))
9699 ;; Remove any trailing spaces in path
9700 (if (string-match " +\\'" path)
9701 (setq path (replace-match "" t t path)))
9702 (if (and org-link-translation-function
9703 (fboundp org-link-translation-function))
9704 ;; Check if we need to translate the link
9705 (let ((tmp (funcall org-link-translation-function type path)))
9706 (setq type (car tmp) path (cdr tmp))))
9708 (cond
9710 ((assoc type org-link-protocols)
9711 (funcall (nth 1 (assoc type org-link-protocols)) path))
9713 ((equal type "mailto")
9714 (let ((cmd (car org-link-mailto-program))
9715 (args (cdr org-link-mailto-program)) args1
9716 (address path) (subject "") a)
9717 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9718 (setq address (match-string 1 path)
9719 subject (org-link-escape (match-string 2 path))))
9720 (while args
9721 (cond
9722 ((not (stringp (car args))) (push (pop args) args1))
9723 (t (setq a (pop args))
9724 (if (string-match "%a" a)
9725 (setq a (replace-match address t t a)))
9726 (if (string-match "%s" a)
9727 (setq a (replace-match subject t t a)))
9728 (push a args1))))
9729 (apply cmd (nreverse args1))))
9731 ((member type '("http" "https" "ftp" "news"))
9732 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9733 (org-link-escape
9734 path org-link-escape-chars-browser)
9735 path))))
9737 ((string= type "doi")
9738 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9739 (org-link-escape
9740 path org-link-escape-chars-browser)
9741 path))))
9743 ((member type '("message"))
9744 (browse-url (concat type ":" path)))
9746 ((string= type "tags")
9747 (org-tags-view arg path))
9749 ((string= type "tree-match")
9750 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9752 ((string= type "file")
9753 (if (string-match "::\\([0-9]+\\)\\'" path)
9754 (setq line (string-to-number (match-string 1 path))
9755 path (substring path 0 (match-beginning 0)))
9756 (if (string-match "::\\(.+\\)\\'" path)
9757 (setq search (match-string 1 path)
9758 path (substring path 0 (match-beginning 0)))))
9759 (if (string-match "[*?{]" (file-name-nondirectory path))
9760 (dired path)
9761 (org-open-file path arg line search)))
9763 ((string= type "shell")
9764 (let ((cmd path))
9765 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9766 (string-match org-confirm-shell-link-not-regexp cmd))
9767 (not org-confirm-shell-link-function)
9768 (funcall org-confirm-shell-link-function
9769 (format "Execute \"%s\" in shell? "
9770 (org-add-props cmd nil
9771 'face 'org-warning))))
9772 (progn
9773 (message "Executing %s" cmd)
9774 (shell-command cmd))
9775 (error "Abort"))))
9777 ((string= type "elisp")
9778 (let ((cmd path))
9779 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9780 (string-match org-confirm-elisp-link-not-regexp cmd))
9781 (not org-confirm-elisp-link-function)
9782 (funcall org-confirm-elisp-link-function
9783 (format "Execute \"%s\" as elisp? "
9784 (org-add-props cmd nil
9785 'face 'org-warning))))
9786 (message "%s => %s" cmd
9787 (if (equal (string-to-char cmd) ?\()
9788 (eval (read cmd))
9789 (call-interactively (read cmd))))
9790 (error "Abort"))))
9792 ((and (string= type "thisfile")
9793 (run-hook-with-args-until-success
9794 'org-open-link-functions path)))
9796 ((string= type "thisfile")
9797 (if arg
9798 (switch-to-buffer-other-window
9799 (org-get-buffer-for-internal-link (current-buffer)))
9800 (org-mark-ring-push))
9801 (let ((cmd `(org-link-search
9802 ,path
9803 ,(cond ((equal arg '(4)) ''occur)
9804 ((equal arg '(16)) ''org-occur)
9805 (t nil))
9806 ,pos)))
9807 (condition-case nil (let ((org-link-search-inhibit-query t))
9808 (eval cmd))
9809 (error (progn (widen) (eval cmd))))))
9812 (browse-url-at-point)))))))
9813 (move-marker org-open-link-marker nil)
9814 (run-hook-with-args 'org-follow-link-hook)))
9816 (defun org-offer-links-in-entry (&optional nth zero)
9817 "Offer links in the current entry and follow the selected link.
9818 If there is only one link, follow it immediately as well.
9819 If NTH is an integer, immediately pick the NTH link found.
9820 If ZERO is a string, check also this string for a link, and if
9821 there is one, offer it as link number zero."
9822 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9823 "\\(" org-angle-link-re "\\)\\|"
9824 "\\(" org-plain-link-re "\\)"))
9825 (cnt ?0)
9826 (in-emacs (if (integerp nth) nil nth))
9827 have-zero end links link c)
9828 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9829 (push (match-string 0 zero) links)
9830 (setq cnt (1- cnt) have-zero t))
9831 (save-excursion
9832 (org-back-to-heading t)
9833 (setq end (save-excursion (outline-next-heading) (point)))
9834 (while (re-search-forward re end t)
9835 (push (match-string 0) links))
9836 (setq links (org-uniquify (reverse links))))
9838 (cond
9839 ((null links)
9840 (message "No links"))
9841 ((equal (length links) 1)
9842 (setq link (list (car links))))
9843 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9844 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9845 (t ; we have to select a link
9846 (save-excursion
9847 (save-window-excursion
9848 (delete-other-windows)
9849 (with-output-to-temp-buffer "*Select Link*"
9850 (mapc (lambda (l)
9851 (if (not (string-match org-bracket-link-regexp l))
9852 (princ (format "[%c] %s\n" (incf cnt)
9853 (org-remove-angle-brackets l)))
9854 (if (match-end 3)
9855 (princ (format "[%c] %s (%s)\n" (incf cnt)
9856 (match-string 3 l) (match-string 1 l)))
9857 (princ (format "[%c] %s\n" (incf cnt)
9858 (match-string 1 l))))))
9859 links))
9860 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9861 (message "Select link to open, RET to open all:")
9862 (setq c (read-char-exclusive))
9863 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9864 (when (equal c ?q) (error "Abort"))
9865 (if (equal c ?\C-m)
9866 (setq link links)
9867 (setq nth (- c ?0))
9868 (if have-zero (setq nth (1+ nth)))
9869 (unless (and (integerp nth) (>= (length links) nth))
9870 (error "Invalid link selection"))
9871 (setq link (list (nth (1- nth) links))))))
9872 (if link
9873 (let ((buf (current-buffer)))
9874 (dolist (l link)
9875 (org-open-link-from-string l in-emacs buf))
9877 nil)))
9879 ;; Add special file links that specify the way of opening
9881 (org-add-link-type "file+sys" 'org-open-file-with-system)
9882 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9883 (defun org-open-file-with-system (path)
9884 "Open file at PATH using the system way of opening it."
9885 (org-open-file path 'system))
9886 (defun org-open-file-with-emacs (path)
9887 "Open file at PATH in Emacs."
9888 (org-open-file path 'emacs))
9889 (defun org-remove-file-link-modifiers ()
9890 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9891 (goto-char (point-min))
9892 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9893 (org-if-unprotected
9894 (replace-match "file:" t t))))
9895 (eval-after-load "org-exp"
9896 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9897 'org-remove-file-link-modifiers))
9899 ;;;; Time estimates
9901 (defun org-get-effort (&optional pom)
9902 "Get the effort estimate for the current entry."
9903 (org-entry-get pom org-effort-property))
9905 ;;; File search
9907 (defvar org-create-file-search-functions nil
9908 "List of functions to construct the right search string for a file link.
9909 These functions are called in turn with point at the location to
9910 which the link should point.
9912 A function in the hook should first test if it would like to
9913 handle this file type, for example by checking the `major-mode'
9914 or the file extension. If it decides not to handle this file, it
9915 should just return nil to give other functions a chance. If it
9916 does handle the file, it must return the search string to be used
9917 when following the link. The search string will be part of the
9918 file link, given after a double colon, and `org-open-at-point'
9919 will automatically search for it. If special measures must be
9920 taken to make the search successful, another function should be
9921 added to the companion hook `org-execute-file-search-functions',
9922 which see.
9924 A function in this hook may also use `setq' to set the variable
9925 `description' to provide a suggestion for the descriptive text to
9926 be used for this link when it gets inserted into an Org-mode
9927 buffer with \\[org-insert-link].")
9929 (defvar org-execute-file-search-functions nil
9930 "List of functions to execute a file search triggered by a link.
9932 Functions added to this hook must accept a single argument, the
9933 search string that was part of the file link, the part after the
9934 double colon. The function must first check if it would like to
9935 handle this search, for example by checking the `major-mode' or
9936 the file extension. If it decides not to handle this search, it
9937 should just return nil to give other functions a chance. If it
9938 does handle the search, it must return a non-nil value to keep
9939 other functions from trying.
9941 Each function can access the current prefix argument through the
9942 variable `current-prefix-argument'. Note that a single prefix is
9943 used to force opening a link in Emacs, so it may be good to only
9944 use a numeric or double prefix to guide the search function.
9946 In case this is needed, a function in this hook can also restore
9947 the window configuration before `org-open-at-point' was called using:
9949 (set-window-configuration org-window-config-before-follow-link)")
9951 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9952 (defun org-link-search (s &optional type avoid-pos stealth)
9953 "Search for a link search option.
9954 If S is surrounded by forward slashes, it is interpreted as a
9955 regular expression. In org-mode files, this will create an `org-occur'
9956 sparse tree. In ordinary files, `occur' will be used to list matches.
9957 If the current buffer is in `dired-mode', grep will be used to search
9958 in all files. If AVOID-POS is given, ignore matches near that position.
9960 When optional argument STEALTH is non-nil, do not modify
9961 visibility around point, thus ignoring
9962 `org-show-hierarchy-above', `org-show-following-heading' and
9963 `org-show-siblings' variables."
9964 (let ((case-fold-search t)
9965 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9966 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9967 (append '(("") (" ") ("\t") ("\n"))
9968 org-emphasis-alist)
9969 "\\|") "\\)"))
9970 (pos (point))
9971 (pre nil) (post nil)
9972 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9973 (cond
9974 ;; First check if there are any special search functions
9975 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9976 ;; Now try the builtin stuff
9977 ((and (equal (string-to-char s0) ?#)
9978 (> (length s0) 1)
9979 (save-excursion
9980 (goto-char (point-min))
9981 (and
9982 (re-search-forward
9983 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9984 (setq type 'dedicated
9985 pos (match-beginning 0))))
9986 ;; There is an exact target for this
9987 (goto-char pos)
9988 (org-back-to-heading t)))
9989 ((save-excursion
9990 (goto-char (point-min))
9991 (and
9992 (re-search-forward
9993 (concat "<<" (regexp-quote s0) ">>") nil t)
9994 (setq type 'dedicated
9995 pos (match-beginning 0))))
9996 ;; There is an exact target for this
9997 (goto-char pos))
9998 ((save-excursion
9999 (goto-char (point-min))
10000 (and
10001 (re-search-forward
10002 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10003 (setq type 'dedicated pos (match-beginning 0))))
10004 ;; Found an invisible target.
10005 (goto-char pos))
10006 ((save-excursion
10007 (goto-char (point-min))
10008 (and
10009 (re-search-forward
10010 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10011 (setq type 'dedicated pos (match-beginning 0))))
10012 ;; Found an element with a matching #+name affiliated keyword.
10013 (goto-char pos))
10014 ((and (string-match "^(\\(.*\\))$" s0)
10015 (save-excursion
10016 (goto-char (point-min))
10017 (and
10018 (re-search-forward
10019 (concat "[^[]" (regexp-quote
10020 (format org-coderef-label-format
10021 (match-string 1 s0))))
10022 nil t)
10023 (setq type 'dedicated
10024 pos (1+ (match-beginning 0))))))
10025 ;; There is a coderef target for this
10026 (goto-char pos))
10027 ((string-match "^/\\(.*\\)/$" s)
10028 ;; A regular expression
10029 (cond
10030 ((derived-mode-p 'org-mode)
10031 (org-occur (match-string 1 s)))
10032 ;;((eq major-mode 'dired-mode)
10033 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10034 (t (org-do-occur (match-string 1 s)))))
10035 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10036 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10037 (goto-char (point-min))
10038 (cond
10039 ((let (case-fold-search)
10040 (re-search-forward (format org-complex-heading-regexp-format
10041 (regexp-quote s))
10042 nil t))
10043 ;; OK, found a match
10044 (setq type 'dedicated)
10045 (goto-char (match-beginning 0)))
10046 ((and (not org-link-search-inhibit-query)
10047 (eq org-link-search-must-match-exact-headline 'query-to-create)
10048 (y-or-n-p "No match - create this as a new heading? "))
10049 (goto-char (point-max))
10050 (or (bolp) (newline))
10051 (insert "* " s "\n")
10052 (beginning-of-line 0))
10054 (goto-char pos)
10055 (error "No match"))))
10057 ;; A normal search string
10058 (when (equal (string-to-char s) ?*)
10059 ;; Anchor on headlines, post may include tags.
10060 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10061 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10062 s (substring s 1)))
10063 (remove-text-properties
10064 0 (length s)
10065 '(face nil mouse-face nil keymap nil fontified nil) s)
10066 ;; Make a series of regular expressions to find a match
10067 (setq words (org-split-string s "[ \n\r\t]+")
10069 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10070 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10071 "\\)" markers)
10072 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10073 re2a (concat "[ \t\r\n]" re2a_)
10074 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10075 re4 (concat "[^a-zA-Z_]" re4_)
10077 re1 (concat pre re2 post)
10078 re3 (concat pre (if pre re4_ re4) post)
10079 re5 (concat pre ".*" re4)
10080 re2 (concat pre re2)
10081 re2a (concat pre (if pre re2a_ re2a))
10082 re4 (concat pre (if pre re4_ re4))
10083 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10084 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10085 re5 "\\)"
10087 (cond
10088 ((eq type 'org-occur) (org-occur reall))
10089 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10090 (t (goto-char (point-min))
10091 (setq type 'fuzzy)
10092 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10093 (org-search-not-self 1 re1 nil t)
10094 (org-search-not-self 1 re2 nil t)
10095 (org-search-not-self 1 re2a nil t)
10096 (org-search-not-self 1 re3 nil t)
10097 (org-search-not-self 1 re4 nil t)
10098 (org-search-not-self 1 re5 nil t)
10100 (goto-char (match-beginning 1))
10101 (goto-char pos)
10102 (error "No match"))))))
10103 (and (derived-mode-p 'org-mode)
10104 (not stealth)
10105 (org-show-context 'link-search))
10106 type))
10108 (defun org-search-not-self (group &rest args)
10109 "Execute `re-search-forward', but only accept matches that do not
10110 enclose the position of `org-open-link-marker'."
10111 (let ((m org-open-link-marker))
10112 (catch 'exit
10113 (while (apply 're-search-forward args)
10114 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10115 (goto-char (match-end group))
10116 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10117 (> (match-beginning 0) (marker-position m))
10118 (< (match-end 0) (marker-position m)))
10119 (save-match-data
10120 (or (not (org-in-regexp
10121 org-bracket-link-analytic-regexp 1))
10122 (not (match-end 4)) ; no description
10123 (and (<= (match-beginning 4) (point))
10124 (>= (match-end 4) (point))))))
10125 (throw 'exit (point))))))))
10127 (defun org-get-buffer-for-internal-link (buffer)
10128 "Return a buffer to be used for displaying the link target of internal links."
10129 (cond
10130 ((not org-display-internal-link-with-indirect-buffer)
10131 buffer)
10132 ((string-match "(Clone)$" (buffer-name buffer))
10133 (message "Buffer is already a clone, not making another one")
10134 ;; we also do not modify visibility in this case
10135 buffer)
10136 (t ; make a new indirect buffer for displaying the link
10137 (let* ((bn (buffer-name buffer))
10138 (ibn (concat bn "(Clone)"))
10139 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10140 (with-current-buffer ib (org-overview))
10141 ib))))
10143 (defun org-do-occur (regexp &optional cleanup)
10144 "Call the Emacs command `occur'.
10145 If CLEANUP is non-nil, remove the printout of the regular expression
10146 in the *Occur* buffer. This is useful if the regex is long and not useful
10147 to read."
10148 (occur regexp)
10149 (when cleanup
10150 (let ((cwin (selected-window)) win beg end)
10151 (when (setq win (get-buffer-window "*Occur*"))
10152 (select-window win))
10153 (goto-char (point-min))
10154 (when (re-search-forward "match[a-z]+" nil t)
10155 (setq beg (match-end 0))
10156 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10157 (setq end (1- (match-beginning 0)))))
10158 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10159 (goto-char (point-min))
10160 (select-window cwin))))
10162 ;;; The mark ring for links jumps
10164 (defvar org-mark-ring nil
10165 "Mark ring for positions before jumps in Org-mode.")
10166 (defvar org-mark-ring-last-goto nil
10167 "Last position in the mark ring used to go back.")
10168 ;; Fill and close the ring
10169 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10170 (loop for i from 1 to org-mark-ring-length do
10171 (push (make-marker) org-mark-ring))
10172 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10173 org-mark-ring)
10175 (defun org-mark-ring-push (&optional pos buffer)
10176 "Put the current position or POS into the mark ring and rotate it."
10177 (interactive)
10178 (setq pos (or pos (point)))
10179 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10180 (move-marker (car org-mark-ring)
10181 (or pos (point))
10182 (or buffer (current-buffer)))
10183 (message "%s"
10184 (substitute-command-keys
10185 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10187 (defun org-mark-ring-goto (&optional n)
10188 "Jump to the previous position in the mark ring.
10189 With prefix arg N, jump back that many stored positions. When
10190 called several times in succession, walk through the entire ring.
10191 Org-mode commands jumping to a different position in the current file,
10192 or to another Org-mode file, automatically push the old position
10193 onto the ring."
10194 (interactive "p")
10195 (let (p m)
10196 (if (eq last-command this-command)
10197 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10198 (setq p org-mark-ring))
10199 (setq org-mark-ring-last-goto p)
10200 (setq m (car p))
10201 (org-pop-to-buffer-same-window (marker-buffer m))
10202 (goto-char m)
10203 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10205 (defun org-remove-angle-brackets (s)
10206 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10207 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10209 (defun org-add-angle-brackets (s)
10210 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10211 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10213 (defun org-remove-double-quotes (s)
10214 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10215 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10218 ;;; Following specific links
10220 (defun org-follow-timestamp-link ()
10221 (cond
10222 ((org-at-date-range-p t)
10223 (let ((org-agenda-start-on-weekday)
10224 (t1 (match-string 1))
10225 (t2 (match-string 2)))
10226 (setq t1 (time-to-days (org-time-string-to-time t1))
10227 t2 (time-to-days (org-time-string-to-time t2)))
10228 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10229 ((org-at-timestamp-p t)
10230 (org-agenda-list nil (time-to-days (org-time-string-to-time
10231 (substring (match-string 1) 0 10)))
10233 (t (error "This should not happen"))))
10236 ;;; Following file links
10237 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10238 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10239 (declare-function mailcap-mime-info
10240 "mailcap" (string &optional request no-decode))
10241 (defvar org-wait nil)
10242 (defun org-open-file (path &optional in-emacs line search)
10243 "Open the file at PATH.
10244 First, this expands any special file name abbreviations. Then the
10245 configuration variable `org-file-apps' is checked if it contains an
10246 entry for this file type, and if yes, the corresponding command is launched.
10248 If no application is found, Emacs simply visits the file.
10250 With optional prefix argument IN-EMACS, Emacs will visit the file.
10251 With a double \\[universal-argument] \\[universal-argument] \
10252 prefix arg, Org tries to avoid opening in Emacs
10253 and to use an external application to visit the file.
10255 Optional LINE specifies a line to go to, optional SEARCH a string
10256 to search for. If LINE or SEARCH is given, the file will be
10257 opened in Emacs, unless an entry from org-file-apps that makes
10258 use of groups in a regexp matches.
10260 If you want to change the way frames are used when following a
10261 link, please customize `org-link-frame-setup'.
10263 If the file does not exist, an error is thrown."
10264 (let* ((file (if (equal path "")
10265 buffer-file-name
10266 (substitute-in-file-name (expand-file-name path))))
10267 (file-apps (append org-file-apps (org-default-apps)))
10268 (apps (org-remove-if
10269 'org-file-apps-entry-match-against-dlink-p file-apps))
10270 (apps-dlink (org-remove-if-not
10271 'org-file-apps-entry-match-against-dlink-p file-apps))
10272 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10273 (dirp (if remp nil (file-directory-p file)))
10274 (file (if (and dirp org-open-directory-means-index-dot-org)
10275 (concat (file-name-as-directory file) "index.org")
10276 file))
10277 (a-m-a-p (assq 'auto-mode apps))
10278 (dfile (downcase file))
10279 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10280 (link (cond ((and (eq line nil)
10281 (eq search nil))
10282 file)
10283 (line
10284 (concat file "::" (number-to-string line)))
10285 (search
10286 (concat file "::" search))))
10287 (dlink (downcase link))
10288 (old-buffer (current-buffer))
10289 (old-pos (point))
10290 (old-mode major-mode)
10291 ext cmd link-match-data)
10292 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10293 (setq ext (match-string 1 dfile))
10294 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10295 (setq ext (match-string 1 dfile))))
10296 (cond
10297 ((member in-emacs '((16) system))
10298 (setq cmd (cdr (assoc 'system apps))))
10299 (in-emacs (setq cmd 'emacs))
10301 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10302 (and dirp (cdr (assoc 'directory apps)))
10303 ; first, try matching against apps-dlink
10304 ; if we get a match here, store the match data for later
10305 (let ((match (assoc-default dlink apps-dlink
10306 'string-match)))
10307 (if match
10308 (progn (setq link-match-data (match-data))
10309 match)
10310 (progn (setq in-emacs (or in-emacs line search))
10311 nil))) ; if we have no match in apps-dlink,
10312 ; always open the file in emacs if line or search
10313 ; is given (for backwards compatibility)
10314 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10315 'string-match)
10316 (cdr (assoc ext apps))
10317 (cdr (assoc t apps))))))
10318 (when (eq cmd 'system)
10319 (setq cmd (cdr (assoc 'system apps))))
10320 (when (eq cmd 'default)
10321 (setq cmd (cdr (assoc t apps))))
10322 (when (eq cmd 'mailcap)
10323 (require 'mailcap)
10324 (mailcap-parse-mailcaps)
10325 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10326 (command (mailcap-mime-info mime-type)))
10327 (if (stringp command)
10328 (setq cmd command)
10329 (setq cmd 'emacs))))
10330 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10331 (not (file-exists-p file))
10332 (not org-open-non-existing-files))
10333 (error "No such file: %s" file))
10334 (cond
10335 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10336 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10337 (while (string-match "['\"]%s['\"]" cmd)
10338 (setq cmd (replace-match "%s" t t cmd)))
10339 (while (string-match "%s" cmd)
10340 (setq cmd (replace-match
10341 (save-match-data
10342 (shell-quote-argument
10343 (convert-standard-filename file)))
10344 t t cmd)))
10346 ;; Replace "%1", "%2" etc. in command with group matches from regex
10347 (save-match-data
10348 (let ((match-index 1)
10349 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10350 (set-match-data link-match-data)
10351 (while (<= match-index number-of-groups)
10352 (let ((regex (concat "%" (number-to-string match-index)))
10353 (replace-with (match-string match-index dlink)))
10354 (while (string-match regex cmd)
10355 (setq cmd (replace-match replace-with t t cmd))))
10356 (setq match-index (+ match-index 1)))))
10358 (save-window-excursion
10359 (start-process-shell-command cmd nil cmd)
10360 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10362 ((or (stringp cmd)
10363 (eq cmd 'emacs))
10364 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10365 (widen)
10366 (if line (org-goto-line line)
10367 (if search (org-link-search search))))
10368 ((consp cmd)
10369 (let ((file (convert-standard-filename file)))
10370 (save-match-data
10371 (set-match-data link-match-data)
10372 (eval cmd))))
10373 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10374 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10375 (or (not (equal old-buffer (current-buffer)))
10376 (not (equal old-pos (point))))
10377 (org-mark-ring-push old-pos old-buffer))))
10379 (defun org-file-apps-entry-match-against-dlink-p (entry)
10380 "This function returns non-nil if `entry' uses a regular
10381 expression which should be matched against the whole link by
10382 org-open-file.
10384 It assumes that is the case when the entry uses a regular
10385 expression which has at least one grouping construct and the
10386 action is either a lisp form or a command string containing
10387 '%1', i.e. using at least one subexpression match as a
10388 parameter."
10389 (let ((selector (car entry))
10390 (action (cdr entry)))
10391 (if (stringp selector)
10392 (and (> (regexp-opt-depth selector) 0)
10393 (or (and (stringp action)
10394 (string-match "%[0-9]" action))
10395 (consp action)))
10396 nil)))
10398 (defun org-default-apps ()
10399 "Return the default applications for this operating system."
10400 (cond
10401 ((eq system-type 'darwin)
10402 org-file-apps-defaults-macosx)
10403 ((eq system-type 'windows-nt)
10404 org-file-apps-defaults-windowsnt)
10405 (t org-file-apps-defaults-gnu)))
10407 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10408 "Convert extensions to regular expressions in the cars of LIST.
10409 Also, weed out any non-string entries, because the return value is used
10410 only for regexp matching.
10411 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10412 point to the symbol `emacs', indicating that the file should
10413 be opened in Emacs."
10414 (append
10415 (delq nil
10416 (mapcar (lambda (x)
10417 (if (not (stringp (car x)))
10419 (if (string-match "\\W" (car x))
10421 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10422 list))
10423 (if add-auto-mode
10424 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10426 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10427 (defun org-file-remote-p (file)
10428 "Test whether FILE specifies a location on a remote system.
10429 Return non-nil if the location is indeed remote.
10431 For example, the filename \"/user@host:/foo\" specifies a location
10432 on the system \"/user@host:\"."
10433 (cond ((fboundp 'file-remote-p)
10434 (file-remote-p file))
10435 ((fboundp 'tramp-handle-file-remote-p)
10436 (tramp-handle-file-remote-p file))
10437 ((and (boundp 'ange-ftp-name-format)
10438 (string-match (car ange-ftp-name-format) file))
10440 (t nil)))
10443 ;;;; Refiling
10445 (defun org-get-org-file ()
10446 "Read a filename, with default directory `org-directory'."
10447 (let ((default (or org-default-notes-file remember-data-file)))
10448 (read-file-name (format "File name [%s]: " default)
10449 (file-name-as-directory org-directory)
10450 default)))
10452 (defun org-notes-order-reversed-p ()
10453 "Check if the current file should receive notes in reversed order."
10454 (cond
10455 ((not org-reverse-note-order) nil)
10456 ((eq t org-reverse-note-order) t)
10457 ((not (listp org-reverse-note-order)) nil)
10458 (t (catch 'exit
10459 (let ((all org-reverse-note-order)
10460 entry)
10461 (while (setq entry (pop all))
10462 (if (string-match (car entry) buffer-file-name)
10463 (throw 'exit (cdr entry))))
10464 nil)))))
10466 (defvar org-refile-target-table nil
10467 "The list of refile targets, created by `org-refile'.")
10469 (defvar org-agenda-new-buffers nil
10470 "Buffers created to visit agenda files.")
10472 (defvar org-refile-cache nil
10473 "Cache for refile targets.")
10475 (defvar org-refile-markers nil
10476 "All the markers used for caching refile locations.")
10478 (defun org-refile-marker (pos)
10479 "Get a new refile marker, but only if caching is in use."
10480 (if (not org-refile-use-cache)
10482 (let ((m (make-marker)))
10483 (move-marker m pos)
10484 (push m org-refile-markers)
10485 m)))
10487 (defun org-refile-cache-clear ()
10488 "Clear the refile cache and disable all the markers."
10489 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10490 (setq org-refile-markers nil)
10491 (setq org-refile-cache nil)
10492 (message "Refile cache has been cleared"))
10494 (defun org-refile-cache-check-set (set)
10495 "Check if all the markers in the cache still have live buffers."
10496 (let (marker)
10497 (catch 'exit
10498 (while (and set (setq marker (nth 3 (pop set))))
10499 ;; if org-refile-use-outline-path is 'file, marker may be nil
10500 (when (and marker (null (marker-buffer marker)))
10501 (message "not found") (sit-for 3)
10502 (throw 'exit nil)))
10503 t)))
10505 (defun org-refile-cache-put (set &rest identifiers)
10506 "Push the refile targets SET into the cache, under IDENTIFIERS."
10507 (let* ((key (sha1 (prin1-to-string identifiers)))
10508 (entry (assoc key org-refile-cache)))
10509 (if entry
10510 (setcdr entry set)
10511 (push (cons key set) org-refile-cache))))
10513 (defun org-refile-cache-get (&rest identifiers)
10514 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10515 (cond
10516 ((not org-refile-cache) nil)
10517 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10519 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10520 org-refile-cache))))
10521 (and set (org-refile-cache-check-set set) set)))))
10523 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10524 "Produce a table with refile targets."
10525 (let ((case-fold-search nil)
10526 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10527 (entries (or org-refile-targets '((nil . (:level . 1)))))
10528 targets tgs txt re files f desc descre fast-path-p level pos0)
10529 (message "Getting targets...")
10530 (with-current-buffer (or default-buffer (current-buffer))
10531 (while (setq entry (pop entries))
10532 (setq files (car entry) desc (cdr entry))
10533 (setq fast-path-p nil)
10534 (cond
10535 ((null files) (setq files (list (current-buffer))))
10536 ((eq files 'org-agenda-files)
10537 (setq files (org-agenda-files 'unrestricted)))
10538 ((and (symbolp files) (fboundp files))
10539 (setq files (funcall files)))
10540 ((and (symbolp files) (boundp files))
10541 (setq files (symbol-value files))))
10542 (if (stringp files) (setq files (list files)))
10543 (cond
10544 ((eq (car desc) :tag)
10545 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10546 ((eq (car desc) :todo)
10547 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10548 ((eq (car desc) :regexp)
10549 (setq descre (cdr desc)))
10550 ((eq (car desc) :level)
10551 (setq descre (concat "^\\*\\{" (number-to-string
10552 (if org-odd-levels-only
10553 (1- (* 2 (cdr desc)))
10554 (cdr desc)))
10555 "\\}[ \t]")))
10556 ((eq (car desc) :maxlevel)
10557 (setq fast-path-p t)
10558 (setq descre (concat "^\\*\\{1," (number-to-string
10559 (if org-odd-levels-only
10560 (1- (* 2 (cdr desc)))
10561 (cdr desc)))
10562 "\\}[ \t]")))
10563 (t (error "Bad refiling target description %s" desc)))
10564 (while (setq f (pop files))
10565 (with-current-buffer
10566 (if (bufferp f) f (org-get-agenda-file-buffer f))
10568 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10569 (progn
10570 (if (bufferp f) (setq f (buffer-file-name
10571 (buffer-base-buffer f))))
10572 (setq f (and f (expand-file-name f)))
10573 (if (eq org-refile-use-outline-path 'file)
10574 (push (list (file-name-nondirectory f) f nil nil) tgs))
10575 (save-excursion
10576 (save-restriction
10577 (widen)
10578 (goto-char (point-min))
10579 (while (re-search-forward descre nil t)
10580 (goto-char (setq pos0 (point-at-bol)))
10581 (catch 'next
10582 (when org-refile-target-verify-function
10583 (save-match-data
10584 (or (funcall org-refile-target-verify-function)
10585 (throw 'next t))))
10586 (when (and (looking-at org-complex-heading-regexp)
10587 (not (member (match-string 4) excluded-entries))
10588 (match-string 4))
10589 (setq level (org-reduced-level
10590 (- (match-end 1) (match-beginning 1)))
10591 txt (org-link-display-format (match-string 4))
10592 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10593 re (format org-complex-heading-regexp-format
10594 (regexp-quote (match-string 4))))
10595 (when org-refile-use-outline-path
10596 (setq txt (mapconcat
10597 'org-protect-slash
10598 (append
10599 (if (eq org-refile-use-outline-path
10600 'file)
10601 (list (file-name-nondirectory
10602 (buffer-file-name
10603 (buffer-base-buffer))))
10604 (if (eq org-refile-use-outline-path
10605 'full-file-path)
10606 (list (buffer-file-name
10607 (buffer-base-buffer)))))
10608 (org-get-outline-path fast-path-p
10609 level txt)
10610 (list txt))
10611 "/")))
10612 (push (list txt f re (org-refile-marker (point)))
10613 tgs)))
10614 (when (= (point) pos0)
10615 ;; verification function has not moved point
10616 (goto-char (point-at-eol))))))))
10617 (when org-refile-use-cache
10618 (org-refile-cache-put tgs (buffer-file-name) descre))
10619 (setq targets (append tgs targets))
10620 ))))
10621 (message "Getting targets...done")
10622 (nreverse targets)))
10624 (defun org-protect-slash (s)
10625 (while (string-match "/" s)
10626 (setq s (replace-match "\\" t t s)))
10629 (defvar org-olpa (make-vector 20 nil))
10631 (defun org-get-outline-path (&optional fastp level heading)
10632 "Return the outline path to the current entry, as a list.
10634 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10635 routine which makes outline path derivations for an entire file,
10636 avoiding backtracing. Refile target collection makes use of that."
10637 (if fastp
10638 (progn
10639 (if (> level 19)
10640 (error "Outline path failure, more than 19 levels"))
10641 (loop for i from level upto 19 do
10642 (aset org-olpa i nil))
10643 (prog1
10644 (delq nil (append org-olpa nil))
10645 (aset org-olpa level heading)))
10646 (let (rtn case-fold-search)
10647 (save-excursion
10648 (save-restriction
10649 (widen)
10650 (while (org-up-heading-safe)
10651 (when (looking-at org-complex-heading-regexp)
10652 (push (org-match-string-no-properties 4) rtn)))
10653 rtn)))))
10655 (defun org-format-outline-path (path &optional width prefix)
10656 "Format the outline path PATH for display.
10657 Width is the maximum number of characters that is available.
10658 Prefix is a prefix to be included in the returned string,
10659 such as the file name."
10660 (setq width (or width 79))
10661 (if prefix (setq width (- width (length prefix))))
10662 (if (not path)
10663 (or prefix "")
10664 (let* ((nsteps (length path))
10665 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10666 (maxwidth (if (<= total-width width)
10667 10000 ;; everything fits
10668 ;; we need to shorten the level headings
10669 (/ (- width nsteps) nsteps)))
10670 (org-odd-levels-only nil)
10671 (n 0)
10672 (total (1+ (length prefix))))
10673 (setq maxwidth (max maxwidth 10))
10674 (concat prefix
10675 (mapconcat
10676 (lambda (h)
10677 (setq n (1+ n))
10678 (if (and (= n nsteps) (< maxwidth 10000))
10679 (setq maxwidth (- total-width total)))
10680 (if (< (length h) maxwidth)
10681 (progn (setq total (+ total (length h) 1)) h)
10682 (setq h (substring h 0 (- maxwidth 2))
10683 total (+ total maxwidth 1))
10684 (if (string-match "[ \t]+\\'" h)
10685 (setq h (substring h 0 (match-beginning 0))))
10686 (setq h (concat h "..")))
10687 (org-add-props h nil 'face
10688 (nth (% (1- n) org-n-level-faces)
10689 org-level-faces))
10691 path "/")))))
10693 (defun org-display-outline-path (&optional file current)
10694 "Display the current outline path in the echo area."
10695 (interactive "P")
10696 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10697 (case-fold-search nil)
10698 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10699 (if current (setq path (append path
10700 (save-excursion
10701 (org-back-to-heading t)
10702 (if (looking-at org-complex-heading-regexp)
10703 (list (match-string 4)))))))
10704 (message "%s"
10705 (org-format-outline-path
10706 path
10707 (1- (frame-width))
10708 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10710 (defvar org-refile-history nil
10711 "History for refiling operations.")
10713 (defvar org-after-refile-insert-hook nil
10714 "Hook run after `org-refile' has inserted its stuff at the new location.
10715 Note that this is still *before* the stuff will be removed from
10716 the *old* location.")
10718 (defvar org-capture-last-stored-marker)
10719 (defun org-refile (&optional goto default-buffer rfloc)
10720 "Move the entry or entries at point to another heading.
10721 The list of target headings is compiled using the information in
10722 `org-refile-targets', which see.
10724 At the target location, the entry is filed as a subitem of the target
10725 heading. Depending on `org-reverse-note-order', the new subitem will
10726 either be the first or the last subitem.
10728 If there is an active region, all entries in that region will be moved.
10729 However, the region must fulfill the requirement that the first heading
10730 is the first one sets the top-level of the moved text - at most siblings
10731 below it are allowed.
10733 With prefix arg GOTO, the command will only visit the target location
10734 and not actually move anything.
10736 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10737 go to the location where the last refiling operation has put the subtree.
10738 With a prefix argument of `2', refile to the running clock.
10740 RFLOC can be a refile location obtained in a different way.
10742 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10744 If you are using target caching (see `org-refile-use-cache'),
10745 you have to clear the target cache in order to find new targets.
10746 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10747 prefix argument (`C-u C-u C-u C-c C-w')."
10749 (interactive "P")
10750 (if (member goto '(0 (64)))
10751 (org-refile-cache-clear)
10752 (let* ((cbuf (current-buffer))
10753 (regionp (org-region-active-p))
10754 (region-start (and regionp (region-beginning)))
10755 (region-end (and regionp (region-end)))
10756 (region-length (and regionp (- region-end region-start)))
10757 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10758 pos it nbuf file re level reversed)
10759 (setq last-command nil)
10760 (when regionp
10761 (goto-char region-start)
10762 (or (bolp) (goto-char (point-at-bol)))
10763 (setq region-start (point))
10764 (unless (or (org-kill-is-subtree-p
10765 (buffer-substring region-start region-end))
10766 (prog1 org-refile-active-region-within-subtree
10767 (org-toggle-heading)))
10768 (error "The region is not a (sequence of) subtree(s)")))
10769 (if (equal goto '(16))
10770 (org-refile-goto-last-stored)
10771 (when (or
10772 (and (equal goto 2)
10773 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10774 (prog1
10775 (setq it (list (or org-clock-heading "running clock")
10776 (buffer-file-name
10777 (marker-buffer org-clock-hd-marker))
10779 (marker-position org-clock-hd-marker)))
10780 (setq goto nil)))
10781 (setq it (or rfloc
10782 (let (heading-text)
10783 (save-excursion
10784 (unless goto
10785 (org-back-to-heading t)
10786 (setq heading-text
10787 (nth 4 (org-heading-components))))
10788 (org-refile-get-location
10789 (cond (goto "Goto")
10790 (regionp "Refile region to")
10791 (t (concat "Refile subtree \""
10792 heading-text "\" to")))
10793 default-buffer
10794 (and (not (equal '(4) goto))
10795 org-refile-allow-creating-parent-nodes)
10796 goto))))))
10797 (setq file (nth 1 it)
10798 re (nth 2 it)
10799 pos (nth 3 it))
10800 (if (and (not goto)
10802 (equal (buffer-file-name) file)
10803 (if regionp
10804 (and (>= pos region-start)
10805 (<= pos region-end))
10806 (and (>= pos (point))
10807 (< pos (save-excursion
10808 (org-end-of-subtree t t))))))
10809 (error "Cannot refile to position inside the tree or region"))
10811 (setq nbuf (or (find-buffer-visiting file)
10812 (find-file-noselect file)))
10813 (if goto
10814 (progn
10815 (org-pop-to-buffer-same-window nbuf)
10816 (goto-char pos)
10817 (org-show-context 'org-goto))
10818 (if regionp
10819 (progn
10820 (org-kill-new (buffer-substring region-start region-end))
10821 (org-save-markers-in-region region-start region-end))
10822 (org-copy-subtree 1 nil t))
10823 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10824 (find-file-noselect file)))
10825 (setq reversed (org-notes-order-reversed-p))
10826 (save-excursion
10827 (save-restriction
10828 (widen)
10829 (if pos
10830 (progn
10831 (goto-char pos)
10832 (looking-at org-outline-regexp)
10833 (setq level (org-get-valid-level (funcall outline-level) 1))
10834 (goto-char
10835 (if reversed
10836 (or (outline-next-heading) (point-max))
10837 (or (save-excursion (org-get-next-sibling))
10838 (org-end-of-subtree t t)
10839 (point-max)))))
10840 (setq level 1)
10841 (if (not reversed)
10842 (goto-char (point-max))
10843 (goto-char (point-min))
10844 (or (outline-next-heading) (goto-char (point-max)))))
10845 (if (not (bolp)) (newline))
10846 (org-paste-subtree level)
10847 (when org-log-refile
10848 (org-add-log-setup 'refile nil nil 'findpos
10849 org-log-refile)
10850 (unless (eq org-log-refile 'note)
10851 (save-excursion (org-add-log-note))))
10852 (and org-auto-align-tags
10853 (let ((org-loop-over-headlines-in-active-region nil))
10854 (org-set-tags nil t)))
10855 (bookmark-set "org-refile-last-stored")
10856 ;; If we are refiling for capture, make sure that the
10857 ;; last-capture pointers point here
10858 (when (org-bound-and-true-p org-refile-for-capture)
10859 (bookmark-set "org-capture-last-stored-marker")
10860 (move-marker org-capture-last-stored-marker (point)))
10861 (if (fboundp 'deactivate-mark) (deactivate-mark))
10862 (run-hooks 'org-after-refile-insert-hook))))
10863 (if regionp
10864 (delete-region (point) (+ (point) region-length))
10865 (org-cut-subtree))
10866 (when (featurep 'org-inlinetask)
10867 (org-inlinetask-remove-END-maybe))
10868 (setq org-markers-to-move nil)
10869 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10871 (defun org-refile-goto-last-stored ()
10872 "Go to the location where the last refile was stored."
10873 (interactive)
10874 (bookmark-jump "org-refile-last-stored")
10875 (message "This is the location of the last refile"))
10877 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10878 no-exclude)
10879 "Prompt the user for a refile location, using PROMPT.
10880 PROMPT should not be suffixed with a colon and a space, because
10881 this function appends the default value from
10882 `org-refile-history' automatically, if that is not empty.
10883 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10884 this is used for the GOTO interface."
10885 (let ((org-refile-targets org-refile-targets)
10886 (org-refile-use-outline-path org-refile-use-outline-path)
10887 excluded-entries)
10888 (when (and (derived-mode-p 'org-mode)
10889 (not org-refile-use-cache)
10890 (not no-exclude))
10891 (org-map-tree
10892 (lambda()
10893 (setq excluded-entries
10894 (append excluded-entries (list (org-get-heading t t)))))))
10895 (setq org-refile-target-table
10896 (org-refile-get-targets default-buffer excluded-entries)))
10897 (unless org-refile-target-table
10898 (error "No refile targets"))
10899 (let* ((prompt (concat prompt
10900 (and (car org-refile-history)
10901 (concat " (default " (car org-refile-history) ")"))
10902 ": "))
10903 (cbuf (current-buffer))
10904 (partial-completion-mode nil)
10905 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10906 (cfunc (if (and org-refile-use-outline-path
10907 org-outline-path-complete-in-steps)
10908 'org-olpath-completing-read
10909 'org-icompleting-read))
10910 (extra (if org-refile-use-outline-path "/" ""))
10911 (filename (and cfn (expand-file-name cfn)))
10912 (tbl (mapcar
10913 (lambda (x)
10914 (if (and (not (member org-refile-use-outline-path
10915 '(file full-file-path)))
10916 (not (equal filename (nth 1 x))))
10917 (cons (concat (car x) extra " ("
10918 (file-name-nondirectory (nth 1 x)) ")")
10919 (cdr x))
10920 (cons (concat (car x) extra) (cdr x))))
10921 org-refile-target-table))
10922 (completion-ignore-case t)
10923 pa answ parent-target child parent old-hist)
10924 (setq old-hist org-refile-history)
10925 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10926 nil 'org-refile-history (car org-refile-history)))
10927 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10928 (org-refile-check-position pa)
10929 (if pa
10930 (progn
10931 (when (or (not org-refile-history)
10932 (not (eq old-hist org-refile-history))
10933 (not (equal (car pa) (car org-refile-history))))
10934 (setq org-refile-history
10935 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10936 org-refile-history
10937 (cdr org-refile-history))))
10938 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10939 (pop org-refile-history)))
10941 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10942 (progn
10943 (setq parent (match-string 1 answ)
10944 child (match-string 2 answ))
10945 (setq parent-target (or (assoc parent tbl)
10946 (assoc (concat parent "/") tbl)))
10947 (when (and parent-target
10948 (or (eq new-nodes t)
10949 (and (eq new-nodes 'confirm)
10950 (y-or-n-p (format "Create new node \"%s\"? "
10951 child)))))
10952 (org-refile-new-child parent-target child)))
10953 (error "Invalid target location")))))
10955 (declare-function org-string-nw-p "org-macs.el" (s))
10956 (defun org-refile-check-position (refile-pointer)
10957 "Check if the refile pointer matches the readline to which it points."
10958 (let* ((file (nth 1 refile-pointer))
10959 (re (nth 2 refile-pointer))
10960 (pos (nth 3 refile-pointer))
10961 buffer)
10962 (when (org-string-nw-p re)
10963 (setq buffer (if (markerp pos)
10964 (marker-buffer pos)
10965 (or (find-buffer-visiting file)
10966 (find-file-noselect file))))
10967 (with-current-buffer buffer
10968 (save-excursion
10969 (save-restriction
10970 (widen)
10971 (goto-char pos)
10972 (beginning-of-line 1)
10973 (unless (org-looking-at-p re)
10974 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10976 (defun org-refile-new-child (parent-target child)
10977 "Use refile target PARENT-TARGET to add new CHILD below it."
10978 (unless parent-target
10979 (error "Cannot find parent for new node"))
10980 (let ((file (nth 1 parent-target))
10981 (pos (nth 3 parent-target))
10982 level)
10983 (with-current-buffer (or (find-buffer-visiting file)
10984 (find-file-noselect file))
10985 (save-excursion
10986 (save-restriction
10987 (widen)
10988 (if pos
10989 (goto-char pos)
10990 (goto-char (point-max))
10991 (if (not (bolp)) (newline)))
10992 (when (looking-at org-outline-regexp)
10993 (setq level (funcall outline-level))
10994 (org-end-of-subtree t t))
10995 (org-back-over-empty-lines)
10996 (insert "\n" (make-string
10997 (if pos (org-get-valid-level level 1) 1) ?*)
10998 " " child "\n")
10999 (beginning-of-line 0)
11000 (list (concat (car parent-target) "/" child) file "" (point)))))))
11002 (defun org-olpath-completing-read (prompt collection &rest args)
11003 "Read an outline path like a file name."
11004 (let ((thetable collection)
11005 (org-completion-use-ido nil) ; does not work with ido.
11006 (org-completion-use-iswitchb nil)) ; or iswitchb
11007 (apply
11008 'org-icompleting-read prompt
11009 (lambda (string predicate &optional flag)
11010 (let (rtn r f (l (length string)))
11011 (cond
11012 ((eq flag nil)
11013 ;; try completion
11014 (try-completion string thetable))
11015 ((eq flag t)
11016 ;; all-completions
11017 (setq rtn (all-completions string thetable predicate))
11018 (mapcar
11019 (lambda (x)
11020 (setq r (substring x l))
11021 (if (string-match " ([^)]*)$" x)
11022 (setq f (match-string 0 x))
11023 (setq f ""))
11024 (if (string-match "/" r)
11025 (concat string (substring r 0 (match-end 0)) f)
11027 rtn))
11028 ((eq flag 'lambda)
11029 ;; exact match?
11030 (assoc string thetable)))))
11031 args)))
11033 ;;;; Dynamic blocks
11035 (defun org-find-dblock (name)
11036 "Find the first dynamic block with name NAME in the buffer.
11037 If not found, stay at current position and return nil."
11038 (let (pos)
11039 (save-excursion
11040 (goto-char (point-min))
11041 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
11042 nil t)
11043 (match-beginning 0))))
11044 (if pos (goto-char pos))
11045 pos))
11047 (defconst org-dblock-start-re
11048 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11049 "Matches the start line of a dynamic block, with parameters.")
11051 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
11052 "Matches the end of a dynamic block.")
11054 (defun org-create-dblock (plist)
11055 "Create a dynamic block section, with parameters taken from PLIST.
11056 PLIST must contain a :name entry which is used as name of the block."
11057 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11058 (end-of-line 1)
11059 (newline))
11060 (let ((col (current-column))
11061 (name (plist-get plist :name)))
11062 (insert "#+BEGIN: " name)
11063 (while plist
11064 (if (eq (car plist) :name)
11065 (setq plist (cddr plist))
11066 (insert " " (prin1-to-string (pop plist)))))
11067 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11068 (beginning-of-line -2)))
11070 (defun org-prepare-dblock ()
11071 "Prepare dynamic block for refresh.
11072 This empties the block, puts the cursor at the insert position and returns
11073 the property list including an extra property :name with the block name."
11074 (unless (looking-at org-dblock-start-re)
11075 (error "Not at a dynamic block"))
11076 (let* ((begdel (1+ (match-end 0)))
11077 (name (org-no-properties (match-string 1)))
11078 (params (append (list :name name)
11079 (read (concat "(" (match-string 3) ")")))))
11080 (save-excursion
11081 (beginning-of-line 1)
11082 (skip-chars-forward " \t")
11083 (setq params (plist-put params :indentation-column (current-column))))
11084 (unless (re-search-forward org-dblock-end-re nil t)
11085 (error "Dynamic block not terminated"))
11086 (setq params
11087 (append params
11088 (list :content (buffer-substring
11089 begdel (match-beginning 0)))))
11090 (delete-region begdel (match-beginning 0))
11091 (goto-char begdel)
11092 (open-line 1)
11093 params))
11095 (defun org-map-dblocks (&optional command)
11096 "Apply COMMAND to all dynamic blocks in the current buffer.
11097 If COMMAND is not given, use `org-update-dblock'."
11098 (let ((cmd (or command 'org-update-dblock)))
11099 (save-excursion
11100 (goto-char (point-min))
11101 (while (re-search-forward org-dblock-start-re nil t)
11102 (goto-char (match-beginning 0))
11103 (save-excursion
11104 (condition-case nil
11105 (funcall cmd)
11106 (error (message "Error during update of dynamic block"))))
11107 (unless (re-search-forward org-dblock-end-re nil t)
11108 (error "Dynamic block not terminated"))))))
11110 (defun org-dblock-update (&optional arg)
11111 "User command for updating dynamic blocks.
11112 Update the dynamic block at point. With prefix ARG, update all dynamic
11113 blocks in the buffer."
11114 (interactive "P")
11115 (if arg
11116 (org-update-all-dblocks)
11117 (or (looking-at org-dblock-start-re)
11118 (org-beginning-of-dblock))
11119 (org-update-dblock)))
11121 (defun org-update-dblock ()
11122 "Update the dynamic block at point.
11123 This means to empty the block, parse for parameters and then call
11124 the correct writing function."
11125 (interactive)
11126 (save-window-excursion
11127 (let* ((pos (point))
11128 (line (org-current-line))
11129 (params (org-prepare-dblock))
11130 (name (plist-get params :name))
11131 (indent (plist-get params :indentation-column))
11132 (cmd (intern (concat "org-dblock-write:" name))))
11133 (message "Updating dynamic block `%s' at line %d..." name line)
11134 (funcall cmd params)
11135 (message "Updating dynamic block `%s' at line %d...done" name line)
11136 (goto-char pos)
11137 (when (and indent (> indent 0))
11138 (setq indent (make-string indent ?\ ))
11139 (save-excursion
11140 (org-beginning-of-dblock)
11141 (forward-line 1)
11142 (while (not (looking-at org-dblock-end-re))
11143 (insert indent)
11144 (beginning-of-line 2))
11145 (when (looking-at org-dblock-end-re)
11146 (and (looking-at "[ \t]+")
11147 (replace-match ""))
11148 (insert indent)))))))
11150 (defun org-beginning-of-dblock ()
11151 "Find the beginning of the dynamic block at point.
11152 Error if there is no such block at point."
11153 (let ((pos (point))
11154 beg)
11155 (end-of-line 1)
11156 (if (and (re-search-backward org-dblock-start-re nil t)
11157 (setq beg (match-beginning 0))
11158 (re-search-forward org-dblock-end-re nil t)
11159 (> (match-end 0) pos))
11160 (goto-char beg)
11161 (goto-char pos)
11162 (error "Not in a dynamic block"))))
11164 ;;;###autoload
11165 (defun org-update-all-dblocks ()
11166 "Update all dynamic blocks in the buffer.
11167 This function can be used in a hook."
11168 (interactive)
11169 (when (derived-mode-p 'org-mode)
11170 (org-map-dblocks 'org-update-dblock)))
11173 ;;;; Completion
11175 (defconst org-additional-option-like-keywords
11176 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11177 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11178 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11179 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11180 "BEGIN:" "END:"
11181 "ORGTBL" "TBLFM:" "TBLNAME:"
11182 "BEGIN_EXAMPLE" "END_EXAMPLE"
11183 "BEGIN_QUOTE" "END_QUOTE"
11184 "BEGIN_VERSE" "END_VERSE"
11185 "BEGIN_CENTER" "END_CENTER"
11186 "BEGIN_SRC" "END_SRC"
11187 "BEGIN_RESULT" "END_RESULT"
11188 "NAME:" "RESULTS:"
11189 "HEADER:" "HEADERS:"
11190 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11191 "CAPTION:" "LABEL:"
11192 "SETUPFILE:"
11193 "INCLUDE:"
11194 "BIND:"
11195 "MACRO:"))
11197 (defcustom org-structure-template-alist
11199 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11200 "<src lang=\"?\">\n\n</src>")
11201 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11202 "<example>\n?\n</example>")
11203 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11204 "<quote>\n?\n</quote>")
11205 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11206 "<verse>\n?\n</verse>")
11207 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11208 "<center>\n?\n</center>")
11209 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11210 "<literal style=\"latex\">\n?\n</literal>")
11211 ("L" "#+LaTeX: "
11212 "<literal style=\"latex\">?</literal>")
11213 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11214 "<literal style=\"html\">\n?\n</literal>")
11215 ("H" "#+HTML: "
11216 "<literal style=\"html\">?</literal>")
11217 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11218 ("A" "#+ASCII: ")
11219 ("i" "#+INDEX: ?"
11220 "#+INDEX: ?")
11221 ("I" "#+INCLUDE %file ?"
11222 "<include file=%file markup=\"?\">")
11224 "Structure completion elements.
11225 This is a list of abbreviation keys and values. The value gets inserted
11226 if you type `<' followed by the key and then press the completion key,
11227 usually `M-TAB'. %file will be replaced by a file name after prompting
11228 for the file using completion. The cursor will be placed at the position
11229 of the `?` in the template.
11230 There are two templates for each key, the first uses the original Org syntax,
11231 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11232 the default when the /org-mtags.el/ module has been loaded. See also the
11233 variable `org-mtags-prefer-muse-templates'."
11234 :group 'org-completion
11235 :type '(repeat
11236 (string :tag "Key")
11237 (string :tag "Template")
11238 (string :tag "Muse Template")))
11240 (defun org-try-structure-completion ()
11241 "Try to complete a structure template before point.
11242 This looks for strings like \"<e\" on an otherwise empty line and
11243 expands them."
11244 (let ((l (buffer-substring (point-at-bol) (point)))
11246 (when (and (looking-at "[ \t]*$")
11247 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11248 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11249 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11250 (match-beginning 1)) a)
11251 t)))
11253 (defun org-complete-expand-structure-template (start cell)
11254 "Expand a structure template."
11255 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11256 (rpl (nth (if musep 2 1) cell))
11257 (ind ""))
11258 (delete-region start (point))
11259 (when (string-match "\\`#\\+" rpl)
11260 (cond
11261 ((bolp))
11262 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11263 (setq ind (buffer-substring (point-at-bol) (point))))
11264 (t (newline))))
11265 (setq start (point))
11266 (if (string-match "%file" rpl)
11267 (setq rpl (replace-match
11268 (concat
11269 "\""
11270 (save-match-data
11271 (abbreviate-file-name (read-file-name "Include file: ")))
11272 "\"")
11273 t t rpl)))
11274 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11275 (concat "\n" ind)))
11276 (insert rpl)
11277 (if (re-search-backward "\\?" start t) (delete-char 1))))
11279 ;;;; TODO, DEADLINE, Comments
11281 (defun org-toggle-comment ()
11282 "Change the COMMENT state of an entry."
11283 (interactive)
11284 (save-excursion
11285 (org-back-to-heading)
11286 (let (case-fold-search)
11287 (cond
11288 ((looking-at (format org-heading-keyword-regexp-format
11289 org-comment-string))
11290 (goto-char (match-end 1))
11291 (looking-at (concat " +" org-comment-string))
11292 (replace-match "" t t)
11293 (when (eolp) (insert " ")))
11294 ((looking-at org-outline-regexp)
11295 (goto-char (match-end 0))
11296 (insert org-comment-string " "))))))
11298 (defvar org-last-todo-state-is-todo nil
11299 "This is non-nil when the last TODO state change led to a TODO state.
11300 If the last change removed the TODO tag or switched to DONE, then
11301 this is nil.")
11303 (defvar org-setting-tags nil) ; dynamically skipped
11305 (defvar org-todo-setup-filter-hook nil
11306 "Hook for functions that pre-filter todo specs.
11307 Each function takes a todo spec and returns either nil or the spec
11308 transformed into canonical form." )
11310 (defvar org-todo-get-default-hook nil
11311 "Hook for functions that get a default item for todo.
11312 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11313 nil or a string to be used for the todo mark." )
11315 (defvar org-agenda-headline-snapshot-before-repeat)
11317 (defun org-current-effective-time ()
11318 "Return current time adjusted for `org-extend-today-until' variable"
11319 (let* ((ct (org-current-time))
11320 (dct (decode-time ct))
11321 (ct1
11322 (if (and org-use-effective-time
11323 (< (nth 2 dct) org-extend-today-until))
11324 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11325 ct)))
11326 ct1))
11328 (defun org-todo-yesterday (&optional arg)
11329 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11330 (interactive "P")
11331 (if (eq major-mode 'org-agenda-mode)
11332 (apply 'org-agenda-todo-yesterday arg)
11333 (let* ((hour (third (decode-time
11334 (org-current-time))))
11335 (org-extend-today-until (1+ hour)))
11336 (org-todo arg))))
11338 (defun org-todo (&optional arg)
11339 "Change the TODO state of an item.
11340 The state of an item is given by a keyword at the start of the heading,
11341 like
11342 *** TODO Write paper
11343 *** DONE Call mom
11345 The different keywords are specified in the variable `org-todo-keywords'.
11346 By default the available states are \"TODO\" and \"DONE\".
11347 So for this example: when the item starts with TODO, it is changed to DONE.
11348 When it starts with DONE, the DONE is removed. And when neither TODO nor
11349 DONE are present, add TODO at the beginning of the heading.
11351 With \\[universal-argument] prefix arg, use completion to determine the new \
11352 state.
11353 With numeric prefix arg, switch to that state.
11354 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11355 keywords (nextset).
11356 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11357 With a numeric prefix arg of 0, inhibit note taking for the change.
11359 For calling through lisp, arg is also interpreted in the following way:
11360 'none -> empty state
11361 \"\"(empty string) -> switch to empty state
11362 'done -> switch to DONE
11363 'nextset -> switch to the next set of keywords
11364 'previousset -> switch to the previous set of keywords
11365 \"WAITING\" -> switch to the specified keyword, but only if it
11366 really is a member of `org-todo-keywords'."
11367 (interactive "P")
11368 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11369 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11370 'region-start-level 'region))
11371 org-loop-over-headlines-in-active-region)
11372 (org-map-entries
11373 `(org-todo ,arg)
11374 org-loop-over-headlines-in-active-region
11375 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11376 (if (equal arg '(16)) (setq arg 'nextset))
11377 (let ((org-blocker-hook org-blocker-hook)
11378 (case-fold-search nil))
11379 (when (equal arg '(64))
11380 (setq arg nil org-blocker-hook nil))
11381 (when (and org-blocker-hook
11382 (or org-inhibit-blocking
11383 (org-entry-get nil "NOBLOCKING")))
11384 (setq org-blocker-hook nil))
11385 (save-excursion
11386 (catch 'exit
11387 (org-back-to-heading t)
11388 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11389 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11390 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11391 (let* ((match-data (match-data))
11392 (startpos (point-at-bol))
11393 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11394 (org-log-done org-log-done)
11395 (org-log-repeat org-log-repeat)
11396 (org-todo-log-states org-todo-log-states)
11397 (org-inhibit-logging
11398 (if (equal arg 0)
11399 (progn (setq arg nil) 'note) org-inhibit-logging))
11400 (this (match-string 1))
11401 (hl-pos (match-beginning 0))
11402 (head (org-get-todo-sequence-head this))
11403 (ass (assoc head org-todo-kwd-alist))
11404 (interpret (nth 1 ass))
11405 (done-word (nth 3 ass))
11406 (final-done-word (nth 4 ass))
11407 (org-last-state (or this ""))
11408 (completion-ignore-case t)
11409 (member (member this org-todo-keywords-1))
11410 (tail (cdr member))
11411 (org-state (cond
11412 ((and org-todo-key-trigger
11413 (or (and (equal arg '(4))
11414 (eq org-use-fast-todo-selection 'prefix))
11415 (and (not arg) org-use-fast-todo-selection
11416 (not (eq org-use-fast-todo-selection
11417 'prefix)))))
11418 ;; Use fast selection
11419 (org-fast-todo-selection))
11420 ((and (equal arg '(4))
11421 (or (not org-use-fast-todo-selection)
11422 (not org-todo-key-trigger)))
11423 ;; Read a state with completion
11424 (org-icompleting-read
11425 "State: " (mapcar (lambda(x) (list x))
11426 org-todo-keywords-1)
11427 nil t))
11428 ((eq arg 'right)
11429 (if this
11430 (if tail (car tail) nil)
11431 (car org-todo-keywords-1)))
11432 ((eq arg 'left)
11433 (if (equal member org-todo-keywords-1)
11435 (if this
11436 (nth (- (length org-todo-keywords-1)
11437 (length tail) 2)
11438 org-todo-keywords-1)
11439 (org-last org-todo-keywords-1))))
11440 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11441 (setq arg nil))) ; hack to fall back to cycling
11442 (arg
11443 ;; user or caller requests a specific state
11444 (cond
11445 ((equal arg "") nil)
11446 ((eq arg 'none) nil)
11447 ((eq arg 'done) (or done-word (car org-done-keywords)))
11448 ((eq arg 'nextset)
11449 (or (car (cdr (member head org-todo-heads)))
11450 (car org-todo-heads)))
11451 ((eq arg 'previousset)
11452 (let ((org-todo-heads (reverse org-todo-heads)))
11453 (or (car (cdr (member head org-todo-heads)))
11454 (car org-todo-heads))))
11455 ((car (member arg org-todo-keywords-1)))
11456 ((stringp arg)
11457 (error "State `%s' not valid in this file" arg))
11458 ((nth (1- (prefix-numeric-value arg))
11459 org-todo-keywords-1))))
11460 ((null member) (or head (car org-todo-keywords-1)))
11461 ((equal this final-done-word) nil) ;; -> make empty
11462 ((null tail) nil) ;; -> first entry
11463 ((memq interpret '(type priority))
11464 (if (eq this-command last-command)
11465 (car tail)
11466 (if (> (length tail) 0)
11467 (or done-word (car org-done-keywords))
11468 nil)))
11470 (car tail))))
11471 (org-state (or
11472 (run-hook-with-args-until-success
11473 'org-todo-get-default-hook org-state org-last-state)
11474 org-state))
11475 (next (if org-state (concat " " org-state " ") " "))
11476 (change-plist (list :type 'todo-state-change :from this :to org-state
11477 :position startpos))
11478 dolog now-done-p)
11479 (when org-blocker-hook
11480 (setq org-last-todo-state-is-todo
11481 (not (member this org-done-keywords)))
11482 (unless (save-excursion
11483 (save-match-data
11484 (org-with-wide-buffer
11485 (run-hook-with-args-until-failure
11486 'org-blocker-hook change-plist))))
11487 (if (org-called-interactively-p 'interactive)
11488 (error "TODO state change from %s to %s blocked" this org-state)
11489 ;; fail silently
11490 (message "TODO state change from %s to %s blocked" this org-state)
11491 (throw 'exit nil))))
11492 (store-match-data match-data)
11493 (replace-match next t t)
11494 (unless (pos-visible-in-window-p hl-pos)
11495 (message "TODO state changed to %s" (org-trim next)))
11496 (unless head
11497 (setq head (org-get-todo-sequence-head org-state)
11498 ass (assoc head org-todo-kwd-alist)
11499 interpret (nth 1 ass)
11500 done-word (nth 3 ass)
11501 final-done-word (nth 4 ass)))
11502 (when (memq arg '(nextset previousset))
11503 (message "Keyword-Set %d/%d: %s"
11504 (- (length org-todo-sets) -1
11505 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11506 (length org-todo-sets)
11507 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11508 (setq org-last-todo-state-is-todo
11509 (not (member org-state org-done-keywords)))
11510 (setq now-done-p (and (member org-state org-done-keywords)
11511 (not (member this org-done-keywords))))
11512 (and logging (org-local-logging logging))
11513 (when (and (or org-todo-log-states org-log-done)
11514 (not (eq org-inhibit-logging t))
11515 (not (memq arg '(nextset previousset))))
11516 ;; we need to look at recording a time and note
11517 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11518 (nth 2 (assoc this org-todo-log-states))))
11519 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11520 (setq dolog 'time))
11521 (when (and org-state
11522 (member org-state org-not-done-keywords)
11523 (not (member this org-not-done-keywords)))
11524 ;; This is now a todo state and was not one before
11525 ;; If there was a CLOSED time stamp, get rid of it.
11526 (org-add-planning-info nil nil 'closed))
11527 (when (and now-done-p org-log-done)
11528 ;; It is now done, and it was not done before
11529 (org-add-planning-info 'closed (org-current-effective-time))
11530 (if (and (not dolog) (eq 'note org-log-done))
11531 (org-add-log-setup 'done org-state this 'findpos 'note)))
11532 (when (and org-state dolog)
11533 ;; This is a non-nil state, and we need to log it
11534 (org-add-log-setup 'state org-state this 'findpos dolog)))
11535 ;; Fixup tag positioning
11536 (org-todo-trigger-tag-changes org-state)
11537 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11538 (when org-provide-todo-statistics
11539 (org-update-parent-todo-statistics))
11540 (run-hooks 'org-after-todo-state-change-hook)
11541 (if (and arg (not (member org-state org-done-keywords)))
11542 (setq head (org-get-todo-sequence-head org-state)))
11543 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11544 ;; Do we need to trigger a repeat?
11545 (when now-done-p
11546 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11547 ;; This is for the agenda, take a snapshot of the headline.
11548 (save-match-data
11549 (setq org-agenda-headline-snapshot-before-repeat
11550 (org-get-heading))))
11551 (org-auto-repeat-maybe org-state))
11552 ;; Fixup cursor location if close to the keyword
11553 (if (and (outline-on-heading-p)
11554 (not (bolp))
11555 (save-excursion (beginning-of-line 1)
11556 (looking-at org-todo-line-regexp))
11557 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11558 (progn
11559 (goto-char (or (match-end 2) (match-end 1)))
11560 (and (looking-at " ") (just-one-space))))
11561 (when org-trigger-hook
11562 (save-excursion
11563 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11565 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11566 "Block turning an entry into a TODO, using the hierarchy.
11567 This checks whether the current task should be blocked from state
11568 changes. Such blocking occurs when:
11570 1. The task has children which are not all in a completed state.
11572 2. A task has a parent with the property :ORDERED:, and there
11573 are siblings prior to the current task with incomplete
11574 status.
11576 3. The parent of the task is blocked because it has siblings that should
11577 be done first, or is child of a block grandparent TODO entry."
11579 (if (not org-enforce-todo-dependencies)
11580 t ; if locally turned off don't block
11581 (catch 'dont-block
11582 ;; If this is not a todo state change, or if this entry is already DONE,
11583 ;; do not block
11584 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11585 (member (plist-get change-plist :from)
11586 (cons 'done org-done-keywords))
11587 (member (plist-get change-plist :to)
11588 (cons 'todo org-not-done-keywords))
11589 (not (plist-get change-plist :to)))
11590 (throw 'dont-block t))
11591 ;; If this task has children, and any are undone, it's blocked
11592 (save-excursion
11593 (org-back-to-heading t)
11594 (let ((this-level (funcall outline-level)))
11595 (outline-next-heading)
11596 (let ((child-level (funcall outline-level)))
11597 (while (and (not (eobp))
11598 (> child-level this-level))
11599 ;; this todo has children, check whether they are all
11600 ;; completed
11601 (if (and (not (org-entry-is-done-p))
11602 (org-entry-is-todo-p))
11603 (throw 'dont-block nil))
11604 (outline-next-heading)
11605 (setq child-level (funcall outline-level))))))
11606 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11607 ;; any previous siblings are undone, it's blocked
11608 (save-excursion
11609 (org-back-to-heading t)
11610 (let* ((pos (point))
11611 (parent-pos (and (org-up-heading-safe) (point))))
11612 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11613 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11614 (forward-line 1)
11615 (re-search-forward org-not-done-heading-regexp pos t))
11616 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11617 ;; Search further up the hierarchy, to see if an ancestor is blocked
11618 (while t
11619 (goto-char parent-pos)
11620 (if (not (looking-at org-not-done-heading-regexp))
11621 (throw 'dont-block t)) ; do not block, parent is not a TODO
11622 (setq pos (point))
11623 (setq parent-pos (and (org-up-heading-safe) (point)))
11624 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11625 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11626 (forward-line 1)
11627 (re-search-forward org-not-done-heading-regexp pos t))
11628 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11630 (defcustom org-track-ordered-property-with-tag nil
11631 "Should the ORDERED property also be shown as a tag?
11632 The ORDERED property decides if an entry should require subtasks to be
11633 completed in sequence. Since a property is not very visible, setting
11634 this option means that toggling the ORDERED property with the command
11635 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11636 not relevant for the behavior, but it makes things more visible.
11638 Note that toggling the tag with tags commands will not change the property
11639 and therefore not influence behavior!
11641 This can be t, meaning the tag ORDERED should be used, It can also be a
11642 string to select a different tag for this task."
11643 :group 'org-todo
11644 :type '(choice
11645 (const :tag "No tracking" nil)
11646 (const :tag "Track with ORDERED tag" t)
11647 (string :tag "Use other tag")))
11649 (defun org-toggle-ordered-property ()
11650 "Toggle the ORDERED property of the current entry.
11651 For better visibility, you can track the value of this property with a tag.
11652 See variable `org-track-ordered-property-with-tag'."
11653 (interactive)
11654 (let* ((t1 org-track-ordered-property-with-tag)
11655 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11656 (save-excursion
11657 (org-back-to-heading)
11658 (if (org-entry-get nil "ORDERED")
11659 (progn
11660 (org-delete-property "ORDERED")
11661 (and tag (org-toggle-tag tag 'off))
11662 (message "Subtasks can be completed in arbitrary order"))
11663 (org-entry-put nil "ORDERED" "t")
11664 (and tag (org-toggle-tag tag 'on))
11665 (message "Subtasks must be completed in sequence")))))
11667 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11668 (defun org-block-todo-from-checkboxes (change-plist)
11669 "Block turning an entry into a TODO, using checkboxes.
11670 This checks whether the current task should be blocked from state
11671 changes because there are unchecked boxes in this entry."
11672 (if (not org-enforce-todo-checkbox-dependencies)
11673 t ; if locally turned off don't block
11674 (catch 'dont-block
11675 ;; If this is not a todo state change, or if this entry is already DONE,
11676 ;; do not block
11677 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11678 (member (plist-get change-plist :from)
11679 (cons 'done org-done-keywords))
11680 (member (plist-get change-plist :to)
11681 (cons 'todo org-not-done-keywords))
11682 (not (plist-get change-plist :to)))
11683 (throw 'dont-block t))
11684 ;; If this task has checkboxes that are not checked, it's blocked
11685 (save-excursion
11686 (org-back-to-heading t)
11687 (let ((beg (point)) end)
11688 (outline-next-heading)
11689 (setq end (point))
11690 (goto-char beg)
11691 (if (org-list-search-forward
11692 (concat (org-item-beginning-re)
11693 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11694 "\\[[- ]\\]")
11695 end t)
11696 (progn
11697 (if (boundp 'org-blocked-by-checkboxes)
11698 (setq org-blocked-by-checkboxes t))
11699 (throw 'dont-block nil)))))
11700 t))) ; do not block
11702 (defun org-entry-blocked-p ()
11703 "Is the current entry blocked?"
11704 (if (org-entry-get nil "NOBLOCKING")
11705 nil ;; Never block this entry
11706 (not
11707 (run-hook-with-args-until-failure
11708 'org-blocker-hook
11709 (list :type 'todo-state-change
11710 :position (point)
11711 :from 'todo
11712 :to 'done)))))
11714 (defun org-update-statistics-cookies (all)
11715 "Update the statistics cookie, either from TODO or from checkboxes.
11716 This should be called with the cursor in a line with a statistics cookie."
11717 (interactive "P")
11718 (if all
11719 (progn
11720 (org-update-checkbox-count 'all)
11721 (org-map-entries 'org-update-parent-todo-statistics))
11722 (if (not (org-at-heading-p))
11723 (org-update-checkbox-count)
11724 (let ((pos (move-marker (make-marker) (point)))
11725 end l1 l2)
11726 (ignore-errors (org-back-to-heading t))
11727 (if (not (org-at-heading-p))
11728 (org-update-checkbox-count)
11729 (setq l1 (org-outline-level))
11730 (setq end (save-excursion
11731 (outline-next-heading)
11732 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11733 (point)))
11734 (if (and (save-excursion
11735 (re-search-forward
11736 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11737 (not (save-excursion (re-search-forward
11738 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11739 (org-update-checkbox-count)
11740 (if (and l2 (> l2 l1))
11741 (progn
11742 (goto-char end)
11743 (org-update-parent-todo-statistics))
11744 (goto-char pos)
11745 (beginning-of-line 1)
11746 (while (re-search-forward
11747 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11748 (point-at-eol) t)
11749 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11750 (goto-char pos)
11751 (move-marker pos nil)))))
11753 (defvar org-entry-property-inherited-from) ;; defined below
11754 (defun org-update-parent-todo-statistics ()
11755 "Update any statistics cookie in the parent of the current headline.
11756 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11757 the entire subtree and this will travel up the hierarchy and update
11758 statistics everywhere."
11759 (let* ((prop (save-excursion (org-up-heading-safe)
11760 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11761 (recursive (or (not org-hierarchical-todo-statistics)
11762 (and prop (string-match "\\<recursive\\>" prop))))
11763 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11765 (first t)
11766 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11767 level ltoggle l1 new ndel
11768 (cnt-all 0) (cnt-done 0) is-percent kwd
11769 checkbox-beg ov ovs ove cookie-present)
11770 (catch 'exit
11771 (save-excursion
11772 (beginning-of-line 1)
11773 (setq ltoggle (funcall outline-level))
11774 ;; Three situations are to consider:
11776 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11777 ;; to the top-level ancestor on the headline;
11779 ;; 2. If parent has "recursive" property, repeat up to the
11780 ;; headline setting that property, taking inheritance into
11781 ;; account;
11783 ;; 3. Else, move up to direct parent and proceed only once.
11784 (while (and (setq level (org-up-heading-safe))
11785 (or recursive first)
11786 (>= (point) lim))
11787 (setq first nil cookie-present nil)
11788 (unless (and level
11789 (not (string-match
11790 "\\<checkbox\\>"
11791 (downcase (or (org-entry-get nil "COOKIE_DATA")
11792 "")))))
11793 (throw 'exit nil))
11794 (while (re-search-forward box-re (point-at-eol) t)
11795 (setq cnt-all 0 cnt-done 0 cookie-present t)
11796 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11797 (save-match-data
11798 (unless (outline-next-heading) (throw 'exit nil))
11799 (while (and (looking-at org-complex-heading-regexp)
11800 (> (setq l1 (length (match-string 1))) level))
11801 (setq kwd (and (or recursive (= l1 ltoggle))
11802 (match-string 2)))
11803 (if (or (eq org-provide-todo-statistics 'all-headlines)
11804 (and (listp org-provide-todo-statistics)
11805 (or (member kwd org-provide-todo-statistics)
11806 (member kwd org-done-keywords))))
11807 (setq cnt-all (1+ cnt-all))
11808 (if (eq org-provide-todo-statistics t)
11809 (and kwd (setq cnt-all (1+ cnt-all)))))
11810 (and (member kwd org-done-keywords)
11811 (setq cnt-done (1+ cnt-done)))
11812 (outline-next-heading)))
11813 (setq new
11814 (if is-percent
11815 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11816 (format "[%d/%d]" cnt-done cnt-all))
11817 ndel (- (match-end 0) checkbox-beg))
11818 ;; handle overlays when updating cookie from column view
11819 (when (setq ov (car (overlays-at checkbox-beg)))
11820 (setq ovs (overlay-start ov) ove (overlay-end ov))
11821 (delete-overlay ov))
11822 (goto-char checkbox-beg)
11823 (insert new)
11824 (delete-region (point) (+ (point) ndel))
11825 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11826 (when ov (move-overlay ov ovs ove)))
11827 (when cookie-present
11828 (run-hook-with-args 'org-after-todo-statistics-hook
11829 cnt-done (- cnt-all cnt-done))))))
11830 (run-hooks 'org-todo-statistics-hook)))
11832 (defvar org-after-todo-statistics-hook nil
11833 "Hook that is called after a TODO statistics cookie has been updated.
11834 Each function is called with two arguments: the number of not-done entries
11835 and the number of done entries.
11837 For example, the following function, when added to this hook, will switch
11838 an entry to DONE when all children are done, and back to TODO when new
11839 entries are set to a TODO status. Note that this hook is only called
11840 when there is a statistics cookie in the headline!
11842 (defun org-summary-todo (n-done n-not-done)
11843 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11844 (let (org-log-done org-log-states) ; turn off logging
11845 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11848 (defvar org-todo-statistics-hook nil
11849 "Hook that is run whenever Org thinks TODO statistics should be updated.
11850 This hook runs even if there is no statistics cookie present, in which case
11851 `org-after-todo-statistics-hook' would not run.")
11853 (defun org-todo-trigger-tag-changes (state)
11854 "Apply the changes defined in `org-todo-state-tags-triggers'."
11855 (let ((l org-todo-state-tags-triggers)
11856 changes)
11857 (when (or (not state) (equal state ""))
11858 (setq changes (append changes (cdr (assoc "" l)))))
11859 (when (and (stringp state) (> (length state) 0))
11860 (setq changes (append changes (cdr (assoc state l)))))
11861 (when (member state org-not-done-keywords)
11862 (setq changes (append changes (cdr (assoc 'todo l)))))
11863 (when (member state org-done-keywords)
11864 (setq changes (append changes (cdr (assoc 'done l)))))
11865 (dolist (c changes)
11866 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11868 (defun org-local-logging (value)
11869 "Get logging settings from a property VALUE."
11870 (let* (words w a)
11871 ;; directly set the variables, they are already local.
11872 (setq org-log-done nil
11873 org-log-repeat nil
11874 org-todo-log-states nil)
11875 (setq words (org-split-string value))
11876 (while (setq w (pop words))
11877 (cond
11878 ((setq a (assoc w org-startup-options))
11879 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11880 (set (nth 1 a) (nth 2 a))))
11881 ((setq a (org-extract-log-state-settings w))
11882 (and (member (car a) org-todo-keywords-1)
11883 (push a org-todo-log-states)))))))
11885 (defun org-get-todo-sequence-head (kwd)
11886 "Return the head of the TODO sequence to which KWD belongs.
11887 If KWD is not set, check if there is a text property remembering the
11888 right sequence."
11889 (let (p)
11890 (cond
11891 ((not kwd)
11892 (or (get-text-property (point-at-bol) 'org-todo-head)
11893 (progn
11894 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11895 nil (point-at-eol)))
11896 (get-text-property p 'org-todo-head))))
11897 ((not (member kwd org-todo-keywords-1))
11898 (car org-todo-keywords-1))
11899 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11901 (defun org-fast-todo-selection ()
11902 "Fast TODO keyword selection with single keys.
11903 Returns the new TODO keyword, or nil if no state change should occur."
11904 (let* ((fulltable org-todo-key-alist)
11905 (done-keywords org-done-keywords) ;; needed for the faces.
11906 (maxlen (apply 'max (mapcar
11907 (lambda (x)
11908 (if (stringp (car x)) (string-width (car x)) 0))
11909 fulltable)))
11910 (expert nil)
11911 (fwidth (+ maxlen 3 1 3))
11912 (ncol (/ (- (window-width) 4) fwidth))
11913 tg cnt e c tbl
11914 groups ingroup)
11915 (save-excursion
11916 (save-window-excursion
11917 (if expert
11918 (set-buffer (get-buffer-create " *Org todo*"))
11919 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11920 (erase-buffer)
11921 (org-set-local 'org-done-keywords done-keywords)
11922 (setq tbl fulltable cnt 0)
11923 (while (setq e (pop tbl))
11924 (cond
11925 ((equal e '(:startgroup))
11926 (push '() groups) (setq ingroup t)
11927 (when (not (= cnt 0))
11928 (setq cnt 0)
11929 (insert "\n"))
11930 (insert "{ "))
11931 ((equal e '(:endgroup))
11932 (setq ingroup nil cnt 0)
11933 (insert "}\n"))
11934 ((equal e '(:newline))
11935 (when (not (= cnt 0))
11936 (setq cnt 0)
11937 (insert "\n")
11938 (setq e (car tbl))
11939 (while (equal (car tbl) '(:newline))
11940 (insert "\n")
11941 (setq tbl (cdr tbl)))))
11943 (setq tg (car e) c (cdr e))
11944 (if ingroup (push tg (car groups)))
11945 (setq tg (org-add-props tg nil 'face
11946 (org-get-todo-face tg)))
11947 (if (and (= cnt 0) (not ingroup)) (insert " "))
11948 (insert "[" c "] " tg (make-string
11949 (- fwidth 4 (length tg)) ?\ ))
11950 (when (= (setq cnt (1+ cnt)) ncol)
11951 (insert "\n")
11952 (if ingroup (insert " "))
11953 (setq cnt 0)))))
11954 (insert "\n")
11955 (goto-char (point-min))
11956 (if (not expert) (org-fit-window-to-buffer))
11957 (message "[a-z..]:Set [SPC]:clear")
11958 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11959 (cond
11960 ((or (= c ?\C-g)
11961 (and (= c ?q) (not (rassoc c fulltable))))
11962 (setq quit-flag t))
11963 ((= c ?\ ) nil)
11964 ((setq e (rassoc c fulltable) tg (car e))
11966 (t (setq quit-flag t)))))))
11968 (defun org-entry-is-todo-p ()
11969 (member (org-get-todo-state) org-not-done-keywords))
11971 (defun org-entry-is-done-p ()
11972 (member (org-get-todo-state) org-done-keywords))
11974 (defun org-get-todo-state ()
11975 (save-excursion
11976 (org-back-to-heading t)
11977 (and (looking-at org-todo-line-regexp)
11978 (match-end 2)
11979 (match-string 2))))
11981 (defun org-at-date-range-p (&optional inactive-ok)
11982 "Is the cursor inside a date range?"
11983 (interactive)
11984 (save-excursion
11985 (catch 'exit
11986 (let ((pos (point)))
11987 (skip-chars-backward "^[<\r\n")
11988 (skip-chars-backward "<[")
11989 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11990 (>= (match-end 0) pos)
11991 (throw 'exit t))
11992 (skip-chars-backward "^<[\r\n")
11993 (skip-chars-backward "<[")
11994 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11995 (>= (match-end 0) pos)
11996 (throw 'exit t)))
11997 nil)))
11999 (defun org-get-repeat (&optional tagline)
12000 "Check if there is a deadline/schedule with repeater in this entry."
12001 (save-match-data
12002 (save-excursion
12003 (org-back-to-heading t)
12004 (and (re-search-forward (if tagline
12005 (concat tagline "\\s-*" org-repeat-re)
12006 org-repeat-re)
12007 (org-entry-end-position) t)
12008 (match-string-no-properties 1)))))
12010 (defvar org-last-changed-timestamp)
12011 (defvar org-last-inserted-timestamp)
12012 (defvar org-log-post-message)
12013 (defvar org-log-note-purpose)
12014 (defvar org-log-note-how)
12015 (defvar org-log-note-extra)
12016 (defun org-auto-repeat-maybe (done-word)
12017 "Check if the current headline contains a repeated deadline/schedule.
12018 If yes, set TODO state back to what it was and change the base date
12019 of repeating deadline/scheduled time stamps to new date.
12020 This function is run automatically after each state change to a DONE state."
12021 ;; last-state is dynamically scoped into this function
12022 (let* ((repeat (org-get-repeat))
12023 (aa (assoc org-last-state org-todo-kwd-alist))
12024 (interpret (nth 1 aa))
12025 (head (nth 2 aa))
12026 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12027 (msg "Entry repeats: ")
12028 (org-log-done nil)
12029 (org-todo-log-states nil)
12030 re type n what ts time to-state)
12031 (when repeat
12032 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12033 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12034 org-todo-repeat-to-state))
12035 (unless (and to-state (member to-state org-todo-keywords-1))
12036 (setq to-state (if (eq interpret 'type) org-last-state head)))
12037 (org-todo to-state)
12038 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12039 (org-entry-put nil "LAST_REPEAT" (format-time-string
12040 (org-time-stamp-format t t))))
12041 (when org-log-repeat
12042 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12043 (memq 'org-add-log-note post-command-hook))
12044 ;; OK, we are already setup for some record
12045 (if (eq org-log-repeat 'note)
12046 ;; make sure we take a note, not only a time stamp
12047 (setq org-log-note-how 'note))
12048 ;; Set up for taking a record
12049 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12050 org-last-state
12051 'findpos org-log-repeat)))
12052 (org-back-to-heading t)
12053 (org-add-planning-info nil nil 'closed)
12054 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12055 org-deadline-time-regexp "\\)\\|\\("
12056 org-ts-regexp "\\)"))
12057 (while (re-search-forward
12058 re (save-excursion (outline-next-heading) (point)) t)
12059 (setq type (if (match-end 1) org-scheduled-string
12060 (if (match-end 3) org-deadline-string "Plain:"))
12061 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12062 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12063 (setq n (string-to-number (match-string 2 ts))
12064 what (match-string 3 ts))
12065 (if (equal what "w") (setq n (* n 7) what "d"))
12066 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12067 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12068 ;; Preparation, see if we need to modify the start date for the change
12069 (when (match-end 1)
12070 (setq time (save-match-data (org-time-string-to-time ts)))
12071 (cond
12072 ((equal (match-string 1 ts) ".")
12073 ;; Shift starting date to today
12074 (org-timestamp-change
12075 (- (org-today) (time-to-days time))
12076 'day))
12077 ((equal (match-string 1 ts) "+")
12078 (let ((nshiftmax 10) (nshift 0))
12079 (while (or (= nshift 0)
12080 (<= (time-to-days time)
12081 (time-to-days (current-time))))
12082 (when (= (incf nshift) nshiftmax)
12083 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12084 (error "Abort")))
12085 (org-timestamp-change n (cdr (assoc what whata)))
12086 (org-at-timestamp-p t)
12087 (setq ts (match-string 1))
12088 (setq time (save-match-data (org-time-string-to-time ts)))))
12089 (org-timestamp-change (- n) (cdr (assoc what whata)))
12090 ;; rematch, so that we have everything in place for the real shift
12091 (org-at-timestamp-p t)
12092 (setq ts (match-string 1))
12093 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12094 (org-timestamp-change n (cdr (assoc what whata)))
12095 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12096 (setq org-log-post-message msg)
12097 (message "%s" msg))))
12099 (defun org-show-todo-tree (arg)
12100 "Make a compact tree which shows all headlines marked with TODO.
12101 The tree will show the lines where the regexp matches, and all higher
12102 headlines above the match.
12103 With a \\[universal-argument] prefix, prompt for a regexp to match.
12104 With a numeric prefix N, construct a sparse tree for the Nth element
12105 of `org-todo-keywords-1'."
12106 (interactive "P")
12107 (let ((case-fold-search nil)
12108 (kwd-re
12109 (cond ((null arg) org-not-done-regexp)
12110 ((equal arg '(4))
12111 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12112 (mapcar 'list org-todo-keywords-1))))
12113 (concat "\\("
12114 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12115 "\\)\\>")))
12116 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12117 (regexp-quote (nth (1- (prefix-numeric-value arg))
12118 org-todo-keywords-1)))
12119 (t (error "Invalid prefix argument: %s" arg)))))
12120 (message "%d TODO entries found"
12121 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12123 (defun org-deadline (&optional remove time)
12124 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12125 With argument REMOVE, remove any deadline from the item.
12126 With argument TIME, set the deadline at the corresponding date. TIME
12127 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12128 (interactive "P")
12129 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12130 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12131 'region-start-level 'region))
12132 org-loop-over-headlines-in-active-region)
12133 (org-map-entries
12134 `(org-deadline ',remove ,time)
12135 org-loop-over-headlines-in-active-region
12136 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12137 (let* ((old-date (org-entry-get nil "DEADLINE"))
12138 (repeater (and old-date
12139 (string-match
12140 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12141 old-date)
12142 (match-string 1 old-date))))
12143 (if remove
12144 (progn
12145 (when (and old-date org-log-redeadline)
12146 (org-add-log-setup 'deldeadline nil old-date 'findpos
12147 org-log-redeadline))
12148 (org-remove-timestamp-with-keyword org-deadline-string)
12149 (message "Item no longer has a deadline."))
12150 (org-add-planning-info 'deadline time 'closed)
12151 (when (and old-date org-log-redeadline
12152 (not (equal old-date
12153 (substring org-last-inserted-timestamp 1 -1))))
12154 (org-add-log-setup 'redeadline nil old-date 'findpos
12155 org-log-redeadline))
12156 (when repeater
12157 (save-excursion
12158 (org-back-to-heading t)
12159 (when (re-search-forward (concat org-deadline-string " "
12160 org-last-inserted-timestamp)
12161 (save-excursion
12162 (outline-next-heading) (point)) t)
12163 (goto-char (1- (match-end 0)))
12164 (insert " " repeater)
12165 (setq org-last-inserted-timestamp
12166 (concat (substring org-last-inserted-timestamp 0 -1)
12167 " " repeater
12168 (substring org-last-inserted-timestamp -1))))))
12169 (message "Deadline on %s" org-last-inserted-timestamp)))))
12171 (defun org-schedule (&optional remove time)
12172 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12173 With argument REMOVE, remove any scheduling date from the item.
12174 With argument TIME, scheduled at the corresponding date. TIME can
12175 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12176 (interactive "P")
12177 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12178 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12179 'region-start-level 'region))
12180 org-loop-over-headlines-in-active-region)
12181 (org-map-entries
12182 `(org-schedule ',remove ,time)
12183 org-loop-over-headlines-in-active-region
12184 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12185 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12186 (repeater (and old-date
12187 (string-match
12188 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12189 old-date)
12190 (match-string 1 old-date))))
12191 (if remove
12192 (progn
12193 (when (and old-date org-log-reschedule)
12194 (org-add-log-setup 'delschedule nil old-date 'findpos
12195 org-log-reschedule))
12196 (org-remove-timestamp-with-keyword org-scheduled-string)
12197 (message "Item is no longer scheduled."))
12198 (org-add-planning-info 'scheduled time 'closed)
12199 (when (and old-date org-log-reschedule
12200 (not (equal old-date
12201 (substring org-last-inserted-timestamp 1 -1))))
12202 (org-add-log-setup 'reschedule nil old-date 'findpos
12203 org-log-reschedule))
12204 (when repeater
12205 (save-excursion
12206 (org-back-to-heading t)
12207 (when (re-search-forward (concat org-scheduled-string " "
12208 org-last-inserted-timestamp)
12209 (save-excursion
12210 (outline-next-heading) (point)) t)
12211 (goto-char (1- (match-end 0)))
12212 (insert " " repeater)
12213 (setq org-last-inserted-timestamp
12214 (concat (substring org-last-inserted-timestamp 0 -1)
12215 " " repeater
12216 (substring org-last-inserted-timestamp -1))))))
12217 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12219 (defun org-get-scheduled-time (pom &optional inherit)
12220 "Get the scheduled time as a time tuple, of a format suitable
12221 for calling org-schedule with, or if there is no scheduling,
12222 returns nil."
12223 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12224 (when time
12225 (apply 'encode-time (org-parse-time-string time)))))
12227 (defun org-get-deadline-time (pom &optional inherit)
12228 "Get the deadline as a time tuple, of a format suitable for
12229 calling org-deadline with, or if there is no scheduling, returns
12230 nil."
12231 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12232 (when time
12233 (apply 'encode-time (org-parse-time-string time)))))
12235 (defun org-remove-timestamp-with-keyword (keyword)
12236 "Remove all time stamps with KEYWORD in the current entry."
12237 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12238 beg)
12239 (save-excursion
12240 (org-back-to-heading t)
12241 (setq beg (point))
12242 (outline-next-heading)
12243 (while (re-search-backward re beg t)
12244 (replace-match "")
12245 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12246 (equal (char-before) ?\ ))
12247 (backward-delete-char 1)
12248 (if (string-match "^[ \t]*$" (buffer-substring
12249 (point-at-bol) (point-at-eol)))
12250 (delete-region (point-at-bol)
12251 (min (point-max) (1+ (point-at-eol))))))))))
12253 (defun org-add-planning-info (what &optional time &rest remove)
12254 "Insert new timestamp with keyword in the line directly after the headline.
12255 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12256 If non is given, the user is prompted for a date.
12257 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12258 be removed."
12259 (interactive)
12260 (let (org-time-was-given org-end-time-was-given ts
12261 end default-time default-input)
12263 (catch 'exit
12264 (when (and (memq what '(scheduled deadline))
12265 (or (not time)
12266 (and (stringp time)
12267 (string-match "^[-+]+[0-9]" time))))
12268 ;; Try to get a default date/time from existing timestamp
12269 (save-excursion
12270 (org-back-to-heading t)
12271 (setq end (save-excursion (outline-next-heading) (point)))
12272 (when (re-search-forward (if (eq what 'scheduled)
12273 org-scheduled-time-regexp
12274 org-deadline-time-regexp)
12275 end t)
12276 (setq ts (match-string 1)
12277 default-time
12278 (apply 'encode-time (org-parse-time-string ts))
12279 default-input (and ts (org-get-compact-tod ts))))))
12280 (when what
12281 (setq time
12282 (if (stringp time)
12283 ;; This is a string (relative or absolute), set proper date
12284 (apply 'encode-time
12285 (org-read-date-analyze
12286 time default-time (decode-time default-time)))
12287 ;; If necessary, get the time from the user
12288 (or time (org-read-date nil 'to-time nil nil
12289 default-time default-input)))))
12291 (when (and org-insert-labeled-timestamps-at-point
12292 (member what '(scheduled deadline)))
12293 (insert
12294 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12295 (org-insert-time-stamp time org-time-was-given
12296 nil nil nil (list org-end-time-was-given))
12297 (setq what nil))
12298 (save-excursion
12299 (save-restriction
12300 (let (col list elt ts buffer-invisibility-spec)
12301 (org-back-to-heading t)
12302 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12303 (goto-char (match-end 1))
12304 (setq col (current-column))
12305 (goto-char (match-end 0))
12306 (if (eobp) (insert "\n") (forward-char 1))
12307 (when (and (not what)
12308 (not (looking-at
12309 (concat "[ \t]*"
12310 org-keyword-time-not-clock-regexp))))
12311 ;; Nothing to add, nothing to remove...... :-)
12312 (throw 'exit nil))
12313 (if (and (not (looking-at org-outline-regexp))
12314 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12315 "[^\r\n]*"))
12316 (not (equal (match-string 1) org-clock-string)))
12317 (narrow-to-region (match-beginning 0) (match-end 0))
12318 (insert-before-markers "\n")
12319 (backward-char 1)
12320 (narrow-to-region (point) (point))
12321 (and org-adapt-indentation (org-indent-to-column col)))
12322 ;; Check if we have to remove something.
12323 (setq list (cons what remove))
12324 (while list
12325 (setq elt (pop list))
12326 (when (or (and (eq elt 'scheduled)
12327 (re-search-forward org-scheduled-time-regexp nil t))
12328 (and (eq elt 'deadline)
12329 (re-search-forward org-deadline-time-regexp nil t))
12330 (and (eq elt 'closed)
12331 (re-search-forward org-closed-time-regexp nil t)))
12332 (replace-match "")
12333 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12334 (and (looking-at "[ \t]+") (replace-match ""))
12335 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12336 (when what
12337 (insert
12338 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12339 (cond ((eq what 'scheduled) org-scheduled-string)
12340 ((eq what 'deadline) org-deadline-string)
12341 ((eq what 'closed) org-closed-string))
12342 " ")
12343 (setq ts (org-insert-time-stamp
12344 time
12345 (or org-time-was-given
12346 (and (eq what 'closed) org-log-done-with-time))
12347 (eq what 'closed)
12348 nil nil (list org-end-time-was-given)))
12349 (insert
12350 (if (not (or (bolp) (eq (char-before) ?\ )
12351 (memq (char-after) '(32 10))
12352 (eobp))) " " ""))
12353 (end-of-line 1))
12354 (goto-char (point-min))
12355 (widen)
12356 (if (and (looking-at "[ \t]*\n")
12357 (equal (char-before) ?\n))
12358 (delete-region (1- (point)) (point-at-eol)))
12359 ts))))))
12361 (defvar org-log-note-marker (make-marker))
12362 (defvar org-log-note-purpose nil)
12363 (defvar org-log-note-state nil)
12364 (defvar org-log-note-previous-state nil)
12365 (defvar org-log-note-how nil)
12366 (defvar org-log-note-extra nil)
12367 (defvar org-log-note-window-configuration nil)
12368 (defvar org-log-note-return-to (make-marker))
12369 (defvar org-log-note-effective-time nil
12370 "Remembered current time so that dynamically scoped
12371 `org-extend-today-until' affects tha timestamps in state change
12372 log")
12374 (defvar org-log-post-message nil
12375 "Message to be displayed after a log note has been stored.
12376 The auto-repeater uses this.")
12378 (defun org-add-note ()
12379 "Add a note to the current entry.
12380 This is done in the same way as adding a state change note."
12381 (interactive)
12382 (org-add-log-setup 'note nil nil 'findpos nil))
12384 (defvar org-property-end-re)
12385 (defun org-add-log-setup (&optional purpose state prev-state
12386 findpos how extra)
12387 "Set up the post command hook to take a note.
12388 If this is about to TODO state change, the new state is expected in STATE.
12389 When FINDPOS is non-nil, find the correct position for the note in
12390 the current entry. If not, assume that it can be inserted at point.
12391 HOW is an indicator what kind of note should be created.
12392 EXTRA is additional text that will be inserted into the notes buffer."
12393 (let* ((org-log-into-drawer (org-log-into-drawer))
12394 (drawer (cond ((stringp org-log-into-drawer)
12395 org-log-into-drawer)
12396 (org-log-into-drawer "LOGBOOK")
12397 (t nil))))
12398 (save-restriction
12399 (save-excursion
12400 (when findpos
12401 (org-back-to-heading t)
12402 (narrow-to-region (point) (save-excursion
12403 (outline-next-heading) (point)))
12404 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12405 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12406 "[^\r\n]*\\)?"))
12407 (goto-char (match-end 0))
12408 (cond
12409 (drawer
12410 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12411 nil t)
12412 (progn
12413 (goto-char (match-end 0))
12414 (or org-log-states-order-reversed
12415 (and (re-search-forward org-property-end-re nil t)
12416 (goto-char (1- (match-beginning 0))))))
12417 (insert "\n:" drawer ":\n:END:")
12418 (beginning-of-line 0)
12419 (org-indent-line)
12420 (beginning-of-line 2)
12421 (org-indent-line)
12422 (end-of-line 0)))
12423 ((and org-log-state-notes-insert-after-drawers
12424 (save-excursion
12425 (forward-line) (looking-at org-drawer-regexp)))
12426 (forward-line)
12427 (while (looking-at org-drawer-regexp)
12428 (goto-char (match-end 0))
12429 (re-search-forward org-property-end-re (point-max) t)
12430 (forward-line))
12431 (forward-line -1)))
12432 (unless org-log-states-order-reversed
12433 (and (= (char-after) ?\n) (forward-char 1))
12434 (org-skip-over-state-notes)
12435 (skip-chars-backward " \t\n\r")))
12436 (move-marker org-log-note-marker (point))
12437 (setq org-log-note-purpose purpose
12438 org-log-note-state state
12439 org-log-note-previous-state prev-state
12440 org-log-note-how how
12441 org-log-note-extra extra
12442 org-log-note-effective-time (org-current-effective-time))
12443 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12445 (defun org-skip-over-state-notes ()
12446 "Skip past the list of State notes in an entry."
12447 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12448 (when (ignore-errors (goto-char (org-in-item-p)))
12449 (let* ((struct (org-list-struct))
12450 (prevs (org-list-prevs-alist struct)))
12451 (while (looking-at "[ \t]*- State")
12452 (goto-char (or (org-list-get-next-item (point) struct prevs)
12453 (org-list-get-item-end (point) struct)))))))
12455 (defun org-add-log-note (&optional purpose)
12456 "Pop up a window for taking a note, and add this note later at point."
12457 (remove-hook 'post-command-hook 'org-add-log-note)
12458 (setq org-log-note-window-configuration (current-window-configuration))
12459 (delete-other-windows)
12460 (move-marker org-log-note-return-to (point))
12461 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12462 (goto-char org-log-note-marker)
12463 (org-switch-to-buffer-other-window "*Org Note*")
12464 (erase-buffer)
12465 (if (memq org-log-note-how '(time state))
12466 (let (current-prefix-arg) (org-store-log-note))
12467 (let ((org-inhibit-startup t)) (org-mode))
12468 (insert (format "# Insert note for %s.
12469 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12470 (cond
12471 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12472 ((eq org-log-note-purpose 'done) "closed todo item")
12473 ((eq org-log-note-purpose 'state)
12474 (format "state change from \"%s\" to \"%s\""
12475 (or org-log-note-previous-state "")
12476 (or org-log-note-state "")))
12477 ((eq org-log-note-purpose 'reschedule)
12478 "rescheduling")
12479 ((eq org-log-note-purpose 'delschedule)
12480 "no longer scheduled")
12481 ((eq org-log-note-purpose 'redeadline)
12482 "changing deadline")
12483 ((eq org-log-note-purpose 'deldeadline)
12484 "removing deadline")
12485 ((eq org-log-note-purpose 'refile)
12486 "refiling")
12487 ((eq org-log-note-purpose 'note)
12488 "this entry")
12489 (t (error "This should not happen")))))
12490 (if org-log-note-extra (insert org-log-note-extra))
12491 (org-set-local 'org-finish-function 'org-store-log-note)
12492 (run-hooks 'org-log-buffer-setup-hook)))
12494 (defvar org-note-abort nil) ; dynamically scoped
12495 (defun org-store-log-note ()
12496 "Finish taking a log note, and insert it to where it belongs."
12497 (let ((txt (buffer-string))
12498 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12499 lines ind bul)
12500 (kill-buffer (current-buffer))
12501 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12502 (setq txt (replace-match "" t t txt)))
12503 (if (string-match "\\s-+\\'" txt)
12504 (setq txt (replace-match "" t t txt)))
12505 (setq lines (org-split-string txt "\n"))
12506 (when (and note (string-match "\\S-" note))
12507 (setq note
12508 (org-replace-escapes
12509 note
12510 (list (cons "%u" (user-login-name))
12511 (cons "%U" user-full-name)
12512 (cons "%t" (format-time-string
12513 (org-time-stamp-format 'long 'inactive)
12514 org-log-note-effective-time))
12515 (cons "%T" (format-time-string
12516 (org-time-stamp-format 'long nil)
12517 org-log-note-effective-time))
12518 (cons "%d" (format-time-string
12519 (org-time-stamp-format nil 'inactive)
12520 org-log-note-effective-time))
12521 (cons "%D" (format-time-string
12522 (org-time-stamp-format nil nil)
12523 org-log-note-effective-time))
12524 (cons "%s" (if org-log-note-state
12525 (concat "\"" org-log-note-state "\"")
12526 ""))
12527 (cons "%S" (if org-log-note-previous-state
12528 (concat "\"" org-log-note-previous-state "\"")
12529 "\"\"")))))
12530 (if lines (setq note (concat note " \\\\")))
12531 (push note lines))
12532 (when (or current-prefix-arg org-note-abort)
12533 (when org-log-into-drawer
12534 (org-remove-empty-drawer-at
12535 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12536 org-log-note-marker))
12537 (setq lines nil))
12538 (when lines
12539 (with-current-buffer (marker-buffer org-log-note-marker)
12540 (save-excursion
12541 (goto-char org-log-note-marker)
12542 (move-marker org-log-note-marker nil)
12543 (end-of-line 1)
12544 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12545 (setq ind (save-excursion
12546 (if (ignore-errors (goto-char (org-in-item-p)))
12547 (let ((struct (org-list-struct)))
12548 (org-list-get-ind
12549 (org-list-get-top-point struct) struct))
12550 (skip-chars-backward " \r\t\n")
12551 (cond
12552 ((and (org-at-heading-p)
12553 org-adapt-indentation)
12554 (1+ (org-current-level)))
12555 ((org-at-heading-p) 0)
12556 (t (org-get-indentation))))))
12557 (setq bul (org-list-bullet-string "-"))
12558 (org-indent-line-to ind)
12559 (insert bul (pop lines))
12560 (let ((ind-body (+ (length bul) ind)))
12561 (while lines
12562 (insert "\n")
12563 (org-indent-line-to ind-body)
12564 (insert (pop lines))))
12565 (message "Note stored")
12566 (org-back-to-heading t)
12567 (org-cycle-hide-drawers 'children)))))
12568 (set-window-configuration org-log-note-window-configuration)
12569 (with-current-buffer (marker-buffer org-log-note-return-to)
12570 (goto-char org-log-note-return-to))
12571 (move-marker org-log-note-return-to nil)
12572 (and org-log-post-message (message "%s" org-log-post-message)))
12574 (defun org-remove-empty-drawer-at (drawer pos)
12575 "Remove an empty drawer DRAWER at position POS.
12576 POS may also be a marker."
12577 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12578 (save-excursion
12579 (save-restriction
12580 (widen)
12581 (goto-char pos)
12582 (if (org-in-regexp
12583 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12584 (replace-match ""))))))
12586 (defun org-sparse-tree (&optional arg)
12587 "Create a sparse tree, prompt for the details.
12588 This command can create sparse trees. You first need to select the type
12589 of match used to create the tree:
12591 t Show all TODO entries.
12592 T Show entries with a specific TODO keyword.
12593 m Show entries selected by a tags/property match.
12594 p Enter a property name and its value (both with completion on existing
12595 names/values) and show entries with that property.
12596 r Show entries matching a regular expression (`/' can be used as well)
12597 d Show deadlines due within `org-deadline-warning-days'.
12598 b Show deadlines and scheduled items before a date.
12599 a Show deadlines and scheduled items after a date."
12600 (interactive "P")
12601 (let (ans kwd value)
12602 (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")
12603 (setq ans (read-char-exclusive))
12604 (cond
12605 ((equal ans ?d)
12606 (call-interactively 'org-check-deadlines))
12607 ((equal ans ?b)
12608 (call-interactively 'org-check-before-date))
12609 ((equal ans ?a)
12610 (call-interactively 'org-check-after-date))
12611 ((equal ans ?D)
12612 (call-interactively 'org-check-dates-range))
12613 ((equal ans ?t)
12614 (org-show-todo-tree nil))
12615 ((equal ans ?T)
12616 (org-show-todo-tree '(4)))
12617 ((member ans '(?T ?m))
12618 (call-interactively 'org-match-sparse-tree))
12619 ((member ans '(?p ?P))
12620 (setq kwd (org-icompleting-read "Property: "
12621 (mapcar 'list (org-buffer-property-keys))))
12622 (setq value (org-icompleting-read "Value: "
12623 (mapcar 'list (org-property-values kwd))))
12624 (unless (string-match "\\`{.*}\\'" value)
12625 (setq value (concat "\"" value "\"")))
12626 (org-match-sparse-tree arg (concat kwd "=" value)))
12627 ((member ans '(?r ?R ?/))
12628 (call-interactively 'org-occur))
12629 (t (error "No such sparse tree command \"%c\"" ans)))))
12631 (defvar org-occur-highlights nil
12632 "List of overlays used for occur matches.")
12633 (make-variable-buffer-local 'org-occur-highlights)
12634 (defvar org-occur-parameters nil
12635 "Parameters of the active org-occur calls.
12636 This is a list, each call to org-occur pushes as cons cell,
12637 containing the regular expression and the callback, onto the list.
12638 The list can contain several entries if `org-occur' has been called
12639 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12640 will only contain one set of parameters. When the highlights are
12641 removed (for example with `C-c C-c', or with the next edit (depending
12642 on `org-remove-highlights-with-change'), this variable is emptied
12643 as well.")
12644 (make-variable-buffer-local 'org-occur-parameters)
12646 (defun org-occur (regexp &optional keep-previous callback)
12647 "Make a compact tree which shows all matches of REGEXP.
12648 The tree will show the lines where the regexp matches, and all higher
12649 headlines above the match. It will also show the heading after the match,
12650 to make sure editing the matching entry is easy.
12651 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12652 call to `org-occur' will be kept, to allow stacking of calls to this
12653 command.
12654 If CALLBACK is non-nil, it is a function which is called to confirm
12655 that the match should indeed be shown."
12656 (interactive "sRegexp: \nP")
12657 (when (equal regexp "")
12658 (error "Regexp cannot be empty"))
12659 (unless keep-previous
12660 (org-remove-occur-highlights nil nil t))
12661 (push (cons regexp callback) org-occur-parameters)
12662 (let ((cnt 0))
12663 (save-excursion
12664 (goto-char (point-min))
12665 (if (or (not keep-previous) ; do not want to keep
12666 (not org-occur-highlights)) ; no previous matches
12667 ;; hide everything
12668 (org-overview))
12669 (while (re-search-forward regexp nil t)
12670 (when (or (not callback)
12671 (save-match-data (funcall callback)))
12672 (setq cnt (1+ cnt))
12673 (when org-highlight-sparse-tree-matches
12674 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12675 (org-show-context 'occur-tree))))
12676 (when org-remove-highlights-with-change
12677 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12678 nil 'local))
12679 (unless org-sparse-tree-open-archived-trees
12680 (org-hide-archived-subtrees (point-min) (point-max)))
12681 (run-hooks 'org-occur-hook)
12682 (if (org-called-interactively-p 'interactive)
12683 (message "%d match(es) for regexp %s" cnt regexp))
12684 cnt))
12686 (defun org-occur-next-match (&optional n reset)
12687 "Function for `next-error-function' to find sparse tree matches.
12688 N is the number of matches to move, when negative move backwards.
12689 RESET is entirely ignored - this function always goes back to the
12690 starting point when no match is found."
12691 (let* ((limit (if (< n 0) (point-min) (point-max)))
12692 (search-func (if (< n 0)
12693 'previous-single-char-property-change
12694 'next-single-char-property-change))
12695 (n (abs n))
12696 (pos (point))
12698 (catch 'exit
12699 (while (setq p1 (funcall search-func (point) 'org-type))
12700 (when (equal p1 limit)
12701 (goto-char pos)
12702 (error "No more matches"))
12703 (when (equal (get-char-property p1 'org-type) 'org-occur)
12704 (setq n (1- n))
12705 (when (= n 0)
12706 (goto-char p1)
12707 (throw 'exit (point))))
12708 (goto-char p1))
12709 (goto-char p1)
12710 (error "No more matches"))))
12712 (defun org-show-context (&optional key)
12713 "Make sure point and context are visible.
12714 How much context is shown depends upon the variables
12715 `org-show-hierarchy-above', `org-show-following-heading',
12716 `org-show-entry-below' and `org-show-siblings'."
12717 (let ((heading-p (org-at-heading-p t))
12718 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12719 (following-p (org-get-alist-option org-show-following-heading key))
12720 (entry-p (org-get-alist-option org-show-entry-below key))
12721 (siblings-p (org-get-alist-option org-show-siblings key)))
12722 (catch 'exit
12723 ;; Show heading or entry text
12724 (if (and heading-p (not entry-p))
12725 (org-flag-heading nil) ; only show the heading
12726 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12727 (org-show-hidden-entry))) ; show entire entry
12728 (when following-p
12729 ;; Show next sibling, or heading below text
12730 (save-excursion
12731 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12732 (org-flag-heading nil))))
12733 (when siblings-p (org-show-siblings))
12734 (when hierarchy-p
12735 ;; show all higher headings, possibly with siblings
12736 (save-excursion
12737 (while (and (condition-case nil
12738 (progn (org-up-heading-all 1) t)
12739 (error nil))
12740 (not (bobp)))
12741 (org-flag-heading nil)
12742 (when siblings-p (org-show-siblings))))))))
12744 (defvar org-reveal-start-hook nil
12745 "Hook run before revealing a location.")
12747 (defun org-reveal (&optional siblings)
12748 "Show current entry, hierarchy above it, and the following headline.
12749 This can be used to show a consistent set of context around locations
12750 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12751 not t for the search context.
12753 With optional argument SIBLINGS, on each level of the hierarchy all
12754 siblings are shown. This repairs the tree structure to what it would
12755 look like when opened with hierarchical calls to `org-cycle'.
12756 With double optional argument \\[universal-argument] \\[universal-argument], \
12757 go to the parent and show the
12758 entire tree."
12759 (interactive "P")
12760 (run-hooks 'org-reveal-start-hook)
12761 (let ((org-show-hierarchy-above t)
12762 (org-show-following-heading t)
12763 (org-show-siblings (if siblings t org-show-siblings)))
12764 (org-show-context nil))
12765 (when (equal siblings '(16))
12766 (save-excursion
12767 (when (org-up-heading-safe)
12768 (org-show-subtree)
12769 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12771 (defun org-highlight-new-match (beg end)
12772 "Highlight from BEG to END and mark the highlight is an occur headline."
12773 (let ((ov (make-overlay beg end)))
12774 (overlay-put ov 'face 'secondary-selection)
12775 (overlay-put ov 'org-type 'org-occur)
12776 (push ov org-occur-highlights)))
12778 (defun org-remove-occur-highlights (&optional beg end noremove)
12779 "Remove the occur highlights from the buffer.
12780 BEG and END are ignored. If NOREMOVE is nil, remove this function
12781 from the `before-change-functions' in the current buffer."
12782 (interactive)
12783 (unless org-inhibit-highlight-removal
12784 (mapc 'delete-overlay org-occur-highlights)
12785 (setq org-occur-highlights nil)
12786 (setq org-occur-parameters nil)
12787 (unless noremove
12788 (remove-hook 'before-change-functions
12789 'org-remove-occur-highlights 'local))))
12791 ;;;; Priorities
12793 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12794 "Regular expression matching the priority indicator.")
12796 (defvar org-remove-priority-next-time nil)
12798 (defun org-priority-up ()
12799 "Increase the priority of the current item."
12800 (interactive)
12801 (org-priority 'up))
12803 (defun org-priority-down ()
12804 "Decrease the priority of the current item."
12805 (interactive)
12806 (org-priority 'down))
12808 (defun org-priority (&optional action)
12809 "Change the priority of an item by ARG.
12810 ACTION can be `set', `up', `down', or a character."
12811 (interactive)
12812 (unless org-enable-priority-commands
12813 (error "Priority commands are disabled"))
12814 (setq action (or action 'set))
12815 (let (current new news have remove)
12816 (save-excursion
12817 (org-back-to-heading t)
12818 (if (looking-at org-priority-regexp)
12819 (setq current (string-to-char (match-string 2))
12820 have t))
12821 (cond
12822 ((eq action 'remove)
12823 (setq remove t new ?\ ))
12824 ((or (eq action 'set)
12825 (if (featurep 'xemacs) (characterp action) (integerp action)))
12826 (if (not (eq action 'set))
12827 (setq new action)
12828 (message "Priority %c-%c, SPC to remove: "
12829 org-highest-priority org-lowest-priority)
12830 (save-match-data
12831 (setq new (read-char-exclusive))))
12832 (if (and (= (upcase org-highest-priority) org-highest-priority)
12833 (= (upcase org-lowest-priority) org-lowest-priority))
12834 (setq new (upcase new)))
12835 (cond ((equal new ?\ ) (setq remove t))
12836 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12837 (error "Priority must be between `%c' and `%c'"
12838 org-highest-priority org-lowest-priority))))
12839 ((eq action 'up)
12840 (setq new (if have
12841 (1- current) ; normal cycling
12842 ;; last priority was empty
12843 (if (eq last-command this-command)
12844 org-lowest-priority ; wrap around empty to lowest
12845 ;; default
12846 (if org-priority-start-cycle-with-default
12847 org-default-priority
12848 (1- org-default-priority))))))
12849 ((eq action 'down)
12850 (setq new (if have
12851 (1+ current) ; normal cycling
12852 ;; last priority was empty
12853 (if (eq last-command this-command)
12854 org-highest-priority ; wrap around empty to highest
12855 ;; default
12856 (if org-priority-start-cycle-with-default
12857 org-default-priority
12858 (1+ org-default-priority))))))
12859 (t (error "Invalid action")))
12860 (if (or (< (upcase new) org-highest-priority)
12861 (> (upcase new) org-lowest-priority))
12862 (if (and (memq action '(up down))
12863 (not have) (not (eq last-command this-command)))
12864 ;; `new' is from default priority
12865 (error
12866 "The default can not be set, see `org-default-priority' why")
12867 ;; normal cycling: `new' is beyond highest/lowest priority
12868 ;; and is wrapped around to the empty priority
12869 (setq remove t)))
12870 (setq news (format "%c" new))
12871 (if have
12872 (if remove
12873 (replace-match "" t t nil 1)
12874 (replace-match news t t nil 2))
12875 (if remove
12876 (error "No priority cookie found in line")
12877 (let ((case-fold-search nil))
12878 (looking-at org-todo-line-regexp))
12879 (if (match-end 2)
12880 (progn
12881 (goto-char (match-end 2))
12882 (insert " [#" news "]"))
12883 (goto-char (match-beginning 3))
12884 (insert "[#" news "] "))))
12885 (org-preserve-lc (org-set-tags nil 'align)))
12886 (if remove
12887 (message "Priority removed")
12888 (message "Priority of current item set to %s" news))))
12890 (defun org-get-priority (s)
12891 "Find priority cookie and return priority."
12892 (if (functionp org-get-priority-function)
12893 (funcall org-get-priority-function)
12894 (save-match-data
12895 (if (not (string-match org-priority-regexp s))
12896 (* 1000 (- org-lowest-priority org-default-priority))
12897 (* 1000 (- org-lowest-priority
12898 (string-to-char (match-string 2 s))))))))
12900 ;;;; Tags
12902 (defvar org-agenda-archives-mode)
12903 (defvar org-map-continue-from nil
12904 "Position from where mapping should continue.
12905 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12907 (defvar org-scanner-tags nil
12908 "The current tag list while the tags scanner is running.")
12909 (defvar org-trust-scanner-tags nil
12910 "Should `org-get-tags-at' use the tags for the scanner.
12911 This is for internal dynamical scoping only.
12912 When this is non-nil, the function `org-get-tags-at' will return the value
12913 of `org-scanner-tags' instead of building the list by itself. This
12914 can lead to large speed-ups when the tags scanner is used in a file with
12915 many entries, and when the list of tags is retrieved, for example to
12916 obtain a list of properties. Building the tags list for each entry in such
12917 a file becomes an N^2 operation - but with this variable set, it scales
12918 as N.")
12920 (defun org-scan-tags (action matcher todo-only &optional start-level)
12921 "Scan headline tags with inheritance and produce output ACTION.
12923 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12924 or `agenda' to produce an entry list for an agenda view. It can also be
12925 a Lisp form or a function that should be called at each matched headline, in
12926 this case the return value is a list of all return values from these calls.
12928 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12929 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12930 only lines with a not-done TODO keyword are included in the output.
12931 This should be the same variable that was scoped into
12932 and set by `org-make-tags-matcher' when it constructed MATCHER.
12934 START-LEVEL can be a string with asterisks, reducing the scope to
12935 headlines matching this string."
12936 (require 'org-agenda)
12937 (let* ((re (concat "^"
12938 (if start-level
12939 ;; Get the correct level to match
12940 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12941 org-outline-regexp)
12942 " *\\(\\<\\("
12943 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12944 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12945 (props (list 'face 'default
12946 'done-face 'org-agenda-done
12947 'undone-face 'default
12948 'mouse-face 'highlight
12949 'org-not-done-regexp org-not-done-regexp
12950 'org-todo-regexp org-todo-regexp
12951 'org-complex-heading-regexp org-complex-heading-regexp
12952 'help-echo
12953 (format "mouse-2 or RET jump to org file %s"
12954 (abbreviate-file-name
12955 (or (buffer-file-name (buffer-base-buffer))
12956 (buffer-name (buffer-base-buffer)))))))
12957 (case-fold-search nil)
12958 (org-map-continue-from nil)
12959 lspos tags tags-list
12960 (tags-alist (list (cons 0 org-file-tags)))
12961 (llast 0) rtn rtn1 level category i txt
12962 todo marker entry priority)
12963 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12964 (setq action (list 'lambda nil action)))
12965 (save-excursion
12966 (goto-char (point-min))
12967 (when (eq action 'sparse-tree)
12968 (org-overview)
12969 (org-remove-occur-highlights))
12970 (while (re-search-forward re nil t)
12971 (setq org-map-continue-from nil)
12972 (catch :skip
12973 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12974 tags (if (match-end 4) (org-match-string-no-properties 4)))
12975 (goto-char (setq lspos (match-beginning 0)))
12976 (setq level (org-reduced-level (funcall outline-level))
12977 category (org-get-category))
12978 (setq i llast llast level)
12979 ;; remove tag lists from same and sublevels
12980 (while (>= i level)
12981 (when (setq entry (assoc i tags-alist))
12982 (setq tags-alist (delete entry tags-alist)))
12983 (setq i (1- i)))
12984 ;; add the next tags
12985 (when tags
12986 (setq tags (org-split-string tags ":")
12987 tags-alist
12988 (cons (cons level tags) tags-alist)))
12989 ;; compile tags for current headline
12990 (setq tags-list
12991 (if org-use-tag-inheritance
12992 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12993 tags)
12994 org-scanner-tags tags-list)
12995 (when org-use-tag-inheritance
12996 (setcdr (car tags-alist)
12997 (mapcar (lambda (x)
12998 (setq x (copy-sequence x))
12999 (org-add-prop-inherited x))
13000 (cdar tags-alist))))
13001 (when (and tags org-use-tag-inheritance
13002 (or (not (eq t org-use-tag-inheritance))
13003 org-tags-exclude-from-inheritance))
13004 ;; selective inheritance, remove uninherited ones
13005 (setcdr (car tags-alist)
13006 (org-remove-uninherited-tags (cdar tags-alist))))
13007 (when (and
13009 ;; eval matcher only when the todo condition is OK
13010 (and (or (not todo-only) (member todo org-not-done-keywords))
13011 (let ((case-fold-search t) (org-trust-scanner-tags t))
13012 (eval matcher)))
13014 ;; Call the skipper, but return t if it does not skip,
13015 ;; so that the `and' form continues evaluating
13016 (progn
13017 (unless (eq action 'sparse-tree) (org-agenda-skip))
13020 ;; Check if timestamps are deselecting this entry
13021 (or (not todo-only)
13022 (and (member todo org-not-done-keywords)
13023 (or (not org-agenda-tags-todo-honor-ignore-options)
13024 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13026 ;; Extra check for the archive tag
13027 ;; FIXME: Does the skipper already do this????
13029 (not (member org-archive-tag tags-list))
13030 ;; we have an archive tag, should we use this anyway?
13031 (or (not org-agenda-skip-archived-trees)
13032 (and (eq action 'agenda) org-agenda-archives-mode))))
13034 ;; select this headline
13036 (cond
13037 ((eq action 'sparse-tree)
13038 (and org-highlight-sparse-tree-matches
13039 (org-get-heading) (match-end 0)
13040 (org-highlight-new-match
13041 (match-beginning 1) (match-end 1)))
13042 (org-show-context 'tags-tree))
13043 ((eq action 'agenda)
13044 (setq txt (org-agenda-format-item
13046 (concat
13047 (if (eq org-tags-match-list-sublevels 'indented)
13048 (make-string (1- level) ?.) "")
13049 (org-get-heading))
13050 category
13051 tags-list)
13052 priority (org-get-priority txt))
13053 (goto-char lspos)
13054 (setq marker (org-agenda-new-marker))
13055 (org-add-props txt props
13056 'org-marker marker 'org-hd-marker marker 'org-category category
13057 'todo-state todo
13058 'priority priority 'type "tagsmatch")
13059 (push txt rtn))
13060 ((functionp action)
13061 (setq org-map-continue-from nil)
13062 (save-excursion
13063 (setq rtn1 (funcall action))
13064 (push rtn1 rtn)))
13065 (t (error "Invalid action")))
13067 ;; if we are to skip sublevels, jump to end of subtree
13068 (unless org-tags-match-list-sublevels
13069 (org-end-of-subtree t)
13070 (backward-char 1))))
13071 ;; Get the correct position from where to continue
13072 (if org-map-continue-from
13073 (goto-char org-map-continue-from)
13074 (and (= (point) lspos) (end-of-line 1)))))
13075 (when (and (eq action 'sparse-tree)
13076 (not org-sparse-tree-open-archived-trees))
13077 (org-hide-archived-subtrees (point-min) (point-max)))
13078 (nreverse rtn)))
13080 (defun org-remove-uninherited-tags (tags)
13081 "Remove all tags that are not inherited from the list TAGS."
13082 (cond
13083 ((eq org-use-tag-inheritance t)
13084 (if org-tags-exclude-from-inheritance
13085 (org-delete-all org-tags-exclude-from-inheritance tags)
13086 tags))
13087 ((not org-use-tag-inheritance) nil)
13088 ((stringp org-use-tag-inheritance)
13089 (delq nil (mapcar
13090 (lambda (x)
13091 (if (and (string-match org-use-tag-inheritance x)
13092 (not (member x org-tags-exclude-from-inheritance)))
13093 x nil))
13094 tags)))
13095 ((listp org-use-tag-inheritance)
13096 (delq nil (mapcar
13097 (lambda (x)
13098 (if (member x org-use-tag-inheritance) x nil))
13099 tags)))))
13101 (defun org-match-sparse-tree (&optional todo-only match)
13102 "Create a sparse tree according to tags string MATCH.
13103 MATCH can contain positive and negative selection of tags, like
13104 \"+WORK+URGENT-WITHBOSS\".
13105 If optional argument TODO-ONLY is non-nil, only select lines that are
13106 also TODO lines."
13107 (interactive "P")
13108 (org-prepare-agenda-buffers (list (current-buffer)))
13109 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13111 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13113 (defvar org-cached-props nil)
13114 (defun org-cached-entry-get (pom property)
13115 (if (or (eq t org-use-property-inheritance)
13116 (and (stringp org-use-property-inheritance)
13117 (string-match org-use-property-inheritance property))
13118 (and (listp org-use-property-inheritance)
13119 (member property org-use-property-inheritance)))
13120 ;; Caching is not possible, check it directly
13121 (org-entry-get pom property 'inherit)
13122 ;; Get all properties, so that we can do complicated checks easily
13123 (cdr (assoc property (or org-cached-props
13124 (setq org-cached-props
13125 (org-entry-properties pom)))))))
13127 (defun org-global-tags-completion-table (&optional files)
13128 "Return the list of all tags in all agenda buffer/files.
13129 Optional FILES argument is a list of files to which can be used
13130 instead of the agenda files."
13131 (save-excursion
13132 (org-uniquify
13133 (delq nil
13134 (apply 'append
13135 (mapcar
13136 (lambda (file)
13137 (set-buffer (find-file-noselect file))
13138 (append (org-get-buffer-tags)
13139 (mapcar (lambda (x) (if (stringp (car-safe x))
13140 (list (car-safe x)) nil))
13141 org-tag-alist)))
13142 (if (and files (car files))
13143 files
13144 (org-agenda-files))))))))
13146 (defun org-make-tags-matcher (match)
13147 "Create the TAGS/TODO matcher form for the selection string MATCH.
13149 The variable `todo-only' is scoped dynamically into this function; it will be
13150 set to t if the matcher restricts matching to TODO entries,
13151 otherwise will not be touched.
13153 Returns a cons of the selection string MATCH and the constructed
13154 lisp form implementing the matcher. The matcher is to be
13155 evaluated at an Org entry, with point on the headline,
13156 and returns t if the entry matches the
13157 selection string MATCH. The returned lisp form references
13158 two variables with information about the entry, which must be
13159 bound around the form's evaluation: todo, the TODO keyword at the
13160 entry (or nil of none); and tags-list, the list of all tags at the
13161 entry including inherited ones. Additionally, the category
13162 of the entry (if any) must be specified as the text property
13163 'org-category on the headline.
13165 See also `org-scan-tags'.
13167 (declare (special todo-only))
13168 (unless (boundp 'todo-only)
13169 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13170 (unless match
13171 ;; Get a new match request, with completion
13172 (let ((org-last-tags-completion-table
13173 (org-global-tags-completion-table)))
13174 (setq match (org-completing-read-no-i
13175 "Match: " 'org-tags-completion-function nil nil nil
13176 'org-tags-history))))
13178 ;; Parse the string and create a lisp form
13179 (let ((match0 match)
13180 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13181 minus tag mm
13182 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13183 orterms term orlist re-p str-p level-p level-op time-p
13184 prop-p pn pv po gv rest)
13185 (if (string-match "/+" match)
13186 ;; match contains also a todo-matching request
13187 (progn
13188 (setq tagsmatch (substring match 0 (match-beginning 0))
13189 todomatch (substring match (match-end 0)))
13190 (if (string-match "^!" todomatch)
13191 (setq todo-only t todomatch (substring todomatch 1)))
13192 (if (string-match "^\\s-*$" todomatch)
13193 (setq todomatch nil)))
13194 ;; only matching tags
13195 (setq tagsmatch match todomatch nil))
13197 ;; Make the tags matcher
13198 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13199 (setq tagsmatcher t)
13200 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13201 (while (setq term (pop orterms))
13202 (while (and (equal (substring term -1) "\\") orterms)
13203 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13204 (while (string-match re term)
13205 (setq rest (substring term (match-end 0))
13206 minus (and (match-end 1)
13207 (equal (match-string 1 term) "-"))
13208 tag (save-match-data (replace-regexp-in-string
13209 "\\\\-" "-"
13210 (match-string 2 term)))
13211 re-p (equal (string-to-char tag) ?{)
13212 level-p (match-end 4)
13213 prop-p (match-end 5)
13214 mm (cond
13215 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13216 (level-p
13217 (setq level-op (org-op-to-function (match-string 3 term)))
13218 `(,level-op level ,(string-to-number
13219 (match-string 4 term))))
13220 (prop-p
13221 (setq pn (match-string 5 term)
13222 po (match-string 6 term)
13223 pv (match-string 7 term)
13224 re-p (equal (string-to-char pv) ?{)
13225 str-p (equal (string-to-char pv) ?\")
13226 time-p (save-match-data
13227 (string-match "^\"[[<].*[]>]\"$" pv))
13228 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13229 (if time-p (setq pv (org-matcher-time pv)))
13230 (setq po (org-op-to-function po (if time-p 'time str-p)))
13231 (cond
13232 ((equal pn "CATEGORY")
13233 (setq gv '(get-text-property (point) 'org-category)))
13234 ((equal pn "TODO")
13235 (setq gv 'todo))
13237 (setq gv `(org-cached-entry-get nil ,pn))))
13238 (if re-p
13239 (if (eq po 'org<>)
13240 `(not (string-match ,pv (or ,gv "")))
13241 `(string-match ,pv (or ,gv "")))
13242 (if str-p
13243 `(,po (or ,gv "") ,pv)
13244 `(,po (string-to-number (or ,gv ""))
13245 ,(string-to-number pv) ))))
13246 (t `(member ,tag tags-list)))
13247 mm (if minus (list 'not mm) mm)
13248 term rest)
13249 (push mm tagsmatcher))
13250 (push (if (> (length tagsmatcher) 1)
13251 (cons 'and tagsmatcher)
13252 (car tagsmatcher))
13253 orlist)
13254 (setq tagsmatcher nil))
13255 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13256 (setq tagsmatcher
13257 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13258 ;; Make the todo matcher
13259 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13260 (setq todomatcher t)
13261 (setq orterms (org-split-string todomatch "|") orlist nil)
13262 (while (setq term (pop orterms))
13263 (while (string-match re term)
13264 (setq minus (and (match-end 1)
13265 (equal (match-string 1 term) "-"))
13266 kwd (match-string 2 term)
13267 re-p (equal (string-to-char kwd) ?{)
13268 term (substring term (match-end 0))
13269 mm (if re-p
13270 `(string-match ,(substring kwd 1 -1) todo)
13271 (list 'equal 'todo kwd))
13272 mm (if minus (list 'not mm) mm))
13273 (push mm todomatcher))
13274 (push (if (> (length todomatcher) 1)
13275 (cons 'and todomatcher)
13276 (car todomatcher))
13277 orlist)
13278 (setq todomatcher nil))
13279 (setq todomatcher (if (> (length orlist) 1)
13280 (cons 'or orlist) (car orlist))))
13282 ;; Return the string and lisp forms of the matcher
13283 (setq matcher (if todomatcher
13284 (list 'and tagsmatcher todomatcher)
13285 tagsmatcher))
13286 (when todo-only
13287 (setq matcher (list 'and '(member todo org-not-done-keywords)
13288 matcher)))
13289 (cons match0 matcher)))
13291 (defun org-op-to-function (op &optional stringp)
13292 "Turn an operator into the appropriate function."
13293 (setq op
13294 (cond
13295 ((equal op "<" ) '(< string< org-time<))
13296 ((equal op ">" ) '(> org-string> org-time>))
13297 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13298 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13299 ((member op '("=" "==")) '(= string= org-time=))
13300 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13301 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13303 (defun org<> (a b) (not (= a b)))
13304 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13305 (defun org-string>= (a b) (not (string< a b)))
13306 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13307 (defun org-string<> (a b) (not (string= a b)))
13308 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13309 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13310 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13311 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13312 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13313 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13314 (defun org-2ft (s)
13315 "Convert S to a floating point time.
13316 If S is already a number, just return it. If it is a string, parse
13317 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13318 (cond
13319 ((numberp s) s)
13320 ((stringp s)
13321 (condition-case nil
13322 (float-time (apply 'encode-time (org-parse-time-string s)))
13323 (error 0.)))
13324 (t 0.)))
13326 (defun org-time-today ()
13327 "Time in seconds today at 0:00.
13328 Returns the float number of seconds since the beginning of the
13329 epoch to the beginning of today (00:00)."
13330 (float-time (apply 'encode-time
13331 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13333 (defun org-matcher-time (s)
13334 "Interpret a time comparison value."
13335 (save-match-data
13336 (cond
13337 ((string= s "<now>") (float-time))
13338 ((string= s "<today>") (org-time-today))
13339 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13340 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13341 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13342 (+ (org-time-today)
13343 (* (string-to-number (match-string 1 s))
13344 (cdr (assoc (match-string 2 s)
13345 '(("d" . 86400.0) ("w" . 604800.0)
13346 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13347 (t (org-2ft s)))))
13349 (defun org-match-any-p (re list)
13350 "Does re match any element of list?"
13351 (setq list (mapcar (lambda (x) (string-match re x)) list))
13352 (delq nil list))
13354 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13355 (defvar org-tags-overlay (make-overlay 1 1))
13356 (org-detach-overlay org-tags-overlay)
13358 (defun org-get-local-tags-at (&optional pos)
13359 "Get a list of tags defined in the current headline."
13360 (org-get-tags-at pos 'local))
13362 (defun org-get-local-tags ()
13363 "Get a list of tags defined in the current headline."
13364 (org-get-tags-at nil 'local))
13366 (defun org-get-tags-at (&optional pos local)
13367 "Get a list of all headline tags applicable at POS.
13368 POS defaults to point. If tags are inherited, the list contains
13369 the targets in the same sequence as the headlines appear, i.e.
13370 the tags of the current headline come last.
13371 When LOCAL is non-nil, only return tags from the current headline,
13372 ignore inherited ones."
13373 (interactive)
13374 (if (and org-trust-scanner-tags
13375 (or (not pos) (equal pos (point)))
13376 (not local))
13377 org-scanner-tags
13378 (let (tags ltags lastpos parent)
13379 (save-excursion
13380 (save-restriction
13381 (widen)
13382 (goto-char (or pos (point)))
13383 (save-match-data
13384 (catch 'done
13385 (condition-case nil
13386 (progn
13387 (org-back-to-heading t)
13388 (while (not (equal lastpos (point)))
13389 (setq lastpos (point))
13390 (when (looking-at
13391 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13392 (setq ltags (org-split-string
13393 (org-match-string-no-properties 1) ":"))
13394 (when parent
13395 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13396 (setq tags (append
13397 (if parent
13398 (org-remove-uninherited-tags ltags)
13399 ltags)
13400 tags)))
13401 (or org-use-tag-inheritance (throw 'done t))
13402 (if local (throw 'done t))
13403 (or (org-up-heading-safe) (error nil))
13404 (setq parent t)))
13405 (error nil)))))
13406 (if local
13407 tags
13408 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13410 (defun org-add-prop-inherited (s)
13411 (add-text-properties 0 (length s) '(inherited t) s)
13414 (defun org-toggle-tag (tag &optional onoff)
13415 "Toggle the tag TAG for the current line.
13416 If ONOFF is `on' or `off', don't toggle but set to this state."
13417 (let (res current)
13418 (save-excursion
13419 (org-back-to-heading t)
13420 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13421 (point-at-eol) t)
13422 (progn
13423 (setq current (match-string 1))
13424 (replace-match ""))
13425 (setq current ""))
13426 (setq current (nreverse (org-split-string current ":")))
13427 (cond
13428 ((eq onoff 'on)
13429 (setq res t)
13430 (or (member tag current) (push tag current)))
13431 ((eq onoff 'off)
13432 (or (not (member tag current)) (setq current (delete tag current))))
13433 (t (if (member tag current)
13434 (setq current (delete tag current))
13435 (setq res t)
13436 (push tag current))))
13437 (end-of-line 1)
13438 (if current
13439 (progn
13440 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13441 (org-set-tags nil t))
13442 (delete-horizontal-space))
13443 (run-hooks 'org-after-tags-change-hook))
13444 res))
13446 (defun org-align-tags-here (to-col)
13447 ;; Assumes that this is a headline
13448 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13449 (beginning-of-line 1)
13450 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13451 (< pos (match-beginning 2)))
13452 (progn
13453 (setq tags-l (- (match-end 2) (match-beginning 2)))
13454 (goto-char (match-beginning 1))
13455 (insert " ")
13456 (delete-region (point) (1+ (match-beginning 2)))
13457 (setq ncol (max (current-column)
13458 (1+ col)
13459 (if (> to-col 0)
13460 to-col
13461 (- (abs to-col) tags-l))))
13462 (setq p (point))
13463 (insert (make-string (- ncol (current-column)) ?\ ))
13464 (setq ncol (current-column))
13465 (when indent-tabs-mode (tabify p (point-at-eol)))
13466 (org-move-to-column (min ncol col) t))
13467 (goto-char pos))))
13469 (defun org-set-tags-command (&optional arg just-align)
13470 "Call the set-tags command for the current entry."
13471 (interactive "P")
13472 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13473 (org-set-tags arg just-align)
13474 (save-excursion
13475 (org-back-to-heading t)
13476 (org-set-tags arg just-align))))
13478 (defun org-set-tags-to (data)
13479 "Set the tags of the current entry to DATA, replacing the current tags.
13480 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13481 If DATA is nil or the empty string, any tags will be removed."
13482 (interactive "sTags: ")
13483 (setq data
13484 (cond
13485 ((eq data nil) "")
13486 ((equal data "") "")
13487 ((stringp data)
13488 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13489 ":"))
13490 ((listp data)
13491 (concat ":" (mapconcat 'identity data ":") ":"))
13492 (t nil)))
13493 (when data
13494 (save-excursion
13495 (org-back-to-heading t)
13496 (when (looking-at org-complex-heading-regexp)
13497 (if (match-end 5)
13498 (progn
13499 (goto-char (match-beginning 5))
13500 (insert data)
13501 (delete-region (point) (point-at-eol))
13502 (org-set-tags nil 'align))
13503 (goto-char (point-at-eol))
13504 (insert " " data)
13505 (org-set-tags nil 'align)))
13506 (beginning-of-line 1)
13507 (if (looking-at ".*?\\([ \t]+\\)$")
13508 (delete-region (match-beginning 1) (match-end 1))))))
13510 (defun org-align-all-tags ()
13511 "Align the tags i all headings."
13512 (interactive)
13513 (save-excursion
13514 (or (ignore-errors (org-back-to-heading t))
13515 (outline-next-heading))
13516 (if (org-at-heading-p)
13517 (org-set-tags t)
13518 (message "No headings"))))
13520 (defvar org-indent-indentation-per-level)
13521 (defun org-set-tags (&optional arg just-align)
13522 "Set the tags for the current headline.
13523 With prefix ARG, realign all tags in headings in the current buffer."
13524 (interactive "P")
13525 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13526 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13527 'region-start-level 'region))
13528 org-loop-over-headlines-in-active-region)
13529 (org-map-entries
13530 ;; We don't use ARG and JUST-ALIGN here these args are not
13531 ;; useful when looping over headlines
13532 `(org-set-tags)
13533 org-loop-over-headlines-in-active-region
13534 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13535 (let* ((re org-outline-regexp-bol)
13536 (current (unless arg (org-get-tags-string)))
13537 (col (current-column))
13538 (org-setting-tags t)
13539 table current-tags inherited-tags ; computed below when needed
13540 tags p0 c0 c1 rpl di tc level)
13541 (if arg
13542 (save-excursion
13543 (goto-char (point-min))
13544 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13545 (while (re-search-forward re nil t)
13546 (org-set-tags nil t)
13547 (end-of-line 1)))
13548 (message "All tags realigned to column %d" org-tags-column))
13549 (if just-align
13550 (setq tags current)
13551 ;; Get a new set of tags from the user
13552 (save-excursion
13553 (setq table (append org-tag-persistent-alist
13554 (or org-tag-alist (org-get-buffer-tags))
13555 (and
13556 org-complete-tags-always-offer-all-agenda-tags
13557 (org-global-tags-completion-table
13558 (org-agenda-files))))
13559 org-last-tags-completion-table table
13560 current-tags (org-split-string current ":")
13561 inherited-tags (nreverse
13562 (nthcdr (length current-tags)
13563 (nreverse (org-get-tags-at))))
13564 tags
13565 (if (or (eq t org-use-fast-tag-selection)
13566 (and org-use-fast-tag-selection
13567 (delq nil (mapcar 'cdr table))))
13568 (org-fast-tag-selection
13569 current-tags inherited-tags table
13570 (if org-fast-tag-selection-include-todo
13571 org-todo-key-alist))
13572 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13573 (org-trim
13574 (org-icompleting-read "Tags: "
13575 'org-tags-completion-function
13576 nil nil current 'org-tags-history))))))
13577 (while (string-match "[-+&]+" tags)
13578 ;; No boolean logic, just a list
13579 (setq tags (replace-match ":" t t tags))))
13581 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13583 (if org-tags-sort-function
13584 (setq tags (mapconcat 'identity
13585 (sort (org-split-string
13586 tags (org-re "[^[:alnum:]_@#%]+"))
13587 org-tags-sort-function) ":")))
13589 (if (string-match "\\`[\t ]*\\'" tags)
13590 (setq tags "")
13591 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13592 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13594 ;; Insert new tags at the correct column
13595 (beginning-of-line 1)
13596 (setq level (or (and (looking-at org-outline-regexp)
13597 (- (match-end 0) (point) 1))
13599 (cond
13600 ((and (equal current "") (equal tags "")))
13601 ((re-search-forward
13602 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13603 (point-at-eol) t)
13604 (if (equal tags "")
13605 (setq rpl "")
13606 (goto-char (match-beginning 0))
13607 (setq c0 (current-column)
13608 ;; compute offset for the case of org-indent-mode active
13609 di (if org-indent-mode
13610 (* (1- org-indent-indentation-per-level) (1- level))
13612 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13613 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13614 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13615 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13616 (replace-match rpl t t)
13617 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13618 tags)
13619 (t (error "Tags alignment failed")))
13620 (org-move-to-column col)
13621 (unless just-align
13622 (run-hooks 'org-after-tags-change-hook))))))
13624 (defun org-change-tag-in-region (beg end tag off)
13625 "Add or remove TAG for each entry in the region.
13626 This works in the agenda, and also in an org-mode buffer."
13627 (interactive
13628 (list (region-beginning) (region-end)
13629 (let ((org-last-tags-completion-table
13630 (if (derived-mode-p 'org-mode)
13631 (org-get-buffer-tags)
13632 (org-global-tags-completion-table))))
13633 (org-icompleting-read
13634 "Tag: " 'org-tags-completion-function nil nil nil
13635 'org-tags-history))
13636 (progn
13637 (message "[s]et or [r]emove? ")
13638 (equal (read-char-exclusive) ?r))))
13639 (if (fboundp 'deactivate-mark) (deactivate-mark))
13640 (let ((agendap (equal major-mode 'org-agenda-mode))
13641 l1 l2 m buf pos newhead (cnt 0))
13642 (goto-char end)
13643 (setq l2 (1- (org-current-line)))
13644 (goto-char beg)
13645 (setq l1 (org-current-line))
13646 (loop for l from l1 to l2 do
13647 (org-goto-line l)
13648 (setq m (get-text-property (point) 'org-hd-marker))
13649 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13650 (and agendap m))
13651 (setq buf (if agendap (marker-buffer m) (current-buffer))
13652 pos (if agendap m (point)))
13653 (with-current-buffer buf
13654 (save-excursion
13655 (save-restriction
13656 (goto-char pos)
13657 (setq cnt (1+ cnt))
13658 (org-toggle-tag tag (if off 'off 'on))
13659 (setq newhead (org-get-heading)))))
13660 (and agendap (org-agenda-change-all-lines newhead m))))
13661 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13663 (defun org-tags-completion-function (string predicate &optional flag)
13664 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13665 (confirm (lambda (x) (stringp (car x)))))
13666 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13667 (setq s1 (match-string 1 string)
13668 s2 (match-string 2 string))
13669 (setq s1 "" s2 string))
13670 (cond
13671 ((eq flag nil)
13672 ;; try completion
13673 (setq rtn (try-completion s2 ctable confirm))
13674 (if (stringp rtn)
13675 (setq rtn
13676 (concat s1 s2 (substring rtn (length s2))
13677 (if (and org-add-colon-after-tag-completion
13678 (assoc rtn ctable))
13679 ":" ""))))
13680 rtn)
13681 ((eq flag t)
13682 ;; all-completions
13683 (all-completions s2 ctable confirm)
13685 ((eq flag 'lambda)
13686 ;; exact match?
13687 (assoc s2 ctable)))
13690 (defun org-fast-tag-insert (kwd tags face &optional end)
13691 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13692 (insert (format "%-12s" (concat kwd ":"))
13693 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13694 (or end "")))
13696 (defun org-fast-tag-show-exit (flag)
13697 (save-excursion
13698 (org-goto-line 3)
13699 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13700 (replace-match ""))
13701 (when flag
13702 (end-of-line 1)
13703 (org-move-to-column (- (window-width) 19) t)
13704 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13706 (defun org-set-current-tags-overlay (current prefix)
13707 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13708 (if (featurep 'xemacs)
13709 (org-overlay-display org-tags-overlay (concat prefix s)
13710 'secondary-selection)
13711 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13712 (org-overlay-display org-tags-overlay (concat prefix s)))))
13714 (defvar org-last-tag-selection-key nil)
13715 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13716 "Fast tag selection with single keys.
13717 CURRENT is the current list of tags in the headline, INHERITED is the
13718 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13719 possibly with grouping information. TODO-TABLE is a similar table with
13720 TODO keywords, should these have keys assigned to them.
13721 If the keys are nil, a-z are automatically assigned.
13722 Returns the new tags string, or nil to not change the current settings."
13723 (let* ((fulltable (append table todo-table))
13724 (maxlen (apply 'max (mapcar
13725 (lambda (x)
13726 (if (stringp (car x)) (string-width (car x)) 0))
13727 fulltable)))
13728 (buf (current-buffer))
13729 (expert (eq org-fast-tag-selection-single-key 'expert))
13730 (buffer-tags nil)
13731 (fwidth (+ maxlen 3 1 3))
13732 (ncol (/ (- (window-width) 4) fwidth))
13733 (i-face 'org-done)
13734 (c-face 'org-todo)
13735 tg cnt e c char c1 c2 ntable tbl rtn
13736 ov-start ov-end ov-prefix
13737 (exit-after-next org-fast-tag-selection-single-key)
13738 (done-keywords org-done-keywords)
13739 groups ingroup)
13740 (save-excursion
13741 (beginning-of-line 1)
13742 (if (looking-at
13743 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13744 (setq ov-start (match-beginning 1)
13745 ov-end (match-end 1)
13746 ov-prefix "")
13747 (setq ov-start (1- (point-at-eol))
13748 ov-end (1+ ov-start))
13749 (skip-chars-forward "^\n\r")
13750 (setq ov-prefix
13751 (concat
13752 (buffer-substring (1- (point)) (point))
13753 (if (> (current-column) org-tags-column)
13755 (make-string (- org-tags-column (current-column)) ?\ ))))))
13756 (move-overlay org-tags-overlay ov-start ov-end)
13757 (save-window-excursion
13758 (if expert
13759 (set-buffer (get-buffer-create " *Org tags*"))
13760 (delete-other-windows)
13761 (split-window-vertically)
13762 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13763 (erase-buffer)
13764 (org-set-local 'org-done-keywords done-keywords)
13765 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13766 (org-fast-tag-insert "Current" current c-face "\n\n")
13767 (org-fast-tag-show-exit exit-after-next)
13768 (org-set-current-tags-overlay current ov-prefix)
13769 (setq tbl fulltable char ?a cnt 0)
13770 (while (setq e (pop tbl))
13771 (cond
13772 ((equal (car e) :startgroup)
13773 (push '() groups) (setq ingroup t)
13774 (when (not (= cnt 0))
13775 (setq cnt 0)
13776 (insert "\n"))
13777 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13778 ((equal (car e) :endgroup)
13779 (setq ingroup nil cnt 0)
13780 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13781 ((equal e '(:newline))
13782 (when (not (= cnt 0))
13783 (setq cnt 0)
13784 (insert "\n")
13785 (setq e (car tbl))
13786 (while (equal (car tbl) '(:newline))
13787 (insert "\n")
13788 (setq tbl (cdr tbl)))))
13790 (setq tg (copy-sequence (car e)) c2 nil)
13791 (if (cdr e)
13792 (setq c (cdr e))
13793 ;; automatically assign a character.
13794 (setq c1 (string-to-char
13795 (downcase (substring
13796 tg (if (= (string-to-char tg) ?@) 1 0)))))
13797 (if (or (rassoc c1 ntable) (rassoc c1 table))
13798 (while (or (rassoc char ntable) (rassoc char table))
13799 (setq char (1+ char)))
13800 (setq c2 c1))
13801 (setq c (or c2 char)))
13802 (if ingroup (push tg (car groups)))
13803 (setq tg (org-add-props tg nil 'face
13804 (cond
13805 ((not (assoc tg table))
13806 (org-get-todo-face tg))
13807 ((member tg current) c-face)
13808 ((member tg inherited) i-face)
13809 (t nil))))
13810 (if (and (= cnt 0) (not ingroup)) (insert " "))
13811 (insert "[" c "] " tg (make-string
13812 (- fwidth 4 (length tg)) ?\ ))
13813 (push (cons tg c) ntable)
13814 (when (= (setq cnt (1+ cnt)) ncol)
13815 (insert "\n")
13816 (if ingroup (insert " "))
13817 (setq cnt 0)))))
13818 (setq ntable (nreverse ntable))
13819 (insert "\n")
13820 (goto-char (point-min))
13821 (if (not expert) (org-fit-window-to-buffer))
13822 (setq rtn
13823 (catch 'exit
13824 (while t
13825 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13826 (if (not groups) "no " "")
13827 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13828 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13829 (setq org-last-tag-selection-key c)
13830 (cond
13831 ((= c ?\r) (throw 'exit t))
13832 ((= c ?!)
13833 (setq groups (not groups))
13834 (goto-char (point-min))
13835 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13836 ((= c ?\C-c)
13837 (if (not expert)
13838 (org-fast-tag-show-exit
13839 (setq exit-after-next (not exit-after-next)))
13840 (setq expert nil)
13841 (delete-other-windows)
13842 (set-window-buffer (split-window-vertically) " *Org tags*")
13843 (org-switch-to-buffer-other-window " *Org tags*")
13844 (org-fit-window-to-buffer)))
13845 ((or (= c ?\C-g)
13846 (and (= c ?q) (not (rassoc c ntable))))
13847 (org-detach-overlay org-tags-overlay)
13848 (setq quit-flag t))
13849 ((= c ?\ )
13850 (setq current nil)
13851 (if exit-after-next (setq exit-after-next 'now)))
13852 ((= c ?\t)
13853 (condition-case nil
13854 (setq tg (org-icompleting-read
13855 "Tag: "
13856 (or buffer-tags
13857 (with-current-buffer buf
13858 (org-get-buffer-tags)))))
13859 (quit (setq tg "")))
13860 (when (string-match "\\S-" tg)
13861 (add-to-list 'buffer-tags (list tg))
13862 (if (member tg current)
13863 (setq current (delete tg current))
13864 (push tg current)))
13865 (if exit-after-next (setq exit-after-next 'now)))
13866 ((setq e (rassoc c todo-table) tg (car e))
13867 (with-current-buffer buf
13868 (save-excursion (org-todo tg)))
13869 (if exit-after-next (setq exit-after-next 'now)))
13870 ((setq e (rassoc c ntable) tg (car e))
13871 (if (member tg current)
13872 (setq current (delete tg current))
13873 (loop for g in groups do
13874 (if (member tg g)
13875 (mapc (lambda (x)
13876 (setq current (delete x current)))
13877 g)))
13878 (push tg current))
13879 (if exit-after-next (setq exit-after-next 'now))))
13881 ;; Create a sorted list
13882 (setq current
13883 (sort current
13884 (lambda (a b)
13885 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13886 (if (eq exit-after-next 'now) (throw 'exit t))
13887 (goto-char (point-min))
13888 (beginning-of-line 2)
13889 (delete-region (point) (point-at-eol))
13890 (org-fast-tag-insert "Current" current c-face)
13891 (org-set-current-tags-overlay current ov-prefix)
13892 (while (re-search-forward
13893 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13894 (setq tg (match-string 1))
13895 (add-text-properties
13896 (match-beginning 1) (match-end 1)
13897 (list 'face
13898 (cond
13899 ((member tg current) c-face)
13900 ((member tg inherited) i-face)
13901 (t (get-text-property (match-beginning 1) 'face))))))
13902 (goto-char (point-min)))))
13903 (org-detach-overlay org-tags-overlay)
13904 (if rtn
13905 (mapconcat 'identity current ":")
13906 nil))))
13908 (defun org-get-tags-string ()
13909 "Get the TAGS string in the current headline."
13910 (unless (org-at-heading-p t)
13911 (error "Not on a heading"))
13912 (save-excursion
13913 (beginning-of-line 1)
13914 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13915 (org-match-string-no-properties 1)
13916 "")))
13918 (defun org-get-tags ()
13919 "Get the list of tags specified in the current headline."
13920 (org-split-string (org-get-tags-string) ":"))
13922 (defun org-get-buffer-tags ()
13923 "Get a table of all tags used in the buffer, for completion."
13924 (let (tags)
13925 (save-excursion
13926 (goto-char (point-min))
13927 (while (re-search-forward
13928 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13929 (when (equal (char-after (point-at-bol 0)) ?*)
13930 (mapc (lambda (x) (add-to-list 'tags x))
13931 (org-split-string (org-match-string-no-properties 1) ":")))))
13932 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13933 (mapcar 'list tags)))
13935 ;;;; The mapping API
13937 ;;;###autoload
13938 (defun org-map-entries (func &optional match scope &rest skip)
13939 "Call FUNC at each headline selected by MATCH in SCOPE.
13941 FUNC is a function or a lisp form. The function will be called without
13942 arguments, with the cursor positioned at the beginning of the headline.
13943 The return values of all calls to the function will be collected and
13944 returned as a list.
13946 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13947 does not need to preserve point. After evaluation, the cursor will be
13948 moved to the end of the line (presumably of the headline of the
13949 processed entry) and search continues from there. Under some
13950 circumstances, this may not produce the wanted results. For example,
13951 if you have removed (e.g. archived) the current (sub)tree it could
13952 mean that the next entry will be skipped entirely. In such cases, you
13953 can specify the position from where search should continue by making
13954 FUNC set the variable `org-map-continue-from' to the desired buffer
13955 position.
13957 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13958 Only headlines that are matched by this query will be considered during
13959 the iteration. When MATCH is nil or t, all headlines will be
13960 visited by the iteration.
13962 SCOPE determines the scope of this command. It can be any of:
13964 nil The current buffer, respecting the restriction if any
13965 tree The subtree started with the entry at point
13966 region The entries within the active region, if any
13967 region-start-level
13968 The entries within the active region, but only those at
13969 the same level than the first one.
13970 file The current buffer, without restriction
13971 file-with-archives
13972 The current buffer, and any archives associated with it
13973 agenda All agenda files
13974 agenda-with-archives
13975 All agenda files with any archive files associated with them
13976 \(file1 file2 ...)
13977 If this is a list, all files in the list will be scanned
13979 The remaining args are treated as settings for the skipping facilities of
13980 the scanner. The following items can be given here:
13982 archive skip trees with the archive tag.
13983 comment skip trees with the COMMENT keyword
13984 function or Emacs Lisp form:
13985 will be used as value for `org-agenda-skip-function', so whenever
13986 the function returns t, FUNC will not be called for that
13987 entry and search will continue from the point where the
13988 function leaves it.
13990 If your function needs to retrieve the tags including inherited tags
13991 at the *current* entry, you can use the value of the variable
13992 `org-scanner-tags' which will be much faster than getting the value
13993 with `org-get-tags-at'. If your function gets properties with
13994 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13995 to t around the call to `org-entry-properties' to get the same speedup.
13996 Note that if your function moves around to retrieve tags and properties at
13997 a *different* entry, you cannot use these techniques."
13998 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13999 (not (org-region-active-p)))
14000 (let* ((org-agenda-archives-mode nil) ; just to make sure
14001 (org-agenda-skip-archived-trees (memq 'archive skip))
14002 (org-agenda-skip-comment-trees (memq 'comment skip))
14003 (org-agenda-skip-function
14004 (car (org-delete-all '(comment archive) skip)))
14005 (org-tags-match-list-sublevels t)
14006 (start-level (eq scope 'region-start-level))
14007 matcher file res
14008 org-todo-keywords-for-agenda
14009 org-done-keywords-for-agenda
14010 org-todo-keyword-alist-for-agenda
14011 org-drawers-for-agenda
14012 org-tag-alist-for-agenda
14013 todo-only)
14015 (cond
14016 ((eq match t) (setq matcher t))
14017 ((eq match nil) (setq matcher t))
14018 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14020 (save-excursion
14021 (save-restriction
14022 (cond ((eq scope 'tree)
14023 (org-back-to-heading t)
14024 (org-narrow-to-subtree)
14025 (setq scope nil))
14026 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14027 (org-region-active-p))
14028 ;; If needed, set start-level to a string like "2"
14029 (when start-level
14030 (save-excursion
14031 (goto-char (region-beginning))
14032 (unless (org-at-heading-p) (outline-next-heading))
14033 (setq start-level (org-current-level))))
14034 (narrow-to-region (region-beginning)
14035 (save-excursion
14036 (goto-char (region-end))
14037 (unless (and (bolp) (org-at-heading-p))
14038 (outline-next-heading))
14039 (point)))
14040 (setq scope nil)))
14042 (if (not scope)
14043 (progn
14044 (org-prepare-agenda-buffers
14045 (list (buffer-file-name (current-buffer))))
14046 (setq res (org-scan-tags func matcher todo-only start-level)))
14047 ;; Get the right scope
14048 (cond
14049 ((and scope (listp scope) (symbolp (car scope)))
14050 (setq scope (eval scope)))
14051 ((eq scope 'agenda)
14052 (setq scope (org-agenda-files t)))
14053 ((eq scope 'agenda-with-archives)
14054 (setq scope (org-agenda-files t))
14055 (setq scope (org-add-archive-files scope)))
14056 ((eq scope 'file)
14057 (setq scope (list (buffer-file-name))))
14058 ((eq scope 'file-with-archives)
14059 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14060 (org-prepare-agenda-buffers scope)
14061 (while (setq file (pop scope))
14062 (with-current-buffer (org-find-base-buffer-visiting file)
14063 (save-excursion
14064 (save-restriction
14065 (widen)
14066 (goto-char (point-min))
14067 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14068 res)))
14070 ;;;; Properties
14072 ;;; Setting and retrieving properties
14074 (defconst org-special-properties
14075 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14076 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
14077 "The special properties valid in Org-mode.
14079 These are properties that are not defined in the property drawer,
14080 but in some other way.")
14082 (defconst org-default-properties
14083 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14084 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14085 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14086 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14087 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14088 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14089 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14090 "Some properties that are used by Org-mode for various purposes.
14091 Being in this list makes sure that they are offered for completion.")
14093 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14094 "Regular expression matching the first line of a property drawer.")
14096 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14097 "Regular expression matching the last line of a property drawer.")
14099 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14100 "Regular expression matching the first line of a property drawer.")
14102 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14103 "Regular expression matching the first line of a property drawer.")
14105 (defconst org-property-drawer-re
14106 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14107 org-property-end-re "\\)\n?")
14108 "Matches an entire property drawer.")
14110 (defconst org-clock-drawer-re
14111 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14112 org-property-end-re "\\)\n?")
14113 "Matches an entire clock drawer.")
14115 (defsubst org-re-property (property)
14116 "Return a regexp matching PROPERTY.
14117 Match group 1 will be set to the value "
14118 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14120 (defun org-property-action ()
14121 "Do an action on properties."
14122 (interactive)
14123 (let (c)
14124 (org-at-property-p)
14125 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14126 (setq c (read-char-exclusive))
14127 (cond
14128 ((equal c ?s)
14129 (call-interactively 'org-set-property))
14130 ((equal c ?d)
14131 (call-interactively 'org-delete-property))
14132 ((equal c ?D)
14133 (call-interactively 'org-delete-property-globally))
14134 ((equal c ?c)
14135 (call-interactively 'org-compute-property-at-point))
14136 (t (error "No such property action %c" c)))))
14138 (defun org-set-effort (&optional value)
14139 "Set the effort property of the current entry.
14140 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14141 allowed value."
14142 (interactive "P")
14143 (if (equal value 0) (setq value 10))
14144 (let* ((completion-ignore-case t)
14145 (prop org-effort-property)
14146 (cur (org-entry-get nil prop))
14147 (allowed (org-property-get-allowed-values nil prop 'table))
14148 (existing (mapcar 'list (org-property-values prop)))
14150 (val (cond
14151 ((stringp value) value)
14152 ((and allowed (integerp value))
14153 (or (car (nth (1- value) allowed))
14154 (car (org-last allowed))))
14155 (allowed
14156 (message "Select 1-9,0, [RET%s]: %s"
14157 (if cur (concat "=" cur) "")
14158 (mapconcat 'car allowed " "))
14159 (setq rpl (read-char-exclusive))
14160 (if (equal rpl ?\r)
14162 (setq rpl (- rpl ?0))
14163 (if (equal rpl 0) (setq rpl 10))
14164 (if (and (> rpl 0) (<= rpl (length allowed)))
14165 (car (nth (1- rpl) allowed))
14166 (org-completing-read "Effort: " allowed nil))))
14168 (let (org-completion-use-ido org-completion-use-iswitchb)
14169 (org-completing-read
14170 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14171 (concat "[" cur "]") "")
14172 ": ")
14173 existing nil nil "" nil cur))))))
14174 (unless (equal (org-entry-get nil prop) val)
14175 (org-entry-put nil prop val))
14176 (message "%s is now %s" prop val)))
14178 (defun org-at-property-p ()
14179 "Is cursor inside a property drawer?"
14180 (save-excursion
14181 (beginning-of-line 1)
14182 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14183 (save-match-data ;; Used by calling procedures
14184 (let ((p (point))
14185 (range (unless (org-before-first-heading-p)
14186 (org-get-property-block))))
14187 (and range (<= (car range) p) (< p (cdr range))))))))
14189 (defun org-get-property-block (&optional beg end force)
14190 "Return the (beg . end) range of the body of the property drawer.
14191 BEG and END can be beginning and end of subtree, if not given
14192 they will be found.
14193 If the drawer does not exist and FORCE is non-nil, create the drawer."
14194 (catch 'exit
14195 (save-excursion
14196 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14197 (end (or end (progn (outline-next-heading) (point)))))
14198 (goto-char beg)
14199 (if (re-search-forward org-property-start-re end t)
14200 (setq beg (1+ (match-end 0)))
14201 (if force
14202 (save-excursion
14203 (org-insert-property-drawer)
14204 (setq end (progn (outline-next-heading) (point))))
14205 (throw 'exit nil))
14206 (goto-char beg)
14207 (if (re-search-forward org-property-start-re end t)
14208 (setq beg (1+ (match-end 0)))))
14209 (if (re-search-forward org-property-end-re end t)
14210 (setq end (match-beginning 0))
14211 (or force (throw 'exit nil))
14212 (goto-char beg)
14213 (setq end beg)
14214 (org-indent-line)
14215 (insert ":END:\n"))
14216 (cons beg end)))))
14218 (defun org-entry-properties (&optional pom which specific)
14219 "Get all properties of the entry at point-or-marker POM.
14220 This includes the TODO keyword, the tags, time strings for deadline,
14221 scheduled, and clocking, and any additional properties defined in the
14222 entry. The return value is an alist, keys may occur multiple times
14223 if the property key was used several times.
14224 POM may also be nil, in which case the current entry is used.
14225 If WHICH is nil or `all', get all properties. If WHICH is
14226 `special' or `standard', only get that subclass. If WHICH
14227 is a string only get exactly this property. SPECIFIC can be a string, the
14228 specific property we are interested in. Specifying it can speed
14229 things up because then unnecessary parsing is avoided."
14230 (setq which (or which 'all))
14231 (org-with-point-at pom
14232 (let ((clockstr (substring org-clock-string 0 -1))
14233 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14234 (case-fold-search nil)
14235 beg end range props sum-props key key1 value string clocksum)
14236 (save-excursion
14237 (when (condition-case nil
14238 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14239 (error nil))
14240 (setq beg (point))
14241 (setq sum-props (get-text-property (point) 'org-summaries))
14242 (setq clocksum (get-text-property (point) :org-clock-minutes))
14243 (outline-next-heading)
14244 (setq end (point))
14245 (when (memq which '(all special))
14246 ;; Get the special properties, like TODO and tags
14247 (goto-char beg)
14248 (when (and (or (not specific) (string= specific "TODO"))
14249 (looking-at org-todo-line-regexp) (match-end 2))
14250 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14251 (when (and (or (not specific) (string= specific "PRIORITY"))
14252 (looking-at org-priority-regexp))
14253 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14254 (when (or (not specific) (string= specific "FILE"))
14255 (push (cons "FILE" buffer-file-name) props))
14256 (when (and (or (not specific) (string= specific "TAGS"))
14257 (setq value (org-get-tags-string))
14258 (string-match "\\S-" value))
14259 (push (cons "TAGS" value) props))
14260 (when (and (or (not specific) (string= specific "ALLTAGS"))
14261 (setq value (org-get-tags-at)))
14262 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14263 ":"))
14264 props))
14265 (when (or (not specific) (string= specific "BLOCKED"))
14266 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14267 (when (or (not specific)
14268 (member specific
14269 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14270 "TIMESTAMP" "TIMESTAMP_IA")))
14271 (catch 'match
14272 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14273 (setq key (if (match-end 1)
14274 (substring (org-match-string-no-properties 1)
14275 0 -1))
14276 string (if (equal key clockstr)
14277 (org-no-properties
14278 (org-trim
14279 (buffer-substring
14280 (match-beginning 3) (goto-char
14281 (point-at-eol)))))
14282 (substring (org-match-string-no-properties 3)
14283 1 -1)))
14284 ;; Get the correct property name from the key. This is
14285 ;; necessary if the user has configured time keywords.
14286 (setq key1 (concat key ":"))
14287 (cond
14288 ((not key)
14289 (setq key
14290 (if (= (char-after (match-beginning 3)) ?\[)
14291 "TIMESTAMP_IA" "TIMESTAMP")))
14292 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14293 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14294 ((equal key1 org-closed-string) (setq key "CLOSED"))
14295 ((equal key1 org-clock-string) (setq key "CLOCK")))
14296 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14297 (progn
14298 (push (cons key string) props)
14299 ;; no need to search further if match is found
14300 (throw 'match t))
14301 (when (or (equal key "CLOCK") (not (assoc key props)))
14302 (push (cons key string) props))))))
14305 (when (memq which '(all standard))
14306 ;; Get the standard properties, like :PROP: ...
14307 (setq range (org-get-property-block beg end))
14308 (when range
14309 (goto-char (car range))
14310 (while (re-search-forward
14311 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14312 (cdr range) t)
14313 (setq key (org-match-string-no-properties 1)
14314 value (org-trim (or (org-match-string-no-properties 2) "")))
14315 (unless (member key excluded)
14316 (push (cons key (or value "")) props)))))
14317 (if clocksum
14318 (push (cons "CLOCKSUM"
14319 (org-columns-number-to-string (/ (float clocksum) 60.)
14320 'add_times))
14321 props))
14322 (unless (assoc "CATEGORY" props)
14323 (push (cons "CATEGORY" (org-get-category)) props))
14324 (append sum-props (nreverse props)))))))
14326 (defun org-entry-get (pom property &optional inherit literal-nil)
14327 "Get value of PROPERTY for entry at point-or-marker POM.
14328 If INHERIT is non-nil and the entry does not have the property,
14329 then also check higher levels of the hierarchy.
14330 If INHERIT is the symbol `selective', use inheritance only if the setting
14331 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14332 If the property is present but empty, the return value is the empty string.
14333 If the property is not present at all, nil is returned.
14335 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14336 do not interpret it as the list atom nil. This is used for inheritance
14337 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14338 (org-with-point-at pom
14339 (if (and inherit (if (eq inherit 'selective)
14340 (org-property-inherit-p property)
14342 (org-entry-get-with-inheritance property literal-nil)
14343 (if (member property org-special-properties)
14344 ;; We need a special property. Use `org-entry-properties' to
14345 ;; retrieve it, but specify the wanted property
14346 (cdr (assoc property (org-entry-properties nil 'special property)))
14347 (let ((range (unless (org-before-first-heading-p)
14348 (org-get-property-block)))
14349 (props (list (or (assoc property org-file-properties)
14350 (assoc property org-global-properties)
14351 (assoc property org-global-properties-fixed))))
14352 val)
14353 (flet ((ap (key)
14354 (when (re-search-forward
14355 (org-re-property key) (cdr range) t)
14356 (setq props
14357 (org-update-property-plist
14359 (if (match-end 1)
14360 (org-match-string-no-properties 1) "")
14361 props)))))
14362 (when (and range (goto-char (car range)))
14363 (ap property)
14364 (goto-char (car range))
14365 (while (ap (concat property "+")))
14366 (setq val (cdr (assoc property props)))
14367 (when val (if literal-nil val (org-not-nil val))))))))))
14369 (defun org-property-or-variable-value (var &optional inherit)
14370 "Check if there is a property fixing the value of VAR.
14371 If yes, return this value. If not, return the current value of the variable."
14372 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14373 (if (and prop (stringp prop) (string-match "\\S-" prop))
14374 (read prop)
14375 (symbol-value var))))
14377 (defun org-entry-delete (pom property)
14378 "Delete the property PROPERTY from entry at point-or-marker POM."
14379 (org-with-point-at pom
14380 (if (member property org-special-properties)
14381 nil ; cannot delete these properties.
14382 (let ((range (org-get-property-block)))
14383 (if (and range
14384 (goto-char (car range))
14385 (re-search-forward
14386 (org-re-property property)
14387 (cdr range) t))
14388 (progn
14389 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14391 nil)))))
14393 ;; Multi-values properties are properties that contain multiple values
14394 ;; These values are assumed to be single words, separated by whitespace.
14395 (defun org-entry-add-to-multivalued-property (pom property value)
14396 "Add VALUE to 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 (unless (member value values)
14401 (setq values (cons value values))
14402 (org-entry-put pom property
14403 (mapconcat 'identity values " ")))))
14405 (defun org-entry-remove-from-multivalued-property (pom property value)
14406 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14407 (let* ((old (org-entry-get pom property))
14408 (values (and old (org-split-string old "[ \t]"))))
14409 (setq value (org-entry-protect-space value))
14410 (when (member value values)
14411 (setq values (delete value values))
14412 (org-entry-put pom property
14413 (mapconcat 'identity values " ")))))
14415 (defun org-entry-member-in-multivalued-property (pom property value)
14416 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14417 (let* ((old (org-entry-get pom property))
14418 (values (and old (org-split-string old "[ \t]"))))
14419 (setq value (org-entry-protect-space value))
14420 (member value values)))
14422 (defun org-entry-get-multivalued-property (pom property)
14423 "Return a list of values in a multivalued property."
14424 (let* ((value (org-entry-get pom property))
14425 (values (and value (org-split-string value "[ \t]"))))
14426 (mapcar 'org-entry-restore-space values)))
14428 (defun org-entry-put-multivalued-property (pom property &rest values)
14429 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14430 VALUES should be a list of strings. Spaces will be protected."
14431 (org-entry-put pom property
14432 (mapconcat 'org-entry-protect-space values " "))
14433 (let* ((value (org-entry-get pom property))
14434 (values (and value (org-split-string value "[ \t]"))))
14435 (mapcar 'org-entry-restore-space values)))
14437 (defun org-entry-protect-space (s)
14438 "Protect spaces and newline in string S."
14439 (while (string-match " " s)
14440 (setq s (replace-match "%20" t t s)))
14441 (while (string-match "\n" s)
14442 (setq s (replace-match "%0A" t t s)))
14445 (defun org-entry-restore-space (s)
14446 "Restore spaces and newline in string S."
14447 (while (string-match "%20" s)
14448 (setq s (replace-match " " t t s)))
14449 (while (string-match "%0A" s)
14450 (setq s (replace-match "\n" t t s)))
14453 (defvar org-entry-property-inherited-from (make-marker)
14454 "Marker pointing to the entry from where a property was inherited.
14455 Each call to `org-entry-get-with-inheritance' will set this marker to the
14456 location of the entry where the inheritance search matched. If there was
14457 no match, the marker will point nowhere.
14458 Note that also `org-entry-get' calls this function, if the INHERIT flag
14459 is set.")
14461 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14462 "Get entry property, and search higher levels if not present.
14463 The search will stop at the first ancestor which has the property defined.
14464 If the value found is \"nil\", return nil to show that the property
14465 should be considered as undefined (this is the meaning of nil here).
14466 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14467 (move-marker org-entry-property-inherited-from nil)
14468 (let (tmp)
14469 (unless (org-before-first-heading-p)
14470 (save-excursion
14471 (save-restriction
14472 (widen)
14473 (catch 'ex
14474 (while t
14475 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14476 (org-back-to-heading t)
14477 (move-marker org-entry-property-inherited-from (point))
14478 (throw 'ex tmp))
14479 (or (org-up-heading-safe) (throw 'ex nil)))))))
14480 (setq tmp (or tmp
14481 (cdr (assoc property org-file-properties))
14482 (cdr (assoc property org-global-properties))
14483 (cdr (assoc property org-global-properties-fixed))))
14484 (if literal-nil tmp (org-not-nil tmp))))
14486 (defvar org-property-changed-functions nil
14487 "Hook called when the value of a property has changed.
14488 Each hook function should accept two arguments, the name of the property
14489 and the new value.")
14491 (defun org-entry-put (pom property value)
14492 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14493 (org-with-point-at pom
14494 (org-back-to-heading t)
14495 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14496 range)
14497 (cond
14498 ((equal property "TODO")
14499 (when (and (stringp value) (string-match "\\S-" value)
14500 (not (member value org-todo-keywords-1)))
14501 (error "\"%s\" is not a valid TODO state" value))
14502 (if (or (not value)
14503 (not (string-match "\\S-" value)))
14504 (setq value 'none))
14505 (org-todo value)
14506 (org-set-tags nil 'align))
14507 ((equal property "PRIORITY")
14508 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14509 (string-to-char value) ?\ ))
14510 (org-set-tags nil 'align))
14511 ((equal property "SCHEDULED")
14512 (if (re-search-forward org-scheduled-time-regexp end t)
14513 (cond
14514 ((eq value 'earlier) (org-timestamp-change -1 'day))
14515 ((eq value 'later) (org-timestamp-change 1 'day))
14516 (t (call-interactively 'org-schedule)))
14517 (call-interactively 'org-schedule)))
14518 ((equal property "DEADLINE")
14519 (if (re-search-forward org-deadline-time-regexp end t)
14520 (cond
14521 ((eq value 'earlier) (org-timestamp-change -1 'day))
14522 ((eq value 'later) (org-timestamp-change 1 'day))
14523 (t (call-interactively 'org-deadline)))
14524 (call-interactively 'org-deadline)))
14525 ((member property org-special-properties)
14526 (error "The %s property can not yet be set with `org-entry-put'"
14527 property))
14528 (t ; a non-special property
14529 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14530 (setq range (org-get-property-block beg end 'force))
14531 (goto-char (car range))
14532 (if (re-search-forward
14533 (org-re-property property) (cdr range) t)
14534 (progn
14535 (delete-region (match-beginning 0) (match-end 0))
14536 (goto-char (match-beginning 0)))
14537 (goto-char (cdr range))
14538 (insert "\n")
14539 (backward-char 1)
14540 (org-indent-line))
14541 (insert ":" property ":")
14542 (and value (insert " " value))
14543 (org-indent-line)))))
14544 (run-hook-with-args 'org-property-changed-functions property value)))
14546 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14547 "Get all property keys in the current buffer.
14548 With INCLUDE-SPECIALS, also list the special properties that reflect things
14549 like tags and TODO state.
14550 With INCLUDE-DEFAULTS, also include properties that has special meaning
14551 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14552 and others.
14553 With INCLUDE-COLUMNS, also include property names given in COLUMN
14554 formats in the current buffer."
14555 (let (rtn range cfmt s p)
14556 (save-excursion
14557 (save-restriction
14558 (widen)
14559 (goto-char (point-min))
14560 (while (re-search-forward org-property-start-re nil t)
14561 (setq range (org-get-property-block))
14562 (goto-char (car range))
14563 (while (re-search-forward
14564 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14565 (cdr range) t)
14566 (add-to-list 'rtn (org-match-string-no-properties 1)))
14567 (outline-next-heading))))
14569 (when include-specials
14570 (setq rtn (append org-special-properties rtn)))
14572 (when include-defaults
14573 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14574 (add-to-list 'rtn org-effort-property))
14576 (when include-columns
14577 (save-excursion
14578 (save-restriction
14579 (widen)
14580 (goto-char (point-min))
14581 (while (re-search-forward
14582 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14583 nil t)
14584 (setq cfmt (match-string 2) s 0)
14585 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14586 cfmt s)
14587 (setq s (match-end 0)
14588 p (match-string 1 cfmt))
14589 (unless (or (equal p "ITEM")
14590 (member p org-special-properties))
14591 (add-to-list 'rtn (match-string 1 cfmt))))))))
14593 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14595 (defun org-property-values (key)
14596 "Return a list of all values of property KEY in the current buffer."
14597 (save-excursion
14598 (save-restriction
14599 (widen)
14600 (goto-char (point-min))
14601 (let ((re (org-re-property key))
14602 values)
14603 (while (re-search-forward re nil t)
14604 (add-to-list 'values (org-trim (match-string 1))))
14605 (delete "" values)))))
14607 (defun org-insert-property-drawer ()
14608 "Insert a property drawer into the current entry."
14609 (org-back-to-heading t)
14610 (looking-at org-outline-regexp)
14611 (let ((indent (if org-adapt-indentation
14612 (- (match-end 0) (match-beginning 0))
14614 (beg (point))
14615 (re (concat "^[ \t]*" org-keyword-time-regexp))
14616 end hiddenp)
14617 (outline-next-heading)
14618 (setq end (point))
14619 (goto-char beg)
14620 (while (re-search-forward re end t))
14621 (setq hiddenp (outline-invisible-p))
14622 (end-of-line 1)
14623 (and (equal (char-after) ?\n) (forward-char 1))
14624 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14625 (if (member (match-string 1) '("CLOCK:" ":END:"))
14626 ;; just skip this line
14627 (beginning-of-line 2)
14628 ;; Drawer start, find the end
14629 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14630 (beginning-of-line 1)))
14631 (org-skip-over-state-notes)
14632 (skip-chars-backward " \t\n\r")
14633 (if (eq (char-before) ?*) (forward-char 1))
14634 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14635 (beginning-of-line 0)
14636 (org-indent-to-column indent)
14637 (beginning-of-line 2)
14638 (org-indent-to-column indent)
14639 (beginning-of-line 0)
14640 (if hiddenp
14641 (save-excursion
14642 (org-back-to-heading t)
14643 (hide-entry))
14644 (org-flag-drawer t))))
14646 (defun org-insert-drawer (&optional arg drawer)
14647 "Insert a drawer at point.
14649 Optional argument DRAWER, when non-nil, is a string representing
14650 drawer's name. Otherwise, the user is prompted for a name.
14652 If a region is active, insert the drawer around that region
14653 instead.
14655 Point is left between drawer's boundaries."
14656 (interactive "P")
14657 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14658 "LOGBOOK"))
14659 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14660 ;; internally by Org. They are meant to be inserted
14661 ;; automatically.
14662 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14663 ;; Remove system drawers from list. Note: For some reason,
14664 ;; `org-completing-read' ignores the predicate while
14665 ;; `completing-read' handles it fine.
14666 (drawer (if arg "PROPERTIES"
14667 (or drawer
14668 (completing-read
14669 "Drawer: " org-drawers
14670 (lambda (d) (not (member d system-drawers))))))))
14671 (cond
14672 ;; With C-u, fall back on `org-insert-property-drawer'
14673 (arg (org-insert-property-drawer))
14674 ;; With an active region, insert a drawer at point.
14675 ((not (org-region-active-p))
14676 (progn
14677 (unless (bolp) (insert "\n"))
14678 (insert (format ":%s:\n\n:END:\n" drawer))
14679 (forward-line -2)))
14680 ;; Otherwise, insert the drawer at point
14682 (let ((rbeg (region-beginning))
14683 (rend (copy-marker (region-end))))
14684 (unwind-protect
14685 (progn
14686 (goto-char rbeg)
14687 (beginning-of-line)
14688 (when (save-excursion
14689 (re-search-forward org-outline-regexp-bol rend t))
14690 (error "Drawers cannot contain headlines"))
14691 ;; Position point at the beginning of the first
14692 ;; non-blank line in region. Insert drawer's opening
14693 ;; there, then indent it.
14694 (org-skip-whitespace)
14695 (beginning-of-line)
14696 (insert ":" drawer ":\n")
14697 (forward-line -1)
14698 (indent-for-tab-command)
14699 ;; Move point to the beginning of the first blank line
14700 ;; after the last non-blank line in region. Insert
14701 ;; drawer's closing, then indent it.
14702 (goto-char rend)
14703 (skip-chars-backward " \r\t\n")
14704 (insert "\n:END:")
14705 (indent-for-tab-command)
14706 (unless (eolp) (insert "\n")))
14707 ;; Clear marker, whatever the outcome of insertion is.
14708 (set-marker rend nil)))))))
14710 (defvar org-property-set-functions-alist nil
14711 "Property set function alist.
14712 Each entry should have the following format:
14714 (PROPERTY . READ-FUNCTION)
14716 The read function will be called with the same argument as
14717 `org-completing-read'.")
14719 (defun org-set-property-function (property)
14720 "Get the function that should be used to set PROPERTY.
14721 This is computed according to `org-property-set-functions-alist'."
14722 (or (cdr (assoc property org-property-set-functions-alist))
14723 'org-completing-read))
14725 (defun org-read-property-value (property)
14726 "Read PROPERTY value from user."
14727 (let* ((completion-ignore-case t)
14728 (allowed (org-property-get-allowed-values nil property 'table))
14729 (cur (org-entry-get nil property))
14730 (prompt (concat property " value"
14731 (if (and cur (string-match "\\S-" cur))
14732 (concat " [" cur "]") "") ": "))
14733 (set-function (org-set-property-function property))
14734 (val (if allowed
14735 (funcall set-function prompt allowed nil
14736 (not (get-text-property 0 'org-unrestricted
14737 (caar allowed))))
14738 (let (org-completion-use-ido org-completion-use-iswitchb)
14739 (funcall set-function prompt
14740 (mapcar 'list (org-property-values property))
14741 nil nil "" nil cur)))))
14742 (if (equal val "")
14744 val)))
14746 (defvar org-last-set-property nil)
14747 (defun org-read-property-name ()
14748 "Read a property name."
14749 (let* ((completion-ignore-case t)
14750 (keys (org-buffer-property-keys nil t t))
14751 (default-prop (or (save-excursion
14752 (save-match-data
14753 (beginning-of-line)
14754 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14755 (null (string= (match-string 1) "END"))
14756 (match-string 1))))
14757 org-last-set-property))
14758 (property (org-icompleting-read
14759 (concat "Property"
14760 (if default-prop (concat " [" default-prop "]") "")
14761 ": ")
14762 (mapcar 'list keys)
14763 nil nil nil nil
14764 default-prop
14766 (if (member property keys)
14767 property
14768 (or (cdr (assoc (downcase property)
14769 (mapcar (lambda (x) (cons (downcase x) x))
14770 keys)))
14771 property))))
14773 (defun org-set-property (property value)
14774 "In the current entry, set PROPERTY to VALUE.
14775 When called interactively, this will prompt for a property name, offering
14776 completion on existing and default properties. And then it will prompt
14777 for a value, offering completion either on allowed values (via an inherited
14778 xxx_ALL property) or on existing values in other instances of this property
14779 in the current file."
14780 (interactive (list nil nil))
14781 (let* ((property (or property (org-read-property-name)))
14782 (value (or value (org-read-property-value property)))
14783 (fn (cdr (assoc property org-properties-postprocess-alist))))
14784 (setq org-last-set-property property)
14785 ;; Possibly postprocess the inserted value:
14786 (when fn (setq value (funcall fn value)))
14787 (unless (equal (org-entry-get nil property) value)
14788 (org-entry-put nil property value))))
14790 (defun org-delete-property (property)
14791 "In the current entry, delete PROPERTY."
14792 (interactive
14793 (let* ((completion-ignore-case t)
14794 (prop (org-icompleting-read "Property: "
14795 (org-entry-properties nil 'standard))))
14796 (list prop)))
14797 (message "Property %s %s" property
14798 (if (org-entry-delete nil property)
14799 "deleted"
14800 "was not present in the entry")))
14802 (defun org-delete-property-globally (property)
14803 "Remove PROPERTY globally, from all entries."
14804 (interactive
14805 (let* ((completion-ignore-case t)
14806 (prop (org-icompleting-read
14807 "Globally remove property: "
14808 (mapcar 'list (org-buffer-property-keys)))))
14809 (list prop)))
14810 (save-excursion
14811 (save-restriction
14812 (widen)
14813 (goto-char (point-min))
14814 (let ((cnt 0))
14815 (while (re-search-forward
14816 (org-re-property property)
14817 nil t)
14818 (setq cnt (1+ cnt))
14819 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14820 (message "Property \"%s\" removed from %d entries" property cnt)))))
14822 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14824 (defun org-compute-property-at-point ()
14825 "Compute the property at point.
14826 This looks for an enclosing column format, extracts the operator and
14827 then applies it to the property in the column format's scope."
14828 (interactive)
14829 (unless (org-at-property-p)
14830 (error "Not at a property"))
14831 (let ((prop (org-match-string-no-properties 2)))
14832 (org-columns-get-format-and-top-level)
14833 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14834 (error "No operator defined for property %s" prop))
14835 (org-columns-compute prop)))
14837 (defvar org-property-allowed-value-functions nil
14838 "Hook for functions supplying allowed values for a specific property.
14839 The functions must take a single argument, the name of the property, and
14840 return a flat list of allowed values. If \":ETC\" is one of
14841 the values, this means that these values are intended as defaults for
14842 completion, but that other values should be allowed too.
14843 The functions must return nil if they are not responsible for this
14844 property.")
14846 (defun org-property-get-allowed-values (pom property &optional table)
14847 "Get allowed values for the property PROPERTY.
14848 When TABLE is non-nil, return an alist that can directly be used for
14849 completion."
14850 (let (vals)
14851 (cond
14852 ((equal property "TODO")
14853 (setq vals (org-with-point-at pom
14854 (append org-todo-keywords-1 '("")))))
14855 ((equal property "PRIORITY")
14856 (let ((n org-lowest-priority))
14857 (while (>= n org-highest-priority)
14858 (push (char-to-string n) vals)
14859 (setq n (1- n)))))
14860 ((member property org-special-properties))
14861 ((setq vals (run-hook-with-args-until-success
14862 'org-property-allowed-value-functions property)))
14864 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14865 (when (and vals (string-match "\\S-" vals))
14866 (setq vals (car (read-from-string (concat "(" vals ")"))))
14867 (setq vals (mapcar (lambda (x)
14868 (cond ((stringp x) x)
14869 ((numberp x) (number-to-string x))
14870 ((symbolp x) (symbol-name x))
14871 (t "???")))
14872 vals)))))
14873 (when (member ":ETC" vals)
14874 (setq vals (remove ":ETC" vals))
14875 (org-add-props (car vals) '(org-unrestricted t)))
14876 (if table (mapcar 'list vals) vals)))
14878 (defun org-property-previous-allowed-value (&optional previous)
14879 "Switch to the next allowed value for this property."
14880 (interactive)
14881 (org-property-next-allowed-value t))
14883 (defun org-property-next-allowed-value (&optional previous)
14884 "Switch to the next allowed value for this property."
14885 (interactive)
14886 (unless (org-at-property-p)
14887 (error "Not at a property"))
14888 (let* ((key (match-string 2))
14889 (value (match-string 3))
14890 (allowed (or (org-property-get-allowed-values (point) key)
14891 (and (member value '("[ ]" "[-]" "[X]"))
14892 '("[ ]" "[X]"))))
14893 nval)
14894 (unless allowed
14895 (error "Allowed values for this property have not been defined"))
14896 (if previous (setq allowed (reverse allowed)))
14897 (if (member value allowed)
14898 (setq nval (car (cdr (member value allowed)))))
14899 (setq nval (or nval (car allowed)))
14900 (if (equal nval value)
14901 (error "Only one allowed value for this property"))
14902 (org-at-property-p)
14903 (replace-match (concat " :" key ": " nval) t t)
14904 (org-indent-line)
14905 (beginning-of-line 1)
14906 (skip-chars-forward " \t")
14907 (run-hook-with-args 'org-property-changed-functions key nval)))
14909 (defun org-find-olp (path &optional this-buffer)
14910 "Return a marker pointing to the entry at outline path OLP.
14911 If anything goes wrong, throw an error.
14912 You can wrap this call to catch the error like this:
14914 (condition-case msg
14915 (org-mobile-locate-entry (match-string 4))
14916 (error (nth 1 msg)))
14918 The return value will then be either a string with the error message,
14919 or a marker if everything is OK.
14921 If THIS-BUFFER is set, the outline path does not contain a file,
14922 only headings."
14923 (let* ((file (if this-buffer buffer-file-name (pop path)))
14924 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14925 (level 1)
14926 (lmin 1)
14927 (lmax 1)
14928 limit re end found pos heading cnt flevel)
14929 (unless buffer (error "File not found :%s" file))
14930 (with-current-buffer buffer
14931 (save-excursion
14932 (save-restriction
14933 (widen)
14934 (setq limit (point-max))
14935 (goto-char (point-min))
14936 (while (setq heading (pop path))
14937 (setq re (format org-complex-heading-regexp-format
14938 (regexp-quote heading)))
14939 (setq cnt 0 pos (point))
14940 (while (re-search-forward re end t)
14941 (setq level (- (match-end 1) (match-beginning 1)))
14942 (if (and (>= level lmin) (<= level lmax))
14943 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14944 (when (= cnt 0) (error "Heading not found on level %d: %s"
14945 lmax heading))
14946 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14947 lmax heading))
14948 (goto-char found)
14949 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14950 (setq end (save-excursion (org-end-of-subtree t t))))
14951 (when (org-at-heading-p)
14952 (move-marker (make-marker) (point))))))))
14954 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14955 "Find node HEADING in BUFFER.
14956 Return a marker to the heading if it was found, or nil if not.
14957 If POS-ONLY is set, return just the position instead of a marker.
14959 The heading text must match exact, but it may have a TODO keyword,
14960 a priority cookie and tags in the standard locations."
14961 (with-current-buffer (or buffer (current-buffer))
14962 (save-excursion
14963 (save-restriction
14964 (widen)
14965 (goto-char (point-min))
14966 (let (case-fold-search)
14967 (if (re-search-forward
14968 (format org-complex-heading-regexp-format
14969 (regexp-quote heading)) nil t)
14970 (if pos-only
14971 (match-beginning 0)
14972 (move-marker (make-marker) (match-beginning 0)))))))))
14974 (defun org-find-exact-heading-in-directory (heading &optional dir)
14975 "Find Org node headline HEADING in all .org files in directory DIR.
14976 When the target headline is found, return a marker to this location."
14977 (let ((files (directory-files (or dir default-directory)
14978 nil "\\`[^.#].*\\.org\\'"))
14979 file visiting m buffer)
14980 (catch 'found
14981 (while (setq file (pop files))
14982 (message "trying %s" file)
14983 (setq visiting (org-find-base-buffer-visiting file))
14984 (setq buffer (or visiting (find-file-noselect file)))
14985 (setq m (org-find-exact-headline-in-buffer
14986 heading buffer))
14987 (when (and (not m) (not visiting)) (kill-buffer buffer))
14988 (and m (throw 'found m))))))
14990 (defun org-find-entry-with-id (ident)
14991 "Locate the entry that contains the ID property with exact value IDENT.
14992 IDENT can be a string, a symbol or a number, this function will search for
14993 the string representation of it.
14994 Return the position where this entry starts, or nil if there is no such entry."
14995 (interactive "sID: ")
14996 (let ((id (cond
14997 ((stringp ident) ident)
14998 ((symbol-name ident) (symbol-name ident))
14999 ((numberp ident) (number-to-string ident))
15000 (t (error "IDENT %s must be a string, symbol or number" ident))))
15001 (case-fold-search nil))
15002 (save-excursion
15003 (save-restriction
15004 (widen)
15005 (goto-char (point-min))
15006 (when (re-search-forward
15007 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15008 nil t)
15009 (org-back-to-heading t)
15010 (point))))))
15012 ;;;; Timestamps
15014 (defvar org-last-changed-timestamp nil)
15015 (defvar org-last-inserted-timestamp nil
15016 "The last time stamp inserted with `org-insert-time-stamp'.")
15017 (defvar org-time-was-given) ; dynamically scoped parameter
15018 (defvar org-end-time-was-given) ; dynamically scoped parameter
15019 (defvar org-ts-what) ; dynamically scoped parameter
15021 (defun org-time-stamp (arg &optional inactive)
15022 "Prompt for a date/time and insert a time stamp.
15023 If the user specifies a time like HH:MM or if this command is
15024 called with at least one prefix argument, the time stamp contains
15025 the date and the time. Otherwise, only the date is be included.
15027 All parts of a date not specified by the user is filled in from
15028 the current date/time. So if you just press return without
15029 typing anything, the time stamp will represent the current
15030 date/time.
15032 If there is already a timestamp at the cursor, it will be
15033 modified.
15035 With two universal prefix arguments, insert an active timestamp
15036 with the current time without prompting the user."
15037 (interactive "P")
15038 (let* ((ts nil)
15039 (default-time
15040 ;; Default time is either today, or, when entering a range,
15041 ;; the range start.
15042 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15043 (save-excursion
15044 (re-search-backward
15045 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15046 (- (point) 20) t)))
15047 (apply 'encode-time (org-parse-time-string (match-string 1)))
15048 (current-time)))
15049 (default-input (and ts (org-get-compact-tod ts)))
15050 (repeater (save-excursion
15051 (save-match-data
15052 (beginning-of-line)
15053 (when (re-search-forward
15054 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15055 (save-excursion (progn (end-of-line) (point))) t)
15056 (match-string 0)))))
15057 org-time-was-given org-end-time-was-given time)
15058 (cond
15059 ((and (org-at-timestamp-p t)
15060 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15061 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15062 (insert "--")
15063 (setq time (let ((this-command this-command))
15064 (org-read-date arg 'totime nil nil
15065 default-time default-input inactive)))
15066 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15067 ((org-at-timestamp-p t)
15068 (setq time (let ((this-command this-command))
15069 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15070 (when (org-at-timestamp-p t) ; just to get the match data
15071 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15072 (replace-match "")
15073 (setq org-last-changed-timestamp
15074 (org-insert-time-stamp
15075 time (or org-time-was-given arg)
15076 inactive nil nil (list org-end-time-was-given)))
15077 (when repeater (goto-char (1- (point))) (insert " " repeater)
15078 (setq org-last-changed-timestamp
15079 (concat (substring org-last-inserted-timestamp 0 -1)
15080 " " repeater ">"))))
15081 (message "Timestamp updated"))
15082 ((equal arg '(16))
15083 (org-insert-time-stamp (current-time) t))
15085 (setq time (let ((this-command this-command))
15086 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15087 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15088 nil nil (list org-end-time-was-given))))))
15090 ;; FIXME: can we use this for something else, like computing time differences?
15091 (defun org-get-compact-tod (s)
15092 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15093 (let* ((t1 (match-string 1 s))
15094 (h1 (string-to-number (match-string 2 s)))
15095 (m1 (string-to-number (match-string 3 s)))
15096 (t2 (and (match-end 4) (match-string 5 s)))
15097 (h2 (and t2 (string-to-number (match-string 6 s))))
15098 (m2 (and t2 (string-to-number (match-string 7 s))))
15099 dh dm)
15100 (if (not t2)
15102 (setq dh (- h2 h1) dm (- m2 m1))
15103 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15104 (concat t1 "+" (number-to-string dh)
15105 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15107 (defun org-time-stamp-inactive (&optional arg)
15108 "Insert an inactive time stamp.
15109 An inactive time stamp is enclosed in square brackets instead of angle
15110 brackets. It is inactive in the sense that it does not trigger agenda entries,
15111 does not link to the calendar and cannot be changed with the S-cursor keys.
15112 So these are more for recording a certain time/date."
15113 (interactive "P")
15114 (org-time-stamp arg 'inactive))
15116 (defvar org-date-ovl (make-overlay 1 1))
15117 (overlay-put org-date-ovl 'face 'org-date-selected)
15118 (org-detach-overlay org-date-ovl)
15120 (defvar org-ans1) ; dynamically scoped parameter
15121 (defvar org-ans2) ; dynamically scoped parameter
15123 (defvar org-plain-time-of-day-regexp) ; defined below
15125 (defvar org-overriding-default-time nil) ; dynamically scoped
15126 (defvar org-read-date-overlay nil)
15127 (defvar org-dcst nil) ; dynamically scoped
15128 (defvar org-read-date-history nil)
15129 (defvar org-read-date-final-answer nil)
15130 (defvar org-read-date-analyze-futurep nil)
15131 (defvar org-read-date-analyze-forced-year nil)
15132 (defvar org-read-date-inactive)
15134 (defun org-read-date (&optional org-with-time to-time from-string prompt
15135 default-time default-input inactive)
15136 "Read a date, possibly a time, and make things smooth for the user.
15137 The prompt will suggest to enter an ISO date, but you can also enter anything
15138 which will at least partially be understood by `parse-time-string'.
15139 Unrecognized parts of the date will default to the current day, month, year,
15140 hour and minute. If this command is called to replace a timestamp at point,
15141 or to enter the second timestamp of a range, the default time is taken
15142 from the existing stamp. Furthermore, the command prefers the future,
15143 so if you are giving a date where the year is not given, and the day-month
15144 combination is already past in the current year, it will assume you
15145 mean next year. For details, see the manual. A few examples:
15147 3-2-5 --> 2003-02-05
15148 feb 15 --> currentyear-02-15
15149 2/15 --> currentyear-02-15
15150 sep 12 9 --> 2009-09-12
15151 12:45 --> today 12:45
15152 22 sept 0:34 --> currentyear-09-22 0:34
15153 12 --> currentyear-currentmonth-12
15154 Fri --> nearest Friday (today or later)
15155 etc.
15157 Furthermore you can specify a relative date by giving, as the *first* thing
15158 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15159 change in days weeks, months, years.
15160 With a single plus or minus, the date is relative to today. With a double
15161 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15162 +4d --> four days from today
15163 +4 --> same as above
15164 +2w --> two weeks from today
15165 ++5 --> five days from default date
15167 The function understands only English month and weekday abbreviations.
15169 While prompting, a calendar is popped up - you can also select the
15170 date with the mouse (button 1). The calendar shows a period of three
15171 months. To scroll it to other months, use the keys `>' and `<'.
15172 If you don't like the calendar, turn it off with
15173 \(setq org-read-date-popup-calendar nil)
15175 With optional argument TO-TIME, the date will immediately be converted
15176 to an internal time.
15177 With an optional argument WITH-TIME, the prompt will suggest to also
15178 insert a time. Note that when WITH-TIME is not set, you can still
15179 enter a time, and this function will inform the calling routine about
15180 this change. The calling routine may then choose to change the format
15181 used to insert the time stamp into the buffer to include the time.
15182 With optional argument FROM-STRING, read from this string instead from
15183 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15184 the time/date that is used for everything that is not specified by the
15185 user."
15186 (require 'parse-time)
15187 (let* ((org-time-stamp-rounding-minutes
15188 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15189 (org-dcst org-display-custom-times)
15190 (ct (org-current-time))
15191 (org-def (or org-overriding-default-time default-time ct))
15192 (org-defdecode (decode-time org-def))
15193 (dummy (progn
15194 (when (< (nth 2 org-defdecode) org-extend-today-until)
15195 (setcar (nthcdr 2 org-defdecode) -1)
15196 (setcar (nthcdr 1 org-defdecode) 59)
15197 (setq org-def (apply 'encode-time org-defdecode)
15198 org-defdecode (decode-time org-def)))))
15199 (calendar-frame-setup nil)
15200 (calendar-setup nil)
15201 (calendar-move-hook nil)
15202 (calendar-view-diary-initially-flag nil)
15203 (calendar-view-holidays-initially-flag nil)
15204 (timestr (format-time-string
15205 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15206 (prompt (concat (if prompt (concat prompt " ") "")
15207 (format "Date+time [%s]: " timestr)))
15208 ans (org-ans0 "") org-ans1 org-ans2 final)
15210 (cond
15211 (from-string (setq ans from-string))
15212 (org-read-date-popup-calendar
15213 (save-excursion
15214 (save-window-excursion
15215 (calendar)
15216 (org-eval-in-calendar '(setq cursor-type nil) t)
15217 (unwind-protect
15218 (progn
15219 (calendar-forward-day (- (time-to-days org-def)
15220 (calendar-absolute-from-gregorian
15221 (calendar-current-date))))
15222 (org-eval-in-calendar nil t)
15223 (let* ((old-map (current-local-map))
15224 (map (copy-keymap calendar-mode-map))
15225 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15226 (org-defkey map (kbd "RET") 'org-calendar-select)
15227 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15228 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15229 (org-defkey minibuffer-local-map [(meta shift left)]
15230 (lambda () (interactive)
15231 (org-eval-in-calendar '(calendar-backward-month 1))))
15232 (org-defkey minibuffer-local-map [(meta shift right)]
15233 (lambda () (interactive)
15234 (org-eval-in-calendar '(calendar-forward-month 1))))
15235 (org-defkey minibuffer-local-map [(meta shift up)]
15236 (lambda () (interactive)
15237 (org-eval-in-calendar '(calendar-backward-year 1))))
15238 (org-defkey minibuffer-local-map [(meta shift down)]
15239 (lambda () (interactive)
15240 (org-eval-in-calendar '(calendar-forward-year 1))))
15241 (org-defkey minibuffer-local-map [?\e (shift left)]
15242 (lambda () (interactive)
15243 (org-eval-in-calendar '(calendar-backward-month 1))))
15244 (org-defkey minibuffer-local-map [?\e (shift right)]
15245 (lambda () (interactive)
15246 (org-eval-in-calendar '(calendar-forward-month 1))))
15247 (org-defkey minibuffer-local-map [?\e (shift up)]
15248 (lambda () (interactive)
15249 (org-eval-in-calendar '(calendar-backward-year 1))))
15250 (org-defkey minibuffer-local-map [?\e (shift down)]
15251 (lambda () (interactive)
15252 (org-eval-in-calendar '(calendar-forward-year 1))))
15253 (org-defkey minibuffer-local-map [(shift up)]
15254 (lambda () (interactive)
15255 (org-eval-in-calendar '(calendar-backward-week 1))))
15256 (org-defkey minibuffer-local-map [(shift down)]
15257 (lambda () (interactive)
15258 (org-eval-in-calendar '(calendar-forward-week 1))))
15259 (org-defkey minibuffer-local-map [(shift left)]
15260 (lambda () (interactive)
15261 (org-eval-in-calendar '(calendar-backward-day 1))))
15262 (org-defkey minibuffer-local-map [(shift right)]
15263 (lambda () (interactive)
15264 (org-eval-in-calendar '(calendar-forward-day 1))))
15265 (org-defkey minibuffer-local-map ">"
15266 (lambda () (interactive)
15267 (org-eval-in-calendar '(scroll-calendar-left 1))))
15268 (org-defkey minibuffer-local-map "<"
15269 (lambda () (interactive)
15270 (org-eval-in-calendar '(scroll-calendar-right 1))))
15271 (org-defkey minibuffer-local-map "\C-v"
15272 (lambda () (interactive)
15273 (org-eval-in-calendar
15274 '(calendar-scroll-left-three-months 1))))
15275 (org-defkey minibuffer-local-map "\M-v"
15276 (lambda () (interactive)
15277 (org-eval-in-calendar
15278 '(calendar-scroll-right-three-months 1))))
15279 (run-hooks 'org-read-date-minibuffer-setup-hook)
15280 (unwind-protect
15281 (progn
15282 (use-local-map map)
15283 (setq org-read-date-inactive inactive)
15284 (add-hook 'post-command-hook 'org-read-date-display)
15285 (setq org-ans0 (read-string prompt default-input
15286 'org-read-date-history nil))
15287 ;; org-ans0: from prompt
15288 ;; org-ans1: from mouse click
15289 ;; org-ans2: from calendar motion
15290 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15291 (remove-hook 'post-command-hook 'org-read-date-display)
15292 (use-local-map old-map)
15293 (when org-read-date-overlay
15294 (delete-overlay org-read-date-overlay)
15295 (setq org-read-date-overlay nil)))))
15296 (bury-buffer "*Calendar*")))))
15298 (t ; Naked prompt only
15299 (unwind-protect
15300 (setq ans (read-string prompt default-input
15301 'org-read-date-history timestr))
15302 (when org-read-date-overlay
15303 (delete-overlay org-read-date-overlay)
15304 (setq org-read-date-overlay nil)))))
15306 (setq final (org-read-date-analyze ans org-def org-defdecode))
15308 (when org-read-date-analyze-forced-year
15309 (message "Year was forced into %s"
15310 (if org-read-date-force-compatible-dates
15311 "compatible range (1970-2037)"
15312 "range representable on this machine"))
15313 (ding))
15315 ;; One round trip to get rid of 34th of August and stuff like that....
15316 (setq final (decode-time (apply 'encode-time final)))
15318 (setq org-read-date-final-answer ans)
15320 (if to-time
15321 (apply 'encode-time final)
15322 (if (and (boundp 'org-time-was-given) org-time-was-given)
15323 (format "%04d-%02d-%02d %02d:%02d"
15324 (nth 5 final) (nth 4 final) (nth 3 final)
15325 (nth 2 final) (nth 1 final))
15326 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15328 (defvar org-def)
15329 (defvar org-defdecode)
15330 (defvar org-with-time)
15331 (defun org-read-date-display ()
15332 "Display the current date prompt interpretation in the minibuffer."
15333 (when org-read-date-display-live
15334 (when org-read-date-overlay
15335 (delete-overlay org-read-date-overlay))
15336 (when (minibufferp (current-buffer))
15337 (save-excursion
15338 (end-of-line 1)
15339 (while (not (equal (buffer-substring
15340 (max (point-min) (- (point) 4)) (point))
15341 " "))
15342 (insert " ")))
15343 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15344 " " (or org-ans1 org-ans2)))
15345 (org-end-time-was-given nil)
15346 (f (org-read-date-analyze ans org-def org-defdecode))
15347 (fmts (if org-dcst
15348 org-time-stamp-custom-formats
15349 org-time-stamp-formats))
15350 (fmt (if (or org-with-time
15351 (and (boundp 'org-time-was-given) org-time-was-given))
15352 (cdr fmts)
15353 (car fmts)))
15354 (txt (format-time-string fmt (apply 'encode-time f)))
15355 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15356 (txt (concat "=> " txt)))
15357 (when (and org-end-time-was-given
15358 (string-match org-plain-time-of-day-regexp txt))
15359 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15360 org-end-time-was-given
15361 (substring txt (match-end 0)))))
15362 (when org-read-date-analyze-futurep
15363 (setq txt (concat txt " (=>F)")))
15364 (setq org-read-date-overlay
15365 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15366 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15368 (defun org-read-date-analyze (ans org-def org-defdecode)
15369 "Analyze the combined answer of the date prompt."
15370 ;; FIXME: cleanup and comment
15371 (let ((nowdecode (decode-time (current-time)))
15372 delta deltan deltaw deltadef year month day
15373 hour minute second wday pm h2 m2 tl wday1
15374 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15375 (setq org-read-date-analyze-futurep nil
15376 org-read-date-analyze-forced-year nil)
15377 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15378 (setq ans "+0"))
15380 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15381 (setq ans (replace-match "" t t ans)
15382 deltan (car delta)
15383 deltaw (nth 1 delta)
15384 deltadef (nth 2 delta)))
15386 ;; Check if there is an iso week date in there
15387 ;; If yes, store the info and postpone interpreting it until the rest
15388 ;; of the parsing is done
15389 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15390 (setq iso-year (if (match-end 1)
15391 (org-small-year-to-year
15392 (string-to-number (match-string 1 ans))))
15393 iso-weekday (if (match-end 3)
15394 (string-to-number (match-string 3 ans)))
15395 iso-week (string-to-number (match-string 2 ans)))
15396 (setq ans (replace-match "" t t ans)))
15398 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15399 (when (string-match
15400 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15401 (setq year (if (match-end 2)
15402 (string-to-number (match-string 2 ans))
15403 (progn (setq kill-year t)
15404 (string-to-number (format-time-string "%Y"))))
15405 month (string-to-number (match-string 3 ans))
15406 day (string-to-number (match-string 4 ans)))
15407 (if (< year 100) (setq year (+ 2000 year)))
15408 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15409 t nil ans)))
15411 ;; Help matching dotted european dates
15412 (when (string-match
15413 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15414 (setq year (if (match-end 3)
15415 (string-to-number (match-string 3 ans))
15416 (progn (setq kill-year t)
15417 (string-to-number (format-time-string "%Y"))))
15418 day (string-to-number (match-string 1 ans))
15419 month (string-to-number (match-string 2 ans))
15420 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15421 t nil ans)))
15423 ;; Help matching american dates, like 5/30 or 5/30/7
15424 (when (string-match
15425 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15426 (setq year (if (match-end 4)
15427 (string-to-number (match-string 4 ans))
15428 (progn (setq kill-year t)
15429 (string-to-number (format-time-string "%Y"))))
15430 month (string-to-number (match-string 1 ans))
15431 day (string-to-number (match-string 2 ans)))
15432 (if (< year 100) (setq year (+ 2000 year)))
15433 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15434 t nil ans)))
15435 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15436 ;; If there is a time with am/pm, and *no* time without it, we convert
15437 ;; so that matching will be successful.
15438 (loop for i from 1 to 2 do ; twice, for end time as well
15439 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15440 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15441 (setq hour (string-to-number (match-string 1 ans))
15442 minute (if (match-end 3)
15443 (string-to-number (match-string 3 ans))
15445 pm (equal ?p
15446 (string-to-char (downcase (match-string 4 ans)))))
15447 (if (and (= hour 12) (not pm))
15448 (setq hour 0)
15449 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15450 (setq ans (replace-match (format "%02d:%02d" hour minute)
15451 t t ans))))
15453 ;; Check if a time range is given as a duration
15454 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15455 (setq hour (string-to-number (match-string 1 ans))
15456 h2 (+ hour (string-to-number (match-string 3 ans)))
15457 minute (string-to-number (match-string 2 ans))
15458 m2 (+ minute (if (match-end 5) (string-to-number
15459 (match-string 5 ans))0)))
15460 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15461 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15462 t t ans)))
15464 ;; Check if there is a time range
15465 (when (boundp 'org-end-time-was-given)
15466 (setq org-time-was-given nil)
15467 (when (and (string-match org-plain-time-of-day-regexp ans)
15468 (match-end 8))
15469 (setq org-end-time-was-given (match-string 8 ans))
15470 (setq ans (concat (substring ans 0 (match-beginning 7))
15471 (substring ans (match-end 7))))))
15473 (setq tl (parse-time-string ans)
15474 day (or (nth 3 tl) (nth 3 org-defdecode))
15475 month (or (nth 4 tl)
15476 (if (and org-read-date-prefer-future
15477 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15478 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15479 (nth 4 org-defdecode)))
15480 year (or (and (not kill-year) (nth 5 tl))
15481 (if (and org-read-date-prefer-future
15482 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15483 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15484 (nth 5 org-defdecode)))
15485 hour (or (nth 2 tl) (nth 2 org-defdecode))
15486 minute (or (nth 1 tl) (nth 1 org-defdecode))
15487 second (or (nth 0 tl) 0)
15488 wday (nth 6 tl))
15490 (when (and (eq org-read-date-prefer-future 'time)
15491 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15492 (equal day (nth 3 nowdecode))
15493 (equal month (nth 4 nowdecode))
15494 (equal year (nth 5 nowdecode))
15495 (nth 2 tl)
15496 (or (< (nth 2 tl) (nth 2 nowdecode))
15497 (and (= (nth 2 tl) (nth 2 nowdecode))
15498 (nth 1 tl)
15499 (< (nth 1 tl) (nth 1 nowdecode)))))
15500 (setq day (1+ day)
15501 futurep t))
15503 ;; Special date definitions below
15504 (cond
15505 (iso-week
15506 ;; There was an iso week
15507 (require 'cal-iso)
15508 (setq futurep nil)
15509 (setq year (or iso-year year)
15510 day (or iso-weekday wday 1)
15511 wday nil ; to make sure that the trigger below does not match
15512 iso-date (calendar-gregorian-from-absolute
15513 (calendar-absolute-from-iso
15514 (list iso-week day year))))
15515 ; FIXME: Should we also push ISO weeks into the future?
15516 ; (when (and org-read-date-prefer-future
15517 ; (not iso-year)
15518 ; (< (calendar-absolute-from-gregorian iso-date)
15519 ; (time-to-days (current-time))))
15520 ; (setq year (1+ year)
15521 ; iso-date (calendar-gregorian-from-absolute
15522 ; (calendar-absolute-from-iso
15523 ; (list iso-week day year)))))
15524 (setq month (car iso-date)
15525 year (nth 2 iso-date)
15526 day (nth 1 iso-date)))
15527 (deltan
15528 (setq futurep nil)
15529 (unless deltadef
15530 (let ((now (decode-time (current-time))))
15531 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15532 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15533 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15534 ((equal deltaw "m") (setq month (+ month deltan)))
15535 ((equal deltaw "y") (setq year (+ year deltan)))))
15536 ((and wday (not (nth 3 tl)))
15537 (setq futurep nil)
15538 ;; Weekday was given, but no day, so pick that day in the week
15539 ;; on or after the derived date.
15540 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15541 (unless (equal wday wday1)
15542 (setq day (+ day (% (- wday wday1 -7) 7))))))
15543 (if (and (boundp 'org-time-was-given)
15544 (nth 2 tl))
15545 (setq org-time-was-given t))
15546 (if (< year 100) (setq year (+ 2000 year)))
15547 ;; Check of the date is representable
15548 (if org-read-date-force-compatible-dates
15549 (progn
15550 (if (< year 1970)
15551 (setq year 1970 org-read-date-analyze-forced-year t))
15552 (if (> year 2037)
15553 (setq year 2037 org-read-date-analyze-forced-year t)))
15554 (condition-case nil
15555 (ignore (encode-time second minute hour day month year))
15556 (error
15557 (setq year (nth 5 org-defdecode))
15558 (setq org-read-date-analyze-forced-year t))))
15559 (setq org-read-date-analyze-futurep futurep)
15560 (list second minute hour day month year)))
15562 (defvar parse-time-weekdays)
15563 (defun org-read-date-get-relative (s today default)
15564 "Check string S for special relative date string.
15565 TODAY and DEFAULT are internal times, for today and for a default.
15566 Return shift list (N what def-flag)
15567 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15568 N is the number of WHATs to shift.
15569 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15570 the DEFAULT date rather than TODAY."
15571 (require 'parse-time)
15572 (when (and
15573 (string-match
15574 (concat
15575 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15576 "\\([0-9]+\\)?"
15577 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15578 "\\([ \t]\\|$\\)") s)
15579 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15580 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15581 (string-to-char (substring (match-string 1 s) -1))
15582 ?+))
15583 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15584 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15585 (what (if (match-end 3) (match-string 3 s) "d"))
15586 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15587 (date (if rel default today))
15588 (wday (nth 6 (decode-time date)))
15589 delta)
15590 (if wday1
15591 (progn
15592 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15593 (if (= dir ?-) (setq delta (- delta 7)))
15594 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15595 (list delta "d" rel))
15596 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15598 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15599 "Turn a user-specified date into the internal representation.
15600 The internal representation needed by the calendar is (month day year).
15601 This is a wrapper to handle the brain-dead convention in calendar that
15602 user function argument order change dependent on argument order."
15603 (if (boundp 'calendar-date-style)
15604 (cond
15605 ((eq calendar-date-style 'american)
15606 (list arg1 arg2 arg3))
15607 ((eq calendar-date-style 'european)
15608 (list arg2 arg1 arg3))
15609 ((eq calendar-date-style 'iso)
15610 (list arg2 arg3 arg1)))
15611 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15612 (if (org-bound-and-true-p european-calendar-style)
15613 (list arg2 arg1 arg3)
15614 (list arg1 arg2 arg3)))))
15616 (defun org-eval-in-calendar (form &optional keepdate)
15617 "Eval FORM in the calendar window and return to current window.
15618 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15619 otherwise stick to the current value of `org-ans2'."
15620 (let ((sf (selected-frame))
15621 (sw (selected-window)))
15622 (select-window (get-buffer-window "*Calendar*" t))
15623 (eval form)
15624 (when (and (not keepdate) (calendar-cursor-to-date))
15625 (let* ((date (calendar-cursor-to-date))
15626 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15627 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15628 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15629 (select-window sw)
15630 (org-select-frame-set-input-focus sf)))
15632 (defun org-calendar-select ()
15633 "Return to `org-read-date' with the date currently selected.
15634 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15635 (interactive)
15636 (when (calendar-cursor-to-date)
15637 (let* ((date (calendar-cursor-to-date))
15638 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15639 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15640 (if (active-minibuffer-window) (exit-minibuffer))))
15642 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15643 "Insert a date stamp for the date given by the internal TIME.
15644 WITH-HM means use the stamp format that includes the time of the day.
15645 INACTIVE means use square brackets instead of angular ones, so that the
15646 stamp will not contribute to the agenda.
15647 PRE and POST are optional strings to be inserted before and after the
15648 stamp.
15649 The command returns the inserted time stamp."
15650 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15651 stamp)
15652 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15653 (insert-before-markers (or pre ""))
15654 (when (listp extra)
15655 (setq extra (car extra))
15656 (if (and (stringp extra)
15657 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15658 (setq extra (format "-%02d:%02d"
15659 (string-to-number (match-string 1 extra))
15660 (string-to-number (match-string 2 extra))))
15661 (setq extra nil)))
15662 (when extra
15663 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15664 (insert-before-markers (setq stamp (format-time-string fmt time)))
15665 (insert-before-markers (or post ""))
15666 (setq org-last-inserted-timestamp stamp)))
15668 (defun org-toggle-time-stamp-overlays ()
15669 "Toggle the use of custom time stamp formats."
15670 (interactive)
15671 (setq org-display-custom-times (not org-display-custom-times))
15672 (unless org-display-custom-times
15673 (let ((p (point-min)) (bmp (buffer-modified-p)))
15674 (while (setq p (next-single-property-change p 'display))
15675 (if (and (get-text-property p 'display)
15676 (eq (get-text-property p 'face) 'org-date))
15677 (remove-text-properties
15678 p (setq p (next-single-property-change p 'display))
15679 '(display t))))
15680 (set-buffer-modified-p bmp)))
15681 (if (featurep 'xemacs)
15682 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15683 (org-restart-font-lock)
15684 (setq org-table-may-need-update t)
15685 (if org-display-custom-times
15686 (message "Time stamps are overlaid with custom format")
15687 (message "Time stamp overlays removed")))
15689 (defun org-display-custom-time (beg end)
15690 "Overlay modified time stamp format over timestamp between BEG and END."
15691 (let* ((ts (buffer-substring beg end))
15692 t1 w1 with-hm tf time str w2 (off 0))
15693 (save-match-data
15694 (setq t1 (org-parse-time-string ts t))
15695 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15696 (setq off (- (match-end 0) (match-beginning 0)))))
15697 (setq end (- end off))
15698 (setq w1 (- end beg)
15699 with-hm (and (nth 1 t1) (nth 2 t1))
15700 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15701 time (org-fix-decoded-time t1)
15702 str (org-add-props
15703 (format-time-string
15704 (substring tf 1 -1) (apply 'encode-time time))
15705 nil 'mouse-face 'highlight)
15706 w2 (length str))
15707 (if (not (= w2 w1))
15708 (add-text-properties (1+ beg) (+ 2 beg)
15709 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15710 (if (featurep 'xemacs)
15711 (progn
15712 (put-text-property beg end 'invisible t)
15713 (put-text-property beg end 'end-glyph (make-glyph str)))
15714 (put-text-property beg end 'display str))))
15716 (defun org-translate-time (string)
15717 "Translate all timestamps in STRING to custom format.
15718 But do this only if the variable `org-display-custom-times' is set."
15719 (when org-display-custom-times
15720 (save-match-data
15721 (let* ((start 0)
15722 (re org-ts-regexp-both)
15723 t1 with-hm inactive tf time str beg end)
15724 (while (setq start (string-match re string start))
15725 (setq beg (match-beginning 0)
15726 end (match-end 0)
15727 t1 (save-match-data
15728 (org-parse-time-string (substring string beg end) t))
15729 with-hm (and (nth 1 t1) (nth 2 t1))
15730 inactive (equal (substring string beg (1+ beg)) "[")
15731 tf (funcall (if with-hm 'cdr 'car)
15732 org-time-stamp-custom-formats)
15733 time (org-fix-decoded-time t1)
15734 str (format-time-string
15735 (concat
15736 (if inactive "[" "<") (substring tf 1 -1)
15737 (if inactive "]" ">"))
15738 (apply 'encode-time time))
15739 string (replace-match str t t string)
15740 start (+ start (length str)))))))
15741 string)
15743 (defun org-fix-decoded-time (time)
15744 "Set 0 instead of nil for the first 6 elements of time.
15745 Don't touch the rest."
15746 (let ((n 0))
15747 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15749 (defun org-days-to-time (timestamp-string)
15750 "Difference between TIMESTAMP-STRING and now in days."
15751 (- (time-to-days (org-time-string-to-time timestamp-string))
15752 (time-to-days (current-time))))
15754 (defun org-deadline-close (timestamp-string &optional ndays)
15755 "Is the time in TIMESTAMP-STRING close to the current date?"
15756 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15757 (and (< (org-days-to-time timestamp-string) ndays)
15758 (not (org-entry-is-done-p))))
15760 (defun org-get-wdays (ts)
15761 "Get the deadline lead time appropriate for timestring TS."
15762 (cond
15763 ((<= org-deadline-warning-days 0)
15764 ;; 0 or negative, enforce this value no matter what
15765 (- org-deadline-warning-days))
15766 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15767 ;; lead time is specified.
15768 (floor (* (string-to-number (match-string 1 ts))
15769 (cdr (assoc (match-string 2 ts)
15770 '(("d" . 1) ("w" . 7)
15771 ("m" . 30.4) ("y" . 365.25)))))))
15772 ;; go for the default.
15773 (t org-deadline-warning-days)))
15775 (defun org-calendar-select-mouse (ev)
15776 "Return to `org-read-date' with the date currently selected.
15777 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15778 (interactive "e")
15779 (mouse-set-point ev)
15780 (when (calendar-cursor-to-date)
15781 (let* ((date (calendar-cursor-to-date))
15782 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15783 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15784 (if (active-minibuffer-window) (exit-minibuffer))))
15786 (defun org-check-deadlines (ndays)
15787 "Check if there are any deadlines due or past due.
15788 A deadline is considered due if it happens within `org-deadline-warning-days'
15789 days from today's date. If the deadline appears in an entry marked DONE,
15790 it is not shown. The prefix arg NDAYS can be used to test that many
15791 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15792 (interactive "P")
15793 (let* ((org-warn-days
15794 (cond
15795 ((equal ndays '(4)) 100000)
15796 (ndays (prefix-numeric-value ndays))
15797 (t (abs org-deadline-warning-days))))
15798 (case-fold-search nil)
15799 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15800 (callback
15801 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15803 (message "%d deadlines past-due or due within %d days"
15804 (org-occur regexp nil callback)
15805 org-warn-days)))
15807 (defun org-check-before-date (date)
15808 "Check if there are deadlines or scheduled entries before DATE."
15809 (interactive (list (org-read-date)))
15810 (let ((case-fold-search nil)
15811 (regexp (concat "\\<\\(" org-deadline-string
15812 "\\|" org-scheduled-string
15813 "\\) *<\\([^>]+\\)>"))
15814 (callback
15815 (lambda () (time-less-p
15816 (org-time-string-to-time (match-string 2))
15817 (org-time-string-to-time date)))))
15818 (message "%d entries before %s"
15819 (org-occur regexp nil callback) date)))
15821 (defun org-check-after-date (date)
15822 "Check if there are deadlines or scheduled entries after DATE."
15823 (interactive (list (org-read-date)))
15824 (let ((case-fold-search nil)
15825 (regexp (concat "\\<\\(" org-deadline-string
15826 "\\|" org-scheduled-string
15827 "\\) *<\\([^>]+\\)>"))
15828 (callback
15829 (lambda () (not
15830 (time-less-p
15831 (org-time-string-to-time (match-string 2))
15832 (org-time-string-to-time date))))))
15833 (message "%d entries after %s"
15834 (org-occur regexp nil callback) date)))
15836 (defun org-check-dates-range (start-date end-date)
15837 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15838 (interactive (list (org-read-date nil nil nil "Range starts")
15839 (org-read-date nil nil nil "Range end")))
15840 (let ((case-fold-search nil)
15841 (regexp (concat "\\<\\(" org-deadline-string
15842 "\\|" org-scheduled-string
15843 "\\) *<\\([^>]+\\)>"))
15844 (callback
15845 (lambda ()
15846 (let ((match (match-string 2)))
15847 (and
15848 (not (time-less-p
15849 (org-time-string-to-time match)
15850 (org-time-string-to-time start-date)))
15851 (time-less-p
15852 (org-time-string-to-time match)
15853 (org-time-string-to-time end-date)))))))
15854 (message "%d entries between %s and %s"
15855 (org-occur regexp nil callback) start-date end-date)))
15857 (defun org-evaluate-time-range (&optional to-buffer)
15858 "Evaluate a time range by computing the difference between start and end.
15859 Normally the result is just printed in the echo area, but with prefix arg
15860 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15861 If the time range is actually in a table, the result is inserted into the
15862 next column.
15863 For time difference computation, a year is assumed to be exactly 365
15864 days in order to avoid rounding problems."
15865 (interactive "P")
15867 (org-clock-update-time-maybe)
15868 (save-excursion
15869 (unless (org-at-date-range-p t)
15870 (goto-char (point-at-bol))
15871 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15872 (if (not (org-at-date-range-p t))
15873 (error "Not at a time-stamp range, and none found in current line")))
15874 (let* ((ts1 (match-string 1))
15875 (ts2 (match-string 2))
15876 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15877 (match-end (match-end 0))
15878 (time1 (org-time-string-to-time ts1))
15879 (time2 (org-time-string-to-time ts2))
15880 (t1 (org-float-time time1))
15881 (t2 (org-float-time time2))
15882 (diff (abs (- t2 t1)))
15883 (negative (< (- t2 t1) 0))
15884 ;; (ys (floor (* 365 24 60 60)))
15885 (ds (* 24 60 60))
15886 (hs (* 60 60))
15887 (fy "%dy %dd %02d:%02d")
15888 (fy1 "%dy %dd")
15889 (fd "%dd %02d:%02d")
15890 (fd1 "%dd")
15891 (fh "%02d:%02d")
15892 y d h m align)
15893 (if havetime
15894 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15896 d (floor (/ diff ds)) diff (mod diff ds)
15897 h (floor (/ diff hs)) diff (mod diff hs)
15898 m (floor (/ diff 60)))
15899 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15901 d (floor (+ (/ diff ds) 0.5))
15902 h 0 m 0))
15903 (if (not to-buffer)
15904 (message "%s" (org-make-tdiff-string y d h m))
15905 (if (org-at-table-p)
15906 (progn
15907 (goto-char match-end)
15908 (setq align t)
15909 (and (looking-at " *|") (goto-char (match-end 0))))
15910 (goto-char match-end))
15911 (if (looking-at
15912 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15913 (replace-match ""))
15914 (if negative (insert " -"))
15915 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15916 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15917 (insert " " (format fh h m))))
15918 (if align (org-table-align))
15919 (message "Time difference inserted")))))
15921 (defun org-make-tdiff-string (y d h m)
15922 (let ((fmt "")
15923 (l nil))
15924 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15925 l (push y l)))
15926 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15927 l (push d l)))
15928 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15929 l (push h l)))
15930 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15931 l (push m l)))
15932 (apply 'format fmt (nreverse l))))
15934 (defun org-time-string-to-time (s &optional buffer pos)
15935 (condition-case errdata
15936 (apply 'encode-time (org-parse-time-string s))
15937 (error (error "Bad timestamp `%s'%s\nError was: %s"
15938 s (if (not (and buffer pos))
15940 (format " at %d in buffer `%s'" pos buffer))
15941 (cdr errdata)))))
15943 (defun org-time-string-to-seconds (s)
15944 (org-float-time (org-time-string-to-time s)))
15946 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15947 "Convert a time stamp to an absolute day number.
15948 If there is a specifier for a cyclic time stamp, get the closest date to
15949 DAYNR.
15950 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15951 The variable date is bound by the calendar when this is called."
15952 (cond
15953 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15954 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15955 daynr
15956 (+ daynr 1000)))
15957 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
15958 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15959 (time-to-days (current-time))) (match-string 0 s)
15960 prefer show-all))
15961 (t (time-to-days
15962 (condition-case errdata
15963 (apply 'encode-time (org-parse-time-string s))
15964 (error (error "Bad timestamp `%s'%s\nError was: %s"
15965 s (if (not (and buffer pos))
15967 (format " at %d in buffer `%s'" pos buffer))
15968 (cdr errdata))))))))
15970 (defun org-days-to-iso-week (days)
15971 "Return the iso week number."
15972 (require 'cal-iso)
15973 (car (calendar-iso-from-absolute days)))
15975 (defun org-small-year-to-year (year)
15976 "Convert 2-digit years into 4-digit years.
15977 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15978 The year 2000 cannot be abbreviated. Any year larger than 99
15979 is returned unchanged."
15980 (if (< year 38)
15981 (setq year (+ 2000 year))
15982 (if (< year 100)
15983 (setq year (+ 1900 year))))
15984 year)
15986 (defun org-time-from-absolute (d)
15987 "Return the time corresponding to date D.
15988 D may be an absolute day number, or a calendar-type list (month day year)."
15989 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15990 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15992 (defun org-calendar-holiday ()
15993 "List of holidays, for Diary display in Org-mode."
15994 (require 'holidays)
15995 (let ((hl (funcall
15996 (if (fboundp 'calendar-check-holidays)
15997 'calendar-check-holidays 'check-calendar-holidays) date)))
15998 (if hl (mapconcat 'identity hl "; "))))
16000 (defun org-diary-sexp-entry (sexp entry date)
16001 "Process a SEXP diary ENTRY for DATE."
16002 (require 'diary-lib)
16003 (let ((result (if calendar-debug-sexp
16004 (let ((stack-trace-on-error t))
16005 (eval (car (read-from-string sexp))))
16006 (condition-case nil
16007 (eval (car (read-from-string sexp)))
16008 (error
16009 (beep)
16010 (message "Bad sexp at line %d in %s: %s"
16011 (org-current-line)
16012 (buffer-file-name) sexp)
16013 (sleep-for 2))))))
16014 (cond ((stringp result) (split-string result "; "))
16015 ((and (consp result)
16016 (not (consp (cdr result)))
16017 (stringp (cdr result))) (cdr result))
16018 ((and (consp result)
16019 (stringp (car result))) result)
16020 (result entry)
16021 (t nil))))
16023 (defun org-diary-to-ical-string (frombuf)
16024 "Get iCalendar entries from diary entries in buffer FROMBUF.
16025 This uses the icalendar.el library."
16026 (let* ((tmpdir (if (featurep 'xemacs)
16027 (temp-directory)
16028 temporary-file-directory))
16029 (tmpfile (make-temp-name
16030 (expand-file-name "orgics" tmpdir)))
16031 buf rtn b e)
16032 (with-current-buffer frombuf
16033 (icalendar-export-region (point-min) (point-max) tmpfile)
16034 (setq buf (find-buffer-visiting tmpfile))
16035 (set-buffer buf)
16036 (goto-char (point-min))
16037 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16038 (setq b (match-beginning 0)))
16039 (goto-char (point-max))
16040 (if (re-search-backward "^END:VEVENT" nil t)
16041 (setq e (match-end 0)))
16042 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16043 (kill-buffer buf)
16044 (delete-file tmpfile)
16045 rtn))
16047 (defun org-closest-date (start current change prefer show-all)
16048 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16049 When PREFER is `past', return a date that is either CURRENT or past.
16050 When PREFER is `future', return a date that is either CURRENT or future.
16051 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16052 ;; Make the proper lists from the dates
16053 (catch 'exit
16054 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16055 dn dw sday cday n1 n2 n0
16056 d m y y1 y2 date1 date2 nmonths nm ny m2)
16058 (setq start (org-date-to-gregorian start)
16059 current (org-date-to-gregorian
16060 (if show-all
16061 current
16062 (time-to-days (current-time))))
16063 sday (calendar-absolute-from-gregorian start)
16064 cday (calendar-absolute-from-gregorian current))
16066 (if (<= cday sday) (throw 'exit sday))
16068 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16069 (setq dn (string-to-number (match-string 1 change))
16070 dw (cdr (assoc (match-string 2 change) a1)))
16071 (error "Invalid change specifier: %s" change))
16072 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16073 (cond
16074 ((eq dw 'day)
16075 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16076 n2 (+ n1 dn)))
16077 ((eq dw 'year)
16078 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16079 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16080 (setq date1 (list m d y1)
16081 n1 (calendar-absolute-from-gregorian date1)
16082 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16083 n2 (calendar-absolute-from-gregorian date2)))
16084 ((eq dw 'month)
16085 ;; approx number of month between the two dates
16086 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16087 ;; How often does dn fit in there?
16088 (setq d (nth 1 start) m (car start) y (nth 2 start)
16089 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16090 m (+ m nm)
16091 ny (floor (/ m 12))
16092 y (+ y ny)
16093 m (- m (* ny 12)))
16094 (while (> m 12) (setq m (- m 12) y (1+ y)))
16095 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16096 (setq m2 (+ m dn) y2 y)
16097 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16098 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16099 (while (<= n2 cday)
16100 (setq n1 n2 m m2 y y2)
16101 (setq m2 (+ m dn) y2 y)
16102 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16103 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16104 ;; Make sure n1 is the earlier date
16105 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16106 (if show-all
16107 (cond
16108 ((eq prefer 'past) (if (= cday n2) n2 n1))
16109 ((eq prefer 'future) (if (= cday n1) n1 n2))
16110 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16111 (cond
16112 ((eq prefer 'past) (if (= cday n2) n2 n1))
16113 ((eq prefer 'future) (if (= cday n1) n1 n2))
16114 (t (if (= cday n1) n1 n2)))))))
16116 (defun org-date-to-gregorian (date)
16117 "Turn any specification of DATE into a Gregorian date for the calendar."
16118 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16119 ((and (listp date) (= (length date) 3)) date)
16120 ((stringp date)
16121 (setq date (org-parse-time-string date))
16122 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16123 ((listp date)
16124 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16126 (defun org-parse-time-string (s &optional nodefault)
16127 "Parse the standard Org-mode time string.
16128 This should be a lot faster than the normal `parse-time-string'.
16129 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16130 hour and minute fields will be nil if not given."
16131 (if (string-match org-ts-regexp0 s)
16132 (list 0
16133 (if (or (match-beginning 8) (not nodefault))
16134 (string-to-number (or (match-string 8 s) "0")))
16135 (if (or (match-beginning 7) (not nodefault))
16136 (string-to-number (or (match-string 7 s) "0")))
16137 (string-to-number (match-string 4 s))
16138 (string-to-number (match-string 3 s))
16139 (string-to-number (match-string 2 s))
16140 nil nil nil)
16141 (error "Not a standard Org-mode time string: %s" s)))
16143 (defun org-timestamp-up (&optional arg)
16144 "Increase the date item at the cursor by one.
16145 If the cursor is on the year, change the year. If it is on the month,
16146 the day or the time, change that.
16147 With prefix ARG, change by that many units."
16148 (interactive "p")
16149 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16151 (defun org-timestamp-down (&optional arg)
16152 "Decrease the date item at the cursor by one.
16153 If the cursor is on the year, change the year. If it is on the month,
16154 the day or the time, change that.
16155 With prefix ARG, change by that many units."
16156 (interactive "p")
16157 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16159 (defun org-timestamp-up-day (&optional arg)
16160 "Increase the date in the time stamp by one day.
16161 With prefix ARG, change that many days."
16162 (interactive "p")
16163 (if (and (not (org-at-timestamp-p t))
16164 (org-at-heading-p))
16165 (org-todo 'up)
16166 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16168 (defun org-timestamp-down-day (&optional arg)
16169 "Decrease the date in the time stamp by one day.
16170 With prefix ARG, change that many days."
16171 (interactive "p")
16172 (if (and (not (org-at-timestamp-p t))
16173 (org-at-heading-p))
16174 (org-todo 'down)
16175 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16177 (defun org-at-timestamp-p (&optional inactive-ok)
16178 "Determine if the cursor is in or at a timestamp."
16179 (interactive)
16180 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16181 (pos (point))
16182 (ans (or (looking-at tsr)
16183 (save-excursion
16184 (skip-chars-backward "^[<\n\r\t")
16185 (if (> (point) (point-min)) (backward-char 1))
16186 (and (looking-at tsr)
16187 (> (- (match-end 0) pos) -1))))))
16188 (and ans
16189 (boundp 'org-ts-what)
16190 (setq org-ts-what
16191 (cond
16192 ((= pos (match-beginning 0)) 'bracket)
16193 ;; Point is considered to be "on the bracket" whether
16194 ;; it's really on it or right after it.
16195 ((= pos (1- (match-end 0))) 'bracket)
16196 ((= pos (match-end 0)) 'after)
16197 ((org-pos-in-match-range pos 2) 'year)
16198 ((org-pos-in-match-range pos 3) 'month)
16199 ((org-pos-in-match-range pos 7) 'hour)
16200 ((org-pos-in-match-range pos 8) 'minute)
16201 ((or (org-pos-in-match-range pos 4)
16202 (org-pos-in-match-range pos 5)) 'day)
16203 ((and (> pos (or (match-end 8) (match-end 5)))
16204 (< pos (match-end 0)))
16205 (- pos (or (match-end 8) (match-end 5))))
16206 (t 'day))))
16207 ans))
16209 (defun org-toggle-timestamp-type ()
16210 "Toggle the type (<active> or [inactive]) of a time stamp."
16211 (interactive)
16212 (when (org-at-timestamp-p t)
16213 (let ((beg (match-beginning 0)) (end (match-end 0))
16214 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16215 (save-excursion
16216 (goto-char beg)
16217 (while (re-search-forward "[][<>]" end t)
16218 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16219 t t)))
16220 (message "Timestamp is now %sactive"
16221 (if (equal (char-after beg) ?<) "" "in")))))
16223 (defun org-timestamp-change (n &optional what updown)
16224 "Change the date in the time stamp at point.
16225 The date will be changed by N times WHAT. WHAT can be `day', `month',
16226 `year', `minute', `second'. If WHAT is not given, the cursor position
16227 in the timestamp determines what will be changed."
16228 (let ((origin (point)) origin-cat
16229 with-hm inactive
16230 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16231 org-ts-what
16232 extra rem
16233 ts time time0)
16234 (if (not (org-at-timestamp-p t))
16235 (error "Not at a timestamp"))
16236 (if (and (not what) (eq org-ts-what 'bracket))
16237 (org-toggle-timestamp-type)
16238 ;; Point isn't on brackets. Remember the part of the time-stamp
16239 ;; the point was in. Indeed, size of time-stamps may change,
16240 ;; but point must be kept in the same category nonetheless.
16241 (setq origin-cat org-ts-what)
16242 (if (and (not what) (not (eq org-ts-what 'day))
16243 org-display-custom-times
16244 (get-text-property (point) 'display)
16245 (not (get-text-property (1- (point)) 'display)))
16246 (setq org-ts-what 'day))
16247 (setq org-ts-what (or what org-ts-what)
16248 inactive (= (char-after (match-beginning 0)) ?\[)
16249 ts (match-string 0))
16250 (replace-match "")
16251 (if (string-match
16252 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16254 (setq extra (match-string 1 ts)))
16255 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16256 (setq with-hm t))
16257 (setq time0 (org-parse-time-string ts))
16258 (when (and updown
16259 (eq org-ts-what 'minute)
16260 (not current-prefix-arg))
16261 ;; This looks like s-up and s-down. Change by one rounding step.
16262 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16263 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16264 (setcar (cdr time0) (+ (nth 1 time0)
16265 (if (> n 0) (- rem) (- dm rem))))))
16266 (setq time
16267 (encode-time (or (car time0) 0)
16268 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16269 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16270 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16271 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16272 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16273 (nthcdr 6 time0)))
16274 (when (and (member org-ts-what '(hour minute))
16275 extra
16276 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16277 (setq extra (org-modify-ts-extra
16278 extra
16279 (if (eq org-ts-what 'hour) 2 5)
16280 n dm)))
16281 (when (integerp org-ts-what)
16282 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16283 (if (eq what 'calendar)
16284 (let ((cal-date (org-get-date-from-calendar)))
16285 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16286 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16287 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16288 (setcar time0 (or (car time0) 0))
16289 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16290 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16291 (setq time (apply 'encode-time time0))))
16292 ;; Insert the new time-stamp, and ensure point stays in the same
16293 ;; category as before (i.e. not after the last position in that
16294 ;; category).
16295 (let ((pos (point)))
16296 ;; Stay before inserted string. `save-excursion' is of no use.
16297 (setq org-last-changed-timestamp
16298 (org-insert-time-stamp time with-hm inactive nil nil extra))
16299 (goto-char pos))
16300 (save-match-data
16301 (looking-at org-ts-regexp3)
16302 (goto-char (cond
16303 ;; `day' category ends before `hour' if any, or at
16304 ;; the end of the day name.
16305 ((eq origin-cat 'day)
16306 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16307 ((eq origin-cat 'hour) (min (match-end 7) origin))
16308 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16309 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16310 ;; `year' and `month' have both fixed size: point
16311 ;; couldn't have moved into another part.
16312 (t origin))))
16313 ;; Update clock if on a CLOCK line.
16314 (org-clock-update-time-maybe)
16315 ;; Try to recenter the calendar window, if any.
16316 (if (and org-calendar-follow-timestamp-change
16317 (get-buffer-window "*Calendar*" t)
16318 (memq org-ts-what '(day month year)))
16319 (org-recenter-calendar (time-to-days time))))))
16321 (defun org-modify-ts-extra (s pos n dm)
16322 "Change the different parts of the lead-time and repeat fields in timestamp."
16323 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16324 ng h m new rem)
16325 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16326 (cond
16327 ((or (org-pos-in-match-range pos 2)
16328 (org-pos-in-match-range pos 3))
16329 (setq m (string-to-number (match-string 3 s))
16330 h (string-to-number (match-string 2 s)))
16331 (if (org-pos-in-match-range pos 2)
16332 (setq h (+ h n))
16333 (setq n (* dm (org-no-warnings (signum n))))
16334 (when (not (= 0 (setq rem (% m dm))))
16335 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16336 (setq m (+ m n)))
16337 (if (< m 0) (setq m (+ m 60) h (1- h)))
16338 (if (> m 59) (setq m (- m 60) h (1+ h)))
16339 (setq h (min 24 (max 0 h)))
16340 (setq ng 1 new (format "-%02d:%02d" h m)))
16341 ((org-pos-in-match-range pos 6)
16342 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16343 ((org-pos-in-match-range pos 5)
16344 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16346 ((org-pos-in-match-range pos 9)
16347 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16348 ((org-pos-in-match-range pos 8)
16349 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16351 (when ng
16352 (setq s (concat
16353 (substring s 0 (match-beginning ng))
16355 (substring s (match-end ng))))))
16358 (defun org-recenter-calendar (date)
16359 "If the calendar is visible, recenter it to DATE."
16360 (let ((cwin (get-buffer-window "*Calendar*" t)))
16361 (when cwin
16362 (let ((calendar-move-hook nil))
16363 (with-selected-window cwin
16364 (calendar-goto-date (if (listp date) date
16365 (calendar-gregorian-from-absolute date))))))))
16367 (defun org-goto-calendar (&optional arg)
16368 "Go to the Emacs calendar at the current date.
16369 If there is a time stamp in the current line, go to that date.
16370 A prefix ARG can be used to force the current date."
16371 (interactive "P")
16372 (let ((tsr org-ts-regexp) diff
16373 (calendar-move-hook nil)
16374 (calendar-view-holidays-initially-flag nil)
16375 (calendar-view-diary-initially-flag nil))
16376 (if (or (org-at-timestamp-p)
16377 (save-excursion
16378 (beginning-of-line 1)
16379 (looking-at (concat ".*" tsr))))
16380 (let ((d1 (time-to-days (current-time)))
16381 (d2 (time-to-days
16382 (org-time-string-to-time (match-string 1)))))
16383 (setq diff (- d2 d1))))
16384 (calendar)
16385 (calendar-goto-today)
16386 (if (and diff (not arg)) (calendar-forward-day diff))))
16388 (defun org-get-date-from-calendar ()
16389 "Return a list (month day year) of date at point in calendar."
16390 (with-current-buffer "*Calendar*"
16391 (save-match-data
16392 (calendar-cursor-to-date))))
16394 (defun org-date-from-calendar ()
16395 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16396 If there is already a time stamp at the cursor position, update it."
16397 (interactive)
16398 (if (org-at-timestamp-p t)
16399 (org-timestamp-change 0 'calendar)
16400 (let ((cal-date (org-get-date-from-calendar)))
16401 (org-insert-time-stamp
16402 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16404 (defun org-minutes-to-hh:mm-string (m)
16405 "Compute H:MM from a number of minutes."
16406 (let ((h (/ m 60)))
16407 (setq m (- m (* 60 h)))
16408 (format org-time-clocksum-format h m)))
16410 (defun org-hh:mm-string-to-minutes (s)
16411 "Convert a string H:MM to a number of minutes.
16412 If the string is just a number, interpret it as minutes.
16413 In fact, the first hh:mm or number in the string will be taken,
16414 there can be extra stuff in the string.
16415 If no number is found, the return value is 0."
16416 (cond
16417 ((integerp s) s)
16418 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16419 (+ (* (string-to-number (match-string 1 s)) 60)
16420 (string-to-number (match-string 2 s))))
16421 ((string-match "\\([0-9]+\\)" s)
16422 (string-to-number (match-string 1 s)))
16423 (t 0)))
16425 (defcustom org-effort-durations
16426 `(("h" . 60)
16427 ("d" . ,(* 60 8))
16428 ("w" . ,(* 60 8 5))
16429 ("m" . ,(* 60 8 5 4))
16430 ("y" . ,(* 60 8 5 40)))
16431 "Conversion factor to minutes for an effort modifier.
16433 Each entry has the form (MODIFIER . MINUTES).
16435 In an effort string, a number followed by MODIFIER is multiplied
16436 by the specified number of MINUTES to obtain an effort in
16437 minutes.
16439 For example, if the value of this variable is ((\"hours\" . 60)), then an
16440 effort string \"2hours\" is equivalent to 120 minutes."
16441 :group 'org-agenda
16442 :version "24.1"
16443 :type '(alist :key-type (string :tag "Modifier")
16444 :value-type (number :tag "Minutes")))
16446 (defun org-duration-string-to-minutes (s &optional output-to-string)
16447 "Convert a duration string S to minutes.
16449 A bare number is interpreted as minutes, modifiers can be set by
16450 customizing `org-effort-durations' (which see).
16452 Entries containing a colon are interpreted as H:MM by
16453 `org-hh:mm-string-to-minutes'."
16454 (let ((result 0)
16455 (re (concat "\\([0-9.]+\\) *\\("
16456 (regexp-opt (mapcar 'car org-effort-durations))
16457 "\\)")))
16458 (while (string-match re s)
16459 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16460 (string-to-number (match-string 1 s))))
16461 (setq s (replace-match "" nil t s)))
16462 (setq result (floor result))
16463 (incf result (org-hh:mm-string-to-minutes s))
16464 (if output-to-string (number-to-string result) result)))
16466 ;;;; Files
16468 (defun org-save-all-org-buffers ()
16469 "Save all Org-mode buffers without user confirmation."
16470 (interactive)
16471 (message "Saving all Org-mode buffers...")
16472 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16473 (when (featurep 'org-id) (org-id-locations-save))
16474 (message "Saving all Org-mode buffers... done"))
16476 (defun org-revert-all-org-buffers ()
16477 "Revert all Org-mode buffers.
16478 Prompt for confirmation when there are unsaved changes.
16479 Be sure you know what you are doing before letting this function
16480 overwrite your changes.
16482 This function is useful in a setup where one tracks org files
16483 with a version control system, to revert on one machine after pulling
16484 changes from another. I believe the procedure must be like this:
16486 1. M-x org-save-all-org-buffers
16487 2. Pull changes from the other machine, resolve conflicts
16488 3. M-x org-revert-all-org-buffers"
16489 (interactive)
16490 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16491 (error "Abort"))
16492 (save-excursion
16493 (save-window-excursion
16494 (mapc
16495 (lambda (b)
16496 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16497 (with-current-buffer b buffer-file-name))
16498 (org-pop-to-buffer-same-window b)
16499 (revert-buffer t 'no-confirm)))
16500 (buffer-list))
16501 (when (and (featurep 'org-id) org-id-track-globally)
16502 (org-id-locations-load)))))
16504 ;;;; Agenda files
16506 ;;;###autoload
16507 (defun org-switchb (&optional arg)
16508 "Switch between Org buffers.
16509 With one prefix argument, restrict available buffers to files.
16510 With two prefix arguments, restrict available buffers to agenda files.
16512 Defaults to `iswitchb' for buffer name completion.
16513 Set `org-completion-use-ido' to make it use ido instead."
16514 (interactive "P")
16515 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16516 ((equal arg '(16)) (org-buffer-list 'agenda))
16517 (t (org-buffer-list))))
16518 (org-completion-use-iswitchb org-completion-use-iswitchb)
16519 (org-completion-use-ido org-completion-use-ido))
16520 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16521 (setq org-completion-use-iswitchb t))
16522 (org-pop-to-buffer-same-window
16523 (org-icompleting-read "Org buffer: "
16524 (mapcar 'list (mapcar 'buffer-name blist))
16525 nil t))))
16527 ;;; Define some older names previously used for this functionality
16528 ;;;###autoload
16529 (defalias 'org-ido-switchb 'org-switchb)
16530 ;;;###autoload
16531 (defalias 'org-iswitchb 'org-switchb)
16533 (defun org-buffer-list (&optional predicate exclude-tmp)
16534 "Return a list of Org buffers.
16535 PREDICATE can be `export', `files' or `agenda'.
16537 export restrict the list to Export buffers.
16538 files restrict the list to buffers visiting Org files.
16539 agenda restrict the list to buffers visiting agenda files.
16541 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16542 (let* ((bfn nil)
16543 (agenda-files (and (eq predicate 'agenda)
16544 (mapcar 'file-truename (org-agenda-files t))))
16545 (filter
16546 (cond
16547 ((eq predicate 'files)
16548 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16549 ((eq predicate 'export)
16550 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16551 ((eq predicate 'agenda)
16552 (lambda (b)
16553 (with-current-buffer b
16554 (and (derived-mode-p 'org-mode)
16555 (setq bfn (buffer-file-name b))
16556 (member (file-truename bfn) agenda-files)))))
16557 (t (lambda (b) (with-current-buffer b
16558 (or (derived-mode-p 'org-mode)
16559 (string-match "\*Org .*Export"
16560 (buffer-name b)))))))))
16561 (delq nil
16562 (mapcar
16563 (lambda(b)
16564 (if (and (funcall filter b)
16565 (or (not exclude-tmp)
16566 (not (string-match "tmp" (buffer-name b)))))
16568 nil))
16569 (buffer-list)))))
16571 (defun org-agenda-files (&optional unrestricted archives)
16572 "Get the list of agenda files.
16573 Optional UNRESTRICTED means return the full list even if a restriction
16574 is currently in place.
16575 When ARCHIVES is t, include all archive files that are really being
16576 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16577 `org-agenda-archives-mode' is t."
16578 (let ((files
16579 (cond
16580 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16581 ((stringp org-agenda-files) (org-read-agenda-file-list))
16582 ((listp org-agenda-files) org-agenda-files)
16583 (t (error "Invalid value of `org-agenda-files'")))))
16584 (setq files (apply 'append
16585 (mapcar (lambda (f)
16586 (if (file-directory-p f)
16587 (directory-files
16588 f t org-agenda-file-regexp)
16589 (list f)))
16590 files)))
16591 (when org-agenda-skip-unavailable-files
16592 (setq files (delq nil
16593 (mapcar (function
16594 (lambda (file)
16595 (and (file-readable-p file) file)))
16596 files))))
16597 (when (or (eq archives t)
16598 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16599 (setq files (org-add-archive-files files)))
16600 files))
16602 (defun org-agenda-file-p (&optional file)
16603 "Return non-nil, if FILE is an agenda file.
16604 If FILE is omitted, use the file associated with the current
16605 buffer."
16606 (member (or file (buffer-file-name))
16607 (org-agenda-files t)))
16609 (defun org-edit-agenda-file-list ()
16610 "Edit the list of agenda files.
16611 Depending on setup, this either uses customize to edit the variable
16612 `org-agenda-files', or it visits the file that is holding the list. In the
16613 latter case, the buffer is set up in a way that saving it automatically kills
16614 the buffer and restores the previous window configuration."
16615 (interactive)
16616 (if (stringp org-agenda-files)
16617 (let ((cw (current-window-configuration)))
16618 (find-file org-agenda-files)
16619 (org-set-local 'org-window-configuration cw)
16620 (org-add-hook 'after-save-hook
16621 (lambda ()
16622 (set-window-configuration
16623 (prog1 org-window-configuration
16624 (kill-buffer (current-buffer))))
16625 (org-install-agenda-files-menu)
16626 (message "New agenda file list installed"))
16627 nil 'local)
16628 (message "%s" (substitute-command-keys
16629 "Edit list and finish with \\[save-buffer]")))
16630 (customize-variable 'org-agenda-files)))
16632 (defun org-store-new-agenda-file-list (list)
16633 "Set new value for the agenda file list and save it correctly."
16634 (if (stringp org-agenda-files)
16635 (let ((fe (org-read-agenda-file-list t)) b u)
16636 (while (setq b (find-buffer-visiting org-agenda-files))
16637 (kill-buffer b))
16638 (with-temp-file org-agenda-files
16639 (insert
16640 (mapconcat
16641 (lambda (f) ;; Keep un-expanded entries.
16642 (if (setq u (assoc f fe))
16643 (cdr u)
16645 list "\n")
16646 "\n")))
16647 (let ((org-mode-hook nil) (org-inhibit-startup t)
16648 (org-insert-mode-line-in-empty-file nil))
16649 (setq org-agenda-files list)
16650 (customize-save-variable 'org-agenda-files org-agenda-files))))
16652 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16653 "Read the list of agenda files from a file.
16654 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16655 filenames, used by `org-store-new-agenda-file-list' to write back
16656 un-expanded file names."
16657 (when (file-directory-p org-agenda-files)
16658 (error "`org-agenda-files' cannot be a single directory"))
16659 (when (stringp org-agenda-files)
16660 (with-temp-buffer
16661 (insert-file-contents org-agenda-files)
16662 (mapcar
16663 (lambda (f)
16664 (let ((e (expand-file-name (substitute-in-file-name f)
16665 org-directory)))
16666 (if pair-with-expansion
16667 (cons e f)
16668 e)))
16669 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16671 ;;;###autoload
16672 (defun org-cycle-agenda-files ()
16673 "Cycle through the files in `org-agenda-files'.
16674 If the current buffer visits an agenda file, find the next one in the list.
16675 If the current buffer does not, find the first agenda file."
16676 (interactive)
16677 (let* ((fs (org-agenda-files t))
16678 (files (append fs (list (car fs))))
16679 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16680 file)
16681 (unless files (error "No agenda files"))
16682 (catch 'exit
16683 (while (setq file (pop files))
16684 (if (equal (file-truename file) tcf)
16685 (when (car files)
16686 (find-file (car files))
16687 (throw 'exit t))))
16688 (find-file (car fs)))
16689 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16691 (defun org-agenda-file-to-front (&optional to-end)
16692 "Move/add the current file to the top of the agenda file list.
16693 If the file is not present in the list, it is added to the front. If it is
16694 present, it is moved there. With optional argument TO-END, add/move to the
16695 end of the list."
16696 (interactive "P")
16697 (let ((org-agenda-skip-unavailable-files nil)
16698 (file-alist (mapcar (lambda (x)
16699 (cons (file-truename x) x))
16700 (org-agenda-files t)))
16701 (ctf (file-truename buffer-file-name))
16702 x had)
16703 (setq x (assoc ctf file-alist) had x)
16705 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16706 (if to-end
16707 (setq file-alist (append (delq x file-alist) (list x)))
16708 (setq file-alist (cons x (delq x file-alist))))
16709 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16710 (org-install-agenda-files-menu)
16711 (message "File %s to %s of agenda file list"
16712 (if had "moved" "added") (if to-end "end" "front"))))
16714 (defun org-remove-file (&optional file)
16715 "Remove current file from the list of files in variable `org-agenda-files'.
16716 These are the files which are being checked for agenda entries.
16717 Optional argument FILE means use this file instead of the current."
16718 (interactive)
16719 (let* ((org-agenda-skip-unavailable-files nil)
16720 (file (or file buffer-file-name))
16721 (true-file (file-truename file))
16722 (afile (abbreviate-file-name file))
16723 (files (delq nil (mapcar
16724 (lambda (x)
16725 (if (equal true-file
16726 (file-truename x))
16727 nil x))
16728 (org-agenda-files t)))))
16729 (if (not (= (length files) (length (org-agenda-files t))))
16730 (progn
16731 (org-store-new-agenda-file-list files)
16732 (org-install-agenda-files-menu)
16733 (message "Removed file: %s" afile))
16734 (message "File was not in list: %s (not removed)" afile))))
16736 (defun org-file-menu-entry (file)
16737 (vector file (list 'find-file file) t))
16739 (defun org-check-agenda-file (file)
16740 "Make sure FILE exists. If not, ask user what to do."
16741 (when (not (file-exists-p file))
16742 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16743 (abbreviate-file-name file))
16744 (let ((r (downcase (read-char-exclusive))))
16745 (cond
16746 ((equal r ?r)
16747 (org-remove-file file)
16748 (throw 'nextfile t))
16749 (t (error "Abort"))))))
16751 (defun org-get-agenda-file-buffer (file)
16752 "Get a buffer visiting FILE. If the buffer needs to be created, add
16753 it to the list of buffers which might be released later."
16754 (let ((buf (org-find-base-buffer-visiting file)))
16755 (if buf
16756 buf ; just return it
16757 ;; Make a new buffer and remember it
16758 (setq buf (find-file-noselect file))
16759 (if buf (push buf org-agenda-new-buffers))
16760 buf)))
16762 (defun org-release-buffers (blist)
16763 "Release all buffers in list, asking the user for confirmation when needed.
16764 When a buffer is unmodified, it is just killed. When modified, it is saved
16765 \(if the user agrees) and then killed."
16766 (let (buf file)
16767 (while (setq buf (pop blist))
16768 (setq file (buffer-file-name buf))
16769 (when (and (buffer-modified-p buf)
16770 file
16771 (y-or-n-p (format "Save file %s? " file)))
16772 (with-current-buffer buf (save-buffer)))
16773 (kill-buffer buf))))
16775 (defun org-prepare-agenda-buffers (files)
16776 "Create buffers for all agenda files, protect archived trees and comments."
16777 (interactive)
16778 (let ((pa '(:org-archived t))
16779 (pc '(:org-comment t))
16780 (pall '(:org-archived t :org-comment t))
16781 (inhibit-read-only t)
16782 (rea (concat ":" org-archive-tag ":"))
16783 bmp file re)
16784 (save-excursion
16785 (save-restriction
16786 (while (setq file (pop files))
16787 (catch 'nextfile
16788 (if (bufferp file)
16789 (set-buffer file)
16790 (org-check-agenda-file file)
16791 (set-buffer (org-get-agenda-file-buffer file)))
16792 (widen)
16793 (setq bmp (buffer-modified-p))
16794 (org-refresh-category-properties)
16795 (setq org-todo-keywords-for-agenda
16796 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16797 (setq org-done-keywords-for-agenda
16798 (append org-done-keywords-for-agenda org-done-keywords))
16799 (setq org-todo-keyword-alist-for-agenda
16800 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16801 (setq org-drawers-for-agenda
16802 (append org-drawers-for-agenda org-drawers))
16803 (setq org-tag-alist-for-agenda
16804 (append org-tag-alist-for-agenda org-tag-alist))
16806 (save-excursion
16807 (remove-text-properties (point-min) (point-max) pall)
16808 (when org-agenda-skip-archived-trees
16809 (goto-char (point-min))
16810 (while (re-search-forward rea nil t)
16811 (if (org-at-heading-p t)
16812 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16813 (goto-char (point-min))
16814 (setq re (format org-heading-keyword-regexp-format
16815 org-comment-string))
16816 (while (re-search-forward re nil t)
16817 (add-text-properties
16818 (match-beginning 0) (org-end-of-subtree t) pc)))
16819 (set-buffer-modified-p bmp)))))
16820 (setq org-todo-keywords-for-agenda
16821 (org-uniquify org-todo-keywords-for-agenda))
16822 (setq org-todo-keyword-alist-for-agenda
16823 (org-uniquify org-todo-keyword-alist-for-agenda)
16824 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16826 ;;;; Embedded LaTeX
16828 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16829 "Keymap for the minor `org-cdlatex-mode'.")
16831 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16832 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16833 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16834 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16835 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16837 (defvar org-cdlatex-texmathp-advice-is-done nil
16838 "Flag remembering if we have applied the advice to texmathp already.")
16840 (define-minor-mode org-cdlatex-mode
16841 "Toggle the minor `org-cdlatex-mode'.
16842 This mode supports entering LaTeX environment and math in LaTeX fragments
16843 in Org-mode.
16844 \\{org-cdlatex-mode-map}"
16845 nil " OCDL" nil
16846 (when org-cdlatex-mode
16847 (require 'cdlatex)
16848 (run-hooks 'cdlatex-mode-hook)
16849 (cdlatex-compute-tables))
16850 (unless org-cdlatex-texmathp-advice-is-done
16851 (setq org-cdlatex-texmathp-advice-is-done t)
16852 (defadvice texmathp (around org-math-always-on activate)
16853 "Always return t in org-mode buffers.
16854 This is because we want to insert math symbols without dollars even outside
16855 the LaTeX math segments. If Orgmode thinks that point is actually inside
16856 an embedded LaTeX fragment, let texmathp do its job.
16857 \\[org-cdlatex-mode-map]"
16858 (interactive)
16859 (let (p)
16860 (cond
16861 ((not (derived-mode-p 'org-mode)) ad-do-it)
16862 ((eq this-command 'cdlatex-math-symbol)
16863 (setq ad-return-value t
16864 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16866 (let ((p (org-inside-LaTeX-fragment-p)))
16867 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16868 (setq ad-return-value t
16869 texmathp-why '("Org-mode embedded math" . 0))
16870 (if p ad-do-it)))))))))
16872 (defun turn-on-org-cdlatex ()
16873 "Unconditionally turn on `org-cdlatex-mode'."
16874 (org-cdlatex-mode 1))
16876 (defun org-inside-LaTeX-fragment-p ()
16877 "Test if point is inside a LaTeX fragment.
16878 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16879 sequence appearing also before point.
16880 Even though the matchers for math are configurable, this function assumes
16881 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16882 delimiters are skipped when they have been removed by customization.
16883 The return value is nil, or a cons cell with the delimiter and the
16884 position of this delimiter.
16886 This function does a reasonably good job, but can locally be fooled by
16887 for example currency specifications. For example it will assume being in
16888 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16889 fragments that are properly closed, but during editing, we have to live
16890 with the uncertainty caused by missing closing delimiters. This function
16891 looks only before point, not after."
16892 (catch 'exit
16893 (let ((pos (point))
16894 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16895 (lim (progn
16896 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16897 (point)))
16898 dd-on str (start 0) m re)
16899 (goto-char pos)
16900 (when dodollar
16901 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16902 re (nth 1 (assoc "$" org-latex-regexps)))
16903 (while (string-match re str start)
16904 (cond
16905 ((= (match-end 0) (length str))
16906 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16907 ((= (match-end 0) (- (length str) 5))
16908 (throw 'exit nil))
16909 (t (setq start (match-end 0))))))
16910 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16911 (goto-char pos)
16912 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16913 (and (match-beginning 2) (throw 'exit nil))
16914 ;; count $$
16915 (while (re-search-backward "\\$\\$" lim t)
16916 (setq dd-on (not dd-on)))
16917 (goto-char pos)
16918 (if dd-on (cons "$$" m))))))
16920 (defun org-inside-latex-macro-p ()
16921 "Is point inside a LaTeX macro or its arguments?"
16922 (save-match-data
16923 (org-in-regexp
16924 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16926 (defun org-try-cdlatex-tab ()
16927 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16928 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16929 - inside a LaTeX fragment, or
16930 - after the first word in a line, where an abbreviation expansion could
16931 insert a LaTeX environment."
16932 (when org-cdlatex-mode
16933 (cond
16934 ;; Before any word on the line: No expansion possible.
16935 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16936 ;; Just after first word on the line: Expand it. Make sure it
16937 ;; cannot happen on headlines, though.
16938 ((save-excursion
16939 (skip-chars-backward "a-zA-Z0-9*")
16940 (skip-chars-backward " \t")
16941 (and (bolp) (not (org-at-heading-p))))
16942 (cdlatex-tab) t)
16943 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16945 (defun org-cdlatex-underscore-caret (&optional arg)
16946 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16947 Revert to the normal definition outside of these fragments."
16948 (interactive "P")
16949 (if (org-inside-LaTeX-fragment-p)
16950 (call-interactively 'cdlatex-sub-superscript)
16951 (let (org-cdlatex-mode)
16952 (call-interactively (key-binding (vector last-input-event))))))
16954 (defun org-cdlatex-math-modify (&optional arg)
16955 "Execute `cdlatex-math-modify' in LaTeX fragments.
16956 Revert to the normal definition outside of these fragments."
16957 (interactive "P")
16958 (if (org-inside-LaTeX-fragment-p)
16959 (call-interactively 'cdlatex-math-modify)
16960 (let (org-cdlatex-mode)
16961 (call-interactively (key-binding (vector last-input-event))))))
16963 (defvar org-latex-fragment-image-overlays nil
16964 "List of overlays carrying the images of latex fragments.")
16965 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16967 (defun org-remove-latex-fragment-image-overlays ()
16968 "Remove all overlays with LaTeX fragment images in current buffer."
16969 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16970 (setq org-latex-fragment-image-overlays nil))
16972 (defun org-preview-latex-fragment (&optional subtree)
16973 "Preview the LaTeX fragment at point, or all locally or globally.
16974 If the cursor is in a LaTeX fragment, create the image and overlay
16975 it over the source code. If there is no fragment at point, display
16976 all fragments in the current text, from one headline to the next. With
16977 prefix SUBTREE, display all fragments in the current subtree. With a
16978 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16979 the cursor is before the first headline,
16980 display all fragments in the buffer.
16981 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16982 (interactive "P")
16983 (unless buffer-file-name
16984 (error "Can't preview LaTeX fragment in a non-file buffer"))
16985 (org-remove-latex-fragment-image-overlays)
16986 (save-excursion
16987 (save-restriction
16988 (let (beg end at msg)
16989 (cond
16990 ((or (equal subtree '(16))
16991 (not (save-excursion
16992 (re-search-backward org-outline-regexp-bol nil t))))
16993 (setq beg (point-min) end (point-max)
16994 msg "Creating images for buffer...%s"))
16995 ((equal subtree '(4))
16996 (org-back-to-heading)
16997 (setq beg (point) end (org-end-of-subtree t)
16998 msg "Creating images for subtree...%s"))
17000 (if (setq at (org-inside-LaTeX-fragment-p))
17001 (goto-char (max (point-min) (- (cdr at) 2)))
17002 (org-back-to-heading))
17003 (setq beg (point) end (progn (outline-next-heading) (point))
17004 msg (if at "Creating image...%s"
17005 "Creating images for entry...%s"))))
17006 (message msg "")
17007 (narrow-to-region beg end)
17008 (goto-char beg)
17009 (org-format-latex
17010 (concat "ltxpng/" (file-name-sans-extension
17011 (file-name-nondirectory
17012 buffer-file-name)))
17013 default-directory 'overlays msg at 'forbuffer
17014 org-latex-create-formula-image-program)
17015 (message msg "done. Use `C-c C-c' to remove images.")))))
17017 (defvar org-latex-regexps
17018 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17019 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17020 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17021 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17022 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17023 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17024 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17025 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17026 "Regular expressions for matching embedded LaTeX.")
17028 (defvar org-export-have-math nil) ;; dynamic scoping
17029 (defun org-format-latex (prefix &optional dir overlays msg at
17030 forbuffer processing-type)
17031 "Replace LaTeX fragments with links to an image, and produce images.
17032 Some of the options can be changed using the variable
17033 `org-format-latex-options'."
17034 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17035 (let* ((prefixnodir (file-name-nondirectory prefix))
17036 (absprefix (expand-file-name prefix dir))
17037 (todir (file-name-directory absprefix))
17038 (opt org-format-latex-options)
17039 (matchers (plist-get opt :matchers))
17040 (re-list org-latex-regexps)
17041 (org-format-latex-header-extra
17042 (plist-get (org-infile-export-plist) :latex-header-extra))
17043 (cnt 0) txt hash link beg end re e checkdir
17044 executables-checked string
17045 m n block-type block linkfile movefile ov)
17046 ;; Check the different regular expressions
17047 (while (setq e (pop re-list))
17048 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17049 block (if block-type "\n\n" ""))
17050 (when (member m matchers)
17051 (goto-char (point-min))
17052 (while (re-search-forward re nil t)
17053 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17054 (not (get-text-property (match-beginning n)
17055 'org-protected))
17056 (or (not overlays)
17057 (not (eq (get-char-property (match-beginning n)
17058 'org-overlay-type)
17059 'org-latex-overlay))))
17060 (setq org-export-have-math t)
17061 (cond
17062 ((eq processing-type 'verbatim)
17063 ;; Leave the text verbatim, just protect it
17064 (add-text-properties (match-beginning n) (match-end n)
17065 '(org-protected t)))
17066 ((eq processing-type 'mathjax)
17067 ;; Prepare for MathJax processing
17068 (setq string (match-string n))
17069 (if (member m '("$" "$1"))
17070 (save-excursion
17071 (delete-region (match-beginning n) (match-end n))
17072 (goto-char (match-beginning n))
17073 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17074 "\\)")
17075 '(org-protected t))))
17076 (add-text-properties (match-beginning n) (match-end n)
17077 '(org-protected t))))
17078 ((or (eq processing-type 'dvipng)
17079 (eq processing-type 'imagemagick))
17080 ;; Process to an image
17081 (setq txt (match-string n)
17082 beg (match-beginning n) end (match-end n)
17083 cnt (1+ cnt))
17084 (let (print-length print-level) ; make sure full list is printed
17085 (setq hash (sha1 (prin1-to-string
17086 (list org-format-latex-header
17087 org-format-latex-header-extra
17088 org-export-latex-default-packages-alist
17089 org-export-latex-packages-alist
17090 org-format-latex-options
17091 forbuffer txt)))
17092 linkfile (format "%s_%s.png" prefix hash)
17093 movefile (format "%s_%s.png" absprefix hash)))
17094 (setq link (concat block "[[file:" linkfile "]]" block))
17095 (if msg (message msg cnt))
17096 (goto-char beg)
17097 (unless checkdir ; make sure the directory exists
17098 (setq checkdir t)
17099 (or (file-directory-p todir) (make-directory todir t)))
17100 (cond
17101 ((eq processing-type 'dvipng)
17102 (unless executables-checked
17103 (org-check-external-command
17104 "latex" "needed to convert LaTeX fragments to images")
17105 (org-check-external-command
17106 "dvipng" "needed to convert LaTeX fragments to images")
17107 (setq executables-checked t))
17108 (unless (file-exists-p movefile)
17109 (org-create-formula-image-with-dvipng
17110 txt movefile opt forbuffer)))
17111 ((eq processing-type 'imagemagick)
17112 (unless executables-checked
17113 (org-check-external-command
17114 "convert" "you need to install imagemagick")
17115 (setq executables-checked t))
17116 (unless (file-exists-p movefile)
17117 (org-create-formula-image-with-imagemagick
17118 txt movefile opt forbuffer))))
17119 (if overlays
17120 (progn
17121 (mapc (lambda (o)
17122 (if (eq (overlay-get o 'org-overlay-type)
17123 'org-latex-overlay)
17124 (delete-overlay o)))
17125 (overlays-in beg end))
17126 (setq ov (make-overlay beg end))
17127 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17128 (if (featurep 'xemacs)
17129 (progn
17130 (overlay-put ov 'invisible t)
17131 (overlay-put
17132 ov 'end-glyph
17133 (make-glyph (vector 'png :file movefile))))
17134 (overlay-put
17135 ov 'display
17136 (list 'image :type 'png :file movefile :ascent 'center)))
17137 (push ov org-latex-fragment-image-overlays)
17138 (goto-char end))
17139 (delete-region beg end)
17140 (insert (org-add-props link
17141 (list 'org-latex-src
17142 (replace-regexp-in-string
17143 "\"" "" txt)
17144 'org-latex-src-embed-type
17145 (if block-type 'paragraph 'character))))))
17146 ((eq processing-type 'mathml)
17147 ;; Process to MathML
17148 (unless executables-checked
17149 (unless (save-match-data (org-format-latex-mathml-available-p))
17150 (error "LaTeX to MathML converter not configured"))
17151 (setq executables-checked t))
17152 (setq txt (match-string n)
17153 beg (match-beginning n) end (match-end n)
17154 cnt (1+ cnt))
17155 (if msg (message msg cnt))
17156 (goto-char beg)
17157 (delete-region beg end)
17158 (insert (org-format-latex-as-mathml
17159 txt block-type prefix dir)))
17161 (error "Unknown conversion type %s for latex fragments"
17162 processing-type)))))))))
17164 (defun org-create-math-formula (latex-frag &optional mathml-file)
17165 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17166 Use `org-latex-to-mathml-convert-command'. If the conversion is
17167 sucessful, return the portion between \"<math...> </math>\"
17168 elements otherwise return nil. When MATHML-FILE is specified,
17169 write the results in to that file. When invoked as an
17170 interactive command, prompt for LATEX-FRAG, with initial value
17171 set to the current active region and echo the results for user
17172 inspection."
17173 (interactive (list (let ((frag (when (region-active-p)
17174 (buffer-substring-no-properties
17175 (region-beginning) (region-end)))))
17176 (read-string "LaTeX Fragment: " frag nil frag))))
17177 (unless latex-frag (error "Invalid latex-frag"))
17178 (let* ((tmp-in-file (file-relative-name
17179 (make-temp-name (expand-file-name "ltxmathml-in"))))
17180 (ignore (write-region latex-frag nil tmp-in-file))
17181 (tmp-out-file (file-relative-name
17182 (make-temp-name (expand-file-name "ltxmathml-out"))))
17183 (cmd (format-spec
17184 org-latex-to-mathml-convert-command
17185 `((?j . ,(shell-quote-argument
17186 (expand-file-name org-latex-to-mathml-jar-file)))
17187 (?I . ,(shell-quote-argument tmp-in-file))
17188 (?o . ,(shell-quote-argument tmp-out-file)))))
17189 mathml shell-command-output)
17190 (when (org-called-interactively-p 'any)
17191 (unless (org-format-latex-mathml-available-p)
17192 (error "LaTeX to MathML converter not configured")))
17193 (message "Running %s" cmd)
17194 (setq shell-command-output (shell-command-to-string cmd))
17195 (setq mathml
17196 (when (file-readable-p tmp-out-file)
17197 (with-current-buffer (find-file-noselect tmp-out-file t)
17198 (goto-char (point-min))
17199 (when (re-search-forward
17200 (concat
17201 (regexp-quote
17202 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17203 "\\(.\\|\n\\)*"
17204 (regexp-quote "</math>")) nil t)
17205 (prog1 (match-string 0) (kill-buffer))))))
17206 (cond
17207 (mathml
17208 (setq mathml
17209 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17210 (when mathml-file
17211 (write-region mathml nil mathml-file))
17212 (when (org-called-interactively-p 'any)
17213 (message mathml)))
17214 ((message "LaTeX to MathML conversion failed")
17215 (message shell-command-output)))
17216 (delete-file tmp-in-file)
17217 (when (file-exists-p tmp-out-file)
17218 (delete-file tmp-out-file))
17219 mathml))
17221 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17222 prefix &optional dir)
17223 "Use `org-create-math-formula' but check local cache first."
17224 (let* ((absprefix (expand-file-name prefix dir))
17225 (print-length nil) (print-level nil)
17226 (formula-id (concat
17227 "formula-"
17228 (sha1
17229 (prin1-to-string
17230 (list latex-frag
17231 org-latex-to-mathml-convert-command)))))
17232 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17233 (formula-cache-dir (file-name-directory formula-cache)))
17235 (unless (file-directory-p formula-cache-dir)
17236 (make-directory formula-cache-dir t))
17238 (unless (file-exists-p formula-cache)
17239 (org-create-math-formula latex-frag formula-cache))
17241 (if (file-exists-p formula-cache)
17242 ;; Successful conversion. Return the link to MathML file.
17243 (org-add-props
17244 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17245 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17246 'org-latex-src-embed-type (if latex-frag-type
17247 'paragraph 'character)))
17248 ;; Failed conversion. Return the LaTeX fragment verbatim
17249 (add-text-properties
17250 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17251 latex-frag)))
17253 ;; This function borrows from Ganesh Swami's latex2png.el
17254 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17255 "This calls dvipng."
17256 (require 'org-latex)
17257 (let* ((tmpdir (if (featurep 'xemacs)
17258 (temp-directory)
17259 temporary-file-directory))
17260 (texfilebase (make-temp-name
17261 (expand-file-name "orgtex" tmpdir)))
17262 (texfile (concat texfilebase ".tex"))
17263 (dvifile (concat texfilebase ".dvi"))
17264 (pngfile (concat texfilebase ".png"))
17265 (fnh (if (featurep 'xemacs)
17266 (font-height (face-font 'default))
17267 (face-attribute 'default :height nil)))
17268 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17269 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17270 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17271 "Black"))
17272 (bg (or (plist-get options (if buffer :background :html-background))
17273 "Transparent")))
17274 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17275 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17276 (with-temp-file texfile
17277 (insert (org-splice-latex-header
17278 org-format-latex-header
17279 org-export-latex-default-packages-alist
17280 org-export-latex-packages-alist t
17281 org-format-latex-header-extra))
17282 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17283 (require 'org-latex)
17284 (org-export-latex-fix-inputenc))
17285 (let ((dir default-directory))
17286 (condition-case nil
17287 (progn
17288 (cd tmpdir)
17289 (call-process "latex" nil nil nil texfile))
17290 (error nil))
17291 (cd dir))
17292 (if (not (file-exists-p dvifile))
17293 (progn (message "Failed to create dvi file from %s" texfile) nil)
17294 (condition-case nil
17295 (if (featurep 'xemacs)
17296 (call-process "dvipng" nil nil nil
17297 "-fg" fg "-bg" bg
17298 "-T" "tight"
17299 "-o" pngfile
17300 dvifile)
17301 (call-process "dvipng" nil nil nil
17302 "-fg" fg "-bg" bg
17303 "-D" dpi
17304 ;;"-x" scale "-y" scale
17305 "-T" "tight"
17306 "-o" pngfile
17307 dvifile))
17308 (error nil))
17309 (if (not (file-exists-p pngfile))
17310 (if org-format-latex-signal-error
17311 (error "Failed to create png file from %s" texfile)
17312 (message "Failed to create png file from %s" texfile)
17313 nil)
17314 ;; Use the requested file name and clean up
17315 (copy-file pngfile tofile 'replace)
17316 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17317 (if (file-exists-p (concat texfilebase e))
17318 (delete-file (concat texfilebase e))))
17319 pngfile))))
17321 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17322 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17323 "This calls convert, which is included into imagemagick."
17324 (require 'org-latex)
17325 (let* ((tmpdir (if (featurep 'xemacs)
17326 (temp-directory)
17327 temporary-file-directory))
17328 (texfilebase (make-temp-name
17329 (expand-file-name "orgtex" tmpdir)))
17330 (texfile (concat texfilebase ".tex"))
17331 (pdffile (concat texfilebase ".pdf"))
17332 (pngfile (concat texfilebase ".png"))
17333 (fnh (if (featurep 'xemacs)
17334 (font-height (face-font 'default))
17335 (face-attribute 'default :height nil)))
17336 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17337 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17338 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17339 "black"))
17340 (bg (or (plist-get options (if buffer :background :html-background))
17341 "white")))
17342 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17343 (setq fg (org-latex-color-format fg)))
17344 (if (eq bg 'default) (setq bg (org-latex-color :background))
17345 (setq bg (org-latex-color-format
17346 (if (string= bg "Transparent")(setq bg "white")))))
17347 (with-temp-file texfile
17348 (insert (org-splice-latex-header
17349 org-format-latex-header
17350 org-export-latex-default-packages-alist
17351 org-export-latex-packages-alist t
17352 org-format-latex-header-extra))
17353 (insert "\n\\begin{document}\n"
17354 "\\definecolor{fg}{rgb}{" fg "}\n"
17355 "\\definecolor{bg}{rgb}{" bg "}\n"
17356 "\n\\pagecolor{bg}\n"
17357 "\n{\\color{fg}\n"
17358 string
17359 "\n}\n"
17360 "\n\\end{document}\n" )
17361 (require 'org-latex)
17362 (org-export-latex-fix-inputenc))
17363 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17364 (condition-case nil
17365 (progn
17366 (cd tmpdir)
17367 (setq cmds org-latex-to-pdf-process)
17368 (while cmds
17369 (setq latex-frags-cmds (pop cmds))
17370 (if (listp latex-frags-cmds)
17371 (setq cmds nil)
17372 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17373 (while latex-frags-cmds
17374 (setq cmd (pop latex-frags-cmds))
17375 (while (string-match "%b" cmd)
17376 (setq cmd (replace-match
17377 (save-match-data
17378 (shell-quote-argument texfile))
17379 t t cmd)))
17380 (while (string-match "%f" cmd)
17381 (setq cmd (replace-match
17382 (save-match-data
17383 (shell-quote-argument (file-name-nondirectory texfile)))
17384 t t cmd)))
17385 (while (string-match "%o" cmd)
17386 (setq cmd (replace-match
17387 (save-match-data
17388 (shell-quote-argument (file-name-directory texfile)))
17389 t t cmd)))
17390 (setq cmd (split-string cmd))
17391 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17392 (error nil))
17393 (cd dir))
17394 (if (not (file-exists-p pdffile))
17395 (progn (message "Failed to create pdf file from %s" texfile) nil)
17396 (condition-case nil
17397 (if (featurep 'xemacs)
17398 (call-process "convert" nil nil nil
17399 "-density" "96"
17400 "-trim"
17401 "-antialias"
17402 pdffile
17403 "-quality" "100"
17404 ;; "-sharpen" "0x1.0"
17405 pngfile)
17406 (call-process "convert" nil nil nil
17407 "-density" dpi
17408 "-trim"
17409 "-antialias"
17410 pdffile
17411 "-quality" "100"
17412 ; "-sharpen" "0x1.0"
17413 pngfile))
17414 (error nil))
17415 (if (not (file-exists-p pngfile))
17416 (if org-format-latex-signal-error
17417 (error "Failed to create png file from %s" texfile)
17418 (message "Failed to create png file from %s" texfile)
17419 nil)
17420 ;; Use the requested file name and clean up
17421 (copy-file pngfile tofile 'replace)
17422 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17423 (if (file-exists-p (concat texfilebase e))
17424 (delete-file (concat texfilebase e))))
17425 pngfile))))
17427 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17428 "Fill a LaTeX header template TPL.
17429 In the template, the following place holders will be recognized:
17431 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17432 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17433 [PACKAGES] \\usepackage statements for PKG
17434 [NO-PACKAGES] do not include PKG
17435 [EXTRA] the string EXTRA
17436 [NO-EXTRA] do not include EXTRA
17438 For backward compatibility, if both the positive and the negative place
17439 holder is missing, the positive one (without the \"NO-\") will be
17440 assumed to be present at the end of the template.
17441 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17442 EXTRA is a string.
17443 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17444 (let (rpl (end ""))
17445 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17446 (setq rpl (if (or (match-end 1) (not def-pkg))
17447 "" (org-latex-packages-to-string def-pkg snippets-p t))
17448 tpl (replace-match rpl t t tpl))
17449 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17451 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17452 (setq rpl (if (or (match-end 1) (not pkg))
17453 "" (org-latex-packages-to-string pkg snippets-p t))
17454 tpl (replace-match rpl t t tpl))
17455 (if pkg (setq end
17456 (concat end "\n"
17457 (org-latex-packages-to-string pkg snippets-p)))))
17459 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17460 (setq rpl (if (or (match-end 1) (not extra))
17461 "" (concat extra "\n"))
17462 tpl (replace-match rpl t t tpl))
17463 (if (and extra (string-match "\\S-" extra))
17464 (setq end (concat end "\n" extra))))
17466 (if (string-match "\\S-" end)
17467 (concat tpl "\n" end)
17468 tpl)))
17470 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17471 "Turn an alist of packages into a string with the \\usepackage macros."
17472 (setq pkg (mapconcat (lambda(p)
17473 (cond
17474 ((stringp p) p)
17475 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17476 (format "%% Package %s omitted" (cadr p)))
17477 ((equal "" (car p))
17478 (format "\\usepackage{%s}" (cadr p)))
17480 (format "\\usepackage[%s]{%s}"
17481 (car p) (cadr p)))))
17483 "\n"))
17484 (if newline (concat pkg "\n") pkg))
17486 (defun org-dvipng-color (attr)
17487 "Return a RGB color specification for dvipng."
17488 (apply 'format "rgb %s %s %s"
17489 (mapcar 'org-normalize-color
17490 (if (featurep 'xemacs)
17491 (color-rgb-components
17492 (face-property 'default
17493 (cond ((eq attr :foreground) 'foreground)
17494 ((eq attr :background) 'background))))
17495 (color-values (face-attribute 'default attr nil))))))
17497 (defun org-latex-color (attr)
17498 "Return a RGB color for the LaTeX color package."
17499 (apply 'format "%s,%s,%s"
17500 (mapcar 'org-normalize-color
17501 (if (featurep 'xemacs)
17502 (color-rgb-components
17503 (face-property 'default
17504 (cond ((eq attr :foreground) 'foreground)
17505 ((eq attr :background) 'background))))
17506 (color-values (face-attribute 'default attr nil))))))
17508 (defun org-latex-color-format (color-name)
17509 "Convert COLOR-NAME to a RGB color value."
17510 (apply 'format "%s,%s,%s"
17511 (mapcar 'org-normalize-color
17512 (color-values color-name))))
17514 (defun org-normalize-color (value)
17515 "Return string to be used as color value for an RGB component."
17516 (format "%g" (/ value 65535.0)))
17518 ;; Image display
17521 (defvar org-inline-image-overlays nil)
17522 (make-variable-buffer-local 'org-inline-image-overlays)
17524 (defun org-toggle-inline-images (&optional include-linked)
17525 "Toggle the display of inline images.
17526 INCLUDE-LINKED is passed to `org-display-inline-images'."
17527 (interactive "P")
17528 (if org-inline-image-overlays
17529 (progn
17530 (org-remove-inline-images)
17531 (message "Inline image display turned off"))
17532 (org-display-inline-images include-linked)
17533 (if org-inline-image-overlays
17534 (message "%d images displayed inline"
17535 (length org-inline-image-overlays))
17536 (message "No images to display inline"))))
17538 (defun org-display-inline-images (&optional include-linked refresh beg end)
17539 "Display inline images.
17540 Normally only links without a description part are inlined, because this
17541 is how it will work for export. When INCLUDE-LINKED is set, also links
17542 with a description part will be inlined. This can be nice for a quick
17543 look at those images, but it does not reflect what exported files will look
17544 like.
17545 When REFRESH is set, refresh existing images between BEG and END.
17546 This will create new image displays only if necessary.
17547 BEG and END default to the buffer boundaries."
17548 (interactive "P")
17549 (unless refresh
17550 (org-remove-inline-images)
17551 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17552 (save-excursion
17553 (save-restriction
17554 (widen)
17555 (setq beg (or beg (point-min)) end (or end (point-max)))
17556 (goto-char beg)
17557 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17558 (substring (org-image-file-name-regexp) 0 -2)
17559 "\\)\\]" (if include-linked "" "\\]")))
17560 old file ov img)
17561 (while (re-search-forward re end t)
17562 (setq old (get-char-property-and-overlay (match-beginning 1)
17563 'org-image-overlay))
17564 (setq file (expand-file-name
17565 (concat (or (match-string 3) "") (match-string 4))))
17566 (when (file-exists-p file)
17567 (if (and (car-safe old) refresh)
17568 (image-refresh (overlay-get (cdr old) 'display))
17569 (setq img (save-match-data (create-image file)))
17570 (when img
17571 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17572 (overlay-put ov 'display img)
17573 (overlay-put ov 'face 'default)
17574 (overlay-put ov 'org-image-overlay t)
17575 (overlay-put ov 'modification-hooks
17576 (list 'org-display-inline-modification-hook))
17577 (push ov org-inline-image-overlays)))))))))
17579 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17580 "Remove inline-display overlay if a corresponding region is modified."
17581 (let ((inhibit-modification-hooks t))
17582 (when (and ov after)
17583 (delete ov org-inline-image-overlays)
17584 (delete-overlay ov))))
17586 (defun org-remove-inline-images ()
17587 "Remove inline display of images."
17588 (interactive)
17589 (mapc 'delete-overlay org-inline-image-overlays)
17590 (setq org-inline-image-overlays nil))
17592 ;;;; Key bindings
17594 ;; Outline functions from `outline-mode-prefix-map'
17595 ;; that can be remapped in Org:
17596 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17597 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17598 (define-key org-mode-map [remap outline-forward-same-level]
17599 'org-forward-same-level)
17600 (define-key org-mode-map [remap outline-backward-same-level]
17601 'org-backward-same-level)
17602 (define-key org-mode-map [remap show-branches]
17603 'org-kill-note-or-show-branches)
17604 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17605 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17606 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17608 ;; Outline functions from `outline-mode-prefix-map' that can not
17609 ;; be remapped in Org:
17611 ;; - the column "key binding" shows whether the Outline function is still
17612 ;; available in Org mode on the same key that it has been bound to in
17613 ;; Outline mode:
17614 ;; - "overridden": key used for a different functionality in Org mode
17615 ;; - else: key still bound to the same Outline function in Org mode
17617 ;; | Outline function | key binding | Org replacement |
17618 ;; |------------------------------------+-------------+-----------------------|
17619 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17620 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17621 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17622 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17623 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17624 ;; | `show-entry' | overridden | no replacement |
17625 ;; | `show-children' | `C-c C-i' | visibility cycling |
17626 ;; | `show-branches' | `C-c C-k' | still same function |
17627 ;; | `show-subtree' | overridden | visibility cycling |
17628 ;; | `show-all' | overridden | no replacement |
17629 ;; | `hide-subtree' | overridden | visibility cycling |
17630 ;; | `hide-body' | overridden | no replacement |
17631 ;; | `hide-entry' | overridden | visibility cycling |
17632 ;; | `hide-leaves' | overridden | no replacement |
17633 ;; | `hide-sublevels' | overridden | no replacement |
17634 ;; | `hide-other' | overridden | no replacement |
17636 ;; Make `C-c C-x' a prefix key
17637 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17639 ;; TAB key with modifiers
17640 (org-defkey org-mode-map "\C-i" 'org-cycle)
17641 (org-defkey org-mode-map [(tab)] 'org-cycle)
17642 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17643 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17644 ;; The following line is necessary under Suse GNU/Linux
17645 (unless (featurep 'xemacs)
17646 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17647 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17648 (define-key org-mode-map [backtab] 'org-shifttab)
17650 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17651 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17652 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17654 ;; Cursor keys with modifiers
17655 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17656 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17657 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17658 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17660 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17661 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17662 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17663 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17665 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17666 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17667 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17668 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17670 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17671 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17672 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17673 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17675 ;; Babel keys
17676 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17677 (mapc (lambda (pair)
17678 (define-key org-babel-map (car pair) (cdr pair)))
17679 org-babel-key-bindings)
17681 ;;; Extra keys for tty access.
17682 ;; We only set them when really needed because otherwise the
17683 ;; menus don't show the simple keys
17685 (when (or org-use-extra-keys
17686 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17687 (not window-system))
17688 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17689 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17690 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17691 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17692 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17693 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17694 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17695 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17696 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17697 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17698 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17699 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17700 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17701 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17702 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17703 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17704 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17705 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17706 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17707 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17708 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17709 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17710 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17711 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17712 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17713 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17714 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17715 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17717 ;; All the other keys
17719 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17720 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17721 (if (boundp 'narrow-map)
17722 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17723 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17724 (if (boundp 'narrow-map)
17725 (org-defkey narrow-map "b" 'org-narrow-to-block)
17726 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17727 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17728 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17729 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17730 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17731 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17732 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17733 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17734 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17735 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17736 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17737 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17738 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17739 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17740 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17741 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17742 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17743 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17744 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17745 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17746 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17747 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17748 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17749 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17750 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17751 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17752 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17753 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17754 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17755 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17756 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17757 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17758 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17759 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17760 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17761 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17762 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17763 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17764 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17765 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17766 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17767 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17768 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17769 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17770 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17771 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17772 (org-defkey org-mode-map "\C-c^" 'org-sort)
17773 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17774 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17775 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17776 (org-defkey org-mode-map "\C-m" 'org-return)
17777 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17778 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17779 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17780 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17781 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17782 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17783 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17784 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17785 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17786 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17787 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17788 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17789 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17790 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17791 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17792 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17793 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17794 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17795 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17796 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17797 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17798 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17799 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17801 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17802 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17803 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17804 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17806 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17807 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17808 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
17809 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17810 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17811 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
17812 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17813 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17814 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17815 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17816 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17817 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17818 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17819 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17820 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17821 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17822 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17823 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17824 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17826 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17827 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17828 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17829 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17830 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17832 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17834 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17836 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17837 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17839 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17842 (when (featurep 'xemacs)
17843 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17846 (defconst org-speed-commands-default
17848 ("Outline Navigation")
17849 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17850 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17851 ("f" . (org-speed-move-safe 'org-forward-same-level))
17852 ("b" . (org-speed-move-safe 'org-backward-same-level))
17853 ("u" . (org-speed-move-safe 'outline-up-heading))
17854 ("j" . org-goto)
17855 ("g" . (org-refile t))
17856 ("Outline Visibility")
17857 ("c" . org-cycle)
17858 ("C" . org-shifttab)
17859 (" " . org-display-outline-path)
17860 (":" . org-columns)
17861 ("Outline Structure Editing")
17862 ("U" . org-shiftmetaup)
17863 ("D" . org-shiftmetadown)
17864 ("r" . org-metaright)
17865 ("l" . org-metaleft)
17866 ("R" . org-shiftmetaright)
17867 ("L" . org-shiftmetaleft)
17868 ("i" . (progn (forward-char 1) (call-interactively
17869 'org-insert-heading-respect-content)))
17870 ("^" . org-sort)
17871 ("w" . org-refile)
17872 ("a" . org-archive-subtree-default-with-confirmation)
17873 ("." . org-mark-subtree)
17874 ("#" . org-toggle-comment)
17875 ("Clock Commands")
17876 ("I" . org-clock-in)
17877 ("O" . org-clock-out)
17878 ("Meta Data Editing")
17879 ("t" . org-todo)
17880 ("0" . (org-priority ?\ ))
17881 ("1" . (org-priority ?A))
17882 ("2" . (org-priority ?B))
17883 ("3" . (org-priority ?C))
17884 (";" . org-set-tags-command)
17885 ("e" . org-set-effort)
17886 ("Agenda Views etc")
17887 ("v" . org-agenda)
17888 ("/" . org-sparse-tree)
17889 ("Misc")
17890 ("o" . org-open-at-point)
17891 ("?" . org-speed-command-help)
17892 ("<" . (org-agenda-set-restriction-lock 'subtree))
17893 (">" . (org-agenda-remove-restriction-lock))
17895 "The default speed commands.")
17897 (defun org-print-speed-command (e)
17898 (if (> (length (car e)) 1)
17899 (progn
17900 (princ "\n")
17901 (princ (car e))
17902 (princ "\n")
17903 (princ (make-string (length (car e)) ?-))
17904 (princ "\n"))
17905 (princ (car e))
17906 (princ " ")
17907 (if (symbolp (cdr e))
17908 (princ (symbol-name (cdr e)))
17909 (prin1 (cdr e)))
17910 (princ "\n")))
17912 (defun org-speed-command-help ()
17913 "Show the available speed commands."
17914 (interactive)
17915 (if (not org-use-speed-commands)
17916 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17917 (with-output-to-temp-buffer "*Help*"
17918 (princ "User-defined Speed commands\n===========================\n")
17919 (mapc 'org-print-speed-command org-speed-commands-user)
17920 (princ "\n")
17921 (princ "Built-in Speed commands\n=======================\n")
17922 (mapc 'org-print-speed-command org-speed-commands-default))
17923 (with-current-buffer "*Help*"
17924 (setq truncate-lines t))))
17926 (defun org-speed-move-safe (cmd)
17927 "Execute CMD, but make sure that the cursor always ends up in a headline.
17928 If not, return to the original position and throw an error."
17929 (interactive)
17930 (let ((pos (point)))
17931 (call-interactively cmd)
17932 (unless (and (bolp) (org-at-heading-p))
17933 (goto-char pos)
17934 (error "Boundary reached while executing %s" cmd))))
17936 (defvar org-self-insert-command-undo-counter 0)
17938 (defvar org-table-auto-blank-field) ; defined in org-table.el
17939 (defvar org-speed-command nil)
17941 (defun org-speed-command-default-hook (keys)
17942 "Hook for activating single-letter speed commands.
17943 `org-speed-commands-default' specifies a minimal command set.
17944 Use `org-speed-commands-user' for further customization."
17945 (when (or (and (bolp) (looking-at org-outline-regexp))
17946 (and (functionp org-use-speed-commands)
17947 (funcall org-use-speed-commands)))
17948 (cdr (assoc keys (append org-speed-commands-user
17949 org-speed-commands-default)))))
17951 (defun org-babel-speed-command-hook (keys)
17952 "Hook for activating single-letter code block commands."
17953 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17954 (cdr (assoc keys org-babel-key-bindings))))
17956 (defcustom org-speed-command-hook
17957 '(org-speed-command-default-hook org-babel-speed-command-hook)
17958 "Hook for activating speed commands at strategic locations.
17959 Hook functions are called in sequence until a valid handler is
17960 found.
17962 Each hook takes a single argument, a user-pressed command key
17963 which is also a `self-insert-command' from the global map.
17965 Within the hook, examine the cursor position and the command key
17966 and return nil or a valid handler as appropriate. Handler could
17967 be one of an interactive command, a function, or a form.
17969 Set `org-use-speed-commands' to non-nil value to enable this
17970 hook. The default setting is `org-speed-command-default-hook'."
17971 :group 'org-structure
17972 :version "24.1"
17973 :type 'hook)
17975 (defun org-self-insert-command (N)
17976 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17977 If the cursor is in a table looking at whitespace, the whitespace is
17978 overwritten, and the table is not marked as requiring realignment."
17979 (interactive "p")
17980 (org-check-before-invisible-edit 'insert)
17981 (cond
17982 ((and org-use-speed-commands
17983 (setq org-speed-command
17984 (run-hook-with-args-until-success
17985 'org-speed-command-hook (this-command-keys))))
17986 (cond
17987 ((commandp org-speed-command)
17988 (setq this-command org-speed-command)
17989 (call-interactively org-speed-command))
17990 ((functionp org-speed-command)
17991 (funcall org-speed-command))
17992 ((and org-speed-command (listp org-speed-command))
17993 (eval org-speed-command))
17994 (t (let (org-use-speed-commands)
17995 (call-interactively 'org-self-insert-command)))))
17996 ((and
17997 (org-table-p)
17998 (progn
17999 ;; check if we blank the field, and if that triggers align
18000 (and (featurep 'org-table) org-table-auto-blank-field
18001 (member last-command
18002 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18003 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18004 ;; got extra space, this field does not determine column width
18005 (let (org-table-may-need-update) (org-table-blank-field))
18006 ;; no extra space, this field may determine column width
18007 (org-table-blank-field)))
18009 (eq N 1)
18010 (looking-at "[^|\n]* |"))
18011 (let (org-table-may-need-update)
18012 (goto-char (1- (match-end 0)))
18013 (backward-delete-char 1)
18014 (goto-char (match-beginning 0))
18015 (self-insert-command N)))
18017 (setq org-table-may-need-update t)
18018 (self-insert-command N)
18019 (org-fix-tags-on-the-fly)
18020 (if org-self-insert-cluster-for-undo
18021 (if (not (eq last-command 'org-self-insert-command))
18022 (setq org-self-insert-command-undo-counter 1)
18023 (if (>= org-self-insert-command-undo-counter 20)
18024 (setq org-self-insert-command-undo-counter 1)
18025 (and (> org-self-insert-command-undo-counter 0)
18026 buffer-undo-list (listp buffer-undo-list)
18027 (not (cadr buffer-undo-list)) ; remove nil entry
18028 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18029 (setq org-self-insert-command-undo-counter
18030 (1+ org-self-insert-command-undo-counter))))))))
18032 (defun org-check-before-invisible-edit (kind)
18033 "Check is editing if kind KIND would be dangerous with invisible text around.
18034 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18035 ;; First, try to get out of here as quickly as possible, to reduce overhead
18036 (if (and org-catch-invisible-edits
18037 (or (not (boundp 'visible-mode)) (not visible-mode))
18038 (or (get-char-property (point) 'invisible)
18039 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18040 ;; OK, we need to take a closer look
18041 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18042 (invisible-before-point (if (bobp) nil (get-char-property
18043 (1- (point)) 'invisible)))
18044 (border-and-ok-direction
18046 ;; Check if we are acting predictably before invisible text
18047 (and invisible-at-point (not invisible-before-point)
18048 (memq kind '(insert delete-backward)))
18049 ;; Check if we are acting predictably after invisible text
18050 ;; This works not well, and I have turned it off. It seems
18051 ;; better to always show and stop after invisible text.
18052 ;; (and (not invisible-at-point) invisible-before-point
18053 ;; (memq kind '(insert delete)))
18056 (when (or (memq invisible-at-point '(outline org-hide-block))
18057 (memq invisible-before-point '(outline org-hide-block)))
18058 (if (eq org-catch-invisible-edits 'error)
18059 (error "Editing in invisible areas is prohibited - make visible first"))
18060 ;; Make the area visible
18061 (save-excursion
18062 (if invisible-before-point
18063 (goto-char (previous-single-char-property-change
18064 (point) 'invisible)))
18065 (org-cycle))
18066 (cond
18067 ((eq org-catch-invisible-edits 'show)
18068 ;; That's it, we do the edit after showing
18069 (message
18070 "Unfolding invisible region around point before editing")
18071 (sit-for 1))
18072 ((and (eq org-catch-invisible-edits 'smart)
18073 border-and-ok-direction)
18074 (message "Unfolding invisible region around point before editing"))
18076 ;; Don't do the edit, make the user repeat it in full visibility
18077 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
18079 (defun org-fix-tags-on-the-fly ()
18080 (when (and (equal (char-after (point-at-bol)) ?*)
18081 (org-at-heading-p))
18082 (org-align-tags-here org-tags-column)))
18084 (defun org-delete-backward-char (N)
18085 "Like `delete-backward-char', insert whitespace at field end in tables.
18086 When deleting backwards, in tables this function will insert whitespace in
18087 front of the next \"|\" separator, to keep the table aligned. The table will
18088 still be marked for re-alignment if the field did fill the entire column,
18089 because, in this case the deletion might narrow the column."
18090 (interactive "p")
18091 (org-check-before-invisible-edit 'delete-backward)
18092 (if (and (org-table-p)
18093 (eq N 1)
18094 (string-match "|" (buffer-substring (point-at-bol) (point)))
18095 (looking-at ".*?|"))
18096 (let ((pos (point))
18097 (noalign (looking-at "[^|\n\r]* |"))
18098 (c org-table-may-need-update))
18099 (backward-delete-char N)
18100 (if (not overwrite-mode)
18101 (progn
18102 (skip-chars-forward "^|")
18103 (insert " ")
18104 (goto-char (1- pos))))
18105 ;; noalign: if there were two spaces at the end, this field
18106 ;; does not determine the width of the column.
18107 (if noalign (setq org-table-may-need-update c)))
18108 (backward-delete-char N)
18109 (org-fix-tags-on-the-fly)))
18111 (defun org-delete-char (N)
18112 "Like `delete-char', but insert whitespace at field end in tables.
18113 When deleting characters, in tables this function will insert whitespace in
18114 front of the next \"|\" separator, to keep the table aligned. The table will
18115 still be marked for re-alignment if the field did fill the entire column,
18116 because, in this case the deletion might narrow the column."
18117 (interactive "p")
18118 (org-check-before-invisible-edit 'delete)
18119 (if (and (org-table-p)
18120 (not (bolp))
18121 (not (= (char-after) ?|))
18122 (eq N 1))
18123 (if (looking-at ".*?|")
18124 (let ((pos (point))
18125 (noalign (looking-at "[^|\n\r]* |"))
18126 (c org-table-may-need-update))
18127 (replace-match (concat
18128 (substring (match-string 0) 1 -1)
18129 " |"))
18130 (goto-char pos)
18131 ;; noalign: if there were two spaces at the end, this field
18132 ;; does not determine the width of the column.
18133 (if noalign (setq org-table-may-need-update c)))
18134 (delete-char N))
18135 (delete-char N)
18136 (org-fix-tags-on-the-fly)))
18138 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18139 (put 'org-self-insert-command 'delete-selection t)
18140 (put 'orgtbl-self-insert-command 'delete-selection t)
18141 (put 'org-delete-char 'delete-selection 'supersede)
18142 (put 'org-delete-backward-char 'delete-selection 'supersede)
18143 (put 'org-yank 'delete-selection 'yank)
18145 ;; Make `flyspell-mode' delay after some commands
18146 (put 'org-self-insert-command 'flyspell-delayed t)
18147 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18148 (put 'org-delete-char 'flyspell-delayed t)
18149 (put 'org-delete-backward-char 'flyspell-delayed t)
18151 ;; Make pabbrev-mode expand after org-mode commands
18152 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18153 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18155 ;; How to do this: Measure non-white length of current string
18156 ;; If equal to column width, we should realign.
18158 (defun org-remap (map &rest commands)
18159 "In MAP, remap the functions given in COMMANDS.
18160 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18161 (let (new old)
18162 (while commands
18163 (setq old (pop commands) new (pop commands))
18164 (if (fboundp 'command-remapping)
18165 (org-defkey map (vector 'remap old) new)
18166 (substitute-key-definition old new map global-map)))))
18168 (when (eq org-enable-table-editor 'optimized)
18169 ;; If the user wants maximum table support, we need to hijack
18170 ;; some standard editing functions
18171 (org-remap org-mode-map
18172 'self-insert-command 'org-self-insert-command
18173 'delete-char 'org-delete-char
18174 'delete-backward-char 'org-delete-backward-char)
18175 (org-defkey org-mode-map "|" 'org-force-self-insert))
18177 (defvar org-ctrl-c-ctrl-c-hook nil
18178 "Hook for functions attaching themselves to `C-c C-c'.
18180 This can be used to add additional functionality to the C-c C-c
18181 key which executes context-dependent commands. This hook is run
18182 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18183 run after the last test.
18185 Each function will be called with no arguments. The function
18186 must check if the context is appropriate for it to act. If yes,
18187 it should do its thing and then return a non-nil value. If the
18188 context is wrong, just do nothing and return nil.")
18190 (defvar org-ctrl-c-ctrl-c-final-hook nil
18191 "Hook for functions attaching themselves to `C-c C-c'.
18193 This can be used to add additional functionality to the C-c C-c
18194 key which executes context-dependent commands. This hook is run
18195 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18196 before the first test.
18198 Each function will be called with no arguments. The function
18199 must check if the context is appropriate for it to act. If yes,
18200 it should do its thing and then return a non-nil value. If the
18201 context is wrong, just do nothing and return nil.")
18203 (defvar org-tab-first-hook nil
18204 "Hook for functions to attach themselves to TAB.
18205 See `org-ctrl-c-ctrl-c-hook' for more information.
18206 This hook runs as the first action when TAB is pressed, even before
18207 `org-cycle' messes around with the `outline-regexp' to cater for
18208 inline tasks and plain list item folding.
18209 If any function in this hook returns t, any other actions that
18210 would have been caused by TAB (such as table field motion or visibility
18211 cycling) will not occur.")
18213 (defvar org-tab-after-check-for-table-hook nil
18214 "Hook for functions to attach themselves to TAB.
18215 See `org-ctrl-c-ctrl-c-hook' for more information.
18216 This hook runs after it has been established that the cursor is not in a
18217 table, but before checking if the cursor is in a headline or if global cycling
18218 should be done.
18219 If any function in this hook returns t, not other actions like visibility
18220 cycling will be done.")
18222 (defvar org-tab-after-check-for-cycling-hook nil
18223 "Hook for functions to attach themselves to TAB.
18224 See `org-ctrl-c-ctrl-c-hook' for more information.
18225 This hook runs after it has been established that not table field motion and
18226 not visibility should be done because of current context. This is probably
18227 the place where a package like yasnippets can hook in.")
18229 (defvar org-tab-before-tab-emulation-hook nil
18230 "Hook for functions to attach themselves to TAB.
18231 See `org-ctrl-c-ctrl-c-hook' for more information.
18232 This hook runs after every other options for TAB have been exhausted, but
18233 before indentation and \t insertion takes place.")
18235 (defvar org-metaleft-hook nil
18236 "Hook for functions attaching themselves to `M-left'.
18237 See `org-ctrl-c-ctrl-c-hook' for more information.")
18238 (defvar org-metaright-hook nil
18239 "Hook for functions attaching themselves to `M-right'.
18240 See `org-ctrl-c-ctrl-c-hook' for more information.")
18241 (defvar org-metaup-hook nil
18242 "Hook for functions attaching themselves to `M-up'.
18243 See `org-ctrl-c-ctrl-c-hook' for more information.")
18244 (defvar org-metadown-hook nil
18245 "Hook for functions attaching themselves to `M-down'.
18246 See `org-ctrl-c-ctrl-c-hook' for more information.")
18247 (defvar org-shiftmetaleft-hook nil
18248 "Hook for functions attaching themselves to `M-S-left'.
18249 See `org-ctrl-c-ctrl-c-hook' for more information.")
18250 (defvar org-shiftmetaright-hook nil
18251 "Hook for functions attaching themselves to `M-S-right'.
18252 See `org-ctrl-c-ctrl-c-hook' for more information.")
18253 (defvar org-shiftmetaup-hook nil
18254 "Hook for functions attaching themselves to `M-S-up'.
18255 See `org-ctrl-c-ctrl-c-hook' for more information.")
18256 (defvar org-shiftmetadown-hook nil
18257 "Hook for functions attaching themselves to `M-S-down'.
18258 See `org-ctrl-c-ctrl-c-hook' for more information.")
18259 (defvar org-metareturn-hook nil
18260 "Hook for functions attaching themselves to `M-RET'.
18261 See `org-ctrl-c-ctrl-c-hook' for more information.")
18262 (defvar org-shiftup-hook nil
18263 "Hook for functions attaching themselves to `S-up'.
18264 See `org-ctrl-c-ctrl-c-hook' for more information.")
18265 (defvar org-shiftup-final-hook nil
18266 "Hook for functions attaching themselves to `S-up'.
18267 This one runs after all other options except shift-select have been excluded.
18268 See `org-ctrl-c-ctrl-c-hook' for more information.")
18269 (defvar org-shiftdown-hook nil
18270 "Hook for functions attaching themselves to `S-down'.
18271 See `org-ctrl-c-ctrl-c-hook' for more information.")
18272 (defvar org-shiftdown-final-hook nil
18273 "Hook for functions attaching themselves to `S-down'.
18274 This one runs after all other options except shift-select have been excluded.
18275 See `org-ctrl-c-ctrl-c-hook' for more information.")
18276 (defvar org-shiftleft-hook nil
18277 "Hook for functions attaching themselves to `S-left'.
18278 See `org-ctrl-c-ctrl-c-hook' for more information.")
18279 (defvar org-shiftleft-final-hook nil
18280 "Hook for functions attaching themselves to `S-left'.
18281 This one runs after all other options except shift-select have been excluded.
18282 See `org-ctrl-c-ctrl-c-hook' for more information.")
18283 (defvar org-shiftright-hook nil
18284 "Hook for functions attaching themselves to `S-right'.
18285 See `org-ctrl-c-ctrl-c-hook' for more information.")
18286 (defvar org-shiftright-final-hook nil
18287 "Hook for functions attaching themselves to `S-right'.
18288 This one runs after all other options except shift-select have been excluded.
18289 See `org-ctrl-c-ctrl-c-hook' for more information.")
18291 (defun org-modifier-cursor-error ()
18292 "Throw an error, a modified cursor command was applied in wrong context."
18293 (error "This command is active in special context like tables, headlines or items"))
18295 (defun org-shiftselect-error ()
18296 "Throw an error because Shift-Cursor command was applied in wrong context."
18297 (if (and (boundp 'shift-select-mode) shift-select-mode)
18298 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18299 (error "This command works only in special context like headlines or timestamps")))
18301 (defun org-call-for-shift-select (cmd)
18302 (let ((this-command-keys-shift-translated t))
18303 (call-interactively cmd)))
18305 (defun org-shifttab (&optional arg)
18306 "Global visibility cycling or move to previous table field.
18307 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18308 on context.
18309 See the individual commands for more information."
18310 (interactive "P")
18311 (cond
18312 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18313 ((integerp arg)
18314 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18315 (message "Content view to level: %d" arg)
18316 (org-content (prefix-numeric-value arg2))
18317 (setq org-cycle-global-status 'overview)))
18318 (t (call-interactively 'org-global-cycle))))
18320 (defun org-shiftmetaleft ()
18321 "Promote subtree or delete table column.
18322 Calls `org-promote-subtree', `org-outdent-item-tree', or
18323 `org-table-delete-column', depending on context. See the
18324 individual commands for more information."
18325 (interactive)
18326 (cond
18327 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18328 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18329 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18330 ((if (not (org-region-active-p)) (org-at-item-p)
18331 (save-excursion (goto-char (region-beginning))
18332 (org-at-item-p)))
18333 (call-interactively 'org-outdent-item-tree))
18334 (t (org-modifier-cursor-error))))
18336 (defun org-shiftmetaright ()
18337 "Demote subtree or insert table column.
18338 Calls `org-demote-subtree', `org-indent-item-tree', or
18339 `org-table-insert-column', depending on context. See the
18340 individual commands for more information."
18341 (interactive)
18342 (cond
18343 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18344 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18345 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18346 ((if (not (org-region-active-p)) (org-at-item-p)
18347 (save-excursion (goto-char (region-beginning))
18348 (org-at-item-p)))
18349 (call-interactively 'org-indent-item-tree))
18350 (t (org-modifier-cursor-error))))
18352 (defun org-shiftmetaup (&optional arg)
18353 "Move subtree up or kill table row.
18354 Calls `org-move-subtree-up' or `org-table-kill-row' or
18355 `org-move-item-up' depending on context. See the individual commands
18356 for more information."
18357 (interactive "P")
18358 (cond
18359 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18360 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18361 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18362 ((org-at-item-p) (call-interactively 'org-move-item-up))
18363 (t (org-modifier-cursor-error))))
18365 (defun org-shiftmetadown (&optional arg)
18366 "Move subtree down or insert table row.
18367 Calls `org-move-subtree-down' or `org-table-insert-row' or
18368 `org-move-item-down', depending on context. See the individual
18369 commands for more information."
18370 (interactive "P")
18371 (cond
18372 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18373 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18374 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18375 ((org-at-item-p) (call-interactively 'org-move-item-down))
18376 (t (org-modifier-cursor-error))))
18378 (defsubst org-hidden-tree-error ()
18379 (error
18380 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18382 (defun org-metaleft (&optional arg)
18383 "Promote heading or move table column to left.
18384 Calls `org-do-promote' or `org-table-move-column', depending on context.
18385 With no specific context, calls the Emacs default `backward-word'.
18386 See the individual commands for more information."
18387 (interactive "P")
18388 (cond
18389 ((run-hook-with-args-until-success 'org-metaleft-hook))
18390 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18391 ((org-with-limited-levels
18392 (or (org-at-heading-p)
18393 (and (org-region-active-p)
18394 (save-excursion
18395 (goto-char (region-beginning))
18396 (org-at-heading-p)))))
18397 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18398 (call-interactively 'org-do-promote))
18399 ;; At an inline task.
18400 ((org-at-heading-p)
18401 (call-interactively 'org-inlinetask-promote))
18402 ((or (org-at-item-p)
18403 (and (org-region-active-p)
18404 (save-excursion
18405 (goto-char (region-beginning))
18406 (org-at-item-p))))
18407 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18408 (call-interactively 'org-outdent-item))
18409 (t (call-interactively 'backward-word))))
18411 (defun org-metaright (&optional arg)
18412 "Demote a subtree, a list item or move table column to right.
18413 In front of a drawer or a block keyword, indent it correctly.
18414 With no specific context, calls the Emacs default `forward-word'.
18415 See the individual commands for more information."
18416 (interactive "P")
18417 (cond
18418 ((run-hook-with-args-until-success 'org-metaright-hook))
18419 ((org-at-table-p) (call-interactively 'org-table-move-column))
18420 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18421 ((org-at-block-p) (call-interactively 'org-indent-block))
18422 ((org-with-limited-levels
18423 (or (org-at-heading-p)
18424 (and (org-region-active-p)
18425 (save-excursion
18426 (goto-char (region-beginning))
18427 (org-at-heading-p)))))
18428 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18429 (call-interactively 'org-do-demote))
18430 ;; At an inline task.
18431 ((org-at-heading-p)
18432 (call-interactively 'org-inlinetask-demote))
18433 ((or (org-at-item-p)
18434 (and (org-region-active-p)
18435 (save-excursion
18436 (goto-char (region-beginning))
18437 (org-at-item-p))))
18438 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18439 (call-interactively 'org-indent-item))
18440 (t (call-interactively 'forward-word))))
18442 (defun org-check-for-hidden (what)
18443 "Check if there are hidden headlines/items in the current visual line.
18444 WHAT can be either `headlines' or `items'. If the current line is
18445 an outline or item heading and it has a folded subtree below it,
18446 this function returns t, nil otherwise."
18447 (let ((re (cond
18448 ((eq what 'headlines) org-outline-regexp-bol)
18449 ((eq what 'items) (org-item-beginning-re))
18450 (t (error "This should not happen"))))
18451 beg end)
18452 (save-excursion
18453 (catch 'exit
18454 (unless (org-region-active-p)
18455 (setq beg (point-at-bol))
18456 (beginning-of-line 2)
18457 (while (and (not (eobp)) ;; this is like `next-line'
18458 (get-char-property (1- (point)) 'invisible))
18459 (beginning-of-line 2))
18460 (setq end (point))
18461 (goto-char beg)
18462 (goto-char (point-at-eol))
18463 (setq end (max end (point)))
18464 (while (re-search-forward re end t)
18465 (if (get-char-property (match-beginning 0) 'invisible)
18466 (throw 'exit t))))
18467 nil))))
18469 (defun org-metaup (&optional arg)
18470 "Move subtree up or move table row up.
18471 Calls `org-move-subtree-up' or `org-table-move-row' or
18472 `org-move-item-up', depending on context. See the individual commands
18473 for more information."
18474 (interactive "P")
18475 (cond
18476 ((run-hook-with-args-until-success 'org-metaup-hook))
18477 ((org-region-active-p)
18478 (let* ((a (min (region-beginning) (region-end)))
18479 (b (1- (max (region-beginning) (region-end))))
18480 (c (save-excursion (goto-char a)
18481 (move-beginning-of-line 0)))
18482 (d (save-excursion (goto-char a)
18483 (move-end-of-line 0) (point))))
18484 (transpose-regions a b c d)
18485 (goto-char c)))
18486 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18487 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18488 ((org-at-item-p) (call-interactively 'org-move-item-up))
18489 (t (transpose-lines 1) (beginning-of-line -1))))
18491 (defun org-metadown (&optional arg)
18492 "Move subtree down or move table row down.
18493 Calls `org-move-subtree-down' or `org-table-move-row' or
18494 `org-move-item-down', depending on context. See the individual
18495 commands for more information."
18496 (interactive "P")
18497 (cond
18498 ((run-hook-with-args-until-success 'org-metadown-hook))
18499 ((org-region-active-p)
18500 (let* ((a (min (region-beginning) (region-end)))
18501 (b (max (region-beginning) (region-end)))
18502 (c (save-excursion (goto-char b)
18503 (move-beginning-of-line 1)))
18504 (d (save-excursion (goto-char b)
18505 (move-end-of-line 1) (1+ (point)))))
18506 (transpose-regions a b c d)
18507 (goto-char d)))
18508 ((org-at-table-p) (call-interactively 'org-table-move-row))
18509 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18510 ((org-at-item-p) (call-interactively 'org-move-item-down))
18511 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18513 (defun org-shiftup (&optional arg)
18514 "Increase item in timestamp or increase priority of current headline.
18515 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18516 depending on context. See the individual commands for more information."
18517 (interactive "P")
18518 (cond
18519 ((run-hook-with-args-until-success 'org-shiftup-hook))
18520 ((and org-support-shift-select (org-region-active-p))
18521 (org-call-for-shift-select 'previous-line))
18522 ((org-at-timestamp-p t)
18523 (call-interactively (if org-edit-timestamp-down-means-later
18524 'org-timestamp-down 'org-timestamp-up)))
18525 ((and (not (eq org-support-shift-select 'always))
18526 org-enable-priority-commands
18527 (org-at-heading-p))
18528 (call-interactively 'org-priority-up))
18529 ((and (not org-support-shift-select) (org-at-item-p))
18530 (call-interactively 'org-previous-item))
18531 ((org-clocktable-try-shift 'up arg))
18532 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18533 (org-support-shift-select
18534 (org-call-for-shift-select 'previous-line))
18535 (t (org-shiftselect-error))))
18537 (defun org-shiftdown (&optional arg)
18538 "Decrease item in timestamp or decrease priority of current headline.
18539 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18540 depending on context. See the individual commands for more information."
18541 (interactive "P")
18542 (cond
18543 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18544 ((and org-support-shift-select (org-region-active-p))
18545 (org-call-for-shift-select 'next-line))
18546 ((org-at-timestamp-p t)
18547 (call-interactively (if org-edit-timestamp-down-means-later
18548 'org-timestamp-up 'org-timestamp-down)))
18549 ((and (not (eq org-support-shift-select 'always))
18550 org-enable-priority-commands
18551 (org-at-heading-p))
18552 (call-interactively 'org-priority-down))
18553 ((and (not org-support-shift-select) (org-at-item-p))
18554 (call-interactively 'org-next-item))
18555 ((org-clocktable-try-shift 'down arg))
18556 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18557 (org-support-shift-select
18558 (org-call-for-shift-select 'next-line))
18559 (t (org-shiftselect-error))))
18561 (defun org-shiftright (&optional arg)
18562 "Cycle the thing at point or in the current line, depending on context.
18563 Depending on context, this does one of the following:
18565 - switch a timestamp at point one day into the future
18566 - on a headline, switch to the next TODO keyword.
18567 - on an item, switch entire list to the next bullet type
18568 - on a property line, switch to the next allowed value
18569 - on a clocktable definition line, move time block into the future"
18570 (interactive "P")
18571 (cond
18572 ((run-hook-with-args-until-success 'org-shiftright-hook))
18573 ((and org-support-shift-select (org-region-active-p))
18574 (org-call-for-shift-select 'forward-char))
18575 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18576 ((and (not (eq org-support-shift-select 'always))
18577 (org-at-heading-p))
18578 (let ((org-inhibit-logging
18579 (not org-treat-S-cursor-todo-selection-as-state-change))
18580 (org-inhibit-blocking
18581 (not org-treat-S-cursor-todo-selection-as-state-change)))
18582 (org-call-with-arg 'org-todo 'right)))
18583 ((or (and org-support-shift-select
18584 (not (eq org-support-shift-select 'always))
18585 (org-at-item-bullet-p))
18586 (and (not org-support-shift-select) (org-at-item-p)))
18587 (org-call-with-arg 'org-cycle-list-bullet nil))
18588 ((and (not (eq org-support-shift-select 'always))
18589 (org-at-property-p))
18590 (call-interactively 'org-property-next-allowed-value))
18591 ((org-clocktable-try-shift 'right arg))
18592 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18593 (org-support-shift-select
18594 (org-call-for-shift-select 'forward-char))
18595 (t (org-shiftselect-error))))
18597 (defun org-shiftleft (&optional arg)
18598 "Cycle the thing at point or in the current line, depending on context.
18599 Depending on context, this does one of the following:
18601 - switch a timestamp at point one day into the past
18602 - on a headline, switch to the previous TODO keyword.
18603 - on an item, switch entire list to the previous bullet type
18604 - on a property line, switch to the previous allowed value
18605 - on a clocktable definition line, move time block into the past"
18606 (interactive "P")
18607 (cond
18608 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18609 ((and org-support-shift-select (org-region-active-p))
18610 (org-call-for-shift-select 'backward-char))
18611 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18612 ((and (not (eq org-support-shift-select 'always))
18613 (org-at-heading-p))
18614 (let ((org-inhibit-logging
18615 (not org-treat-S-cursor-todo-selection-as-state-change))
18616 (org-inhibit-blocking
18617 (not org-treat-S-cursor-todo-selection-as-state-change)))
18618 (org-call-with-arg 'org-todo 'left)))
18619 ((or (and org-support-shift-select
18620 (not (eq org-support-shift-select 'always))
18621 (org-at-item-bullet-p))
18622 (and (not org-support-shift-select) (org-at-item-p)))
18623 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18624 ((and (not (eq org-support-shift-select 'always))
18625 (org-at-property-p))
18626 (call-interactively 'org-property-previous-allowed-value))
18627 ((org-clocktable-try-shift 'left arg))
18628 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18629 (org-support-shift-select
18630 (org-call-for-shift-select 'backward-char))
18631 (t (org-shiftselect-error))))
18633 (defun org-shiftcontrolright ()
18634 "Switch to next TODO set."
18635 (interactive)
18636 (cond
18637 ((and org-support-shift-select (org-region-active-p))
18638 (org-call-for-shift-select 'forward-word))
18639 ((and (not (eq org-support-shift-select 'always))
18640 (org-at-heading-p))
18641 (org-call-with-arg 'org-todo 'nextset))
18642 (org-support-shift-select
18643 (org-call-for-shift-select 'forward-word))
18644 (t (org-shiftselect-error))))
18646 (defun org-shiftcontrolleft ()
18647 "Switch to previous TODO set."
18648 (interactive)
18649 (cond
18650 ((and org-support-shift-select (org-region-active-p))
18651 (org-call-for-shift-select 'backward-word))
18652 ((and (not (eq org-support-shift-select 'always))
18653 (org-at-heading-p))
18654 (org-call-with-arg 'org-todo 'previousset))
18655 (org-support-shift-select
18656 (org-call-for-shift-select 'backward-word))
18657 (t (org-shiftselect-error))))
18659 (defun org-shiftcontrolup ()
18660 "Change timestamps synchronously up in CLOCK log lines."
18661 (interactive)
18662 (cond ((and (not org-support-shift-select)
18663 (org-at-clock-log-p)
18664 (org-at-timestamp-p t))
18665 (org-clock-timestamps-up))
18666 (t (org-shiftselect-error))))
18668 (defun org-shiftcontroldown ()
18669 "Change timestamps synchronously down in CLOCK log lines."
18670 (interactive)
18671 (cond ((and (not org-support-shift-select)
18672 (org-at-clock-log-p)
18673 (org-at-timestamp-p t))
18674 (org-clock-timestamps-down))
18675 (t (org-shiftselect-error))))
18677 (defun org-ctrl-c-ret ()
18678 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18679 (interactive)
18680 (cond
18681 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18682 (t (call-interactively 'org-insert-heading))))
18684 (defun org-find-visible ()
18685 (let ((s (point)))
18686 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18687 (get-char-property s 'invisible)))
18689 (defun org-find-invisible ()
18690 (let ((s (point)))
18691 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18692 (not (get-char-property s 'invisible))))
18695 (defun org-copy-visible (beg end)
18696 "Copy the visible parts of the region."
18697 (interactive "r")
18698 (let (snippets s)
18699 (save-excursion
18700 (save-restriction
18701 (narrow-to-region beg end)
18702 (setq s (goto-char (point-min)))
18703 (while (not (= (point) (point-max)))
18704 (goto-char (org-find-invisible))
18705 (push (buffer-substring s (point)) snippets)
18706 (setq s (goto-char (org-find-visible))))))
18707 (kill-new (apply 'concat (nreverse snippets)))))
18709 (defun org-copy-special ()
18710 "Copy region in table or copy current subtree.
18711 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18712 See the individual commands for more information."
18713 (interactive)
18714 (call-interactively
18715 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18717 (defun org-cut-special ()
18718 "Cut region in table or cut current subtree.
18719 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18720 See the individual commands for more information."
18721 (interactive)
18722 (call-interactively
18723 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18725 (defun org-paste-special (arg)
18726 "Paste rectangular region into table, or past subtree relative to level.
18727 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18728 See the individual commands for more information."
18729 (interactive "P")
18730 (if (org-at-table-p)
18731 (org-table-paste-rectangle)
18732 (org-paste-subtree arg)))
18734 (defun org-edit-special (&optional arg)
18735 "Call a special editor for the stuff at point.
18736 When at a table, call the formula editor with `org-table-edit-formulas'.
18737 When at the first line of an src example, call `org-edit-src-code'.
18738 When in an #+include line, visit the include file. Otherwise call
18739 `ffap' to visit the file at point."
18740 (interactive)
18741 ;; possibly prep session before editing source
18742 (when arg
18743 (let* ((info (org-babel-get-src-block-info))
18744 (lang (nth 0 info))
18745 (params (nth 2 info))
18746 (session (cdr (assoc :session params))))
18747 (when (and info session) ;; we are in a source-code block with a session
18748 (funcall
18749 (intern (concat "org-babel-prep-session:" lang)) session params))))
18750 (cond ;; proceed with `org-edit-special'
18751 ((save-excursion
18752 (beginning-of-line 1)
18753 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18754 (find-file (org-trim (match-string 1))))
18755 ((org-edit-src-code))
18756 ((org-edit-fixed-width-region))
18757 ((org-at-table.el-p)
18758 (org-edit-src-code))
18759 ((or (org-at-table-p)
18760 (save-excursion
18761 (beginning-of-line 1)
18762 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18763 (call-interactively 'org-table-edit-formulas))
18764 (t (call-interactively 'ffap))))
18766 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18767 (defun org-ctrl-c-ctrl-c (&optional arg)
18768 "Set tags in headline, or update according to changed information at point.
18770 This command does many different things, depending on context:
18772 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18773 this is what we do.
18775 - If the cursor is on a statistics cookie, update it.
18777 - If the cursor is in a headline, prompt for tags and insert them
18778 into the current line, aligned to `org-tags-column'. When called
18779 with prefix arg, realign all tags in the current buffer.
18781 - If the cursor is in one of the special #+KEYWORD lines, this
18782 triggers scanning the buffer for these lines and updating the
18783 information.
18785 - If the cursor is inside a table, realign the table. This command
18786 works even if the automatic table editor has been turned off.
18788 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18789 the entire table.
18791 - If the cursor is at a footnote reference or definition, jump to
18792 the corresponding definition or references, respectively.
18794 - If the cursor is a the beginning of a dynamic block, update it.
18796 - If the current buffer is a capture buffer, close note and file it.
18798 - If the cursor is on a <<<target>>>, update radio targets and
18799 corresponding links in this buffer.
18801 - If the cursor is on a numbered item in a plain list, renumber the
18802 ordered list.
18804 - If the cursor is on a checkbox, toggle it.
18806 - If the cursor is on a code block, evaluate it. The variable
18807 `org-confirm-babel-evaluate' can be used to control prompting
18808 before code block evaluation, by default every code block
18809 evaluation requires confirmation. Code block evaluation can be
18810 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18811 (interactive "P")
18812 (let ((org-enable-table-editor t))
18813 (cond
18814 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18815 org-occur-highlights
18816 org-latex-fragment-image-overlays)
18817 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18818 (org-remove-occur-highlights)
18819 (org-remove-latex-fragment-image-overlays)
18820 (message "Temporary highlights/overlays removed from current buffer"))
18821 ((and (local-variable-p 'org-finish-function (current-buffer))
18822 (fboundp org-finish-function))
18823 (funcall org-finish-function))
18824 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18825 ((org-in-regexp org-ts-regexp-both)
18826 (org-timestamp-change 0 'day))
18827 ((or (looking-at org-property-start-re)
18828 (org-at-property-p))
18829 (call-interactively 'org-property-action))
18830 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18831 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18832 (or (org-at-heading-p) (org-at-item-p)))
18833 (call-interactively 'org-update-statistics-cookies))
18834 ((org-at-heading-p) (call-interactively 'org-set-tags))
18835 ((org-at-table.el-p)
18836 (message "Use C-c ' to edit table.el tables"))
18837 ((org-at-table-p)
18838 (org-table-maybe-eval-formula)
18839 (if arg
18840 (call-interactively 'org-table-recalculate)
18841 (org-table-maybe-recalculate-line))
18842 (call-interactively 'org-table-align)
18843 (orgtbl-send-table 'maybe))
18844 ((or (org-footnote-at-reference-p)
18845 (org-footnote-at-definition-p))
18846 (call-interactively 'org-footnote-action))
18847 ((org-at-item-checkbox-p)
18848 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18849 ;; list only if at top item.
18850 (let* ((cbox (match-string 1))
18851 (struct (org-list-struct))
18852 (old-struct (copy-tree struct))
18853 (parents (org-list-parents-alist struct))
18854 (orderedp (org-entry-get nil "ORDERED"))
18855 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18856 block-item)
18857 ;; Use a light version of `org-toggle-checkbox' to avoid
18858 ;; computing list structure twice.
18859 (let ((new-box (cond
18860 ((equal arg '(16)) "[-]")
18861 ((equal arg '(4)) nil)
18862 ((equal "[X]" cbox) "[ ]")
18863 (t "[X]"))))
18864 (if (and firstp arg)
18865 ;; If at first item of sub-list, remove check-box from
18866 ;; every item at the same level.
18867 (mapc
18868 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18869 (org-list-get-all-items
18870 (point-at-bol) struct (org-list-prevs-alist struct)))
18871 (org-list-set-checkbox (point-at-bol) struct new-box)))
18872 ;; Replicate `org-list-write-struct', while grabbing a return
18873 ;; value from `org-list-struct-fix-box'.
18874 (org-list-struct-fix-ind struct parents 2)
18875 (org-list-struct-fix-item-end struct)
18876 (let ((prevs (org-list-prevs-alist struct)))
18877 (org-list-struct-fix-bul struct prevs)
18878 (org-list-struct-fix-ind struct parents)
18879 (setq block-item
18880 (org-list-struct-fix-box struct parents prevs orderedp)))
18881 (org-list-struct-apply-struct struct old-struct)
18882 (org-update-checkbox-count-maybe)
18883 (when block-item
18884 (message
18885 "Checkboxes were removed due to unchecked box at line %d"
18886 (org-current-line block-item)))
18887 (when firstp (org-list-send-list 'maybe))))
18888 ((org-at-item-p)
18889 ;; Cursor at an item: repair list. Do checkbox related actions
18890 ;; only if function was called with an argument. Send list only
18891 ;; if at top item.
18892 (let* ((struct (org-list-struct))
18893 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18894 old-struct)
18895 (when arg
18896 (setq old-struct (copy-tree struct))
18897 (if firstp
18898 ;; If at first item of sub-list, add check-box to every
18899 ;; item at the same level.
18900 (mapc
18901 (lambda (pos)
18902 (unless (org-list-get-checkbox pos struct)
18903 (org-list-set-checkbox pos struct "[ ]")))
18904 (org-list-get-all-items
18905 (point-at-bol) struct (org-list-prevs-alist struct)))
18906 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18907 (org-list-write-struct
18908 struct (org-list-parents-alist struct) old-struct)
18909 (when arg (org-update-checkbox-count-maybe))
18910 (when firstp (org-list-send-list 'maybe))))
18911 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18912 ;; Dynamic block
18913 (beginning-of-line 1)
18914 (save-excursion (org-update-dblock)))
18915 ((save-excursion
18916 (let ((case-fold-search t))
18917 (beginning-of-line 1)
18918 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
18919 (cond
18920 ((or (equal (match-string 1) "TBLFM")
18921 (equal (match-string 1) "tblfm"))
18922 ;; Recalculate the table before this line
18923 (save-excursion
18924 (beginning-of-line 1)
18925 (skip-chars-backward " \r\n\t")
18926 (if (org-at-table-p)
18927 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18929 (let ((org-inhibit-startup-visibility-stuff t)
18930 (org-startup-align-all-tables nil))
18931 (when (boundp 'org-table-coordinate-overlays)
18932 (mapc 'delete-overlay org-table-coordinate-overlays)
18933 (setq org-table-coordinate-overlays nil))
18934 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18935 (message "Local setup has been refreshed"))))
18936 ((org-clock-update-time-maybe))
18938 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18939 (error "C-c C-c can do nothing useful at this location"))))))
18941 (defun org-mode-restart ()
18942 "Restart Org-mode, to scan again for special lines.
18943 Also updates the keyword regular expressions."
18944 (interactive)
18945 (org-mode)
18946 (message "Org-mode restarted"))
18948 (defun org-kill-note-or-show-branches ()
18949 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18950 (interactive)
18951 (if (not org-finish-function)
18952 (progn
18953 (hide-subtree)
18954 (call-interactively 'show-branches))
18955 (let ((org-note-abort t))
18956 (funcall org-finish-function))))
18958 (defun org-return (&optional indent)
18959 "Goto next table row or insert a newline.
18960 Calls `org-table-next-row' or `newline', depending on context.
18961 See the individual commands for more information."
18962 (interactive)
18963 (let (org-ts-what)
18964 (cond
18965 ((or (bobp) (org-in-src-block-p))
18966 (if indent (newline-and-indent) (newline)))
18967 ((org-at-table-p)
18968 (org-table-justify-field-maybe)
18969 (call-interactively 'org-table-next-row))
18970 ;; when `newline-and-indent' is called within a list, make sure
18971 ;; text moved stays inside the item.
18972 ((and (org-in-item-p) indent)
18973 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18974 (progn
18975 (save-match-data (newline))
18976 (org-indent-line-to (length (match-string 0))))
18977 (let ((ind (org-get-indentation)))
18978 (newline)
18979 (if (org-looking-back org-list-end-re)
18980 (org-indent-line)
18981 (org-indent-line-to ind)))))
18982 ((and org-return-follows-link
18983 (org-at-timestamp-p t)
18984 (not (eq org-ts-what 'after)))
18985 (org-follow-timestamp-link))
18986 ((and org-return-follows-link
18987 (let ((tprop (get-text-property (point) 'face)))
18988 (or (eq tprop 'org-link)
18989 (and (listp tprop) (memq 'org-link tprop)))))
18990 (call-interactively 'org-open-at-point))
18991 ((and (org-at-heading-p)
18992 (looking-at
18993 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18994 (org-show-entry)
18995 (end-of-line 1)
18996 (newline))
18997 (t (if indent (newline-and-indent) (newline))))))
18999 (defun org-return-indent ()
19000 "Goto next table row or insert a newline and indent.
19001 Calls `org-table-next-row' or `newline-and-indent', depending on
19002 context. See the individual commands for more information."
19003 (interactive)
19004 (org-return t))
19006 (defun org-ctrl-c-star ()
19007 "Compute table, or change heading status of lines.
19008 Calls `org-table-recalculate' or `org-toggle-heading',
19009 depending on context."
19010 (interactive)
19011 (cond
19012 ((org-at-table-p)
19013 (call-interactively 'org-table-recalculate))
19015 ;; Convert all lines in region to list items
19016 (call-interactively 'org-toggle-heading))))
19018 (defun org-ctrl-c-minus ()
19019 "Insert separator line in table or modify bullet status of line.
19020 Also turns a plain line or a region of lines into list items.
19021 Calls `org-table-insert-hline', `org-toggle-item', or
19022 `org-cycle-list-bullet', depending on context."
19023 (interactive)
19024 (cond
19025 ((org-at-table-p)
19026 (call-interactively 'org-table-insert-hline))
19027 ((org-region-active-p)
19028 (call-interactively 'org-toggle-item))
19029 ((org-in-item-p)
19030 (call-interactively 'org-cycle-list-bullet))
19032 (call-interactively 'org-toggle-item))))
19034 (defun org-toggle-item (arg)
19035 "Convert headings or normal lines to items, items to normal lines.
19036 If there is no active region, only the current line is considered.
19038 If the first non blank line in the region is an headline, convert
19039 all headlines to items, shifting text accordingly.
19041 If it is an item, convert all items to normal lines.
19043 If it is normal text, change region into an item. With a prefix
19044 argument ARG, change each line in region into an item."
19045 (interactive "P")
19046 (let ((shift-text
19047 (function
19048 ;; Shift text in current section to IND, from point to END.
19049 ;; The function leaves point to END line.
19050 (lambda (ind end)
19051 (let ((min-i 1000) (end (copy-marker end)))
19052 ;; First determine the minimum indentation (MIN-I) of
19053 ;; the text.
19054 (save-excursion
19055 (catch 'exit
19056 (while (< (point) end)
19057 (let ((i (org-get-indentation)))
19058 (cond
19059 ;; Skip blank lines and inline tasks.
19060 ((looking-at "^[ \t]*$"))
19061 ((looking-at org-outline-regexp-bol))
19062 ;; We can't find less than 0 indentation.
19063 ((zerop i) (throw 'exit (setq min-i 0)))
19064 ((< i min-i) (setq min-i i))))
19065 (forward-line))))
19066 ;; Then indent each line so that a line indented to
19067 ;; MIN-I becomes indented to IND. Ignore blank lines
19068 ;; and inline tasks in the process.
19069 (let ((delta (- ind min-i)))
19070 (while (< (point) end)
19071 (unless (or (looking-at "^[ \t]*$")
19072 (looking-at org-outline-regexp-bol))
19073 (org-indent-line-to (+ (org-get-indentation) delta)))
19074 (forward-line)))))))
19075 (skip-blanks
19076 (function
19077 ;; Return beginning of first non-blank line, starting from
19078 ;; line at POS.
19079 (lambda (pos)
19080 (save-excursion
19081 (goto-char pos)
19082 (skip-chars-forward " \r\t\n")
19083 (point-at-bol)))))
19084 beg end)
19085 ;; Determine boundaries of changes.
19086 (if (org-region-active-p)
19087 (setq beg (funcall skip-blanks (region-beginning))
19088 end (copy-marker (region-end)))
19089 (setq beg (funcall skip-blanks (point-at-bol))
19090 end (copy-marker (point-at-eol))))
19091 ;; Depending on the starting line, choose an action on the text
19092 ;; between BEG and END.
19093 (org-with-limited-levels
19094 (save-excursion
19095 (goto-char beg)
19096 (cond
19097 ;; Case 1. Start at an item: de-itemize. Note that it only
19098 ;; happens when a region is active: `org-ctrl-c-minus'
19099 ;; would call `org-cycle-list-bullet' otherwise.
19100 ((org-at-item-p)
19101 (while (< (point) end)
19102 (when (org-at-item-p)
19103 (skip-chars-forward " \t")
19104 (delete-region (point) (match-end 0)))
19105 (forward-line)))
19106 ;; Case 2. Start at an heading: convert to items.
19107 ((org-at-heading-p)
19108 (let* ((bul (org-list-bullet-string "-"))
19109 (bul-len (length bul))
19110 ;; Indentation of the first heading. It should be
19111 ;; relative to the indentation of its parent, if any.
19112 (start-ind (save-excursion
19113 (cond
19114 ((not org-adapt-indentation) 0)
19115 ((not (outline-previous-heading)) 0)
19116 (t (length (match-string 0))))))
19117 ;; Level of first heading. Further headings will be
19118 ;; compared to it to determine hierarchy in the list.
19119 (ref-level (org-reduced-level (org-outline-level))))
19120 (while (< (point) end)
19121 (let* ((level (org-reduced-level (org-outline-level)))
19122 (delta (max 0 (- level ref-level))))
19123 ;; If current headline is less indented than the first
19124 ;; one, set it as reference, in order to preserve
19125 ;; subtrees.
19126 (when (< level ref-level) (setq ref-level level))
19127 (replace-match bul t t)
19128 (org-indent-line-to (+ start-ind (* delta bul-len)))
19129 ;; Ensure all text down to END (or SECTION-END) belongs
19130 ;; to the newly created item.
19131 (let ((section-end (save-excursion
19132 (or (outline-next-heading) (point)))))
19133 (forward-line)
19134 (funcall shift-text
19135 (+ start-ind (* (1+ delta) bul-len))
19136 (min end section-end)))))))
19137 ;; Case 3. Normal line with ARG: turn each non-item line into
19138 ;; an item.
19139 (arg
19140 (while (< (point) end)
19141 (unless (or (org-at-heading-p) (org-at-item-p))
19142 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19143 (replace-match
19144 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19145 (forward-line)))
19146 ;; Case 4. Normal line without ARG: make the first line of
19147 ;; region an item, and shift indentation of others
19148 ;; lines to set them as item's body.
19149 (t (let* ((bul (org-list-bullet-string "-"))
19150 (bul-len (length bul))
19151 (ref-ind (org-get-indentation)))
19152 (skip-chars-forward " \t")
19153 (insert bul)
19154 (forward-line)
19155 (while (< (point) end)
19156 ;; Ensure that lines less indented than first one
19157 ;; still get included in item body.
19158 (funcall shift-text
19159 (+ ref-ind bul-len)
19160 (min end (save-excursion (or (outline-next-heading)
19161 (point)))))
19162 (forward-line)))))))))
19164 (defun org-toggle-heading (&optional nstars)
19165 "Convert headings to normal text, or items or text to headings.
19166 If there is no active region, only the current line is considered.
19168 With a \\[universal-argument] prefix, convert the whole list at
19169 point into heading.
19171 In a region:
19173 - If the first non blank line is an headline, remove the stars
19174 from all headlines in the region.
19176 - If it is a normal line turn each and every normal line (i.e. not an
19177 heading or an item) in the region into a heading.
19179 - If it is a plain list item, turn all plain list items into headings.
19181 When converting a line into a heading, the number of stars is chosen
19182 such that the lines become children of the current entry. However,
19183 when a prefix argument is given, its value determines the number of
19184 stars to add."
19185 (interactive "P")
19186 (let ((skip-blanks
19187 (function
19188 ;; Return beginning of first non-blank line, starting from
19189 ;; line at POS.
19190 (lambda (pos)
19191 (save-excursion
19192 (goto-char pos)
19193 (while (org-at-comment-p) (forward-line))
19194 (skip-chars-forward " \r\t\n")
19195 (point-at-bol)))))
19196 beg end toggled)
19197 ;; Determine boundaries of changes. If a universal prefix has
19198 ;; been given, put the list in a region. If region ends at a bol,
19199 ;; do not consider the last line to be in the region.
19201 (when (and current-prefix-arg (org-at-item-p))
19202 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19203 (org-mark-list))
19205 (if (org-region-active-p)
19206 (setq beg (funcall skip-blanks (region-beginning))
19207 end (copy-marker (save-excursion
19208 (goto-char (region-end))
19209 (if (bolp) (point) (point-at-eol)))))
19210 (setq beg (funcall skip-blanks (point-at-bol))
19211 end (copy-marker (point-at-eol))))
19212 ;; Ensure inline tasks don't count as headings.
19213 (org-with-limited-levels
19214 (save-excursion
19215 (goto-char beg)
19216 (cond
19217 ;; Case 1. Started at an heading: de-star headings.
19218 ((org-at-heading-p)
19219 (while (< (point) end)
19220 (when (org-at-heading-p t)
19221 (looking-at org-outline-regexp) (replace-match "")
19222 (setq toggled t))
19223 (forward-line)))
19224 ;; Case 2. Started at an item: change items into headlines.
19225 ;; One star will be added by `org-list-to-subtree'.
19226 ((org-at-item-p)
19227 (let* ((stars (make-string
19228 (if nstars
19229 ;; subtract the star that will be added again by
19230 ;; `org-list-to-subtree'
19231 (1- (prefix-numeric-value current-prefix-arg))
19232 (or (org-current-level) 0))
19233 ?*))
19234 (add-stars
19235 (cond (nstars "") ; stars from prefix only
19236 ((equal stars "") "") ; before first heading
19237 (org-odd-levels-only "*") ; inside heading, odd
19238 (t "")))) ; inside heading, oddeven
19239 (while (< (point) end)
19240 (when (org-at-item-p)
19241 ;; Pay attention to cases when region ends before list.
19242 (let* ((struct (org-list-struct))
19243 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19244 (save-restriction
19245 (narrow-to-region (point) list-end)
19246 (insert
19247 (org-list-to-subtree
19248 (org-list-parse-list t)
19249 '(:istart (concat stars add-stars (funcall get-stars depth))
19250 :icount (concat stars add-stars (funcall get-stars depth)))))))
19251 (setq toggled t))
19252 (forward-line))))
19253 ;; Case 3. Started at normal text: make every line an heading,
19254 ;; skipping headlines and items.
19255 (t (let* ((stars (make-string
19256 (if nstars
19257 (prefix-numeric-value current-prefix-arg)
19258 (or (org-current-level) 0))
19259 ?*))
19260 (add-stars
19261 (cond (nstars "") ; stars from prefix only
19262 ((equal stars "") "*") ; before first heading
19263 (org-odd-levels-only "**") ; inside heading, odd
19264 (t "*"))) ; inside heading, oddeven
19265 (rpl (concat stars add-stars " ")))
19266 (while (< (point) end)
19267 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19268 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19269 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19270 (forward-line)))))))
19271 (unless toggled (message "Cannot toggle heading from here"))))
19273 (defun org-meta-return (&optional arg)
19274 "Insert a new heading or wrap a region in a table.
19275 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19276 See the individual commands for more information."
19277 (interactive "P")
19278 (cond
19279 ((run-hook-with-args-until-success 'org-metareturn-hook))
19280 ((or (org-at-drawer-p) (org-at-property-p))
19281 (newline-and-indent))
19282 ((org-at-table-p)
19283 (call-interactively 'org-table-wrap-region))
19284 (t (call-interactively 'org-insert-heading))))
19286 ;;; Menu entries
19288 ;; Define the Org-mode menus
19289 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19290 '("Tbl"
19291 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19292 ["Next Field" org-cycle (org-at-table-p)]
19293 ["Previous Field" org-shifttab (org-at-table-p)]
19294 ["Next Row" org-return (org-at-table-p)]
19295 "--"
19296 ["Blank Field" org-table-blank-field (org-at-table-p)]
19297 ["Edit Field" org-table-edit-field (org-at-table-p)]
19298 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19299 "--"
19300 ("Column"
19301 ["Move Column Left" org-metaleft (org-at-table-p)]
19302 ["Move Column Right" org-metaright (org-at-table-p)]
19303 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19304 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19305 ("Row"
19306 ["Move Row Up" org-metaup (org-at-table-p)]
19307 ["Move Row Down" org-metadown (org-at-table-p)]
19308 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19309 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19310 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19311 "--"
19312 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19313 ("Rectangle"
19314 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19315 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19316 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19317 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19318 "--"
19319 ("Calculate"
19320 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19321 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19322 ["Edit Formulas" org-edit-special (org-at-table-p)]
19323 "--"
19324 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19325 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19326 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19327 "--"
19328 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19329 "--"
19330 ["Sum Column/Rectangle" org-table-sum
19331 (or (org-at-table-p) (org-region-active-p))]
19332 ["Which Column?" org-table-current-column (org-at-table-p)])
19333 ["Debug Formulas"
19334 org-table-toggle-formula-debugger
19335 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19336 ["Show Col/Row Numbers"
19337 org-table-toggle-coordinate-overlays
19338 :style toggle
19339 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19340 "--"
19341 ["Create" org-table-create (and (not (org-at-table-p))
19342 org-enable-table-editor)]
19343 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19344 ["Import from File" org-table-import (not (org-at-table-p))]
19345 ["Export to File" org-table-export (org-at-table-p)]
19346 "--"
19347 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19349 (easy-menu-define org-org-menu org-mode-map "Org menu"
19350 '("Org"
19351 ("Show/Hide"
19352 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19353 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19354 ["Sparse Tree..." org-sparse-tree t]
19355 ["Reveal Context" org-reveal t]
19356 ["Show All" show-all t]
19357 "--"
19358 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19359 "--"
19360 ["New Heading" org-insert-heading t]
19361 ("Navigate Headings"
19362 ["Up" outline-up-heading t]
19363 ["Next" outline-next-visible-heading t]
19364 ["Previous" outline-previous-visible-heading t]
19365 ["Next Same Level" outline-forward-same-level t]
19366 ["Previous Same Level" outline-backward-same-level t]
19367 "--"
19368 ["Jump" org-goto t])
19369 ("Edit Structure"
19370 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19371 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19372 "--"
19373 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19374 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19375 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19376 "--"
19377 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19378 "--"
19379 ["Copy visible text" org-copy-visible t]
19380 "--"
19381 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19382 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19383 ["Demote Heading" org-metaright (not (org-at-table-p))]
19384 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19385 "--"
19386 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19387 "--"
19388 ["Convert to odd levels" org-convert-to-odd-levels t]
19389 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19390 ("Editing"
19391 ["Emphasis..." org-emphasize t]
19392 ["Edit Source Example" org-edit-special t]
19393 "--"
19394 ["Footnote new/jump" org-footnote-action t]
19395 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19396 ("Archive"
19397 ["Archive (default method)" org-archive-subtree-default t]
19398 "--"
19399 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19400 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19401 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19403 "--"
19404 ("Hyperlinks"
19405 ["Store Link (Global)" org-store-link t]
19406 ["Find existing link to here" org-occur-link-in-agenda-files t]
19407 ["Insert Link" org-insert-link t]
19408 ["Follow Link" org-open-at-point t]
19409 "--"
19410 ["Next link" org-next-link t]
19411 ["Previous link" org-previous-link t]
19412 "--"
19413 ["Descriptive Links"
19414 org-toggle-link-display
19415 :style radio
19416 :selected org-descriptive-links
19418 ["Literal Links"
19419 org-toggle-link-display
19420 :style radio
19421 :selected (not org-descriptive-links)])
19422 "--"
19423 ("TODO Lists"
19424 ["TODO/DONE/-" org-todo t]
19425 ("Select keyword"
19426 ["Next keyword" org-shiftright (org-at-heading-p)]
19427 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19428 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19429 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19430 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19431 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19432 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19433 "--"
19434 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19435 :selected org-enforce-todo-dependencies :style toggle :active t]
19436 "Settings for tree at point"
19437 ["Do Children sequentially" org-toggle-ordered-property :style radio
19438 :selected (org-entry-get nil "ORDERED")
19439 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19440 ["Do Children parallel" org-toggle-ordered-property :style radio
19441 :selected (not (org-entry-get nil "ORDERED"))
19442 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19443 "--"
19444 ["Set Priority" org-priority t]
19445 ["Priority Up" org-shiftup t]
19446 ["Priority Down" org-shiftdown t]
19447 "--"
19448 ["Get news from all feeds" org-feed-update-all t]
19449 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19450 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19451 ("TAGS and Properties"
19452 ["Set Tags" org-set-tags-command t]
19453 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19454 "--"
19455 ["Set property" org-set-property t]
19456 ["Column view of properties" org-columns t]
19457 ["Insert Column View DBlock" org-insert-columns-dblock t])
19458 ("Dates and Scheduling"
19459 ["Timestamp" org-time-stamp t]
19460 ["Timestamp (inactive)" org-time-stamp-inactive t]
19461 ("Change Date"
19462 ["1 Day Later" org-shiftright t]
19463 ["1 Day Earlier" org-shiftleft t]
19464 ["1 ... Later" org-shiftup t]
19465 ["1 ... Earlier" org-shiftdown t])
19466 ["Compute Time Range" org-evaluate-time-range t]
19467 ["Schedule Item" org-schedule t]
19468 ["Deadline" org-deadline t]
19469 "--"
19470 ["Custom time format" org-toggle-time-stamp-overlays
19471 :style radio :selected org-display-custom-times]
19472 "--"
19473 ["Goto Calendar" org-goto-calendar t]
19474 ["Date from Calendar" org-date-from-calendar t]
19475 "--"
19476 ["Start/Restart Timer" org-timer-start t]
19477 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19478 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19479 ["Insert Timer String" org-timer t]
19480 ["Insert Timer Item" org-timer-item t])
19481 ("Logging work"
19482 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19483 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19484 ["Clock out" org-clock-out t]
19485 ["Clock cancel" org-clock-cancel t]
19486 "--"
19487 ["Mark as default task" org-clock-mark-default-task t]
19488 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19489 ["Goto running clock" org-clock-goto t]
19490 "--"
19491 ["Display times" org-clock-display t]
19492 ["Create clock table" org-clock-report t]
19493 "--"
19494 ["Record DONE time"
19495 (progn (setq org-log-done (not org-log-done))
19496 (message "Switching to %s will %s record a timestamp"
19497 (car org-done-keywords)
19498 (if org-log-done "automatically" "not")))
19499 :style toggle :selected org-log-done])
19500 "--"
19501 ["Agenda Command..." org-agenda t]
19502 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19503 ("File List for Agenda")
19504 ("Special views current file"
19505 ["TODO Tree" org-show-todo-tree t]
19506 ["Check Deadlines" org-check-deadlines t]
19507 ["Timeline" org-timeline t]
19508 ["Tags/Property tree" org-match-sparse-tree t])
19509 "--"
19510 ["Export/Publish..." org-export t]
19511 ("LaTeX"
19512 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19513 :selected org-cdlatex-mode]
19514 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19515 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19516 ["Modify math symbol" org-cdlatex-math-modify
19517 (org-inside-LaTeX-fragment-p)]
19518 ["Insert citation" org-reftex-citation t]
19519 "--"
19520 ["Template for BEAMER" (progn (require 'org-beamer)
19521 (org-insert-beamer-options-template)) t])
19522 "--"
19523 ("MobileOrg"
19524 ["Push Files and Views" org-mobile-push t]
19525 ["Get Captured and Flagged" org-mobile-pull t]
19526 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19527 "--"
19528 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19529 "--"
19530 ("Documentation"
19531 ["Show Version" org-version t]
19532 ["Info Documentation" org-info t])
19533 ("Customize"
19534 ["Browse Org Group" org-customize t]
19535 "--"
19536 ["Expand This Menu" org-create-customize-menu
19537 (fboundp 'customize-menu-create)])
19538 ["Send bug report" org-submit-bug-report t]
19539 "--"
19540 ("Refresh/Reload"
19541 ["Refresh setup current buffer" org-mode-restart t]
19542 ["Reload Org (after update)" org-reload t]
19543 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19546 (defun org-info (&optional node)
19547 "Read documentation for Org-mode in the info system.
19548 With optional NODE, go directly to that node."
19549 (interactive)
19550 (info (format "(org)%s" (or node ""))))
19552 ;;;###autoload
19553 (defun org-submit-bug-report ()
19554 "Submit a bug report on Org-mode via mail.
19556 Don't hesitate to report any problems or inaccurate documentation.
19558 If you don't have setup sending mail from (X)Emacs, please copy the
19559 output buffer into your mail program, as it gives us important
19560 information about your Org-mode version and configuration."
19561 (interactive)
19562 (require 'reporter)
19563 (org-load-modules-maybe)
19564 (org-require-autoloaded-modules)
19565 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19566 (reporter-submit-bug-report
19567 "emacs-orgmode@gnu.org"
19568 (org-version nil 'full)
19569 (let (list)
19570 (save-window-excursion
19571 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19572 (delete-other-windows)
19573 (erase-buffer)
19574 (insert "You are about to submit a bug report to the Org-mode mailing list.
19576 We would like to add your full Org-mode and Outline configuration to the
19577 bug report. This greatly simplifies the work of the maintainer and
19578 other experts on the mailing list.
19580 HOWEVER, some variables you have customized may contain private
19581 information. The names of customers, colleagues, or friends, might
19582 appear in the form of file names, tags, todo states, or search strings.
19583 If you answer yes to the prompt, you might want to check and remove
19584 such private information before sending the email.")
19585 (add-text-properties (point-min) (point-max) '(face org-warning))
19586 (when (yes-or-no-p "Include your Org-mode configuration ")
19587 (mapatoms
19588 (lambda (v)
19589 (and (boundp v)
19590 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19591 (or (and (symbol-value v)
19592 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19593 (and
19594 (get v 'custom-type) (get v 'standard-value)
19595 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19596 (push v list)))))
19597 (kill-buffer (get-buffer "*Warn about privacy*"))
19598 list))
19599 nil nil
19600 "Remember to cover the basics, that is, what you expected to happen and
19601 what in fact did happen. You don't know how to make a good report? See
19603 http://orgmode.org/manual/Feedback.html#Feedback
19605 Your bug report will be posted to the Org-mode mailing list.
19606 ------------------------------------------------------------------------")
19607 (save-excursion
19608 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19609 (replace-match "\\1Bug: \\3 [\\2]")))))
19612 (defun org-install-agenda-files-menu ()
19613 (let ((bl (buffer-list)))
19614 (save-excursion
19615 (while bl
19616 (set-buffer (pop bl))
19617 (if (derived-mode-p 'org-mode) (setq bl nil)))
19618 (when (derived-mode-p 'org-mode)
19619 (easy-menu-change
19620 '("Org") "File List for Agenda"
19621 (append
19622 (list
19623 ["Edit File List" (org-edit-agenda-file-list) t]
19624 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19625 ["Remove Current File from List" org-remove-file t]
19626 ["Cycle through agenda files" org-cycle-agenda-files t]
19627 ["Occur in all agenda files" org-occur-in-agenda-files t]
19628 "--")
19629 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19631 ;;;; Documentation
19633 ;;;###autoload
19634 (defun org-require-autoloaded-modules ()
19635 (interactive)
19636 (mapc 'require
19637 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19638 org-docbook org-exp org-html org-icalendar
19639 org-id org-latex
19640 org-publish org-remember org-table
19641 org-timer org-xoxo)))
19643 ;;;###autoload
19644 (defun org-reload (&optional uncompiled)
19645 "Reload all org lisp files.
19646 With prefix arg UNCOMPILED, load the uncompiled versions."
19647 (interactive "P")
19648 (require 'find-func)
19649 (let* ((file-re "^org\\(-.*\\)?\\.el")
19650 (dir-org (file-name-directory (org-find-library-dir "org")))
19651 (dir-org-contrib (ignore-errors
19652 (file-name-directory
19653 (org-find-library-dir "org-contribdir"))))
19654 (babel-files
19655 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19656 (append (list nil "comint" "eval" "exp" "keys"
19657 "lob" "ref" "table" "tangle")
19658 (delq nil
19659 (mapcar
19660 (lambda (lang)
19661 (when (cdr lang) (symbol-name (car lang))))
19662 org-babel-load-languages)))))
19663 (files
19664 (append babel-files
19665 (and dir-org-contrib
19666 (directory-files dir-org-contrib t file-re))
19667 (directory-files dir-org t file-re)))
19668 (remove-re (concat (if (featurep 'xemacs)
19669 "org-colview" "org-colview-xemacs")
19670 "\\'")))
19671 (setq files (mapcar 'file-name-sans-extension files))
19672 (setq files (mapcar
19673 (lambda (x) (if (string-match remove-re x) nil x))
19674 files))
19675 (setq files (delq nil files))
19676 (mapc
19677 (lambda (f)
19678 (when (featurep (intern (file-name-nondirectory f)))
19679 (if (and (not uncompiled)
19680 (file-exists-p (concat f ".elc")))
19681 (load (concat f ".elc") nil nil 'nosuffix)
19682 (load (concat f ".el") nil nil 'nosuffix))))
19683 files)
19684 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19685 (org-version nil 'full 'message))
19687 ;;;###autoload
19688 (defun org-customize ()
19689 "Call the customize function with org as argument."
19690 (interactive)
19691 (org-load-modules-maybe)
19692 (org-require-autoloaded-modules)
19693 (customize-browse 'org))
19695 (defun org-create-customize-menu ()
19696 "Create a full customization menu for Org-mode, insert it into the menu."
19697 (interactive)
19698 (org-load-modules-maybe)
19699 (org-require-autoloaded-modules)
19700 (if (fboundp 'customize-menu-create)
19701 (progn
19702 (easy-menu-change
19703 '("Org") "Customize"
19704 `(["Browse Org group" org-customize t]
19705 "--"
19706 ,(customize-menu-create 'org)
19707 ["Set" Custom-set t]
19708 ["Save" Custom-save t]
19709 ["Reset to Current" Custom-reset-current t]
19710 ["Reset to Saved" Custom-reset-saved t]
19711 ["Reset to Standard Settings" Custom-reset-standard t]))
19712 (message "\"Org\"-menu now contains full customization menu"))
19713 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19715 ;;;; Miscellaneous stuff
19717 ;;; Generally useful functions
19719 (defun org-get-at-bol (property)
19720 "Get text property PROPERTY at beginning of line."
19721 (get-text-property (point-at-bol) property))
19723 (defun org-find-text-property-in-string (prop s)
19724 "Return the first non-nil value of property PROP in string S."
19725 (or (get-text-property 0 prop s)
19726 (get-text-property (or (next-single-property-change 0 prop s) 0)
19727 prop s)))
19729 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19730 "Display the given MESSAGE as a warning."
19731 (if (fboundp 'display-warning)
19732 (display-warning 'org message
19733 (if (featurep 'xemacs) 'warning :warning))
19734 (let ((buf (get-buffer-create "*Org warnings*")))
19735 (with-current-buffer buf
19736 (goto-char (point-max))
19737 (insert "Warning (Org): " message)
19738 (unless (bolp)
19739 (newline)))
19740 (display-buffer buf)
19741 (sit-for 0))))
19743 (defun org-eval (form)
19744 "Eval FORM and return result."
19745 (condition-case error
19746 (eval form)
19747 (error (format "%%![Error: %s]" error))))
19749 (defun org-in-clocktable-p ()
19750 "Check if the cursor is in a clocktable."
19751 (let ((pos (point)) start)
19752 (save-excursion
19753 (end-of-line 1)
19754 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19755 (setq start (match-beginning 0))
19756 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19757 (>= (match-end 0) pos)
19758 start))))
19760 (defun org-in-commented-line ()
19761 "Is point in a line starting with `#'?"
19762 (equal (char-after (point-at-bol)) ?#))
19764 (defun org-in-indented-comment-line ()
19765 "Is point in a line starting with `#' after some white space?"
19766 (save-excursion
19767 (save-match-data
19768 (goto-char (point-at-bol))
19769 (looking-at "[ \t]*#"))))
19771 (defun org-in-verbatim-emphasis ()
19772 (save-match-data
19773 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19775 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19776 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19777 (if (and marker (marker-buffer marker)
19778 (buffer-live-p (marker-buffer marker)))
19779 (progn
19780 (org-pop-to-buffer-same-window (marker-buffer marker))
19781 (if (or (> marker (point-max)) (< marker (point-min)))
19782 (widen))
19783 (goto-char marker)
19784 (org-show-context 'org-goto))
19785 (if bookmark
19786 (bookmark-jump bookmark)
19787 (error "Cannot find location"))))
19789 (defun org-quote-csv-field (s)
19790 "Quote field for inclusion in CSV material."
19791 (if (string-match "[\",]" s)
19792 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19795 (defun org-force-self-insert (N)
19796 "Needed to enforce self-insert under remapping."
19797 (interactive "p")
19798 (self-insert-command N))
19800 (defun org-string-width (s)
19801 "Compute width of string, ignoring invisible characters.
19802 This ignores character with invisibility property `org-link', and also
19803 characters with property `org-cwidth', because these will become invisible
19804 upon the next fontification round."
19805 (let (b l)
19806 (when (or (eq t buffer-invisibility-spec)
19807 (assq 'org-link buffer-invisibility-spec))
19808 (while (setq b (text-property-any 0 (length s)
19809 'invisible 'org-link s))
19810 (setq s (concat (substring s 0 b)
19811 (substring s (or (next-single-property-change
19812 b 'invisible s) (length s)))))))
19813 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19814 (setq s (concat (substring s 0 b)
19815 (substring s (or (next-single-property-change
19816 b 'org-cwidth s) (length s))))))
19817 (setq l (string-width s) b -1)
19818 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19819 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19822 (defun org-shorten-string (s maxlength)
19823 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19824 If the string is shorter or has length MAXLENGTH, just return the
19825 original string. If it is longer, the functions finds a space in the
19826 string, breaks this string off at that locations and adds three dots
19827 as ellipsis. Including the ellipsis, the string will not be longer
19828 than MAXLENGTH. If finding a good breaking point in the string does
19829 not work, the string is just chopped off in the middle of a word
19830 if necessary."
19831 (if (<= (length s) maxlength)
19833 (let* ((n (max (- maxlength 4) 1))
19834 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19835 (if (string-match re s)
19836 (concat (match-string 1 s) "...")
19837 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19839 (defun org-get-indentation (&optional line)
19840 "Get the indentation of the current line, interpreting tabs.
19841 When LINE is given, assume it represents a line and compute its indentation."
19842 (if line
19843 (if (string-match "^ *" (org-remove-tabs line))
19844 (match-end 0))
19845 (save-excursion
19846 (beginning-of-line 1)
19847 (skip-chars-forward " \t")
19848 (current-column))))
19850 (defun org-get-string-indentation (s)
19851 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19852 (let ((n -1) (i 0) (w tab-width) c)
19853 (catch 'exit
19854 (while (< (setq n (1+ n)) (length s))
19855 (setq c (aref s n))
19856 (cond ((= c ?\ ) (setq i (1+ i)))
19857 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19858 (t (throw 'exit t)))))
19861 (defun org-remove-tabs (s &optional width)
19862 "Replace tabulators in S with spaces.
19863 Assumes that s is a single line, starting in column 0."
19864 (setq width (or width tab-width))
19865 (while (string-match "\t" s)
19866 (setq s (replace-match
19867 (make-string
19868 (- (* width (/ (+ (match-beginning 0) width) width))
19869 (match-beginning 0)) ?\ )
19870 t t s)))
19873 (defun org-fix-indentation (line ind)
19874 "Fix indentation in LINE.
19875 IND is a cons cell with target and minimum indentation.
19876 If the current indentation in LINE is smaller than the minimum,
19877 leave it alone. If it is larger than ind, set it to the target."
19878 (let* ((l (org-remove-tabs line))
19879 (i (org-get-indentation l))
19880 (i1 (car ind)) (i2 (cdr ind)))
19881 (if (>= i i2) (setq l (substring line i2)))
19882 (if (> i1 0)
19883 (concat (make-string i1 ?\ ) l)
19884 l)))
19886 (defun org-remove-indentation (code &optional n)
19887 "Remove the maximum common indentation from the lines in CODE.
19888 N may optionally be the number of spaces to remove."
19889 (with-temp-buffer
19890 (insert code)
19891 (org-do-remove-indentation n)
19892 (buffer-string)))
19894 (defun org-do-remove-indentation (&optional n)
19895 "Remove the maximum common indentation from the buffer."
19896 (untabify (point-min) (point-max))
19897 (let ((min 10000) re)
19898 (if n
19899 (setq min n)
19900 (goto-char (point-min))
19901 (while (re-search-forward "^ *[^ \n]" nil t)
19902 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19903 (unless (or (= min 0) (= min 10000))
19904 (setq re (format "^ \\{%d\\}" min))
19905 (goto-char (point-min))
19906 (while (re-search-forward re nil t)
19907 (replace-match "")
19908 (end-of-line 1))
19909 min)))
19911 (defun org-fill-template (template alist)
19912 "Find each %key of ALIST in TEMPLATE and replace it."
19913 (let ((case-fold-search nil)
19914 entry key value)
19915 (setq alist (sort (copy-sequence alist)
19916 (lambda (a b) (< (length (car a)) (length (car b))))))
19917 (while (setq entry (pop alist))
19918 (setq template
19919 (replace-regexp-in-string
19920 (concat "%" (regexp-quote (car entry)))
19921 (cdr entry) template t t)))
19922 template))
19924 (defun org-base-buffer (buffer)
19925 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19926 (if (not buffer)
19927 buffer
19928 (or (buffer-base-buffer buffer)
19929 buffer)))
19931 (defun org-trim (s)
19932 "Remove whitespace at beginning and end of string."
19933 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19934 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19937 (defun org-wrap (string &optional width lines)
19938 "Wrap string to either a number of lines, or a width in characters.
19939 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19940 that costs. If there is a word longer than WIDTH, the text is actually
19941 wrapped to the length of that word.
19942 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19943 many lines, whatever width that takes.
19944 The return value is a list of lines, without newlines at the end."
19945 (let* ((words (org-split-string string "[ \t\n]+"))
19946 (maxword (apply 'max (mapcar 'org-string-width words)))
19947 w ll)
19948 (cond (width
19949 (org-do-wrap words (max maxword width)))
19950 (lines
19951 (setq w maxword)
19952 (setq ll (org-do-wrap words maxword))
19953 (if (<= (length ll) lines)
19955 (setq ll words)
19956 (while (> (length ll) lines)
19957 (setq w (1+ w))
19958 (setq ll (org-do-wrap words w)))
19959 ll))
19960 (t (error "Cannot wrap this")))))
19962 (defun org-do-wrap (words width)
19963 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19964 (let (lines line)
19965 (while words
19966 (setq line (pop words))
19967 (while (and words (< (+ (length line) (length (car words))) width))
19968 (setq line (concat line " " (pop words))))
19969 (setq lines (push line lines)))
19970 (nreverse lines)))
19972 (defun org-split-string (string &optional separators)
19973 "Splits STRING into substrings at SEPARATORS.
19974 No empty strings are returned if there are matches at the beginning
19975 and end of string."
19976 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19977 (start 0)
19978 notfirst
19979 (list nil))
19980 (while (and (string-match rexp string
19981 (if (and notfirst
19982 (= start (match-beginning 0))
19983 (< start (length string)))
19984 (1+ start) start))
19985 (< (match-beginning 0) (length string)))
19986 (setq notfirst t)
19987 (or (eq (match-beginning 0) 0)
19988 (and (eq (match-beginning 0) (match-end 0))
19989 (eq (match-beginning 0) start))
19990 (setq list
19991 (cons (substring string start (match-beginning 0))
19992 list)))
19993 (setq start (match-end 0)))
19994 (or (eq start (length string))
19995 (setq list
19996 (cons (substring string start)
19997 list)))
19998 (nreverse list)))
20000 (defun org-quote-vert (s)
20001 "Replace \"|\" with \"\\vert\"."
20002 (while (string-match "|" s)
20003 (setq s (replace-match "\\vert" t t s)))
20006 (defun org-uuidgen-p (s)
20007 "Is S an ID created by UUIDGEN?"
20008 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20010 (defun org-in-src-block-p nil
20011 "Whether point is in a code source block."
20012 (let (ov)
20013 (when (setq ov (overlays-at (point)))
20014 (memq 'org-block-background
20015 (overlay-properties
20016 (car ov))))))
20018 (defun org-context ()
20019 "Return a list of contexts of the current cursor position.
20020 If several contexts apply, all are returned.
20021 Each context entry is a list with a symbol naming the context, and
20022 two positions indicating start and end of the context. Possible
20023 contexts are:
20025 :headline anywhere in a headline
20026 :headline-stars on the leading stars in a headline
20027 :todo-keyword on a TODO keyword (including DONE) in a headline
20028 :tags on the TAGS in a headline
20029 :priority on the priority cookie in a headline
20030 :item on the first line of a plain list item
20031 :item-bullet on the bullet/number of a plain list item
20032 :checkbox on the checkbox in a plain list item
20033 :table in an org-mode table
20034 :table-special on a special filed in a table
20035 :table-table in a table.el table
20036 :clocktable in a clocktable
20037 :src-block in a source block
20038 :link on a hyperlink
20039 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20040 :target on a <<target>>
20041 :radio-target on a <<<radio-target>>>
20042 :latex-fragment on a LaTeX fragment
20043 :latex-preview on a LaTeX fragment with overlaid preview image
20045 This function expects the position to be visible because it uses font-lock
20046 faces as a help to recognize the following contexts: :table-special, :link,
20047 and :keyword."
20048 (let* ((f (get-text-property (point) 'face))
20049 (faces (if (listp f) f (list f)))
20050 (case-fold-search t)
20051 (p (point)) clist o)
20052 ;; First the large context
20053 (cond
20054 ((org-at-heading-p t)
20055 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20056 (when (progn
20057 (beginning-of-line 1)
20058 (looking-at org-todo-line-tags-regexp))
20059 (push (org-point-in-group p 1 :headline-stars) clist)
20060 (push (org-point-in-group p 2 :todo-keyword) clist)
20061 (push (org-point-in-group p 4 :tags) clist))
20062 (goto-char p)
20063 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20064 (if (looking-at "\\[#[A-Z0-9]\\]")
20065 (push (org-point-in-group p 0 :priority) clist)))
20067 ((org-at-item-p)
20068 (push (org-point-in-group p 2 :item-bullet) clist)
20069 (push (list :item (point-at-bol)
20070 (save-excursion (org-end-of-item) (point)))
20071 clist)
20072 (and (org-at-item-checkbox-p)
20073 (push (org-point-in-group p 0 :checkbox) clist)))
20075 ((org-at-table-p)
20076 (push (list :table (org-table-begin) (org-table-end)) clist)
20077 (if (memq 'org-formula faces)
20078 (push (list :table-special
20079 (previous-single-property-change p 'face)
20080 (next-single-property-change p 'face)) clist)))
20081 ((org-at-table-p 'any)
20082 (push (list :table-table) clist)))
20083 (goto-char p)
20085 ;; New the "medium" contexts: clocktables, source blocks
20086 (cond ((org-in-clocktable-p)
20087 (push (list :clocktable
20088 (and (or (looking-at "#\\+BEGIN: clocktable")
20089 (search-backward "#+BEGIN: clocktable" nil t))
20090 (match-beginning 0))
20091 (and (re-search-forward "#\\+END:?" nil t)
20092 (match-end 0))) clist))
20093 ((org-in-src-block-p)
20094 (push (list :src-block
20095 (and (or (looking-at "#\\+BEGIN_SRC")
20096 (search-backward "#+BEGIN_SRC" nil t))
20097 (match-beginning 0))
20098 (and (search-forward "#+END_SRC" nil t)
20099 (match-beginning 0))) clist)))
20100 (goto-char p)
20102 ;; Now the small context
20103 (cond
20104 ((org-at-timestamp-p)
20105 (push (org-point-in-group p 0 :timestamp) clist))
20106 ((memq 'org-link faces)
20107 (push (list :link
20108 (previous-single-property-change p 'face)
20109 (next-single-property-change p 'face)) clist))
20110 ((memq 'org-special-keyword faces)
20111 (push (list :keyword
20112 (previous-single-property-change p 'face)
20113 (next-single-property-change p 'face)) clist))
20114 ((org-at-target-p)
20115 (push (org-point-in-group p 0 :target) clist)
20116 (goto-char (1- (match-beginning 0)))
20117 (if (looking-at org-radio-target-regexp)
20118 (push (org-point-in-group p 0 :radio-target) clist))
20119 (goto-char p))
20120 ((setq o (car (delq nil
20121 (mapcar
20122 (lambda (x)
20123 (if (memq x org-latex-fragment-image-overlays) x))
20124 (overlays-at (point))))))
20125 (push (list :latex-fragment
20126 (overlay-start o) (overlay-end o)) clist)
20127 (push (list :latex-preview
20128 (overlay-start o) (overlay-end o)) clist))
20129 ((org-inside-LaTeX-fragment-p)
20130 ;; FIXME: positions wrong.
20131 (push (list :latex-fragment (point) (point)) clist)))
20133 (setq clist (nreverse (delq nil clist)))
20134 clist))
20136 ;; FIXME: Compare with at-regexp-p Do we need both?
20137 (defun org-in-regexp (re &optional nlines visually)
20138 "Check if point is inside a match of regexp.
20139 Normally only the current line is checked, but you can include NLINES extra
20140 lines both before and after point into the search.
20141 If VISUALLY is set, require that the cursor is not after the match but
20142 really on, so that the block visually is on the match."
20143 (catch 'exit
20144 (let ((pos (point))
20145 (eol (point-at-eol (+ 1 (or nlines 0))))
20146 (inc (if visually 1 0)))
20147 (save-excursion
20148 (beginning-of-line (- 1 (or nlines 0)))
20149 (while (re-search-forward re eol t)
20150 (if (and (<= (match-beginning 0) pos)
20151 (>= (+ inc (match-end 0)) pos))
20152 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20154 (defun org-at-regexp-p (regexp)
20155 "Is point inside a match of REGEXP in the current line?"
20156 (catch 'exit
20157 (save-excursion
20158 (let ((pos (point)) (end (point-at-eol)))
20159 (beginning-of-line 1)
20160 (while (re-search-forward regexp end t)
20161 (if (and (<= (match-beginning 0) pos)
20162 (>= (match-end 0) pos))
20163 (throw 'exit t)))
20164 nil))))
20166 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20167 "Non-nil when point is between matches of START-RE and END-RE.
20169 Also return a non-nil value when point is on one of the matches.
20171 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20172 buffer positions. Default values are the positions of headlines
20173 surrounding the point.
20175 The functions returns a cons cell whose car (resp. cdr) is the
20176 position before START-RE (resp. after END-RE)."
20177 (save-match-data
20178 (let ((pos (point))
20179 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20180 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20181 beg end)
20182 (save-excursion
20183 ;; Point is on a block when on START-RE or if START-RE can be
20184 ;; found before it...
20185 (and (or (org-at-regexp-p start-re)
20186 (re-search-backward start-re limit-up t))
20187 (setq beg (match-beginning 0))
20188 ;; ... and END-RE after it...
20189 (goto-char (match-end 0))
20190 (re-search-forward end-re limit-down t)
20191 (> (setq end (match-end 0)) pos)
20192 ;; ... without another START-RE in-between.
20193 (goto-char (match-beginning 0))
20194 (not (re-search-backward start-re (1+ beg) t))
20195 ;; Return value.
20196 (cons beg end))))))
20198 (defun org-in-block-p (names)
20199 "Non-nil when point belongs to a block whose name belongs to NAMES.
20201 NAMES is a list of strings containing names of blocks.
20203 Return first block name matched, or nil. Beware that in case of
20204 nested blocks, the returned name may not belong to the closest
20205 block from point."
20206 (save-match-data
20207 (catch 'exit
20208 (let ((case-fold-search t)
20209 (lim-up (save-excursion (outline-previous-heading)))
20210 (lim-down (save-excursion (outline-next-heading))))
20211 (mapc (lambda (name)
20212 (let ((n (regexp-quote name)))
20213 (when (org-between-regexps-p
20214 (concat "^[ \t]*#\\+begin_" n)
20215 (concat "^[ \t]*#\\+end_" n)
20216 lim-up lim-down)
20217 (throw 'exit n))))
20218 names))
20219 nil)))
20221 (defun org-occur-in-agenda-files (regexp &optional nlines)
20222 "Call `multi-occur' with buffers for all agenda files."
20223 (interactive "sOrg-files matching: \np")
20224 (let* ((files (org-agenda-files))
20225 (tnames (mapcar 'file-truename files))
20226 (extra org-agenda-text-search-extra-files)
20228 (when (eq (car extra) 'agenda-archives)
20229 (setq extra (cdr extra))
20230 (setq files (org-add-archive-files files)))
20231 (while (setq f (pop extra))
20232 (unless (member (file-truename f) tnames)
20233 (add-to-list 'files f 'append)
20234 (add-to-list 'tnames (file-truename f) 'append)))
20235 (multi-occur
20236 (mapcar (lambda (x)
20237 (with-current-buffer
20238 (or (get-file-buffer x) (find-file-noselect x))
20239 (widen)
20240 (current-buffer)))
20241 files)
20242 regexp)))
20244 (if (boundp 'occur-mode-find-occurrence-hook)
20245 ;; Emacs 23
20246 (add-hook 'occur-mode-find-occurrence-hook
20247 (lambda ()
20248 (when (derived-mode-p 'org-mode)
20249 (org-reveal))))
20250 ;; Emacs 22
20251 (defadvice occur-mode-goto-occurrence
20252 (after org-occur-reveal activate)
20253 (and (derived-mode-p 'org-mode) (org-reveal)))
20254 (defadvice occur-mode-goto-occurrence-other-window
20255 (after org-occur-reveal activate)
20256 (and (derived-mode-p 'org-mode) (org-reveal)))
20257 (defadvice occur-mode-display-occurrence
20258 (after org-occur-reveal activate)
20259 (when (derived-mode-p 'org-mode)
20260 (let ((pos (occur-mode-find-occurrence)))
20261 (with-current-buffer (marker-buffer pos)
20262 (save-excursion
20263 (goto-char pos)
20264 (org-reveal)))))))
20266 (defun org-occur-link-in-agenda-files ()
20267 "Create a link and search for it in the agendas.
20268 The link is not stored in `org-stored-links', it is just created
20269 for the search purpose."
20270 (interactive)
20271 (let ((link (condition-case nil
20272 (org-store-link nil)
20273 (error "Unable to create a link to here"))))
20274 (org-occur-in-agenda-files (regexp-quote link))))
20276 (defun org-uniquify (list)
20277 "Remove duplicate elements from LIST."
20278 (let (res)
20279 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20280 res))
20282 (defun org-delete-all (elts list)
20283 "Remove all elements in ELTS from LIST."
20284 (while elts
20285 (setq list (delete (pop elts) list)))
20286 list)
20288 (defun org-count (cl-item cl-seq)
20289 "Count the number of occurrences of ITEM in SEQ.
20290 Taken from `count' in cl-seq.el with all keyword arguments removed."
20291 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20292 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20293 (while (< cl-start cl-end)
20294 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20295 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20296 (setq cl-start (1+ cl-start)))
20297 cl-count))
20299 (defun org-remove-if (predicate seq)
20300 "Remove everything from SEQ that fulfills PREDICATE."
20301 (let (res e)
20302 (while seq
20303 (setq e (pop seq))
20304 (if (not (funcall predicate e)) (push e res)))
20305 (nreverse res)))
20307 (defun org-remove-if-not (predicate seq)
20308 "Remove everything from SEQ that does not fulfill PREDICATE."
20309 (let (res e)
20310 (while seq
20311 (setq e (pop seq))
20312 (if (funcall predicate e) (push e res)))
20313 (nreverse res)))
20315 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20316 "Reduce two-argument FUNCTION across SEQ.
20317 Taken from `reduce' in cl-seq.el with all keyword arguments but
20318 \":initial-value\" removed."
20319 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20320 (cadr (memq :initial-value cl-keys)))
20321 (cl-seq (pop cl-seq))
20322 (t (funcall cl-func)))))
20323 (while cl-seq
20324 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20325 cl-accum))
20327 (defun org-back-over-empty-lines ()
20328 "Move backwards over whitespace, to the beginning of the first empty line.
20329 Returns the number of empty lines passed."
20330 (let ((pos (point)))
20331 (if (cdr (assoc 'heading org-blank-before-new-entry))
20332 (skip-chars-backward " \t\n\r")
20333 (unless (eobp)
20334 (forward-line -1)))
20335 (beginning-of-line 2)
20336 (goto-char (min (point) pos))
20337 (count-lines (point) pos)))
20339 (defun org-skip-whitespace ()
20340 (skip-chars-forward " \t\n\r"))
20342 (defun org-point-in-group (point group &optional context)
20343 "Check if POINT is in match-group GROUP.
20344 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20345 match. If the match group does not exist or point is not inside it,
20346 return nil."
20347 (and (match-beginning group)
20348 (>= point (match-beginning group))
20349 (<= point (match-end group))
20350 (if context
20351 (list context (match-beginning group) (match-end group))
20352 t)))
20354 (defun org-switch-to-buffer-other-window (&rest args)
20355 "Switch to buffer in a second window on the current frame.
20356 In particular, do not allow pop-up frames.
20357 Returns the newly created buffer."
20358 (let (pop-up-frames special-display-buffer-names special-display-regexps
20359 special-display-function)
20360 (apply 'switch-to-buffer-other-window args)))
20362 (defun org-combine-plists (&rest plists)
20363 "Create a single property list from all plists in PLISTS.
20364 The process starts by copying the first list, and then setting properties
20365 from the other lists. Settings in the last list are the most significant
20366 ones and overrule settings in the other lists."
20367 (let ((rtn (copy-sequence (pop plists)))
20368 p v ls)
20369 (while plists
20370 (setq ls (pop plists))
20371 (while ls
20372 (setq p (pop ls) v (pop ls))
20373 (setq rtn (plist-put rtn p v))))
20374 rtn))
20376 (defun org-replace-escapes (string table)
20377 "Replace %-escapes in STRING with values in TABLE.
20378 TABLE is an association list with keys like \"%a\" and string values.
20379 The sequences in STRING may contain normal field width and padding information,
20380 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20381 so values can contain further %-escapes if they are define later in TABLE."
20382 (let ((tbl (copy-alist table))
20383 (case-fold-search nil)
20384 (pchg 0)
20385 e re rpl)
20386 (while (setq e (pop tbl))
20387 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20388 (when (and (cdr e) (string-match re (cdr e)))
20389 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20390 (safe "SREF"))
20391 (add-text-properties 0 3 (list 'sref sref) safe)
20392 (setcdr e (replace-match safe t t (cdr e)))))
20393 (while (string-match re string)
20394 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20395 (cdr e)))
20396 (setq string (replace-match rpl t t string))))
20397 (while (setq pchg (next-property-change pchg string))
20398 (let ((sref (get-text-property pchg 'sref string)))
20399 (when (and sref (string-match "SREF" string pchg))
20400 (setq string (replace-match sref t t string)))))
20401 string))
20403 (defun org-sublist (list start end)
20404 "Return a section of LIST, from START to END.
20405 Counting starts at 1."
20406 (let (rtn (c start))
20407 (setq list (nthcdr (1- start) list))
20408 (while (and list (<= c end))
20409 (push (pop list) rtn)
20410 (setq c (1+ c)))
20411 (nreverse rtn)))
20413 (defun org-find-base-buffer-visiting (file)
20414 "Like `find-buffer-visiting' but always return the base buffer and
20415 not an indirect buffer."
20416 (let ((buf (or (get-file-buffer file)
20417 (find-buffer-visiting file))))
20418 (if buf
20419 (or (buffer-base-buffer buf) buf)
20420 nil)))
20422 (defun org-image-file-name-regexp (&optional extensions)
20423 "Return regexp matching the file names of images.
20424 If EXTENSIONS is given, only match these."
20425 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20426 (image-file-name-regexp)
20427 (let ((image-file-name-extensions
20428 (or extensions
20429 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20430 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20431 (concat "\\."
20432 (regexp-opt (nconc (mapcar 'upcase
20433 image-file-name-extensions)
20434 image-file-name-extensions)
20436 "\\'"))))
20438 (defun org-file-image-p (file &optional extensions)
20439 "Return non-nil if FILE is an image."
20440 (save-match-data
20441 (string-match (org-image-file-name-regexp extensions) file)))
20443 (defun org-get-cursor-date ()
20444 "Return the date at cursor in as a time.
20445 This works in the calendar and in the agenda, anywhere else it just
20446 returns the current time."
20447 (let (date day defd)
20448 (cond
20449 ((eq major-mode 'calendar-mode)
20450 (setq date (calendar-cursor-to-date)
20451 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20452 ((eq major-mode 'org-agenda-mode)
20453 (setq day (get-text-property (point) 'day))
20454 (if day
20455 (setq date (calendar-gregorian-from-absolute day)
20456 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20457 (nth 2 date))))))
20458 (or defd (current-time))))
20460 (defvar org-agenda-action-marker (make-marker)
20461 "Marker pointing to the entry for the next agenda action.")
20463 (defun org-mark-entry-for-agenda-action ()
20464 "Mark the current entry as target of an agenda action.
20465 Agenda actions are actions executed from the agenda with the key `k',
20466 which make use of the date at the cursor."
20467 (interactive)
20468 (move-marker org-agenda-action-marker
20469 (save-excursion (org-back-to-heading t) (point))
20470 (current-buffer))
20471 (message
20472 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20474 (defun org-mark-subtree ()
20475 "Mark the current subtree.
20476 This puts point at the start of the current subtree, and mark at the end.
20478 If point is in an inline task, mark that task instead."
20479 (interactive)
20480 (let ((inline-task-p
20481 (and (featurep 'org-inlinetask)
20482 (org-inlinetask-in-task-p)))
20483 (beg))
20484 ;; Get beginning of subtree
20485 (cond
20486 (inline-task-p (org-inlinetask-goto-beginning))
20487 ((org-at-heading-p) (beginning-of-line))
20488 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20489 (setq beg (point))
20490 ;; Get end of it
20491 (if inline-task-p
20492 (org-inlinetask-goto-end)
20493 (org-end-of-subtree))
20494 ;; Mark zone
20495 (push-mark (point) nil t)
20496 (goto-char beg)))
20498 ;;; Paragraph filling stuff.
20499 ;; We want this to be just right, so use the full arsenal.
20501 (defun org-indent-line ()
20502 "Indent line depending on context."
20503 (interactive)
20504 (let* ((pos (point))
20505 (itemp (org-at-item-p))
20506 (case-fold-search t)
20507 (org-drawer-regexp (or org-drawer-regexp "\000"))
20508 (inline-task-p (and (featurep 'org-inlinetask)
20509 (org-inlinetask-in-task-p)))
20510 (inline-re (and inline-task-p
20511 (org-inlinetask-outline-regexp)))
20512 column)
20513 (beginning-of-line 1)
20514 (cond
20515 ;; Comments
20516 ((looking-at "# ") (setq column 0))
20517 ;; Headings
20518 ((looking-at org-outline-regexp) (setq column 0))
20519 ;; Included files
20520 ((looking-at "#\\+include:") (setq column 0))
20521 ;; Footnote definition
20522 ((looking-at org-footnote-definition-re) (setq column 0))
20523 ;; Literal examples
20524 ((looking-at "[ \t]*:\\( \\|$\\)")
20525 (setq column (org-get-indentation))) ; do nothing
20526 ;; Lists
20527 ((ignore-errors (goto-char (org-in-item-p)))
20528 (setq column (if itemp
20529 (org-get-indentation)
20530 (org-list-item-body-column (point))))
20531 (goto-char pos))
20532 ;; Drawers
20533 ((and (looking-at "[ \t]*:END:")
20534 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20535 (save-excursion
20536 (goto-char (1- (match-beginning 1)))
20537 (setq column (current-column))))
20538 ;; Special blocks
20539 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20540 (save-excursion
20541 (re-search-backward
20542 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20543 (setq column (org-get-indentation (match-string 0))))
20544 ((and (not (looking-at "[ \t]*#\\+begin_"))
20545 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20546 (save-excursion
20547 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20548 (setq column
20549 (cond ((equal (downcase (match-string 1)) "src")
20550 ;; src blocks: let `org-edit-src-exit' handle them
20551 (org-get-indentation))
20552 ((equal (downcase (match-string 1)) "example")
20553 (max (org-get-indentation)
20554 (org-get-indentation (match-string 0))))
20556 (org-get-indentation (match-string 0))))))
20557 ;; This line has nothing special, look at the previous relevant
20558 ;; line to compute indentation
20560 (beginning-of-line 0)
20561 (while (and (not (bobp))
20562 (not (looking-at org-drawer-regexp))
20563 ;; When point started in an inline task, do not move
20564 ;; above task starting line.
20565 (not (and inline-task-p (looking-at inline-re)))
20566 ;; Skip drawers, blocks, empty lines, verbatim,
20567 ;; comments, tables, footnotes definitions, lists,
20568 ;; inline tasks.
20569 (or (and (looking-at "[ \t]*:END:")
20570 (re-search-backward org-drawer-regexp nil t))
20571 (and (looking-at "[ \t]*#\\+end_")
20572 (re-search-backward "[ \t]*#\\+begin_"nil t))
20573 (looking-at "[ \t]*[\n:#|]")
20574 (looking-at org-footnote-definition-re)
20575 (and (ignore-errors (goto-char (org-in-item-p)))
20576 (goto-char
20577 (org-list-get-top-point (org-list-struct))))
20578 (and (not inline-task-p)
20579 (featurep 'org-inlinetask)
20580 (org-inlinetask-in-task-p)
20581 (or (org-inlinetask-goto-beginning) t))))
20582 (beginning-of-line 0))
20583 (cond
20584 ;; There was an heading above.
20585 ((looking-at "\\*+[ \t]+")
20586 (if (not org-adapt-indentation)
20587 (setq column 0)
20588 (goto-char (match-end 0))
20589 (setq column (current-column))))
20590 ;; A drawer had started and is unfinished
20591 ((looking-at org-drawer-regexp)
20592 (goto-char (1- (match-beginning 1)))
20593 (setq column (current-column)))
20594 ;; Else, nothing noticeable found: get indentation and go on.
20595 (t (setq column (org-get-indentation))))))
20596 ;; Now apply indentation and move cursor accordingly
20597 (goto-char pos)
20598 (if (<= (current-column) (current-indentation))
20599 (org-indent-line-to column)
20600 (save-excursion (org-indent-line-to column)))
20601 ;; Special polishing for properties, see `org-property-format'
20602 (setq column (current-column))
20603 (beginning-of-line 1)
20604 (if (looking-at
20605 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20606 (replace-match (concat (match-string 1)
20607 (format org-property-format
20608 (match-string 2) (match-string 3)))
20609 t t))
20610 (org-move-to-column column)
20611 (when (and orgstruct-is-++ (eq pos (point)))
20612 (org-let org-fb-vars
20613 '(indent-according-to-mode)))))
20615 (defun org-indent-drawer ()
20616 "Indent the drawer at point."
20617 (interactive)
20618 (let ((p (point))
20619 (e (and (save-excursion (re-search-forward ":END:" nil t))
20620 (match-end 0)))
20621 (folded
20622 (save-excursion
20623 (end-of-line)
20624 (when (overlays-at (point))
20625 (member 'invisible (overlay-properties
20626 (car (overlays-at (point)))))))))
20627 (when folded (org-cycle))
20628 (indent-for-tab-command)
20629 (while (and (move-beginning-of-line 2) (< (point) e))
20630 (indent-for-tab-command))
20631 (goto-char p)
20632 (when folded (org-cycle)))
20633 (message "Drawer at point indented"))
20635 (defun org-indent-block ()
20636 "Indent the block at point."
20637 (interactive)
20638 (let ((p (point))
20639 (case-fold-search t)
20640 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20641 (match-end 0)))
20642 (folded
20643 (save-excursion
20644 (end-of-line)
20645 (when (overlays-at (point))
20646 (member 'invisible (overlay-properties
20647 (car (overlays-at (point)))))))))
20648 (when folded (org-cycle))
20649 (indent-for-tab-command)
20650 (while (and (move-beginning-of-line 2) (< (point) e))
20651 (indent-for-tab-command))
20652 (goto-char p)
20653 (when folded (org-cycle)))
20654 (message "Block at point indented"))
20656 (defun org-indent-region (start end)
20657 "Indent region."
20658 (interactive "r")
20659 (save-excursion
20660 (let ((line-end (org-current-line end)))
20661 (goto-char start)
20662 (while (< (org-current-line) line-end)
20663 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20664 (t (call-interactively 'org-indent-line)))
20665 (move-beginning-of-line 2)))))
20667 ;; For reference, this is the default value of adaptive-fill-regexp
20668 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20669 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20670 "Variable to store copy of `adaptive-fill-regexp'.
20671 Since `adaptive-fill-regexp' is set to never match, we need to
20672 store a backup of its value before entering `org-mode' so that
20673 the functionality can be provided as a fall-back.")
20675 (defun org-set-autofill-regexps ()
20676 (interactive)
20677 ;; In the paragraph separator we include headlines, because filling
20678 ;; text in a line directly attached to a headline would otherwise
20679 ;; fill the headline as well.
20680 (org-set-local 'comment-start-skip "^#+[ \t]*")
20681 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20682 ;; The paragraph starter includes hand-formatted lists.
20683 (org-set-local
20684 'paragraph-start
20685 (concat
20686 "\f" "\\|"
20687 "[ ]*$" "\\|"
20688 org-outline-regexp "\\|"
20689 "[ \t]*#" "\\|"
20690 (org-item-re) "\\|"
20691 "[ \t]*[:|]" "\\|"
20692 "\\$\\$" "\\|"
20693 "\\\\\\(begin\\|end\\|[][]\\)"))
20694 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20695 ;; But only if the user has not turned off tables or fixed-width regions
20696 (org-set-local
20697 'auto-fill-inhibit-regexp
20698 (concat org-outline-regexp
20699 "\\|#\\+"
20700 "\\|[ \t]*" org-keyword-time-regexp
20701 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20702 (concat
20703 "\\|[ \t]*["
20704 (if org-enable-table-editor "|" "")
20705 (if org-enable-fixed-width-editor ":" "")
20706 "]"))))
20707 ;; We use our own fill-paragraph function, to make sure that tables
20708 ;; and fixed-width regions are not wrapped. That function will pass
20709 ;; through to `fill-paragraph' when appropriate.
20710 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20711 ;; Prevent auto-fill from inserting unwanted new items.
20712 (if (boundp 'fill-nobreak-predicate)
20713 (org-set-local
20714 'fill-nobreak-predicate
20715 (org-uniquify
20716 (append fill-nobreak-predicate
20717 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20718 ;; Adaptive filling: To get full control, first make sure that
20719 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20720 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20721 (org-set-local 'org-adaptive-fill-regexp-backup
20722 adaptive-fill-regexp))
20723 (org-set-local 'adaptive-fill-regexp "\000")
20724 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20725 (org-set-local 'adaptive-fill-function
20726 'org-adaptive-fill-function)
20727 (org-set-local
20728 'align-mode-rules-list
20729 '((org-in-buffer-settings
20730 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20731 (modes . '(org-mode))))))
20733 (defun org-fill-item-nobreak-p ()
20734 "Non-nil when a line break at point would insert a new item."
20735 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20737 (defun org-fill-line-break-nobreak-p ()
20738 "Non-nil when a line break at point would create an Org line break."
20739 (save-excursion
20740 (skip-chars-backward "[ \t]")
20741 (skip-chars-backward "\\\\")
20742 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20744 (defun org-fill-paragraph (&optional justify)
20745 "Re-align a table, pass through to fill-paragraph if no table."
20746 (let ((table-p (org-at-table-p))
20747 (table.el-p (org-at-table.el-p))
20748 (itemp (org-in-item-p))
20749 (srcp (org-in-src-block-p)))
20750 (cond ((and (equal (char-after (point-at-bol)) ?*)
20751 (save-excursion (goto-char (point-at-bol))
20752 (looking-at org-outline-regexp)))
20753 t) ; skip headlines
20754 (table.el-p t) ; skip table.el tables
20755 (table-p (org-table-align) t) ; align Org tables
20756 (srcp ; indent entire src block to prevent
20757 (save-excursion ; fill-paragraph-as-region to mess up
20758 (org-babel-do-in-edit-buffer
20759 (indent-region (point-min) (point-max)))))
20760 (itemp ; align text in items
20761 (let* ((struct (save-excursion (goto-char itemp)
20762 (org-list-struct)))
20763 (parents (org-list-parents-alist struct))
20764 (children (org-list-get-children itemp struct parents))
20765 beg end prev next prefix)
20766 ;; Determine in which part of item point is: before
20767 ;; first child, after last child, between two
20768 ;; sub-lists, or simply in item if there's no child.
20769 (cond
20770 ((not children)
20771 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20772 beg itemp
20773 end (org-list-get-item-end itemp struct)))
20774 ((< (point) (setq next (car children)))
20775 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20776 beg itemp
20777 end next))
20778 ((> (point) (setq prev (car (last children))))
20779 (setq beg (org-list-get-item-end prev struct)
20780 end (org-list-get-item-end itemp struct)
20781 prefix (save-excursion
20782 (goto-char beg)
20783 (skip-chars-forward " \t")
20784 (make-string (current-column) ?\ ))))
20785 (t (catch 'exit
20786 (while (setq next (pop children))
20787 (if (> (point) next)
20788 (setq prev next)
20789 (setq beg (org-list-get-item-end prev struct)
20790 end next
20791 prefix (save-excursion
20792 (goto-char beg)
20793 (skip-chars-forward " \t")
20794 (make-string (current-column) ?\ )))
20795 (throw 'exit nil))))))
20796 ;; Use `fill-paragraph' with buffer narrowed to item
20797 ;; without any child, and with our computed PREFIX.
20798 (flet ((fill-context-prefix (from to &optional flr) prefix))
20799 (save-restriction
20800 (narrow-to-region beg end)
20801 (save-excursion (fill-paragraph justify)))) t))
20802 ;; Special case where point is not in a list but is on
20803 ;; a paragraph adjacent to a list: make sure this paragraph
20804 ;; doesn't get merged with the end of the list by narrowing
20805 ;; buffer first.
20806 ((and (derived-mode-p 'org-mode)
20807 (save-excursion (forward-paragraph -1)
20808 (setq itemp (org-in-item-p))))
20809 (let ((struct (save-excursion (goto-char itemp)
20810 (org-list-struct))))
20811 (save-restriction
20812 (narrow-to-region (org-list-get-bottom-point struct)
20813 (save-excursion (forward-paragraph 1)
20814 (point)))
20815 (fill-paragraph justify) t)))
20816 ;; Don't fill schedule/deadline line before a paragraph
20817 ;; This only makes sense in real org-mode buffers
20818 ((and (eq major-mode 'org-mode)
20819 (save-excursion (forward-paragraph -1)
20820 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20821 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$")))))
20822 (save-restriction
20823 (narrow-to-region (1+ (match-end 0))
20824 (save-excursion (forward-paragraph 1) (point)))
20825 (fill-paragraph justify) t))
20826 ;; Else fall back on fill-paragraph-function as possibly
20827 ;; defined in `org-fb-vars'
20828 (orgstruct-is-++
20829 (org-let org-fb-vars
20830 '(fill-paragraph justify)))
20831 (t nil))))
20833 (defun org-adaptive-fill-function ()
20834 "Return a fill prefix for org-mode files."
20835 (let (itemp)
20836 (save-excursion
20837 (cond
20838 ;; Comment line
20839 ((looking-at "#[ \t]+")
20840 (match-string-no-properties 0))
20841 ;; Plain list item
20842 ((org-at-item-p)
20843 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20844 ;; Point is in a list after `backward-paragraph': original
20845 ;; point wasn't in the list, or filling would have been taken
20846 ;; care of by `org-auto-fill-function', but the list and the
20847 ;; real paragraph are not separated by a blank line. Thus, move
20848 ;; point after the list to go back to real paragraph and
20849 ;; determine fill-prefix.
20850 ((setq itemp (org-in-item-p))
20851 (goto-char itemp)
20852 (let* ((struct (org-list-struct))
20853 (bottom (org-list-get-bottom-point struct)))
20854 (goto-char bottom)
20855 (make-string (org-get-indentation) ?\ )))
20856 ;; Other text
20857 ((looking-at org-adaptive-fill-regexp-backup)
20858 (match-string-no-properties 0))))))
20860 (defun org-auto-fill-function ()
20861 "Auto-fill function."
20862 (unless (and org-src-prevent-auto-filling (org-in-src-block-p))
20863 (let (itemp prefix)
20864 ;; When in a list, compute an appropriate fill-prefix and make
20865 ;; sure it will be used by `do-auto-fill'.
20866 (cond ((setq itemp (org-in-item-p))
20867 (progn
20868 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20869 (flet ((fill-context-prefix (from to &optional flr) prefix))
20870 (do-auto-fill))))
20871 (orgstruct-is-++
20872 (org-let org-fb-vars
20873 '(do-auto-fill)))
20874 (t (do-auto-fill))))))
20876 ;;; Other stuff.
20878 (defun org-toggle-fixed-width-section (arg)
20879 "Toggle the fixed-width export.
20880 If there is no active region, the QUOTE keyword at the current headline is
20881 inserted or removed. When present, it causes the text between this headline
20882 and the next to be exported as fixed-width text, and unmodified.
20883 If there is an active region, this command adds or removes a colon as the
20884 first character of this line. If the first character of a line is a colon,
20885 this line is also exported in fixed-width font."
20886 (interactive "P")
20887 (let* ((cc 0)
20888 (regionp (org-region-active-p))
20889 (beg (if regionp (region-beginning) (point)))
20890 (end (if regionp (region-end)))
20891 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20892 (case-fold-search nil)
20893 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20894 off)
20895 (if regionp
20896 (save-excursion
20897 (goto-char beg)
20898 (setq cc (current-column))
20899 (beginning-of-line 1)
20900 (setq off (looking-at re))
20901 (while (> nlines 0)
20902 (setq nlines (1- nlines))
20903 (beginning-of-line 1)
20904 (cond
20905 (arg
20906 (org-move-to-column cc t)
20907 (insert ": \n")
20908 (forward-line -1))
20909 ((and off (looking-at re))
20910 (replace-match "" t t nil 1))
20911 ((not off) (org-move-to-column cc t) (insert ": ")))
20912 (forward-line 1)))
20913 (save-excursion
20914 (org-back-to-heading)
20915 (cond
20916 ((looking-at (format org-heading-keyword-regexp-format
20917 org-quote-string))
20918 (goto-char (match-end 1))
20919 (looking-at (concat " +" org-quote-string))
20920 (replace-match "" t t)
20921 (when (eolp) (insert " ")))
20922 ((looking-at org-outline-regexp)
20923 (goto-char (match-end 0))
20924 (insert org-quote-string " ")))))))
20926 (defun org-reftex-citation ()
20927 "Use reftex-citation to insert a citation into the buffer.
20928 This looks for a line like
20930 #+BIBLIOGRAPHY: foo plain option:-d
20932 and derives from it that foo.bib is the bibliography file relevant
20933 for this document. It then installs the necessary environment for RefTeX
20934 to work in this buffer and calls `reftex-citation' to insert a citation
20935 into the buffer.
20937 Export of such citations to both LaTeX and HTML is handled by the contributed
20938 package org-exp-bibtex by Taru Karttunen."
20939 (interactive)
20940 (let ((reftex-docstruct-symbol 'rds)
20941 (reftex-cite-format "\\cite{%l}")
20942 rds bib)
20943 (save-excursion
20944 (save-restriction
20945 (widen)
20946 (let ((case-fold-search t)
20947 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20948 (if (not (save-excursion
20949 (or (re-search-forward re nil t)
20950 (re-search-backward re nil t))))
20951 (error "No bibliography defined in file")
20952 (setq bib (concat (match-string 1) ".bib")
20953 rds (list (list 'bib bib)))))))
20954 (call-interactively 'reftex-citation)))
20956 ;;;; Functions extending outline functionality
20958 (defun org-beginning-of-line (&optional arg)
20959 "Go to the beginning of the current line. If that is invisible, continue
20960 to a visible line beginning. This makes the function of C-a more intuitive.
20961 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20962 first attempt, and only move to after the tags when the cursor is already
20963 beyond the end of the headline."
20964 (interactive "P")
20965 (let ((pos (point))
20966 (special (if (consp org-special-ctrl-a/e)
20967 (car org-special-ctrl-a/e)
20968 org-special-ctrl-a/e))
20969 refpos)
20970 (if (org-bound-and-true-p line-move-visual)
20971 (beginning-of-visual-line 1)
20972 (beginning-of-line 1))
20973 (if (and arg (fboundp 'move-beginning-of-line))
20974 (call-interactively 'move-beginning-of-line)
20975 (if (bobp)
20977 (backward-char 1)
20978 (if (org-truely-invisible-p)
20979 (while (and (not (bobp)) (org-truely-invisible-p))
20980 (backward-char 1)
20981 (beginning-of-line 1))
20982 (forward-char 1))))
20983 (when special
20984 (cond
20985 ((and (looking-at org-complex-heading-regexp)
20986 (= (char-after (match-end 1)) ?\ ))
20987 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20988 (point-at-eol)))
20989 (goto-char
20990 (if (eq special t)
20991 (cond ((> pos refpos) refpos)
20992 ((= pos (point)) refpos)
20993 (t (point)))
20994 (cond ((> pos (point)) (point))
20995 ((not (eq last-command this-command)) (point))
20996 (t refpos)))))
20997 ((org-at-item-p)
20998 ;; Being at an item and not looking at an the item means point
20999 ;; was previously moved to beginning of a visual line, which
21000 ;; doesn't contain the item. Therefore, do nothing special,
21001 ;; just stay here.
21002 (when (looking-at org-list-full-item-re)
21003 ;; Set special position at first white space character after
21004 ;; bullet, and check-box, if any.
21005 (let ((after-bullet
21006 (let ((box (match-end 3)))
21007 (if (not box) (match-end 1)
21008 (let ((after (char-after box)))
21009 (if (and after (= after ? )) (1+ box) box))))))
21010 ;; Special case: Move point to special position when
21011 ;; currently after it or at beginning of line.
21012 (if (eq special t)
21013 (when (or (> pos after-bullet) (= (point) pos))
21014 (goto-char after-bullet))
21015 ;; Reversed case: Move point to special position when
21016 ;; point was already at beginning of line and command is
21017 ;; repeated.
21018 (when (and (= (point) pos) (eq last-command this-command))
21019 (goto-char after-bullet))))))))
21020 (org-no-warnings
21021 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21023 (defun org-end-of-line (&optional arg)
21024 "Go to the end of the line.
21025 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21026 first attempt, and only move to after the tags when the cursor is already
21027 beyond the end of the headline."
21028 (interactive "P")
21029 (let ((special (if (consp org-special-ctrl-a/e)
21030 (cdr org-special-ctrl-a/e)
21031 org-special-ctrl-a/e)))
21032 (cond
21033 ((or (not special) arg
21034 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21035 (call-interactively
21036 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21037 ((fboundp 'move-end-of-line) 'move-end-of-line)
21038 (t 'end-of-line))))
21039 ((org-at-heading-p)
21040 (let ((pos (point)))
21041 (beginning-of-line 1)
21042 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21043 (if (eq special t)
21044 (if (or (< pos (match-beginning 1))
21045 (= pos (match-end 0)))
21046 (goto-char (match-beginning 1))
21047 (goto-char (match-end 0)))
21048 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21049 (goto-char (match-end 0))
21050 (goto-char (match-beginning 1))))
21051 (call-interactively (if (fboundp 'move-end-of-line)
21052 'move-end-of-line
21053 'end-of-line)))))
21054 ((org-at-drawer-p)
21055 (move-end-of-line 1)
21056 (when (overlays-at (1- (point))) (backward-char 1)))
21057 ;; At an item: Move before any hidden text.
21058 (t (call-interactively
21059 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21060 ((fboundp 'move-end-of-line) 'move-end-of-line)
21061 (t 'end-of-line)))))
21062 (org-no-warnings
21063 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21065 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21066 (define-key org-mode-map "\C-e" 'org-end-of-line)
21068 (defun org-backward-sentence (&optional arg)
21069 "Go to beginning of sentence, or beginning of table field.
21070 This will call `backward-sentence' or `org-table-beginning-of-field',
21071 depending on context."
21072 (interactive "P")
21073 (cond
21074 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21075 (t (call-interactively 'backward-sentence))))
21077 (defun org-forward-sentence (&optional arg)
21078 "Go to end of sentence, or end of table field.
21079 This will call `forward-sentence' or `org-table-end-of-field',
21080 depending on context."
21081 (interactive "P")
21082 (cond
21083 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21084 (t (call-interactively 'forward-sentence))))
21086 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21087 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21089 (defun org-kill-line (&optional arg)
21090 "Kill line, to tags or end of line."
21091 (interactive "P")
21092 (cond
21093 ((or (not org-special-ctrl-k)
21094 (bolp)
21095 (not (org-at-heading-p)))
21096 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21097 org-ctrl-k-protect-subtree)
21098 (if (or (eq org-ctrl-k-protect-subtree 'error)
21099 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21100 (error "C-k aborted - would kill hidden subtree")))
21101 (call-interactively
21102 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21103 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21104 (kill-region (point) (match-beginning 1))
21105 (org-set-tags nil t))
21106 (t (kill-region (point) (point-at-eol)))))
21108 (define-key org-mode-map "\C-k" 'org-kill-line)
21110 (defun org-yank (&optional arg)
21111 "Yank. If the kill is a subtree, treat it specially.
21112 This command will look at the current kill and check if is a single
21113 subtree, or a series of subtrees[1]. If it passes the test, and if the
21114 cursor is at the beginning of a line or after the stars of a currently
21115 empty headline, then the yank is handled specially. How exactly depends
21116 on the value of the following variables, both set by default.
21118 org-yank-folded-subtrees
21119 When set, the subtree(s) will be folded after insertion, but only
21120 if doing so would now swallow text after the yanked text.
21122 org-yank-adjusted-subtrees
21123 When set, the subtree will be promoted or demoted in order to
21124 fit into the local outline tree structure, which means that the level
21125 will be adjusted so that it becomes the smaller one of the two
21126 *visible* surrounding headings.
21128 Any prefix to this command will cause `yank' to be called directly with
21129 no special treatment. In particular, a simple \\[universal-argument] prefix \
21130 will just
21131 plainly yank the text as it is.
21133 \[1] The test checks if the first non-white line is a heading
21134 and if there are no other headings with fewer stars."
21135 (interactive "P")
21136 (org-yank-generic 'yank arg))
21138 (defun org-yank-generic (command arg)
21139 "Perform some yank-like command.
21141 This function implements the behavior described in the `org-yank'
21142 documentation. However, it has been generalized to work for any
21143 interactive command with similar behavior."
21145 ;; pretend to be command COMMAND
21146 (setq this-command command)
21148 (if arg
21149 (call-interactively command)
21151 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21152 (and (org-kill-is-subtree-p)
21153 (or (bolp)
21154 (and (looking-at "[ \t]*$")
21155 (string-match
21156 "\\`\\*+\\'"
21157 (buffer-substring (point-at-bol) (point)))))))
21158 swallowp)
21159 (cond
21160 ((and subtreep org-yank-folded-subtrees)
21161 (let ((beg (point))
21162 end)
21163 (if (and subtreep org-yank-adjusted-subtrees)
21164 (org-paste-subtree nil nil 'for-yank)
21165 (call-interactively command))
21167 (setq end (point))
21168 (goto-char beg)
21169 (when (and (bolp) subtreep
21170 (not (setq swallowp
21171 (org-yank-folding-would-swallow-text beg end))))
21172 (org-with-limited-levels
21173 (or (looking-at org-outline-regexp)
21174 (re-search-forward org-outline-regexp-bol end t))
21175 (while (and (< (point) end) (looking-at org-outline-regexp))
21176 (hide-subtree)
21177 (org-cycle-show-empty-lines 'folded)
21178 (condition-case nil
21179 (outline-forward-same-level 1)
21180 (error (goto-char end))))))
21181 (when swallowp
21182 (message
21183 "Inserted text not folded because that would swallow text"))
21185 (goto-char end)
21186 (skip-chars-forward " \t\n\r")
21187 (beginning-of-line 1)
21188 (push-mark beg 'nomsg)))
21189 ((and subtreep org-yank-adjusted-subtrees)
21190 (let ((beg (point-at-bol)))
21191 (org-paste-subtree nil nil 'for-yank)
21192 (push-mark beg 'nomsg)))
21194 (call-interactively command))))))
21196 (defun org-yank-folding-would-swallow-text (beg end)
21197 "Would hide-subtree at BEG swallow any text after END?"
21198 (let (level)
21199 (org-with-limited-levels
21200 (save-excursion
21201 (goto-char beg)
21202 (when (or (looking-at org-outline-regexp)
21203 (re-search-forward org-outline-regexp-bol end t))
21204 (setq level (org-outline-level)))
21205 (goto-char end)
21206 (skip-chars-forward " \t\r\n\v\f")
21207 (if (or (eobp)
21208 (and (bolp) (looking-at org-outline-regexp)
21209 (<= (org-outline-level) level)))
21210 nil ; Nothing would be swallowed
21211 t))))) ; something would swallow
21213 (define-key org-mode-map "\C-y" 'org-yank)
21215 (defun org-truely-invisible-p ()
21216 "Check if point is at a character currently not visible.
21217 This version does not only check the character property, but also
21218 `visible-mode'."
21219 ;; Early versions of noutline don't have `outline-invisible-p'.
21220 (if (org-bound-and-true-p visible-mode)
21222 (outline-invisible-p)))
21224 (defun org-invisible-p2 ()
21225 "Check if point is at a character currently not visible."
21226 (save-excursion
21227 (if (and (eolp) (not (bobp))) (backward-char 1))
21228 ;; Early versions of noutline don't have `outline-invisible-p'.
21229 (outline-invisible-p)))
21231 (defun org-back-to-heading (&optional invisible-ok)
21232 "Call `outline-back-to-heading', but provide a better error message."
21233 (condition-case nil
21234 (outline-back-to-heading invisible-ok)
21235 (error (error "Before first headline at position %d in buffer %s"
21236 (point) (current-buffer)))))
21238 (defun org-beginning-of-defun ()
21239 "Go to the beginning of the subtree, i.e. back to the heading."
21240 (org-back-to-heading))
21241 (defun org-end-of-defun ()
21242 "Go to the end of the subtree."
21243 (org-end-of-subtree nil t))
21245 (defun org-before-first-heading-p ()
21246 "Before first heading?"
21247 (save-excursion
21248 (end-of-line)
21249 (null (re-search-backward org-outline-regexp-bol nil t))))
21251 (defun org-at-heading-p (&optional ignored)
21252 (outline-on-heading-p t))
21253 ;; Compatibility alias with Org versions < 7.8.03
21254 (defalias 'org-on-heading-p 'org-at-heading-p)
21256 (defun org-at-comment-p nil
21257 "Is cursor in a line starting with a # character?"
21258 (save-excursion
21259 (beginning-of-line)
21260 (looking-at "^#")))
21262 (defun org-at-drawer-p nil
21263 "Is cursor at a drawer keyword?"
21264 (save-excursion
21265 (move-beginning-of-line 1)
21266 (looking-at org-drawer-regexp)))
21268 (defun org-at-block-p nil
21269 "Is cursor at a block keyword?"
21270 (save-excursion
21271 (move-beginning-of-line 1)
21272 (looking-at org-block-regexp)))
21274 (defun org-point-at-end-of-empty-headline ()
21275 "If point is at the end of an empty headline, return t, else nil.
21276 If the heading only contains a TODO keyword, it is still still considered
21277 empty."
21278 (and (looking-at "[ \t]*$")
21279 (when org-todo-line-regexp
21280 (save-excursion
21281 (beginning-of-line 1)
21282 (let ((case-fold-search nil))
21283 (looking-at org-todo-line-regexp)
21284 (string= (match-string 3) ""))))))
21286 (defun org-at-heading-or-item-p ()
21287 (or (org-at-heading-p) (org-at-item-p)))
21289 (defun org-at-target-p ()
21290 (or (org-in-regexp org-radio-target-regexp)
21291 (org-in-regexp org-target-regexp)))
21292 ;; Compatibility alias with Org versions < 7.8.03
21293 (defalias 'org-on-target-p 'org-at-target-p)
21295 (defun org-up-heading-all (arg)
21296 "Move to the heading line of which the present line is a subheading.
21297 This function considers both visible and invisible heading lines.
21298 With argument, move up ARG levels."
21299 (if (fboundp 'outline-up-heading-all)
21300 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21301 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21303 (defun org-up-heading-safe ()
21304 "Move to the heading line of which the present line is a subheading.
21305 This version will not throw an error. It will return the level of the
21306 headline found, or nil if no higher level is found.
21308 Also, this function will be a lot faster than `outline-up-heading',
21309 because it relies on stars being the outline starters. This can really
21310 make a significant difference in outlines with very many siblings."
21311 (let (start-level re)
21312 (org-back-to-heading t)
21313 (setq start-level (funcall outline-level))
21314 (if (equal start-level 1)
21316 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21317 (if (re-search-backward re nil t)
21318 (funcall outline-level)))))
21320 (defun org-first-sibling-p ()
21321 "Is this heading the first child of its parents?"
21322 (interactive)
21323 (let ((re org-outline-regexp-bol)
21324 level l)
21325 (unless (org-at-heading-p t)
21326 (error "Not at a heading"))
21327 (setq level (funcall outline-level))
21328 (save-excursion
21329 (if (not (re-search-backward re nil t))
21331 (setq l (funcall outline-level))
21332 (< l level)))))
21334 (defun org-goto-sibling (&optional previous)
21335 "Goto the next sibling, even if it is invisible.
21336 When PREVIOUS is set, go to the previous sibling instead. Returns t
21337 when a sibling was found. When none is found, return nil and don't
21338 move point."
21339 (let ((fun (if previous 're-search-backward 're-search-forward))
21340 (pos (point))
21341 (re org-outline-regexp-bol)
21342 level l)
21343 (when (condition-case nil (org-back-to-heading t) (error nil))
21344 (setq level (funcall outline-level))
21345 (catch 'exit
21346 (or previous (forward-char 1))
21347 (while (funcall fun re nil t)
21348 (setq l (funcall outline-level))
21349 (when (< l level) (goto-char pos) (throw 'exit nil))
21350 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21351 (goto-char pos)
21352 nil))))
21354 (defun org-show-siblings ()
21355 "Show all siblings of the current headline."
21356 (save-excursion
21357 (while (org-goto-sibling) (org-flag-heading nil)))
21358 (save-excursion
21359 (while (org-goto-sibling 'previous)
21360 (org-flag-heading nil))))
21362 (defun org-goto-first-child ()
21363 "Goto the first child, even if it is invisible.
21364 Return t when a child was found. Otherwise don't move point and
21365 return nil."
21366 (let (level (pos (point)) (re org-outline-regexp-bol))
21367 (when (condition-case nil (org-back-to-heading t) (error nil))
21368 (setq level (outline-level))
21369 (forward-char 1)
21370 (if (and (re-search-forward re nil t) (> (outline-level) level))
21371 (progn (goto-char (match-beginning 0)) t)
21372 (goto-char pos) nil))))
21374 (defun org-show-hidden-entry ()
21375 "Show an entry where even the heading is hidden."
21376 (save-excursion
21377 (org-show-entry)))
21379 (defun org-flag-heading (flag &optional entry)
21380 "Flag the current heading. FLAG non-nil means make invisible.
21381 When ENTRY is non-nil, show the entire entry."
21382 (save-excursion
21383 (org-back-to-heading t)
21384 ;; Check if we should show the entire entry
21385 (if entry
21386 (progn
21387 (org-show-entry)
21388 (save-excursion
21389 (and (outline-next-heading)
21390 (org-flag-heading nil))))
21391 (outline-flag-region (max (point-min) (1- (point)))
21392 (save-excursion (outline-end-of-heading) (point))
21393 flag))))
21395 (defun org-get-next-sibling ()
21396 "Move to next heading of the same level, and return point.
21397 If there is no such heading, return nil.
21398 This is like outline-next-sibling, but invisible headings are ok."
21399 (let ((level (funcall outline-level)))
21400 (outline-next-heading)
21401 (while (and (not (eobp)) (> (funcall outline-level) level))
21402 (outline-next-heading))
21403 (if (or (eobp) (< (funcall outline-level) level))
21405 (point))))
21407 (defun org-get-last-sibling ()
21408 "Move to previous heading of the same level, and return point.
21409 If there is no such heading, return nil."
21410 (let ((opoint (point))
21411 (level (funcall outline-level)))
21412 (outline-previous-heading)
21413 (when (and (/= (point) opoint) (outline-on-heading-p t))
21414 (while (and (> (funcall outline-level) level)
21415 (not (bobp)))
21416 (outline-previous-heading))
21417 (if (< (funcall outline-level) level)
21419 (point)))))
21421 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21422 ;; This contains an exact copy of the original function, but it uses
21423 ;; `org-back-to-heading', to make it work also in invisible
21424 ;; trees. And is uses an invisible-OK argument.
21425 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21426 ;; Furthermore, when used inside Org, finding the end of a large subtree
21427 ;; with many children and grandchildren etc, this can be much faster
21428 ;; than the outline version.
21429 (org-back-to-heading invisible-OK)
21430 (let ((first t)
21431 (level (funcall outline-level)))
21432 (if (and (derived-mode-p 'org-mode) (< level 1000))
21433 ;; A true heading (not a plain list item), in Org-mode
21434 ;; This means we can easily find the end by looking
21435 ;; only for the right number of stars. Using a regexp to do
21436 ;; this is so much faster than using a Lisp loop.
21437 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21438 (forward-char 1)
21439 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21440 ;; something else, do it the slow way
21441 (while (and (not (eobp))
21442 (or first (> (funcall outline-level) level)))
21443 (setq first nil)
21444 (outline-next-heading)))
21445 (unless to-heading
21446 (if (memq (preceding-char) '(?\n ?\^M))
21447 (progn
21448 ;; Go to end of line before heading
21449 (forward-char -1)
21450 (if (memq (preceding-char) '(?\n ?\^M))
21451 ;; leave blank line before heading
21452 (forward-char -1))))))
21453 (point))
21455 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21456 "Use Org version in org-mode, for dramatic speed-up."
21457 (if (derived-mode-p 'org-mode)
21458 (progn
21459 (org-end-of-subtree nil t)
21460 (unless (eobp) (backward-char 1)))
21461 ad-do-it))
21463 (defun org-end-of-meta-data-and-drawers ()
21464 "Jump to the first text after meta data and drawers in the current entry.
21465 This will move over empty lines, lines with planning time stamps,
21466 clocking lines, and drawers."
21467 (org-back-to-heading t)
21468 (let ((end (save-excursion (outline-next-heading) (point)))
21469 (re (concat "\\(" org-drawer-regexp "\\)"
21470 "\\|" "[ \t]*" org-keyword-time-regexp)))
21471 (forward-line 1)
21472 (while (re-search-forward re end t)
21473 (if (not (match-end 1))
21474 ;; empty or planning line
21475 (forward-line 1)
21476 ;; a drawer, find the end
21477 (re-search-forward "^[ \t]*:END:" end 'move)
21478 (forward-line 1)))
21479 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21480 (point)))
21482 (defun org-forward-same-level (arg &optional invisible-ok)
21483 "Move forward to the arg'th subheading at same level as this one.
21484 Stop at the first and last subheadings of a superior heading.
21485 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21486 it wil also look at invisible ones."
21487 (interactive "p")
21488 (org-back-to-heading invisible-ok)
21489 (org-at-heading-p)
21490 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21491 (re (format "^\\*\\{1,%d\\} " level))
21493 (forward-char 1)
21494 (while (> arg 0)
21495 (while (and (re-search-forward re nil 'move)
21496 (setq l (- (match-end 0) (match-beginning 0) 1))
21497 (= l level)
21498 (not invisible-ok)
21499 (progn (backward-char 1) (outline-invisible-p)))
21500 (if (< l level) (setq arg 1)))
21501 (setq arg (1- arg)))
21502 (beginning-of-line 1)))
21504 (defun org-backward-same-level (arg &optional invisible-ok)
21505 "Move backward to the arg'th subheading at same level as this one.
21506 Stop at the first and last subheadings of a superior heading."
21507 (interactive "p")
21508 (org-back-to-heading)
21509 (org-at-heading-p)
21510 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21511 (re (format "^\\*\\{1,%d\\} " level))
21513 (while (> arg 0)
21514 (while (and (re-search-backward re nil 'move)
21515 (setq l (- (match-end 0) (match-beginning 0) 1))
21516 (= l level)
21517 (not invisible-ok)
21518 (outline-invisible-p))
21519 (if (< l level) (setq arg 1)))
21520 (setq arg (1- arg)))))
21522 (defun org-show-subtree ()
21523 "Show everything after this heading at deeper levels."
21524 (interactive)
21525 (outline-flag-region
21526 (point)
21527 (save-excursion
21528 (org-end-of-subtree t t))
21529 nil))
21531 (defun org-show-entry ()
21532 "Show the body directly following this heading.
21533 Show the heading too, if it is currently invisible."
21534 (interactive)
21535 (save-excursion
21536 (condition-case nil
21537 (progn
21538 (org-back-to-heading t)
21539 (outline-flag-region
21540 (max (point-min) (1- (point)))
21541 (save-excursion
21542 (if (re-search-forward
21543 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21544 (match-beginning 1)
21545 (point-max)))
21546 nil)
21547 (org-cycle-hide-drawers 'children))
21548 (error nil))))
21550 (defun org-make-options-regexp (kwds &optional extra)
21551 "Make a regular expression for keyword lines."
21552 (concat
21554 "#?[ \t]*\\+\\("
21555 (mapconcat 'regexp-quote kwds "\\|")
21556 (if extra (concat "\\|" extra))
21557 "\\):[ \t]*"
21558 "\\(.*\\)"))
21560 ;; Make isearch reveal the necessary context
21561 (defun org-isearch-end ()
21562 "Reveal context after isearch exits."
21563 (when isearch-success ; only if search was successful
21564 (if (featurep 'xemacs)
21565 ;; Under XEmacs, the hook is run in the correct place,
21566 ;; we directly show the context.
21567 (org-show-context 'isearch)
21568 ;; In Emacs the hook runs *before* restoring the overlays.
21569 ;; So we have to use a one-time post-command-hook to do this.
21570 ;; (Emacs 22 has a special variable, see function `org-mode')
21571 (unless (and (boundp 'isearch-mode-end-hook-quit)
21572 isearch-mode-end-hook-quit)
21573 ;; Only when the isearch was not quitted.
21574 (org-add-hook 'post-command-hook 'org-isearch-post-command
21575 'append 'local)))))
21577 (defun org-isearch-post-command ()
21578 "Remove self from hook, and show context."
21579 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21580 (org-show-context 'isearch))
21583 ;;;; Integration with and fixes for other packages
21585 ;;; Imenu support
21587 (defvar org-imenu-markers nil
21588 "All markers currently used by Imenu.")
21589 (make-variable-buffer-local 'org-imenu-markers)
21591 (defun org-imenu-new-marker (&optional pos)
21592 "Return a new marker for use by Imenu, and remember the marker."
21593 (let ((m (make-marker)))
21594 (move-marker m (or pos (point)))
21595 (push m org-imenu-markers)
21598 (defun org-imenu-get-tree ()
21599 "Produce the index for Imenu."
21600 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21601 (setq org-imenu-markers nil)
21602 (let* ((n org-imenu-depth)
21603 (re (concat "^" (org-get-limited-outline-regexp)))
21604 (subs (make-vector (1+ n) nil))
21605 (last-level 0)
21606 m level head)
21607 (save-excursion
21608 (save-restriction
21609 (widen)
21610 (goto-char (point-max))
21611 (while (re-search-backward re nil t)
21612 (setq level (org-reduced-level (funcall outline-level)))
21613 (when (and (<= level n)
21614 (looking-at org-complex-heading-regexp))
21615 (setq head (org-link-display-format
21616 (org-match-string-no-properties 4))
21617 m (org-imenu-new-marker))
21618 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21619 (if (>= level last-level)
21620 (push (cons head m) (aref subs level))
21621 (push (cons head (aref subs (1+ level))) (aref subs level))
21622 (loop for i from (1+ level) to n do (aset subs i nil)))
21623 (setq last-level level)))))
21624 (aref subs 1)))
21626 (eval-after-load "imenu"
21627 '(progn
21628 (add-hook 'imenu-after-jump-hook
21629 (lambda ()
21630 (if (derived-mode-p 'org-mode)
21631 (org-show-context 'org-goto))))))
21633 (defun org-link-display-format (link)
21634 "Replace a link with either the description, or the link target
21635 if no description is present"
21636 (save-match-data
21637 (if (string-match org-bracket-link-analytic-regexp link)
21638 (replace-match (if (match-end 5)
21639 (match-string 5 link)
21640 (concat (match-string 1 link)
21641 (match-string 3 link)))
21642 nil t link)
21643 link)))
21645 (defun org-toggle-link-display ()
21646 "Toggle the literal or descriptive display of links."
21647 (interactive)
21648 (if org-descriptive-links
21649 (progn (org-remove-from-invisibility-spec '(org-link))
21650 (org-restart-font-lock)
21651 (setq org-descriptive-links nil))
21652 (progn (add-to-invisibility-spec '(org-link))
21653 (org-restart-font-lock)
21654 (setq org-descriptive-links t))))
21656 ;; Speedbar support
21658 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21659 "Overlay marking the agenda restriction line in speedbar.")
21660 (overlay-put org-speedbar-restriction-lock-overlay
21661 'face 'org-agenda-restriction-lock)
21662 (overlay-put org-speedbar-restriction-lock-overlay
21663 'help-echo "Agendas are currently limited to this item.")
21664 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21666 (defun org-speedbar-set-agenda-restriction ()
21667 "Restrict future agenda commands to the location at point in speedbar.
21668 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21669 (interactive)
21670 (require 'org-agenda)
21671 (let (p m tp np dir txt)
21672 (cond
21673 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21674 'org-imenu t))
21675 (setq m (get-text-property p 'org-imenu-marker))
21676 (with-current-buffer (marker-buffer m)
21677 (goto-char m)
21678 (org-agenda-set-restriction-lock 'subtree)))
21679 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21680 'speedbar-function 'speedbar-find-file))
21681 (setq tp (previous-single-property-change
21682 (1+ p) 'speedbar-function)
21683 np (next-single-property-change
21684 tp 'speedbar-function)
21685 dir (speedbar-line-directory)
21686 txt (buffer-substring-no-properties (or tp (point-min))
21687 (or np (point-max))))
21688 (with-current-buffer (find-file-noselect
21689 (let ((default-directory dir))
21690 (expand-file-name txt)))
21691 (unless (derived-mode-p 'org-mode)
21692 (error "Cannot restrict to non-Org-mode file"))
21693 (org-agenda-set-restriction-lock 'file)))
21694 (t (error "Don't know how to restrict Org-mode's agenda")))
21695 (move-overlay org-speedbar-restriction-lock-overlay
21696 (point-at-bol) (point-at-eol))
21697 (setq current-prefix-arg nil)
21698 (org-agenda-maybe-redo)))
21700 (eval-after-load "speedbar"
21701 '(progn
21702 (speedbar-add-supported-extension ".org")
21703 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21704 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21705 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21706 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21707 (add-hook 'speedbar-visiting-tag-hook
21708 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
21710 ;;; Fixes and Hacks for problems with other packages
21712 ;; Make flyspell not check words in links, to not mess up our keymap
21713 (defun org-mode-flyspell-verify ()
21714 "Don't let flyspell put overlays at active buttons, or on
21715 {todo,all-time,additional-option-like}-keywords."
21716 (let ((pos (max (1- (point)) (point-min)))
21717 (word (thing-at-point 'word)))
21718 (and (not (get-text-property pos 'keymap))
21719 (not (get-text-property pos 'org-no-flyspell))
21720 (not (member word org-todo-keywords-1))
21721 (not (member word org-all-time-keywords))
21722 (not (member word org-additional-option-like-keywords)))))
21724 (defun org-remove-flyspell-overlays-in (beg end)
21725 "Remove flyspell overlays in region."
21726 (and (org-bound-and-true-p flyspell-mode)
21727 (fboundp 'flyspell-delete-region-overlays)
21728 (flyspell-delete-region-overlays beg end))
21729 (add-text-properties beg end '(org-no-flyspell t)))
21731 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21732 (eval-after-load "bookmark"
21733 '(if (boundp 'bookmark-after-jump-hook)
21734 ;; We can use the hook
21735 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21736 ;; Hook not available, use advice
21737 (defadvice bookmark-jump (after org-make-visible activate)
21738 "Make the position visible."
21739 (org-bookmark-jump-unhide))))
21741 ;; Make sure saveplace shows the location if it was hidden
21742 (eval-after-load "saveplace"
21743 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21744 "Make the position visible."
21745 (org-bookmark-jump-unhide)))
21747 ;; Make sure ecb shows the location if it was hidden
21748 (eval-after-load "ecb"
21749 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21750 "Make hierarchy visible when jumping into location from ECB tree buffer."
21751 (if (derived-mode-p 'org-mode)
21752 (org-show-context))))
21754 (defun org-bookmark-jump-unhide ()
21755 "Unhide the current position, to show the bookmark location."
21756 (and (derived-mode-p 'org-mode)
21757 (or (outline-invisible-p)
21758 (save-excursion (goto-char (max (point-min) (1- (point))))
21759 (outline-invisible-p)))
21760 (org-show-context 'bookmark-jump)))
21762 ;; Make session.el ignore our circular variable
21763 (eval-after-load "session"
21764 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21766 ;;;; Experimental code
21768 (defun org-closed-in-range ()
21769 "Sparse tree of items closed in a certain time range.
21770 Still experimental, may disappear in the future."
21771 (interactive)
21772 ;; Get the time interval from the user.
21773 (let* ((time1 (org-float-time
21774 (org-read-date nil 'to-time nil "Starting date: ")))
21775 (time2 (org-float-time
21776 (org-read-date nil 'to-time nil "End date:")))
21777 ;; callback function
21778 (callback (lambda ()
21779 (let ((time
21780 (org-float-time
21781 (apply 'encode-time
21782 (org-parse-time-string
21783 (match-string 1))))))
21784 ;; check if time in interval
21785 (and (>= time time1) (<= time time2))))))
21786 ;; make tree, check each match with the callback
21787 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21789 ;;;; Finish up
21791 (provide 'org)
21793 (run-hooks 'org-load-hook)
21795 ;;; org.el ends here