Revert "org.el: (org-mode): Use `face-background' instead of `org-find-invisible...
[org-mode.git] / lisp / org.el
blobe8bfd2b66f1abb2bc0c08ea9c8075163014160a2
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 (let ((load-suffixes (list ".el")))
82 (load "org-loaddefs" 'noerror nil nil 'mustsuffix))
84 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
85 ;; some places -- e.g. see the macro org-with-limited-levels.
87 ;; In Org buffers, the value of `outline-regexp' is that of
88 ;; `org-outline-regexp'. The only function still directly relying on
89 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
90 ;; job when `orgstruct-mode' is active.
91 (defvar org-outline-regexp "\\*+ "
92 "Regexp to match Org headlines.")
94 (defvar org-outline-regexp-bol "^\\*+ "
95 "Regexp to match Org headlines.
96 This is similar to `org-outline-regexp' but additionally makes
97 sure that we are at the beginning of the line.")
99 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
100 "Matches an headline, putting stars and text into groups.
101 Stars are put in group 1 and the trimmed body in group 2.")
103 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
104 (when (fboundp 'defvaralias)
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-at-clock-log-p "org-clock" ())
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
121 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function orgtbl-mode "org-table" (&optional arg))
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-beamer-mode "org-beamer" ())
127 (declare-function org-table-edit-field "org-table" (arg))
128 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
129 (declare-function org-id-get-create "org-id" (&optional force))
130 (declare-function org-id-find-id-file "org-id" (id))
131 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
132 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
133 (declare-function org-table-align "org-table" ())
134 (declare-function org-table-paste-rectangle "org-table" ())
135 (declare-function org-table-maybe-eval-formula "org-table" ())
136 (declare-function org-table-maybe-recalculate-line "org-table" ())
138 (autoload 'org-element-at-point "org-element")
139 (autoload 'org-element-type "org-element")
141 (declare-function org-element-at-point "org-element" (&optional keep-trail))
142 (declare-function org-element-type "org-element" (element))
143 (declare-function org-element-context "org-element" ())
144 (declare-function org-element-contents "org-element" (element))
145 (declare-function org-element-property "org-element" (property element))
146 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
147 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
150 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
152 ;; load languages based on value of `org-babel-load-languages'
153 (defvar org-babel-load-languages)
155 ;;;###autoload
156 (defun org-babel-do-load-languages (sym value)
157 "Load the languages defined in `org-babel-load-languages'."
158 (set-default sym value)
159 (mapc (lambda (pair)
160 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
161 (if active
162 (progn
163 (require (intern (concat "ob-" lang))))
164 (progn
165 (funcall 'fmakunbound
166 (intern (concat "org-babel-execute:" lang)))
167 (funcall 'fmakunbound
168 (intern (concat "org-babel-expand-body:" lang)))))))
169 org-babel-load-languages))
171 (defcustom org-babel-load-languages '((emacs-lisp . t))
172 "Languages which can be evaluated in Org-mode buffers.
173 This list can be used to load support for any of the languages
174 below, note that each language will depend on a different set of
175 system executables and/or Emacs modes. When a language is
176 \"loaded\", then code blocks in that language can be evaluated
177 with `org-babel-execute-src-block' bound by default to C-c
178 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
179 be set to remove code block evaluation from the C-c C-c
180 keybinding. By default only Emacs Lisp (which has no
181 requirements) is loaded."
182 :group 'org-babel
183 :set 'org-babel-do-load-languages
184 :version "24.1"
185 :type '(alist :tag "Babel Languages"
186 :key-type
187 (choice
188 (const :tag "Awk" awk)
189 (const :tag "C" C)
190 (const :tag "R" R)
191 (const :tag "Asymptote" asymptote)
192 (const :tag "Calc" calc)
193 (const :tag "Clojure" clojure)
194 (const :tag "CSS" css)
195 (const :tag "Ditaa" ditaa)
196 (const :tag "Dot" dot)
197 (const :tag "Emacs Lisp" emacs-lisp)
198 (const :tag "Fortran" fortran)
199 (const :tag "Gnuplot" gnuplot)
200 (const :tag "Haskell" haskell)
201 (const :tag "IO" io)
202 (const :tag "Java" java)
203 (const :tag "Javascript" js)
204 (const :tag "LaTeX" latex)
205 (const :tag "Ledger" ledger)
206 (const :tag "Lilypond" lilypond)
207 (const :tag "Lisp" lisp)
208 (const :tag "Makefile" makefile)
209 (const :tag "Maxima" maxima)
210 (const :tag "Matlab" matlab)
211 (const :tag "Mscgen" mscgen)
212 (const :tag "Ocaml" ocaml)
213 (const :tag "Octave" octave)
214 (const :tag "Org" org)
215 (const :tag "Perl" perl)
216 (const :tag "Pico Lisp" picolisp)
217 (const :tag "PlantUML" plantuml)
218 (const :tag "Python" python)
219 (const :tag "Ruby" ruby)
220 (const :tag "Sass" sass)
221 (const :tag "Scala" scala)
222 (const :tag "Scheme" scheme)
223 (const :tag "Screen" screen)
224 (const :tag "Shell Script" sh)
225 (const :tag "Shen" shen)
226 (const :tag "Sql" sql)
227 (const :tag "Sqlite" sqlite))
228 :value-type (boolean :tag "Activate" :value t)))
230 ;;;; Customization variables
231 (defcustom org-clone-delete-id nil
232 "Remove ID property of clones of a subtree.
233 When non-nil, clones of a subtree don't inherit the ID property.
234 Otherwise they inherit the ID property with a new unique
235 identifier."
236 :type 'boolean
237 :version "24.1"
238 :group 'org-id)
240 ;;; Version
241 (require 'org-compat)
242 (org-check-version)
244 ;;;###autoload
245 (defun org-version (&optional here full message)
246 "Show the org-mode version in the echo area.
247 With prefix argument HERE, insert it at point.
248 When FULL is non-nil, use a verbose version string.
249 When MESSAGE is non-nil, display a message with the version."
250 (interactive "P")
251 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
252 (save-load-suffixes load-suffixes)
253 (load-suffixes (list ".el"))
254 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
255 (org-trash (or
256 (and (fboundp 'org-release) (fboundp 'org-git-version))
257 (load (concat org-dir "org-version")
258 'noerror 'nomessage nil 'mustsuffix)))
259 (load-suffixes save-load-suffixes)
260 (org-version (org-release))
261 (git-version (org-git-version))
262 (version (format "Org-mode version %s (%s @ %s)"
263 org-version
264 git-version
265 (if org-install-dir
266 (if (string= org-dir org-install-dir)
267 org-install-dir
268 (concat "mixed installation! " org-install-dir " and " org-dir))
269 "org-loaddefs.el can not be found!")))
270 (_version (if full version org-version)))
271 (if (org-called-interactively-p 'interactive)
272 (if here
273 (insert version)
274 (message version))
275 (if message (message _version))
276 _version)))
278 (defconst org-version (org-version))
280 ;;; Compatibility constants
282 ;;; The custom variables
284 (defgroup org nil
285 "Outline-based notes management and organizer."
286 :tag "Org"
287 :group 'outlines
288 :group 'calendar)
290 (defcustom org-mode-hook nil
291 "Mode hook for Org-mode, run after the mode was turned on."
292 :group 'org
293 :type 'hook)
295 (defcustom org-load-hook nil
296 "Hook that is run after org.el has been loaded."
297 :group 'org
298 :type 'hook)
300 (defcustom org-log-buffer-setup-hook nil
301 "Hook that is run after an Org log buffer is created."
302 :group 'org
303 :version "24.1"
304 :type 'hook)
306 (defvar org-modules) ; defined below
307 (defvar org-modules-loaded nil
308 "Have the modules been loaded already?")
310 (defun org-load-modules-maybe (&optional force)
311 "Load all extensions listed in `org-modules'."
312 (when (or force (not org-modules-loaded))
313 (mapc (lambda (ext)
314 (condition-case nil (require ext)
315 (error (message "Problems while trying to load feature `%s'" ext))))
316 org-modules)
317 (setq org-modules-loaded t)))
319 (defun org-set-modules (var value)
320 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
321 (set var value)
322 (when (featurep 'org)
323 (org-load-modules-maybe 'force)))
325 (when (org-bound-and-true-p org-modules)
326 (let ((a (member 'org-infojs org-modules)))
327 (and a (setcar a 'org-jsinfo))))
329 (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)
330 "Modules that should always be loaded together with org.el.
331 If a description starts with <C>, the file is not part of Emacs
332 and loading it will require that you have downloaded and properly installed
333 the org-mode distribution.
335 You can also use this system to load external packages (i.e. neither Org
336 core modules, nor modules from the CONTRIB directory). Just add symbols
337 to the end of the list. If the package is called org-xyz.el, then you need
338 to add the symbol `xyz', and the package must have a call to
340 (provide 'org-xyz)"
341 :group 'org
342 :set 'org-set-modules
343 :type
344 '(set :greedy t
345 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
346 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
347 (const :tag " crypt: Encryption of subtrees" org-crypt)
348 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
349 (const :tag " docview: Links to doc-view buffers" org-docview)
350 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
351 (const :tag " id: Global IDs for identifying entries" org-id)
352 (const :tag " info: Links to Info nodes" org-info)
353 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
354 (const :tag " habit: Track your consistency with habits" org-habit)
355 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
356 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
357 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
358 (const :tag " mew Links to Mew folders/messages" org-mew)
359 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
360 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
361 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
362 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
363 (const :tag " vm: Links to VM folders/messages" org-vm)
364 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
365 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
366 (const :tag " mouse: Additional mouse support" org-mouse)
367 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
369 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
370 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
371 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
372 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
373 (const :tag "C collector: Collect properties into tables" org-collector)
374 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
375 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
376 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
377 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
378 (const :tag "C eval: Include command output as text" org-eval)
379 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
380 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
381 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
382 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
383 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
385 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
387 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
388 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
389 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
390 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
391 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
392 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
393 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
394 (const :tag "C mtags: Support for muse-like tags" org-mtags)
395 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
396 (const :tag "C registry: A registry for Org-mode links" org-registry)
397 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
398 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
399 (const :tag "C secretary: Team management with org-mode" org-secretary)
400 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
401 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
402 (const :tag "C track: Keep up with Org-mode development" org-track)
403 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
404 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
405 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
407 (defcustom org-support-shift-select nil
408 "Non-nil means make shift-cursor commands select text when possible.
410 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
411 start selecting a region, or enlarge regions started in this way.
412 In Org-mode, in special contexts, these same keys are used for
413 other purposes, important enough to compete with shift selection.
414 Org tries to balance these needs by supporting `shift-select-mode'
415 outside these special contexts, under control of this variable.
417 The default of this variable is nil, to avoid confusing behavior. Shifted
418 cursor keys will then execute Org commands in the following contexts:
419 - on a headline, changing TODO state (left/right) and priority (up/down)
420 - on a time stamp, changing the time
421 - in a plain list item, changing the bullet type
422 - in a property definition line, switching between allowed values
423 - in the BEGIN line of a clock table (changing the time block).
424 Outside these contexts, the commands will throw an error.
426 When this variable is t and the cursor is not in a special
427 context, Org-mode will support shift-selection for making and
428 enlarging regions. To make this more effective, the bullet
429 cycling will no longer happen anywhere in an item line, but only
430 if the cursor is exactly on the bullet.
432 If you set this variable to the symbol `always', then the keys
433 will not be special in headlines, property lines, and item lines,
434 to make shift selection work there as well. If this is what you
435 want, you can use the following alternative commands: `C-c C-t'
436 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
437 can be used to switch TODO sets, `C-c -' to cycle item bullet
438 types, and properties can be edited by hand or in column view.
440 However, when the cursor is on a timestamp, shift-cursor commands
441 will still edit the time stamp - this is just too good to give up.
443 XEmacs user should have this variable set to nil, because
444 `shift-select-mode' is in Emacs 23 or later only."
445 :group 'org
446 :type '(choice
447 (const :tag "Never" nil)
448 (const :tag "When outside special context" t)
449 (const :tag "Everywhere except timestamps" always)))
451 (defcustom org-loop-over-headlines-in-active-region nil
452 "Shall some commands act upon headlines in the active region?
454 When set to `t', some commands will be performed in all headlines
455 within the active region.
457 When set to `start-level', some commands will be performed in all
458 headlines within the active region, provided that these headlines
459 are of the same level than the first one.
461 When set to a string, those commands will be performed on the
462 matching headlines within the active region. Such string must be
463 a tags/property/todo match as it is used in the agenda tags view.
465 The list of commands is: `org-schedule', `org-deadline',
466 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
467 `org-archive-to-archive-sibling'. The archiving commands skip
468 already archived entries."
469 :type '(choice (const :tag "Don't loop" nil)
470 (const :tag "All headlines in active region" t)
471 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
472 (string :tag "Tags/Property/Todo matcher"))
473 :version "24.1"
474 :group 'org-todo
475 :group 'org-archive)
477 (defgroup org-startup nil
478 "Options concerning startup of Org-mode."
479 :tag "Org Startup"
480 :group 'org)
482 (defcustom org-startup-folded t
483 "Non-nil means entering Org-mode will switch to OVERVIEW.
484 This can also be configured on a per-file basis by adding one of
485 the following lines anywhere in the buffer:
487 #+STARTUP: fold (or `overview', this is equivalent)
488 #+STARTUP: nofold (or `showall', this is equivalent)
489 #+STARTUP: content
490 #+STARTUP: showeverything"
491 :group 'org-startup
492 :type '(choice
493 (const :tag "nofold: show all" nil)
494 (const :tag "fold: overview" t)
495 (const :tag "content: all headlines" content)
496 (const :tag "show everything, even drawers" showeverything)))
498 (defcustom org-startup-truncated t
499 "Non-nil means entering Org-mode will set `truncate-lines'.
500 This is useful since some lines containing links can be very long and
501 uninteresting. Also tables look terrible when wrapped."
502 :group 'org-startup
503 :type 'boolean)
505 (defcustom org-startup-indented nil
506 "Non-nil means turn on `org-indent-mode' on startup.
507 This can also be configured on a per-file basis by adding one of
508 the following lines anywhere in the buffer:
510 #+STARTUP: indent
511 #+STARTUP: noindent"
512 :group 'org-structure
513 :type '(choice
514 (const :tag "Not" nil)
515 (const :tag "Globally (slow on startup in large files)" t)))
517 (defcustom org-use-sub-superscripts t
518 "Non-nil means interpret \"_\" and \"^\" for export.
519 When this option is turned on, you can use TeX-like syntax for sub- and
520 superscripts. Several characters after \"_\" or \"^\" will be
521 considered as a single item - so grouping with {} is normally not
522 needed. For example, the following things will be parsed as single
523 sub- or superscripts.
525 10^24 or 10^tau several digits will be considered 1 item.
526 10^-12 or 10^-tau a leading sign with digits or a word
527 x^2-y^3 will be read as x^2 - y^3, because items are
528 terminated by almost any nonword/nondigit char.
529 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
531 Still, ambiguity is possible - so when in doubt use {} to enclose the
532 sub/superscript. If you set this variable to the symbol `{}',
533 the braces are *required* in order to trigger interpretations as
534 sub/superscript. This can be helpful in documents that need \"_\"
535 frequently in plain text.
537 Not all export backends support this, but HTML does.
539 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
540 :group 'org-startup
541 :group 'org-export-translation
542 :version "24.1"
543 :type '(choice
544 (const :tag "Always interpret" t)
545 (const :tag "Only with braces" {})
546 (const :tag "Never interpret" nil)))
548 (if (fboundp 'defvaralias)
549 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
552 (defcustom org-startup-with-beamer-mode nil
553 "Non-nil means turn on `org-beamer-mode' on startup.
554 This can also be configured on a per-file basis by adding one of
555 the following lines anywhere in the buffer:
557 #+STARTUP: beamer"
558 :group 'org-startup
559 :version "24.1"
560 :type 'boolean)
562 (defcustom org-startup-align-all-tables nil
563 "Non-nil means align all tables when visiting a file.
564 This is useful when the column width in tables is forced with <N> cookies
565 in table fields. Such tables will look correct only after the first re-align.
566 This can also be configured on a per-file basis by adding one of
567 the following lines anywhere in the buffer:
568 #+STARTUP: align
569 #+STARTUP: noalign"
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-startup-with-inline-images nil
574 "Non-nil means show inline images when loading a new Org file.
575 This can also be configured on a per-file basis by adding one of
576 the following lines anywhere in the buffer:
577 #+STARTUP: inlineimages
578 #+STARTUP: noinlineimages"
579 :group 'org-startup
580 :version "24.1"
581 :type 'boolean)
583 (defcustom org-insert-mode-line-in-empty-file nil
584 "Non-nil means insert the first line setting Org-mode in empty files.
585 When the function `org-mode' is called interactively in an empty file, this
586 normally means that the file name does not automatically trigger Org-mode.
587 To ensure that the file will always be in Org-mode in the future, a
588 line enforcing Org-mode will be inserted into the buffer, if this option
589 has been set."
590 :group 'org-startup
591 :type 'boolean)
593 (defcustom org-replace-disputed-keys nil
594 "Non-nil means use alternative key bindings for some keys.
595 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
596 These keys are also used by other packages like shift-selection-mode'
597 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
598 If you want to use Org-mode together with one of these other modes,
599 or more generally if you would like to move some Org-mode commands to
600 other keys, set this variable and configure the keys with the variable
601 `org-disputed-keys'.
603 This option is only relevant at load-time of Org-mode, and must be set
604 *before* org.el is loaded. Changing it requires a restart of Emacs to
605 become effective."
606 :group 'org-startup
607 :type 'boolean)
609 (defcustom org-use-extra-keys nil
610 "Non-nil means use extra key sequence definitions for certain commands.
611 This happens automatically if you run XEmacs or if `window-system'
612 is nil. This variable lets you do the same manually. You must
613 set it before loading org.
615 Example: on Carbon Emacs 22 running graphically, with an external
616 keyboard on a Powerbook, the default way of setting M-left might
617 not work for either Alt or ESC. Setting this variable will make
618 it work for ESC."
619 :group 'org-startup
620 :type 'boolean)
622 (if (fboundp 'defvaralias)
623 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
625 (defcustom org-disputed-keys
626 '(([(shift up)] . [(meta p)])
627 ([(shift down)] . [(meta n)])
628 ([(shift left)] . [(meta -)])
629 ([(shift right)] . [(meta +)])
630 ([(control shift right)] . [(meta shift +)])
631 ([(control shift left)] . [(meta shift -)]))
632 "Keys for which Org-mode and other modes compete.
633 This is an alist, cars are the default keys, second element specifies
634 the alternative to use when `org-replace-disputed-keys' is t.
636 Keys can be specified in any syntax supported by `define-key'.
637 The value of this option takes effect only at Org-mode's startup,
638 therefore you'll have to restart Emacs to apply it after changing."
639 :group 'org-startup
640 :type 'alist)
642 (defun org-key (key)
643 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
644 Or return the original if not disputed.
645 Also apply the translations defined in `org-xemacs-key-equivalents'."
646 (when org-replace-disputed-keys
647 (let* ((nkey (key-description key))
648 (x (org-find-if (lambda (x)
649 (equal (key-description (car x)) nkey))
650 org-disputed-keys)))
651 (setq key (if x (cdr x) key))))
652 (when (featurep 'xemacs)
653 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
654 key)
656 (defun org-find-if (predicate seq)
657 (catch 'exit
658 (while seq
659 (if (funcall predicate (car seq))
660 (throw 'exit (car seq))
661 (pop seq)))))
663 (defun org-defkey (keymap key def)
664 "Define a key, possibly translated, as returned by `org-key'."
665 (define-key keymap (org-key key) def))
667 (defcustom org-ellipsis nil
668 "The ellipsis to use in the Org-mode outline.
669 When nil, just use the standard three dots. When a string, use that instead,
670 When a face, use the standard 3 dots, but with the specified face.
671 The change affects only Org-mode (which will then use its own display table).
672 Changing this requires executing `M-x org-mode' in a buffer to become
673 effective."
674 :group 'org-startup
675 :type '(choice (const :tag "Default" nil)
676 (face :tag "Face" :value org-warning)
677 (string :tag "String" :value "...#")))
679 (defvar org-display-table nil
680 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
682 (defgroup org-keywords nil
683 "Keywords in Org-mode."
684 :tag "Org Keywords"
685 :group 'org)
687 (defcustom org-deadline-string "DEADLINE:"
688 "String to mark deadline entries.
689 A deadline is this string, followed by a time stamp. Should be a word,
690 terminated by a colon. You can insert a schedule keyword and
691 a timestamp with \\[org-deadline].
692 Changes become only effective after restarting Emacs."
693 :group 'org-keywords
694 :type 'string)
696 (defcustom org-scheduled-string "SCHEDULED:"
697 "String to mark scheduled TODO entries.
698 A schedule is this string, followed by a time stamp. Should be a word,
699 terminated by a colon. You can insert a schedule keyword and
700 a timestamp with \\[org-schedule].
701 Changes become only effective after restarting Emacs."
702 :group 'org-keywords
703 :type 'string)
705 (defcustom org-closed-string "CLOSED:"
706 "String used as the prefix for timestamps logging closing a TODO entry."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-clock-string "CLOCK:"
711 "String used as prefix for timestamps clocking work hours on an item."
712 :group 'org-keywords
713 :type 'string)
715 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
716 org-scheduled-string "\\|"
717 org-deadline-string "\\|"
718 org-closed-string "\\|"
719 org-clock-string "\\)")
720 "Matches a line with planning or clock info.")
722 (defcustom org-comment-string "COMMENT"
723 "Entries starting with this keyword will never be exported.
724 An entry can be toggled between COMMENT and normal with
725 \\[org-toggle-comment].
726 Changes become only effective after restarting Emacs."
727 :group 'org-keywords
728 :type 'string)
730 (defcustom org-quote-string "QUOTE"
731 "Entries starting with this keyword will be exported in fixed-width font.
732 Quoting applies only to the text in the entry following the headline, and does
733 not extend beyond the next headline, even if that is lower level.
734 An entry can be toggled between QUOTE and normal with
735 \\[org-toggle-fixed-width-section]."
736 :group 'org-keywords
737 :type 'string)
739 (defconst org-repeat-re
740 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
741 "Regular expression for specifying repeated events.
742 After a match, group 1 contains the repeat expression.")
744 (defgroup org-structure nil
745 "Options concerning the general structure of Org-mode files."
746 :tag "Org Structure"
747 :group 'org)
749 (defgroup org-reveal-location nil
750 "Options about how to make context of a location visible."
751 :tag "Org Reveal Location"
752 :group 'org-structure)
754 (defconst org-context-choice
755 '(choice
756 (const :tag "Always" t)
757 (const :tag "Never" nil)
758 (repeat :greedy t :tag "Individual contexts"
759 (cons
760 (choice :tag "Context"
761 (const agenda)
762 (const org-goto)
763 (const occur-tree)
764 (const tags-tree)
765 (const link-search)
766 (const mark-goto)
767 (const bookmark-jump)
768 (const isearch)
769 (const default))
770 (boolean))))
771 "Contexts for the reveal options.")
773 (defcustom org-show-hierarchy-above '((default . t))
774 "Non-nil means show full hierarchy when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the hierarchy of headings
777 above the exposed location is shown.
778 Turning this off for example for sparse trees makes them very compact.
779 Instead of t, this can also be an alist specifying this option for different
780 contexts. Valid contexts are
781 agenda when exposing an entry from the agenda
782 org-goto when using the command `org-goto' on key C-c C-j
783 occur-tree when using the command `org-occur' on key C-c /
784 tags-tree when constructing a sparse tree based on tags matches
785 link-search when exposing search matches associated with a link
786 mark-goto when exposing the jump goal of a mark
787 bookmark-jump when exposing a bookmark location
788 isearch when exiting from an incremental search
789 default default for all contexts not set explicitly"
790 :group 'org-reveal-location
791 :type org-context-choice)
793 (defcustom org-show-following-heading '((default . nil))
794 "Non-nil means show following heading when revealing a location.
795 Org-mode often shows locations in an org-mode file which might have
796 been invisible before. When this is set, the heading following the
797 match is shown.
798 Turning this off for example for sparse trees makes them very compact,
799 but makes it harder to edit the location of the match. In such a case,
800 use the command \\[org-reveal] to show more context.
801 Instead of t, this can also be an alist specifying this option for different
802 contexts. See `org-show-hierarchy-above' for valid contexts."
803 :group 'org-reveal-location
804 :type org-context-choice)
806 (defcustom org-show-siblings '((default . nil) (isearch t))
807 "Non-nil means show all sibling heading when revealing a location.
808 Org-mode often shows locations in an org-mode file which might have
809 been invisible before. When this is set, the sibling of the current entry
810 heading are all made visible. If `org-show-hierarchy-above' is t,
811 the same happens on each level of the hierarchy above the current entry.
813 By default this is on for the isearch context, off for all other contexts.
814 Turning this off for example for sparse trees makes them very compact,
815 but makes it harder to edit the location of the match. In such a case,
816 use the command \\[org-reveal] to show more context.
817 Instead of t, this can also be an alist specifying this option for different
818 contexts. See `org-show-hierarchy-above' for valid contexts."
819 :group 'org-reveal-location
820 :type org-context-choice)
822 (defcustom org-show-entry-below '((default . nil))
823 "Non-nil means show the entry below a headline when revealing a location.
824 Org-mode often shows locations in an org-mode file which might have
825 been invisible before. When this is set, the text below the headline that is
826 exposed is also shown.
828 By default this is off for all contexts.
829 Instead of t, this can also be an alist specifying this option for different
830 contexts. See `org-show-hierarchy-above' for valid contexts."
831 :group 'org-reveal-location
832 :type org-context-choice)
834 (defcustom org-indirect-buffer-display 'other-window
835 "How should indirect tree buffers be displayed?
836 This applies to indirect buffers created with the commands
837 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
838 Valid values are:
839 current-window Display in the current window
840 other-window Just display in another window.
841 dedicated-frame Create one new frame, and re-use it each time.
842 new-frame Make a new frame each time. Note that in this case
843 previously-made indirect buffers are kept, and you need to
844 kill these buffers yourself."
845 :group 'org-structure
846 :group 'org-agenda-windows
847 :type '(choice
848 (const :tag "In current window" current-window)
849 (const :tag "In current frame, other window" other-window)
850 (const :tag "Each time a new frame" new-frame)
851 (const :tag "One dedicated frame" dedicated-frame)))
853 (defcustom org-use-speed-commands nil
854 "Non-nil means activate single letter commands at beginning of a headline.
855 This may also be a function to test for appropriate locations where speed
856 commands should be active."
857 :group 'org-structure
858 :type '(choice
859 (const :tag "Never" nil)
860 (const :tag "At beginning of headline stars" t)
861 (function)))
863 (defcustom org-speed-commands-user nil
864 "Alist of additional speed commands.
865 This list will be checked before `org-speed-commands-default'
866 when the variable `org-use-speed-commands' is non-nil
867 and when the cursor is at the beginning of a headline.
868 The car if each entry is a string with a single letter, which must
869 be assigned to `self-insert-command' in the global map.
870 The cdr is either a command to be called interactively, a function
871 to be called, or a form to be evaluated.
872 An entry that is just a list with a single string will be interpreted
873 as a descriptive headline that will be added when listing the speed
874 commands in the Help buffer using the `?' speed command."
875 :group 'org-structure
876 :type '(repeat :value ("k" . ignore)
877 (choice :value ("k" . ignore)
878 (list :tag "Descriptive Headline" (string :tag "Headline"))
879 (cons :tag "Letter and Command"
880 (string :tag "Command letter")
881 (choice
882 (function)
883 (sexp))))))
885 (defgroup org-cycle nil
886 "Options concerning visibility cycling in Org-mode."
887 :tag "Org Cycle"
888 :group 'org-structure)
890 (defcustom org-cycle-skip-children-state-if-no-children t
891 "Non-nil means skip CHILDREN state in entries that don't have any."
892 :group 'org-cycle
893 :type 'boolean)
895 (defcustom org-cycle-max-level nil
896 "Maximum level which should still be subject to visibility cycling.
897 Levels higher than this will, for cycling, be treated as text, not a headline.
898 When `org-odd-levels-only' is set, a value of N in this variable actually
899 means 2N-1 stars as the limiting headline.
900 When nil, cycle all levels.
901 Note that the limiting level of cycling is also influenced by
902 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
903 `org-inlinetask-min-level' is, cycling will be limited to levels one less
904 than its value."
905 :group 'org-cycle
906 :type '(choice
907 (const :tag "No limit" nil)
908 (integer :tag "Maximum level")))
910 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
911 "Names of drawers. Drawers are not opened by cycling on the headline above.
912 Drawers only open with a TAB on the drawer line itself. A drawer looks like
913 this:
914 :DRAWERNAME:
915 .....
916 :END:
917 The drawer \"PROPERTIES\" is special for capturing properties through
918 the property API.
920 Drawers can be defined on the per-file basis with a line like:
922 #+DRAWERS: HIDDEN STATE PROPERTIES"
923 :group 'org-structure
924 :group 'org-cycle
925 :type '(repeat (string :tag "Drawer Name")))
927 (defcustom org-hide-block-startup nil
928 "Non-nil means entering Org-mode will fold all blocks.
929 This can also be set in on a per-file basis with
931 #+STARTUP: hideblocks
932 #+STARTUP: showblocks"
933 :group 'org-startup
934 :group 'org-cycle
935 :type 'boolean)
937 (defcustom org-cycle-global-at-bob nil
938 "Cycle globally if cursor is at beginning of buffer and not at a headline.
939 This makes it possible to do global cycling without having to use S-TAB or
940 \\[universal-argument] TAB. For this special case to work, the first line
941 of the buffer must not be a headline -- it may be empty or some other text.
942 When used in this way, `org-cycle-hook' is disabled temporarily to make
943 sure the cursor stays at the beginning of the buffer. When this option is
944 nil, don't do anything special at the beginning of the buffer."
945 :group 'org-cycle
946 :type 'boolean)
948 (defcustom org-cycle-level-after-item/entry-creation t
949 "Non-nil means cycle entry level or item indentation in new empty entries.
951 When the cursor is at the end of an empty headline, i.e with only stars
952 and maybe a TODO keyword, TAB will then switch the entry to become a child,
953 and then all possible ancestor states, before returning to the original state.
954 This makes data entry extremely fast: M-RET to create a new headline,
955 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
957 When the cursor is at the end of an empty plain list item, one TAB will
958 make it a subitem, two or more tabs will back up to make this an item
959 higher up in the item hierarchy."
960 :group 'org-cycle
961 :type 'boolean)
963 (defcustom org-cycle-emulate-tab t
964 "Where should `org-cycle' emulate TAB.
965 nil Never
966 white Only in completely white lines
967 whitestart Only at the beginning of lines, before the first non-white char
968 t Everywhere except in headlines
969 exc-hl-bol Everywhere except at the start of a headline
970 If TAB is used in a place where it does not emulate TAB, the current subtree
971 visibility is cycled."
972 :group 'org-cycle
973 :type '(choice (const :tag "Never" nil)
974 (const :tag "Only in completely white lines" white)
975 (const :tag "Before first char in a line" whitestart)
976 (const :tag "Everywhere except in headlines" t)
977 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
980 (defcustom org-cycle-separator-lines 2
981 "Number of empty lines needed to keep an empty line between collapsed trees.
982 If you leave an empty line between the end of a subtree and the following
983 headline, this empty line is hidden when the subtree is folded.
984 Org-mode will leave (exactly) one empty line visible if the number of
985 empty lines is equal or larger to the number given in this variable.
986 So the default 2 means at least 2 empty lines after the end of a subtree
987 are needed to produce free space between a collapsed subtree and the
988 following headline.
990 If the number is negative, and the number of empty lines is at least -N,
991 all empty lines are shown.
993 Special case: when 0, never leave empty lines in collapsed view."
994 :group 'org-cycle
995 :type 'integer)
996 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
998 (defcustom org-pre-cycle-hook nil
999 "Hook that is run before visibility cycling is happening.
1000 The function(s) in this hook must accept a single argument which indicates
1001 the new state that will be set right after running this hook. The
1002 argument is a symbol. Before a global state change, it can have the values
1003 `overview', `content', or `all'. Before a local state change, it can have
1004 the values `folded', `children', or `subtree'."
1005 :group 'org-cycle
1006 :type 'hook)
1008 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1009 org-cycle-hide-drawers
1010 org-cycle-hide-inline-tasks
1011 org-cycle-show-empty-lines
1012 org-optimize-window-after-visibility-change)
1013 "Hook that is run after `org-cycle' has changed the buffer visibility.
1014 The function(s) in this hook must accept a single argument which indicates
1015 the new state that was set by the most recent `org-cycle' command. The
1016 argument is a symbol. After a global state change, it can have the values
1017 `overview', `contents', or `all'. After a local state change, it can have
1018 the values `folded', `children', or `subtree'."
1019 :group 'org-cycle
1020 :type 'hook)
1022 (defgroup org-edit-structure nil
1023 "Options concerning structure editing in Org-mode."
1024 :tag "Org Edit Structure"
1025 :group 'org-structure)
1027 (defcustom org-odd-levels-only nil
1028 "Non-nil means skip even levels and only use odd levels for the outline.
1029 This has the effect that two stars are being added/taken away in
1030 promotion/demotion commands. It also influences how levels are
1031 handled by the exporters.
1032 Changing it requires restart of `font-lock-mode' to become effective
1033 for fontification also in regions already fontified.
1034 You may also set this on a per-file basis by adding one of the following
1035 lines to the buffer:
1037 #+STARTUP: odd
1038 #+STARTUP: oddeven"
1039 :group 'org-edit-structure
1040 :group 'org-appearance
1041 :type 'boolean)
1043 (defcustom org-adapt-indentation t
1044 "Non-nil means adapt indentation to outline node level.
1046 When this variable is set, Org assumes that you write outlines by
1047 indenting text in each node to align with the headline (after the stars).
1048 The following issues are influenced by this variable:
1050 - When this is set and the *entire* text in an entry is indented, the
1051 indentation is increased by one space in a demotion command, and
1052 decreased by one in a promotion command. If any line in the entry
1053 body starts with text at column 0, indentation is not changed at all.
1055 - Property drawers and planning information is inserted indented when
1056 this variable s set. When nil, they will not be indented.
1058 - TAB indents a line relative to context. The lines below a headline
1059 will be indented when this variable is set.
1061 Note that this is all about true indentation, by adding and removing
1062 space characters. See also `org-indent.el' which does level-dependent
1063 indentation in a virtual way, i.e. at display time in Emacs."
1064 :group 'org-edit-structure
1065 :type 'boolean)
1067 (defcustom org-special-ctrl-a/e nil
1068 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1070 When t, `C-a' will bring back the cursor to the beginning of the
1071 headline text, i.e. after the stars and after a possible TODO
1072 keyword. In an item, this will be the position after bullet and
1073 check-box, if any. When the cursor is already at that position,
1074 another `C-a' will bring it to the beginning of the line.
1076 `C-e' will jump to the end of the headline, ignoring the presence
1077 of tags in the headline. A second `C-e' will then jump to the
1078 true end of the line, after any tags. This also means that, when
1079 this variable is non-nil, `C-e' also will never jump beyond the
1080 end of the heading of a folded section, i.e. not after the
1081 ellipses.
1083 When set to the symbol `reversed', the first `C-a' or `C-e' works
1084 normally, going to the true line boundary first. Only a directly
1085 following, identical keypress will bring the cursor to the
1086 special positions.
1088 This may also be a cons cell where the behavior for `C-a' and
1089 `C-e' is set separately."
1090 :group 'org-edit-structure
1091 :type '(choice
1092 (const :tag "off" nil)
1093 (const :tag "on: after stars/bullet and before tags first" t)
1094 (const :tag "reversed: true line boundary first" reversed)
1095 (cons :tag "Set C-a and C-e separately"
1096 (choice :tag "Special C-a"
1097 (const :tag "off" nil)
1098 (const :tag "on: after stars/bullet first" t)
1099 (const :tag "reversed: before stars/bullet first" reversed))
1100 (choice :tag "Special C-e"
1101 (const :tag "off" nil)
1102 (const :tag "on: before tags first" t)
1103 (const :tag "reversed: after tags first" reversed)))))
1104 (if (fboundp 'defvaralias)
1105 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1107 (defcustom org-special-ctrl-k nil
1108 "Non-nil means `C-k' will behave specially in headlines.
1109 When nil, `C-k' will call the default `kill-line' command.
1110 When t, the following will happen while the cursor is in the headline:
1112 - When the cursor is at the beginning of a headline, kill the entire
1113 line and possible the folded subtree below the line.
1114 - When in the middle of the headline text, kill the headline up to the tags.
1115 - When after the headline text, kill the tags."
1116 :group 'org-edit-structure
1117 :type 'boolean)
1119 (defcustom org-ctrl-k-protect-subtree nil
1120 "Non-nil means, do not delete a hidden subtree with C-k.
1121 When set to the symbol `error', simply throw an error when C-k is
1122 used to kill (part-of) a headline that has hidden text behind it.
1123 Any other non-nil value will result in a query to the user, if it is
1124 OK to kill that hidden subtree. When nil, kill without remorse."
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not protect hidden subtrees" nil)
1129 (const :tag "Protect hidden subtrees with a security query" t)
1130 (const :tag "Never kill a hidden subtree with C-k" error)))
1132 (defcustom org-catch-invisible-edits nil
1133 "Check if in invisible region before inserting or deleting a character.
1134 Valid values are:
1136 nil Do not check, so just do invisible edits.
1137 error Throw an error and do nothing.
1138 show Make point visible, and do the requested edit.
1139 show-and-error Make point visible, then throw an error and abort the edit.
1140 smart Make point visible, and do insertion/deletion if it is
1141 adjacent to visible text and the change feels predictable.
1142 Never delete a previously invisible character or add in the
1143 middle or right after an invisible region. Basically, this
1144 allows insertion and backward-delete right before ellipses.
1145 FIXME: maybe in this case we should not even show?"
1146 :group 'org-edit-structure
1147 :version "24.1"
1148 :type '(choice
1149 (const :tag "Do not check" nil)
1150 (const :tag "Throw error when trying to edit" error)
1151 (const :tag "Unhide, but do not do the edit" show-and-error)
1152 (const :tag "Show invisible part and do the edit" show)
1153 (const :tag "Be smart and do the right thing" smart)))
1155 (defcustom org-yank-folded-subtrees t
1156 "Non-nil means when yanking subtrees, fold them.
1157 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1158 it starts with a heading and all other headings in it are either children
1159 or siblings, then fold all the subtrees. However, do this only if no
1160 text after the yank would be swallowed into a folded tree by this action."
1161 :group 'org-edit-structure
1162 :type 'boolean)
1164 (defcustom org-yank-adjusted-subtrees nil
1165 "Non-nil means when yanking subtrees, adjust the level.
1166 With this setting, `org-paste-subtree' is used to insert the subtree, see
1167 this function for details."
1168 :group 'org-edit-structure
1169 :type 'boolean)
1171 (defcustom org-M-RET-may-split-line '((default . t))
1172 "Non-nil means M-RET will split the line at the cursor position.
1173 When nil, it will go to the end of the line before making a
1174 new line.
1175 You may also set this option in a different way for different
1176 contexts. Valid contexts are:
1178 headline when creating a new headline
1179 item when creating a new item
1180 table in a table field
1181 default the value to be used for all contexts not explicitly
1182 customized"
1183 :group 'org-structure
1184 :group 'org-table
1185 :type '(choice
1186 (const :tag "Always" t)
1187 (const :tag "Never" nil)
1188 (repeat :greedy t :tag "Individual contexts"
1189 (cons
1190 (choice :tag "Context"
1191 (const headline)
1192 (const item)
1193 (const table)
1194 (const default))
1195 (boolean)))))
1198 (defcustom org-insert-heading-respect-content nil
1199 "Non-nil means insert new headings after the current subtree.
1200 When nil, the new heading is created directly after the current line.
1201 The commands \\[org-insert-heading-respect-content] and
1202 \\[org-insert-todo-heading-respect-content] turn this variable on
1203 for the duration of the command."
1204 :group 'org-structure
1205 :type 'boolean)
1207 (defcustom org-blank-before-new-entry '((heading . auto)
1208 (plain-list-item . auto))
1209 "Should `org-insert-heading' leave a blank line before new heading/item?
1210 The value is an alist, with `heading' and `plain-list-item' as CAR,
1211 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1212 which case Org will look at the surrounding headings/items and try to
1213 make an intelligent decision whether to insert a blank line or not.
1215 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1216 set, the setting here is ignored and no empty line is inserted, to avoid
1217 breaking the list structure."
1218 :group 'org-edit-structure
1219 :type '(list
1220 (cons (const heading)
1221 (choice (const :tag "Never" nil)
1222 (const :tag "Always" t)
1223 (const :tag "Auto" auto)))
1224 (cons (const plain-list-item)
1225 (choice (const :tag "Never" nil)
1226 (const :tag "Always" t)
1227 (const :tag "Auto" auto)))))
1229 (defcustom org-insert-heading-hook nil
1230 "Hook being run after inserting a new heading."
1231 :group 'org-edit-structure
1232 :type 'hook)
1234 (defcustom org-enable-fixed-width-editor t
1235 "Non-nil means lines starting with \":\" are treated as fixed-width.
1236 This currently only means they are never auto-wrapped.
1237 When nil, such lines will be treated like ordinary lines.
1238 See also the QUOTE keyword."
1239 :group 'org-edit-structure
1240 :type 'boolean)
1242 (defcustom org-goto-auto-isearch t
1243 "Non-nil means typing characters in `org-goto' starts incremental search."
1244 :group 'org-edit-structure
1245 :type 'boolean)
1247 (defgroup org-sparse-trees nil
1248 "Options concerning sparse trees in Org-mode."
1249 :tag "Org Sparse Trees"
1250 :group 'org-structure)
1252 (defcustom org-highlight-sparse-tree-matches t
1253 "Non-nil means highlight all matches that define a sparse tree.
1254 The highlights will automatically disappear the next time the buffer is
1255 changed by an edit command."
1256 :group 'org-sparse-trees
1257 :type 'boolean)
1259 (defcustom org-remove-highlights-with-change t
1260 "Non-nil means any change to the buffer will remove temporary highlights.
1261 Such highlights are created by `org-occur' and `org-clock-display'.
1262 When nil, `C-c C-c needs to be used to get rid of the highlights.
1263 The highlights created by `org-preview-latex-fragment' always need
1264 `C-c C-c' to be removed."
1265 :group 'org-sparse-trees
1266 :group 'org-time
1267 :type 'boolean)
1270 (defcustom org-occur-hook '(org-first-headline-recenter)
1271 "Hook that is run after `org-occur' has constructed a sparse tree.
1272 This can be used to recenter the window to show as much of the structure
1273 as possible."
1274 :group 'org-sparse-trees
1275 :type 'hook)
1277 (defgroup org-imenu-and-speedbar nil
1278 "Options concerning imenu and speedbar in Org-mode."
1279 :tag "Org Imenu and Speedbar"
1280 :group 'org-structure)
1282 (defcustom org-imenu-depth 2
1283 "The maximum level for Imenu access to Org-mode headlines.
1284 This also applied for speedbar access."
1285 :group 'org-imenu-and-speedbar
1286 :type 'integer)
1288 (defgroup org-table nil
1289 "Options concerning tables in Org-mode."
1290 :tag "Org Table"
1291 :group 'org)
1293 (defcustom org-enable-table-editor 'optimized
1294 "Non-nil means lines starting with \"|\" are handled by the table editor.
1295 When nil, such lines will be treated like ordinary lines.
1297 When equal to the symbol `optimized', the table editor will be optimized to
1298 do the following:
1299 - Automatic overwrite mode in front of whitespace in table fields.
1300 This makes the structure of the table stay in tact as long as the edited
1301 field does not exceed the column width.
1302 - Minimize the number of realigns. Normally, the table is aligned each time
1303 TAB or RET are pressed to move to another field. With optimization this
1304 happens only if changes to a field might have changed the column width.
1305 Optimization requires replacing the functions `self-insert-command',
1306 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1307 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1308 very good at guessing when a re-align will be necessary, but you can always
1309 force one with \\[org-ctrl-c-ctrl-c].
1311 If you would like to use the optimized version in Org-mode, but the
1312 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1314 This variable can be used to turn on and off the table editor during a session,
1315 but in order to toggle optimization, a restart is required.
1317 See also the variable `org-table-auto-blank-field'."
1318 :group 'org-table
1319 :type '(choice
1320 (const :tag "off" nil)
1321 (const :tag "on" t)
1322 (const :tag "on, optimized" optimized)))
1324 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1325 (version<= emacs-version "24.1"))
1326 "Non-nil means cluster self-insert commands for undo when possible.
1327 If this is set, then, like in the Emacs command loop, 20 consecutive
1328 characters will be undone together.
1329 This is configurable, because there is some impact on typing performance."
1330 :group 'org-table
1331 :type 'boolean)
1333 (defcustom org-table-tab-recognizes-table.el t
1334 "Non-nil means TAB will automatically notice a table.el table.
1335 When it sees such a table, it moves point into it and - if necessary -
1336 calls `table-recognize-table'."
1337 :group 'org-table-editing
1338 :type 'boolean)
1340 (defgroup org-link nil
1341 "Options concerning links in Org-mode."
1342 :tag "Org Link"
1343 :group 'org)
1345 (defvar org-link-abbrev-alist-local nil
1346 "Buffer-local version of `org-link-abbrev-alist', which see.
1347 The value of this is taken from the #+LINK lines.")
1348 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1350 (defcustom org-link-abbrev-alist nil
1351 "Alist of link abbreviations.
1352 The car of each element is a string, to be replaced at the start of a link.
1353 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1354 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1356 [[linkkey:tag][description]]
1358 The 'linkkey' must be a word word, starting with a letter, followed
1359 by letters, numbers, '-' or '_'.
1361 If REPLACE is a string, the tag will simply be appended to create the link.
1362 If the string contains \"%s\", the tag will be inserted there. If the string
1363 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1364 at that point (see the function `url-hexify-string'). If the string contains
1365 the specifier \"%(my-function)\", then the custom function `my-function' will
1366 be invoked: this function takes the tag as its only argument and must return
1367 a string.
1369 REPLACE may also be a function that will be called with the tag as the
1370 only argument to create the link, which should be returned as a string.
1372 See the manual for examples."
1373 :group 'org-link
1374 :type '(repeat
1375 (cons
1376 (string :tag "Protocol")
1377 (choice
1378 (string :tag "Format")
1379 (function)))))
1381 (defcustom org-descriptive-links t
1382 "Non-nil means Org will display descriptive links.
1383 E.g. [[http://orgmode.org][Org website]] will be displayed as
1384 \"Org Website\", hiding the link itself and just displaying its
1385 description. When set to `nil', Org will display the full links
1386 literally.
1388 You can interactively set the value of this variable by calling
1389 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1390 :group 'org-link
1391 :type 'boolean)
1393 (defcustom org-link-file-path-type 'adaptive
1394 "How the path name in file links should be stored.
1395 Valid values are:
1397 relative Relative to the current directory, i.e. the directory of the file
1398 into which the link is being inserted.
1399 absolute Absolute path, if possible with ~ for home directory.
1400 noabbrev Absolute path, no abbreviation of home directory.
1401 adaptive Use relative path for files in the current directory and sub-
1402 directories of it. For other files, use an absolute path."
1403 :group 'org-link
1404 :type '(choice
1405 (const relative)
1406 (const absolute)
1407 (const noabbrev)
1408 (const adaptive)))
1410 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1411 "Types of links that should be activated in Org-mode files.
1412 This is a list of symbols, each leading to the activation of a certain link
1413 type. In principle, it does not hurt to turn on most link types - there may
1414 be a small gain when turning off unused link types. The types are:
1416 bracket The recommended [[link][description]] or [[link]] links with hiding.
1417 angle Links in angular brackets that may contain whitespace like
1418 <bbdb:Carsten Dominik>.
1419 plain Plain links in normal text, no whitespace, like http://google.com.
1420 radio Text that is matched by a radio target, see manual for details.
1421 tag Tag settings in a headline (link to tag search).
1422 date Time stamps (link to calendar).
1423 footnote Footnote labels.
1425 Changing this variable requires a restart of Emacs to become effective."
1426 :group 'org-link
1427 :type '(set :greedy t
1428 (const :tag "Double bracket links" bracket)
1429 (const :tag "Angular bracket links" angle)
1430 (const :tag "Plain text links" plain)
1431 (const :tag "Radio target matches" radio)
1432 (const :tag "Tags" tag)
1433 (const :tag "Timestamps" date)
1434 (const :tag "Footnotes" footnote)))
1436 (defcustom org-make-link-description-function nil
1437 "Function to use for generating link descriptions from links.
1438 When nil, the link location will be used. This function must take
1439 two parameters: the first one is the link, the second one is the
1440 description generated by `org-insert-link'. The function should
1441 return the description to use."
1442 :group 'org-link
1443 :type 'function)
1445 (defgroup org-link-store nil
1446 "Options concerning storing links in Org-mode."
1447 :tag "Org Store Link"
1448 :group 'org-link)
1450 (defcustom org-url-hexify-p t
1451 "When non-nil, hexify URL when creating a link."
1452 :type 'boolean
1453 :version "24.3"
1454 :group 'org-link-store)
1456 (defcustom org-email-link-description-format "Email %c: %.30s"
1457 "Format of the description part of a link to an email or usenet message.
1458 The following %-escapes will be replaced by corresponding information:
1460 %F full \"From\" field
1461 %f name, taken from \"From\" field, address if no name
1462 %T full \"To\" field
1463 %t first name in \"To\" field, address if no name
1464 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1465 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1466 %s subject
1467 %d date
1468 %m message-id.
1470 You may use normal field width specification between the % and the letter.
1471 This is for example useful to limit the length of the subject.
1473 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1474 :group 'org-link-store
1475 :type 'string)
1477 (defcustom org-from-is-user-regexp
1478 (let (r1 r2)
1479 (when (and user-mail-address (not (string= user-mail-address "")))
1480 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1481 (when (and user-full-name (not (string= user-full-name "")))
1482 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1483 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1484 "Regexp matched against the \"From:\" header of an email or usenet message.
1485 It should match if the message is from the user him/herself."
1486 :group 'org-link-store
1487 :type 'regexp)
1489 (defcustom org-context-in-file-links t
1490 "Non-nil means file links from `org-store-link' contain context.
1491 A search string will be added to the file name with :: as separator and
1492 used to find the context when the link is activated by the command
1493 `org-open-at-point'. When this option is t, the entire active region
1494 will be placed in the search string of the file link. If set to a
1495 positive integer, only the first n lines of context will be stored.
1497 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1498 negates this setting for the duration of the command."
1499 :group 'org-link-store
1500 :type '(choice boolean integer))
1502 (defcustom org-keep-stored-link-after-insertion nil
1503 "Non-nil means keep link in list for entire session.
1505 The command `org-store-link' adds a link pointing to the current
1506 location to an internal list. These links accumulate during a session.
1507 The command `org-insert-link' can be used to insert links into any
1508 Org-mode file (offering completion for all stored links). When this
1509 option is nil, every link which has been inserted once using \\[org-insert-link]
1510 will be removed from the list, to make completing the unused links
1511 more efficient."
1512 :group 'org-link-store
1513 :type 'boolean)
1515 (defgroup org-link-follow nil
1516 "Options concerning following links in Org-mode."
1517 :tag "Org Follow Link"
1518 :group 'org-link)
1520 (defcustom org-link-translation-function nil
1521 "Function to translate links with different syntax to Org syntax.
1522 This can be used to translate links created for example by the Planner
1523 or emacs-wiki packages to Org syntax.
1524 The function must accept two parameters, a TYPE containing the link
1525 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1526 which is everything after the link protocol. It should return a cons
1527 with possibly modified values of type and path.
1528 Org contains a function for this, so if you set this variable to
1529 `org-translate-link-from-planner', you should be able follow many
1530 links created by planner."
1531 :group 'org-link-follow
1532 :type 'function)
1534 (defcustom org-follow-link-hook nil
1535 "Hook that is run after a link has been followed."
1536 :group 'org-link-follow
1537 :type 'hook)
1539 (defcustom org-tab-follows-link nil
1540 "Non-nil means on links TAB will follow the link.
1541 Needs to be set before org.el is loaded.
1542 This really should not be used, it does not make sense, and the
1543 implementation is bad."
1544 :group 'org-link-follow
1545 :type 'boolean)
1547 (defcustom org-return-follows-link nil
1548 "Non-nil means on links RET will follow the link."
1549 :group 'org-link-follow
1550 :type 'boolean)
1552 (defcustom org-mouse-1-follows-link
1553 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1554 "Non-nil means mouse-1 on a link will follow the link.
1555 A longer mouse click will still set point. Does not work on XEmacs.
1556 Needs to be set before org.el is loaded."
1557 :group 'org-link-follow
1558 :type 'boolean)
1560 (defcustom org-mark-ring-length 4
1561 "Number of different positions to be recorded in the ring.
1562 Changing this requires a restart of Emacs to work correctly."
1563 :group 'org-link-follow
1564 :type 'integer)
1566 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1567 "Non-nil means internal links in Org files must exactly match a headline.
1568 When nil, the link search tries to match a phrase with all words
1569 in the search text."
1570 :group 'org-link-follow
1571 :version "24.1"
1572 :type '(choice
1573 (const :tag "Use fuzzy text search" nil)
1574 (const :tag "Match only exact headline" t)
1575 (const :tag "Match exact headline or query to create it"
1576 query-to-create)))
1578 (defcustom org-link-frame-setup
1579 '((vm . vm-visit-folder-other-frame)
1580 (vm-imap . vm-visit-imap-folder-other-frame)
1581 (gnus . org-gnus-no-new-news)
1582 (file . find-file-other-window)
1583 (wl . wl-other-frame))
1584 "Setup the frame configuration for following links.
1585 When following a link with Emacs, it may often be useful to display
1586 this link in another window or frame. This variable can be used to
1587 set this up for the different types of links.
1588 For VM, use any of
1589 `vm-visit-folder'
1590 `vm-visit-folder-other-window'
1591 `vm-visit-folder-other-frame'
1592 For Gnus, use any of
1593 `gnus'
1594 `gnus-other-frame'
1595 `org-gnus-no-new-news'
1596 For FILE, use any of
1597 `find-file'
1598 `find-file-other-window'
1599 `find-file-other-frame'
1600 For Wanderlust use any of
1601 `wl'
1602 `wl-other-frame'
1603 For the calendar, use the variable `calendar-setup'.
1604 For BBDB, it is currently only possible to display the matches in
1605 another window."
1606 :group 'org-link-follow
1607 :type '(list
1608 (cons (const vm)
1609 (choice
1610 (const vm-visit-folder)
1611 (const vm-visit-folder-other-window)
1612 (const vm-visit-folder-other-frame)))
1613 (cons (const gnus)
1614 (choice
1615 (const gnus)
1616 (const gnus-other-frame)
1617 (const org-gnus-no-new-news)))
1618 (cons (const file)
1619 (choice
1620 (const find-file)
1621 (const find-file-other-window)
1622 (const find-file-other-frame)))
1623 (cons (const wl)
1624 (choice
1625 (const wl)
1626 (const wl-other-frame)))))
1628 (defcustom org-display-internal-link-with-indirect-buffer nil
1629 "Non-nil means use indirect buffer to display infile links.
1630 Activating internal links (from one location in a file to another location
1631 in the same file) normally just jumps to the location. When the link is
1632 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1633 is displayed in
1634 another window. When this option is set, the other window actually displays
1635 an indirect buffer clone of the current buffer, to avoid any visibility
1636 changes to the current buffer."
1637 :group 'org-link-follow
1638 :type 'boolean)
1640 (defcustom org-open-non-existing-files nil
1641 "Non-nil means `org-open-file' will open non-existing files.
1642 When nil, an error will be generated.
1643 This variable applies only to external applications because they
1644 might choke on non-existing files. If the link is to a file that
1645 will be opened in Emacs, the variable is ignored."
1646 :group 'org-link-follow
1647 :type 'boolean)
1649 (defcustom org-open-directory-means-index-dot-org nil
1650 "Non-nil means a link to a directory really means to index.org.
1651 When nil, following a directory link will run dired or open a finder/explorer
1652 window on that directory."
1653 :group 'org-link-follow
1654 :type 'boolean)
1656 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1657 "Function and arguments to call for following mailto links.
1658 This is a list with the first element being a Lisp function, and the
1659 remaining elements being arguments to the function. In string arguments,
1660 %a will be replaced by the address, and %s will be replaced by the subject
1661 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1662 :group 'org-link-follow
1663 :type '(choice
1664 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1665 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1666 (const :tag "message-mail" (message-mail "%a" "%s"))
1667 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1669 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1670 "Non-nil means ask for confirmation before executing shell links.
1671 Shell links can be dangerous: just think about a link
1673 [[shell:rm -rf ~/*][Google Search]]
1675 This link would show up in your Org-mode document as \"Google Search\",
1676 but really it would remove your entire home directory.
1677 Therefore we advise against setting this variable to nil.
1678 Just change it to `y-or-n-p' if you want to confirm with a
1679 single keystroke rather than having to type \"yes\"."
1680 :group 'org-link-follow
1681 :type '(choice
1682 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1683 (const :tag "with y-or-n (faster)" y-or-n-p)
1684 (const :tag "no confirmation (dangerous)" nil)))
1685 (put 'org-confirm-shell-link-function
1686 'safe-local-variable
1687 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1689 (defcustom org-confirm-shell-link-not-regexp ""
1690 "A regexp to skip confirmation for shell links."
1691 :group 'org-link-follow
1692 :version "24.1"
1693 :type 'regexp)
1695 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1696 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1697 Elisp links can be dangerous: just think about a link
1699 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1701 This link would show up in your Org-mode document as \"Google Search\",
1702 but really it would remove your entire home directory.
1703 Therefore we advise against setting this variable to nil.
1704 Just change it to `y-or-n-p' if you want to confirm with a
1705 single keystroke rather than having to type \"yes\"."
1706 :group 'org-link-follow
1707 :type '(choice
1708 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1709 (const :tag "with y-or-n (faster)" y-or-n-p)
1710 (const :tag "no confirmation (dangerous)" nil)))
1711 (put 'org-confirm-shell-link-function
1712 'safe-local-variable
1713 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1715 (defcustom org-confirm-elisp-link-not-regexp ""
1716 "A regexp to skip confirmation for Elisp links."
1717 :group 'org-link-follow
1718 :version "24.1"
1719 :type 'regexp)
1721 (defconst org-file-apps-defaults-gnu
1722 '((remote . emacs)
1723 (system . mailcap)
1724 (t . mailcap))
1725 "Default file applications on a UNIX or GNU/Linux system.
1726 See `org-file-apps'.")
1728 (defconst org-file-apps-defaults-macosx
1729 '((remote . emacs)
1730 (t . "open %s")
1731 (system . "open %s")
1732 ("ps.gz" . "gv %s")
1733 ("eps.gz" . "gv %s")
1734 ("dvi" . "xdvi %s")
1735 ("fig" . "xfig %s"))
1736 "Default file applications on a MacOS X system.
1737 The system \"open\" is known as a default, but we use X11 applications
1738 for some files for which the OS does not have a good default.
1739 See `org-file-apps'.")
1741 (defconst org-file-apps-defaults-windowsnt
1742 (list
1743 '(remote . emacs)
1744 (cons t
1745 (list (if (featurep 'xemacs)
1746 'mswindows-shell-execute
1747 'w32-shell-execute)
1748 "open" 'file))
1749 (cons 'system
1750 (list (if (featurep 'xemacs)
1751 'mswindows-shell-execute
1752 'w32-shell-execute)
1753 "open" 'file)))
1754 "Default file applications on a Windows NT system.
1755 The system \"open\" is used for most files.
1756 See `org-file-apps'.")
1758 (defcustom org-file-apps
1760 (auto-mode . emacs)
1761 ("\\.mm\\'" . default)
1762 ("\\.x?html?\\'" . default)
1763 ("\\.pdf\\'" . default)
1765 "External applications for opening `file:path' items in a document.
1766 Org-mode uses system defaults for different file types, but
1767 you can use this variable to set the application for a given file
1768 extension. The entries in this list are cons cells where the car identifies
1769 files and the cdr the corresponding command. Possible values for the
1770 file identifier are
1771 \"string\" A string as a file identifier can be interpreted in different
1772 ways, depending on its contents:
1774 - Alphanumeric characters only:
1775 Match links with this file extension.
1776 Example: (\"pdf\" . \"evince %s\")
1777 to open PDFs with evince.
1779 - Regular expression: Match links where the
1780 filename matches the regexp. If you want to
1781 use groups here, use shy groups.
1783 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1784 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1785 to open *.html and *.xhtml with firefox.
1787 - Regular expression which contains (non-shy) groups:
1788 Match links where the whole link, including \"::\", and
1789 anything after that, matches the regexp.
1790 In a custom command string, %1, %2, etc. are replaced with
1791 the parts of the link that were matched by the groups.
1792 For backwards compatibility, if a command string is given
1793 that does not use any of the group matches, this case is
1794 handled identically to the second one (i.e. match against
1795 file name only).
1796 In a custom lisp form, you can access the group matches with
1797 (match-string n link).
1799 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1800 to open [[file:document.pdf::5]] with evince at page 5.
1802 `directory' Matches a directory
1803 `remote' Matches a remote file, accessible through tramp or efs.
1804 Remote files most likely should be visited through Emacs
1805 because external applications cannot handle such paths.
1806 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1807 so all files Emacs knows how to handle. Using this with
1808 command `emacs' will open most files in Emacs. Beware that this
1809 will also open html files inside Emacs, unless you add
1810 (\"html\" . default) to the list as well.
1811 t Default for files not matched by any of the other options.
1812 `system' The system command to open files, like `open' on Windows
1813 and Mac OS X, and mailcap under GNU/Linux. This is the command
1814 that will be selected if you call `C-c C-o' with a double
1815 \\[universal-argument] \\[universal-argument] prefix.
1817 Possible values for the command are:
1818 `emacs' The file will be visited by the current Emacs process.
1819 `default' Use the default application for this file type, which is the
1820 association for t in the list, most likely in the system-specific
1821 part.
1822 This can be used to overrule an unwanted setting in the
1823 system-specific variable.
1824 `system' Use the system command for opening files, like \"open\".
1825 This command is specified by the entry whose car is `system'.
1826 Most likely, the system-specific version of this variable
1827 does define this command, but you can overrule/replace it
1828 here.
1829 string A command to be executed by a shell; %s will be replaced
1830 by the path to the file.
1831 sexp A Lisp form which will be evaluated. The file path will
1832 be available in the Lisp variable `file'.
1833 For more examples, see the system specific constants
1834 `org-file-apps-defaults-macosx'
1835 `org-file-apps-defaults-windowsnt'
1836 `org-file-apps-defaults-gnu'."
1837 :group 'org-link-follow
1838 :type '(repeat
1839 (cons (choice :value ""
1840 (string :tag "Extension")
1841 (const :tag "System command to open files" system)
1842 (const :tag "Default for unrecognized files" t)
1843 (const :tag "Remote file" remote)
1844 (const :tag "Links to a directory" directory)
1845 (const :tag "Any files that have Emacs modes"
1846 auto-mode))
1847 (choice :value ""
1848 (const :tag "Visit with Emacs" emacs)
1849 (const :tag "Use default" default)
1850 (const :tag "Use the system command" system)
1851 (string :tag "Command")
1852 (sexp :tag "Lisp form")))))
1854 (defcustom org-doi-server-url "http://dx.doi.org/"
1855 "The URL of the DOI server."
1856 :type 'string
1857 :version "24.3"
1858 :group 'org-link-follow)
1860 (defgroup org-refile nil
1861 "Options concerning refiling entries in Org-mode."
1862 :tag "Org Refile"
1863 :group 'org)
1865 (defcustom org-directory "~/org"
1866 "Directory with org files.
1867 This is just a default location to look for Org files. There is no need
1868 at all to put your files into this directory. It is only used in the
1869 following situations:
1871 1. When a capture template specifies a target file that is not an
1872 absolute path. The path will then be interpreted relative to
1873 `org-directory'
1874 2. When a capture note is filed away in an interactive way (when exiting the
1875 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1876 with `org-directory' as the default path."
1877 :group 'org-refile
1878 :group 'org-remember
1879 :group 'org-capture
1880 :type 'directory)
1882 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1883 "Default target for storing notes.
1884 Used as a fall back file for org-remember.el and org-capture.el, for
1885 templates that do not specify a target file."
1886 :group 'org-refile
1887 :group 'org-remember
1888 :group 'org-capture
1889 :type '(choice
1890 (const :tag "Default from remember-data-file" nil)
1891 file))
1893 (defcustom org-goto-interface 'outline
1894 "The default interface to be used for `org-goto'.
1895 Allowed values are:
1896 outline The interface shows an outline of the relevant file
1897 and the correct heading is found by moving through
1898 the outline or by searching with incremental search.
1899 outline-path-completion Headlines in the current buffer are offered via
1900 completion. This is the interface also used by
1901 the refile command."
1902 :group 'org-refile
1903 :type '(choice
1904 (const :tag "Outline" outline)
1905 (const :tag "Outline-path-completion" outline-path-completion)))
1907 (defcustom org-goto-max-level 5
1908 "Maximum target level when running `org-goto' with refile interface."
1909 :group 'org-refile
1910 :type 'integer)
1912 (defcustom org-reverse-note-order nil
1913 "Non-nil means store new notes at the beginning of a file or entry.
1914 When nil, new notes will be filed to the end of a file or entry.
1915 This can also be a list with cons cells of regular expressions that
1916 are matched against file names, and values."
1917 :group 'org-remember
1918 :group 'org-capture
1919 :group 'org-refile
1920 :type '(choice
1921 (const :tag "Reverse always" t)
1922 (const :tag "Reverse never" nil)
1923 (repeat :tag "By file name regexp"
1924 (cons regexp boolean))))
1926 (defcustom org-log-refile nil
1927 "Information to record when a task is refiled.
1929 Possible values are:
1931 nil Don't add anything
1932 time Add a time stamp to the task
1933 note Prompt for a note and add it with template `org-log-note-headings'
1935 This option can also be set with on a per-file-basis with
1937 #+STARTUP: nologrefile
1938 #+STARTUP: logrefile
1939 #+STARTUP: lognoterefile
1941 You can have local logging settings for a subtree by setting the LOGGING
1942 property to one or more of these keywords.
1944 When bulk-refiling from the agenda, the value `note' is forbidden and
1945 will temporarily be changed to `time'."
1946 :group 'org-refile
1947 :group 'org-progress
1948 :version "24.1"
1949 :type '(choice
1950 (const :tag "No logging" nil)
1951 (const :tag "Record timestamp" time)
1952 (const :tag "Record timestamp with note." note)))
1954 (defcustom org-refile-targets nil
1955 "Targets for refiling entries with \\[org-refile].
1956 This is a list of cons cells. Each cell contains:
1957 - a specification of the files to be considered, either a list of files,
1958 or a symbol whose function or variable value will be used to retrieve
1959 a file name or a list of file names. If you use `org-agenda-files' for
1960 that, all agenda files will be scanned for targets. Nil means consider
1961 headings in the current buffer.
1962 - A specification of how to find candidate refile targets. This may be
1963 any of:
1964 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1965 This tag has to be present in all target headlines, inheritance will
1966 not be considered.
1967 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1968 todo keyword.
1969 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1970 headlines that are refiling targets.
1971 - a cons cell (:level . N). Any headline of level N is considered a target.
1972 Note that, when `org-odd-levels-only' is set, level corresponds to
1973 order in hierarchy, not to the number of stars.
1974 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1975 Note that, when `org-odd-levels-only' is set, level corresponds to
1976 order in hierarchy, not to the number of stars.
1978 Each element of this list generates a set of possible targets.
1979 The union of these sets is presented (with completion) to
1980 the user by `org-refile'.
1982 You can set the variable `org-refile-target-verify-function' to a function
1983 to verify each headline found by the simple criteria above.
1985 When this variable is nil, all top-level headlines in the current buffer
1986 are used, equivalent to the value `((nil . (:level . 1))'."
1987 :group 'org-refile
1988 :type '(repeat
1989 (cons
1990 (choice :value org-agenda-files
1991 (const :tag "All agenda files" org-agenda-files)
1992 (const :tag "Current buffer" nil)
1993 (function) (variable) (file))
1994 (choice :tag "Identify target headline by"
1995 (cons :tag "Specific tag" (const :value :tag) (string))
1996 (cons :tag "TODO keyword" (const :value :todo) (string))
1997 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1998 (cons :tag "Level number" (const :value :level) (integer))
1999 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2001 (defcustom org-refile-target-verify-function nil
2002 "Function to verify if the headline at point should be a refile target.
2003 The function will be called without arguments, with point at the
2004 beginning of the headline. It should return t and leave point
2005 where it is if the headline is a valid target for refiling.
2007 If the target should not be selected, the function must return nil.
2008 In addition to this, it may move point to a place from where the search
2009 should be continued. For example, the function may decide that the entire
2010 subtree of the current entry should be excluded and move point to the end
2011 of the subtree."
2012 :group 'org-refile
2013 :type 'function)
2015 (defcustom org-refile-use-cache nil
2016 "Non-nil means cache refile targets to speed up the process.
2017 The cache for a particular file will be updated automatically when
2018 the buffer has been killed, or when any of the marker used for flagging
2019 refile targets no longer points at a live buffer.
2020 If you have added new entries to a buffer that might themselves be targets,
2021 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2022 find that easier, `C-u C-u C-u C-c C-w'."
2023 :group 'org-refile
2024 :version "24.1"
2025 :type 'boolean)
2027 (defcustom org-refile-use-outline-path nil
2028 "Non-nil means provide refile targets as paths.
2029 So a level 3 headline will be available as level1/level2/level3.
2031 When the value is `file', also include the file name (without directory)
2032 into the path. In this case, you can also stop the completion after
2033 the file name, to get entries inserted as top level in the file.
2035 When `full-file-path', include the full file path."
2036 :group 'org-refile
2037 :type '(choice
2038 (const :tag "Not" nil)
2039 (const :tag "Yes" t)
2040 (const :tag "Start with file name" file)
2041 (const :tag "Start with full file path" full-file-path)))
2043 (defcustom org-outline-path-complete-in-steps t
2044 "Non-nil means complete the outline path in hierarchical steps.
2045 When Org-mode uses the refile interface to select an outline path
2046 \(see variable `org-refile-use-outline-path'), the completion of
2047 the path can be done is a single go, or if can be done in steps down
2048 the headline hierarchy. Going in steps is probably the best if you
2049 do not use a special completion package like `ido' or `icicles'.
2050 However, when using these packages, going in one step can be very
2051 fast, while still showing the whole path to the entry."
2052 :group 'org-refile
2053 :type 'boolean)
2055 (defcustom org-refile-allow-creating-parent-nodes nil
2056 "Non-nil means allow to create new nodes as refile targets.
2057 New nodes are then created by adding \"/new node name\" to the completion
2058 of an existing node. When the value of this variable is `confirm',
2059 new node creation must be confirmed by the user (recommended)
2060 When nil, the completion must match an existing entry.
2062 Note that, if the new heading is not seen by the criteria
2063 listed in `org-refile-targets', multiple instances of the same
2064 heading would be created by trying again to file under the new
2065 heading."
2066 :group 'org-refile
2067 :type '(choice
2068 (const :tag "Never" nil)
2069 (const :tag "Always" t)
2070 (const :tag "Prompt for confirmation" confirm)))
2072 (defcustom org-refile-active-region-within-subtree nil
2073 "Non-nil means also refile active region within a subtree.
2075 By default `org-refile' doesn't allow refiling regions if they
2076 don't contain a set of subtrees, but it might be convenient to
2077 do so sometimes: in that case, the first line of the region is
2078 converted to a headline before refiling."
2079 :group 'org-refile
2080 :version "24.1"
2081 :type 'boolean)
2083 (defgroup org-todo nil
2084 "Options concerning TODO items in Org-mode."
2085 :tag "Org TODO"
2086 :group 'org)
2088 (defgroup org-progress nil
2089 "Options concerning Progress logging in Org-mode."
2090 :tag "Org Progress"
2091 :group 'org-time)
2093 (defvar org-todo-interpretation-widgets
2094 '((:tag "Sequence (cycling hits every state)" sequence)
2095 (:tag "Type (cycling directly to DONE)" type))
2096 "The available interpretation symbols for customizing `org-todo-keywords'.
2097 Interested libraries should add to this list.")
2099 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2100 "List of TODO entry keyword sequences and their interpretation.
2101 \\<org-mode-map>This is a list of sequences.
2103 Each sequence starts with a symbol, either `sequence' or `type',
2104 indicating if the keywords should be interpreted as a sequence of
2105 action steps, or as different types of TODO items. The first
2106 keywords are states requiring action - these states will select a headline
2107 for inclusion into the global TODO list Org-mode produces. If one of
2108 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2109 signify that no further action is necessary. If \"|\" is not found,
2110 the last keyword is treated as the only DONE state of the sequence.
2112 The command \\[org-todo] cycles an entry through these states, and one
2113 additional state where no keyword is present. For details about this
2114 cycling, see the manual.
2116 TODO keywords and interpretation can also be set on a per-file basis with
2117 the special #+SEQ_TODO and #+TYP_TODO lines.
2119 Each keyword can optionally specify a character for fast state selection
2120 \(in combination with the variable `org-use-fast-todo-selection')
2121 and specifiers for state change logging, using the same syntax that
2122 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2123 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2124 indicates to record a time stamp each time this state is selected.
2126 Each keyword may also specify if a timestamp or a note should be
2127 recorded when entering or leaving the state, by adding additional
2128 characters in the parenthesis after the keyword. This looks like this:
2129 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2130 record only the time of the state change. With X and Y being either
2131 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2132 Y when leaving the state if and only if the *target* state does not
2133 define X. You may omit any of the fast-selection key or X or /Y,
2134 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2136 For backward compatibility, this variable may also be just a list
2137 of keywords. In this case the interpretation (sequence or type) will be
2138 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2139 :group 'org-todo
2140 :group 'org-keywords
2141 :type '(choice
2142 (repeat :tag "Old syntax, just keywords"
2143 (string :tag "Keyword"))
2144 (repeat :tag "New syntax"
2145 (cons
2146 (choice
2147 :tag "Interpretation"
2148 ;;Quick and dirty way to see
2149 ;;`org-todo-interpretations'. This takes the
2150 ;;place of item arguments
2151 :convert-widget
2152 (lambda (widget)
2153 (widget-put widget
2154 :args (mapcar
2155 #'(lambda (x)
2156 (widget-convert
2157 (cons 'const x)))
2158 org-todo-interpretation-widgets))
2159 widget))
2160 (repeat
2161 (string :tag "Keyword"))))))
2163 (defvar org-todo-keywords-1 nil
2164 "All TODO and DONE keywords active in a buffer.")
2165 (make-variable-buffer-local 'org-todo-keywords-1)
2166 (defvar org-todo-keywords-for-agenda nil)
2167 (defvar org-done-keywords-for-agenda nil)
2168 (defvar org-drawers-for-agenda nil)
2169 (defvar org-todo-keyword-alist-for-agenda nil)
2170 (defvar org-tag-alist-for-agenda nil)
2171 (defvar org-agenda-contributing-files nil)
2172 (defvar org-not-done-keywords nil)
2173 (make-variable-buffer-local 'org-not-done-keywords)
2174 (defvar org-done-keywords nil)
2175 (make-variable-buffer-local 'org-done-keywords)
2176 (defvar org-todo-heads nil)
2177 (make-variable-buffer-local 'org-todo-heads)
2178 (defvar org-todo-sets nil)
2179 (make-variable-buffer-local 'org-todo-sets)
2180 (defvar org-todo-log-states nil)
2181 (make-variable-buffer-local 'org-todo-log-states)
2182 (defvar org-todo-kwd-alist nil)
2183 (make-variable-buffer-local 'org-todo-kwd-alist)
2184 (defvar org-todo-key-alist nil)
2185 (make-variable-buffer-local 'org-todo-key-alist)
2186 (defvar org-todo-key-trigger nil)
2187 (make-variable-buffer-local 'org-todo-key-trigger)
2189 (defcustom org-todo-interpretation 'sequence
2190 "Controls how TODO keywords are interpreted.
2191 This variable is in principle obsolete and is only used for
2192 backward compatibility, if the interpretation of todo keywords is
2193 not given already in `org-todo-keywords'. See that variable for
2194 more information."
2195 :group 'org-todo
2196 :group 'org-keywords
2197 :type '(choice (const sequence)
2198 (const type)))
2200 (defcustom org-use-fast-todo-selection t
2201 "Non-nil means use the fast todo selection scheme with C-c C-t.
2202 This variable describes if and under what circumstances the cycling
2203 mechanism for TODO keywords will be replaced by a single-key, direct
2204 selection scheme.
2206 When nil, fast selection is never used.
2208 When the symbol `prefix', it will be used when `org-todo' is called
2209 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2210 `C-u t' in an agenda buffer.
2212 When t, fast selection is used by default. In this case, the prefix
2213 argument forces cycling instead.
2215 In all cases, the special interface is only used if access keys have
2216 actually been assigned by the user, i.e. if keywords in the configuration
2217 are followed by a letter in parenthesis, like TODO(t)."
2218 :group 'org-todo
2219 :type '(choice
2220 (const :tag "Never" nil)
2221 (const :tag "By default" t)
2222 (const :tag "Only with C-u C-c C-t" prefix)))
2224 (defcustom org-provide-todo-statistics t
2225 "Non-nil means update todo statistics after insert and toggle.
2226 ALL-HEADLINES means update todo statistics by including headlines
2227 with no TODO keyword as well, counting them as not done.
2228 A list of TODO keywords means the same, but skip keywords that are
2229 not in this list.
2231 When this is set, todo statistics is updated in the parent of the
2232 current entry each time a todo state is changed."
2233 :group 'org-todo
2234 :type '(choice
2235 (const :tag "Yes, only for TODO entries" t)
2236 (const :tag "Yes, including all entries" 'all-headlines)
2237 (repeat :tag "Yes, for TODOs in this list"
2238 (string :tag "TODO keyword"))
2239 (other :tag "No TODO statistics" nil)))
2241 (defcustom org-hierarchical-todo-statistics t
2242 "Non-nil means TODO statistics covers just direct children.
2243 When nil, all entries in the subtree are considered.
2244 This has only an effect if `org-provide-todo-statistics' is set.
2245 To set this to nil for only a single subtree, use a COOKIE_DATA
2246 property and include the word \"recursive\" into the value."
2247 :group 'org-todo
2248 :type 'boolean)
2250 (defcustom org-after-todo-state-change-hook nil
2251 "Hook which is run after the state of a TODO item was changed.
2252 The new state (a string with a TODO keyword, or nil) is available in the
2253 Lisp variable `org-state'."
2254 :group 'org-todo
2255 :type 'hook)
2257 (defvar org-blocker-hook nil
2258 "Hook for functions that are allowed to block a state change.
2260 Each function gets as its single argument a property list, see
2261 `org-trigger-hook' for more information about this list.
2263 If any of the functions in this hook returns nil, the state change
2264 is blocked.")
2266 (defvar org-trigger-hook nil
2267 "Hook for functions that are triggered by a state change.
2269 Each function gets as its single argument a property list with at least
2270 the following elements:
2272 (:type type-of-change :position pos-at-entry-start
2273 :from old-state :to new-state)
2275 Depending on the type, more properties may be present.
2277 This mechanism is currently implemented for:
2279 TODO state changes
2280 ------------------
2281 :type todo-state-change
2282 :from previous state (keyword as a string), or nil, or a symbol
2283 'todo' or 'done', to indicate the general type of state.
2284 :to new state, like in :from")
2286 (defcustom org-enforce-todo-dependencies nil
2287 "Non-nil means undone TODO entries will block switching the parent to DONE.
2288 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2289 be blocked if any prior sibling is not yet done.
2290 Finally, if the parent is blocked because of ordered siblings of its own,
2291 the child will also be blocked."
2292 :set (lambda (var val)
2293 (set var val)
2294 (if val
2295 (add-hook 'org-blocker-hook
2296 'org-block-todo-from-children-or-siblings-or-parent)
2297 (remove-hook 'org-blocker-hook
2298 'org-block-todo-from-children-or-siblings-or-parent)))
2299 :group 'org-todo
2300 :type 'boolean)
2302 (defcustom org-enforce-todo-checkbox-dependencies nil
2303 "Non-nil means unchecked boxes will block switching the parent to DONE.
2304 When this is nil, checkboxes have no influence on switching TODO states.
2305 When non-nil, you first need to check off all check boxes before the TODO
2306 entry can be switched to DONE.
2307 This variable needs to be set before org.el is loaded, and you need to
2308 restart Emacs after a change to make the change effective. The only way
2309 to change is while Emacs is running is through the customize interface."
2310 :set (lambda (var val)
2311 (set var val)
2312 (if val
2313 (add-hook 'org-blocker-hook
2314 'org-block-todo-from-checkboxes)
2315 (remove-hook 'org-blocker-hook
2316 'org-block-todo-from-checkboxes)))
2317 :group 'org-todo
2318 :type 'boolean)
2320 (defcustom org-treat-insert-todo-heading-as-state-change nil
2321 "Non-nil means inserting a TODO heading is treated as state change.
2322 So when the command \\[org-insert-todo-heading] is used, state change
2323 logging will apply if appropriate. When nil, the new TODO item will
2324 be inserted directly, and no logging will take place."
2325 :group 'org-todo
2326 :type 'boolean)
2328 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2329 "Non-nil means switching TODO states with S-cursor counts as state change.
2330 This is the default behavior. However, setting this to nil allows a
2331 convenient way to select a TODO state and bypass any logging associated
2332 with that."
2333 :group 'org-todo
2334 :type 'boolean)
2336 (defcustom org-todo-state-tags-triggers nil
2337 "Tag changes that should be triggered by TODO state changes.
2338 This is a list. Each entry is
2340 (state-change (tag . flag) .......)
2342 State-change can be a string with a state, and empty string to indicate the
2343 state that has no TODO keyword, or it can be one of the symbols `todo'
2344 or `done', meaning any not-done or done state, respectively."
2345 :group 'org-todo
2346 :group 'org-tags
2347 :type '(repeat
2348 (cons (choice :tag "When changing to"
2349 (const :tag "Not-done state" todo)
2350 (const :tag "Done state" done)
2351 (string :tag "State"))
2352 (repeat
2353 (cons :tag "Tag action"
2354 (string :tag "Tag")
2355 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2357 (defcustom org-log-done nil
2358 "Information to record when a task moves to the DONE state.
2360 Possible values are:
2362 nil Don't add anything, just change the keyword
2363 time Add a time stamp to the task
2364 note Prompt for a note and add it with template `org-log-note-headings'
2366 This option can also be set with on a per-file-basis with
2368 #+STARTUP: nologdone
2369 #+STARTUP: logdone
2370 #+STARTUP: lognotedone
2372 You can have local logging settings for a subtree by setting the LOGGING
2373 property to one or more of these keywords."
2374 :group 'org-todo
2375 :group 'org-progress
2376 :type '(choice
2377 (const :tag "No logging" nil)
2378 (const :tag "Record CLOSED timestamp" time)
2379 (const :tag "Record CLOSED timestamp with note." note)))
2381 ;; Normalize old uses of org-log-done.
2382 (cond
2383 ((eq org-log-done t) (setq org-log-done 'time))
2384 ((and (listp org-log-done) (memq 'done org-log-done))
2385 (setq org-log-done 'note)))
2387 (defcustom org-log-reschedule nil
2388 "Information to record when the scheduling date of a tasks is modified.
2390 Possible values are:
2392 nil Don't add anything, just change the date
2393 time Add a time stamp to the task
2394 note Prompt for a note and add it with template `org-log-note-headings'
2396 This option can also be set with on a per-file-basis with
2398 #+STARTUP: nologreschedule
2399 #+STARTUP: logreschedule
2400 #+STARTUP: lognotereschedule"
2401 :group 'org-todo
2402 :group 'org-progress
2403 :type '(choice
2404 (const :tag "No logging" nil)
2405 (const :tag "Record timestamp" time)
2406 (const :tag "Record timestamp with note." note)))
2408 (defcustom org-log-redeadline nil
2409 "Information to record when the deadline date of a tasks is modified.
2411 Possible values are:
2413 nil Don't add anything, just change the date
2414 time Add a time stamp to the task
2415 note Prompt for a note and add it with template `org-log-note-headings'
2417 This option can also be set with on a per-file-basis with
2419 #+STARTUP: nologredeadline
2420 #+STARTUP: logredeadline
2421 #+STARTUP: lognoteredeadline
2423 You can have local logging settings for a subtree by setting the LOGGING
2424 property to one or more of these keywords."
2425 :group 'org-todo
2426 :group 'org-progress
2427 :type '(choice
2428 (const :tag "No logging" nil)
2429 (const :tag "Record timestamp" time)
2430 (const :tag "Record timestamp with note." note)))
2432 (defcustom org-log-note-clock-out nil
2433 "Non-nil means record a note when clocking out of an item.
2434 This can also be configured on a per-file basis by adding one of
2435 the following lines anywhere in the buffer:
2437 #+STARTUP: lognoteclock-out
2438 #+STARTUP: nolognoteclock-out"
2439 :group 'org-todo
2440 :group 'org-progress
2441 :type 'boolean)
2443 (defcustom org-log-done-with-time t
2444 "Non-nil means the CLOSED time stamp will contain date and time.
2445 When nil, only the date will be recorded."
2446 :group 'org-progress
2447 :type 'boolean)
2449 (defcustom org-log-note-headings
2450 '((done . "CLOSING NOTE %t")
2451 (state . "State %-12s from %-12S %t")
2452 (note . "Note taken on %t")
2453 (reschedule . "Rescheduled from %S on %t")
2454 (delschedule . "Not scheduled, was %S on %t")
2455 (redeadline . "New deadline from %S on %t")
2456 (deldeadline . "Removed deadline, was %S on %t")
2457 (refile . "Refiled on %t")
2458 (clock-out . ""))
2459 "Headings for notes added to entries.
2460 The value is an alist, with the car being a symbol indicating the note
2461 context, and the cdr is the heading to be used. The heading may also be the
2462 empty string.
2463 %t in the heading will be replaced by a time stamp.
2464 %T will be an active time stamp instead the default inactive one
2465 %d will be replaced by a short-format time stamp.
2466 %D will be replaced by an active short-format time stamp.
2467 %s will be replaced by the new TODO state, in double quotes.
2468 %S will be replaced by the old TODO state, in double quotes.
2469 %u will be replaced by the user name.
2470 %U will be replaced by the full user name.
2472 In fact, it is not a good idea to change the `state' entry, because
2473 agenda log mode depends on the format of these entries."
2474 :group 'org-todo
2475 :group 'org-progress
2476 :type '(list :greedy t
2477 (cons (const :tag "Heading when closing an item" done) string)
2478 (cons (const :tag
2479 "Heading when changing todo state (todo sequence only)"
2480 state) string)
2481 (cons (const :tag "Heading when just taking a note" note) string)
2482 (cons (const :tag "Heading when clocking out" clock-out) string)
2483 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2484 (cons (const :tag "Heading when rescheduling" reschedule) string)
2485 (cons (const :tag "Heading when changing deadline" redeadline) string)
2486 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2487 (cons (const :tag "Heading when refiling" refile) string)))
2489 (unless (assq 'note org-log-note-headings)
2490 (push '(note . "%t") org-log-note-headings))
2492 (defcustom org-log-into-drawer nil
2493 "Non-nil means insert state change notes and time stamps into a drawer.
2494 When nil, state changes notes will be inserted after the headline and
2495 any scheduling and clock lines, but not inside a drawer.
2497 The value of this variable should be the name of the drawer to use.
2498 LOGBOOK is proposed as the default drawer for this purpose, you can
2499 also set this to a string to define the drawer of your choice.
2501 A value of t is also allowed, representing \"LOGBOOK\".
2503 A value of t or nil can also be set with on a per-file-basis with
2505 #+STARTUP: logdrawer
2506 #+STARTUP: nologdrawer
2508 If this variable is set, `org-log-state-notes-insert-after-drawers'
2509 will be ignored.
2511 You can set the property LOG_INTO_DRAWER to overrule this setting for
2512 a subtree."
2513 :group 'org-todo
2514 :group 'org-progress
2515 :type '(choice
2516 (const :tag "Not into a drawer" nil)
2517 (const :tag "LOGBOOK" t)
2518 (string :tag "Other")))
2520 (if (fboundp 'defvaralias)
2521 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2523 (defun org-log-into-drawer ()
2524 "Return the value of `org-log-into-drawer', but let properties overrule.
2525 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2526 used instead of the default value."
2527 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2528 (cond
2529 ((not p) org-log-into-drawer)
2530 ((equal p "nil") nil)
2531 ((equal p "t") "LOGBOOK")
2532 (t p))))
2534 (defcustom org-log-state-notes-insert-after-drawers nil
2535 "Non-nil means insert state change notes after any drawers in entry.
2536 Only the drawers that *immediately* follow the headline and the
2537 deadline/scheduled line are skipped.
2538 When nil, insert notes right after the heading and perhaps the line
2539 with deadline/scheduling if present.
2541 This variable will have no effect if `org-log-into-drawer' is
2542 set."
2543 :group 'org-todo
2544 :group 'org-progress
2545 :type 'boolean)
2547 (defcustom org-log-states-order-reversed t
2548 "Non-nil means the latest state note will be directly after heading.
2549 When nil, the state change notes will be ordered according to time.
2551 This option can also be set with on a per-file-basis with
2553 #+STARTUP: logstatesreversed
2554 #+STARTUP: nologstatesreversed"
2555 :group 'org-todo
2556 :group 'org-progress
2557 :type 'boolean)
2559 (defcustom org-todo-repeat-to-state nil
2560 "The TODO state to which a repeater should return the repeating task.
2561 By default this is the first task in a TODO sequence, or the previous state
2562 in a TODO_TYP set. But you can specify another task here.
2563 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2564 :group 'org-todo
2565 :version "24.1"
2566 :type '(choice (const :tag "Head of sequence" nil)
2567 (string :tag "Specific state")))
2569 (defcustom org-log-repeat 'time
2570 "Non-nil means record moving through the DONE state when triggering repeat.
2571 An auto-repeating task is immediately switched back to TODO when
2572 marked DONE. If you are not logging state changes (by adding \"@\"
2573 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2574 record a closing note, there will be no record of the task moving
2575 through DONE. This variable forces taking a note anyway.
2577 nil Don't force a record
2578 time Record a time stamp
2579 note Prompt for a note and add it with template `org-log-note-headings'
2581 This option can also be set with on a per-file-basis with
2583 #+STARTUP: nologrepeat
2584 #+STARTUP: logrepeat
2585 #+STARTUP: lognoterepeat
2587 You can have local logging settings for a subtree by setting the LOGGING
2588 property to one or more of these keywords."
2589 :group 'org-todo
2590 :group 'org-progress
2591 :type '(choice
2592 (const :tag "Don't force a record" nil)
2593 (const :tag "Force recording the DONE state" time)
2594 (const :tag "Force recording a note with the DONE state" note)))
2597 (defgroup org-priorities nil
2598 "Priorities in Org-mode."
2599 :tag "Org Priorities"
2600 :group 'org-todo)
2602 (defcustom org-enable-priority-commands t
2603 "Non-nil means priority commands are active.
2604 When nil, these commands will be disabled, so that you never accidentally
2605 set a priority."
2606 :group 'org-priorities
2607 :type 'boolean)
2609 (defcustom org-highest-priority ?A
2610 "The highest priority of TODO items. A character like ?A, ?B etc.
2611 Must have a smaller ASCII number than `org-lowest-priority'."
2612 :group 'org-priorities
2613 :type 'character)
2615 (defcustom org-lowest-priority ?C
2616 "The lowest priority of TODO items. A character like ?A, ?B etc.
2617 Must have a larger ASCII number than `org-highest-priority'."
2618 :group 'org-priorities
2619 :type 'character)
2621 (defcustom org-default-priority ?B
2622 "The default priority of TODO items.
2623 This is the priority an item gets if no explicit priority is given.
2624 When starting to cycle on an empty priority the first step in the cycle
2625 depends on `org-priority-start-cycle-with-default'. The resulting first
2626 step priority must not exceed the range from `org-highest-priority' to
2627 `org-lowest-priority' which means that `org-default-priority' has to be
2628 in this range exclusive or inclusive the range boundaries. Else the
2629 first step refuses to set the default and the second will fall back
2630 to (depending on the command used) the highest or lowest priority."
2631 :group 'org-priorities
2632 :type 'character)
2634 (defcustom org-priority-start-cycle-with-default t
2635 "Non-nil means start with default priority when starting to cycle.
2636 When this is nil, the first step in the cycle will be (depending on the
2637 command used) one higher or lower than the default priority.
2638 See also `org-default-priority'."
2639 :group 'org-priorities
2640 :type 'boolean)
2642 (defcustom org-get-priority-function nil
2643 "Function to extract the priority from a string.
2644 The string is normally the headline. If this is nil Org computes the
2645 priority from the priority cookie like [#A] in the headline. It returns
2646 an integer, increasing by 1000 for each priority level.
2647 The user can set a different function here, which should take a string
2648 as an argument and return the numeric priority."
2649 :group 'org-priorities
2650 :version "24.1"
2651 :type 'function)
2653 (defgroup org-time nil
2654 "Options concerning time stamps and deadlines in Org-mode."
2655 :tag "Org Time"
2656 :group 'org)
2658 (defcustom org-insert-labeled-timestamps-at-point nil
2659 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2660 When nil, these labeled time stamps are forces into the second line of an
2661 entry, just after the headline. When scheduling from the global TODO list,
2662 the time stamp will always be forced into the second line."
2663 :group 'org-time
2664 :type 'boolean)
2666 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2667 "Formats for `format-time-string' which are used for time stamps.
2668 It is not recommended to change this constant.")
2670 (defcustom org-time-stamp-rounding-minutes '(0 5)
2671 "Number of minutes to round time stamps to.
2672 These are two values, the first applies when first creating a time stamp.
2673 The second applies when changing it with the commands `S-up' and `S-down'.
2674 When changing the time stamp, this means that it will change in steps
2675 of N minutes, as given by the second value.
2677 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2678 numbers should be factors of 60, so for example 5, 10, 15.
2680 When this is larger than 1, you can still force an exact time stamp by using
2681 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2682 and by using a prefix arg to `S-up/down' to specify the exact number
2683 of minutes to shift."
2684 :group 'org-time
2685 :get #'(lambda (var) ; Make sure both elements are there
2686 (if (integerp (default-value var))
2687 (list (default-value var) 5)
2688 (default-value var)))
2689 :type '(list
2690 (integer :tag "when inserting times")
2691 (integer :tag "when modifying times")))
2693 ;; Normalize old customizations of this variable.
2694 (when (integerp org-time-stamp-rounding-minutes)
2695 (setq org-time-stamp-rounding-minutes
2696 (list org-time-stamp-rounding-minutes
2697 org-time-stamp-rounding-minutes)))
2699 (defcustom org-display-custom-times nil
2700 "Non-nil means overlay custom formats over all time stamps.
2701 The formats are defined through the variable `org-time-stamp-custom-formats'.
2702 To turn this on on a per-file basis, insert anywhere in the file:
2703 #+STARTUP: customtime"
2704 :group 'org-time
2705 :set 'set-default
2706 :type 'sexp)
2707 (make-variable-buffer-local 'org-display-custom-times)
2709 (defcustom org-time-stamp-custom-formats
2710 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2711 "Custom formats for time stamps. See `format-time-string' for the syntax.
2712 These are overlaid over the default ISO format if the variable
2713 `org-display-custom-times' is set. Time like %H:%M should be at the
2714 end of the second format. The custom formats are also honored by export
2715 commands, if custom time display is turned on at the time of export."
2716 :group 'org-time
2717 :type 'sexp)
2719 (defun org-time-stamp-format (&optional long inactive)
2720 "Get the right format for a time string."
2721 (let ((f (if long (cdr org-time-stamp-formats)
2722 (car org-time-stamp-formats))))
2723 (if inactive
2724 (concat "[" (substring f 1 -1) "]")
2725 f)))
2727 (defcustom org-time-clocksum-format
2728 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2729 "The format string used when creating CLOCKSUM lines.
2730 This is also used when Org mode generates a time duration.
2732 The value can be a single format string containing two
2733 %-sequences, which will be filled with the number of hours and
2734 minutes in that order.
2736 Alternatively, the value can be a plist associating any of the
2737 keys :years, :months, :weeks, :days, :hours or :minutes with
2738 format strings. The time duration is formatted using only the
2739 time components that are needed and concatenating the results.
2740 If a time unit in absent, it falls back to the next smallest
2741 unit.
2743 The keys :require-years, :require-months, :require-days,
2744 :require-weeks, :require-hours, :require-minutes are also
2745 meaningful. A non-nil value for these keys indicates that the
2746 corresponding time component should always be included, even if
2747 its value is 0.
2750 For example,
2752 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2753 :require-minutes t)
2755 means durations longer than a day will be expressed in days,
2756 hours and minutes, and durations less than a day will always be
2757 expressed in hours and minutes (even for durations less than an
2758 hour).
2760 The value
2762 \(:days \"%dd\" :minutes \"%dm\")
2764 means durations longer than a day will be expressed in days and
2765 minutes, and durations less than a day will be expressed entirely
2766 in minutes (even for durations longer than an hour)."
2767 :group 'org-time
2768 :type '(choice (string :tag "Format string")
2769 (set :tag "Plist"
2770 (group :inline t (const :tag "Years" :years)
2771 (string :tag "Format string"))
2772 (group :inline t
2773 (const :tag "Always show years" :require-years)
2774 (const t))
2775 (group :inline t (const :tag "Months" :months)
2776 (string :tag "Format string"))
2777 (group :inline t
2778 (const :tag "Always show months" :require-months)
2779 (const t))
2780 (group :inline t (const :tag "Weeks" :weeks)
2781 (string :tag "Format string"))
2782 (group :inline t
2783 (const :tag "Always show weeks" :require-weeks)
2784 (const t))
2785 (group :inline t (const :tag "Days" :days)
2786 (string :tag "Format string"))
2787 (group :inline t
2788 (const :tag "Always show days" :require-days)
2789 (const t))
2790 (group :inline t (const :tag "Hours" :hours)
2791 (string :tag "Format string"))
2792 (group :inline t
2793 (const :tag "Always show hours" :require-hours)
2794 (const t))
2795 (group :inline t (const :tag "Minutes" :minutes)
2796 (string :tag "Format string"))
2797 (group :inline t
2798 (const :tag "Always show minutes" :require-minutes)
2799 (const t)))))
2801 (defcustom org-time-clocksum-use-fractional nil
2802 "If non-nil, \\[org-clock-display] uses fractional times.
2803 org-mode generates a time duration."
2804 :group 'org-time
2805 :type 'boolean)
2807 (defcustom org-time-clocksum-fractional-format "%.2f"
2808 "The format string used when creating CLOCKSUM lines,
2809 or when Org mode generates a time duration, if
2810 `org-time-clocksum-use-fractional' is enabled.
2812 The value can be a single format string containing one
2813 %-sequence, which will be filled with the number of hours as
2814 a float.
2816 Alternatively, the value can be a plist associating any of the
2817 keys :years, :months, :weeks, :days, :hours or :minutes with
2818 a format string. The time duration is formatted using the
2819 largest time unit which gives a non-zero integer part. If all
2820 specified formats have zero integer part, the smallest time unit
2821 is used."
2822 :group 'org-time
2823 :type '(choice (string :tag "Format string")
2824 (set (group :inline t (const :tag "Years" :years)
2825 (string :tag "Format string"))
2826 (group :inline t (const :tag "Months" :months)
2827 (string :tag "Format string"))
2828 (group :inline t (const :tag "Weeks" :weeks)
2829 (string :tag "Format string"))
2830 (group :inline t (const :tag "Days" :days)
2831 (string :tag "Format string"))
2832 (group :inline t (const :tag "Hours" :hours)
2833 (string :tag "Format string"))
2834 (group :inline t (const :tag "Minutes" :minutes)
2835 (string :tag "Format string")))))
2837 (defcustom org-deadline-warning-days 14
2838 "No. of days before expiration during which a deadline becomes active.
2839 This variable governs the display in sparse trees and in the agenda.
2840 When 0 or negative, it means use this number (the absolute value of it)
2841 even if a deadline has a different individual lead time specified.
2843 Custom commands can set this variable in the options section."
2844 :group 'org-time
2845 :group 'org-agenda-daily/weekly
2846 :type 'integer)
2848 (defcustom org-read-date-prefer-future t
2849 "Non-nil means assume future for incomplete date input from user.
2850 This affects the following situations:
2851 1. The user gives a month but not a year.
2852 For example, if it is April and you enter \"feb 2\", this will be read
2853 as Feb 2, *next* year. \"May 5\", however, will be this year.
2854 2. The user gives a day, but no month.
2855 For example, if today is the 15th, and you enter \"3\", Org-mode will
2856 read this as the third of *next* month. However, if you enter \"17\",
2857 it will be considered as *this* month.
2859 If you set this variable to the symbol `time', then also the following
2860 will work:
2862 3. If the user gives a time.
2863 If the time is before now, it will be interpreted as tomorrow.
2865 Currently none of this works for ISO week specifications.
2867 When this option is nil, the current day, month and year will always be
2868 used as defaults.
2870 See also `org-agenda-jump-prefer-future'."
2871 :group 'org-time
2872 :type '(choice
2873 (const :tag "Never" nil)
2874 (const :tag "Check month and day" t)
2875 (const :tag "Check month, day, and time" time)))
2877 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2878 "Should the agenda jump command prefer the future for incomplete dates?
2879 The default is to do the same as configured in `org-read-date-prefer-future'.
2880 But you can also set a deviating value here.
2881 This may t or nil, or the symbol `org-read-date-prefer-future'."
2882 :group 'org-agenda
2883 :group 'org-time
2884 :version "24.1"
2885 :type '(choice
2886 (const :tag "Use org-read-date-prefer-future"
2887 org-read-date-prefer-future)
2888 (const :tag "Never" nil)
2889 (const :tag "Always" t)))
2891 (defcustom org-read-date-force-compatible-dates t
2892 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2894 Depending on the system Emacs is running on, certain dates cannot
2895 be represented with the type used internally to represent time.
2896 Dates between 1970-1-1 and 2038-1-1 can always be represented
2897 correctly. Some systems allow for earlier dates, some for later,
2898 some for both. One way to find out it to insert any date into an
2899 Org buffer, putting the cursor on the year and hitting S-up and
2900 S-down to test the range.
2902 When this variable is set to t, the date/time prompt will not let
2903 you specify dates outside the 1970-2037 range, so it is certain that
2904 these dates will work in whatever version of Emacs you are
2905 running, and also that you can move a file from one Emacs implementation
2906 to another. WHenever Org is forcing the year for you, it will display
2907 a message and beep.
2909 When this variable is nil, Org will check if the date is
2910 representable in the specific Emacs implementation you are using.
2911 If not, it will force a year, usually the current year, and beep
2912 to remind you. Currently this setting is not recommended because
2913 the likelihood that you will open your Org files in an Emacs that
2914 has limited date range is not negligible.
2916 A workaround for this problem is to use diary sexp dates for time
2917 stamps outside of this range."
2918 :group 'org-time
2919 :version "24.1"
2920 :type 'boolean)
2922 (defcustom org-read-date-display-live t
2923 "Non-nil means display current interpretation of date prompt live.
2924 This display will be in an overlay, in the minibuffer."
2925 :group 'org-time
2926 :type 'boolean)
2928 (defcustom org-read-date-popup-calendar t
2929 "Non-nil means pop up a calendar when prompting for a date.
2930 In the calendar, the date can be selected with mouse-1. However, the
2931 minibuffer will also be active, and you can simply enter the date as well.
2932 When nil, only the minibuffer will be available."
2933 :group 'org-time
2934 :type 'boolean)
2935 (if (fboundp 'defvaralias)
2936 (defvaralias 'org-popup-calendar-for-date-prompt
2937 'org-read-date-popup-calendar))
2939 (defcustom org-read-date-minibuffer-setup-hook nil
2940 "Hook to be used to set up keys for the date/time interface.
2941 Add key definitions to `minibuffer-local-map', which will be a temporary
2942 copy."
2943 :group 'org-time
2944 :type 'hook)
2946 (defcustom org-extend-today-until 0
2947 "The hour when your day really ends. Must be an integer.
2948 This has influence for the following applications:
2949 - When switching the agenda to \"today\". It it is still earlier than
2950 the time given here, the day recognized as TODAY is actually yesterday.
2951 - When a date is read from the user and it is still before the time given
2952 here, the current date and time will be assumed to be yesterday, 23:59.
2953 Also, timestamps inserted in capture templates follow this rule.
2955 IMPORTANT: This is a feature whose implementation is and likely will
2956 remain incomplete. Really, it is only here because past midnight seems to
2957 be the favorite working time of John Wiegley :-)"
2958 :group 'org-time
2959 :type 'integer)
2961 (defcustom org-use-effective-time nil
2962 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2963 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2964 \"effective time\" of any timestamps between midnight and 8am will be
2965 23:59 of the previous day."
2966 :group 'org-time
2967 :version "24.1"
2968 :type 'boolean)
2970 (defcustom org-use-last-clock-out-time-as-effective-time nil
2971 "When non-nil, use the last clock out time for `org-todo'.
2972 Note that this option has precedence over the combined use of
2973 `org-use-effective-time' and `org-extend-today-until'."
2974 :group 'org-time
2975 ;; :version "24.3"
2976 :type 'boolean)
2978 (defcustom org-edit-timestamp-down-means-later nil
2979 "Non-nil means S-down will increase the time in a time stamp.
2980 When nil, S-up will increase."
2981 :group 'org-time
2982 :type 'boolean)
2984 (defcustom org-calendar-follow-timestamp-change t
2985 "Non-nil means make the calendar window follow timestamp changes.
2986 When a timestamp is modified and the calendar window is visible, it will be
2987 moved to the new date."
2988 :group 'org-time
2989 :type 'boolean)
2991 (defgroup org-tags nil
2992 "Options concerning tags in Org-mode."
2993 :tag "Org Tags"
2994 :group 'org)
2996 (defcustom org-tag-alist nil
2997 "List of tags allowed in Org-mode files.
2998 When this list is nil, Org-mode will base TAG input on what is already in the
2999 buffer.
3000 The value of this variable is an alist, the car of each entry must be a
3001 keyword as a string, the cdr may be a character that is used to select
3002 that tag through the fast-tag-selection interface.
3003 See the manual for details."
3004 :group 'org-tags
3005 :type '(repeat
3006 (choice
3007 (cons (string :tag "Tag name")
3008 (character :tag "Access char"))
3009 (list :tag "Start radio group"
3010 (const :startgroup)
3011 (option (string :tag "Group description")))
3012 (list :tag "End radio group"
3013 (const :endgroup)
3014 (option (string :tag "Group description")))
3015 (const :tag "New line" (:newline)))))
3017 (defcustom org-tag-persistent-alist nil
3018 "List of tags that will always appear in all Org-mode files.
3019 This is in addition to any in buffer settings or customizations
3020 of `org-tag-alist'.
3021 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3022 The value of this variable is an alist, the car of each entry must be a
3023 keyword as a string, the cdr may be a character that is used to select
3024 that tag through the fast-tag-selection interface.
3025 See the manual for details.
3026 To disable these tags on a per-file basis, insert anywhere in the file:
3027 #+STARTUP: noptag"
3028 :group 'org-tags
3029 :type '(repeat
3030 (choice
3031 (cons (string :tag "Tag name")
3032 (character :tag "Access char"))
3033 (const :tag "Start radio group" (:startgroup))
3034 (const :tag "End radio group" (:endgroup))
3035 (const :tag "New line" (:newline)))))
3037 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3038 "If non-nil, always offer completion for all tags of all agenda files.
3039 Instead of customizing this variable directly, you might want to
3040 set it locally for capture buffers, because there no list of
3041 tags in that file can be created dynamically (there are none).
3043 (add-hook 'org-capture-mode-hook
3044 (lambda ()
3045 (set (make-local-variable
3046 'org-complete-tags-always-offer-all-agenda-tags)
3047 t)))"
3048 :group 'org-tags
3049 :version "24.1"
3050 :type 'boolean)
3052 (defvar org-file-tags nil
3053 "List of tags that can be inherited by all entries in the file.
3054 The tags will be inherited if the variable `org-use-tag-inheritance'
3055 says they should be.
3056 This variable is populated from #+FILETAGS lines.")
3058 (defcustom org-use-fast-tag-selection 'auto
3059 "Non-nil means use fast tag selection scheme.
3060 This is a special interface to select and deselect tags with single keys.
3061 When nil, fast selection is never used.
3062 When the symbol `auto', fast selection is used if and only if selection
3063 characters for tags have been configured, either through the variable
3064 `org-tag-alist' or through a #+TAGS line in the buffer.
3065 When t, fast selection is always used and selection keys are assigned
3066 automatically if necessary."
3067 :group 'org-tags
3068 :type '(choice
3069 (const :tag "Always" t)
3070 (const :tag "Never" nil)
3071 (const :tag "When selection characters are configured" 'auto)))
3073 (defcustom org-fast-tag-selection-single-key nil
3074 "Non-nil means fast tag selection exits after first change.
3075 When nil, you have to press RET to exit it.
3076 During fast tag selection, you can toggle this flag with `C-c'.
3077 This variable can also have the value `expert'. In this case, the window
3078 displaying the tags menu is not even shown, until you press C-c again."
3079 :group 'org-tags
3080 :type '(choice
3081 (const :tag "No" nil)
3082 (const :tag "Yes" t)
3083 (const :tag "Expert" expert)))
3085 (defvar org-fast-tag-selection-include-todo nil
3086 "Non-nil means fast tags selection interface will also offer TODO states.
3087 This is an undocumented feature, you should not rely on it.")
3089 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3090 "The column to which tags should be indented in a headline.
3091 If this number is positive, it specifies the column. If it is negative,
3092 it means that the tags should be flushright to that column. For example,
3093 -80 works well for a normal 80 character screen.
3094 When 0, place tags directly after headline text, with only one space in
3095 between."
3096 :group 'org-tags
3097 :type 'integer)
3099 (defcustom org-auto-align-tags t
3100 "Non-nil keeps tags aligned when modifying headlines.
3101 Some operations (i.e. demoting) change the length of a headline and
3102 therefore shift the tags around. With this option turned on, after
3103 each such operation the tags are again aligned to `org-tags-column'."
3104 :group 'org-tags
3105 :type 'boolean)
3107 (defcustom org-use-tag-inheritance t
3108 "Non-nil means tags in levels apply also for sublevels.
3109 When nil, only the tags directly given in a specific line apply there.
3110 This may also be a list of tags that should be inherited, or a regexp that
3111 matches tags that should be inherited. Additional control is possible
3112 with the variable `org-tags-exclude-from-inheritance' which gives an
3113 explicit list of tags to be excluded from inheritance., even if the value of
3114 `org-use-tag-inheritance' would select it for inheritance.
3116 If this option is t, a match early-on in a tree can lead to a large
3117 number of matches in the subtree when constructing the agenda or creating
3118 a sparse tree. If you only want to see the first match in a tree during
3119 a search, check out the variable `org-tags-match-list-sublevels'."
3120 :group 'org-tags
3121 :type '(choice
3122 (const :tag "Not" nil)
3123 (const :tag "Always" t)
3124 (repeat :tag "Specific tags" (string :tag "Tag"))
3125 (regexp :tag "Tags matched by regexp")))
3127 (defcustom org-tags-exclude-from-inheritance nil
3128 "List of tags that should never be inherited.
3129 This is a way to exclude a few tags from inheritance. For way to do
3130 the opposite, to actively allow inheritance for selected tags,
3131 see the variable `org-use-tag-inheritance'."
3132 :group 'org-tags
3133 :type '(repeat (string :tag "Tag")))
3135 (defun org-tag-inherit-p (tag)
3136 "Check if TAG is one that should be inherited."
3137 (cond
3138 ((member tag org-tags-exclude-from-inheritance) nil)
3139 ((eq org-use-tag-inheritance t) t)
3140 ((not org-use-tag-inheritance) nil)
3141 ((stringp org-use-tag-inheritance)
3142 (string-match org-use-tag-inheritance tag))
3143 ((listp org-use-tag-inheritance)
3144 (member tag org-use-tag-inheritance))
3145 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3147 (defcustom org-tags-match-list-sublevels t
3148 "Non-nil means list also sublevels of headlines matching a search.
3149 This variable applies to tags/property searches, and also to stuck
3150 projects because this search is based on a tags match as well.
3152 When set to the symbol `indented', sublevels are indented with
3153 leading dots.
3155 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3156 the sublevels of a headline matching a tag search often also match
3157 the same search. Listing all of them can create very long lists.
3158 Setting this variable to nil causes subtrees of a match to be skipped.
3160 This variable is semi-obsolete and probably should always be true. It
3161 is better to limit inheritance to certain tags using the variables
3162 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3163 :group 'org-tags
3164 :type '(choice
3165 (const :tag "No, don't list them" nil)
3166 (const :tag "Yes, do list them" t)
3167 (const :tag "List them, indented with leading dots" indented)))
3169 (defcustom org-tags-sort-function nil
3170 "When set, tags are sorted using this function as a comparator."
3171 :group 'org-tags
3172 :type '(choice
3173 (const :tag "No sorting" nil)
3174 (const :tag "Alphabetical" string<)
3175 (const :tag "Reverse alphabetical" string>)
3176 (function :tag "Custom function" nil)))
3178 (defvar org-tags-history nil
3179 "History of minibuffer reads for tags.")
3180 (defvar org-last-tags-completion-table nil
3181 "The last used completion table for tags.")
3182 (defvar org-after-tags-change-hook nil
3183 "Hook that is run after the tags in a line have changed.")
3185 (defgroup org-properties nil
3186 "Options concerning properties in Org-mode."
3187 :tag "Org Properties"
3188 :group 'org)
3190 (defcustom org-property-format "%-10s %s"
3191 "How property key/value pairs should be formatted by `indent-line'.
3192 When `indent-line' hits a property definition, it will format the line
3193 according to this format, mainly to make sure that the values are
3194 lined-up with respect to each other."
3195 :group 'org-properties
3196 :type 'string)
3198 (defcustom org-properties-postprocess-alist nil
3199 "Alist of properties and functions to adjust inserted values.
3200 Elements of this alist must be of the form
3202 ([string] [function])
3204 where [string] must be a property name and [function] must be a
3205 lambda expression: this lambda expression must take one argument,
3206 the value to adjust, and return the new value as a string.
3208 For example, this element will allow the property \"Remaining\"
3209 to be updated wrt the relation between the \"Effort\" property
3210 and the clock summary:
3212 ((\"Remaining\" (lambda(value)
3213 (let ((clocksum (org-clock-sum-current-item))
3214 (effort (org-duration-string-to-minutes
3215 (org-entry-get (point) \"Effort\"))))
3216 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3217 :group 'org-properties
3218 :version "24.1"
3219 :type '(alist :key-type (string :tag "Property")
3220 :value-type (function :tag "Function")))
3222 (defcustom org-use-property-inheritance nil
3223 "Non-nil means properties apply also for sublevels.
3225 This setting is chiefly used during property searches. Turning it on can
3226 cause significant overhead when doing a search, which is why it is not
3227 on by default.
3229 When nil, only the properties directly given in the current entry count.
3230 When t, every property is inherited. The value may also be a list of
3231 properties that should have inheritance, or a regular expression matching
3232 properties that should be inherited.
3234 However, note that some special properties use inheritance under special
3235 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3236 and the properties ending in \"_ALL\" when they are used as descriptor
3237 for valid values of a property.
3239 Note for programmers:
3240 When querying an entry with `org-entry-get', you can control if inheritance
3241 should be used. By default, `org-entry-get' looks only at the local
3242 properties. You can request inheritance by setting the inherit argument
3243 to t (to force inheritance) or to `selective' (to respect the setting
3244 in this variable)."
3245 :group 'org-properties
3246 :type '(choice
3247 (const :tag "Not" nil)
3248 (const :tag "Always" t)
3249 (repeat :tag "Specific properties" (string :tag "Property"))
3250 (regexp :tag "Properties matched by regexp")))
3252 (defun org-property-inherit-p (property)
3253 "Check if PROPERTY is one that should be inherited."
3254 (cond
3255 ((eq org-use-property-inheritance t) t)
3256 ((not org-use-property-inheritance) nil)
3257 ((stringp org-use-property-inheritance)
3258 (string-match org-use-property-inheritance property))
3259 ((listp org-use-property-inheritance)
3260 (member property org-use-property-inheritance))
3261 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3263 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3264 "The default column format, if no other format has been defined.
3265 This variable can be set on the per-file basis by inserting a line
3267 #+COLUMNS: %25ITEM ....."
3268 :group 'org-properties
3269 :type 'string)
3271 (defcustom org-columns-ellipses ".."
3272 "The ellipses to be used when a field in column view is truncated.
3273 When this is the empty string, as many characters as possible are shown,
3274 but then there will be no visual indication that the field has been truncated.
3275 When this is a string of length N, the last N characters of a truncated
3276 field are replaced by this string. If the column is narrower than the
3277 ellipses string, only part of the ellipses string will be shown."
3278 :group 'org-properties
3279 :type 'string)
3281 (defcustom org-columns-modify-value-for-display-function nil
3282 "Function that modifies values for display in column view.
3283 For example, it can be used to cut out a certain part from a time stamp.
3284 The function must take 2 arguments:
3286 column-title The title of the column (*not* the property name)
3287 value The value that should be modified.
3289 The function should return the value that should be displayed,
3290 or nil if the normal value should be used."
3291 :group 'org-properties
3292 :type 'function)
3294 (defcustom org-effort-property "Effort"
3295 "The property that is being used to keep track of effort estimates.
3296 Effort estimates given in this property need to have the format H:MM."
3297 :group 'org-properties
3298 :group 'org-progress
3299 :type '(string :tag "Property"))
3301 (defconst org-global-properties-fixed
3302 '(("VISIBILITY_ALL" . "folded children content all")
3303 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3304 "List of property/value pairs that can be inherited by any entry.
3306 These are fixed values, for the preset properties. The user variable
3307 that can be used to add to this list is `org-global-properties'.
3309 The entries in this list are cons cells where the car is a property
3310 name and cdr is a string with the value. If the value represents
3311 multiple items like an \"_ALL\" property, separate the items by
3312 spaces.")
3314 (defcustom org-global-properties nil
3315 "List of property/value pairs that can be inherited by any entry.
3317 This list will be combined with the constant `org-global-properties-fixed'.
3319 The entries in this list are cons cells where the car is a property
3320 name and cdr is a string with the value.
3322 You can set buffer-local values for the same purpose in the variable
3323 `org-file-properties' this by adding lines like
3325 #+PROPERTY: NAME VALUE"
3326 :group 'org-properties
3327 :type '(repeat
3328 (cons (string :tag "Property")
3329 (string :tag "Value"))))
3331 (defvar org-file-properties nil
3332 "List of property/value pairs that can be inherited by any entry.
3333 Valid for the current buffer.
3334 This variable is populated from #+PROPERTY lines.")
3335 (make-variable-buffer-local 'org-file-properties)
3337 (defgroup org-agenda nil
3338 "Options concerning agenda views in Org-mode."
3339 :tag "Org Agenda"
3340 :group 'org)
3342 (defvar org-category nil
3343 "Variable used by org files to set a category for agenda display.
3344 Such files should use a file variable to set it, for example
3346 # -*- mode: org; org-category: \"ELisp\"
3348 or contain a special line
3350 #+CATEGORY: ELisp
3352 If the file does not specify a category, then file's base name
3353 is used instead.")
3354 (make-variable-buffer-local 'org-category)
3355 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3357 (defcustom org-agenda-files nil
3358 "The files to be used for agenda display.
3359 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3360 \\[org-remove-file]. You can also use customize to edit the list.
3362 If an entry is a directory, all files in that directory that are matched by
3363 `org-agenda-file-regexp' will be part of the file list.
3365 If the value of the variable is not a list but a single file name, then
3366 the list of agenda files is actually stored and maintained in that file, one
3367 agenda file per line. In this file paths can be given relative to
3368 `org-directory'. Tilde expansion and environment variable substitution
3369 are also made."
3370 :group 'org-agenda
3371 :type '(choice
3372 (repeat :tag "List of files and directories" file)
3373 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3375 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3376 "Regular expression to match files for `org-agenda-files'.
3377 If any element in the list in that variable contains a directory instead
3378 of a normal file, all files in that directory that are matched by this
3379 regular expression will be included."
3380 :group 'org-agenda
3381 :type 'regexp)
3383 (defcustom org-agenda-text-search-extra-files nil
3384 "List of extra files to be searched by text search commands.
3385 These files will be search in addition to the agenda files by the
3386 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3387 Note that these files will only be searched for text search commands,
3388 not for the other agenda views like todo lists, tag searches or the weekly
3389 agenda. This variable is intended to list notes and possibly archive files
3390 that should also be searched by these two commands.
3391 In fact, if the first element in the list is the symbol `agenda-archives',
3392 than all archive files of all agenda files will be added to the search
3393 scope."
3394 :group 'org-agenda
3395 :type '(set :greedy t
3396 (const :tag "Agenda Archives" agenda-archives)
3397 (repeat :inline t (file))))
3399 (if (fboundp 'defvaralias)
3400 (defvaralias 'org-agenda-multi-occur-extra-files
3401 'org-agenda-text-search-extra-files))
3403 (defcustom org-agenda-skip-unavailable-files nil
3404 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3405 A nil value means to remove them, after a query, from the list."
3406 :group 'org-agenda
3407 :type 'boolean)
3409 (defcustom org-calendar-to-agenda-key [?c]
3410 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3411 The command `org-calendar-goto-agenda' will be bound to this key. The
3412 default is the character `c' because then `c' can be used to switch back and
3413 forth between agenda and calendar."
3414 :group 'org-agenda
3415 :type 'sexp)
3417 (defcustom org-calendar-insert-diary-entry-key [?i]
3418 "The key to be installed in `calendar-mode-map' for adding diary entries.
3419 This option is irrelevant until `org-agenda-diary-file' has been configured
3420 to point to an Org-mode file. When that is the case, the command
3421 `org-agenda-diary-entry' will be bound to the key given here, by default
3422 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3423 if you want to continue doing this, you need to change this to a different
3424 key."
3425 :group 'org-agenda
3426 :type 'sexp)
3428 (defcustom org-agenda-diary-file 'diary-file
3429 "File to which to add new entries with the `i' key in agenda and calendar.
3430 When this is the symbol `diary-file', the functionality in the Emacs
3431 calendar will be used to add entries to the `diary-file'. But when this
3432 points to a file, `org-agenda-diary-entry' will be used instead."
3433 :group 'org-agenda
3434 :type '(choice
3435 (const :tag "The standard Emacs diary file" diary-file)
3436 (file :tag "Special Org file diary entries")))
3438 (eval-after-load "calendar"
3439 '(progn
3440 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3441 'org-calendar-goto-agenda)
3442 (add-hook 'calendar-mode-hook
3443 (lambda ()
3444 (unless (eq org-agenda-diary-file 'diary-file)
3445 (define-key calendar-mode-map
3446 org-calendar-insert-diary-entry-key
3447 'org-agenda-diary-entry))))))
3449 (defgroup org-latex nil
3450 "Options for embedding LaTeX code into Org-mode."
3451 :tag "Org LaTeX"
3452 :group 'org)
3454 (defcustom org-format-latex-options
3455 '(:foreground default :background default :scale 1.0
3456 :html-foreground "Black" :html-background "Transparent"
3457 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3458 "Options for creating images from LaTeX fragments.
3459 This is a property list with the following properties:
3460 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3461 `default' means use the foreground of the default face.
3462 `auto' means use the foreground from the text face.
3463 :background the background color, or \"Transparent\".
3464 `default' means use the background of the default face.
3465 `auto' means use the background from the text face.
3466 :scale a scaling factor for the size of the images, to get more pixels
3467 :html-foreground, :html-background, :html-scale
3468 the same numbers for HTML export.
3469 :matchers a list indicating which matchers should be used to
3470 find LaTeX fragments. Valid members of this list are:
3471 \"begin\" find environments
3472 \"$1\" find single characters surrounded by $.$
3473 \"$\" find math expressions surrounded by $...$
3474 \"$$\" find math expressions surrounded by $$....$$
3475 \"\\(\" find math expressions surrounded by \\(...\\)
3476 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3477 :group 'org-latex
3478 :type 'plist)
3480 (defcustom org-format-latex-signal-error t
3481 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3482 When nil, just push out a message."
3483 :group 'org-latex
3484 :version "24.1"
3485 :type 'boolean)
3487 (defcustom org-latex-to-mathml-jar-file nil
3488 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3489 Use this to specify additional executable file say a jar file.
3491 When using MathToWeb as the converter, specify the full-path to
3492 your mathtoweb.jar file."
3493 :group 'org-latex
3494 :version "24.1"
3495 :type '(choice
3496 (const :tag "None" nil)
3497 (file :tag "JAR file" :must-match t)))
3499 (defcustom org-latex-to-mathml-convert-command nil
3500 "Command to convert LaTeX fragments to MathML.
3501 Replace format-specifiers in the command as noted below and use
3502 `shell-command' to convert LaTeX to MathML.
3503 %j: Executable file in fully expanded form as specified by
3504 `org-latex-to-mathml-jar-file'.
3505 %I: Input LaTeX file in fully expanded form
3506 %o: Output MathML file
3507 This command is used by `org-create-math-formula'.
3509 When using MathToWeb as the converter, set this to
3510 \"java -jar %j -unicode -force -df %o %I\"."
3511 :group 'org-latex
3512 :version "24.1"
3513 :type '(choice
3514 (const :tag "None" nil)
3515 (string :tag "\nShell command")))
3517 (defcustom org-latex-create-formula-image-program 'dvipng
3518 "Program to convert LaTeX fragments with.
3520 dvipng Process the LaTeX fragments to dvi file, then convert
3521 dvi files to png files using dvipng.
3522 This will also include processing of non-math environments.
3523 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3524 to convert pdf files to png files"
3525 :group 'org-latex
3526 :version "24.1"
3527 :type '(choice
3528 (const :tag "dvipng" dvipng)
3529 (const :tag "imagemagick" imagemagick)))
3531 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3532 "Path to store latex preview images.
3533 A relative path here creates many directories relative to the
3534 processed org files paths. An absolute path puts all preview
3535 images at the same place."
3536 :group 'org-latex
3537 :version "24.3"
3538 :type 'string)
3540 (defun org-format-latex-mathml-available-p ()
3541 "Return t if `org-latex-to-mathml-convert-command' is usable."
3542 (save-match-data
3543 (when (and (boundp 'org-latex-to-mathml-convert-command)
3544 org-latex-to-mathml-convert-command)
3545 (let ((executable (car (split-string
3546 org-latex-to-mathml-convert-command))))
3547 (when (executable-find executable)
3548 (if (string-match
3549 "%j" org-latex-to-mathml-convert-command)
3550 (file-readable-p org-latex-to-mathml-jar-file)
3551 t))))))
3553 (defcustom org-format-latex-header "\\documentclass{article}
3554 \\usepackage[usenames]{color}
3555 \\usepackage{amsmath}
3556 \\usepackage[mathscr]{eucal}
3557 \\pagestyle{empty} % do not remove
3558 \[PACKAGES]
3559 \[DEFAULT-PACKAGES]
3560 % The settings below are copied from fullpage.sty
3561 \\setlength{\\textwidth}{\\paperwidth}
3562 \\addtolength{\\textwidth}{-3cm}
3563 \\setlength{\\oddsidemargin}{1.5cm}
3564 \\addtolength{\\oddsidemargin}{-2.54cm}
3565 \\setlength{\\evensidemargin}{\\oddsidemargin}
3566 \\setlength{\\textheight}{\\paperheight}
3567 \\addtolength{\\textheight}{-\\headheight}
3568 \\addtolength{\\textheight}{-\\headsep}
3569 \\addtolength{\\textheight}{-\\footskip}
3570 \\addtolength{\\textheight}{-3cm}
3571 \\setlength{\\topmargin}{1.5cm}
3572 \\addtolength{\\topmargin}{-2.54cm}"
3573 "The document header used for processing LaTeX fragments.
3574 It is imperative that this header make sure that no page number
3575 appears on the page. The package defined in the variables
3576 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3577 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3578 will be appended."
3579 :group 'org-latex
3580 :type 'string)
3582 (defvar org-format-latex-header-extra nil)
3584 (defun org-set-packages-alist (var val)
3585 "Set the packages alist and make sure it has 3 elements per entry."
3586 (set var (mapcar (lambda (x)
3587 (if (and (consp x) (= (length x) 2))
3588 (list (car x) (nth 1 x) t)
3590 val)))
3592 (defun org-get-packages-alist (var)
3594 "Get the packages alist and make sure it has 3 elements per entry."
3595 (mapcar (lambda (x)
3596 (if (and (consp x) (= (length x) 2))
3597 (list (car x) (nth 1 x) t)
3599 (default-value var)))
3601 ;; The following variables are defined here because is it also used
3602 ;; when formatting latex fragments. Originally it was part of the
3603 ;; LaTeX exporter, which is why the name includes "export".
3604 (defcustom org-export-latex-default-packages-alist
3605 '(("AUTO" "inputenc" t)
3606 ("T1" "fontenc" t)
3607 ("" "fixltx2e" nil)
3608 ("" "graphicx" t)
3609 ("" "longtable" nil)
3610 ("" "float" nil)
3611 ("" "wrapfig" nil)
3612 ("" "soul" t)
3613 ("" "textcomp" t)
3614 ("" "marvosym" t)
3615 ("" "wasysym" t)
3616 ("" "latexsym" t)
3617 ("" "amssymb" t)
3618 ("" "hyperref" nil)
3619 "\\tolerance=1000"
3621 "Alist of default packages to be inserted in the header.
3622 Change this only if one of the packages here causes an incompatibility
3623 with another package you are using.
3624 The packages in this list are needed by one part or another of Org-mode
3625 to function properly.
3627 - inputenc, fontenc: for basic font and character selection
3628 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3629 for interpreting the entities in `org-entities'. You can skip some of these
3630 packages if you don't use any of the symbols in it.
3631 - graphicx: for including images
3632 - float, wrapfig: for figure placement
3633 - longtable: for long tables
3634 - hyperref: for cross references
3636 Therefore you should not modify this variable unless you know what you
3637 are doing. The one reason to change it anyway is that you might be loading
3638 some other package that conflicts with one of the default packages.
3639 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3640 If SNIPPET-FLAG is t, the package also needs to be included when
3641 compiling LaTeX snippets into images for inclusion into HTML."
3642 :group 'org-export-latex
3643 :set 'org-set-packages-alist
3644 :get 'org-get-packages-alist
3645 :version "24.1"
3646 :type '(repeat
3647 (choice
3648 (list :tag "options/package pair"
3649 (string :tag "options")
3650 (string :tag "package")
3651 (boolean :tag "Snippet"))
3652 (string :tag "A line of LaTeX"))))
3654 (defcustom org-export-latex-packages-alist nil
3655 "Alist of packages to be inserted in every LaTeX header.
3656 These will be inserted after `org-export-latex-default-packages-alist'.
3657 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3658 SNIPPET-FLAG, when t, indicates that this package is also needed when
3659 turning LaTeX snippets into images for inclusion into HTML.
3660 Make sure that you only list packages here which:
3661 - you want in every file
3662 - do not conflict with the default packages in
3663 `org-export-latex-default-packages-alist'
3664 - do not conflict with the setup in `org-format-latex-header'."
3665 :group 'org-export-latex
3666 :set 'org-set-packages-alist
3667 :get 'org-get-packages-alist
3668 :type '(repeat
3669 (choice
3670 (list :tag "options/package pair"
3671 (string :tag "options")
3672 (string :tag "package")
3673 (boolean :tag "Snippet"))
3674 (string :tag "A line of LaTeX"))))
3677 (defgroup org-appearance nil
3678 "Settings for Org-mode appearance."
3679 :tag "Org Appearance"
3680 :group 'org)
3682 (defcustom org-level-color-stars-only nil
3683 "Non-nil means fontify only the stars in each headline.
3684 When nil, the entire headline is fontified.
3685 Changing it requires restart of `font-lock-mode' to become effective
3686 also in regions already fontified."
3687 :group 'org-appearance
3688 :type 'boolean)
3690 (defcustom org-hide-leading-stars nil
3691 "Non-nil means hide the first N-1 stars in a headline.
3692 This works by using the face `org-hide' for these stars. This
3693 face is white for a light background, and black for a dark
3694 background. You may have to customize the face `org-hide' to
3695 make this work.
3696 Changing it requires restart of `font-lock-mode' to become effective
3697 also in regions already fontified.
3698 You may also set this on a per-file basis by adding one of the following
3699 lines to the buffer:
3701 #+STARTUP: hidestars
3702 #+STARTUP: showstars"
3703 :group 'org-appearance
3704 :type 'boolean)
3706 (defcustom org-hidden-keywords nil
3707 "List of symbols corresponding to keywords to be hidden the org buffer.
3708 For example, a value '(title) for this list will make the document's title
3709 appear in the buffer without the initial #+TITLE: keyword."
3710 :group 'org-appearance
3711 :version "24.1"
3712 :type '(set (const :tag "#+AUTHOR" author)
3713 (const :tag "#+DATE" date)
3714 (const :tag "#+EMAIL" email)
3715 (const :tag "#+TITLE" title)))
3717 (defcustom org-custom-properties nil
3718 "List of properties (as strings) with a special meaning.
3719 The default use of these custom properties is to let the user
3720 hide them with `org-toggle-custom-properties-visibility'."
3721 :group 'org-properties
3722 :group 'org-appearance
3723 :version "24.3"
3724 :type '(repeat (string :tag "Property Name")))
3726 (defcustom org-fontify-done-headline nil
3727 "Non-nil means change the face of a headline if it is marked DONE.
3728 Normally, only the TODO/DONE keyword indicates the state of a headline.
3729 When this is non-nil, the headline after the keyword is set to the
3730 `org-headline-done' as an additional indication."
3731 :group 'org-appearance
3732 :type 'boolean)
3734 (defcustom org-fontify-emphasized-text t
3735 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3736 Changing this variable requires a restart of Emacs to take effect."
3737 :group 'org-appearance
3738 :type 'boolean)
3740 (defcustom org-fontify-whole-heading-line nil
3741 "Non-nil means fontify the whole line for headings.
3742 This is useful when setting a background color for the
3743 org-level-* faces."
3744 :group 'org-appearance
3745 :type 'boolean)
3747 (defcustom org-highlight-latex-fragments-and-specials nil
3748 "Non-nil means fontify what is treated specially by the exporters."
3749 :group 'org-appearance
3750 :type 'boolean)
3752 (defcustom org-hide-emphasis-markers nil
3753 "Non-nil mean font-lock should hide the emphasis marker characters."
3754 :group 'org-appearance
3755 :type 'boolean)
3757 (defcustom org-pretty-entities nil
3758 "Non-nil means show entities as UTF8 characters.
3759 When nil, the \\name form remains in the buffer."
3760 :group 'org-appearance
3761 :version "24.1"
3762 :type 'boolean)
3764 (defcustom org-pretty-entities-include-sub-superscripts t
3765 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3766 :group 'org-appearance
3767 :version "24.1"
3768 :type 'boolean)
3770 (defvar org-emph-re nil
3771 "Regular expression for matching emphasis.
3772 After a match, the match groups contain these elements:
3773 0 The match of the full regular expression, including the characters
3774 before and after the proper match
3775 1 The character before the proper match, or empty at beginning of line
3776 2 The proper match, including the leading and trailing markers
3777 3 The leading marker like * or /, indicating the type of highlighting
3778 4 The text between the emphasis markers, not including the markers
3779 5 The character after the match, empty at the end of a line")
3780 (defvar org-verbatim-re nil
3781 "Regular expression for matching verbatim text.")
3782 (defvar org-emphasis-regexp-components) ; defined just below
3783 (defvar org-emphasis-alist) ; defined just below
3784 (defun org-set-emph-re (var val)
3785 "Set variable and compute the emphasis regular expression."
3786 (set var val)
3787 (when (and (boundp 'org-emphasis-alist)
3788 (boundp 'org-emphasis-regexp-components)
3789 org-emphasis-alist org-emphasis-regexp-components)
3790 (let* ((e org-emphasis-regexp-components)
3791 (pre (car e))
3792 (post (nth 1 e))
3793 (border (nth 2 e))
3794 (body (nth 3 e))
3795 (nl (nth 4 e))
3796 (body1 (concat body "*?"))
3797 (markers (mapconcat 'car org-emphasis-alist ""))
3798 (vmarkers (mapconcat
3799 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3800 org-emphasis-alist "")))
3801 ;; make sure special characters appear at the right position in the class
3802 (if (string-match "\\^" markers)
3803 (setq markers (concat (replace-match "" t t markers) "^")))
3804 (if (string-match "-" markers)
3805 (setq markers (concat (replace-match "" t t markers) "-")))
3806 (if (string-match "\\^" vmarkers)
3807 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3808 (if (string-match "-" vmarkers)
3809 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3810 (if (> nl 0)
3811 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3812 (int-to-string nl) "\\}")))
3813 ;; Make the regexp
3814 (setq org-emph-re
3815 (concat "\\([" pre "]\\|^\\)"
3816 "\\("
3817 "\\([" markers "]\\)"
3818 "\\("
3819 "[^" border "]\\|"
3820 "[^" border "]"
3821 body1
3822 "[^" border "]"
3823 "\\)"
3824 "\\3\\)"
3825 "\\([" post "]\\|$\\)"))
3826 (setq org-verbatim-re
3827 (concat "\\([" pre "]\\|^\\)"
3828 "\\("
3829 "\\([" vmarkers "]\\)"
3830 "\\("
3831 "[^" border "]\\|"
3832 "[^" border "]"
3833 body1
3834 "[^" border "]"
3835 "\\)"
3836 "\\3\\)"
3837 "\\([" post "]\\|$\\)")))))
3839 (defcustom org-emphasis-regexp-components
3840 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3841 "Components used to build the regular expression for emphasis.
3842 This is a list with five entries. Terminology: In an emphasis string
3843 like \" *strong word* \", we call the initial space PREMATCH, the final
3844 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3845 and \"trong wor\" is the body. The different components in this variable
3846 specify what is allowed/forbidden in each part:
3848 pre Chars allowed as prematch. Beginning of line will be allowed too.
3849 post Chars allowed as postmatch. End of line will be allowed too.
3850 border The chars *forbidden* as border characters.
3851 body-regexp A regexp like \".\" to match a body character. Don't use
3852 non-shy groups here, and don't allow newline here.
3853 newline The maximum number of newlines allowed in an emphasis exp.
3855 Use customize to modify this, or restart Emacs after changing it."
3856 :group 'org-appearance
3857 :set 'org-set-emph-re
3858 :type '(list
3859 (sexp :tag "Allowed chars in pre ")
3860 (sexp :tag "Allowed chars in post ")
3861 (sexp :tag "Forbidden chars in border ")
3862 (sexp :tag "Regexp for body ")
3863 (integer :tag "number of newlines allowed")
3864 (option (boolean :tag "Please ignore this button"))))
3866 (defcustom org-emphasis-alist
3867 `(("*" bold "<b>" "</b>")
3868 ("/" italic "<i>" "</i>")
3869 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3870 ("=" org-code "<code>" "</code>" verbatim)
3871 ("~" org-verbatim "<code>" "</code>" verbatim)
3872 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3873 "<del>" "</del>")
3875 "Special syntax for emphasized text.
3876 Text starting and ending with a special character will be emphasized, for
3877 example *bold*, _underlined_ and /italic/. This variable sets the marker
3878 characters, the face to be used by font-lock for highlighting in Org-mode
3879 Emacs buffers, and the HTML tags to be used for this.
3880 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3881 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3882 Use customize to modify this, or restart Emacs after changing it."
3883 :group 'org-appearance
3884 :set 'org-set-emph-re
3885 :type '(repeat
3886 (list
3887 (string :tag "Marker character")
3888 (choice
3889 (face :tag "Font-lock-face")
3890 (plist :tag "Face property list"))
3891 (string :tag "HTML start tag")
3892 (string :tag "HTML end tag")
3893 (option (const verbatim)))))
3895 (defvar org-syntax-table
3896 (let ((st (make-syntax-table)))
3897 (mapc (lambda(c) (modify-syntax-entry
3898 (string-to-char (car c)) "w p" st))
3899 org-emphasis-alist)
3900 st))
3902 (defvar org-protecting-blocks
3903 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3904 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3905 This is needed for font-lock setup.")
3907 ;;; Miscellaneous options
3909 (defgroup org-completion nil
3910 "Completion in Org-mode."
3911 :tag "Org Completion"
3912 :group 'org)
3914 (defcustom org-completion-use-ido nil
3915 "Non-nil means use ido completion wherever possible.
3916 Note that `ido-mode' must be active for this variable to be relevant.
3917 If you decide to turn this variable on, you might well want to turn off
3918 `org-outline-path-complete-in-steps'.
3919 See also `org-completion-use-iswitchb'."
3920 :group 'org-completion
3921 :type 'boolean)
3923 (defcustom org-completion-use-iswitchb nil
3924 "Non-nil means use iswitchb completion wherever possible.
3925 Note that `iswitchb-mode' must be active for this variable to be relevant.
3926 If you decide to turn this variable on, you might well want to turn off
3927 `org-outline-path-complete-in-steps'.
3928 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3929 :group 'org-completion
3930 :type 'boolean)
3932 (defcustom org-completion-fallback-command 'hippie-expand
3933 "The expansion command called by \\[pcomplete] in normal context.
3934 Normal means, no org-mode-specific context."
3935 :group 'org-completion
3936 :type 'function)
3938 ;;; Functions and variables from their packages
3939 ;; Declared here to avoid compiler warnings
3941 ;; XEmacs only
3942 (defvar outline-mode-menu-heading)
3943 (defvar outline-mode-menu-show)
3944 (defvar outline-mode-menu-hide)
3945 (defvar zmacs-regions) ; XEmacs regions
3947 ;; Emacs only
3948 (defvar mark-active)
3950 ;; Various packages
3951 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3952 (declare-function calendar-forward-day "cal-move" (arg))
3953 (declare-function calendar-goto-date "cal-move" (date))
3954 (declare-function calendar-goto-today "cal-move" ())
3955 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3956 (defvar calc-embedded-close-formula)
3957 (defvar calc-embedded-open-formula)
3958 (declare-function cdlatex-tab "ext:cdlatex" ())
3959 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3960 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3961 (defvar font-lock-unfontify-region-function)
3962 (declare-function iswitchb-read-buffer "iswitchb"
3963 (prompt &optional default require-match start matches-set))
3964 (defvar iswitchb-temp-buflist)
3965 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3966 (defvar org-agenda-tags-todo-honor-ignore-options)
3967 (declare-function org-agenda-skip "org-agenda" ())
3968 (declare-function
3969 org-agenda-format-item "org-agenda"
3970 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3971 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3972 (declare-function org-agenda-change-all-lines "org-agenda"
3973 (newhead hdmarker &optional fixface just-this))
3974 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3975 (declare-function org-agenda-maybe-redo "org-agenda" ())
3976 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3977 (beg end))
3978 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3979 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3980 "org-agenda" (&optional end))
3981 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3982 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3983 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3984 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3985 (declare-function org-indent-mode "org-indent" (&optional arg))
3986 (declare-function parse-time-string "parse-time" (string))
3987 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3988 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3989 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3990 (defvar remember-data-file)
3991 (defvar texmathp-why)
3992 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3993 (declare-function table--at-cell-p "table" (position &optional object at-column))
3995 (defvar org-latex-regexps)
3997 ;;; Autoload and prepare some org modules
3999 ;; Some table stuff that needs to be defined here, because it is used
4000 ;; by the functions setting up org-mode or checking for table context.
4002 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4003 "Detect an org-type or table-type table.")
4004 (defconst org-table-line-regexp "^[ \t]*|"
4005 "Detect an org-type table line.")
4006 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4007 "Detect an org-type table line.")
4008 (defconst org-table-hline-regexp "^[ \t]*|-"
4009 "Detect an org-type table hline.")
4010 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4011 "Detect a table-type table hline.")
4012 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4013 "Detect the first line outside a table when searching from within it.
4014 This works for both table types.")
4016 ;; Autoload the functions in org-table.el that are needed by functions here.
4018 (eval-and-compile
4019 (org-autoload "org-table"
4020 '(org-table-begin org-table-blank-field org-table-end)))
4022 ;;;###autoload
4023 (defun turn-on-orgtbl ()
4024 "Unconditionally turn on `orgtbl-mode'."
4025 (require 'org-table)
4026 (orgtbl-mode 1))
4028 (defun org-at-table-p (&optional table-type)
4029 "Return t if the cursor is inside an org-type table.
4030 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4031 (if org-enable-table-editor
4032 (save-excursion
4033 (beginning-of-line 1)
4034 (looking-at (if table-type org-table-any-line-regexp
4035 org-table-line-regexp)))
4036 nil))
4037 (defsubst org-table-p () (org-at-table-p))
4039 (defun org-at-table.el-p ()
4040 "Return t if and only if we are at a table.el table."
4041 (and (org-at-table-p 'any)
4042 (save-excursion
4043 (goto-char (org-table-begin 'any))
4044 (looking-at org-table1-hline-regexp))))
4045 (defun org-table-recognize-table.el ()
4046 "If there is a table.el table nearby, recognize it and move into it."
4047 (if org-table-tab-recognizes-table.el
4048 (if (org-at-table.el-p)
4049 (progn
4050 (beginning-of-line 1)
4051 (if (looking-at org-table-dataline-regexp)
4053 (if (looking-at org-table1-hline-regexp)
4054 (progn
4055 (beginning-of-line 2)
4056 (if (looking-at org-table-any-border-regexp)
4057 (beginning-of-line -1)))))
4058 (if (re-search-forward "|" (org-table-end t) t)
4059 (progn
4060 (require 'table)
4061 (if (table--at-cell-p (point))
4063 (message "recognizing table.el table...")
4064 (table-recognize-table)
4065 (message "recognizing table.el table...done")))
4066 (error "This should not happen"))
4068 nil)
4069 nil))
4071 (defun org-at-table-hline-p ()
4072 "Return t if the cursor is inside a hline in a table."
4073 (if org-enable-table-editor
4074 (save-excursion
4075 (beginning-of-line 1)
4076 (looking-at org-table-hline-regexp))
4077 nil))
4079 (defvar org-table-clean-did-remove-column nil)
4081 (defun org-table-map-tables (function &optional quietly)
4082 "Apply FUNCTION to the start of all tables in the buffer."
4083 (save-excursion
4084 (save-restriction
4085 (widen)
4086 (goto-char (point-min))
4087 (while (re-search-forward org-table-any-line-regexp nil t)
4088 (unless quietly
4089 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4090 (beginning-of-line 1)
4091 (when (and (looking-at org-table-line-regexp)
4092 ;; Exclude tables in src/example/verbatim/clocktable blocks
4093 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4094 (save-excursion (funcall function))
4095 (or (looking-at org-table-line-regexp)
4096 (forward-char 1)))
4097 (re-search-forward org-table-any-border-regexp nil 1))))
4098 (unless quietly (message "Mapping tables: done")))
4100 ;; Declare and autoload functions from org-exp.el & Co
4102 (declare-function org-default-export-plist "org-exp")
4103 (declare-function org-infile-export-plist "org-exp")
4104 (declare-function org-get-current-options "org-exp")
4106 ;; Declare and autoload functions from org-agenda.el
4108 (eval-and-compile
4109 (org-autoload "org-agenda"
4110 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4112 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4113 (declare-function org-clock-update-mode-line "org-clock" ())
4114 (declare-function org-resolve-clocks "org-clock"
4115 (&optional also-non-dangling-p prompt last-valid))
4116 (defvar org-clock-start-time)
4117 (defvar org-clock-marker (make-marker)
4118 "Marker recording the last clock-in.")
4119 (defvar org-clock-hd-marker (make-marker)
4120 "Marker recording the last clock-in, but the headline position.")
4121 (defvar org-clock-heading ""
4122 "The heading of the current clock entry.")
4123 (defun org-clock-is-active ()
4124 "Return non-nil if clock is currently running.
4125 The return value is actually the clock marker."
4126 (marker-buffer org-clock-marker))
4128 (eval-and-compile
4129 (org-autoload "org-clock" '(org-clock-remove-overlays
4130 org-clock-update-time-maybe
4131 org-clocktable-shift)))
4133 (defun org-check-running-clock ()
4134 "Check if the current buffer contains the running clock.
4135 If yes, offer to stop it and to save the buffer with the changes."
4136 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4137 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4138 (buffer-name))))
4139 (org-clock-out)
4140 (when (y-or-n-p "Save changed buffer?")
4141 (save-buffer))))
4143 (defun org-clocktable-try-shift (dir n)
4144 "Check if this line starts a clock table, if yes, shift the time block."
4145 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4146 (org-clocktable-shift dir n)))
4148 ;;;###autoload
4149 (defun org-clock-persistence-insinuate ()
4150 "Set up hooks for clock persistence."
4151 (require 'org-clock)
4152 (add-hook 'org-mode-hook 'org-clock-load)
4153 (add-hook 'kill-emacs-hook 'org-clock-save))
4155 ;; Define the variable already here, to make sure we have it.
4156 (defvar org-indent-mode nil
4157 "Non-nil if Org-Indent mode is enabled.
4158 Use the command `org-indent-mode' to change this variable.")
4160 ;; Autoload archiving code
4161 ;; The stuff that is needed for cycling and tags has to be defined here.
4163 (defgroup org-archive nil
4164 "Options concerning archiving in Org-mode."
4165 :tag "Org Archive"
4166 :group 'org-structure)
4168 (defcustom org-archive-location "%s_archive::"
4169 "The location where subtrees should be archived.
4171 The value of this variable is a string, consisting of two parts,
4172 separated by a double-colon. The first part is a filename and
4173 the second part is a headline.
4175 When the filename is omitted, archiving happens in the same file.
4176 %s in the filename will be replaced by the current file
4177 name (without the directory part). Archiving to a different file
4178 is useful to keep archived entries from contributing to the
4179 Org-mode Agenda.
4181 The archived entries will be filed as subtrees of the specified
4182 headline. When the headline is omitted, the subtrees are simply
4183 filed away at the end of the file, as top-level entries. Also in
4184 the heading you can use %s to represent the file name, this can be
4185 useful when using the same archive for a number of different files.
4187 Here are a few examples:
4188 \"%s_archive::\"
4189 If the current file is Projects.org, archive in file
4190 Projects.org_archive, as top-level trees. This is the default.
4192 \"::* Archived Tasks\"
4193 Archive in the current file, under the top-level headline
4194 \"* Archived Tasks\".
4196 \"~/org/archive.org::\"
4197 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4199 \"~/org/archive.org::* From %s\"
4200 Archive in file ~/org/archive.org (absolute path), under headlines
4201 \"From FILENAME\" where file name is the current file name.
4203 \"~/org/datetree.org::datetree/* Finished Tasks\"
4204 The \"datetree/\" string is special, signifying to archive
4205 items to the datetree. Items are placed in either the CLOSED
4206 date of the item, or the current date if there is no CLOSED date.
4207 The heading will be a subentry to the current date. There doesn't
4208 need to be a heading, but there always needs to be a slash after
4209 datetree. For example, to store archived items directly in the
4210 datetree, use \"~/org/datetree.org::datetree/\".
4212 \"basement::** Finished Tasks\"
4213 Archive in file ./basement (relative path), as level 3 trees
4214 below the level 2 heading \"** Finished Tasks\".
4216 You may set this option on a per-file basis by adding to the buffer a
4217 line like
4219 #+ARCHIVE: basement::** Finished Tasks
4221 You may also define it locally for a subtree by setting an ARCHIVE property
4222 in the entry. If such a property is found in an entry, or anywhere up
4223 the hierarchy, it will be used."
4224 :group 'org-archive
4225 :type 'string)
4227 (defcustom org-archive-tag "ARCHIVE"
4228 "The tag that marks a subtree as archived.
4229 An archived subtree does not open during visibility cycling, and does
4230 not contribute to the agenda listings.
4231 After changing this, font-lock must be restarted in the relevant buffers to
4232 get the proper fontification."
4233 :group 'org-archive
4234 :group 'org-keywords
4235 :type 'string)
4237 (defcustom org-agenda-skip-archived-trees t
4238 "Non-nil means the agenda will skip any items located in archived trees.
4239 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4240 variable is no longer recommended, you should leave it at the value t.
4241 Instead, use the key `v' to cycle the archives-mode in the agenda."
4242 :group 'org-archive
4243 :group 'org-agenda-skip
4244 :type 'boolean)
4246 (defcustom org-columns-skip-archived-trees t
4247 "Non-nil means ignore archived trees when creating column view."
4248 :group 'org-archive
4249 :group 'org-properties
4250 :type 'boolean)
4252 (defcustom org-cycle-open-archived-trees nil
4253 "Non-nil means `org-cycle' will open archived trees.
4254 An archived tree is a tree marked with the tag ARCHIVE.
4255 When nil, archived trees will stay folded. You can still open them with
4256 normal outline commands like `show-all', but not with the cycling commands."
4257 :group 'org-archive
4258 :group 'org-cycle
4259 :type 'boolean)
4261 (defcustom org-sparse-tree-open-archived-trees nil
4262 "Non-nil means sparse tree construction shows matches in archived trees.
4263 When nil, matches in these trees are highlighted, but the trees are kept in
4264 collapsed state."
4265 :group 'org-archive
4266 :group 'org-sparse-trees
4267 :type 'boolean)
4269 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4270 "The default date type when building a sparse tree.
4271 When this is nil, a date is a scheduled or a deadline timestamp.
4272 Otherwise, these types are allowed:
4274 all: all timestamps
4275 active: only active timestamps (<...>)
4276 inactive: only inactive timestamps (<...)
4277 scheduled: only scheduled timestamps
4278 deadline: only deadline timestamps"
4279 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4280 (const :tag "All timestamps" all)
4281 (const :tag "Only active timestamps" active)
4282 (const :tag "Only inactive timestamps" inactive)
4283 (const :tag "Only scheduled timestamps" scheduled)
4284 (const :tag "Only deadline timestamps" deadline))
4285 :version "24.3"
4286 :group 'org-sparse-trees)
4288 (defun org-cycle-hide-archived-subtrees (state)
4289 "Re-hide all archived subtrees after a visibility state change."
4290 (when (and (not org-cycle-open-archived-trees)
4291 (not (memq state '(overview folded))))
4292 (save-excursion
4293 (let* ((globalp (memq state '(contents all)))
4294 (beg (if globalp (point-min) (point)))
4295 (end (if globalp (point-max) (org-end-of-subtree t))))
4296 (org-hide-archived-subtrees beg end)
4297 (goto-char beg)
4298 (if (looking-at (concat ".*:" org-archive-tag ":"))
4299 (message "%s" (substitute-command-keys
4300 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4302 (defun org-force-cycle-archived ()
4303 "Cycle subtree even if it is archived."
4304 (interactive)
4305 (setq this-command 'org-cycle)
4306 (let ((org-cycle-open-archived-trees t))
4307 (call-interactively 'org-cycle)))
4309 (defun org-hide-archived-subtrees (beg end)
4310 "Re-hide all archived subtrees after a visibility state change."
4311 (save-excursion
4312 (let* ((re (concat ":" org-archive-tag ":")))
4313 (goto-char beg)
4314 (while (re-search-forward re end t)
4315 (when (org-at-heading-p)
4316 (org-flag-subtree t)
4317 (org-end-of-subtree t))))))
4319 (declare-function outline-end-of-heading "outline" ())
4320 (declare-function outline-flag-region "outline" (from to flag))
4321 (defun org-flag-subtree (flag)
4322 (save-excursion
4323 (org-back-to-heading t)
4324 (outline-end-of-heading)
4325 (outline-flag-region (point)
4326 (progn (org-end-of-subtree t) (point))
4327 flag)))
4329 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4331 (eval-and-compile
4332 (org-autoload "org-archive"
4333 '(org-add-archive-files)))
4335 ;; Autoload Column View Code
4337 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4338 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4339 (declare-function org-columns-compute "org-colview" (property))
4341 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4342 '(org-columns-number-to-string
4343 org-columns-get-format-and-top-level
4344 org-columns-compute
4345 org-columns-remove-overlays))
4347 ;; Autoload ID code
4349 (declare-function org-id-store-link "org-id")
4350 (declare-function org-id-locations-load "org-id")
4351 (declare-function org-id-locations-save "org-id")
4352 (defvar org-id-track-globally)
4353 (org-autoload "org-id"
4354 '(org-id-new
4355 org-id-copy
4356 org-id-get-with-outline-path-completion
4357 org-id-get-with-outline-drilling))
4359 ;;; Variables for pre-computed regular expressions, all buffer local
4361 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4362 "Matches first line of a hidden block.")
4363 (make-variable-buffer-local 'org-drawer-regexp)
4364 (defvar org-todo-regexp nil
4365 "Matches any of the TODO state keywords.")
4366 (make-variable-buffer-local 'org-todo-regexp)
4367 (defvar org-not-done-regexp nil
4368 "Matches any of the TODO state keywords except the last one.")
4369 (make-variable-buffer-local 'org-not-done-regexp)
4370 (defvar org-not-done-heading-regexp nil
4371 "Matches a TODO headline that is not done.")
4372 (make-variable-buffer-local 'org-not-done-regexp)
4373 (defvar org-todo-line-regexp nil
4374 "Matches a headline and puts TODO state into group 2 if present.")
4375 (make-variable-buffer-local 'org-todo-line-regexp)
4376 (defvar org-complex-heading-regexp nil
4377 "Matches a headline and puts everything into groups:
4378 group 1: the stars
4379 group 2: The todo keyword, maybe
4380 group 3: Priority cookie
4381 group 4: True headline
4382 group 5: Tags")
4383 (make-variable-buffer-local 'org-complex-heading-regexp)
4384 (defvar org-complex-heading-regexp-format nil
4385 "Printf format to make regexp to match an exact headline.
4386 This regexp will match the headline of any node which has the
4387 exact headline text that is put into the format, but may have any
4388 TODO state, priority and tags.")
4389 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4390 (defvar org-todo-line-tags-regexp nil
4391 "Matches a headline and puts TODO state into group 2 if present.
4392 Also put tags into group 4 if tags are present.")
4393 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4394 (defvar org-ds-keyword-length 12
4395 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4396 (make-variable-buffer-local 'org-ds-keyword-length)
4397 (defvar org-deadline-regexp nil
4398 "Matches the DEADLINE keyword.")
4399 (make-variable-buffer-local 'org-deadline-regexp)
4400 (defvar org-deadline-time-regexp nil
4401 "Matches the DEADLINE keyword together with a time stamp.")
4402 (make-variable-buffer-local 'org-deadline-time-regexp)
4403 (defvar org-deadline-line-regexp nil
4404 "Matches the DEADLINE keyword and the rest of the line.")
4405 (make-variable-buffer-local 'org-deadline-line-regexp)
4406 (defvar org-scheduled-regexp nil
4407 "Matches the SCHEDULED keyword.")
4408 (make-variable-buffer-local 'org-scheduled-regexp)
4409 (defvar org-scheduled-time-regexp nil
4410 "Matches the SCHEDULED keyword together with a time stamp.")
4411 (make-variable-buffer-local 'org-scheduled-time-regexp)
4412 (defvar org-closed-time-regexp nil
4413 "Matches the CLOSED keyword together with a time stamp.")
4414 (make-variable-buffer-local 'org-closed-time-regexp)
4416 (defvar org-keyword-time-regexp nil
4417 "Matches any of the 4 keywords, together with the time stamp.")
4418 (make-variable-buffer-local 'org-keyword-time-regexp)
4419 (defvar org-keyword-time-not-clock-regexp nil
4420 "Matches any of the 3 keywords, together with the time stamp.")
4421 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4422 (defvar org-maybe-keyword-time-regexp nil
4423 "Matches a timestamp, possibly preceded by a keyword.")
4424 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4425 (defvar org-all-time-keywords nil
4426 "List of time keywords.")
4427 (make-variable-buffer-local 'org-all-time-keywords)
4429 (defconst org-plain-time-of-day-regexp
4430 (concat
4431 "\\(\\<[012]?[0-9]"
4432 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4433 "\\(--?"
4434 "\\(\\<[012]?[0-9]"
4435 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4436 "\\)?")
4437 "Regular expression to match a plain time or time range.
4438 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4439 groups carry important information:
4440 0 the full match
4441 1 the first time, range or not
4442 8 the second time, if it is a range.")
4444 (defconst org-plain-time-extension-regexp
4445 (concat
4446 "\\(\\<[012]?[0-9]"
4447 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4448 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4449 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4450 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4451 groups carry important information:
4452 0 the full match
4453 7 hours of duration
4454 9 minutes of duration")
4456 (defconst org-stamp-time-of-day-regexp
4457 (concat
4458 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4459 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4460 "\\(--?"
4461 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4462 "Regular expression to match a timestamp time or time range.
4463 After a match, the following groups carry important information:
4464 0 the full match
4465 1 date plus weekday, for back referencing to make sure both times are on the same day
4466 2 the first time, range or not
4467 4 the second time, if it is a range.")
4469 (defconst org-startup-options
4470 '(("fold" org-startup-folded t)
4471 ("overview" org-startup-folded t)
4472 ("nofold" org-startup-folded nil)
4473 ("showall" org-startup-folded nil)
4474 ("showeverything" org-startup-folded showeverything)
4475 ("content" org-startup-folded content)
4476 ("indent" org-startup-indented t)
4477 ("noindent" org-startup-indented nil)
4478 ("hidestars" org-hide-leading-stars t)
4479 ("showstars" org-hide-leading-stars nil)
4480 ("odd" org-odd-levels-only t)
4481 ("oddeven" org-odd-levels-only nil)
4482 ("align" org-startup-align-all-tables t)
4483 ("noalign" org-startup-align-all-tables nil)
4484 ("inlineimages" org-startup-with-inline-images t)
4485 ("noinlineimages" org-startup-with-inline-images nil)
4486 ("customtime" org-display-custom-times t)
4487 ("logdone" org-log-done time)
4488 ("lognotedone" org-log-done note)
4489 ("nologdone" org-log-done nil)
4490 ("lognoteclock-out" org-log-note-clock-out t)
4491 ("nolognoteclock-out" org-log-note-clock-out nil)
4492 ("logrepeat" org-log-repeat state)
4493 ("lognoterepeat" org-log-repeat note)
4494 ("logdrawer" org-log-into-drawer t)
4495 ("nologdrawer" org-log-into-drawer nil)
4496 ("logstatesreversed" org-log-states-order-reversed t)
4497 ("nologstatesreversed" org-log-states-order-reversed nil)
4498 ("nologrepeat" org-log-repeat nil)
4499 ("logreschedule" org-log-reschedule time)
4500 ("lognotereschedule" org-log-reschedule note)
4501 ("nologreschedule" org-log-reschedule nil)
4502 ("logredeadline" org-log-redeadline time)
4503 ("lognoteredeadline" org-log-redeadline note)
4504 ("nologredeadline" org-log-redeadline nil)
4505 ("logrefile" org-log-refile time)
4506 ("lognoterefile" org-log-refile note)
4507 ("nologrefile" org-log-refile nil)
4508 ("fninline" org-footnote-define-inline t)
4509 ("nofninline" org-footnote-define-inline nil)
4510 ("fnlocal" org-footnote-section nil)
4511 ("fnauto" org-footnote-auto-label t)
4512 ("fnprompt" org-footnote-auto-label nil)
4513 ("fnconfirm" org-footnote-auto-label confirm)
4514 ("fnplain" org-footnote-auto-label plain)
4515 ("fnadjust" org-footnote-auto-adjust t)
4516 ("nofnadjust" org-footnote-auto-adjust nil)
4517 ("constcgs" constants-unit-system cgs)
4518 ("constSI" constants-unit-system SI)
4519 ("noptag" org-tag-persistent-alist nil)
4520 ("hideblocks" org-hide-block-startup t)
4521 ("nohideblocks" org-hide-block-startup nil)
4522 ("beamer" org-startup-with-beamer-mode t)
4523 ("entitiespretty" org-pretty-entities t)
4524 ("entitiesplain" org-pretty-entities nil))
4525 "Variable associated with STARTUP options for org-mode.
4526 Each element is a list of three items: the startup options (as written
4527 in the #+STARTUP line), the corresponding variable, and the value to set
4528 this variable to if the option is found. An optional forth element PUSH
4529 means to push this value onto the list in the variable.")
4531 (defun org-update-property-plist (key val props)
4532 "Update PROPS with KEY and VAL."
4533 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4534 (key (if appending (substring key 0 (- (length key) 1)) key))
4535 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4536 (previous (cdr (assoc key props))))
4537 (if appending
4538 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4539 (cons (cons key val) remainder))))
4541 (defconst org-block-regexp
4542 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4543 "Regular expression for hiding blocks.")
4544 (defconst org-heading-keyword-regexp-format
4545 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4546 "Printf format for a regexp matching an headline with some keyword.
4547 This regexp will match the headline of any node which has the
4548 exact keyword that is put into the format. The keyword isn't in
4549 any group by default, but the stars and the body are.")
4550 (defconst org-heading-keyword-maybe-regexp-format
4551 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4552 "Printf format for a regexp matching an headline, possibly with some keyword.
4553 This regexp can match any headline with the specified keyword, or
4554 without a keyword. The keyword isn't in any group by default,
4555 but the stars and the body are.")
4557 (defun org-set-regexps-and-options ()
4558 "Precompute regular expressions for current buffer."
4559 (when (derived-mode-p 'org-mode)
4560 (org-set-local 'org-todo-kwd-alist nil)
4561 (org-set-local 'org-todo-key-alist nil)
4562 (org-set-local 'org-todo-key-trigger nil)
4563 (org-set-local 'org-todo-keywords-1 nil)
4564 (org-set-local 'org-done-keywords nil)
4565 (org-set-local 'org-todo-heads nil)
4566 (org-set-local 'org-todo-sets nil)
4567 (org-set-local 'org-todo-log-states nil)
4568 (org-set-local 'org-file-properties nil)
4569 (org-set-local 'org-file-tags nil)
4570 (let ((re (org-make-options-regexp
4571 '("CATEGORY" "TODO" "COLUMNS"
4572 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4573 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4574 "OPTIONS")
4575 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4576 (splitre "[ \t]+")
4577 (scripts org-use-sub-superscripts)
4578 kwds kws0 kwsa key log value cat arch tags const links hw dws
4579 tail sep kws1 prio props ftags drawers beamer-p
4580 ext-setup-or-nil setup-contents (start 0))
4581 (save-excursion
4582 (save-restriction
4583 (widen)
4584 (goto-char (point-min))
4585 (while (or (and ext-setup-or-nil
4586 (string-match re ext-setup-or-nil start)
4587 (setq start (match-end 0)))
4588 (and (setq ext-setup-or-nil nil start 0)
4589 (re-search-forward re nil t)))
4590 (setq key (upcase (match-string 1 ext-setup-or-nil))
4591 value (org-match-string-no-properties 2 ext-setup-or-nil))
4592 (if (stringp value) (setq value (org-trim value)))
4593 (cond
4594 ((equal key "CATEGORY")
4595 (setq cat value))
4596 ((member key '("SEQ_TODO" "TODO"))
4597 (push (cons 'sequence (org-split-string value splitre)) kwds))
4598 ((equal key "TYP_TODO")
4599 (push (cons 'type (org-split-string value splitre)) kwds))
4600 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4601 ;; general TODO-like setup
4602 (push (cons (intern (downcase (match-string 1 key)))
4603 (org-split-string value splitre)) kwds))
4604 ((equal key "TAGS")
4605 (setq tags (append tags (if tags '("\\n") nil)
4606 (org-split-string value splitre))))
4607 ((equal key "COLUMNS")
4608 (org-set-local 'org-columns-default-format value))
4609 ((equal key "LINK")
4610 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4611 (push (cons (match-string 1 value)
4612 (org-trim (match-string 2 value)))
4613 links)))
4614 ((equal key "PRIORITIES")
4615 (setq prio (org-split-string value " +")))
4616 ((equal key "PROPERTY")
4617 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4618 (setq props (org-update-property-plist (match-string 1 value)
4619 (match-string 2 value)
4620 props))))
4621 ((equal key "FILETAGS")
4622 (when (string-match "\\S-" value)
4623 (setq ftags
4624 (append
4625 ftags
4626 (apply 'append
4627 (mapcar (lambda (x) (org-split-string x ":"))
4628 (org-split-string value)))))))
4629 ((equal key "DRAWERS")
4630 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4631 ((equal key "CONSTANTS")
4632 (setq const (append const (org-split-string value splitre))))
4633 ((equal key "STARTUP")
4634 (let ((opts (org-split-string value splitre))
4635 l var val)
4636 (while (setq l (pop opts))
4637 (when (setq l (assoc l org-startup-options))
4638 (setq var (nth 1 l) val (nth 2 l))
4639 (if (not (nth 3 l))
4640 (set (make-local-variable var) val)
4641 (if (not (listp (symbol-value var)))
4642 (set (make-local-variable var) nil))
4643 (set (make-local-variable var) (symbol-value var))
4644 (add-to-list var val))))))
4645 ((equal key "ARCHIVE")
4646 (setq arch value)
4647 (remove-text-properties 0 (length arch)
4648 '(face t fontified t) arch))
4649 ((equal key "LATEX_CLASS")
4650 (setq beamer-p (equal value "beamer")))
4651 ((equal key "OPTIONS")
4652 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4653 (setq scripts (read (match-string 2 value)))))
4654 ((equal key "SETUPFILE")
4655 (setq setup-contents (org-file-contents
4656 (expand-file-name
4657 (org-remove-double-quotes value))
4658 'noerror))
4659 (if (not ext-setup-or-nil)
4660 (setq ext-setup-or-nil setup-contents start 0)
4661 (setq ext-setup-or-nil
4662 (concat (substring ext-setup-or-nil 0 start)
4663 "\n" setup-contents "\n"
4664 (substring ext-setup-or-nil start)))))))
4665 ;; search for property blocks
4666 (goto-char (point-min))
4667 (while (re-search-forward org-block-regexp nil t)
4668 (when (equal "PROPERTY" (upcase (match-string 1)))
4669 (setq value (replace-regexp-in-string
4670 "[\n\r]" " " (match-string 4)))
4671 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4672 (setq props (org-update-property-plist (match-string 1 value)
4673 (match-string 2 value)
4674 props)))))))
4675 (org-set-local 'org-use-sub-superscripts scripts)
4676 (when cat
4677 (org-set-local 'org-category (intern cat))
4678 (push (cons "CATEGORY" cat) props))
4679 (when prio
4680 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4681 (setq prio (mapcar 'string-to-char prio))
4682 (org-set-local 'org-highest-priority (nth 0 prio))
4683 (org-set-local 'org-lowest-priority (nth 1 prio))
4684 (org-set-local 'org-default-priority (nth 2 prio)))
4685 (and props (org-set-local 'org-file-properties (nreverse props)))
4686 (and ftags (org-set-local 'org-file-tags
4687 (mapcar 'org-add-prop-inherited ftags)))
4688 (and drawers (org-set-local 'org-drawers drawers))
4689 (and arch (org-set-local 'org-archive-location arch))
4690 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4691 ;; Process the TODO keywords
4692 (unless kwds
4693 ;; Use the global values as if they had been given locally.
4694 (setq kwds (default-value 'org-todo-keywords))
4695 (if (stringp (car kwds))
4696 (setq kwds (list (cons org-todo-interpretation
4697 (default-value 'org-todo-keywords)))))
4698 (setq kwds (reverse kwds)))
4699 (setq kwds (nreverse kwds))
4700 (let (inter kws kw)
4701 (while (setq kws (pop kwds))
4702 (let ((kws (or
4703 (run-hook-with-args-until-success
4704 'org-todo-setup-filter-hook kws)
4705 kws)))
4706 (setq inter (pop kws) sep (member "|" kws)
4707 kws0 (delete "|" (copy-sequence kws))
4708 kwsa nil
4709 kws1 (mapcar
4710 (lambda (x)
4711 ;; 1 2
4712 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4713 (progn
4714 (setq kw (match-string 1 x)
4715 key (and (match-end 2) (match-string 2 x))
4716 log (org-extract-log-state-settings x))
4717 (push (cons kw (and key (string-to-char key))) kwsa)
4718 (and log (push log org-todo-log-states))
4720 (error "Invalid TODO keyword %s" x)))
4721 kws0)
4722 kwsa (if kwsa (append '((:startgroup))
4723 (nreverse kwsa)
4724 '((:endgroup))))
4725 hw (car kws1)
4726 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4727 tail (list inter hw (car dws) (org-last dws))))
4728 (add-to-list 'org-todo-heads hw 'append)
4729 (push kws1 org-todo-sets)
4730 (setq org-done-keywords (append org-done-keywords dws nil))
4731 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4732 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4733 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4734 (setq org-todo-sets (nreverse org-todo-sets)
4735 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4736 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4737 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4738 ;; Process the constants
4739 (when const
4740 (let (e cst)
4741 (while (setq e (pop const))
4742 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4743 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4744 (setq org-table-formula-constants-local cst)))
4746 ;; Process the tags.
4747 (when tags
4748 (let (e tgs)
4749 (while (setq e (pop tags))
4750 (cond
4751 ((equal e "{") (push '(:startgroup) tgs))
4752 ((equal e "}") (push '(:endgroup) tgs))
4753 ((equal e "\\n") (push '(:newline) tgs))
4754 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4755 (push (cons (match-string 1 e)
4756 (string-to-char (match-string 2 e)))
4757 tgs))
4758 (t (push (list e) tgs))))
4759 (org-set-local 'org-tag-alist nil)
4760 (while (setq e (pop tgs))
4761 (or (and (stringp (car e))
4762 (assoc (car e) org-tag-alist))
4763 (push e org-tag-alist)))))
4765 ;; Compute the regular expressions and other local variables.
4766 ;; Using `org-outline-regexp-bol' would complicate them much,
4767 ;; because of the fixed white space at the end of that string.
4768 (if (not org-done-keywords)
4769 (setq org-done-keywords (and org-todo-keywords-1
4770 (list (org-last org-todo-keywords-1)))))
4771 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4772 (length org-scheduled-string)
4773 (length org-clock-string)
4774 (length org-closed-string)))
4775 org-drawer-regexp
4776 (concat "^[ \t]*:\\("
4777 (mapconcat 'regexp-quote org-drawers "\\|")
4778 "\\):[ \t]*$")
4779 org-not-done-keywords
4780 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4781 org-todo-regexp
4782 (concat "\\("
4783 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4784 "\\)")
4785 org-not-done-regexp
4786 (concat "\\("
4787 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4788 "\\)")
4789 org-not-done-heading-regexp
4790 (format org-heading-keyword-regexp-format org-not-done-regexp)
4791 org-todo-line-regexp
4792 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4793 org-complex-heading-regexp
4794 (concat "^\\(\\*+\\)"
4795 "\\(?: +" org-todo-regexp "\\)?"
4796 "\\(?: +\\(\\[#.\\]\\)\\)?"
4797 "\\(?: +\\(.*?\\)\\)??"
4798 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4799 "[ \t]*$")
4800 org-complex-heading-regexp-format
4801 (concat "^\\(\\*+\\)"
4802 "\\(?: +" org-todo-regexp "\\)?"
4803 "\\(?: +\\(\\[#.\\]\\)\\)?"
4804 "\\(?: +"
4805 ;; Stats cookies can be stuck to body.
4806 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4807 "\\(%s\\)"
4808 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4809 "\\)"
4810 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4811 "[ \t]*$")
4812 org-todo-line-tags-regexp
4813 (concat "^\\(\\*+\\)"
4814 "\\(?: +" org-todo-regexp "\\)?"
4815 "\\(?: +\\(.*?\\)\\)??"
4816 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4817 "[ \t]*$")
4818 org-deadline-regexp (concat "\\<" org-deadline-string)
4819 org-deadline-time-regexp
4820 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4821 org-deadline-line-regexp
4822 (concat "\\<\\(" org-deadline-string "\\).*")
4823 org-scheduled-regexp
4824 (concat "\\<" org-scheduled-string)
4825 org-scheduled-time-regexp
4826 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4827 org-closed-time-regexp
4828 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4829 org-keyword-time-regexp
4830 (concat "\\<\\(" org-scheduled-string
4831 "\\|" org-deadline-string
4832 "\\|" org-closed-string
4833 "\\|" org-clock-string "\\)"
4834 " *[[<]\\([^]>]+\\)[]>]")
4835 org-keyword-time-not-clock-regexp
4836 (concat "\\<\\(" org-scheduled-string
4837 "\\|" org-deadline-string
4838 "\\|" org-closed-string
4839 "\\)"
4840 " *[[<]\\([^]>]+\\)[]>]")
4841 org-maybe-keyword-time-regexp
4842 (concat "\\(\\<\\(" org-scheduled-string
4843 "\\|" org-deadline-string
4844 "\\|" org-closed-string
4845 "\\|" org-clock-string "\\)\\)?"
4846 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4847 org-all-time-keywords
4848 (mapcar (lambda (w) (substring w 0 -1))
4849 (list org-scheduled-string org-deadline-string
4850 org-clock-string org-closed-string))
4852 (org-compute-latex-and-specials-regexp)
4853 (org-set-font-lock-defaults))))
4855 (defun org-file-contents (file &optional noerror)
4856 "Return the contents of FILE, as a string."
4857 (if (or (not file)
4858 (not (file-readable-p file)))
4859 (if noerror
4860 (progn
4861 (message "Cannot read file \"%s\"" file)
4862 (ding) (sit-for 2)
4864 (error "Cannot read file \"%s\"" file))
4865 (with-temp-buffer
4866 (insert-file-contents file)
4867 (buffer-string))))
4869 (defun org-extract-log-state-settings (x)
4870 "Extract the log state setting from a TODO keyword string.
4871 This will extract info from a string like \"WAIT(w@/!)\"."
4872 (let (kw key log1 log2)
4873 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4874 (setq kw (match-string 1 x)
4875 key (and (match-end 2) (match-string 2 x))
4876 log1 (and (match-end 3) (match-string 3 x))
4877 log2 (and (match-end 4) (match-string 4 x)))
4878 (and (or log1 log2)
4879 (list kw
4880 (and log1 (if (equal log1 "!") 'time 'note))
4881 (and log2 (if (equal log2 "!") 'time 'note)))))))
4883 (defun org-remove-keyword-keys (list)
4884 "Remove a pair of parenthesis at the end of each string in LIST."
4885 (mapcar (lambda (x)
4886 (if (string-match "(.*)$" x)
4887 (substring x 0 (match-beginning 0))
4889 list))
4891 (defun org-assign-fast-keys (alist)
4892 "Assign fast keys to a keyword-key alist.
4893 Respect keys that are already there."
4894 (let (new e (alt ?0))
4895 (while (setq e (pop alist))
4896 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4897 (cdr e)) ;; Key already assigned.
4898 (push e new)
4899 (let ((clist (string-to-list (downcase (car e))))
4900 (used (append new alist)))
4901 (when (= (car clist) ?@)
4902 (pop clist))
4903 (while (and clist (rassoc (car clist) used))
4904 (pop clist))
4905 (unless clist
4906 (while (rassoc alt used)
4907 (incf alt)))
4908 (push (cons (car e) (or (car clist) alt)) new))))
4909 (nreverse new)))
4911 ;;; Some variables used in various places
4913 (defvar org-window-configuration nil
4914 "Used in various places to store a window configuration.")
4915 (defvar org-selected-window nil
4916 "Used in various places to store a window configuration.")
4917 (defvar org-finish-function nil
4918 "Function to be called when `C-c C-c' is used.
4919 This is for getting out of special buffers like capture.")
4922 ;; FIXME: Occasionally check by commenting these, to make sure
4923 ;; no other functions uses these, forgetting to let-bind them.
4924 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4925 (defvar org-last-state)
4926 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4928 ;; Defined somewhere in this file, but used before definition.
4929 (defvar org-entities) ;; defined in org-entities.el
4930 (defvar org-struct-menu)
4931 (defvar org-org-menu)
4932 (defvar org-tbl-menu)
4934 ;;;; Define the Org-mode
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 (defvar bidi-paragraph-direction)
4954 (defvar buffer-face-mode-face)
4956 (require 'outline)
4957 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4958 (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"))
4959 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4961 ;; Other stuff we need.
4962 (require 'time-date)
4963 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4964 (require 'easymenu)
4965 (require 'overlay)
4967 (require 'org-macs)
4968 (require 'org-entities)
4969 ;; (require 'org-compat) moved higher up in the file before it is first used
4970 (require 'org-faces)
4971 (require 'org-list)
4972 (require 'org-pcomplete)
4973 (require 'org-src)
4974 (require 'org-footnote)
4976 ;; babel
4977 (require 'ob)
4979 ;;;###autoload
4980 (define-derived-mode org-mode outline-mode "Org"
4981 "Outline-based notes management and organizer, alias
4982 \"Carsten's outline-mode for keeping track of everything.\"
4984 Org-mode develops organizational tasks around a NOTES file which
4985 contains information about projects as plain text. Org-mode is
4986 implemented on top of outline-mode, which is ideal to keep the content
4987 of large files well structured. It supports ToDo items, deadlines and
4988 time stamps, which magically appear in the diary listing of the Emacs
4989 calendar. Tables are easily created with a built-in table editor.
4990 Plain text URL-like links connect to websites, emails (VM), Usenet
4991 messages (Gnus), BBDB entries, and any files related to the project.
4992 For printing and sharing of notes, an Org-mode file (or a part of it)
4993 can be exported as a structured ASCII or HTML file.
4995 The following commands are available:
4997 \\{org-mode-map}"
4999 ;; Get rid of Outline menus, they are not needed
5000 ;; Need to do this here because define-derived-mode sets up
5001 ;; the keymap so late. Still, it is a waste to call this each time
5002 ;; we switch another buffer into org-mode.
5003 (if (featurep 'xemacs)
5004 (when (boundp 'outline-mode-menu-heading)
5005 ;; Assume this is Greg's port, it uses easymenu
5006 (easy-menu-remove outline-mode-menu-heading)
5007 (easy-menu-remove outline-mode-menu-show)
5008 (easy-menu-remove outline-mode-menu-hide))
5009 (define-key org-mode-map [menu-bar headings] 'undefined)
5010 (define-key org-mode-map [menu-bar hide] 'undefined)
5011 (define-key org-mode-map [menu-bar show] 'undefined))
5013 (org-load-modules-maybe)
5014 (easy-menu-add org-org-menu)
5015 (easy-menu-add org-tbl-menu)
5016 (org-install-agenda-files-menu)
5017 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5018 (add-to-invisibility-spec '(org-cwidth))
5019 (add-to-invisibility-spec '(org-hide-block . t))
5020 (when (featurep 'xemacs)
5021 (org-set-local 'line-move-ignore-invisible t))
5022 (org-set-local 'outline-regexp org-outline-regexp)
5023 (org-set-local 'outline-level 'org-outline-level)
5024 (setq bidi-paragraph-direction 'left-to-right)
5025 (when (and org-ellipsis
5026 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5027 (fboundp 'make-glyph-code))
5028 (unless org-display-table
5029 (setq org-display-table (make-display-table)))
5030 (set-display-table-slot
5031 org-display-table 4
5032 (vconcat (mapcar
5033 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5034 org-ellipsis)))
5035 (if (stringp org-ellipsis) org-ellipsis "..."))))
5036 (setq buffer-display-table org-display-table))
5037 (org-set-regexps-and-options)
5038 (when (and org-tag-faces (not org-tags-special-faces-re))
5039 ;; tag faces set outside customize.... force initialization.
5040 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5041 ;; Calc embedded
5042 (org-set-local 'calc-embedded-open-mode "# ")
5043 (modify-syntax-entry ?@ "w")
5044 (modify-syntax-entry ?\" "\"")
5045 (if org-startup-truncated (setq truncate-lines t))
5046 (org-set-local 'font-lock-unfontify-region-function
5047 'org-unfontify-region)
5048 ;; Activate before-change-function
5049 (org-set-local 'org-table-may-need-update t)
5050 (org-add-hook 'before-change-functions 'org-before-change-function nil
5051 'local)
5052 ;; Check for running clock before killing a buffer
5053 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5054 ;; Initialize macros templates.
5055 (org-macro-initialize-templates)
5056 ;; Initialize radio targets.
5057 (org-update-radio-target-regexp)
5058 ;; Indentation.
5059 (org-set-local 'indent-line-function 'org-indent-line)
5060 (org-set-local 'indent-region-function 'org-indent-region)
5061 ;; Filling and auto-filling.
5062 (org-setup-filling)
5063 ;; Comments.
5064 (org-setup-comments-handling)
5065 ;; Beginning/end of defun
5066 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5067 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5068 ;; Next error for sparse trees
5069 (org-set-local 'next-error-function 'org-occur-next-match)
5070 ;; Make sure dependence stuff works reliably, even for users who set it
5071 ;; too late :-(
5072 (if org-enforce-todo-dependencies
5073 (add-hook 'org-blocker-hook
5074 'org-block-todo-from-children-or-siblings-or-parent)
5075 (remove-hook 'org-blocker-hook
5076 'org-block-todo-from-children-or-siblings-or-parent))
5077 (if org-enforce-todo-checkbox-dependencies
5078 (add-hook 'org-blocker-hook
5079 'org-block-todo-from-checkboxes)
5080 (remove-hook 'org-blocker-hook
5081 'org-block-todo-from-checkboxes))
5083 ;; Align options lines
5084 (org-set-local
5085 'align-mode-rules-list
5086 '((org-in-buffer-settings
5087 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5088 (modes . '(org-mode)))))
5090 ;; Imenu
5091 (org-set-local 'imenu-create-index-function
5092 'org-imenu-get-tree)
5094 ;; Make isearch reveal context
5095 (if (or (featurep 'xemacs)
5096 (not (boundp 'outline-isearch-open-invisible-function)))
5097 ;; Emacs 21 and XEmacs make use of the hook
5098 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5099 ;; Emacs 22 deals with this through a special variable
5100 (org-set-local 'outline-isearch-open-invisible-function
5101 (lambda (&rest ignore) (org-show-context 'isearch))))
5103 ;; Turn on org-beamer-mode?
5104 (and org-startup-with-beamer-mode (org-beamer-mode))
5106 ;; Setup the pcomplete hooks
5107 (set (make-local-variable 'pcomplete-command-completion-function)
5108 'org-pcomplete-initial)
5109 (set (make-local-variable 'pcomplete-command-name-function)
5110 'org-command-at-point)
5111 (set (make-local-variable 'pcomplete-default-completion-function)
5112 'ignore)
5113 (set (make-local-variable 'pcomplete-parse-arguments-function)
5114 'org-parse-arguments)
5115 (set (make-local-variable 'pcomplete-termination-string) "")
5116 (when (>= emacs-major-version 23)
5117 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5119 ;; If empty file that did not turn on org-mode automatically, make it to.
5120 (if (and org-insert-mode-line-in-empty-file
5121 (org-called-interactively-p 'any)
5122 (= (point-min) (point-max)))
5123 (insert "# -*- mode: org -*-\n\n"))
5124 (unless org-inhibit-startup
5125 (when org-startup-align-all-tables
5126 (let ((bmp (buffer-modified-p)))
5127 (org-table-map-tables 'org-table-align 'quietly)
5128 (set-buffer-modified-p bmp)))
5129 (when org-startup-with-inline-images
5130 (org-display-inline-images))
5131 (when org-startup-indented
5132 (require 'org-indent)
5133 (org-indent-mode 1))
5134 (unless org-inhibit-startup-visibility-stuff
5135 (org-set-startup-visibility)))
5136 ;; Try to set org-hide correctly
5137 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5139 (when (fboundp 'abbrev-table-put)
5140 (abbrev-table-put org-mode-abbrev-table
5141 :parents (list text-mode-abbrev-table)))
5143 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5146 (defun org-find-invisible-foreground ()
5147 (let ((candidates (remove
5148 "unspecified-bg"
5149 (nconc
5150 (list (face-background 'default)
5151 (face-background 'org-default))
5152 (mapcar
5153 (lambda (alist)
5154 (when (boundp alist)
5155 (cdr (assoc 'background-color (symbol-value alist)))))
5156 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5157 (list (face-foreground 'org-hide))))))
5158 (car (remove nil candidates))))
5160 (defun org-current-time ()
5161 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5162 (if (> (car org-time-stamp-rounding-minutes) 1)
5163 (let ((r (car org-time-stamp-rounding-minutes))
5164 (time (decode-time)))
5165 (apply 'encode-time
5166 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5167 (nthcdr 2 time))))
5168 (current-time)))
5170 (defun org-today ()
5171 "Return today date, considering `org-extend-today-until'."
5172 (time-to-days
5173 (time-subtract (current-time)
5174 (list 0 (* 3600 org-extend-today-until) 0))))
5176 ;;;; Font-Lock stuff, including the activators
5178 (defvar org-mouse-map (make-sparse-keymap))
5179 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5180 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5181 (when org-mouse-1-follows-link
5182 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5183 (when org-tab-follows-link
5184 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5185 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5187 (require 'font-lock)
5189 (defconst org-non-link-chars "]\t\n\r<>")
5190 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5191 "shell" "elisp" "doi" "message"))
5192 (defvar org-link-types-re nil
5193 "Matches a link that has a url-like prefix like \"http:\"")
5194 (defvar org-link-re-with-space nil
5195 "Matches a link with spaces, optional angular brackets around it.")
5196 (defvar org-link-re-with-space2 nil
5197 "Matches a link with spaces, optional angular brackets around it.")
5198 (defvar org-link-re-with-space3 nil
5199 "Matches a link with spaces, only for internal part in bracket links.")
5200 (defvar org-angle-link-re nil
5201 "Matches link with angular brackets, spaces are allowed.")
5202 (defvar org-plain-link-re nil
5203 "Matches plain link, without spaces.")
5204 (defvar org-bracket-link-regexp nil
5205 "Matches a link in double brackets.")
5206 (defvar org-bracket-link-analytic-regexp nil
5207 "Regular expression used to analyze links.
5208 Here is what the match groups contain after a match:
5209 1: http:
5210 2: http
5211 3: path
5212 4: [desc]
5213 5: desc")
5214 (defvar org-bracket-link-analytic-regexp++ nil
5215 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5216 (defvar org-any-link-re nil
5217 "Regular expression matching any link.")
5219 (defcustom org-match-sexp-depth 3
5220 "Number of stacked braces for sub/superscript matching.
5221 This has to be set before loading org.el to be effective."
5222 :group 'org-export-translation ; ??????????????????????????/
5223 :type 'integer)
5225 (defun org-create-multibrace-regexp (left right n)
5226 "Create a regular expression which will match a balanced sexp.
5227 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5228 as single character strings.
5229 The regexp returned will match the entire expression including the
5230 delimiters. It will also define a single group which contains the
5231 match except for the outermost delimiters. The maximum depth of
5232 stacked delimiters is N. Escaping delimiters is not possible."
5233 (let* ((nothing (concat "[^" left right "]*?"))
5234 (or "\\|")
5235 (re nothing)
5236 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5237 (while (> n 1)
5238 (setq n (1- n)
5239 re (concat re or next)
5240 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5241 (concat left "\\(" re "\\)" right)))
5243 (defvar org-match-substring-regexp
5244 (concat
5245 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5246 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5247 "\\|"
5248 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5249 "\\|"
5250 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5251 "The regular expression matching a sub- or superscript.")
5253 (defvar org-match-substring-with-braces-regexp
5254 (concat
5255 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5256 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5257 "\\)")
5258 "The regular expression matching a sub- or superscript, forcing braces.")
5260 (defun org-make-link-regexps ()
5261 "Update the link regular expressions.
5262 This should be called after the variable `org-link-types' has changed."
5263 (setq org-link-types-re
5264 (concat
5265 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5266 org-link-re-with-space
5267 (concat
5268 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5269 "\\([^" org-non-link-chars " ]"
5270 "[^" org-non-link-chars "]*"
5271 "[^" org-non-link-chars " ]\\)>?")
5272 org-link-re-with-space2
5273 (concat
5274 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5275 "\\([^" org-non-link-chars " ]"
5276 "[^\t\n\r]*"
5277 "[^" org-non-link-chars " ]\\)>?")
5278 org-link-re-with-space3
5279 (concat
5280 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5281 "\\([^" org-non-link-chars " ]"
5282 "[^\t\n\r]*\\)")
5283 org-angle-link-re
5284 (concat
5285 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5286 "\\([^" org-non-link-chars " ]"
5287 "[^" org-non-link-chars "]*"
5288 "\\)>")
5289 org-plain-link-re
5290 (concat
5291 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5292 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5293 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5294 org-bracket-link-regexp
5295 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5296 org-bracket-link-analytic-regexp
5297 (concat
5298 "\\[\\["
5299 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5300 "\\([^]]+\\)"
5301 "\\]"
5302 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5303 "\\]")
5304 org-bracket-link-analytic-regexp++
5305 (concat
5306 "\\[\\["
5307 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5308 "\\([^]]+\\)"
5309 "\\]"
5310 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5311 "\\]")
5312 org-any-link-re
5313 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5314 org-angle-link-re "\\)\\|\\("
5315 org-plain-link-re "\\)")))
5317 (org-make-link-regexps)
5319 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5320 "Regular expression for fast time stamp matching.")
5321 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5322 "Regular expression for fast time stamp matching.")
5323 (defconst org-ts-regexp0
5324 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5325 "Regular expression matching time strings for analysis.
5326 This one does not require the space after the date, so it can be used
5327 on a string that terminates immediately after the date.")
5328 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5329 "Regular expression matching time strings for analysis.")
5330 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5331 "Regular expression matching time stamps, with groups.")
5332 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5333 "Regular expression matching time stamps (also [..]), with groups.")
5334 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5335 "Regular expression matching a time stamp range.")
5336 (defconst org-tr-regexp-both
5337 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5338 "Regular expression matching a time stamp range.")
5339 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5340 org-ts-regexp "\\)?")
5341 "Regular expression matching a time stamp or time stamp range.")
5342 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5343 org-ts-regexp-both "\\)?")
5344 "Regular expression matching a time stamp or time stamp range.
5345 The time stamps may be either active or inactive.")
5347 (defvar org-emph-face nil)
5349 (defun org-do-emphasis-faces (limit)
5350 "Run through the buffer and add overlays to emphasized strings."
5351 (let (rtn a)
5352 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5353 (if (not (= (char-after (match-beginning 3))
5354 (char-after (match-beginning 4))))
5355 (progn
5356 (setq rtn t)
5357 (setq a (assoc (match-string 3) org-emphasis-alist))
5358 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5359 'face
5360 (nth 1 a))
5361 (and (nth 4 a)
5362 (org-remove-flyspell-overlays-in
5363 (match-beginning 0) (match-end 0)))
5364 (add-text-properties (match-beginning 2) (match-end 2)
5365 '(font-lock-multiline t org-emphasis t))
5366 (when org-hide-emphasis-markers
5367 (add-text-properties (match-end 4) (match-beginning 5)
5368 '(invisible org-link))
5369 (add-text-properties (match-beginning 3) (match-end 3)
5370 '(invisible org-link)))))
5371 (backward-char 1))
5372 rtn))
5374 (defun org-emphasize (&optional char)
5375 "Insert or change an emphasis, i.e. a font like bold or italic.
5376 If there is an active region, change that region to a new emphasis.
5377 If there is no region, just insert the marker characters and position
5378 the cursor between them.
5379 CHAR should be either the marker character, or the first character of the
5380 HTML tag associated with that emphasis. If CHAR is a space, the means
5381 to remove the emphasis of the selected region.
5382 If char is not given (for example in an interactive call) it
5383 will be prompted for."
5384 (interactive)
5385 (let ((eal org-emphasis-alist) e det
5386 (erc org-emphasis-regexp-components)
5387 (prompt "")
5388 (string "") beg end move tag c s)
5389 (if (org-region-active-p)
5390 (setq beg (region-beginning) end (region-end)
5391 string (buffer-substring beg end))
5392 (setq move t))
5394 (while (setq e (pop eal))
5395 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5396 c (aref tag 0))
5397 (push (cons c (string-to-char (car e))) det)
5398 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5399 (substring tag 1)))))
5400 (setq det (nreverse det))
5401 (unless char
5402 (message "%s" (concat "Emphasis marker or tag:" prompt))
5403 (setq char (read-char-exclusive)))
5404 (setq char (or (cdr (assoc char det)) char))
5405 (if (equal char ?\ )
5406 (setq s "" move nil)
5407 (unless (assoc (char-to-string char) org-emphasis-alist)
5408 (error "No such emphasis marker: \"%c\"" char))
5409 (setq s (char-to-string char)))
5410 (while (and (> (length string) 1)
5411 (equal (substring string 0 1) (substring string -1))
5412 (assoc (substring string 0 1) org-emphasis-alist))
5413 (setq string (substring string 1 -1)))
5414 (setq string (concat s string s))
5415 (if beg (delete-region beg end))
5416 (unless (or (bolp)
5417 (string-match (concat "[" (nth 0 erc) "\n]")
5418 (char-to-string (char-before (point)))))
5419 (insert " "))
5420 (unless (or (eobp)
5421 (string-match (concat "[" (nth 1 erc) "\n]")
5422 (char-to-string (char-after (point)))))
5423 (insert " ") (backward-char 1))
5424 (insert string)
5425 (and move (backward-char 1))))
5427 (defconst org-nonsticky-props
5428 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5430 (defsubst org-rear-nonsticky-at (pos)
5431 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5433 (defun org-activate-plain-links (limit)
5434 "Run through the buffer and add overlays to links."
5435 (catch 'exit
5436 (let (f hl)
5437 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5438 (not (org-in-src-block-p)))
5439 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5440 (setq f (get-text-property (match-beginning 0) 'face))
5441 (setq hl (org-match-string-no-properties 0))
5442 (if (or (eq f 'org-tag)
5443 (and (listp f) (memq 'org-tag f)))
5445 (add-text-properties (match-beginning 0) (match-end 0)
5446 (list 'mouse-face 'highlight
5447 'face 'org-link
5448 'htmlize-link `(:uri ,hl)
5449 'keymap org-mouse-map))
5450 (org-rear-nonsticky-at (match-end 0)))
5451 t))))
5453 (defun org-activate-code (limit)
5454 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5455 (progn
5456 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5457 (remove-text-properties (match-beginning 0) (match-end 0)
5458 '(display t invisible t intangible t))
5459 t)))
5461 (defcustom org-src-fontify-natively nil
5462 "When non-nil, fontify code in code blocks."
5463 :type 'boolean
5464 :version "24.1"
5465 :group 'org-appearance
5466 :group 'org-babel)
5468 (defcustom org-allow-promoting-top-level-subtree nil
5469 "When non-nil, allow promoting a top level subtree.
5470 The leading star of the top level headline will be replaced
5471 by a #."
5472 :type 'boolean
5473 :version "24.1"
5474 :group 'org-appearance)
5476 (defun org-fontify-meta-lines-and-blocks (limit)
5477 (condition-case nil
5478 (org-fontify-meta-lines-and-blocks-1 limit)
5479 (error (message "org-mode fontification error"))))
5481 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5482 "Fontify #+ lines and blocks, in the correct ways."
5483 (let ((case-fold-search t))
5484 (if (re-search-forward
5485 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5486 limit t)
5487 (let ((beg (match-beginning 0))
5488 (block-start (match-end 0))
5489 (block-end nil)
5490 (lang (match-string 7))
5491 (beg1 (line-beginning-position 2))
5492 (dc1 (downcase (match-string 2)))
5493 (dc3 (downcase (match-string 3)))
5494 end end1 quoting block-type ovl)
5495 (cond
5496 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5497 ;; a single line of backend-specific content
5498 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5499 (remove-text-properties (match-beginning 0) (match-end 0)
5500 '(display t invisible t intangible t))
5501 (add-text-properties (match-beginning 1) (match-end 3)
5502 '(font-lock-fontified t face org-meta-line))
5503 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5504 '(font-lock-fontified t face org-block))
5505 ; for backend-specific code
5507 ((and (match-end 4) (equal dc3 "+begin"))
5508 ;; Truly a block
5509 (setq block-type (downcase (match-string 5))
5510 quoting (member block-type org-protecting-blocks))
5511 (when (re-search-forward
5512 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5513 nil t) ;; on purpose, we look further than LIMIT
5514 (setq end (min (point-max) (match-end 0))
5515 end1 (min (point-max) (1- (match-beginning 0))))
5516 (setq block-end (match-beginning 0))
5517 (when quoting
5518 (remove-text-properties beg end
5519 '(display t invisible t intangible t)))
5520 (add-text-properties
5521 beg end
5522 '(font-lock-fontified t font-lock-multiline t))
5523 (add-text-properties beg beg1 '(face org-meta-line))
5524 (add-text-properties end1 (min (point-max) (1+ end))
5525 '(face org-meta-line)) ; for end_src
5526 (cond
5527 ((and lang (not (string= lang "")) org-src-fontify-natively)
5528 (org-src-font-lock-fontify-block lang block-start block-end)
5529 ;; remove old background overlays
5530 (mapc (lambda (ov)
5531 (if (eq (overlay-get ov 'face) 'org-block-background)
5532 (delete-overlay ov)))
5533 (overlays-at (/ (+ beg1 block-end) 2)))
5534 ;; add a background overlay
5535 (setq ovl (make-overlay beg1 block-end))
5536 (overlay-put ovl 'face 'org-block-background)
5537 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5538 (quoting
5539 (add-text-properties beg1 (min (point-max) (1+ end1))
5540 '(face org-block))) ; end of source block
5541 ((not org-fontify-quote-and-verse-blocks))
5542 ((string= block-type "quote")
5543 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5544 ((string= block-type "verse")
5545 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5546 (add-text-properties beg beg1 '(face org-block-begin-line))
5547 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5548 '(face org-block-end-line))
5550 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5551 (add-text-properties
5552 beg (match-end 3)
5553 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5554 '(font-lock-fontified t invisible t)
5555 '(font-lock-fontified t face org-document-info-keyword)))
5556 (add-text-properties
5557 (match-beginning 6) (match-end 6)
5558 (if (string-equal dc1 "+title:")
5559 '(font-lock-fontified t face org-document-title)
5560 '(font-lock-fontified t face org-document-info))))
5561 ((or (equal dc1 "+results")
5562 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5563 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5564 "+call:" "+header:" "+headers:" "+name:"))
5565 (and (match-end 4) (equal dc3 "+attr")))
5566 (add-text-properties
5567 beg (match-end 0)
5568 '(font-lock-fontified t face org-meta-line))
5570 ((member dc3 '(" " ""))
5571 (add-text-properties
5572 beg (match-end 0)
5573 '(font-lock-fontified t face font-lock-comment-face)))
5574 ((not (member (char-after beg) '(?\ ?\t)))
5575 ;; just any other in-buffer setting, but not indented
5576 (add-text-properties
5577 beg (match-end 0)
5578 '(font-lock-fontified t face org-meta-line))
5580 (t nil))))))
5582 (defun org-activate-angle-links (limit)
5583 "Run through the buffer and add overlays to links."
5584 (if (and (re-search-forward org-angle-link-re limit t)
5585 (not (org-in-src-block-p)))
5586 (progn
5587 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5588 (add-text-properties (match-beginning 0) (match-end 0)
5589 (list 'mouse-face 'highlight
5590 'keymap org-mouse-map))
5591 (org-rear-nonsticky-at (match-end 0))
5592 t)))
5594 (defun org-activate-footnote-links (limit)
5595 "Run through the buffer and add overlays to footnotes."
5596 (let ((fn (org-footnote-next-reference-or-definition limit)))
5597 (when fn
5598 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5599 (org-remove-flyspell-overlays-in beg end)
5600 (add-text-properties beg end
5601 (list 'mouse-face 'highlight
5602 'keymap org-mouse-map
5603 'help-echo
5604 (if (= (point-at-bol) beg)
5605 "Footnote definition"
5606 "Footnote reference")
5607 'font-lock-fontified t
5608 'font-lock-multiline t
5609 'face 'org-footnote))))))
5611 (defun org-activate-bracket-links (limit)
5612 "Run through the buffer and add overlays to bracketed links."
5613 (if (and (re-search-forward org-bracket-link-regexp limit t)
5614 (not (org-in-src-block-p)))
5615 (let* ((hl (org-match-string-no-properties 1))
5616 (help (concat "LINK: " hl))
5617 ;; FIXME: Above we should remove the escapes. But that
5618 ;; requires another match, protecting match data, a lot
5619 ;; of overhead for font-lock.
5620 (ip (org-maybe-intangible
5621 (list 'invisible 'org-link
5622 'keymap org-mouse-map 'mouse-face 'highlight
5623 'font-lock-multiline t 'help-echo help
5624 'htmlize-link `(:uri ,hl))))
5625 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5626 'font-lock-multiline t 'help-echo help
5627 'htmlize-link `(:uri ,hl))))
5628 ;; We need to remove the invisible property here. Table narrowing
5629 ;; may have made some of this invisible.
5630 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5631 (remove-text-properties (match-beginning 0) (match-end 0)
5632 '(invisible nil))
5633 (if (match-end 3)
5634 (progn
5635 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5636 (org-rear-nonsticky-at (match-beginning 3))
5637 (add-text-properties (match-beginning 3) (match-end 3) vp)
5638 (org-rear-nonsticky-at (match-end 3))
5639 (add-text-properties (match-end 3) (match-end 0) ip)
5640 (org-rear-nonsticky-at (match-end 0)))
5641 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5642 (org-rear-nonsticky-at (match-beginning 1))
5643 (add-text-properties (match-beginning 1) (match-end 1) vp)
5644 (org-rear-nonsticky-at (match-end 1))
5645 (add-text-properties (match-end 1) (match-end 0) ip)
5646 (org-rear-nonsticky-at (match-end 0)))
5647 t)))
5649 (defun org-activate-dates (limit)
5650 "Run through the buffer and add overlays to dates."
5651 (if (re-search-forward org-tsr-regexp-both limit t)
5652 (progn
5653 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5654 (add-text-properties (match-beginning 0) (match-end 0)
5655 (list 'mouse-face 'highlight
5656 'keymap org-mouse-map))
5657 (org-rear-nonsticky-at (match-end 0))
5658 (when org-display-custom-times
5659 (if (match-end 3)
5660 (org-display-custom-time (match-beginning 3) (match-end 3)))
5661 (org-display-custom-time (match-beginning 1) (match-end 1)))
5662 t)))
5664 (defvar org-target-link-regexp nil
5665 "Regular expression matching radio targets in plain text.")
5666 (make-variable-buffer-local 'org-target-link-regexp)
5667 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5668 "Regular expression matching a link target.")
5669 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5670 "Regular expression matching a radio target.")
5671 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5672 "Regular expression matching any target.")
5674 (defun org-activate-target-links (limit)
5675 "Run through the buffer and add overlays to target matches."
5676 (when org-target-link-regexp
5677 (let ((case-fold-search t))
5678 (if (re-search-forward org-target-link-regexp limit t)
5679 (progn
5680 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5681 (add-text-properties (match-beginning 0) (match-end 0)
5682 (list 'mouse-face 'highlight
5683 'keymap org-mouse-map
5684 'help-echo "Radio target link"
5685 'org-linked-text t))
5686 (org-rear-nonsticky-at (match-end 0))
5687 t)))))
5689 (defun org-update-radio-target-regexp ()
5690 "Find all radio targets in this file and update the regular expression."
5691 (interactive)
5692 (when (memq 'radio org-activate-links)
5693 (setq org-target-link-regexp
5694 (org-make-target-link-regexp (org-all-targets 'radio)))
5695 (org-restart-font-lock)))
5697 (defun org-hide-wide-columns (limit)
5698 (let (s e)
5699 (setq s (text-property-any (point) (or limit (point-max))
5700 'org-cwidth t))
5701 (when s
5702 (setq e (next-single-property-change s 'org-cwidth))
5703 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5704 (goto-char e)
5705 t)))
5707 (defvar org-latex-and-specials-regexp nil
5708 "Regular expression for highlighting export special stuff.")
5709 (defvar org-match-substring-regexp)
5710 (defvar org-match-substring-with-braces-regexp)
5712 ;; This should be with the exporter code, but we also use if for font-locking
5713 (defconst org-export-html-special-string-regexps
5714 '(("\\\\-" . "&shy;")
5715 ("---\\([^-]\\)" . "&mdash;\\1")
5716 ("--\\([^-]\\)" . "&ndash;\\1")
5717 ("\\.\\.\\." . "&hellip;"))
5718 "Regular expressions for special string conversion.")
5721 (defun org-compute-latex-and-specials-regexp ()
5722 "Compute regular expression for stuff treated specially by exporters."
5723 (if (not org-highlight-latex-fragments-and-specials)
5724 (org-set-local 'org-latex-and-specials-regexp nil)
5725 (require 'org-exp)
5726 (let*
5727 ((matchers (plist-get org-format-latex-options :matchers))
5728 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5729 org-latex-regexps)))
5730 (org-export-allow-BIND nil)
5731 (options (org-combine-plists (org-default-export-plist)
5732 (org-infile-export-plist)))
5733 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5734 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5735 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5736 (org-export-html-expand (plist-get options :expand-quoted-html))
5737 (org-export-with-special-strings (plist-get options :special-strings))
5738 (re-sub
5739 (cond
5740 ((equal org-export-with-sub-superscripts '{})
5741 (list org-match-substring-with-braces-regexp))
5742 (org-export-with-sub-superscripts
5743 (list org-match-substring-regexp))))
5744 (re-latex
5745 (if org-export-with-LaTeX-fragments
5746 (mapcar (lambda (x) (nth 1 x)) latexs)))
5747 (re-macros
5748 (if org-export-with-TeX-macros
5749 (list (concat "\\\\"
5750 (regexp-opt
5751 (append
5753 (delq nil
5754 (mapcar 'car-safe
5755 (append org-entities-user
5756 org-entities)))
5757 (if (boundp 'org-latex-entities)
5758 (mapcar (lambda (x)
5759 (or (car-safe x) x))
5760 org-latex-entities)
5761 nil))
5762 'words))) ; FIXME
5764 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5765 (re-special (if org-export-with-special-strings
5766 (mapcar (lambda (x) (car x))
5767 org-export-html-special-string-regexps)))
5768 (re-rest
5769 (delq nil
5770 (list
5771 (if org-export-html-expand "@<[^>\n]+>")
5772 ))))
5773 (org-set-local
5774 'org-latex-and-specials-regexp
5775 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5776 re-rest) "\\|")))))
5778 (defun org-do-latex-and-special-faces (limit)
5779 "Run through the buffer and add overlays to links."
5780 (when org-latex-and-specials-regexp
5781 (let (rtn d)
5782 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5783 limit t))
5784 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5785 'face))
5786 '(org-code org-verbatim underline)))
5787 (progn
5788 (setq rtn t
5789 d (cond ((member (char-after (1+ (match-beginning 0)))
5790 '(?_ ?^)) 1)
5791 (t 0)))
5792 (font-lock-prepend-text-property
5793 (+ d (match-beginning 0)) (match-end 0)
5794 'face 'org-latex-and-export-specials)
5795 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5796 '(font-lock-multiline t)))))
5797 rtn)))
5799 (defun org-restart-font-lock ()
5800 "Restart `font-lock-mode', to force refontification."
5801 (when (and (boundp 'font-lock-mode) font-lock-mode)
5802 (font-lock-mode -1)
5803 (font-lock-mode 1)))
5805 (defun org-all-targets (&optional radio)
5806 "Return a list of all targets in this file.
5807 When optional argument RADIO is non-nil, only find radio
5808 targets."
5809 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5810 (save-excursion
5811 (goto-char (point-min))
5812 (while (re-search-forward re nil t)
5813 ;; Make sure point is really within the object.
5814 (backward-char)
5815 (let ((obj (org-element-context)))
5816 (when (memq (org-element-type obj) '(radio-target target))
5817 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5818 rtn)))
5820 (defun org-make-target-link-regexp (targets)
5821 "Make regular expression matching all strings in TARGETS.
5822 The regular expression finds the targets also if there is a line break
5823 between words."
5824 (and targets
5825 (concat
5826 "\\<\\("
5827 (mapconcat
5828 (lambda (x)
5829 (setq x (regexp-quote x))
5830 (while (string-match " +" x)
5831 (setq x (replace-match "\\s-+" t t x)))
5833 targets
5834 "\\|")
5835 "\\)\\>")))
5837 (defun org-activate-tags (limit)
5838 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5839 (progn
5840 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5841 (add-text-properties (match-beginning 1) (match-end 1)
5842 (list 'mouse-face 'highlight
5843 'keymap org-mouse-map))
5844 (org-rear-nonsticky-at (match-end 1))
5845 t)))
5847 (defun org-outline-level ()
5848 "Compute the outline level of the heading at point.
5849 If this is called at a normal headline, the level is the number of stars.
5850 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5851 (save-excursion
5852 (if (not (condition-case nil
5853 (org-back-to-heading t)
5854 (error nil)))
5856 (looking-at org-outline-regexp)
5857 (1- (- (match-end 0) (match-beginning 0))))))
5859 (defvar org-font-lock-keywords nil)
5861 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5862 "Regular expression matching a property line.")
5864 (defvar org-font-lock-hook nil
5865 "Functions to be called for special font lock stuff.")
5867 (defvar org-font-lock-set-keywords-hook nil
5868 "Functions that can manipulate `org-font-lock-extra-keywords'.
5869 This is called after `org-font-lock-extra-keywords' is defined, but before
5870 it is installed to be used by font lock. This can be useful if something
5871 needs to be inserted at a specific position in the font-lock sequence.")
5873 (defun org-font-lock-hook (limit)
5874 "Run `org-font-lock-hook' within LIMIT."
5875 (run-hook-with-args 'org-font-lock-hook limit))
5877 (defun org-set-font-lock-defaults ()
5878 "Set font lock defaults for the current buffer."
5879 (let* ((em org-fontify-emphasized-text)
5880 (lk org-activate-links)
5881 (org-font-lock-extra-keywords
5882 (list
5883 ;; Call the hook
5884 '(org-font-lock-hook)
5885 ;; Headlines
5886 `(,(if org-fontify-whole-heading-line
5887 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5888 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5889 (1 (org-get-level-face 1))
5890 (2 (org-get-level-face 2))
5891 (3 (org-get-level-face 3)))
5892 ;; Table lines
5893 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5894 (1 'org-table t))
5895 ;; Table internals
5896 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5897 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5898 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5899 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5900 ;; Drawers
5901 (list org-drawer-regexp '(0 'org-special-keyword t))
5902 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5903 ;; Properties
5904 (list org-property-re
5905 '(1 'org-special-keyword t)
5906 '(3 'org-property-value t))
5907 ;; Links
5908 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5909 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5910 (if (memq 'plain lk) '(org-activate-plain-links))
5911 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5912 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5913 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5914 (if (memq 'footnote lk) '(org-activate-footnote-links))
5915 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5916 '(org-hide-wide-columns (0 nil append))
5917 ;; TODO keyword
5918 (list (format org-heading-keyword-regexp-format
5919 org-todo-regexp)
5920 '(2 (org-get-todo-face 2) t))
5921 ;; DONE
5922 (if org-fontify-done-headline
5923 (list (format org-heading-keyword-regexp-format
5924 (concat
5925 "\\(?:"
5926 (mapconcat 'regexp-quote org-done-keywords "\\|")
5927 "\\)"))
5928 '(2 'org-headline-done t))
5929 nil)
5930 ;; Priorities
5931 '(org-font-lock-add-priority-faces)
5932 ;; Tags
5933 '(org-font-lock-add-tag-faces)
5934 ;; Special keywords
5935 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5936 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5937 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5938 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5939 ;; Emphasis
5940 (if em
5941 (if (featurep 'xemacs)
5942 '(org-do-emphasis-faces (0 nil append))
5943 '(org-do-emphasis-faces)))
5944 ;; Checkboxes
5945 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5946 1 'org-checkbox prepend)
5947 (if (cdr (assq 'checkbox org-list-automatic-rules))
5948 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5949 (0 (org-get-checkbox-statistics-face) t)))
5950 ;; Description list items
5951 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5952 1 'org-list-dt prepend)
5953 ;; ARCHIVEd headings
5954 (list (concat
5955 org-outline-regexp-bol
5956 "\\(.*:" org-archive-tag ":.*\\)")
5957 '(1 'org-archived prepend))
5958 ;; Specials
5959 '(org-do-latex-and-special-faces)
5960 '(org-fontify-entities)
5961 '(org-raise-scripts)
5962 ;; Code
5963 '(org-activate-code (1 'org-code t))
5964 ;; COMMENT
5965 (list (format org-heading-keyword-regexp-format
5966 (concat "\\("
5967 org-comment-string "\\|" org-quote-string
5968 "\\)"))
5969 '(2 'org-special-keyword t))
5970 ;; Blocks and meta lines
5971 '(org-fontify-meta-lines-and-blocks)
5973 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5974 (run-hooks 'org-font-lock-set-keywords-hook)
5975 ;; Now set the full font-lock-keywords
5976 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5977 (org-set-local 'font-lock-defaults
5978 '(org-font-lock-keywords t nil nil backward-paragraph))
5979 (kill-local-variable 'font-lock-keywords) nil))
5981 (defun org-toggle-pretty-entities ()
5982 "Toggle the composition display of entities as UTF8 characters."
5983 (interactive)
5984 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5985 (org-restart-font-lock)
5986 (if org-pretty-entities
5987 (message "Entities are displayed as UTF8 characters")
5988 (save-restriction
5989 (widen)
5990 (org-decompose-region (point-min) (point-max))
5991 (message "Entities are displayed plain"))))
5993 (defvar org-custom-properties-overlays nil
5994 "List of overlays used for custom properties.")
5995 (make-variable-buffer-local 'org-custom-properties-overlays)
5997 (defun org-toggle-custom-properties-visibility ()
5998 "Display or hide properties in `org-custom-properties'."
5999 (interactive)
6000 (if org-custom-properties-overlays
6001 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6002 (setq org-custom-properties-overlays nil))
6003 (unless (not org-custom-properties)
6004 (save-excursion
6005 (save-restriction
6006 (widen)
6007 (goto-char (point-min))
6008 (while (re-search-forward org-property-re nil t)
6009 (mapc (lambda(p)
6010 (when (equal p (substring (match-string 1) 1 -1))
6011 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6012 (overlay-put o 'invisible t)
6013 (overlay-put o 'org-custom-property t)
6014 (push o org-custom-properties-overlays))))
6015 org-custom-properties)))))))
6017 (defun org-fontify-entities (limit)
6018 "Find an entity to fontify."
6019 (let (ee)
6020 (when org-pretty-entities
6021 (catch 'match
6022 (while (re-search-forward
6023 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6024 limit t)
6025 (if (and (not (org-in-indented-comment-line))
6026 (setq ee (org-entity-get (match-string 1)))
6027 (= (length (nth 6 ee)) 1))
6028 (let*
6029 ((end (if (equal (match-string 2) "{}")
6030 (match-end 2)
6031 (match-end 1))))
6032 (add-text-properties
6033 (match-beginning 0) end
6034 (list 'font-lock-fontified t))
6035 (compose-region (match-beginning 0) end
6036 (nth 6 ee) nil)
6037 (backward-char 1)
6038 (throw 'match t))))
6039 nil))))
6041 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6042 "Fontify string S like in Org-mode."
6043 (with-temp-buffer
6044 (insert s)
6045 (let ((org-odd-levels-only odd-levels))
6046 (org-mode)
6047 (font-lock-fontify-buffer)
6048 (buffer-string))))
6050 (defvar org-m nil)
6051 (defvar org-l nil)
6052 (defvar org-f nil)
6053 (defun org-get-level-face (n)
6054 "Get the right face for match N in font-lock matching of headlines."
6055 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6056 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6057 (if org-cycle-level-faces
6058 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6059 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6060 (cond
6061 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6062 ((eq n 2) org-f)
6063 (t (if org-level-color-stars-only nil org-f))))
6066 (defun org-get-todo-face (kwd)
6067 "Get the right face for a TODO keyword KWD.
6068 If KWD is a number, get the corresponding match group."
6069 (if (numberp kwd) (setq kwd (match-string kwd)))
6070 (or (org-face-from-face-or-color
6071 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6072 (and (member kwd org-done-keywords) 'org-done)
6073 'org-todo))
6075 (defun org-face-from-face-or-color (context inherit face-or-color)
6076 "Create a face list that inherits INHERIT, but sets the foreground color.
6077 When FACE-OR-COLOR is not a string, just return it."
6078 (if (stringp face-or-color)
6079 (list :inherit inherit
6080 (cdr (assoc context org-faces-easy-properties))
6081 face-or-color)
6082 face-or-color))
6084 (defun org-font-lock-add-tag-faces (limit)
6085 "Add the special tag faces."
6086 (when (and org-tag-faces org-tags-special-faces-re)
6087 (while (re-search-forward org-tags-special-faces-re limit t)
6088 (add-text-properties (match-beginning 1) (match-end 1)
6089 (list 'face (org-get-tag-face 1)
6090 'font-lock-fontified t))
6091 (backward-char 1))))
6093 (defun org-font-lock-add-priority-faces (limit)
6094 "Add the special priority faces."
6095 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6096 (when (save-match-data (org-at-heading-p))
6097 (add-text-properties
6098 (match-beginning 0) (match-end 0)
6099 (list 'face (or (org-face-from-face-or-color
6100 'priority 'org-special-keyword
6101 (cdr (assoc (char-after (match-beginning 1))
6102 org-priority-faces)))
6103 'org-special-keyword)
6104 'font-lock-fontified t)))))
6106 (defun org-get-tag-face (kwd)
6107 "Get the right face for a TODO keyword KWD.
6108 If KWD is a number, get the corresponding match group."
6109 (if (numberp kwd) (setq kwd (match-string kwd)))
6110 (or (org-face-from-face-or-color
6111 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6112 'org-tag))
6114 (defun org-unfontify-region (beg end &optional maybe_loudly)
6115 "Remove fontification and activation overlays from links."
6116 (font-lock-default-unfontify-region beg end)
6117 (let* ((buffer-undo-list t)
6118 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6119 (inhibit-modification-hooks t)
6120 deactivate-mark buffer-file-name buffer-file-truename)
6121 (org-decompose-region beg end)
6122 (remove-text-properties beg end
6123 '(mouse-face t keymap t org-linked-text t
6124 invisible t intangible t
6125 org-no-flyspell t org-emphasis t))
6126 (org-remove-font-lock-display-properties beg end)))
6128 (defconst org-script-display '(((raise -0.3) (height 0.7))
6129 ((raise 0.3) (height 0.7))
6130 ((raise -0.5))
6131 ((raise 0.5)))
6132 "Display properties for showing superscripts and subscripts.")
6134 (defun org-remove-font-lock-display-properties (beg end)
6135 "Remove specific display properties that have been added by font lock.
6136 The will remove the raise properties that are used to show superscripts
6137 and subscripts."
6138 (let (next prop)
6139 (while (< beg end)
6140 (setq next (next-single-property-change beg 'display nil end)
6141 prop (get-text-property beg 'display))
6142 (if (member prop org-script-display)
6143 (put-text-property beg next 'display nil))
6144 (setq beg next))))
6146 (defun org-raise-scripts (limit)
6147 "Add raise properties to sub/superscripts."
6148 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6149 (if (re-search-forward
6150 (if (eq org-use-sub-superscripts t)
6151 org-match-substring-regexp
6152 org-match-substring-with-braces-regexp)
6153 limit t)
6154 (let* ((pos (point)) table-p comment-p
6155 (mpos (match-beginning 3))
6156 (emph-p (get-text-property mpos 'org-emphasis))
6157 (link-p (get-text-property mpos 'mouse-face))
6158 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6159 (goto-char (point-at-bol))
6160 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6161 comment-p (org-looking-at-p "[ \t]*#"))
6162 (goto-char pos)
6163 ;; FIXME: Should we go back one character here, for a_b^c
6164 ;; (goto-char (1- pos)) ;????????????????????
6165 (if (or comment-p emph-p link-p keyw-p)
6167 (put-text-property (match-beginning 3) (match-end 0)
6168 'display
6169 (if (equal (char-after (match-beginning 2)) ?^)
6170 (nth (if table-p 3 1) org-script-display)
6171 (nth (if table-p 2 0) org-script-display)))
6172 (add-text-properties (match-beginning 2) (match-end 2)
6173 (list 'invisible t
6174 'org-dwidth t 'org-dwidth-n 1))
6175 (if (and (eq (char-after (match-beginning 3)) ?{)
6176 (eq (char-before (match-end 3)) ?}))
6177 (progn
6178 (add-text-properties
6179 (match-beginning 3) (1+ (match-beginning 3))
6180 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6181 (add-text-properties
6182 (1- (match-end 3)) (match-end 3)
6183 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6184 t)))))
6186 ;;;; Visibility cycling, including org-goto and indirect buffer
6188 ;;; Cycling
6190 (defvar org-cycle-global-status nil)
6191 (make-variable-buffer-local 'org-cycle-global-status)
6192 (defvar org-cycle-subtree-status nil)
6193 (make-variable-buffer-local 'org-cycle-subtree-status)
6195 (defvar org-inlinetask-min-level)
6197 ;;;###autoload
6198 (defun org-cycle (&optional arg)
6199 "TAB-action and visibility cycling for Org-mode.
6201 This is the command invoked in Org-mode by the TAB key. Its main purpose
6202 is outline visibility cycling, but it also invokes other actions
6203 in special contexts.
6205 - When this function is called with a prefix argument, rotate the entire
6206 buffer through 3 states (global cycling)
6207 1. OVERVIEW: Show only top-level headlines.
6208 2. CONTENTS: Show all headlines of all levels, but no body text.
6209 3. SHOW ALL: Show everything.
6210 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6211 determined by the variable `org-startup-folded', and by any VISIBILITY
6212 properties in the buffer.
6213 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6214 including any drawers.
6216 - When inside a table, re-align the table and move to the next field.
6218 - When point is at the beginning of a headline, rotate the subtree started
6219 by this line through 3 different states (local cycling)
6220 1. FOLDED: Only the main headline is shown.
6221 2. CHILDREN: The main headline and the direct children are shown.
6222 From this state, you can move to one of the children
6223 and zoom in further.
6224 3. SUBTREE: Show the entire subtree, including body text.
6225 If there is no subtree, switch directly from CHILDREN to FOLDED.
6227 - When point is at the beginning of an empty headline and the variable
6228 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6229 of the headline by demoting and promoting it to likely levels. This
6230 speeds up creation document structure by pressing TAB once or several
6231 times right after creating a new headline.
6233 - When there is a numeric prefix, go up to a heading with level ARG, do
6234 a `show-subtree' and return to the previous cursor position. If ARG
6235 is negative, go up that many levels.
6237 - When point is not at the beginning of a headline, execute the global
6238 binding for TAB, which is re-indenting the line. See the option
6239 `org-cycle-emulate-tab' for details.
6241 - Special case: if point is at the beginning of the buffer and there is
6242 no headline in line 1, this function will act as if called with prefix arg
6243 (C-u TAB, same as S-TAB) also when called without prefix arg.
6244 But only if also the variable `org-cycle-global-at-bob' is t."
6245 (interactive "P")
6246 (org-load-modules-maybe)
6247 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6248 (and org-cycle-level-after-item/entry-creation
6249 (or (org-cycle-level)
6250 (org-cycle-item-indentation))))
6251 (let* (message-log-max ; Don't populate the *Messages* buffer
6252 (limit-level
6253 (or org-cycle-max-level
6254 (and (boundp 'org-inlinetask-min-level)
6255 org-inlinetask-min-level
6256 (1- org-inlinetask-min-level))))
6257 (nstars (and limit-level
6258 (if org-odd-levels-only
6259 (and limit-level (1- (* limit-level 2)))
6260 limit-level)))
6261 (org-outline-regexp
6262 (if (not (derived-mode-p 'org-mode))
6263 outline-regexp
6264 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6265 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6266 (not (looking-at org-outline-regexp))))
6267 (org-cycle-hook
6268 (if bob-special
6269 (delq 'org-optimize-window-after-visibility-change
6270 (copy-sequence org-cycle-hook))
6271 org-cycle-hook))
6272 (pos (point)))
6274 (if (or bob-special (equal arg '(4)))
6275 ;; special case: use global cycling
6276 (setq arg t))
6278 (cond
6280 ((equal arg '(16))
6281 (setq last-command 'dummy)
6282 (org-set-startup-visibility)
6283 (message "Startup visibility, plus VISIBILITY properties"))
6285 ((equal arg '(64))
6286 (show-all)
6287 (message "Entire buffer visible, including drawers"))
6289 ;; Table: enter it or move to the next field.
6290 ((org-at-table-p 'any)
6291 (if (org-at-table.el-p)
6292 (message "Use C-c ' to edit table.el tables")
6293 (if arg (org-table-edit-field t)
6294 (org-table-justify-field-maybe)
6295 (call-interactively 'org-table-next-field))))
6297 ((run-hook-with-args-until-success
6298 'org-tab-after-check-for-table-hook))
6300 ;; Global cycling: delegate to `org-cycle-internal-global'.
6301 ((eq arg t) (org-cycle-internal-global))
6303 ;; Drawers: delegate to `org-flag-drawer'.
6304 ((and org-drawers org-drawer-regexp
6305 (save-excursion
6306 (beginning-of-line 1)
6307 (looking-at org-drawer-regexp)))
6308 (org-flag-drawer ; toggle block visibility
6309 (not (get-char-property (match-end 0) 'invisible))))
6311 ;; Show-subtree, ARG levels up from here.
6312 ((integerp arg)
6313 (save-excursion
6314 (org-back-to-heading)
6315 (outline-up-heading (if (< arg 0) (- arg)
6316 (- (funcall outline-level) arg)))
6317 (org-show-subtree)))
6319 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6320 ((and (featurep 'org-inlinetask)
6321 (org-inlinetask-at-task-p)
6322 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6323 (org-inlinetask-toggle-visibility))
6325 ((org-try-cdlatex-tab))
6327 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6328 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6329 (save-excursion (beginning-of-line 1)
6330 (looking-at org-outline-regexp)))
6331 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6332 (org-cycle-internal-local))
6334 ;; From there: TAB emulation and template completion.
6335 (buffer-read-only (org-back-to-heading))
6337 ((run-hook-with-args-until-success
6338 'org-tab-after-check-for-cycling-hook))
6340 ((org-try-structure-completion))
6342 ((run-hook-with-args-until-success
6343 'org-tab-before-tab-emulation-hook))
6345 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6346 (or (not (bolp))
6347 (not (looking-at org-outline-regexp))))
6348 (call-interactively (global-key-binding "\t")))
6350 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6351 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6352 (or (and (eq org-cycle-emulate-tab 'white)
6353 (= (match-end 0) (point-at-eol)))
6354 (and (eq org-cycle-emulate-tab 'whitestart)
6355 (>= (match-end 0) pos))))
6357 (eq org-cycle-emulate-tab t))
6358 (call-interactively (global-key-binding "\t")))
6360 (t (save-excursion
6361 (org-back-to-heading)
6362 (org-cycle)))))))
6364 (defun org-cycle-internal-global ()
6365 "Do the global cycling action."
6366 ;; Hack to avoid display of messages for .org attachments in Gnus
6367 (let (message-log-max ; Don't populate the *Messages* buffer
6368 (ga (string-match "\\*fontification" (buffer-name))))
6369 (cond
6370 ((and (eq last-command this-command)
6371 (eq org-cycle-global-status 'overview))
6372 ;; We just created the overview - now do table of contents
6373 ;; This can be slow in very large buffers, so indicate action
6374 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6375 (unless ga (message "CONTENTS..."))
6376 (org-content)
6377 (unless ga (message "CONTENTS...done"))
6378 (setq org-cycle-global-status 'contents)
6379 (run-hook-with-args 'org-cycle-hook 'contents))
6381 ((and (eq last-command this-command)
6382 (eq org-cycle-global-status 'contents))
6383 ;; We just showed the table of contents - now show everything
6384 (run-hook-with-args 'org-pre-cycle-hook 'all)
6385 (show-all)
6386 (unless ga (message "SHOW ALL"))
6387 (setq org-cycle-global-status 'all)
6388 (run-hook-with-args 'org-cycle-hook 'all))
6391 ;; Default action: go to overview
6392 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6393 (org-overview)
6394 (unless ga (message "OVERVIEW"))
6395 (setq org-cycle-global-status 'overview)
6396 (run-hook-with-args 'org-cycle-hook 'overview)))))
6398 (defun org-cycle-internal-local ()
6399 "Do the local cycling action."
6400 (let (message-log-max ; Don't populate the *Messages* buffer
6401 (goal-column 0) eoh eol eos has-children children-skipped struct)
6402 ;; First, determine end of headline (EOH), end of subtree or item
6403 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6404 (save-excursion
6405 (if (org-at-item-p)
6406 (progn
6407 (beginning-of-line)
6408 (setq struct (org-list-struct))
6409 (setq eoh (point-at-eol))
6410 (setq eos (org-list-get-item-end-before-blank (point) struct))
6411 (setq has-children (org-list-has-child-p (point) struct)))
6412 (org-back-to-heading)
6413 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6414 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6415 (setq has-children
6416 (or (save-excursion
6417 (let ((level (funcall outline-level)))
6418 (outline-next-heading)
6419 (and (org-at-heading-p t)
6420 (> (funcall outline-level) level))))
6421 (save-excursion
6422 (org-list-search-forward (org-item-beginning-re) eos t)))))
6423 ;; Determine end invisible part of buffer (EOL)
6424 (beginning-of-line 2)
6425 ;; XEmacs doesn't have `next-single-char-property-change'
6426 (if (featurep 'xemacs)
6427 (while (and (not (eobp)) ;; this is like `next-line'
6428 (get-char-property (1- (point)) 'invisible))
6429 (beginning-of-line 2))
6430 (while (and (not (eobp)) ;; this is like `next-line'
6431 (get-char-property (1- (point)) 'invisible))
6432 (goto-char (next-single-char-property-change (point) 'invisible))
6433 (and (eolp) (beginning-of-line 2))))
6434 (setq eol (point)))
6435 ;; Find out what to do next and set `this-command'
6436 (cond
6437 ((= eos eoh)
6438 ;; Nothing is hidden behind this heading
6439 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6440 (message "EMPTY ENTRY")
6441 (setq org-cycle-subtree-status nil)
6442 (save-excursion
6443 (goto-char eos)
6444 (outline-next-heading)
6445 (if (outline-invisible-p) (org-flag-heading nil))))
6446 ((and (or (>= eol eos)
6447 (not (string-match "\\S-" (buffer-substring eol eos))))
6448 (or has-children
6449 (not (setq children-skipped
6450 org-cycle-skip-children-state-if-no-children))))
6451 ;; Entire subtree is hidden in one line: children view
6452 (run-hook-with-args 'org-pre-cycle-hook 'children)
6453 (if (org-at-item-p)
6454 (org-list-set-item-visibility (point-at-bol) struct 'children)
6455 (org-show-entry)
6456 (org-with-limited-levels (show-children))
6457 ;; FIXME: This slows down the func way too much.
6458 ;; How keep drawers hidden in subtree anyway?
6459 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6460 ;; (org-cycle-hide-drawers 'subtree))
6462 ;; Fold every list in subtree to top-level items.
6463 (when (eq org-cycle-include-plain-lists 'integrate)
6464 (save-excursion
6465 (org-back-to-heading)
6466 (while (org-list-search-forward (org-item-beginning-re) eos t)
6467 (beginning-of-line 1)
6468 (let* ((struct (org-list-struct))
6469 (prevs (org-list-prevs-alist struct))
6470 (end (org-list-get-bottom-point struct)))
6471 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6472 (org-list-get-all-items (point) struct prevs))
6473 (goto-char end))))))
6474 (message "CHILDREN")
6475 (save-excursion
6476 (goto-char eos)
6477 (outline-next-heading)
6478 (if (outline-invisible-p) (org-flag-heading nil)))
6479 (setq org-cycle-subtree-status 'children)
6480 (run-hook-with-args 'org-cycle-hook 'children))
6481 ((or children-skipped
6482 (and (eq last-command this-command)
6483 (eq org-cycle-subtree-status 'children)))
6484 ;; We just showed the children, or no children are there,
6485 ;; now show everything.
6486 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6487 (outline-flag-region eoh eos nil)
6488 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6489 (setq org-cycle-subtree-status 'subtree)
6490 (run-hook-with-args 'org-cycle-hook 'subtree))
6492 ;; Default action: hide the subtree.
6493 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6494 (outline-flag-region eoh eos t)
6495 (message "FOLDED")
6496 (setq org-cycle-subtree-status 'folded)
6497 (run-hook-with-args 'org-cycle-hook 'folded)))))
6499 ;;;###autoload
6500 (defun org-global-cycle (&optional arg)
6501 "Cycle the global visibility. For details see `org-cycle'.
6502 With \\[universal-argument] prefix arg, switch to startup visibility.
6503 With a numeric prefix, show all headlines up to that level."
6504 (interactive "P")
6505 (let ((org-cycle-include-plain-lists
6506 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6507 (cond
6508 ((integerp arg)
6509 (show-all)
6510 (hide-sublevels arg)
6511 (setq org-cycle-global-status 'contents))
6512 ((equal arg '(4))
6513 (org-set-startup-visibility)
6514 (message "Startup visibility, plus VISIBILITY properties."))
6516 (org-cycle '(4))))))
6518 (defun org-set-startup-visibility ()
6519 "Set the visibility required by startup options and properties."
6520 (cond
6521 ((eq org-startup-folded t)
6522 (org-cycle '(4)))
6523 ((eq org-startup-folded 'content)
6524 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6525 (org-cycle '(4)) (org-cycle '(4)))))
6526 (unless (eq org-startup-folded 'showeverything)
6527 (if org-hide-block-startup (org-hide-block-all))
6528 (org-set-visibility-according-to-property 'no-cleanup)
6529 (org-cycle-hide-archived-subtrees 'all)
6530 (org-cycle-hide-drawers 'all)
6531 (org-cycle-show-empty-lines t)))
6533 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6534 "Switch subtree visibilities according to :VISIBILITY: property."
6535 (interactive)
6536 (let (org-show-entry-below state)
6537 (save-excursion
6538 (goto-char (point-min))
6539 (while (re-search-forward
6540 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6541 nil t)
6542 (setq state (match-string 1))
6543 (save-excursion
6544 (org-back-to-heading t)
6545 (hide-subtree)
6546 (org-reveal)
6547 (cond
6548 ((equal state '("fold" "folded"))
6549 (hide-subtree))
6550 ((equal state "children")
6551 (org-show-hidden-entry)
6552 (show-children))
6553 ((equal state "content")
6554 (save-excursion
6555 (save-restriction
6556 (org-narrow-to-subtree)
6557 (org-content))))
6558 ((member state '("all" "showall"))
6559 (show-subtree)))))
6560 (unless no-cleanup
6561 (org-cycle-hide-archived-subtrees 'all)
6562 (org-cycle-hide-drawers 'all)
6563 (org-cycle-show-empty-lines 'all)))))
6565 ;; This function uses outline-regexp instead of the more fundamental
6566 ;; org-outline-regexp so that org-cycle-global works outside of Org
6567 ;; buffers, where outline-regexp is needed.
6568 (defun org-overview ()
6569 "Switch to overview mode, showing only top-level headlines.
6570 Really, this shows all headlines with level equal or greater than the level
6571 of the first headline in the buffer. This is important, because if the
6572 first headline is not level one, then (hide-sublevels 1) gives confusing
6573 results."
6574 (interactive)
6575 (let ((level (save-excursion
6576 (goto-char (point-min))
6577 (if (re-search-forward (concat "^" outline-regexp) nil t)
6578 (progn
6579 (goto-char (match-beginning 0))
6580 (funcall outline-level))))))
6581 (and level (hide-sublevels level))))
6583 (defun org-content (&optional arg)
6584 "Show all headlines in the buffer, like a table of contents.
6585 With numerical argument N, show content up to level N."
6586 (interactive "P")
6587 (save-excursion
6588 ;; Visit all headings and show their offspring
6589 (and (integerp arg) (org-overview))
6590 (goto-char (point-max))
6591 (catch 'exit
6592 (while (and (progn (condition-case nil
6593 (outline-previous-visible-heading 1)
6594 (error (goto-char (point-min))))
6596 (looking-at org-outline-regexp))
6597 (if (integerp arg)
6598 (show-children (1- arg))
6599 (show-branches))
6600 (if (bobp) (throw 'exit nil))))))
6603 (defun org-optimize-window-after-visibility-change (state)
6604 "Adjust the window after a change in outline visibility.
6605 This function is the default value of the hook `org-cycle-hook'."
6606 (when (get-buffer-window (current-buffer))
6607 (cond
6608 ((eq state 'content) nil)
6609 ((eq state 'all) nil)
6610 ((eq state 'folded) nil)
6611 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6612 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6614 (defun org-remove-empty-overlays-at (pos)
6615 "Remove outline overlays that do not contain non-white stuff."
6616 (mapc
6617 (lambda (o)
6618 (and (eq 'outline (overlay-get o 'invisible))
6619 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6620 (overlay-end o))))
6621 (delete-overlay o)))
6622 (overlays-at pos)))
6624 (defun org-clean-visibility-after-subtree-move ()
6625 "Fix visibility issues after moving a subtree."
6626 ;; First, find a reasonable region to look at:
6627 ;; Start two siblings above, end three below
6628 (let* ((beg (save-excursion
6629 (and (org-get-last-sibling)
6630 (org-get-last-sibling))
6631 (point)))
6632 (end (save-excursion
6633 (and (org-get-next-sibling)
6634 (org-get-next-sibling)
6635 (org-get-next-sibling))
6636 (if (org-at-heading-p)
6637 (point-at-eol)
6638 (point))))
6639 (level (looking-at "\\*+"))
6640 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6641 (save-excursion
6642 (save-restriction
6643 (narrow-to-region beg end)
6644 (when re
6645 ;; Properly fold already folded siblings
6646 (goto-char (point-min))
6647 (while (re-search-forward re nil t)
6648 (if (and (not (outline-invisible-p))
6649 (save-excursion
6650 (goto-char (point-at-eol)) (outline-invisible-p)))
6651 (hide-entry))))
6652 (org-cycle-show-empty-lines 'overview)
6653 (org-cycle-hide-drawers 'overview)))))
6655 (defun org-cycle-show-empty-lines (state)
6656 "Show empty lines above all visible headlines.
6657 The region to be covered depends on STATE when called through
6658 `org-cycle-hook'. Lisp program can use t for STATE to get the
6659 entire buffer covered. Note that an empty line is only shown if there
6660 are at least `org-cycle-separator-lines' empty lines before the headline."
6661 (when (not (= org-cycle-separator-lines 0))
6662 (save-excursion
6663 (let* ((n (abs org-cycle-separator-lines))
6664 (re (cond
6665 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6666 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6667 (t (let ((ns (number-to-string (- n 2))))
6668 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6669 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6670 beg end b e)
6671 (cond
6672 ((memq state '(overview contents t))
6673 (setq beg (point-min) end (point-max)))
6674 ((memq state '(children folded))
6675 (setq beg (point) end (progn (org-end-of-subtree t t)
6676 (beginning-of-line 2)
6677 (point)))))
6678 (when beg
6679 (goto-char beg)
6680 (while (re-search-forward re end t)
6681 (unless (get-char-property (match-end 1) 'invisible)
6682 (setq e (match-end 1))
6683 (if (< org-cycle-separator-lines 0)
6684 (setq b (save-excursion
6685 (goto-char (match-beginning 0))
6686 (org-back-over-empty-lines)
6687 (if (save-excursion
6688 (goto-char (max (point-min) (1- (point))))
6689 (org-at-heading-p))
6690 (1- (point))
6691 (point))))
6692 (setq b (match-beginning 1)))
6693 (outline-flag-region b e nil)))))))
6694 ;; Never hide empty lines at the end of the file.
6695 (save-excursion
6696 (goto-char (point-max))
6697 (outline-previous-heading)
6698 (outline-end-of-heading)
6699 (if (and (looking-at "[ \t\n]+")
6700 (= (match-end 0) (point-max)))
6701 (outline-flag-region (point) (match-end 0) nil))))
6703 (defun org-show-empty-lines-in-parent ()
6704 "Move to the parent and re-show empty lines before visible headlines."
6705 (save-excursion
6706 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6707 (org-cycle-show-empty-lines context))))
6709 (defun org-files-list ()
6710 "Return `org-agenda-files' list, plus all open org-mode files.
6711 This is useful for operations that need to scan all of a user's
6712 open and agenda-wise Org files."
6713 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6714 (dolist (buf (buffer-list))
6715 (with-current-buffer buf
6716 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6717 (let ((file (expand-file-name (buffer-file-name))))
6718 (unless (member file files)
6719 (push file files))))))
6720 files))
6722 (defsubst org-entry-beginning-position ()
6723 "Return the beginning position of the current entry."
6724 (save-excursion (outline-back-to-heading t) (point)))
6726 (defsubst org-entry-end-position ()
6727 "Return the end position of the current entry."
6728 (save-excursion (outline-next-heading) (point)))
6730 (defun org-cycle-hide-drawers (state)
6731 "Re-hide all drawers after a visibility state change."
6732 (when (and (derived-mode-p 'org-mode)
6733 (not (memq state '(overview folded contents))))
6734 (save-excursion
6735 (let* ((globalp (memq state '(contents all)))
6736 (beg (if globalp (point-min) (point)))
6737 (end (if globalp (point-max)
6738 (if (eq state 'children)
6739 (save-excursion (outline-next-heading) (point))
6740 (org-end-of-subtree t)))))
6741 (goto-char beg)
6742 (while (re-search-forward org-drawer-regexp end t)
6743 (org-flag-drawer t))))))
6745 (defun org-cycle-hide-inline-tasks (state)
6746 "Re-hide inline task when switching to 'contents visibility state."
6747 (when (and (eq state 'contents)
6748 (boundp 'org-inlinetask-min-level)
6749 org-inlinetask-min-level)
6750 (hide-sublevels (1- org-inlinetask-min-level))))
6752 (defun org-flag-drawer (flag)
6753 "When FLAG is non-nil, hide the drawer we are within.
6754 Otherwise make it visible."
6755 (save-excursion
6756 (beginning-of-line 1)
6757 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6758 (let ((b (match-end 0)))
6759 (if (re-search-forward
6760 "^[ \t]*:END:"
6761 (save-excursion (outline-next-heading) (point)) t)
6762 (outline-flag-region b (point-at-eol) flag)
6763 (error ":END: line missing at position %s" b))))))
6765 (defun org-subtree-end-visible-p ()
6766 "Is the end of the current subtree visible?"
6767 (pos-visible-in-window-p
6768 (save-excursion (org-end-of-subtree t) (point))))
6770 (defun org-first-headline-recenter (&optional N)
6771 "Move cursor to the first headline and recenter the headline.
6772 Optional argument N means put the headline into the Nth line of the window."
6773 (goto-char (point-min))
6774 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6775 (beginning-of-line)
6776 (recenter (prefix-numeric-value N))))
6778 ;;; Saving and restoring visibility
6780 (defun org-outline-overlay-data (&optional use-markers)
6781 "Return a list of the locations of all outline overlays.
6782 These are overlays with the `invisible' property value `outline'.
6783 The return value is a list of cons cells, with start and stop
6784 positions for each overlay.
6785 If USE-MARKERS is set, return the positions as markers."
6786 (let (beg end)
6787 (save-excursion
6788 (save-restriction
6789 (widen)
6790 (delq nil
6791 (mapcar (lambda (o)
6792 (when (eq (overlay-get o 'invisible) 'outline)
6793 (setq beg (overlay-start o)
6794 end (overlay-end o))
6795 (and beg end (> end beg)
6796 (if use-markers
6797 (cons (move-marker (make-marker) beg)
6798 (move-marker (make-marker) end))
6799 (cons beg end)))))
6800 (overlays-in (point-min) (point-max))))))))
6802 (defun org-set-outline-overlay-data (data)
6803 "Create visibility overlays for all positions in DATA.
6804 DATA should have been made by `org-outline-overlay-data'."
6805 (let (o)
6806 (save-excursion
6807 (save-restriction
6808 (widen)
6809 (show-all)
6810 (mapc (lambda (c)
6811 (outline-flag-region (car c) (cdr c) t))
6812 data)))))
6814 ;;; Folding of blocks
6816 (defvar org-hide-block-overlays nil
6817 "Overlays hiding blocks.")
6818 (make-variable-buffer-local 'org-hide-block-overlays)
6820 (defun org-block-map (function &optional start end)
6821 "Call FUNCTION at the head of all source blocks in the current buffer.
6822 Optional arguments START and END can be used to limit the range."
6823 (let ((start (or start (point-min)))
6824 (end (or end (point-max))))
6825 (save-excursion
6826 (goto-char start)
6827 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6828 (save-excursion
6829 (save-match-data
6830 (goto-char (match-beginning 0))
6831 (funcall function)))))))
6833 (defun org-hide-block-toggle-all ()
6834 "Toggle the visibility of all blocks in the current buffer."
6835 (org-block-map #'org-hide-block-toggle))
6837 (defun org-hide-block-all ()
6838 "Fold all blocks in the current buffer."
6839 (interactive)
6840 (org-show-block-all)
6841 (org-block-map #'org-hide-block-toggle-maybe))
6843 (defun org-show-block-all ()
6844 "Unfold all blocks in the current buffer."
6845 (interactive)
6846 (mapc 'delete-overlay org-hide-block-overlays)
6847 (setq org-hide-block-overlays nil))
6849 (defun org-hide-block-toggle-maybe ()
6850 "Toggle visibility of block at point."
6851 (interactive)
6852 (let ((case-fold-search t))
6853 (if (save-excursion
6854 (beginning-of-line 1)
6855 (looking-at org-block-regexp))
6856 (progn (org-hide-block-toggle)
6857 t) ;; to signal that we took action
6858 nil))) ;; to signal that we did not
6860 (defun org-hide-block-toggle (&optional force)
6861 "Toggle the visibility of the current block."
6862 (interactive)
6863 (save-excursion
6864 (beginning-of-line)
6865 (if (re-search-forward org-block-regexp nil t)
6866 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6867 (end (match-end 0)) ;; end of entire body
6869 (if (memq t (mapcar (lambda (overlay)
6870 (eq (overlay-get overlay 'invisible)
6871 'org-hide-block))
6872 (overlays-at start)))
6873 (if (or (not force) (eq force 'off))
6874 (mapc (lambda (ov)
6875 (when (member ov org-hide-block-overlays)
6876 (setq org-hide-block-overlays
6877 (delq ov org-hide-block-overlays)))
6878 (when (eq (overlay-get ov 'invisible)
6879 'org-hide-block)
6880 (delete-overlay ov)))
6881 (overlays-at start)))
6882 (setq ov (make-overlay start end))
6883 (overlay-put ov 'invisible 'org-hide-block)
6884 ;; make the block accessible to isearch
6885 (overlay-put
6886 ov 'isearch-open-invisible
6887 (lambda (ov)
6888 (when (member ov org-hide-block-overlays)
6889 (setq org-hide-block-overlays
6890 (delq ov org-hide-block-overlays)))
6891 (when (eq (overlay-get ov 'invisible)
6892 'org-hide-block)
6893 (delete-overlay ov))))
6894 (push ov org-hide-block-overlays)))
6895 (error "Not looking at a source block"))))
6897 ;; org-tab-after-check-for-cycling-hook
6898 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6899 ;; Remove overlays when changing major mode
6900 (add-hook 'org-mode-hook
6901 (lambda () (org-add-hook 'change-major-mode-hook
6902 'org-show-block-all 'append 'local)))
6904 ;;; Org-goto
6906 (defvar org-goto-window-configuration nil)
6907 (defvar org-goto-marker nil)
6908 (defvar org-goto-map
6909 (let ((map (make-sparse-keymap)))
6910 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6911 (while (setq cmd (pop cmds))
6912 (substitute-key-definition cmd cmd map global-map)))
6913 (suppress-keymap map)
6914 (org-defkey map "\C-m" 'org-goto-ret)
6915 (org-defkey map [(return)] 'org-goto-ret)
6916 (org-defkey map [(left)] 'org-goto-left)
6917 (org-defkey map [(right)] 'org-goto-right)
6918 (org-defkey map [(control ?g)] 'org-goto-quit)
6919 (org-defkey map "\C-i" 'org-cycle)
6920 (org-defkey map [(tab)] 'org-cycle)
6921 (org-defkey map [(down)] 'outline-next-visible-heading)
6922 (org-defkey map [(up)] 'outline-previous-visible-heading)
6923 (if org-goto-auto-isearch
6924 (if (fboundp 'define-key-after)
6925 (define-key-after map [t] 'org-goto-local-auto-isearch)
6926 nil)
6927 (org-defkey map "q" 'org-goto-quit)
6928 (org-defkey map "n" 'outline-next-visible-heading)
6929 (org-defkey map "p" 'outline-previous-visible-heading)
6930 (org-defkey map "f" 'outline-forward-same-level)
6931 (org-defkey map "b" 'outline-backward-same-level)
6932 (org-defkey map "u" 'outline-up-heading))
6933 (org-defkey map "/" 'org-occur)
6934 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6935 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6936 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6937 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6938 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6939 map))
6941 (defconst org-goto-help
6942 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6943 RET=jump to location [Q]uit and return to previous location
6944 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6946 (defvar org-goto-start-pos) ; dynamically scoped parameter
6948 ;; FIXME: Docstring does not mention both interfaces
6949 (defun org-goto (&optional alternative-interface)
6950 "Look up a different location in the current file, keeping current visibility.
6952 When you want look-up or go to a different location in a
6953 document, the fastest way is often to fold the entire buffer and
6954 then dive into the tree. This method has the disadvantage, that
6955 the previous location will be folded, which may not be what you
6956 want.
6958 This command works around this by showing a copy of the current
6959 buffer in an indirect buffer, in overview mode. You can dive
6960 into the tree in that copy, use org-occur and incremental search
6961 to find a location. When pressing RET or `Q', the command
6962 returns to the original buffer in which the visibility is still
6963 unchanged. After RET it will also jump to the location selected
6964 in the indirect buffer and expose the headline hierarchy above.
6966 With a prefix argument, use the alternative interface: e.g. if
6967 `org-goto-interface' is 'outline use 'outline-path-completion."
6968 (interactive "P")
6969 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6970 (org-refile-use-outline-path t)
6971 (org-refile-target-verify-function nil)
6972 (interface
6973 (if (not alternative-interface)
6974 org-goto-interface
6975 (if (eq org-goto-interface 'outline)
6976 'outline-path-completion
6977 'outline)))
6978 (org-goto-start-pos (point))
6979 (selected-point
6980 (if (eq interface 'outline)
6981 (car (org-get-location (current-buffer) org-goto-help))
6982 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6983 (org-refile-check-position pa)
6984 (nth 3 pa)))))
6985 (if selected-point
6986 (progn
6987 (org-mark-ring-push org-goto-start-pos)
6988 (goto-char selected-point)
6989 (if (or (outline-invisible-p) (org-invisible-p2))
6990 (org-show-context 'org-goto)))
6991 (message "Quit"))))
6993 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6994 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6995 (defvar org-goto-local-auto-isearch-map) ; defined below
6997 (defun org-get-location (buf help)
6998 "Let the user select a location in the Org-mode buffer BUF.
6999 This function uses a recursive edit. It returns the selected position
7000 or nil."
7001 (org-no-popups
7002 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7003 (isearch-hide-immediately nil)
7004 (isearch-search-fun-function
7005 (lambda () 'org-goto-local-search-headings))
7006 (org-goto-selected-point org-goto-exit-command))
7007 (save-excursion
7008 (save-window-excursion
7009 (delete-other-windows)
7010 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7011 (org-pop-to-buffer-same-window
7012 (condition-case nil
7013 (make-indirect-buffer (current-buffer) "*org-goto*")
7014 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7015 (with-output-to-temp-buffer "*Help*"
7016 (princ help))
7017 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7018 (setq buffer-read-only nil)
7019 (let ((org-startup-truncated t)
7020 (org-startup-folded nil)
7021 (org-startup-align-all-tables nil))
7022 (org-mode)
7023 (org-overview))
7024 (setq buffer-read-only t)
7025 (if (and (boundp 'org-goto-start-pos)
7026 (integer-or-marker-p org-goto-start-pos))
7027 (let ((org-show-hierarchy-above t)
7028 (org-show-siblings t)
7029 (org-show-following-heading t))
7030 (goto-char org-goto-start-pos)
7031 (and (outline-invisible-p) (org-show-context)))
7032 (goto-char (point-min)))
7033 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7034 (message "Select location and press RET")
7035 (use-local-map org-goto-map)
7036 (recursive-edit)
7038 (kill-buffer "*org-goto*")
7039 (cons org-goto-selected-point org-goto-exit-command))))
7041 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7042 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7043 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7044 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7046 (defun org-goto-local-search-headings (string bound noerror)
7047 "Search and make sure that any matches are in headlines."
7048 (catch 'return
7049 (while (if isearch-forward
7050 (search-forward string bound noerror)
7051 (search-backward string bound noerror))
7052 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7053 (and (member :headline context)
7054 (not (member :tags context))))
7055 (throw 'return (point))))))
7057 (defun org-goto-local-auto-isearch ()
7058 "Start isearch."
7059 (interactive)
7060 (goto-char (point-min))
7061 (let ((keys (this-command-keys)))
7062 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7063 (isearch-mode t)
7064 (isearch-process-search-char (string-to-char keys)))))
7066 (defun org-goto-ret (&optional arg)
7067 "Finish `org-goto' by going to the new location."
7068 (interactive "P")
7069 (setq org-goto-selected-point (point)
7070 org-goto-exit-command 'return)
7071 (throw 'exit nil))
7073 (defun org-goto-left ()
7074 "Finish `org-goto' by going to the new location."
7075 (interactive)
7076 (if (org-at-heading-p)
7077 (progn
7078 (beginning-of-line 1)
7079 (setq org-goto-selected-point (point)
7080 org-goto-exit-command 'left)
7081 (throw 'exit nil))
7082 (error "Not on a heading")))
7084 (defun org-goto-right ()
7085 "Finish `org-goto' by going to the new location."
7086 (interactive)
7087 (if (org-at-heading-p)
7088 (progn
7089 (setq org-goto-selected-point (point)
7090 org-goto-exit-command 'right)
7091 (throw 'exit nil))
7092 (error "Not on a heading")))
7094 (defun org-goto-quit ()
7095 "Finish `org-goto' without cursor motion."
7096 (interactive)
7097 (setq org-goto-selected-point nil)
7098 (setq org-goto-exit-command 'quit)
7099 (throw 'exit nil))
7101 ;;; Indirect buffer display of subtrees
7103 (defvar org-indirect-dedicated-frame nil
7104 "This is the frame being used for indirect tree display.")
7105 (defvar org-last-indirect-buffer nil)
7107 (defun org-tree-to-indirect-buffer (&optional arg)
7108 "Create indirect buffer and narrow it to current subtree.
7109 With a numerical prefix ARG, go up to this level and then take that tree.
7110 If ARG is negative, go up that many levels.
7112 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7113 indirect buffer previously made with this command, to avoid proliferation of
7114 indirect buffers. However, when you call the command with a \
7115 \\[universal-argument] prefix, or
7116 when `org-indirect-buffer-display' is `new-frame', the last buffer
7117 is kept so that you can work with several indirect buffers at the same time.
7118 If `org-indirect-buffer-display' is `dedicated-frame', the \
7119 \\[universal-argument] prefix also
7120 requests that a new frame be made for the new buffer, so that the dedicated
7121 frame is not changed."
7122 (interactive "P")
7123 (let ((cbuf (current-buffer))
7124 (cwin (selected-window))
7125 (pos (point))
7126 beg end level heading ibuf)
7127 (save-excursion
7128 (org-back-to-heading t)
7129 (when (numberp arg)
7130 (setq level (org-outline-level))
7131 (if (< arg 0) (setq arg (+ level arg)))
7132 (while (> (setq level (org-outline-level)) arg)
7133 (org-up-heading-safe)))
7134 (setq beg (point)
7135 heading (org-get-heading))
7136 (org-end-of-subtree t t)
7137 (if (org-at-heading-p) (backward-char 1))
7138 (setq end (point)))
7139 (if (and (buffer-live-p org-last-indirect-buffer)
7140 (not (eq org-indirect-buffer-display 'new-frame))
7141 (not arg))
7142 (kill-buffer org-last-indirect-buffer))
7143 (setq ibuf (org-get-indirect-buffer cbuf)
7144 org-last-indirect-buffer ibuf)
7145 (cond
7146 ((or (eq org-indirect-buffer-display 'new-frame)
7147 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7148 (select-frame (make-frame))
7149 (delete-other-windows)
7150 (org-pop-to-buffer-same-window ibuf)
7151 (org-set-frame-title heading))
7152 ((eq org-indirect-buffer-display 'dedicated-frame)
7153 (raise-frame
7154 (select-frame (or (and org-indirect-dedicated-frame
7155 (frame-live-p org-indirect-dedicated-frame)
7156 org-indirect-dedicated-frame)
7157 (setq org-indirect-dedicated-frame (make-frame)))))
7158 (delete-other-windows)
7159 (org-pop-to-buffer-same-window ibuf)
7160 (org-set-frame-title (concat "Indirect: " heading)))
7161 ((eq org-indirect-buffer-display 'current-window)
7162 (org-pop-to-buffer-same-window ibuf))
7163 ((eq org-indirect-buffer-display 'other-window)
7164 (pop-to-buffer ibuf))
7165 (t (error "Invalid value")))
7166 (if (featurep 'xemacs)
7167 (save-excursion (org-mode) (turn-on-font-lock)))
7168 (narrow-to-region beg end)
7169 (show-all)
7170 (goto-char pos)
7171 (run-hook-with-args 'org-cycle-hook 'all)
7172 (and (window-live-p cwin) (select-window cwin))))
7174 (defun org-get-indirect-buffer (&optional buffer)
7175 (setq buffer (or buffer (current-buffer)))
7176 (let ((n 1) (base (buffer-name buffer)) bname)
7177 (while (buffer-live-p
7178 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7179 (setq n (1+ n)))
7180 (condition-case nil
7181 (make-indirect-buffer buffer bname 'clone)
7182 (error (make-indirect-buffer buffer bname)))))
7184 (defun org-set-frame-title (title)
7185 "Set the title of the current frame to the string TITLE."
7186 ;; FIXME: how to name a single frame in XEmacs???
7187 (unless (featurep 'xemacs)
7188 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7190 ;;;; Structure editing
7192 ;;; Inserting headlines
7194 (defun org-previous-line-empty-p ()
7195 (save-excursion
7196 (and (not (bobp))
7197 (or (beginning-of-line 0) t)
7198 (save-match-data
7199 (looking-at "[ \t]*$")))))
7201 (defun org-insert-heading (&optional force-heading invisible-ok)
7202 "Insert a new heading or item with same depth at point.
7203 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7204 If point is at the beginning of a headline, insert a sibling before the
7205 current headline. If point is not at the beginning, split the line,
7206 create the new headline with the text in the current line after point
7207 \(but see also the variable `org-M-RET-may-split-line').
7209 With a double prefix arg, force the heading to be inserted at the
7210 end of the parent subtree.
7212 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7213 This is important for non-interactive uses of the command."
7214 (interactive "P")
7215 (if (or (= (buffer-size) 0)
7216 (and (not (save-excursion
7217 (and (ignore-errors (org-back-to-heading invisible-ok))
7218 (org-at-heading-p))))
7219 (or force-heading (not (org-in-item-p)))))
7220 (progn
7221 (insert "\n* ")
7222 (run-hooks 'org-insert-heading-hook))
7223 (when (or force-heading (not (org-insert-item)))
7224 (let* ((empty-line-p nil)
7225 (level nil)
7226 (on-heading (org-at-heading-p))
7227 (head (save-excursion
7228 (condition-case nil
7229 (progn
7230 (org-back-to-heading invisible-ok)
7231 (when (and (not on-heading)
7232 (featurep 'org-inlinetask)
7233 (integerp org-inlinetask-min-level)
7234 (>= (length (match-string 0))
7235 org-inlinetask-min-level))
7236 ;; Find a heading level before the inline task
7237 (while (and (setq level (org-up-heading-safe))
7238 (>= level org-inlinetask-min-level)))
7239 (if (org-at-heading-p)
7240 (org-back-to-heading invisible-ok)
7241 (error "This should not happen")))
7242 (setq empty-line-p (org-previous-line-empty-p))
7243 (match-string 0))
7244 (error "*"))))
7245 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7246 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7247 pos hide-previous previous-pos)
7248 (cond
7249 ((and (org-at-heading-p) (bolp)
7250 (or (bobp)
7251 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7252 ;; insert before the current line
7253 (open-line (if blank 2 1)))
7254 ((and (bolp)
7255 (not org-insert-heading-respect-content)
7256 (or (bobp)
7257 (save-excursion
7258 (backward-char 1) (not (outline-invisible-p)))))
7259 ;; insert right here
7260 nil)
7262 ;; somewhere in the line
7263 (save-excursion
7264 (setq previous-pos (point-at-bol))
7265 (end-of-line)
7266 (setq hide-previous (outline-invisible-p)))
7267 (and org-insert-heading-respect-content (org-show-subtree))
7268 (let ((split
7269 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7270 (save-excursion
7271 (let ((p (point)))
7272 (goto-char (point-at-bol))
7273 (and (looking-at org-complex-heading-regexp)
7274 (match-beginning 4)
7275 (> p (match-beginning 4)))))))
7276 tags pos)
7277 (cond
7278 (org-insert-heading-respect-content
7279 (if (not (equal force-heading '(16)))
7280 (org-end-of-subtree nil t)
7281 (org-up-heading-safe)
7282 (org-end-of-subtree nil t))
7283 (when (featurep 'org-inlinetask)
7284 (while (and (not (eobp))
7285 (looking-at "\\(\\*+\\)[ \t]+")
7286 (>= (length (match-string 1))
7287 org-inlinetask-min-level))
7288 (org-end-of-subtree nil t)))
7289 (or (bolp) (newline))
7290 (or (org-previous-line-empty-p)
7291 (and blank (newline)))
7292 (open-line 1))
7293 ((org-at-heading-p)
7294 (when hide-previous
7295 (show-children)
7296 (org-show-entry))
7297 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7298 (setq tags (and (match-end 2) (match-string 2)))
7299 (and (match-end 1)
7300 (delete-region (match-beginning 1) (match-end 1)))
7301 (setq pos (point-at-bol))
7302 (or split (end-of-line 1))
7303 (delete-horizontal-space)
7304 (if (string-match "\\`\\*+\\'"
7305 (buffer-substring (point-at-bol) (point)))
7306 (insert " "))
7307 (newline (if blank 2 1))
7308 (when tags
7309 (save-excursion
7310 (goto-char pos)
7311 (end-of-line 1)
7312 (insert " " tags)
7313 (org-set-tags nil 'align))))
7315 (or split (end-of-line 1))
7316 (newline (if blank 2 1)))))))
7317 (insert head) (just-one-space)
7318 (setq pos (point))
7319 (end-of-line 1)
7320 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7321 (when (and org-insert-heading-respect-content hide-previous)
7322 (save-excursion
7323 (goto-char previous-pos)
7324 (hide-subtree)))
7325 (run-hooks 'org-insert-heading-hook)))))
7327 (defun org-get-heading (&optional no-tags no-todo)
7328 "Return the heading of the current entry, without the stars.
7329 When NO-TAGS is non-nil, don't include tags.
7330 When NO-TODO is non-nil, don't include TODO keywords."
7331 (save-excursion
7332 (org-back-to-heading t)
7333 (cond
7334 ((and no-tags no-todo)
7335 (looking-at org-complex-heading-regexp)
7336 (match-string 4))
7337 (no-tags
7338 (looking-at (concat org-outline-regexp
7339 "\\(.*?\\)"
7340 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7341 (match-string 1))
7342 (no-todo
7343 (looking-at org-todo-line-regexp)
7344 (match-string 3))
7345 (t (looking-at org-heading-regexp)
7346 (match-string 2)))))
7348 (defun org-heading-components ()
7349 "Return the components of the current heading.
7350 This is a list with the following elements:
7351 - the level as an integer
7352 - the reduced level, different if `org-odd-levels-only' is set.
7353 - the TODO keyword, or nil
7354 - the priority character, like ?A, or nil if no priority is given
7355 - the headline text itself, or the tags string if no headline text
7356 - the tags string, or nil."
7357 (save-excursion
7358 (org-back-to-heading t)
7359 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7360 (list (length (match-string 1))
7361 (org-reduced-level (length (match-string 1)))
7362 (org-match-string-no-properties 2)
7363 (and (match-end 3) (aref (match-string 3) 2))
7364 (org-match-string-no-properties 4)
7365 (org-match-string-no-properties 5)))))
7367 (defun org-get-entry ()
7368 "Get the entry text, after heading, entire subtree."
7369 (save-excursion
7370 (org-back-to-heading t)
7371 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7373 (defun org-insert-heading-after-current ()
7374 "Insert a new heading with same level as current, after current subtree."
7375 (interactive)
7376 (org-back-to-heading)
7377 (org-insert-heading)
7378 (org-move-subtree-down)
7379 (end-of-line 1))
7381 (defun org-insert-heading-respect-content ()
7382 (interactive)
7383 (let ((org-insert-heading-respect-content t))
7384 (org-insert-heading t)))
7386 (defun org-insert-todo-heading-respect-content (&optional force-state)
7387 (interactive "P")
7388 (let ((org-insert-heading-respect-content t))
7389 (org-insert-todo-heading force-state t)))
7391 (defun org-insert-todo-heading (arg &optional force-heading)
7392 "Insert a new heading with the same level and TODO state as current heading.
7393 If the heading has no TODO state, or if the state is DONE, use the first
7394 state (TODO by default). Also one prefix arg, force first state. With two
7395 prefix args, force inserting at the end of the parent subtree."
7396 (interactive "P")
7397 (when (or force-heading (not (org-insert-item 'checkbox)))
7398 (org-insert-heading (or (and (equal arg '(16)) '(16))
7399 force-heading))
7400 (save-excursion
7401 (org-back-to-heading)
7402 (outline-previous-heading)
7403 (looking-at org-todo-line-regexp))
7404 (let*
7405 ((new-mark-x
7406 (if (or arg
7407 (not (match-beginning 2))
7408 (member (match-string 2) org-done-keywords))
7409 (car org-todo-keywords-1)
7410 (match-string 2)))
7411 (new-mark
7413 (run-hook-with-args-until-success
7414 'org-todo-get-default-hook new-mark-x nil)
7415 new-mark-x)))
7416 (beginning-of-line 1)
7417 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7418 (if org-treat-insert-todo-heading-as-state-change
7419 (org-todo new-mark)
7420 (insert new-mark " "))))
7421 (when org-provide-todo-statistics
7422 (org-update-parent-todo-statistics))))
7424 (defun org-insert-subheading (arg)
7425 "Insert a new subheading and demote it.
7426 Works for outline headings and for plain lists alike."
7427 (interactive "P")
7428 (org-insert-heading arg)
7429 (cond
7430 ((org-at-heading-p) (org-do-demote))
7431 ((org-at-item-p) (org-indent-item))))
7433 (defun org-insert-todo-subheading (arg)
7434 "Insert a new subheading with TODO keyword or checkbox and demote it.
7435 Works for outline headings and for plain lists alike."
7436 (interactive "P")
7437 (org-insert-todo-heading arg)
7438 (cond
7439 ((org-at-heading-p) (org-do-demote))
7440 ((org-at-item-p) (org-indent-item))))
7442 ;;; Promotion and Demotion
7444 (defvar org-after-demote-entry-hook nil
7445 "Hook run after an entry has been demoted.
7446 The cursor will be at the beginning of the entry.
7447 When a subtree is being demoted, the hook will be called for each node.")
7449 (defvar org-after-promote-entry-hook nil
7450 "Hook run after an entry has been promoted.
7451 The cursor will be at the beginning of the entry.
7452 When a subtree is being promoted, the hook will be called for each node.")
7454 (defun org-promote-subtree ()
7455 "Promote the entire subtree.
7456 See also `org-promote'."
7457 (interactive)
7458 (save-excursion
7459 (org-with-limited-levels (org-map-tree 'org-promote)))
7460 (org-fix-position-after-promote))
7462 (defun org-demote-subtree ()
7463 "Demote the entire subtree. See `org-demote'.
7464 See also `org-promote'."
7465 (interactive)
7466 (save-excursion
7467 (org-with-limited-levels (org-map-tree 'org-demote)))
7468 (org-fix-position-after-promote))
7471 (defun org-do-promote ()
7472 "Promote the current heading higher up the tree.
7473 If the region is active in `transient-mark-mode', promote all headings
7474 in the region."
7475 (interactive)
7476 (save-excursion
7477 (if (org-region-active-p)
7478 (org-map-region 'org-promote (region-beginning) (region-end))
7479 (org-promote)))
7480 (org-fix-position-after-promote))
7482 (defun org-do-demote ()
7483 "Demote the current heading lower down the tree.
7484 If the region is active in `transient-mark-mode', demote all headings
7485 in the region."
7486 (interactive)
7487 (save-excursion
7488 (if (org-region-active-p)
7489 (org-map-region 'org-demote (region-beginning) (region-end))
7490 (org-demote)))
7491 (org-fix-position-after-promote))
7493 (defun org-fix-position-after-promote ()
7494 "Make sure that after pro/demotion cursor position is right."
7495 (let ((pos (point)))
7496 (when (save-excursion
7497 (beginning-of-line 1)
7498 (looking-at org-todo-line-regexp)
7499 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7500 (cond ((eobp) (insert " "))
7501 ((eolp) (insert " "))
7502 ((equal (char-after) ?\ ) (forward-char 1))))))
7504 (defun org-current-level ()
7505 "Return the level of the current entry, or nil if before the first headline.
7506 The level is the number of stars at the beginning of the headline."
7507 (save-excursion
7508 (org-with-limited-levels
7509 (if (ignore-errors (org-back-to-heading t))
7510 (funcall outline-level)))))
7512 (defun org-get-previous-line-level ()
7513 "Return the outline depth of the last headline before the current line.
7514 Returns 0 for the first headline in the buffer, and nil if before the
7515 first headline."
7516 (let ((current-level (org-current-level))
7517 (prev-level (when (> (line-number-at-pos) 1)
7518 (save-excursion
7519 (beginning-of-line 0)
7520 (org-current-level)))))
7521 (cond ((null current-level) nil) ; Before first headline
7522 ((null prev-level) 0) ; At first headline
7523 (prev-level))))
7525 (defun org-reduced-level (l)
7526 "Compute the effective level of a heading.
7527 This takes into account the setting of `org-odd-levels-only'."
7528 (cond
7529 ((zerop l) 0)
7530 (org-odd-levels-only (1+ (floor (/ l 2))))
7531 (t l)))
7533 (defun org-level-increment ()
7534 "Return the number of stars that will be added or removed at a
7535 time to headlines when structure editing, based on the value of
7536 `org-odd-levels-only'."
7537 (if org-odd-levels-only 2 1))
7539 (defun org-get-valid-level (level &optional change)
7540 "Rectify a level change under the influence of `org-odd-levels-only'
7541 LEVEL is a current level, CHANGE is by how much the level should be
7542 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7543 even level numbers will become the next higher odd number."
7544 (if org-odd-levels-only
7545 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7546 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7547 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7548 (max 1 (+ level (or change 0)))))
7550 (if (boundp 'define-obsolete-function-alias)
7551 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7552 (define-obsolete-function-alias 'org-get-legal-level
7553 'org-get-valid-level)
7554 (define-obsolete-function-alias 'org-get-legal-level
7555 'org-get-valid-level "23.1")))
7557 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7558 ;; ̀org-with-limited-levels'
7559 (defun org-promote ()
7560 "Promote the current heading higher up the tree.
7561 If the region is active in `transient-mark-mode', promote all headings
7562 in the region."
7563 (org-back-to-heading t)
7564 (let* ((level (save-match-data (funcall outline-level)))
7565 (after-change-functions (remove 'flyspell-after-change-function
7566 after-change-functions))
7567 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7568 (diff (abs (- level (length up-head) -1))))
7569 (cond ((and (= level 1) org-called-with-limited-levels
7570 org-allow-promoting-top-level-subtree)
7571 (replace-match "# " nil t))
7572 ((= level 1)
7573 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7574 (t (replace-match up-head nil t)))
7575 ;; Fixup tag positioning
7576 (unless (= level 1)
7577 (and org-auto-align-tags (org-set-tags nil t))
7578 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7579 (run-hooks 'org-after-promote-entry-hook)))
7581 (defun org-demote ()
7582 "Demote the current heading lower down the tree.
7583 If the region is active in `transient-mark-mode', demote all headings
7584 in the region."
7585 (org-back-to-heading t)
7586 (let* ((level (save-match-data (funcall outline-level)))
7587 (after-change-functions (remove 'flyspell-after-change-function
7588 after-change-functions))
7589 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7590 (diff (abs (- level (length down-head) -1))))
7591 (replace-match down-head nil t)
7592 ;; Fixup tag positioning
7593 (and org-auto-align-tags (org-set-tags nil t))
7594 (if org-adapt-indentation (org-fixup-indentation diff))
7595 (run-hooks 'org-after-demote-entry-hook)))
7597 (defun org-cycle-level ()
7598 "Cycle the level of an empty headline through possible states.
7599 This goes first to child, then to parent, level, then up the hierarchy.
7600 After top level, it switches back to sibling level."
7601 (interactive)
7602 (let ((org-adapt-indentation nil))
7603 (when (org-point-at-end-of-empty-headline)
7604 (setq this-command 'org-cycle-level) ; Only needed for caching
7605 (let ((cur-level (org-current-level))
7606 (prev-level (org-get-previous-line-level)))
7607 (cond
7608 ;; If first headline in file, promote to top-level.
7609 ((= prev-level 0)
7610 (loop repeat (/ (- cur-level 1) (org-level-increment))
7611 do (org-do-promote)))
7612 ;; If same level as prev, demote one.
7613 ((= prev-level cur-level)
7614 (org-do-demote))
7615 ;; If parent is top-level, promote to top level if not already.
7616 ((= prev-level 1)
7617 (loop repeat (/ (- cur-level 1) (org-level-increment))
7618 do (org-do-promote)))
7619 ;; If top-level, return to prev-level.
7620 ((= cur-level 1)
7621 (loop repeat (/ (- prev-level 1) (org-level-increment))
7622 do (org-do-demote)))
7623 ;; If less than prev-level, promote one.
7624 ((< cur-level prev-level)
7625 (org-do-promote))
7626 ;; If deeper than prev-level, promote until higher than
7627 ;; prev-level.
7628 ((> cur-level prev-level)
7629 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7630 do (org-do-promote))))
7631 t))))
7633 (defun org-map-tree (fun)
7634 "Call FUN for every heading underneath the current one."
7635 (org-back-to-heading)
7636 (let ((level (funcall outline-level)))
7637 (save-excursion
7638 (funcall fun)
7639 (while (and (progn
7640 (outline-next-heading)
7641 (> (funcall outline-level) level))
7642 (not (eobp)))
7643 (funcall fun)))))
7645 (defun org-map-region (fun beg end)
7646 "Call FUN for every heading between BEG and END."
7647 (let ((org-ignore-region t))
7648 (save-excursion
7649 (setq end (copy-marker end))
7650 (goto-char beg)
7651 (if (and (re-search-forward org-outline-regexp-bol nil t)
7652 (< (point) end))
7653 (funcall fun))
7654 (while (and (progn
7655 (outline-next-heading)
7656 (< (point) end))
7657 (not (eobp)))
7658 (funcall fun)))))
7660 (defvar org-property-end-re) ; silence byte-compiler
7661 (defun org-fixup-indentation (diff)
7662 "Change the indentation in the current entry by DIFF.
7663 However, if any line in the current entry has no indentation, or if it
7664 would end up with no indentation after the change, nothing at all is done."
7665 (save-excursion
7666 (let ((end (save-excursion (outline-next-heading)
7667 (point-marker)))
7668 (prohibit (if (> diff 0)
7669 "^\\S-"
7670 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7671 col)
7672 (unless (save-excursion (end-of-line 1)
7673 (re-search-forward prohibit end t))
7674 (while (and (< (point) end)
7675 (re-search-forward "^[ \t]+" end t))
7676 (goto-char (match-end 0))
7677 (setq col (current-column))
7678 (if (< diff 0) (replace-match ""))
7679 (org-indent-to-column (+ diff col))))
7680 (move-marker end nil))))
7682 (defun org-convert-to-odd-levels ()
7683 "Convert an org-mode file with all levels allowed to one with odd levels.
7684 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7685 level 5 etc."
7686 (interactive)
7687 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7688 (let ((outline-level 'org-outline-level)
7689 (org-odd-levels-only nil) n)
7690 (save-excursion
7691 (goto-char (point-min))
7692 (while (re-search-forward "^\\*\\*+ " nil t)
7693 (setq n (- (length (match-string 0)) 2))
7694 (while (>= (setq n (1- n)) 0)
7695 (org-demote))
7696 (end-of-line 1))))))
7698 (defun org-convert-to-oddeven-levels ()
7699 "Convert an org-mode file with only odd levels to one with odd/even levels.
7700 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7701 file contains a section with an even level, conversion would
7702 destroy the structure of the file. An error is signaled in this
7703 case."
7704 (interactive)
7705 (goto-char (point-min))
7706 ;; First check if there are no even levels
7707 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7708 (org-show-context t)
7709 (error "Not all levels are odd in this file. Conversion not possible"))
7710 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7711 (let ((outline-regexp org-outline-regexp)
7712 (outline-level 'org-outline-level)
7713 (org-odd-levels-only nil) n)
7714 (save-excursion
7715 (goto-char (point-min))
7716 (while (re-search-forward "^\\*\\*+ " nil t)
7717 (setq n (/ (1- (length (match-string 0))) 2))
7718 (while (>= (setq n (1- n)) 0)
7719 (org-promote))
7720 (end-of-line 1))))))
7722 (defun org-tr-level (n)
7723 "Make N odd if required."
7724 (if org-odd-levels-only (1+ (/ n 2)) n))
7726 ;;; Vertical tree motion, cutting and pasting of subtrees
7728 (defun org-move-subtree-up (&optional arg)
7729 "Move the current subtree up past ARG headlines of the same level."
7730 (interactive "p")
7731 (org-move-subtree-down (- (prefix-numeric-value arg))))
7733 (defun org-move-subtree-down (&optional arg)
7734 "Move the current subtree down past ARG headlines of the same level."
7735 (interactive "p")
7736 (setq arg (prefix-numeric-value arg))
7737 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7738 'org-get-last-sibling))
7739 (ins-point (make-marker))
7740 (cnt (abs arg))
7741 (col (current-column))
7742 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7743 ;; Select the tree
7744 (org-back-to-heading)
7745 (setq beg0 (point))
7746 (save-excursion
7747 (setq ne-beg (org-back-over-empty-lines))
7748 (setq beg (point)))
7749 (save-match-data
7750 (save-excursion (outline-end-of-heading)
7751 (setq folded (outline-invisible-p)))
7752 (outline-end-of-subtree))
7753 (outline-next-heading)
7754 (setq ne-end (org-back-over-empty-lines))
7755 (setq end (point))
7756 (goto-char beg0)
7757 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7758 ;; include less whitespace
7759 (save-excursion
7760 (goto-char beg)
7761 (forward-line (- ne-beg ne-end))
7762 (setq beg (point))))
7763 ;; Find insertion point, with error handling
7764 (while (> cnt 0)
7765 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7766 (progn (goto-char beg0)
7767 (error "Cannot move past superior level or buffer limit")))
7768 (setq cnt (1- cnt)))
7769 (if (> arg 0)
7770 ;; Moving forward - still need to move over subtree
7771 (progn (org-end-of-subtree t t)
7772 (save-excursion
7773 (org-back-over-empty-lines)
7774 (or (bolp) (newline)))))
7775 (setq ne-ins (org-back-over-empty-lines))
7776 (move-marker ins-point (point))
7777 (setq txt (buffer-substring beg end))
7778 (org-save-markers-in-region beg end)
7779 (delete-region beg end)
7780 (org-remove-empty-overlays-at beg)
7781 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7782 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7783 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7784 (let ((bbb (point)))
7785 (insert-before-markers txt)
7786 (org-reinstall-markers-in-region bbb)
7787 (move-marker ins-point bbb))
7788 (or (bolp) (insert "\n"))
7789 (setq ins-end (point))
7790 (goto-char ins-point)
7791 (org-skip-whitespace)
7792 (when (and (< arg 0)
7793 (org-first-sibling-p)
7794 (> ne-ins ne-beg))
7795 ;; Move whitespace back to beginning
7796 (save-excursion
7797 (goto-char ins-end)
7798 (let ((kill-whole-line t))
7799 (kill-line (- ne-ins ne-beg)) (point)))
7800 (insert (make-string (- ne-ins ne-beg) ?\n)))
7801 (move-marker ins-point nil)
7802 (if folded
7803 (hide-subtree)
7804 (org-show-entry)
7805 (show-children)
7806 (org-cycle-hide-drawers 'children))
7807 (org-clean-visibility-after-subtree-move)
7808 ;; move back to the initial column we were at
7809 (move-to-column col)))
7811 (defvar org-subtree-clip ""
7812 "Clipboard for cut and paste of subtrees.
7813 This is actually only a copy of the kill, because we use the normal kill
7814 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7816 (defvar org-subtree-clip-folded nil
7817 "Was the last copied subtree folded?
7818 This is used to fold the tree back after pasting.")
7820 (defun org-cut-subtree (&optional n)
7821 "Cut the current subtree into the clipboard.
7822 With prefix arg N, cut this many sequential subtrees.
7823 This is a short-hand for marking the subtree and then cutting it."
7824 (interactive "p")
7825 (org-copy-subtree n 'cut))
7827 (defun org-copy-subtree (&optional n cut force-store-markers)
7828 "Cut the current subtree into the clipboard.
7829 With prefix arg N, cut this many sequential subtrees.
7830 This is a short-hand for marking the subtree and then copying it.
7831 If CUT is non-nil, actually cut the subtree.
7832 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7833 of some markers in the region, even if CUT is non-nil. This is
7834 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7835 (interactive "p")
7836 (let (beg end folded (beg0 (point)))
7837 (if (org-called-interactively-p 'any)
7838 (org-back-to-heading nil) ; take what looks like a subtree
7839 (org-back-to-heading t)) ; take what is really there
7840 (setq beg (point))
7841 (skip-chars-forward " \t\r\n")
7842 (save-match-data
7843 (save-excursion (outline-end-of-heading)
7844 (setq folded (outline-invisible-p)))
7845 (condition-case nil
7846 (org-forward-heading-same-level (1- n) t)
7847 (error nil))
7848 (org-end-of-subtree t t))
7849 (setq end (point))
7850 (goto-char beg0)
7851 (when (> end beg)
7852 (setq org-subtree-clip-folded folded)
7853 (when (or cut force-store-markers)
7854 (org-save-markers-in-region beg end))
7855 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7856 (setq org-subtree-clip (current-kill 0))
7857 (message "%s: Subtree(s) with %d characters"
7858 (if cut "Cut" "Copied")
7859 (length org-subtree-clip)))))
7861 (defun org-paste-subtree (&optional level tree for-yank)
7862 "Paste the clipboard as a subtree, with modification of headline level.
7863 The entire subtree is promoted or demoted in order to match a new headline
7864 level.
7866 If the cursor is at the beginning of a headline, the same level as
7867 that headline is used to paste the tree
7869 If not, the new level is derived from the *visible* headings
7870 before and after the insertion point, and taken to be the inferior headline
7871 level of the two. So if the previous visible heading is level 3 and the
7872 next is level 4 (or vice versa), level 4 will be used for insertion.
7873 This makes sure that the subtree remains an independent subtree and does
7874 not swallow low level entries.
7876 You can also force a different level, either by using a numeric prefix
7877 argument, or by inserting the heading marker by hand. For example, if the
7878 cursor is after \"*****\", then the tree will be shifted to level 5.
7880 If optional TREE is given, use this text instead of the kill ring.
7882 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7883 move back over whitespace before inserting, and move point to the end of
7884 the inserted text when done."
7885 (interactive "P")
7886 (setq tree (or tree (and kill-ring (current-kill 0))))
7887 (unless (org-kill-is-subtree-p tree)
7888 (error "%s"
7889 (substitute-command-keys
7890 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7891 (org-with-limited-levels
7892 (let* ((visp (not (outline-invisible-p)))
7893 (txt tree)
7894 (^re_ "\\(\\*+\\)[ \t]*")
7895 (old-level (if (string-match org-outline-regexp-bol txt)
7896 (- (match-end 0) (match-beginning 0) 1)
7897 -1))
7898 (force-level (cond (level (prefix-numeric-value level))
7899 ((and (looking-at "[ \t]*$")
7900 (string-match
7901 "^\\*+$" (buffer-substring
7902 (point-at-bol) (point))))
7903 (- (match-end 1) (match-beginning 1)))
7904 ((and (bolp)
7905 (looking-at org-outline-regexp))
7906 (- (match-end 0) (point) 1))))
7907 (previous-level (save-excursion
7908 (condition-case nil
7909 (progn
7910 (outline-previous-visible-heading 1)
7911 (if (looking-at ^re_)
7912 (- (match-end 0) (match-beginning 0) 1)
7914 (error 1))))
7915 (next-level (save-excursion
7916 (condition-case nil
7917 (progn
7918 (or (looking-at org-outline-regexp)
7919 (outline-next-visible-heading 1))
7920 (if (looking-at ^re_)
7921 (- (match-end 0) (match-beginning 0) 1)
7923 (error 1))))
7924 (new-level (or force-level (max previous-level next-level)))
7925 (shift (if (or (= old-level -1)
7926 (= new-level -1)
7927 (= old-level new-level))
7929 (- new-level old-level)))
7930 (delta (if (> shift 0) -1 1))
7931 (func (if (> shift 0) 'org-demote 'org-promote))
7932 (org-odd-levels-only nil)
7933 beg end newend)
7934 ;; Remove the forced level indicator
7935 (if force-level
7936 (delete-region (point-at-bol) (point)))
7937 ;; Paste
7938 (beginning-of-line (if (bolp) 1 2))
7939 (setq beg (point))
7940 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7941 (insert-before-markers txt)
7942 (unless (string-match "\n\\'" txt) (insert "\n"))
7943 (setq newend (point))
7944 (org-reinstall-markers-in-region beg)
7945 (setq end (point))
7946 (goto-char beg)
7947 (skip-chars-forward " \t\n\r")
7948 (setq beg (point))
7949 (if (and (outline-invisible-p) visp)
7950 (save-excursion (outline-show-heading)))
7951 ;; Shift if necessary
7952 (unless (= shift 0)
7953 (save-restriction
7954 (narrow-to-region beg end)
7955 (while (not (= shift 0))
7956 (org-map-region func (point-min) (point-max))
7957 (setq shift (+ delta shift)))
7958 (goto-char (point-min))
7959 (setq newend (point-max))))
7960 (when (or (org-called-interactively-p 'interactive) for-yank)
7961 (message "Clipboard pasted as level %d subtree" new-level))
7962 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7963 kill-ring
7964 (eq org-subtree-clip (current-kill 0))
7965 org-subtree-clip-folded)
7966 ;; The tree was folded before it was killed/copied
7967 (hide-subtree))
7968 (and for-yank (goto-char newend)))))
7970 (defun org-kill-is-subtree-p (&optional txt)
7971 "Check if the current kill is an outline subtree, or a set of trees.
7972 Returns nil if kill does not start with a headline, or if the first
7973 headline level is not the largest headline level in the tree.
7974 So this will actually accept several entries of equal levels as well,
7975 which is OK for `org-paste-subtree'.
7976 If optional TXT is given, check this string instead of the current kill."
7977 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7978 (re (org-get-limited-outline-regexp))
7979 (^re (concat "^" re))
7980 (start-level (and kill
7981 (string-match
7982 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7983 kill)
7984 (- (match-end 2) (match-beginning 2) 1)))
7985 (start (1+ (or (match-beginning 2) -1))))
7986 (if (not start-level)
7987 (progn
7988 nil) ;; does not even start with a heading
7989 (catch 'exit
7990 (while (setq start (string-match ^re kill (1+ start)))
7991 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7992 (throw 'exit nil)))
7993 t))))
7995 (defvar org-markers-to-move nil
7996 "Markers that should be moved with a cut-and-paste operation.
7997 Those markers are stored together with their positions relative to
7998 the start of the region.")
8000 (defun org-save-markers-in-region (beg end)
8001 "Check markers in region.
8002 If these markers are between BEG and END, record their position relative
8003 to BEG, so that after moving the block of text, we can put the markers back
8004 into place.
8005 This function gets called just before an entry or tree gets cut from the
8006 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8007 called immediately, to move the markers with the entries."
8008 (setq org-markers-to-move nil)
8009 (when (featurep 'org-clock)
8010 (org-clock-save-markers-for-cut-and-paste beg end))
8011 (when (featurep 'org-agenda)
8012 (org-agenda-save-markers-for-cut-and-paste beg end)))
8014 (defun org-check-and-save-marker (marker beg end)
8015 "Check if MARKER is between BEG and END.
8016 If yes, remember the marker and the distance to BEG."
8017 (when (and (marker-buffer marker)
8018 (equal (marker-buffer marker) (current-buffer)))
8019 (if (and (>= marker beg) (< marker end))
8020 (push (cons marker (- marker beg)) org-markers-to-move))))
8022 (defun org-reinstall-markers-in-region (beg)
8023 "Move all remembered markers to their position relative to BEG."
8024 (mapc (lambda (x)
8025 (move-marker (car x) (+ beg (cdr x))))
8026 org-markers-to-move)
8027 (setq org-markers-to-move nil))
8029 (defun org-narrow-to-subtree ()
8030 "Narrow buffer to the current subtree."
8031 (interactive)
8032 (save-excursion
8033 (save-match-data
8034 (org-with-limited-levels
8035 (narrow-to-region
8036 (progn (org-back-to-heading t) (point))
8037 (progn (org-end-of-subtree t t)
8038 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8039 (point)))))))
8041 (defun org-narrow-to-block ()
8042 "Narrow buffer to the current block."
8043 (interactive)
8044 (let* ((case-fold-search t)
8045 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8046 "^[ \t]*#\\+end_.*")))
8047 (if blockp
8048 (narrow-to-region (car blockp) (cdr blockp))
8049 (error "Not in a block"))))
8051 (eval-when-compile
8052 (defvar org-property-drawer-re))
8054 (defvar org-property-start-re) ;; defined below
8055 (defun org-clone-subtree-with-time-shift (n &optional shift)
8056 "Clone the task (subtree) at point N times.
8057 The clones will be inserted as siblings.
8059 In interactive use, the user will be prompted for the number of
8060 clones to be produced, and for a time SHIFT, which may be a
8061 repeater as used in time stamps, for example `+3d'.
8063 When a valid repeater is given and the entry contains any time
8064 stamps, the clones will become a sequence in time, with time
8065 stamps in the subtree shifted for each clone produced. If SHIFT
8066 is nil or the empty string, time stamps will be left alone. The
8067 ID property of the original subtree is removed.
8069 If the original subtree did contain time stamps with a repeater,
8070 the following will happen:
8071 - the repeater will be removed in each clone
8072 - an additional clone will be produced, with the current, unshifted
8073 date(s) in the entry.
8074 - the original entry will be placed *after* all the clones, with
8075 repeater intact.
8076 - the start days in the repeater in the original entry will be shifted
8077 to past the last clone.
8078 In this way you can spell out a number of instances of a repeating task,
8079 and still retain the repeater to cover future instances of the task."
8080 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8081 (let (beg end template task idprop
8082 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8083 (drawer-re org-drawer-regexp))
8084 (if (not (and (integerp n) (> n 0)))
8085 (error "Invalid number of replications %s" n))
8086 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8087 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8088 shift)))
8089 (error "Invalid shift specification %s" shift))
8090 (when doshift
8091 (setq shift-n (string-to-number (match-string 1 shift))
8092 shift-what (cdr (assoc (match-string 2 shift)
8093 '(("d" . day) ("w" . week)
8094 ("m" . month) ("y" . year))))))
8095 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8096 (setq nmin 1 nmax n)
8097 (org-back-to-heading t)
8098 (setq beg (point))
8099 (setq idprop (org-entry-get nil "ID"))
8100 (org-end-of-subtree t t)
8101 (or (bolp) (insert "\n"))
8102 (setq end (point))
8103 (setq template (buffer-substring beg end))
8104 (when (and doshift
8105 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8106 (delete-region beg end)
8107 (setq end beg)
8108 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8109 (goto-char end)
8110 (loop for n from nmin to nmax do
8111 ;; prepare clone
8112 (with-temp-buffer
8113 (insert template)
8114 (org-mode)
8115 (goto-char (point-min))
8116 (org-show-subtree)
8117 (and idprop (if org-clone-delete-id
8118 (org-entry-delete nil "ID")
8119 (org-id-get-create t)))
8120 (unless (= n 0)
8121 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8122 (kill-whole-line))
8123 (goto-char (point-min))
8124 (while (re-search-forward drawer-re nil t)
8125 (mapc (lambda (d)
8126 (org-remove-empty-drawer-at d (point))) org-drawers)))
8127 (goto-char (point-min))
8128 (when doshift
8129 (while (re-search-forward org-ts-regexp-both nil t)
8130 (org-timestamp-change (* n shift-n) shift-what))
8131 (unless (= n n-no-remove)
8132 (goto-char (point-min))
8133 (while (re-search-forward org-ts-regexp nil t)
8134 (save-excursion
8135 (goto-char (match-beginning 0))
8136 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8137 (delete-region (match-beginning 1) (match-end 1)))))))
8138 (setq task (buffer-string)))
8139 (insert task))
8140 (goto-char beg)))
8142 ;;; Outline Sorting
8144 (defun org-sort (with-case)
8145 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8146 Optional argument WITH-CASE means sort case-sensitively."
8147 (interactive "P")
8148 (cond
8149 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8150 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8152 (org-call-with-arg 'org-sort-entries with-case))))
8154 (defun org-sort-remove-invisible (s)
8155 (remove-text-properties 0 (length s) org-rm-props s)
8156 (while (string-match org-bracket-link-regexp s)
8157 (setq s (replace-match (if (match-end 2)
8158 (match-string 3 s)
8159 (match-string 1 s)) t t s)))
8162 (defvar org-priority-regexp) ; defined later in the file
8164 (defvar org-after-sorting-entries-or-items-hook nil
8165 "Hook that is run after a bunch of entries or items have been sorted.
8166 When children are sorted, the cursor is in the parent line when this
8167 hook gets called. When a region or a plain list is sorted, the cursor
8168 will be in the first entry of the sorted region/list.")
8170 (defun org-sort-entries
8171 (&optional with-case sorting-type getkey-func compare-func property)
8172 "Sort entries on a certain level of an outline tree.
8173 If there is an active region, the entries in the region are sorted.
8174 Else, if the cursor is before the first entry, sort the top-level items.
8175 Else, the children of the entry at point are sorted.
8177 Sorting can be alphabetically, numerically, by date/time as given by
8178 a time stamp, by a property or by priority.
8180 The command prompts for the sorting type unless it has been given to the
8181 function through the SORTING-TYPE argument, which needs to be a character,
8182 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8183 precise meaning of each character:
8185 n Numerically, by converting the beginning of the entry/item to a number.
8186 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8187 o By order of TODO keywords.
8188 t By date/time, either the first active time stamp in the entry, or, if
8189 none exist, by the first inactive one.
8190 s By the scheduled date/time.
8191 d By deadline date/time.
8192 c By creation time, which is assumed to be the first inactive time stamp
8193 at the beginning of a line.
8194 p By priority according to the cookie.
8195 r By the value of a property.
8197 Capital letters will reverse the sort order.
8199 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8200 called with point at the beginning of the record. It must return either
8201 a string or a number that should serve as the sorting key for that record.
8203 Comparing entries ignores case by default. However, with an optional argument
8204 WITH-CASE, the sorting considers case as well."
8205 (interactive "P")
8206 (let ((case-func (if with-case 'identity 'downcase))
8207 (cmstr
8208 ;; The clock marker is lost when using `sort-subr', let's
8209 ;; store the clocking string.
8210 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8211 (save-excursion
8212 (goto-char org-clock-marker)
8213 (looking-back "^.*") (match-string-no-properties 0))))
8214 start beg end stars re re2
8215 txt what tmp)
8216 ;; Find beginning and end of region to sort
8217 (cond
8218 ((org-region-active-p)
8219 ;; we will sort the region
8220 (setq end (region-end)
8221 what "region")
8222 (goto-char (region-beginning))
8223 (if (not (org-at-heading-p)) (outline-next-heading))
8224 (setq start (point)))
8225 ((or (org-at-heading-p)
8226 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8227 ;; we will sort the children of the current headline
8228 (org-back-to-heading)
8229 (setq start (point)
8230 end (progn (org-end-of-subtree t t)
8231 (or (bolp) (insert "\n"))
8232 (org-back-over-empty-lines)
8233 (point))
8234 what "children")
8235 (goto-char start)
8236 (show-subtree)
8237 (outline-next-heading))
8239 ;; we will sort the top-level entries in this file
8240 (goto-char (point-min))
8241 (or (org-at-heading-p) (outline-next-heading))
8242 (setq start (point))
8243 (goto-char (point-max))
8244 (beginning-of-line 1)
8245 (when (looking-at ".*?\\S-")
8246 ;; File ends in a non-white line
8247 (end-of-line 1)
8248 (insert "\n"))
8249 (setq end (point-max))
8250 (setq what "top-level")
8251 (goto-char start)
8252 (show-all)))
8254 (setq beg (point))
8255 (if (>= beg end) (error "Nothing to sort"))
8257 (looking-at "\\(\\*+\\)")
8258 (setq stars (match-string 1)
8259 re (concat "^" (regexp-quote stars) " +")
8260 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8261 txt (buffer-substring beg end))
8262 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8263 (if (and (not (equal stars "*")) (string-match re2 txt))
8264 (error "Region to sort contains a level above the first entry"))
8266 (unless sorting-type
8267 (message
8268 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8269 [t]ime [s]cheduled [d]eadline [c]reated
8270 A/N/P/R/O/F/T/S/D/C means reversed:"
8271 what)
8272 (setq sorting-type (read-char-exclusive))
8274 (unless getkey-func
8275 (and (= (downcase sorting-type) ?f)
8276 (setq getkey-func
8277 (org-icompleting-read "Sort using function: "
8278 obarray 'fboundp t nil nil))
8279 (setq getkey-func (intern getkey-func))))
8281 (and (= (downcase sorting-type) ?r)
8282 (not property)
8283 (setq property
8284 (org-icompleting-read "Property: "
8285 (mapcar 'list (org-buffer-property-keys t))
8286 nil t))))
8288 (message "Sorting entries...")
8290 (save-restriction
8291 (narrow-to-region start end)
8292 (let ((dcst (downcase sorting-type))
8293 (case-fold-search nil)
8294 (now (current-time)))
8295 (sort-subr
8296 (/= dcst sorting-type)
8297 ;; This function moves to the beginning character of the "record" to
8298 ;; be sorted.
8299 (lambda nil
8300 (if (re-search-forward re nil t)
8301 (goto-char (match-beginning 0))
8302 (goto-char (point-max))))
8303 ;; This function moves to the last character of the "record" being
8304 ;; sorted.
8305 (lambda nil
8306 (save-match-data
8307 (condition-case nil
8308 (outline-forward-same-level 1)
8309 (error
8310 (goto-char (point-max))))))
8311 ;; This function returns the value that gets sorted against.
8312 (lambda nil
8313 (cond
8314 ((= dcst ?n)
8315 (if (looking-at org-complex-heading-regexp)
8316 (string-to-number (match-string 4))
8317 nil))
8318 ((= dcst ?a)
8319 (if (looking-at org-complex-heading-regexp)
8320 (funcall case-func (match-string 4))
8321 nil))
8322 ((= dcst ?t)
8323 (let ((end (save-excursion (outline-next-heading) (point))))
8324 (if (or (re-search-forward org-ts-regexp end t)
8325 (re-search-forward org-ts-regexp-both end t))
8326 (org-time-string-to-seconds (match-string 0))
8327 (org-float-time now))))
8328 ((= dcst ?c)
8329 (let ((end (save-excursion (outline-next-heading) (point))))
8330 (if (re-search-forward
8331 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8332 end t)
8333 (org-time-string-to-seconds (match-string 0))
8334 (org-float-time now))))
8335 ((= dcst ?s)
8336 (let ((end (save-excursion (outline-next-heading) (point))))
8337 (if (re-search-forward org-scheduled-time-regexp end t)
8338 (org-time-string-to-seconds (match-string 1))
8339 (org-float-time now))))
8340 ((= dcst ?d)
8341 (let ((end (save-excursion (outline-next-heading) (point))))
8342 (if (re-search-forward org-deadline-time-regexp end t)
8343 (org-time-string-to-seconds (match-string 1))
8344 (org-float-time now))))
8345 ((= dcst ?p)
8346 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8347 (string-to-char (match-string 2))
8348 org-default-priority))
8349 ((= dcst ?r)
8350 (or (org-entry-get nil property) ""))
8351 ((= dcst ?o)
8352 (if (looking-at org-complex-heading-regexp)
8353 (- 9999 (length (member (match-string 2)
8354 org-todo-keywords-1)))))
8355 ((= dcst ?f)
8356 (if getkey-func
8357 (progn
8358 (setq tmp (funcall getkey-func))
8359 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8360 tmp)
8361 (error "Invalid key function `%s'" getkey-func)))
8362 (t (error "Invalid sorting type `%c'" sorting-type))))
8364 (cond
8365 ((= dcst ?a) 'string<)
8366 ((= dcst ?f) compare-func)
8367 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8368 (run-hooks 'org-after-sorting-entries-or-items-hook)
8369 ;; Reset the clock marker if needed
8370 (when cmstr
8371 (save-excursion
8372 (goto-char start)
8373 (search-forward cmstr nil t)
8374 (move-marker org-clock-marker (point))))
8375 (message "Sorting entries...done")))
8377 (defun org-do-sort (table what &optional with-case sorting-type)
8378 "Sort TABLE of WHAT according to SORTING-TYPE.
8379 The user will be prompted for the SORTING-TYPE if the call to this
8380 function does not specify it. WHAT is only for the prompt, to indicate
8381 what is being sorted. The sorting key will be extracted from
8382 the car of the elements of the table.
8383 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8384 (unless sorting-type
8385 (message
8386 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8387 what)
8388 (setq sorting-type (read-char-exclusive)))
8389 (let ((dcst (downcase sorting-type))
8390 extractfun comparefun)
8391 ;; Define the appropriate functions
8392 (cond
8393 ((= dcst ?n)
8394 (setq extractfun 'string-to-number
8395 comparefun (if (= dcst sorting-type) '< '>)))
8396 ((= dcst ?a)
8397 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8398 (lambda(x) (downcase (org-sort-remove-invisible x))))
8399 comparefun (if (= dcst sorting-type)
8400 'string<
8401 (lambda (a b) (and (not (string< a b))
8402 (not (string= a b)))))))
8403 ((= dcst ?t)
8404 (setq extractfun
8405 (lambda (x)
8406 (if (or (string-match org-ts-regexp x)
8407 (string-match org-ts-regexp-both x))
8408 (org-float-time
8409 (org-time-string-to-time (match-string 0 x)))
8411 comparefun (if (= dcst sorting-type) '< '>)))
8412 (t (error "Invalid sorting type `%c'" sorting-type)))
8414 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8415 table)
8416 (lambda (a b) (funcall comparefun (car a) (car b))))))
8419 ;;; The orgstruct minor mode
8421 ;; Define a minor mode which can be used in other modes in order to
8422 ;; integrate the org-mode structure editing commands.
8424 ;; This is really a hack, because the org-mode structure commands use
8425 ;; keys which normally belong to the major mode. Here is how it
8426 ;; works: The minor mode defines all the keys necessary to operate the
8427 ;; structure commands, but wraps the commands into a function which
8428 ;; tests if the cursor is currently at a headline or a plain list
8429 ;; item. If that is the case, the structure command is used,
8430 ;; temporarily setting many Org-mode variables like regular
8431 ;; expressions for filling etc. However, when any of those keys is
8432 ;; used at a different location, function uses `key-binding' to look
8433 ;; up if the key has an associated command in another currently active
8434 ;; keymap (minor modes, major mode, global), and executes that
8435 ;; command. There might be problems if any of the keys is otherwise
8436 ;; used as a prefix key.
8438 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8439 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8440 ;; addresses this by checking explicitly for both bindings.
8442 (defvar orgstruct-mode-map (make-sparse-keymap)
8443 "Keymap for the minor `orgstruct-mode'.")
8445 (defvar org-local-vars nil
8446 "List of local variables, for use by `orgstruct-mode'.")
8448 ;;;###autoload
8449 (define-minor-mode orgstruct-mode
8450 "Toggle the minor mode `orgstruct-mode'.
8451 This mode is for using Org-mode structure commands in other
8452 modes. The following keys behave as if Org-mode were active, if
8453 the cursor is on a headline, or on a plain list item (both as
8454 defined by Org-mode).
8456 M-up Move entry/item up
8457 M-down Move entry/item down
8458 M-left Promote
8459 M-right Demote
8460 M-S-up Move entry/item up
8461 M-S-down Move entry/item down
8462 M-S-left Promote subtree
8463 M-S-right Demote subtree
8464 M-q Fill paragraph and items like in Org-mode
8465 C-c ^ Sort entries
8466 C-c - Cycle list bullet
8467 TAB Cycle item visibility
8468 M-RET Insert new heading/item
8469 S-M-RET Insert new TODO heading / Checkbox item
8470 C-c C-c Set tags / toggle checkbox"
8471 nil " OrgStruct" nil
8472 (org-load-modules-maybe)
8473 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8475 ;;;###autoload
8476 (defun turn-on-orgstruct ()
8477 "Unconditionally turn on `orgstruct-mode'."
8478 (orgstruct-mode 1))
8480 (defvar org-fb-vars nil)
8481 (make-variable-buffer-local 'org-fb-vars)
8482 (defun orgstruct++-mode (&optional arg)
8483 "Toggle `orgstruct-mode', the enhanced version of it.
8484 In addition to setting orgstruct-mode, this also exports all
8485 indentation and autofilling variables from org-mode into the
8486 buffer. It will also recognize item context in multiline items."
8487 (interactive "P")
8488 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8489 (if (< arg 1)
8490 (progn (orgstruct-mode -1)
8491 (mapc (lambda(v)
8492 (org-set-local (car v)
8493 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8494 org-fb-vars))
8495 (orgstruct-mode 1)
8496 (setq org-fb-vars nil)
8497 (let (var val)
8498 (mapc
8499 (lambda (x)
8500 (when (string-match
8501 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8502 (symbol-name (car x)))
8503 (setq var (car x) val (nth 1 x))
8504 (push (list var `(quote ,(eval var))) org-fb-vars)
8505 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8506 org-local-vars)
8507 (org-set-local 'orgstruct-is-++ t))))
8509 (defvar orgstruct-is-++ nil
8510 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8511 (make-variable-buffer-local 'orgstruct-is-++)
8513 ;;;###autoload
8514 (defun turn-on-orgstruct++ ()
8515 "Unconditionally turn on `orgstruct++-mode'."
8516 (orgstruct++-mode 1))
8518 (defun orgstruct-error ()
8519 "Error when there is no default binding for a structure key."
8520 (interactive)
8521 (error "This key has no function outside structure elements"))
8523 (defun orgstruct-setup ()
8524 "Setup orgstruct keymaps."
8525 (let ((nfunc 0)
8526 (bindings
8527 (list
8528 '([(meta up)] org-metaup)
8529 '([(meta down)] org-metadown)
8530 '([(meta left)] org-metaleft)
8531 '([(meta right)] org-metaright)
8532 '([(meta shift up)] org-shiftmetaup)
8533 '([(meta shift down)] org-shiftmetadown)
8534 '([(meta shift left)] org-shiftmetaleft)
8535 '([(meta shift right)] org-shiftmetaright)
8536 '([?\e (up)] org-metaup)
8537 '([?\e (down)] org-metadown)
8538 '([?\e (left)] org-metaleft)
8539 '([?\e (right)] org-metaright)
8540 '([?\e (shift up)] org-shiftmetaup)
8541 '([?\e (shift down)] org-shiftmetadown)
8542 '([?\e (shift left)] org-shiftmetaleft)
8543 '([?\e (shift right)] org-shiftmetaright)
8544 '([(shift up)] org-shiftup)
8545 '([(shift down)] org-shiftdown)
8546 '([(shift left)] org-shiftleft)
8547 '([(shift right)] org-shiftright)
8548 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8549 '("\M-q" fill-paragraph)
8550 '("\C-c^" org-sort)
8551 '("\C-c-" org-cycle-list-bullet)))
8552 elt key fun cmd)
8553 (while (setq elt (pop bindings))
8554 (setq nfunc (1+ nfunc))
8555 (setq key (org-key (car elt))
8556 fun (nth 1 elt)
8557 cmd (orgstruct-make-binding fun nfunc key))
8558 (org-defkey orgstruct-mode-map key cmd))
8560 ;; Prevent an error for users who forgot to make autoloads
8561 (require 'org-element)
8563 ;; Special treatment needed for TAB and RET
8564 (org-defkey orgstruct-mode-map [(tab)]
8565 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8566 (org-defkey orgstruct-mode-map "\C-i"
8567 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8569 (org-defkey orgstruct-mode-map "\M-\C-m"
8570 (orgstruct-make-binding 'org-insert-heading 105
8571 "\M-\C-m" [(meta return)]))
8572 (org-defkey orgstruct-mode-map [(meta return)]
8573 (orgstruct-make-binding 'org-insert-heading 106
8574 [(meta return)] "\M-\C-m"))
8576 (org-defkey orgstruct-mode-map [(shift meta return)]
8577 (orgstruct-make-binding 'org-insert-todo-heading 107
8578 [(meta return)] "\M-\C-m"))
8580 (org-defkey orgstruct-mode-map "\e\C-m"
8581 (orgstruct-make-binding 'org-insert-heading 108
8582 "\e\C-m" [?\e (return)]))
8583 (org-defkey orgstruct-mode-map [?\e (return)]
8584 (orgstruct-make-binding 'org-insert-heading 109
8585 [?\e (return)] "\e\C-m"))
8586 (org-defkey orgstruct-mode-map [?\e (shift return)]
8587 (orgstruct-make-binding 'org-insert-todo-heading 110
8588 [?\e (return)] "\e\C-m"))
8590 (unless org-local-vars
8591 (setq org-local-vars (org-get-local-variables)))
8595 (defun orgstruct-make-binding (fun n &rest keys)
8596 "Create a function for binding in the structure minor mode.
8597 FUN is the command to call inside a table. N is used to create a unique
8598 command name. KEYS are keys that should be checked in for a command
8599 to execute outside of tables."
8600 (eval
8601 (list 'defun
8602 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8603 '(arg)
8604 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8605 "Outside of structure, run the binding of `"
8606 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8607 "'.")
8608 '(interactive "p")
8609 (list 'if
8610 `(org-context-p 'headline 'item
8611 (and orgstruct-is-++
8612 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8613 'item-body))
8614 (list 'org-run-like-in-org-mode (list 'quote fun))
8615 (list 'let '(orgstruct-mode)
8616 (list 'call-interactively
8617 (append '(or)
8618 (mapcar (lambda (k)
8619 (list 'key-binding k))
8620 keys)
8621 '('orgstruct-error))))))))
8623 (defun org-contextualize-keys (alist contexts)
8624 "Return valid elements in ALIST depending on CONTEXTS.
8626 `org-agenda-custom-commands' or `org-capture-templates' are the
8627 values used for ALIST, and `org-agenda-custom-commands-contexts'
8628 or `org-capture-templates-contexts' are the associated contexts
8629 definitions."
8630 (let ((contexts
8631 ;; normalize contexts
8632 (mapcar
8633 (lambda(c) (cond ((listp (cadr c))
8634 (list (car c) (car c) (cadr c)))
8635 ((string= "" (cadr c))
8636 (list (car c) (car c) (caddr c)))
8637 (t c))) contexts))
8638 (a alist) c r s)
8639 ;; loop over all commands or templates
8640 (while (setq c (pop a))
8641 (let (vrules repl)
8642 (cond
8643 ((not (assoc (car c) contexts))
8644 (push c r))
8645 ((and (assoc (car c) contexts)
8646 (setq vrules (org-contextualize-validate-key
8647 (car c) contexts)))
8648 (mapc (lambda (vr)
8649 (when (not (equal (car vr) (cadr vr)))
8650 (setq repl vr))) vrules)
8651 (if (not repl) (push c r)
8652 (push (cadr repl) s)
8653 (push
8654 (cons (car c)
8655 (cdr (or (assoc (cadr repl) alist)
8656 (error "Undefined key `%s' as contextual replacement for `%s'"
8657 (cadr repl) (car c)))))
8658 r))))))
8659 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8660 (delq
8662 (delete-dups
8663 (mapcar (lambda (x)
8664 (let ((tpl (car x)))
8665 (when (not (delq
8667 (mapcar (lambda(y)
8668 (equal y tpl)) s))) x)))
8669 (reverse r))))))
8671 (defun org-contextualize-validate-key (key contexts)
8672 "Check CONTEXTS for agenda or capture KEY."
8673 (let (r rr res)
8674 (while (setq r (pop contexts))
8675 (mapc
8676 (lambda (rr)
8677 (when
8678 (and (equal key (car r))
8679 (if (functionp rr) (funcall rr)
8680 (or (and (eq (car rr) 'in-file)
8681 (buffer-file-name)
8682 (string-match (cdr rr) (buffer-file-name)))
8683 (and (eq (car rr) 'in-mode)
8684 (string-match (cdr rr) (symbol-name major-mode)))
8685 (when (and (eq (car rr) 'not-in-file)
8686 (buffer-file-name))
8687 (not (string-match (cdr rr) (buffer-file-name))))
8688 (when (eq (car rr) 'not-in-mode)
8689 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8690 (push r res)))
8691 (car (last r))))
8692 (delete-dups (delq nil res))))
8694 (defun org-context-p (&rest contexts)
8695 "Check if local context is any of CONTEXTS.
8696 Possible values in the list of contexts are `table', `headline', and `item'."
8697 (let ((pos (point)))
8698 (goto-char (point-at-bol))
8699 (prog1 (or (and (memq 'table contexts)
8700 (looking-at "[ \t]*|"))
8701 (and (memq 'headline contexts)
8702 (looking-at org-outline-regexp))
8703 (and (memq 'item contexts)
8704 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8705 (and (memq 'item-body contexts)
8706 (org-in-item-p)))
8707 (goto-char pos))))
8709 (defun org-get-local-variables ()
8710 "Return a list of all local variables in an Org mode buffer."
8711 (let (varlist)
8712 (with-current-buffer (get-buffer-create "*Org tmp*")
8713 (erase-buffer)
8714 (org-mode)
8715 (setq varlist (buffer-local-variables)))
8716 (kill-buffer "*Org tmp*")
8717 (delq nil
8718 (mapcar
8719 (lambda (x)
8720 (setq x
8721 (if (symbolp x)
8722 (list x)
8723 (list (car x) (list 'quote (cdr x)))))
8724 (if (string-match
8725 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8726 (symbol-name (car x)))
8727 x nil))
8728 varlist))))
8730 (defun org-clone-local-variables (from-buffer &optional regexp)
8731 "Clone local variables from FROM-BUFFER.
8732 Optional argument REGEXP selects variables to clone."
8733 (mapc
8734 (lambda (pair)
8735 (and (symbolp (car pair))
8736 (or (null regexp)
8737 (string-match regexp (symbol-name (car pair))))
8738 (set (make-local-variable (car pair))
8739 (cdr pair))))
8740 (buffer-local-variables from-buffer)))
8742 ;;;###autoload
8743 (defun org-run-like-in-org-mode (cmd)
8744 "Run a command, pretending that the current buffer is in Org-mode.
8745 This will temporarily bind local variables that are typically bound in
8746 Org-mode to the values they have in Org-mode, and then interactively
8747 call CMD."
8748 (org-load-modules-maybe)
8749 (unless org-local-vars
8750 (setq org-local-vars (org-get-local-variables)))
8751 (eval (list 'let org-local-vars
8752 (list 'call-interactively (list 'quote cmd)))))
8754 ;;;; Archiving
8756 (defun org-get-category (&optional pos force-refresh)
8757 "Get the category applying to position POS."
8758 (save-match-data
8759 (if force-refresh (org-refresh-category-properties))
8760 (let ((pos (or pos (point))))
8761 (or (get-text-property pos 'org-category)
8762 (progn (org-refresh-category-properties)
8763 (get-text-property pos 'org-category))))))
8765 (defun org-refresh-category-properties ()
8766 "Refresh category text properties in the buffer."
8767 (let ((case-fold-search t)
8768 (inhibit-read-only t)
8769 (def-cat (cond
8770 ((null org-category)
8771 (if buffer-file-name
8772 (file-name-sans-extension
8773 (file-name-nondirectory buffer-file-name))
8774 "???"))
8775 ((symbolp org-category) (symbol-name org-category))
8776 (t org-category)))
8777 beg end cat pos optionp)
8778 (org-unmodified
8779 (save-excursion
8780 (save-restriction
8781 (widen)
8782 (goto-char (point-min))
8783 (put-text-property (point) (point-max) 'org-category def-cat)
8784 (while (re-search-forward
8785 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8786 (setq pos (match-end 0)
8787 optionp (equal (char-after (match-beginning 0)) ?#)
8788 cat (org-trim (match-string 2)))
8789 (if optionp
8790 (setq beg (point-at-bol) end (point-max))
8791 (org-back-to-heading t)
8792 (setq beg (point) end (org-end-of-subtree t t)))
8793 (put-text-property beg end 'org-category cat)
8794 (put-text-property beg end 'org-category-position beg)
8795 (goto-char pos)))))))
8798 ;;;; Link Stuff
8800 ;;; Link abbreviations
8802 (defun org-link-expand-abbrev (link)
8803 "Apply replacements as defined in `org-link-abbrev-alist'."
8804 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8805 (let* ((key (match-string 1 link))
8806 (as (or (assoc key org-link-abbrev-alist-local)
8807 (assoc key org-link-abbrev-alist)))
8808 (tag (and (match-end 2) (match-string 3 link)))
8809 rpl)
8810 (if (not as)
8811 link
8812 (setq rpl (cdr as))
8813 (cond
8814 ((symbolp rpl) (funcall rpl tag))
8815 ((string-match "%(\\([^)]+\\))" rpl)
8816 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8817 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8818 ((string-match "%h" rpl)
8819 (replace-match (url-hexify-string (or tag "")) t t rpl))
8820 (t (concat rpl tag)))))
8821 link))
8823 ;;; Storing and inserting links
8825 (defvar org-insert-link-history nil
8826 "Minibuffer history for links inserted with `org-insert-link'.")
8828 (defvar org-stored-links nil
8829 "Contains the links stored with `org-store-link'.")
8831 (defvar org-store-link-plist nil
8832 "Plist with info about the most recently link created with `org-store-link'.")
8834 (defvar org-link-protocols nil
8835 "Link protocols added to Org-mode using `org-add-link-type'.")
8837 (defvar org-store-link-functions nil
8838 "List of functions that are called to create and store a link.
8839 Each function will be called in turn until one returns a non-nil
8840 value. Each function should check if it is responsible for creating
8841 this link (for example by looking at the major mode).
8842 If not, it must exit and return nil.
8843 If yes, it should return a non-nil value after a calling
8844 `org-store-link-props' with a list of properties and values.
8845 Special properties are:
8847 :type The link prefix, like \"http\". This must be given.
8848 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8849 This is obligatory as well.
8850 :description Optional default description for the second pair
8851 of brackets in an Org-mode link. The user can still change
8852 this when inserting this link into an Org-mode buffer.
8854 In addition to these, any additional properties can be specified
8855 and then used in capture templates.")
8857 (defun org-add-link-type (type &optional follow export)
8858 "Add TYPE to the list of `org-link-types'.
8859 Re-compute all regular expressions depending on `org-link-types'
8861 FOLLOW and EXPORT are two functions.
8863 FOLLOW should take the link path as the single argument and do whatever
8864 is necessary to follow the link, for example find a file or display
8865 a mail message.
8867 EXPORT should format the link path for export to one of the export formats.
8868 It should be a function accepting three arguments:
8870 path the path of the link, the text after the prefix (like \"http:\")
8871 desc the description of the link, if any, or a description added by
8872 org-export-normalize-links if there is none
8873 format the export format, a symbol like `html' or `latex' or `ascii'..
8875 The function may use the FORMAT information to return different values
8876 depending on the format. The return value will be put literally into
8877 the exported file. If the return value is nil, this means Org should
8878 do what it normally does with links which do not have EXPORT defined.
8880 Org-mode has a built-in default for exporting links. If you are happy with
8881 this default, there is no need to define an export function for the link
8882 type. For a simple example of an export function, see `org-bbdb.el'."
8883 (add-to-list 'org-link-types type t)
8884 (org-make-link-regexps)
8885 (if (assoc type org-link-protocols)
8886 (setcdr (assoc type org-link-protocols) (list follow export))
8887 (push (list type follow export) org-link-protocols)))
8889 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8890 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8892 ;;;###autoload
8893 (defun org-store-link (arg)
8894 "\\<org-mode-map>Store an org-link to the current location.
8895 This link is added to `org-stored-links' and can later be inserted
8896 into an org-buffer with \\[org-insert-link].
8898 For some link types, a prefix arg is interpreted.
8899 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8900 For file links, arg negates `org-context-in-file-links'.
8902 A double prefix arg force skipping storing functions that are not
8903 part of Org's core."
8904 (interactive "P")
8905 (org-load-modules-maybe)
8906 (setq org-store-link-plist nil) ; reset
8907 (org-with-limited-levels
8908 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8909 (cond
8910 ((and (not (equal arg '(16)))
8911 (setq sfuns
8912 (delq
8913 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8914 org-store-link-functions))
8915 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8916 (or (and (cdr sfuns)
8917 (funcall (intern
8918 (completing-read "Which function for creating the link? "
8919 sfunsn t (car sfunsn)))))
8920 (funcall (caar sfuns)))
8921 (setq link (plist-get org-store-link-plist :link)
8922 desc (or (plist-get org-store-link-plist :description) link))))
8923 ((org-src-edit-buffer-p)
8924 (let (label gc)
8925 (while (or (not label)
8926 (save-excursion
8927 (save-restriction
8928 (widen)
8929 (goto-char (point-min))
8930 (re-search-forward
8931 (regexp-quote (format org-coderef-label-format label))
8932 nil t))))
8933 (when label (message "Label exists already") (sit-for 2))
8934 (setq label (read-string "Code line label: " label)))
8935 (end-of-line 1)
8936 (setq link (format org-coderef-label-format label))
8937 (setq gc (- 79 (length link)))
8938 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8939 (insert link)
8940 (setq link (concat "(" label ")") desc nil)))
8942 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8943 ;; We are in the agenda, link to referenced location
8944 (let ((m (or (get-text-property (point) 'org-hd-marker)
8945 (get-text-property (point) 'org-marker))))
8946 (when m
8947 (org-with-point-at m
8948 (setq agenda-link
8949 (if (org-called-interactively-p 'any)
8950 (call-interactively 'org-store-link)
8951 (org-store-link nil)))))))
8953 ((eq major-mode 'calendar-mode)
8954 (let ((cd (calendar-cursor-to-date)))
8955 (setq link
8956 (format-time-string
8957 (car org-time-stamp-formats)
8958 (apply 'encode-time
8959 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8960 nil nil nil))))
8961 (org-store-link-props :type "calendar" :date cd)))
8963 ((eq major-mode 'help-mode)
8964 (setq link (concat "help:" (save-excursion
8965 (goto-char (point-min))
8966 (looking-at "^[^ ]+")
8967 (match-string 0))))
8968 (org-store-link-props :type "help"))
8970 ((eq major-mode 'w3-mode)
8971 (setq cpltxt (if (and (buffer-name)
8972 (not (string-match "Untitled" (buffer-name))))
8973 (buffer-name)
8974 (url-view-url t))
8975 link (url-view-url t))
8976 (org-store-link-props :type "w3" :url (url-view-url t)))
8978 ((setq search (run-hook-with-args-until-success
8979 'org-create-file-search-functions))
8980 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8981 "::" search))
8982 (setq cpltxt (or description link)))
8984 ((eq major-mode 'image-mode)
8985 (setq cpltxt (concat "file:"
8986 (abbreviate-file-name buffer-file-name))
8987 link cpltxt)
8988 (org-store-link-props :type "image" :file buffer-file-name))
8990 ((eq major-mode 'dired-mode)
8991 ;; link to the file in the current line
8992 (let ((file (dired-get-filename nil t)))
8993 (setq file (if file
8994 (abbreviate-file-name
8995 (expand-file-name (dired-get-filename nil t)))
8996 ;; otherwise, no file so use current directory.
8997 default-directory))
8998 (setq cpltxt (concat "file:" file)
8999 link cpltxt)))
9001 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9002 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9003 (cond
9004 ((org-in-regexp "<<\\(.*?\\)>>")
9005 (setq cpltxt
9006 (concat "file:"
9007 (abbreviate-file-name
9008 (buffer-file-name (buffer-base-buffer)))
9009 "::" (match-string 1))
9010 link cpltxt))
9011 ((and (featurep 'org-id)
9012 (or (eq org-link-to-org-use-id t)
9013 (and (org-called-interactively-p 'any)
9014 (or (eq org-link-to-org-use-id 'create-if-interactive)
9015 (and (eq org-link-to-org-use-id
9016 'create-if-interactive-and-no-custom-id)
9017 (not custom-id))))
9018 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
9019 ;; We can make a link using the ID.
9020 (setq link (condition-case nil
9021 (prog1 (org-id-store-link)
9022 (setq desc (plist-get org-store-link-plist :description)))
9023 (error
9024 ;; probably before first headline, link to file only
9025 (concat "file:"
9026 (abbreviate-file-name
9027 (buffer-file-name (buffer-base-buffer))))))))
9029 ;; Just link to current headline
9030 (setq cpltxt (concat "file:"
9031 (abbreviate-file-name
9032 (buffer-file-name (buffer-base-buffer)))))
9033 ;; Add a context search string
9034 (when (org-xor org-context-in-file-links arg)
9035 (let ((e (org-element-at-point)))
9036 (setq txt (cond
9037 ((org-at-heading-p) nil)
9038 ((eq (org-element-type e) 'keyword)
9039 (plist-get (cadr e) :value))
9040 ((org-region-active-p)
9041 (buffer-substring (region-beginning) (region-end))))))
9042 (when (or (null txt) (string-match "\\S-" txt))
9043 (setq cpltxt
9044 (concat cpltxt "::"
9045 (condition-case nil
9046 (org-make-org-heading-search-string txt)
9047 (error "")))
9048 desc (or (nth 4 (ignore-errors
9049 (org-heading-components))) "NONE"))))
9050 (if (string-match "::\\'" cpltxt)
9051 (setq cpltxt (substring cpltxt 0 -2)))
9052 (setq link cpltxt))))
9054 ((buffer-file-name (buffer-base-buffer))
9055 ;; Just link to this file here.
9056 (setq cpltxt (concat "file:"
9057 (abbreviate-file-name
9058 (buffer-file-name (buffer-base-buffer)))))
9059 ;; Add a context string
9060 (when (org-xor org-context-in-file-links arg)
9061 (setq txt (if (org-region-active-p)
9062 (buffer-substring (region-beginning) (region-end))
9063 (buffer-substring (point-at-bol) (point-at-eol))))
9064 ;; Only use search option if there is some text.
9065 (when (string-match "\\S-" txt)
9066 (setq cpltxt
9067 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9068 desc "NONE")))
9069 (setq link cpltxt))
9071 ((org-called-interactively-p 'interactive)
9072 (user-error "No method for storing a link from this buffer"))
9074 (t (setq link nil)))
9076 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9077 (setq link (or link cpltxt)
9078 desc (or desc cpltxt))
9079 (cond ((equal desc "NONE") (setq desc nil))
9080 ((string-match org-bracket-link-regexp desc)
9081 (setq desc (replace-regexp-in-string
9082 org-bracket-link-regexp
9083 (concat "\\3" (if (equal (length (match-string 0 desc))
9084 (length desc)) "*" "")) desc))))
9086 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9087 (progn
9088 (setq org-stored-links
9089 (cons (list link desc) org-stored-links))
9090 (message "Stored: %s" (or desc link))
9091 (when custom-id
9092 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9093 "::#" custom-id))
9094 (setq org-stored-links
9095 (cons (list link desc) org-stored-links))))
9096 (or agenda-link (and link (org-make-link-string link desc)))))))
9098 (defun org-store-link-props (&rest plist)
9099 "Store link properties, extract names and addresses."
9100 (let (x adr)
9101 (when (setq x (plist-get plist :from))
9102 (setq adr (mail-extract-address-components x))
9103 (setq plist (plist-put plist :fromname (car adr)))
9104 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9105 (when (setq x (plist-get plist :to))
9106 (setq adr (mail-extract-address-components x))
9107 (setq plist (plist-put plist :toname (car adr)))
9108 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9109 (let ((from (plist-get plist :from))
9110 (to (plist-get plist :to)))
9111 (when (and from to org-from-is-user-regexp)
9112 (setq plist
9113 (plist-put plist :fromto
9114 (if (string-match org-from-is-user-regexp from)
9115 (concat "to %t")
9116 (concat "from %f"))))))
9117 (setq org-store-link-plist plist))
9119 (defun org-add-link-props (&rest plist)
9120 "Add these properties to the link property list."
9121 (let (key value)
9122 (while plist
9123 (setq key (pop plist) value (pop plist))
9124 (setq org-store-link-plist
9125 (plist-put org-store-link-plist key value)))))
9127 (defun org-email-link-description (&optional fmt)
9128 "Return the description part of an email link.
9129 This takes information from `org-store-link-plist' and formats it
9130 according to FMT (default from `org-email-link-description-format')."
9131 (setq fmt (or fmt org-email-link-description-format))
9132 (let* ((p org-store-link-plist)
9133 (to (plist-get p :toaddress))
9134 (from (plist-get p :fromaddress))
9135 (table
9136 (list
9137 (cons "%c" (plist-get p :fromto))
9138 (cons "%F" (plist-get p :from))
9139 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9140 (cons "%T" (plist-get p :to))
9141 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9142 (cons "%s" (plist-get p :subject))
9143 (cons "%d" (plist-get p :date))
9144 (cons "%m" (plist-get p :message-id)))))
9145 (when (string-match "%c" fmt)
9146 ;; Check if the user wrote this message
9147 (if (and org-from-is-user-regexp from to
9148 (save-match-data (string-match org-from-is-user-regexp from)))
9149 (setq fmt (replace-match "to %t" t t fmt))
9150 (setq fmt (replace-match "from %f" t t fmt))))
9151 (org-replace-escapes fmt table)))
9153 (defun org-make-org-heading-search-string (&optional string)
9154 "Make search string for the current headline or STRING."
9155 (let ((s (or string
9156 (and (derived-mode-p 'org-mode)
9157 (save-excursion
9158 (org-back-to-heading t)
9159 (plist-get (cadr (org-element-at-point))
9160 :raw-value)))))
9161 (lines org-context-in-file-links))
9162 (or string (setq s (concat "*" s))) ; Add * for headlines
9163 (when (and string (integerp lines) (> lines 0))
9164 (let ((slines (org-split-string s "\n")))
9165 (when (< lines (length slines))
9166 (setq s (mapconcat
9167 'identity
9168 (reverse (nthcdr (- (length slines) lines)
9169 (reverse slines))) "\n")))))
9170 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9172 (defun org-make-link-string (link &optional description)
9173 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9174 (unless (string-match "\\S-" link)
9175 (error "Empty link"))
9176 (when (and description
9177 (stringp description)
9178 (not (string-match "\\S-" description)))
9179 (setq description nil))
9180 (when (stringp description)
9181 ;; Remove brackets from the description, they are fatal.
9182 (while (string-match "\\[" description)
9183 (setq description (replace-match "{" t t description)))
9184 (while (string-match "\\]" description)
9185 (setq description (replace-match "}" t t description))))
9186 (when (equal link description)
9187 ;; No description needed, it is identical
9188 (setq description nil))
9189 (when (and (not description)
9190 (not (string-match (org-image-file-name-regexp) link))
9191 (not (equal link (org-link-escape link))))
9192 (setq description (org-extract-attributes link)))
9193 (setq link
9194 (cond ((string-match (org-image-file-name-regexp) link) link)
9195 ((string-match org-link-types-re link)
9196 (concat (match-string 1 link)
9197 (org-link-escape (substring link (match-end 1)))))
9198 (t (org-link-escape link))))
9199 (concat "[[" link "]"
9200 (if description (concat "[" description "]") "")
9201 "]"))
9203 (defconst org-link-escape-chars
9204 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9205 "List of characters that should be escaped in link.
9206 This is the list that is used for internal purposes.")
9208 (defconst org-link-escape-chars-browser
9209 '(?\ )
9210 "List of escapes for characters that are problematic in links.
9211 This is the list that is used before handing over to the browser.")
9213 (defun org-link-escape (text &optional table merge)
9214 "Return percent escaped representation of TEXT.
9215 TEXT is a string with the text to escape.
9216 Optional argument TABLE is a list with characters that should be
9217 escaped. When nil, `org-link-escape-chars' is used.
9218 If optional argument MERGE is set, merge TABLE into
9219 `org-link-escape-chars'."
9220 (cond
9221 ((and table merge)
9222 (mapc (lambda (defchr)
9223 (unless (member defchr table)
9224 (setq table (cons defchr table)))) org-link-escape-chars))
9225 ((null table)
9226 (setq table org-link-escape-chars)))
9227 (mapconcat
9228 (lambda (char)
9229 (if (or (member char table)
9230 (and (or (< char 32) (= char 37) (> char 126))
9231 org-url-hexify-p))
9232 (mapconcat (lambda (sequence-element)
9233 (format "%%%.2X" sequence-element))
9234 (or (encode-coding-char char 'utf-8)
9235 (error "Unable to percent escape character: %s"
9236 (char-to-string char))) "")
9237 (char-to-string char))) text ""))
9239 (defun org-link-unescape (str)
9240 "Unhex hexified Unicode strings as returned from the JavaScript function
9241 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9242 (unless (and (null str) (string= "" str))
9243 (let ((pos 0) (case-fold-search t) unhexed)
9244 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9245 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9246 (setq str (replace-match unhexed t t str))
9247 (setq pos (+ pos (length unhexed))))))
9248 str)
9250 (defun org-link-unescape-compound (hex)
9251 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9252 Note: this function also decodes single byte encodings like
9253 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9254 (save-match-data
9255 (let* ((bytes (cdr (split-string hex "%")))
9256 (ret "")
9257 (eat 0)
9258 (sum 0))
9259 (while bytes
9260 (let* ((val (string-to-number (pop bytes) 16))
9261 (shift-xor
9262 (if (= 0 eat)
9263 (cond
9264 ((>= val 252) (cons 6 252))
9265 ((>= val 248) (cons 5 248))
9266 ((>= val 240) (cons 4 240))
9267 ((>= val 224) (cons 3 224))
9268 ((>= val 192) (cons 2 192))
9269 (t (cons 0 0)))
9270 (cons 6 128))))
9271 (if (>= val 192) (setq eat (car shift-xor)))
9272 (setq val (logxor val (cdr shift-xor)))
9273 (setq sum (+ (lsh sum (car shift-xor)) val))
9274 (if (> eat 0) (setq eat (- eat 1)))
9275 (cond
9276 ((= 0 eat) ;multi byte
9277 (setq ret (concat ret (org-char-to-string sum)))
9278 (setq sum 0))
9279 ((not bytes) ; single byte(s)
9280 (setq ret (org-link-unescape-single-byte-sequence hex))))
9281 )) ;; end (while bytes
9282 ret )))
9284 (defun org-link-unescape-single-byte-sequence (hex)
9285 "Unhexify hex-encoded single byte character sequences."
9286 (mapconcat (lambda (byte)
9287 (char-to-string (string-to-number byte 16)))
9288 (cdr (split-string hex "%")) ""))
9290 (defun org-xor (a b)
9291 "Exclusive or."
9292 (if a (not b) b))
9294 (defun org-fixup-message-id-for-http (s)
9295 "Replace special characters in a message id, so it can be used in an http query."
9296 (when (string-match "%" s)
9297 (setq s (mapconcat (lambda (c)
9298 (if (eq c ?%)
9299 "%25"
9300 (char-to-string c)))
9301 s "")))
9302 (while (string-match "<" s)
9303 (setq s (replace-match "%3C" t t s)))
9304 (while (string-match ">" s)
9305 (setq s (replace-match "%3E" t t s)))
9306 (while (string-match "@" s)
9307 (setq s (replace-match "%40" t t s)))
9310 (defun org-link-prettify (link)
9311 "Return a human-readable representation of LINK.
9312 The car of LINK must be a raw link the cdr of LINK must be either
9313 a link description or nil."
9314 (let ((desc (or (cadr link) "<no description>")))
9315 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9316 "<" (car link) ">")))
9318 ;;;###autoload
9319 (defun org-insert-link-global ()
9320 "Insert a link like Org-mode does.
9321 This command can be called in any mode to insert a link in Org-mode syntax."
9322 (interactive)
9323 (org-load-modules-maybe)
9324 (org-run-like-in-org-mode 'org-insert-link))
9326 (defun org-insert-all-links (&optional keep)
9327 "Insert all links in `org-stored-links'."
9328 (interactive "P")
9329 (let ((links (copy-sequence org-stored-links)) l)
9330 (while (setq l (if keep (pop links) (pop org-stored-links)))
9331 (insert "- ")
9332 (org-insert-link nil (car l) (cadr l))
9333 (insert "\n"))))
9335 (defun org-link-fontify-links-to-this-file ()
9336 "Fontify links to the current file in `org-stored-links'."
9337 (let ((f (buffer-file-name)) a b)
9338 (setq a (mapcar (lambda(l)
9339 (let ((ll (car l)))
9340 (when (and (string-match "^file:\\(.+\\)::" ll)
9341 (equal f (expand-file-name (match-string 1 ll))))
9342 ll)))
9343 org-stored-links))
9344 (when (featurep 'org-id)
9345 (setq b (mapcar (lambda(l)
9346 (let ((ll (car l)))
9347 (when (and (string-match "^id:\\(.+\\)$" ll)
9348 (equal f (expand-file-name
9349 (or (org-id-find-id-file
9350 (match-string 1 ll)) ""))))
9351 ll)))
9352 org-stored-links)))
9353 (mapcar (lambda(l)
9354 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9355 (delq nil (append a b)))))
9357 (defvar org-link-links-in-this-file nil)
9358 (defun org-insert-link (&optional complete-file link-location default-description)
9359 "Insert a link. At the prompt, enter the link.
9361 Completion can be used to insert any of the link protocol prefixes like
9362 http or ftp in use.
9364 The history can be used to select a link previously stored with
9365 `org-store-link'. When the empty string is entered (i.e. if you just
9366 press RET at the prompt), the link defaults to the most recently
9367 stored link. As SPC triggers completion in the minibuffer, you need to
9368 use M-SPC or C-q SPC to force the insertion of a space character.
9370 You will also be prompted for a description, and if one is given, it will
9371 be displayed in the buffer instead of the link.
9373 If there is already a link at point, this command will allow you to edit link
9374 and description parts.
9376 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9377 be selected using completion. The path to the file will be relative to the
9378 current directory if the file is in the current directory or a subdirectory.
9379 Otherwise, the link will be the absolute path as completed in the minibuffer
9380 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9381 option `org-link-file-path-type'.
9383 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9384 the current directory or below.
9386 With three \\[universal-argument] prefixes, negate the meaning of
9387 `org-keep-stored-link-after-insertion'.
9389 If `org-make-link-description-function' is non-nil, this function will be
9390 called with the link target, and the result will be the default
9391 link description.
9393 If the LINK-LOCATION parameter is non-nil, this value will be
9394 used as the link location instead of reading one interactively.
9396 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9397 be used as the default description."
9398 (interactive "P")
9399 (let* ((wcf (current-window-configuration))
9400 (origbuf (current-buffer))
9401 (region (if (org-region-active-p)
9402 (buffer-substring (region-beginning) (region-end))))
9403 (remove (and region (list (region-beginning) (region-end))))
9404 (desc region)
9405 tmphist ; byte-compile incorrectly complains about this
9406 (link link-location)
9407 (abbrevs org-link-abbrev-alist-local)
9408 entry file all-prefixes auto-desc)
9409 (cond
9410 (link-location) ; specified by arg, just use it.
9411 ((org-in-regexp org-bracket-link-regexp 1)
9412 ;; We do have a link at point, and we are going to edit it.
9413 (setq remove (list (match-beginning 0) (match-end 0)))
9414 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9415 (setq link (read-string "Link: "
9416 (org-link-unescape
9417 (org-match-string-no-properties 1)))))
9418 ((or (org-in-regexp org-angle-link-re)
9419 (org-in-regexp org-plain-link-re))
9420 ;; Convert to bracket link
9421 (setq remove (list (match-beginning 0) (match-end 0))
9422 link (read-string "Link: "
9423 (org-remove-angle-brackets (match-string 0)))))
9424 ((member complete-file '((4) (16)))
9425 ;; Completing read for file names.
9426 (setq link (org-file-complete-link complete-file)))
9428 ;; Read link, with completion for stored links.
9429 (org-link-fontify-links-to-this-file)
9430 (org-switch-to-buffer-other-window "*Org Links*")
9431 (with-current-buffer "*Org Links*"
9432 (erase-buffer)
9433 (insert "Insert a link.
9434 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9435 (when org-stored-links
9436 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9437 (insert (mapconcat 'org-link-prettify
9438 (reverse org-stored-links) "\n")))
9439 (goto-char (point-min)))
9440 (let ((cw (selected-window)))
9441 (select-window (get-buffer-window "*Org Links*" 'visible))
9442 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9443 (unless (pos-visible-in-window-p (point-max))
9444 (org-fit-window-to-buffer))
9445 (and (window-live-p cw) (select-window cw)))
9446 ;; Fake a link history, containing the stored links.
9447 (setq tmphist (append (mapcar 'car org-stored-links)
9448 org-insert-link-history))
9449 (setq all-prefixes (append (mapcar 'car abbrevs)
9450 (mapcar 'car org-link-abbrev-alist)
9451 org-link-types))
9452 (unwind-protect
9453 (progn
9454 (setq link
9455 (org-completing-read
9456 "Link: "
9457 (append
9458 (mapcar (lambda (x) (concat x ":"))
9459 all-prefixes)
9460 (mapcar 'car org-stored-links))
9461 nil nil nil
9462 'tmphist
9463 (caar org-stored-links)))
9464 (if (not (string-match "\\S-" link))
9465 (error "No link selected"))
9466 (mapc (lambda(l)
9467 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9468 org-stored-links)
9469 (if (or (member link all-prefixes)
9470 (and (equal ":" (substring link -1))
9471 (member (substring link 0 -1) all-prefixes)
9472 (setq link (substring link 0 -1))))
9473 (setq link (with-current-buffer origbuf
9474 (org-link-try-special-completion link)))))
9475 (set-window-configuration wcf)
9476 (kill-buffer "*Org Links*"))
9477 (setq entry (assoc link org-stored-links))
9478 (or entry (push link org-insert-link-history))
9479 (setq desc (or desc (nth 1 entry)))))
9481 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9482 (not org-keep-stored-link-after-insertion))
9483 (setq org-stored-links (delq (assoc link org-stored-links)
9484 org-stored-links)))
9486 (if (string-match org-plain-link-re link)
9487 ;; URL-like link, normalize the use of angular brackets.
9488 (setq link (org-remove-angle-brackets link)))
9490 ;; Check if we are linking to the current file with a search
9491 ;; option If yes, simplify the link by using only the search
9492 ;; option.
9493 (when (and buffer-file-name
9494 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9495 (let* ((path (match-string 1 link))
9496 (case-fold-search nil)
9497 (search (match-string 2 link)))
9498 (save-match-data
9499 (if (equal (file-truename buffer-file-name) (file-truename path))
9500 ;; We are linking to this same file, with a search option
9501 (setq link search)))))
9503 ;; Check if we can/should use a relative path. If yes, simplify the link
9504 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9505 (let* ((type (match-string 1 link))
9506 (path (match-string 2 link))
9507 (origpath path)
9508 (case-fold-search nil))
9509 (cond
9510 ((or (eq org-link-file-path-type 'absolute)
9511 (equal complete-file '(16)))
9512 (setq path (abbreviate-file-name (expand-file-name path))))
9513 ((eq org-link-file-path-type 'noabbrev)
9514 (setq path (expand-file-name path)))
9515 ((eq org-link-file-path-type 'relative)
9516 (setq path (file-relative-name path)))
9518 (save-match-data
9519 (if (string-match (concat "^" (regexp-quote
9520 (expand-file-name
9521 (file-name-as-directory
9522 default-directory))))
9523 (expand-file-name path))
9524 ;; We are linking a file with relative path name.
9525 (setq path (substring (expand-file-name path)
9526 (match-end 0)))
9527 (setq path (abbreviate-file-name (expand-file-name path)))))))
9528 (setq link (concat type path))
9529 (if (equal desc origpath)
9530 (setq desc path))))
9532 (if org-make-link-description-function
9533 (setq desc
9534 (or (condition-case nil
9535 (funcall org-make-link-description-function link desc)
9536 (error (progn (message "Can't get link description from `%s'"
9537 (symbol-name org-make-link-description-function))
9538 (sit-for 2) nil)))
9539 (read-string "Description: " default-description)))
9540 (if default-description (setq desc default-description)
9541 (setq desc (or (and auto-desc desc)
9542 (read-string "Description: " desc)))))
9544 (unless (string-match "\\S-" desc) (setq desc nil))
9545 (if remove (apply 'delete-region remove))
9546 (insert (org-make-link-string link desc))))
9548 (defun org-link-try-special-completion (type)
9549 "If there is completion support for link type TYPE, offer it."
9550 (let ((fun (intern (concat "org-" type "-complete-link"))))
9551 (if (functionp fun)
9552 (funcall fun)
9553 (read-string "Link (no completion support): " (concat type ":")))))
9555 (defun org-file-complete-link (&optional arg)
9556 "Create a file link using completion."
9557 (let (file link)
9558 (setq file (org-iread-file-name "File: "))
9559 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9560 (pwd1 (file-name-as-directory (abbreviate-file-name
9561 (expand-file-name ".")))))
9562 (cond
9563 ((equal arg '(16))
9564 (setq link (concat
9565 "file:"
9566 (abbreviate-file-name (expand-file-name file)))))
9567 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9568 (setq link (concat "file:" (match-string 1 file))))
9569 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9570 (expand-file-name file))
9571 (setq link (concat
9572 "file:" (match-string 1 (expand-file-name file)))))
9573 (t (setq link (concat "file:" file)))))
9574 link))
9576 (defun org-iread-file-name (&rest args)
9577 "Read-file-name using `ido-mode' speedup if available.
9578 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9579 See `read-file-name' for a description of parameters."
9580 (org-without-partial-completion
9581 (if (and org-completion-use-ido
9582 (fboundp 'ido-read-file-name)
9583 (boundp 'ido-mode) ido-mode
9584 (listp (second args)))
9585 (let ((ido-enter-matching-directory nil))
9586 (apply 'ido-read-file-name args))
9587 (apply 'read-file-name args))))
9589 (defun org-completing-read (&rest args)
9590 "Completing-read with SPACE being a normal character."
9591 (let ((enable-recursive-minibuffers t)
9592 (minibuffer-local-completion-map
9593 (copy-keymap minibuffer-local-completion-map)))
9594 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9595 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9596 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9597 (apply 'org-icompleting-read args)))
9599 (defun org-completing-read-no-i (&rest args)
9600 (let (org-completion-use-ido org-completion-use-iswitchb)
9601 (apply 'org-completing-read args)))
9603 (defun org-iswitchb-completing-read (prompt choices &rest args)
9604 "Use iswitch as a completing-read replacement to choose from choices.
9605 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9606 from."
9607 (let* ((iswitchb-use-virtual-buffers nil)
9608 (iswitchb-make-buflist-hook
9609 (lambda ()
9610 (setq iswitchb-temp-buflist choices))))
9611 (iswitchb-read-buffer prompt)))
9613 (defun org-icompleting-read (&rest args)
9614 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9615 (org-without-partial-completion
9616 (if (and org-completion-use-ido
9617 (fboundp 'ido-completing-read)
9618 (boundp 'ido-mode) ido-mode
9619 (listp (second args)))
9620 (let ((ido-enter-matching-directory nil))
9621 (apply 'ido-completing-read (concat (car args))
9622 (if (consp (car (nth 1 args)))
9623 (mapcar 'car (nth 1 args))
9624 (nth 1 args))
9625 (cddr args)))
9626 (if (and org-completion-use-iswitchb
9627 (boundp 'iswitchb-mode) iswitchb-mode
9628 (listp (second args)))
9629 (apply 'org-iswitchb-completing-read (concat (car args))
9630 (if (consp (car (nth 1 args)))
9631 (mapcar 'car (nth 1 args))
9632 (nth 1 args))
9633 (cddr args))
9634 (apply 'completing-read args)))))
9636 (defun org-extract-attributes (s)
9637 "Extract the attributes cookie from a string and set as text property."
9638 (let (a attr (start 0) key value)
9639 (save-match-data
9640 (when (string-match "{{\\([^}]+\\)}}$" s)
9641 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9642 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9643 (setq key (match-string 1 a) value (match-string 2 a)
9644 start (match-end 0)
9645 attr (plist-put attr (intern key) value))))
9646 (org-add-props s nil 'org-attr attr))
9649 (defun org-extract-attributes-from-string (tag)
9650 (let (key value attr)
9651 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9652 (setq key (match-string 1 tag) value (match-string 2 tag)
9653 tag (replace-match "" t t tag)
9654 attr (plist-put attr (intern key) value)))
9655 (cons tag attr)))
9657 (defun org-attributes-to-string (plist)
9658 "Format a property list into an HTML attribute list."
9659 (let ((s "") key value)
9660 (while plist
9661 (setq key (pop plist) value (pop plist))
9662 (and value
9663 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9666 ;;; Opening/following a link
9668 (defvar org-link-search-failed nil)
9670 (defvar org-open-link-functions nil
9671 "Hook for functions finding a plain text link.
9672 These functions must take a single argument, the link content.
9673 They will be called for links that look like [[link text][description]]
9674 when LINK TEXT does not have a protocol like \"http:\" and does not look
9675 like a filename (e.g. \"./blue.png\").
9677 These functions will be called *before* Org attempts to resolve the
9678 link by doing text searches in the current buffer - so if you want a
9679 link \"[[target]]\" to still find \"<<target>>\", your function should
9680 handle this as a special case.
9682 When the function does handle the link, it must return a non-nil value.
9683 If it decides that it is not responsible for this link, it must return
9684 nil to indicate that that Org-mode can continue with other options
9685 like exact and fuzzy text search.")
9687 (defun org-next-link ()
9688 "Move forward to the next link.
9689 If the link is in hidden text, expose it."
9690 (interactive)
9691 (when (and org-link-search-failed (eq this-command last-command))
9692 (goto-char (point-min))
9693 (message "Link search wrapped back to beginning of buffer"))
9694 (setq org-link-search-failed nil)
9695 (let* ((pos (point))
9696 (ct (org-context))
9697 (a (assoc :link ct)))
9698 (if a (goto-char (nth 2 a)))
9699 (if (re-search-forward org-any-link-re nil t)
9700 (progn
9701 (goto-char (match-beginning 0))
9702 (if (outline-invisible-p) (org-show-context)))
9703 (goto-char pos)
9704 (setq org-link-search-failed t)
9705 (error "No further link found"))))
9707 (defun org-previous-link ()
9708 "Move backward to the previous link.
9709 If the link is in hidden text, expose it."
9710 (interactive)
9711 (when (and org-link-search-failed (eq this-command last-command))
9712 (goto-char (point-max))
9713 (message "Link search wrapped back to end of buffer"))
9714 (setq org-link-search-failed nil)
9715 (let* ((pos (point))
9716 (ct (org-context))
9717 (a (assoc :link ct)))
9718 (if a (goto-char (nth 1 a)))
9719 (if (re-search-backward org-any-link-re nil t)
9720 (progn
9721 (goto-char (match-beginning 0))
9722 (if (outline-invisible-p) (org-show-context)))
9723 (goto-char pos)
9724 (setq org-link-search-failed t)
9725 (error "No further link found"))))
9727 (defun org-translate-link (s)
9728 "Translate a link string if a translation function has been defined."
9729 (if (and org-link-translation-function
9730 (fboundp org-link-translation-function)
9731 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9732 (progn
9733 (setq s (funcall org-link-translation-function
9734 (match-string 1 s) (match-string 2 s)))
9735 (concat (car s) ":" (cdr s)))
9738 (defun org-translate-link-from-planner (type path)
9739 "Translate a link from Emacs Planner syntax so that Org can follow it.
9740 This is still an experimental function, your mileage may vary."
9741 (cond
9742 ((member type '("http" "https" "news" "ftp"))
9743 ;; standard Internet links are the same.
9744 nil)
9745 ((and (equal type "irc") (string-match "^//" path))
9746 ;; Planner has two / at the beginning of an irc link, we have 1.
9747 ;; We should have zero, actually....
9748 (setq path (substring path 1)))
9749 ((and (equal type "lisp") (string-match "^/" path))
9750 ;; Planner has a slash, we do not.
9751 (setq type "elisp" path (substring path 1)))
9752 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9753 ;; A typical message link. Planner has the id after the final slash,
9754 ;; we separate it with a hash mark
9755 (setq path (concat (match-string 1 path) "#"
9756 (org-remove-angle-brackets (match-string 2 path)))))
9758 (cons type path))
9760 (defun org-find-file-at-mouse (ev)
9761 "Open file link or URL at mouse."
9762 (interactive "e")
9763 (mouse-set-point ev)
9764 (org-open-at-point 'in-emacs))
9766 (defun org-open-at-mouse (ev)
9767 "Open file link or URL at mouse.
9768 See the docstring of `org-open-file' for details."
9769 (interactive "e")
9770 (mouse-set-point ev)
9771 (if (eq major-mode 'org-agenda-mode)
9772 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9773 (org-open-at-point))
9775 (defvar org-window-config-before-follow-link nil
9776 "The window configuration before following a link.
9777 This is saved in case the need arises to restore it.")
9779 (defvar org-open-link-marker (make-marker)
9780 "Marker pointing to the location where `org-open-at-point; was called.")
9782 ;;;###autoload
9783 (defun org-open-at-point-global ()
9784 "Follow a link like Org-mode does.
9785 This command can be called in any mode to follow a link that has
9786 Org-mode syntax."
9787 (interactive)
9788 (org-run-like-in-org-mode 'org-open-at-point))
9790 ;;;###autoload
9791 (defun org-open-link-from-string (s &optional arg reference-buffer)
9792 "Open a link in the string S, as if it was in Org-mode."
9793 (interactive "sLink: \nP")
9794 (let ((reference-buffer (or reference-buffer (current-buffer))))
9795 (with-temp-buffer
9796 (let ((org-inhibit-startup (not reference-buffer)))
9797 (org-mode)
9798 (insert s)
9799 (goto-char (point-min))
9800 (when reference-buffer
9801 (setq org-link-abbrev-alist-local
9802 (with-current-buffer reference-buffer
9803 org-link-abbrev-alist-local)))
9804 (org-open-at-point arg reference-buffer)))))
9806 (defvar org-open-at-point-functions nil
9807 "Hook that is run when following a link at point.
9809 Functions in this hook must return t if they identify and follow
9810 a link at point. If they don't find anything interesting at point,
9811 they must return nil.")
9813 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9814 (defun org-open-at-point (&optional arg reference-buffer)
9815 "Open link at or after point.
9816 If there is no link at point, this function will search forward up to
9817 the end of the current line.
9818 Normally, files will be opened by an appropriate application. If the
9819 optional prefix argument ARG is non-nil, Emacs will visit the file.
9820 With a double prefix argument, try to open outside of Emacs, in the
9821 application the system uses for this file type."
9822 (interactive "P")
9823 ;; if in a code block, then open the block's results
9824 (unless (call-interactively #'org-babel-open-src-block-result)
9825 (org-load-modules-maybe)
9826 (move-marker org-open-link-marker (point))
9827 (setq org-window-config-before-follow-link (current-window-configuration))
9828 (org-remove-occur-highlights nil nil t)
9829 (cond
9830 ((and (org-at-heading-p)
9831 (not (org-at-timestamp-p t))
9832 (not (org-in-regexp
9833 (concat org-plain-link-re "\\|"
9834 org-bracket-link-regexp "\\|"
9835 org-angle-link-re "\\|"
9836 "[ \t]:[^ \t\n]+:[ \t]*$")))
9837 (not (get-text-property (point) 'org-linked-text)))
9838 (or (org-offer-links-in-entry arg)
9839 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9840 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9841 ((and (org-at-timestamp-p t)
9842 (not (org-in-regexp org-bracket-link-regexp)))
9843 (org-follow-timestamp-link))
9844 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9845 (not (org-in-regexp org-any-link-re)))
9846 (org-footnote-action))
9848 (let (type path link line search (pos (point)))
9849 (catch 'match
9850 (save-excursion
9851 (skip-chars-forward "^]\n\r")
9852 (when (org-in-regexp org-bracket-link-regexp 1)
9853 (setq link (org-extract-attributes
9854 (org-link-unescape (org-match-string-no-properties 1))))
9855 (while (string-match " *\n *" link)
9856 (setq link (replace-match " " t t link)))
9857 (setq link (org-link-expand-abbrev link))
9858 (cond
9859 ((or (file-name-absolute-p link)
9860 (string-match "^\\.\\.?/" link))
9861 (setq type "file" path link))
9862 ((string-match org-link-re-with-space3 link)
9863 (setq type (match-string 1 link) path (match-string 2 link)))
9864 ((string-match "^help:+\\(.+\\)" link)
9865 (setq type "help" path (match-string 1 link)))
9866 (t (setq type "thisfile" path link)))
9867 (throw 'match t)))
9869 (when (get-text-property (point) 'org-linked-text)
9870 (setq type "thisfile"
9871 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9872 (1+ (point)) (point))
9873 path (buffer-substring
9874 (or (previous-single-property-change pos 'org-linked-text)
9875 (point-min))
9876 (or (next-single-property-change pos 'org-linked-text)
9877 (point-max))))
9878 (throw 'match t))
9880 (save-excursion
9881 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9882 (when (or (org-in-regexp org-angle-link-re)
9883 (and plinkpos (goto-char (car plinkpos))
9884 (save-match-data (not (looking-back "\\[\\[")))))
9885 (setq type (match-string 1)
9886 path (org-link-unescape (match-string 2)))
9887 (throw 'match t))))
9888 (save-excursion
9889 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9890 (setq type "tags"
9891 path (match-string 1))
9892 (while (string-match ":" path)
9893 (setq path (replace-match "+" t t path)))
9894 (throw 'match t)))
9895 (when (org-in-regexp "<\\([^><\n]+\\)>")
9896 (setq type "tree-match"
9897 path (match-string 1))
9898 (throw 'match t)))
9899 (unless path
9900 (user-error "No link found"))
9902 ;; switch back to reference buffer
9903 ;; needed when if called in a temporary buffer through
9904 ;; org-open-link-from-string
9905 (with-current-buffer (or reference-buffer (current-buffer))
9907 ;; Remove any trailing spaces in path
9908 (if (string-match " +\\'" path)
9909 (setq path (replace-match "" t t path)))
9910 (if (and org-link-translation-function
9911 (fboundp org-link-translation-function))
9912 ;; Check if we need to translate the link
9913 (let ((tmp (funcall org-link-translation-function type path)))
9914 (setq type (car tmp) path (cdr tmp))))
9916 (cond
9918 ((assoc type org-link-protocols)
9919 (funcall (nth 1 (assoc type org-link-protocols)) path))
9921 ((equal type "help")
9922 (let ((f-or-v (intern path)))
9923 (cond ((fboundp f-or-v)
9924 (describe-function f-or-v))
9925 ((boundp f-or-v)
9926 (describe-variable f-or-v))
9927 (t (error "Not a known function or variable")))))
9929 ((equal type "mailto")
9930 (let ((cmd (car org-link-mailto-program))
9931 (args (cdr org-link-mailto-program)) args1
9932 (address path) (subject "") a)
9933 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9934 (setq address (match-string 1 path)
9935 subject (org-link-escape (match-string 2 path))))
9936 (while args
9937 (cond
9938 ((not (stringp (car args))) (push (pop args) args1))
9939 (t (setq a (pop args))
9940 (if (string-match "%a" a)
9941 (setq a (replace-match address t t a)))
9942 (if (string-match "%s" a)
9943 (setq a (replace-match subject t t a)))
9944 (push a args1))))
9945 (apply cmd (nreverse args1))))
9947 ((member type '("http" "https" "ftp" "news"))
9948 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9949 (org-link-escape
9950 path org-link-escape-chars-browser)
9951 path))))
9953 ((string= type "doi")
9954 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9955 (org-link-escape
9956 path org-link-escape-chars-browser)
9957 path))))
9959 ((member type '("message"))
9960 (browse-url (concat type ":" path)))
9962 ((string= type "tags")
9963 (org-tags-view arg path))
9965 ((string= type "tree-match")
9966 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9968 ((string= type "file")
9969 (if (string-match "::\\([0-9]+\\)\\'" path)
9970 (setq line (string-to-number (match-string 1 path))
9971 path (substring path 0 (match-beginning 0)))
9972 (if (string-match "::\\(.+\\)\\'" path)
9973 (setq search (match-string 1 path)
9974 path (substring path 0 (match-beginning 0)))))
9975 (if (string-match "[*?{]" (file-name-nondirectory path))
9976 (dired path)
9977 (org-open-file path arg line search)))
9979 ((string= type "shell")
9980 (let ((buf (generate-new-buffer "*Org Shell Output"))
9981 (cmd path))
9982 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9983 (string-match org-confirm-shell-link-not-regexp cmd))
9984 (not org-confirm-shell-link-function)
9985 (funcall org-confirm-shell-link-function
9986 (format "Execute \"%s\" in shell? "
9987 (org-add-props cmd nil
9988 'face 'org-warning))))
9989 (progn
9990 (message "Executing %s" cmd)
9991 (shell-command cmd buf)
9992 (if (featurep 'midnight)
9993 (setq clean-buffer-list-kill-buffer-names
9994 (cons buf clean-buffer-list-kill-buffer-names))))
9995 (error "Abort"))))
9997 ((string= type "elisp")
9998 (let ((cmd path))
9999 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10000 (string-match org-confirm-elisp-link-not-regexp cmd))
10001 (not org-confirm-elisp-link-function)
10002 (funcall org-confirm-elisp-link-function
10003 (format "Execute \"%s\" as elisp? "
10004 (org-add-props cmd nil
10005 'face 'org-warning))))
10006 (message "%s => %s" cmd
10007 (if (equal (string-to-char cmd) ?\()
10008 (eval (read cmd))
10009 (call-interactively (read cmd))))
10010 (error "Abort"))))
10012 ((and (string= type "thisfile")
10013 (run-hook-with-args-until-success
10014 'org-open-link-functions path)))
10016 ((string= type "thisfile")
10017 (if arg
10018 (switch-to-buffer-other-window
10019 (org-get-buffer-for-internal-link (current-buffer)))
10020 (org-mark-ring-push))
10021 (let ((cmd `(org-link-search
10022 ,path
10023 ,(cond ((equal arg '(4)) ''occur)
10024 ((equal arg '(16)) ''org-occur))
10025 ,pos)))
10026 (condition-case nil (let ((org-link-search-inhibit-query t))
10027 (eval cmd))
10028 (error (progn (widen) (eval cmd))))))
10030 (t (browse-url-at-point)))))))
10031 (move-marker org-open-link-marker nil)
10032 (run-hook-with-args 'org-follow-link-hook)))
10034 (defun org-offer-links-in-entry (&optional nth zero)
10035 "Offer links in the current entry and follow the selected link.
10036 If there is only one link, follow it immediately as well.
10037 If NTH is an integer, immediately pick the NTH link found.
10038 If ZERO is a string, check also this string for a link, and if
10039 there is one, offer it as link number zero."
10040 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10041 "\\(" org-angle-link-re "\\)\\|"
10042 "\\(" org-plain-link-re "\\)"))
10043 (cnt ?0)
10044 (in-emacs (if (integerp nth) nil nth))
10045 have-zero end links link c)
10046 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10047 (push (match-string 0 zero) links)
10048 (setq cnt (1- cnt) have-zero t))
10049 (save-excursion
10050 (org-back-to-heading t)
10051 (setq end (save-excursion (outline-next-heading) (point)))
10052 (while (re-search-forward re end t)
10053 (push (match-string 0) links))
10054 (setq links (org-uniquify (reverse links))))
10056 (cond
10057 ((null links)
10058 (message "No links"))
10059 ((equal (length links) 1)
10060 (setq link (list (car links))))
10061 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10062 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10063 (t ; we have to select a link
10064 (save-excursion
10065 (save-window-excursion
10066 (delete-other-windows)
10067 (with-output-to-temp-buffer "*Select Link*"
10068 (mapc (lambda (l)
10069 (if (not (string-match org-bracket-link-regexp l))
10070 (princ (format "[%c] %s\n" (incf cnt)
10071 (org-remove-angle-brackets l)))
10072 (if (match-end 3)
10073 (princ (format "[%c] %s (%s)\n" (incf cnt)
10074 (match-string 3 l) (match-string 1 l)))
10075 (princ (format "[%c] %s\n" (incf cnt)
10076 (match-string 1 l))))))
10077 links))
10078 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10079 (message "Select link to open, RET to open all:")
10080 (setq c (read-char-exclusive))
10081 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10082 (when (equal c ?q) (error "Abort"))
10083 (if (equal c ?\C-m)
10084 (setq link links)
10085 (setq nth (- c ?0))
10086 (if have-zero (setq nth (1+ nth)))
10087 (unless (and (integerp nth) (>= (length links) nth))
10088 (error "Invalid link selection"))
10089 (setq link (list (nth (1- nth) links))))))
10090 (if link
10091 (let ((buf (current-buffer)))
10092 (dolist (l link)
10093 (org-open-link-from-string l in-emacs buf))
10095 nil)))
10097 ;; Add special file links that specify the way of opening
10099 (org-add-link-type "file+sys" 'org-open-file-with-system)
10100 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10101 (defun org-open-file-with-system (path)
10102 "Open file at PATH using the system way of opening it."
10103 (org-open-file path 'system))
10104 (defun org-open-file-with-emacs (path)
10105 "Open file at PATH in Emacs."
10106 (org-open-file path 'emacs))
10107 (defun org-remove-file-link-modifiers ()
10108 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10109 (goto-char (point-min))
10110 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10111 (org-if-unprotected
10112 (replace-match "file:" t t))))
10113 (eval-after-load "org-exp"
10114 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10115 'org-remove-file-link-modifiers))
10117 ;;;; Time estimates
10119 (defun org-get-effort (&optional pom)
10120 "Get the effort estimate for the current entry."
10121 (org-entry-get pom org-effort-property))
10123 ;;; File search
10125 (defvar org-create-file-search-functions nil
10126 "List of functions to construct the right search string for a file link.
10127 These functions are called in turn with point at the location to
10128 which the link should point.
10130 A function in the hook should first test if it would like to
10131 handle this file type, for example by checking the `major-mode'
10132 or the file extension. If it decides not to handle this file, it
10133 should just return nil to give other functions a chance. If it
10134 does handle the file, it must return the search string to be used
10135 when following the link. The search string will be part of the
10136 file link, given after a double colon, and `org-open-at-point'
10137 will automatically search for it. If special measures must be
10138 taken to make the search successful, another function should be
10139 added to the companion hook `org-execute-file-search-functions',
10140 which see.
10142 A function in this hook may also use `setq' to set the variable
10143 `description' to provide a suggestion for the descriptive text to
10144 be used for this link when it gets inserted into an Org-mode
10145 buffer with \\[org-insert-link].")
10147 (defvar org-execute-file-search-functions nil
10148 "List of functions to execute a file search triggered by a link.
10150 Functions added to this hook must accept a single argument, the
10151 search string that was part of the file link, the part after the
10152 double colon. The function must first check if it would like to
10153 handle this search, for example by checking the `major-mode' or
10154 the file extension. If it decides not to handle this search, it
10155 should just return nil to give other functions a chance. If it
10156 does handle the search, it must return a non-nil value to keep
10157 other functions from trying.
10159 Each function can access the current prefix argument through the
10160 variable `current-prefix-argument'. Note that a single prefix is
10161 used to force opening a link in Emacs, so it may be good to only
10162 use a numeric or double prefix to guide the search function.
10164 In case this is needed, a function in this hook can also restore
10165 the window configuration before `org-open-at-point' was called using:
10167 (set-window-configuration org-window-config-before-follow-link)")
10169 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10170 (defun org-link-search (s &optional type avoid-pos stealth)
10171 "Search for a link search option.
10172 If S is surrounded by forward slashes, it is interpreted as a
10173 regular expression. In org-mode files, this will create an `org-occur'
10174 sparse tree. In ordinary files, `occur' will be used to list matches.
10175 If the current buffer is in `dired-mode', grep will be used to search
10176 in all files. If AVOID-POS is given, ignore matches near that position.
10178 When optional argument STEALTH is non-nil, do not modify
10179 visibility around point, thus ignoring
10180 `org-show-hierarchy-above', `org-show-following-heading' and
10181 `org-show-siblings' variables."
10182 (let ((case-fold-search t)
10183 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10184 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10185 (append '(("") (" ") ("\t") ("\n"))
10186 org-emphasis-alist)
10187 "\\|") "\\)"))
10188 (pos (point))
10189 (pre nil) (post nil)
10190 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10191 (cond
10192 ;; First check if there are any special search functions
10193 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10194 ;; Now try the builtin stuff
10195 ((and (equal (string-to-char s0) ?#)
10196 (> (length s0) 1)
10197 (save-excursion
10198 (goto-char (point-min))
10199 (and
10200 (re-search-forward
10201 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10202 (setq type 'dedicated
10203 pos (match-beginning 0))))
10204 ;; There is an exact target for this
10205 (goto-char pos)
10206 (org-back-to-heading t)))
10207 ((save-excursion
10208 (goto-char (point-min))
10209 (and
10210 (re-search-forward
10211 (concat "<<" (regexp-quote s0) ">>") nil t)
10212 (setq type 'dedicated
10213 pos (match-beginning 0))))
10214 ;; There is an exact target for this
10215 (goto-char pos))
10216 ((save-excursion
10217 (goto-char (point-min))
10218 (and
10219 (re-search-forward
10220 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10221 (setq type 'dedicated pos (match-beginning 0))))
10222 ;; Found an invisible target.
10223 (goto-char pos))
10224 ((save-excursion
10225 (goto-char (point-min))
10226 (and
10227 (re-search-forward
10228 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10229 (setq type 'dedicated pos (match-beginning 0))))
10230 ;; Found an element with a matching #+name affiliated keyword.
10231 (goto-char pos))
10232 ((and (string-match "^(\\(.*\\))$" s0)
10233 (save-excursion
10234 (goto-char (point-min))
10235 (and
10236 (re-search-forward
10237 (concat "[^[]" (regexp-quote
10238 (format org-coderef-label-format
10239 (match-string 1 s0))))
10240 nil t)
10241 (setq type 'dedicated
10242 pos (1+ (match-beginning 0))))))
10243 ;; There is a coderef target for this
10244 (goto-char pos))
10245 ((string-match "^/\\(.*\\)/$" s)
10246 ;; A regular expression
10247 (cond
10248 ((derived-mode-p 'org-mode)
10249 (org-occur (match-string 1 s)))
10250 ;;((eq major-mode 'dired-mode)
10251 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10252 (t (org-do-occur (match-string 1 s)))))
10253 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10254 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10255 (goto-char (point-min))
10256 (cond
10257 ((let (case-fold-search)
10258 (re-search-forward (format org-complex-heading-regexp-format
10259 (regexp-quote s))
10260 nil t))
10261 ;; OK, found a match
10262 (setq type 'dedicated)
10263 (goto-char (match-beginning 0)))
10264 ((and (not org-link-search-inhibit-query)
10265 (eq org-link-search-must-match-exact-headline 'query-to-create)
10266 (y-or-n-p "No match - create this as a new heading? "))
10267 (goto-char (point-max))
10268 (or (bolp) (newline))
10269 (insert "* " s "\n")
10270 (beginning-of-line 0))
10272 (goto-char pos)
10273 (error "No match"))))
10275 ;; A normal search string
10276 (when (equal (string-to-char s) ?*)
10277 ;; Anchor on headlines, post may include tags.
10278 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10279 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10280 s (substring s 1)))
10281 (remove-text-properties
10282 0 (length s)
10283 '(face nil mouse-face nil keymap nil fontified nil) s)
10284 ;; Make a series of regular expressions to find a match
10285 (setq words (org-split-string s "[ \n\r\t]+")
10287 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10288 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10289 "\\)" markers)
10290 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10291 re2a (concat "[ \t\r\n]" re2a_)
10292 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10293 re4 (concat "[^a-zA-Z_]" re4_)
10295 re1 (concat pre re2 post)
10296 re3 (concat pre (if pre re4_ re4) post)
10297 re5 (concat pre ".*" re4)
10298 re2 (concat pre re2)
10299 re2a (concat pre (if pre re2a_ re2a))
10300 re4 (concat pre (if pre re4_ re4))
10301 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10302 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10303 re5 "\\)"
10305 (cond
10306 ((eq type 'org-occur) (org-occur reall))
10307 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10308 (t (goto-char (point-min))
10309 (setq type 'fuzzy)
10310 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10311 (org-search-not-self 1 re1 nil t)
10312 (org-search-not-self 1 re2 nil t)
10313 (org-search-not-self 1 re2a nil t)
10314 (org-search-not-self 1 re3 nil t)
10315 (org-search-not-self 1 re4 nil t)
10316 (org-search-not-self 1 re5 nil t)
10318 (goto-char (match-beginning 1))
10319 (goto-char pos)
10320 (error "No match"))))))
10321 (and (derived-mode-p 'org-mode)
10322 (not stealth)
10323 (org-show-context 'link-search))
10324 type))
10326 (defun org-search-not-self (group &rest args)
10327 "Execute `re-search-forward', but only accept matches that do not
10328 enclose the position of `org-open-link-marker'."
10329 (let ((m org-open-link-marker))
10330 (catch 'exit
10331 (while (apply 're-search-forward args)
10332 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10333 (goto-char (match-end group))
10334 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10335 (> (match-beginning 0) (marker-position m))
10336 (< (match-end 0) (marker-position m)))
10337 (save-match-data
10338 (or (not (org-in-regexp
10339 org-bracket-link-analytic-regexp 1))
10340 (not (match-end 4)) ; no description
10341 (and (<= (match-beginning 4) (point))
10342 (>= (match-end 4) (point))))))
10343 (throw 'exit (point))))))))
10345 (defun org-get-buffer-for-internal-link (buffer)
10346 "Return a buffer to be used for displaying the link target of internal links."
10347 (cond
10348 ((not org-display-internal-link-with-indirect-buffer)
10349 buffer)
10350 ((string-match "(Clone)$" (buffer-name buffer))
10351 (message "Buffer is already a clone, not making another one")
10352 ;; we also do not modify visibility in this case
10353 buffer)
10354 (t ; make a new indirect buffer for displaying the link
10355 (let* ((bn (buffer-name buffer))
10356 (ibn (concat bn "(Clone)"))
10357 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10358 (with-current-buffer ib (org-overview))
10359 ib))))
10361 (defun org-do-occur (regexp &optional cleanup)
10362 "Call the Emacs command `occur'.
10363 If CLEANUP is non-nil, remove the printout of the regular expression
10364 in the *Occur* buffer. This is useful if the regex is long and not useful
10365 to read."
10366 (occur regexp)
10367 (when cleanup
10368 (let ((cwin (selected-window)) win beg end)
10369 (when (setq win (get-buffer-window "*Occur*"))
10370 (select-window win))
10371 (goto-char (point-min))
10372 (when (re-search-forward "match[a-z]+" nil t)
10373 (setq beg (match-end 0))
10374 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10375 (setq end (1- (match-beginning 0)))))
10376 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10377 (goto-char (point-min))
10378 (select-window cwin))))
10380 ;;; The mark ring for links jumps
10382 (defvar org-mark-ring nil
10383 "Mark ring for positions before jumps in Org-mode.")
10384 (defvar org-mark-ring-last-goto nil
10385 "Last position in the mark ring used to go back.")
10386 ;; Fill and close the ring
10387 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10388 (loop for i from 1 to org-mark-ring-length do
10389 (push (make-marker) org-mark-ring))
10390 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10391 org-mark-ring)
10393 (defun org-mark-ring-push (&optional pos buffer)
10394 "Put the current position or POS into the mark ring and rotate it."
10395 (interactive)
10396 (setq pos (or pos (point)))
10397 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10398 (move-marker (car org-mark-ring)
10399 (or pos (point))
10400 (or buffer (current-buffer)))
10401 (message "%s"
10402 (substitute-command-keys
10403 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10405 (defun org-mark-ring-goto (&optional n)
10406 "Jump to the previous position in the mark ring.
10407 With prefix arg N, jump back that many stored positions. When
10408 called several times in succession, walk through the entire ring.
10409 Org-mode commands jumping to a different position in the current file,
10410 or to another Org-mode file, automatically push the old position
10411 onto the ring."
10412 (interactive "p")
10413 (let (p m)
10414 (if (eq last-command this-command)
10415 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10416 (setq p org-mark-ring))
10417 (setq org-mark-ring-last-goto p)
10418 (setq m (car p))
10419 (org-pop-to-buffer-same-window (marker-buffer m))
10420 (goto-char m)
10421 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10423 (defun org-remove-angle-brackets (s)
10424 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10425 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10427 (defun org-add-angle-brackets (s)
10428 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10429 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10431 (defun org-remove-double-quotes (s)
10432 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10433 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10436 ;;; Following specific links
10438 (defun org-follow-timestamp-link ()
10439 "Open an agenda view for the time-stamp date/range at point."
10440 (cond
10441 ((org-at-date-range-p t)
10442 (let ((org-agenda-start-on-weekday)
10443 (t1 (match-string 1))
10444 (t2 (match-string 2)) tt1 tt2)
10445 (setq tt1 (time-to-days (org-time-string-to-time t1))
10446 tt2 (time-to-days (org-time-string-to-time t2)))
10447 (let ((org-agenda-buffer-tmp-name
10448 (format "*Org Agenda(a:%s)"
10449 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10450 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10451 ((org-at-timestamp-p t)
10452 (let ((org-agenda-buffer-tmp-name
10453 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10454 (org-agenda-list nil (time-to-days (org-time-string-to-time
10455 (substring (match-string 1) 0 10)))
10456 1)))
10457 (t (error "This should not happen"))))
10460 ;;; Following file links
10461 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10462 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10463 (declare-function mailcap-mime-info
10464 "mailcap" (string &optional request no-decode))
10465 (defvar org-wait nil)
10466 (defun org-open-file (path &optional in-emacs line search)
10467 "Open the file at PATH.
10468 First, this expands any special file name abbreviations. Then the
10469 configuration variable `org-file-apps' is checked if it contains an
10470 entry for this file type, and if yes, the corresponding command is launched.
10472 If no application is found, Emacs simply visits the file.
10474 With optional prefix argument IN-EMACS, Emacs will visit the file.
10475 With a double \\[universal-argument] \\[universal-argument] \
10476 prefix arg, Org tries to avoid opening in Emacs
10477 and to use an external application to visit the file.
10479 Optional LINE specifies a line to go to, optional SEARCH a string
10480 to search for. If LINE or SEARCH is given, the file will be
10481 opened in Emacs, unless an entry from org-file-apps that makes
10482 use of groups in a regexp matches.
10484 If you want to change the way frames are used when following a
10485 link, please customize `org-link-frame-setup'.
10487 If the file does not exist, an error is thrown."
10488 (let* ((file (if (equal path "")
10489 buffer-file-name
10490 (substitute-in-file-name (expand-file-name path))))
10491 (file-apps (append org-file-apps (org-default-apps)))
10492 (apps (org-remove-if
10493 'org-file-apps-entry-match-against-dlink-p file-apps))
10494 (apps-dlink (org-remove-if-not
10495 'org-file-apps-entry-match-against-dlink-p file-apps))
10496 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10497 (dirp (if remp nil (file-directory-p file)))
10498 (file (if (and dirp org-open-directory-means-index-dot-org)
10499 (concat (file-name-as-directory file) "index.org")
10500 file))
10501 (a-m-a-p (assq 'auto-mode apps))
10502 (dfile (downcase file))
10503 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10504 (link (cond ((and (eq line nil)
10505 (eq search nil))
10506 file)
10507 (line
10508 (concat file "::" (number-to-string line)))
10509 (search
10510 (concat file "::" search))))
10511 (dlink (downcase link))
10512 (old-buffer (current-buffer))
10513 (old-pos (point))
10514 (old-mode major-mode)
10515 ext cmd link-match-data)
10516 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10517 (setq ext (match-string 1 dfile))
10518 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10519 (setq ext (match-string 1 dfile))))
10520 (cond
10521 ((member in-emacs '((16) system))
10522 (setq cmd (cdr (assoc 'system apps))))
10523 (in-emacs (setq cmd 'emacs))
10525 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10526 (and dirp (cdr (assoc 'directory apps)))
10527 ; first, try matching against apps-dlink
10528 ; if we get a match here, store the match data for later
10529 (let ((match (assoc-default dlink apps-dlink
10530 'string-match)))
10531 (if match
10532 (progn (setq link-match-data (match-data))
10533 match)
10534 (progn (setq in-emacs (or in-emacs line search))
10535 nil))) ; if we have no match in apps-dlink,
10536 ; always open the file in emacs if line or search
10537 ; is given (for backwards compatibility)
10538 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10539 'string-match)
10540 (cdr (assoc ext apps))
10541 (cdr (assoc t apps))))))
10542 (when (eq cmd 'system)
10543 (setq cmd (cdr (assoc 'system apps))))
10544 (when (eq cmd 'default)
10545 (setq cmd (cdr (assoc t apps))))
10546 (when (eq cmd 'mailcap)
10547 (require 'mailcap)
10548 (mailcap-parse-mailcaps)
10549 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10550 (command (mailcap-mime-info mime-type)))
10551 (if (stringp command)
10552 (setq cmd command)
10553 (setq cmd 'emacs))))
10554 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10555 (not (file-exists-p file))
10556 (not org-open-non-existing-files))
10557 (error "No such file: %s" file))
10558 (cond
10559 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10560 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10561 (while (string-match "['\"]%s['\"]" cmd)
10562 (setq cmd (replace-match "%s" t t cmd)))
10563 (while (string-match "%s" cmd)
10564 (setq cmd (replace-match
10565 (save-match-data
10566 (shell-quote-argument
10567 (convert-standard-filename file)))
10568 t t cmd)))
10570 ;; Replace "%1", "%2" etc. in command with group matches from regex
10571 (save-match-data
10572 (let ((match-index 1)
10573 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10574 (set-match-data link-match-data)
10575 (while (<= match-index number-of-groups)
10576 (let ((regex (concat "%" (number-to-string match-index)))
10577 (replace-with (match-string match-index dlink)))
10578 (while (string-match regex cmd)
10579 (setq cmd (replace-match replace-with t t cmd))))
10580 (setq match-index (+ match-index 1)))))
10582 (save-window-excursion
10583 (message "Running %s...done" cmd)
10584 (start-process-shell-command cmd nil cmd)
10585 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10586 ((or (stringp cmd)
10587 (eq cmd 'emacs))
10588 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10589 (widen)
10590 (if line (org-goto-line line)
10591 (if search (org-link-search search))))
10592 ((consp cmd)
10593 (let ((file (convert-standard-filename file)))
10594 (save-match-data
10595 (set-match-data link-match-data)
10596 (eval cmd))))
10597 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10598 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10599 (or (not (equal old-buffer (current-buffer)))
10600 (not (equal old-pos (point))))
10601 (org-mark-ring-push old-pos old-buffer))))
10603 (defun org-file-apps-entry-match-against-dlink-p (entry)
10604 "This function returns non-nil if `entry' uses a regular
10605 expression which should be matched against the whole link by
10606 org-open-file.
10608 It assumes that is the case when the entry uses a regular
10609 expression which has at least one grouping construct and the
10610 action is either a lisp form or a command string containing
10611 '%1', i.e. using at least one subexpression match as a
10612 parameter."
10613 (let ((selector (car entry))
10614 (action (cdr entry)))
10615 (if (stringp selector)
10616 (and (> (regexp-opt-depth selector) 0)
10617 (or (and (stringp action)
10618 (string-match "%[0-9]" action))
10619 (consp action)))
10620 nil)))
10622 (defun org-default-apps ()
10623 "Return the default applications for this operating system."
10624 (cond
10625 ((eq system-type 'darwin)
10626 org-file-apps-defaults-macosx)
10627 ((eq system-type 'windows-nt)
10628 org-file-apps-defaults-windowsnt)
10629 (t org-file-apps-defaults-gnu)))
10631 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10632 "Convert extensions to regular expressions in the cars of LIST.
10633 Also, weed out any non-string entries, because the return value is used
10634 only for regexp matching.
10635 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10636 point to the symbol `emacs', indicating that the file should
10637 be opened in Emacs."
10638 (append
10639 (delq nil
10640 (mapcar (lambda (x)
10641 (if (not (stringp (car x)))
10643 (if (string-match "\\W" (car x))
10645 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10646 list))
10647 (if add-auto-mode
10648 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10650 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10651 (defun org-file-remote-p (file)
10652 "Test whether FILE specifies a location on a remote system.
10653 Return non-nil if the location is indeed remote.
10655 For example, the filename \"/user@host:/foo\" specifies a location
10656 on the system \"/user@host:\"."
10657 (cond ((fboundp 'file-remote-p)
10658 (file-remote-p file))
10659 ((fboundp 'tramp-handle-file-remote-p)
10660 (tramp-handle-file-remote-p file))
10661 ((and (boundp 'ange-ftp-name-format)
10662 (string-match (car ange-ftp-name-format) file))
10663 t)))
10666 ;;;; Refiling
10668 (defun org-get-org-file ()
10669 "Read a filename, with default directory `org-directory'."
10670 (let ((default (or org-default-notes-file remember-data-file)))
10671 (read-file-name (format "File name [%s]: " default)
10672 (file-name-as-directory org-directory)
10673 default)))
10675 (defun org-notes-order-reversed-p ()
10676 "Check if the current file should receive notes in reversed order."
10677 (cond
10678 ((not org-reverse-note-order) nil)
10679 ((eq t org-reverse-note-order) t)
10680 ((not (listp org-reverse-note-order)) nil)
10681 (t (catch 'exit
10682 (let ((all org-reverse-note-order)
10683 entry)
10684 (while (setq entry (pop all))
10685 (if (string-match (car entry) buffer-file-name)
10686 (throw 'exit (cdr entry))))
10687 nil)))))
10689 (defvar org-refile-target-table nil
10690 "The list of refile targets, created by `org-refile'.")
10692 (defvar org-agenda-new-buffers nil
10693 "Buffers created to visit agenda files.")
10695 (defvar org-refile-cache nil
10696 "Cache for refile targets.")
10698 (defvar org-refile-markers nil
10699 "All the markers used for caching refile locations.")
10701 (defun org-refile-marker (pos)
10702 "Get a new refile marker, but only if caching is in use."
10703 (if (not org-refile-use-cache)
10705 (let ((m (make-marker)))
10706 (move-marker m pos)
10707 (push m org-refile-markers)
10708 m)))
10710 (defun org-refile-cache-clear ()
10711 "Clear the refile cache and disable all the markers."
10712 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10713 (setq org-refile-markers nil)
10714 (setq org-refile-cache nil)
10715 (message "Refile cache has been cleared"))
10717 (defun org-refile-cache-check-set (set)
10718 "Check if all the markers in the cache still have live buffers."
10719 (let (marker)
10720 (catch 'exit
10721 (while (and set (setq marker (nth 3 (pop set))))
10722 ;; if org-refile-use-outline-path is 'file, marker may be nil
10723 (when (and marker (null (marker-buffer marker)))
10724 (message "not found") (sit-for 3)
10725 (throw 'exit nil)))
10726 t)))
10728 (defun org-refile-cache-put (set &rest identifiers)
10729 "Push the refile targets SET into the cache, under IDENTIFIERS."
10730 (let* ((key (sha1 (prin1-to-string identifiers)))
10731 (entry (assoc key org-refile-cache)))
10732 (if entry
10733 (setcdr entry set)
10734 (push (cons key set) org-refile-cache))))
10736 (defun org-refile-cache-get (&rest identifiers)
10737 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10738 (cond
10739 ((not org-refile-cache) nil)
10740 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10742 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10743 org-refile-cache))))
10744 (and set (org-refile-cache-check-set set) set)))))
10746 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10747 "Produce a table with refile targets."
10748 (let ((case-fold-search nil)
10749 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10750 (entries (or org-refile-targets '((nil . (:level . 1)))))
10751 targets tgs txt re files f desc descre fast-path-p level pos0)
10752 (message "Getting targets...")
10753 (with-current-buffer (or default-buffer (current-buffer))
10754 (while (setq entry (pop entries))
10755 (setq files (car entry) desc (cdr entry))
10756 (setq fast-path-p nil)
10757 (cond
10758 ((null files) (setq files (list (current-buffer))))
10759 ((eq files 'org-agenda-files)
10760 (setq files (org-agenda-files 'unrestricted)))
10761 ((and (symbolp files) (fboundp files))
10762 (setq files (funcall files)))
10763 ((and (symbolp files) (boundp files))
10764 (setq files (symbol-value files))))
10765 (if (stringp files) (setq files (list files)))
10766 (cond
10767 ((eq (car desc) :tag)
10768 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10769 ((eq (car desc) :todo)
10770 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10771 ((eq (car desc) :regexp)
10772 (setq descre (cdr desc)))
10773 ((eq (car desc) :level)
10774 (setq descre (concat "^\\*\\{" (number-to-string
10775 (if org-odd-levels-only
10776 (1- (* 2 (cdr desc)))
10777 (cdr desc)))
10778 "\\}[ \t]")))
10779 ((eq (car desc) :maxlevel)
10780 (setq fast-path-p t)
10781 (setq descre (concat "^\\*\\{1," (number-to-string
10782 (if org-odd-levels-only
10783 (1- (* 2 (cdr desc)))
10784 (cdr desc)))
10785 "\\}[ \t]")))
10786 (t (error "Bad refiling target description %s" desc)))
10787 (while (setq f (pop files))
10788 (with-current-buffer
10789 (if (bufferp f) f (org-get-agenda-file-buffer f))
10791 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10792 (progn
10793 (if (bufferp f) (setq f (buffer-file-name
10794 (buffer-base-buffer f))))
10795 (setq f (and f (expand-file-name f)))
10796 (if (eq org-refile-use-outline-path 'file)
10797 (push (list (file-name-nondirectory f) f nil nil) tgs))
10798 (save-excursion
10799 (save-restriction
10800 (widen)
10801 (goto-char (point-min))
10802 (while (re-search-forward descre nil t)
10803 (goto-char (setq pos0 (point-at-bol)))
10804 (catch 'next
10805 (when org-refile-target-verify-function
10806 (save-match-data
10807 (or (funcall org-refile-target-verify-function)
10808 (throw 'next t))))
10809 (when (and (looking-at org-complex-heading-regexp)
10810 (not (member (match-string 4) excluded-entries))
10811 (match-string 4))
10812 (setq level (org-reduced-level
10813 (- (match-end 1) (match-beginning 1)))
10814 txt (org-link-display-format (match-string 4))
10815 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10816 re (format org-complex-heading-regexp-format
10817 (regexp-quote (match-string 4))))
10818 (when org-refile-use-outline-path
10819 (setq txt (mapconcat
10820 'org-protect-slash
10821 (append
10822 (if (eq org-refile-use-outline-path
10823 'file)
10824 (list (file-name-nondirectory
10825 (buffer-file-name
10826 (buffer-base-buffer))))
10827 (if (eq org-refile-use-outline-path
10828 'full-file-path)
10829 (list (buffer-file-name
10830 (buffer-base-buffer)))))
10831 (org-get-outline-path fast-path-p
10832 level txt)
10833 (list txt))
10834 "/")))
10835 (push (list txt f re (org-refile-marker (point)))
10836 tgs)))
10837 (when (= (point) pos0)
10838 ;; verification function has not moved point
10839 (goto-char (point-at-eol))))))))
10840 (when org-refile-use-cache
10841 (org-refile-cache-put tgs (buffer-file-name) descre))
10842 (setq targets (append tgs targets))
10843 ))))
10844 (message "Getting targets...done")
10845 (nreverse targets)))
10847 (defun org-protect-slash (s)
10848 (while (string-match "/" s)
10849 (setq s (replace-match "\\" t t s)))
10852 (defvar org-olpa (make-vector 20 nil))
10854 (defun org-get-outline-path (&optional fastp level heading)
10855 "Return the outline path to the current entry, as a list.
10857 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10858 routine which makes outline path derivations for an entire file,
10859 avoiding backtracing. Refile target collection makes use of that."
10860 (if fastp
10861 (progn
10862 (if (> level 19)
10863 (error "Outline path failure, more than 19 levels"))
10864 (loop for i from level upto 19 do
10865 (aset org-olpa i nil))
10866 (prog1
10867 (delq nil (append org-olpa nil))
10868 (aset org-olpa level heading)))
10869 (let (rtn case-fold-search)
10870 (save-excursion
10871 (save-restriction
10872 (widen)
10873 (while (org-up-heading-safe)
10874 (when (looking-at org-complex-heading-regexp)
10875 (push (org-match-string-no-properties 4) rtn)))
10876 rtn)))))
10878 (defun org-format-outline-path (path &optional width prefix separator)
10879 "Format the outline path PATH for display.
10880 WIDTH is the maximum number of characters that is available.
10881 PREFIX is a prefix to be included in the returned string,
10882 such as the file name.
10883 SEPARATOR is inserted between the different parts of the path,
10884 the default is \"/\"."
10885 (setq width (or width 79))
10886 (if prefix (setq width (- width (length prefix))))
10887 (if (not path)
10888 (or prefix "")
10889 (let* ((nsteps (length path))
10890 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10891 (maxwidth (if (<= total-width width)
10892 10000 ;; everything fits
10893 ;; we need to shorten the level headings
10894 (/ (- width nsteps) nsteps)))
10895 (org-odd-levels-only nil)
10896 (n 0)
10897 (total (1+ (length prefix))))
10898 (setq maxwidth (max maxwidth 10))
10899 (concat prefix
10900 (if prefix (or separator "/"))
10901 (mapconcat
10902 (lambda (h)
10903 (setq n (1+ n))
10904 (if (and (= n nsteps) (< maxwidth 10000))
10905 (setq maxwidth (- total-width total)))
10906 (if (< (length h) maxwidth)
10907 (progn (setq total (+ total (length h) 1)) h)
10908 (setq h (substring h 0 (- maxwidth 2))
10909 total (+ total maxwidth 1))
10910 (if (string-match "[ \t]+\\'" h)
10911 (setq h (substring h 0 (match-beginning 0))))
10912 (setq h (concat h "..")))
10913 (org-add-props h nil 'face
10914 (nth (% (1- n) org-n-level-faces)
10915 org-level-faces))
10917 path (or separator "/"))))))
10919 (defun org-display-outline-path (&optional file current separator just-return-string)
10920 "Display the current outline path in the echo area.
10922 If FILE is non-nil, prepend the output with the file name.
10923 If CURRENT is non-nil, append the current heading to the output.
10924 SEPARATOR is passed through to `org-format-outline-path'. It separates
10925 the different parts of the path and defaults to \"/\".
10926 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10927 (interactive "P")
10928 (let* (case-fold-search
10929 message-log-max ; Don't populate the *Messages* buffer
10930 (bfn (buffer-file-name (buffer-base-buffer)))
10931 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10932 res)
10933 (if current (setq path (append path
10934 (save-excursion
10935 (org-back-to-heading t)
10936 (if (looking-at org-complex-heading-regexp)
10937 (list (match-string 4)))))))
10938 (setq res
10939 (org-format-outline-path
10940 path
10941 (1- (frame-width))
10942 (and file bfn (concat (file-name-nondirectory bfn) separator))
10943 separator))
10944 (if just-return-string
10945 (org-no-properties res)
10946 (message "%s" res))))
10948 (defvar org-refile-history nil
10949 "History for refiling operations.")
10951 (defvar org-after-refile-insert-hook nil
10952 "Hook run after `org-refile' has inserted its stuff at the new location.
10953 Note that this is still *before* the stuff will be removed from
10954 the *old* location.")
10956 (defvar org-capture-last-stored-marker)
10957 (defvar org-refile-keep nil
10958 "Non-nil means `org-refile' will copy instead of refile.")
10960 (defun org-copy ()
10961 "Like `org-refile', but copy."
10962 (interactive)
10963 (let ((org-refile-keep t))
10964 (funcall 'org-refile nil nil nil "Copy")))
10966 (defun org-refile (&optional goto default-buffer rfloc msg)
10967 "Move the entry or entries at point to another heading.
10968 The list of target headings is compiled using the information in
10969 `org-refile-targets', which see.
10971 At the target location, the entry is filed as a subitem of the target
10972 heading. Depending on `org-reverse-note-order', the new subitem will
10973 either be the first or the last subitem.
10975 If there is an active region, all entries in that region will be moved.
10976 However, the region must fulfill the requirement that the first heading
10977 is the first one sets the top-level of the moved text - at most siblings
10978 below it are allowed.
10980 With prefix arg GOTO, the command will only visit the target location
10981 and not actually move anything.
10983 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10984 go to the location where the last refiling operation has put the subtree.
10985 With a prefix argument of `2', refile to the running clock.
10987 RFLOC can be a refile location obtained in a different way.
10989 MSG is a string to replace \"Refile\" in the default prompt with
10990 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
10992 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10994 If you are using target caching (see `org-refile-use-cache'),
10995 you have to clear the target cache in order to find new targets.
10996 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10997 prefix argument (`C-u C-u C-u C-c C-w')."
10999 (interactive "P")
11000 (if (member goto '(0 (64)))
11001 (org-refile-cache-clear)
11002 (let* ((actionmsg (or msg "Refile"))
11003 (cbuf (current-buffer))
11004 (regionp (org-region-active-p))
11005 (region-start (and regionp (region-beginning)))
11006 (region-end (and regionp (region-end)))
11007 (region-length (and regionp (- region-end region-start)))
11008 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11009 pos it nbuf file re level reversed)
11010 (setq last-command nil)
11011 (when regionp
11012 (goto-char region-start)
11013 (or (bolp) (goto-char (point-at-bol)))
11014 (setq region-start (point))
11015 (unless (or (org-kill-is-subtree-p
11016 (buffer-substring region-start region-end))
11017 (prog1 org-refile-active-region-within-subtree
11018 (org-toggle-heading)))
11019 (error "The region is not a (sequence of) subtree(s)")))
11020 (if (equal goto '(16))
11021 (org-refile-goto-last-stored)
11022 (when (or
11023 (and (equal goto 2)
11024 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11025 (prog1
11026 (setq it (list (or org-clock-heading "running clock")
11027 (buffer-file-name
11028 (marker-buffer org-clock-hd-marker))
11030 (marker-position org-clock-hd-marker)))
11031 (setq goto nil)))
11032 (setq it (or rfloc
11033 (let (heading-text)
11034 (save-excursion
11035 (unless goto
11036 (org-back-to-heading t)
11037 (setq heading-text
11038 (nth 4 (org-heading-components))))
11040 (org-refile-get-location
11041 (cond (goto "Goto")
11042 (regionp (concat actionmsg " region to"))
11043 (t (concat actionmsg " subtree \""
11044 heading-text "\" to")))
11045 default-buffer
11046 (and (not (equal '(4) goto))
11047 org-refile-allow-creating-parent-nodes)
11048 goto))))))
11049 (setq file (nth 1 it)
11050 re (nth 2 it)
11051 pos (nth 3 it))
11052 (if (and (not goto)
11054 (equal (buffer-file-name) file)
11055 (if regionp
11056 (and (>= pos region-start)
11057 (<= pos region-end))
11058 (and (>= pos (point))
11059 (< pos (save-excursion
11060 (org-end-of-subtree t t))))))
11061 (error "Cannot refile to position inside the tree or region"))
11063 (setq nbuf (or (find-buffer-visiting file)
11064 (find-file-noselect file)))
11065 (if goto
11066 (progn
11067 (org-pop-to-buffer-same-window nbuf)
11068 (goto-char pos)
11069 (org-show-context 'org-goto))
11070 (if regionp
11071 (progn
11072 (org-kill-new (buffer-substring region-start region-end))
11073 (org-save-markers-in-region region-start region-end))
11074 (org-copy-subtree 1 nil t))
11075 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11076 (find-file-noselect file)))
11077 (setq reversed (org-notes-order-reversed-p))
11078 (save-excursion
11079 (save-restriction
11080 (widen)
11081 (if pos
11082 (progn
11083 (goto-char pos)
11084 (looking-at org-outline-regexp)
11085 (setq level (org-get-valid-level (funcall outline-level) 1))
11086 (goto-char
11087 (if reversed
11088 (or (outline-next-heading) (point-max))
11089 (or (save-excursion (org-get-next-sibling))
11090 (org-end-of-subtree t t)
11091 (point-max)))))
11092 (setq level 1)
11093 (if (not reversed)
11094 (goto-char (point-max))
11095 (goto-char (point-min))
11096 (or (outline-next-heading) (goto-char (point-max)))))
11097 (if (not (bolp)) (newline))
11098 (org-paste-subtree level)
11099 (when org-log-refile
11100 (org-add-log-setup 'refile nil nil 'findpos
11101 org-log-refile)
11102 (unless (eq org-log-refile 'note)
11103 (save-excursion (org-add-log-note))))
11104 (and org-auto-align-tags
11105 (let ((org-loop-over-headlines-in-active-region nil))
11106 (org-set-tags nil t)))
11107 (with-demoted-errors
11108 (bookmark-set "org-refile-last-stored"))
11109 ;; If we are refiling for capture, make sure that the
11110 ;; last-capture pointers point here
11111 (when (org-bound-and-true-p org-refile-for-capture)
11112 (with-demoted-errors
11113 (bookmark-set "org-capture-last-stored-marker"))
11114 (move-marker org-capture-last-stored-marker (point)))
11115 (if (fboundp 'deactivate-mark) (deactivate-mark))
11116 (run-hooks 'org-after-refile-insert-hook))))
11117 (unless org-refile-keep
11118 (if regionp
11119 (delete-region (point) (+ (point) region-length))
11120 (org-cut-subtree)))
11121 (when (featurep 'org-inlinetask)
11122 (org-inlinetask-remove-END-maybe))
11123 (setq org-markers-to-move nil)
11124 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11126 (defun org-refile-goto-last-stored ()
11127 "Go to the location where the last refile was stored."
11128 (interactive)
11129 (bookmark-jump "org-refile-last-stored")
11130 (message "This is the location of the last refile"))
11132 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11133 no-exclude)
11134 "Prompt the user for a refile location, using PROMPT.
11135 PROMPT should not be suffixed with a colon and a space, because
11136 this function appends the default value from
11137 `org-refile-history' automatically, if that is not empty.
11138 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11139 this is used for the GOTO interface."
11140 (let ((org-refile-targets org-refile-targets)
11141 (org-refile-use-outline-path org-refile-use-outline-path)
11142 excluded-entries)
11143 (when (and (derived-mode-p 'org-mode)
11144 (not org-refile-use-cache)
11145 (not no-exclude))
11146 (org-map-tree
11147 (lambda()
11148 (setq excluded-entries
11149 (append excluded-entries (list (org-get-heading t t)))))))
11150 (setq org-refile-target-table
11151 (org-refile-get-targets default-buffer excluded-entries)))
11152 (unless org-refile-target-table
11153 (error "No refile targets"))
11154 (let* ((cbuf (current-buffer))
11155 (partial-completion-mode nil)
11156 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11157 (cfunc (if (and org-refile-use-outline-path
11158 org-outline-path-complete-in-steps)
11159 'org-olpath-completing-read
11160 'org-icompleting-read))
11161 (extra (if org-refile-use-outline-path "/" ""))
11162 (cbnex (concat (buffer-name) extra))
11163 (filename (and cfn (expand-file-name cfn)))
11164 (tbl (mapcar
11165 (lambda (x)
11166 (if (and (not (member org-refile-use-outline-path
11167 '(file full-file-path)))
11168 (not (equal filename (nth 1 x))))
11169 (cons (concat (car x) extra " ("
11170 (file-name-nondirectory (nth 1 x)) ")")
11171 (cdr x))
11172 (cons (concat (car x) extra) (cdr x))))
11173 org-refile-target-table))
11174 (completion-ignore-case t)
11175 cdef
11176 (prompt (concat prompt
11177 (or (and (car org-refile-history)
11178 (concat " (default " (car org-refile-history) ")"))
11179 (and (assoc cbnex tbl) (setq cdef cbnex)
11180 (concat " (default " cbnex ")"))) ": "))
11181 pa answ parent-target child parent old-hist)
11182 (setq old-hist org-refile-history)
11183 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11184 nil 'org-refile-history (or cdef (car org-refile-history))))
11185 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11186 (org-refile-check-position pa)
11187 (if pa
11188 (progn
11189 (when (or (not org-refile-history)
11190 (not (eq old-hist org-refile-history))
11191 (not (equal (car pa) (car org-refile-history))))
11192 (setq org-refile-history
11193 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11194 org-refile-history
11195 (cdr org-refile-history))))
11196 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11197 (pop org-refile-history)))
11199 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11200 (progn
11201 (setq parent (match-string 1 answ)
11202 child (match-string 2 answ))
11203 (setq parent-target (or (assoc parent tbl)
11204 (assoc (concat parent "/") tbl)))
11205 (when (and parent-target
11206 (or (eq new-nodes t)
11207 (and (eq new-nodes 'confirm)
11208 (y-or-n-p (format "Create new node \"%s\"? "
11209 child)))))
11210 (org-refile-new-child parent-target child)))
11211 (error "Invalid target location")))))
11213 (declare-function org-string-nw-p "org-macs" (s))
11214 (defun org-refile-check-position (refile-pointer)
11215 "Check if the refile pointer matches the headline to which it points."
11216 (let* ((file (nth 1 refile-pointer))
11217 (re (nth 2 refile-pointer))
11218 (pos (nth 3 refile-pointer))
11219 buffer)
11220 (if (and (not (markerp pos)) (not file))
11221 (error "Please save the buffer to a file before refiling")
11222 (when (org-string-nw-p re)
11223 (setq buffer (if (markerp pos)
11224 (marker-buffer pos)
11225 (or (find-buffer-visiting file)
11226 (find-file-noselect file))))
11227 (with-current-buffer buffer
11228 (save-excursion
11229 (save-restriction
11230 (widen)
11231 (goto-char pos)
11232 (beginning-of-line 1)
11233 (unless (org-looking-at-p re)
11234 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11236 (defun org-refile-new-child (parent-target child)
11237 "Use refile target PARENT-TARGET to add new CHILD below it."
11238 (unless parent-target
11239 (error "Cannot find parent for new node"))
11240 (let ((file (nth 1 parent-target))
11241 (pos (nth 3 parent-target))
11242 level)
11243 (with-current-buffer (or (find-buffer-visiting file)
11244 (find-file-noselect file))
11245 (save-excursion
11246 (save-restriction
11247 (widen)
11248 (if pos
11249 (goto-char pos)
11250 (goto-char (point-max))
11251 (if (not (bolp)) (newline)))
11252 (when (looking-at org-outline-regexp)
11253 (setq level (funcall outline-level))
11254 (org-end-of-subtree t t))
11255 (org-back-over-empty-lines)
11256 (insert "\n" (make-string
11257 (if pos (org-get-valid-level level 1) 1) ?*)
11258 " " child "\n")
11259 (beginning-of-line 0)
11260 (list (concat (car parent-target) "/" child) file "" (point)))))))
11262 (defun org-olpath-completing-read (prompt collection &rest args)
11263 "Read an outline path like a file name."
11264 (let ((thetable collection)
11265 (org-completion-use-ido nil) ; does not work with ido.
11266 (org-completion-use-iswitchb nil)) ; or iswitchb
11267 (apply
11268 'org-icompleting-read prompt
11269 (lambda (string predicate &optional flag)
11270 (let (rtn r f (l (length string)))
11271 (cond
11272 ((eq flag nil)
11273 ;; try completion
11274 (try-completion string thetable))
11275 ((eq flag t)
11276 ;; all-completions
11277 (setq rtn (all-completions string thetable predicate))
11278 (mapcar
11279 (lambda (x)
11280 (setq r (substring x l))
11281 (if (string-match " ([^)]*)$" x)
11282 (setq f (match-string 0 x))
11283 (setq f ""))
11284 (if (string-match "/" r)
11285 (concat string (substring r 0 (match-end 0)) f)
11287 rtn))
11288 ((eq flag 'lambda)
11289 ;; exact match?
11290 (assoc string thetable)))))
11291 args)))
11293 ;;;; Dynamic blocks
11295 (defun org-find-dblock (name)
11296 "Find the first dynamic block with name NAME in the buffer.
11297 If not found, stay at current position and return nil."
11298 (let ((case-fold-search t) pos)
11299 (save-excursion
11300 (goto-char (point-min))
11301 (setq pos (and (re-search-forward
11302 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11303 (match-beginning 0))))
11304 (if pos (goto-char pos))
11305 pos))
11307 (defconst org-dblock-start-re
11308 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11309 "Matches the start line of a dynamic block, with parameters.")
11311 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11312 "Matches the end of a dynamic block.")
11314 (defun org-create-dblock (plist)
11315 "Create a dynamic block section, with parameters taken from PLIST.
11316 PLIST must contain a :name entry which is used as name of the block."
11317 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11318 (end-of-line 1)
11319 (newline))
11320 (let ((col (current-column))
11321 (name (plist-get plist :name)))
11322 (insert "#+BEGIN: " name)
11323 (while plist
11324 (if (eq (car plist) :name)
11325 (setq plist (cddr plist))
11326 (insert " " (prin1-to-string (pop plist)))))
11327 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11328 (beginning-of-line -2)))
11330 (defun org-prepare-dblock ()
11331 "Prepare dynamic block for refresh.
11332 This empties the block, puts the cursor at the insert position and returns
11333 the property list including an extra property :name with the block name."
11334 (unless (looking-at org-dblock-start-re)
11335 (error "Not at a dynamic block"))
11336 (let* ((begdel (1+ (match-end 0)))
11337 (name (org-no-properties (match-string 1)))
11338 (params (append (list :name name)
11339 (read (concat "(" (match-string 3) ")")))))
11340 (save-excursion
11341 (beginning-of-line 1)
11342 (skip-chars-forward " \t")
11343 (setq params (plist-put params :indentation-column (current-column))))
11344 (unless (re-search-forward org-dblock-end-re nil t)
11345 (error "Dynamic block not terminated"))
11346 (setq params
11347 (append params
11348 (list :content (buffer-substring
11349 begdel (match-beginning 0)))))
11350 (delete-region begdel (match-beginning 0))
11351 (goto-char begdel)
11352 (open-line 1)
11353 params))
11355 (defun org-map-dblocks (&optional command)
11356 "Apply COMMAND to all dynamic blocks in the current buffer.
11357 If COMMAND is not given, use `org-update-dblock'."
11358 (let ((cmd (or command 'org-update-dblock)))
11359 (save-excursion
11360 (goto-char (point-min))
11361 (while (re-search-forward org-dblock-start-re nil t)
11362 (goto-char (match-beginning 0))
11363 (save-excursion
11364 (condition-case nil
11365 (funcall cmd)
11366 (error (message "Error during update of dynamic block"))))
11367 (unless (re-search-forward org-dblock-end-re nil t)
11368 (error "Dynamic block not terminated"))))))
11370 (defun org-dblock-update (&optional arg)
11371 "User command for updating dynamic blocks.
11372 Update the dynamic block at point. With prefix ARG, update all dynamic
11373 blocks in the buffer."
11374 (interactive "P")
11375 (if arg
11376 (org-update-all-dblocks)
11377 (or (looking-at org-dblock-start-re)
11378 (org-beginning-of-dblock))
11379 (org-update-dblock)))
11381 (defun org-update-dblock ()
11382 "Update the dynamic block at point.
11383 This means to empty the block, parse for parameters and then call
11384 the correct writing function."
11385 (interactive)
11386 (save-window-excursion
11387 (let* ((pos (point))
11388 (line (org-current-line))
11389 (params (org-prepare-dblock))
11390 (name (plist-get params :name))
11391 (indent (plist-get params :indentation-column))
11392 (cmd (intern (concat "org-dblock-write:" name))))
11393 (message "Updating dynamic block `%s' at line %d..." name line)
11394 (funcall cmd params)
11395 (message "Updating dynamic block `%s' at line %d...done" name line)
11396 (goto-char pos)
11397 (when (and indent (> indent 0))
11398 (setq indent (make-string indent ?\ ))
11399 (save-excursion
11400 (org-beginning-of-dblock)
11401 (forward-line 1)
11402 (while (not (looking-at org-dblock-end-re))
11403 (insert indent)
11404 (beginning-of-line 2))
11405 (when (looking-at org-dblock-end-re)
11406 (and (looking-at "[ \t]+")
11407 (replace-match ""))
11408 (insert indent)))))))
11410 (defun org-beginning-of-dblock ()
11411 "Find the beginning of the dynamic block at point.
11412 Error if there is no such block at point."
11413 (let ((pos (point))
11414 beg)
11415 (end-of-line 1)
11416 (if (and (re-search-backward org-dblock-start-re nil t)
11417 (setq beg (match-beginning 0))
11418 (re-search-forward org-dblock-end-re nil t)
11419 (> (match-end 0) pos))
11420 (goto-char beg)
11421 (goto-char pos)
11422 (error "Not in a dynamic block"))))
11424 (defun org-update-all-dblocks ()
11425 "Update all dynamic blocks in the buffer.
11426 This function can be used in a hook."
11427 (interactive)
11428 (when (derived-mode-p 'org-mode)
11429 (org-map-dblocks 'org-update-dblock)))
11432 ;;;; Completion
11434 (defconst org-additional-option-like-keywords
11435 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11436 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11437 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11438 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11439 "BEGIN:" "END:"
11440 "ORGTBL" "TBLFM:" "TBLNAME:"
11441 "BEGIN_EXAMPLE" "END_EXAMPLE"
11442 "BEGIN_VERBATIM" "END_VERBATIM"
11443 "BEGIN_QUOTE" "END_QUOTE"
11444 "BEGIN_VERSE" "END_VERSE"
11445 "BEGIN_CENTER" "END_CENTER"
11446 "BEGIN_SRC" "END_SRC"
11447 "BEGIN_RESULT" "END_RESULT"
11448 "BEGIN_lstlisting" "END_lstlisting"
11449 "NAME:" "RESULTS:"
11450 "HEADER:" "HEADERS:"
11451 "COLUMNS:" "PROPERTY:"
11452 "CAPTION:" "LABEL:"
11453 "SETUPFILE:"
11454 "INCLUDE:" "INDEX:"
11455 "BIND:"
11456 "MACRO:"))
11458 (defconst org-options-keywords
11459 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11460 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11461 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11462 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11463 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11464 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11465 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11467 (defconst org-additional-option-like-keywords-for-flyspell
11468 (delete-dups
11469 (split-string
11470 (mapconcat (lambda(k)
11471 (replace-regexp-in-string
11472 "_\\|:" " "
11473 (concat k " " (downcase k) " " (upcase k))))
11474 (append org-options-keywords org-additional-option-like-keywords)
11475 " ")
11476 " +" t)))
11478 (defcustom org-structure-template-alist
11479 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11480 "<src lang=\"?\">\n\n</src>")
11481 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11482 "<example>\n?\n</example>")
11483 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11484 "<quote>\n?\n</quote>")
11485 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11486 "<verse>\n?\n</verse>")
11487 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11488 "<verbatim>\n?\n</verbatim>")
11489 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11490 "<center>\n?\n</center>")
11491 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11492 "<literal style=\"latex\">\n?\n</literal>")
11493 ("L" "#+LaTeX: "
11494 "<literal style=\"latex\">?</literal>")
11495 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11496 "<literal style=\"html\">\n?\n</literal>")
11497 ("H" "#+HTML: "
11498 "<literal style=\"html\">?</literal>")
11499 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11500 ("A" "#+ASCII: ")
11501 ("i" "#+INDEX: ?"
11502 "#+INDEX: ?")
11503 ("I" "#+INCLUDE: %file ?"
11504 "<include file=%file markup=\"?\">"))
11505 "Structure completion elements.
11506 This is a list of abbreviation keys and values. The value gets inserted
11507 if you type `<' followed by the key and then press the completion key,
11508 usually `M-TAB'. %file will be replaced by a file name after prompting
11509 for the file using completion. The cursor will be placed at the position
11510 of the `?` in the template.
11511 There are two templates for each key, the first uses the original Org syntax,
11512 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11513 the default when the /org-mtags.el/ module has been loaded. See also the
11514 variable `org-mtags-prefer-muse-templates'."
11515 :group 'org-completion
11516 :type '(repeat
11517 (string :tag "Key")
11518 (string :tag "Template")
11519 (string :tag "Muse Template")))
11521 (defun org-try-structure-completion ()
11522 "Try to complete a structure template before point.
11523 This looks for strings like \"<e\" on an otherwise empty line and
11524 expands them."
11525 (let ((l (buffer-substring (point-at-bol) (point)))
11527 (when (and (looking-at "[ \t]*$")
11528 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11529 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11530 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11531 (match-beginning 1)) a)
11532 t)))
11534 (defun org-complete-expand-structure-template (start cell)
11535 "Expand a structure template."
11536 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11537 (rpl (nth (if musep 2 1) cell))
11538 (ind ""))
11539 (delete-region start (point))
11540 (when (string-match "\\`#\\+" rpl)
11541 (cond
11542 ((bolp))
11543 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11544 (setq ind (buffer-substring (point-at-bol) (point))))
11545 (t (newline))))
11546 (setq start (point))
11547 (if (string-match "%file" rpl)
11548 (setq rpl (replace-match
11549 (concat
11550 "\""
11551 (save-match-data
11552 (abbreviate-file-name (read-file-name "Include file: ")))
11553 "\"")
11554 t t rpl)))
11555 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11556 (concat "\n" ind)))
11557 (insert rpl)
11558 (if (re-search-backward "\\?" start t) (delete-char 1))))
11560 ;;;; TODO, DEADLINE, Comments
11562 (defun org-toggle-comment ()
11563 "Change the COMMENT state of an entry."
11564 (interactive)
11565 (save-excursion
11566 (org-back-to-heading)
11567 (let (case-fold-search)
11568 (cond
11569 ((looking-at (format org-heading-keyword-regexp-format
11570 org-comment-string))
11571 (goto-char (match-end 1))
11572 (looking-at (concat " +" org-comment-string))
11573 (replace-match "" t t)
11574 (when (eolp) (insert " ")))
11575 ((looking-at org-outline-regexp)
11576 (goto-char (match-end 0))
11577 (insert org-comment-string " "))))))
11579 (defvar org-last-todo-state-is-todo nil
11580 "This is non-nil when the last TODO state change led to a TODO state.
11581 If the last change removed the TODO tag or switched to DONE, then
11582 this is nil.")
11584 (defvar org-setting-tags nil) ; dynamically skipped
11586 (defvar org-todo-setup-filter-hook nil
11587 "Hook for functions that pre-filter todo specs.
11588 Each function takes a todo spec and returns either nil or the spec
11589 transformed into canonical form." )
11591 (defvar org-todo-get-default-hook nil
11592 "Hook for functions that get a default item for todo.
11593 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11594 nil or a string to be used for the todo mark." )
11596 (defvar org-agenda-headline-snapshot-before-repeat)
11598 (defun org-current-effective-time ()
11599 "Return current time adjusted for `org-extend-today-until' variable."
11600 (let* ((ct (org-current-time))
11601 (dct (decode-time ct))
11602 (ct1
11603 (cond
11604 (org-use-last-clock-out-time-as-effective-time
11605 (or (org-clock-get-last-clock-out-time) ct))
11606 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11607 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11608 (t ct))))
11609 ct1))
11611 (defun org-todo-yesterday (&optional arg)
11612 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11613 (interactive "P")
11614 (if (eq major-mode 'org-agenda-mode)
11615 (apply 'org-agenda-todo-yesterday arg)
11616 (let* ((hour (third (decode-time
11617 (org-current-time))))
11618 (org-extend-today-until (1+ hour)))
11619 (org-todo arg))))
11621 (defvar org-block-entry-blocking ""
11622 "First entry preventing the TODO state change.")
11624 (defun org-todo (&optional arg)
11625 "Change the TODO state of an item.
11626 The state of an item is given by a keyword at the start of the heading,
11627 like
11628 *** TODO Write paper
11629 *** DONE Call mom
11631 The different keywords are specified in the variable `org-todo-keywords'.
11632 By default the available states are \"TODO\" and \"DONE\".
11633 So for this example: when the item starts with TODO, it is changed to DONE.
11634 When it starts with DONE, the DONE is removed. And when neither TODO nor
11635 DONE are present, add TODO at the beginning of the heading.
11637 With \\[universal-argument] prefix arg, use completion to determine the new \
11638 state.
11639 With numeric prefix arg, switch to that state.
11640 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11641 keywords (nextset).
11642 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11643 With a numeric prefix arg of 0, inhibit note taking for the change.
11645 For calling through lisp, arg is also interpreted in the following way:
11646 'none -> empty state
11647 \"\"(empty string) -> switch to empty state
11648 'done -> switch to DONE
11649 'nextset -> switch to the next set of keywords
11650 'previousset -> switch to the previous set of keywords
11651 \"WAITING\" -> switch to the specified keyword, but only if it
11652 really is a member of `org-todo-keywords'."
11653 (interactive "P")
11654 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11655 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11656 'region-start-level 'region))
11657 org-loop-over-headlines-in-active-region)
11658 (org-map-entries
11659 `(org-todo ,arg)
11660 org-loop-over-headlines-in-active-region
11661 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11662 (if (equal arg '(16)) (setq arg 'nextset))
11663 (let ((org-blocker-hook org-blocker-hook)
11664 commentp
11665 case-fold-search)
11666 (when (equal arg '(64))
11667 (setq arg nil org-blocker-hook nil))
11668 (when (and org-blocker-hook
11669 (or org-inhibit-blocking
11670 (org-entry-get nil "NOBLOCKING")))
11671 (setq org-blocker-hook nil))
11672 (save-excursion
11673 (catch 'exit
11674 (org-back-to-heading t)
11675 (when (looking-at (concat "^\\*+ " org-comment-string))
11676 (org-toggle-comment)
11677 (setq commentp t))
11678 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11679 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11680 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11681 (let* ((match-data (match-data))
11682 (startpos (point-at-bol))
11683 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11684 (org-log-done org-log-done)
11685 (org-log-repeat org-log-repeat)
11686 (org-todo-log-states org-todo-log-states)
11687 (org-inhibit-logging
11688 (if (equal arg 0)
11689 (progn (setq arg nil) 'note) org-inhibit-logging))
11690 (this (match-string 1))
11691 (hl-pos (match-beginning 0))
11692 (head (org-get-todo-sequence-head this))
11693 (ass (assoc head org-todo-kwd-alist))
11694 (interpret (nth 1 ass))
11695 (done-word (nth 3 ass))
11696 (final-done-word (nth 4 ass))
11697 (org-last-state (or this ""))
11698 (completion-ignore-case t)
11699 (member (member this org-todo-keywords-1))
11700 (tail (cdr member))
11701 (org-state (cond
11702 ((and org-todo-key-trigger
11703 (or (and (equal arg '(4))
11704 (eq org-use-fast-todo-selection 'prefix))
11705 (and (not arg) org-use-fast-todo-selection
11706 (not (eq org-use-fast-todo-selection
11707 'prefix)))))
11708 ;; Use fast selection
11709 (org-fast-todo-selection))
11710 ((and (equal arg '(4))
11711 (or (not org-use-fast-todo-selection)
11712 (not org-todo-key-trigger)))
11713 ;; Read a state with completion
11714 (org-icompleting-read
11715 "State: " (mapcar (lambda(x) (list x))
11716 org-todo-keywords-1)
11717 nil t))
11718 ((eq arg 'right)
11719 (if this
11720 (if tail (car tail) nil)
11721 (car org-todo-keywords-1)))
11722 ((eq arg 'left)
11723 (if (equal member org-todo-keywords-1)
11725 (if this
11726 (nth (- (length org-todo-keywords-1)
11727 (length tail) 2)
11728 org-todo-keywords-1)
11729 (org-last org-todo-keywords-1))))
11730 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11731 (setq arg nil))) ; hack to fall back to cycling
11732 (arg
11733 ;; user or caller requests a specific state
11734 (cond
11735 ((equal arg "") nil)
11736 ((eq arg 'none) nil)
11737 ((eq arg 'done) (or done-word (car org-done-keywords)))
11738 ((eq arg 'nextset)
11739 (or (car (cdr (member head org-todo-heads)))
11740 (car org-todo-heads)))
11741 ((eq arg 'previousset)
11742 (let ((org-todo-heads (reverse org-todo-heads)))
11743 (or (car (cdr (member head org-todo-heads)))
11744 (car org-todo-heads))))
11745 ((car (member arg org-todo-keywords-1)))
11746 ((stringp arg)
11747 (error "State `%s' not valid in this file" arg))
11748 ((nth (1- (prefix-numeric-value arg))
11749 org-todo-keywords-1))))
11750 ((null member) (or head (car org-todo-keywords-1)))
11751 ((equal this final-done-word) nil) ;; -> make empty
11752 ((null tail) nil) ;; -> first entry
11753 ((memq interpret '(type priority))
11754 (if (eq this-command last-command)
11755 (car tail)
11756 (if (> (length tail) 0)
11757 (or done-word (car org-done-keywords))
11758 nil)))
11760 (car tail))))
11761 (org-state (or
11762 (run-hook-with-args-until-success
11763 'org-todo-get-default-hook org-state org-last-state)
11764 org-state))
11765 (next (if org-state (concat " " org-state " ") " "))
11766 (change-plist (list :type 'todo-state-change :from this :to org-state
11767 :position startpos))
11768 dolog now-done-p)
11769 (when org-blocker-hook
11770 (setq org-last-todo-state-is-todo
11771 (not (member this org-done-keywords)))
11772 (unless (save-excursion
11773 (save-match-data
11774 (org-with-wide-buffer
11775 (run-hook-with-args-until-failure
11776 'org-blocker-hook change-plist))))
11777 (if (org-called-interactively-p 'interactive)
11778 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11779 this org-state org-block-entry-blocking)
11780 ;; fail silently
11781 (message "TODO state change from %s to %s blocked (by \"%s\")"
11782 this org-state org-block-entry-blocking)
11783 (throw 'exit nil))))
11784 (store-match-data match-data)
11785 (replace-match next t t)
11786 (unless (pos-visible-in-window-p hl-pos)
11787 (message "TODO state changed to %s" (org-trim next)))
11788 (unless head
11789 (setq head (org-get-todo-sequence-head org-state)
11790 ass (assoc head org-todo-kwd-alist)
11791 interpret (nth 1 ass)
11792 done-word (nth 3 ass)
11793 final-done-word (nth 4 ass)))
11794 (when (memq arg '(nextset previousset))
11795 (message "Keyword-Set %d/%d: %s"
11796 (- (length org-todo-sets) -1
11797 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11798 (length org-todo-sets)
11799 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11800 (setq org-last-todo-state-is-todo
11801 (not (member org-state org-done-keywords)))
11802 (setq now-done-p (and (member org-state org-done-keywords)
11803 (not (member this org-done-keywords))))
11804 (and logging (org-local-logging logging))
11805 (when (and (or org-todo-log-states org-log-done)
11806 (not (eq org-inhibit-logging t))
11807 (not (memq arg '(nextset previousset))))
11808 ;; we need to look at recording a time and note
11809 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11810 (nth 2 (assoc this org-todo-log-states))))
11811 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11812 (setq dolog 'time))
11813 (when (and org-state
11814 (member org-state org-not-done-keywords)
11815 (not (member this org-not-done-keywords)))
11816 ;; This is now a todo state and was not one before
11817 ;; If there was a CLOSED time stamp, get rid of it.
11818 (org-add-planning-info nil nil 'closed))
11819 (when (and now-done-p org-log-done)
11820 ;; It is now done, and it was not done before
11821 (org-add-planning-info 'closed (org-current-effective-time))
11822 (if (and (not dolog) (eq 'note org-log-done))
11823 (org-add-log-setup 'done org-state this 'findpos 'note)))
11824 (when (and org-state dolog)
11825 ;; This is a non-nil state, and we need to log it
11826 (org-add-log-setup 'state org-state this 'findpos dolog)))
11827 ;; Fixup tag positioning
11828 (org-todo-trigger-tag-changes org-state)
11829 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11830 (when org-provide-todo-statistics
11831 (org-update-parent-todo-statistics))
11832 (run-hooks 'org-after-todo-state-change-hook)
11833 (if (and arg (not (member org-state org-done-keywords)))
11834 (setq head (org-get-todo-sequence-head org-state)))
11835 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11836 ;; Do we need to trigger a repeat?
11837 (when now-done-p
11838 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11839 ;; This is for the agenda, take a snapshot of the headline.
11840 (save-match-data
11841 (setq org-agenda-headline-snapshot-before-repeat
11842 (org-get-heading))))
11843 (org-auto-repeat-maybe org-state))
11844 ;; Fixup cursor location if close to the keyword
11845 (if (and (outline-on-heading-p)
11846 (not (bolp))
11847 (save-excursion (beginning-of-line 1)
11848 (looking-at org-todo-line-regexp))
11849 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11850 (progn
11851 (goto-char (or (match-end 2) (match-end 1)))
11852 (and (looking-at " ") (just-one-space))))
11853 (when org-trigger-hook
11854 (save-excursion
11855 (run-hook-with-args 'org-trigger-hook change-plist)))
11856 (when commentp (org-toggle-comment))))))))
11858 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11859 "Block turning an entry into a TODO, using the hierarchy.
11860 This checks whether the current task should be blocked from state
11861 changes. Such blocking occurs when:
11863 1. The task has children which are not all in a completed state.
11865 2. A task has a parent with the property :ORDERED:, and there
11866 are siblings prior to the current task with incomplete
11867 status.
11869 3. The parent of the task is blocked because it has siblings that should
11870 be done first, or is child of a block grandparent TODO entry."
11872 (if (not org-enforce-todo-dependencies)
11873 t ; if locally turned off don't block
11874 (catch 'dont-block
11875 ;; If this is not a todo state change, or if this entry is already DONE,
11876 ;; do not block
11877 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11878 (member (plist-get change-plist :from)
11879 (cons 'done org-done-keywords))
11880 (member (plist-get change-plist :to)
11881 (cons 'todo org-not-done-keywords))
11882 (not (plist-get change-plist :to)))
11883 (throw 'dont-block t))
11884 ;; If this task has children, and any are undone, it's blocked
11885 (save-excursion
11886 (org-back-to-heading t)
11887 (let ((this-level (funcall outline-level)))
11888 (outline-next-heading)
11889 (let ((child-level (funcall outline-level)))
11890 (while (and (not (eobp))
11891 (> child-level this-level))
11892 ;; this todo has children, check whether they are all
11893 ;; completed
11894 (if (and (not (org-entry-is-done-p))
11895 (org-entry-is-todo-p))
11896 (progn (setq org-block-entry-blocking (org-get-heading))
11897 (throw 'dont-block nil)))
11898 (outline-next-heading)
11899 (setq child-level (funcall outline-level))))))
11900 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11901 ;; any previous siblings are undone, it's blocked
11902 (save-excursion
11903 (org-back-to-heading t)
11904 (let* ((pos (point))
11905 (parent-pos (and (org-up-heading-safe) (point))))
11906 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11907 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11908 (forward-line 1)
11909 (re-search-forward org-not-done-heading-regexp pos t))
11910 (setq org-block-entry-blocking (match-string 0))
11911 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11912 ;; Search further up the hierarchy, to see if an ancestor is blocked
11913 (while t
11914 (goto-char parent-pos)
11915 (if (not (looking-at org-not-done-heading-regexp))
11916 (throw 'dont-block t)) ; do not block, parent is not a TODO
11917 (setq pos (point))
11918 (setq parent-pos (and (org-up-heading-safe) (point)))
11919 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11920 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11921 (forward-line 1)
11922 (re-search-forward org-not-done-heading-regexp pos t)
11923 (setq org-block-entry-blocking (org-get-heading)))
11924 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11926 (defcustom org-track-ordered-property-with-tag nil
11927 "Should the ORDERED property also be shown as a tag?
11928 The ORDERED property decides if an entry should require subtasks to be
11929 completed in sequence. Since a property is not very visible, setting
11930 this option means that toggling the ORDERED property with the command
11931 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11932 not relevant for the behavior, but it makes things more visible.
11934 Note that toggling the tag with tags commands will not change the property
11935 and therefore not influence behavior!
11937 This can be t, meaning the tag ORDERED should be used, It can also be a
11938 string to select a different tag for this task."
11939 :group 'org-todo
11940 :type '(choice
11941 (const :tag "No tracking" nil)
11942 (const :tag "Track with ORDERED tag" t)
11943 (string :tag "Use other tag")))
11945 (defun org-toggle-ordered-property ()
11946 "Toggle the ORDERED property of the current entry.
11947 For better visibility, you can track the value of this property with a tag.
11948 See variable `org-track-ordered-property-with-tag'."
11949 (interactive)
11950 (let* ((t1 org-track-ordered-property-with-tag)
11951 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11952 (save-excursion
11953 (org-back-to-heading)
11954 (if (org-entry-get nil "ORDERED")
11955 (progn
11956 (org-delete-property "ORDERED")
11957 (and tag (org-toggle-tag tag 'off))
11958 (message "Subtasks can be completed in arbitrary order"))
11959 (org-entry-put nil "ORDERED" "t")
11960 (and tag (org-toggle-tag tag 'on))
11961 (message "Subtasks must be completed in sequence")))))
11963 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11964 (defun org-block-todo-from-checkboxes (change-plist)
11965 "Block turning an entry into a TODO, using checkboxes.
11966 This checks whether the current task should be blocked from state
11967 changes because there are unchecked boxes in this entry."
11968 (if (not org-enforce-todo-checkbox-dependencies)
11969 t ; if locally turned off don't block
11970 (catch 'dont-block
11971 ;; If this is not a todo state change, or if this entry is already DONE,
11972 ;; do not block
11973 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11974 (member (plist-get change-plist :from)
11975 (cons 'done org-done-keywords))
11976 (member (plist-get change-plist :to)
11977 (cons 'todo org-not-done-keywords))
11978 (not (plist-get change-plist :to)))
11979 (throw 'dont-block t))
11980 ;; If this task has checkboxes that are not checked, it's blocked
11981 (save-excursion
11982 (org-back-to-heading t)
11983 (let ((beg (point)) end)
11984 (outline-next-heading)
11985 (setq end (point))
11986 (goto-char beg)
11987 (if (org-list-search-forward
11988 (concat (org-item-beginning-re)
11989 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11990 "\\[[- ]\\]")
11991 end t)
11992 (progn
11993 (if (boundp 'org-blocked-by-checkboxes)
11994 (setq org-blocked-by-checkboxes t))
11995 (throw 'dont-block nil)))))
11996 t))) ; do not block
11998 (defun org-entry-blocked-p ()
11999 "Is the current entry blocked?"
12000 (if (org-entry-get nil "NOBLOCKING")
12001 nil ;; Never block this entry
12002 (not
12003 (run-hook-with-args-until-failure
12004 'org-blocker-hook
12005 (list :type 'todo-state-change
12006 :position (point)
12007 :from 'todo
12008 :to 'done)))))
12010 (defun org-update-statistics-cookies (all)
12011 "Update the statistics cookie, either from TODO or from checkboxes.
12012 This should be called with the cursor in a line with a statistics cookie."
12013 (interactive "P")
12014 (if all
12015 (progn
12016 (org-update-checkbox-count 'all)
12017 (org-map-entries 'org-update-parent-todo-statistics))
12018 (if (not (org-at-heading-p))
12019 (org-update-checkbox-count)
12020 (let ((pos (point-marker))
12021 end l1 l2)
12022 (ignore-errors (org-back-to-heading t))
12023 (if (not (org-at-heading-p))
12024 (org-update-checkbox-count)
12025 (setq l1 (org-outline-level))
12026 (setq end (save-excursion
12027 (outline-next-heading)
12028 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12029 (point)))
12030 (if (and (save-excursion
12031 (re-search-forward
12032 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12033 (not (save-excursion (re-search-forward
12034 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12035 (org-update-checkbox-count)
12036 (if (and l2 (> l2 l1))
12037 (progn
12038 (goto-char end)
12039 (org-update-parent-todo-statistics))
12040 (goto-char pos)
12041 (beginning-of-line 1)
12042 (while (re-search-forward
12043 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12044 (point-at-eol) t)
12045 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12046 (goto-char pos)
12047 (move-marker pos nil)))))
12049 (defvar org-entry-property-inherited-from) ;; defined below
12050 (defun org-update-parent-todo-statistics ()
12051 "Update any statistics cookie in the parent of the current headline.
12052 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12053 the entire subtree and this will travel up the hierarchy and update
12054 statistics everywhere."
12055 (let* ((prop (save-excursion (org-up-heading-safe)
12056 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12057 (recursive (or (not org-hierarchical-todo-statistics)
12058 (and prop (string-match "\\<recursive\\>" prop))))
12059 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12061 (first t)
12062 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12063 level ltoggle l1 new ndel
12064 (cnt-all 0) (cnt-done 0) is-percent kwd
12065 checkbox-beg ov ovs ove cookie-present)
12066 (catch 'exit
12067 (save-excursion
12068 (beginning-of-line 1)
12069 (setq ltoggle (funcall outline-level))
12070 ;; Three situations are to consider:
12072 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12073 ;; to the top-level ancestor on the headline;
12075 ;; 2. If parent has "recursive" property, repeat up to the
12076 ;; headline setting that property, taking inheritance into
12077 ;; account;
12079 ;; 3. Else, move up to direct parent and proceed only once.
12080 (while (and (setq level (org-up-heading-safe))
12081 (or recursive first)
12082 (>= (point) lim))
12083 (setq first nil cookie-present nil)
12084 (unless (and level
12085 (not (string-match
12086 "\\<checkbox\\>"
12087 (downcase (or (org-entry-get nil "COOKIE_DATA")
12088 "")))))
12089 (throw 'exit nil))
12090 (while (re-search-forward box-re (point-at-eol) t)
12091 (setq cnt-all 0 cnt-done 0 cookie-present t)
12092 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12093 (save-match-data
12094 (unless (outline-next-heading) (throw 'exit nil))
12095 (while (and (looking-at org-complex-heading-regexp)
12096 (> (setq l1 (length (match-string 1))) level))
12097 (setq kwd (and (or recursive (= l1 ltoggle))
12098 (match-string 2)))
12099 (if (or (eq org-provide-todo-statistics 'all-headlines)
12100 (and (listp org-provide-todo-statistics)
12101 (or (member kwd org-provide-todo-statistics)
12102 (member kwd org-done-keywords))))
12103 (setq cnt-all (1+ cnt-all))
12104 (if (eq org-provide-todo-statistics t)
12105 (and kwd (setq cnt-all (1+ cnt-all)))))
12106 (and (member kwd org-done-keywords)
12107 (setq cnt-done (1+ cnt-done)))
12108 (outline-next-heading)))
12109 (setq new
12110 (if is-percent
12111 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12112 (format "[%d/%d]" cnt-done cnt-all))
12113 ndel (- (match-end 0) checkbox-beg))
12114 ;; handle overlays when updating cookie from column view
12115 (when (setq ov (car (overlays-at checkbox-beg)))
12116 (setq ovs (overlay-start ov) ove (overlay-end ov))
12117 (delete-overlay ov))
12118 (goto-char checkbox-beg)
12119 (insert new)
12120 (delete-region (point) (+ (point) ndel))
12121 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12122 (when ov (move-overlay ov ovs ove)))
12123 (when cookie-present
12124 (run-hook-with-args 'org-after-todo-statistics-hook
12125 cnt-done (- cnt-all cnt-done))))))
12126 (run-hooks 'org-todo-statistics-hook)))
12128 (defvar org-after-todo-statistics-hook nil
12129 "Hook that is called after a TODO statistics cookie has been updated.
12130 Each function is called with two arguments: the number of not-done entries
12131 and the number of done entries.
12133 For example, the following function, when added to this hook, will switch
12134 an entry to DONE when all children are done, and back to TODO when new
12135 entries are set to a TODO status. Note that this hook is only called
12136 when there is a statistics cookie in the headline!
12138 (defun org-summary-todo (n-done n-not-done)
12139 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12140 (let (org-log-done org-log-states) ; turn off logging
12141 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12144 (defvar org-todo-statistics-hook nil
12145 "Hook that is run whenever Org thinks TODO statistics should be updated.
12146 This hook runs even if there is no statistics cookie present, in which case
12147 `org-after-todo-statistics-hook' would not run.")
12149 (defun org-todo-trigger-tag-changes (state)
12150 "Apply the changes defined in `org-todo-state-tags-triggers'."
12151 (let ((l org-todo-state-tags-triggers)
12152 changes)
12153 (when (or (not state) (equal state ""))
12154 (setq changes (append changes (cdr (assoc "" l)))))
12155 (when (and (stringp state) (> (length state) 0))
12156 (setq changes (append changes (cdr (assoc state l)))))
12157 (when (member state org-not-done-keywords)
12158 (setq changes (append changes (cdr (assoc 'todo l)))))
12159 (when (member state org-done-keywords)
12160 (setq changes (append changes (cdr (assoc 'done l)))))
12161 (dolist (c changes)
12162 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12164 (defun org-local-logging (value)
12165 "Get logging settings from a property VALUE."
12166 (let* (words w a)
12167 ;; directly set the variables, they are already local.
12168 (setq org-log-done nil
12169 org-log-repeat nil
12170 org-todo-log-states nil)
12171 (setq words (org-split-string value))
12172 (while (setq w (pop words))
12173 (cond
12174 ((setq a (assoc w org-startup-options))
12175 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12176 (set (nth 1 a) (nth 2 a))))
12177 ((setq a (org-extract-log-state-settings w))
12178 (and (member (car a) org-todo-keywords-1)
12179 (push a org-todo-log-states)))))))
12181 (defun org-get-todo-sequence-head (kwd)
12182 "Return the head of the TODO sequence to which KWD belongs.
12183 If KWD is not set, check if there is a text property remembering the
12184 right sequence."
12185 (let (p)
12186 (cond
12187 ((not kwd)
12188 (or (get-text-property (point-at-bol) 'org-todo-head)
12189 (progn
12190 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12191 nil (point-at-eol)))
12192 (get-text-property p 'org-todo-head))))
12193 ((not (member kwd org-todo-keywords-1))
12194 (car org-todo-keywords-1))
12195 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12197 (defun org-fast-todo-selection ()
12198 "Fast TODO keyword selection with single keys.
12199 Returns the new TODO keyword, or nil if no state change should occur."
12200 (let* ((fulltable org-todo-key-alist)
12201 (done-keywords org-done-keywords) ;; needed for the faces.
12202 (maxlen (apply 'max (mapcar
12203 (lambda (x)
12204 (if (stringp (car x)) (string-width (car x)) 0))
12205 fulltable)))
12206 (expert nil)
12207 (fwidth (+ maxlen 3 1 3))
12208 (ncol (/ (- (window-width) 4) fwidth))
12209 tg cnt e c tbl
12210 groups ingroup)
12211 (save-excursion
12212 (save-window-excursion
12213 (if expert
12214 (set-buffer (get-buffer-create " *Org todo*"))
12215 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12216 (erase-buffer)
12217 (org-set-local 'org-done-keywords done-keywords)
12218 (setq tbl fulltable cnt 0)
12219 (while (setq e (pop tbl))
12220 (cond
12221 ((equal e '(:startgroup))
12222 (push '() groups) (setq ingroup t)
12223 (when (not (= cnt 0))
12224 (setq cnt 0)
12225 (insert "\n"))
12226 (insert "{ "))
12227 ((equal e '(:endgroup))
12228 (setq ingroup nil cnt 0)
12229 (insert "}\n"))
12230 ((equal e '(:newline))
12231 (when (not (= cnt 0))
12232 (setq cnt 0)
12233 (insert "\n")
12234 (setq e (car tbl))
12235 (while (equal (car tbl) '(:newline))
12236 (insert "\n")
12237 (setq tbl (cdr tbl)))))
12239 (setq tg (car e) c (cdr e))
12240 (if ingroup (push tg (car groups)))
12241 (setq tg (org-add-props tg nil 'face
12242 (org-get-todo-face tg)))
12243 (if (and (= cnt 0) (not ingroup)) (insert " "))
12244 (insert "[" c "] " tg (make-string
12245 (- fwidth 4 (length tg)) ?\ ))
12246 (when (= (setq cnt (1+ cnt)) ncol)
12247 (insert "\n")
12248 (if ingroup (insert " "))
12249 (setq cnt 0)))))
12250 (insert "\n")
12251 (goto-char (point-min))
12252 (if (not expert) (org-fit-window-to-buffer))
12253 (message "[a-z..]:Set [SPC]:clear")
12254 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12255 (cond
12256 ((or (= c ?\C-g)
12257 (and (= c ?q) (not (rassoc c fulltable))))
12258 (setq quit-flag t))
12259 ((= c ?\ ) nil)
12260 ((setq e (rassoc c fulltable) tg (car e))
12262 (t (setq quit-flag t)))))))
12264 (defun org-entry-is-todo-p ()
12265 (member (org-get-todo-state) org-not-done-keywords))
12267 (defun org-entry-is-done-p ()
12268 (member (org-get-todo-state) org-done-keywords))
12270 (defun org-get-todo-state ()
12271 (save-excursion
12272 (org-back-to-heading t)
12273 (and (looking-at org-todo-line-regexp)
12274 (match-end 2)
12275 (match-string 2))))
12277 (defun org-at-date-range-p (&optional inactive-ok)
12278 "Is the cursor inside a date range?"
12279 (interactive)
12280 (save-excursion
12281 (catch 'exit
12282 (let ((pos (point)))
12283 (skip-chars-backward "^[<\r\n")
12284 (skip-chars-backward "<[")
12285 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12286 (>= (match-end 0) pos)
12287 (throw 'exit t))
12288 (skip-chars-backward "^<[\r\n")
12289 (skip-chars-backward "<[")
12290 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12291 (>= (match-end 0) pos)
12292 (throw 'exit t)))
12293 nil)))
12295 (defun org-get-repeat (&optional tagline)
12296 "Check if there is a deadline/schedule with repeater in this entry."
12297 (save-match-data
12298 (save-excursion
12299 (org-back-to-heading t)
12300 (and (re-search-forward (if tagline
12301 (concat tagline "\\s-*" org-repeat-re)
12302 org-repeat-re)
12303 (org-entry-end-position) t)
12304 (match-string-no-properties 1)))))
12306 (defvar org-last-changed-timestamp)
12307 (defvar org-last-inserted-timestamp)
12308 (defvar org-log-post-message)
12309 (defvar org-log-note-purpose)
12310 (defvar org-log-note-how)
12311 (defvar org-log-note-extra)
12312 (defun org-auto-repeat-maybe (done-word)
12313 "Check if the current headline contains a repeated deadline/schedule.
12314 If yes, set TODO state back to what it was and change the base date
12315 of repeating deadline/scheduled time stamps to new date.
12316 This function is run automatically after each state change to a DONE state."
12317 ;; last-state is dynamically scoped into this function
12318 (let* ((repeat (org-get-repeat))
12319 (aa (assoc org-last-state org-todo-kwd-alist))
12320 (interpret (nth 1 aa))
12321 (head (nth 2 aa))
12322 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12323 (msg "Entry repeats: ")
12324 (org-log-done nil)
12325 (org-todo-log-states nil)
12326 re type n what ts time to-state)
12327 (when repeat
12328 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12329 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12330 org-todo-repeat-to-state))
12331 (unless (and to-state (member to-state org-todo-keywords-1))
12332 (setq to-state (if (eq interpret 'type) org-last-state head)))
12333 (org-todo to-state)
12334 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12335 (org-entry-put nil "LAST_REPEAT" (format-time-string
12336 (org-time-stamp-format t t))))
12337 (when org-log-repeat
12338 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12339 (memq 'org-add-log-note post-command-hook))
12340 ;; OK, we are already setup for some record
12341 (if (eq org-log-repeat 'note)
12342 ;; make sure we take a note, not only a time stamp
12343 (setq org-log-note-how 'note))
12344 ;; Set up for taking a record
12345 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12346 org-last-state
12347 'findpos org-log-repeat)))
12348 (org-back-to-heading t)
12349 (org-add-planning-info nil nil 'closed)
12350 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12351 org-deadline-time-regexp "\\)\\|\\("
12352 org-ts-regexp "\\)"))
12353 (while (re-search-forward
12354 re (save-excursion (outline-next-heading) (point)) t)
12355 (setq type (if (match-end 1) org-scheduled-string
12356 (if (match-end 3) org-deadline-string "Plain:"))
12357 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12358 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12359 (setq n (string-to-number (match-string 2 ts))
12360 what (match-string 3 ts))
12361 (if (equal what "w") (setq n (* n 7) what "d"))
12362 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12363 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12364 ;; Preparation, see if we need to modify the start date for the change
12365 (when (match-end 1)
12366 (setq time (save-match-data (org-time-string-to-time ts)))
12367 (cond
12368 ((equal (match-string 1 ts) ".")
12369 ;; Shift starting date to today
12370 (org-timestamp-change
12371 (- (org-today) (time-to-days time))
12372 'day))
12373 ((equal (match-string 1 ts) "+")
12374 (let ((nshiftmax 10) (nshift 0))
12375 (while (or (= nshift 0)
12376 (<= (time-to-days time)
12377 (time-to-days (current-time))))
12378 (when (= (incf nshift) nshiftmax)
12379 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12380 (error "Abort")))
12381 (org-timestamp-change n (cdr (assoc what whata)))
12382 (org-at-timestamp-p t)
12383 (setq ts (match-string 1))
12384 (setq time (save-match-data (org-time-string-to-time ts)))))
12385 (org-timestamp-change (- n) (cdr (assoc what whata)))
12386 ;; rematch, so that we have everything in place for the real shift
12387 (org-at-timestamp-p t)
12388 (setq ts (match-string 1))
12389 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12390 (org-timestamp-change n (cdr (assoc what whata)))
12391 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12392 (setq org-log-post-message msg)
12393 (message "%s" msg))))
12395 (defun org-show-todo-tree (arg)
12396 "Make a compact tree which shows all headlines marked with TODO.
12397 The tree will show the lines where the regexp matches, and all higher
12398 headlines above the match.
12399 With a \\[universal-argument] prefix, prompt for a regexp to match.
12400 With a numeric prefix N, construct a sparse tree for the Nth element
12401 of `org-todo-keywords-1'."
12402 (interactive "P")
12403 (let ((case-fold-search nil)
12404 (kwd-re
12405 (cond ((null arg) org-not-done-regexp)
12406 ((equal arg '(4))
12407 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12408 (mapcar 'list org-todo-keywords-1))))
12409 (concat "\\("
12410 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12411 "\\)\\>")))
12412 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12413 (regexp-quote (nth (1- (prefix-numeric-value arg))
12414 org-todo-keywords-1)))
12415 (t (error "Invalid prefix argument: %s" arg)))))
12416 (message "%d TODO entries found"
12417 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12419 (defun org-deadline (&optional remove time)
12420 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12421 With argument REMOVE, remove any deadline from the item.
12422 With argument TIME, set the deadline at the corresponding date. TIME
12423 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12424 (interactive "P")
12425 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12426 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12427 'region-start-level 'region))
12428 org-loop-over-headlines-in-active-region)
12429 (org-map-entries
12430 `(org-deadline ',remove ,time)
12431 org-loop-over-headlines-in-active-region
12432 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12433 (let* ((old-date (org-entry-get nil "DEADLINE"))
12434 (repeater (and old-date
12435 (string-match
12436 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12437 old-date)
12438 (match-string 1 old-date))))
12439 (if remove
12440 (progn
12441 (when (and old-date org-log-redeadline)
12442 (org-add-log-setup 'deldeadline nil old-date 'findpos
12443 org-log-redeadline))
12444 (org-remove-timestamp-with-keyword org-deadline-string)
12445 (message "Item no longer has a deadline."))
12446 (org-add-planning-info 'deadline time 'closed)
12447 (when (and old-date org-log-redeadline
12448 (not (equal old-date
12449 (substring org-last-inserted-timestamp 1 -1))))
12450 (org-add-log-setup 'redeadline nil old-date 'findpos
12451 org-log-redeadline))
12452 (when repeater
12453 (save-excursion
12454 (org-back-to-heading t)
12455 (when (re-search-forward (concat org-deadline-string " "
12456 org-last-inserted-timestamp)
12457 (save-excursion
12458 (outline-next-heading) (point)) t)
12459 (goto-char (1- (match-end 0)))
12460 (insert " " repeater)
12461 (setq org-last-inserted-timestamp
12462 (concat (substring org-last-inserted-timestamp 0 -1)
12463 " " repeater
12464 (substring org-last-inserted-timestamp -1))))))
12465 (message "Deadline on %s" org-last-inserted-timestamp)))))
12467 (defun org-schedule (&optional remove time)
12468 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12469 With argument REMOVE, remove any scheduling date from the item.
12470 With argument TIME, scheduled at the corresponding date. TIME can
12471 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12472 (interactive "P")
12473 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12474 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12475 'region-start-level 'region))
12476 org-loop-over-headlines-in-active-region)
12477 (org-map-entries
12478 `(org-schedule ',remove ,time)
12479 org-loop-over-headlines-in-active-region
12480 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12481 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12482 (repeater (and old-date
12483 (string-match
12484 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12485 old-date)
12486 (match-string 1 old-date))))
12487 (if remove
12488 (progn
12489 (when (and old-date org-log-reschedule)
12490 (org-add-log-setup 'delschedule nil old-date 'findpos
12491 org-log-reschedule))
12492 (org-remove-timestamp-with-keyword org-scheduled-string)
12493 (message "Item is no longer scheduled."))
12494 (org-add-planning-info 'scheduled time 'closed)
12495 (when (and old-date org-log-reschedule
12496 (not (equal old-date
12497 (substring org-last-inserted-timestamp 1 -1))))
12498 (org-add-log-setup 'reschedule nil old-date 'findpos
12499 org-log-reschedule))
12500 (when repeater
12501 (save-excursion
12502 (org-back-to-heading t)
12503 (when (re-search-forward (concat org-scheduled-string " "
12504 org-last-inserted-timestamp)
12505 (save-excursion
12506 (outline-next-heading) (point)) t)
12507 (goto-char (1- (match-end 0)))
12508 (insert " " repeater)
12509 (setq org-last-inserted-timestamp
12510 (concat (substring org-last-inserted-timestamp 0 -1)
12511 " " repeater
12512 (substring org-last-inserted-timestamp -1))))))
12513 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12515 (defun org-get-scheduled-time (pom &optional inherit)
12516 "Get the scheduled time as a time tuple, of a format suitable
12517 for calling org-schedule with, or if there is no scheduling,
12518 returns nil."
12519 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12520 (when time
12521 (apply 'encode-time (org-parse-time-string time)))))
12523 (defun org-get-deadline-time (pom &optional inherit)
12524 "Get the deadline as a time tuple, of a format suitable for
12525 calling org-deadline with, or if there is no scheduling, returns
12526 nil."
12527 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12528 (when time
12529 (apply 'encode-time (org-parse-time-string time)))))
12531 (defun org-remove-timestamp-with-keyword (keyword)
12532 "Remove all time stamps with KEYWORD in the current entry."
12533 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12534 beg)
12535 (save-excursion
12536 (org-back-to-heading t)
12537 (setq beg (point))
12538 (outline-next-heading)
12539 (while (re-search-backward re beg t)
12540 (replace-match "")
12541 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12542 (equal (char-before) ?\ ))
12543 (backward-delete-char 1)
12544 (if (string-match "^[ \t]*$" (buffer-substring
12545 (point-at-bol) (point-at-eol)))
12546 (delete-region (point-at-bol)
12547 (min (point-max) (1+ (point-at-eol))))))))))
12549 (defun org-add-planning-info (what &optional time &rest remove)
12550 "Insert new timestamp with keyword in the line directly after the headline.
12551 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12552 If non is given, the user is prompted for a date.
12553 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12554 be removed."
12555 (interactive)
12556 (let (org-time-was-given org-end-time-was-given ts
12557 end default-time default-input)
12559 (catch 'exit
12560 (when (and (memq what '(scheduled deadline))
12561 (or (not time)
12562 (and (stringp time)
12563 (string-match "^[-+]+[0-9]" time))))
12564 ;; Try to get a default date/time from existing timestamp
12565 (save-excursion
12566 (org-back-to-heading t)
12567 (setq end (save-excursion (outline-next-heading) (point)))
12568 (when (re-search-forward (if (eq what 'scheduled)
12569 org-scheduled-time-regexp
12570 org-deadline-time-regexp)
12571 end t)
12572 (setq ts (match-string 1)
12573 default-time
12574 (apply 'encode-time (org-parse-time-string ts))
12575 default-input (and ts (org-get-compact-tod ts))))))
12576 (when what
12577 (setq time
12578 (if (stringp time)
12579 ;; This is a string (relative or absolute), set proper date
12580 (apply 'encode-time
12581 (org-read-date-analyze
12582 time default-time (decode-time default-time)))
12583 ;; If necessary, get the time from the user
12584 (or time (org-read-date nil 'to-time nil nil
12585 default-time default-input)))))
12587 (when (and org-insert-labeled-timestamps-at-point
12588 (member what '(scheduled deadline)))
12589 (insert
12590 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12591 (org-insert-time-stamp time org-time-was-given
12592 nil nil nil (list org-end-time-was-given))
12593 (setq what nil))
12594 (save-excursion
12595 (save-restriction
12596 (let (col list elt ts buffer-invisibility-spec)
12597 (org-back-to-heading t)
12598 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12599 (goto-char (match-end 1))
12600 (setq col (current-column))
12601 (goto-char (match-end 0))
12602 (if (eobp) (insert "\n") (forward-char 1))
12603 (when (and (not what)
12604 (not (looking-at
12605 (concat "[ \t]*"
12606 org-keyword-time-not-clock-regexp))))
12607 ;; Nothing to add, nothing to remove...... :-)
12608 (throw 'exit nil))
12609 (if (and (not (looking-at org-outline-regexp))
12610 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12611 "[^\r\n]*"))
12612 (not (equal (match-string 1) org-clock-string)))
12613 (narrow-to-region (match-beginning 0) (match-end 0))
12614 (insert-before-markers "\n")
12615 (backward-char 1)
12616 (narrow-to-region (point) (point))
12617 (and org-adapt-indentation (org-indent-to-column col)))
12618 ;; Check if we have to remove something.
12619 (setq list (cons what remove))
12620 (while list
12621 (setq elt (pop list))
12622 (when (or (and (eq elt 'scheduled)
12623 (re-search-forward org-scheduled-time-regexp nil t))
12624 (and (eq elt 'deadline)
12625 (re-search-forward org-deadline-time-regexp nil t))
12626 (and (eq elt 'closed)
12627 (re-search-forward org-closed-time-regexp nil t)))
12628 (replace-match "")
12629 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12630 (and (looking-at "[ \t]+") (replace-match ""))
12631 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12632 (when what
12633 (insert
12634 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12635 (cond ((eq what 'scheduled) org-scheduled-string)
12636 ((eq what 'deadline) org-deadline-string)
12637 ((eq what 'closed) org-closed-string))
12638 " ")
12639 (setq ts (org-insert-time-stamp
12640 time
12641 (or org-time-was-given
12642 (and (eq what 'closed) org-log-done-with-time))
12643 (eq what 'closed)
12644 nil nil (list org-end-time-was-given)))
12645 (insert
12646 (if (not (or (bolp) (eq (char-before) ?\ )
12647 (memq (char-after) '(32 10))
12648 (eobp))) " " ""))
12649 (end-of-line 1))
12650 (goto-char (point-min))
12651 (widen)
12652 (if (and (looking-at "[ \t]*\n")
12653 (equal (char-before) ?\n))
12654 (delete-region (1- (point)) (point-at-eol)))
12655 ts))))))
12657 (defvar org-log-note-marker (make-marker))
12658 (defvar org-log-note-purpose nil)
12659 (defvar org-log-note-state nil)
12660 (defvar org-log-note-previous-state nil)
12661 (defvar org-log-note-how nil)
12662 (defvar org-log-note-extra nil)
12663 (defvar org-log-note-window-configuration nil)
12664 (defvar org-log-note-return-to (make-marker))
12665 (defvar org-log-note-effective-time nil
12666 "Remembered current time so that dynamically scoped
12667 `org-extend-today-until' affects tha timestamps in state change
12668 log")
12670 (defvar org-log-post-message nil
12671 "Message to be displayed after a log note has been stored.
12672 The auto-repeater uses this.")
12674 (defun org-add-note ()
12675 "Add a note to the current entry.
12676 This is done in the same way as adding a state change note."
12677 (interactive)
12678 (org-add-log-setup 'note nil nil 'findpos nil))
12680 (defvar org-property-end-re)
12681 (defun org-add-log-setup (&optional purpose state prev-state
12682 findpos how extra)
12683 "Set up the post command hook to take a note.
12684 If this is about to TODO state change, the new state is expected in STATE.
12685 When FINDPOS is non-nil, find the correct position for the note in
12686 the current entry. If not, assume that it can be inserted at point.
12687 HOW is an indicator what kind of note should be created.
12688 EXTRA is additional text that will be inserted into the notes buffer."
12689 (let* ((org-log-into-drawer (org-log-into-drawer))
12690 (drawer (cond ((stringp org-log-into-drawer)
12691 org-log-into-drawer)
12692 (org-log-into-drawer "LOGBOOK"))))
12693 (save-restriction
12694 (save-excursion
12695 (when findpos
12696 (org-back-to-heading t)
12697 (narrow-to-region (point) (save-excursion
12698 (outline-next-heading) (point)))
12699 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12700 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12701 "[^\r\n]*\\)?"))
12702 (goto-char (match-end 0))
12703 (cond
12704 (drawer
12705 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12706 nil t)
12707 (progn
12708 (goto-char (match-end 0))
12709 (or org-log-states-order-reversed
12710 (and (re-search-forward org-property-end-re nil t)
12711 (goto-char (1- (match-beginning 0))))))
12712 (insert "\n:" drawer ":\n:END:")
12713 (beginning-of-line 0)
12714 (org-indent-line)
12715 (beginning-of-line 2)
12716 (org-indent-line)
12717 (end-of-line 0)))
12718 ((and org-log-state-notes-insert-after-drawers
12719 (save-excursion
12720 (forward-line) (looking-at org-drawer-regexp)))
12721 (forward-line)
12722 (while (looking-at org-drawer-regexp)
12723 (goto-char (match-end 0))
12724 (re-search-forward org-property-end-re (point-max) t)
12725 (forward-line))
12726 (forward-line -1)))
12727 (unless org-log-states-order-reversed
12728 (and (= (char-after) ?\n) (forward-char 1))
12729 (org-skip-over-state-notes)
12730 (skip-chars-backward " \t\n\r")))
12731 (move-marker org-log-note-marker (point))
12732 (setq org-log-note-purpose purpose
12733 org-log-note-state state
12734 org-log-note-previous-state prev-state
12735 org-log-note-how how
12736 org-log-note-extra extra
12737 org-log-note-effective-time (org-current-effective-time))
12738 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12740 (defun org-skip-over-state-notes ()
12741 "Skip past the list of State notes in an entry."
12742 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12743 (when (ignore-errors (goto-char (org-in-item-p)))
12744 (let* ((struct (org-list-struct))
12745 (prevs (org-list-prevs-alist struct)))
12746 (while (looking-at "[ \t]*- State")
12747 (goto-char (or (org-list-get-next-item (point) struct prevs)
12748 (org-list-get-item-end (point) struct)))))))
12750 (defun org-add-log-note (&optional purpose)
12751 "Pop up a window for taking a note, and add this note later at point."
12752 (remove-hook 'post-command-hook 'org-add-log-note)
12753 (setq org-log-note-window-configuration (current-window-configuration))
12754 (delete-other-windows)
12755 (move-marker org-log-note-return-to (point))
12756 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12757 (goto-char org-log-note-marker)
12758 (org-switch-to-buffer-other-window "*Org Note*")
12759 (erase-buffer)
12760 (if (memq org-log-note-how '(time state))
12761 (let (current-prefix-arg) (org-store-log-note))
12762 (let ((org-inhibit-startup t)) (org-mode))
12763 (insert (format "# Insert note for %s.
12764 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12765 (cond
12766 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12767 ((eq org-log-note-purpose 'done) "closed todo item")
12768 ((eq org-log-note-purpose 'state)
12769 (format "state change from \"%s\" to \"%s\""
12770 (or org-log-note-previous-state "")
12771 (or org-log-note-state "")))
12772 ((eq org-log-note-purpose 'reschedule)
12773 "rescheduling")
12774 ((eq org-log-note-purpose 'delschedule)
12775 "no longer scheduled")
12776 ((eq org-log-note-purpose 'redeadline)
12777 "changing deadline")
12778 ((eq org-log-note-purpose 'deldeadline)
12779 "removing deadline")
12780 ((eq org-log-note-purpose 'refile)
12781 "refiling")
12782 ((eq org-log-note-purpose 'note)
12783 "this entry")
12784 (t (error "This should not happen")))))
12785 (if org-log-note-extra (insert org-log-note-extra))
12786 (org-set-local 'org-finish-function 'org-store-log-note)
12787 (run-hooks 'org-log-buffer-setup-hook)))
12789 (defvar org-note-abort nil) ; dynamically scoped
12790 (defun org-store-log-note ()
12791 "Finish taking a log note, and insert it to where it belongs."
12792 (let ((txt (buffer-string)))
12793 (kill-buffer (current-buffer))
12794 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12795 lines ind bul)
12796 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12797 (setq txt (replace-match "" t t txt)))
12798 (if (string-match "\\s-+\\'" txt)
12799 (setq txt (replace-match "" t t txt)))
12800 (setq lines (org-split-string txt "\n"))
12801 (when (and note (string-match "\\S-" note))
12802 (setq note
12803 (org-replace-escapes
12804 note
12805 (list (cons "%u" (user-login-name))
12806 (cons "%U" user-full-name)
12807 (cons "%t" (format-time-string
12808 (org-time-stamp-format 'long 'inactive)
12809 org-log-note-effective-time))
12810 (cons "%T" (format-time-string
12811 (org-time-stamp-format 'long nil)
12812 org-log-note-effective-time))
12813 (cons "%d" (format-time-string
12814 (org-time-stamp-format nil 'inactive)
12815 org-log-note-effective-time))
12816 (cons "%D" (format-time-string
12817 (org-time-stamp-format nil nil)
12818 org-log-note-effective-time))
12819 (cons "%s" (if org-log-note-state
12820 (concat "\"" org-log-note-state "\"")
12821 ""))
12822 (cons "%S" (if org-log-note-previous-state
12823 (concat "\"" org-log-note-previous-state "\"")
12824 "\"\"")))))
12825 (if lines (setq note (concat note " \\\\")))
12826 (push note lines))
12827 (when (or current-prefix-arg org-note-abort)
12828 (when org-log-into-drawer
12829 (org-remove-empty-drawer-at
12830 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12831 org-log-note-marker))
12832 (setq lines nil))
12833 (when lines
12834 (with-current-buffer (marker-buffer org-log-note-marker)
12835 (save-excursion
12836 (goto-char org-log-note-marker)
12837 (move-marker org-log-note-marker nil)
12838 (end-of-line 1)
12839 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12840 (setq ind (save-excursion
12841 (if (ignore-errors (goto-char (org-in-item-p)))
12842 (let ((struct (org-list-struct)))
12843 (org-list-get-ind
12844 (org-list-get-top-point struct) struct))
12845 (skip-chars-backward " \r\t\n")
12846 (cond
12847 ((and (org-at-heading-p)
12848 org-adapt-indentation)
12849 (1+ (org-current-level)))
12850 ((org-at-heading-p) 0)
12851 (t (org-get-indentation))))))
12852 (setq bul (org-list-bullet-string "-"))
12853 (org-indent-line-to ind)
12854 (insert bul (pop lines))
12855 (let ((ind-body (+ (length bul) ind)))
12856 (while lines
12857 (insert "\n")
12858 (org-indent-line-to ind-body)
12859 (insert (pop lines))))
12860 (message "Note stored")
12861 (org-back-to-heading t)
12862 (org-cycle-hide-drawers 'children))))))
12863 (set-window-configuration org-log-note-window-configuration)
12864 (with-current-buffer (marker-buffer org-log-note-return-to)
12865 (goto-char org-log-note-return-to))
12866 (move-marker org-log-note-return-to nil)
12867 (and org-log-post-message (message "%s" org-log-post-message)))
12869 (defun org-remove-empty-drawer-at (drawer pos)
12870 "Remove an empty drawer DRAWER at position POS.
12871 POS may also be a marker."
12872 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12873 (save-excursion
12874 (save-restriction
12875 (widen)
12876 (goto-char pos)
12877 (if (org-in-regexp
12878 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12879 (replace-match ""))))))
12881 (defvar org-ts-type nil)
12882 (defun org-sparse-tree (&optional arg type)
12883 "Create a sparse tree, prompt for the details.
12884 This command can create sparse trees. You first need to select the type
12885 of match used to create the tree:
12887 t Show all TODO entries.
12888 T Show entries with a specific TODO keyword.
12889 m Show entries selected by a tags/property match.
12890 p Enter a property name and its value (both with completion on existing
12891 names/values) and show entries with that property.
12892 r Show entries matching a regular expression (`/' can be used as well).
12893 b Show deadlines and scheduled items before a date.
12894 a Show deadlines and scheduled items after a date.
12895 d Show deadlines due within `org-deadline-warning-days'.
12896 D Show deadlines and scheduled items between a date range."
12897 (interactive "P")
12898 (let (ans kwd value ts-type)
12899 (setq type (or type org-sparse-tree-default-date-type))
12900 (setq org-ts-type type)
12901 (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\n [c]ycle through date types: %s"
12902 (cond ((eq type 'all) "all timestamps")
12903 ((eq type 'scheduled) "only scheduled")
12904 ((eq type 'deadline) "only deadline")
12905 ((eq type 'active) "only active timestamps")
12906 ((eq type 'inactive) "only inactive timestamps")
12907 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12908 (t "scheduled/deadline")))
12909 (setq ans (read-char-exclusive))
12910 (cond
12911 ((equal ans ?c)
12912 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12913 ((equal ans ?d)
12914 (call-interactively 'org-check-deadlines))
12915 ((equal ans ?b)
12916 (call-interactively 'org-check-before-date))
12917 ((equal ans ?a)
12918 (call-interactively 'org-check-after-date))
12919 ((equal ans ?D)
12920 (call-interactively 'org-check-dates-range))
12921 ((equal ans ?t)
12922 (call-interactively 'org-show-todo-tree))
12923 ((equal ans ?T)
12924 (org-show-todo-tree '(4)))
12925 ((member ans '(?T ?m))
12926 (call-interactively 'org-match-sparse-tree))
12927 ((member ans '(?p ?P))
12928 (setq kwd (org-icompleting-read "Property: "
12929 (mapcar 'list (org-buffer-property-keys))))
12930 (setq value (org-icompleting-read "Value: "
12931 (mapcar 'list (org-property-values kwd))))
12932 (unless (string-match "\\`{.*}\\'" value)
12933 (setq value (concat "\"" value "\"")))
12934 (org-match-sparse-tree arg (concat kwd "=" value)))
12935 ((member ans '(?r ?R ?/))
12936 (call-interactively 'org-occur))
12937 (t (error "No such sparse tree command \"%c\"" ans)))))
12939 (defvar org-occur-highlights nil
12940 "List of overlays used for occur matches.")
12941 (make-variable-buffer-local 'org-occur-highlights)
12942 (defvar org-occur-parameters nil
12943 "Parameters of the active org-occur calls.
12944 This is a list, each call to org-occur pushes as cons cell,
12945 containing the regular expression and the callback, onto the list.
12946 The list can contain several entries if `org-occur' has been called
12947 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12948 will only contain one set of parameters. When the highlights are
12949 removed (for example with `C-c C-c', or with the next edit (depending
12950 on `org-remove-highlights-with-change'), this variable is emptied
12951 as well.")
12952 (make-variable-buffer-local 'org-occur-parameters)
12954 (defun org-occur (regexp &optional keep-previous callback)
12955 "Make a compact tree which shows all matches of REGEXP.
12956 The tree will show the lines where the regexp matches, and all higher
12957 headlines above the match. It will also show the heading after the match,
12958 to make sure editing the matching entry is easy.
12959 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12960 call to `org-occur' will be kept, to allow stacking of calls to this
12961 command.
12962 If CALLBACK is non-nil, it is a function which is called to confirm
12963 that the match should indeed be shown."
12964 (interactive "sRegexp: \nP")
12965 (when (equal regexp "")
12966 (error "Regexp cannot be empty"))
12967 (unless keep-previous
12968 (org-remove-occur-highlights nil nil t))
12969 (push (cons regexp callback) org-occur-parameters)
12970 (let ((cnt 0))
12971 (save-excursion
12972 (goto-char (point-min))
12973 (if (or (not keep-previous) ; do not want to keep
12974 (not org-occur-highlights)) ; no previous matches
12975 ;; hide everything
12976 (org-overview))
12977 (while (re-search-forward regexp nil t)
12978 (when (or (not callback)
12979 (save-match-data (funcall callback)))
12980 (setq cnt (1+ cnt))
12981 (when org-highlight-sparse-tree-matches
12982 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12983 (org-show-context 'occur-tree))))
12984 (when org-remove-highlights-with-change
12985 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12986 nil 'local))
12987 (unless org-sparse-tree-open-archived-trees
12988 (org-hide-archived-subtrees (point-min) (point-max)))
12989 (run-hooks 'org-occur-hook)
12990 (if (org-called-interactively-p 'interactive)
12991 (message "%d match(es) for regexp %s" cnt regexp))
12992 cnt))
12994 (defun org-occur-next-match (&optional n reset)
12995 "Function for `next-error-function' to find sparse tree matches.
12996 N is the number of matches to move, when negative move backwards.
12997 RESET is entirely ignored - this function always goes back to the
12998 starting point when no match is found."
12999 (let* ((limit (if (< n 0) (point-min) (point-max)))
13000 (search-func (if (< n 0)
13001 'previous-single-char-property-change
13002 'next-single-char-property-change))
13003 (n (abs n))
13004 (pos (point))
13006 (catch 'exit
13007 (while (setq p1 (funcall search-func (point) 'org-type))
13008 (when (equal p1 limit)
13009 (goto-char pos)
13010 (error "No more matches"))
13011 (when (equal (get-char-property p1 'org-type) 'org-occur)
13012 (setq n (1- n))
13013 (when (= n 0)
13014 (goto-char p1)
13015 (throw 'exit (point))))
13016 (goto-char p1))
13017 (goto-char p1)
13018 (error "No more matches"))))
13020 (defun org-show-context (&optional key)
13021 "Make sure point and context are visible.
13022 How much context is shown depends upon the variables
13023 `org-show-hierarchy-above', `org-show-following-heading',
13024 `org-show-entry-below' and `org-show-siblings'."
13025 (let ((heading-p (org-at-heading-p t))
13026 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13027 (following-p (org-get-alist-option org-show-following-heading key))
13028 (entry-p (org-get-alist-option org-show-entry-below key))
13029 (siblings-p (org-get-alist-option org-show-siblings key)))
13030 (catch 'exit
13031 ;; Show heading or entry text
13032 (if (and heading-p (not entry-p))
13033 (org-flag-heading nil) ; only show the heading
13034 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13035 (org-show-hidden-entry))) ; show entire entry
13036 (when following-p
13037 ;; Show next sibling, or heading below text
13038 (save-excursion
13039 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13040 (org-flag-heading nil))))
13041 (when siblings-p (org-show-siblings))
13042 (when hierarchy-p
13043 ;; show all higher headings, possibly with siblings
13044 (save-excursion
13045 (while (and (condition-case nil
13046 (progn (org-up-heading-all 1) t)
13047 (error nil))
13048 (not (bobp)))
13049 (org-flag-heading nil)
13050 (when siblings-p (org-show-siblings))))))))
13052 (defvar org-reveal-start-hook nil
13053 "Hook run before revealing a location.")
13055 (defun org-reveal (&optional siblings)
13056 "Show current entry, hierarchy above it, and the following headline.
13057 This can be used to show a consistent set of context around locations
13058 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13059 not t for the search context.
13061 With optional argument SIBLINGS, on each level of the hierarchy all
13062 siblings are shown. This repairs the tree structure to what it would
13063 look like when opened with hierarchical calls to `org-cycle'.
13064 With double optional argument \\[universal-argument] \\[universal-argument], \
13065 go to the parent and show the
13066 entire tree."
13067 (interactive "P")
13068 (run-hooks 'org-reveal-start-hook)
13069 (let ((org-show-hierarchy-above t)
13070 (org-show-following-heading t)
13071 (org-show-siblings (if siblings t org-show-siblings)))
13072 (org-show-context nil))
13073 (when (equal siblings '(16))
13074 (save-excursion
13075 (when (org-up-heading-safe)
13076 (org-show-subtree)
13077 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13079 (defun org-highlight-new-match (beg end)
13080 "Highlight from BEG to END and mark the highlight is an occur headline."
13081 (let ((ov (make-overlay beg end)))
13082 (overlay-put ov 'face 'secondary-selection)
13083 (overlay-put ov 'org-type 'org-occur)
13084 (push ov org-occur-highlights)))
13086 (defun org-remove-occur-highlights (&optional beg end noremove)
13087 "Remove the occur highlights from the buffer.
13088 BEG and END are ignored. If NOREMOVE is nil, remove this function
13089 from the `before-change-functions' in the current buffer."
13090 (interactive)
13091 (unless org-inhibit-highlight-removal
13092 (mapc 'delete-overlay org-occur-highlights)
13093 (setq org-occur-highlights nil)
13094 (setq org-occur-parameters nil)
13095 (unless noremove
13096 (remove-hook 'before-change-functions
13097 'org-remove-occur-highlights 'local))))
13099 ;;;; Priorities
13101 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13102 "Regular expression matching the priority indicator.")
13104 (defvar org-remove-priority-next-time nil)
13106 (defun org-priority-up ()
13107 "Increase the priority of the current item."
13108 (interactive)
13109 (org-priority 'up))
13111 (defun org-priority-down ()
13112 "Decrease the priority of the current item."
13113 (interactive)
13114 (org-priority 'down))
13116 (defun org-priority (&optional action show)
13117 "Change the priority of an item.
13118 ACTION can be `set', `up', `down', or a character."
13119 (interactive "P")
13120 (if (equal action '(4))
13121 (org-show-priority)
13122 (unless org-enable-priority-commands
13123 (error "Priority commands are disabled"))
13124 (setq action (or action 'set))
13125 (let (current new news have remove)
13126 (save-excursion
13127 (org-back-to-heading t)
13128 (if (looking-at org-priority-regexp)
13129 (setq current (string-to-char (match-string 2))
13130 have t))
13131 (cond
13132 ((eq action 'remove)
13133 (setq remove t new ?\ ))
13134 ((or (eq action 'set)
13135 (if (featurep 'xemacs) (characterp action) (integerp action)))
13136 (if (not (eq action 'set))
13137 (setq new action)
13138 (message "Priority %c-%c, SPC to remove: "
13139 org-highest-priority org-lowest-priority)
13140 (save-match-data
13141 (setq new (read-char-exclusive))))
13142 (if (and (= (upcase org-highest-priority) org-highest-priority)
13143 (= (upcase org-lowest-priority) org-lowest-priority))
13144 (setq new (upcase new)))
13145 (cond ((equal new ?\ ) (setq remove t))
13146 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13147 (error "Priority must be between `%c' and `%c'"
13148 org-highest-priority org-lowest-priority))))
13149 ((eq action 'up)
13150 (setq new (if have
13151 (1- current) ; normal cycling
13152 ;; last priority was empty
13153 (if (eq last-command this-command)
13154 org-lowest-priority ; wrap around empty to lowest
13155 ;; default
13156 (if org-priority-start-cycle-with-default
13157 org-default-priority
13158 (1- org-default-priority))))))
13159 ((eq action 'down)
13160 (setq new (if have
13161 (1+ current) ; normal cycling
13162 ;; last priority was empty
13163 (if (eq last-command this-command)
13164 org-highest-priority ; wrap around empty to highest
13165 ;; default
13166 (if org-priority-start-cycle-with-default
13167 org-default-priority
13168 (1+ org-default-priority))))))
13169 (t (error "Invalid action")))
13170 (if (or (< (upcase new) org-highest-priority)
13171 (> (upcase new) org-lowest-priority))
13172 (if (and (memq action '(up down))
13173 (not have) (not (eq last-command this-command)))
13174 ;; `new' is from default priority
13175 (error
13176 "The default can not be set, see `org-default-priority' why")
13177 ;; normal cycling: `new' is beyond highest/lowest priority
13178 ;; and is wrapped around to the empty priority
13179 (setq remove t)))
13180 (setq news (format "%c" new))
13181 (if have
13182 (if remove
13183 (replace-match "" t t nil 1)
13184 (replace-match news t t nil 2))
13185 (if remove
13186 (error "No priority cookie found in line")
13187 (let ((case-fold-search nil))
13188 (looking-at org-todo-line-regexp))
13189 (if (match-end 2)
13190 (progn
13191 (goto-char (match-end 2))
13192 (insert " [#" news "]"))
13193 (goto-char (match-beginning 3))
13194 (insert "[#" news "] "))))
13195 (org-preserve-lc (org-set-tags nil 'align)))
13196 (if remove
13197 (message "Priority removed")
13198 (message "Priority of current item set to %s" news)))))
13200 (defun org-show-priority ()
13201 "Show the priority of the current item.
13202 This priority is composed of the main priority given with the [#A] cookies,
13203 and by additional input from the age of a schedules or deadline entry."
13204 (interactive)
13205 (let ((pri (if (eq major-mode 'org-agenda-mode)
13206 (org-get-at-bol 'priority)
13207 (save-excursion
13208 (save-match-data
13209 (beginning-of-line)
13210 (and (looking-at org-heading-regexp)
13211 (org-get-priority (match-string 0))))))))
13212 (message "Priority is %d" (if pri pri -1000))))
13214 (defun org-get-priority (s)
13215 "Find priority cookie and return priority."
13216 (if (functionp org-get-priority-function)
13217 (funcall org-get-priority-function)
13218 (save-match-data
13219 (if (not (string-match org-priority-regexp s))
13220 (* 1000 (- org-lowest-priority org-default-priority))
13221 (* 1000 (- org-lowest-priority
13222 (string-to-char (match-string 2 s))))))))
13224 ;;;; Tags
13226 (defvar org-agenda-archives-mode)
13227 (defvar org-map-continue-from nil
13228 "Position from where mapping should continue.
13229 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13231 (defvar org-scanner-tags nil
13232 "The current tag list while the tags scanner is running.")
13233 (defvar org-trust-scanner-tags nil
13234 "Should `org-get-tags-at' use the tags for the scanner.
13235 This is for internal dynamical scoping only.
13236 When this is non-nil, the function `org-get-tags-at' will return the value
13237 of `org-scanner-tags' instead of building the list by itself. This
13238 can lead to large speed-ups when the tags scanner is used in a file with
13239 many entries, and when the list of tags is retrieved, for example to
13240 obtain a list of properties. Building the tags list for each entry in such
13241 a file becomes an N^2 operation - but with this variable set, it scales
13242 as N.")
13244 (defun org-scan-tags (action matcher todo-only &optional start-level)
13245 "Scan headline tags with inheritance and produce output ACTION.
13247 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13248 or `agenda' to produce an entry list for an agenda view. It can also be
13249 a Lisp form or a function that should be called at each matched headline, in
13250 this case the return value is a list of all return values from these calls.
13252 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13253 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13254 only lines with a not-done TODO keyword are included in the output.
13255 This should be the same variable that was scoped into
13256 and set by `org-make-tags-matcher' when it constructed MATCHER.
13258 START-LEVEL can be a string with asterisks, reducing the scope to
13259 headlines matching this string."
13260 (require 'org-agenda)
13261 (let* ((re (concat "^"
13262 (if start-level
13263 ;; Get the correct level to match
13264 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13265 org-outline-regexp)
13266 " *\\(\\<\\("
13267 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13268 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13269 (props (list 'face 'default
13270 'done-face 'org-agenda-done
13271 'undone-face 'default
13272 'mouse-face 'highlight
13273 'org-not-done-regexp org-not-done-regexp
13274 'org-todo-regexp org-todo-regexp
13275 'org-complex-heading-regexp org-complex-heading-regexp
13276 'help-echo
13277 (format "mouse-2 or RET jump to org file %s"
13278 (abbreviate-file-name
13279 (or (buffer-file-name (buffer-base-buffer))
13280 (buffer-name (buffer-base-buffer)))))))
13281 (case-fold-search nil)
13282 (org-map-continue-from nil)
13283 lspos tags tags-list
13284 (tags-alist (list (cons 0 org-file-tags)))
13285 (llast 0) rtn rtn1 level category i txt
13286 todo marker entry priority)
13287 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13288 (setq action (list 'lambda nil action)))
13289 (save-excursion
13290 (goto-char (point-min))
13291 (when (eq action 'sparse-tree)
13292 (org-overview)
13293 (org-remove-occur-highlights))
13294 (while (re-search-forward re nil t)
13295 (setq org-map-continue-from nil)
13296 (catch :skip
13297 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13298 tags (if (match-end 4) (org-match-string-no-properties 4)))
13299 (goto-char (setq lspos (match-beginning 0)))
13300 (setq level (org-reduced-level (org-outline-level))
13301 category (org-get-category))
13302 (setq i llast llast level)
13303 ;; remove tag lists from same and sublevels
13304 (while (>= i level)
13305 (when (setq entry (assoc i tags-alist))
13306 (setq tags-alist (delete entry tags-alist)))
13307 (setq i (1- i)))
13308 ;; add the next tags
13309 (when tags
13310 (setq tags (org-split-string tags ":")
13311 tags-alist
13312 (cons (cons level tags) tags-alist)))
13313 ;; compile tags for current headline
13314 (setq tags-list
13315 (if org-use-tag-inheritance
13316 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13317 tags)
13318 org-scanner-tags tags-list)
13319 (when org-use-tag-inheritance
13320 (setcdr (car tags-alist)
13321 (mapcar (lambda (x)
13322 (setq x (copy-sequence x))
13323 (org-add-prop-inherited x))
13324 (cdar tags-alist))))
13325 (when (and tags org-use-tag-inheritance
13326 (or (not (eq t org-use-tag-inheritance))
13327 org-tags-exclude-from-inheritance))
13328 ;; selective inheritance, remove uninherited ones
13329 (setcdr (car tags-alist)
13330 (org-remove-uninherited-tags (cdar tags-alist))))
13331 (when (and
13333 ;; eval matcher only when the todo condition is OK
13334 (and (or (not todo-only) (member todo org-not-done-keywords))
13335 (let ((case-fold-search t) (org-trust-scanner-tags t))
13336 (eval matcher)))
13338 ;; Call the skipper, but return t if it does not skip,
13339 ;; so that the `and' form continues evaluating
13340 (progn
13341 (unless (eq action 'sparse-tree) (org-agenda-skip))
13344 ;; Check if timestamps are deselecting this entry
13345 (or (not todo-only)
13346 (and (member todo org-not-done-keywords)
13347 (or (not org-agenda-tags-todo-honor-ignore-options)
13348 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13350 ;; Extra check for the archive tag
13351 ;; FIXME: Does the skipper already do this????
13353 (not (member org-archive-tag tags-list))
13354 ;; we have an archive tag, should we use this anyway?
13355 (or (not org-agenda-skip-archived-trees)
13356 (and (eq action 'agenda) org-agenda-archives-mode))))
13358 ;; select this headline
13359 (cond
13360 ((eq action 'sparse-tree)
13361 (and org-highlight-sparse-tree-matches
13362 (org-get-heading) (match-end 0)
13363 (org-highlight-new-match
13364 (match-beginning 1) (match-end 1)))
13365 (org-show-context 'tags-tree))
13366 ((eq action 'agenda)
13367 (setq txt (org-agenda-format-item
13369 (concat
13370 (if (eq org-tags-match-list-sublevels 'indented)
13371 (make-string (1- level) ?.) "")
13372 (org-get-heading))
13373 level category
13374 tags-list)
13375 priority (org-get-priority txt))
13376 (goto-char lspos)
13377 (setq marker (org-agenda-new-marker))
13378 (org-add-props txt props
13379 'org-marker marker 'org-hd-marker marker 'org-category category
13380 'todo-state todo
13381 'priority priority 'type "tagsmatch")
13382 (push txt rtn))
13383 ((functionp action)
13384 (setq org-map-continue-from nil)
13385 (save-excursion
13386 (setq rtn1 (funcall action))
13387 (push rtn1 rtn)))
13388 (t (error "Invalid action")))
13390 ;; if we are to skip sublevels, jump to end of subtree
13391 (unless org-tags-match-list-sublevels
13392 (org-end-of-subtree t)
13393 (backward-char 1))))
13394 ;; Get the correct position from where to continue
13395 (if org-map-continue-from
13396 (goto-char org-map-continue-from)
13397 (and (= (point) lspos) (end-of-line 1)))))
13398 (when (and (eq action 'sparse-tree)
13399 (not org-sparse-tree-open-archived-trees))
13400 (org-hide-archived-subtrees (point-min) (point-max)))
13401 (nreverse rtn)))
13403 (defun org-remove-uninherited-tags (tags)
13404 "Remove all tags that are not inherited from the list TAGS."
13405 (cond
13406 ((eq org-use-tag-inheritance t)
13407 (if org-tags-exclude-from-inheritance
13408 (org-delete-all org-tags-exclude-from-inheritance tags)
13409 tags))
13410 ((not org-use-tag-inheritance) nil)
13411 ((stringp org-use-tag-inheritance)
13412 (delq nil (mapcar
13413 (lambda (x)
13414 (if (and (string-match org-use-tag-inheritance x)
13415 (not (member x org-tags-exclude-from-inheritance)))
13416 x nil))
13417 tags)))
13418 ((listp org-use-tag-inheritance)
13419 (delq nil (mapcar
13420 (lambda (x)
13421 (if (member x org-use-tag-inheritance) x nil))
13422 tags)))))
13424 (defun org-match-sparse-tree (&optional todo-only match)
13425 "Create a sparse tree according to tags string MATCH.
13426 MATCH can contain positive and negative selection of tags, like
13427 \"+WORK+URGENT-WITHBOSS\".
13428 If optional argument TODO-ONLY is non-nil, only select lines that are
13429 also TODO lines."
13430 (interactive "P")
13431 (org-agenda-prepare-buffers (list (current-buffer)))
13432 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13434 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13436 (defvar org-cached-props nil)
13437 (defun org-cached-entry-get (pom property)
13438 (if (or (eq t org-use-property-inheritance)
13439 (and (stringp org-use-property-inheritance)
13440 (string-match org-use-property-inheritance property))
13441 (and (listp org-use-property-inheritance)
13442 (member property org-use-property-inheritance)))
13443 ;; Caching is not possible, check it directly
13444 (org-entry-get pom property 'inherit)
13445 ;; Get all properties, so that we can do complicated checks easily
13446 (cdr (assoc property (or org-cached-props
13447 (setq org-cached-props
13448 (org-entry-properties pom)))))))
13450 (defun org-global-tags-completion-table (&optional files)
13451 "Return the list of all tags in all agenda buffer/files.
13452 Optional FILES argument is a list of files which can be used
13453 instead of the agenda files."
13454 (save-excursion
13455 (org-uniquify
13456 (delq nil
13457 (apply 'append
13458 (mapcar
13459 (lambda (file)
13460 (set-buffer (find-file-noselect file))
13461 (append (org-get-buffer-tags)
13462 (mapcar (lambda (x) (if (stringp (car-safe x))
13463 (list (car-safe x)) nil))
13464 org-tag-alist)))
13465 (if (and files (car files))
13466 files
13467 (org-agenda-files))))))))
13469 (defun org-make-tags-matcher (match)
13470 "Create the TAGS/TODO matcher form for the selection string MATCH.
13472 The variable `todo-only' is scoped dynamically into this function.
13473 It will be set to t if the matcher restricts matching to TODO entries,
13474 otherwise will not be touched.
13476 Returns a cons of the selection string MATCH and the constructed
13477 lisp form implementing the matcher. The matcher is to be evaluated
13478 at an Org entry, with point on the headline, and returns t if the
13479 entry matches the selection string MATCH. The returned lisp form
13480 references two variables with information about the entry, which
13481 must be bound around the form's evaluation: todo, the TODO keyword
13482 at the entry (or nil of none); and tags-list, the list of all tags
13483 at the entry including inherited ones. Additionally, the category
13484 of the entry (if any) must be specified as the text property
13485 'org-category on the headline.
13487 See also `org-scan-tags'.
13489 (declare (special todo-only))
13490 (unless (boundp 'todo-only)
13491 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13492 (unless match
13493 ;; Get a new match request, with completion
13494 (let ((org-last-tags-completion-table
13495 (org-global-tags-completion-table)))
13496 (setq match (org-completing-read-no-i
13497 "Match: " 'org-tags-completion-function nil nil nil
13498 'org-tags-history))))
13500 ;; Parse the string and create a lisp form
13501 (let ((match0 match)
13502 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13503 minus tag mm
13504 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13505 orterms term orlist re-p str-p level-p level-op time-p
13506 prop-p pn pv po gv rest)
13507 (if (string-match "/+" match)
13508 ;; match contains also a todo-matching request
13509 (progn
13510 (setq tagsmatch (substring match 0 (match-beginning 0))
13511 todomatch (substring match (match-end 0)))
13512 (if (string-match "^!" todomatch)
13513 (setq todo-only t todomatch (substring todomatch 1)))
13514 (if (string-match "^\\s-*$" todomatch)
13515 (setq todomatch nil)))
13516 ;; only matching tags
13517 (setq tagsmatch match todomatch nil))
13519 ;; Make the tags matcher
13520 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13521 (setq tagsmatcher t)
13522 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13523 (while (setq term (pop orterms))
13524 (while (and (equal (substring term -1) "\\") orterms)
13525 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13526 (while (string-match re term)
13527 (setq rest (substring term (match-end 0))
13528 minus (and (match-end 1)
13529 (equal (match-string 1 term) "-"))
13530 tag (save-match-data (replace-regexp-in-string
13531 "\\\\-" "-"
13532 (match-string 2 term)))
13533 re-p (equal (string-to-char tag) ?{)
13534 level-p (match-end 4)
13535 prop-p (match-end 5)
13536 mm (cond
13537 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13538 (level-p
13539 (setq level-op (org-op-to-function (match-string 3 term)))
13540 `(,level-op level ,(string-to-number
13541 (match-string 4 term))))
13542 (prop-p
13543 (setq pn (match-string 5 term)
13544 po (match-string 6 term)
13545 pv (match-string 7 term)
13546 re-p (equal (string-to-char pv) ?{)
13547 str-p (equal (string-to-char pv) ?\")
13548 time-p (save-match-data
13549 (string-match "^\"[[<].*[]>]\"$" pv))
13550 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13551 (if time-p (setq pv (org-matcher-time pv)))
13552 (setq po (org-op-to-function po (if time-p 'time str-p)))
13553 (cond
13554 ((equal pn "CATEGORY")
13555 (setq gv '(get-text-property (point) 'org-category)))
13556 ((equal pn "TODO")
13557 (setq gv 'todo))
13559 (setq gv `(org-cached-entry-get nil ,pn))))
13560 (if re-p
13561 (if (eq po 'org<>)
13562 `(not (string-match ,pv (or ,gv "")))
13563 `(string-match ,pv (or ,gv "")))
13564 (if str-p
13565 `(,po (or ,gv "") ,pv)
13566 `(,po (string-to-number (or ,gv ""))
13567 ,(string-to-number pv) ))))
13568 (t `(member ,tag tags-list)))
13569 mm (if minus (list 'not mm) mm)
13570 term rest)
13571 (push mm tagsmatcher))
13572 (push (if (> (length tagsmatcher) 1)
13573 (cons 'and tagsmatcher)
13574 (car tagsmatcher))
13575 orlist)
13576 (setq tagsmatcher nil))
13577 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13578 (setq tagsmatcher
13579 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13580 ;; Make the todo matcher
13581 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13582 (setq todomatcher t)
13583 (setq orterms (org-split-string todomatch "|") orlist nil)
13584 (while (setq term (pop orterms))
13585 (while (string-match re term)
13586 (setq minus (and (match-end 1)
13587 (equal (match-string 1 term) "-"))
13588 kwd (match-string 2 term)
13589 re-p (equal (string-to-char kwd) ?{)
13590 term (substring term (match-end 0))
13591 mm (if re-p
13592 `(string-match ,(substring kwd 1 -1) todo)
13593 (list 'equal 'todo kwd))
13594 mm (if minus (list 'not mm) mm))
13595 (push mm todomatcher))
13596 (push (if (> (length todomatcher) 1)
13597 (cons 'and todomatcher)
13598 (car todomatcher))
13599 orlist)
13600 (setq todomatcher nil))
13601 (setq todomatcher (if (> (length orlist) 1)
13602 (cons 'or orlist) (car orlist))))
13604 ;; Return the string and lisp forms of the matcher
13605 (setq matcher (if todomatcher
13606 (list 'and tagsmatcher todomatcher)
13607 tagsmatcher))
13608 (when todo-only
13609 (setq matcher (list 'and '(member todo org-not-done-keywords)
13610 matcher)))
13611 (cons match0 matcher)))
13613 (defun org-op-to-function (op &optional stringp)
13614 "Turn an operator into the appropriate function."
13615 (setq op
13616 (cond
13617 ((equal op "<" ) '(< string< org-time<))
13618 ((equal op ">" ) '(> org-string> org-time>))
13619 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13620 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13621 ((member op '("=" "==")) '(= string= org-time=))
13622 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13623 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13625 (defun org<> (a b) (not (= a b)))
13626 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13627 (defun org-string>= (a b) (not (string< a b)))
13628 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13629 (defun org-string<> (a b) (not (string= a b)))
13630 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13631 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13632 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13633 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13634 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13635 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13636 (defun org-2ft (s)
13637 "Convert S to a floating point time.
13638 If S is already a number, just return it. If it is a string, parse
13639 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13640 (cond
13641 ((numberp s) s)
13642 ((stringp s)
13643 (condition-case nil
13644 (float-time (apply 'encode-time (org-parse-time-string s)))
13645 (error 0.)))
13646 (t 0.)))
13648 (defun org-time-today ()
13649 "Time in seconds today at 0:00.
13650 Returns the float number of seconds since the beginning of the
13651 epoch to the beginning of today (00:00)."
13652 (float-time (apply 'encode-time
13653 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13655 (defun org-matcher-time (s)
13656 "Interpret a time comparison value."
13657 (save-match-data
13658 (cond
13659 ((string= s "<now>") (float-time))
13660 ((string= s "<today>") (org-time-today))
13661 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13662 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13663 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13664 (+ (org-time-today)
13665 (* (string-to-number (match-string 1 s))
13666 (cdr (assoc (match-string 2 s)
13667 '(("d" . 86400.0) ("w" . 604800.0)
13668 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13669 (t (org-2ft s)))))
13671 (defun org-match-any-p (re list)
13672 "Does re match any element of list?"
13673 (setq list (mapcar (lambda (x) (string-match re x)) list))
13674 (delq nil list))
13676 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13677 (defvar org-tags-overlay (make-overlay 1 1))
13678 (org-detach-overlay org-tags-overlay)
13680 (defun org-get-local-tags-at (&optional pos)
13681 "Get a list of tags defined in the current headline."
13682 (org-get-tags-at pos 'local))
13684 (defun org-get-local-tags ()
13685 "Get a list of tags defined in the current headline."
13686 (org-get-tags-at nil 'local))
13688 (defun org-get-tags-at (&optional pos local)
13689 "Get a list of all headline tags applicable at POS.
13690 POS defaults to point. If tags are inherited, the list contains
13691 the targets in the same sequence as the headlines appear, i.e.
13692 the tags of the current headline come last.
13693 When LOCAL is non-nil, only return tags from the current headline,
13694 ignore inherited ones."
13695 (interactive)
13696 (if (and org-trust-scanner-tags
13697 (or (not pos) (equal pos (point)))
13698 (not local))
13699 org-scanner-tags
13700 (let (tags ltags lastpos parent)
13701 (save-excursion
13702 (save-restriction
13703 (widen)
13704 (goto-char (or pos (point)))
13705 (save-match-data
13706 (catch 'done
13707 (condition-case nil
13708 (progn
13709 (org-back-to-heading t)
13710 (while (not (equal lastpos (point)))
13711 (setq lastpos (point))
13712 (when (looking-at
13713 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13714 (setq ltags (org-split-string
13715 (org-match-string-no-properties 1) ":"))
13716 (when parent
13717 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13718 (setq tags (append
13719 (if parent
13720 (org-remove-uninherited-tags ltags)
13721 ltags)
13722 tags)))
13723 (or org-use-tag-inheritance (throw 'done t))
13724 (if local (throw 'done t))
13725 (or (org-up-heading-safe) (error nil))
13726 (setq parent t)))
13727 (error nil)))))
13728 (if local
13729 tags
13730 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13732 (defun org-add-prop-inherited (s)
13733 (add-text-properties 0 (length s) '(inherited t) s)
13736 (defun org-toggle-tag (tag &optional onoff)
13737 "Toggle the tag TAG for the current line.
13738 If ONOFF is `on' or `off', don't toggle but set to this state."
13739 (let (res current)
13740 (save-excursion
13741 (org-back-to-heading t)
13742 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13743 (point-at-eol) t)
13744 (progn
13745 (setq current (match-string 1))
13746 (replace-match ""))
13747 (setq current ""))
13748 (setq current (nreverse (org-split-string current ":")))
13749 (cond
13750 ((eq onoff 'on)
13751 (setq res t)
13752 (or (member tag current) (push tag current)))
13753 ((eq onoff 'off)
13754 (or (not (member tag current)) (setq current (delete tag current))))
13755 (t (if (member tag current)
13756 (setq current (delete tag current))
13757 (setq res t)
13758 (push tag current))))
13759 (end-of-line 1)
13760 (if current
13761 (progn
13762 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13763 (org-set-tags nil t))
13764 (delete-horizontal-space))
13765 (run-hooks 'org-after-tags-change-hook))
13766 res))
13768 (defun org-align-tags-here (to-col)
13769 ;; Assumes that this is a headline
13770 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13771 (beginning-of-line 1)
13772 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13773 (< pos (match-beginning 2)))
13774 (progn
13775 (setq tags-l (- (match-end 2) (match-beginning 2)))
13776 (goto-char (match-beginning 1))
13777 (insert " ")
13778 (delete-region (point) (1+ (match-beginning 2)))
13779 (setq ncol (max (current-column)
13780 (1+ col)
13781 (if (> to-col 0)
13782 to-col
13783 (- (abs to-col) tags-l))))
13784 (setq p (point))
13785 (insert (make-string (- ncol (current-column)) ?\ ))
13786 (setq ncol (current-column))
13787 (when indent-tabs-mode (tabify p (point-at-eol)))
13788 (org-move-to-column (min ncol col) t))
13789 (goto-char pos))))
13791 (defun org-set-tags-command (&optional arg just-align)
13792 "Call the set-tags command for the current entry."
13793 (interactive "P")
13794 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13795 (org-set-tags arg just-align)
13796 (save-excursion
13797 (org-back-to-heading t)
13798 (org-set-tags arg just-align))))
13800 (defun org-set-tags-to (data)
13801 "Set the tags of the current entry to DATA, replacing the current tags.
13802 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13803 If DATA is nil or the empty string, any tags will be removed."
13804 (interactive "sTags: ")
13805 (setq data
13806 (cond
13807 ((eq data nil) "")
13808 ((equal data "") "")
13809 ((stringp data)
13810 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13811 ":"))
13812 ((listp data)
13813 (concat ":" (mapconcat 'identity data ":") ":"))))
13814 (when data
13815 (save-excursion
13816 (org-back-to-heading t)
13817 (when (looking-at org-complex-heading-regexp)
13818 (if (match-end 5)
13819 (progn
13820 (goto-char (match-beginning 5))
13821 (insert data)
13822 (delete-region (point) (point-at-eol))
13823 (org-set-tags nil 'align))
13824 (goto-char (point-at-eol))
13825 (insert " " data)
13826 (org-set-tags nil 'align)))
13827 (beginning-of-line 1)
13828 (if (looking-at ".*?\\([ \t]+\\)$")
13829 (delete-region (match-beginning 1) (match-end 1))))))
13831 (defun org-align-all-tags ()
13832 "Align the tags i all headings."
13833 (interactive)
13834 (save-excursion
13835 (or (ignore-errors (org-back-to-heading t))
13836 (outline-next-heading))
13837 (if (org-at-heading-p)
13838 (org-set-tags t)
13839 (message "No headings"))))
13841 (defvar org-indent-indentation-per-level)
13842 (defun org-set-tags (&optional arg just-align)
13843 "Set the tags for the current headline.
13844 With prefix ARG, realign all tags in headings in the current buffer."
13845 (interactive "P")
13846 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13847 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13848 'region-start-level 'region))
13849 org-loop-over-headlines-in-active-region)
13850 (org-map-entries
13851 ;; We don't use ARG and JUST-ALIGN here these args are not
13852 ;; useful when looping over headlines
13853 `(org-set-tags)
13854 org-loop-over-headlines-in-active-region
13855 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13856 (let* ((re org-outline-regexp-bol)
13857 (current (unless arg (org-get-tags-string)))
13858 (col (current-column))
13859 (org-setting-tags t)
13860 table current-tags inherited-tags ; computed below when needed
13861 tags p0 c0 c1 rpl di tc level)
13862 (if arg
13863 (save-excursion
13864 (goto-char (point-min))
13865 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13866 (while (re-search-forward re nil t)
13867 (org-set-tags nil t)
13868 (end-of-line 1)))
13869 (message "All tags realigned to column %d" org-tags-column))
13870 (if just-align
13871 (setq tags current)
13872 ;; Get a new set of tags from the user
13873 (save-excursion
13874 (setq table (append org-tag-persistent-alist
13875 (or org-tag-alist (org-get-buffer-tags))
13876 (and
13877 org-complete-tags-always-offer-all-agenda-tags
13878 (org-global-tags-completion-table
13879 (org-agenda-files))))
13880 org-last-tags-completion-table table
13881 current-tags (org-split-string current ":")
13882 inherited-tags (nreverse
13883 (nthcdr (length current-tags)
13884 (nreverse (org-get-tags-at))))
13885 tags
13886 (if (or (eq t org-use-fast-tag-selection)
13887 (and org-use-fast-tag-selection
13888 (delq nil (mapcar 'cdr table))))
13889 (org-fast-tag-selection
13890 current-tags inherited-tags table
13891 (if org-fast-tag-selection-include-todo
13892 org-todo-key-alist))
13893 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13894 (org-trim
13895 (org-icompleting-read "Tags: "
13896 'org-tags-completion-function
13897 nil nil current 'org-tags-history))))))
13898 (while (string-match "[-+&]+" tags)
13899 ;; No boolean logic, just a list
13900 (setq tags (replace-match ":" t t tags))))
13902 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13904 (if org-tags-sort-function
13905 (setq tags (mapconcat 'identity
13906 (sort (org-split-string
13907 tags (org-re "[^[:alnum:]_@#%]+"))
13908 org-tags-sort-function) ":")))
13910 (if (string-match "\\`[\t ]*\\'" tags)
13911 (setq tags "")
13912 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13913 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13915 ;; Insert new tags at the correct column
13916 (beginning-of-line 1)
13917 (setq level (or (and (looking-at org-outline-regexp)
13918 (- (match-end 0) (point) 1))
13920 (cond
13921 ((and (equal current "") (equal tags "")))
13922 ((re-search-forward
13923 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13924 (point-at-eol) t)
13925 (if (equal tags "")
13926 (setq rpl "")
13927 (goto-char (match-beginning 0))
13928 (setq c0 (current-column)
13929 ;; compute offset for the case of org-indent-mode active
13930 di (if org-indent-mode
13931 (* (1- org-indent-indentation-per-level) (1- level))
13933 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13934 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13935 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13936 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13937 (replace-match rpl t t)
13938 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13939 tags)
13940 (t (error "Tags alignment failed")))
13941 (org-move-to-column col)
13942 (unless just-align
13943 (run-hooks 'org-after-tags-change-hook))))))
13945 (defun org-change-tag-in-region (beg end tag off)
13946 "Add or remove TAG for each entry in the region.
13947 This works in the agenda, and also in an org-mode buffer."
13948 (interactive
13949 (list (region-beginning) (region-end)
13950 (let ((org-last-tags-completion-table
13951 (if (derived-mode-p 'org-mode)
13952 (org-get-buffer-tags)
13953 (org-global-tags-completion-table))))
13954 (org-icompleting-read
13955 "Tag: " 'org-tags-completion-function nil nil nil
13956 'org-tags-history))
13957 (progn
13958 (message "[s]et or [r]emove? ")
13959 (equal (read-char-exclusive) ?r))))
13960 (if (fboundp 'deactivate-mark) (deactivate-mark))
13961 (let ((agendap (equal major-mode 'org-agenda-mode))
13962 l1 l2 m buf pos newhead (cnt 0))
13963 (goto-char end)
13964 (setq l2 (1- (org-current-line)))
13965 (goto-char beg)
13966 (setq l1 (org-current-line))
13967 (loop for l from l1 to l2 do
13968 (org-goto-line l)
13969 (setq m (get-text-property (point) 'org-hd-marker))
13970 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13971 (and agendap m))
13972 (setq buf (if agendap (marker-buffer m) (current-buffer))
13973 pos (if agendap m (point)))
13974 (with-current-buffer buf
13975 (save-excursion
13976 (save-restriction
13977 (goto-char pos)
13978 (setq cnt (1+ cnt))
13979 (org-toggle-tag tag (if off 'off 'on))
13980 (setq newhead (org-get-heading)))))
13981 (and agendap (org-agenda-change-all-lines newhead m))))
13982 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13984 (defun org-tags-completion-function (string predicate &optional flag)
13985 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13986 (confirm (lambda (x) (stringp (car x)))))
13987 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13988 (setq s1 (match-string 1 string)
13989 s2 (match-string 2 string))
13990 (setq s1 "" s2 string))
13991 (cond
13992 ((eq flag nil)
13993 ;; try completion
13994 (setq rtn (try-completion s2 ctable confirm))
13995 (if (stringp rtn)
13996 (setq rtn
13997 (concat s1 s2 (substring rtn (length s2))
13998 (if (and org-add-colon-after-tag-completion
13999 (assoc rtn ctable))
14000 ":" ""))))
14001 rtn)
14002 ((eq flag t)
14003 ;; all-completions
14004 (all-completions s2 ctable confirm)
14006 ((eq flag 'lambda)
14007 ;; exact match?
14008 (assoc s2 ctable)))
14011 (defun org-fast-tag-insert (kwd tags face &optional end)
14012 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14013 (insert (format "%-12s" (concat kwd ":"))
14014 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14015 (or end "")))
14017 (defun org-fast-tag-show-exit (flag)
14018 (save-excursion
14019 (org-goto-line 3)
14020 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14021 (replace-match ""))
14022 (when flag
14023 (end-of-line 1)
14024 (org-move-to-column (- (window-width) 19) t)
14025 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14027 (defun org-set-current-tags-overlay (current prefix)
14028 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14029 (if (featurep 'xemacs)
14030 (org-overlay-display org-tags-overlay (concat prefix s)
14031 'secondary-selection)
14032 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14033 (org-overlay-display org-tags-overlay (concat prefix s)))))
14035 (defvar org-last-tag-selection-key nil)
14036 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14037 "Fast tag selection with single keys.
14038 CURRENT is the current list of tags in the headline, INHERITED is the
14039 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14040 possibly with grouping information. TODO-TABLE is a similar table with
14041 TODO keywords, should these have keys assigned to them.
14042 If the keys are nil, a-z are automatically assigned.
14043 Returns the new tags string, or nil to not change the current settings."
14044 (let* ((fulltable (append table todo-table))
14045 (maxlen (apply 'max (mapcar
14046 (lambda (x)
14047 (if (stringp (car x)) (string-width (car x)) 0))
14048 fulltable)))
14049 (buf (current-buffer))
14050 (expert (eq org-fast-tag-selection-single-key 'expert))
14051 (buffer-tags nil)
14052 (fwidth (+ maxlen 3 1 3))
14053 (ncol (/ (- (window-width) 4) fwidth))
14054 (i-face 'org-done)
14055 (c-face 'org-todo)
14056 tg cnt e c char c1 c2 ntable tbl rtn
14057 ov-start ov-end ov-prefix
14058 (exit-after-next org-fast-tag-selection-single-key)
14059 (done-keywords org-done-keywords)
14060 groups ingroup)
14061 (save-excursion
14062 (beginning-of-line 1)
14063 (if (looking-at
14064 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14065 (setq ov-start (match-beginning 1)
14066 ov-end (match-end 1)
14067 ov-prefix "")
14068 (setq ov-start (1- (point-at-eol))
14069 ov-end (1+ ov-start))
14070 (skip-chars-forward "^\n\r")
14071 (setq ov-prefix
14072 (concat
14073 (buffer-substring (1- (point)) (point))
14074 (if (> (current-column) org-tags-column)
14076 (make-string (- org-tags-column (current-column)) ?\ ))))))
14077 (move-overlay org-tags-overlay ov-start ov-end)
14078 (save-window-excursion
14079 (if expert
14080 (set-buffer (get-buffer-create " *Org tags*"))
14081 (delete-other-windows)
14082 (split-window-vertically)
14083 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14084 (erase-buffer)
14085 (org-set-local 'org-done-keywords done-keywords)
14086 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14087 (org-fast-tag-insert "Current" current c-face "\n\n")
14088 (org-fast-tag-show-exit exit-after-next)
14089 (org-set-current-tags-overlay current ov-prefix)
14090 (setq tbl fulltable char ?a cnt 0)
14091 (while (setq e (pop tbl))
14092 (cond
14093 ((equal (car e) :startgroup)
14094 (push '() groups) (setq ingroup t)
14095 (when (not (= cnt 0))
14096 (setq cnt 0)
14097 (insert "\n"))
14098 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14099 ((equal (car e) :endgroup)
14100 (setq ingroup nil cnt 0)
14101 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14102 ((equal e '(:newline))
14103 (when (not (= cnt 0))
14104 (setq cnt 0)
14105 (insert "\n")
14106 (setq e (car tbl))
14107 (while (equal (car tbl) '(:newline))
14108 (insert "\n")
14109 (setq tbl (cdr tbl)))))
14111 (setq tg (copy-sequence (car e)) c2 nil)
14112 (if (cdr e)
14113 (setq c (cdr e))
14114 ;; automatically assign a character.
14115 (setq c1 (string-to-char
14116 (downcase (substring
14117 tg (if (= (string-to-char tg) ?@) 1 0)))))
14118 (if (or (rassoc c1 ntable) (rassoc c1 table))
14119 (while (or (rassoc char ntable) (rassoc char table))
14120 (setq char (1+ char)))
14121 (setq c2 c1))
14122 (setq c (or c2 char)))
14123 (if ingroup (push tg (car groups)))
14124 (setq tg (org-add-props tg nil 'face
14125 (cond
14126 ((not (assoc tg table))
14127 (org-get-todo-face tg))
14128 ((member tg current) c-face)
14129 ((member tg inherited) i-face))))
14130 (if (and (= cnt 0) (not ingroup)) (insert " "))
14131 (insert "[" c "] " tg (make-string
14132 (- fwidth 4 (length tg)) ?\ ))
14133 (push (cons tg c) ntable)
14134 (when (= (setq cnt (1+ cnt)) ncol)
14135 (insert "\n")
14136 (if ingroup (insert " "))
14137 (setq cnt 0)))))
14138 (setq ntable (nreverse ntable))
14139 (insert "\n")
14140 (goto-char (point-min))
14141 (if (not expert) (org-fit-window-to-buffer))
14142 (setq rtn
14143 (catch 'exit
14144 (while t
14145 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14146 (if (not groups) "no " "")
14147 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14148 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14149 (setq org-last-tag-selection-key c)
14150 (cond
14151 ((= c ?\r) (throw 'exit t))
14152 ((= c ?!)
14153 (setq groups (not groups))
14154 (goto-char (point-min))
14155 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14156 ((= c ?\C-c)
14157 (if (not expert)
14158 (org-fast-tag-show-exit
14159 (setq exit-after-next (not exit-after-next)))
14160 (setq expert nil)
14161 (delete-other-windows)
14162 (set-window-buffer (split-window-vertically) " *Org tags*")
14163 (org-switch-to-buffer-other-window " *Org tags*")
14164 (org-fit-window-to-buffer)))
14165 ((or (= c ?\C-g)
14166 (and (= c ?q) (not (rassoc c ntable))))
14167 (org-detach-overlay org-tags-overlay)
14168 (setq quit-flag t))
14169 ((= c ?\ )
14170 (setq current nil)
14171 (if exit-after-next (setq exit-after-next 'now)))
14172 ((= c ?\t)
14173 (condition-case nil
14174 (setq tg (org-icompleting-read
14175 "Tag: "
14176 (or buffer-tags
14177 (with-current-buffer buf
14178 (org-get-buffer-tags)))))
14179 (quit (setq tg "")))
14180 (when (string-match "\\S-" tg)
14181 (add-to-list 'buffer-tags (list tg))
14182 (if (member tg current)
14183 (setq current (delete tg current))
14184 (push tg current)))
14185 (if exit-after-next (setq exit-after-next 'now)))
14186 ((setq e (rassoc c todo-table) tg (car e))
14187 (with-current-buffer buf
14188 (save-excursion (org-todo tg)))
14189 (if exit-after-next (setq exit-after-next 'now)))
14190 ((setq e (rassoc c ntable) tg (car e))
14191 (if (member tg current)
14192 (setq current (delete tg current))
14193 (loop for g in groups do
14194 (if (member tg g)
14195 (mapc (lambda (x)
14196 (setq current (delete x current)))
14197 g)))
14198 (push tg current))
14199 (if exit-after-next (setq exit-after-next 'now))))
14201 ;; Create a sorted list
14202 (setq current
14203 (sort current
14204 (lambda (a b)
14205 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14206 (if (eq exit-after-next 'now) (throw 'exit t))
14207 (goto-char (point-min))
14208 (beginning-of-line 2)
14209 (delete-region (point) (point-at-eol))
14210 (org-fast-tag-insert "Current" current c-face)
14211 (org-set-current-tags-overlay current ov-prefix)
14212 (while (re-search-forward
14213 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14214 (setq tg (match-string 1))
14215 (add-text-properties
14216 (match-beginning 1) (match-end 1)
14217 (list 'face
14218 (cond
14219 ((member tg current) c-face)
14220 ((member tg inherited) i-face)
14221 (t (get-text-property (match-beginning 1) 'face))))))
14222 (goto-char (point-min)))))
14223 (org-detach-overlay org-tags-overlay)
14224 (if rtn
14225 (mapconcat 'identity current ":")
14226 nil))))
14228 (defun org-get-tags-string ()
14229 "Get the TAGS string in the current headline."
14230 (unless (org-at-heading-p t)
14231 (error "Not on a heading"))
14232 (save-excursion
14233 (beginning-of-line 1)
14234 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14235 (org-match-string-no-properties 1)
14236 "")))
14238 (defun org-get-tags ()
14239 "Get the list of tags specified in the current headline."
14240 (org-split-string (org-get-tags-string) ":"))
14242 (defun org-get-buffer-tags ()
14243 "Get a table of all tags used in the buffer, for completion."
14244 (let (tags)
14245 (save-excursion
14246 (goto-char (point-min))
14247 (while (re-search-forward
14248 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14249 (when (equal (char-after (point-at-bol 0)) ?*)
14250 (mapc (lambda (x) (add-to-list 'tags x))
14251 (org-split-string (org-match-string-no-properties 1) ":")))))
14252 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14253 (mapcar 'list tags)))
14255 ;;;; The mapping API
14257 (defun org-map-entries (func &optional match scope &rest skip)
14258 "Call FUNC at each headline selected by MATCH in SCOPE.
14260 FUNC is a function or a lisp form. The function will be called without
14261 arguments, with the cursor positioned at the beginning of the headline.
14262 The return values of all calls to the function will be collected and
14263 returned as a list.
14265 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14266 does not need to preserve point. After evaluation, the cursor will be
14267 moved to the end of the line (presumably of the headline of the
14268 processed entry) and search continues from there. Under some
14269 circumstances, this may not produce the wanted results. For example,
14270 if you have removed (e.g. archived) the current (sub)tree it could
14271 mean that the next entry will be skipped entirely. In such cases, you
14272 can specify the position from where search should continue by making
14273 FUNC set the variable `org-map-continue-from' to the desired buffer
14274 position.
14276 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14277 Only headlines that are matched by this query will be considered during
14278 the iteration. When MATCH is nil or t, all headlines will be
14279 visited by the iteration.
14281 SCOPE determines the scope of this command. It can be any of:
14283 nil The current buffer, respecting the restriction if any
14284 tree The subtree started with the entry at point
14285 region The entries within the active region, if any
14286 region-start-level
14287 The entries within the active region, but only those at
14288 the same level than the first one.
14289 file The current buffer, without restriction
14290 file-with-archives
14291 The current buffer, and any archives associated with it
14292 agenda All agenda files
14293 agenda-with-archives
14294 All agenda files with any archive files associated with them
14295 \(file1 file2 ...)
14296 If this is a list, all files in the list will be scanned
14298 The remaining args are treated as settings for the skipping facilities of
14299 the scanner. The following items can be given here:
14301 archive skip trees with the archive tag.
14302 comment skip trees with the COMMENT keyword
14303 function or Emacs Lisp form:
14304 will be used as value for `org-agenda-skip-function', so whenever
14305 the function returns t, FUNC will not be called for that
14306 entry and search will continue from the point where the
14307 function leaves it.
14309 If your function needs to retrieve the tags including inherited tags
14310 at the *current* entry, you can use the value of the variable
14311 `org-scanner-tags' which will be much faster than getting the value
14312 with `org-get-tags-at'. If your function gets properties with
14313 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14314 to t around the call to `org-entry-properties' to get the same speedup.
14315 Note that if your function moves around to retrieve tags and properties at
14316 a *different* entry, you cannot use these techniques."
14317 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14318 (not (org-region-active-p)))
14319 (let* ((org-agenda-archives-mode nil) ; just to make sure
14320 (org-agenda-skip-archived-trees (memq 'archive skip))
14321 (org-agenda-skip-comment-trees (memq 'comment skip))
14322 (org-agenda-skip-function
14323 (car (org-delete-all '(comment archive) skip)))
14324 (org-tags-match-list-sublevels t)
14325 (start-level (eq scope 'region-start-level))
14326 matcher file res
14327 org-todo-keywords-for-agenda
14328 org-done-keywords-for-agenda
14329 org-todo-keyword-alist-for-agenda
14330 org-drawers-for-agenda
14331 org-tag-alist-for-agenda
14332 todo-only)
14334 (cond
14335 ((eq match t) (setq matcher t))
14336 ((eq match nil) (setq matcher t))
14337 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14339 (save-excursion
14340 (save-restriction
14341 (cond ((eq scope 'tree)
14342 (org-back-to-heading t)
14343 (org-narrow-to-subtree)
14344 (setq scope nil))
14345 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14346 (org-region-active-p))
14347 ;; If needed, set start-level to a string like "2"
14348 (when start-level
14349 (save-excursion
14350 (goto-char (region-beginning))
14351 (unless (org-at-heading-p) (outline-next-heading))
14352 (setq start-level (org-current-level))))
14353 (narrow-to-region (region-beginning)
14354 (save-excursion
14355 (goto-char (region-end))
14356 (unless (and (bolp) (org-at-heading-p))
14357 (outline-next-heading))
14358 (point)))
14359 (setq scope nil)))
14361 (if (not scope)
14362 (progn
14363 (org-agenda-prepare-buffers
14364 (list (buffer-file-name (current-buffer))))
14365 (setq res (org-scan-tags func matcher todo-only start-level)))
14366 ;; Get the right scope
14367 (cond
14368 ((and scope (listp scope) (symbolp (car scope)))
14369 (setq scope (eval scope)))
14370 ((eq scope 'agenda)
14371 (setq scope (org-agenda-files t)))
14372 ((eq scope 'agenda-with-archives)
14373 (setq scope (org-agenda-files t))
14374 (setq scope (org-add-archive-files scope)))
14375 ((eq scope 'file)
14376 (setq scope (list (buffer-file-name))))
14377 ((eq scope 'file-with-archives)
14378 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14379 (org-agenda-prepare-buffers scope)
14380 (while (setq file (pop scope))
14381 (with-current-buffer (org-find-base-buffer-visiting file)
14382 (save-excursion
14383 (save-restriction
14384 (widen)
14385 (goto-char (point-min))
14386 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14387 res)))
14389 ;;;; Properties
14391 ;;; Setting and retrieving properties
14393 (defconst org-special-properties
14394 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14395 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14396 "The special properties valid in Org-mode.
14398 These are properties that are not defined in the property drawer,
14399 but in some other way.")
14401 (defconst org-default-properties
14402 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14403 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14404 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14405 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14406 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14407 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14408 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14409 "Some properties that are used by Org-mode for various purposes.
14410 Being in this list makes sure that they are offered for completion.")
14412 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14413 "Regular expression matching the first line of a property drawer.")
14415 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14416 "Regular expression matching the last line of a property drawer.")
14418 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14419 "Regular expression matching the first line of a property drawer.")
14421 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14422 "Regular expression matching the first line of a property drawer.")
14424 (defconst org-property-drawer-re
14425 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14426 org-property-end-re "\\)\n?")
14427 "Matches an entire property drawer.")
14429 (defconst org-clock-drawer-re
14430 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14431 org-property-end-re "\\)\n?")
14432 "Matches an entire clock drawer.")
14434 (defsubst org-re-property (property)
14435 "Return a regexp matching a PROPERTY line.
14436 Match group 1 will be set to the value."
14437 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14439 (defsubst org-re-property-keyword (property)
14440 "Return a regexp matching a PROPERTY line, possibly with no
14441 value for the property."
14442 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14444 (defun org-property-action ()
14445 "Do an action on properties."
14446 (interactive)
14447 (let (c)
14448 (org-at-property-p)
14449 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14450 (setq c (read-char-exclusive))
14451 (cond
14452 ((equal c ?s)
14453 (call-interactively 'org-set-property))
14454 ((equal c ?d)
14455 (call-interactively 'org-delete-property))
14456 ((equal c ?D)
14457 (call-interactively 'org-delete-property-globally))
14458 ((equal c ?c)
14459 (call-interactively 'org-compute-property-at-point))
14460 (t (error "No such property action %c" c)))))
14462 (defun org-inc-effort ()
14463 "Increment the value of the effort property in the current entry."
14464 (interactive)
14465 (org-set-effort nil t))
14467 (defun org-set-effort (&optional value increment)
14468 "Set the effort property of the current entry.
14469 With numerical prefix arg, use the nth allowed value, 0 stands for the
14470 10th allowed value.
14472 When INCREMENT is non-nil, set the property to the next allowed value."
14473 (interactive "P")
14474 (if (equal value 0) (setq value 10))
14475 (let* ((completion-ignore-case t)
14476 (prop org-effort-property)
14477 (cur (org-entry-get nil prop))
14478 (allowed (org-property-get-allowed-values nil prop 'table))
14479 (existing (mapcar 'list (org-property-values prop)))
14481 (val (cond
14482 ((stringp value) value)
14483 ((and allowed (integerp value))
14484 (or (car (nth (1- value) allowed))
14485 (car (org-last allowed))))
14486 ((and allowed increment)
14487 (or (caadr (member (list cur) allowed))
14488 (error "Allowed effort values are not set")))
14489 (allowed
14490 (message "Select 1-9,0, [RET%s]: %s"
14491 (if cur (concat "=" cur) "")
14492 (mapconcat 'car allowed " "))
14493 (setq rpl (read-char-exclusive))
14494 (if (equal rpl ?\r)
14496 (setq rpl (- rpl ?0))
14497 (if (equal rpl 0) (setq rpl 10))
14498 (if (and (> rpl 0) (<= rpl (length allowed)))
14499 (car (nth (1- rpl) allowed))
14500 (org-completing-read "Effort: " allowed nil))))
14502 (let (org-completion-use-ido org-completion-use-iswitchb)
14503 (org-completing-read
14504 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14505 (concat "[" cur "]") "")
14506 ": ")
14507 existing nil nil "" nil cur))))))
14508 (unless (equal (org-entry-get nil prop) val)
14509 (org-entry-put nil prop val))
14510 (message "%s is now %s" prop val)))
14512 (defun org-at-property-p ()
14513 "Is cursor inside a property drawer?"
14514 (save-excursion
14515 (beginning-of-line 1)
14516 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14517 (save-match-data ;; Used by calling procedures
14518 (let ((p (point))
14519 (range (unless (org-before-first-heading-p)
14520 (org-get-property-block))))
14521 (and range (<= (car range) p) (< p (cdr range))))))))
14523 (defun org-get-property-block (&optional beg end force)
14524 "Return the (beg . end) range of the body of the property drawer.
14525 BEG and END are the beginning and end of the current subtree, or of
14526 the part before the first headline. If they are not given, they will
14527 be found. If the drawer does not exist and FORCE is non-nil, create
14528 the drawer."
14529 (catch 'exit
14530 (save-excursion
14531 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14532 (progn (org-back-to-heading t) (point))))
14533 (end (or end (and (not (outline-next-heading)) (point-max))
14534 (point))))
14535 (goto-char beg)
14536 (if (re-search-forward org-property-start-re end t)
14537 (setq beg (1+ (match-end 0)))
14538 (if force
14539 (save-excursion
14540 (org-insert-property-drawer)
14541 (setq end (progn (outline-next-heading) (point))))
14542 (throw 'exit nil))
14543 (goto-char beg)
14544 (if (re-search-forward org-property-start-re end t)
14545 (setq beg (1+ (match-end 0)))))
14546 (if (re-search-forward org-property-end-re end t)
14547 (setq end (match-beginning 0))
14548 (or force (throw 'exit nil))
14549 (goto-char beg)
14550 (setq end beg)
14551 (org-indent-line)
14552 (insert ":END:\n"))
14553 (cons beg end)))))
14555 (defun org-entry-properties (&optional pom which specific)
14556 "Get all properties of the entry at point-or-marker POM.
14557 This includes the TODO keyword, the tags, time strings for deadline,
14558 scheduled, and clocking, and any additional properties defined in the
14559 entry. The return value is an alist, keys may occur multiple times
14560 if the property key was used several times.
14561 POM may also be nil, in which case the current entry is used.
14562 If WHICH is nil or `all', get all properties. If WHICH is
14563 `special' or `standard', only get that subclass. If WHICH
14564 is a string only get exactly this property. SPECIFIC can be a string, the
14565 specific property we are interested in. Specifying it can speed
14566 things up because then unnecessary parsing is avoided."
14567 (setq which (or which 'all))
14568 (org-with-point-at pom
14569 (let ((clockstr (substring org-clock-string 0 -1))
14570 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14571 (case-fold-search nil)
14572 beg end range props sum-props key key1 value string clocksum clocksumt)
14573 (save-excursion
14574 (when (condition-case nil
14575 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14576 (error nil))
14577 (setq beg (point))
14578 (setq sum-props (get-text-property (point) 'org-summaries))
14579 (setq clocksum (get-text-property (point) :org-clock-minutes)
14580 clocksumt (get-text-property (point) :org-clock-minutes-today))
14581 (outline-next-heading)
14582 (setq end (point))
14583 (when (memq which '(all special))
14584 ;; Get the special properties, like TODO and tags
14585 (goto-char beg)
14586 (when (and (or (not specific) (string= specific "TODO"))
14587 (looking-at org-todo-line-regexp) (match-end 2))
14588 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14589 (when (and (or (not specific) (string= specific "PRIORITY"))
14590 (looking-at org-priority-regexp))
14591 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14592 (when (or (not specific) (string= specific "FILE"))
14593 (push (cons "FILE" buffer-file-name) props))
14594 (when (and (or (not specific) (string= specific "TAGS"))
14595 (setq value (org-get-tags-string))
14596 (string-match "\\S-" value))
14597 (push (cons "TAGS" value) props))
14598 (when (and (or (not specific) (string= specific "ALLTAGS"))
14599 (setq value (org-get-tags-at)))
14600 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14601 ":"))
14602 props))
14603 (when (or (not specific) (string= specific "BLOCKED"))
14604 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14605 (when (or (not specific)
14606 (member specific
14607 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14608 "TIMESTAMP" "TIMESTAMP_IA")))
14609 (catch 'match
14610 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14611 (setq key (if (match-end 1)
14612 (substring (org-match-string-no-properties 1)
14613 0 -1))
14614 string (if (equal key clockstr)
14615 (org-trim
14616 (buffer-substring-no-properties
14617 (match-beginning 3) (goto-char
14618 (point-at-eol))))
14619 (substring (org-match-string-no-properties 3)
14620 1 -1)))
14621 ;; Get the correct property name from the key. This is
14622 ;; necessary if the user has configured time keywords.
14623 (setq key1 (concat key ":"))
14624 (cond
14625 ((not key)
14626 (setq key
14627 (if (= (char-after (match-beginning 3)) ?\[)
14628 "TIMESTAMP_IA" "TIMESTAMP")))
14629 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14630 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14631 ((equal key1 org-closed-string) (setq key "CLOSED"))
14632 ((equal key1 org-clock-string) (setq key "CLOCK")))
14633 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14634 (progn
14635 (push (cons key string) props)
14636 ;; no need to search further if match is found
14637 (throw 'match t))
14638 (when (or (equal key "CLOCK") (not (assoc key props)))
14639 (push (cons key string) props)))))))
14641 (when (memq which '(all standard))
14642 ;; Get the standard properties, like :PROP: ...
14643 (setq range (org-get-property-block beg end))
14644 (when range
14645 (goto-char (car range))
14646 (while (re-search-forward
14647 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14648 (cdr range) t)
14649 (setq key (org-match-string-no-properties 1)
14650 value (org-trim (or (org-match-string-no-properties 2) "")))
14651 (unless (member key excluded)
14652 (push (cons key (or value "")) props)))))
14653 (if clocksum
14654 (push (cons "CLOCKSUM"
14655 (org-columns-number-to-string (/ (float clocksum) 60.)
14656 'add_times))
14657 props))
14658 (if clocksumt
14659 (push (cons "CLOCKSUM_T"
14660 (org-columns-number-to-string (/ (float clocksumt) 60.)
14661 'add_times))
14662 props))
14663 (unless (assoc "CATEGORY" props)
14664 (push (cons "CATEGORY" (org-get-category)) props))
14665 (append sum-props (nreverse props)))))))
14667 (defun org-entry-get (pom property &optional inherit literal-nil)
14668 "Get value of PROPERTY for entry or content at point-or-marker POM.
14669 If INHERIT is non-nil and the entry does not have the property,
14670 then also check higher levels of the hierarchy.
14671 If INHERIT is the symbol `selective', use inheritance only if the setting
14672 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14673 If the property is present but empty, the return value is the empty string.
14674 If the property is not present at all, nil is returned.
14676 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14677 do not interpret it as the list atom nil. This is used for inheritance
14678 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14679 (org-with-point-at pom
14680 (if (and inherit (if (eq inherit 'selective)
14681 (org-property-inherit-p property)
14683 (org-entry-get-with-inheritance property literal-nil)
14684 (if (member property org-special-properties)
14685 ;; We need a special property. Use `org-entry-properties' to
14686 ;; retrieve it, but specify the wanted property
14687 (cdr (assoc property (org-entry-properties nil 'special property)))
14688 (let* ((range (org-get-property-block))
14689 (props (list (or (assoc property org-file-properties)
14690 (assoc property org-global-properties)
14691 (assoc property org-global-properties-fixed))))
14692 (ap (lambda (key)
14693 (when (re-search-forward
14694 (org-re-property key) (cdr range) t)
14695 (setq props
14696 (org-update-property-plist
14698 (if (match-end 1)
14699 (org-match-string-no-properties 1) "")
14700 props)))))
14701 val)
14702 (when (and range (goto-char (car range)))
14703 (funcall ap property)
14704 (goto-char (car range))
14705 (while (funcall ap (concat property "+")))
14706 (setq val (cdr (assoc property props)))
14707 (when val (if literal-nil val (org-not-nil val)))))))))
14709 (defun org-property-or-variable-value (var &optional inherit)
14710 "Check if there is a property fixing the value of VAR.
14711 If yes, return this value. If not, return the current value of the variable."
14712 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14713 (if (and prop (stringp prop) (string-match "\\S-" prop))
14714 (read prop)
14715 (symbol-value var))))
14717 (defun org-entry-delete (pom property)
14718 "Delete the property PROPERTY from entry at point-or-marker POM."
14719 (org-with-point-at pom
14720 (if (member property org-special-properties)
14721 nil ; cannot delete these properties.
14722 (let ((range (org-get-property-block)))
14723 (if (and range
14724 (goto-char (car range))
14725 (re-search-forward
14726 (org-re-property property)
14727 (cdr range) t))
14728 (progn
14729 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14731 nil)))))
14733 ;; Multi-values properties are properties that contain multiple values
14734 ;; These values are assumed to be single words, separated by whitespace.
14735 (defun org-entry-add-to-multivalued-property (pom property value)
14736 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14737 (let* ((old (org-entry-get pom property))
14738 (values (and old (org-split-string old "[ \t]"))))
14739 (setq value (org-entry-protect-space value))
14740 (unless (member value values)
14741 (setq values (cons value values))
14742 (org-entry-put pom property
14743 (mapconcat 'identity values " ")))))
14745 (defun org-entry-remove-from-multivalued-property (pom property value)
14746 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14747 (let* ((old (org-entry-get pom property))
14748 (values (and old (org-split-string old "[ \t]"))))
14749 (setq value (org-entry-protect-space value))
14750 (when (member value values)
14751 (setq values (delete value values))
14752 (org-entry-put pom property
14753 (mapconcat 'identity values " ")))))
14755 (defun org-entry-member-in-multivalued-property (pom property value)
14756 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14757 (let* ((old (org-entry-get pom property))
14758 (values (and old (org-split-string old "[ \t]"))))
14759 (setq value (org-entry-protect-space value))
14760 (member value values)))
14762 (defun org-entry-get-multivalued-property (pom property)
14763 "Return a list of values in a multivalued property."
14764 (let* ((value (org-entry-get pom property))
14765 (values (and value (org-split-string value "[ \t]"))))
14766 (mapcar 'org-entry-restore-space values)))
14768 (defun org-entry-put-multivalued-property (pom property &rest values)
14769 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14770 VALUES should be a list of strings. Spaces will be protected."
14771 (org-entry-put pom property
14772 (mapconcat 'org-entry-protect-space values " "))
14773 (let* ((value (org-entry-get pom property))
14774 (values (and value (org-split-string value "[ \t]"))))
14775 (mapcar 'org-entry-restore-space values)))
14777 (defun org-entry-protect-space (s)
14778 "Protect spaces and newline in string S."
14779 (while (string-match " " s)
14780 (setq s (replace-match "%20" t t s)))
14781 (while (string-match "\n" s)
14782 (setq s (replace-match "%0A" t t s)))
14785 (defun org-entry-restore-space (s)
14786 "Restore spaces and newline in string S."
14787 (while (string-match "%20" s)
14788 (setq s (replace-match " " t t s)))
14789 (while (string-match "%0A" s)
14790 (setq s (replace-match "\n" t t s)))
14793 (defvar org-entry-property-inherited-from (make-marker)
14794 "Marker pointing to the entry from where a property was inherited.
14795 Each call to `org-entry-get-with-inheritance' will set this marker to the
14796 location of the entry where the inheritance search matched. If there was
14797 no match, the marker will point nowhere.
14798 Note that also `org-entry-get' calls this function, if the INHERIT flag
14799 is set.")
14801 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14802 "Get PROPERTY of entry or content at point, search higher levels if needed.
14803 The search will stop at the first ancestor which has the property defined.
14804 If the value found is \"nil\", return nil to show that the property
14805 should be considered as undefined (this is the meaning of nil here).
14806 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14807 (move-marker org-entry-property-inherited-from nil)
14808 (let (tmp)
14809 (save-excursion
14810 (save-restriction
14811 (widen)
14812 (catch 'ex
14813 (while t
14814 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14815 (or (ignore-errors (org-back-to-heading t))
14816 (goto-char (point-min)))
14817 (move-marker org-entry-property-inherited-from (point))
14818 (throw 'ex tmp))
14819 (or (ignore-errors (org-up-heading-safe))
14820 (throw 'ex nil))))))
14821 (setq tmp (or tmp
14822 (cdr (assoc property org-file-properties))
14823 (cdr (assoc property org-global-properties))
14824 (cdr (assoc property org-global-properties-fixed))))
14825 (if literal-nil tmp (org-not-nil tmp))))
14827 (defvar org-property-changed-functions nil
14828 "Hook called when the value of a property has changed.
14829 Each hook function should accept two arguments, the name of the property
14830 and the new value.")
14832 (defun org-entry-put (pom property value)
14833 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14834 (org-with-point-at pom
14835 (org-back-to-heading t)
14836 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14837 range)
14838 (cond
14839 ((equal property "TODO")
14840 (when (and (stringp value) (string-match "\\S-" value)
14841 (not (member value org-todo-keywords-1)))
14842 (error "\"%s\" is not a valid TODO state" value))
14843 (if (or (not value)
14844 (not (string-match "\\S-" value)))
14845 (setq value 'none))
14846 (org-todo value)
14847 (org-set-tags nil 'align))
14848 ((equal property "PRIORITY")
14849 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14850 (string-to-char value) ?\ ))
14851 (org-set-tags nil 'align))
14852 ((equal property "CLOCKSUM")
14853 (if (not (re-search-forward
14854 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14855 (error "Cannot find a clock log")
14856 (goto-char (- (match-end 1) 2))
14857 (cond
14858 ((eq value 'earlier) (org-timestamp-down))
14859 ((eq value 'later) (org-timestamp-up)))
14860 (org-clock-sum-current-item)))
14861 ((equal property "SCHEDULED")
14862 (if (re-search-forward org-scheduled-time-regexp end t)
14863 (cond
14864 ((eq value 'earlier) (org-timestamp-change -1 'day))
14865 ((eq value 'later) (org-timestamp-change 1 'day))
14866 (t (call-interactively 'org-schedule)))
14867 (call-interactively 'org-schedule)))
14868 ((equal property "DEADLINE")
14869 (if (re-search-forward org-deadline-time-regexp end t)
14870 (cond
14871 ((eq value 'earlier) (org-timestamp-change -1 'day))
14872 ((eq value 'later) (org-timestamp-change 1 'day))
14873 (t (call-interactively 'org-deadline)))
14874 (call-interactively 'org-deadline)))
14875 ((member property org-special-properties)
14876 (error "The %s property can not yet be set with `org-entry-put'"
14877 property))
14878 (t ; a non-special property
14879 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14880 (setq range (org-get-property-block beg end 'force))
14881 (goto-char (car range))
14882 (if (re-search-forward
14883 (org-re-property-keyword property) (cdr range) t)
14884 (progn
14885 (delete-region (match-beginning 0) (match-end 0))
14886 (goto-char (match-beginning 0)))
14887 (goto-char (cdr range))
14888 (insert "\n")
14889 (backward-char 1)
14890 (org-indent-line))
14891 (insert ":" property ":")
14892 (and value (insert " " value))
14893 (org-indent-line)))))
14894 (run-hook-with-args 'org-property-changed-functions property value)))
14896 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14897 "Get all property keys in the current buffer.
14898 With INCLUDE-SPECIALS, also list the special properties that reflect things
14899 like tags and TODO state.
14900 With INCLUDE-DEFAULTS, also include properties that has special meaning
14901 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14902 and others.
14903 With INCLUDE-COLUMNS, also include property names given in COLUMN
14904 formats in the current buffer."
14905 (let (rtn range cfmt s p)
14906 (save-excursion
14907 (save-restriction
14908 (widen)
14909 (goto-char (point-min))
14910 (while (re-search-forward org-property-start-re nil t)
14911 (setq range (org-get-property-block))
14912 (goto-char (car range))
14913 (while (re-search-forward
14914 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14915 (cdr range) t)
14916 (add-to-list 'rtn (org-match-string-no-properties 1)))
14917 (outline-next-heading))))
14919 (when include-specials
14920 (setq rtn (append org-special-properties rtn)))
14922 (when include-defaults
14923 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14924 (add-to-list 'rtn org-effort-property))
14926 (when include-columns
14927 (save-excursion
14928 (save-restriction
14929 (widen)
14930 (goto-char (point-min))
14931 (while (re-search-forward
14932 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14933 nil t)
14934 (setq cfmt (match-string 2) s 0)
14935 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14936 cfmt s)
14937 (setq s (match-end 0)
14938 p (match-string 1 cfmt))
14939 (unless (or (equal p "ITEM")
14940 (member p org-special-properties))
14941 (add-to-list 'rtn (match-string 1 cfmt))))))))
14943 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14945 (defun org-property-values (key)
14946 "Return a list of all values of property KEY in the current buffer."
14947 (save-excursion
14948 (save-restriction
14949 (widen)
14950 (goto-char (point-min))
14951 (let ((re (org-re-property key))
14952 values)
14953 (while (re-search-forward re nil t)
14954 (add-to-list 'values (org-trim (match-string 1))))
14955 (delete "" values)))))
14957 (defun org-insert-property-drawer ()
14958 "Insert a property drawer into the current entry."
14959 (org-back-to-heading t)
14960 (looking-at org-outline-regexp)
14961 (let ((indent (if org-adapt-indentation
14962 (- (match-end 0) (match-beginning 0))
14964 (beg (point))
14965 (re (concat "^[ \t]*" org-keyword-time-regexp))
14966 end hiddenp)
14967 (outline-next-heading)
14968 (setq end (point))
14969 (goto-char beg)
14970 (while (re-search-forward re end t))
14971 (setq hiddenp (outline-invisible-p))
14972 (end-of-line 1)
14973 (and (equal (char-after) ?\n) (forward-char 1))
14974 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14975 (if (member (match-string 1) '("CLOCK:" ":END:"))
14976 ;; just skip this line
14977 (beginning-of-line 2)
14978 ;; Drawer start, find the end
14979 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14980 (beginning-of-line 1)))
14981 (org-skip-over-state-notes)
14982 (skip-chars-backward " \t\n\r")
14983 (if (eq (char-before) ?*) (forward-char 1))
14984 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14985 (beginning-of-line 0)
14986 (org-indent-to-column indent)
14987 (beginning-of-line 2)
14988 (org-indent-to-column indent)
14989 (beginning-of-line 0)
14990 (if hiddenp
14991 (save-excursion
14992 (org-back-to-heading t)
14993 (hide-entry))
14994 (org-flag-drawer t))))
14996 (defun org-insert-drawer (&optional arg drawer)
14997 "Insert a drawer at point.
14999 Optional argument DRAWER, when non-nil, is a string representing
15000 drawer's name. Otherwise, the user is prompted for a name.
15002 If a region is active, insert the drawer around that region
15003 instead.
15005 Point is left between drawer's boundaries."
15006 (interactive "P")
15007 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15008 "LOGBOOK"))
15009 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15010 ;; internally by Org. They are meant to be inserted
15011 ;; automatically.
15012 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15013 ;; Remove system drawers from list. Note: For some reason,
15014 ;; `org-completing-read' ignores the predicate while
15015 ;; `completing-read' handles it fine.
15016 (drawer (if arg "PROPERTIES"
15017 (or drawer
15018 (completing-read
15019 "Drawer: " org-drawers
15020 (lambda (d) (not (member d system-drawers))))))))
15021 (cond
15022 ;; With C-u, fall back on `org-insert-property-drawer'
15023 (arg (org-insert-property-drawer))
15024 ;; With an active region, insert a drawer at point.
15025 ((not (org-region-active-p))
15026 (progn
15027 (unless (bolp) (insert "\n"))
15028 (insert (format ":%s:\n\n:END:\n" drawer))
15029 (forward-line -2)))
15030 ;; Otherwise, insert the drawer at point
15032 (let ((rbeg (region-beginning))
15033 (rend (copy-marker (region-end))))
15034 (unwind-protect
15035 (progn
15036 (goto-char rbeg)
15037 (beginning-of-line)
15038 (when (save-excursion
15039 (re-search-forward org-outline-regexp-bol rend t))
15040 (error "Drawers cannot contain headlines"))
15041 ;; Position point at the beginning of the first
15042 ;; non-blank line in region. Insert drawer's opening
15043 ;; there, then indent it.
15044 (org-skip-whitespace)
15045 (beginning-of-line)
15046 (insert ":" drawer ":\n")
15047 (forward-line -1)
15048 (indent-for-tab-command)
15049 ;; Move point to the beginning of the first blank line
15050 ;; after the last non-blank line in region. Insert
15051 ;; drawer's closing, then indent it.
15052 (goto-char rend)
15053 (skip-chars-backward " \r\t\n")
15054 (insert "\n:END:")
15055 (deactivate-mark t)
15056 (indent-for-tab-command)
15057 (unless (eolp) (insert "\n")))
15058 ;; Clear marker, whatever the outcome of insertion is.
15059 (set-marker rend nil)))))))
15061 (defvar org-property-set-functions-alist nil
15062 "Property set function alist.
15063 Each entry should have the following format:
15065 (PROPERTY . READ-FUNCTION)
15067 The read function will be called with the same argument as
15068 `org-completing-read'.")
15070 (defun org-set-property-function (property)
15071 "Get the function that should be used to set PROPERTY.
15072 This is computed according to `org-property-set-functions-alist'."
15073 (or (cdr (assoc property org-property-set-functions-alist))
15074 'org-completing-read))
15076 (defun org-read-property-value (property)
15077 "Read PROPERTY value from user."
15078 (let* ((completion-ignore-case t)
15079 (allowed (org-property-get-allowed-values nil property 'table))
15080 (cur (org-entry-get nil property))
15081 (prompt (concat property " value"
15082 (if (and cur (string-match "\\S-" cur))
15083 (concat " [" cur "]") "") ": "))
15084 (set-function (org-set-property-function property))
15085 (val (if allowed
15086 (funcall set-function prompt allowed nil
15087 (not (get-text-property 0 'org-unrestricted
15088 (caar allowed))))
15089 (let (org-completion-use-ido org-completion-use-iswitchb)
15090 (funcall set-function prompt
15091 (mapcar 'list (org-property-values property))
15092 nil nil "" nil cur)))))
15093 (if (equal val "")
15095 val)))
15097 (defvar org-last-set-property nil)
15098 (defvar org-last-set-property-value nil)
15099 (defun org-read-property-name ()
15100 "Read a property name."
15101 (let* ((completion-ignore-case t)
15102 (keys (org-buffer-property-keys nil t t))
15103 (default-prop (or (save-excursion
15104 (save-match-data
15105 (beginning-of-line)
15106 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15107 (null (string= (match-string 1) "END"))
15108 (match-string 1))))
15109 org-last-set-property))
15110 (property (org-icompleting-read
15111 (concat "Property"
15112 (if default-prop (concat " [" default-prop "]") "")
15113 ": ")
15114 (mapcar 'list keys)
15115 nil nil nil nil
15116 default-prop)))
15117 (if (member property keys)
15118 property
15119 (or (cdr (assoc (downcase property)
15120 (mapcar (lambda (x) (cons (downcase x) x))
15121 keys)))
15122 property))))
15124 (defun org-set-property-and-value (use-last)
15125 "Allow to set [PROPERTY]: [value] direction from prompt.
15126 When use-default, don't even ask, just use the last
15127 \"[PROPERTY]: [value]\" string from the history."
15128 (interactive "P")
15129 (let* ((completion-ignore-case t)
15130 (pv (or (and use-last org-last-set-property-value)
15131 (org-completing-read
15132 "Enter a \"[Property]: [value]\" pair: "
15133 nil nil nil nil nil
15134 org-last-set-property-value)))
15135 prop val)
15136 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15137 (setq prop (match-string 1 pv)
15138 val (match-string 2 pv))
15139 (org-set-property prop val))))
15141 (defun org-set-property (property value)
15142 "In the current entry, set PROPERTY to VALUE.
15143 When called interactively, this will prompt for a property name, offering
15144 completion on existing and default properties. And then it will prompt
15145 for a value, offering completion either on allowed values (via an inherited
15146 xxx_ALL property) or on existing values in other instances of this property
15147 in the current file."
15148 (interactive (list nil nil))
15149 (let* ((property (or property (org-read-property-name)))
15150 (value (or value (org-read-property-value property)))
15151 (fn (cdr (assoc property org-properties-postprocess-alist))))
15152 (setq org-last-set-property property)
15153 (setq org-last-set-property-value (concat property ": " value))
15154 ;; Possibly postprocess the inserted value:
15155 (when fn (setq value (funcall fn value)))
15156 (unless (equal (org-entry-get nil property) value)
15157 (org-entry-put nil property value))))
15159 (defun org-delete-property (property)
15160 "In the current entry, delete PROPERTY."
15161 (interactive
15162 (let* ((completion-ignore-case t)
15163 (prop (org-icompleting-read "Property: "
15164 (org-entry-properties nil 'standard))))
15165 (list prop)))
15166 (message "Property %s %s" property
15167 (if (org-entry-delete nil property)
15168 "deleted"
15169 "was not present in the entry")))
15171 (defun org-delete-property-globally (property)
15172 "Remove PROPERTY globally, from all entries."
15173 (interactive
15174 (let* ((completion-ignore-case t)
15175 (prop (org-icompleting-read
15176 "Globally remove property: "
15177 (mapcar 'list (org-buffer-property-keys)))))
15178 (list prop)))
15179 (save-excursion
15180 (save-restriction
15181 (widen)
15182 (goto-char (point-min))
15183 (let ((cnt 0))
15184 (while (re-search-forward
15185 (org-re-property property)
15186 nil t)
15187 (setq cnt (1+ cnt))
15188 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15189 (message "Property \"%s\" removed from %d entries" property cnt)))))
15191 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15193 (defun org-compute-property-at-point ()
15194 "Compute the property at point.
15195 This looks for an enclosing column format, extracts the operator and
15196 then applies it to the property in the column format's scope."
15197 (interactive)
15198 (unless (org-at-property-p)
15199 (error "Not at a property"))
15200 (let ((prop (org-match-string-no-properties 2)))
15201 (org-columns-get-format-and-top-level)
15202 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15203 (error "No operator defined for property %s" prop))
15204 (org-columns-compute prop)))
15206 (defvar org-property-allowed-value-functions nil
15207 "Hook for functions supplying allowed values for a specific property.
15208 The functions must take a single argument, the name of the property, and
15209 return a flat list of allowed values. If \":ETC\" is one of
15210 the values, this means that these values are intended as defaults for
15211 completion, but that other values should be allowed too.
15212 The functions must return nil if they are not responsible for this
15213 property.")
15215 (defun org-property-get-allowed-values (pom property &optional table)
15216 "Get allowed values for the property PROPERTY.
15217 When TABLE is non-nil, return an alist that can directly be used for
15218 completion."
15219 (let (vals)
15220 (cond
15221 ((equal property "TODO")
15222 (setq vals (org-with-point-at pom
15223 (append org-todo-keywords-1 '("")))))
15224 ((equal property "PRIORITY")
15225 (let ((n org-lowest-priority))
15226 (while (>= n org-highest-priority)
15227 (push (char-to-string n) vals)
15228 (setq n (1- n)))))
15229 ((member property org-special-properties))
15230 ((setq vals (run-hook-with-args-until-success
15231 'org-property-allowed-value-functions property)))
15233 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15234 (when (and vals (string-match "\\S-" vals))
15235 (setq vals (car (read-from-string (concat "(" vals ")"))))
15236 (setq vals (mapcar (lambda (x)
15237 (cond ((stringp x) x)
15238 ((numberp x) (number-to-string x))
15239 ((symbolp x) (symbol-name x))
15240 (t "???")))
15241 vals)))))
15242 (when (member ":ETC" vals)
15243 (setq vals (remove ":ETC" vals))
15244 (org-add-props (car vals) '(org-unrestricted t)))
15245 (if table (mapcar 'list vals) vals)))
15247 (defun org-property-previous-allowed-value (&optional previous)
15248 "Switch to the next allowed value for this property."
15249 (interactive)
15250 (org-property-next-allowed-value t))
15252 (defun org-property-next-allowed-value (&optional previous)
15253 "Switch to the next allowed value for this property."
15254 (interactive)
15255 (unless (org-at-property-p)
15256 (error "Not at a property"))
15257 (let* ((key (match-string 2))
15258 (value (match-string 3))
15259 (allowed (or (org-property-get-allowed-values (point) key)
15260 (and (member value '("[ ]" "[-]" "[X]"))
15261 '("[ ]" "[X]"))))
15262 nval)
15263 (unless allowed
15264 (error "Allowed values for this property have not been defined"))
15265 (if previous (setq allowed (reverse allowed)))
15266 (if (member value allowed)
15267 (setq nval (car (cdr (member value allowed)))))
15268 (setq nval (or nval (car allowed)))
15269 (if (equal nval value)
15270 (error "Only one allowed value for this property"))
15271 (org-at-property-p)
15272 (replace-match (concat " :" key ": " nval) t t)
15273 (org-indent-line)
15274 (beginning-of-line 1)
15275 (skip-chars-forward " \t")
15276 (run-hook-with-args 'org-property-changed-functions key nval)))
15278 (defun org-find-olp (path &optional this-buffer)
15279 "Return a marker pointing to the entry at outline path OLP.
15280 If anything goes wrong, throw an error.
15281 You can wrap this call to catch the error like this:
15283 (condition-case msg
15284 (org-mobile-locate-entry (match-string 4))
15285 (error (nth 1 msg)))
15287 The return value will then be either a string with the error message,
15288 or a marker if everything is OK.
15290 If THIS-BUFFER is set, the outline path does not contain a file,
15291 only headings."
15292 (let* ((file (if this-buffer buffer-file-name (pop path)))
15293 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15294 (level 1)
15295 (lmin 1)
15296 (lmax 1)
15297 limit re end found pos heading cnt flevel)
15298 (unless buffer (error "File not found :%s" file))
15299 (with-current-buffer buffer
15300 (save-excursion
15301 (save-restriction
15302 (widen)
15303 (setq limit (point-max))
15304 (goto-char (point-min))
15305 (while (setq heading (pop path))
15306 (setq re (format org-complex-heading-regexp-format
15307 (regexp-quote heading)))
15308 (setq cnt 0 pos (point))
15309 (while (re-search-forward re end t)
15310 (setq level (- (match-end 1) (match-beginning 1)))
15311 (if (and (>= level lmin) (<= level lmax))
15312 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15313 (when (= cnt 0) (error "Heading not found on level %d: %s"
15314 lmax heading))
15315 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15316 lmax heading))
15317 (goto-char found)
15318 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15319 (setq end (save-excursion (org-end-of-subtree t t))))
15320 (when (org-at-heading-p)
15321 (point-marker)))))))
15323 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15324 "Find node HEADING in BUFFER.
15325 Return a marker to the heading if it was found, or nil if not.
15326 If POS-ONLY is set, return just the position instead of a marker.
15328 The heading text must match exact, but it may have a TODO keyword,
15329 a priority cookie and tags in the standard locations."
15330 (with-current-buffer (or buffer (current-buffer))
15331 (save-excursion
15332 (save-restriction
15333 (widen)
15334 (goto-char (point-min))
15335 (let (case-fold-search)
15336 (if (re-search-forward
15337 (format org-complex-heading-regexp-format
15338 (regexp-quote heading)) nil t)
15339 (if pos-only
15340 (match-beginning 0)
15341 (move-marker (make-marker) (match-beginning 0)))))))))
15343 (defun org-find-exact-heading-in-directory (heading &optional dir)
15344 "Find Org node headline HEADING in all .org files in directory DIR.
15345 When the target headline is found, return a marker to this location."
15346 (let ((files (directory-files (or dir default-directory)
15347 nil "\\`[^.#].*\\.org\\'"))
15348 file visiting m buffer)
15349 (catch 'found
15350 (while (setq file (pop files))
15351 (message "trying %s" file)
15352 (setq visiting (org-find-base-buffer-visiting file))
15353 (setq buffer (or visiting (find-file-noselect file)))
15354 (setq m (org-find-exact-headline-in-buffer
15355 heading buffer))
15356 (when (and (not m) (not visiting)) (kill-buffer buffer))
15357 (and m (throw 'found m))))))
15359 (defun org-find-entry-with-id (ident)
15360 "Locate the entry that contains the ID property with exact value IDENT.
15361 IDENT can be a string, a symbol or a number, this function will search for
15362 the string representation of it.
15363 Return the position where this entry starts, or nil if there is no such entry."
15364 (interactive "sID: ")
15365 (let ((id (cond
15366 ((stringp ident) ident)
15367 ((symbol-name ident) (symbol-name ident))
15368 ((numberp ident) (number-to-string ident))
15369 (t (error "IDENT %s must be a string, symbol or number" ident))))
15370 (case-fold-search nil))
15371 (save-excursion
15372 (save-restriction
15373 (widen)
15374 (goto-char (point-min))
15375 (when (re-search-forward
15376 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15377 nil t)
15378 (org-back-to-heading t)
15379 (point))))))
15381 ;;;; Timestamps
15383 (defvar org-last-changed-timestamp nil)
15384 (defvar org-last-inserted-timestamp nil
15385 "The last time stamp inserted with `org-insert-time-stamp'.")
15386 (defvar org-time-was-given) ; dynamically scoped parameter
15387 (defvar org-end-time-was-given) ; dynamically scoped parameter
15388 (defvar org-ts-what) ; dynamically scoped parameter
15390 (defun org-time-stamp (arg &optional inactive)
15391 "Prompt for a date/time and insert a time stamp.
15392 If the user specifies a time like HH:MM or if this command is
15393 called with at least one prefix argument, the time stamp contains
15394 the date and the time. Otherwise, only the date is be included.
15396 All parts of a date not specified by the user is filled in from
15397 the current date/time. So if you just press return without
15398 typing anything, the time stamp will represent the current
15399 date/time.
15401 If there is already a timestamp at the cursor, it will be
15402 modified.
15404 With two universal prefix arguments, insert an active timestamp
15405 with the current time without prompting the user."
15406 (interactive "P")
15407 (let* ((ts nil)
15408 (default-time
15409 ;; Default time is either today, or, when entering a range,
15410 ;; the range start.
15411 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15412 (save-excursion
15413 (re-search-backward
15414 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15415 (- (point) 20) t)))
15416 (apply 'encode-time (org-parse-time-string (match-string 1)))
15417 (current-time)))
15418 (default-input (and ts (org-get-compact-tod ts)))
15419 (repeater (save-excursion
15420 (save-match-data
15421 (beginning-of-line)
15422 (when (re-search-forward
15423 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15424 (save-excursion (progn (end-of-line) (point))) t)
15425 (match-string 0)))))
15426 org-time-was-given org-end-time-was-given time)
15427 (cond
15428 ((and (org-at-timestamp-p t)
15429 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15430 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15431 (insert "--")
15432 (setq time (let ((this-command this-command))
15433 (org-read-date arg 'totime nil nil
15434 default-time default-input inactive)))
15435 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15436 ((org-at-timestamp-p t)
15437 (setq time (let ((this-command this-command))
15438 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15439 (when (org-at-timestamp-p t) ; just to get the match data
15440 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15441 (replace-match "")
15442 (setq org-last-changed-timestamp
15443 (org-insert-time-stamp
15444 time (or org-time-was-given arg)
15445 inactive nil nil (list org-end-time-was-given)))
15446 (when repeater (goto-char (1- (point))) (insert " " repeater)
15447 (setq org-last-changed-timestamp
15448 (concat (substring org-last-inserted-timestamp 0 -1)
15449 " " repeater ">"))))
15450 (message "Timestamp updated"))
15451 ((equal arg '(16))
15452 (org-insert-time-stamp (current-time) t))
15454 (setq time (let ((this-command this-command))
15455 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15456 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15457 nil nil (list org-end-time-was-given))))))
15459 ;; FIXME: can we use this for something else, like computing time differences?
15460 (defun org-get-compact-tod (s)
15461 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15462 (let* ((t1 (match-string 1 s))
15463 (h1 (string-to-number (match-string 2 s)))
15464 (m1 (string-to-number (match-string 3 s)))
15465 (t2 (and (match-end 4) (match-string 5 s)))
15466 (h2 (and t2 (string-to-number (match-string 6 s))))
15467 (m2 (and t2 (string-to-number (match-string 7 s))))
15468 dh dm)
15469 (if (not t2)
15471 (setq dh (- h2 h1) dm (- m2 m1))
15472 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15473 (concat t1 "+" (number-to-string dh)
15474 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15476 (defun org-time-stamp-inactive (&optional arg)
15477 "Insert an inactive time stamp.
15478 An inactive time stamp is enclosed in square brackets instead of angle
15479 brackets. It is inactive in the sense that it does not trigger agenda entries,
15480 does not link to the calendar and cannot be changed with the S-cursor keys.
15481 So these are more for recording a certain time/date."
15482 (interactive "P")
15483 (org-time-stamp arg 'inactive))
15485 (defvar org-date-ovl (make-overlay 1 1))
15486 (overlay-put org-date-ovl 'face 'org-date-selected)
15487 (org-detach-overlay org-date-ovl)
15489 (defvar org-ans1) ; dynamically scoped parameter
15490 (defvar org-ans2) ; dynamically scoped parameter
15492 (defvar org-plain-time-of-day-regexp) ; defined below
15494 (defvar org-overriding-default-time nil) ; dynamically scoped
15495 (defvar org-read-date-overlay nil)
15496 (defvar org-dcst nil) ; dynamically scoped
15497 (defvar org-read-date-history nil)
15498 (defvar org-read-date-final-answer nil)
15499 (defvar org-read-date-analyze-futurep nil)
15500 (defvar org-read-date-analyze-forced-year nil)
15501 (defvar org-read-date-inactive)
15503 (defun org-read-date (&optional org-with-time to-time from-string prompt
15504 default-time default-input inactive)
15505 "Read a date, possibly a time, and make things smooth for the user.
15506 The prompt will suggest to enter an ISO date, but you can also enter anything
15507 which will at least partially be understood by `parse-time-string'.
15508 Unrecognized parts of the date will default to the current day, month, year,
15509 hour and minute. If this command is called to replace a timestamp at point,
15510 or to enter the second timestamp of a range, the default time is taken
15511 from the existing stamp. Furthermore, the command prefers the future,
15512 so if you are giving a date where the year is not given, and the day-month
15513 combination is already past in the current year, it will assume you
15514 mean next year. For details, see the manual. A few examples:
15516 3-2-5 --> 2003-02-05
15517 feb 15 --> currentyear-02-15
15518 2/15 --> currentyear-02-15
15519 sep 12 9 --> 2009-09-12
15520 12:45 --> today 12:45
15521 22 sept 0:34 --> currentyear-09-22 0:34
15522 12 --> currentyear-currentmonth-12
15523 Fri --> nearest Friday (today or later)
15524 etc.
15526 Furthermore you can specify a relative date by giving, as the *first* thing
15527 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15528 change in days weeks, months, years.
15529 With a single plus or minus, the date is relative to today. With a double
15530 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15531 +4d --> four days from today
15532 +4 --> same as above
15533 +2w --> two weeks from today
15534 ++5 --> five days from default date
15536 The function understands only English month and weekday abbreviations.
15538 While prompting, a calendar is popped up - you can also select the
15539 date with the mouse (button 1). The calendar shows a period of three
15540 months. To scroll it to other months, use the keys `>' and `<'.
15541 If you don't like the calendar, turn it off with
15542 \(setq org-read-date-popup-calendar nil)
15544 With optional argument TO-TIME, the date will immediately be converted
15545 to an internal time.
15546 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15547 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15548 still enter a time, and this function will inform the calling routine
15549 about this change. The calling routine may then choose to change the
15550 format used to insert the time stamp into the buffer to include the time.
15551 With optional argument FROM-STRING, read from this string instead from
15552 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15553 the time/date that is used for everything that is not specified by the
15554 user."
15555 (require 'parse-time)
15556 (let* ((org-time-stamp-rounding-minutes
15557 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15558 (org-dcst org-display-custom-times)
15559 (ct (org-current-time))
15560 (org-def (or org-overriding-default-time default-time ct))
15561 (org-defdecode (decode-time org-def))
15562 (dummy (progn
15563 (when (< (nth 2 org-defdecode) org-extend-today-until)
15564 (setcar (nthcdr 2 org-defdecode) -1)
15565 (setcar (nthcdr 1 org-defdecode) 59)
15566 (setq org-def (apply 'encode-time org-defdecode)
15567 org-defdecode (decode-time org-def)))))
15568 (calendar-frame-setup nil)
15569 (calendar-setup nil)
15570 (calendar-move-hook nil)
15571 (calendar-view-diary-initially-flag nil)
15572 (calendar-view-holidays-initially-flag nil)
15573 (timestr (format-time-string
15574 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15575 (prompt (concat (if prompt (concat prompt " ") "")
15576 (format "Date+time [%s]: " timestr)))
15577 ans (org-ans0 "") org-ans1 org-ans2 final)
15579 (cond
15580 (from-string (setq ans from-string))
15581 (org-read-date-popup-calendar
15582 (save-excursion
15583 (save-window-excursion
15584 (calendar)
15585 (org-eval-in-calendar '(setq cursor-type nil) t)
15586 (unwind-protect
15587 (progn
15588 (calendar-forward-day (- (time-to-days org-def)
15589 (calendar-absolute-from-gregorian
15590 (calendar-current-date))))
15591 (org-eval-in-calendar nil t)
15592 (let* ((old-map (current-local-map))
15593 (map (copy-keymap calendar-mode-map))
15594 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15595 (org-defkey map (kbd "RET") 'org-calendar-select)
15596 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15597 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15598 (org-defkey minibuffer-local-map [(meta shift left)]
15599 (lambda () (interactive)
15600 (org-eval-in-calendar '(calendar-backward-month 1))))
15601 (org-defkey minibuffer-local-map [(meta shift right)]
15602 (lambda () (interactive)
15603 (org-eval-in-calendar '(calendar-forward-month 1))))
15604 (org-defkey minibuffer-local-map [(meta shift up)]
15605 (lambda () (interactive)
15606 (org-eval-in-calendar '(calendar-backward-year 1))))
15607 (org-defkey minibuffer-local-map [(meta shift down)]
15608 (lambda () (interactive)
15609 (org-eval-in-calendar '(calendar-forward-year 1))))
15610 (org-defkey minibuffer-local-map [?\e (shift left)]
15611 (lambda () (interactive)
15612 (org-eval-in-calendar '(calendar-backward-month 1))))
15613 (org-defkey minibuffer-local-map [?\e (shift right)]
15614 (lambda () (interactive)
15615 (org-eval-in-calendar '(calendar-forward-month 1))))
15616 (org-defkey minibuffer-local-map [?\e (shift up)]
15617 (lambda () (interactive)
15618 (org-eval-in-calendar '(calendar-backward-year 1))))
15619 (org-defkey minibuffer-local-map [?\e (shift down)]
15620 (lambda () (interactive)
15621 (org-eval-in-calendar '(calendar-forward-year 1))))
15622 (org-defkey minibuffer-local-map [(shift up)]
15623 (lambda () (interactive)
15624 (org-eval-in-calendar '(calendar-backward-week 1))))
15625 (org-defkey minibuffer-local-map [(shift down)]
15626 (lambda () (interactive)
15627 (org-eval-in-calendar '(calendar-forward-week 1))))
15628 (org-defkey minibuffer-local-map [(shift left)]
15629 (lambda () (interactive)
15630 (org-eval-in-calendar '(calendar-backward-day 1))))
15631 (org-defkey minibuffer-local-map [(shift right)]
15632 (lambda () (interactive)
15633 (org-eval-in-calendar '(calendar-forward-day 1))))
15634 (org-defkey minibuffer-local-map ">"
15635 (lambda () (interactive)
15636 (org-eval-in-calendar '(scroll-calendar-left 1))))
15637 (org-defkey minibuffer-local-map "<"
15638 (lambda () (interactive)
15639 (org-eval-in-calendar '(scroll-calendar-right 1))))
15640 (org-defkey minibuffer-local-map "\C-v"
15641 (lambda () (interactive)
15642 (org-eval-in-calendar
15643 '(calendar-scroll-left-three-months 1))))
15644 (org-defkey minibuffer-local-map "\M-v"
15645 (lambda () (interactive)
15646 (org-eval-in-calendar
15647 '(calendar-scroll-right-three-months 1))))
15648 (run-hooks 'org-read-date-minibuffer-setup-hook)
15649 (unwind-protect
15650 (progn
15651 (use-local-map map)
15652 (setq org-read-date-inactive inactive)
15653 (add-hook 'post-command-hook 'org-read-date-display)
15654 (setq org-ans0 (read-string prompt default-input
15655 'org-read-date-history nil))
15656 ;; org-ans0: from prompt
15657 ;; org-ans1: from mouse click
15658 ;; org-ans2: from calendar motion
15659 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15660 (remove-hook 'post-command-hook 'org-read-date-display)
15661 (use-local-map old-map)
15662 (when org-read-date-overlay
15663 (delete-overlay org-read-date-overlay)
15664 (setq org-read-date-overlay nil)))))
15665 (bury-buffer "*Calendar*")))))
15667 (t ; Naked prompt only
15668 (unwind-protect
15669 (setq ans (read-string prompt default-input
15670 'org-read-date-history timestr))
15671 (when org-read-date-overlay
15672 (delete-overlay org-read-date-overlay)
15673 (setq org-read-date-overlay nil)))))
15675 (setq final (org-read-date-analyze ans org-def org-defdecode))
15677 (when org-read-date-analyze-forced-year
15678 (message "Year was forced into %s"
15679 (if org-read-date-force-compatible-dates
15680 "compatible range (1970-2037)"
15681 "range representable on this machine"))
15682 (ding))
15684 ;; One round trip to get rid of 34th of August and stuff like that....
15685 (setq final (decode-time (apply 'encode-time final)))
15687 (setq org-read-date-final-answer ans)
15689 (if to-time
15690 (apply 'encode-time final)
15691 (if (and (boundp 'org-time-was-given) org-time-was-given)
15692 (format "%04d-%02d-%02d %02d:%02d"
15693 (nth 5 final) (nth 4 final) (nth 3 final)
15694 (nth 2 final) (nth 1 final))
15695 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15697 (defvar org-def)
15698 (defvar org-defdecode)
15699 (defvar org-with-time)
15700 (defun org-read-date-display ()
15701 "Display the current date prompt interpretation in the minibuffer."
15702 (when org-read-date-display-live
15703 (when org-read-date-overlay
15704 (delete-overlay org-read-date-overlay))
15705 (when (minibufferp (current-buffer))
15706 (save-excursion
15707 (end-of-line 1)
15708 (while (not (equal (buffer-substring
15709 (max (point-min) (- (point) 4)) (point))
15710 " "))
15711 (insert " ")))
15712 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15713 " " (or org-ans1 org-ans2)))
15714 (org-end-time-was-given nil)
15715 (f (org-read-date-analyze ans org-def org-defdecode))
15716 (fmts (if org-dcst
15717 org-time-stamp-custom-formats
15718 org-time-stamp-formats))
15719 (fmt (if (or org-with-time
15720 (and (boundp 'org-time-was-given) org-time-was-given))
15721 (cdr fmts)
15722 (car fmts)))
15723 (txt (format-time-string fmt (apply 'encode-time f)))
15724 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15725 (txt (concat "=> " txt)))
15726 (when (and org-end-time-was-given
15727 (string-match org-plain-time-of-day-regexp txt))
15728 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15729 org-end-time-was-given
15730 (substring txt (match-end 0)))))
15731 (when org-read-date-analyze-futurep
15732 (setq txt (concat txt " (=>F)")))
15733 (setq org-read-date-overlay
15734 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15735 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15737 (defun org-read-date-analyze (ans org-def org-defdecode)
15738 "Analyze the combined answer of the date prompt."
15739 ;; FIXME: cleanup and comment
15740 (let ((nowdecode (decode-time (current-time)))
15741 delta deltan deltaw deltadef year month day
15742 hour minute second wday pm h2 m2 tl wday1
15743 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15744 (setq org-read-date-analyze-futurep nil
15745 org-read-date-analyze-forced-year nil)
15746 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15747 (setq ans "+0"))
15749 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15750 (setq ans (replace-match "" t t ans)
15751 deltan (car delta)
15752 deltaw (nth 1 delta)
15753 deltadef (nth 2 delta)))
15755 ;; Check if there is an iso week date in there. If yes, store the
15756 ;; info and postpone interpreting it until the rest of the parsing
15757 ;; is done.
15758 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15759 (setq iso-year (if (match-end 1)
15760 (org-small-year-to-year
15761 (string-to-number (match-string 1 ans))))
15762 iso-weekday (if (match-end 3)
15763 (string-to-number (match-string 3 ans)))
15764 iso-week (string-to-number (match-string 2 ans)))
15765 (setq ans (replace-match "" t t ans)))
15767 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15768 (when (string-match
15769 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15770 (setq year (if (match-end 2)
15771 (string-to-number (match-string 2 ans))
15772 (progn (setq kill-year t)
15773 (string-to-number (format-time-string "%Y"))))
15774 month (string-to-number (match-string 3 ans))
15775 day (string-to-number (match-string 4 ans)))
15776 (if (< year 100) (setq year (+ 2000 year)))
15777 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15778 t nil ans)))
15780 ;; Help matching dotted european dates
15781 (when (string-match
15782 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15783 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15784 (setq kill-year t)
15785 (string-to-number (format-time-string "%Y")))
15786 day (string-to-number (match-string 1 ans))
15787 month (string-to-number (match-string 2 ans))
15788 ans (replace-match (format "%04d-%02d-%02d" year month day)
15789 t nil ans)))
15791 ;; Help matching american dates, like 5/30 or 5/30/7
15792 (when (string-match
15793 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15794 (setq year (if (match-end 4)
15795 (string-to-number (match-string 4 ans))
15796 (progn (setq kill-year t)
15797 (string-to-number (format-time-string "%Y"))))
15798 month (string-to-number (match-string 1 ans))
15799 day (string-to-number (match-string 2 ans)))
15800 (if (< year 100) (setq year (+ 2000 year)))
15801 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15802 t nil ans)))
15803 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15804 ;; If there is a time with am/pm, and *no* time without it, we convert
15805 ;; so that matching will be successful.
15806 (loop for i from 1 to 2 do ; twice, for end time as well
15807 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15808 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15809 (setq hour (string-to-number (match-string 1 ans))
15810 minute (if (match-end 3)
15811 (string-to-number (match-string 3 ans))
15813 pm (equal ?p
15814 (string-to-char (downcase (match-string 4 ans)))))
15815 (if (and (= hour 12) (not pm))
15816 (setq hour 0)
15817 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15818 (setq ans (replace-match (format "%02d:%02d" hour minute)
15819 t t ans))))
15821 ;; Check if a time range is given as a duration
15822 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15823 (setq hour (string-to-number (match-string 1 ans))
15824 h2 (+ hour (string-to-number (match-string 3 ans)))
15825 minute (string-to-number (match-string 2 ans))
15826 m2 (+ minute (if (match-end 5) (string-to-number
15827 (match-string 5 ans))0)))
15828 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15829 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15830 t t ans)))
15832 ;; Check if there is a time range
15833 (when (boundp 'org-end-time-was-given)
15834 (setq org-time-was-given nil)
15835 (when (and (string-match org-plain-time-of-day-regexp ans)
15836 (match-end 8))
15837 (setq org-end-time-was-given (match-string 8 ans))
15838 (setq ans (concat (substring ans 0 (match-beginning 7))
15839 (substring ans (match-end 7))))))
15841 (setq tl (parse-time-string ans)
15842 day (or (nth 3 tl) (nth 3 org-defdecode))
15843 month (or (nth 4 tl)
15844 (if (and org-read-date-prefer-future
15845 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15846 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15847 (nth 4 org-defdecode)))
15848 year (or (and (not kill-year) (nth 5 tl))
15849 (if (and org-read-date-prefer-future
15850 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15851 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15852 (nth 5 org-defdecode)))
15853 hour (or (nth 2 tl) (nth 2 org-defdecode))
15854 minute (or (nth 1 tl) (nth 1 org-defdecode))
15855 second (or (nth 0 tl) 0)
15856 wday (nth 6 tl))
15858 (when (and (eq org-read-date-prefer-future 'time)
15859 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15860 (equal day (nth 3 nowdecode))
15861 (equal month (nth 4 nowdecode))
15862 (equal year (nth 5 nowdecode))
15863 (nth 2 tl)
15864 (or (< (nth 2 tl) (nth 2 nowdecode))
15865 (and (= (nth 2 tl) (nth 2 nowdecode))
15866 (nth 1 tl)
15867 (< (nth 1 tl) (nth 1 nowdecode)))))
15868 (setq day (1+ day)
15869 futurep t))
15871 ;; Special date definitions below
15872 (cond
15873 (iso-week
15874 ;; There was an iso week
15875 (require 'cal-iso)
15876 (setq futurep nil)
15877 (setq year (or iso-year year)
15878 day (or iso-weekday wday 1)
15879 wday nil ; to make sure that the trigger below does not match
15880 iso-date (calendar-gregorian-from-absolute
15881 (calendar-absolute-from-iso
15882 (list iso-week day year))))
15883 ; FIXME: Should we also push ISO weeks into the future?
15884 ; (when (and org-read-date-prefer-future
15885 ; (not iso-year)
15886 ; (< (calendar-absolute-from-gregorian iso-date)
15887 ; (time-to-days (current-time))))
15888 ; (setq year (1+ year)
15889 ; iso-date (calendar-gregorian-from-absolute
15890 ; (calendar-absolute-from-iso
15891 ; (list iso-week day year)))))
15892 (setq month (car iso-date)
15893 year (nth 2 iso-date)
15894 day (nth 1 iso-date)))
15895 (deltan
15896 (setq futurep nil)
15897 (unless deltadef
15898 (let ((now (decode-time (current-time))))
15899 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15900 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15901 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15902 ((equal deltaw "m") (setq month (+ month deltan)))
15903 ((equal deltaw "y") (setq year (+ year deltan)))))
15904 ((and wday (not (nth 3 tl)))
15905 ;; Weekday was given, but no day, so pick that day in the week
15906 ;; on or after the derived date.
15907 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15908 (unless (equal wday wday1)
15909 (setq day (+ day (% (- wday wday1 -7) 7))))))
15910 (if (and (boundp 'org-time-was-given)
15911 (nth 2 tl))
15912 (setq org-time-was-given t))
15913 (if (< year 100) (setq year (+ 2000 year)))
15914 ;; Check of the date is representable
15915 (if org-read-date-force-compatible-dates
15916 (progn
15917 (if (< year 1970)
15918 (setq year 1970 org-read-date-analyze-forced-year t))
15919 (if (> year 2037)
15920 (setq year 2037 org-read-date-analyze-forced-year t)))
15921 (condition-case nil
15922 (ignore (encode-time second minute hour day month year))
15923 (error
15924 (setq year (nth 5 org-defdecode))
15925 (setq org-read-date-analyze-forced-year t))))
15926 (setq org-read-date-analyze-futurep futurep)
15927 (list second minute hour day month year)))
15929 (defvar parse-time-weekdays)
15930 (defun org-read-date-get-relative (s today default)
15931 "Check string S for special relative date string.
15932 TODAY and DEFAULT are internal times, for today and for a default.
15933 Return shift list (N what def-flag)
15934 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15935 N is the number of WHATs to shift.
15936 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15937 the DEFAULT date rather than TODAY."
15938 (require 'parse-time)
15939 (when (and
15940 (string-match
15941 (concat
15942 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15943 "\\([0-9]+\\)?"
15944 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15945 "\\([ \t]\\|$\\)") s)
15946 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15947 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15948 (string-to-char (substring (match-string 1 s) -1))
15949 ?+))
15950 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15951 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15952 (what (if (match-end 3) (match-string 3 s) "d"))
15953 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15954 (date (if rel default today))
15955 (wday (nth 6 (decode-time date)))
15956 delta)
15957 (if wday1
15958 (progn
15959 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15960 (if (= dir ?-) (setq delta (- delta 7)))
15961 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15962 (list delta "d" rel))
15963 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15965 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15966 "Turn a user-specified date into the internal representation.
15967 The internal representation needed by the calendar is (month day year).
15968 This is a wrapper to handle the brain-dead convention in calendar that
15969 user function argument order change dependent on argument order."
15970 (if (boundp 'calendar-date-style)
15971 (cond
15972 ((eq calendar-date-style 'american)
15973 (list arg1 arg2 arg3))
15974 ((eq calendar-date-style 'european)
15975 (list arg2 arg1 arg3))
15976 ((eq calendar-date-style 'iso)
15977 (list arg2 arg3 arg1)))
15978 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15979 (if (org-bound-and-true-p european-calendar-style)
15980 (list arg2 arg1 arg3)
15981 (list arg1 arg2 arg3)))))
15983 (defun org-eval-in-calendar (form &optional keepdate)
15984 "Eval FORM in the calendar window and return to current window.
15985 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15986 otherwise stick to the current value of `org-ans2'."
15987 (let ((sf (selected-frame))
15988 (sw (selected-window)))
15989 (select-window (get-buffer-window "*Calendar*" t))
15990 (eval form)
15991 (when (and (not keepdate) (calendar-cursor-to-date))
15992 (let* ((date (calendar-cursor-to-date))
15993 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15994 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15995 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15996 (select-window sw)
15997 (org-select-frame-set-input-focus sf)))
15999 (defun org-calendar-select ()
16000 "Return to `org-read-date' with the date currently selected.
16001 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16002 (interactive)
16003 (when (calendar-cursor-to-date)
16004 (let* ((date (calendar-cursor-to-date))
16005 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16006 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16007 (if (active-minibuffer-window) (exit-minibuffer))))
16009 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16010 "Insert a date stamp for the date given by the internal TIME.
16011 WITH-HM means use the stamp format that includes the time of the day.
16012 INACTIVE means use square brackets instead of angular ones, so that the
16013 stamp will not contribute to the agenda.
16014 PRE and POST are optional strings to be inserted before and after the
16015 stamp.
16016 The command returns the inserted time stamp."
16017 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16018 stamp)
16019 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16020 (insert-before-markers (or pre ""))
16021 (when (listp extra)
16022 (setq extra (car extra))
16023 (if (and (stringp extra)
16024 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16025 (setq extra (format "-%02d:%02d"
16026 (string-to-number (match-string 1 extra))
16027 (string-to-number (match-string 2 extra))))
16028 (setq extra nil)))
16029 (when extra
16030 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16031 (insert-before-markers (setq stamp (format-time-string fmt time)))
16032 (insert-before-markers (or post ""))
16033 (setq org-last-inserted-timestamp stamp)))
16035 (defun org-toggle-time-stamp-overlays ()
16036 "Toggle the use of custom time stamp formats."
16037 (interactive)
16038 (setq org-display-custom-times (not org-display-custom-times))
16039 (unless org-display-custom-times
16040 (let ((p (point-min)) (bmp (buffer-modified-p)))
16041 (while (setq p (next-single-property-change p 'display))
16042 (if (and (get-text-property p 'display)
16043 (eq (get-text-property p 'face) 'org-date))
16044 (remove-text-properties
16045 p (setq p (next-single-property-change p 'display))
16046 '(display t))))
16047 (set-buffer-modified-p bmp)))
16048 (if (featurep 'xemacs)
16049 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16050 (org-restart-font-lock)
16051 (setq org-table-may-need-update t)
16052 (if org-display-custom-times
16053 (message "Time stamps are overlaid with custom format")
16054 (message "Time stamp overlays removed")))
16056 (defun org-display-custom-time (beg end)
16057 "Overlay modified time stamp format over timestamp between BEG and END."
16058 (let* ((ts (buffer-substring beg end))
16059 t1 w1 with-hm tf time str w2 (off 0))
16060 (save-match-data
16061 (setq t1 (org-parse-time-string ts t))
16062 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16063 (setq off (- (match-end 0) (match-beginning 0)))))
16064 (setq end (- end off))
16065 (setq w1 (- end beg)
16066 with-hm (and (nth 1 t1) (nth 2 t1))
16067 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16068 time (org-fix-decoded-time t1)
16069 str (org-add-props
16070 (format-time-string
16071 (substring tf 1 -1) (apply 'encode-time time))
16072 nil 'mouse-face 'highlight)
16073 w2 (length str))
16074 (if (not (= w2 w1))
16075 (add-text-properties (1+ beg) (+ 2 beg)
16076 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16077 (if (featurep 'xemacs)
16078 (progn
16079 (put-text-property beg end 'invisible t)
16080 (put-text-property beg end 'end-glyph (make-glyph str)))
16081 (put-text-property beg end 'display str))))
16083 (defun org-translate-time (string)
16084 "Translate all timestamps in STRING to custom format.
16085 But do this only if the variable `org-display-custom-times' is set."
16086 (when org-display-custom-times
16087 (save-match-data
16088 (let* ((start 0)
16089 (re org-ts-regexp-both)
16090 t1 with-hm inactive tf time str beg end)
16091 (while (setq start (string-match re string start))
16092 (setq beg (match-beginning 0)
16093 end (match-end 0)
16094 t1 (save-match-data
16095 (org-parse-time-string (substring string beg end) t))
16096 with-hm (and (nth 1 t1) (nth 2 t1))
16097 inactive (equal (substring string beg (1+ beg)) "[")
16098 tf (funcall (if with-hm 'cdr 'car)
16099 org-time-stamp-custom-formats)
16100 time (org-fix-decoded-time t1)
16101 str (format-time-string
16102 (concat
16103 (if inactive "[" "<") (substring tf 1 -1)
16104 (if inactive "]" ">"))
16105 (apply 'encode-time time))
16106 string (replace-match str t t string)
16107 start (+ start (length str)))))))
16108 string)
16110 (defun org-fix-decoded-time (time)
16111 "Set 0 instead of nil for the first 6 elements of time.
16112 Don't touch the rest."
16113 (let ((n 0))
16114 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16116 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16118 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16119 "Difference between TIMESTAMP-STRING and now in days.
16120 If SECONDS is non-nil, return the difference in seconds."
16121 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16122 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16123 (funcall fdiff (current-time)))))
16125 (defun org-deadline-close (timestamp-string &optional ndays)
16126 "Is the time in TIMESTAMP-STRING close to the current date?"
16127 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16128 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16129 (not (org-entry-is-done-p))))
16131 (defun org-get-wdays (ts)
16132 "Get the deadline lead time appropriate for timestring TS."
16133 (cond
16134 ((<= org-deadline-warning-days 0)
16135 ;; 0 or negative, enforce this value no matter what
16136 (- org-deadline-warning-days))
16137 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16138 ;; lead time is specified.
16139 (floor (* (string-to-number (match-string 1 ts))
16140 (cdr (assoc (match-string 2 ts)
16141 '(("d" . 1) ("w" . 7)
16142 ("m" . 30.4) ("y" . 365.25)))))))
16143 ;; go for the default.
16144 (t org-deadline-warning-days)))
16146 (defun org-calendar-select-mouse (ev)
16147 "Return to `org-read-date' with the date currently selected.
16148 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16149 (interactive "e")
16150 (mouse-set-point ev)
16151 (when (calendar-cursor-to-date)
16152 (let* ((date (calendar-cursor-to-date))
16153 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16154 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16155 (if (active-minibuffer-window) (exit-minibuffer))))
16157 (defun org-check-deadlines (ndays)
16158 "Check if there are any deadlines due or past due.
16159 A deadline is considered due if it happens within `org-deadline-warning-days'
16160 days from today's date. If the deadline appears in an entry marked DONE,
16161 it is not shown. The prefix arg NDAYS can be used to test that many
16162 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16163 (interactive "P")
16164 (let* ((org-warn-days
16165 (cond
16166 ((equal ndays '(4)) 100000)
16167 (ndays (prefix-numeric-value ndays))
16168 (t (abs org-deadline-warning-days))))
16169 (case-fold-search nil)
16170 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16171 (callback
16172 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16174 (message "%d deadlines past-due or due within %d days"
16175 (org-occur regexp nil callback)
16176 org-warn-days)))
16178 (defsubst org-re-timestamp (type)
16179 "Return a regexp for timestamp TYPE.
16180 Allowed values for TYPE are:
16182 all: all timestamps
16183 active: only active timestamps (<...>)
16184 inactive: only inactive timestamps ([...])
16185 scheduled: only scheduled timestamps
16186 deadline: only deadline timestamps
16188 When TYPE is nil, fall back on returning a regexp that matches
16189 both scheduled and deadline timestamps."
16190 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16191 ((eq type 'active) org-ts-regexp)
16192 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16193 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16194 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16195 ((eq type 'scheduled-or-deadline)
16196 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16198 (defun org-check-before-date (date)
16199 "Check if there are deadlines or scheduled entries before DATE."
16200 (interactive (list (org-read-date)))
16201 (let ((case-fold-search nil)
16202 (regexp (org-re-timestamp org-ts-type))
16203 (callback
16204 (lambda () (time-less-p
16205 (org-time-string-to-time (match-string 1))
16206 (org-time-string-to-time date)))))
16207 (message "%d entries before %s"
16208 (org-occur regexp nil callback) date)))
16210 (defun org-check-after-date (date)
16211 "Check if there are deadlines or scheduled entries after DATE."
16212 (interactive (list (org-read-date)))
16213 (let ((case-fold-search nil)
16214 (regexp (org-re-timestamp org-ts-type))
16215 (callback
16216 (lambda () (not
16217 (time-less-p
16218 (org-time-string-to-time (match-string 1))
16219 (org-time-string-to-time date))))))
16220 (message "%d entries after %s"
16221 (org-occur regexp nil callback) date)))
16223 (defun org-check-dates-range (start-date end-date)
16224 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16225 (interactive (list (org-read-date nil nil nil "Range starts")
16226 (org-read-date nil nil nil "Range end")))
16227 (let ((case-fold-search nil)
16228 (regexp (org-re-timestamp org-ts-type))
16229 (callback
16230 (lambda ()
16231 (let ((match (match-string 1)))
16232 (and
16233 (not (time-less-p
16234 (org-time-string-to-time match)
16235 (org-time-string-to-time start-date)))
16236 (time-less-p
16237 (org-time-string-to-time match)
16238 (org-time-string-to-time end-date)))))))
16239 (message "%d entries between %s and %s"
16240 (org-occur regexp nil callback) start-date end-date)))
16242 (defun org-evaluate-time-range (&optional to-buffer)
16243 "Evaluate a time range by computing the difference between start and end.
16244 Normally the result is just printed in the echo area, but with prefix arg
16245 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16246 If the time range is actually in a table, the result is inserted into the
16247 next column.
16248 For time difference computation, a year is assumed to be exactly 365
16249 days in order to avoid rounding problems."
16250 (interactive "P")
16252 (org-clock-update-time-maybe)
16253 (save-excursion
16254 (unless (org-at-date-range-p t)
16255 (goto-char (point-at-bol))
16256 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16257 (if (not (org-at-date-range-p t))
16258 (error "Not at a time-stamp range, and none found in current line")))
16259 (let* ((ts1 (match-string 1))
16260 (ts2 (match-string 2))
16261 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16262 (match-end (match-end 0))
16263 (time1 (org-time-string-to-time ts1))
16264 (time2 (org-time-string-to-time ts2))
16265 (t1 (org-float-time time1))
16266 (t2 (org-float-time time2))
16267 (diff (abs (- t2 t1)))
16268 (negative (< (- t2 t1) 0))
16269 ;; (ys (floor (* 365 24 60 60)))
16270 (ds (* 24 60 60))
16271 (hs (* 60 60))
16272 (fy "%dy %dd %02d:%02d")
16273 (fy1 "%dy %dd")
16274 (fd "%dd %02d:%02d")
16275 (fd1 "%dd")
16276 (fh "%02d:%02d")
16277 y d h m align)
16278 (if havetime
16279 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16281 d (floor (/ diff ds)) diff (mod diff ds)
16282 h (floor (/ diff hs)) diff (mod diff hs)
16283 m (floor (/ diff 60)))
16284 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16286 d (floor (+ (/ diff ds) 0.5))
16287 h 0 m 0))
16288 (if (not to-buffer)
16289 (message "%s" (org-make-tdiff-string y d h m))
16290 (if (org-at-table-p)
16291 (progn
16292 (goto-char match-end)
16293 (setq align t)
16294 (and (looking-at " *|") (goto-char (match-end 0))))
16295 (goto-char match-end))
16296 (if (looking-at
16297 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16298 (replace-match ""))
16299 (if negative (insert " -"))
16300 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16301 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16302 (insert " " (format fh h m))))
16303 (if align (org-table-align))
16304 (message "Time difference inserted")))))
16306 (defun org-make-tdiff-string (y d h m)
16307 (let ((fmt "")
16308 (l nil))
16309 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16310 l (push y l)))
16311 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16312 l (push d l)))
16313 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16314 l (push h l)))
16315 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16316 l (push m l)))
16317 (apply 'format fmt (nreverse l))))
16319 (defun org-time-string-to-time (s &optional buffer pos)
16320 "Convert a timestamp string into internal time."
16321 (condition-case errdata
16322 (apply 'encode-time (org-parse-time-string s))
16323 (error (error "Bad timestamp `%s'%s\nError was: %s"
16324 s (if (not (and buffer pos))
16326 (format " at %d in buffer `%s'" pos buffer))
16327 (cdr errdata)))))
16329 (defun org-time-string-to-seconds (s)
16330 "Convert a timestamp string to a number of seconds."
16331 (org-float-time (org-time-string-to-time s)))
16333 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16334 "Convert a time stamp to an absolute day number.
16335 If there is a specifier for a cyclic time stamp, get the closest date to
16336 DAYNR.
16337 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16338 The variable date is bound by the calendar when this is called."
16339 (cond
16340 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16341 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16342 daynr
16343 (+ daynr 1000)))
16344 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16345 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16346 (time-to-days (current-time))) (match-string 0 s)
16347 prefer show-all))
16348 (t (time-to-days
16349 (condition-case errdata
16350 (apply 'encode-time (org-parse-time-string s))
16351 (error (error "Bad timestamp `%s'%s\nError was: %s"
16352 s (if (not (and buffer pos))
16354 (format " at %d in buffer `%s'" pos buffer))
16355 (cdr errdata))))))))
16357 (defun org-days-to-iso-week (days)
16358 "Return the iso week number."
16359 (require 'cal-iso)
16360 (car (calendar-iso-from-absolute days)))
16362 (defun org-small-year-to-year (year)
16363 "Convert 2-digit years into 4-digit years.
16364 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16365 The year 2000 cannot be abbreviated. Any year larger than 99
16366 is returned unchanged."
16367 (if (< year 38)
16368 (setq year (+ 2000 year))
16369 (if (< year 100)
16370 (setq year (+ 1900 year))))
16371 year)
16373 (defun org-time-from-absolute (d)
16374 "Return the time corresponding to date D.
16375 D may be an absolute day number, or a calendar-type list (month day year)."
16376 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16377 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16379 (defun org-calendar-holiday ()
16380 "List of holidays, for Diary display in Org-mode."
16381 (require 'holidays)
16382 (let ((hl (funcall
16383 (if (fboundp 'calendar-check-holidays)
16384 'calendar-check-holidays 'check-calendar-holidays) date)))
16385 (if hl (mapconcat 'identity hl "; "))))
16387 (defun org-diary-sexp-entry (sexp entry date)
16388 "Process a SEXP diary ENTRY for DATE."
16389 (require 'diary-lib)
16390 (let ((result (if calendar-debug-sexp
16391 (let ((stack-trace-on-error t))
16392 (eval (car (read-from-string sexp))))
16393 (condition-case nil
16394 (eval (car (read-from-string sexp)))
16395 (error
16396 (beep)
16397 (message "Bad sexp at line %d in %s: %s"
16398 (org-current-line)
16399 (buffer-file-name) sexp)
16400 (sleep-for 2))))))
16401 (cond ((stringp result) (split-string result "; "))
16402 ((and (consp result)
16403 (not (consp (cdr result)))
16404 (stringp (cdr result))) (cdr result))
16405 ((and (consp result)
16406 (stringp (car result))) result)
16407 (result entry))))
16409 (defun org-diary-to-ical-string (frombuf)
16410 "Get iCalendar entries from diary entries in buffer FROMBUF.
16411 This uses the icalendar.el library."
16412 (let* ((tmpdir (if (featurep 'xemacs)
16413 (temp-directory)
16414 temporary-file-directory))
16415 (tmpfile (make-temp-name
16416 (expand-file-name "orgics" tmpdir)))
16417 buf rtn b e)
16418 (with-current-buffer frombuf
16419 (icalendar-export-region (point-min) (point-max) tmpfile)
16420 (setq buf (find-buffer-visiting tmpfile))
16421 (set-buffer buf)
16422 (goto-char (point-min))
16423 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16424 (setq b (match-beginning 0)))
16425 (goto-char (point-max))
16426 (if (re-search-backward "^END:VEVENT" nil t)
16427 (setq e (match-end 0)))
16428 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16429 (kill-buffer buf)
16430 (delete-file tmpfile)
16431 rtn))
16433 (defun org-closest-date (start current change prefer show-all)
16434 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16435 When PREFER is `past', return a date that is either CURRENT or past.
16436 When PREFER is `future', return a date that is either CURRENT or future.
16437 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16438 ;; Make the proper lists from the dates
16439 (catch 'exit
16440 (let ((a1 '(("h" . hour)
16441 ("d" . day)
16442 ("w" . week)
16443 ("m" . month)
16444 ("y" . year)))
16445 (shour (nth 2 (org-parse-time-string start)))
16446 dn dw sday cday n1 n2 n0
16447 d m y y1 y2 date1 date2 nmonths nm ny m2)
16449 (setq start (org-date-to-gregorian start)
16450 current (org-date-to-gregorian
16451 (if show-all
16452 current
16453 (time-to-days (current-time))))
16454 sday (calendar-absolute-from-gregorian start)
16455 cday (calendar-absolute-from-gregorian current))
16457 (if (<= cday sday) (throw 'exit sday))
16459 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16460 (setq dn (string-to-number (match-string 1 change))
16461 dw (cdr (assoc (match-string 2 change) a1)))
16462 (error "Invalid change specifier: %s" change))
16463 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16464 (cond
16465 ((eq dw 'hour)
16466 (let ((missing-hours
16467 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16468 dn)))
16469 (setq n1 (if (zerop missing-hours) cday
16470 (- cday (1+ (floor (/ missing-hours 24)))))
16471 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16472 ((eq dw 'day)
16473 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16474 n2 (+ n1 dn)))
16475 ((eq dw 'year)
16476 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16477 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16478 (setq date1 (list m d y1)
16479 n1 (calendar-absolute-from-gregorian date1)
16480 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16481 n2 (calendar-absolute-from-gregorian date2)))
16482 ((eq dw 'month)
16483 ;; approx number of month between the two dates
16484 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16485 ;; How often does dn fit in there?
16486 (setq d (nth 1 start) m (car start) y (nth 2 start)
16487 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16488 m (+ m nm)
16489 ny (floor (/ m 12))
16490 y (+ y ny)
16491 m (- m (* ny 12)))
16492 (while (> m 12) (setq m (- m 12) y (1+ y)))
16493 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16494 (setq m2 (+ m dn) y2 y)
16495 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16496 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16497 (while (<= n2 cday)
16498 (setq n1 n2 m m2 y y2)
16499 (setq m2 (+ m dn) y2 y)
16500 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16501 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16502 ;; Make sure n1 is the earlier date
16503 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16504 (if show-all
16505 (cond
16506 ((eq prefer 'past) (if (= cday n2) n2 n1))
16507 ((eq prefer 'future) (if (= cday n1) n1 n2))
16508 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16509 (cond
16510 ((eq prefer 'past) (if (= cday n2) n2 n1))
16511 ((eq prefer 'future) (if (= cday n1) n1 n2))
16512 (t (if (= cday n1) n1 n2)))))))
16514 (defun org-date-to-gregorian (date)
16515 "Turn any specification of DATE into a Gregorian date for the calendar."
16516 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16517 ((and (listp date) (= (length date) 3)) date)
16518 ((stringp date)
16519 (setq date (org-parse-time-string date))
16520 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16521 ((listp date)
16522 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16524 (defun org-parse-time-string (s &optional nodefault)
16525 "Parse the standard Org-mode time string.
16526 This should be a lot faster than the normal `parse-time-string'.
16527 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16528 hour and minute fields will be nil if not given."
16529 (if (string-match org-ts-regexp0 s)
16530 (list 0
16531 (if (or (match-beginning 8) (not nodefault))
16532 (string-to-number (or (match-string 8 s) "0")))
16533 (if (or (match-beginning 7) (not nodefault))
16534 (string-to-number (or (match-string 7 s) "0")))
16535 (string-to-number (match-string 4 s))
16536 (string-to-number (match-string 3 s))
16537 (string-to-number (match-string 2 s))
16538 nil nil nil)
16539 (error "Not a standard Org-mode time string: %s" s)))
16541 (defun org-timestamp-up (&optional arg)
16542 "Increase the date item at the cursor by one.
16543 If the cursor is on the year, change the year. If it is on the month,
16544 the day or the time, change that.
16545 With prefix ARG, change by that many units."
16546 (interactive "p")
16547 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16549 (defun org-timestamp-down (&optional arg)
16550 "Decrease the date item at the cursor by one.
16551 If the cursor is on the year, change the year. If it is on the month,
16552 the day or the time, change that.
16553 With prefix ARG, change by that many units."
16554 (interactive "p")
16555 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16557 (defun org-timestamp-up-day (&optional arg)
16558 "Increase the date in the time stamp by one day.
16559 With prefix ARG, change that many days."
16560 (interactive "p")
16561 (if (and (not (org-at-timestamp-p t))
16562 (org-at-heading-p))
16563 (org-todo 'up)
16564 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16566 (defun org-timestamp-down-day (&optional arg)
16567 "Decrease the date in the time stamp by one day.
16568 With prefix ARG, change that many days."
16569 (interactive "p")
16570 (if (and (not (org-at-timestamp-p t))
16571 (org-at-heading-p))
16572 (org-todo 'down)
16573 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16575 (defun org-at-timestamp-p (&optional inactive-ok)
16576 "Determine if the cursor is in or at a timestamp."
16577 (interactive)
16578 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16579 (pos (point))
16580 (ans (or (looking-at tsr)
16581 (save-excursion
16582 (skip-chars-backward "^[<\n\r\t")
16583 (if (> (point) (point-min)) (backward-char 1))
16584 (and (looking-at tsr)
16585 (> (- (match-end 0) pos) -1))))))
16586 (and ans
16587 (boundp 'org-ts-what)
16588 (setq org-ts-what
16589 (cond
16590 ((= pos (match-beginning 0)) 'bracket)
16591 ;; Point is considered to be "on the bracket" whether
16592 ;; it's really on it or right after it.
16593 ((= pos (1- (match-end 0))) 'bracket)
16594 ((= pos (match-end 0)) 'after)
16595 ((org-pos-in-match-range pos 2) 'year)
16596 ((org-pos-in-match-range pos 3) 'month)
16597 ((org-pos-in-match-range pos 7) 'hour)
16598 ((org-pos-in-match-range pos 8) 'minute)
16599 ((or (org-pos-in-match-range pos 4)
16600 (org-pos-in-match-range pos 5)) 'day)
16601 ((and (> pos (or (match-end 8) (match-end 5)))
16602 (< pos (match-end 0)))
16603 (- pos (or (match-end 8) (match-end 5))))
16604 (t 'day))))
16605 ans))
16607 (defun org-toggle-timestamp-type ()
16608 "Toggle the type (<active> or [inactive]) of a time stamp."
16609 (interactive)
16610 (when (org-at-timestamp-p t)
16611 (let ((beg (match-beginning 0)) (end (match-end 0))
16612 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16613 (save-excursion
16614 (goto-char beg)
16615 (while (re-search-forward "[][<>]" end t)
16616 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16617 t t)))
16618 (message "Timestamp is now %sactive"
16619 (if (equal (char-after beg) ?<) "" "in")))))
16621 (defvar org-clock-history) ; defined in org-clock.el
16622 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16623 (defun org-timestamp-change (n &optional what updown)
16624 "Change the date in the time stamp at point.
16625 The date will be changed by N times WHAT. WHAT can be `day', `month',
16626 `year', `minute', `second'. If WHAT is not given, the cursor position
16627 in the timestamp determines what will be changed."
16628 (let ((origin (point)) origin-cat
16629 with-hm inactive
16630 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16631 org-ts-what
16632 extra rem
16633 ts time time0 fixnext clrgx)
16634 (if (not (org-at-timestamp-p t))
16635 (error "Not at a timestamp"))
16636 (if (and (not what) (eq org-ts-what 'bracket))
16637 (org-toggle-timestamp-type)
16638 ;; Point isn't on brackets. Remember the part of the time-stamp
16639 ;; the point was in. Indeed, size of time-stamps may change,
16640 ;; but point must be kept in the same category nonetheless.
16641 (setq origin-cat org-ts-what)
16642 (if (and (not what) (not (eq org-ts-what 'day))
16643 org-display-custom-times
16644 (get-text-property (point) 'display)
16645 (not (get-text-property (1- (point)) 'display)))
16646 (setq org-ts-what 'day))
16647 (setq org-ts-what (or what org-ts-what)
16648 inactive (= (char-after (match-beginning 0)) ?\[)
16649 ts (match-string 0))
16650 (replace-match "")
16651 (if (string-match
16652 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16654 (setq extra (match-string 1 ts)))
16655 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16656 (setq with-hm t))
16657 (setq time0 (org-parse-time-string ts))
16658 (when (and updown
16659 (eq org-ts-what 'minute)
16660 (not current-prefix-arg))
16661 ;; This looks like s-up and s-down. Change by one rounding step.
16662 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16663 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16664 (setcar (cdr time0) (+ (nth 1 time0)
16665 (if (> n 0) (- rem) (- dm rem))))))
16666 (setq time
16667 (encode-time (or (car time0) 0)
16668 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16669 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16670 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16671 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16672 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16673 (nthcdr 6 time0)))
16674 (when (and (member org-ts-what '(hour minute))
16675 extra
16676 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16677 (setq extra (org-modify-ts-extra
16678 extra
16679 (if (eq org-ts-what 'hour) 2 5)
16680 n dm)))
16681 (when (integerp org-ts-what)
16682 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16683 (if (eq what 'calendar)
16684 (let ((cal-date (org-get-date-from-calendar)))
16685 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16686 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16687 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16688 (setcar time0 (or (car time0) 0))
16689 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16690 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16691 (setq time (apply 'encode-time time0))))
16692 ;; Insert the new time-stamp, and ensure point stays in the same
16693 ;; category as before (i.e. not after the last position in that
16694 ;; category).
16695 (let ((pos (point)))
16696 ;; Stay before inserted string. `save-excursion' is of no use.
16697 (setq org-last-changed-timestamp
16698 (org-insert-time-stamp time with-hm inactive nil nil extra))
16699 (goto-char pos))
16700 (save-match-data
16701 (looking-at org-ts-regexp3)
16702 (goto-char (cond
16703 ;; `day' category ends before `hour' if any, or at
16704 ;; the end of the day name.
16705 ((eq origin-cat 'day)
16706 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16707 ((eq origin-cat 'hour) (min (match-end 7) origin))
16708 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16709 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16710 ;; `year' and `month' have both fixed size: point
16711 ;; couldn't have moved into another part.
16712 (t origin))))
16713 ;; Update clock if on a CLOCK line.
16714 (org-clock-update-time-maybe)
16715 ;; Maybe adjust the closest clock in `org-clock-history'
16716 (when org-clock-adjust-closest
16717 (if (not (and (org-at-clock-log-p)
16718 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16719 org-clock-history))))))
16720 (message "No clock to adjust")
16721 (cond ((save-excursion ; fix previous clock?
16722 (re-search-backward org-ts-regexp0 nil t)
16723 (org-looking-back (concat org-clock-string " \\[")))
16724 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16725 ((save-excursion ; fix next clock?
16726 (re-search-backward org-ts-regexp0 nil t)
16727 (looking-at (concat org-ts-regexp0 "\\] =>")))
16728 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16729 (save-window-excursion
16730 ;; Find closest clock to point, adjust the previous/next one in history
16731 (let* ((p (save-excursion (org-back-to-heading t)))
16732 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16733 (clfixnth
16734 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16735 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16736 (if (not clfixpos)
16737 (message "No clock to adjust")
16738 (save-excursion
16739 (org-goto-marker-or-bmk clfixpos)
16740 (org-show-subtree)
16741 (when (re-search-forward clrgx nil t)
16742 (goto-char (match-beginning 1))
16743 (let (org-clock-adjust-closest)
16744 (org-timestamp-change n org-ts-what updown))
16745 (message "Clock adjusted in %s for heading: %s"
16746 (file-name-nondirectory (buffer-file-name))
16747 (org-get-heading t t)))))))))
16748 ;; Try to recenter the calendar window, if any.
16749 (if (and org-calendar-follow-timestamp-change
16750 (get-buffer-window "*Calendar*" t)
16751 (memq org-ts-what '(day month year)))
16752 (org-recenter-calendar (time-to-days time))))))
16754 (defun org-modify-ts-extra (s pos n dm)
16755 "Change the different parts of the lead-time and repeat fields in timestamp."
16756 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16757 ng h m new rem)
16758 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16759 (cond
16760 ((or (org-pos-in-match-range pos 2)
16761 (org-pos-in-match-range pos 3))
16762 (setq m (string-to-number (match-string 3 s))
16763 h (string-to-number (match-string 2 s)))
16764 (if (org-pos-in-match-range pos 2)
16765 (setq h (+ h n))
16766 (setq n (* dm (org-no-warnings (signum n))))
16767 (when (not (= 0 (setq rem (% m dm))))
16768 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16769 (setq m (+ m n)))
16770 (if (< m 0) (setq m (+ m 60) h (1- h)))
16771 (if (> m 59) (setq m (- m 60) h (1+ h)))
16772 (setq h (min 24 (max 0 h)))
16773 (setq ng 1 new (format "-%02d:%02d" h m)))
16774 ((org-pos-in-match-range pos 6)
16775 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16776 ((org-pos-in-match-range pos 5)
16777 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16779 ((org-pos-in-match-range pos 9)
16780 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16781 ((org-pos-in-match-range pos 8)
16782 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16784 (when ng
16785 (setq s (concat
16786 (substring s 0 (match-beginning ng))
16788 (substring s (match-end ng))))))
16791 (defun org-recenter-calendar (date)
16792 "If the calendar is visible, recenter it to DATE."
16793 (let ((cwin (get-buffer-window "*Calendar*" t)))
16794 (when cwin
16795 (let ((calendar-move-hook nil))
16796 (with-selected-window cwin
16797 (calendar-goto-date (if (listp date) date
16798 (calendar-gregorian-from-absolute date))))))))
16800 (defun org-goto-calendar (&optional arg)
16801 "Go to the Emacs calendar at the current date.
16802 If there is a time stamp in the current line, go to that date.
16803 A prefix ARG can be used to force the current date."
16804 (interactive "P")
16805 (let ((tsr org-ts-regexp) diff
16806 (calendar-move-hook nil)
16807 (calendar-view-holidays-initially-flag nil)
16808 (calendar-view-diary-initially-flag nil))
16809 (if (or (org-at-timestamp-p)
16810 (save-excursion
16811 (beginning-of-line 1)
16812 (looking-at (concat ".*" tsr))))
16813 (let ((d1 (time-to-days (current-time)))
16814 (d2 (time-to-days
16815 (org-time-string-to-time (match-string 1)))))
16816 (setq diff (- d2 d1))))
16817 (calendar)
16818 (calendar-goto-today)
16819 (if (and diff (not arg)) (calendar-forward-day diff))))
16821 (defun org-get-date-from-calendar ()
16822 "Return a list (month day year) of date at point in calendar."
16823 (with-current-buffer "*Calendar*"
16824 (save-match-data
16825 (calendar-cursor-to-date))))
16827 (defun org-date-from-calendar ()
16828 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16829 If there is already a time stamp at the cursor position, update it."
16830 (interactive)
16831 (if (org-at-timestamp-p t)
16832 (org-timestamp-change 0 'calendar)
16833 (let ((cal-date (org-get-date-from-calendar)))
16834 (org-insert-time-stamp
16835 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16837 (defun org-minutes-to-clocksum-string (m)
16838 "Format number of minutes as a clocksum string.
16839 The format is determined by `org-time-clocksum-format',
16840 `org-time-clocksum-use-fractional' and
16841 `org-time-clocksum-fractional-format'."
16842 (let ((clocksum "") fmt n)
16843 ;; fractional format
16844 (if org-time-clocksum-use-fractional
16845 (cond
16846 ;; single format string
16847 ((stringp org-time-clocksum-fractional-format)
16848 (format org-time-clocksum-fractional-format (/ m 60.0)))
16849 ;; choice of fractional formats for different time units
16850 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
16851 (> (/ (truncate m) (* 365 24 60)) 0))
16852 (format fmt (/ m (* 365 24 60.0))))
16853 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
16854 (> (/ (truncate m) (* 30 24 60)) 0))
16855 (format fmt (/ m (* 30 24 60.0))))
16856 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16857 (> (/ (truncate m) (* 7 24 60)) 0))
16858 (format fmt (/ m (* 7 24 60.0))))
16859 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
16860 (> (/ (truncate m) (* 24 60)) 0))
16861 (format fmt (/ m (* 24 60.0))))
16862 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16863 (> (/ (truncate m) 60) 0))
16864 (format fmt (/ m 60.0)))
16865 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
16866 (format fmt m))
16867 ;; fall back to smallest time unit with a format
16868 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16869 (format fmt (/ m 60.0)))
16870 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
16871 (format fmt (/ m (* 24 60.0))))
16872 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16873 (format fmt (/ m (* 7 24 60.0))))
16874 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
16875 (format fmt (/ m (* 30 24 60.0))))
16876 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
16877 (format fmt (/ m (* 365 24 60.0)))))
16878 ;; standard (non-fractional) format, with single format string
16879 (if (stringp org-time-clocksum-format)
16880 (format org-time-clocksum-format (setq n (/ m 60)) (- m (* 60 n)))
16881 ;; separate formats components
16882 (and (setq fmt (plist-get org-time-clocksum-format :years))
16883 (or (> (setq n (/ (truncate m) (* 365 24 60))) 0)
16884 (plist-get org-time-clocksum-format :require-years))
16885 (setq clocksum (concat clocksum (format fmt n))
16886 m (- m (* n 365 24 60))))
16887 (and (setq fmt (plist-get org-time-clocksum-format :months))
16888 (or (> (setq n (/ (truncate m) (* 30 24 60))) 0)
16889 (plist-get org-time-clocksum-format :require-months))
16890 (setq clocksum (concat clocksum (format fmt n))
16891 m (- m (* n 30 24 60))))
16892 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
16893 (or (> (setq n (/ (truncate m) (* 7 24 60))) 0)
16894 (plist-get org-time-clocksum-format :require-weeks))
16895 (setq clocksum (concat clocksum (format fmt n))
16896 m (- m (* n 7 24 60))))
16897 (and (setq fmt (plist-get org-time-clocksum-format :days))
16898 (or (> (setq n (/ (truncate m) (* 24 60))) 0)
16899 (plist-get org-time-clocksum-format :require-days))
16900 (setq clocksum (concat clocksum (format fmt n))
16901 m (- m (* n 24 60))))
16902 (and (setq fmt (plist-get org-time-clocksum-format :hours))
16903 (or (> (setq n (/ (truncate m) 60)) 0)
16904 (plist-get org-time-clocksum-format :require-hours))
16905 (setq clocksum (concat clocksum (format fmt n))
16906 m (- m (* n 60))))
16907 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
16908 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
16909 (setq clocksum (concat clocksum (format fmt m))))
16910 ;; return formatted time duration
16911 clocksum))))
16913 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
16914 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
16915 "Org mode version 8.0")
16917 (defun org-hours-to-clocksum-string (n)
16918 (org-minutes-to-clocksum-string (* n 60)))
16920 (defun org-hh:mm-string-to-minutes (s)
16921 "Convert a string H:MM to a number of minutes.
16922 If the string is just a number, interpret it as minutes.
16923 In fact, the first hh:mm or number in the string will be taken,
16924 there can be extra stuff in the string.
16925 If no number is found, the return value is 0."
16926 (cond
16927 ((integerp s) s)
16928 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16929 (+ (* (string-to-number (match-string 1 s)) 60)
16930 (string-to-number (match-string 2 s))))
16931 ((string-match "\\([0-9]+\\)" s)
16932 (string-to-number (match-string 1 s)))
16933 (t 0)))
16935 (defcustom org-effort-durations
16936 `(("h" . 60)
16937 ("d" . ,(* 60 8))
16938 ("w" . ,(* 60 8 5))
16939 ("m" . ,(* 60 8 5 4))
16940 ("y" . ,(* 60 8 5 40)))
16941 "Conversion factor to minutes for an effort modifier.
16943 Each entry has the form (MODIFIER . MINUTES).
16945 In an effort string, a number followed by MODIFIER is multiplied
16946 by the specified number of MINUTES to obtain an effort in
16947 minutes.
16949 For example, if the value of this variable is ((\"hours\" . 60)), then an
16950 effort string \"2hours\" is equivalent to 120 minutes."
16951 :group 'org-agenda
16952 :version "24.1"
16953 :type '(alist :key-type (string :tag "Modifier")
16954 :value-type (number :tag "Minutes")))
16956 (defcustom org-image-actual-width t
16957 "Should we use the actual width of images when inlining them?
16959 When set to `t', always use the image width.
16961 When set to a number, use imagemagick (when available) to set
16962 the image's width to this value.
16964 When set to a number in a list, try to get the width from the
16965 #+ATTR.* keyword if it matches a width specification like
16966 width=\"[0-9]+\", and fall back on that number if none is found.
16968 When set to nil, try to get the width from an #+ATTR.* keyword
16969 and fall back on the original width if none is found.
16971 This requires Emacs >= 24.1, build with imagemagick support."
16972 :group 'org-appearance
16973 :version "24.3"
16974 :type '(choice
16975 (const :tag "Use the image width" t)
16976 (integer :tag "Use a number of pixels")
16977 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16978 (const :tag "Use #+ATTR* or don't resize" nil)))
16980 (defun org-duration-string-to-minutes (s &optional output-to-string)
16981 "Convert a duration string S to minutes.
16983 A bare number is interpreted as minutes, modifiers can be set by
16984 customizing `org-effort-durations' (which see).
16986 Entries containing a colon are interpreted as H:MM by
16987 `org-hh:mm-string-to-minutes'."
16988 (let ((result 0)
16989 (re (concat "\\([0-9.]+\\) *\\("
16990 (regexp-opt (mapcar 'car org-effort-durations))
16991 "\\)")))
16992 (while (string-match re s)
16993 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16994 (string-to-number (match-string 1 s))))
16995 (setq s (replace-match "" nil t s)))
16996 (setq result (floor result))
16997 (incf result (org-hh:mm-string-to-minutes s))
16998 (if output-to-string (number-to-string result) result)))
17000 ;;;; Files
17002 (defun org-save-all-org-buffers ()
17003 "Save all Org-mode buffers without user confirmation."
17004 (interactive)
17005 (message "Saving all Org-mode buffers...")
17006 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17007 (when (featurep 'org-id) (org-id-locations-save))
17008 (message "Saving all Org-mode buffers... done"))
17010 (defun org-revert-all-org-buffers ()
17011 "Revert all Org-mode buffers.
17012 Prompt for confirmation when there are unsaved changes.
17013 Be sure you know what you are doing before letting this function
17014 overwrite your changes.
17016 This function is useful in a setup where one tracks org files
17017 with a version control system, to revert on one machine after pulling
17018 changes from another. I believe the procedure must be like this:
17020 1. M-x org-save-all-org-buffers
17021 2. Pull changes from the other machine, resolve conflicts
17022 3. M-x org-revert-all-org-buffers"
17023 (interactive)
17024 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17025 (error "Abort"))
17026 (save-excursion
17027 (save-window-excursion
17028 (mapc
17029 (lambda (b)
17030 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17031 (with-current-buffer b buffer-file-name))
17032 (org-pop-to-buffer-same-window b)
17033 (revert-buffer t 'no-confirm)))
17034 (buffer-list))
17035 (when (and (featurep 'org-id) org-id-track-globally)
17036 (org-id-locations-load)))))
17038 ;;;; Agenda files
17040 ;;;###autoload
17041 (defun org-switchb (&optional arg)
17042 "Switch between Org buffers.
17043 With one prefix argument, restrict available buffers to files.
17044 With two prefix arguments, restrict available buffers to agenda files.
17046 Defaults to `iswitchb' for buffer name completion.
17047 Set `org-completion-use-ido' to make it use ido instead."
17048 (interactive "P")
17049 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17050 ((equal arg '(16)) (org-buffer-list 'agenda))
17051 (t (org-buffer-list))))
17052 (org-completion-use-iswitchb org-completion-use-iswitchb)
17053 (org-completion-use-ido org-completion-use-ido))
17054 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17055 (setq org-completion-use-iswitchb t))
17056 (org-pop-to-buffer-same-window
17057 (org-icompleting-read "Org buffer: "
17058 (mapcar 'list (mapcar 'buffer-name blist))
17059 nil t))))
17061 ;;; Define some older names previously used for this functionality
17062 ;;;###autoload
17063 (defalias 'org-ido-switchb 'org-switchb)
17064 ;;;###autoload
17065 (defalias 'org-iswitchb 'org-switchb)
17067 (defun org-buffer-list (&optional predicate exclude-tmp)
17068 "Return a list of Org buffers.
17069 PREDICATE can be `export', `files' or `agenda'.
17071 export restrict the list to Export buffers.
17072 files restrict the list to buffers visiting Org files.
17073 agenda restrict the list to buffers visiting agenda files.
17075 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17076 (let* ((bfn nil)
17077 (agenda-files (and (eq predicate 'agenda)
17078 (mapcar 'file-truename (org-agenda-files t))))
17079 (filter
17080 (cond
17081 ((eq predicate 'files)
17082 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17083 ((eq predicate 'export)
17084 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17085 ((eq predicate 'agenda)
17086 (lambda (b)
17087 (with-current-buffer b
17088 (and (derived-mode-p 'org-mode)
17089 (setq bfn (buffer-file-name b))
17090 (member (file-truename bfn) agenda-files)))))
17091 (t (lambda (b) (with-current-buffer b
17092 (or (derived-mode-p 'org-mode)
17093 (string-match "\*Org .*Export"
17094 (buffer-name b)))))))))
17095 (delq nil
17096 (mapcar
17097 (lambda(b)
17098 (if (and (funcall filter b)
17099 (or (not exclude-tmp)
17100 (not (string-match "tmp" (buffer-name b)))))
17102 nil))
17103 (buffer-list)))))
17105 (defun org-agenda-files (&optional unrestricted archives)
17106 "Get the list of agenda files.
17107 Optional UNRESTRICTED means return the full list even if a restriction
17108 is currently in place.
17109 When ARCHIVES is t, include all archive files that are really being
17110 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17111 `org-agenda-archives-mode' is t."
17112 (let ((files
17113 (cond
17114 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17115 ((stringp org-agenda-files) (org-read-agenda-file-list))
17116 ((listp org-agenda-files) org-agenda-files)
17117 (t (error "Invalid value of `org-agenda-files'")))))
17118 (setq files (apply 'append
17119 (mapcar (lambda (f)
17120 (if (file-directory-p f)
17121 (directory-files
17122 f t org-agenda-file-regexp)
17123 (list f)))
17124 files)))
17125 (when org-agenda-skip-unavailable-files
17126 (setq files (delq nil
17127 (mapcar (function
17128 (lambda (file)
17129 (and (file-readable-p file) file)))
17130 files))))
17131 (when (or (eq archives t)
17132 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17133 (setq files (org-add-archive-files files)))
17134 files))
17136 (defun org-agenda-file-p (&optional file)
17137 "Return non-nil, if FILE is an agenda file.
17138 If FILE is omitted, use the file associated with the current
17139 buffer."
17140 (member (or file (buffer-file-name))
17141 (org-agenda-files t)))
17143 (defun org-edit-agenda-file-list ()
17144 "Edit the list of agenda files.
17145 Depending on setup, this either uses customize to edit the variable
17146 `org-agenda-files', or it visits the file that is holding the list. In the
17147 latter case, the buffer is set up in a way that saving it automatically kills
17148 the buffer and restores the previous window configuration."
17149 (interactive)
17150 (if (stringp org-agenda-files)
17151 (let ((cw (current-window-configuration)))
17152 (find-file org-agenda-files)
17153 (org-set-local 'org-window-configuration cw)
17154 (org-add-hook 'after-save-hook
17155 (lambda ()
17156 (set-window-configuration
17157 (prog1 org-window-configuration
17158 (kill-buffer (current-buffer))))
17159 (org-install-agenda-files-menu)
17160 (message "New agenda file list installed"))
17161 nil 'local)
17162 (message "%s" (substitute-command-keys
17163 "Edit list and finish with \\[save-buffer]")))
17164 (customize-variable 'org-agenda-files)))
17166 (defun org-store-new-agenda-file-list (list)
17167 "Set new value for the agenda file list and save it correctly."
17168 (if (stringp org-agenda-files)
17169 (let ((fe (org-read-agenda-file-list t)) b u)
17170 (while (setq b (find-buffer-visiting org-agenda-files))
17171 (kill-buffer b))
17172 (with-temp-file org-agenda-files
17173 (insert
17174 (mapconcat
17175 (lambda (f) ;; Keep un-expanded entries.
17176 (if (setq u (assoc f fe))
17177 (cdr u)
17179 list "\n")
17180 "\n")))
17181 (let ((org-mode-hook nil) (org-inhibit-startup t)
17182 (org-insert-mode-line-in-empty-file nil))
17183 (setq org-agenda-files list)
17184 (customize-save-variable 'org-agenda-files org-agenda-files))))
17186 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17187 "Read the list of agenda files from a file.
17188 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17189 filenames, used by `org-store-new-agenda-file-list' to write back
17190 un-expanded file names."
17191 (when (file-directory-p org-agenda-files)
17192 (error "`org-agenda-files' cannot be a single directory"))
17193 (when (stringp org-agenda-files)
17194 (with-temp-buffer
17195 (insert-file-contents org-agenda-files)
17196 (mapcar
17197 (lambda (f)
17198 (let ((e (expand-file-name (substitute-in-file-name f)
17199 org-directory)))
17200 (if pair-with-expansion
17201 (cons e f)
17202 e)))
17203 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17205 ;;;###autoload
17206 (defun org-cycle-agenda-files ()
17207 "Cycle through the files in `org-agenda-files'.
17208 If the current buffer visits an agenda file, find the next one in the list.
17209 If the current buffer does not, find the first agenda file."
17210 (interactive)
17211 (let* ((fs (org-agenda-files t))
17212 (files (append fs (list (car fs))))
17213 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17214 file)
17215 (unless files (error "No agenda files"))
17216 (catch 'exit
17217 (while (setq file (pop files))
17218 (if (equal (file-truename file) tcf)
17219 (when (car files)
17220 (find-file (car files))
17221 (throw 'exit t))))
17222 (find-file (car fs)))
17223 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17225 (defun org-agenda-file-to-front (&optional to-end)
17226 "Move/add the current file to the top of the agenda file list.
17227 If the file is not present in the list, it is added to the front. If it is
17228 present, it is moved there. With optional argument TO-END, add/move to the
17229 end of the list."
17230 (interactive "P")
17231 (let ((org-agenda-skip-unavailable-files nil)
17232 (file-alist (mapcar (lambda (x)
17233 (cons (file-truename x) x))
17234 (org-agenda-files t)))
17235 (ctf (file-truename
17236 (or buffer-file-name
17237 (error "Please save the current buffer to a file"))))
17238 x had)
17239 (setq x (assoc ctf file-alist) had x)
17241 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17242 (if to-end
17243 (setq file-alist (append (delq x file-alist) (list x)))
17244 (setq file-alist (cons x (delq x file-alist))))
17245 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17246 (org-install-agenda-files-menu)
17247 (message "File %s to %s of agenda file list"
17248 (if had "moved" "added") (if to-end "end" "front"))))
17250 (defun org-remove-file (&optional file)
17251 "Remove current file from the list of files in variable `org-agenda-files'.
17252 These are the files which are being checked for agenda entries.
17253 Optional argument FILE means use this file instead of the current."
17254 (interactive)
17255 (let* ((org-agenda-skip-unavailable-files nil)
17256 (file (or file buffer-file-name
17257 (error "Current buffer does not visit a file")))
17258 (true-file (file-truename file))
17259 (afile (abbreviate-file-name file))
17260 (files (delq nil (mapcar
17261 (lambda (x)
17262 (if (equal true-file
17263 (file-truename x))
17264 nil x))
17265 (org-agenda-files t)))))
17266 (if (not (= (length files) (length (org-agenda-files t))))
17267 (progn
17268 (org-store-new-agenda-file-list files)
17269 (org-install-agenda-files-menu)
17270 (message "Removed file: %s" afile))
17271 (message "File was not in list: %s (not removed)" afile))))
17273 (defun org-file-menu-entry (file)
17274 (vector file (list 'find-file file) t))
17276 (defun org-check-agenda-file (file)
17277 "Make sure FILE exists. If not, ask user what to do."
17278 (when (not (file-exists-p file))
17279 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17280 (abbreviate-file-name file))
17281 (let ((r (downcase (read-char-exclusive))))
17282 (cond
17283 ((equal r ?r)
17284 (org-remove-file file)
17285 (throw 'nextfile t))
17286 (t (error "Abort"))))))
17288 (defun org-get-agenda-file-buffer (file)
17289 "Get a buffer visiting FILE. If the buffer needs to be created, add
17290 it to the list of buffers which might be released later."
17291 (let ((buf (org-find-base-buffer-visiting file)))
17292 (if buf
17293 buf ; just return it
17294 ;; Make a new buffer and remember it
17295 (setq buf (find-file-noselect file))
17296 (if buf (push buf org-agenda-new-buffers))
17297 buf)))
17299 (defun org-release-buffers (blist)
17300 "Release all buffers in list, asking the user for confirmation when needed.
17301 When a buffer is unmodified, it is just killed. When modified, it is saved
17302 \(if the user agrees) and then killed."
17303 (let (buf file)
17304 (while (setq buf (pop blist))
17305 (setq file (buffer-file-name buf))
17306 (when (and (buffer-modified-p buf)
17307 file
17308 (y-or-n-p (format "Save file %s? " file)))
17309 (with-current-buffer buf (save-buffer)))
17310 (kill-buffer buf))))
17312 (defun org-agenda-prepare-buffers (files)
17313 "Create buffers for all agenda files, protect archived trees and comments."
17314 (interactive)
17315 (let ((pa '(:org-archived t))
17316 (pc '(:org-comment t))
17317 (pall '(:org-archived t :org-comment t))
17318 (inhibit-read-only t)
17319 (rea (concat ":" org-archive-tag ":"))
17320 bmp file re)
17321 (save-excursion
17322 (save-restriction
17323 (while (setq file (pop files))
17324 (catch 'nextfile
17325 (if (bufferp file)
17326 (set-buffer file)
17327 (org-check-agenda-file file)
17328 (set-buffer (org-get-agenda-file-buffer file)))
17329 (widen)
17330 (setq bmp (buffer-modified-p))
17331 (org-refresh-category-properties)
17332 (setq org-todo-keywords-for-agenda
17333 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17334 (setq org-done-keywords-for-agenda
17335 (append org-done-keywords-for-agenda org-done-keywords))
17336 (setq org-todo-keyword-alist-for-agenda
17337 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17338 (setq org-drawers-for-agenda
17339 (append org-drawers-for-agenda org-drawers))
17340 (setq org-tag-alist-for-agenda
17341 (append org-tag-alist-for-agenda org-tag-alist))
17343 (save-excursion
17344 (remove-text-properties (point-min) (point-max) pall)
17345 (when org-agenda-skip-archived-trees
17346 (goto-char (point-min))
17347 (while (re-search-forward rea nil t)
17348 (if (org-at-heading-p t)
17349 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17350 (goto-char (point-min))
17351 (setq re (format org-heading-keyword-regexp-format
17352 org-comment-string))
17353 (while (re-search-forward re nil t)
17354 (add-text-properties
17355 (match-beginning 0) (org-end-of-subtree t) pc)))
17356 (set-buffer-modified-p bmp)))))
17357 (setq org-todo-keywords-for-agenda
17358 (org-uniquify org-todo-keywords-for-agenda))
17359 (setq org-todo-keyword-alist-for-agenda
17360 (org-uniquify org-todo-keyword-alist-for-agenda)
17361 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17363 ;;;; Embedded LaTeX
17365 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17366 "Keymap for the minor `org-cdlatex-mode'.")
17368 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17369 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17370 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17371 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17372 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17374 (defvar org-cdlatex-texmathp-advice-is-done nil
17375 "Flag remembering if we have applied the advice to texmathp already.")
17377 (define-minor-mode org-cdlatex-mode
17378 "Toggle the minor `org-cdlatex-mode'.
17379 This mode supports entering LaTeX environment and math in LaTeX fragments
17380 in Org-mode.
17381 \\{org-cdlatex-mode-map}"
17382 nil " OCDL" nil
17383 (when org-cdlatex-mode
17384 (require 'cdlatex)
17385 (run-hooks 'cdlatex-mode-hook)
17386 (cdlatex-compute-tables))
17387 (unless org-cdlatex-texmathp-advice-is-done
17388 (setq org-cdlatex-texmathp-advice-is-done t)
17389 (defadvice texmathp (around org-math-always-on activate)
17390 "Always return t in org-mode buffers.
17391 This is because we want to insert math symbols without dollars even outside
17392 the LaTeX math segments. If Orgmode thinks that point is actually inside
17393 an embedded LaTeX fragment, let texmathp do its job.
17394 \\[org-cdlatex-mode-map]"
17395 (interactive)
17396 (let (p)
17397 (cond
17398 ((not (derived-mode-p 'org-mode)) ad-do-it)
17399 ((eq this-command 'cdlatex-math-symbol)
17400 (setq ad-return-value t
17401 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17403 (let ((p (org-inside-LaTeX-fragment-p)))
17404 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17405 (setq ad-return-value t
17406 texmathp-why '("Org-mode embedded math" . 0))
17407 (if p ad-do-it)))))))))
17409 (defun turn-on-org-cdlatex ()
17410 "Unconditionally turn on `org-cdlatex-mode'."
17411 (org-cdlatex-mode 1))
17413 (defun org-inside-LaTeX-fragment-p ()
17414 "Test if point is inside a LaTeX fragment.
17415 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17416 sequence appearing also before point.
17417 Even though the matchers for math are configurable, this function assumes
17418 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17419 delimiters are skipped when they have been removed by customization.
17420 The return value is nil, or a cons cell with the delimiter and the
17421 position of this delimiter.
17423 This function does a reasonably good job, but can locally be fooled by
17424 for example currency specifications. For example it will assume being in
17425 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17426 fragments that are properly closed, but during editing, we have to live
17427 with the uncertainty caused by missing closing delimiters. This function
17428 looks only before point, not after."
17429 (catch 'exit
17430 (let ((pos (point))
17431 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17432 (lim (progn
17433 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17434 (point)))
17435 dd-on str (start 0) m re)
17436 (goto-char pos)
17437 (when dodollar
17438 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17439 re (nth 1 (assoc "$" org-latex-regexps)))
17440 (while (string-match re str start)
17441 (cond
17442 ((= (match-end 0) (length str))
17443 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17444 ((= (match-end 0) (- (length str) 5))
17445 (throw 'exit nil))
17446 (t (setq start (match-end 0))))))
17447 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17448 (goto-char pos)
17449 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17450 (and (match-beginning 2) (throw 'exit nil))
17451 ;; count $$
17452 (while (re-search-backward "\\$\\$" lim t)
17453 (setq dd-on (not dd-on)))
17454 (goto-char pos)
17455 (if dd-on (cons "$$" m))))))
17457 (defun org-inside-latex-macro-p ()
17458 "Is point inside a LaTeX macro or its arguments?"
17459 (save-match-data
17460 (org-in-regexp
17461 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17463 (defun org-try-cdlatex-tab ()
17464 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17465 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17466 - inside a LaTeX fragment, or
17467 - after the first word in a line, where an abbreviation expansion could
17468 insert a LaTeX environment."
17469 (when org-cdlatex-mode
17470 (cond
17471 ;; Before any word on the line: No expansion possible.
17472 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17473 ;; Just after first word on the line: Expand it. Make sure it
17474 ;; cannot happen on headlines, though.
17475 ((save-excursion
17476 (skip-chars-backward "a-zA-Z0-9*")
17477 (skip-chars-backward " \t")
17478 (and (bolp) (not (org-at-heading-p))))
17479 (cdlatex-tab) t)
17480 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17482 (defun org-cdlatex-underscore-caret (&optional arg)
17483 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17484 Revert to the normal definition outside of these fragments."
17485 (interactive "P")
17486 (if (org-inside-LaTeX-fragment-p)
17487 (call-interactively 'cdlatex-sub-superscript)
17488 (let (org-cdlatex-mode)
17489 (call-interactively (key-binding (vector last-input-event))))))
17491 (defun org-cdlatex-math-modify (&optional arg)
17492 "Execute `cdlatex-math-modify' in LaTeX fragments.
17493 Revert to the normal definition outside of these fragments."
17494 (interactive "P")
17495 (if (org-inside-LaTeX-fragment-p)
17496 (call-interactively 'cdlatex-math-modify)
17497 (let (org-cdlatex-mode)
17498 (call-interactively (key-binding (vector last-input-event))))))
17500 (defvar org-latex-fragment-image-overlays nil
17501 "List of overlays carrying the images of latex fragments.")
17502 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17504 (defun org-remove-latex-fragment-image-overlays ()
17505 "Remove all overlays with LaTeX fragment images in current buffer."
17506 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17507 (setq org-latex-fragment-image-overlays nil))
17509 (defun org-preview-latex-fragment (&optional subtree)
17510 "Preview the LaTeX fragment at point, or all locally or globally.
17511 If the cursor is in a LaTeX fragment, create the image and overlay
17512 it over the source code. If there is no fragment at point, display
17513 all fragments in the current text, from one headline to the next. With
17514 prefix SUBTREE, display all fragments in the current subtree. With a
17515 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17516 the cursor is before the first headline,
17517 display all fragments in the buffer.
17518 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17519 (interactive "P")
17520 (unless buffer-file-name
17521 (error "Can't preview LaTeX fragment in a non-file buffer"))
17522 (org-remove-latex-fragment-image-overlays)
17523 (save-excursion
17524 (save-restriction
17525 (let (beg end at msg)
17526 (cond
17527 ((or (equal subtree '(16))
17528 (not (save-excursion
17529 (re-search-backward org-outline-regexp-bol nil t))))
17530 (setq beg (point-min) end (point-max)
17531 msg "Creating images for buffer...%s"))
17532 ((equal subtree '(4))
17533 (org-back-to-heading)
17534 (setq beg (point) end (org-end-of-subtree t)
17535 msg "Creating images for subtree...%s"))
17537 (if (setq at (org-inside-LaTeX-fragment-p))
17538 (goto-char (max (point-min) (- (cdr at) 2)))
17539 (org-back-to-heading))
17540 (setq beg (point) end (progn (outline-next-heading) (point))
17541 msg (if at "Creating image...%s"
17542 "Creating images for entry...%s"))))
17543 (message msg "")
17544 (narrow-to-region beg end)
17545 (goto-char beg)
17546 (org-format-latex
17547 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17548 (file-name-nondirectory
17549 buffer-file-name)))
17550 default-directory 'overlays msg at 'forbuffer
17551 org-latex-create-formula-image-program)
17552 (message msg "done. Use `C-c C-c' to remove images.")))))
17554 (defvar org-latex-regexps
17555 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17556 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17557 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17558 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17559 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17560 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17561 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17562 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17563 "Regular expressions for matching embedded LaTeX.")
17565 (defvar org-export-have-math nil) ;; dynamic scoping
17566 (defun org-format-latex (prefix &optional dir overlays msg at
17567 forbuffer processing-type)
17568 "Replace LaTeX fragments with links to an image, and produce images.
17569 Some of the options can be changed using the variable
17570 `org-format-latex-options'."
17571 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17572 (let* ((prefixnodir (file-name-nondirectory prefix))
17573 (absprefix (expand-file-name prefix dir))
17574 (todir (file-name-directory absprefix))
17575 (opt org-format-latex-options)
17576 (optnew org-format-latex-options)
17577 (matchers (plist-get opt :matchers))
17578 (re-list org-latex-regexps)
17579 (org-format-latex-header-extra
17580 (plist-get (org-infile-export-plist) :latex-header-extra))
17581 (cnt 0) txt hash link beg end re e checkdir
17582 string
17583 m n block-type block linkfile movefile ov)
17584 ;; Check the different regular expressions
17585 (while (setq e (pop re-list))
17586 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17587 block (if block-type "\n\n" ""))
17588 (when (member m matchers)
17589 (goto-char (point-min))
17590 (while (re-search-forward re nil t)
17591 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17592 (not (get-text-property (match-beginning n)
17593 'org-protected))
17594 (or (not overlays)
17595 (not (eq (get-char-property (match-beginning n)
17596 'org-overlay-type)
17597 'org-latex-overlay))))
17598 (setq org-export-have-math t)
17599 (cond
17600 ((eq processing-type 'verbatim)
17601 ;; Leave the text verbatim, just protect it
17602 (add-text-properties (match-beginning n) (match-end n)
17603 '(org-protected t)))
17604 ((eq processing-type 'mathjax)
17605 ;; Prepare for MathJax processing
17606 (setq string (match-string n))
17607 (if (member m '("$" "$1"))
17608 (save-excursion
17609 (delete-region (match-beginning n) (match-end n))
17610 (goto-char (match-beginning n))
17611 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17612 "\\)")
17613 '(org-protected t))))
17614 (add-text-properties (match-beginning n) (match-end n)
17615 '(org-protected t))))
17616 ((or (eq processing-type 'dvipng)
17617 (eq processing-type 'imagemagick))
17618 ;; Process to an image
17619 (setq txt (match-string n)
17620 beg (match-beginning n) end (match-end n)
17621 cnt (1+ cnt))
17622 (let ((face (face-at-point))
17623 (fg (plist-get opt :foreground))
17624 (bg (plist-get opt :background))
17625 print-length print-level) ; make sure full list is printed
17626 (when forbuffer
17627 ; Get the colors from the face at point
17628 (goto-char beg)
17629 (when (eq fg 'auto)
17630 (setq fg (face-attribute face :foreground nil 'default)))
17631 (when (eq bg 'auto)
17632 (setq bg (face-attribute face :background nil 'default)))
17633 (setq optnew (copy-sequence opt))
17634 (plist-put optnew :foreground fg)
17635 (plist-put optnew :background bg))
17636 (setq hash (sha1 (prin1-to-string
17637 (list org-format-latex-header
17638 org-format-latex-header-extra
17639 org-export-latex-default-packages-alist
17640 org-export-latex-packages-alist
17641 org-format-latex-options
17642 forbuffer txt fg bg)))
17643 linkfile (format "%s_%s.png" prefix hash)
17644 movefile (format "%s_%s.png" absprefix hash)))
17645 (setq link (concat block "[[file:" linkfile "]]" block))
17646 (if msg (message msg cnt))
17647 (goto-char beg)
17648 (unless checkdir ; make sure the directory exists
17649 (setq checkdir t)
17650 (or (file-directory-p todir) (make-directory todir t)))
17651 (unless (file-exists-p movefile)
17652 (org-create-formula-image
17653 txt movefile optnew forbuffer processing-type))
17654 (if overlays
17655 (progn
17656 (mapc (lambda (o)
17657 (if (eq (overlay-get o 'org-overlay-type)
17658 'org-latex-overlay)
17659 (delete-overlay o)))
17660 (overlays-in beg end))
17661 (setq ov (make-overlay beg end))
17662 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17663 (if (featurep 'xemacs)
17664 (progn
17665 (overlay-put ov 'invisible t)
17666 (overlay-put
17667 ov 'end-glyph
17668 (make-glyph (vector 'png :file movefile))))
17669 (overlay-put
17670 ov 'display
17671 (list 'image :type 'png :file movefile :ascent 'center)))
17672 (push ov org-latex-fragment-image-overlays)
17673 (goto-char end))
17674 (delete-region beg end)
17675 (insert (org-add-props link
17676 (list 'org-latex-src
17677 (replace-regexp-in-string
17678 "\"" "" txt)
17679 'org-latex-src-embed-type
17680 (if block-type 'paragraph 'character))))))
17681 ((eq processing-type 'mathml)
17682 ;; Process to MathML
17683 (unless (save-match-data (org-format-latex-mathml-available-p))
17684 (error "LaTeX to MathML converter not configured"))
17685 (setq txt (match-string n)
17686 beg (match-beginning n) end (match-end n)
17687 cnt (1+ cnt))
17688 (if msg (message msg cnt))
17689 (goto-char beg)
17690 (delete-region beg end)
17691 (insert (org-format-latex-as-mathml
17692 txt block-type prefix dir)))
17694 (error "Unknown conversion type %s for latex fragments"
17695 processing-type)))))))))
17697 (defun org-create-math-formula (latex-frag &optional mathml-file)
17698 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17699 Use `org-latex-to-mathml-convert-command'. If the conversion is
17700 sucessful, return the portion between \"<math...> </math>\"
17701 elements otherwise return nil. When MATHML-FILE is specified,
17702 write the results in to that file. When invoked as an
17703 interactive command, prompt for LATEX-FRAG, with initial value
17704 set to the current active region and echo the results for user
17705 inspection."
17706 (interactive (list (let ((frag (when (org-region-active-p)
17707 (buffer-substring-no-properties
17708 (region-beginning) (region-end)))))
17709 (read-string "LaTeX Fragment: " frag nil frag))))
17710 (unless latex-frag (error "Invalid latex-frag"))
17711 (let* ((tmp-in-file (file-relative-name
17712 (make-temp-name (expand-file-name "ltxmathml-in"))))
17713 (ignore (write-region latex-frag nil tmp-in-file))
17714 (tmp-out-file (file-relative-name
17715 (make-temp-name (expand-file-name "ltxmathml-out"))))
17716 (cmd (format-spec
17717 org-latex-to-mathml-convert-command
17718 `((?j . ,(shell-quote-argument
17719 (expand-file-name org-latex-to-mathml-jar-file)))
17720 (?I . ,(shell-quote-argument tmp-in-file))
17721 (?o . ,(shell-quote-argument tmp-out-file)))))
17722 mathml shell-command-output)
17723 (when (org-called-interactively-p 'any)
17724 (unless (org-format-latex-mathml-available-p)
17725 (error "LaTeX to MathML converter not configured")))
17726 (message "Running %s" cmd)
17727 (setq shell-command-output (shell-command-to-string cmd))
17728 (setq mathml
17729 (when (file-readable-p tmp-out-file)
17730 (with-current-buffer (find-file-noselect tmp-out-file t)
17731 (goto-char (point-min))
17732 (when (re-search-forward
17733 (concat
17734 (regexp-quote
17735 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17736 "\\(.\\|\n\\)*"
17737 (regexp-quote "</math>")) nil t)
17738 (prog1 (match-string 0) (kill-buffer))))))
17739 (cond
17740 (mathml
17741 (setq mathml
17742 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17743 (when mathml-file
17744 (write-region mathml nil mathml-file))
17745 (when (org-called-interactively-p 'any)
17746 (message mathml)))
17747 ((message "LaTeX to MathML conversion failed")
17748 (message shell-command-output)))
17749 (delete-file tmp-in-file)
17750 (when (file-exists-p tmp-out-file)
17751 (delete-file tmp-out-file))
17752 mathml))
17754 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17755 prefix &optional dir)
17756 "Use `org-create-math-formula' but check local cache first."
17757 (let* ((absprefix (expand-file-name prefix dir))
17758 (print-length nil) (print-level nil)
17759 (formula-id (concat
17760 "formula-"
17761 (sha1
17762 (prin1-to-string
17763 (list latex-frag
17764 org-latex-to-mathml-convert-command)))))
17765 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17766 (formula-cache-dir (file-name-directory formula-cache)))
17768 (unless (file-directory-p formula-cache-dir)
17769 (make-directory formula-cache-dir t))
17771 (unless (file-exists-p formula-cache)
17772 (org-create-math-formula latex-frag formula-cache))
17774 (if (file-exists-p formula-cache)
17775 ;; Successful conversion. Return the link to MathML file.
17776 (org-add-props
17777 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17778 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17779 'org-latex-src-embed-type (if latex-frag-type
17780 'paragraph 'character)))
17781 ;; Failed conversion. Return the LaTeX fragment verbatim
17782 (add-text-properties
17783 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17784 latex-frag)))
17786 (defun org-create-formula-image (string tofile options buffer &optional type)
17787 "Create an image from LaTeX source using dvipng or convert.
17788 This function calls either `org-create-formula-image-with-dvipng'
17789 or `org-create-formula-image-with-imagemagick' depending on the
17790 value of `org-latex-create-formula-image-program' or on the value
17791 of the optional TYPE variable.
17793 Note: ultimately these two function should be combined as they
17794 share a good deal of logic."
17795 (org-check-external-command
17796 "latex" "needed to convert LaTeX fragments to images")
17797 (funcall
17798 (case (or type org-latex-create-formula-image-program)
17799 ('dvipng
17800 (org-check-external-command
17801 "dvipng" "needed to convert LaTeX fragments to images")
17802 #'org-create-formula-image-with-dvipng)
17803 ('imagemagick
17804 (org-check-external-command
17805 "convert" "you need to install imagemagick")
17806 #'org-create-formula-image-with-imagemagick)
17807 (t (error
17808 "invalid value of `org-latex-create-formula-image-program'")))
17809 string tofile options buffer))
17811 ;; This function borrows from Ganesh Swami's latex2png.el
17812 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17813 "This calls dvipng."
17814 (require 'org-latex)
17815 (let* ((tmpdir (if (featurep 'xemacs)
17816 (temp-directory)
17817 temporary-file-directory))
17818 (texfilebase (make-temp-name
17819 (expand-file-name "orgtex" tmpdir)))
17820 (texfile (concat texfilebase ".tex"))
17821 (dvifile (concat texfilebase ".dvi"))
17822 (pngfile (concat texfilebase ".png"))
17823 (fnh (if (featurep 'xemacs)
17824 (font-height (face-font 'default))
17825 (face-attribute 'default :height nil)))
17826 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17827 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17828 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17829 "Black"))
17830 (bg (or (plist-get options (if buffer :background :html-background))
17831 "Transparent")))
17832 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17833 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17834 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17835 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17836 (with-temp-file texfile
17837 (insert (org-splice-latex-header
17838 org-format-latex-header
17839 org-export-latex-default-packages-alist
17840 org-export-latex-packages-alist t
17841 org-format-latex-header-extra))
17842 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17843 (require 'org-latex)
17844 (org-export-latex-fix-inputenc))
17845 (let ((dir default-directory))
17846 (condition-case nil
17847 (progn
17848 (cd tmpdir)
17849 (call-process "latex" nil nil nil texfile))
17850 (error nil))
17851 (cd dir))
17852 (if (not (file-exists-p dvifile))
17853 (progn (message "Failed to create dvi file from %s" texfile) nil)
17854 (condition-case nil
17855 (if (featurep 'xemacs)
17856 (call-process "dvipng" nil nil nil
17857 "-fg" fg "-bg" bg
17858 "-T" "tight"
17859 "-o" pngfile
17860 dvifile)
17861 (call-process "dvipng" nil nil nil
17862 "-fg" fg "-bg" bg
17863 "-D" dpi
17864 ;;"-x" scale "-y" scale
17865 "-T" "tight"
17866 "-o" pngfile
17867 dvifile))
17868 (error nil))
17869 (if (not (file-exists-p pngfile))
17870 (if org-format-latex-signal-error
17871 (error "Failed to create png file from %s" texfile)
17872 (message "Failed to create png file from %s" texfile)
17873 nil)
17874 ;; Use the requested file name and clean up
17875 (copy-file pngfile tofile 'replace)
17876 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17877 (if (file-exists-p (concat texfilebase e))
17878 (delete-file (concat texfilebase e))))
17879 pngfile))))
17881 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17882 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17883 "This calls convert, which is included into imagemagick."
17884 (require 'org-latex)
17885 (let* ((tmpdir (if (featurep 'xemacs)
17886 (temp-directory)
17887 temporary-file-directory))
17888 (texfilebase (make-temp-name
17889 (expand-file-name "orgtex" tmpdir)))
17890 (texfile (concat texfilebase ".tex"))
17891 (pdffile (concat texfilebase ".pdf"))
17892 (pngfile (concat texfilebase ".png"))
17893 (fnh (if (featurep 'xemacs)
17894 (font-height (face-font 'default))
17895 (face-attribute 'default :height nil)))
17896 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17897 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17898 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17899 "black"))
17900 (bg (or (plist-get options (if buffer :background :html-background))
17901 "white")))
17902 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17903 (setq fg (org-latex-color-format fg)))
17904 (if (eq bg 'default) (setq bg (org-latex-color :background))
17905 (setq bg (org-latex-color-format
17906 (if (string= bg "Transparent") "white" bg))))
17907 (with-temp-file texfile
17908 (insert (org-splice-latex-header
17909 org-format-latex-header
17910 org-export-latex-default-packages-alist
17911 org-export-latex-packages-alist t
17912 org-format-latex-header-extra))
17913 (insert "\n\\begin{document}\n"
17914 "\\definecolor{fg}{rgb}{" fg "}\n"
17915 "\\definecolor{bg}{rgb}{" bg "}\n"
17916 "\n\\pagecolor{bg}\n"
17917 "\n{\\color{fg}\n"
17918 string
17919 "\n}\n"
17920 "\n\\end{document}\n" )
17921 (require 'org-latex)
17922 (org-export-latex-fix-inputenc))
17923 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17924 (condition-case nil
17925 (progn
17926 (cd tmpdir)
17927 (setq cmds org-latex-to-pdf-process)
17928 (while cmds
17929 (setq latex-frags-cmds (pop cmds))
17930 (if (listp latex-frags-cmds)
17931 (setq cmds nil)
17932 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17933 (while latex-frags-cmds
17934 (setq cmd (pop latex-frags-cmds))
17935 (while (string-match "%b" cmd)
17936 (setq cmd (replace-match
17937 (save-match-data
17938 (shell-quote-argument texfile))
17939 t t cmd)))
17940 (while (string-match "%f" cmd)
17941 (setq cmd (replace-match
17942 (save-match-data
17943 (shell-quote-argument (file-name-nondirectory texfile)))
17944 t t cmd)))
17945 (while (string-match "%o" cmd)
17946 (setq cmd (replace-match
17947 (save-match-data
17948 (shell-quote-argument (file-name-directory texfile)))
17949 t t cmd)))
17950 (setq cmd (split-string cmd))
17951 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17952 (error nil))
17953 (cd dir))
17954 (if (not (file-exists-p pdffile))
17955 (progn (message "Failed to create pdf file from %s" texfile) nil)
17956 (condition-case nil
17957 (if (featurep 'xemacs)
17958 (call-process "convert" nil nil nil
17959 "-density" "96"
17960 "-trim"
17961 "-antialias"
17962 pdffile
17963 "-quality" "100"
17964 ;; "-sharpen" "0x1.0"
17965 pngfile)
17966 (call-process "convert" nil nil nil
17967 "-density" dpi
17968 "-trim"
17969 "-antialias"
17970 pdffile
17971 "-quality" "100"
17972 ; "-sharpen" "0x1.0"
17973 pngfile))
17974 (error nil))
17975 (if (not (file-exists-p pngfile))
17976 (if org-format-latex-signal-error
17977 (error "Failed to create png file from %s" texfile)
17978 (message "Failed to create png file from %s" texfile)
17979 nil)
17980 ;; Use the requested file name and clean up
17981 (copy-file pngfile tofile 'replace)
17982 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17983 (if (file-exists-p (concat texfilebase e))
17984 (delete-file (concat texfilebase e))))
17985 pngfile))))
17987 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17988 "Fill a LaTeX header template TPL.
17989 In the template, the following place holders will be recognized:
17991 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17992 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17993 [PACKAGES] \\usepackage statements for PKG
17994 [NO-PACKAGES] do not include PKG
17995 [EXTRA] the string EXTRA
17996 [NO-EXTRA] do not include EXTRA
17998 For backward compatibility, if both the positive and the negative place
17999 holder is missing, the positive one (without the \"NO-\") will be
18000 assumed to be present at the end of the template.
18001 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18002 EXTRA is a string.
18003 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18004 (let (rpl (end ""))
18005 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18006 (setq rpl (if (or (match-end 1) (not def-pkg))
18007 "" (org-latex-packages-to-string def-pkg snippets-p t))
18008 tpl (replace-match rpl t t tpl))
18009 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18011 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18012 (setq rpl (if (or (match-end 1) (not pkg))
18013 "" (org-latex-packages-to-string pkg snippets-p t))
18014 tpl (replace-match rpl t t tpl))
18015 (if pkg (setq end
18016 (concat end "\n"
18017 (org-latex-packages-to-string pkg snippets-p)))))
18019 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18020 (setq rpl (if (or (match-end 1) (not extra))
18021 "" (concat extra "\n"))
18022 tpl (replace-match rpl t t tpl))
18023 (if (and extra (string-match "\\S-" extra))
18024 (setq end (concat end "\n" extra))))
18026 (if (string-match "\\S-" end)
18027 (concat tpl "\n" end)
18028 tpl)))
18030 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18031 "Turn an alist of packages into a string with the \\usepackage macros."
18032 (setq pkg (mapconcat (lambda(p)
18033 (cond
18034 ((stringp p) p)
18035 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18036 (format "%% Package %s omitted" (cadr p)))
18037 ((equal "" (car p))
18038 (format "\\usepackage{%s}" (cadr p)))
18040 (format "\\usepackage[%s]{%s}"
18041 (car p) (cadr p)))))
18043 "\n"))
18044 (if newline (concat pkg "\n") pkg))
18046 (defun org-dvipng-color (attr)
18047 "Return a RGB color specification for dvipng."
18048 (apply 'format "rgb %s %s %s"
18049 (mapcar 'org-normalize-color
18050 (if (featurep 'xemacs)
18051 (color-rgb-components
18052 (face-property 'default
18053 (cond ((eq attr :foreground) 'foreground)
18054 ((eq attr :background) 'background))))
18055 (color-values (face-attribute 'default attr nil))))))
18057 (defun org-dvipng-color-format (color-name)
18058 "Convert COLOR-NAME to a RGB color value for dvipng."
18059 (apply 'format "rgb %s %s %s"
18060 (mapcar 'org-normalize-color
18061 (color-values color-name))))
18063 (defun org-latex-color (attr)
18064 "Return a RGB color for the LaTeX color package."
18065 (apply 'format "%s,%s,%s"
18066 (mapcar 'org-normalize-color
18067 (if (featurep 'xemacs)
18068 (color-rgb-components
18069 (face-property 'default
18070 (cond ((eq attr :foreground) 'foreground)
18071 ((eq attr :background) 'background))))
18072 (color-values (face-attribute 'default attr nil))))))
18074 (defun org-latex-color-format (color-name)
18075 "Convert COLOR-NAME to a RGB color value."
18076 (apply 'format "%s,%s,%s"
18077 (mapcar 'org-normalize-color
18078 (color-values color-name))))
18080 (defun org-normalize-color (value)
18081 "Return string to be used as color value for an RGB component."
18082 (format "%g" (/ value 65535.0)))
18084 ;; Image display
18087 (defvar org-inline-image-overlays nil)
18088 (make-variable-buffer-local 'org-inline-image-overlays)
18090 (defun org-toggle-inline-images (&optional include-linked)
18091 "Toggle the display of inline images.
18092 INCLUDE-LINKED is passed to `org-display-inline-images'."
18093 (interactive "P")
18094 (if org-inline-image-overlays
18095 (progn
18096 (org-remove-inline-images)
18097 (message "Inline image display turned off"))
18098 (org-display-inline-images include-linked)
18099 (if (and (org-called-interactively-p)
18100 org-inline-image-overlays)
18101 (message "%d images displayed inline"
18102 (length org-inline-image-overlays))
18103 (message "No images to display inline"))))
18105 (defun org-redisplay-inline-images ()
18106 "Refresh the display of inline images."
18107 (interactive)
18108 (if (not org-inline-image-overlays)
18109 (org-toggle-inline-images)
18110 (org-toggle-inline-images)
18111 (org-toggle-inline-images)))
18113 (defun org-display-inline-images (&optional include-linked refresh beg end)
18114 "Display inline images.
18115 Normally only links without a description part are inlined, because this
18116 is how it will work for export. When INCLUDE-LINKED is set, also links
18117 with a description part will be inlined. This can be nice for a quick
18118 look at those images, but it does not reflect what exported files will look
18119 like.
18120 When REFRESH is set, refresh existing images between BEG and END.
18121 This will create new image displays only if necessary.
18122 BEG and END default to the buffer boundaries."
18123 (interactive "P")
18124 (unless refresh
18125 (org-remove-inline-images)
18126 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18127 (save-excursion
18128 (save-restriction
18129 (widen)
18130 (setq beg (or beg (point-min)) end (or end (point-max)))
18131 (goto-char beg)
18132 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18133 (substring (org-image-file-name-regexp) 0 -2)
18134 "\\)\\]" (if include-linked "" "\\]")))
18135 old file ov img type attrwidth width)
18136 (while (re-search-forward re end t)
18137 (setq old (get-char-property-and-overlay (match-beginning 1)
18138 'org-image-overlay)
18139 file (expand-file-name
18140 (concat (or (match-string 3) "") (match-string 4))))
18141 (when (image-type-available-p 'imagemagick)
18142 (setq attrwidth (if (or (listp org-image-actual-width)
18143 (null org-image-actual-width))
18144 (save-excursion
18145 (save-match-data
18146 (when (re-search-backward
18147 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18148 (save-excursion
18149 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18150 (string-to-number (match-string 1))))))
18151 width (cond ((eq org-image-actual-width t) nil)
18152 ((null org-image-actual-width) attrwidth)
18153 ((numberp org-image-actual-width)
18154 org-image-actual-width)
18155 ((listp org-image-actual-width)
18156 (or attrwidth (car org-image-actual-width))))
18157 type (if width 'imagemagick)))
18158 (when (file-exists-p file)
18159 (if (and (car-safe old) refresh)
18160 (image-refresh (overlay-get (cdr old) 'display))
18161 (setq img (save-match-data (create-image file type nil :width width)))
18162 (when img
18163 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18164 (overlay-put ov 'display img)
18165 (overlay-put ov 'face 'default)
18166 (overlay-put ov 'org-image-overlay t)
18167 (overlay-put ov 'modification-hooks
18168 (list 'org-display-inline-remove-overlay))
18169 (push ov org-inline-image-overlays)))))))))
18171 (define-obsolete-function-alias
18172 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18174 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18175 "Remove inline-display overlay if a corresponding region is modified."
18176 (let ((inhibit-modification-hooks t))
18177 (when (and ov after)
18178 (delete ov org-inline-image-overlays)
18179 (delete-overlay ov))))
18181 (defun org-remove-inline-images ()
18182 "Remove inline display of images."
18183 (interactive)
18184 (mapc 'delete-overlay org-inline-image-overlays)
18185 (setq org-inline-image-overlays nil))
18187 ;;;; Key bindings
18189 ;; Outline functions from `outline-mode-prefix-map'
18190 ;; that can be remapped in Org:
18191 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18192 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18193 (define-key org-mode-map [remap outline-forward-same-level]
18194 'org-forward-heading-same-level)
18195 (define-key org-mode-map [remap outline-backward-same-level]
18196 'org-backward-heading-same-level)
18197 (define-key org-mode-map [remap show-branches]
18198 'org-kill-note-or-show-branches)
18199 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18200 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18201 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18203 ;; Outline functions from `outline-mode-prefix-map' that can not
18204 ;; be remapped in Org:
18206 ;; - the column "key binding" shows whether the Outline function is still
18207 ;; available in Org mode on the same key that it has been bound to in
18208 ;; Outline mode:
18209 ;; - "overridden": key used for a different functionality in Org mode
18210 ;; - else: key still bound to the same Outline function in Org mode
18212 ;; | Outline function | key binding | Org replacement |
18213 ;; |------------------------------------+-------------+-----------------------|
18214 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18215 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18216 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18217 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18218 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18219 ;; | `show-entry' | overridden | no replacement |
18220 ;; | `show-children' | `C-c C-i' | visibility cycling |
18221 ;; | `show-branches' | `C-c C-k' | still same function |
18222 ;; | `show-subtree' | overridden | visibility cycling |
18223 ;; | `show-all' | overridden | no replacement |
18224 ;; | `hide-subtree' | overridden | visibility cycling |
18225 ;; | `hide-body' | overridden | no replacement |
18226 ;; | `hide-entry' | overridden | visibility cycling |
18227 ;; | `hide-leaves' | overridden | no replacement |
18228 ;; | `hide-sublevels' | overridden | no replacement |
18229 ;; | `hide-other' | overridden | no replacement |
18231 ;; Make `C-c C-x' a prefix key
18232 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18234 ;; TAB key with modifiers
18235 (org-defkey org-mode-map "\C-i" 'org-cycle)
18236 (org-defkey org-mode-map [(tab)] 'org-cycle)
18237 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18238 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18239 ;; The following line is necessary under Suse GNU/Linux
18240 (unless (featurep 'xemacs)
18241 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18242 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18243 (define-key org-mode-map [backtab] 'org-shifttab)
18245 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18246 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18247 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18249 ;; Cursor keys with modifiers
18250 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18251 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18252 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18253 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18255 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18256 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18257 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18258 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18260 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18261 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18262 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18263 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18265 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18266 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18267 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18268 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18270 ;; Babel keys
18271 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18272 (mapc (lambda (pair)
18273 (define-key org-babel-map (car pair) (cdr pair)))
18274 org-babel-key-bindings)
18276 ;;; Extra keys for tty access.
18277 ;; We only set them when really needed because otherwise the
18278 ;; menus don't show the simple keys
18280 (when (or org-use-extra-keys
18281 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18282 (not window-system))
18283 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18284 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18285 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18286 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18287 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18288 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18289 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18290 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18291 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18292 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18293 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18294 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18295 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18296 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18297 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18298 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18299 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18300 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18301 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18302 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18303 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18304 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18305 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18306 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18307 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18308 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18309 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18310 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18312 ;; All the other keys
18314 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18315 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18316 (if (boundp 'narrow-map)
18317 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18318 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18319 (if (boundp 'narrow-map)
18320 (org-defkey narrow-map "b" 'org-narrow-to-block)
18321 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18322 (if (boundp 'narrow-map)
18323 (org-defkey narrow-map "e" 'org-narrow-to-element)
18324 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18325 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18326 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18327 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18328 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18329 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18330 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18331 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18332 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18333 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18334 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18335 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18336 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18337 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18338 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18339 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18340 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18341 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18342 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18343 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18344 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18345 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18346 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18347 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18348 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18349 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18350 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18351 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18352 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18353 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18354 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18355 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18356 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18357 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18358 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18359 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18360 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18361 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18362 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18363 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18364 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18365 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18366 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18367 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18368 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18369 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18370 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18371 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18372 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18373 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18374 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18375 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18376 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18377 (org-defkey org-mode-map "\C-c^" 'org-sort)
18378 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18379 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18380 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18381 (org-defkey org-mode-map "\C-m" 'org-return)
18382 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18383 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18384 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18385 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18386 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18387 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18388 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18389 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18390 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18391 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18392 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18393 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18394 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18395 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18396 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18397 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18398 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18399 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18400 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18401 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18402 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18403 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18404 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18406 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18407 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18408 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18410 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18411 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18412 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18413 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18414 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18415 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18416 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18417 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18418 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18419 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18420 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18421 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18422 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18423 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18424 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18425 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18426 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18427 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18428 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18429 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18430 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18431 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18432 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18434 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18435 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18436 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18437 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18438 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18440 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18442 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18444 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18445 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18447 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18450 (when (featurep 'xemacs)
18451 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18454 (defconst org-speed-commands-default
18456 ("Outline Navigation")
18457 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18458 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18459 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18460 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18461 ("u" . (org-speed-move-safe 'outline-up-heading))
18462 ("j" . org-goto)
18463 ("g" . (org-refile t))
18464 ("Outline Visibility")
18465 ("c" . org-cycle)
18466 ("C" . org-shifttab)
18467 (" " . org-display-outline-path)
18468 (":" . org-columns)
18469 ("Outline Structure Editing")
18470 ("U" . org-shiftmetaup)
18471 ("D" . org-shiftmetadown)
18472 ("r" . org-metaright)
18473 ("l" . org-metaleft)
18474 ("R" . org-shiftmetaright)
18475 ("L" . org-shiftmetaleft)
18476 ("i" . (progn (forward-char 1) (call-interactively
18477 'org-insert-heading-respect-content)))
18478 ("^" . org-sort)
18479 ("w" . org-refile)
18480 ("a" . org-archive-subtree-default-with-confirmation)
18481 ("." . org-mark-subtree)
18482 ("#" . org-toggle-comment)
18483 ("Clock Commands")
18484 ("I" . org-clock-in)
18485 ("O" . org-clock-out)
18486 ("Meta Data Editing")
18487 ("t" . org-todo)
18488 ("," . (org-priority))
18489 ("0" . (org-priority ?\ ))
18490 ("1" . (org-priority ?A))
18491 ("2" . (org-priority ?B))
18492 ("3" . (org-priority ?C))
18493 (";" . org-set-tags-command)
18494 ("e" . org-set-effort)
18495 ("E" . org-inc-effort)
18496 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18497 (org-entry-put (point) "APPT_WARNTIME" m)))
18498 ("Agenda Views etc")
18499 ("v" . org-agenda)
18500 ("/" . org-sparse-tree)
18501 ("Misc")
18502 ("o" . org-open-at-point)
18503 ("?" . org-speed-command-help)
18504 ("<" . (org-agenda-set-restriction-lock 'subtree))
18505 (">" . (org-agenda-remove-restriction-lock))
18507 "The default speed commands.")
18509 (defun org-print-speed-command (e)
18510 (if (> (length (car e)) 1)
18511 (progn
18512 (princ "\n")
18513 (princ (car e))
18514 (princ "\n")
18515 (princ (make-string (length (car e)) ?-))
18516 (princ "\n"))
18517 (princ (car e))
18518 (princ " ")
18519 (if (symbolp (cdr e))
18520 (princ (symbol-name (cdr e)))
18521 (prin1 (cdr e)))
18522 (princ "\n")))
18524 (defun org-speed-command-help ()
18525 "Show the available speed commands."
18526 (interactive)
18527 (if (not org-use-speed-commands)
18528 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18529 (with-output-to-temp-buffer "*Help*"
18530 (princ "User-defined Speed commands\n===========================\n")
18531 (mapc 'org-print-speed-command org-speed-commands-user)
18532 (princ "\n")
18533 (princ "Built-in Speed commands\n=======================\n")
18534 (mapc 'org-print-speed-command org-speed-commands-default))
18535 (with-current-buffer "*Help*"
18536 (setq truncate-lines t))))
18538 (defun org-speed-move-safe (cmd)
18539 "Execute CMD, but make sure that the cursor always ends up in a headline.
18540 If not, return to the original position and throw an error."
18541 (interactive)
18542 (let ((pos (point)))
18543 (call-interactively cmd)
18544 (unless (and (bolp) (org-at-heading-p))
18545 (goto-char pos)
18546 (error "Boundary reached while executing %s" cmd))))
18548 (defvar org-self-insert-command-undo-counter 0)
18550 (defvar org-table-auto-blank-field) ; defined in org-table.el
18551 (defvar org-speed-command nil)
18553 (define-obsolete-function-alias
18554 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18556 (defun org-speed-command-activate (keys)
18557 "Hook for activating single-letter speed commands.
18558 `org-speed-commands-default' specifies a minimal command set.
18559 Use `org-speed-commands-user' for further customization."
18560 (when (or (and (bolp) (looking-at org-outline-regexp))
18561 (and (functionp org-use-speed-commands)
18562 (funcall org-use-speed-commands)))
18563 (cdr (assoc keys (append org-speed-commands-user
18564 org-speed-commands-default)))))
18566 (define-obsolete-function-alias
18567 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18569 (defun org-babel-speed-command-activate (keys)
18570 "Hook for activating single-letter code block commands."
18571 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18572 (cdr (assoc keys org-babel-key-bindings))))
18574 (defcustom org-speed-command-hook
18575 '(org-speed-command-default-hook org-babel-speed-command-hook)
18576 "Hook for activating speed commands at strategic locations.
18577 Hook functions are called in sequence until a valid handler is
18578 found.
18580 Each hook takes a single argument, a user-pressed command key
18581 which is also a `self-insert-command' from the global map.
18583 Within the hook, examine the cursor position and the command key
18584 and return nil or a valid handler as appropriate. Handler could
18585 be one of an interactive command, a function, or a form.
18587 Set `org-use-speed-commands' to non-nil value to enable this
18588 hook. The default setting is `org-speed-command-activate'."
18589 :group 'org-structure
18590 :version "24.1"
18591 :type 'hook)
18593 (defun org-self-insert-command (N)
18594 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18595 If the cursor is in a table looking at whitespace, the whitespace is
18596 overwritten, and the table is not marked as requiring realignment."
18597 (interactive "p")
18598 (org-check-before-invisible-edit 'insert)
18599 (cond
18600 ((and org-use-speed-commands
18601 (setq org-speed-command
18602 (run-hook-with-args-until-success
18603 'org-speed-command-hook (this-command-keys))))
18604 (cond
18605 ((commandp org-speed-command)
18606 (setq this-command org-speed-command)
18607 (call-interactively org-speed-command))
18608 ((functionp org-speed-command)
18609 (funcall org-speed-command))
18610 ((and org-speed-command (listp org-speed-command))
18611 (eval org-speed-command))
18612 (t (let (org-use-speed-commands)
18613 (call-interactively 'org-self-insert-command)))))
18614 ((and
18615 (org-table-p)
18616 (progn
18617 ;; check if we blank the field, and if that triggers align
18618 (and (featurep 'org-table) org-table-auto-blank-field
18619 (member last-command
18620 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18621 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18622 ;; got extra space, this field does not determine column width
18623 (let (org-table-may-need-update) (org-table-blank-field))
18624 ;; no extra space, this field may determine column width
18625 (org-table-blank-field)))
18627 (eq N 1)
18628 (looking-at "[^|\n]* |"))
18629 (let (org-table-may-need-update)
18630 (goto-char (1- (match-end 0)))
18631 (backward-delete-char 1)
18632 (goto-char (match-beginning 0))
18633 (self-insert-command N)))
18635 (setq org-table-may-need-update t)
18636 (self-insert-command N)
18637 (org-fix-tags-on-the-fly)
18638 (if org-self-insert-cluster-for-undo
18639 (if (not (eq last-command 'org-self-insert-command))
18640 (setq org-self-insert-command-undo-counter 1)
18641 (if (>= org-self-insert-command-undo-counter 20)
18642 (setq org-self-insert-command-undo-counter 1)
18643 (and (> org-self-insert-command-undo-counter 0)
18644 buffer-undo-list (listp buffer-undo-list)
18645 (not (cadr buffer-undo-list)) ; remove nil entry
18646 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18647 (setq org-self-insert-command-undo-counter
18648 (1+ org-self-insert-command-undo-counter))))))))
18650 (defun org-check-before-invisible-edit (kind)
18651 "Check is editing if kind KIND would be dangerous with invisible text around.
18652 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18653 ;; First, try to get out of here as quickly as possible, to reduce overhead
18654 (if (and org-catch-invisible-edits
18655 (or (not (boundp 'visible-mode)) (not visible-mode))
18656 (or (get-char-property (point) 'invisible)
18657 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18658 ;; OK, we need to take a closer look
18659 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18660 (invisible-before-point (if (bobp) nil (get-char-property
18661 (1- (point)) 'invisible)))
18662 (border-and-ok-direction
18664 ;; Check if we are acting predictably before invisible text
18665 (and invisible-at-point (not invisible-before-point)
18666 (memq kind '(insert delete-backward)))
18667 ;; Check if we are acting predictably after invisible text
18668 ;; This works not well, and I have turned it off. It seems
18669 ;; better to always show and stop after invisible text.
18670 ;; (and (not invisible-at-point) invisible-before-point
18671 ;; (memq kind '(insert delete)))
18673 (when (or (memq invisible-at-point '(outline org-hide-block t))
18674 (memq invisible-before-point '(outline org-hide-block t)))
18675 (if (eq org-catch-invisible-edits 'error)
18676 (error "Editing in invisible areas is prohibited - make visible first"))
18677 (if (and org-custom-properties-overlays
18678 (y-or-n-p "Display invisible properties in this buffer? "))
18679 (org-toggle-custom-properties-visibility)
18680 ;; Make the area visible
18681 (save-excursion
18682 (if invisible-before-point
18683 (goto-char (previous-single-char-property-change
18684 (point) 'invisible)))
18685 (org-cycle))
18686 (cond
18687 ((eq org-catch-invisible-edits 'show)
18688 ;; That's it, we do the edit after showing
18689 (message
18690 "Unfolding invisible region around point before editing")
18691 (sit-for 1))
18692 ((and (eq org-catch-invisible-edits 'smart)
18693 border-and-ok-direction)
18694 (message "Unfolding invisible region around point before editing"))
18696 ;; Don't do the edit, make the user repeat it in full visibility
18697 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18699 (defun org-fix-tags-on-the-fly ()
18700 (when (and (equal (char-after (point-at-bol)) ?*)
18701 (org-at-heading-p))
18702 (org-align-tags-here org-tags-column)))
18704 (defun org-delete-backward-char (N)
18705 "Like `delete-backward-char', insert whitespace at field end in tables.
18706 When deleting backwards, in tables this function will insert whitespace in
18707 front of the next \"|\" separator, to keep the table aligned. The table will
18708 still be marked for re-alignment if the field did fill the entire column,
18709 because, in this case the deletion might narrow the column."
18710 (interactive "p")
18711 (save-match-data
18712 (org-check-before-invisible-edit 'delete-backward)
18713 (if (and (org-table-p)
18714 (eq N 1)
18715 (string-match "|" (buffer-substring (point-at-bol) (point)))
18716 (looking-at ".*?|"))
18717 (let ((pos (point))
18718 (noalign (looking-at "[^|\n\r]* |"))
18719 (c org-table-may-need-update))
18720 (backward-delete-char N)
18721 (if (not overwrite-mode)
18722 (progn
18723 (skip-chars-forward "^|")
18724 (insert " ")
18725 (goto-char (1- pos))))
18726 ;; noalign: if there were two spaces at the end, this field
18727 ;; does not determine the width of the column.
18728 (if noalign (setq org-table-may-need-update c)))
18729 (backward-delete-char N)
18730 (org-fix-tags-on-the-fly))))
18732 (defun org-delete-char (N)
18733 "Like `delete-char', but insert whitespace at field end in tables.
18734 When deleting characters, in tables this function will insert whitespace in
18735 front of the next \"|\" separator, to keep the table aligned. The table will
18736 still be marked for re-alignment if the field did fill the entire column,
18737 because, in this case the deletion might narrow the column."
18738 (interactive "p")
18739 (save-match-data
18740 (org-check-before-invisible-edit 'delete)
18741 (if (and (org-table-p)
18742 (not (bolp))
18743 (not (= (char-after) ?|))
18744 (eq N 1))
18745 (if (looking-at ".*?|")
18746 (let ((pos (point))
18747 (noalign (looking-at "[^|\n\r]* |"))
18748 (c org-table-may-need-update))
18749 (replace-match (concat
18750 (substring (match-string 0) 1 -1)
18751 " |"))
18752 (goto-char pos)
18753 ;; noalign: if there were two spaces at the end, this field
18754 ;; does not determine the width of the column.
18755 (if noalign (setq org-table-may-need-update c)))
18756 (delete-char N))
18757 (delete-char N)
18758 (org-fix-tags-on-the-fly))))
18760 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18761 (put 'org-self-insert-command 'delete-selection t)
18762 (put 'orgtbl-self-insert-command 'delete-selection t)
18763 (put 'org-delete-char 'delete-selection 'supersede)
18764 (put 'org-delete-backward-char 'delete-selection 'supersede)
18765 (put 'org-yank 'delete-selection 'yank)
18767 ;; Make `flyspell-mode' delay after some commands
18768 (put 'org-self-insert-command 'flyspell-delayed t)
18769 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18770 (put 'org-delete-char 'flyspell-delayed t)
18771 (put 'org-delete-backward-char 'flyspell-delayed t)
18773 ;; Make pabbrev-mode expand after org-mode commands
18774 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18775 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18777 ;; How to do this: Measure non-white length of current string
18778 ;; If equal to column width, we should realign.
18780 (defun org-remap (map &rest commands)
18781 "In MAP, remap the functions given in COMMANDS.
18782 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18783 (let (new old)
18784 (while commands
18785 (setq old (pop commands) new (pop commands))
18786 (if (fboundp 'command-remapping)
18787 (org-defkey map (vector 'remap old) new)
18788 (substitute-key-definition old new map global-map)))))
18790 (when (eq org-enable-table-editor 'optimized)
18791 ;; If the user wants maximum table support, we need to hijack
18792 ;; some standard editing functions
18793 (org-remap org-mode-map
18794 'self-insert-command 'org-self-insert-command
18795 'delete-char 'org-delete-char
18796 'delete-backward-char 'org-delete-backward-char)
18797 (org-defkey org-mode-map "|" 'org-force-self-insert))
18799 (defvar org-ctrl-c-ctrl-c-hook nil
18800 "Hook for functions attaching themselves to `C-c C-c'.
18802 This can be used to add additional functionality to the C-c C-c
18803 key which executes context-dependent commands. This hook is run
18804 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18805 run after the last test.
18807 Each function will be called with no arguments. The function
18808 must check if the context is appropriate for it to act. If yes,
18809 it should do its thing and then return a non-nil value. If the
18810 context is wrong, just do nothing and return nil.")
18812 (defvar org-ctrl-c-ctrl-c-final-hook nil
18813 "Hook for functions attaching themselves to `C-c C-c'.
18815 This can be used to add additional functionality to the C-c C-c
18816 key which executes context-dependent commands. This hook is run
18817 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18818 before the first test.
18820 Each function will be called with no arguments. The function
18821 must check if the context is appropriate for it to act. If yes,
18822 it should do its thing and then return a non-nil value. If the
18823 context is wrong, just do nothing and return nil.")
18825 (defvar org-tab-first-hook nil
18826 "Hook for functions to attach themselves to TAB.
18827 See `org-ctrl-c-ctrl-c-hook' for more information.
18828 This hook runs as the first action when TAB is pressed, even before
18829 `org-cycle' messes around with the `outline-regexp' to cater for
18830 inline tasks and plain list item folding.
18831 If any function in this hook returns t, any other actions that
18832 would have been caused by TAB (such as table field motion or visibility
18833 cycling) will not occur.")
18835 (defvar org-tab-after-check-for-table-hook nil
18836 "Hook for functions to attach themselves to TAB.
18837 See `org-ctrl-c-ctrl-c-hook' for more information.
18838 This hook runs after it has been established that the cursor is not in a
18839 table, but before checking if the cursor is in a headline or if global cycling
18840 should be done.
18841 If any function in this hook returns t, not other actions like visibility
18842 cycling will be done.")
18844 (defvar org-tab-after-check-for-cycling-hook nil
18845 "Hook for functions to attach themselves to TAB.
18846 See `org-ctrl-c-ctrl-c-hook' for more information.
18847 This hook runs after it has been established that not table field motion and
18848 not visibility should be done because of current context. This is probably
18849 the place where a package like yasnippets can hook in.")
18851 (defvar org-tab-before-tab-emulation-hook nil
18852 "Hook for functions to attach themselves to TAB.
18853 See `org-ctrl-c-ctrl-c-hook' for more information.
18854 This hook runs after every other options for TAB have been exhausted, but
18855 before indentation and \t insertion takes place.")
18857 (defvar org-metaleft-hook nil
18858 "Hook for functions attaching themselves to `M-left'.
18859 See `org-ctrl-c-ctrl-c-hook' for more information.")
18860 (defvar org-metaright-hook nil
18861 "Hook for functions attaching themselves to `M-right'.
18862 See `org-ctrl-c-ctrl-c-hook' for more information.")
18863 (defvar org-metaup-hook nil
18864 "Hook for functions attaching themselves to `M-up'.
18865 See `org-ctrl-c-ctrl-c-hook' for more information.")
18866 (defvar org-metadown-hook nil
18867 "Hook for functions attaching themselves to `M-down'.
18868 See `org-ctrl-c-ctrl-c-hook' for more information.")
18869 (defvar org-shiftmetaleft-hook nil
18870 "Hook for functions attaching themselves to `M-S-left'.
18871 See `org-ctrl-c-ctrl-c-hook' for more information.")
18872 (defvar org-shiftmetaright-hook nil
18873 "Hook for functions attaching themselves to `M-S-right'.
18874 See `org-ctrl-c-ctrl-c-hook' for more information.")
18875 (defvar org-shiftmetaup-hook nil
18876 "Hook for functions attaching themselves to `M-S-up'.
18877 See `org-ctrl-c-ctrl-c-hook' for more information.")
18878 (defvar org-shiftmetadown-hook nil
18879 "Hook for functions attaching themselves to `M-S-down'.
18880 See `org-ctrl-c-ctrl-c-hook' for more information.")
18881 (defvar org-metareturn-hook nil
18882 "Hook for functions attaching themselves to `M-RET'.
18883 See `org-ctrl-c-ctrl-c-hook' for more information.")
18884 (defvar org-shiftup-hook nil
18885 "Hook for functions attaching themselves to `S-up'.
18886 See `org-ctrl-c-ctrl-c-hook' for more information.")
18887 (defvar org-shiftup-final-hook nil
18888 "Hook for functions attaching themselves to `S-up'.
18889 This one runs after all other options except shift-select have been excluded.
18890 See `org-ctrl-c-ctrl-c-hook' for more information.")
18891 (defvar org-shiftdown-hook nil
18892 "Hook for functions attaching themselves to `S-down'.
18893 See `org-ctrl-c-ctrl-c-hook' for more information.")
18894 (defvar org-shiftdown-final-hook nil
18895 "Hook for functions attaching themselves to `S-down'.
18896 This one runs after all other options except shift-select have been excluded.
18897 See `org-ctrl-c-ctrl-c-hook' for more information.")
18898 (defvar org-shiftleft-hook nil
18899 "Hook for functions attaching themselves to `S-left'.
18900 See `org-ctrl-c-ctrl-c-hook' for more information.")
18901 (defvar org-shiftleft-final-hook nil
18902 "Hook for functions attaching themselves to `S-left'.
18903 This one runs after all other options except shift-select have been excluded.
18904 See `org-ctrl-c-ctrl-c-hook' for more information.")
18905 (defvar org-shiftright-hook nil
18906 "Hook for functions attaching themselves to `S-right'.
18907 See `org-ctrl-c-ctrl-c-hook' for more information.")
18908 (defvar org-shiftright-final-hook nil
18909 "Hook for functions attaching themselves to `S-right'.
18910 This one runs after all other options except shift-select have been excluded.
18911 See `org-ctrl-c-ctrl-c-hook' for more information.")
18913 (defun org-modifier-cursor-error ()
18914 "Throw an error, a modified cursor command was applied in wrong context."
18915 (error "This command is active in special context like tables, headlines or items"))
18917 (defun org-shiftselect-error ()
18918 "Throw an error because Shift-Cursor command was applied in wrong context."
18919 (if (and (boundp 'shift-select-mode) shift-select-mode)
18920 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18921 (error "This command works only in special context like headlines or timestamps")))
18923 (defun org-call-for-shift-select (cmd)
18924 (let ((this-command-keys-shift-translated t))
18925 (call-interactively cmd)))
18927 (defun org-shifttab (&optional arg)
18928 "Global visibility cycling or move to previous table field.
18929 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18930 on context.
18931 See the individual commands for more information."
18932 (interactive "P")
18933 (cond
18934 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18935 ((integerp arg)
18936 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18937 (message "Content view to level: %d" arg)
18938 (org-content (prefix-numeric-value arg2))
18939 (setq org-cycle-global-status 'overview)))
18940 (t (call-interactively 'org-global-cycle))))
18942 (defun org-shiftmetaleft ()
18943 "Promote subtree or delete table column.
18944 Calls `org-promote-subtree', `org-outdent-item-tree', or
18945 `org-table-delete-column', depending on context. See the
18946 individual commands for more information."
18947 (interactive)
18948 (cond
18949 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18950 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18951 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18952 ((if (not (org-region-active-p)) (org-at-item-p)
18953 (save-excursion (goto-char (region-beginning))
18954 (org-at-item-p)))
18955 (call-interactively 'org-outdent-item-tree))
18956 (t (org-modifier-cursor-error))))
18958 (defun org-shiftmetaright ()
18959 "Demote subtree or insert table column.
18960 Calls `org-demote-subtree', `org-indent-item-tree', or
18961 `org-table-insert-column', depending on context. See the
18962 individual commands for more information."
18963 (interactive)
18964 (cond
18965 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18966 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18967 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18968 ((if (not (org-region-active-p)) (org-at-item-p)
18969 (save-excursion (goto-char (region-beginning))
18970 (org-at-item-p)))
18971 (call-interactively 'org-indent-item-tree))
18972 (t (org-modifier-cursor-error))))
18974 (defun org-shiftmetaup (&optional arg)
18975 "Move subtree up or kill table row.
18976 Calls `org-move-subtree-up' or `org-table-kill-row' or
18977 `org-move-item-up' or `org-timestamp-up', depending on context.
18978 See the individual commands for more information."
18979 (interactive "P")
18980 (cond
18981 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18982 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18983 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18984 ((org-at-item-p) (call-interactively 'org-move-item-up))
18985 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18986 (call-interactively 'org-timestamp-up)))
18987 (t (org-modifier-cursor-error))))
18989 (defun org-shiftmetadown (&optional arg)
18990 "Move subtree down or insert table row.
18991 Calls `org-move-subtree-down' or `org-table-insert-row' or
18992 `org-move-item-down' or `org-timestamp-up', depending on context.
18993 See the individual commands for more information."
18994 (interactive "P")
18995 (cond
18996 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18997 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18998 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18999 ((org-at-item-p) (call-interactively 'org-move-item-down))
19000 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19001 (call-interactively 'org-timestamp-down)))
19002 (t (org-modifier-cursor-error))))
19004 (defsubst org-hidden-tree-error ()
19005 (error
19006 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19008 (defun org-metaleft (&optional arg)
19009 "Promote heading or move table column to left.
19010 Calls `org-do-promote' or `org-table-move-column', depending on context.
19011 With no specific context, calls the Emacs default `backward-word'.
19012 See the individual commands for more information."
19013 (interactive "P")
19014 (cond
19015 ((run-hook-with-args-until-success 'org-metaleft-hook))
19016 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19017 ((org-with-limited-levels
19018 (or (org-at-heading-p)
19019 (and (org-region-active-p)
19020 (save-excursion
19021 (goto-char (region-beginning))
19022 (org-at-heading-p)))))
19023 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19024 (call-interactively 'org-do-promote))
19025 ;; At an inline task.
19026 ((org-at-heading-p)
19027 (call-interactively 'org-inlinetask-promote))
19028 ((or (org-at-item-p)
19029 (and (org-region-active-p)
19030 (save-excursion
19031 (goto-char (region-beginning))
19032 (org-at-item-p))))
19033 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19034 (call-interactively 'org-outdent-item))
19035 (t (call-interactively 'backward-word))))
19037 (defun org-metaright (&optional arg)
19038 "Demote a subtree, a list item or move table column to right.
19039 In front of a drawer or a block keyword, indent it correctly.
19040 With no specific context, calls the Emacs default `forward-word'.
19041 See the individual commands for more information."
19042 (interactive "P")
19043 (cond
19044 ((run-hook-with-args-until-success 'org-metaright-hook))
19045 ((org-at-table-p) (call-interactively 'org-table-move-column))
19046 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19047 ((org-at-block-p) (call-interactively 'org-indent-block))
19048 ((org-with-limited-levels
19049 (or (org-at-heading-p)
19050 (and (org-region-active-p)
19051 (save-excursion
19052 (goto-char (region-beginning))
19053 (org-at-heading-p)))))
19054 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19055 (call-interactively 'org-do-demote))
19056 ;; At an inline task.
19057 ((org-at-heading-p)
19058 (call-interactively 'org-inlinetask-demote))
19059 ((or (org-at-item-p)
19060 (and (org-region-active-p)
19061 (save-excursion
19062 (goto-char (region-beginning))
19063 (org-at-item-p))))
19064 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19065 (call-interactively 'org-indent-item))
19066 (t (call-interactively 'forward-word))))
19068 (defun org-check-for-hidden (what)
19069 "Check if there are hidden headlines/items in the current visual line.
19070 WHAT can be either `headlines' or `items'. If the current line is
19071 an outline or item heading and it has a folded subtree below it,
19072 this function returns t, nil otherwise."
19073 (let ((re (cond
19074 ((eq what 'headlines) org-outline-regexp-bol)
19075 ((eq what 'items) (org-item-beginning-re))
19076 (t (error "This should not happen"))))
19077 beg end)
19078 (save-excursion
19079 (catch 'exit
19080 (unless (org-region-active-p)
19081 (setq beg (point-at-bol))
19082 (beginning-of-line 2)
19083 (while (and (not (eobp)) ;; this is like `next-line'
19084 (get-char-property (1- (point)) 'invisible))
19085 (beginning-of-line 2))
19086 (setq end (point))
19087 (goto-char beg)
19088 (goto-char (point-at-eol))
19089 (setq end (max end (point)))
19090 (while (re-search-forward re end t)
19091 (if (get-char-property (match-beginning 0) 'invisible)
19092 (throw 'exit t))))
19093 nil))))
19095 (defun org-metaup (&optional arg)
19096 "Move subtree up or move table row up.
19097 Calls `org-move-subtree-up' or `org-table-move-row' or
19098 `org-move-item-up', depending on context. See the individual commands
19099 for more information."
19100 (interactive "P")
19101 (cond
19102 ((run-hook-with-args-until-success 'org-metaup-hook))
19103 ((org-region-active-p)
19104 (let* ((a (min (region-beginning) (region-end)))
19105 (b (1- (max (region-beginning) (region-end))))
19106 (c (save-excursion (goto-char a)
19107 (move-beginning-of-line 0)))
19108 (d (save-excursion (goto-char a)
19109 (move-end-of-line 0) (point))))
19110 (transpose-regions a b c d)
19111 (goto-char c)))
19112 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19113 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19114 ((org-at-item-p) (call-interactively 'org-move-item-up))
19115 (t (org-drag-element-backward))))
19117 (defun org-metadown (&optional arg)
19118 "Move subtree down or move table row down.
19119 Calls `org-move-subtree-down' or `org-table-move-row' or
19120 `org-move-item-down', depending on context. See the individual
19121 commands for more information."
19122 (interactive "P")
19123 (cond
19124 ((run-hook-with-args-until-success 'org-metadown-hook))
19125 ((org-region-active-p)
19126 (let* ((a (min (region-beginning) (region-end)))
19127 (b (max (region-beginning) (region-end)))
19128 (c (save-excursion (goto-char b)
19129 (move-beginning-of-line 1)))
19130 (d (save-excursion (goto-char b)
19131 (move-end-of-line 1) (1+ (point)))))
19132 (transpose-regions a b c d)
19133 (goto-char d)))
19134 ((org-at-table-p) (call-interactively 'org-table-move-row))
19135 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19136 ((org-at-item-p) (call-interactively 'org-move-item-down))
19137 (t (org-drag-element-forward))))
19139 (defun org-shiftup (&optional arg)
19140 "Increase item in timestamp or increase priority of current headline.
19141 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19142 depending on context. See the individual commands for more information."
19143 (interactive "P")
19144 (cond
19145 ((run-hook-with-args-until-success 'org-shiftup-hook))
19146 ((and org-support-shift-select (org-region-active-p))
19147 (org-call-for-shift-select 'previous-line))
19148 ((org-at-timestamp-p t)
19149 (call-interactively (if org-edit-timestamp-down-means-later
19150 'org-timestamp-down 'org-timestamp-up)))
19151 ((and (not (eq org-support-shift-select 'always))
19152 org-enable-priority-commands
19153 (org-at-heading-p))
19154 (call-interactively 'org-priority-up))
19155 ((and (not org-support-shift-select) (org-at-item-p))
19156 (call-interactively 'org-previous-item))
19157 ((org-clocktable-try-shift 'up arg))
19158 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19159 (org-support-shift-select
19160 (org-call-for-shift-select 'previous-line))
19161 (t (org-shiftselect-error))))
19163 (defun org-shiftdown (&optional arg)
19164 "Decrease item in timestamp or decrease priority of current headline.
19165 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19166 depending on context. See the individual commands for more information."
19167 (interactive "P")
19168 (cond
19169 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19170 ((and org-support-shift-select (org-region-active-p))
19171 (org-call-for-shift-select 'next-line))
19172 ((org-at-timestamp-p t)
19173 (call-interactively (if org-edit-timestamp-down-means-later
19174 'org-timestamp-up 'org-timestamp-down)))
19175 ((and (not (eq org-support-shift-select 'always))
19176 org-enable-priority-commands
19177 (org-at-heading-p))
19178 (call-interactively 'org-priority-down))
19179 ((and (not org-support-shift-select) (org-at-item-p))
19180 (call-interactively 'org-next-item))
19181 ((org-clocktable-try-shift 'down arg))
19182 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19183 (org-support-shift-select
19184 (org-call-for-shift-select 'next-line))
19185 (t (org-shiftselect-error))))
19187 (defun org-shiftright (&optional arg)
19188 "Cycle the thing at point or in the current line, depending on context.
19189 Depending on context, this does one of the following:
19191 - switch a timestamp at point one day into the future
19192 - on a headline, switch to the next TODO keyword.
19193 - on an item, switch entire list to the next bullet type
19194 - on a property line, switch to the next allowed value
19195 - on a clocktable definition line, move time block into the future"
19196 (interactive "P")
19197 (cond
19198 ((run-hook-with-args-until-success 'org-shiftright-hook))
19199 ((and org-support-shift-select (org-region-active-p))
19200 (org-call-for-shift-select 'forward-char))
19201 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19202 ((and (not (eq org-support-shift-select 'always))
19203 (org-at-heading-p))
19204 (let ((org-inhibit-logging
19205 (not org-treat-S-cursor-todo-selection-as-state-change))
19206 (org-inhibit-blocking
19207 (not org-treat-S-cursor-todo-selection-as-state-change)))
19208 (org-call-with-arg 'org-todo 'right)))
19209 ((or (and org-support-shift-select
19210 (not (eq org-support-shift-select 'always))
19211 (org-at-item-bullet-p))
19212 (and (not org-support-shift-select) (org-at-item-p)))
19213 (org-call-with-arg 'org-cycle-list-bullet nil))
19214 ((and (not (eq org-support-shift-select 'always))
19215 (org-at-property-p))
19216 (call-interactively 'org-property-next-allowed-value))
19217 ((org-clocktable-try-shift 'right arg))
19218 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19219 (org-support-shift-select
19220 (org-call-for-shift-select 'forward-char))
19221 (t (org-shiftselect-error))))
19223 (defun org-shiftleft (&optional arg)
19224 "Cycle the thing at point or in the current line, depending on context.
19225 Depending on context, this does one of the following:
19227 - switch a timestamp at point one day into the past
19228 - on a headline, switch to the previous TODO keyword.
19229 - on an item, switch entire list to the previous bullet type
19230 - on a property line, switch to the previous allowed value
19231 - on a clocktable definition line, move time block into the past"
19232 (interactive "P")
19233 (cond
19234 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19235 ((and org-support-shift-select (org-region-active-p))
19236 (org-call-for-shift-select 'backward-char))
19237 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19238 ((and (not (eq org-support-shift-select 'always))
19239 (org-at-heading-p))
19240 (let ((org-inhibit-logging
19241 (not org-treat-S-cursor-todo-selection-as-state-change))
19242 (org-inhibit-blocking
19243 (not org-treat-S-cursor-todo-selection-as-state-change)))
19244 (org-call-with-arg 'org-todo 'left)))
19245 ((or (and org-support-shift-select
19246 (not (eq org-support-shift-select 'always))
19247 (org-at-item-bullet-p))
19248 (and (not org-support-shift-select) (org-at-item-p)))
19249 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19250 ((and (not (eq org-support-shift-select 'always))
19251 (org-at-property-p))
19252 (call-interactively 'org-property-previous-allowed-value))
19253 ((org-clocktable-try-shift 'left arg))
19254 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19255 (org-support-shift-select
19256 (org-call-for-shift-select 'backward-char))
19257 (t (org-shiftselect-error))))
19259 (defun org-shiftcontrolright ()
19260 "Switch to next TODO set."
19261 (interactive)
19262 (cond
19263 ((and org-support-shift-select (org-region-active-p))
19264 (org-call-for-shift-select 'forward-word))
19265 ((and (not (eq org-support-shift-select 'always))
19266 (org-at-heading-p))
19267 (org-call-with-arg 'org-todo 'nextset))
19268 (org-support-shift-select
19269 (org-call-for-shift-select 'forward-word))
19270 (t (org-shiftselect-error))))
19272 (defun org-shiftcontrolleft ()
19273 "Switch to previous TODO set."
19274 (interactive)
19275 (cond
19276 ((and org-support-shift-select (org-region-active-p))
19277 (org-call-for-shift-select 'backward-word))
19278 ((and (not (eq org-support-shift-select 'always))
19279 (org-at-heading-p))
19280 (org-call-with-arg 'org-todo 'previousset))
19281 (org-support-shift-select
19282 (org-call-for-shift-select 'backward-word))
19283 (t (org-shiftselect-error))))
19285 (defun org-shiftcontrolup (&optional n)
19286 "Change timestamps synchronously up in CLOCK log lines.
19287 Optional argument N tells to change by that many units."
19288 (interactive "P")
19289 (cond ((and (not org-support-shift-select)
19290 (org-at-clock-log-p)
19291 (org-at-timestamp-p t))
19292 (org-clock-timestamps-up n))
19293 (t (org-shiftselect-error))))
19295 (defun org-shiftcontroldown (&optional n)
19296 "Change timestamps synchronously down in CLOCK log lines.
19297 Optional argument N tells to change by that many units."
19298 (interactive "P")
19299 (cond ((and (not org-support-shift-select)
19300 (org-at-clock-log-p)
19301 (org-at-timestamp-p t))
19302 (org-clock-timestamps-down n))
19303 (t (org-shiftselect-error))))
19305 (defun org-ctrl-c-ret ()
19306 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19307 (interactive)
19308 (cond
19309 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19310 (t (call-interactively 'org-insert-heading))))
19312 (defun org-find-visible ()
19313 (let ((s (point)))
19314 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19315 (get-char-property s 'invisible)))
19317 (defun org-find-invisible ()
19318 (let ((s (point)))
19319 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19320 (not (get-char-property s 'invisible))))
19323 (defun org-copy-visible (beg end)
19324 "Copy the visible parts of the region."
19325 (interactive "r")
19326 (let (snippets s)
19327 (save-excursion
19328 (save-restriction
19329 (narrow-to-region beg end)
19330 (setq s (goto-char (point-min)))
19331 (while (not (= (point) (point-max)))
19332 (goto-char (org-find-invisible))
19333 (push (buffer-substring s (point)) snippets)
19334 (setq s (goto-char (org-find-visible))))))
19335 (kill-new (apply 'concat (nreverse snippets)))))
19337 (defun org-copy-special ()
19338 "Copy region in table or copy current subtree.
19339 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19340 See the individual commands for more information."
19341 (interactive)
19342 (call-interactively
19343 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19345 (defun org-cut-special ()
19346 "Cut region in table or cut current subtree.
19347 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19348 See the individual commands for more information."
19349 (interactive)
19350 (call-interactively
19351 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19353 (defun org-paste-special (arg)
19354 "Paste rectangular region into table, or past subtree relative to level.
19355 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19356 See the individual commands for more information."
19357 (interactive "P")
19358 (if (org-at-table-p)
19359 (org-table-paste-rectangle)
19360 (org-paste-subtree arg)))
19362 (defsubst org-in-fixed-width-region-p ()
19363 "Is point in a fixed-width region?"
19364 (save-match-data
19365 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19367 (defun org-edit-special (&optional arg)
19368 "Call a special editor for the stuff at point.
19369 When at a table, call the formula editor with `org-table-edit-formulas'.
19370 When in a source code block, call `org-edit-src-code'.
19371 When in a fixed-width region, call `org-edit-fixed-width-region'.
19372 When in an #+include line, visit the included file.
19373 On a link, call `ffap' to visit the link at point.
19374 Otherwise, return a user error."
19375 (interactive)
19376 ;; possibly prep session before editing source
19377 (when (and (org-in-src-block-p) arg)
19378 (let* ((info (org-babel-get-src-block-info))
19379 (lang (nth 0 info))
19380 (params (nth 2 info))
19381 (session (cdr (assoc :session params))))
19382 (when (and info session) ;; we are in a source-code block with a session
19383 (funcall
19384 (intern (concat "org-babel-prep-session:" lang)) session params))))
19385 (cond ;; proceed with `org-edit-special'
19386 ((save-excursion
19387 (beginning-of-line 1)
19388 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19389 (find-file (org-trim (match-string 1))))
19390 ((or (org-at-table-p)
19391 (save-excursion
19392 (beginning-of-line 1)
19393 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19394 (call-interactively 'org-table-edit-formulas))
19395 ((or (org-in-block-p '("src" "example" "latex" "html"))
19396 (org-at-table.el-p))
19397 (org-edit-src-code))
19398 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19399 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19400 (t (user-error "No special environment to edit here"))))
19402 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19403 (defun org-ctrl-c-ctrl-c (&optional arg)
19404 "Set tags in headline, or update according to changed information at point.
19406 This command does many different things, depending on context:
19408 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19409 this is what we do.
19411 - If the cursor is on a statistics cookie, update it.
19413 - If the cursor is in a headline, prompt for tags and insert them
19414 into the current line, aligned to `org-tags-column'. When called
19415 with prefix arg, realign all tags in the current buffer.
19417 - If the cursor is in one of the special #+KEYWORD lines, this
19418 triggers scanning the buffer for these lines and updating the
19419 information.
19421 - If the cursor is inside a table, realign the table. This command
19422 works even if the automatic table editor has been turned off.
19424 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19425 the entire table.
19427 - If the cursor is at a footnote reference or definition, jump to
19428 the corresponding definition or references, respectively.
19430 - If the cursor is a the beginning of a dynamic block, update it.
19432 - If the current buffer is a capture buffer, close note and file it.
19434 - If the cursor is on a <<<target>>>, update radio targets and
19435 corresponding links in this buffer.
19437 - If the cursor is on a numbered item in a plain list, renumber the
19438 ordered list.
19440 - If the cursor is on a checkbox, toggle it.
19442 - If the cursor is on a code block, evaluate it. The variable
19443 `org-confirm-babel-evaluate' can be used to control prompting
19444 before code block evaluation, by default every code block
19445 evaluation requires confirmation. Code block evaluation can be
19446 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19447 (interactive "P")
19448 (let ((org-enable-table-editor t))
19449 (cond
19450 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19451 org-occur-highlights
19452 org-latex-fragment-image-overlays)
19453 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19454 (org-remove-occur-highlights)
19455 (org-remove-latex-fragment-image-overlays)
19456 (message "Temporary highlights/overlays removed from current buffer"))
19457 ((and (local-variable-p 'org-finish-function (current-buffer))
19458 (fboundp org-finish-function))
19459 (funcall org-finish-function))
19460 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19461 ((org-in-regexp org-ts-regexp-both)
19462 (org-timestamp-change 0 'day))
19463 ((or (looking-at org-property-start-re)
19464 (org-at-property-p))
19465 (call-interactively 'org-property-action))
19466 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19467 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19468 (or (org-at-heading-p) (org-at-item-p)))
19469 (call-interactively 'org-update-statistics-cookies))
19470 ((org-at-heading-p) (call-interactively 'org-set-tags))
19471 ((org-at-table.el-p)
19472 (message "Use C-c ' to edit table.el tables"))
19473 ((org-at-table-p)
19474 (org-table-maybe-eval-formula)
19475 (if arg
19476 (call-interactively 'org-table-recalculate)
19477 (org-table-maybe-recalculate-line))
19478 (call-interactively 'org-table-align)
19479 (orgtbl-send-table 'maybe))
19480 ((or (org-footnote-at-reference-p)
19481 (org-footnote-at-definition-p))
19482 (call-interactively 'org-footnote-action))
19483 ((org-at-item-checkbox-p)
19484 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19485 ;; list only if at top item.
19486 (let* ((cbox (match-string 1))
19487 (struct (org-list-struct))
19488 (old-struct (copy-tree struct))
19489 (parents (org-list-parents-alist struct))
19490 (orderedp (org-entry-get nil "ORDERED"))
19491 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19492 block-item)
19493 ;; Use a light version of `org-toggle-checkbox' to avoid
19494 ;; computing list structure twice.
19495 (let ((new-box (cond
19496 ((equal arg '(16)) "[-]")
19497 ((equal arg '(4)) nil)
19498 ((equal "[X]" cbox) "[ ]")
19499 (t "[X]"))))
19500 (if (and firstp arg)
19501 ;; If at first item of sub-list, remove check-box from
19502 ;; every item at the same level.
19503 (mapc
19504 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19505 (org-list-get-all-items
19506 (point-at-bol) struct (org-list-prevs-alist struct)))
19507 (org-list-set-checkbox (point-at-bol) struct new-box)))
19508 ;; Replicate `org-list-write-struct', while grabbing a return
19509 ;; value from `org-list-struct-fix-box'.
19510 (org-list-struct-fix-ind struct parents 2)
19511 (org-list-struct-fix-item-end struct)
19512 (let ((prevs (org-list-prevs-alist struct)))
19513 (org-list-struct-fix-bul struct prevs)
19514 (org-list-struct-fix-ind struct parents)
19515 (setq block-item
19516 (org-list-struct-fix-box struct parents prevs orderedp)))
19517 (org-list-struct-apply-struct struct old-struct)
19518 (org-update-checkbox-count-maybe)
19519 (when block-item
19520 (message
19521 "Checkboxes were removed due to unchecked box at line %d"
19522 (org-current-line block-item)))
19523 (when firstp (org-list-send-list 'maybe))))
19524 ((org-at-item-p)
19525 ;; Cursor at an item: repair list. Do checkbox related actions
19526 ;; only if function was called with an argument. Send list only
19527 ;; if at top item.
19528 (let* ((struct (org-list-struct))
19529 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19530 old-struct)
19531 (when arg
19532 (setq old-struct (copy-tree struct))
19533 (if firstp
19534 ;; If at first item of sub-list, add check-box to every
19535 ;; item at the same level.
19536 (mapc
19537 (lambda (pos)
19538 (unless (org-list-get-checkbox pos struct)
19539 (org-list-set-checkbox pos struct "[ ]")))
19540 (org-list-get-all-items
19541 (point-at-bol) struct (org-list-prevs-alist struct)))
19542 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19543 (org-list-write-struct
19544 struct (org-list-parents-alist struct) old-struct)
19545 (when arg (org-update-checkbox-count-maybe))
19546 (when firstp (org-list-send-list 'maybe))))
19547 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19548 ;; Dynamic block
19549 (beginning-of-line 1)
19550 (save-excursion (org-update-dblock)))
19551 ((save-excursion
19552 (let ((case-fold-search t))
19553 (beginning-of-line 1)
19554 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19555 (cond
19556 ((or (equal (match-string 1) "TBLFM")
19557 (equal (match-string 1) "tblfm"))
19558 ;; Recalculate the table before this line
19559 (save-excursion
19560 (beginning-of-line 1)
19561 (skip-chars-backward " \r\n\t")
19562 (if (org-at-table-p)
19563 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19565 (let ((org-inhibit-startup-visibility-stuff t)
19566 (org-startup-align-all-tables nil))
19567 (when (boundp 'org-table-coordinate-overlays)
19568 (mapc 'delete-overlay org-table-coordinate-overlays)
19569 (setq org-table-coordinate-overlays nil))
19570 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19571 (message "Local setup has been refreshed"))))
19572 ((org-clock-update-time-maybe))
19574 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19575 (error "C-c C-c can do nothing useful at this location"))))))
19577 (defun org-mode-restart ()
19578 "Restart Org-mode, to scan again for special lines.
19579 Also updates the keyword regular expressions."
19580 (interactive)
19581 (org-mode)
19582 (message "Org-mode restarted"))
19584 (defun org-kill-note-or-show-branches ()
19585 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19586 (interactive)
19587 (if (not org-finish-function)
19588 (progn
19589 (hide-subtree)
19590 (call-interactively 'show-branches))
19591 (let ((org-note-abort t))
19592 (funcall org-finish-function))))
19594 (defun org-return (&optional indent)
19595 "Goto next table row or insert a newline.
19596 Calls `org-table-next-row' or `newline', depending on context.
19597 See the individual commands for more information."
19598 (interactive)
19599 (let (org-ts-what)
19600 (cond
19601 ((or (bobp) (org-in-src-block-p))
19602 (if indent (newline-and-indent) (newline)))
19603 ((org-at-table-p)
19604 (org-table-justify-field-maybe)
19605 (call-interactively 'org-table-next-row))
19606 ;; when `newline-and-indent' is called within a list, make sure
19607 ;; text moved stays inside the item.
19608 ((and (org-in-item-p) indent)
19609 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19610 (progn
19611 (save-match-data (newline))
19612 (org-indent-line-to (length (match-string 0))))
19613 (let ((ind (org-get-indentation)))
19614 (newline)
19615 (if (org-looking-back org-list-end-re)
19616 (org-indent-line)
19617 (org-indent-line-to ind)))))
19618 ((and org-return-follows-link
19619 (org-at-timestamp-p t)
19620 (not (eq org-ts-what 'after)))
19621 (org-follow-timestamp-link))
19622 ((and org-return-follows-link
19623 (let ((tprop (get-text-property (point) 'face)))
19624 (or (eq tprop 'org-link)
19625 (and (listp tprop) (memq 'org-link tprop)))))
19626 (call-interactively 'org-open-at-point))
19627 ((and (org-at-heading-p)
19628 (looking-at
19629 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19630 (org-show-entry)
19631 (end-of-line 1)
19632 (newline))
19633 (t (if indent (newline-and-indent) (newline))))))
19635 (defun org-return-indent ()
19636 "Goto next table row or insert a newline and indent.
19637 Calls `org-table-next-row' or `newline-and-indent', depending on
19638 context. See the individual commands for more information."
19639 (interactive)
19640 (org-return t))
19642 (defun org-ctrl-c-star ()
19643 "Compute table, or change heading status of lines.
19644 Calls `org-table-recalculate' or `org-toggle-heading',
19645 depending on context."
19646 (interactive)
19647 (cond
19648 ((org-at-table-p)
19649 (call-interactively 'org-table-recalculate))
19651 ;; Convert all lines in region to list items
19652 (call-interactively 'org-toggle-heading))))
19654 (defun org-ctrl-c-minus ()
19655 "Insert separator line in table or modify bullet status of line.
19656 Also turns a plain line or a region of lines into list items.
19657 Calls `org-table-insert-hline', `org-toggle-item', or
19658 `org-cycle-list-bullet', depending on context."
19659 (interactive)
19660 (cond
19661 ((org-at-table-p)
19662 (call-interactively 'org-table-insert-hline))
19663 ((org-region-active-p)
19664 (call-interactively 'org-toggle-item))
19665 ((org-in-item-p)
19666 (call-interactively 'org-cycle-list-bullet))
19668 (call-interactively 'org-toggle-item))))
19670 (defun org-toggle-item (arg)
19671 "Convert headings or normal lines to items, items to normal lines.
19672 If there is no active region, only the current line is considered.
19674 If the first non blank line in the region is an headline, convert
19675 all headlines to items, shifting text accordingly.
19677 If it is an item, convert all items to normal lines.
19679 If it is normal text, change region into an item. With a prefix
19680 argument ARG, change each line in region into an item."
19681 (interactive "P")
19682 (let ((shift-text
19683 (function
19684 ;; Shift text in current section to IND, from point to END.
19685 ;; The function leaves point to END line.
19686 (lambda (ind end)
19687 (let ((min-i 1000) (end (copy-marker end)))
19688 ;; First determine the minimum indentation (MIN-I) of
19689 ;; the text.
19690 (save-excursion
19691 (catch 'exit
19692 (while (< (point) end)
19693 (let ((i (org-get-indentation)))
19694 (cond
19695 ;; Skip blank lines and inline tasks.
19696 ((looking-at "^[ \t]*$"))
19697 ((looking-at org-outline-regexp-bol))
19698 ;; We can't find less than 0 indentation.
19699 ((zerop i) (throw 'exit (setq min-i 0)))
19700 ((< i min-i) (setq min-i i))))
19701 (forward-line))))
19702 ;; Then indent each line so that a line indented to
19703 ;; MIN-I becomes indented to IND. Ignore blank lines
19704 ;; and inline tasks in the process.
19705 (let ((delta (- ind min-i)))
19706 (while (< (point) end)
19707 (unless (or (looking-at "^[ \t]*$")
19708 (looking-at org-outline-regexp-bol))
19709 (org-indent-line-to (+ (org-get-indentation) delta)))
19710 (forward-line)))))))
19711 (skip-blanks
19712 (function
19713 ;; Return beginning of first non-blank line, starting from
19714 ;; line at POS.
19715 (lambda (pos)
19716 (save-excursion
19717 (goto-char pos)
19718 (skip-chars-forward " \r\t\n")
19719 (point-at-bol)))))
19720 beg end)
19721 ;; Determine boundaries of changes.
19722 (if (org-region-active-p)
19723 (setq beg (funcall skip-blanks (region-beginning))
19724 end (copy-marker (region-end)))
19725 (setq beg (funcall skip-blanks (point-at-bol))
19726 end (copy-marker (point-at-eol))))
19727 ;; Depending on the starting line, choose an action on the text
19728 ;; between BEG and END.
19729 (org-with-limited-levels
19730 (save-excursion
19731 (goto-char beg)
19732 (cond
19733 ;; Case 1. Start at an item: de-itemize. Note that it only
19734 ;; happens when a region is active: `org-ctrl-c-minus'
19735 ;; would call `org-cycle-list-bullet' otherwise.
19736 ((org-at-item-p)
19737 (while (< (point) end)
19738 (when (org-at-item-p)
19739 (skip-chars-forward " \t")
19740 (delete-region (point) (match-end 0)))
19741 (forward-line)))
19742 ;; Case 2. Start at an heading: convert to items.
19743 ((org-at-heading-p)
19744 (let* ((bul (org-list-bullet-string "-"))
19745 (bul-len (length bul))
19746 ;; Indentation of the first heading. It should be
19747 ;; relative to the indentation of its parent, if any.
19748 (start-ind (save-excursion
19749 (cond
19750 ((not org-adapt-indentation) 0)
19751 ((not (outline-previous-heading)) 0)
19752 (t (length (match-string 0))))))
19753 ;; Level of first heading. Further headings will be
19754 ;; compared to it to determine hierarchy in the list.
19755 (ref-level (org-reduced-level (org-outline-level))))
19756 (while (< (point) end)
19757 (let* ((level (org-reduced-level (org-outline-level)))
19758 (delta (max 0 (- level ref-level))))
19759 ;; If current headline is less indented than the first
19760 ;; one, set it as reference, in order to preserve
19761 ;; subtrees.
19762 (when (< level ref-level) (setq ref-level level))
19763 (replace-match bul t t)
19764 (org-indent-line-to (+ start-ind (* delta bul-len)))
19765 ;; Ensure all text down to END (or SECTION-END) belongs
19766 ;; to the newly created item.
19767 (let ((section-end (save-excursion
19768 (or (outline-next-heading) (point)))))
19769 (forward-line)
19770 (funcall shift-text
19771 (+ start-ind (* (1+ delta) bul-len))
19772 (min end section-end)))))))
19773 ;; Case 3. Normal line with ARG: turn each non-item line into
19774 ;; an item.
19775 (arg
19776 (while (< (point) end)
19777 (unless (or (org-at-heading-p) (org-at-item-p))
19778 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19779 (replace-match
19780 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19781 (forward-line)))
19782 ;; Case 4. Normal line without ARG: make the first line of
19783 ;; region an item, and shift indentation of others
19784 ;; lines to set them as item's body.
19785 (t (let* ((bul (org-list-bullet-string "-"))
19786 (bul-len (length bul))
19787 (ref-ind (org-get-indentation)))
19788 (skip-chars-forward " \t")
19789 (insert bul)
19790 (forward-line)
19791 (while (< (point) end)
19792 ;; Ensure that lines less indented than first one
19793 ;; still get included in item body.
19794 (funcall shift-text
19795 (+ ref-ind bul-len)
19796 (min end (save-excursion (or (outline-next-heading)
19797 (point)))))
19798 (forward-line)))))))))
19800 (defun org-toggle-heading (&optional nstars)
19801 "Convert headings to normal text, or items or text to headings.
19802 If there is no active region, only the current line is considered.
19804 With a \\[universal-argument] prefix, convert the whole list at
19805 point into heading.
19807 In a region:
19809 - If the first non blank line is an headline, remove the stars
19810 from all headlines in the region.
19812 - If it is a normal line turn each and every normal line (i.e. not an
19813 heading or an item) in the region into a heading.
19815 - If it is a plain list item, turn all plain list items into headings.
19817 When converting a line into a heading, the number of stars is chosen
19818 such that the lines become children of the current entry. However,
19819 when a prefix argument is given, its value determines the number of
19820 stars to add."
19821 (interactive "P")
19822 (let ((skip-blanks
19823 (function
19824 ;; Return beginning of first non-blank line, starting from
19825 ;; line at POS.
19826 (lambda (pos)
19827 (save-excursion
19828 (goto-char pos)
19829 (while (org-at-comment-p) (forward-line))
19830 (skip-chars-forward " \r\t\n")
19831 (point-at-bol)))))
19832 beg end toggled)
19833 ;; Determine boundaries of changes. If a universal prefix has
19834 ;; been given, put the list in a region. If region ends at a bol,
19835 ;; do not consider the last line to be in the region.
19837 (when (and current-prefix-arg (org-at-item-p))
19838 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19839 (org-mark-element))
19841 (if (org-region-active-p)
19842 (setq beg (funcall skip-blanks (region-beginning))
19843 end (copy-marker (save-excursion
19844 (goto-char (region-end))
19845 (if (bolp) (point) (point-at-eol)))))
19846 (setq beg (funcall skip-blanks (point-at-bol))
19847 end (copy-marker (point-at-eol))))
19848 ;; Ensure inline tasks don't count as headings.
19849 (org-with-limited-levels
19850 (save-excursion
19851 (goto-char beg)
19852 (cond
19853 ;; Case 1. Started at an heading: de-star headings.
19854 ((org-at-heading-p)
19855 (while (< (point) end)
19856 (when (org-at-heading-p t)
19857 (looking-at org-outline-regexp) (replace-match "")
19858 (setq toggled t))
19859 (forward-line)))
19860 ;; Case 2. Started at an item: change items into headlines.
19861 ;; One star will be added by `org-list-to-subtree'.
19862 ((org-at-item-p)
19863 (let* ((stars (make-string
19864 (if nstars
19865 ;; subtract the star that will be added again by
19866 ;; `org-list-to-subtree'
19867 (1- (prefix-numeric-value current-prefix-arg))
19868 (or (org-current-level) 0))
19869 ?*))
19870 (add-stars
19871 (cond (nstars "") ; stars from prefix only
19872 ((equal stars "") "") ; before first heading
19873 (org-odd-levels-only "*") ; inside heading, odd
19874 (t "")))) ; inside heading, oddeven
19875 (while (< (point) end)
19876 (when (org-at-item-p)
19877 ;; Pay attention to cases when region ends before list.
19878 (let* ((struct (org-list-struct))
19879 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19880 (save-restriction
19881 (narrow-to-region (point) list-end)
19882 (insert
19883 (org-list-to-subtree
19884 (org-list-parse-list t)
19885 '(:istart (concat stars add-stars (funcall get-stars depth))
19886 :icount (concat stars add-stars (funcall get-stars depth)))))))
19887 (setq toggled t))
19888 (forward-line))))
19889 ;; Case 3. Started at normal text: make every line an heading,
19890 ;; skipping headlines and items.
19891 (t (let* ((stars (make-string
19892 (if nstars
19893 (prefix-numeric-value current-prefix-arg)
19894 (or (org-current-level) 0))
19895 ?*))
19896 (add-stars
19897 (cond (nstars "") ; stars from prefix only
19898 ((equal stars "") "*") ; before first heading
19899 (org-odd-levels-only "**") ; inside heading, odd
19900 (t "*"))) ; inside heading, oddeven
19901 (rpl (concat stars add-stars " ")))
19902 (while (< (point) end)
19903 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19904 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19905 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19906 (forward-line)))))))
19907 (unless toggled (message "Cannot toggle heading from here"))))
19909 (defun org-meta-return (&optional arg)
19910 "Insert a new heading or wrap a region in a table.
19911 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19912 See the individual commands for more information."
19913 (interactive "P")
19914 (cond
19915 ((run-hook-with-args-until-success 'org-metareturn-hook))
19916 ((or (org-at-drawer-p) (org-at-property-p))
19917 (newline-and-indent))
19918 ((org-at-table-p)
19919 (call-interactively 'org-table-wrap-region))
19920 (t (call-interactively 'org-insert-heading))))
19922 ;;; Menu entries
19924 (defsubst org-in-subtree-not-table-p ()
19925 "Are we in a subtree and not in a table?"
19926 (and (not (org-before-first-heading-p))
19927 (not (org-at-table-p))))
19929 ;; Define the Org-mode menus
19930 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19931 '("Tbl"
19932 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19933 ["Next Field" org-cycle (org-at-table-p)]
19934 ["Previous Field" org-shifttab (org-at-table-p)]
19935 ["Next Row" org-return (org-at-table-p)]
19936 "--"
19937 ["Blank Field" org-table-blank-field (org-at-table-p)]
19938 ["Edit Field" org-table-edit-field (org-at-table-p)]
19939 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19940 "--"
19941 ("Column"
19942 ["Move Column Left" org-metaleft (org-at-table-p)]
19943 ["Move Column Right" org-metaright (org-at-table-p)]
19944 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19945 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19946 ("Row"
19947 ["Move Row Up" org-metaup (org-at-table-p)]
19948 ["Move Row Down" org-metadown (org-at-table-p)]
19949 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19950 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19951 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19952 "--"
19953 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19954 ("Rectangle"
19955 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19956 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19957 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19958 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19959 "--"
19960 ("Calculate"
19961 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19962 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19963 ["Edit Formulas" org-edit-special (org-at-table-p)]
19964 "--"
19965 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19966 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19967 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19968 "--"
19969 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19970 "--"
19971 ["Sum Column/Rectangle" org-table-sum
19972 (or (org-at-table-p) (org-region-active-p))]
19973 ["Which Column?" org-table-current-column (org-at-table-p)])
19974 ["Debug Formulas"
19975 org-table-toggle-formula-debugger
19976 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19977 ["Show Col/Row Numbers"
19978 org-table-toggle-coordinate-overlays
19979 :style toggle
19980 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19981 "--"
19982 ["Create" org-table-create (and (not (org-at-table-p))
19983 org-enable-table-editor)]
19984 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19985 ["Import from File" org-table-import (not (org-at-table-p))]
19986 ["Export to File" org-table-export (org-at-table-p)]
19987 "--"
19988 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19990 (easy-menu-define org-org-menu org-mode-map "Org menu"
19991 '("Org"
19992 ("Show/Hide"
19993 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19994 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19995 ["Sparse Tree..." org-sparse-tree t]
19996 ["Reveal Context" org-reveal t]
19997 ["Show All" show-all t]
19998 "--"
19999 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20000 "--"
20001 ["New Heading" org-insert-heading t]
20002 ("Navigate Headings"
20003 ["Up" outline-up-heading t]
20004 ["Next" outline-next-visible-heading t]
20005 ["Previous" outline-previous-visible-heading t]
20006 ["Next Same Level" outline-forward-same-level t]
20007 ["Previous Same Level" outline-backward-same-level t]
20008 "--"
20009 ["Jump" org-goto t])
20010 ("Edit Structure"
20011 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20012 "--"
20013 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20014 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20015 "--"
20016 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20017 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20018 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20019 "--"
20020 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20021 "--"
20022 ["Copy visible text" org-copy-visible t]
20023 "--"
20024 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20025 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20026 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20027 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20028 "--"
20029 ["Sort Region/Children" org-sort t]
20030 "--"
20031 ["Convert to odd levels" org-convert-to-odd-levels t]
20032 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20033 ("Editing"
20034 ["Emphasis..." org-emphasize t]
20035 ["Edit Source Example" org-edit-special t]
20036 "--"
20037 ["Footnote new/jump" org-footnote-action t]
20038 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20039 ("Archive"
20040 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20041 "--"
20042 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20043 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20044 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20046 "--"
20047 ("Hyperlinks"
20048 ["Store Link (Global)" org-store-link t]
20049 ["Find existing link to here" org-occur-link-in-agenda-files t]
20050 ["Insert Link" org-insert-link t]
20051 ["Follow Link" org-open-at-point t]
20052 "--"
20053 ["Next link" org-next-link t]
20054 ["Previous link" org-previous-link t]
20055 "--"
20056 ["Descriptive Links"
20057 org-toggle-link-display
20058 :style radio
20059 :selected org-descriptive-links
20061 ["Literal Links"
20062 org-toggle-link-display
20063 :style radio
20064 :selected (not org-descriptive-links)])
20065 "--"
20066 ("TODO Lists"
20067 ["TODO/DONE/-" org-todo t]
20068 ("Select keyword"
20069 ["Next keyword" org-shiftright (org-at-heading-p)]
20070 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20071 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20072 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20073 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20074 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20075 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20076 "--"
20077 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20078 :selected org-enforce-todo-dependencies :style toggle :active t]
20079 "Settings for tree at point"
20080 ["Do Children sequentially" org-toggle-ordered-property :style radio
20081 :selected (org-entry-get nil "ORDERED")
20082 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20083 ["Do Children parallel" org-toggle-ordered-property :style radio
20084 :selected (not (org-entry-get nil "ORDERED"))
20085 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20086 "--"
20087 ["Set Priority" org-priority t]
20088 ["Priority Up" org-shiftup t]
20089 ["Priority Down" org-shiftdown t]
20090 "--"
20091 ["Get news from all feeds" org-feed-update-all t]
20092 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20093 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20094 ("TAGS and Properties"
20095 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20096 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20097 "--"
20098 ["Set property" org-set-property (not (org-before-first-heading-p))]
20099 ["Column view of properties" org-columns t]
20100 ["Insert Column View DBlock" org-insert-columns-dblock t])
20101 ("Dates and Scheduling"
20102 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20103 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20104 ("Change Date"
20105 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20106 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20107 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20108 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20109 ["Compute Time Range" org-evaluate-time-range t]
20110 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20111 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20112 "--"
20113 ["Custom time format" org-toggle-time-stamp-overlays
20114 :style radio :selected org-display-custom-times]
20115 "--"
20116 ["Goto Calendar" org-goto-calendar t]
20117 ["Date from Calendar" org-date-from-calendar t]
20118 "--"
20119 ["Start/Restart Timer" org-timer-start t]
20120 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20121 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20122 ["Insert Timer String" org-timer t]
20123 ["Insert Timer Item" org-timer-item t])
20124 ("Logging work"
20125 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20126 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20127 ["Clock out" org-clock-out t]
20128 ["Clock cancel" org-clock-cancel t]
20129 "--"
20130 ["Mark as default task" org-clock-mark-default-task t]
20131 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20132 ["Goto running clock" org-clock-goto t]
20133 "--"
20134 ["Display times" org-clock-display t]
20135 ["Create clock table" org-clock-report t]
20136 "--"
20137 ["Record DONE time"
20138 (progn (setq org-log-done (not org-log-done))
20139 (message "Switching to %s will %s record a timestamp"
20140 (car org-done-keywords)
20141 (if org-log-done "automatically" "not")))
20142 :style toggle :selected org-log-done])
20143 "--"
20144 ["Agenda Command..." org-agenda t]
20145 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20146 ("File List for Agenda")
20147 ("Special views current file"
20148 ["TODO Tree" org-show-todo-tree t]
20149 ["Check Deadlines" org-check-deadlines t]
20150 ["Timeline" org-timeline t]
20151 ["Tags/Property tree" org-match-sparse-tree t])
20152 "--"
20153 ["Export/Publish..." org-export t]
20154 ("LaTeX"
20155 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20156 :selected org-cdlatex-mode]
20157 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20158 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20159 ["Modify math symbol" org-cdlatex-math-modify
20160 (org-inside-LaTeX-fragment-p)]
20161 ["Insert citation" org-reftex-citation t]
20162 "--"
20163 ["Template for BEAMER" (progn (require 'org-beamer)
20164 (org-insert-beamer-options-template)) t])
20165 "--"
20166 ("MobileOrg"
20167 ["Push Files and Views" org-mobile-push t]
20168 ["Get Captured and Flagged" org-mobile-pull t]
20169 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20170 "--"
20171 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20172 "--"
20173 ("Documentation"
20174 ["Show Version" org-version t]
20175 ["Info Documentation" org-info t])
20176 ("Customize"
20177 ["Browse Org Group" org-customize t]
20178 "--"
20179 ["Expand This Menu" org-create-customize-menu
20180 (fboundp 'customize-menu-create)])
20181 ["Send bug report" org-submit-bug-report t]
20182 "--"
20183 ("Refresh/Reload"
20184 ["Refresh setup current buffer" org-mode-restart t]
20185 ["Reload Org (after update)" org-reload t]
20186 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20189 (defun org-info (&optional node)
20190 "Read documentation for Org-mode in the info system.
20191 With optional NODE, go directly to that node."
20192 (interactive)
20193 (info (format "(org)%s" (or node ""))))
20195 ;;;###autoload
20196 (defun org-submit-bug-report ()
20197 "Submit a bug report on Org-mode via mail.
20199 Don't hesitate to report any problems or inaccurate documentation.
20201 If you don't have setup sending mail from (X)Emacs, please copy the
20202 output buffer into your mail program, as it gives us important
20203 information about your Org-mode version and configuration."
20204 (interactive)
20205 (require 'reporter)
20206 (org-load-modules-maybe)
20207 (org-require-autoloaded-modules)
20208 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20209 (reporter-submit-bug-report
20210 "emacs-orgmode@gnu.org"
20211 (org-version nil 'full)
20212 (let (list)
20213 (save-window-excursion
20214 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20215 (delete-other-windows)
20216 (erase-buffer)
20217 (insert "You are about to submit a bug report to the Org-mode mailing list.
20219 We would like to add your full Org-mode and Outline configuration to the
20220 bug report. This greatly simplifies the work of the maintainer and
20221 other experts on the mailing list.
20223 HOWEVER, some variables you have customized may contain private
20224 information. The names of customers, colleagues, or friends, might
20225 appear in the form of file names, tags, todo states, or search strings.
20226 If you answer yes to the prompt, you might want to check and remove
20227 such private information before sending the email.")
20228 (add-text-properties (point-min) (point-max) '(face org-warning))
20229 (when (yes-or-no-p "Include your Org-mode configuration ")
20230 (mapatoms
20231 (lambda (v)
20232 (and (boundp v)
20233 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20234 (or (and (symbol-value v)
20235 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20236 (and
20237 (get v 'custom-type) (get v 'standard-value)
20238 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20239 (push v list)))))
20240 (kill-buffer (get-buffer "*Warn about privacy*"))
20241 list))
20242 nil nil
20243 "Remember to cover the basics, that is, what you expected to happen and
20244 what in fact did happen. You don't know how to make a good report? See
20246 http://orgmode.org/manual/Feedback.html#Feedback
20248 Your bug report will be posted to the Org-mode mailing list.
20249 ------------------------------------------------------------------------")
20250 (save-excursion
20251 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20252 (replace-match "\\1Bug: \\3 [\\2]")))))
20255 (defun org-install-agenda-files-menu ()
20256 (let ((bl (buffer-list)))
20257 (save-excursion
20258 (while bl
20259 (set-buffer (pop bl))
20260 (if (derived-mode-p 'org-mode) (setq bl nil)))
20261 (when (derived-mode-p 'org-mode)
20262 (easy-menu-change
20263 '("Org") "File List for Agenda"
20264 (append
20265 (list
20266 ["Edit File List" (org-edit-agenda-file-list) t]
20267 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20268 ["Remove Current File from List" org-remove-file t]
20269 ["Cycle through agenda files" org-cycle-agenda-files t]
20270 ["Occur in all agenda files" org-occur-in-agenda-files t]
20271 "--")
20272 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20274 ;;;; Documentation
20276 (defun org-require-autoloaded-modules ()
20277 (interactive)
20278 (mapc 'require
20279 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20280 org-docbook org-exp org-html org-icalendar
20281 org-id org-latex
20282 org-publish org-remember org-table
20283 org-timer org-xoxo)))
20285 ;;;###autoload
20286 (defun org-reload (&optional uncompiled)
20287 "Reload all org lisp files.
20288 With prefix arg UNCOMPILED, load the uncompiled versions."
20289 (interactive "P")
20290 (require 'loadhist)
20291 (let* ((org-dir (org-find-library-dir "org"))
20292 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20293 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20294 (remove-re (mapconcat 'identity
20295 (mapcar (lambda (f) (concat "^" f "$"))
20296 (list (if (featurep 'xemacs)
20297 "org-colview"
20298 "org-colview-xemacs")
20299 "org" "org-loaddefs" "org-version"))
20300 "\\|"))
20301 (feats (delete-dups
20302 (mapcar 'file-name-sans-extension
20303 (mapcar 'file-name-nondirectory
20304 (delq nil
20305 (mapcar 'feature-file
20306 features))))))
20307 (lfeat (append
20308 (sort
20309 (setq feats
20310 (delq nil (mapcar
20311 (lambda (f)
20312 (if (and (string-match feature-re f)
20313 (not (string-match remove-re f)))
20314 f nil))
20315 feats)))
20316 'string-lessp)
20317 (list "org-version" "org")))
20318 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20319 load-uncore load-misses)
20320 (setq load-misses
20321 (delq 't
20322 (mapcar (lambda (f)
20323 (or (load (concat org-dir f) 'noerror nil nil 'mustsuffix)
20324 (and (string= org-dir contrib-dir)
20325 (load (concat contrib-dir f) 'noerror nil nil 'mustsuffix))
20326 (and (load (concat (org-find-library-dir f) f) 'noerror nil nil 'mustsuffix)
20327 (add-to-list 'load-uncore f 'append)
20330 lfeat)))
20331 (if load-uncore
20332 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20333 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20334 (if load-misses
20335 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20336 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20337 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20339 ;;;###autoload
20340 (defun org-customize ()
20341 "Call the customize function with org as argument."
20342 (interactive)
20343 (org-load-modules-maybe)
20344 (org-require-autoloaded-modules)
20345 (customize-browse 'org))
20347 (defun org-create-customize-menu ()
20348 "Create a full customization menu for Org-mode, insert it into the menu."
20349 (interactive)
20350 (org-load-modules-maybe)
20351 (org-require-autoloaded-modules)
20352 (if (fboundp 'customize-menu-create)
20353 (progn
20354 (easy-menu-change
20355 '("Org") "Customize"
20356 `(["Browse Org group" org-customize t]
20357 "--"
20358 ,(customize-menu-create 'org)
20359 ["Set" Custom-set t]
20360 ["Save" Custom-save t]
20361 ["Reset to Current" Custom-reset-current t]
20362 ["Reset to Saved" Custom-reset-saved t]
20363 ["Reset to Standard Settings" Custom-reset-standard t]))
20364 (message "\"Org\"-menu now contains full customization menu"))
20365 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20367 ;;;; Miscellaneous stuff
20369 ;;; Generally useful functions
20371 (defun org-get-at-bol (property)
20372 "Get text property PROPERTY at beginning of line."
20373 (get-text-property (point-at-bol) property))
20375 (defun org-find-text-property-in-string (prop s)
20376 "Return the first non-nil value of property PROP in string S."
20377 (or (get-text-property 0 prop s)
20378 (get-text-property (or (next-single-property-change 0 prop s) 0)
20379 prop s)))
20381 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20382 "Display the given MESSAGE as a warning."
20383 (if (fboundp 'display-warning)
20384 (display-warning 'org message
20385 (if (featurep 'xemacs) 'warning :warning))
20386 (let ((buf (get-buffer-create "*Org warnings*")))
20387 (with-current-buffer buf
20388 (goto-char (point-max))
20389 (insert "Warning (Org): " message)
20390 (unless (bolp)
20391 (newline)))
20392 (display-buffer buf)
20393 (sit-for 0))))
20395 (defun org-eval (form)
20396 "Eval FORM and return result."
20397 (condition-case error
20398 (eval form)
20399 (error (format "%%![Error: %s]" error))))
20401 (defun org-in-clocktable-p ()
20402 "Check if the cursor is in a clocktable."
20403 (let ((pos (point)) start)
20404 (save-excursion
20405 (end-of-line 1)
20406 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20407 (setq start (match-beginning 0))
20408 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20409 (>= (match-end 0) pos)
20410 start))))
20412 (defun org-in-commented-line ()
20413 "Is point in a line starting with `#'?"
20414 (equal (char-after (point-at-bol)) ?#))
20416 (defun org-in-indented-comment-line ()
20417 "Is point in a line starting with `#' after some white space?"
20418 (save-excursion
20419 (save-match-data
20420 (goto-char (point-at-bol))
20421 (looking-at "[ \t]*#"))))
20423 (defun org-in-verbatim-emphasis ()
20424 (save-match-data
20425 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20427 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20428 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20429 (if (and marker (marker-buffer marker)
20430 (buffer-live-p (marker-buffer marker)))
20431 (progn
20432 (org-pop-to-buffer-same-window (marker-buffer marker))
20433 (if (or (> marker (point-max)) (< marker (point-min)))
20434 (widen))
20435 (goto-char marker)
20436 (org-show-context 'org-goto))
20437 (if bookmark
20438 (bookmark-jump bookmark)
20439 (error "Cannot find location"))))
20441 (defun org-quote-csv-field (s)
20442 "Quote field for inclusion in CSV material."
20443 (if (string-match "[\",]" s)
20444 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20447 (defun org-force-self-insert (N)
20448 "Needed to enforce self-insert under remapping."
20449 (interactive "p")
20450 (self-insert-command N))
20452 (defun org-string-width (s)
20453 "Compute width of string, ignoring invisible characters.
20454 This ignores character with invisibility property `org-link', and also
20455 characters with property `org-cwidth', because these will become invisible
20456 upon the next fontification round."
20457 (let (b l)
20458 (when (or (eq t buffer-invisibility-spec)
20459 (assq 'org-link buffer-invisibility-spec))
20460 (while (setq b (text-property-any 0 (length s)
20461 'invisible 'org-link s))
20462 (setq s (concat (substring s 0 b)
20463 (substring s (or (next-single-property-change
20464 b 'invisible s) (length s)))))))
20465 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20466 (setq s (concat (substring s 0 b)
20467 (substring s (or (next-single-property-change
20468 b 'org-cwidth s) (length s))))))
20469 (setq l (string-width s) b -1)
20470 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20471 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20474 (defun org-shorten-string (s maxlength)
20475 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20476 If the string is shorter or has length MAXLENGTH, just return the
20477 original string. If it is longer, the functions finds a space in the
20478 string, breaks this string off at that locations and adds three dots
20479 as ellipsis. Including the ellipsis, the string will not be longer
20480 than MAXLENGTH. If finding a good breaking point in the string does
20481 not work, the string is just chopped off in the middle of a word
20482 if necessary."
20483 (if (<= (length s) maxlength)
20485 (let* ((n (max (- maxlength 4) 1))
20486 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20487 (if (string-match re s)
20488 (concat (match-string 1 s) "...")
20489 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20491 (defun org-get-indentation (&optional line)
20492 "Get the indentation of the current line, interpreting tabs.
20493 When LINE is given, assume it represents a line and compute its indentation."
20494 (if line
20495 (if (string-match "^ *" (org-remove-tabs line))
20496 (match-end 0))
20497 (save-excursion
20498 (beginning-of-line 1)
20499 (skip-chars-forward " \t")
20500 (current-column))))
20502 (defun org-get-string-indentation (s)
20503 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20504 (let ((n -1) (i 0) (w tab-width) c)
20505 (catch 'exit
20506 (while (< (setq n (1+ n)) (length s))
20507 (setq c (aref s n))
20508 (cond ((= c ?\ ) (setq i (1+ i)))
20509 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20510 (t (throw 'exit t)))))
20513 (defun org-remove-tabs (s &optional width)
20514 "Replace tabulators in S with spaces.
20515 Assumes that s is a single line, starting in column 0."
20516 (setq width (or width tab-width))
20517 (while (string-match "\t" s)
20518 (setq s (replace-match
20519 (make-string
20520 (- (* width (/ (+ (match-beginning 0) width) width))
20521 (match-beginning 0)) ?\ )
20522 t t s)))
20525 (defun org-fix-indentation (line ind)
20526 "Fix indentation in LINE.
20527 IND is a cons cell with target and minimum indentation.
20528 If the current indentation in LINE is smaller than the minimum,
20529 leave it alone. If it is larger than ind, set it to the target."
20530 (let* ((l (org-remove-tabs line))
20531 (i (org-get-indentation l))
20532 (i1 (car ind)) (i2 (cdr ind)))
20533 (if (>= i i2) (setq l (substring line i2)))
20534 (if (> i1 0)
20535 (concat (make-string i1 ?\ ) l)
20536 l)))
20538 (defun org-remove-indentation (code &optional n)
20539 "Remove the maximum common indentation from the lines in CODE.
20540 N may optionally be the number of spaces to remove."
20541 (with-temp-buffer
20542 (insert code)
20543 (org-do-remove-indentation n)
20544 (buffer-string)))
20546 (defun org-do-remove-indentation (&optional n)
20547 "Remove the maximum common indentation from the buffer."
20548 (untabify (point-min) (point-max))
20549 (let ((min 10000) re)
20550 (if n
20551 (setq min n)
20552 (goto-char (point-min))
20553 (while (re-search-forward "^ *[^ \n]" nil t)
20554 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20555 (unless (or (= min 0) (= min 10000))
20556 (setq re (format "^ \\{%d\\}" min))
20557 (goto-char (point-min))
20558 (while (re-search-forward re nil t)
20559 (replace-match "")
20560 (end-of-line 1))
20561 min)))
20563 (defun org-fill-template (template alist)
20564 "Find each %key of ALIST in TEMPLATE and replace it."
20565 (let ((case-fold-search nil)
20566 entry key value)
20567 (setq alist (sort (copy-sequence alist)
20568 (lambda (a b) (< (length (car a)) (length (car b))))))
20569 (while (setq entry (pop alist))
20570 (setq template
20571 (replace-regexp-in-string
20572 (concat "%" (regexp-quote (car entry)))
20573 (or (cdr entry) "") template t t)))
20574 template))
20576 (defun org-base-buffer (buffer)
20577 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20578 (if (not buffer)
20579 buffer
20580 (or (buffer-base-buffer buffer)
20581 buffer)))
20583 (defun org-trim (s)
20584 "Remove whitespace at beginning and end of string."
20585 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20586 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20589 (defun org-wrap (string &optional width lines)
20590 "Wrap string to either a number of lines, or a width in characters.
20591 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20592 that costs. If there is a word longer than WIDTH, the text is actually
20593 wrapped to the length of that word.
20594 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20595 many lines, whatever width that takes.
20596 The return value is a list of lines, without newlines at the end."
20597 (let* ((words (org-split-string string "[ \t\n]+"))
20598 (maxword (apply 'max (mapcar 'org-string-width words)))
20599 w ll)
20600 (cond (width
20601 (org-do-wrap words (max maxword width)))
20602 (lines
20603 (setq w maxword)
20604 (setq ll (org-do-wrap words maxword))
20605 (if (<= (length ll) lines)
20607 (setq ll words)
20608 (while (> (length ll) lines)
20609 (setq w (1+ w))
20610 (setq ll (org-do-wrap words w)))
20611 ll))
20612 (t (error "Cannot wrap this")))))
20614 (defun org-do-wrap (words width)
20615 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20616 (let (lines line)
20617 (while words
20618 (setq line (pop words))
20619 (while (and words (< (+ (length line) (length (car words))) width))
20620 (setq line (concat line " " (pop words))))
20621 (setq lines (push line lines)))
20622 (nreverse lines)))
20624 (defun org-split-string (string &optional separators)
20625 "Splits STRING into substrings at SEPARATORS.
20626 No empty strings are returned if there are matches at the beginning
20627 and end of string."
20628 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20629 (start 0)
20630 notfirst
20631 (list nil))
20632 (while (and (string-match rexp string
20633 (if (and notfirst
20634 (= start (match-beginning 0))
20635 (< start (length string)))
20636 (1+ start) start))
20637 (< (match-beginning 0) (length string)))
20638 (setq notfirst t)
20639 (or (eq (match-beginning 0) 0)
20640 (and (eq (match-beginning 0) (match-end 0))
20641 (eq (match-beginning 0) start))
20642 (setq list
20643 (cons (substring string start (match-beginning 0))
20644 list)))
20645 (setq start (match-end 0)))
20646 (or (eq start (length string))
20647 (setq list
20648 (cons (substring string start)
20649 list)))
20650 (nreverse list)))
20652 (defun org-quote-vert (s)
20653 "Replace \"|\" with \"\\vert\"."
20654 (while (string-match "|" s)
20655 (setq s (replace-match "\\vert" t t s)))
20658 (defun org-uuidgen-p (s)
20659 "Is S an ID created by UUIDGEN?"
20660 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20662 (defun org-in-src-block-p (&optional inside)
20663 "Whether point is in a code source block.
20664 When INSIDE is non-nil, don't consider we are within a src block
20665 when point is at #+BEGIN_SRC or #+END_SRC."
20666 (let ((case-fold-search t) ov)
20667 (or (and (setq ov (overlays-at (point)))
20668 (memq 'org-block-background
20669 (overlay-properties (car ov))))
20670 (and (not inside)
20671 (save-match-data
20672 (save-excursion
20673 (beginning-of-line)
20674 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20676 (defun org-context ()
20677 "Return a list of contexts of the current cursor position.
20678 If several contexts apply, all are returned.
20679 Each context entry is a list with a symbol naming the context, and
20680 two positions indicating start and end of the context. Possible
20681 contexts are:
20683 :headline anywhere in a headline
20684 :headline-stars on the leading stars in a headline
20685 :todo-keyword on a TODO keyword (including DONE) in a headline
20686 :tags on the TAGS in a headline
20687 :priority on the priority cookie in a headline
20688 :item on the first line of a plain list item
20689 :item-bullet on the bullet/number of a plain list item
20690 :checkbox on the checkbox in a plain list item
20691 :table in an org-mode table
20692 :table-special on a special filed in a table
20693 :table-table in a table.el table
20694 :clocktable in a clocktable
20695 :src-block in a source block
20696 :link on a hyperlink
20697 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20698 :target on a <<target>>
20699 :radio-target on a <<<radio-target>>>
20700 :latex-fragment on a LaTeX fragment
20701 :latex-preview on a LaTeX fragment with overlaid preview image
20703 This function expects the position to be visible because it uses font-lock
20704 faces as a help to recognize the following contexts: :table-special, :link,
20705 and :keyword."
20706 (let* ((f (get-text-property (point) 'face))
20707 (faces (if (listp f) f (list f)))
20708 (case-fold-search t)
20709 (p (point)) clist o)
20710 ;; First the large context
20711 (cond
20712 ((org-at-heading-p t)
20713 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20714 (when (progn
20715 (beginning-of-line 1)
20716 (looking-at org-todo-line-tags-regexp))
20717 (push (org-point-in-group p 1 :headline-stars) clist)
20718 (push (org-point-in-group p 2 :todo-keyword) clist)
20719 (push (org-point-in-group p 4 :tags) clist))
20720 (goto-char p)
20721 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20722 (if (looking-at "\\[#[A-Z0-9]\\]")
20723 (push (org-point-in-group p 0 :priority) clist)))
20725 ((org-at-item-p)
20726 (push (org-point-in-group p 2 :item-bullet) clist)
20727 (push (list :item (point-at-bol)
20728 (save-excursion (org-end-of-item) (point)))
20729 clist)
20730 (and (org-at-item-checkbox-p)
20731 (push (org-point-in-group p 0 :checkbox) clist)))
20733 ((org-at-table-p)
20734 (push (list :table (org-table-begin) (org-table-end)) clist)
20735 (if (memq 'org-formula faces)
20736 (push (list :table-special
20737 (previous-single-property-change p 'face)
20738 (next-single-property-change p 'face)) clist)))
20739 ((org-at-table-p 'any)
20740 (push (list :table-table) clist)))
20741 (goto-char p)
20743 (let ((case-fold-search t))
20744 ;; New the "medium" contexts: clocktables, source blocks
20745 (cond ((org-in-clocktable-p)
20746 (push (list :clocktable
20747 (and (or (looking-at "#\\+BEGIN: clocktable")
20748 (search-backward "#+BEGIN: clocktable" nil t))
20749 (match-beginning 0))
20750 (and (re-search-forward "#\\+END:?" nil t)
20751 (match-end 0))) clist))
20752 ((org-in-src-block-p)
20753 (push (list :src-block
20754 (and (or (looking-at "#\\+BEGIN_SRC")
20755 (search-backward "#+BEGIN_SRC" nil t))
20756 (match-beginning 0))
20757 (and (search-forward "#+END_SRC" nil t)
20758 (match-beginning 0))) clist))))
20759 (goto-char p)
20761 ;; Now the small context
20762 (cond
20763 ((org-at-timestamp-p)
20764 (push (org-point-in-group p 0 :timestamp) clist))
20765 ((memq 'org-link faces)
20766 (push (list :link
20767 (previous-single-property-change p 'face)
20768 (next-single-property-change p 'face)) clist))
20769 ((memq 'org-special-keyword faces)
20770 (push (list :keyword
20771 (previous-single-property-change p 'face)
20772 (next-single-property-change p 'face)) clist))
20773 ((org-at-target-p)
20774 (push (org-point-in-group p 0 :target) clist)
20775 (goto-char (1- (match-beginning 0)))
20776 (if (looking-at org-radio-target-regexp)
20777 (push (org-point-in-group p 0 :radio-target) clist))
20778 (goto-char p))
20779 ((setq o (car (delq nil
20780 (mapcar
20781 (lambda (x)
20782 (if (memq x org-latex-fragment-image-overlays) x))
20783 (overlays-at (point))))))
20784 (push (list :latex-fragment
20785 (overlay-start o) (overlay-end o)) clist)
20786 (push (list :latex-preview
20787 (overlay-start o) (overlay-end o)) clist))
20788 ((org-inside-LaTeX-fragment-p)
20789 ;; FIXME: positions wrong.
20790 (push (list :latex-fragment (point) (point)) clist)))
20792 (setq clist (nreverse (delq nil clist)))
20793 clist))
20795 ;; FIXME: Compare with at-regexp-p Do we need both?
20796 (defun org-in-regexp (re &optional nlines visually)
20797 "Check if point is inside a match of regexp.
20798 Normally only the current line is checked, but you can include NLINES extra
20799 lines both before and after point into the search.
20800 If VISUALLY is set, require that the cursor is not after the match but
20801 really on, so that the block visually is on the match."
20802 (catch 'exit
20803 (let ((pos (point))
20804 (eol (point-at-eol (+ 1 (or nlines 0))))
20805 (inc (if visually 1 0)))
20806 (save-excursion
20807 (beginning-of-line (- 1 (or nlines 0)))
20808 (while (re-search-forward re eol t)
20809 (if (and (<= (match-beginning 0) pos)
20810 (>= (+ inc (match-end 0)) pos))
20811 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20813 (defun org-at-regexp-p (regexp)
20814 "Is point inside a match of REGEXP in the current line?"
20815 (catch 'exit
20816 (save-excursion
20817 (let ((pos (point)) (end (point-at-eol)))
20818 (beginning-of-line 1)
20819 (while (re-search-forward regexp end t)
20820 (if (and (<= (match-beginning 0) pos)
20821 (>= (match-end 0) pos))
20822 (throw 'exit t)))
20823 nil))))
20825 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20826 "Non-nil when point is between matches of START-RE and END-RE.
20828 Also return a non-nil value when point is on one of the matches.
20830 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20831 buffer positions. Default values are the positions of headlines
20832 surrounding the point.
20834 The functions returns a cons cell whose car (resp. cdr) is the
20835 position before START-RE (resp. after END-RE)."
20836 (save-match-data
20837 (let ((pos (point))
20838 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20839 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20840 beg end)
20841 (save-excursion
20842 ;; Point is on a block when on START-RE or if START-RE can be
20843 ;; found before it...
20844 (and (or (org-at-regexp-p start-re)
20845 (re-search-backward start-re limit-up t))
20846 (setq beg (match-beginning 0))
20847 ;; ... and END-RE after it...
20848 (goto-char (match-end 0))
20849 (re-search-forward end-re limit-down t)
20850 (> (setq end (match-end 0)) pos)
20851 ;; ... without another START-RE in-between.
20852 (goto-char (match-beginning 0))
20853 (not (re-search-backward start-re (1+ beg) t))
20854 ;; Return value.
20855 (cons beg end))))))
20857 (defun org-in-block-p (names)
20858 "Non-nil when point belongs to a block whose name belongs to NAMES.
20860 NAMES is a list of strings containing names of blocks.
20862 Return first block name matched, or nil. Beware that in case of
20863 nested blocks, the returned name may not belong to the closest
20864 block from point."
20865 (save-match-data
20866 (catch 'exit
20867 (let ((case-fold-search t)
20868 (lim-up (save-excursion (outline-previous-heading)))
20869 (lim-down (save-excursion (outline-next-heading))))
20870 (mapc (lambda (name)
20871 (let ((n (regexp-quote name)))
20872 (when (org-between-regexps-p
20873 (concat "^[ \t]*#\\+begin_" n)
20874 (concat "^[ \t]*#\\+end_" n)
20875 lim-up lim-down)
20876 (throw 'exit n))))
20877 names))
20878 nil)))
20880 (defun org-occur-in-agenda-files (regexp &optional nlines)
20881 "Call `multi-occur' with buffers for all agenda files."
20882 (interactive "sOrg-files matching: \np")
20883 (let* ((files (org-agenda-files))
20884 (tnames (mapcar 'file-truename files))
20885 (extra org-agenda-text-search-extra-files)
20887 (when (eq (car extra) 'agenda-archives)
20888 (setq extra (cdr extra))
20889 (setq files (org-add-archive-files files)))
20890 (while (setq f (pop extra))
20891 (unless (member (file-truename f) tnames)
20892 (add-to-list 'files f 'append)
20893 (add-to-list 'tnames (file-truename f) 'append)))
20894 (multi-occur
20895 (mapcar (lambda (x)
20896 (with-current-buffer
20897 (or (get-file-buffer x) (find-file-noselect x))
20898 (widen)
20899 (current-buffer)))
20900 files)
20901 regexp)))
20903 (if (boundp 'occur-mode-find-occurrence-hook)
20904 ;; Emacs 23
20905 (add-hook 'occur-mode-find-occurrence-hook
20906 (lambda ()
20907 (when (derived-mode-p 'org-mode)
20908 (org-reveal))))
20909 ;; Emacs 22
20910 (defadvice occur-mode-goto-occurrence
20911 (after org-occur-reveal activate)
20912 (and (derived-mode-p 'org-mode) (org-reveal)))
20913 (defadvice occur-mode-goto-occurrence-other-window
20914 (after org-occur-reveal activate)
20915 (and (derived-mode-p 'org-mode) (org-reveal)))
20916 (defadvice occur-mode-display-occurrence
20917 (after org-occur-reveal activate)
20918 (when (derived-mode-p 'org-mode)
20919 (let ((pos (occur-mode-find-occurrence)))
20920 (with-current-buffer (marker-buffer pos)
20921 (save-excursion
20922 (goto-char pos)
20923 (org-reveal)))))))
20925 (defun org-occur-link-in-agenda-files ()
20926 "Create a link and search for it in the agendas.
20927 The link is not stored in `org-stored-links', it is just created
20928 for the search purpose."
20929 (interactive)
20930 (let ((link (condition-case nil
20931 (org-store-link nil)
20932 (error "Unable to create a link to here"))))
20933 (org-occur-in-agenda-files (regexp-quote link))))
20935 (defun org-uniquify (list)
20936 "Remove duplicate elements from LIST."
20937 (let (res)
20938 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20939 res))
20941 (defun org-delete-all (elts list)
20942 "Remove all elements in ELTS from LIST."
20943 (while elts
20944 (setq list (delete (pop elts) list)))
20945 list)
20947 (defun org-count (cl-item cl-seq)
20948 "Count the number of occurrences of ITEM in SEQ.
20949 Taken from `count' in cl-seq.el with all keyword arguments removed."
20950 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20951 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20952 (while (< cl-start cl-end)
20953 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20954 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20955 (setq cl-start (1+ cl-start)))
20956 cl-count))
20958 (defun org-remove-if (predicate seq)
20959 "Remove everything from SEQ that fulfills PREDICATE."
20960 (let (res e)
20961 (while seq
20962 (setq e (pop seq))
20963 (if (not (funcall predicate e)) (push e res)))
20964 (nreverse res)))
20966 (defun org-remove-if-not (predicate seq)
20967 "Remove everything from SEQ that does not fulfill PREDICATE."
20968 (let (res e)
20969 (while seq
20970 (setq e (pop seq))
20971 (if (funcall predicate e) (push e res)))
20972 (nreverse res)))
20974 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20975 "Reduce two-argument FUNCTION across SEQ.
20976 Taken from `reduce' in cl-seq.el with all keyword arguments but
20977 \":initial-value\" removed."
20978 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20979 (cadr (memq :initial-value cl-keys)))
20980 (cl-seq (pop cl-seq))
20981 (t (funcall cl-func)))))
20982 (while cl-seq
20983 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20984 cl-accum))
20986 (defun org-back-over-empty-lines ()
20987 "Move backwards over whitespace, to the beginning of the first empty line.
20988 Returns the number of empty lines passed."
20989 (let ((pos (point)))
20990 (if (cdr (assoc 'heading org-blank-before-new-entry))
20991 (skip-chars-backward " \t\n\r")
20992 (unless (eobp)
20993 (forward-line -1)))
20994 (beginning-of-line 2)
20995 (goto-char (min (point) pos))
20996 (count-lines (point) pos)))
20998 (defun org-skip-whitespace ()
20999 (skip-chars-forward " \t\n\r"))
21001 (defun org-point-in-group (point group &optional context)
21002 "Check if POINT is in match-group GROUP.
21003 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21004 match. If the match group does not exist or point is not inside it,
21005 return nil."
21006 (and (match-beginning group)
21007 (>= point (match-beginning group))
21008 (<= point (match-end group))
21009 (if context
21010 (list context (match-beginning group) (match-end group))
21011 t)))
21013 (defun org-switch-to-buffer-other-window (&rest args)
21014 "Switch to buffer in a second window on the current frame.
21015 In particular, do not allow pop-up frames.
21016 Returns the newly created buffer."
21017 (org-no-popups
21018 (apply 'switch-to-buffer-other-window args)))
21020 (defun org-combine-plists (&rest plists)
21021 "Create a single property list from all plists in PLISTS.
21022 The process starts by copying the first list, and then setting properties
21023 from the other lists. Settings in the last list are the most significant
21024 ones and overrule settings in the other lists."
21025 (let ((rtn (copy-sequence (pop plists)))
21026 p v ls)
21027 (while plists
21028 (setq ls (pop plists))
21029 (while ls
21030 (setq p (pop ls) v (pop ls))
21031 (setq rtn (plist-put rtn p v))))
21032 rtn))
21034 (defun org-replace-escapes (string table)
21035 "Replace %-escapes in STRING with values in TABLE.
21036 TABLE is an association list with keys like \"%a\" and string values.
21037 The sequences in STRING may contain normal field width and padding information,
21038 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21039 so values can contain further %-escapes if they are define later in TABLE."
21040 (let ((tbl (copy-alist table))
21041 (case-fold-search nil)
21042 (pchg 0)
21043 e re rpl)
21044 (while (setq e (pop tbl))
21045 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21046 (when (and (cdr e) (string-match re (cdr e)))
21047 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21048 (safe "SREF"))
21049 (add-text-properties 0 3 (list 'sref sref) safe)
21050 (setcdr e (replace-match safe t t (cdr e)))))
21051 (while (string-match re string)
21052 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21053 (cdr e)))
21054 (setq string (replace-match rpl t t string))))
21055 (while (setq pchg (next-property-change pchg string))
21056 (let ((sref (get-text-property pchg 'sref string)))
21057 (when (and sref (string-match "SREF" string pchg))
21058 (setq string (replace-match sref t t string)))))
21059 string))
21061 (defun org-sublist (list start end)
21062 "Return a section of LIST, from START to END.
21063 Counting starts at 1."
21064 (let (rtn (c start))
21065 (setq list (nthcdr (1- start) list))
21066 (while (and list (<= c end))
21067 (push (pop list) rtn)
21068 (setq c (1+ c)))
21069 (nreverse rtn)))
21071 (defun org-find-base-buffer-visiting (file)
21072 "Like `find-buffer-visiting' but always return the base buffer and
21073 not an indirect buffer."
21074 (let ((buf (or (get-file-buffer file)
21075 (find-buffer-visiting file))))
21076 (if buf
21077 (or (buffer-base-buffer buf) buf)
21078 nil)))
21080 (defun org-image-file-name-regexp (&optional extensions)
21081 "Return regexp matching the file names of images.
21082 If EXTENSIONS is given, only match these."
21083 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21084 (image-file-name-regexp)
21085 (let ((image-file-name-extensions
21086 (or extensions
21087 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21088 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21089 (concat "\\."
21090 (regexp-opt (nconc (mapcar 'upcase
21091 image-file-name-extensions)
21092 image-file-name-extensions)
21094 "\\'"))))
21096 (defun org-file-image-p (file &optional extensions)
21097 "Return non-nil if FILE is an image."
21098 (save-match-data
21099 (string-match (org-image-file-name-regexp extensions) file)))
21101 (defun org-get-cursor-date (&optional with-time)
21102 "Return the date at cursor in as a time.
21103 This works in the calendar and in the agenda, anywhere else it just
21104 returns the current time.
21105 If WITH-TIME is non-nil, returns the time of the event at point (in
21106 the agenda) or the current time of the day."
21107 (let (date day defd tp tm hod mod)
21108 (when with-time
21109 (setq tp (get-text-property (point) 'time))
21110 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21111 (setq hod (string-to-number (match-string 1 tp))
21112 mod (string-to-number (match-string 2 tp))))
21113 (or tp (setq hod (nth 2 (decode-time (current-time)))
21114 mod (nth 1 (decode-time (current-time))))))
21115 (cond
21116 ((eq major-mode 'calendar-mode)
21117 (setq date (calendar-cursor-to-date)
21118 defd (encode-time 0 (or mod 0) (or hod 0)
21119 (nth 1 date) (nth 0 date) (nth 2 date))))
21120 ((eq major-mode 'org-agenda-mode)
21121 (setq day (get-text-property (point) 'day))
21122 (if day
21123 (setq date (calendar-gregorian-from-absolute day)
21124 defd (encode-time 0 (or mod 0) (or hod 0)
21125 (nth 1 date) (nth 0 date) (nth 2 date))))))
21126 (or defd (current-time))))
21128 (defun org-mark-subtree (&optional up)
21129 "Mark the current subtree.
21130 This puts point at the start of the current subtree, and mark at
21131 the end. If a numeric prefix UP is given, move up into the
21132 hierarchy of headlines by UP levels before marking the subtree."
21133 (interactive "P")
21134 (org-with-limited-levels
21135 (cond ((org-at-heading-p) (beginning-of-line))
21136 ((org-before-first-heading-p) (error "Not in a subtree"))
21137 (t (outline-previous-visible-heading 1))))
21138 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21139 (if (org-called-interactively-p 'any)
21140 (call-interactively 'org-mark-element)
21141 (org-mark-element)))
21144 ;;; Macros
21146 ;; Macros are expanded with `org-macro-replace-all', which relies
21147 ;; internally on `org-macro-expand'.
21149 ;; Default templates for expansion are stored in the buffer-local
21150 ;; variable `org-macro-templates'. This variable is updated by
21151 ;; `org-macro-initialize-templates'.
21153 ;; Along with macros defined through #+MACRO: keyword, default
21154 ;; templates include the following hard-coded macros:
21155 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21156 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21158 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21159 ;; {{{title}}} will also be provided.
21162 (defvar org-macro-templates nil
21163 "Alist containing all macro templates in current buffer.
21164 Associations are in the shape of (NAME . TEMPLATE) where NAME
21165 stands for macro's name and template for its replacement value,
21166 both as strings. This is an internal variable. Do not set it
21167 directly, use instead:
21169 #+MACRO: name template")
21170 (make-variable-buffer-local 'org-macro-templates)
21172 (defun org-macro-expand (macro templates)
21173 "Return expanded MACRO, as a string.
21174 MACRO is an object, obtained, for example, with
21175 `org-element-context'. TEMPLATES is an alist of templates used
21176 for expansion. See `org-macro-templates' for a buffer-local
21177 default value. Return nil if no template was found."
21178 (let ((template
21179 ;; Macro names are case-insensitive.
21180 (cdr (assoc-string (org-element-property :key macro) templates t))))
21181 (when template
21182 (let ((value (replace-regexp-in-string
21183 "\\$[0-9]+"
21184 (lambda (arg)
21185 (or (nth (1- (string-to-number (substring arg 1)))
21186 (org-element-property :args macro))
21187 ;; No argument provided: remove
21188 ;; place-holder.
21189 ""))
21190 template)))
21191 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21192 (when (string-match "\\`(eval\\>" value)
21193 (setq value (eval (read value))))
21194 ;; Return string.
21195 (format "%s" (or value ""))))))
21197 (defun org-macro-replace-all (templates)
21198 "Replace all macros in current buffer by their expansion.
21199 TEMPLATES is an alist of templates used for expansion. See
21200 `org-macro-templates' for a buffer-local default value."
21201 (save-excursion
21202 (goto-char (point-min))
21203 (let (record)
21204 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21205 (let ((object (org-element-context)))
21206 (when (eq (org-element-type object) 'macro)
21207 (let* ((value (org-macro-expand object templates))
21208 (begin (org-element-property :begin object))
21209 (signature (list begin
21210 object
21211 (org-element-property :args object))))
21212 ;; Avoid circular dependencies by checking if the same
21213 ;; macro with the same arguments is expanded at the same
21214 ;; position twice.
21215 (if (member signature record)
21216 (error "Circular macro expansion: %s"
21217 (org-element-property :key object))
21218 (when value
21219 (push signature record)
21220 (delete-region
21221 begin
21222 ;; Preserve white spaces after the macro.
21223 (progn (goto-char (org-element-property :end object))
21224 (skip-chars-backward " \t")
21225 (point)))
21226 ;; Leave point before replacement in case of recursive
21227 ;; expansions.
21228 (save-excursion (insert value)))))))))))
21230 (defun org-macro-initialize-templates ()
21231 "Collect macro templates defined in current buffer.
21232 Templates are stored in buffer-local variable
21233 `org-macro-templates'. In addition to buffer-defined macros, the
21234 function installs the following ones: \"property\",
21235 \"time\". and, if the buffer is associated to a file,
21236 \"input-file\" and \"modification-time\"."
21237 (let ((case-fold-search t)
21238 (set-template
21239 (lambda (cell)
21240 ;; Add CELL to `org-macro-templates' if there's no
21241 ;; association matching its name already. Otherwise,
21242 ;; replace old association with the new one in that
21243 ;; variable.
21244 (let ((old-template (assoc (car cell) org-macro-templates)))
21245 (if old-template (setcdr old-template (cdr cell))
21246 (push cell org-macro-templates))))))
21247 ;; Install buffer-local macros.
21248 (org-with-wide-buffer
21249 (goto-char (point-min))
21250 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21251 (let ((element (org-element-at-point)))
21252 (when (eq (org-element-type element) 'keyword)
21253 (let ((value (org-element-property :value element)))
21254 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21255 (funcall set-template
21256 (cons (match-string 1 value)
21257 (or (match-string 2 value) "")))))))))
21258 ;; Install hard-coded macros.
21259 (mapc (lambda (cell) (funcall set-template cell))
21260 (list
21261 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21262 (cons "time" "(eval (format-time-string \"$1\"))")))
21263 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21264 (when (and visited-file (file-exists-p visited-file))
21265 (mapc (lambda (cell) (funcall set-template cell))
21266 (list
21267 (cons "input-file" (file-name-nondirectory visited-file))
21268 (cons "modification-time"
21269 (format "(eval (format-time-string \"$1\" '%s))"
21270 (prin1-to-string
21271 (nth 5 (file-attributes visited-file)))))))))))
21274 ;;; Indentation
21276 (defun org-indent-line ()
21277 "Indent line depending on context."
21278 (interactive)
21279 (let* ((pos (point))
21280 (itemp (org-at-item-p))
21281 (case-fold-search t)
21282 (org-drawer-regexp (or org-drawer-regexp "\000"))
21283 (inline-task-p (and (featurep 'org-inlinetask)
21284 (org-inlinetask-in-task-p)))
21285 (inline-re (and inline-task-p
21286 (org-inlinetask-outline-regexp)))
21287 column)
21288 (if (and orgstruct-is-++ (eq pos (point)))
21289 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21290 (indent-according-to-mode))
21291 (beginning-of-line 1)
21292 (cond
21293 ;; Headings
21294 ((looking-at org-outline-regexp) (setq column 0))
21295 ;; Included files
21296 ((looking-at "#\\+include:") (setq column 0))
21297 ;; Footnote definition
21298 ((looking-at org-footnote-definition-re) (setq column 0))
21299 ;; Literal examples
21300 ((looking-at "[ \t]*:\\( \\|$\\)")
21301 (setq column (org-get-indentation))) ; do nothing
21302 ;; Lists
21303 ((ignore-errors (goto-char (org-in-item-p)))
21304 (setq column (if itemp
21305 (org-get-indentation)
21306 (org-list-item-body-column (point))))
21307 (goto-char pos))
21308 ;; Drawers
21309 ((and (looking-at "[ \t]*:END:")
21310 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21311 (save-excursion
21312 (goto-char (1- (match-beginning 1)))
21313 (setq column (current-column))))
21314 ;; Special blocks
21315 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21316 (save-excursion
21317 (re-search-backward
21318 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21319 (setq column (org-get-indentation (match-string 0))))
21320 ((and (not (looking-at "[ \t]*#\\+begin_"))
21321 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21322 (save-excursion
21323 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21324 (setq column
21325 (cond ((equal (downcase (match-string 1)) "src")
21326 ;; src blocks: let `org-edit-src-exit' handle them
21327 (org-get-indentation))
21328 ((equal (downcase (match-string 1)) "example")
21329 (max (org-get-indentation)
21330 (org-get-indentation (match-string 0))))
21332 (org-get-indentation (match-string 0))))))
21333 ;; This line has nothing special, look at the previous relevant
21334 ;; line to compute indentation
21336 (beginning-of-line 0)
21337 (while (and (not (bobp))
21338 (not (looking-at org-drawer-regexp))
21339 ;; When point started in an inline task, do not move
21340 ;; above task starting line.
21341 (not (and inline-task-p (looking-at inline-re)))
21342 ;; Skip drawers, blocks, empty lines, verbatim,
21343 ;; comments, tables, footnotes definitions, lists,
21344 ;; inline tasks.
21345 (or (and (looking-at "[ \t]*:END:")
21346 (re-search-backward org-drawer-regexp nil t))
21347 (and (looking-at "[ \t]*#\\+end_")
21348 (re-search-backward "[ \t]*#\\+begin_"nil t))
21349 (looking-at "[ \t]*[\n:#|]")
21350 (looking-at org-footnote-definition-re)
21351 (and (ignore-errors (goto-char (org-in-item-p)))
21352 (goto-char
21353 (org-list-get-top-point (org-list-struct))))
21354 (and (not inline-task-p)
21355 (featurep 'org-inlinetask)
21356 (org-inlinetask-in-task-p)
21357 (or (org-inlinetask-goto-beginning) t))))
21358 (beginning-of-line 0))
21359 (cond
21360 ;; There was an heading above.
21361 ((looking-at "\\*+[ \t]+")
21362 (if (not org-adapt-indentation)
21363 (setq column 0)
21364 (goto-char (match-end 0))
21365 (setq column (current-column))))
21366 ;; A drawer had started and is unfinished
21367 ((looking-at org-drawer-regexp)
21368 (goto-char (1- (match-beginning 1)))
21369 (setq column (current-column)))
21370 ;; Else, nothing noticeable found: get indentation and go on.
21371 (t (setq column (org-get-indentation))))))
21372 ;; Now apply indentation and move cursor accordingly
21373 (goto-char pos)
21374 (if (<= (current-column) (current-indentation))
21375 (org-indent-line-to column)
21376 (save-excursion (org-indent-line-to column)))
21377 ;; Special polishing for properties, see `org-property-format'
21378 (setq column (current-column))
21379 (beginning-of-line 1)
21380 (if (looking-at
21381 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21382 (replace-match (concat (match-string 1)
21383 (format org-property-format
21384 (match-string 2) (match-string 3)))
21385 t t))
21386 (org-move-to-column column))))
21388 (defun org-indent-drawer ()
21389 "Indent the drawer at point."
21390 (interactive)
21391 (let ((p (point))
21392 (e (and (save-excursion (re-search-forward ":END:" nil t))
21393 (match-end 0)))
21394 (folded
21395 (save-excursion
21396 (end-of-line)
21397 (when (overlays-at (point))
21398 (member 'invisible (overlay-properties
21399 (car (overlays-at (point)))))))))
21400 (when folded (org-cycle))
21401 (indent-for-tab-command)
21402 (while (and (move-beginning-of-line 2) (< (point) e))
21403 (indent-for-tab-command))
21404 (goto-char p)
21405 (when folded (org-cycle)))
21406 (message "Drawer at point indented"))
21408 (defun org-indent-block ()
21409 "Indent the block at point."
21410 (interactive)
21411 (let ((p (point))
21412 (case-fold-search t)
21413 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21414 (match-end 0)))
21415 (folded
21416 (save-excursion
21417 (end-of-line)
21418 (when (overlays-at (point))
21419 (member 'invisible (overlay-properties
21420 (car (overlays-at (point)))))))))
21421 (when folded (org-cycle))
21422 (indent-for-tab-command)
21423 (while (and (move-beginning-of-line 2) (< (point) e))
21424 (indent-for-tab-command))
21425 (goto-char p)
21426 (when folded (org-cycle)))
21427 (message "Block at point indented"))
21429 (defun org-indent-region (start end)
21430 "Indent region."
21431 (interactive "r")
21432 (save-excursion
21433 (let ((line-end (org-current-line end)))
21434 (goto-char start)
21435 (while (< (org-current-line) line-end)
21436 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21437 (t (call-interactively 'org-indent-line)))
21438 (move-beginning-of-line 2)))))
21441 ;;; Filling
21443 ;; We use our own fill-paragraph and auto-fill functions.
21445 ;; `org-fill-paragraph' relies on adaptive filling and context
21446 ;; checking. Appropriate `fill-prefix' is computed with
21447 ;; `org-adaptive-fill-function'.
21449 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21450 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21451 ;; `org-adaptive-fill-function' value. Internally,
21452 ;; `org-comment-line-break-function' breaks the line.
21454 ;; `org-setup-filling' installs filling and auto-filling related
21455 ;; variables during `org-mode' initialization.
21457 (defun org-setup-filling ()
21458 (interactive)
21459 ;; Prevent auto-fill from inserting unwanted new items.
21460 (when (boundp 'fill-nobreak-predicate)
21461 (org-set-local
21462 'fill-nobreak-predicate
21463 (org-uniquify
21464 (append fill-nobreak-predicate
21465 '(org-fill-paragraph-separate-nobreak-p
21466 org-fill-line-break-nobreak-p)))))
21467 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21468 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21469 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21470 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21472 (defvar org-element-paragraph-separate) ; org-element.el
21473 (defun org-fill-paragraph-separate-nobreak-p ()
21474 "Non-nil when a line break at point would insert a new item."
21475 (looking-at (substring org-element-paragraph-separate 1)))
21477 (defun org-fill-line-break-nobreak-p ()
21478 "Non-nil when a line break at point would create an Org line break."
21479 (save-excursion
21480 (skip-chars-backward "[ \t]")
21481 (skip-chars-backward "\\\\")
21482 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21484 (declare-function message-in-body-p "message" ())
21485 (defun org-adaptive-fill-function ()
21486 "Compute a fill prefix for the current line.
21487 Return fill prefix, as a string, or nil if current line isn't
21488 meant to be filled."
21489 (org-with-wide-buffer
21490 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21491 ;; FIXME: This is really the job of orgstruct++-mode
21492 (let* ((p (line-beginning-position))
21493 (element (save-excursion (beginning-of-line)
21494 (org-element-at-point)))
21495 (type (org-element-type element))
21496 (post-affiliated (org-element-property :post-affiliated element)))
21497 (unless (and post-affiliated (< p post-affiliated))
21498 (case type
21499 (comment (looking-at "[ \t]*# ?") (match-string 0))
21500 (footnote-definition "")
21501 ((item plain-list)
21502 (make-string (org-list-item-body-column
21503 (or post-affiliated
21504 (org-element-property :begin element)))
21505 ? ))
21506 (paragraph
21507 ;; Fill prefix is usually the same as the current line,
21508 ;; except if the paragraph is at the beginning of an item.
21509 (let ((parent (org-element-property :parent element)))
21510 (cond ((eq (org-element-type parent) 'item)
21511 (make-string (org-list-item-body-column
21512 (org-element-property :begin parent))
21513 ? ))
21514 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21515 (match-string 0))
21516 (t ""))))
21517 (comment-block
21518 ;; Only fill contents if P is within block boundaries.
21519 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21520 (forward-line)
21521 (point)))
21522 (cend (save-excursion
21523 (goto-char (org-element-property :end element))
21524 (skip-chars-backward " \r\t\n")
21525 (line-beginning-position))))
21526 (when (and (>= p cbeg) (< p cend))
21527 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21528 (match-string 0)
21529 ""))))))))))
21531 (declare-function message-goto-body "message" ())
21532 (defvar message-cite-prefix-regexp) ; From message.el
21533 (defvar org-element-all-objects) ; From org-element.el
21534 (defun org-fill-paragraph (&optional justify)
21535 "Fill element at point, when applicable.
21537 This function only applies to comment blocks, comments, example
21538 blocks and paragraphs. Also, as a special case, re-align table
21539 when point is at one.
21541 If JUSTIFY is non-nil (interactively, with prefix argument),
21542 justify as well. If `sentence-end-double-space' is non-nil, then
21543 period followed by one space does not end a sentence, so don't
21544 break a line there. The variable `fill-column' controls the
21545 width for filling.
21547 For convenience, when point is at a plain list, an item or
21548 a footnote definition, try to fill the first paragraph within."
21549 (interactive)
21550 (if (and (derived-mode-p 'message-mode)
21551 (or (not (message-in-body-p))
21552 (save-excursion (move-beginning-of-line 1)
21553 (looking-at message-cite-prefix-regexp))))
21554 ;; First ensure filling is correct in message-mode.
21555 (let ((fill-paragraph-function
21556 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21557 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21558 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21559 (paragraph-separate
21560 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21561 (fill-paragraph nil))
21562 (save-excursion
21563 ;; Move to end of line in order to get the first paragraph
21564 ;; within a plain list or a footnote definition.
21565 (end-of-line)
21566 (let ((element (org-element-at-point)))
21567 ;; First check if point is in a blank line at the beginning of
21568 ;; the buffer. In that case, ignore filling.
21569 (if (< (point) (org-element-property :begin element)) t
21570 (case (org-element-type element)
21571 ;; Use major mode filling function is src blocks.
21572 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21573 ;; Align Org tables, leave table.el tables as-is.
21574 (table-row (org-table-align) t)
21575 (table
21576 (when (eq (org-element-property :type element) 'org)
21577 (org-table-align))
21579 (paragraph
21580 ;; Paragraphs may contain `line-break' type objects.
21581 (let ((beg (max (point-min)
21582 (org-element-property :contents-begin element)))
21583 (end (min (point-max)
21584 (org-element-property :contents-end element))))
21585 ;; Do nothing if point is at an affiliated keyword.
21586 (if (< (point) beg) t
21587 (when (derived-mode-p 'message-mode)
21588 ;; In `message-mode', do not fill following
21589 ;; citation in current paragraph nor text before
21590 ;; message body.
21591 (let ((body-start (save-excursion (message-goto-body))))
21592 (when body-start (setq beg (max body-start beg))))
21593 (when (save-excursion
21594 (re-search-forward
21595 (concat "^" message-cite-prefix-regexp) end t))
21596 (setq end (match-beginning 0))))
21597 ;; Fill paragraph, taking line breaks into
21598 ;; consideration. For that, slice the paragraph
21599 ;; using line breaks as separators, and fill the
21600 ;; parts in reverse order to avoid messing with
21601 ;; markers.
21602 (save-excursion
21603 (goto-char end)
21604 (mapc
21605 (lambda (pos)
21606 (fill-region-as-paragraph pos (point) justify)
21607 (goto-char pos))
21608 ;; Find the list of ending positions for line
21609 ;; breaks in the current paragraph. Add paragraph
21610 ;; beginning to include first slice.
21611 (nreverse
21612 (cons
21614 (org-element-map
21615 (org-element--parse-objects
21616 beg end nil org-element-all-objects)
21617 'line-break
21618 (lambda (lb) (org-element-property :end lb)))))))
21619 t)))
21620 ;; Contents of `comment-block' type elements should be
21621 ;; filled as plain text, but only if point is within block
21622 ;; markers.
21623 (comment-block
21624 (let* ((case-fold-search t)
21625 (beg (save-excursion
21626 (goto-char (org-element-property :begin element))
21627 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21628 (forward-line)
21629 (point)))
21630 (end (save-excursion
21631 (goto-char (org-element-property :end element))
21632 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21633 (line-beginning-position))))
21634 (when (and (>= (point) beg) (< (point) end))
21635 (fill-region-as-paragraph
21636 (save-excursion
21637 (end-of-line)
21638 (re-search-backward "^[ \t]*$" beg 'move)
21639 (line-beginning-position))
21640 (save-excursion
21641 (beginning-of-line)
21642 (re-search-forward "^[ \t]*$" end 'move)
21643 (line-beginning-position))
21644 justify)))
21646 ;; Fill comments.
21647 (comment (fill-comment-paragraph justify))
21648 ;; Ignore every other element.
21649 (otherwise t)))))))
21651 (defun org-auto-fill-function ()
21652 "Auto-fill function."
21653 ;; Check if auto-filling is meaningful.
21654 (let ((fc (current-fill-column)))
21655 (when (and fc (> (current-column) fc))
21656 (let* ((fill-prefix (org-adaptive-fill-function))
21657 ;; Enforce empty fill prefix, if required. Otherwise, it
21658 ;; will be computed again.
21659 (adaptive-fill-mode (not (equal fill-prefix ""))))
21660 (when fill-prefix (do-auto-fill))))))
21662 (defun org-comment-line-break-function (&optional soft)
21663 "Break line at point and indent, continuing comment if within one.
21664 The inserted newline is marked hard if variable
21665 `use-hard-newlines' is true, unless optional argument SOFT is
21666 non-nil."
21667 (if soft (insert-and-inherit ?\n) (newline 1))
21668 (save-excursion (forward-char -1) (delete-horizontal-space))
21669 (delete-horizontal-space)
21670 (indent-to-left-margin)
21671 (insert-before-markers-and-inherit fill-prefix))
21674 ;;; Comments
21676 ;; Org comments syntax is quite complex. It requires the entire line
21677 ;; to be just a comment. Also, even with the right syntax at the
21678 ;; beginning of line, some some elements (i.e. verse-block or
21679 ;; example-block) don't accept comments. Usual Emacs comment commands
21680 ;; cannot cope with those requirements. Therefore, Org replaces them.
21682 ;; Org still relies on `comment-dwim', but cannot trust
21683 ;; `comment-only-p'. So, `comment-region-function' and
21684 ;; `uncomment-region-function' both point
21685 ;; to`org-comment-or-uncomment-region'. Eventually,
21686 ;; `org-insert-comment' takes care of insertion of comments at the
21687 ;; beginning of line.
21689 ;; `org-setup-comments-handling' install comments related variables
21690 ;; during `org-mode' initialization.
21692 (defun org-setup-comments-handling ()
21693 (interactive)
21694 (org-set-local 'comment-use-syntax nil)
21695 (org-set-local 'comment-start "# ")
21696 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21697 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21698 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21699 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21701 (defun org-insert-comment ()
21702 "Insert an empty comment above current line.
21703 If the line is empty, insert comment at its beginning."
21704 (beginning-of-line)
21705 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21706 (org-indent-line)
21707 (insert "# "))
21709 (defvar comment-empty-lines) ; From newcomment.el.
21710 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21711 "Comment or uncomment each non-blank line in the region.
21712 Uncomment each non-blank line between BEG and END if it only
21713 contains commented lines. Otherwise, comment them."
21714 (save-restriction
21715 ;; Restrict region
21716 (narrow-to-region (save-excursion (goto-char beg)
21717 (skip-chars-forward " \r\t\n" end)
21718 (line-beginning-position))
21719 (save-excursion (goto-char end)
21720 (skip-chars-backward " \r\t\n" beg)
21721 (line-end-position)))
21722 (let ((uncommentp
21723 ;; UNCOMMENTP is non-nil when every non blank line between
21724 ;; BEG and END is a comment.
21725 (save-excursion
21726 (goto-char (point-min))
21727 (while (and (not (eobp))
21728 (let ((element (org-element-at-point)))
21729 (and (eq (org-element-type element) 'comment)
21730 (goto-char (min (point-max)
21731 (org-element-property
21732 :end element)))))))
21733 (eobp))))
21734 (if uncommentp
21735 ;; Only blank lines and comments in region: uncomment it.
21736 (save-excursion
21737 (goto-char (point-min))
21738 (while (not (eobp))
21739 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21740 (replace-match "" nil nil nil 1))
21741 (forward-line)))
21742 ;; Comment each line in region.
21743 (let ((min-indent (point-max)))
21744 ;; First find the minimum indentation across all lines.
21745 (save-excursion
21746 (goto-char (point-min))
21747 (while (and (not (eobp)) (not (zerop min-indent)))
21748 (unless (looking-at "[ \t]*$")
21749 (setq min-indent (min min-indent (current-indentation))))
21750 (forward-line)))
21751 ;; Then loop over all lines.
21752 (save-excursion
21753 (goto-char (point-min))
21754 (while (not (eobp))
21755 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21756 (org-move-to-column min-indent t)
21757 (insert comment-start))
21758 (forward-line))))))))
21761 ;;; Other stuff.
21763 (defun org-toggle-fixed-width-section (arg)
21764 "Toggle the fixed-width export.
21765 If there is no active region, the QUOTE keyword at the current headline is
21766 inserted or removed. When present, it causes the text between this headline
21767 and the next to be exported as fixed-width text, and unmodified.
21768 If there is an active region, this command adds or removes a colon as the
21769 first character of this line. If the first character of a line is a colon,
21770 this line is also exported in fixed-width font."
21771 (interactive "P")
21772 (let* ((cc 0)
21773 (regionp (org-region-active-p))
21774 (beg (if regionp (region-beginning) (point)))
21775 (end (if regionp (region-end)))
21776 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21777 (case-fold-search nil)
21778 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21779 off)
21780 (if regionp
21781 (save-excursion
21782 (goto-char beg)
21783 (setq cc (current-column))
21784 (beginning-of-line 1)
21785 (setq off (looking-at re))
21786 (while (> nlines 0)
21787 (setq nlines (1- nlines))
21788 (beginning-of-line 1)
21789 (cond
21790 (arg
21791 (org-move-to-column cc t)
21792 (insert ": \n")
21793 (forward-line -1))
21794 ((and off (looking-at re))
21795 (replace-match "" t t nil 1))
21796 ((not off) (org-move-to-column cc t) (insert ": ")))
21797 (forward-line 1)))
21798 (save-excursion
21799 (org-back-to-heading)
21800 (cond
21801 ((looking-at (format org-heading-keyword-regexp-format
21802 org-quote-string))
21803 (goto-char (match-end 1))
21804 (looking-at (concat " +" org-quote-string))
21805 (replace-match "" t t)
21806 (when (eolp) (insert " ")))
21807 ((looking-at org-outline-regexp)
21808 (goto-char (match-end 0))
21809 (insert org-quote-string " ")))))))
21811 (defun org-reftex-citation ()
21812 "Use reftex-citation to insert a citation into the buffer.
21813 This looks for a line like
21815 #+BIBLIOGRAPHY: foo plain option:-d
21817 and derives from it that foo.bib is the bibliography file relevant
21818 for this document. It then installs the necessary environment for RefTeX
21819 to work in this buffer and calls `reftex-citation' to insert a citation
21820 into the buffer.
21822 Export of such citations to both LaTeX and HTML is handled by the contributed
21823 package org-exp-bibtex by Taru Karttunen."
21824 (interactive)
21825 (let ((reftex-docstruct-symbol 'rds)
21826 (reftex-cite-format "\\cite{%l}")
21827 rds bib)
21828 (save-excursion
21829 (save-restriction
21830 (widen)
21831 (let ((case-fold-search t)
21832 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21833 (if (not (save-excursion
21834 (or (re-search-forward re nil t)
21835 (re-search-backward re nil t))))
21836 (error "No bibliography defined in file")
21837 (setq bib (concat (match-string 1) ".bib")
21838 rds (list (list 'bib bib)))))))
21839 (call-interactively 'reftex-citation)))
21841 ;;;; Functions extending outline functionality
21843 (defun org-beginning-of-line (&optional arg)
21844 "Go to the beginning of the current line. If that is invisible, continue
21845 to a visible line beginning. This makes the function of C-a more intuitive.
21846 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21847 first attempt, and only move to after the tags when the cursor is already
21848 beyond the end of the headline."
21849 (interactive "P")
21850 (let ((pos (point))
21851 (special (if (consp org-special-ctrl-a/e)
21852 (car org-special-ctrl-a/e)
21853 org-special-ctrl-a/e))
21854 refpos)
21855 (if (org-bound-and-true-p visual-line-mode)
21856 (beginning-of-visual-line 1)
21857 (beginning-of-line 1))
21858 (if (and arg (fboundp 'move-beginning-of-line))
21859 (call-interactively 'move-beginning-of-line)
21860 (if (bobp)
21862 (backward-char 1)
21863 (if (org-truely-invisible-p)
21864 (while (and (not (bobp)) (org-truely-invisible-p))
21865 (backward-char 1)
21866 (beginning-of-line 1))
21867 (forward-char 1))))
21868 (when special
21869 (cond
21870 ((and (looking-at org-complex-heading-regexp)
21871 (= (char-after (match-end 1)) ?\ ))
21872 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21873 (point-at-eol)))
21874 (goto-char
21875 (if (eq special t)
21876 (cond ((> pos refpos) refpos)
21877 ((= pos (point)) refpos)
21878 (t (point)))
21879 (cond ((> pos (point)) (point))
21880 ((not (eq last-command this-command)) (point))
21881 (t refpos)))))
21882 ((org-at-item-p)
21883 ;; Being at an item and not looking at an the item means point
21884 ;; was previously moved to beginning of a visual line, which
21885 ;; doesn't contain the item. Therefore, do nothing special,
21886 ;; just stay here.
21887 (when (looking-at org-list-full-item-re)
21888 ;; Set special position at first white space character after
21889 ;; bullet, and check-box, if any.
21890 (let ((after-bullet
21891 (let ((box (match-end 3)))
21892 (if (not box) (match-end 1)
21893 (let ((after (char-after box)))
21894 (if (and after (= after ? )) (1+ box) box))))))
21895 ;; Special case: Move point to special position when
21896 ;; currently after it or at beginning of line.
21897 (if (eq special t)
21898 (when (or (> pos after-bullet) (= (point) pos))
21899 (goto-char after-bullet))
21900 ;; Reversed case: Move point to special position when
21901 ;; point was already at beginning of line and command is
21902 ;; repeated.
21903 (when (and (= (point) pos) (eq last-command this-command))
21904 (goto-char after-bullet))))))))
21905 (org-no-warnings
21906 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21908 (defun org-end-of-line (&optional arg)
21909 "Go to the end of the line.
21910 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21911 tags on the first attempt, and only move to after the tags when
21912 the cursor is already beyond the end of the headline."
21913 (interactive "P")
21914 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21915 org-special-ctrl-a/e))
21916 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21917 'end-of-visual-line)
21918 ((fboundp 'move-end-of-line) 'move-end-of-line)
21919 (t 'end-of-line))))
21920 (if (or (not special) arg) (call-interactively move-fun)
21921 (let* ((element (save-excursion (beginning-of-line)
21922 (org-element-at-point)))
21923 (type (org-element-type element)))
21924 (cond
21925 ((memq type '(headline inlinetask))
21926 (let ((pos (point)))
21927 (beginning-of-line 1)
21928 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21929 (if (eq special t)
21930 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21931 (goto-char (match-beginning 1))
21932 (goto-char (match-end 0)))
21933 (if (or (< pos (match-end 0))
21934 (not (eq this-command last-command)))
21935 (goto-char (match-end 0))
21936 (goto-char (match-beginning 1))))
21937 (call-interactively move-fun))))
21938 ((org-element-property :hiddenp element)
21939 ;; If element is hidden, `move-end-of-line' would put point
21940 ;; after it. Use `end-of-line' to stay on current line.
21941 (call-interactively 'end-of-line))
21942 (t (call-interactively move-fun)))))
21943 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21945 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21946 (define-key org-mode-map "\C-e" 'org-end-of-line)
21948 (defun org-backward-sentence (&optional arg)
21949 "Go to beginning of sentence, or beginning of table field.
21950 This will call `backward-sentence' or `org-table-beginning-of-field',
21951 depending on context."
21952 (interactive "P")
21953 (cond
21954 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21955 (t (call-interactively 'backward-sentence))))
21957 (defun org-forward-sentence (&optional arg)
21958 "Go to end of sentence, or end of table field.
21959 This will call `forward-sentence' or `org-table-end-of-field',
21960 depending on context."
21961 (interactive "P")
21962 (cond
21963 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21964 (t (call-interactively 'forward-sentence))))
21966 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21967 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21969 (defun org-kill-line (&optional arg)
21970 "Kill line, to tags or end of line."
21971 (interactive "P")
21972 (cond
21973 ((or (not org-special-ctrl-k)
21974 (bolp)
21975 (not (org-at-heading-p)))
21976 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21977 org-ctrl-k-protect-subtree)
21978 (if (or (eq org-ctrl-k-protect-subtree 'error)
21979 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21980 (error "C-k aborted - would kill hidden subtree")))
21981 (call-interactively
21982 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21983 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21984 (kill-region (point) (match-beginning 1))
21985 (org-set-tags nil t))
21986 (t (kill-region (point) (point-at-eol)))))
21988 (define-key org-mode-map "\C-k" 'org-kill-line)
21990 (defun org-yank (&optional arg)
21991 "Yank. If the kill is a subtree, treat it specially.
21992 This command will look at the current kill and check if is a single
21993 subtree, or a series of subtrees[1]. If it passes the test, and if the
21994 cursor is at the beginning of a line or after the stars of a currently
21995 empty headline, then the yank is handled specially. How exactly depends
21996 on the value of the following variables, both set by default.
21998 org-yank-folded-subtrees
21999 When set, the subtree(s) will be folded after insertion, but only
22000 if doing so would now swallow text after the yanked text.
22002 org-yank-adjusted-subtrees
22003 When set, the subtree will be promoted or demoted in order to
22004 fit into the local outline tree structure, which means that the level
22005 will be adjusted so that it becomes the smaller one of the two
22006 *visible* surrounding headings.
22008 Any prefix to this command will cause `yank' to be called directly with
22009 no special treatment. In particular, a simple \\[universal-argument] prefix \
22010 will just
22011 plainly yank the text as it is.
22013 \[1] The test checks if the first non-white line is a heading
22014 and if there are no other headings with fewer stars."
22015 (interactive "P")
22016 (org-yank-generic 'yank arg))
22018 (defun org-yank-generic (command arg)
22019 "Perform some yank-like command.
22021 This function implements the behavior described in the `org-yank'
22022 documentation. However, it has been generalized to work for any
22023 interactive command with similar behavior."
22025 ;; pretend to be command COMMAND
22026 (setq this-command command)
22028 (if arg
22029 (call-interactively command)
22031 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22032 (and (org-kill-is-subtree-p)
22033 (or (bolp)
22034 (and (looking-at "[ \t]*$")
22035 (string-match
22036 "\\`\\*+\\'"
22037 (buffer-substring (point-at-bol) (point)))))))
22038 swallowp)
22039 (cond
22040 ((and subtreep org-yank-folded-subtrees)
22041 (let ((beg (point))
22042 end)
22043 (if (and subtreep org-yank-adjusted-subtrees)
22044 (org-paste-subtree nil nil 'for-yank)
22045 (call-interactively command))
22047 (setq end (point))
22048 (goto-char beg)
22049 (when (and (bolp) subtreep
22050 (not (setq swallowp
22051 (org-yank-folding-would-swallow-text beg end))))
22052 (org-with-limited-levels
22053 (or (looking-at org-outline-regexp)
22054 (re-search-forward org-outline-regexp-bol end t))
22055 (while (and (< (point) end) (looking-at org-outline-regexp))
22056 (hide-subtree)
22057 (org-cycle-show-empty-lines 'folded)
22058 (condition-case nil
22059 (outline-forward-same-level 1)
22060 (error (goto-char end))))))
22061 (when swallowp
22062 (message
22063 "Inserted text not folded because that would swallow text"))
22065 (goto-char end)
22066 (skip-chars-forward " \t\n\r")
22067 (beginning-of-line 1)
22068 (push-mark beg 'nomsg)))
22069 ((and subtreep org-yank-adjusted-subtrees)
22070 (let ((beg (point-at-bol)))
22071 (org-paste-subtree nil nil 'for-yank)
22072 (push-mark beg 'nomsg)))
22074 (call-interactively command))))))
22076 (defun org-yank-folding-would-swallow-text (beg end)
22077 "Would hide-subtree at BEG swallow any text after END?"
22078 (let (level)
22079 (org-with-limited-levels
22080 (save-excursion
22081 (goto-char beg)
22082 (when (or (looking-at org-outline-regexp)
22083 (re-search-forward org-outline-regexp-bol end t))
22084 (setq level (org-outline-level)))
22085 (goto-char end)
22086 (skip-chars-forward " \t\r\n\v\f")
22087 (if (or (eobp)
22088 (and (bolp) (looking-at org-outline-regexp)
22089 (<= (org-outline-level) level)))
22090 nil ; Nothing would be swallowed
22091 t))))) ; something would swallow
22093 (define-key org-mode-map "\C-y" 'org-yank)
22095 (defun org-truely-invisible-p ()
22096 "Check if point is at a character currently not visible.
22097 This version does not only check the character property, but also
22098 `visible-mode'."
22099 ;; Early versions of noutline don't have `outline-invisible-p'.
22100 (if (org-bound-and-true-p visible-mode)
22102 (outline-invisible-p)))
22104 (defun org-invisible-p2 ()
22105 "Check if point is at a character currently not visible."
22106 (save-excursion
22107 (if (and (eolp) (not (bobp))) (backward-char 1))
22108 ;; Early versions of noutline don't have `outline-invisible-p'.
22109 (outline-invisible-p)))
22111 (defun org-back-to-heading (&optional invisible-ok)
22112 "Call `outline-back-to-heading', but provide a better error message."
22113 (condition-case nil
22114 (outline-back-to-heading invisible-ok)
22115 (error (error "Before first headline at position %d in buffer %s"
22116 (point) (current-buffer)))))
22118 (defun org-before-first-heading-p ()
22119 "Before first heading?"
22120 (save-excursion
22121 (end-of-line)
22122 (null (re-search-backward org-outline-regexp-bol nil t))))
22124 (defun org-at-heading-p (&optional ignored)
22125 (outline-on-heading-p t))
22126 ;; Compatibility alias with Org versions < 7.8.03
22127 (defalias 'org-on-heading-p 'org-at-heading-p)
22129 (defun org-at-comment-p nil
22130 "Is cursor in a line starting with a # character?"
22131 (save-excursion
22132 (beginning-of-line)
22133 (looking-at "^#")))
22135 (defun org-at-drawer-p nil
22136 "Is cursor at a drawer keyword?"
22137 (save-excursion
22138 (move-beginning-of-line 1)
22139 (looking-at org-drawer-regexp)))
22141 (defun org-at-block-p nil
22142 "Is cursor at a block keyword?"
22143 (save-excursion
22144 (move-beginning-of-line 1)
22145 (looking-at org-block-regexp)))
22147 (defun org-point-at-end-of-empty-headline ()
22148 "If point is at the end of an empty headline, return t, else nil.
22149 If the heading only contains a TODO keyword, it is still still considered
22150 empty."
22151 (and (looking-at "[ \t]*$")
22152 (when org-todo-line-regexp
22153 (save-excursion
22154 (beginning-of-line 1)
22155 (let ((case-fold-search nil))
22156 (looking-at org-todo-line-regexp)
22157 (string= (match-string 3) ""))))))
22159 (defun org-at-heading-or-item-p ()
22160 (or (org-at-heading-p) (org-at-item-p)))
22162 (defun org-at-target-p ()
22163 (or (org-in-regexp org-radio-target-regexp)
22164 (org-in-regexp org-target-regexp)))
22165 ;; Compatibility alias with Org versions < 7.8.03
22166 (defalias 'org-on-target-p 'org-at-target-p)
22168 (defun org-up-heading-all (arg)
22169 "Move to the heading line of which the present line is a subheading.
22170 This function considers both visible and invisible heading lines.
22171 With argument, move up ARG levels."
22172 (if (fboundp 'outline-up-heading-all)
22173 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22174 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22176 (defun org-up-heading-safe ()
22177 "Move to the heading line of which the present line is a subheading.
22178 This version will not throw an error. It will return the level of the
22179 headline found, or nil if no higher level is found.
22181 Also, this function will be a lot faster than `outline-up-heading',
22182 because it relies on stars being the outline starters. This can really
22183 make a significant difference in outlines with very many siblings."
22184 (let (start-level re)
22185 (org-back-to-heading t)
22186 (setq start-level (funcall outline-level))
22187 (if (equal start-level 1)
22189 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22190 (if (re-search-backward re nil t)
22191 (funcall outline-level)))))
22193 (defun org-first-sibling-p ()
22194 "Is this heading the first child of its parents?"
22195 (interactive)
22196 (let ((re org-outline-regexp-bol)
22197 level l)
22198 (unless (org-at-heading-p t)
22199 (error "Not at a heading"))
22200 (setq level (funcall outline-level))
22201 (save-excursion
22202 (if (not (re-search-backward re nil t))
22204 (setq l (funcall outline-level))
22205 (< l level)))))
22207 (defun org-goto-sibling (&optional previous)
22208 "Goto the next sibling, even if it is invisible.
22209 When PREVIOUS is set, go to the previous sibling instead. Returns t
22210 when a sibling was found. When none is found, return nil and don't
22211 move point."
22212 (let ((fun (if previous 're-search-backward 're-search-forward))
22213 (pos (point))
22214 (re org-outline-regexp-bol)
22215 level l)
22216 (when (condition-case nil (org-back-to-heading t) (error nil))
22217 (setq level (funcall outline-level))
22218 (catch 'exit
22219 (or previous (forward-char 1))
22220 (while (funcall fun re nil t)
22221 (setq l (funcall outline-level))
22222 (when (< l level) (goto-char pos) (throw 'exit nil))
22223 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22224 (goto-char pos)
22225 nil))))
22227 (defun org-show-siblings ()
22228 "Show all siblings of the current headline."
22229 (save-excursion
22230 (while (org-goto-sibling) (org-flag-heading nil)))
22231 (save-excursion
22232 (while (org-goto-sibling 'previous)
22233 (org-flag-heading nil))))
22235 (defun org-goto-first-child ()
22236 "Goto the first child, even if it is invisible.
22237 Return t when a child was found. Otherwise don't move point and
22238 return nil."
22239 (let (level (pos (point)) (re org-outline-regexp-bol))
22240 (when (condition-case nil (org-back-to-heading t) (error nil))
22241 (setq level (outline-level))
22242 (forward-char 1)
22243 (if (and (re-search-forward re nil t) (> (outline-level) level))
22244 (progn (goto-char (match-beginning 0)) t)
22245 (goto-char pos) nil))))
22247 (defun org-show-hidden-entry ()
22248 "Show an entry where even the heading is hidden."
22249 (save-excursion
22250 (org-show-entry)))
22252 (defun org-flag-heading (flag &optional entry)
22253 "Flag the current heading. FLAG non-nil means make invisible.
22254 When ENTRY is non-nil, show the entire entry."
22255 (save-excursion
22256 (org-back-to-heading t)
22257 ;; Check if we should show the entire entry
22258 (if entry
22259 (progn
22260 (org-show-entry)
22261 (save-excursion
22262 (and (outline-next-heading)
22263 (org-flag-heading nil))))
22264 (outline-flag-region (max (point-min) (1- (point)))
22265 (save-excursion (outline-end-of-heading) (point))
22266 flag))))
22268 (defun org-get-next-sibling ()
22269 "Move to next heading of the same level, and return point.
22270 If there is no such heading, return nil.
22271 This is like outline-next-sibling, but invisible headings are ok."
22272 (let ((level (funcall outline-level)))
22273 (outline-next-heading)
22274 (while (and (not (eobp)) (> (funcall outline-level) level))
22275 (outline-next-heading))
22276 (if (or (eobp) (< (funcall outline-level) level))
22278 (point))))
22280 (defun org-get-last-sibling ()
22281 "Move to previous heading of the same level, and return point.
22282 If there is no such heading, return nil."
22283 (let ((opoint (point))
22284 (level (funcall outline-level)))
22285 (outline-previous-heading)
22286 (when (and (/= (point) opoint) (outline-on-heading-p t))
22287 (while (and (> (funcall outline-level) level)
22288 (not (bobp)))
22289 (outline-previous-heading))
22290 (if (< (funcall outline-level) level)
22292 (point)))))
22294 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22295 "Goto to the end of a subtree."
22296 ;; This contains an exact copy of the original function, but it uses
22297 ;; `org-back-to-heading', to make it work also in invisible
22298 ;; trees. And is uses an invisible-ok argument.
22299 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22300 ;; Furthermore, when used inside Org, finding the end of a large subtree
22301 ;; with many children and grandchildren etc, this can be much faster
22302 ;; than the outline version.
22303 (org-back-to-heading invisible-ok)
22304 (let ((first t)
22305 (level (funcall outline-level)))
22306 (if (and (derived-mode-p 'org-mode) (< level 1000))
22307 ;; A true heading (not a plain list item), in Org-mode
22308 ;; This means we can easily find the end by looking
22309 ;; only for the right number of stars. Using a regexp to do
22310 ;; this is so much faster than using a Lisp loop.
22311 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22312 (forward-char 1)
22313 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22314 ;; something else, do it the slow way
22315 (while (and (not (eobp))
22316 (or first (> (funcall outline-level) level)))
22317 (setq first nil)
22318 (outline-next-heading)))
22319 (unless to-heading
22320 (if (memq (preceding-char) '(?\n ?\^M))
22321 (progn
22322 ;; Go to end of line before heading
22323 (forward-char -1)
22324 (if (memq (preceding-char) '(?\n ?\^M))
22325 ;; leave blank line before heading
22326 (forward-char -1))))))
22327 (point))
22329 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22330 "Use Org version in org-mode, for dramatic speed-up."
22331 (if (derived-mode-p 'org-mode)
22332 (progn
22333 (org-end-of-subtree nil t)
22334 (unless (eobp) (backward-char 1)))
22335 ad-do-it))
22337 (defun org-end-of-meta-data-and-drawers ()
22338 "Jump to the first text after meta data and drawers in the current entry.
22339 This will move over empty lines, lines with planning time stamps,
22340 clocking lines, and drawers."
22341 (org-back-to-heading t)
22342 (let ((end (save-excursion (outline-next-heading) (point)))
22343 (re (concat "\\(" org-drawer-regexp "\\)"
22344 "\\|" "[ \t]*" org-keyword-time-regexp)))
22345 (forward-line 1)
22346 (while (re-search-forward re end t)
22347 (if (not (match-end 1))
22348 ;; empty or planning line
22349 (forward-line 1)
22350 ;; a drawer, find the end
22351 (re-search-forward "^[ \t]*:END:" end 'move)
22352 (forward-line 1)))
22353 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22354 (point)))
22356 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22357 "Move forward to the arg'th subheading at same level as this one.
22358 Stop at the first and last subheadings of a superior heading.
22359 Normally this only looks at visible headings, but when INVISIBLE-OK is
22360 non-nil it will also look at invisible ones."
22361 (interactive "p")
22362 (org-back-to-heading invisible-ok)
22363 (org-at-heading-p)
22364 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22365 (re (format "^\\*\\{1,%d\\} " level))
22367 (forward-char 1)
22368 (while (> arg 0)
22369 (while (and (re-search-forward re nil 'move)
22370 (setq l (- (match-end 0) (match-beginning 0) 1))
22371 (= l level)
22372 (not invisible-ok)
22373 (progn (backward-char 1) (outline-invisible-p)))
22374 (if (< l level) (setq arg 1)))
22375 (setq arg (1- arg)))
22376 (beginning-of-line 1)))
22378 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22379 "Move backward to the arg'th subheading at same level as this one.
22380 Stop at the first and last subheadings of a superior heading."
22381 (interactive "p")
22382 (org-back-to-heading)
22383 (org-at-heading-p)
22384 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22385 (re (format "^\\*\\{1,%d\\} " level))
22387 (while (> arg 0)
22388 (while (and (re-search-backward re nil 'move)
22389 (setq l (- (match-end 0) (match-beginning 0) 1))
22390 (= l level)
22391 (not invisible-ok)
22392 (outline-invisible-p))
22393 (if (< l level) (setq arg 1)))
22394 (setq arg (1- arg)))))
22396 (defun org-forward-element ()
22397 "Move forward by one element.
22398 Move to the next element at the same level, when possible."
22399 (interactive)
22400 (cond ((eobp) (error "Cannot move further down"))
22401 ((org-with-limited-levels (org-at-heading-p))
22402 (let ((origin (point)))
22403 (org-forward-heading-same-level 1)
22404 (unless (org-with-limited-levels (org-at-heading-p))
22405 (goto-char origin)
22406 (error "Cannot move further down"))))
22408 (let* ((elem (org-element-at-point))
22409 (end (org-element-property :end elem))
22410 (parent (org-element-property :parent elem)))
22411 (if (and parent (= (org-element-property :contents-end parent) end))
22412 (goto-char (org-element-property :end parent))
22413 (goto-char end))))))
22415 (defun org-backward-element ()
22416 "Move backward by one element.
22417 Move to the previous element at the same level, when possible."
22418 (interactive)
22419 (cond ((bobp) (error "Cannot move further up"))
22420 ((org-with-limited-levels (org-at-heading-p))
22421 ;; At an headline, move to the previous one, if any, or stay
22422 ;; here.
22423 (let ((origin (point)))
22424 (org-backward-heading-same-level 1)
22425 (unless (org-with-limited-levels (org-at-heading-p))
22426 (goto-char origin)
22427 (error "Cannot move further up"))))
22429 (let* ((trail (org-element-at-point 'keep-trail))
22430 (elem (car trail))
22431 (prev-elem (nth 1 trail))
22432 (beg (org-element-property :begin elem)))
22433 (cond
22434 ;; Move to beginning of current element if point isn't
22435 ;; there already.
22436 ((/= (point) beg) (goto-char beg))
22437 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22438 ((org-before-first-heading-p) (goto-char (point-min)))
22439 (t (org-back-to-heading)))))))
22441 (defun org-up-element ()
22442 "Move to upper element."
22443 (interactive)
22444 (if (org-with-limited-levels (org-at-heading-p))
22445 (unless (org-up-heading-safe) (error "No surrounding element"))
22446 (let* ((elem (org-element-at-point))
22447 (parent (org-element-property :parent elem)))
22448 (if parent (goto-char (org-element-property :begin parent))
22449 (if (org-with-limited-levels (org-before-first-heading-p))
22450 (error "No surrounding element")
22451 (org-with-limited-levels (org-back-to-heading)))))))
22453 (defvar org-element-greater-elements)
22454 (defun org-down-element ()
22455 "Move to inner element."
22456 (interactive)
22457 (let ((element (org-element-at-point)))
22458 (cond
22459 ((memq (org-element-type element) '(plain-list table))
22460 (goto-char (org-element-property :contents-begin element))
22461 (forward-char))
22462 ((memq (org-element-type element) org-element-greater-elements)
22463 ;; If contents are hidden, first disclose them.
22464 (when (org-element-property :hiddenp element) (org-cycle))
22465 (goto-char (or (org-element-property :contents-begin element)
22466 (error "No content for this element"))))
22467 (t (error "No inner element")))))
22469 (defun org-drag-element-backward ()
22470 "Move backward element at point."
22471 (interactive)
22472 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22473 (let* ((trail (org-element-at-point 'keep-trail))
22474 (elem (car trail))
22475 (prev-elem (nth 1 trail)))
22476 ;; Error out if no previous element or previous element is
22477 ;; a parent of the current one.
22478 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22479 (error "Cannot drag element backward")
22480 (let ((pos (point)))
22481 (org-element-swap-A-B prev-elem elem)
22482 (goto-char (+ (org-element-property :begin prev-elem)
22483 (- pos (org-element-property :begin elem)))))))))
22485 (defun org-drag-element-forward ()
22486 "Move forward element at point."
22487 (interactive)
22488 (let* ((pos (point))
22489 (elem (org-element-at-point)))
22490 (when (= (point-max) (org-element-property :end elem))
22491 (error "Cannot drag element forward"))
22492 (goto-char (org-element-property :end elem))
22493 (let ((next-elem (org-element-at-point)))
22494 (when (or (org-element-nested-p elem next-elem)
22495 (and (eq (org-element-type next-elem) 'headline)
22496 (not (eq (org-element-type elem) 'headline))))
22497 (goto-char pos)
22498 (error "Cannot drag element forward"))
22499 ;; Compute new position of point: it's shifted by NEXT-ELEM
22500 ;; body's length (without final blanks) and by the length of
22501 ;; blanks between ELEM and NEXT-ELEM.
22502 (let ((size-next (- (save-excursion
22503 (goto-char (org-element-property :end next-elem))
22504 (skip-chars-backward " \r\t\n")
22505 (forward-line)
22506 ;; Small correction if buffer doesn't end
22507 ;; with a newline character.
22508 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22509 (org-element-property :begin next-elem)))
22510 (size-blank (- (org-element-property :end elem)
22511 (save-excursion
22512 (goto-char (org-element-property :end elem))
22513 (skip-chars-backward " \r\t\n")
22514 (forward-line)
22515 (point)))))
22516 (org-element-swap-A-B elem next-elem)
22517 (goto-char (+ pos size-next size-blank))))))
22519 (defun org-mark-element ()
22520 "Put point at beginning of this element, mark at end.
22522 Interactively, if this command is repeated or (in Transient Mark
22523 mode) if the mark is active, it marks the next element after the
22524 ones already marked."
22525 (interactive)
22526 (let (deactivate-mark)
22527 (if (and (org-called-interactively-p 'any)
22528 (or (and (eq last-command this-command) (mark t))
22529 (and transient-mark-mode mark-active)))
22530 (set-mark
22531 (save-excursion
22532 (goto-char (mark))
22533 (goto-char (org-element-property :end (org-element-at-point)))))
22534 (let ((element (org-element-at-point)))
22535 (end-of-line)
22536 (push-mark (org-element-property :end element) t t)
22537 (goto-char (org-element-property :begin element))))))
22539 (defun org-narrow-to-element ()
22540 "Narrow buffer to current element."
22541 (interactive)
22542 (let ((elem (org-element-at-point)))
22543 (cond
22544 ((eq (car elem) 'headline)
22545 (narrow-to-region
22546 (org-element-property :begin elem)
22547 (org-element-property :end elem)))
22548 ((memq (car elem) org-element-greater-elements)
22549 (narrow-to-region
22550 (org-element-property :contents-begin elem)
22551 (org-element-property :contents-end elem)))
22553 (narrow-to-region
22554 (org-element-property :begin elem)
22555 (org-element-property :end elem))))))
22557 (defun org-transpose-words ()
22558 "Transpose words, using `org-mode' syntax table."
22559 (interactive)
22560 (with-syntax-table org-syntax-table
22561 (call-interactively 'transpose-words)))
22562 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22564 (defun org-transpose-element ()
22565 "Transpose current and previous elements, keeping blank lines between.
22566 Point is moved after both elements."
22567 (interactive)
22568 (org-skip-whitespace)
22569 (let ((end (org-element-property :end (org-element-at-point))))
22570 (org-drag-element-backward)
22571 (goto-char end)))
22573 (defun org-unindent-buffer ()
22574 "Un-indent the visible part of the buffer.
22575 Relative indentation (between items, inside blocks, etc.) isn't
22576 modified."
22577 (interactive)
22578 (unless (eq major-mode 'org-mode)
22579 (error "Cannot un-indent a buffer not in Org mode"))
22580 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22581 unindent-tree ; For byte-compiler.
22582 (unindent-tree
22583 (function
22584 (lambda (contents)
22585 (mapc
22586 (lambda (element)
22587 (if (memq (org-element-type element) '(headline section))
22588 (funcall unindent-tree (org-element-contents element))
22589 (save-excursion
22590 (save-restriction
22591 (narrow-to-region
22592 (org-element-property :begin element)
22593 (org-element-property :end element))
22594 (org-do-remove-indentation)))))
22595 (reverse contents))))))
22596 (funcall unindent-tree (org-element-contents parse-tree))))
22598 (defun org-show-subtree ()
22599 "Show everything after this heading at deeper levels."
22600 (interactive)
22601 (outline-flag-region
22602 (point)
22603 (save-excursion
22604 (org-end-of-subtree t t))
22605 nil))
22607 (defun org-show-entry ()
22608 "Show the body directly following this heading.
22609 Show the heading too, if it is currently invisible."
22610 (interactive)
22611 (save-excursion
22612 (condition-case nil
22613 (progn
22614 (org-back-to-heading t)
22615 (outline-flag-region
22616 (max (point-min) (1- (point)))
22617 (save-excursion
22618 (if (re-search-forward
22619 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22620 (match-beginning 1)
22621 (point-max)))
22622 nil)
22623 (org-cycle-hide-drawers 'children))
22624 (error nil))))
22626 (defun org-make-options-regexp (kwds &optional extra)
22627 "Make a regular expression for keyword lines."
22628 (concat
22629 "^#\\+\\("
22630 (mapconcat 'regexp-quote kwds "\\|")
22631 (if extra (concat "\\|" extra))
22632 "\\):[ \t]*\\(.*\\)"))
22634 ;; Make isearch reveal the necessary context
22635 (defun org-isearch-end ()
22636 "Reveal context after isearch exits."
22637 (when isearch-success ; only if search was successful
22638 (if (featurep 'xemacs)
22639 ;; Under XEmacs, the hook is run in the correct place,
22640 ;; we directly show the context.
22641 (org-show-context 'isearch)
22642 ;; In Emacs the hook runs *before* restoring the overlays.
22643 ;; So we have to use a one-time post-command-hook to do this.
22644 ;; (Emacs 22 has a special variable, see function `org-mode')
22645 (unless (and (boundp 'isearch-mode-end-hook-quit)
22646 isearch-mode-end-hook-quit)
22647 ;; Only when the isearch was not quitted.
22648 (org-add-hook 'post-command-hook 'org-isearch-post-command
22649 'append 'local)))))
22651 (defun org-isearch-post-command ()
22652 "Remove self from hook, and show context."
22653 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22654 (org-show-context 'isearch))
22657 ;;;; Integration with and fixes for other packages
22659 ;;; Imenu support
22661 (defvar org-imenu-markers nil
22662 "All markers currently used by Imenu.")
22663 (make-variable-buffer-local 'org-imenu-markers)
22665 (defun org-imenu-new-marker (&optional pos)
22666 "Return a new marker for use by Imenu, and remember the marker."
22667 (let ((m (make-marker)))
22668 (move-marker m (or pos (point)))
22669 (push m org-imenu-markers)
22672 (defun org-imenu-get-tree ()
22673 "Produce the index for Imenu."
22674 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22675 (setq org-imenu-markers nil)
22676 (let* ((n org-imenu-depth)
22677 (re (concat "^" (org-get-limited-outline-regexp)))
22678 (subs (make-vector (1+ n) nil))
22679 (last-level 0)
22680 m level head)
22681 (save-excursion
22682 (save-restriction
22683 (widen)
22684 (goto-char (point-max))
22685 (while (re-search-backward re nil t)
22686 (setq level (org-reduced-level (funcall outline-level)))
22687 (when (and (<= level n)
22688 (looking-at org-complex-heading-regexp))
22689 (setq head (org-link-display-format
22690 (org-match-string-no-properties 4))
22691 m (org-imenu-new-marker))
22692 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22693 (if (>= level last-level)
22694 (push (cons head m) (aref subs level))
22695 (push (cons head (aref subs (1+ level))) (aref subs level))
22696 (loop for i from (1+ level) to n do (aset subs i nil)))
22697 (setq last-level level)))))
22698 (aref subs 1)))
22700 (eval-after-load "imenu"
22701 '(progn
22702 (add-hook 'imenu-after-jump-hook
22703 (lambda ()
22704 (if (derived-mode-p 'org-mode)
22705 (org-show-context 'org-goto))))))
22707 (defun org-link-display-format (link)
22708 "Replace a link with either the description, or the link target
22709 if no description is present"
22710 (save-match-data
22711 (if (string-match org-bracket-link-analytic-regexp link)
22712 (replace-match (if (match-end 5)
22713 (match-string 5 link)
22714 (concat (match-string 1 link)
22715 (match-string 3 link)))
22716 nil t link)
22717 link)))
22719 (defun org-toggle-link-display ()
22720 "Toggle the literal or descriptive display of links."
22721 (interactive)
22722 (if org-descriptive-links
22723 (progn (org-remove-from-invisibility-spec '(org-link))
22724 (org-restart-font-lock)
22725 (setq org-descriptive-links nil))
22726 (progn (add-to-invisibility-spec '(org-link))
22727 (org-restart-font-lock)
22728 (setq org-descriptive-links t))))
22730 ;; Speedbar support
22732 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22733 "Overlay marking the agenda restriction line in speedbar.")
22734 (overlay-put org-speedbar-restriction-lock-overlay
22735 'face 'org-agenda-restriction-lock)
22736 (overlay-put org-speedbar-restriction-lock-overlay
22737 'help-echo "Agendas are currently limited to this item.")
22738 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22740 (defun org-speedbar-set-agenda-restriction ()
22741 "Restrict future agenda commands to the location at point in speedbar.
22742 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22743 (interactive)
22744 (require 'org-agenda)
22745 (let (p m tp np dir txt)
22746 (cond
22747 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22748 'org-imenu t))
22749 (setq m (get-text-property p 'org-imenu-marker))
22750 (with-current-buffer (marker-buffer m)
22751 (goto-char m)
22752 (org-agenda-set-restriction-lock 'subtree)))
22753 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22754 'speedbar-function 'speedbar-find-file))
22755 (setq tp (previous-single-property-change
22756 (1+ p) 'speedbar-function)
22757 np (next-single-property-change
22758 tp 'speedbar-function)
22759 dir (speedbar-line-directory)
22760 txt (buffer-substring-no-properties (or tp (point-min))
22761 (or np (point-max))))
22762 (with-current-buffer (find-file-noselect
22763 (let ((default-directory dir))
22764 (expand-file-name txt)))
22765 (unless (derived-mode-p 'org-mode)
22766 (error "Cannot restrict to non-Org-mode file"))
22767 (org-agenda-set-restriction-lock 'file)))
22768 (t (error "Don't know how to restrict Org-mode's agenda")))
22769 (move-overlay org-speedbar-restriction-lock-overlay
22770 (point-at-bol) (point-at-eol))
22771 (setq current-prefix-arg nil)
22772 (org-agenda-maybe-redo)))
22774 (eval-after-load "speedbar"
22775 '(progn
22776 (speedbar-add-supported-extension ".org")
22777 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22778 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22779 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22780 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22781 (add-hook 'speedbar-visiting-tag-hook
22782 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22784 ;;; Fixes and Hacks for problems with other packages
22786 ;; Make flyspell not check words in links, to not mess up our keymap
22787 (defun org-mode-flyspell-verify ()
22788 "Don't let flyspell put overlays at active buttons, or on
22789 {todo,all-time,additional-option-like}-keywords."
22790 (let ((pos (max (1- (point)) (point-min)))
22791 (word (thing-at-point 'word)))
22792 (and (not (get-text-property pos 'keymap))
22793 (not (get-text-property pos 'org-no-flyspell))
22794 (not (member word org-todo-keywords-1))
22795 (not (member word org-all-time-keywords))
22796 (not (member word org-options-keywords))
22797 (not (member word (mapcar 'car org-startup-options)))
22798 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22800 (defun org-remove-flyspell-overlays-in (beg end)
22801 "Remove flyspell overlays in region."
22802 (and (org-bound-and-true-p flyspell-mode)
22803 (fboundp 'flyspell-delete-region-overlays)
22804 (flyspell-delete-region-overlays beg end))
22805 (add-text-properties beg end '(org-no-flyspell t)))
22807 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22808 (eval-after-load "bookmark"
22809 '(if (boundp 'bookmark-after-jump-hook)
22810 ;; We can use the hook
22811 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22812 ;; Hook not available, use advice
22813 (defadvice bookmark-jump (after org-make-visible activate)
22814 "Make the position visible."
22815 (org-bookmark-jump-unhide))))
22817 ;; Make sure saveplace shows the location if it was hidden
22818 (eval-after-load "saveplace"
22819 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22820 "Make the position visible."
22821 (org-bookmark-jump-unhide)))
22823 ;; Make sure ecb shows the location if it was hidden
22824 (eval-after-load "ecb"
22825 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22826 "Make hierarchy visible when jumping into location from ECB tree buffer."
22827 (if (derived-mode-p 'org-mode)
22828 (org-show-context))))
22830 (defun org-bookmark-jump-unhide ()
22831 "Unhide the current position, to show the bookmark location."
22832 (and (derived-mode-p 'org-mode)
22833 (or (outline-invisible-p)
22834 (save-excursion (goto-char (max (point-min) (1- (point))))
22835 (outline-invisible-p)))
22836 (org-show-context 'bookmark-jump)))
22838 ;; Make session.el ignore our circular variable
22839 (eval-after-load "session"
22840 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22842 ;;;; Experimental code
22844 (defun org-closed-in-range ()
22845 "Sparse tree of items closed in a certain time range.
22846 Still experimental, may disappear in the future."
22847 (interactive)
22848 ;; Get the time interval from the user.
22849 (let* ((time1 (org-float-time
22850 (org-read-date nil 'to-time nil "Starting date: ")))
22851 (time2 (org-float-time
22852 (org-read-date nil 'to-time nil "End date:")))
22853 ;; callback function
22854 (callback (lambda ()
22855 (let ((time
22856 (org-float-time
22857 (apply 'encode-time
22858 (org-parse-time-string
22859 (match-string 1))))))
22860 ;; check if time in interval
22861 (and (>= time time1) (<= time time2))))))
22862 ;; make tree, check each match with the callback
22863 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22865 ;;;; Finish up
22867 (provide 'org)
22869 (run-hooks 'org-load-hook)
22871 ;;; org.el ends here