org.el (org-insert-link): Call `org-link-try-special-completion' from the original...
[org-mode/org-tableheadings.git] / lisp / org.el
blobfe63b62f1f057eb78e7dde4a64db181363d1870c
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 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
82 ;; some places -- e.g. see the macro org-with-limited-levels.
84 ;; In Org buffers, the value of `outline-regexp' is that of
85 ;; `org-outline-regexp'. The only function still directly relying on
86 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
87 ;; job when `orgstruct-mode' is active.
88 (defvar org-outline-regexp "\\*+ "
89 "Regexp to match Org headlines.")
91 (defvar org-outline-regexp-bol "^\\*+ "
92 "Regexp to match Org headlines.
93 This is similar to `org-outline-regexp' but additionally makes
94 sure that we are at the beginning of the line.")
96 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
97 "Matches an headline, putting stars and text into groups.
98 Stars are put in group 1 and the trimmed body in group 2.")
100 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
101 (when (fboundp 'defvaralias)
102 (unless (boundp 'calendar-view-holidays-initially-flag)
103 (defvaralias 'calendar-view-holidays-initially-flag
104 'view-calendar-holidays-initially))
105 (unless (boundp 'calendar-view-diary-initially-flag)
106 (defvaralias 'calendar-view-diary-initially-flag
107 'view-diary-entries-initially))
108 (unless (boundp 'diary-fancy-buffer)
109 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
111 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
112 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
113 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
114 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
115 (declare-function org-at-clock-log-p "org-clock" ())
116 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
117 (declare-function org-clock-timestamps-up "org-clock" ())
118 (declare-function org-clock-timestamps-down "org-clock" ())
119 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
121 ;; load languages based on value of `org-babel-load-languages'
122 (defvar org-babel-load-languages)
123 ;;;###autoload
124 (defun org-babel-do-load-languages (sym value)
125 "Load the languages defined in `org-babel-load-languages'."
126 (set-default sym value)
127 (mapc (lambda (pair)
128 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
129 (if active
130 (progn
131 (require (intern (concat "ob-" lang))))
132 (progn
133 (funcall 'fmakunbound
134 (intern (concat "org-babel-execute:" lang)))
135 (funcall 'fmakunbound
136 (intern (concat "org-babel-expand-body:" lang)))))))
137 org-babel-load-languages))
139 (defcustom org-babel-load-languages '((emacs-lisp . t))
140 "Languages which can be evaluated in Org-mode buffers.
141 This list can be used to load support for any of the languages
142 below, note that each language will depend on a different set of
143 system executables and/or Emacs modes. When a language is
144 \"loaded\", then code blocks in that language can be evaluated
145 with `org-babel-execute-src-block' bound by default to C-c
146 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
147 be set to remove code block evaluation from the C-c C-c
148 keybinding. By default only Emacs Lisp (which has no
149 requirements) is loaded."
150 :group 'org-babel
151 :set 'org-babel-do-load-languages
152 :version "24.1"
153 :type '(alist :tag "Babel Languages"
154 :key-type
155 (choice
156 (const :tag "Awk" awk)
157 (const :tag "C" C)
158 (const :tag "R" R)
159 (const :tag "Asymptote" asymptote)
160 (const :tag "Calc" calc)
161 (const :tag "Clojure" clojure)
162 (const :tag "CSS" css)
163 (const :tag "Ditaa" ditaa)
164 (const :tag "Dot" dot)
165 (const :tag "Emacs Lisp" emacs-lisp)
166 (const :tag "Fortran" fortran)
167 (const :tag "Gnuplot" gnuplot)
168 (const :tag "Haskell" haskell)
169 (const :tag "IO" io)
170 (const :tag "Java" java)
171 (const :tag "Javascript" js)
172 (const :tag "LaTeX" latex)
173 (const :tag "Ledger" ledger)
174 (const :tag "Lilypond" lilypond)
175 (const :tag "Lisp" lisp)
176 (const :tag "Maxima" maxima)
177 (const :tag "Matlab" matlab)
178 (const :tag "Mscgen" mscgen)
179 (const :tag "Ocaml" ocaml)
180 (const :tag "Octave" octave)
181 (const :tag "Org" org)
182 (const :tag "Perl" perl)
183 (const :tag "Pico Lisp" picolisp)
184 (const :tag "PlantUML" plantuml)
185 (const :tag "Python" python)
186 (const :tag "Ruby" ruby)
187 (const :tag "Sass" sass)
188 (const :tag "Scala" scala)
189 (const :tag "Scheme" scheme)
190 (const :tag "Screen" screen)
191 (const :tag "Shell Script" sh)
192 (const :tag "Shen" shen)
193 (const :tag "Sql" sql)
194 (const :tag "Sqlite" sqlite))
195 :value-type (boolean :tag "Activate" :value t)))
197 ;;;; Customization variables
198 (defcustom org-clone-delete-id nil
199 "Remove ID property of clones of a subtree.
200 When non-nil, clones of a subtree don't inherit the ID property.
201 Otherwise they inherit the ID property with a new unique
202 identifier."
203 :type 'boolean
204 :version "24.1"
205 :group 'org-id)
207 ;;; Version
208 (require 'org-compat)
209 (org-check-version)
210 ;;;###autoload
211 (defun org-version (&optional here full message)
212 "Show the org-mode version in the echo area.
213 With prefix argument HERE, insert it at point.
214 When FULL is non-nil, use a verbose version string.
215 When MESSAGE is non-nil, display a message with the version."
216 (interactive "P")
217 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
218 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
219 (org-trash (or
220 (and (fboundp 'org-release) (fboundp 'org-git-version))
221 (load (concat org-dir "org-version.el")
222 'noerror 'nomessage 'nosuffix)))
223 (org-version (org-release))
224 (git-version (org-git-version))
225 (version (format "Org-mode version %s (%s @ %s)"
226 org-version
227 git-version
228 (if org-install-dir
229 (if (string= org-dir org-install-dir)
230 org-install-dir
231 (concat "mixed installation! " org-install-dir " and " org-dir))
232 "org-install.el can not be found!")))
233 (_version (if full version org-version)))
234 (if (org-called-interactively-p 'interactive)
235 (if here
236 (insert version)
237 (message version))
238 (if message (message _version))
239 _version)))
241 (defconst org-version (org-version))
243 ;;; Compatibility constants
245 ;;; The custom variables
247 (defgroup org nil
248 "Outline-based notes management and organizer."
249 :tag "Org"
250 :group 'outlines
251 :group 'calendar)
253 (defcustom org-mode-hook nil
254 "Mode hook for Org-mode, run after the mode was turned on."
255 :group 'org
256 :type 'hook)
258 (defcustom org-load-hook nil
259 "Hook that is run after org.el has been loaded."
260 :group 'org
261 :type 'hook)
263 (defcustom org-log-buffer-setup-hook nil
264 "Hook that is run after an Org log buffer is created."
265 :group 'org
266 :version "24.1"
267 :type 'hook)
269 (defvar org-modules) ; defined below
270 (defvar org-modules-loaded nil
271 "Have the modules been loaded already?")
273 (defun org-load-modules-maybe (&optional force)
274 "Load all extensions listed in `org-modules'."
275 (when (or force (not org-modules-loaded))
276 (mapc (lambda (ext)
277 (condition-case nil (require ext)
278 (error (message "Problems while trying to load feature `%s'" ext))))
279 org-modules)
280 (setq org-modules-loaded t)))
282 (defun org-set-modules (var value)
283 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
284 (set var value)
285 (when (featurep 'org)
286 (org-load-modules-maybe 'force)))
288 (when (org-bound-and-true-p org-modules)
289 (let ((a (member 'org-infojs org-modules)))
290 (and a (setcar a 'org-jsinfo))))
292 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
293 "Modules that should always be loaded together with org.el.
294 If a description starts with <C>, the file is not part of Emacs
295 and loading it will require that you have downloaded and properly installed
296 the org-mode distribution.
298 You can also use this system to load external packages (i.e. neither Org
299 core modules, nor modules from the CONTRIB directory). Just add symbols
300 to the end of the list. If the package is called org-xyz.el, then you need
301 to add the symbol `xyz', and the package must have a call to
303 (provide 'org-xyz)"
304 :group 'org
305 :set 'org-set-modules
306 :type
307 '(set :greedy t
308 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
309 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
310 (const :tag " crypt: Encryption of subtrees" org-crypt)
311 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
312 (const :tag " docview: Links to doc-view buffers" org-docview)
313 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
314 (const :tag " id: Global IDs for identifying entries" org-id)
315 (const :tag " info: Links to Info nodes" org-info)
316 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
317 (const :tag " habit: Track your consistency with habits" org-habit)
318 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
319 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
320 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
321 (const :tag " mew Links to Mew folders/messages" org-mew)
322 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
323 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
324 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
325 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
326 (const :tag " vm: Links to VM folders/messages" org-vm)
327 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
328 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
329 (const :tag " mouse: Additional mouse support" org-mouse)
330 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
332 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
333 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
334 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
335 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
336 (const :tag "C collector: Collect properties into tables" org-collector)
337 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
338 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
339 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
340 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
341 (const :tag "C eval: Include command output as text" org-eval)
342 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
343 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
344 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
345 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
346 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
348 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
350 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
351 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
352 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
353 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
354 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
355 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
356 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
357 (const :tag "C mtags: Support for muse-like tags" org-mtags)
358 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
359 (const :tag "C registry: A registry for Org-mode links" org-registry)
360 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
361 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
362 (const :tag "C secretary: Team management with org-mode" org-secretary)
363 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
364 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
365 (const :tag "C track: Keep up with Org-mode development" org-track)
366 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
367 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
368 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
370 (defcustom org-support-shift-select nil
371 "Non-nil means make shift-cursor commands select text when possible.
373 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
374 start selecting a region, or enlarge regions started in this way.
375 In Org-mode, in special contexts, these same keys are used for
376 other purposes, important enough to compete with shift selection.
377 Org tries to balance these needs by supporting `shift-select-mode'
378 outside these special contexts, under control of this variable.
380 The default of this variable is nil, to avoid confusing behavior. Shifted
381 cursor keys will then execute Org commands in the following contexts:
382 - on a headline, changing TODO state (left/right) and priority (up/down)
383 - on a time stamp, changing the time
384 - in a plain list item, changing the bullet type
385 - in a property definition line, switching between allowed values
386 - in the BEGIN line of a clock table (changing the time block).
387 Outside these contexts, the commands will throw an error.
389 When this variable is t and the cursor is not in a special
390 context, Org-mode will support shift-selection for making and
391 enlarging regions. To make this more effective, the bullet
392 cycling will no longer happen anywhere in an item line, but only
393 if the cursor is exactly on the bullet.
395 If you set this variable to the symbol `always', then the keys
396 will not be special in headlines, property lines, and item lines,
397 to make shift selection work there as well. If this is what you
398 want, you can use the following alternative commands: `C-c C-t'
399 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
400 can be used to switch TODO sets, `C-c -' to cycle item bullet
401 types, and properties can be edited by hand or in column view.
403 However, when the cursor is on a timestamp, shift-cursor commands
404 will still edit the time stamp - this is just too good to give up.
406 XEmacs user should have this variable set to nil, because
407 `shift-select-mode' is in Emacs 23 or later only."
408 :group 'org
409 :type '(choice
410 (const :tag "Never" nil)
411 (const :tag "When outside special context" t)
412 (const :tag "Everywhere except timestamps" always)))
414 (defcustom org-loop-over-headlines-in-active-region nil
415 "Shall some commands act upon headlines in the active region?
417 When set to `t', some commands will be performed in all headlines
418 within the active region.
420 When set to `start-level', some commands will be performed in all
421 headlines within the active region, provided that these headlines
422 are of the same level than the first one.
424 When set to a string, those commands will be performed on the
425 matching headlines within the active region. Such string must be
426 a tags/property/todo match as it is used in the agenda tags view.
428 The list of commands is: `org-schedule', `org-deadline',
429 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
430 `org-archive-to-archive-sibling'. The archiving commands skip
431 already archived entries."
432 :type '(choice (const :tag "Don't loop" nil)
433 (const :tag "All headlines in active region" t)
434 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
435 (string :tag "Tags/Property/Todo matcher"))
436 :version "24.1"
437 :group 'org-todo
438 :group 'org-archive)
440 (defgroup org-startup nil
441 "Options concerning startup of Org-mode."
442 :tag "Org Startup"
443 :group 'org)
445 (defcustom org-startup-folded t
446 "Non-nil means entering Org-mode will switch to OVERVIEW.
447 This can also be configured on a per-file basis by adding one of
448 the following lines anywhere in the buffer:
450 #+STARTUP: fold (or `overview', this is equivalent)
451 #+STARTUP: nofold (or `showall', this is equivalent)
452 #+STARTUP: content
453 #+STARTUP: showeverything"
454 :group 'org-startup
455 :type '(choice
456 (const :tag "nofold: show all" nil)
457 (const :tag "fold: overview" t)
458 (const :tag "content: all headlines" content)
459 (const :tag "show everything, even drawers" showeverything)))
461 (defcustom org-startup-truncated t
462 "Non-nil means entering Org-mode will set `truncate-lines'.
463 This is useful since some lines containing links can be very long and
464 uninteresting. Also tables look terrible when wrapped."
465 :group 'org-startup
466 :type 'boolean)
468 (defcustom org-startup-indented nil
469 "Non-nil means turn on `org-indent-mode' on startup.
470 This can also be configured on a per-file basis by adding one of
471 the following lines anywhere in the buffer:
473 #+STARTUP: indent
474 #+STARTUP: noindent"
475 :group 'org-structure
476 :type '(choice
477 (const :tag "Not" nil)
478 (const :tag "Globally (slow on startup in large files)" t)))
480 (defcustom org-use-sub-superscripts t
481 "Non-nil means interpret \"_\" and \"^\" for export.
482 When this option is turned on, you can use TeX-like syntax for sub- and
483 superscripts. Several characters after \"_\" or \"^\" will be
484 considered as a single item - so grouping with {} is normally not
485 needed. For example, the following things will be parsed as single
486 sub- or superscripts.
488 10^24 or 10^tau several digits will be considered 1 item.
489 10^-12 or 10^-tau a leading sign with digits or a word
490 x^2-y^3 will be read as x^2 - y^3, because items are
491 terminated by almost any nonword/nondigit char.
492 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
494 Still, ambiguity is possible - so when in doubt use {} to enclose the
495 sub/superscript. If you set this variable to the symbol `{}',
496 the braces are *required* in order to trigger interpretations as
497 sub/superscript. This can be helpful in documents that need \"_\"
498 frequently in plain text.
500 Not all export backends support this, but HTML does.
502 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
503 :group 'org-startup
504 :group 'org-export-translation
505 :version "24.1"
506 :type '(choice
507 (const :tag "Always interpret" t)
508 (const :tag "Only with braces" {})
509 (const :tag "Never interpret" nil)))
511 (if (fboundp 'defvaralias)
512 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
515 (defcustom org-startup-with-beamer-mode nil
516 "Non-nil means turn on `org-beamer-mode' on startup.
517 This can also be configured on a per-file basis by adding one of
518 the following lines anywhere in the buffer:
520 #+STARTUP: beamer"
521 :group 'org-startup
522 :version "24.1"
523 :type 'boolean)
525 (defcustom org-startup-align-all-tables nil
526 "Non-nil means align all tables when visiting a file.
527 This is useful when the column width in tables is forced with <N> cookies
528 in table fields. Such tables will look correct only after the first re-align.
529 This can also be configured on a per-file basis by adding one of
530 the following lines anywhere in the buffer:
531 #+STARTUP: align
532 #+STARTUP: noalign"
533 :group 'org-startup
534 :type 'boolean)
536 (defcustom org-startup-with-inline-images nil
537 "Non-nil means show inline images when loading a new Org file.
538 This can also be configured on a per-file basis by adding one of
539 the following lines anywhere in the buffer:
540 #+STARTUP: inlineimages
541 #+STARTUP: noinlineimages"
542 :group 'org-startup
543 :version "24.1"
544 :type 'boolean)
546 (defcustom org-insert-mode-line-in-empty-file nil
547 "Non-nil means insert the first line setting Org-mode in empty files.
548 When the function `org-mode' is called interactively in an empty file, this
549 normally means that the file name does not automatically trigger Org-mode.
550 To ensure that the file will always be in Org-mode in the future, a
551 line enforcing Org-mode will be inserted into the buffer, if this option
552 has been set."
553 :group 'org-startup
554 :type 'boolean)
556 (defcustom org-replace-disputed-keys nil
557 "Non-nil means use alternative key bindings for some keys.
558 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
559 These keys are also used by other packages like shift-selection-mode'
560 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
561 If you want to use Org-mode together with one of these other modes,
562 or more generally if you would like to move some Org-mode commands to
563 other keys, set this variable and configure the keys with the variable
564 `org-disputed-keys'.
566 This option is only relevant at load-time of Org-mode, and must be set
567 *before* org.el is loaded. Changing it requires a restart of Emacs to
568 become effective."
569 :group 'org-startup
570 :type 'boolean)
572 (defcustom org-use-extra-keys nil
573 "Non-nil means use extra key sequence definitions for certain commands.
574 This happens automatically if you run XEmacs or if `window-system'
575 is nil. This variable lets you do the same manually. You must
576 set it before loading org.
578 Example: on Carbon Emacs 22 running graphically, with an external
579 keyboard on a Powerbook, the default way of setting M-left might
580 not work for either Alt or ESC. Setting this variable will make
581 it work for ESC."
582 :group 'org-startup
583 :type 'boolean)
585 (if (fboundp 'defvaralias)
586 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
588 (defcustom org-disputed-keys
589 '(([(shift up)] . [(meta p)])
590 ([(shift down)] . [(meta n)])
591 ([(shift left)] . [(meta -)])
592 ([(shift right)] . [(meta +)])
593 ([(control shift right)] . [(meta shift +)])
594 ([(control shift left)] . [(meta shift -)]))
595 "Keys for which Org-mode and other modes compete.
596 This is an alist, cars are the default keys, second element specifies
597 the alternative to use when `org-replace-disputed-keys' is t.
599 Keys can be specified in any syntax supported by `define-key'.
600 The value of this option takes effect only at Org-mode's startup,
601 therefore you'll have to restart Emacs to apply it after changing."
602 :group 'org-startup
603 :type 'alist)
605 (defun org-key (key)
606 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
607 Or return the original if not disputed.
608 Also apply the translations defined in `org-xemacs-key-equivalents'."
609 (when org-replace-disputed-keys
610 (let* ((nkey (key-description key))
611 (x (org-find-if (lambda (x)
612 (equal (key-description (car x)) nkey))
613 org-disputed-keys)))
614 (setq key (if x (cdr x) key))))
615 (when (featurep 'xemacs)
616 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
617 key)
619 (defun org-find-if (predicate seq)
620 (catch 'exit
621 (while seq
622 (if (funcall predicate (car seq))
623 (throw 'exit (car seq))
624 (pop seq)))))
626 (defun org-defkey (keymap key def)
627 "Define a key, possibly translated, as returned by `org-key'."
628 (define-key keymap (org-key key) def))
630 (defcustom org-ellipsis nil
631 "The ellipsis to use in the Org-mode outline.
632 When nil, just use the standard three dots. When a string, use that instead,
633 When a face, use the standard 3 dots, but with the specified face.
634 The change affects only Org-mode (which will then use its own display table).
635 Changing this requires executing `M-x org-mode' in a buffer to become
636 effective."
637 :group 'org-startup
638 :type '(choice (const :tag "Default" nil)
639 (face :tag "Face" :value org-warning)
640 (string :tag "String" :value "...#")))
642 (defvar org-display-table nil
643 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
645 (defgroup org-keywords nil
646 "Keywords in Org-mode."
647 :tag "Org Keywords"
648 :group 'org)
650 (defcustom org-deadline-string "DEADLINE:"
651 "String to mark deadline entries.
652 A deadline is this string, followed by a time stamp. Should be a word,
653 terminated by a colon. You can insert a schedule keyword and
654 a timestamp with \\[org-deadline].
655 Changes become only effective after restarting Emacs."
656 :group 'org-keywords
657 :type 'string)
659 (defcustom org-scheduled-string "SCHEDULED:"
660 "String to mark scheduled TODO entries.
661 A schedule is this string, followed by a time stamp. Should be a word,
662 terminated by a colon. You can insert a schedule keyword and
663 a timestamp with \\[org-schedule].
664 Changes become only effective after restarting Emacs."
665 :group 'org-keywords
666 :type 'string)
668 (defcustom org-closed-string "CLOSED:"
669 "String used as the prefix for timestamps logging closing a TODO entry."
670 :group 'org-keywords
671 :type 'string)
673 (defcustom org-clock-string "CLOCK:"
674 "String used as prefix for timestamps clocking work hours on an item."
675 :group 'org-keywords
676 :type 'string)
678 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
679 org-scheduled-string "\\|"
680 org-deadline-string "\\|"
681 org-closed-string "\\|"
682 org-clock-string "\\)")
683 "Matches a line with planning or clock info.")
685 (defcustom org-comment-string "COMMENT"
686 "Entries starting with this keyword will never be exported.
687 An entry can be toggled between COMMENT and normal with
688 \\[org-toggle-comment].
689 Changes become only effective after restarting Emacs."
690 :group 'org-keywords
691 :type 'string)
693 (defcustom org-quote-string "QUOTE"
694 "Entries starting with this keyword will be exported in fixed-width font.
695 Quoting applies only to the text in the entry following the headline, and does
696 not extend beyond the next headline, even if that is lower level.
697 An entry can be toggled between QUOTE and normal with
698 \\[org-toggle-fixed-width-section]."
699 :group 'org-keywords
700 :type 'string)
702 (defconst org-repeat-re
703 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
704 "Regular expression for specifying repeated events.
705 After a match, group 1 contains the repeat expression.")
707 (defgroup org-structure nil
708 "Options concerning the general structure of Org-mode files."
709 :tag "Org Structure"
710 :group 'org)
712 (defgroup org-reveal-location nil
713 "Options about how to make context of a location visible."
714 :tag "Org Reveal Location"
715 :group 'org-structure)
717 (defconst org-context-choice
718 '(choice
719 (const :tag "Always" t)
720 (const :tag "Never" nil)
721 (repeat :greedy t :tag "Individual contexts"
722 (cons
723 (choice :tag "Context"
724 (const agenda)
725 (const org-goto)
726 (const occur-tree)
727 (const tags-tree)
728 (const link-search)
729 (const mark-goto)
730 (const bookmark-jump)
731 (const isearch)
732 (const default))
733 (boolean))))
734 "Contexts for the reveal options.")
736 (defcustom org-show-hierarchy-above '((default . t))
737 "Non-nil means show full hierarchy when revealing a location.
738 Org-mode often shows locations in an org-mode file which might have
739 been invisible before. When this is set, the hierarchy of headings
740 above the exposed location is shown.
741 Turning this off for example for sparse trees makes them very compact.
742 Instead of t, this can also be an alist specifying this option for different
743 contexts. Valid contexts are
744 agenda when exposing an entry from the agenda
745 org-goto when using the command `org-goto' on key C-c C-j
746 occur-tree when using the command `org-occur' on key C-c /
747 tags-tree when constructing a sparse tree based on tags matches
748 link-search when exposing search matches associated with a link
749 mark-goto when exposing the jump goal of a mark
750 bookmark-jump when exposing a bookmark location
751 isearch when exiting from an incremental search
752 default default for all contexts not set explicitly"
753 :group 'org-reveal-location
754 :type org-context-choice)
756 (defcustom org-show-following-heading '((default . nil))
757 "Non-nil means show following heading when revealing a location.
758 Org-mode often shows locations in an org-mode file which might have
759 been invisible before. When this is set, the heading following the
760 match is shown.
761 Turning this off for example for sparse trees makes them very compact,
762 but makes it harder to edit the location of the match. In such a case,
763 use the command \\[org-reveal] to show more context.
764 Instead of t, this can also be an alist specifying this option for different
765 contexts. See `org-show-hierarchy-above' for valid contexts."
766 :group 'org-reveal-location
767 :type org-context-choice)
769 (defcustom org-show-siblings '((default . nil) (isearch t))
770 "Non-nil means show all sibling heading when revealing a location.
771 Org-mode often shows locations in an org-mode file which might have
772 been invisible before. When this is set, the sibling of the current entry
773 heading are all made visible. If `org-show-hierarchy-above' is t,
774 the same happens on each level of the hierarchy above the current entry.
776 By default this is on for the isearch context, off for all other contexts.
777 Turning this off for example for sparse trees makes them very compact,
778 but makes it harder to edit the location of the match. In such a case,
779 use the command \\[org-reveal] to show more context.
780 Instead of t, this can also be an alist specifying this option for different
781 contexts. See `org-show-hierarchy-above' for valid contexts."
782 :group 'org-reveal-location
783 :type org-context-choice)
785 (defcustom org-show-entry-below '((default . nil))
786 "Non-nil means show the entry below a headline when revealing a location.
787 Org-mode often shows locations in an org-mode file which might have
788 been invisible before. When this is set, the text below the headline that is
789 exposed is also shown.
791 By default this is off for all contexts.
792 Instead of t, this can also be an alist specifying this option for different
793 contexts. See `org-show-hierarchy-above' for valid contexts."
794 :group 'org-reveal-location
795 :type org-context-choice)
797 (defcustom org-indirect-buffer-display 'other-window
798 "How should indirect tree buffers be displayed?
799 This applies to indirect buffers created with the commands
800 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
801 Valid values are:
802 current-window Display in the current window
803 other-window Just display in another window.
804 dedicated-frame Create one new frame, and re-use it each time.
805 new-frame Make a new frame each time. Note that in this case
806 previously-made indirect buffers are kept, and you need to
807 kill these buffers yourself."
808 :group 'org-structure
809 :group 'org-agenda-windows
810 :type '(choice
811 (const :tag "In current window" current-window)
812 (const :tag "In current frame, other window" other-window)
813 (const :tag "Each time a new frame" new-frame)
814 (const :tag "One dedicated frame" dedicated-frame)))
816 (defcustom org-use-speed-commands nil
817 "Non-nil means activate single letter commands at beginning of a headline.
818 This may also be a function to test for appropriate locations where speed
819 commands should be active."
820 :group 'org-structure
821 :type '(choice
822 (const :tag "Never" nil)
823 (const :tag "At beginning of headline stars" t)
824 (function)))
826 (defcustom org-speed-commands-user nil
827 "Alist of additional speed commands.
828 This list will be checked before `org-speed-commands-default'
829 when the variable `org-use-speed-commands' is non-nil
830 and when the cursor is at the beginning of a headline.
831 The car if each entry is a string with a single letter, which must
832 be assigned to `self-insert-command' in the global map.
833 The cdr is either a command to be called interactively, a function
834 to be called, or a form to be evaluated.
835 An entry that is just a list with a single string will be interpreted
836 as a descriptive headline that will be added when listing the speed
837 commands in the Help buffer using the `?' speed command."
838 :group 'org-structure
839 :type '(repeat :value ("k" . ignore)
840 (choice :value ("k" . ignore)
841 (list :tag "Descriptive Headline" (string :tag "Headline"))
842 (cons :tag "Letter and Command"
843 (string :tag "Command letter")
844 (choice
845 (function)
846 (sexp))))))
848 (defgroup org-cycle nil
849 "Options concerning visibility cycling in Org-mode."
850 :tag "Org Cycle"
851 :group 'org-structure)
853 (defcustom org-cycle-skip-children-state-if-no-children t
854 "Non-nil means skip CHILDREN state in entries that don't have any."
855 :group 'org-cycle
856 :type 'boolean)
858 (defcustom org-cycle-max-level nil
859 "Maximum level which should still be subject to visibility cycling.
860 Levels higher than this will, for cycling, be treated as text, not a headline.
861 When `org-odd-levels-only' is set, a value of N in this variable actually
862 means 2N-1 stars as the limiting headline.
863 When nil, cycle all levels.
864 Note that the limiting level of cycling is also influenced by
865 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
866 `org-inlinetask-min-level' is, cycling will be limited to levels one less
867 than its value."
868 :group 'org-cycle
869 :type '(choice
870 (const :tag "No limit" nil)
871 (integer :tag "Maximum level")))
873 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
874 "Names of drawers. Drawers are not opened by cycling on the headline above.
875 Drawers only open with a TAB on the drawer line itself. A drawer looks like
876 this:
877 :DRAWERNAME:
878 .....
879 :END:
880 The drawer \"PROPERTIES\" is special for capturing properties through
881 the property API.
883 Drawers can be defined on the per-file basis with a line like:
885 #+DRAWERS: HIDDEN STATE PROPERTIES"
886 :group 'org-structure
887 :group 'org-cycle
888 :type '(repeat (string :tag "Drawer Name")))
890 (defcustom org-hide-block-startup nil
891 "Non-nil means entering Org-mode will fold all blocks.
892 This can also be set in on a per-file basis with
894 #+STARTUP: hideblocks
895 #+STARTUP: showblocks"
896 :group 'org-startup
897 :group 'org-cycle
898 :type 'boolean)
900 (defcustom org-cycle-global-at-bob nil
901 "Cycle globally if cursor is at beginning of buffer and not at a headline.
902 This makes it possible to do global cycling without having to use S-TAB or
903 \\[universal-argument] TAB. For this special case to work, the first line
904 of the buffer must not be a headline -- it may be empty or some other text.
905 When used in this way, `org-cycle-hook' is disabled temporarily to make
906 sure the cursor stays at the beginning of the buffer. When this option is
907 nil, don't do anything special at the beginning of the buffer."
908 :group 'org-cycle
909 :type 'boolean)
911 (defcustom org-cycle-level-after-item/entry-creation t
912 "Non-nil means cycle entry level or item indentation in new empty entries.
914 When the cursor is at the end of an empty headline, i.e with only stars
915 and maybe a TODO keyword, TAB will then switch the entry to become a child,
916 and then all possible ancestor states, before returning to the original state.
917 This makes data entry extremely fast: M-RET to create a new headline,
918 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
920 When the cursor is at the end of an empty plain list item, one TAB will
921 make it a subitem, two or more tabs will back up to make this an item
922 higher up in the item hierarchy."
923 :group 'org-cycle
924 :type 'boolean)
926 (defcustom org-cycle-emulate-tab t
927 "Where should `org-cycle' emulate TAB.
928 nil Never
929 white Only in completely white lines
930 whitestart Only at the beginning of lines, before the first non-white char
931 t Everywhere except in headlines
932 exc-hl-bol Everywhere except at the start of a headline
933 If TAB is used in a place where it does not emulate TAB, the current subtree
934 visibility is cycled."
935 :group 'org-cycle
936 :type '(choice (const :tag "Never" nil)
937 (const :tag "Only in completely white lines" white)
938 (const :tag "Before first char in a line" whitestart)
939 (const :tag "Everywhere except in headlines" t)
940 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
943 (defcustom org-cycle-separator-lines 2
944 "Number of empty lines needed to keep an empty line between collapsed trees.
945 If you leave an empty line between the end of a subtree and the following
946 headline, this empty line is hidden when the subtree is folded.
947 Org-mode will leave (exactly) one empty line visible if the number of
948 empty lines is equal or larger to the number given in this variable.
949 So the default 2 means at least 2 empty lines after the end of a subtree
950 are needed to produce free space between a collapsed subtree and the
951 following headline.
953 If the number is negative, and the number of empty lines is at least -N,
954 all empty lines are shown.
956 Special case: when 0, never leave empty lines in collapsed view."
957 :group 'org-cycle
958 :type 'integer)
959 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
961 (defcustom org-pre-cycle-hook nil
962 "Hook that is run before visibility cycling is happening.
963 The function(s) in this hook must accept a single argument which indicates
964 the new state that will be set right after running this hook. The
965 argument is a symbol. Before a global state change, it can have the values
966 `overview', `content', or `all'. Before a local state change, it can have
967 the values `folded', `children', or `subtree'."
968 :group 'org-cycle
969 :type 'hook)
971 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
972 org-cycle-hide-drawers
973 org-cycle-hide-inline-tasks
974 org-cycle-show-empty-lines
975 org-optimize-window-after-visibility-change)
976 "Hook that is run after `org-cycle' has changed the buffer visibility.
977 The function(s) in this hook must accept a single argument which indicates
978 the new state that was set by the most recent `org-cycle' command. The
979 argument is a symbol. After a global state change, it can have the values
980 `overview', `contents', or `all'. After a local state change, it can have
981 the values `folded', `children', or `subtree'."
982 :group 'org-cycle
983 :type 'hook)
985 (defgroup org-edit-structure nil
986 "Options concerning structure editing in Org-mode."
987 :tag "Org Edit Structure"
988 :group 'org-structure)
990 (defcustom org-odd-levels-only nil
991 "Non-nil means skip even levels and only use odd levels for the outline.
992 This has the effect that two stars are being added/taken away in
993 promotion/demotion commands. It also influences how levels are
994 handled by the exporters.
995 Changing it requires restart of `font-lock-mode' to become effective
996 for fontification also in regions already fontified.
997 You may also set this on a per-file basis by adding one of the following
998 lines to the buffer:
1000 #+STARTUP: odd
1001 #+STARTUP: oddeven"
1002 :group 'org-edit-structure
1003 :group 'org-appearance
1004 :type 'boolean)
1006 (defcustom org-adapt-indentation t
1007 "Non-nil means adapt indentation to outline node level.
1009 When this variable is set, Org assumes that you write outlines by
1010 indenting text in each node to align with the headline (after the stars).
1011 The following issues are influenced by this variable:
1013 - When this is set and the *entire* text in an entry is indented, the
1014 indentation is increased by one space in a demotion command, and
1015 decreased by one in a promotion command. If any line in the entry
1016 body starts with text at column 0, indentation is not changed at all.
1018 - Property drawers and planning information is inserted indented when
1019 this variable s set. When nil, they will not be indented.
1021 - TAB indents a line relative to context. The lines below a headline
1022 will be indented when this variable is set.
1024 Note that this is all about true indentation, by adding and removing
1025 space characters. See also `org-indent.el' which does level-dependent
1026 indentation in a virtual way, i.e. at display time in Emacs."
1027 :group 'org-edit-structure
1028 :type 'boolean)
1030 (defcustom org-special-ctrl-a/e nil
1031 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1033 When t, `C-a' will bring back the cursor to the beginning of the
1034 headline text, i.e. after the stars and after a possible TODO
1035 keyword. In an item, this will be the position after bullet and
1036 check-box, if any. When the cursor is already at that position,
1037 another `C-a' will bring it to the beginning of the line.
1039 `C-e' will jump to the end of the headline, ignoring the presence
1040 of tags in the headline. A second `C-e' will then jump to the
1041 true end of the line, after any tags. This also means that, when
1042 this variable is non-nil, `C-e' also will never jump beyond the
1043 end of the heading of a folded section, i.e. not after the
1044 ellipses.
1046 When set to the symbol `reversed', the first `C-a' or `C-e' works
1047 normally, going to the true line boundary first. Only a directly
1048 following, identical keypress will bring the cursor to the
1049 special positions.
1051 This may also be a cons cell where the behavior for `C-a' and
1052 `C-e' is set separately."
1053 :group 'org-edit-structure
1054 :type '(choice
1055 (const :tag "off" nil)
1056 (const :tag "on: after stars/bullet and before tags first" t)
1057 (const :tag "reversed: true line boundary first" reversed)
1058 (cons :tag "Set C-a and C-e separately"
1059 (choice :tag "Special C-a"
1060 (const :tag "off" nil)
1061 (const :tag "on: after stars/bullet first" t)
1062 (const :tag "reversed: before stars/bullet first" reversed))
1063 (choice :tag "Special C-e"
1064 (const :tag "off" nil)
1065 (const :tag "on: before tags first" t)
1066 (const :tag "reversed: after tags first" reversed)))))
1067 (if (fboundp 'defvaralias)
1068 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1070 (defcustom org-special-ctrl-k nil
1071 "Non-nil means `C-k' will behave specially in headlines.
1072 When nil, `C-k' will call the default `kill-line' command.
1073 When t, the following will happen while the cursor is in the headline:
1075 - When the cursor is at the beginning of a headline, kill the entire
1076 line and possible the folded subtree below the line.
1077 - When in the middle of the headline text, kill the headline up to the tags.
1078 - When after the headline text, kill the tags."
1079 :group 'org-edit-structure
1080 :type 'boolean)
1082 (defcustom org-ctrl-k-protect-subtree nil
1083 "Non-nil means, do not delete a hidden subtree with C-k.
1084 When set to the symbol `error', simply throw an error when C-k is
1085 used to kill (part-of) a headline that has hidden text behind it.
1086 Any other non-nil value will result in a query to the user, if it is
1087 OK to kill that hidden subtree. When nil, kill without remorse."
1088 :group 'org-edit-structure
1089 :version "24.1"
1090 :type '(choice
1091 (const :tag "Do not protect hidden subtrees" nil)
1092 (const :tag "Protect hidden subtrees with a security query" t)
1093 (const :tag "Never kill a hidden subtree with C-k" error)))
1095 (defcustom org-catch-invisible-edits nil
1096 "Check if in invisible region before inserting or deleting a character.
1097 Valid values are:
1099 nil Do not check, so just do invisible edits.
1100 error Throw an error and do nothing.
1101 show Make point visible, and do the requested edit.
1102 show-and-error Make point visible, then throw an error and abort the edit.
1103 smart Make point visible, and do insertion/deletion if it is
1104 adjacent to visible text and the change feels predictable.
1105 Never delete a previously invisible character or add in the
1106 middle or right after an invisible region. Basically, this
1107 allows insertion and backward-delete right before ellipses.
1108 FIXME: maybe in this case we should not even show?"
1109 :group 'org-edit-structure
1110 :version "24.1"
1111 :type '(choice
1112 (const :tag "Do not check" nil)
1113 (const :tag "Throw error when trying to edit" error)
1114 (const :tag "Unhide, but do not do the edit" show-and-error)
1115 (const :tag "Show invisible part and do the edit" show)
1116 (const :tag "Be smart and do the right thing" smart)))
1118 (defcustom org-yank-folded-subtrees t
1119 "Non-nil means when yanking subtrees, fold them.
1120 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1121 it starts with a heading and all other headings in it are either children
1122 or siblings, then fold all the subtrees. However, do this only if no
1123 text after the yank would be swallowed into a folded tree by this action."
1124 :group 'org-edit-structure
1125 :type 'boolean)
1127 (defcustom org-yank-adjusted-subtrees nil
1128 "Non-nil means when yanking subtrees, adjust the level.
1129 With this setting, `org-paste-subtree' is used to insert the subtree, see
1130 this function for details."
1131 :group 'org-edit-structure
1132 :type 'boolean)
1134 (defcustom org-M-RET-may-split-line '((default . t))
1135 "Non-nil means M-RET will split the line at the cursor position.
1136 When nil, it will go to the end of the line before making a
1137 new line.
1138 You may also set this option in a different way for different
1139 contexts. Valid contexts are:
1141 headline when creating a new headline
1142 item when creating a new item
1143 table in a table field
1144 default the value to be used for all contexts not explicitly
1145 customized"
1146 :group 'org-structure
1147 :group 'org-table
1148 :type '(choice
1149 (const :tag "Always" t)
1150 (const :tag "Never" nil)
1151 (repeat :greedy t :tag "Individual contexts"
1152 (cons
1153 (choice :tag "Context"
1154 (const headline)
1155 (const item)
1156 (const table)
1157 (const default))
1158 (boolean)))))
1161 (defcustom org-insert-heading-respect-content nil
1162 "Non-nil means insert new headings after the current subtree.
1163 When nil, the new heading is created directly after the current line.
1164 The commands \\[org-insert-heading-respect-content] and
1165 \\[org-insert-todo-heading-respect-content] turn this variable on
1166 for the duration of the command."
1167 :group 'org-structure
1168 :type 'boolean)
1170 (defcustom org-blank-before-new-entry '((heading . auto)
1171 (plain-list-item . auto))
1172 "Should `org-insert-heading' leave a blank line before new heading/item?
1173 The value is an alist, with `heading' and `plain-list-item' as CAR,
1174 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1175 which case Org will look at the surrounding headings/items and try to
1176 make an intelligent decision whether to insert a blank line or not.
1178 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1179 set, the setting here is ignored and no empty line is inserted, to avoid
1180 breaking the list structure."
1181 :group 'org-edit-structure
1182 :type '(list
1183 (cons (const heading)
1184 (choice (const :tag "Never" nil)
1185 (const :tag "Always" t)
1186 (const :tag "Auto" auto)))
1187 (cons (const plain-list-item)
1188 (choice (const :tag "Never" nil)
1189 (const :tag "Always" t)
1190 (const :tag "Auto" auto)))))
1192 (defcustom org-insert-heading-hook nil
1193 "Hook being run after inserting a new heading."
1194 :group 'org-edit-structure
1195 :type 'hook)
1197 (defcustom org-enable-fixed-width-editor t
1198 "Non-nil means lines starting with \":\" are treated as fixed-width.
1199 This currently only means they are never auto-wrapped.
1200 When nil, such lines will be treated like ordinary lines.
1201 See also the QUOTE keyword."
1202 :group 'org-edit-structure
1203 :type 'boolean)
1205 (defcustom org-goto-auto-isearch t
1206 "Non-nil means typing characters in `org-goto' starts incremental search."
1207 :group 'org-edit-structure
1208 :type 'boolean)
1210 (defgroup org-sparse-trees nil
1211 "Options concerning sparse trees in Org-mode."
1212 :tag "Org Sparse Trees"
1213 :group 'org-structure)
1215 (defcustom org-highlight-sparse-tree-matches t
1216 "Non-nil means highlight all matches that define a sparse tree.
1217 The highlights will automatically disappear the next time the buffer is
1218 changed by an edit command."
1219 :group 'org-sparse-trees
1220 :type 'boolean)
1222 (defcustom org-remove-highlights-with-change t
1223 "Non-nil means any change to the buffer will remove temporary highlights.
1224 Such highlights are created by `org-occur' and `org-clock-display'.
1225 When nil, `C-c C-c needs to be used to get rid of the highlights.
1226 The highlights created by `org-preview-latex-fragment' always need
1227 `C-c C-c' to be removed."
1228 :group 'org-sparse-trees
1229 :group 'org-time
1230 :type 'boolean)
1233 (defcustom org-occur-hook '(org-first-headline-recenter)
1234 "Hook that is run after `org-occur' has constructed a sparse tree.
1235 This can be used to recenter the window to show as much of the structure
1236 as possible."
1237 :group 'org-sparse-trees
1238 :type 'hook)
1240 (defgroup org-imenu-and-speedbar nil
1241 "Options concerning imenu and speedbar in Org-mode."
1242 :tag "Org Imenu and Speedbar"
1243 :group 'org-structure)
1245 (defcustom org-imenu-depth 2
1246 "The maximum level for Imenu access to Org-mode headlines.
1247 This also applied for speedbar access."
1248 :group 'org-imenu-and-speedbar
1249 :type 'integer)
1251 (defgroup org-table nil
1252 "Options concerning tables in Org-mode."
1253 :tag "Org Table"
1254 :group 'org)
1256 (defcustom org-enable-table-editor 'optimized
1257 "Non-nil means lines starting with \"|\" are handled by the table editor.
1258 When nil, such lines will be treated like ordinary lines.
1260 When equal to the symbol `optimized', the table editor will be optimized to
1261 do the following:
1262 - Automatic overwrite mode in front of whitespace in table fields.
1263 This makes the structure of the table stay in tact as long as the edited
1264 field does not exceed the column width.
1265 - Minimize the number of realigns. Normally, the table is aligned each time
1266 TAB or RET are pressed to move to another field. With optimization this
1267 happens only if changes to a field might have changed the column width.
1268 Optimization requires replacing the functions `self-insert-command',
1269 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1270 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1271 very good at guessing when a re-align will be necessary, but you can always
1272 force one with \\[org-ctrl-c-ctrl-c].
1274 If you would like to use the optimized version in Org-mode, but the
1275 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1277 This variable can be used to turn on and off the table editor during a session,
1278 but in order to toggle optimization, a restart is required.
1280 See also the variable `org-table-auto-blank-field'."
1281 :group 'org-table
1282 :type '(choice
1283 (const :tag "off" nil)
1284 (const :tag "on" t)
1285 (const :tag "on, optimized" optimized)))
1287 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1288 (version<= emacs-version "24.1"))
1289 "Non-nil means cluster self-insert commands for undo when possible.
1290 If this is set, then, like in the Emacs command loop, 20 consecutive
1291 characters will be undone together.
1292 This is configurable, because there is some impact on typing performance."
1293 :group 'org-table
1294 :type 'boolean)
1296 (defcustom org-table-tab-recognizes-table.el t
1297 "Non-nil means TAB will automatically notice a table.el table.
1298 When it sees such a table, it moves point into it and - if necessary -
1299 calls `table-recognize-table'."
1300 :group 'org-table-editing
1301 :type 'boolean)
1303 (defgroup org-link nil
1304 "Options concerning links in Org-mode."
1305 :tag "Org Link"
1306 :group 'org)
1308 (defvar org-link-abbrev-alist-local nil
1309 "Buffer-local version of `org-link-abbrev-alist', which see.
1310 The value of this is taken from the #+LINK lines.")
1311 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1313 (defcustom org-link-abbrev-alist nil
1314 "Alist of link abbreviations.
1315 The car of each element is a string, to be replaced at the start of a link.
1316 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1317 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1319 [[linkkey:tag][description]]
1321 The 'linkkey' must be a word word, starting with a letter, followed
1322 by letters, numbers, '-' or '_'.
1324 If REPLACE is a string, the tag will simply be appended to create the link.
1325 If the string contains \"%s\", the tag will be inserted there. If the string
1326 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1327 at that point (see the function `url-hexify-string'). If the string contains
1328 the specifier \"%(my-function)\", then the custom function `my-function' will
1329 be invoked: this function takes the tag as its only argument and must return
1330 a string.
1332 REPLACE may also be a function that will be called with the tag as the
1333 only argument to create the link, which should be returned as a string.
1335 See the manual for examples."
1336 :group 'org-link
1337 :type '(repeat
1338 (cons
1339 (string :tag "Protocol")
1340 (choice
1341 (string :tag "Format")
1342 (function)))))
1344 (defcustom org-descriptive-links t
1345 "Non-nil means Org will display descriptive links.
1346 E.g. [[http://orgmode.org][Org website]] will be displayed as
1347 \"Org Website\", hiding the link itself and just displaying its
1348 description. When set to `nil', Org will display the full links
1349 literally.
1351 You can interactively set the value of this variable by calling
1352 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1353 :group 'org-link
1354 :type 'boolean)
1356 (defcustom org-link-file-path-type 'adaptive
1357 "How the path name in file links should be stored.
1358 Valid values are:
1360 relative Relative to the current directory, i.e. the directory of the file
1361 into which the link is being inserted.
1362 absolute Absolute path, if possible with ~ for home directory.
1363 noabbrev Absolute path, no abbreviation of home directory.
1364 adaptive Use relative path for files in the current directory and sub-
1365 directories of it. For other files, use an absolute path."
1366 :group 'org-link
1367 :type '(choice
1368 (const relative)
1369 (const absolute)
1370 (const noabbrev)
1371 (const adaptive)))
1373 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1374 "Types of links that should be activated in Org-mode files.
1375 This is a list of symbols, each leading to the activation of a certain link
1376 type. In principle, it does not hurt to turn on most link types - there may
1377 be a small gain when turning off unused link types. The types are:
1379 bracket The recommended [[link][description]] or [[link]] links with hiding.
1380 angle Links in angular brackets that may contain whitespace like
1381 <bbdb:Carsten Dominik>.
1382 plain Plain links in normal text, no whitespace, like http://google.com.
1383 radio Text that is matched by a radio target, see manual for details.
1384 tag Tag settings in a headline (link to tag search).
1385 date Time stamps (link to calendar).
1386 footnote Footnote labels.
1388 Changing this variable requires a restart of Emacs to become effective."
1389 :group 'org-link
1390 :type '(set :greedy t
1391 (const :tag "Double bracket links" bracket)
1392 (const :tag "Angular bracket links" angle)
1393 (const :tag "Plain text links" plain)
1394 (const :tag "Radio target matches" radio)
1395 (const :tag "Tags" tag)
1396 (const :tag "Timestamps" date)
1397 (const :tag "Footnotes" footnote)))
1399 (defcustom org-make-link-description-function nil
1400 "Function to use to generate link descriptions from links.
1401 If nil the link location will be used. This function must take
1402 two parameters; the first is the link and the second the
1403 description `org-insert-link' has generated, and should return the
1404 description to use."
1405 :group 'org-link
1406 :type 'function)
1408 (defgroup org-link-store nil
1409 "Options concerning storing links in Org-mode."
1410 :tag "Org Store Link"
1411 :group 'org-link)
1413 (defcustom org-url-hexify-p t
1414 "When non-nil, hexify URL when creating a link."
1415 :type 'boolean
1416 ;; :version "24.3"
1417 :group 'org-link-store)
1419 (defcustom org-email-link-description-format "Email %c: %.30s"
1420 "Format of the description part of a link to an email or usenet message.
1421 The following %-escapes will be replaced by corresponding information:
1423 %F full \"From\" field
1424 %f name, taken from \"From\" field, address if no name
1425 %T full \"To\" field
1426 %t first name in \"To\" field, address if no name
1427 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1428 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1429 %s subject
1430 %d date
1431 %m message-id.
1433 You may use normal field width specification between the % and the letter.
1434 This is for example useful to limit the length of the subject.
1436 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1437 :group 'org-link-store
1438 :type 'string)
1440 (defcustom org-from-is-user-regexp
1441 (let (r1 r2)
1442 (when (and user-mail-address (not (string= user-mail-address "")))
1443 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1444 (when (and user-full-name (not (string= user-full-name "")))
1445 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1446 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1447 "Regexp matched against the \"From:\" header of an email or usenet message.
1448 It should match if the message is from the user him/herself."
1449 :group 'org-link-store
1450 :type 'regexp)
1452 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1453 "Non-nil means storing a link to an Org file will use entry IDs.
1455 Note that before this variable is even considered, org-id must be loaded,
1456 so please customize `org-modules' and turn it on.
1458 The variable can have the following values:
1460 t Create an ID if needed to make a link to the current entry.
1462 create-if-interactive
1463 If `org-store-link' is called directly (interactively, as a user
1464 command), do create an ID to support the link. But when doing the
1465 job for capture, only use the ID if it already exists. The
1466 purpose of this setting is to avoid proliferation of unwanted
1467 IDs, just because you happen to be in an Org file when you
1468 call `org-capture' that automatically and preemptively creates a
1469 link. If you do want to get an ID link in a capture template to
1470 an entry not having an ID, create it first by explicitly creating
1471 a link to it, using `C-c C-l' first.
1473 create-if-interactive-and-no-custom-id
1474 Like create-if-interactive, but do not create an ID if there is
1475 a CUSTOM_ID property defined in the entry. This is the default.
1477 use-existing
1478 Use existing ID, do not create one.
1480 nil Never use an ID to make a link, instead link using a text search for
1481 the headline text."
1482 :group 'org-link-store
1483 :type '(choice
1484 (const :tag "Create ID to make link" t)
1485 (const :tag "Create if storing link interactively"
1486 create-if-interactive)
1487 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1488 create-if-interactive-and-no-custom-id)
1489 (const :tag "Only use existing" use-existing)
1490 (const :tag "Do not use ID to create link" nil)))
1492 (defcustom org-context-in-file-links t
1493 "Non-nil means file links from `org-store-link' contain context.
1494 A search string will be added to the file name with :: as separator and
1495 used to find the context when the link is activated by the command
1496 `org-open-at-point'. When this option is t, the entire active region
1497 will be placed in the search string of the file link. If set to a
1498 positive integer, only the first n lines of context will be stored.
1500 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1501 negates this setting for the duration of the command."
1502 :group 'org-link-store
1503 :type '(choice boolean integer))
1505 (defcustom org-keep-stored-link-after-insertion nil
1506 "Non-nil means keep link in list for entire session.
1508 The command `org-store-link' adds a link pointing to the current
1509 location to an internal list. These links accumulate during a session.
1510 The command `org-insert-link' can be used to insert links into any
1511 Org-mode file (offering completion for all stored links). When this
1512 option is nil, every link which has been inserted once using \\[org-insert-link]
1513 will be removed from the list, to make completing the unused links
1514 more efficient."
1515 :group 'org-link-store
1516 :type 'boolean)
1518 (defgroup org-link-follow nil
1519 "Options concerning following links in Org-mode."
1520 :tag "Org Follow Link"
1521 :group 'org-link)
1523 (defcustom org-link-translation-function nil
1524 "Function to translate links with different syntax to Org syntax.
1525 This can be used to translate links created for example by the Planner
1526 or emacs-wiki packages to Org syntax.
1527 The function must accept two parameters, a TYPE containing the link
1528 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1529 which is everything after the link protocol. It should return a cons
1530 with possibly modified values of type and path.
1531 Org contains a function for this, so if you set this variable to
1532 `org-translate-link-from-planner', you should be able follow many
1533 links created by planner."
1534 :group 'org-link-follow
1535 :type 'function)
1537 (defcustom org-follow-link-hook nil
1538 "Hook that is run after a link has been followed."
1539 :group 'org-link-follow
1540 :type 'hook)
1542 (defcustom org-tab-follows-link nil
1543 "Non-nil means on links TAB will follow the link.
1544 Needs to be set before org.el is loaded.
1545 This really should not be used, it does not make sense, and the
1546 implementation is bad."
1547 :group 'org-link-follow
1548 :type 'boolean)
1550 (defcustom org-return-follows-link nil
1551 "Non-nil means on links RET will follow the link."
1552 :group 'org-link-follow
1553 :type 'boolean)
1555 (defcustom org-mouse-1-follows-link
1556 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1557 "Non-nil means mouse-1 on a link will follow the link.
1558 A longer mouse click will still set point. Does not work on XEmacs.
1559 Needs to be set before org.el is loaded."
1560 :group 'org-link-follow
1561 :type 'boolean)
1563 (defcustom org-mark-ring-length 4
1564 "Number of different positions to be recorded in the ring.
1565 Changing this requires a restart of Emacs to work correctly."
1566 :group 'org-link-follow
1567 :type 'integer)
1569 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1570 "Non-nil means internal links in Org files must exactly match a headline.
1571 When nil, the link search tries to match a phrase with all words
1572 in the search text."
1573 :group 'org-link-follow
1574 :version "24.1"
1575 :type '(choice
1576 (const :tag "Use fuzzy text search" nil)
1577 (const :tag "Match only exact headline" t)
1578 (const :tag "Match exact headline or query to create it"
1579 query-to-create)))
1581 (defcustom org-link-frame-setup
1582 '((vm . vm-visit-folder-other-frame)
1583 (vm-imap . vm-visit-imap-folder-other-frame)
1584 (gnus . org-gnus-no-new-news)
1585 (file . find-file-other-window)
1586 (wl . wl-other-frame))
1587 "Setup the frame configuration for following links.
1588 When following a link with Emacs, it may often be useful to display
1589 this link in another window or frame. This variable can be used to
1590 set this up for the different types of links.
1591 For VM, use any of
1592 `vm-visit-folder'
1593 `vm-visit-folder-other-window'
1594 `vm-visit-folder-other-frame'
1595 For Gnus, use any of
1596 `gnus'
1597 `gnus-other-frame'
1598 `org-gnus-no-new-news'
1599 For FILE, use any of
1600 `find-file'
1601 `find-file-other-window'
1602 `find-file-other-frame'
1603 For Wanderlust use any of
1604 `wl'
1605 `wl-other-frame'
1606 For the calendar, use the variable `calendar-setup'.
1607 For BBDB, it is currently only possible to display the matches in
1608 another window."
1609 :group 'org-link-follow
1610 :type '(list
1611 (cons (const vm)
1612 (choice
1613 (const vm-visit-folder)
1614 (const vm-visit-folder-other-window)
1615 (const vm-visit-folder-other-frame)))
1616 (cons (const gnus)
1617 (choice
1618 (const gnus)
1619 (const gnus-other-frame)
1620 (const org-gnus-no-new-news)))
1621 (cons (const file)
1622 (choice
1623 (const find-file)
1624 (const find-file-other-window)
1625 (const find-file-other-frame)))
1626 (cons (const wl)
1627 (choice
1628 (const wl)
1629 (const wl-other-frame)))))
1631 (defcustom org-display-internal-link-with-indirect-buffer nil
1632 "Non-nil means use indirect buffer to display infile links.
1633 Activating internal links (from one location in a file to another location
1634 in the same file) normally just jumps to the location. When the link is
1635 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1636 is displayed in
1637 another window. When this option is set, the other window actually displays
1638 an indirect buffer clone of the current buffer, to avoid any visibility
1639 changes to the current buffer."
1640 :group 'org-link-follow
1641 :type 'boolean)
1643 (defcustom org-open-non-existing-files nil
1644 "Non-nil means `org-open-file' will open non-existing files.
1645 When nil, an error will be generated.
1646 This variable applies only to external applications because they
1647 might choke on non-existing files. If the link is to a file that
1648 will be opened in Emacs, the variable is ignored."
1649 :group 'org-link-follow
1650 :type 'boolean)
1652 (defcustom org-open-directory-means-index-dot-org nil
1653 "Non-nil means a link to a directory really means to index.org.
1654 When nil, following a directory link will run dired or open a finder/explorer
1655 window on that directory."
1656 :group 'org-link-follow
1657 :type 'boolean)
1659 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1660 "Function and arguments to call for following mailto links.
1661 This is a list with the first element being a Lisp function, and the
1662 remaining elements being arguments to the function. In string arguments,
1663 %a will be replaced by the address, and %s will be replaced by the subject
1664 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1665 :group 'org-link-follow
1666 :type '(choice
1667 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1668 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1669 (const :tag "message-mail" (message-mail "%a" "%s"))
1670 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1672 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1673 "Non-nil means ask for confirmation before executing shell links.
1674 Shell links can be dangerous: just think about a link
1676 [[shell:rm -rf ~/*][Google Search]]
1678 This link would show up in your Org-mode document as \"Google Search\",
1679 but really it would remove your entire home directory.
1680 Therefore we advise against setting this variable to nil.
1681 Just change it to `y-or-n-p' if you want to confirm with a
1682 single keystroke rather than having to type \"yes\"."
1683 :group 'org-link-follow
1684 :type '(choice
1685 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1686 (const :tag "with y-or-n (faster)" y-or-n-p)
1687 (const :tag "no confirmation (dangerous)" nil)))
1688 (put 'org-confirm-shell-link-function
1689 'safe-local-variable
1690 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1692 (defcustom org-confirm-shell-link-not-regexp ""
1693 "A regexp to skip confirmation for shell links."
1694 :group 'org-link-follow
1695 :version "24.1"
1696 :type 'regexp)
1698 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1699 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1700 Elisp links can be dangerous: just think about a link
1702 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1704 This link would show up in your Org-mode document as \"Google Search\",
1705 but really it would remove your entire home directory.
1706 Therefore we advise against setting this variable to nil.
1707 Just change it to `y-or-n-p' if you want to confirm with a
1708 single keystroke rather than having to type \"yes\"."
1709 :group 'org-link-follow
1710 :type '(choice
1711 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1712 (const :tag "with y-or-n (faster)" y-or-n-p)
1713 (const :tag "no confirmation (dangerous)" nil)))
1714 (put 'org-confirm-shell-link-function
1715 'safe-local-variable
1716 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1718 (defcustom org-confirm-elisp-link-not-regexp ""
1719 "A regexp to skip confirmation for Elisp links."
1720 :group 'org-link-follow
1721 :version "24.1"
1722 :type 'regexp)
1724 (defconst org-file-apps-defaults-gnu
1725 '((remote . emacs)
1726 (system . mailcap)
1727 (t . mailcap))
1728 "Default file applications on a UNIX or GNU/Linux system.
1729 See `org-file-apps'.")
1731 (defconst org-file-apps-defaults-macosx
1732 '((remote . emacs)
1733 (t . "open %s")
1734 (system . "open %s")
1735 ("ps.gz" . "gv %s")
1736 ("eps.gz" . "gv %s")
1737 ("dvi" . "xdvi %s")
1738 ("fig" . "xfig %s"))
1739 "Default file applications on a MacOS X system.
1740 The system \"open\" is known as a default, but we use X11 applications
1741 for some files for which the OS does not have a good default.
1742 See `org-file-apps'.")
1744 (defconst org-file-apps-defaults-windowsnt
1745 (list
1746 '(remote . emacs)
1747 (cons t
1748 (list (if (featurep 'xemacs)
1749 'mswindows-shell-execute
1750 'w32-shell-execute)
1751 "open" 'file))
1752 (cons 'system
1753 (list (if (featurep 'xemacs)
1754 'mswindows-shell-execute
1755 'w32-shell-execute)
1756 "open" 'file)))
1757 "Default file applications on a Windows NT system.
1758 The system \"open\" is used for most files.
1759 See `org-file-apps'.")
1761 (defcustom org-file-apps
1763 (auto-mode . emacs)
1764 ("\\.mm\\'" . default)
1765 ("\\.x?html?\\'" . default)
1766 ("\\.pdf\\'" . default)
1768 "External applications for opening `file:path' items in a document.
1769 Org-mode uses system defaults for different file types, but
1770 you can use this variable to set the application for a given file
1771 extension. The entries in this list are cons cells where the car identifies
1772 files and the cdr the corresponding command. Possible values for the
1773 file identifier are
1774 \"string\" A string as a file identifier can be interpreted in different
1775 ways, depending on its contents:
1777 - Alphanumeric characters only:
1778 Match links with this file extension.
1779 Example: (\"pdf\" . \"evince %s\")
1780 to open PDFs with evince.
1782 - Regular expression: Match links where the
1783 filename matches the regexp. If you want to
1784 use groups here, use shy groups.
1786 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1787 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1788 to open *.html and *.xhtml with firefox.
1790 - Regular expression which contains (non-shy) groups:
1791 Match links where the whole link, including \"::\", and
1792 anything after that, matches the regexp.
1793 In a custom command string, %1, %2, etc. are replaced with
1794 the parts of the link that were matched by the groups.
1795 For backwards compatibility, if a command string is given
1796 that does not use any of the group matches, this case is
1797 handled identically to the second one (i.e. match against
1798 file name only).
1799 In a custom lisp form, you can access the group matches with
1800 (match-string n link).
1802 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1803 to open [[file:document.pdf::5]] with evince at page 5.
1805 `directory' Matches a directory
1806 `remote' Matches a remote file, accessible through tramp or efs.
1807 Remote files most likely should be visited through Emacs
1808 because external applications cannot handle such paths.
1809 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1810 so all files Emacs knows how to handle. Using this with
1811 command `emacs' will open most files in Emacs. Beware that this
1812 will also open html files inside Emacs, unless you add
1813 (\"html\" . default) to the list as well.
1814 t Default for files not matched by any of the other options.
1815 `system' The system command to open files, like `open' on Windows
1816 and Mac OS X, and mailcap under GNU/Linux. This is the command
1817 that will be selected if you call `C-c C-o' with a double
1818 \\[universal-argument] \\[universal-argument] prefix.
1820 Possible values for the command are:
1821 `emacs' The file will be visited by the current Emacs process.
1822 `default' Use the default application for this file type, which is the
1823 association for t in the list, most likely in the system-specific
1824 part.
1825 This can be used to overrule an unwanted setting in the
1826 system-specific variable.
1827 `system' Use the system command for opening files, like \"open\".
1828 This command is specified by the entry whose car is `system'.
1829 Most likely, the system-specific version of this variable
1830 does define this command, but you can overrule/replace it
1831 here.
1832 string A command to be executed by a shell; %s will be replaced
1833 by the path to the file.
1834 sexp A Lisp form which will be evaluated. The file path will
1835 be available in the Lisp variable `file'.
1836 For more examples, see the system specific constants
1837 `org-file-apps-defaults-macosx'
1838 `org-file-apps-defaults-windowsnt'
1839 `org-file-apps-defaults-gnu'."
1840 :group 'org-link-follow
1841 :type '(repeat
1842 (cons (choice :value ""
1843 (string :tag "Extension")
1844 (const :tag "System command to open files" system)
1845 (const :tag "Default for unrecognized files" t)
1846 (const :tag "Remote file" remote)
1847 (const :tag "Links to a directory" directory)
1848 (const :tag "Any files that have Emacs modes"
1849 auto-mode))
1850 (choice :value ""
1851 (const :tag "Visit with Emacs" emacs)
1852 (const :tag "Use default" default)
1853 (const :tag "Use the system command" system)
1854 (string :tag "Command")
1855 (sexp :tag "Lisp form")))))
1857 (defcustom org-doi-server-url "http://dx.doi.org/"
1858 "The URL of the DOI server."
1859 :type 'string
1860 ;; :version "24.3"
1861 :group 'org-link-follow)
1863 (defgroup org-refile nil
1864 "Options concerning refiling entries in Org-mode."
1865 :tag "Org Refile"
1866 :group 'org)
1868 (defcustom org-directory "~/org"
1869 "Directory with org files.
1870 This is just a default location to look for Org files. There is no need
1871 at all to put your files into this directory. It is only used in the
1872 following situations:
1874 1. When a capture template specifies a target file that is not an
1875 absolute path. The path will then be interpreted relative to
1876 `org-directory'
1877 2. When a capture note is filed away in an interactive way (when exiting the
1878 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1879 with `org-directory' as the default path."
1880 :group 'org-refile
1881 :group 'org-remember
1882 :group 'org-capture
1883 :type 'directory)
1885 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1886 "Default target for storing notes.
1887 Used as a fall back file for org-remember.el and org-capture.el, for
1888 templates that do not specify a target file."
1889 :group 'org-refile
1890 :group 'org-remember
1891 :group 'org-capture
1892 :type '(choice
1893 (const :tag "Default from remember-data-file" nil)
1894 file))
1896 (defcustom org-goto-interface 'outline
1897 "The default interface to be used for `org-goto'.
1898 Allowed values are:
1899 outline The interface shows an outline of the relevant file
1900 and the correct heading is found by moving through
1901 the outline or by searching with incremental search.
1902 outline-path-completion Headlines in the current buffer are offered via
1903 completion. This is the interface also used by
1904 the refile command."
1905 :group 'org-refile
1906 :type '(choice
1907 (const :tag "Outline" outline)
1908 (const :tag "Outline-path-completion" outline-path-completion)))
1910 (defcustom org-goto-max-level 5
1911 "Maximum target level when running `org-goto' with refile interface."
1912 :group 'org-refile
1913 :type 'integer)
1915 (defcustom org-reverse-note-order nil
1916 "Non-nil means store new notes at the beginning of a file or entry.
1917 When nil, new notes will be filed to the end of a file or entry.
1918 This can also be a list with cons cells of regular expressions that
1919 are matched against file names, and values."
1920 :group 'org-remember
1921 :group 'org-capture
1922 :group 'org-refile
1923 :type '(choice
1924 (const :tag "Reverse always" t)
1925 (const :tag "Reverse never" nil)
1926 (repeat :tag "By file name regexp"
1927 (cons regexp boolean))))
1929 (defcustom org-log-refile nil
1930 "Information to record when a task is refiled.
1932 Possible values are:
1934 nil Don't add anything
1935 time Add a time stamp to the task
1936 note Prompt for a note and add it with template `org-log-note-headings'
1938 This option can also be set with on a per-file-basis with
1940 #+STARTUP: nologrefile
1941 #+STARTUP: logrefile
1942 #+STARTUP: lognoterefile
1944 You can have local logging settings for a subtree by setting the LOGGING
1945 property to one or more of these keywords.
1947 When bulk-refiling from the agenda, the value `note' is forbidden and
1948 will temporarily be changed to `time'."
1949 :group 'org-refile
1950 :group 'org-progress
1951 :version "24.1"
1952 :type '(choice
1953 (const :tag "No logging" nil)
1954 (const :tag "Record timestamp" time)
1955 (const :tag "Record timestamp with note." note)))
1957 (defcustom org-refile-targets nil
1958 "Targets for refiling entries with \\[org-refile].
1959 This is a list of cons cells. Each cell contains:
1960 - a specification of the files to be considered, either a list of files,
1961 or a symbol whose function or variable value will be used to retrieve
1962 a file name or a list of file names. If you use `org-agenda-files' for
1963 that, all agenda files will be scanned for targets. Nil means consider
1964 headings in the current buffer.
1965 - A specification of how to find candidate refile targets. This may be
1966 any of:
1967 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1968 This tag has to be present in all target headlines, inheritance will
1969 not be considered.
1970 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1971 todo keyword.
1972 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1973 headlines that are refiling targets.
1974 - a cons cell (:level . N). Any headline of level N is considered 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.
1977 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1978 Note that, when `org-odd-levels-only' is set, level corresponds to
1979 order in hierarchy, not to the number of stars.
1981 Each element of this list generates a set of possible targets.
1982 The union of these sets is presented (with completion) to
1983 the user by `org-refile'.
1985 You can set the variable `org-refile-target-verify-function' to a function
1986 to verify each headline found by the simple criteria above.
1988 When this variable is nil, all top-level headlines in the current buffer
1989 are used, equivalent to the value `((nil . (:level . 1))'."
1990 :group 'org-refile
1991 :type '(repeat
1992 (cons
1993 (choice :value org-agenda-files
1994 (const :tag "All agenda files" org-agenda-files)
1995 (const :tag "Current buffer" nil)
1996 (function) (variable) (file))
1997 (choice :tag "Identify target headline by"
1998 (cons :tag "Specific tag" (const :value :tag) (string))
1999 (cons :tag "TODO keyword" (const :value :todo) (string))
2000 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2001 (cons :tag "Level number" (const :value :level) (integer))
2002 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2004 (defcustom org-refile-target-verify-function nil
2005 "Function to verify if the headline at point should be a refile target.
2006 The function will be called without arguments, with point at the
2007 beginning of the headline. It should return t and leave point
2008 where it is if the headline is a valid target for refiling.
2010 If the target should not be selected, the function must return nil.
2011 In addition to this, it may move point to a place from where the search
2012 should be continued. For example, the function may decide that the entire
2013 subtree of the current entry should be excluded and move point to the end
2014 of the subtree."
2015 :group 'org-refile
2016 :type 'function)
2018 (defcustom org-refile-use-cache nil
2019 "Non-nil means cache refile targets to speed up the process.
2020 The cache for a particular file will be updated automatically when
2021 the buffer has been killed, or when any of the marker used for flagging
2022 refile targets no longer points at a live buffer.
2023 If you have added new entries to a buffer that might themselves be targets,
2024 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2025 find that easier, `C-u C-u C-u C-c C-w'."
2026 :group 'org-refile
2027 :version "24.1"
2028 :type 'boolean)
2030 (defcustom org-refile-use-outline-path nil
2031 "Non-nil means provide refile targets as paths.
2032 So a level 3 headline will be available as level1/level2/level3.
2034 When the value is `file', also include the file name (without directory)
2035 into the path. In this case, you can also stop the completion after
2036 the file name, to get entries inserted as top level in the file.
2038 When `full-file-path', include the full file path."
2039 :group 'org-refile
2040 :type '(choice
2041 (const :tag "Not" nil)
2042 (const :tag "Yes" t)
2043 (const :tag "Start with file name" file)
2044 (const :tag "Start with full file path" full-file-path)))
2046 (defcustom org-outline-path-complete-in-steps t
2047 "Non-nil means complete the outline path in hierarchical steps.
2048 When Org-mode uses the refile interface to select an outline path
2049 \(see variable `org-refile-use-outline-path'), the completion of
2050 the path can be done is a single go, or if can be done in steps down
2051 the headline hierarchy. Going in steps is probably the best if you
2052 do not use a special completion package like `ido' or `icicles'.
2053 However, when using these packages, going in one step can be very
2054 fast, while still showing the whole path to the entry."
2055 :group 'org-refile
2056 :type 'boolean)
2058 (defcustom org-refile-allow-creating-parent-nodes nil
2059 "Non-nil means allow to create new nodes as refile targets.
2060 New nodes are then created by adding \"/new node name\" to the completion
2061 of an existing node. When the value of this variable is `confirm',
2062 new node creation must be confirmed by the user (recommended)
2063 When nil, the completion must match an existing entry.
2065 Note that, if the new heading is not seen by the criteria
2066 listed in `org-refile-targets', multiple instances of the same
2067 heading would be created by trying again to file under the new
2068 heading."
2069 :group 'org-refile
2070 :type '(choice
2071 (const :tag "Never" nil)
2072 (const :tag "Always" t)
2073 (const :tag "Prompt for confirmation" confirm)))
2075 (defcustom org-refile-active-region-within-subtree nil
2076 "Non-nil means also refile active region within a subtree.
2078 By default `org-refile' doesn't allow refiling regions if they
2079 don't contain a set of subtrees, but it might be convenient to
2080 do so sometimes: in that case, the first line of the region is
2081 converted to a headline before refiling."
2082 :group 'org-refile
2083 :version "24.1"
2084 :type 'boolean)
2086 (defgroup org-todo nil
2087 "Options concerning TODO items in Org-mode."
2088 :tag "Org TODO"
2089 :group 'org)
2091 (defgroup org-progress nil
2092 "Options concerning Progress logging in Org-mode."
2093 :tag "Org Progress"
2094 :group 'org-time)
2096 (defvar org-todo-interpretation-widgets
2097 '((:tag "Sequence (cycling hits every state)" sequence)
2098 (:tag "Type (cycling directly to DONE)" type))
2099 "The available interpretation symbols for customizing `org-todo-keywords'.
2100 Interested libraries should add to this list.")
2102 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2103 "List of TODO entry keyword sequences and their interpretation.
2104 \\<org-mode-map>This is a list of sequences.
2106 Each sequence starts with a symbol, either `sequence' or `type',
2107 indicating if the keywords should be interpreted as a sequence of
2108 action steps, or as different types of TODO items. The first
2109 keywords are states requiring action - these states will select a headline
2110 for inclusion into the global TODO list Org-mode produces. If one of
2111 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2112 signify that no further action is necessary. If \"|\" is not found,
2113 the last keyword is treated as the only DONE state of the sequence.
2115 The command \\[org-todo] cycles an entry through these states, and one
2116 additional state where no keyword is present. For details about this
2117 cycling, see the manual.
2119 TODO keywords and interpretation can also be set on a per-file basis with
2120 the special #+SEQ_TODO and #+TYP_TODO lines.
2122 Each keyword can optionally specify a character for fast state selection
2123 \(in combination with the variable `org-use-fast-todo-selection')
2124 and specifiers for state change logging, using the same syntax that
2125 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2126 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2127 indicates to record a time stamp each time this state is selected.
2129 Each keyword may also specify if a timestamp or a note should be
2130 recorded when entering or leaving the state, by adding additional
2131 characters in the parenthesis after the keyword. This looks like this:
2132 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2133 record only the time of the state change. With X and Y being either
2134 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2135 Y when leaving the state if and only if the *target* state does not
2136 define X. You may omit any of the fast-selection key or X or /Y,
2137 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2139 For backward compatibility, this variable may also be just a list
2140 of keywords. In this case the interpretation (sequence or type) will be
2141 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2142 :group 'org-todo
2143 :group 'org-keywords
2144 :type '(choice
2145 (repeat :tag "Old syntax, just keywords"
2146 (string :tag "Keyword"))
2147 (repeat :tag "New syntax"
2148 (cons
2149 (choice
2150 :tag "Interpretation"
2151 ;;Quick and dirty way to see
2152 ;;`org-todo-interpretations'. This takes the
2153 ;;place of item arguments
2154 :convert-widget
2155 (lambda (widget)
2156 (widget-put widget
2157 :args (mapcar
2158 #'(lambda (x)
2159 (widget-convert
2160 (cons 'const x)))
2161 org-todo-interpretation-widgets))
2162 widget))
2163 (repeat
2164 (string :tag "Keyword"))))))
2166 (defvar org-todo-keywords-1 nil
2167 "All TODO and DONE keywords active in a buffer.")
2168 (make-variable-buffer-local 'org-todo-keywords-1)
2169 (defvar org-todo-keywords-for-agenda nil)
2170 (defvar org-done-keywords-for-agenda nil)
2171 (defvar org-drawers-for-agenda nil)
2172 (defvar org-todo-keyword-alist-for-agenda nil)
2173 (defvar org-tag-alist-for-agenda nil)
2174 (defvar org-agenda-contributing-files nil)
2175 (defvar org-not-done-keywords nil)
2176 (make-variable-buffer-local 'org-not-done-keywords)
2177 (defvar org-done-keywords nil)
2178 (make-variable-buffer-local 'org-done-keywords)
2179 (defvar org-todo-heads nil)
2180 (make-variable-buffer-local 'org-todo-heads)
2181 (defvar org-todo-sets nil)
2182 (make-variable-buffer-local 'org-todo-sets)
2183 (defvar org-todo-log-states nil)
2184 (make-variable-buffer-local 'org-todo-log-states)
2185 (defvar org-todo-kwd-alist nil)
2186 (make-variable-buffer-local 'org-todo-kwd-alist)
2187 (defvar org-todo-key-alist nil)
2188 (make-variable-buffer-local 'org-todo-key-alist)
2189 (defvar org-todo-key-trigger nil)
2190 (make-variable-buffer-local 'org-todo-key-trigger)
2192 (defcustom org-todo-interpretation 'sequence
2193 "Controls how TODO keywords are interpreted.
2194 This variable is in principle obsolete and is only used for
2195 backward compatibility, if the interpretation of todo keywords is
2196 not given already in `org-todo-keywords'. See that variable for
2197 more information."
2198 :group 'org-todo
2199 :group 'org-keywords
2200 :type '(choice (const sequence)
2201 (const type)))
2203 (defcustom org-use-fast-todo-selection t
2204 "Non-nil means use the fast todo selection scheme with C-c C-t.
2205 This variable describes if and under what circumstances the cycling
2206 mechanism for TODO keywords will be replaced by a single-key, direct
2207 selection scheme.
2209 When nil, fast selection is never used.
2211 When the symbol `prefix', it will be used when `org-todo' is called
2212 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2213 `C-u t' in an agenda buffer.
2215 When t, fast selection is used by default. In this case, the prefix
2216 argument forces cycling instead.
2218 In all cases, the special interface is only used if access keys have
2219 actually been assigned by the user, i.e. if keywords in the configuration
2220 are followed by a letter in parenthesis, like TODO(t)."
2221 :group 'org-todo
2222 :type '(choice
2223 (const :tag "Never" nil)
2224 (const :tag "By default" t)
2225 (const :tag "Only with C-u C-c C-t" prefix)))
2227 (defcustom org-provide-todo-statistics t
2228 "Non-nil means update todo statistics after insert and toggle.
2229 ALL-HEADLINES means update todo statistics by including headlines
2230 with no TODO keyword as well, counting them as not done.
2231 A list of TODO keywords means the same, but skip keywords that are
2232 not in this list.
2234 When this is set, todo statistics is updated in the parent of the
2235 current entry each time a todo state is changed."
2236 :group 'org-todo
2237 :type '(choice
2238 (const :tag "Yes, only for TODO entries" t)
2239 (const :tag "Yes, including all entries" 'all-headlines)
2240 (repeat :tag "Yes, for TODOs in this list"
2241 (string :tag "TODO keyword"))
2242 (other :tag "No TODO statistics" nil)))
2244 (defcustom org-hierarchical-todo-statistics t
2245 "Non-nil means TODO statistics covers just direct children.
2246 When nil, all entries in the subtree are considered.
2247 This has only an effect if `org-provide-todo-statistics' is set.
2248 To set this to nil for only a single subtree, use a COOKIE_DATA
2249 property and include the word \"recursive\" into the value."
2250 :group 'org-todo
2251 :type 'boolean)
2253 (defcustom org-after-todo-state-change-hook nil
2254 "Hook which is run after the state of a TODO item was changed.
2255 The new state (a string with a TODO keyword, or nil) is available in the
2256 Lisp variable `org-state'."
2257 :group 'org-todo
2258 :type 'hook)
2260 (defvar org-blocker-hook nil
2261 "Hook for functions that are allowed to block a state change.
2263 Each function gets as its single argument a property list, see
2264 `org-trigger-hook' for more information about this list.
2266 If any of the functions in this hook returns nil, the state change
2267 is blocked.")
2269 (defvar org-trigger-hook nil
2270 "Hook for functions that are triggered by a state change.
2272 Each function gets as its single argument a property list with at least
2273 the following elements:
2275 (:type type-of-change :position pos-at-entry-start
2276 :from old-state :to new-state)
2278 Depending on the type, more properties may be present.
2280 This mechanism is currently implemented for:
2282 TODO state changes
2283 ------------------
2284 :type todo-state-change
2285 :from previous state (keyword as a string), or nil, or a symbol
2286 'todo' or 'done', to indicate the general type of state.
2287 :to new state, like in :from")
2289 (defcustom org-enforce-todo-dependencies nil
2290 "Non-nil means undone TODO entries will block switching the parent to DONE.
2291 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2292 be blocked if any prior sibling is not yet done.
2293 Finally, if the parent is blocked because of ordered siblings of its own,
2294 the child will also be blocked."
2295 :set (lambda (var val)
2296 (set var val)
2297 (if val
2298 (add-hook 'org-blocker-hook
2299 'org-block-todo-from-children-or-siblings-or-parent)
2300 (remove-hook 'org-blocker-hook
2301 'org-block-todo-from-children-or-siblings-or-parent)))
2302 :group 'org-todo
2303 :type 'boolean)
2305 (defcustom org-enforce-todo-checkbox-dependencies nil
2306 "Non-nil means unchecked boxes will block switching the parent to DONE.
2307 When this is nil, checkboxes have no influence on switching TODO states.
2308 When non-nil, you first need to check off all check boxes before the TODO
2309 entry can be switched to DONE.
2310 This variable needs to be set before org.el is loaded, and you need to
2311 restart Emacs after a change to make the change effective. The only way
2312 to change is while Emacs is running is through the customize interface."
2313 :set (lambda (var val)
2314 (set var val)
2315 (if val
2316 (add-hook 'org-blocker-hook
2317 'org-block-todo-from-checkboxes)
2318 (remove-hook 'org-blocker-hook
2319 'org-block-todo-from-checkboxes)))
2320 :group 'org-todo
2321 :type 'boolean)
2323 (defcustom org-treat-insert-todo-heading-as-state-change nil
2324 "Non-nil means inserting a TODO heading is treated as state change.
2325 So when the command \\[org-insert-todo-heading] is used, state change
2326 logging will apply if appropriate. When nil, the new TODO item will
2327 be inserted directly, and no logging will take place."
2328 :group 'org-todo
2329 :type 'boolean)
2331 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2332 "Non-nil means switching TODO states with S-cursor counts as state change.
2333 This is the default behavior. However, setting this to nil allows a
2334 convenient way to select a TODO state and bypass any logging associated
2335 with that."
2336 :group 'org-todo
2337 :type 'boolean)
2339 (defcustom org-todo-state-tags-triggers nil
2340 "Tag changes that should be triggered by TODO state changes.
2341 This is a list. Each entry is
2343 (state-change (tag . flag) .......)
2345 State-change can be a string with a state, and empty string to indicate the
2346 state that has no TODO keyword, or it can be one of the symbols `todo'
2347 or `done', meaning any not-done or done state, respectively."
2348 :group 'org-todo
2349 :group 'org-tags
2350 :type '(repeat
2351 (cons (choice :tag "When changing to"
2352 (const :tag "Not-done state" todo)
2353 (const :tag "Done state" done)
2354 (string :tag "State"))
2355 (repeat
2356 (cons :tag "Tag action"
2357 (string :tag "Tag")
2358 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2360 (defcustom org-log-done nil
2361 "Information to record when a task moves to the DONE state.
2363 Possible values are:
2365 nil Don't add anything, just change the keyword
2366 time Add a time stamp to the task
2367 note Prompt for a note and add it with template `org-log-note-headings'
2369 This option can also be set with on a per-file-basis with
2371 #+STARTUP: nologdone
2372 #+STARTUP: logdone
2373 #+STARTUP: lognotedone
2375 You can have local logging settings for a subtree by setting the LOGGING
2376 property to one or more of these keywords."
2377 :group 'org-todo
2378 :group 'org-progress
2379 :type '(choice
2380 (const :tag "No logging" nil)
2381 (const :tag "Record CLOSED timestamp" time)
2382 (const :tag "Record CLOSED timestamp with note." note)))
2384 ;; Normalize old uses of org-log-done.
2385 (cond
2386 ((eq org-log-done t) (setq org-log-done 'time))
2387 ((and (listp org-log-done) (memq 'done org-log-done))
2388 (setq org-log-done 'note)))
2390 (defcustom org-log-reschedule nil
2391 "Information to record when the scheduling date of a tasks is modified.
2393 Possible values are:
2395 nil Don't add anything, just change the date
2396 time Add a time stamp to the task
2397 note Prompt for a note and add it with template `org-log-note-headings'
2399 This option can also be set with on a per-file-basis with
2401 #+STARTUP: nologreschedule
2402 #+STARTUP: logreschedule
2403 #+STARTUP: lognotereschedule"
2404 :group 'org-todo
2405 :group 'org-progress
2406 :type '(choice
2407 (const :tag "No logging" nil)
2408 (const :tag "Record timestamp" time)
2409 (const :tag "Record timestamp with note." note)))
2411 (defcustom org-log-redeadline nil
2412 "Information to record when the deadline date of a tasks is modified.
2414 Possible values are:
2416 nil Don't add anything, just change the date
2417 time Add a time stamp to the task
2418 note Prompt for a note and add it with template `org-log-note-headings'
2420 This option can also be set with on a per-file-basis with
2422 #+STARTUP: nologredeadline
2423 #+STARTUP: logredeadline
2424 #+STARTUP: lognoteredeadline
2426 You can have local logging settings for a subtree by setting the LOGGING
2427 property to one or more of these keywords."
2428 :group 'org-todo
2429 :group 'org-progress
2430 :type '(choice
2431 (const :tag "No logging" nil)
2432 (const :tag "Record timestamp" time)
2433 (const :tag "Record timestamp with note." note)))
2435 (defcustom org-log-note-clock-out nil
2436 "Non-nil means record a note when clocking out of an item.
2437 This can also be configured on a per-file basis by adding one of
2438 the following lines anywhere in the buffer:
2440 #+STARTUP: lognoteclock-out
2441 #+STARTUP: nolognoteclock-out"
2442 :group 'org-todo
2443 :group 'org-progress
2444 :type 'boolean)
2446 (defcustom org-log-done-with-time t
2447 "Non-nil means the CLOSED time stamp will contain date and time.
2448 When nil, only the date will be recorded."
2449 :group 'org-progress
2450 :type 'boolean)
2452 (defcustom org-log-note-headings
2453 '((done . "CLOSING NOTE %t")
2454 (state . "State %-12s from %-12S %t")
2455 (note . "Note taken on %t")
2456 (reschedule . "Rescheduled from %S on %t")
2457 (delschedule . "Not scheduled, was %S on %t")
2458 (redeadline . "New deadline from %S on %t")
2459 (deldeadline . "Removed deadline, was %S on %t")
2460 (refile . "Refiled on %t")
2461 (clock-out . ""))
2462 "Headings for notes added to entries.
2463 The value is an alist, with the car being a symbol indicating the note
2464 context, and the cdr is the heading to be used. The heading may also be the
2465 empty string.
2466 %t in the heading will be replaced by a time stamp.
2467 %T will be an active time stamp instead the default inactive one
2468 %d will be replaced by a short-format time stamp.
2469 %D will be replaced by an active short-format time stamp.
2470 %s will be replaced by the new TODO state, in double quotes.
2471 %S will be replaced by the old TODO state, in double quotes.
2472 %u will be replaced by the user name.
2473 %U will be replaced by the full user name.
2475 In fact, it is not a good idea to change the `state' entry, because
2476 agenda log mode depends on the format of these entries."
2477 :group 'org-todo
2478 :group 'org-progress
2479 :type '(list :greedy t
2480 (cons (const :tag "Heading when closing an item" done) string)
2481 (cons (const :tag
2482 "Heading when changing todo state (todo sequence only)"
2483 state) string)
2484 (cons (const :tag "Heading when just taking a note" note) string)
2485 (cons (const :tag "Heading when clocking out" clock-out) string)
2486 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2487 (cons (const :tag "Heading when rescheduling" reschedule) string)
2488 (cons (const :tag "Heading when changing deadline" redeadline) string)
2489 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2490 (cons (const :tag "Heading when refiling" refile) string)))
2492 (unless (assq 'note org-log-note-headings)
2493 (push '(note . "%t") org-log-note-headings))
2495 (defcustom org-log-into-drawer nil
2496 "Non-nil means insert state change notes and time stamps into a drawer.
2497 When nil, state changes notes will be inserted after the headline and
2498 any scheduling and clock lines, but not inside a drawer.
2500 The value of this variable should be the name of the drawer to use.
2501 LOGBOOK is proposed as the default drawer for this purpose, you can
2502 also set this to a string to define the drawer of your choice.
2504 A value of t is also allowed, representing \"LOGBOOK\".
2506 If this variable is set, `org-log-state-notes-insert-after-drawers'
2507 will be ignored.
2509 You can set the property LOG_INTO_DRAWER to overrule this setting for
2510 a subtree."
2511 :group 'org-todo
2512 :group 'org-progress
2513 :type '(choice
2514 (const :tag "Not into a drawer" nil)
2515 (const :tag "LOGBOOK" t)
2516 (string :tag "Other")))
2518 (if (fboundp 'defvaralias)
2519 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2521 (defun org-log-into-drawer ()
2522 "Return the value of `org-log-into-drawer', but let properties overrule.
2523 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2524 used instead of the default value."
2525 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2526 (cond
2527 ((or (not p) (equal p "nil")) org-log-into-drawer)
2528 ((equal p "t") "LOGBOOK")
2529 (t p))))
2531 (defcustom org-log-state-notes-insert-after-drawers nil
2532 "Non-nil means insert state change notes after any drawers in entry.
2533 Only the drawers that *immediately* follow the headline and the
2534 deadline/scheduled line are skipped.
2535 When nil, insert notes right after the heading and perhaps the line
2536 with deadline/scheduling if present.
2538 This variable will have no effect if `org-log-into-drawer' is
2539 set."
2540 :group 'org-todo
2541 :group 'org-progress
2542 :type 'boolean)
2544 (defcustom org-log-states-order-reversed t
2545 "Non-nil means the latest state note will be directly after heading.
2546 When nil, the state change notes will be ordered according to time."
2547 :group 'org-todo
2548 :group 'org-progress
2549 :type 'boolean)
2551 (defcustom org-todo-repeat-to-state nil
2552 "The TODO state to which a repeater should return the repeating task.
2553 By default this is the first task in a TODO sequence, or the previous state
2554 in a TODO_TYP set. But you can specify another task here.
2555 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2556 :group 'org-todo
2557 :version "24.1"
2558 :type '(choice (const :tag "Head of sequence" nil)
2559 (string :tag "Specific state")))
2561 (defcustom org-log-repeat 'time
2562 "Non-nil means record moving through the DONE state when triggering repeat.
2563 An auto-repeating task is immediately switched back to TODO when
2564 marked DONE. If you are not logging state changes (by adding \"@\"
2565 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2566 record a closing note, there will be no record of the task moving
2567 through DONE. This variable forces taking a note anyway.
2569 nil Don't force a record
2570 time Record a time stamp
2571 note Prompt for a note and add it with template `org-log-note-headings'
2573 This option can also be set with on a per-file-basis with
2575 #+STARTUP: nologrepeat
2576 #+STARTUP: logrepeat
2577 #+STARTUP: lognoterepeat
2579 You can have local logging settings for a subtree by setting the LOGGING
2580 property to one or more of these keywords."
2581 :group 'org-todo
2582 :group 'org-progress
2583 :type '(choice
2584 (const :tag "Don't force a record" nil)
2585 (const :tag "Force recording the DONE state" time)
2586 (const :tag "Force recording a note with the DONE state" note)))
2589 (defgroup org-priorities nil
2590 "Priorities in Org-mode."
2591 :tag "Org Priorities"
2592 :group 'org-todo)
2594 (defcustom org-enable-priority-commands t
2595 "Non-nil means priority commands are active.
2596 When nil, these commands will be disabled, so that you never accidentally
2597 set a priority."
2598 :group 'org-priorities
2599 :type 'boolean)
2601 (defcustom org-highest-priority ?A
2602 "The highest priority of TODO items. A character like ?A, ?B etc.
2603 Must have a smaller ASCII number than `org-lowest-priority'."
2604 :group 'org-priorities
2605 :type 'character)
2607 (defcustom org-lowest-priority ?C
2608 "The lowest priority of TODO items. A character like ?A, ?B etc.
2609 Must have a larger ASCII number than `org-highest-priority'."
2610 :group 'org-priorities
2611 :type 'character)
2613 (defcustom org-default-priority ?B
2614 "The default priority of TODO items.
2615 This is the priority an item gets if no explicit priority is given.
2616 When starting to cycle on an empty priority the first step in the cycle
2617 depends on `org-priority-start-cycle-with-default'. The resulting first
2618 step priority must not exceed the range from `org-highest-priority' to
2619 `org-lowest-priority' which means that `org-default-priority' has to be
2620 in this range exclusive or inclusive the range boundaries. Else the
2621 first step refuses to set the default and the second will fall back
2622 to (depending on the command used) the highest or lowest priority."
2623 :group 'org-priorities
2624 :type 'character)
2626 (defcustom org-priority-start-cycle-with-default t
2627 "Non-nil means start with default priority when starting to cycle.
2628 When this is nil, the first step in the cycle will be (depending on the
2629 command used) one higher or lower than the default priority.
2630 See also `org-default-priority'."
2631 :group 'org-priorities
2632 :type 'boolean)
2634 (defcustom org-get-priority-function nil
2635 "Function to extract the priority from a string.
2636 The string is normally the headline. If this is nil Org computes the
2637 priority from the priority cookie like [#A] in the headline. It returns
2638 an integer, increasing by 1000 for each priority level.
2639 The user can set a different function here, which should take a string
2640 as an argument and return the numeric priority."
2641 :group 'org-priorities
2642 :version "24.1"
2643 :type 'function)
2645 (defgroup org-time nil
2646 "Options concerning time stamps and deadlines in Org-mode."
2647 :tag "Org Time"
2648 :group 'org)
2650 (defcustom org-insert-labeled-timestamps-at-point nil
2651 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2652 When nil, these labeled time stamps are forces into the second line of an
2653 entry, just after the headline. When scheduling from the global TODO list,
2654 the time stamp will always be forced into the second line."
2655 :group 'org-time
2656 :type 'boolean)
2658 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2659 "Formats for `format-time-string' which are used for time stamps.
2660 It is not recommended to change this constant.")
2662 (defcustom org-time-stamp-rounding-minutes '(0 5)
2663 "Number of minutes to round time stamps to.
2664 These are two values, the first applies when first creating a time stamp.
2665 The second applies when changing it with the commands `S-up' and `S-down'.
2666 When changing the time stamp, this means that it will change in steps
2667 of N minutes, as given by the second value.
2669 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2670 numbers should be factors of 60, so for example 5, 10, 15.
2672 When this is larger than 1, you can still force an exact time stamp by using
2673 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2674 and by using a prefix arg to `S-up/down' to specify the exact number
2675 of minutes to shift."
2676 :group 'org-time
2677 :get #'(lambda (var) ; Make sure both elements are there
2678 (if (integerp (default-value var))
2679 (list (default-value var) 5)
2680 (default-value var)))
2681 :type '(list
2682 (integer :tag "when inserting times")
2683 (integer :tag "when modifying times")))
2685 ;; Normalize old customizations of this variable.
2686 (when (integerp org-time-stamp-rounding-minutes)
2687 (setq org-time-stamp-rounding-minutes
2688 (list org-time-stamp-rounding-minutes
2689 org-time-stamp-rounding-minutes)))
2691 (defcustom org-display-custom-times nil
2692 "Non-nil means overlay custom formats over all time stamps.
2693 The formats are defined through the variable `org-time-stamp-custom-formats'.
2694 To turn this on on a per-file basis, insert anywhere in the file:
2695 #+STARTUP: customtime"
2696 :group 'org-time
2697 :set 'set-default
2698 :type 'sexp)
2699 (make-variable-buffer-local 'org-display-custom-times)
2701 (defcustom org-time-stamp-custom-formats
2702 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2703 "Custom formats for time stamps. See `format-time-string' for the syntax.
2704 These are overlaid over the default ISO format if the variable
2705 `org-display-custom-times' is set. Time like %H:%M should be at the
2706 end of the second format. The custom formats are also honored by export
2707 commands, if custom time display is turned on at the time of export."
2708 :group 'org-time
2709 :type 'sexp)
2711 (defun org-time-stamp-format (&optional long inactive)
2712 "Get the right format for a time string."
2713 (let ((f (if long (cdr org-time-stamp-formats)
2714 (car org-time-stamp-formats))))
2715 (if inactive
2716 (concat "[" (substring f 1 -1) "]")
2717 f)))
2719 (defcustom org-time-clocksum-format "%d:%02d"
2720 "The format string used when creating CLOCKSUM lines.
2721 This is also used when org-mode generates a time duration."
2722 :group 'org-time
2723 :type 'string)
2725 (defcustom org-time-clocksum-use-fractional nil
2726 "If non-nil, \\[org-clock-display] uses fractional times.
2727 org-mode generates a time duration."
2728 :group 'org-time
2729 :type 'boolean)
2731 (defcustom org-time-clocksum-fractional-format "%.2f"
2732 "The format string used when creating CLOCKSUM lines, or when
2733 org-mode generates a time duration."
2734 :group 'org-time
2735 :type 'string)
2737 (defcustom org-deadline-warning-days 14
2738 "No. of days before expiration during which a deadline becomes active.
2739 This variable governs the display in sparse trees and in the agenda.
2740 When 0 or negative, it means use this number (the absolute value of it)
2741 even if a deadline has a different individual lead time specified.
2743 Custom commands can set this variable in the options section."
2744 :group 'org-time
2745 :group 'org-agenda-daily/weekly
2746 :type 'integer)
2748 (defcustom org-read-date-prefer-future t
2749 "Non-nil means assume future for incomplete date input from user.
2750 This affects the following situations:
2751 1. The user gives a month but not a year.
2752 For example, if it is April and you enter \"feb 2\", this will be read
2753 as Feb 2, *next* year. \"May 5\", however, will be this year.
2754 2. The user gives a day, but no month.
2755 For example, if today is the 15th, and you enter \"3\", Org-mode will
2756 read this as the third of *next* month. However, if you enter \"17\",
2757 it will be considered as *this* month.
2759 If you set this variable to the symbol `time', then also the following
2760 will work:
2762 3. If the user gives a time.
2763 If the time is before now, it will be interpreted as tomorrow.
2765 Currently none of this works for ISO week specifications.
2767 When this option is nil, the current day, month and year will always be
2768 used as defaults.
2770 See also `org-agenda-jump-prefer-future'."
2771 :group 'org-time
2772 :type '(choice
2773 (const :tag "Never" nil)
2774 (const :tag "Check month and day" t)
2775 (const :tag "Check month, day, and time" time)))
2777 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2778 "Should the agenda jump command prefer the future for incomplete dates?
2779 The default is to do the same as configured in `org-read-date-prefer-future'.
2780 But you can also set a deviating value here.
2781 This may t or nil, or the symbol `org-read-date-prefer-future'."
2782 :group 'org-agenda
2783 :group 'org-time
2784 :version "24.1"
2785 :type '(choice
2786 (const :tag "Use org-read-date-prefer-future"
2787 org-read-date-prefer-future)
2788 (const :tag "Never" nil)
2789 (const :tag "Always" t)))
2791 (defcustom org-read-date-force-compatible-dates t
2792 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2794 Depending on the system Emacs is running on, certain dates cannot
2795 be represented with the type used internally to represent time.
2796 Dates between 1970-1-1 and 2038-1-1 can always be represented
2797 correctly. Some systems allow for earlier dates, some for later,
2798 some for both. One way to find out it to insert any date into an
2799 Org buffer, putting the cursor on the year and hitting S-up and
2800 S-down to test the range.
2802 When this variable is set to t, the date/time prompt will not let
2803 you specify dates outside the 1970-2037 range, so it is certain that
2804 these dates will work in whatever version of Emacs you are
2805 running, and also that you can move a file from one Emacs implementation
2806 to another. WHenever Org is forcing the year for you, it will display
2807 a message and beep.
2809 When this variable is nil, Org will check if the date is
2810 representable in the specific Emacs implementation you are using.
2811 If not, it will force a year, usually the current year, and beep
2812 to remind you. Currently this setting is not recommended because
2813 the likelihood that you will open your Org files in an Emacs that
2814 has limited date range is not negligible.
2816 A workaround for this problem is to use diary sexp dates for time
2817 stamps outside of this range."
2818 :group 'org-time
2819 :version "24.1"
2820 :type 'boolean)
2822 (defcustom org-read-date-display-live t
2823 "Non-nil means display current interpretation of date prompt live.
2824 This display will be in an overlay, in the minibuffer."
2825 :group 'org-time
2826 :type 'boolean)
2828 (defcustom org-read-date-popup-calendar t
2829 "Non-nil means pop up a calendar when prompting for a date.
2830 In the calendar, the date can be selected with mouse-1. However, the
2831 minibuffer will also be active, and you can simply enter the date as well.
2832 When nil, only the minibuffer will be available."
2833 :group 'org-time
2834 :type 'boolean)
2835 (if (fboundp 'defvaralias)
2836 (defvaralias 'org-popup-calendar-for-date-prompt
2837 'org-read-date-popup-calendar))
2839 (defcustom org-read-date-minibuffer-setup-hook nil
2840 "Hook to be used to set up keys for the date/time interface.
2841 Add key definitions to `minibuffer-local-map', which will be a temporary
2842 copy."
2843 :group 'org-time
2844 :type 'hook)
2846 (defcustom org-extend-today-until 0
2847 "The hour when your day really ends. Must be an integer.
2848 This has influence for the following applications:
2849 - When switching the agenda to \"today\". It it is still earlier than
2850 the time given here, the day recognized as TODAY is actually yesterday.
2851 - When a date is read from the user and it is still before the time given
2852 here, the current date and time will be assumed to be yesterday, 23:59.
2853 Also, timestamps inserted in capture templates follow this rule.
2855 IMPORTANT: This is a feature whose implementation is and likely will
2856 remain incomplete. Really, it is only here because past midnight seems to
2857 be the favorite working time of John Wiegley :-)"
2858 :group 'org-time
2859 :type 'integer)
2861 (defcustom org-use-effective-time nil
2862 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2863 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2864 \"effective time\" of any timestamps between midnight and 8am will be
2865 23:59 of the previous day."
2866 :group 'org-time
2867 :version "24.1"
2868 :type 'boolean)
2870 (defcustom org-use-last-clock-out-time-as-effective-time nil
2871 "When non-nil, use the last clock out time for `org-todo'.
2872 Note that this option has precedence over the combined use of
2873 `org-use-effective-time' and `org-extend-today-until'."
2874 :group 'org-time
2875 ;; :version "24.3"
2876 :type 'boolean)
2878 (defcustom org-edit-timestamp-down-means-later nil
2879 "Non-nil means S-down will increase the time in a time stamp.
2880 When nil, S-up will increase."
2881 :group 'org-time
2882 :type 'boolean)
2884 (defcustom org-calendar-follow-timestamp-change t
2885 "Non-nil means make the calendar window follow timestamp changes.
2886 When a timestamp is modified and the calendar window is visible, it will be
2887 moved to the new date."
2888 :group 'org-time
2889 :type 'boolean)
2891 (defgroup org-tags nil
2892 "Options concerning tags in Org-mode."
2893 :tag "Org Tags"
2894 :group 'org)
2896 (defcustom org-tag-alist nil
2897 "List of tags allowed in Org-mode files.
2898 When this list is nil, Org-mode will base TAG input on what is already in the
2899 buffer.
2900 The value of this variable is an alist, the car of each entry must be a
2901 keyword as a string, the cdr may be a character that is used to select
2902 that tag through the fast-tag-selection interface.
2903 See the manual for details."
2904 :group 'org-tags
2905 :type '(repeat
2906 (choice
2907 (cons (string :tag "Tag name")
2908 (character :tag "Access char"))
2909 (list :tag "Start radio group"
2910 (const :startgroup)
2911 (option (string :tag "Group description")))
2912 (list :tag "End radio group"
2913 (const :endgroup)
2914 (option (string :tag "Group description")))
2915 (const :tag "New line" (:newline)))))
2917 (defcustom org-tag-persistent-alist nil
2918 "List of tags that will always appear in all Org-mode files.
2919 This is in addition to any in buffer settings or customizations
2920 of `org-tag-alist'.
2921 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2922 The value of this variable is an alist, the car of each entry must be a
2923 keyword as a string, the cdr may be a character that is used to select
2924 that tag through the fast-tag-selection interface.
2925 See the manual for details.
2926 To disable these tags on a per-file basis, insert anywhere in the file:
2927 #+STARTUP: noptag"
2928 :group 'org-tags
2929 :type '(repeat
2930 (choice
2931 (cons (string :tag "Tag name")
2932 (character :tag "Access char"))
2933 (const :tag "Start radio group" (:startgroup))
2934 (const :tag "End radio group" (:endgroup))
2935 (const :tag "New line" (:newline)))))
2937 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2938 "If non-nil, always offer completion for all tags of all agenda files.
2939 Instead of customizing this variable directly, you might want to
2940 set it locally for capture buffers, because there no list of
2941 tags in that file can be created dynamically (there are none).
2943 (add-hook 'org-capture-mode-hook
2944 (lambda ()
2945 (set (make-local-variable
2946 'org-complete-tags-always-offer-all-agenda-tags)
2947 t)))"
2948 :group 'org-tags
2949 :version "24.1"
2950 :type 'boolean)
2952 (defvar org-file-tags nil
2953 "List of tags that can be inherited by all entries in the file.
2954 The tags will be inherited if the variable `org-use-tag-inheritance'
2955 says they should be.
2956 This variable is populated from #+FILETAGS lines.")
2958 (defcustom org-use-fast-tag-selection 'auto
2959 "Non-nil means use fast tag selection scheme.
2960 This is a special interface to select and deselect tags with single keys.
2961 When nil, fast selection is never used.
2962 When the symbol `auto', fast selection is used if and only if selection
2963 characters for tags have been configured, either through the variable
2964 `org-tag-alist' or through a #+TAGS line in the buffer.
2965 When t, fast selection is always used and selection keys are assigned
2966 automatically if necessary."
2967 :group 'org-tags
2968 :type '(choice
2969 (const :tag "Always" t)
2970 (const :tag "Never" nil)
2971 (const :tag "When selection characters are configured" 'auto)))
2973 (defcustom org-fast-tag-selection-single-key nil
2974 "Non-nil means fast tag selection exits after first change.
2975 When nil, you have to press RET to exit it.
2976 During fast tag selection, you can toggle this flag with `C-c'.
2977 This variable can also have the value `expert'. In this case, the window
2978 displaying the tags menu is not even shown, until you press C-c again."
2979 :group 'org-tags
2980 :type '(choice
2981 (const :tag "No" nil)
2982 (const :tag "Yes" t)
2983 (const :tag "Expert" expert)))
2985 (defvar org-fast-tag-selection-include-todo nil
2986 "Non-nil means fast tags selection interface will also offer TODO states.
2987 This is an undocumented feature, you should not rely on it.")
2989 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2990 "The column to which tags should be indented in a headline.
2991 If this number is positive, it specifies the column. If it is negative,
2992 it means that the tags should be flushright to that column. For example,
2993 -80 works well for a normal 80 character screen.
2994 When 0, place tags directly after headline text, with only one space in
2995 between."
2996 :group 'org-tags
2997 :type 'integer)
2999 (defcustom org-auto-align-tags t
3000 "Non-nil keeps tags aligned when modifying headlines.
3001 Some operations (i.e. demoting) change the length of a headline and
3002 therefore shift the tags around. With this option turned on, after
3003 each such operation the tags are again aligned to `org-tags-column'."
3004 :group 'org-tags
3005 :type 'boolean)
3007 (defcustom org-use-tag-inheritance t
3008 "Non-nil means tags in levels apply also for sublevels.
3009 When nil, only the tags directly given in a specific line apply there.
3010 This may also be a list of tags that should be inherited, or a regexp that
3011 matches tags that should be inherited. Additional control is possible
3012 with the variable `org-tags-exclude-from-inheritance' which gives an
3013 explicit list of tags to be excluded from inheritance., even if the value of
3014 `org-use-tag-inheritance' would select it for inheritance.
3016 If this option is t, a match early-on in a tree can lead to a large
3017 number of matches in the subtree when constructing the agenda or creating
3018 a sparse tree. If you only want to see the first match in a tree during
3019 a search, check out the variable `org-tags-match-list-sublevels'."
3020 :group 'org-tags
3021 :type '(choice
3022 (const :tag "Not" nil)
3023 (const :tag "Always" t)
3024 (repeat :tag "Specific tags" (string :tag "Tag"))
3025 (regexp :tag "Tags matched by regexp")))
3027 (defcustom org-tags-exclude-from-inheritance nil
3028 "List of tags that should never be inherited.
3029 This is a way to exclude a few tags from inheritance. For way to do
3030 the opposite, to actively allow inheritance for selected tags,
3031 see the variable `org-use-tag-inheritance'."
3032 :group 'org-tags
3033 :type '(repeat (string :tag "Tag")))
3035 (defun org-tag-inherit-p (tag)
3036 "Check if TAG is one that should be inherited."
3037 (cond
3038 ((member tag org-tags-exclude-from-inheritance) nil)
3039 ((eq org-use-tag-inheritance t) t)
3040 ((not org-use-tag-inheritance) nil)
3041 ((stringp org-use-tag-inheritance)
3042 (string-match org-use-tag-inheritance tag))
3043 ((listp org-use-tag-inheritance)
3044 (member tag org-use-tag-inheritance))
3045 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3047 (defcustom org-tags-match-list-sublevels t
3048 "Non-nil means list also sublevels of headlines matching a search.
3049 This variable applies to tags/property searches, and also to stuck
3050 projects because this search is based on a tags match as well.
3052 When set to the symbol `indented', sublevels are indented with
3053 leading dots.
3055 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3056 the sublevels of a headline matching a tag search often also match
3057 the same search. Listing all of them can create very long lists.
3058 Setting this variable to nil causes subtrees of a match to be skipped.
3060 This variable is semi-obsolete and probably should always be true. It
3061 is better to limit inheritance to certain tags using the variables
3062 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3063 :group 'org-tags
3064 :type '(choice
3065 (const :tag "No, don't list them" nil)
3066 (const :tag "Yes, do list them" t)
3067 (const :tag "List them, indented with leading dots" indented)))
3069 (defcustom org-tags-sort-function nil
3070 "When set, tags are sorted using this function as a comparator."
3071 :group 'org-tags
3072 :type '(choice
3073 (const :tag "No sorting" nil)
3074 (const :tag "Alphabetical" string<)
3075 (const :tag "Reverse alphabetical" string>)
3076 (function :tag "Custom function" nil)))
3078 (defvar org-tags-history nil
3079 "History of minibuffer reads for tags.")
3080 (defvar org-last-tags-completion-table nil
3081 "The last used completion table for tags.")
3082 (defvar org-after-tags-change-hook nil
3083 "Hook that is run after the tags in a line have changed.")
3085 (defgroup org-properties nil
3086 "Options concerning properties in Org-mode."
3087 :tag "Org Properties"
3088 :group 'org)
3090 (defcustom org-property-format "%-10s %s"
3091 "How property key/value pairs should be formatted by `indent-line'.
3092 When `indent-line' hits a property definition, it will format the line
3093 according to this format, mainly to make sure that the values are
3094 lined-up with respect to each other."
3095 :group 'org-properties
3096 :type 'string)
3098 (defcustom org-properties-postprocess-alist nil
3099 "Alist of properties and functions to adjust inserted values.
3100 Elements of this alist must be of the form
3102 ([string] [function])
3104 where [string] must be a property name and [function] must be a
3105 lambda expression: this lambda expression must take one argument,
3106 the value to adjust, and return the new value as a string.
3108 For example, this element will allow the property \"Remaining\"
3109 to be updated wrt the relation between the \"Effort\" property
3110 and the clock summary:
3112 ((\"Remaining\" (lambda(value)
3113 (let ((clocksum (org-clock-sum-current-item))
3114 (effort (org-duration-string-to-minutes
3115 (org-entry-get (point) \"Effort\"))))
3116 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3117 :group 'org-properties
3118 :version "24.1"
3119 :type '(alist :key-type (string :tag "Property")
3120 :value-type (function :tag "Function")))
3122 (defcustom org-use-property-inheritance nil
3123 "Non-nil means properties apply also for sublevels.
3125 This setting is chiefly used during property searches. Turning it on can
3126 cause significant overhead when doing a search, which is why it is not
3127 on by default.
3129 When nil, only the properties directly given in the current entry count.
3130 When t, every property is inherited. The value may also be a list of
3131 properties that should have inheritance, or a regular expression matching
3132 properties that should be inherited.
3134 However, note that some special properties use inheritance under special
3135 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3136 and the properties ending in \"_ALL\" when they are used as descriptor
3137 for valid values of a property.
3139 Note for programmers:
3140 When querying an entry with `org-entry-get', you can control if inheritance
3141 should be used. By default, `org-entry-get' looks only at the local
3142 properties. You can request inheritance by setting the inherit argument
3143 to t (to force inheritance) or to `selective' (to respect the setting
3144 in this variable)."
3145 :group 'org-properties
3146 :type '(choice
3147 (const :tag "Not" nil)
3148 (const :tag "Always" t)
3149 (repeat :tag "Specific properties" (string :tag "Property"))
3150 (regexp :tag "Properties matched by regexp")))
3152 (defun org-property-inherit-p (property)
3153 "Check if PROPERTY is one that should be inherited."
3154 (cond
3155 ((eq org-use-property-inheritance t) t)
3156 ((not org-use-property-inheritance) nil)
3157 ((stringp org-use-property-inheritance)
3158 (string-match org-use-property-inheritance property))
3159 ((listp org-use-property-inheritance)
3160 (member property org-use-property-inheritance))
3161 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3163 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3164 "The default column format, if no other format has been defined.
3165 This variable can be set on the per-file basis by inserting a line
3167 #+COLUMNS: %25ITEM ....."
3168 :group 'org-properties
3169 :type 'string)
3171 (defcustom org-columns-ellipses ".."
3172 "The ellipses to be used when a field in column view is truncated.
3173 When this is the empty string, as many characters as possible are shown,
3174 but then there will be no visual indication that the field has been truncated.
3175 When this is a string of length N, the last N characters of a truncated
3176 field are replaced by this string. If the column is narrower than the
3177 ellipses string, only part of the ellipses string will be shown."
3178 :group 'org-properties
3179 :type 'string)
3181 (defcustom org-columns-modify-value-for-display-function nil
3182 "Function that modifies values for display in column view.
3183 For example, it can be used to cut out a certain part from a time stamp.
3184 The function must take 2 arguments:
3186 column-title The title of the column (*not* the property name)
3187 value The value that should be modified.
3189 The function should return the value that should be displayed,
3190 or nil if the normal value should be used."
3191 :group 'org-properties
3192 :type 'function)
3194 (defcustom org-effort-property "Effort"
3195 "The property that is being used to keep track of effort estimates.
3196 Effort estimates given in this property need to have the format H:MM."
3197 :group 'org-properties
3198 :group 'org-progress
3199 :type '(string :tag "Property"))
3201 (defconst org-global-properties-fixed
3202 '(("VISIBILITY_ALL" . "folded children content all")
3203 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3204 "List of property/value pairs that can be inherited by any entry.
3206 These are fixed values, for the preset properties. The user variable
3207 that can be used to add to this list is `org-global-properties'.
3209 The entries in this list are cons cells where the car is a property
3210 name and cdr is a string with the value. If the value represents
3211 multiple items like an \"_ALL\" property, separate the items by
3212 spaces.")
3214 (defcustom org-global-properties nil
3215 "List of property/value pairs that can be inherited by any entry.
3217 This list will be combined with the constant `org-global-properties-fixed'.
3219 The entries in this list are cons cells where the car is a property
3220 name and cdr is a string with the value.
3222 You can set buffer-local values for the same purpose in the variable
3223 `org-file-properties' this by adding lines like
3225 #+PROPERTY: NAME VALUE"
3226 :group 'org-properties
3227 :type '(repeat
3228 (cons (string :tag "Property")
3229 (string :tag "Value"))))
3231 (defvar org-file-properties nil
3232 "List of property/value pairs that can be inherited by any entry.
3233 Valid for the current buffer.
3234 This variable is populated from #+PROPERTY lines.")
3235 (make-variable-buffer-local 'org-file-properties)
3237 (defgroup org-agenda nil
3238 "Options concerning agenda views in Org-mode."
3239 :tag "Org Agenda"
3240 :group 'org)
3242 (defvar org-category nil
3243 "Variable used by org files to set a category for agenda display.
3244 Such files should use a file variable to set it, for example
3246 # -*- mode: org; org-category: \"ELisp\"
3248 or contain a special line
3250 #+CATEGORY: ELisp
3252 If the file does not specify a category, then file's base name
3253 is used instead.")
3254 (make-variable-buffer-local 'org-category)
3255 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3257 (defcustom org-agenda-files nil
3258 "The files to be used for agenda display.
3259 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3260 \\[org-remove-file]. You can also use customize to edit the list.
3262 If an entry is a directory, all files in that directory that are matched by
3263 `org-agenda-file-regexp' will be part of the file list.
3265 If the value of the variable is not a list but a single file name, then
3266 the list of agenda files is actually stored and maintained in that file, one
3267 agenda file per line. In this file paths can be given relative to
3268 `org-directory'. Tilde expansion and environment variable substitution
3269 are also made."
3270 :group 'org-agenda
3271 :type '(choice
3272 (repeat :tag "List of files and directories" file)
3273 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3275 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3276 "Regular expression to match files for `org-agenda-files'.
3277 If any element in the list in that variable contains a directory instead
3278 of a normal file, all files in that directory that are matched by this
3279 regular expression will be included."
3280 :group 'org-agenda
3281 :type 'regexp)
3283 (defcustom org-agenda-text-search-extra-files nil
3284 "List of extra files to be searched by text search commands.
3285 These files will be search in addition to the agenda files by the
3286 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3287 Note that these files will only be searched for text search commands,
3288 not for the other agenda views like todo lists, tag searches or the weekly
3289 agenda. This variable is intended to list notes and possibly archive files
3290 that should also be searched by these two commands.
3291 In fact, if the first element in the list is the symbol `agenda-archives',
3292 than all archive files of all agenda files will be added to the search
3293 scope."
3294 :group 'org-agenda
3295 :type '(set :greedy t
3296 (const :tag "Agenda Archives" agenda-archives)
3297 (repeat :inline t (file))))
3299 (if (fboundp 'defvaralias)
3300 (defvaralias 'org-agenda-multi-occur-extra-files
3301 'org-agenda-text-search-extra-files))
3303 (defcustom org-agenda-skip-unavailable-files nil
3304 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3305 A nil value means to remove them, after a query, from the list."
3306 :group 'org-agenda
3307 :type 'boolean)
3309 (defcustom org-calendar-to-agenda-key [?c]
3310 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3311 The command `org-calendar-goto-agenda' will be bound to this key. The
3312 default is the character `c' because then `c' can be used to switch back and
3313 forth between agenda and calendar."
3314 :group 'org-agenda
3315 :type 'sexp)
3317 (defcustom org-calendar-agenda-action-key [?k]
3318 "The key to be installed in `calendar-mode-map' for agenda-action.
3319 The command `org-agenda-action' will be bound to this key. The
3320 default is the character `k' because we use the same key in the agenda."
3321 :group 'org-agenda
3322 :type 'sexp)
3324 (defcustom org-calendar-insert-diary-entry-key [?i]
3325 "The key to be installed in `calendar-mode-map' for adding diary entries.
3326 This option is irrelevant until `org-agenda-diary-file' has been configured
3327 to point to an Org-mode file. When that is the case, the command
3328 `org-agenda-diary-entry' will be bound to the key given here, by default
3329 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3330 if you want to continue doing this, you need to change this to a different
3331 key."
3332 :group 'org-agenda
3333 :type 'sexp)
3335 (defcustom org-agenda-diary-file 'diary-file
3336 "File to which to add new entries with the `i' key in agenda and calendar.
3337 When this is the symbol `diary-file', the functionality in the Emacs
3338 calendar will be used to add entries to the `diary-file'. But when this
3339 points to a file, `org-agenda-diary-entry' will be used instead."
3340 :group 'org-agenda
3341 :type '(choice
3342 (const :tag "The standard Emacs diary file" diary-file)
3343 (file :tag "Special Org file diary entries")))
3345 (eval-after-load "calendar"
3346 '(progn
3347 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3348 'org-calendar-goto-agenda)
3349 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3350 'org-agenda-action)
3351 (add-hook 'calendar-mode-hook
3352 (lambda ()
3353 (unless (eq org-agenda-diary-file 'diary-file)
3354 (define-key calendar-mode-map
3355 org-calendar-insert-diary-entry-key
3356 'org-agenda-diary-entry))))))
3358 (defgroup org-latex nil
3359 "Options for embedding LaTeX code into Org-mode."
3360 :tag "Org LaTeX"
3361 :group 'org)
3363 (defcustom org-format-latex-options
3364 '(:foreground default :background default :scale 1.0
3365 :html-foreground "Black" :html-background "Transparent"
3366 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3367 "Options for creating images from LaTeX fragments.
3368 This is a property list with the following properties:
3369 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3370 `default' means use the foreground of the default face.
3371 `auto' means use the foreground from the text face.
3372 :background the background color, or \"Transparent\".
3373 `default' means use the background of the default face.
3374 `auto' means use the background from the text face.
3375 :scale a scaling factor for the size of the images, to get more pixels
3376 :html-foreground, :html-background, :html-scale
3377 the same numbers for HTML export.
3378 :matchers a list indicating which matchers should be used to
3379 find LaTeX fragments. Valid members of this list are:
3380 \"begin\" find environments
3381 \"$1\" find single characters surrounded by $.$
3382 \"$\" find math expressions surrounded by $...$
3383 \"$$\" find math expressions surrounded by $$....$$
3384 \"\\(\" find math expressions surrounded by \\(...\\)
3385 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3386 :group 'org-latex
3387 :type 'plist)
3389 (defcustom org-format-latex-signal-error t
3390 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3391 When nil, just push out a message."
3392 :group 'org-latex
3393 :version "24.1"
3394 :type 'boolean)
3396 (defcustom org-latex-to-mathml-jar-file nil
3397 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3398 Use this to specify additional executable file say a jar file.
3400 When using MathToWeb as the converter, specify the full-path to
3401 your mathtoweb.jar file."
3402 :group 'org-latex
3403 :version "24.1"
3404 :type '(choice
3405 (const :tag "None" nil)
3406 (file :tag "JAR file" :must-match t)))
3408 (defcustom org-latex-to-mathml-convert-command nil
3409 "Command to convert LaTeX fragments to MathML.
3410 Replace format-specifiers in the command as noted below and use
3411 `shell-command' to convert LaTeX to MathML.
3412 %j: Executable file in fully expanded form as specified by
3413 `org-latex-to-mathml-jar-file'.
3414 %I: Input LaTeX file in fully expanded form
3415 %o: Output MathML file
3416 This command is used by `org-create-math-formula'.
3418 When using MathToWeb as the converter, set this to
3419 \"java -jar %j -unicode -force -df %o %I\"."
3420 :group 'org-latex
3421 :version "24.1"
3422 :type '(choice
3423 (const :tag "None" nil)
3424 (string :tag "\nShell command")))
3426 (defcustom org-latex-create-formula-image-program 'dvipng
3427 "Program to convert LaTeX fragments with.
3429 dvipng Process the LaTeX fragments to dvi file, then convert
3430 dvi files to png files using dvipng.
3431 This will also include processing of non-math environments.
3432 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3433 to convert pdf files to png files"
3434 :group 'org-latex
3435 :version "24.1"
3436 :type '(choice
3437 (const :tag "dvipng" dvipng)
3438 (const :tag "imagemagick" imagemagick)))
3440 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3441 "Path to store latex preview images. A relative path here creates many
3442 directories relative to the processed org files paths. An absolute path
3443 puts all preview images at the same place."
3444 :group 'org-latex
3445 ;; :version "24.3"
3446 :type 'string)
3448 (defun org-format-latex-mathml-available-p ()
3449 "Return t if `org-latex-to-mathml-convert-command' is usable."
3450 (save-match-data
3451 (when (and (boundp 'org-latex-to-mathml-convert-command)
3452 org-latex-to-mathml-convert-command)
3453 (let ((executable (car (split-string
3454 org-latex-to-mathml-convert-command))))
3455 (when (executable-find executable)
3456 (if (string-match
3457 "%j" org-latex-to-mathml-convert-command)
3458 (file-readable-p org-latex-to-mathml-jar-file)
3459 t))))))
3461 (defcustom org-format-latex-header "\\documentclass{article}
3462 \\usepackage[usenames]{color}
3463 \\usepackage{amsmath}
3464 \\usepackage[mathscr]{eucal}
3465 \\pagestyle{empty} % do not remove
3466 \[PACKAGES]
3467 \[DEFAULT-PACKAGES]
3468 % The settings below are copied from fullpage.sty
3469 \\setlength{\\textwidth}{\\paperwidth}
3470 \\addtolength{\\textwidth}{-3cm}
3471 \\setlength{\\oddsidemargin}{1.5cm}
3472 \\addtolength{\\oddsidemargin}{-2.54cm}
3473 \\setlength{\\evensidemargin}{\\oddsidemargin}
3474 \\setlength{\\textheight}{\\paperheight}
3475 \\addtolength{\\textheight}{-\\headheight}
3476 \\addtolength{\\textheight}{-\\headsep}
3477 \\addtolength{\\textheight}{-\\footskip}
3478 \\addtolength{\\textheight}{-3cm}
3479 \\setlength{\\topmargin}{1.5cm}
3480 \\addtolength{\\topmargin}{-2.54cm}"
3481 "The document header used for processing LaTeX fragments.
3482 It is imperative that this header make sure that no page number
3483 appears on the page. The package defined in the variables
3484 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3485 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3486 will be appended."
3487 :group 'org-latex
3488 :type 'string)
3490 (defvar org-format-latex-header-extra nil)
3492 (defun org-set-packages-alist (var val)
3493 "Set the packages alist and make sure it has 3 elements per entry."
3494 (set var (mapcar (lambda (x)
3495 (if (and (consp x) (= (length x) 2))
3496 (list (car x) (nth 1 x) t)
3498 val)))
3500 (defun org-get-packages-alist (var)
3502 "Get the packages alist and make sure it has 3 elements per entry."
3503 (mapcar (lambda (x)
3504 (if (and (consp x) (= (length x) 2))
3505 (list (car x) (nth 1 x) t)
3507 (default-value var)))
3509 ;; The following variables are defined here because is it also used
3510 ;; when formatting latex fragments. Originally it was part of the
3511 ;; LaTeX exporter, which is why the name includes "export".
3512 (defcustom org-export-latex-default-packages-alist
3513 '(("AUTO" "inputenc" t)
3514 ("T1" "fontenc" t)
3515 ("" "fixltx2e" nil)
3516 ("" "graphicx" t)
3517 ("" "longtable" nil)
3518 ("" "float" nil)
3519 ("" "wrapfig" nil)
3520 ("" "soul" t)
3521 ("" "textcomp" t)
3522 ("" "marvosym" t)
3523 ("" "wasysym" t)
3524 ("" "latexsym" t)
3525 ("" "amssymb" t)
3526 ("" "hyperref" nil)
3527 "\\tolerance=1000"
3529 "Alist of default packages to be inserted in the header.
3530 Change this only if one of the packages here causes an incompatibility
3531 with another package you are using.
3532 The packages in this list are needed by one part or another of Org-mode
3533 to function properly.
3535 - inputenc, fontenc: for basic font and character selection
3536 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3537 for interpreting the entities in `org-entities'. You can skip some of these
3538 packages if you don't use any of the symbols in it.
3539 - graphicx: for including images
3540 - float, wrapfig: for figure placement
3541 - longtable: for long tables
3542 - hyperref: for cross references
3544 Therefore you should not modify this variable unless you know what you
3545 are doing. The one reason to change it anyway is that you might be loading
3546 some other package that conflicts with one of the default packages.
3547 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3548 If SNIPPET-FLAG is t, the package also needs to be included when
3549 compiling LaTeX snippets into images for inclusion into HTML."
3550 :group 'org-export-latex
3551 :set 'org-set-packages-alist
3552 :get 'org-get-packages-alist
3553 :version "24.1"
3554 :type '(repeat
3555 (choice
3556 (list :tag "options/package pair"
3557 (string :tag "options")
3558 (string :tag "package")
3559 (boolean :tag "Snippet"))
3560 (string :tag "A line of LaTeX"))))
3562 (defcustom org-export-latex-packages-alist nil
3563 "Alist of packages to be inserted in every LaTeX header.
3564 These will be inserted after `org-export-latex-default-packages-alist'.
3565 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3566 SNIPPET-FLAG, when t, indicates that this package is also needed when
3567 turning LaTeX snippets into images for inclusion into HTML.
3568 Make sure that you only list packages here which:
3569 - you want in every file
3570 - do not conflict with the default packages in
3571 `org-export-latex-default-packages-alist'
3572 - do not conflict with the setup in `org-format-latex-header'."
3573 :group 'org-export-latex
3574 :set 'org-set-packages-alist
3575 :get 'org-get-packages-alist
3576 :type '(repeat
3577 (choice
3578 (list :tag "options/package pair"
3579 (string :tag "options")
3580 (string :tag "package")
3581 (boolean :tag "Snippet"))
3582 (string :tag "A line of LaTeX"))))
3585 (defgroup org-appearance nil
3586 "Settings for Org-mode appearance."
3587 :tag "Org Appearance"
3588 :group 'org)
3590 (defcustom org-level-color-stars-only nil
3591 "Non-nil means fontify only the stars in each headline.
3592 When nil, the entire headline is fontified.
3593 Changing it requires restart of `font-lock-mode' to become effective
3594 also in regions already fontified."
3595 :group 'org-appearance
3596 :type 'boolean)
3598 (defcustom org-hide-leading-stars nil
3599 "Non-nil means hide the first N-1 stars in a headline.
3600 This works by using the face `org-hide' for these stars. This
3601 face is white for a light background, and black for a dark
3602 background. You may have to customize the face `org-hide' to
3603 make this work.
3604 Changing it requires restart of `font-lock-mode' to become effective
3605 also in regions already fontified.
3606 You may also set this on a per-file basis by adding one of the following
3607 lines to the buffer:
3609 #+STARTUP: hidestars
3610 #+STARTUP: showstars"
3611 :group 'org-appearance
3612 :type 'boolean)
3614 (defcustom org-hidden-keywords nil
3615 "List of symbols corresponding to keywords to be hidden the org buffer.
3616 For example, a value '(title) for this list will make the document's title
3617 appear in the buffer without the initial #+TITLE: keyword."
3618 :group 'org-appearance
3619 :version "24.1"
3620 :type '(set (const :tag "#+AUTHOR" author)
3621 (const :tag "#+DATE" date)
3622 (const :tag "#+EMAIL" email)
3623 (const :tag "#+TITLE" title)))
3625 (defcustom org-custom-properties nil
3626 "List of properties (as strings) with a special meaning.
3627 The default use of these custom properties is to let the user
3628 hide them with `org-toggle-custom-properties-visibility'."
3629 :group 'org-properties
3630 :group 'org-appearance
3631 ;; :version "24.3"
3632 :type '(repeat (string :tag "Property Name")))
3634 (defcustom org-fontify-done-headline nil
3635 "Non-nil means change the face of a headline if it is marked DONE.
3636 Normally, only the TODO/DONE keyword indicates the state of a headline.
3637 When this is non-nil, the headline after the keyword is set to the
3638 `org-headline-done' as an additional indication."
3639 :group 'org-appearance
3640 :type 'boolean)
3642 (defcustom org-fontify-emphasized-text t
3643 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3644 Changing this variable requires a restart of Emacs to take effect."
3645 :group 'org-appearance
3646 :type 'boolean)
3648 (defcustom org-fontify-whole-heading-line nil
3649 "Non-nil means fontify the whole line for headings.
3650 This is useful when setting a background color for the
3651 org-level-* faces."
3652 :group 'org-appearance
3653 :type 'boolean)
3655 (defcustom org-highlight-latex-fragments-and-specials nil
3656 "Non-nil means fontify what is treated specially by the exporters."
3657 :group 'org-appearance
3658 :type 'boolean)
3660 (defcustom org-hide-emphasis-markers nil
3661 "Non-nil mean font-lock should hide the emphasis marker characters."
3662 :group 'org-appearance
3663 :type 'boolean)
3665 (defcustom org-pretty-entities nil
3666 "Non-nil means show entities as UTF8 characters.
3667 When nil, the \\name form remains in the buffer."
3668 :group 'org-appearance
3669 :version "24.1"
3670 :type 'boolean)
3672 (defcustom org-pretty-entities-include-sub-superscripts t
3673 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3674 :group 'org-appearance
3675 :version "24.1"
3676 :type 'boolean)
3678 (defvar org-emph-re nil
3679 "Regular expression for matching emphasis.
3680 After a match, the match groups contain these elements:
3681 0 The match of the full regular expression, including the characters
3682 before and after the proper match
3683 1 The character before the proper match, or empty at beginning of line
3684 2 The proper match, including the leading and trailing markers
3685 3 The leading marker like * or /, indicating the type of highlighting
3686 4 The text between the emphasis markers, not including the markers
3687 5 The character after the match, empty at the end of a line")
3688 (defvar org-verbatim-re nil
3689 "Regular expression for matching verbatim text.")
3690 (defvar org-emphasis-regexp-components) ; defined just below
3691 (defvar org-emphasis-alist) ; defined just below
3692 (defun org-set-emph-re (var val)
3693 "Set variable and compute the emphasis regular expression."
3694 (set var val)
3695 (when (and (boundp 'org-emphasis-alist)
3696 (boundp 'org-emphasis-regexp-components)
3697 org-emphasis-alist org-emphasis-regexp-components)
3698 (let* ((e org-emphasis-regexp-components)
3699 (pre (car e))
3700 (post (nth 1 e))
3701 (border (nth 2 e))
3702 (body (nth 3 e))
3703 (nl (nth 4 e))
3704 (body1 (concat body "*?"))
3705 (markers (mapconcat 'car org-emphasis-alist ""))
3706 (vmarkers (mapconcat
3707 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3708 org-emphasis-alist "")))
3709 ;; make sure special characters appear at the right position in the class
3710 (if (string-match "\\^" markers)
3711 (setq markers (concat (replace-match "" t t markers) "^")))
3712 (if (string-match "-" markers)
3713 (setq markers (concat (replace-match "" t t markers) "-")))
3714 (if (string-match "\\^" vmarkers)
3715 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3716 (if (string-match "-" vmarkers)
3717 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3718 (if (> nl 0)
3719 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3720 (int-to-string nl) "\\}")))
3721 ;; Make the regexp
3722 (setq org-emph-re
3723 (concat "\\([" pre "]\\|^\\)"
3724 "\\("
3725 "\\([" markers "]\\)"
3726 "\\("
3727 "[^" border "]\\|"
3728 "[^" border "]"
3729 body1
3730 "[^" border "]"
3731 "\\)"
3732 "\\3\\)"
3733 "\\([" post "]\\|$\\)"))
3734 (setq org-verbatim-re
3735 (concat "\\([" pre "]\\|^\\)"
3736 "\\("
3737 "\\([" vmarkers "]\\)"
3738 "\\("
3739 "[^" border "]\\|"
3740 "[^" border "]"
3741 body1
3742 "[^" border "]"
3743 "\\)"
3744 "\\3\\)"
3745 "\\([" post "]\\|$\\)")))))
3747 (defcustom org-emphasis-regexp-components
3748 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3749 "Components used to build the regular expression for emphasis.
3750 This is a list with five entries. Terminology: In an emphasis string
3751 like \" *strong word* \", we call the initial space PREMATCH, the final
3752 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3753 and \"trong wor\" is the body. The different components in this variable
3754 specify what is allowed/forbidden in each part:
3756 pre Chars allowed as prematch. Beginning of line will be allowed too.
3757 post Chars allowed as postmatch. End of line will be allowed too.
3758 border The chars *forbidden* as border characters.
3759 body-regexp A regexp like \".\" to match a body character. Don't use
3760 non-shy groups here, and don't allow newline here.
3761 newline The maximum number of newlines allowed in an emphasis exp.
3763 Use customize to modify this, or restart Emacs after changing it."
3764 :group 'org-appearance
3765 :set 'org-set-emph-re
3766 :type '(list
3767 (sexp :tag "Allowed chars in pre ")
3768 (sexp :tag "Allowed chars in post ")
3769 (sexp :tag "Forbidden chars in border ")
3770 (sexp :tag "Regexp for body ")
3771 (integer :tag "number of newlines allowed")
3772 (option (boolean :tag "Please ignore this button"))))
3774 (defcustom org-emphasis-alist
3775 `(("*" bold "<b>" "</b>")
3776 ("/" italic "<i>" "</i>")
3777 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3778 ("=" org-code "<code>" "</code>" verbatim)
3779 ("~" org-verbatim "<code>" "</code>" verbatim)
3780 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3781 "<del>" "</del>")
3783 "Special syntax for emphasized text.
3784 Text starting and ending with a special character will be emphasized, for
3785 example *bold*, _underlined_ and /italic/. This variable sets the marker
3786 characters, the face to be used by font-lock for highlighting in Org-mode
3787 Emacs buffers, and the HTML tags to be used for this.
3788 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3789 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3790 Use customize to modify this, or restart Emacs after changing it."
3791 :group 'org-appearance
3792 :set 'org-set-emph-re
3793 :type '(repeat
3794 (list
3795 (string :tag "Marker character")
3796 (choice
3797 (face :tag "Font-lock-face")
3798 (plist :tag "Face property list"))
3799 (string :tag "HTML start tag")
3800 (string :tag "HTML end tag")
3801 (option (const verbatim)))))
3803 (defvar org-protecting-blocks
3804 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3805 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3806 This is needed for font-lock setup.")
3808 ;;; Miscellaneous options
3810 (defgroup org-completion nil
3811 "Completion in Org-mode."
3812 :tag "Org Completion"
3813 :group 'org)
3815 (defcustom org-completion-use-ido nil
3816 "Non-nil means use ido completion wherever possible.
3817 Note that `ido-mode' must be active for this variable to be relevant.
3818 If you decide to turn this variable on, you might well want to turn off
3819 `org-outline-path-complete-in-steps'.
3820 See also `org-completion-use-iswitchb'."
3821 :group 'org-completion
3822 :type 'boolean)
3824 (defcustom org-completion-use-iswitchb nil
3825 "Non-nil means use iswitchb completion wherever possible.
3826 Note that `iswitchb-mode' must be active for this variable to be relevant.
3827 If you decide to turn this variable on, you might well want to turn off
3828 `org-outline-path-complete-in-steps'.
3829 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3830 :group 'org-completion
3831 :type 'boolean)
3833 (defcustom org-completion-fallback-command 'hippie-expand
3834 "The expansion command called by \\[pcomplete] in normal context.
3835 Normal means, no org-mode-specific context."
3836 :group 'org-completion
3837 :type 'function)
3839 ;;; Functions and variables from their packages
3840 ;; Declared here to avoid compiler warnings
3842 ;; XEmacs only
3843 (defvar outline-mode-menu-heading)
3844 (defvar outline-mode-menu-show)
3845 (defvar outline-mode-menu-hide)
3846 (defvar zmacs-regions) ; XEmacs regions
3848 ;; Emacs only
3849 (defvar mark-active)
3851 ;; Various packages
3852 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3853 (declare-function calendar-forward-day "cal-move" (arg))
3854 (declare-function calendar-goto-date "cal-move" (date))
3855 (declare-function calendar-goto-today "cal-move" ())
3856 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3857 (defvar calc-embedded-close-formula)
3858 (defvar calc-embedded-open-formula)
3859 (declare-function cdlatex-tab "ext:cdlatex" ())
3860 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3861 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3862 (defvar font-lock-unfontify-region-function)
3863 (declare-function iswitchb-read-buffer "iswitchb"
3864 (prompt &optional default require-match start matches-set))
3865 (defvar iswitchb-temp-buflist)
3866 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3867 (defvar org-agenda-tags-todo-honor-ignore-options)
3868 (declare-function org-agenda-skip "org-agenda" ())
3869 (declare-function
3870 org-agenda-format-item "org-agenda"
3871 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3872 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3873 (declare-function org-agenda-change-all-lines "org-agenda"
3874 (newhead hdmarker &optional fixface just-this))
3875 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3876 (declare-function org-agenda-maybe-redo "org-agenda" ())
3877 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3878 (beg end))
3879 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3880 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3881 "org-agenda" (&optional end))
3882 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3883 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3884 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3885 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3886 (declare-function org-indent-mode "org-indent" (&optional arg))
3887 (declare-function parse-time-string "parse-time" (string))
3888 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3889 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3890 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3891 (defvar remember-data-file)
3892 (defvar texmathp-why)
3893 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3894 (declare-function table--at-cell-p "table" (position &optional object at-column))
3896 (defvar w3m-current-url)
3897 (defvar w3m-current-title)
3899 (defvar org-latex-regexps)
3901 ;;; Autoload and prepare some org modules
3903 ;; Some table stuff that needs to be defined here, because it is used
3904 ;; by the functions setting up org-mode or checking for table context.
3906 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3907 "Detect an org-type or table-type table.")
3908 (defconst org-table-line-regexp "^[ \t]*|"
3909 "Detect an org-type table line.")
3910 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3911 "Detect an org-type table line.")
3912 (defconst org-table-hline-regexp "^[ \t]*|-"
3913 "Detect an org-type table hline.")
3914 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3915 "Detect a table-type table hline.")
3916 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3917 "Detect the first line outside a table when searching from within it.
3918 This works for both table types.")
3920 ;; Autoload the functions in org-table.el that are needed by functions here.
3922 (eval-and-compile
3923 (org-autoload "org-table"
3924 '(org-table-align org-table-begin org-table-blank-field
3925 org-table-convert org-table-convert-region org-table-copy-down
3926 org-table-copy-region org-table-create
3927 org-table-create-or-convert-from-region
3928 org-table-create-with-table.el org-table-current-dline
3929 org-table-cut-region org-table-delete-column org-table-edit-field
3930 org-table-edit-formulas org-table-end org-table-eval-formula
3931 org-table-export org-table-field-info
3932 org-table-get-stored-formulas org-table-goto-column
3933 org-table-hline-and-move org-table-import org-table-insert-column
3934 org-table-insert-hline org-table-insert-row org-table-iterate
3935 org-table-justify-field-maybe org-table-kill-row
3936 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3937 org-table-move-column org-table-move-column-left
3938 org-table-move-column-right org-table-move-row
3939 org-table-move-row-down org-table-move-row-up
3940 org-table-next-field org-table-next-row org-table-paste-rectangle
3941 org-table-previous-field org-table-recalculate
3942 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3943 org-table-toggle-coordinate-overlays
3944 org-table-toggle-formula-debugger org-table-wrap-region
3945 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3946 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3947 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3949 (defun org-at-table-p (&optional table-type)
3950 "Return t if the cursor is inside an org-type table.
3951 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3952 (if org-enable-table-editor
3953 (save-excursion
3954 (beginning-of-line 1)
3955 (looking-at (if table-type org-table-any-line-regexp
3956 org-table-line-regexp)))
3957 nil))
3958 (defsubst org-table-p () (org-at-table-p))
3960 (defun org-at-table.el-p ()
3961 "Return t if and only if we are at a table.el table."
3962 (and (org-at-table-p 'any)
3963 (save-excursion
3964 (goto-char (org-table-begin 'any))
3965 (looking-at org-table1-hline-regexp))))
3966 (defun org-table-recognize-table.el ()
3967 "If there is a table.el table nearby, recognize it and move into it."
3968 (if org-table-tab-recognizes-table.el
3969 (if (org-at-table.el-p)
3970 (progn
3971 (beginning-of-line 1)
3972 (if (looking-at org-table-dataline-regexp)
3974 (if (looking-at org-table1-hline-regexp)
3975 (progn
3976 (beginning-of-line 2)
3977 (if (looking-at org-table-any-border-regexp)
3978 (beginning-of-line -1)))))
3979 (if (re-search-forward "|" (org-table-end t) t)
3980 (progn
3981 (require 'table)
3982 (if (table--at-cell-p (point))
3984 (message "recognizing table.el table...")
3985 (table-recognize-table)
3986 (message "recognizing table.el table...done")))
3987 (error "This should not happen"))
3989 nil)
3990 nil))
3992 (defun org-at-table-hline-p ()
3993 "Return t if the cursor is inside a hline in a table."
3994 (if org-enable-table-editor
3995 (save-excursion
3996 (beginning-of-line 1)
3997 (looking-at org-table-hline-regexp))
3998 nil))
4000 (defvar org-table-clean-did-remove-column nil)
4002 (defun org-table-map-tables (function &optional quietly)
4003 "Apply FUNCTION to the start of all tables in the buffer."
4004 (save-excursion
4005 (save-restriction
4006 (widen)
4007 (goto-char (point-min))
4008 (while (re-search-forward org-table-any-line-regexp nil t)
4009 (unless quietly
4010 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4011 (beginning-of-line 1)
4012 (when (and (looking-at org-table-line-regexp)
4013 ;; Exclude tables in src/example/verbatim/clocktable blocks
4014 (not (org-in-block-p '("src" "example"))))
4015 (save-excursion (funcall function))
4016 (or (looking-at org-table-line-regexp)
4017 (forward-char 1)))
4018 (re-search-forward org-table-any-border-regexp nil 1))))
4019 (unless quietly (message "Mapping tables: done")))
4021 ;; Declare and autoload functions from org-exp.el & Co
4023 (declare-function org-default-export-plist "org-exp")
4024 (declare-function org-infile-export-plist "org-exp")
4025 (declare-function org-get-current-options "org-exp")
4026 (eval-and-compile
4027 (org-autoload "org-exp"
4028 '(org-export org-export-visible
4029 org-insert-export-options-template
4030 org-table-clean-before-export))
4031 (org-autoload "org-ascii"
4032 '(org-export-as-ascii org-export-ascii-preprocess
4033 org-export-as-ascii-to-buffer org-replace-region-by-ascii
4034 org-export-region-as-ascii))
4035 (org-autoload "org-latex"
4036 '(org-export-as-latex-batch org-export-as-latex-to-buffer
4037 org-replace-region-by-latex org-export-region-as-latex
4038 org-export-as-latex org-export-as-pdf
4039 org-export-as-pdf-and-open))
4040 (org-autoload "org-html"
4041 '(org-export-as-html-and-open
4042 org-export-as-html-batch org-export-as-html-to-buffer
4043 org-replace-region-by-html org-export-region-as-html
4044 org-export-as-html))
4045 (org-autoload "org-docbook"
4046 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4047 org-replace-region-by-docbook org-export-region-as-docbook
4048 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4049 org-export-as-docbook))
4050 (org-autoload "org-icalendar"
4051 '(org-export-icalendar-this-file
4052 org-export-icalendar-all-agenda-files
4053 org-export-icalendar-combine-agenda-files))
4054 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4055 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4057 ;; Declare and autoload functions from org-agenda.el
4059 (eval-and-compile
4060 (org-autoload "org-agenda"
4061 '(org-agenda org-agenda-list org-search-view
4062 org-todo-list org-tags-view org-agenda-list-stuck-projects
4063 org-diary org-agenda-to-appt
4064 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4066 ;; Autoload org-remember
4068 (eval-and-compile
4069 (org-autoload "org-remember"
4070 '(org-remember-insinuate org-remember-annotation
4071 org-remember-apply-template org-remember org-remember-handler)))
4073 (eval-and-compile
4074 (org-autoload "org-capture"
4075 '(org-capture org-capture-insert-template-here
4076 org-capture-import-remember-templates)))
4078 ;; Autoload org-clock.el
4080 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4081 (beg end))
4082 (declare-function org-clock-update-mode-line "org-clock" ())
4083 (declare-function org-resolve-clocks "org-clock"
4084 (&optional also-non-dangling-p prompt last-valid))
4085 (defvar org-clock-start-time)
4086 (defvar org-clock-marker (make-marker)
4087 "Marker recording the last clock-in.")
4088 (defvar org-clock-hd-marker (make-marker)
4089 "Marker recording the last clock-in, but the headline position.")
4090 (defvar org-clock-heading ""
4091 "The heading of the current clock entry.")
4092 (defun org-clock-is-active ()
4093 "Return non-nil if clock is currently running.
4094 The return value is actually the clock marker."
4095 (marker-buffer org-clock-marker))
4097 (eval-and-compile
4098 (org-autoload
4099 "org-clock"
4100 '(org-clock-in org-clock-out org-clock-cancel
4101 org-clock-goto org-clock-sum org-clock-display
4102 org-clock-remove-overlays org-clock-report
4103 org-clocktable-shift org-dblock-write:clocktable
4104 org-get-clocktable org-resolve-clocks)))
4106 (defun org-clock-update-time-maybe ()
4107 "If this is a CLOCK line, update it and return t.
4108 Otherwise, return nil."
4109 (interactive)
4110 (save-excursion
4111 (beginning-of-line 1)
4112 (skip-chars-forward " \t")
4113 (when (looking-at org-clock-string)
4114 (let ((re (concat "[ \t]*" org-clock-string
4115 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4116 "\\([ \t]*=>.*\\)?\\)?"))
4117 ts te h m s neg)
4118 (cond
4119 ((not (looking-at re))
4120 nil)
4121 ((not (match-end 2))
4122 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4123 (> org-clock-marker (point))
4124 (<= org-clock-marker (point-at-eol)))
4125 ;; The clock is running here
4126 (setq org-clock-start-time
4127 (apply 'encode-time
4128 (org-parse-time-string (match-string 1))))
4129 (org-clock-update-mode-line)))
4131 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4132 (end-of-line 1)
4133 (setq ts (match-string 1)
4134 te (match-string 3))
4135 (setq s (- (org-float-time
4136 (apply 'encode-time (org-parse-time-string te)))
4137 (org-float-time
4138 (apply 'encode-time (org-parse-time-string ts))))
4139 neg (< s 0)
4140 s (abs s)
4141 h (floor (/ s 3600))
4142 s (- s (* 3600 h))
4143 m (floor (/ s 60))
4144 s (- s (* 60 s)))
4145 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4146 t))))))
4148 (defun org-check-running-clock ()
4149 "Check if the current buffer contains the running clock.
4150 If yes, offer to stop it and to save the buffer with the changes."
4151 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4152 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4153 (buffer-name))))
4154 (org-clock-out)
4155 (when (y-or-n-p "Save changed buffer?")
4156 (save-buffer))))
4158 (defun org-clocktable-try-shift (dir n)
4159 "Check if this line starts a clock table, if yes, shift the time block."
4160 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4161 (org-clocktable-shift dir n)))
4163 ;; Autoload org-timer.el
4165 (eval-and-compile
4166 (org-autoload
4167 "org-timer"
4168 '(org-timer-start org-timer org-timer-item
4169 org-timer-change-times-in-region
4170 org-timer-set-timer
4171 org-timer-reset-timers
4172 org-timer-show-remaining-time)))
4174 ;; Autoload org-feed.el
4176 (eval-and-compile
4177 (org-autoload
4178 "org-feed"
4179 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4182 ;; Autoload org-indent.el
4184 ;; Define the variable already here, to make sure we have it.
4185 (defvar org-indent-mode nil
4186 "Non-nil if Org-Indent mode is enabled.
4187 Use the command `org-indent-mode' to change this variable.")
4189 (eval-and-compile
4190 (org-autoload
4191 "org-indent"
4192 '(org-indent-mode)))
4194 ;; Autoload org-mobile.el
4196 (eval-and-compile
4197 (org-autoload
4198 "org-mobile"
4199 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4201 ;; Autoload archiving code
4202 ;; The stuff that is needed for cycling and tags has to be defined here.
4204 (defgroup org-archive nil
4205 "Options concerning archiving in Org-mode."
4206 :tag "Org Archive"
4207 :group 'org-structure)
4209 (defcustom org-archive-location "%s_archive::"
4210 "The location where subtrees should be archived.
4212 The value of this variable is a string, consisting of two parts,
4213 separated by a double-colon. The first part is a filename and
4214 the second part is a headline.
4216 When the filename is omitted, archiving happens in the same file.
4217 %s in the filename will be replaced by the current file
4218 name (without the directory part). Archiving to a different file
4219 is useful to keep archived entries from contributing to the
4220 Org-mode Agenda.
4222 The archived entries will be filed as subtrees of the specified
4223 headline. When the headline is omitted, the subtrees are simply
4224 filed away at the end of the file, as top-level entries. Also in
4225 the heading you can use %s to represent the file name, this can be
4226 useful when using the same archive for a number of different files.
4228 Here are a few examples:
4229 \"%s_archive::\"
4230 If the current file is Projects.org, archive in file
4231 Projects.org_archive, as top-level trees. This is the default.
4233 \"::* Archived Tasks\"
4234 Archive in the current file, under the top-level headline
4235 \"* Archived Tasks\".
4237 \"~/org/archive.org::\"
4238 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4240 \"~/org/archive.org::* From %s\"
4241 Archive in file ~/org/archive.org (absolute path), under headlines
4242 \"From FILENAME\" where file name is the current file name.
4244 \"~/org/datetree.org::datetree/* Finished Tasks\"
4245 The \"datetree/\" string is special, signifying to archive
4246 items to the datetree. Items are placed in either the CLOSED
4247 date of the item, or the current date if there is no CLOSED date.
4248 The heading will be a subentry to the current date. There doesn't
4249 need to be a heading, but there always needs to be a slash after
4250 datetree. For example, to store archived items directly in the
4251 datetree, use \"~/org/datetree.org::datetree/\".
4253 \"basement::** Finished Tasks\"
4254 Archive in file ./basement (relative path), as level 3 trees
4255 below the level 2 heading \"** Finished Tasks\".
4257 You may set this option on a per-file basis by adding to the buffer a
4258 line like
4260 #+ARCHIVE: basement::** Finished Tasks
4262 You may also define it locally for a subtree by setting an ARCHIVE property
4263 in the entry. If such a property is found in an entry, or anywhere up
4264 the hierarchy, it will be used."
4265 :group 'org-archive
4266 :type 'string)
4268 (defcustom org-archive-tag "ARCHIVE"
4269 "The tag that marks a subtree as archived.
4270 An archived subtree does not open during visibility cycling, and does
4271 not contribute to the agenda listings.
4272 After changing this, font-lock must be restarted in the relevant buffers to
4273 get the proper fontification."
4274 :group 'org-archive
4275 :group 'org-keywords
4276 :type 'string)
4278 (defcustom org-agenda-skip-archived-trees t
4279 "Non-nil means the agenda will skip any items located in archived trees.
4280 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4281 variable is no longer recommended, you should leave it at the value t.
4282 Instead, use the key `v' to cycle the archives-mode in the agenda."
4283 :group 'org-archive
4284 :group 'org-agenda-skip
4285 :type 'boolean)
4287 (defcustom org-columns-skip-archived-trees t
4288 "Non-nil means ignore archived trees when creating column view."
4289 :group 'org-archive
4290 :group 'org-properties
4291 :type 'boolean)
4293 (defcustom org-cycle-open-archived-trees nil
4294 "Non-nil means `org-cycle' will open archived trees.
4295 An archived tree is a tree marked with the tag ARCHIVE.
4296 When nil, archived trees will stay folded. You can still open them with
4297 normal outline commands like `show-all', but not with the cycling commands."
4298 :group 'org-archive
4299 :group 'org-cycle
4300 :type 'boolean)
4302 (defcustom org-sparse-tree-open-archived-trees nil
4303 "Non-nil means sparse tree construction shows matches in archived trees.
4304 When nil, matches in these trees are highlighted, but the trees are kept in
4305 collapsed state."
4306 :group 'org-archive
4307 :group 'org-sparse-trees
4308 :type 'boolean)
4310 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4311 "The default date type when building a sparse tree.
4312 When this is nil, a date is a scheduled or a deadline timestamp.
4313 Otherwise, these types are allowed:
4315 all: all timestamps
4316 active: only active timestamps (<...>)
4317 inactive: only inactive timestamps (<...)
4318 scheduled: only scheduled timestamps
4319 deadline: only deadline timestamps"
4320 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4321 (const :tag "All timestamps" all)
4322 (const :tag "Only active timestamps" active)
4323 (const :tag "Only inactive timestamps" inactive)
4324 (const :tag "Only scheduled timestamps" scheduled)
4325 (const :tag "Only deadline timestamps" deadline))
4326 ;; :version "24.3"
4327 :group 'org-sparse-trees)
4329 (defun org-cycle-hide-archived-subtrees (state)
4330 "Re-hide all archived subtrees after a visibility state change."
4331 (when (and (not org-cycle-open-archived-trees)
4332 (not (memq state '(overview folded))))
4333 (save-excursion
4334 (let* ((globalp (memq state '(contents all)))
4335 (beg (if globalp (point-min) (point)))
4336 (end (if globalp (point-max) (org-end-of-subtree t))))
4337 (org-hide-archived-subtrees beg end)
4338 (goto-char beg)
4339 (if (looking-at (concat ".*:" org-archive-tag ":"))
4340 (message "%s" (substitute-command-keys
4341 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4343 (defun org-force-cycle-archived ()
4344 "Cycle subtree even if it is archived."
4345 (interactive)
4346 (setq this-command 'org-cycle)
4347 (let ((org-cycle-open-archived-trees t))
4348 (call-interactively 'org-cycle)))
4350 (defun org-hide-archived-subtrees (beg end)
4351 "Re-hide all archived subtrees after a visibility state change."
4352 (save-excursion
4353 (let* ((re (concat ":" org-archive-tag ":")))
4354 (goto-char beg)
4355 (while (re-search-forward re end t)
4356 (when (org-at-heading-p)
4357 (org-flag-subtree t)
4358 (org-end-of-subtree t))))))
4360 (declare-function outline-end-of-heading "outline" ())
4361 (declare-function outline-flag-region "outline" (from to flag))
4362 (defun org-flag-subtree (flag)
4363 (save-excursion
4364 (org-back-to-heading t)
4365 (outline-end-of-heading)
4366 (outline-flag-region (point)
4367 (progn (org-end-of-subtree t) (point))
4368 flag)))
4370 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4372 (eval-and-compile
4373 (org-autoload "org-archive"
4374 '(org-add-archive-files org-archive-subtree
4375 org-archive-to-archive-sibling org-toggle-archive-tag
4376 org-archive-subtree-default
4377 org-archive-subtree-default-with-confirmation)))
4379 ;; Autoload Column View Code
4381 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4382 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4383 (declare-function org-columns-compute "org-colview" (property))
4385 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4386 '(org-columns-number-to-string org-columns-get-format-and-top-level
4387 org-columns-compute org-agenda-columns org-columns-remove-overlays
4388 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4390 ;; Autoload ID code
4392 (declare-function org-id-store-link "org-id")
4393 (declare-function org-id-locations-load "org-id")
4394 (declare-function org-id-locations-save "org-id")
4395 (defvar org-id-track-globally)
4396 (org-autoload "org-id"
4397 '(org-id-get-create org-id-new org-id-copy org-id-get
4398 org-id-get-with-outline-path-completion
4399 org-id-get-with-outline-drilling org-id-store-link
4400 org-id-goto org-id-find org-id-store-link))
4402 ;; Autoload Plotting Code
4404 (org-autoload "org-plot"
4405 '(org-plot/gnuplot))
4407 ;;; Variables for pre-computed regular expressions, all buffer local
4409 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4410 "Matches first line of a hidden block.")
4411 (make-variable-buffer-local 'org-drawer-regexp)
4412 (defvar org-todo-regexp nil
4413 "Matches any of the TODO state keywords.")
4414 (make-variable-buffer-local 'org-todo-regexp)
4415 (defvar org-not-done-regexp nil
4416 "Matches any of the TODO state keywords except the last one.")
4417 (make-variable-buffer-local 'org-not-done-regexp)
4418 (defvar org-not-done-heading-regexp nil
4419 "Matches a TODO headline that is not done.")
4420 (make-variable-buffer-local 'org-not-done-regexp)
4421 (defvar org-todo-line-regexp nil
4422 "Matches a headline and puts TODO state into group 2 if present.")
4423 (make-variable-buffer-local 'org-todo-line-regexp)
4424 (defvar org-complex-heading-regexp nil
4425 "Matches a headline and puts everything into groups:
4426 group 1: the stars
4427 group 2: The todo keyword, maybe
4428 group 3: Priority cookie
4429 group 4: True headline
4430 group 5: Tags")
4431 (make-variable-buffer-local 'org-complex-heading-regexp)
4432 (defvar org-complex-heading-regexp-format nil
4433 "Printf format to make regexp to match an exact headline.
4434 This regexp will match the headline of any node which has the
4435 exact headline text that is put into the format, but may have any
4436 TODO state, priority and tags.")
4437 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4438 (defvar org-todo-line-tags-regexp nil
4439 "Matches a headline and puts TODO state into group 2 if present.
4440 Also put tags into group 4 if tags are present.")
4441 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4442 (defvar org-ds-keyword-length 12
4443 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4444 (make-variable-buffer-local 'org-ds-keyword-length)
4445 (defvar org-deadline-regexp nil
4446 "Matches the DEADLINE keyword.")
4447 (make-variable-buffer-local 'org-deadline-regexp)
4448 (defvar org-deadline-time-regexp nil
4449 "Matches the DEADLINE keyword together with a time stamp.")
4450 (make-variable-buffer-local 'org-deadline-time-regexp)
4451 (defvar org-deadline-line-regexp nil
4452 "Matches the DEADLINE keyword and the rest of the line.")
4453 (make-variable-buffer-local 'org-deadline-line-regexp)
4454 (defvar org-scheduled-regexp nil
4455 "Matches the SCHEDULED keyword.")
4456 (make-variable-buffer-local 'org-scheduled-regexp)
4457 (defvar org-scheduled-time-regexp nil
4458 "Matches the SCHEDULED keyword together with a time stamp.")
4459 (make-variable-buffer-local 'org-scheduled-time-regexp)
4460 (defvar org-closed-time-regexp nil
4461 "Matches the CLOSED keyword together with a time stamp.")
4462 (make-variable-buffer-local 'org-closed-time-regexp)
4464 (defvar org-keyword-time-regexp nil
4465 "Matches any of the 4 keywords, together with the time stamp.")
4466 (make-variable-buffer-local 'org-keyword-time-regexp)
4467 (defvar org-keyword-time-not-clock-regexp nil
4468 "Matches any of the 3 keywords, together with the time stamp.")
4469 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4470 (defvar org-maybe-keyword-time-regexp nil
4471 "Matches a timestamp, possibly preceded by a keyword.")
4472 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4473 (defvar org-all-time-keywords nil
4474 "List of time keywords.")
4475 (make-variable-buffer-local 'org-all-time-keywords)
4477 (defconst org-plain-time-of-day-regexp
4478 (concat
4479 "\\(\\<[012]?[0-9]"
4480 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4481 "\\(--?"
4482 "\\(\\<[012]?[0-9]"
4483 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4484 "\\)?")
4485 "Regular expression to match a plain time or time range.
4486 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4487 groups carry important information:
4488 0 the full match
4489 1 the first time, range or not
4490 8 the second time, if it is a range.")
4492 (defconst org-plain-time-extension-regexp
4493 (concat
4494 "\\(\\<[012]?[0-9]"
4495 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4496 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4497 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4498 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4499 groups carry important information:
4500 0 the full match
4501 7 hours of duration
4502 9 minutes of duration")
4504 (defconst org-stamp-time-of-day-regexp
4505 (concat
4506 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4507 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4508 "\\(--?"
4509 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4510 "Regular expression to match a timestamp time or time range.
4511 After a match, the following groups carry important information:
4512 0 the full match
4513 1 date plus weekday, for back referencing to make sure both times are on the same day
4514 2 the first time, range or not
4515 4 the second time, if it is a range.")
4517 (defconst org-startup-options
4518 '(("fold" org-startup-folded t)
4519 ("overview" org-startup-folded t)
4520 ("nofold" org-startup-folded nil)
4521 ("showall" org-startup-folded nil)
4522 ("showeverything" org-startup-folded showeverything)
4523 ("content" org-startup-folded content)
4524 ("indent" org-startup-indented t)
4525 ("noindent" org-startup-indented nil)
4526 ("hidestars" org-hide-leading-stars t)
4527 ("showstars" org-hide-leading-stars nil)
4528 ("odd" org-odd-levels-only t)
4529 ("oddeven" org-odd-levels-only nil)
4530 ("align" org-startup-align-all-tables t)
4531 ("noalign" org-startup-align-all-tables nil)
4532 ("inlineimages" org-startup-with-inline-images t)
4533 ("noinlineimages" org-startup-with-inline-images nil)
4534 ("customtime" org-display-custom-times t)
4535 ("logdone" org-log-done time)
4536 ("lognotedone" org-log-done note)
4537 ("nologdone" org-log-done nil)
4538 ("lognoteclock-out" org-log-note-clock-out t)
4539 ("nolognoteclock-out" org-log-note-clock-out nil)
4540 ("logrepeat" org-log-repeat state)
4541 ("lognoterepeat" org-log-repeat note)
4542 ("nologrepeat" org-log-repeat nil)
4543 ("logreschedule" org-log-reschedule time)
4544 ("lognotereschedule" org-log-reschedule note)
4545 ("nologreschedule" org-log-reschedule nil)
4546 ("logredeadline" org-log-redeadline time)
4547 ("lognoteredeadline" org-log-redeadline note)
4548 ("nologredeadline" org-log-redeadline nil)
4549 ("logrefile" org-log-refile time)
4550 ("lognoterefile" org-log-refile note)
4551 ("nologrefile" org-log-refile nil)
4552 ("fninline" org-footnote-define-inline t)
4553 ("nofninline" org-footnote-define-inline nil)
4554 ("fnlocal" org-footnote-section nil)
4555 ("fnauto" org-footnote-auto-label t)
4556 ("fnprompt" org-footnote-auto-label nil)
4557 ("fnconfirm" org-footnote-auto-label confirm)
4558 ("fnplain" org-footnote-auto-label plain)
4559 ("fnadjust" org-footnote-auto-adjust t)
4560 ("nofnadjust" org-footnote-auto-adjust nil)
4561 ("constcgs" constants-unit-system cgs)
4562 ("constSI" constants-unit-system SI)
4563 ("noptag" org-tag-persistent-alist nil)
4564 ("hideblocks" org-hide-block-startup t)
4565 ("nohideblocks" org-hide-block-startup nil)
4566 ("beamer" org-startup-with-beamer-mode t)
4567 ("entitiespretty" org-pretty-entities t)
4568 ("entitiesplain" org-pretty-entities nil))
4569 "Variable associated with STARTUP options for org-mode.
4570 Each element is a list of three items: the startup options (as written
4571 in the #+STARTUP line), the corresponding variable, and the value to set
4572 this variable to if the option is found. An optional forth element PUSH
4573 means to push this value onto the list in the variable.")
4575 (defun org-update-property-plist (key val props)
4576 "Update PROPS with KEY and VAL."
4577 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4578 (key (if appending (substring key 0 (- (length key) 1)) key))
4579 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4580 (previous (cdr (assoc key props))))
4581 (if appending
4582 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4583 (cons (cons key val) remainder))))
4585 (defconst org-block-regexp
4586 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4587 "Regular expression for hiding blocks.")
4588 (defconst org-heading-keyword-regexp-format
4589 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4590 "Printf format for a regexp matching an headline with some keyword.
4591 This regexp will match the headline of any node which has the
4592 exact keyword that is put into the format. The keyword isn't in
4593 any group by default, but the stars and the body are.")
4594 (defconst org-heading-keyword-maybe-regexp-format
4595 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4596 "Printf format for a regexp matching an headline, possibly with some keyword.
4597 This regexp can match any headline with the specified keyword, or
4598 without a keyword. The keyword isn't in any group by default,
4599 but the stars and the body are.")
4601 (defun org-set-regexps-and-options ()
4602 "Precompute regular expressions for current buffer."
4603 (when (derived-mode-p 'org-mode)
4604 (org-set-local 'org-todo-kwd-alist nil)
4605 (org-set-local 'org-todo-key-alist nil)
4606 (org-set-local 'org-todo-key-trigger nil)
4607 (org-set-local 'org-todo-keywords-1 nil)
4608 (org-set-local 'org-done-keywords nil)
4609 (org-set-local 'org-todo-heads nil)
4610 (org-set-local 'org-todo-sets nil)
4611 (org-set-local 'org-todo-log-states nil)
4612 (org-set-local 'org-file-properties nil)
4613 (org-set-local 'org-file-tags nil)
4614 (let ((re (org-make-options-regexp
4615 '("CATEGORY" "TODO" "COLUMNS"
4616 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4617 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4618 "OPTIONS")
4619 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4620 (splitre "[ \t]+")
4621 (scripts org-use-sub-superscripts)
4622 kwds kws0 kwsa key log value cat arch tags const links hw dws
4623 tail sep kws1 prio props ftags drawers beamer-p
4624 ext-setup-or-nil setup-contents (start 0))
4625 (save-excursion
4626 (save-restriction
4627 (widen)
4628 (goto-char (point-min))
4629 (while (or (and ext-setup-or-nil
4630 (string-match re ext-setup-or-nil start)
4631 (setq start (match-end 0)))
4632 (and (setq ext-setup-or-nil nil start 0)
4633 (re-search-forward re nil t)))
4634 (setq key (upcase (match-string 1 ext-setup-or-nil))
4635 value (org-match-string-no-properties 2 ext-setup-or-nil))
4636 (if (stringp value) (setq value (org-trim value)))
4637 (cond
4638 ((equal key "CATEGORY")
4639 (setq cat value))
4640 ((member key '("SEQ_TODO" "TODO"))
4641 (push (cons 'sequence (org-split-string value splitre)) kwds))
4642 ((equal key "TYP_TODO")
4643 (push (cons 'type (org-split-string value splitre)) kwds))
4644 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4645 ;; general TODO-like setup
4646 (push (cons (intern (downcase (match-string 1 key)))
4647 (org-split-string value splitre)) kwds))
4648 ((equal key "TAGS")
4649 (setq tags (append tags (if tags '("\\n") nil)
4650 (org-split-string value splitre))))
4651 ((equal key "COLUMNS")
4652 (org-set-local 'org-columns-default-format value))
4653 ((equal key "LINK")
4654 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4655 (push (cons (match-string 1 value)
4656 (org-trim (match-string 2 value)))
4657 links)))
4658 ((equal key "PRIORITIES")
4659 (setq prio (org-split-string value " +")))
4660 ((equal key "PROPERTY")
4661 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4662 (setq props (org-update-property-plist (match-string 1 value)
4663 (match-string 2 value)
4664 props))))
4665 ((equal key "FILETAGS")
4666 (when (string-match "\\S-" value)
4667 (setq ftags
4668 (append
4669 ftags
4670 (apply 'append
4671 (mapcar (lambda (x) (org-split-string x ":"))
4672 (org-split-string value)))))))
4673 ((equal key "DRAWERS")
4674 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4675 ((equal key "CONSTANTS")
4676 (setq const (append const (org-split-string value splitre))))
4677 ((equal key "STARTUP")
4678 (let ((opts (org-split-string value splitre))
4679 l var val)
4680 (while (setq l (pop opts))
4681 (when (setq l (assoc l org-startup-options))
4682 (setq var (nth 1 l) val (nth 2 l))
4683 (if (not (nth 3 l))
4684 (set (make-local-variable var) val)
4685 (if (not (listp (symbol-value var)))
4686 (set (make-local-variable var) nil))
4687 (set (make-local-variable var) (symbol-value var))
4688 (add-to-list var val))))))
4689 ((equal key "ARCHIVE")
4690 (setq arch value)
4691 (remove-text-properties 0 (length arch)
4692 '(face t fontified t) arch))
4693 ((equal key "LATEX_CLASS")
4694 (setq beamer-p (equal value "beamer")))
4695 ((equal key "OPTIONS")
4696 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4697 (setq scripts (read (match-string 2 value)))))
4698 ((equal key "SETUPFILE")
4699 (setq setup-contents (org-file-contents
4700 (expand-file-name
4701 (org-remove-double-quotes value))
4702 'noerror))
4703 (if (not ext-setup-or-nil)
4704 (setq ext-setup-or-nil setup-contents start 0)
4705 (setq ext-setup-or-nil
4706 (concat (substring ext-setup-or-nil 0 start)
4707 "\n" setup-contents "\n"
4708 (substring ext-setup-or-nil start)))))))
4709 ;; search for property blocks
4710 (goto-char (point-min))
4711 (while (re-search-forward org-block-regexp nil t)
4712 (when (equal "PROPERTY" (upcase (match-string 1)))
4713 (setq value (replace-regexp-in-string
4714 "[\n\r]" " " (match-string 4)))
4715 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4716 (setq props (org-update-property-plist (match-string 1 value)
4717 (match-string 2 value)
4718 props)))))))
4719 (org-set-local 'org-use-sub-superscripts scripts)
4720 (when cat
4721 (org-set-local 'org-category (intern cat))
4722 (push (cons "CATEGORY" cat) props))
4723 (when prio
4724 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4725 (setq prio (mapcar 'string-to-char prio))
4726 (org-set-local 'org-highest-priority (nth 0 prio))
4727 (org-set-local 'org-lowest-priority (nth 1 prio))
4728 (org-set-local 'org-default-priority (nth 2 prio)))
4729 (and props (org-set-local 'org-file-properties (nreverse props)))
4730 (and ftags (org-set-local 'org-file-tags
4731 (mapcar 'org-add-prop-inherited ftags)))
4732 (and drawers (org-set-local 'org-drawers drawers))
4733 (and arch (org-set-local 'org-archive-location arch))
4734 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4735 ;; Process the TODO keywords
4736 (unless kwds
4737 ;; Use the global values as if they had been given locally.
4738 (setq kwds (default-value 'org-todo-keywords))
4739 (if (stringp (car kwds))
4740 (setq kwds (list (cons org-todo-interpretation
4741 (default-value 'org-todo-keywords)))))
4742 (setq kwds (reverse kwds)))
4743 (setq kwds (nreverse kwds))
4744 (let (inter kws kw)
4745 (while (setq kws (pop kwds))
4746 (let ((kws (or
4747 (run-hook-with-args-until-success
4748 'org-todo-setup-filter-hook kws)
4749 kws)))
4750 (setq inter (pop kws) sep (member "|" kws)
4751 kws0 (delete "|" (copy-sequence kws))
4752 kwsa nil
4753 kws1 (mapcar
4754 (lambda (x)
4755 ;; 1 2
4756 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4757 (progn
4758 (setq kw (match-string 1 x)
4759 key (and (match-end 2) (match-string 2 x))
4760 log (org-extract-log-state-settings x))
4761 (push (cons kw (and key (string-to-char key))) kwsa)
4762 (and log (push log org-todo-log-states))
4764 (error "Invalid TODO keyword %s" x)))
4765 kws0)
4766 kwsa (if kwsa (append '((:startgroup))
4767 (nreverse kwsa)
4768 '((:endgroup))))
4769 hw (car kws1)
4770 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4771 tail (list inter hw (car dws) (org-last dws))))
4772 (add-to-list 'org-todo-heads hw 'append)
4773 (push kws1 org-todo-sets)
4774 (setq org-done-keywords (append org-done-keywords dws nil))
4775 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4776 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4777 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4778 (setq org-todo-sets (nreverse org-todo-sets)
4779 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4780 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4781 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4782 ;; Process the constants
4783 (when const
4784 (let (e cst)
4785 (while (setq e (pop const))
4786 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4787 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4788 (setq org-table-formula-constants-local cst)))
4790 ;; Process the tags.
4791 (when tags
4792 (let (e tgs)
4793 (while (setq e (pop tags))
4794 (cond
4795 ((equal e "{") (push '(:startgroup) tgs))
4796 ((equal e "}") (push '(:endgroup) tgs))
4797 ((equal e "\\n") (push '(:newline) tgs))
4798 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4799 (push (cons (match-string 1 e)
4800 (string-to-char (match-string 2 e)))
4801 tgs))
4802 (t (push (list e) tgs))))
4803 (org-set-local 'org-tag-alist nil)
4804 (while (setq e (pop tgs))
4805 (or (and (stringp (car e))
4806 (assoc (car e) org-tag-alist))
4807 (push e org-tag-alist)))))
4809 ;; Compute the regular expressions and other local variables.
4810 ;; Using `org-outline-regexp-bol' would complicate them much,
4811 ;; because of the fixed white space at the end of that string.
4812 (if (not org-done-keywords)
4813 (setq org-done-keywords (and org-todo-keywords-1
4814 (list (org-last org-todo-keywords-1)))))
4815 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4816 (length org-scheduled-string)
4817 (length org-clock-string)
4818 (length org-closed-string)))
4819 org-drawer-regexp
4820 (concat "^[ \t]*:\\("
4821 (mapconcat 'regexp-quote org-drawers "\\|")
4822 "\\):[ \t]*$")
4823 org-not-done-keywords
4824 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4825 org-todo-regexp
4826 (concat "\\("
4827 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4828 "\\)")
4829 org-not-done-regexp
4830 (concat "\\("
4831 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4832 "\\)")
4833 org-not-done-heading-regexp
4834 (format org-heading-keyword-regexp-format org-not-done-regexp)
4835 org-todo-line-regexp
4836 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4837 org-complex-heading-regexp
4838 (concat "^\\(\\*+\\)"
4839 "\\(?: +" org-todo-regexp "\\)?"
4840 "\\(?: +\\(\\[#.\\]\\)\\)?"
4841 "\\(?: +\\(.*?\\)\\)??"
4842 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4843 "[ \t]*$")
4844 org-complex-heading-regexp-format
4845 (concat "^\\(\\*+\\)"
4846 "\\(?: +" org-todo-regexp "\\)?"
4847 "\\(?: +\\(\\[#.\\]\\)\\)?"
4848 "\\(?: +"
4849 ;; Stats cookies can be stuck to body.
4850 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4851 "\\(%s\\)"
4852 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4853 "\\)"
4854 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4855 "[ \t]*$")
4856 org-todo-line-tags-regexp
4857 (concat "^\\(\\*+\\)"
4858 "\\(?: +" org-todo-regexp "\\)?"
4859 "\\(?: +\\(.*?\\)\\)??"
4860 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4861 "[ \t]*$")
4862 org-deadline-regexp (concat "\\<" org-deadline-string)
4863 org-deadline-time-regexp
4864 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4865 org-deadline-line-regexp
4866 (concat "\\<\\(" org-deadline-string "\\).*")
4867 org-scheduled-regexp
4868 (concat "\\<" org-scheduled-string)
4869 org-scheduled-time-regexp
4870 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4871 org-closed-time-regexp
4872 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4873 org-keyword-time-regexp
4874 (concat "\\<\\(" org-scheduled-string
4875 "\\|" org-deadline-string
4876 "\\|" org-closed-string
4877 "\\|" org-clock-string "\\)"
4878 " *[[<]\\([^]>]+\\)[]>]")
4879 org-keyword-time-not-clock-regexp
4880 (concat "\\<\\(" org-scheduled-string
4881 "\\|" org-deadline-string
4882 "\\|" org-closed-string
4883 "\\)"
4884 " *[[<]\\([^]>]+\\)[]>]")
4885 org-maybe-keyword-time-regexp
4886 (concat "\\(\\<\\(" org-scheduled-string
4887 "\\|" org-deadline-string
4888 "\\|" org-closed-string
4889 "\\|" org-clock-string "\\)\\)?"
4890 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4891 org-all-time-keywords
4892 (mapcar (lambda (w) (substring w 0 -1))
4893 (list org-scheduled-string org-deadline-string
4894 org-clock-string org-closed-string))
4896 (org-compute-latex-and-specials-regexp)
4897 (org-set-font-lock-defaults))))
4899 (defun org-file-contents (file &optional noerror)
4900 "Return the contents of FILE, as a string."
4901 (if (or (not file)
4902 (not (file-readable-p file)))
4903 (if noerror
4904 (progn
4905 (message "Cannot read file \"%s\"" file)
4906 (ding) (sit-for 2)
4908 (error "Cannot read file \"%s\"" file))
4909 (with-temp-buffer
4910 (insert-file-contents file)
4911 (buffer-string))))
4913 (defun org-extract-log-state-settings (x)
4914 "Extract the log state setting from a TODO keyword string.
4915 This will extract info from a string like \"WAIT(w@/!)\"."
4916 (let (kw key log1 log2)
4917 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4918 (setq kw (match-string 1 x)
4919 key (and (match-end 2) (match-string 2 x))
4920 log1 (and (match-end 3) (match-string 3 x))
4921 log2 (and (match-end 4) (match-string 4 x)))
4922 (and (or log1 log2)
4923 (list kw
4924 (and log1 (if (equal log1 "!") 'time 'note))
4925 (and log2 (if (equal log2 "!") 'time 'note)))))))
4927 (defun org-remove-keyword-keys (list)
4928 "Remove a pair of parenthesis at the end of each string in LIST."
4929 (mapcar (lambda (x)
4930 (if (string-match "(.*)$" x)
4931 (substring x 0 (match-beginning 0))
4933 list))
4935 (defun org-assign-fast-keys (alist)
4936 "Assign fast keys to a keyword-key alist.
4937 Respect keys that are already there."
4938 (let (new e (alt ?0))
4939 (while (setq e (pop alist))
4940 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4941 (cdr e)) ;; Key already assigned.
4942 (push e new)
4943 (let ((clist (string-to-list (downcase (car e))))
4944 (used (append new alist)))
4945 (when (= (car clist) ?@)
4946 (pop clist))
4947 (while (and clist (rassoc (car clist) used))
4948 (pop clist))
4949 (unless clist
4950 (while (rassoc alt used)
4951 (incf alt)))
4952 (push (cons (car e) (or (car clist) alt)) new))))
4953 (nreverse new)))
4955 ;;; Some variables used in various places
4957 (defvar org-window-configuration nil
4958 "Used in various places to store a window configuration.")
4959 (defvar org-selected-window nil
4960 "Used in various places to store a window configuration.")
4961 (defvar org-finish-function nil
4962 "Function to be called when `C-c C-c' is used.
4963 This is for getting out of special buffers like capture.")
4966 ;; FIXME: Occasionally check by commenting these, to make sure
4967 ;; no other functions uses these, forgetting to let-bind them.
4968 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4969 (defvar org-last-state)
4970 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4972 ;; Defined somewhere in this file, but used before definition.
4973 (defvar org-entities) ;; defined in org-entities.el
4974 (defvar org-struct-menu)
4975 (defvar org-org-menu)
4976 (defvar org-tbl-menu)
4978 ;;;; Define the Org-mode
4980 ;; We use a before-change function to check if a table might need
4981 ;; an update.
4982 (defvar org-table-may-need-update t
4983 "Indicates that a table might need an update.
4984 This variable is set by `org-before-change-function'.
4985 `org-table-align' sets it back to nil.")
4986 (defun org-before-change-function (beg end)
4987 "Every change indicates that a table might need an update."
4988 (setq org-table-may-need-update t))
4989 (defvar org-mode-map)
4990 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4991 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4992 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4993 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4994 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4995 (defvar org-table-buffer-is-an nil)
4997 (defvar bidi-paragraph-direction)
4998 (defvar buffer-face-mode-face)
5000 (require 'outline)
5001 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5002 (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"))
5003 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5005 ;; Other stuff we need.
5006 (require 'time-date)
5007 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5008 (require 'easymenu)
5009 (require 'overlay)
5011 (require 'org-macs)
5012 (require 'org-entities)
5013 ;; (require 'org-compat) moved higher up in the file before it is first used
5014 (require 'org-faces)
5015 (require 'org-list)
5016 (require 'org-pcomplete)
5017 (require 'org-src)
5018 (require 'org-footnote)
5020 ;; babel
5021 (require 'ob)
5022 (require 'ob-table)
5023 (require 'ob-lob)
5024 (require 'ob-ref)
5025 (require 'ob-tangle)
5026 (require 'ob-comint)
5027 (require 'ob-keys)
5029 ;;;###autoload
5030 (define-derived-mode org-mode outline-mode "Org"
5031 "Outline-based notes management and organizer, alias
5032 \"Carsten's outline-mode for keeping track of everything.\"
5034 Org-mode develops organizational tasks around a NOTES file which
5035 contains information about projects as plain text. Org-mode is
5036 implemented on top of outline-mode, which is ideal to keep the content
5037 of large files well structured. It supports ToDo items, deadlines and
5038 time stamps, which magically appear in the diary listing of the Emacs
5039 calendar. Tables are easily created with a built-in table editor.
5040 Plain text URL-like links connect to websites, emails (VM), Usenet
5041 messages (Gnus), BBDB entries, and any files related to the project.
5042 For printing and sharing of notes, an Org-mode file (or a part of it)
5043 can be exported as a structured ASCII or HTML file.
5045 The following commands are available:
5047 \\{org-mode-map}"
5049 ;; Get rid of Outline menus, they are not needed
5050 ;; Need to do this here because define-derived-mode sets up
5051 ;; the keymap so late. Still, it is a waste to call this each time
5052 ;; we switch another buffer into org-mode.
5053 (if (featurep 'xemacs)
5054 (when (boundp 'outline-mode-menu-heading)
5055 ;; Assume this is Greg's port, it uses easymenu
5056 (easy-menu-remove outline-mode-menu-heading)
5057 (easy-menu-remove outline-mode-menu-show)
5058 (easy-menu-remove outline-mode-menu-hide))
5059 (define-key org-mode-map [menu-bar headings] 'undefined)
5060 (define-key org-mode-map [menu-bar hide] 'undefined)
5061 (define-key org-mode-map [menu-bar show] 'undefined))
5063 (org-load-modules-maybe)
5064 (easy-menu-add org-org-menu)
5065 (easy-menu-add org-tbl-menu)
5066 (org-install-agenda-files-menu)
5067 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5068 (add-to-invisibility-spec '(org-cwidth))
5069 (add-to-invisibility-spec '(org-hide-block . t))
5070 (when (featurep 'xemacs)
5071 (org-set-local 'line-move-ignore-invisible t))
5072 (org-set-local 'outline-regexp org-outline-regexp)
5073 (org-set-local 'outline-level 'org-outline-level)
5074 (setq bidi-paragraph-direction 'left-to-right)
5075 (when (and org-ellipsis
5076 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5077 (fboundp 'make-glyph-code))
5078 (unless org-display-table
5079 (setq org-display-table (make-display-table)))
5080 (set-display-table-slot
5081 org-display-table 4
5082 (vconcat (mapcar
5083 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5084 org-ellipsis)))
5085 (if (stringp org-ellipsis) org-ellipsis "..."))))
5086 (setq buffer-display-table org-display-table))
5087 (org-set-regexps-and-options)
5088 (when (and org-tag-faces (not org-tags-special-faces-re))
5089 ;; tag faces set outside customize.... force initialization.
5090 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5091 ;; Calc embedded
5092 (org-set-local 'calc-embedded-open-mode "# ")
5093 (modify-syntax-entry ?@ "w")
5094 (modify-syntax-entry ?\" "\"")
5095 (if org-startup-truncated (setq truncate-lines t))
5096 (org-set-local 'font-lock-unfontify-region-function
5097 'org-unfontify-region)
5098 ;; Activate before-change-function
5099 (org-set-local 'org-table-may-need-update t)
5100 (org-add-hook 'before-change-functions 'org-before-change-function nil
5101 'local)
5102 ;; Check for running clock before killing a buffer
5103 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5104 ;; Initialize macros templates.
5105 (org-macro-initialize-templates)
5106 ;; Initialize radio targets.
5107 (org-update-radio-target-regexp)
5108 ;; Indentation.
5109 (org-set-local 'indent-line-function 'org-indent-line)
5110 (org-set-local 'indent-region-function 'org-indent-region)
5111 ;; Filling and auto-filling.
5112 (org-setup-filling)
5113 ;; Comments.
5114 (org-setup-comments-handling)
5115 ;; Beginning/end of defun
5116 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5117 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5118 ;; Next error for sparse trees
5119 (org-set-local 'next-error-function 'org-occur-next-match)
5120 ;; Make sure dependence stuff works reliably, even for users who set it
5121 ;; too late :-(
5122 (if org-enforce-todo-dependencies
5123 (add-hook 'org-blocker-hook
5124 'org-block-todo-from-children-or-siblings-or-parent)
5125 (remove-hook 'org-blocker-hook
5126 'org-block-todo-from-children-or-siblings-or-parent))
5127 (if org-enforce-todo-checkbox-dependencies
5128 (add-hook 'org-blocker-hook
5129 'org-block-todo-from-checkboxes)
5130 (remove-hook 'org-blocker-hook
5131 'org-block-todo-from-checkboxes))
5133 ;; Align options lines
5134 (org-set-local
5135 'align-mode-rules-list
5136 '((org-in-buffer-settings
5137 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5138 (modes . '(org-mode)))))
5140 ;; Imenu
5141 (org-set-local 'imenu-create-index-function
5142 'org-imenu-get-tree)
5144 ;; Make isearch reveal context
5145 (if (or (featurep 'xemacs)
5146 (not (boundp 'outline-isearch-open-invisible-function)))
5147 ;; Emacs 21 and XEmacs make use of the hook
5148 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5149 ;; Emacs 22 deals with this through a special variable
5150 (org-set-local 'outline-isearch-open-invisible-function
5151 (lambda (&rest ignore) (org-show-context 'isearch))))
5153 ;; Turn on org-beamer-mode?
5154 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5156 ;; Setup the pcomplete hooks
5157 (set (make-local-variable 'pcomplete-command-completion-function)
5158 'org-pcomplete-initial)
5159 (set (make-local-variable 'pcomplete-command-name-function)
5160 'org-command-at-point)
5161 (set (make-local-variable 'pcomplete-default-completion-function)
5162 'ignore)
5163 (set (make-local-variable 'pcomplete-parse-arguments-function)
5164 'org-parse-arguments)
5165 (set (make-local-variable 'pcomplete-termination-string) "")
5166 (when (>= emacs-major-version 23)
5167 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5169 ;; If empty file that did not turn on org-mode automatically, make it to.
5170 (if (and org-insert-mode-line-in-empty-file
5171 (org-called-interactively-p 'any)
5172 (= (point-min) (point-max)))
5173 (insert "# -*- mode: org -*-\n\n"))
5174 (unless org-inhibit-startup
5175 (when org-startup-align-all-tables
5176 (let ((bmp (buffer-modified-p)))
5177 (org-table-map-tables 'org-table-align 'quietly)
5178 (set-buffer-modified-p bmp)))
5179 (when org-startup-with-inline-images
5180 (org-display-inline-images))
5181 (when org-startup-indented
5182 (require 'org-indent)
5183 (org-indent-mode 1))
5184 (unless org-inhibit-startup-visibility-stuff
5185 (org-set-startup-visibility)))
5186 ;; Try to set org-hide correctly
5187 (set-face-foreground
5188 'org-hide
5189 (or (face-background 'default)
5190 (face-background 'org-default)
5191 (cdr (assoc 'background-color default-frame-alist))
5192 (cdr (assoc 'background-color initial-frame-alist))
5193 (cdr (assoc 'background-color window-system-default-frame-alist))
5194 (face-foreground 'org-hide))))
5196 (when (fboundp 'abbrev-table-put)
5197 (abbrev-table-put org-mode-abbrev-table
5198 :parents (list text-mode-abbrev-table)))
5200 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5202 (defun org-current-time ()
5203 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5204 (if (> (car org-time-stamp-rounding-minutes) 1)
5205 (let ((r (car org-time-stamp-rounding-minutes))
5206 (time (decode-time)))
5207 (apply 'encode-time
5208 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5209 (nthcdr 2 time))))
5210 (current-time)))
5212 (defun org-today ()
5213 "Return today date, considering `org-extend-today-until'."
5214 (time-to-days
5215 (time-subtract (current-time)
5216 (list 0 (* 3600 org-extend-today-until) 0))))
5218 ;;;; Font-Lock stuff, including the activators
5220 (defvar org-mouse-map (make-sparse-keymap))
5221 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5222 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5223 (when org-mouse-1-follows-link
5224 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5225 (when org-tab-follows-link
5226 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5227 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5229 (require 'font-lock)
5231 (defconst org-non-link-chars "]\t\n\r<>")
5232 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5233 "shell" "elisp" "doi" "message"))
5234 (defvar org-link-types-re nil
5235 "Matches a link that has a url-like prefix like \"http:\"")
5236 (defvar org-link-re-with-space nil
5237 "Matches a link with spaces, optional angular brackets around it.")
5238 (defvar org-link-re-with-space2 nil
5239 "Matches a link with spaces, optional angular brackets around it.")
5240 (defvar org-link-re-with-space3 nil
5241 "Matches a link with spaces, only for internal part in bracket links.")
5242 (defvar org-angle-link-re nil
5243 "Matches link with angular brackets, spaces are allowed.")
5244 (defvar org-plain-link-re nil
5245 "Matches plain link, without spaces.")
5246 (defvar org-bracket-link-regexp nil
5247 "Matches a link in double brackets.")
5248 (defvar org-bracket-link-analytic-regexp nil
5249 "Regular expression used to analyze links.
5250 Here is what the match groups contain after a match:
5251 1: http:
5252 2: http
5253 3: path
5254 4: [desc]
5255 5: desc")
5256 (defvar org-bracket-link-analytic-regexp++ nil
5257 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5258 (defvar org-any-link-re nil
5259 "Regular expression matching any link.")
5261 (defcustom org-match-sexp-depth 3
5262 "Number of stacked braces for sub/superscript matching.
5263 This has to be set before loading org.el to be effective."
5264 :group 'org-export-translation ; ??????????????????????????/
5265 :type 'integer)
5267 (defun org-create-multibrace-regexp (left right n)
5268 "Create a regular expression which will match a balanced sexp.
5269 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5270 as single character strings.
5271 The regexp returned will match the entire expression including the
5272 delimiters. It will also define a single group which contains the
5273 match except for the outermost delimiters. The maximum depth of
5274 stacked delimiters is N. Escaping delimiters is not possible."
5275 (let* ((nothing (concat "[^" left right "]*?"))
5276 (or "\\|")
5277 (re nothing)
5278 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5279 (while (> n 1)
5280 (setq n (1- n)
5281 re (concat re or next)
5282 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5283 (concat left "\\(" re "\\)" right)))
5285 (defvar org-match-substring-regexp
5286 (concat
5287 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5288 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5289 "\\|"
5290 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5291 "\\|"
5292 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5293 "The regular expression matching a sub- or superscript.")
5295 (defvar org-match-substring-with-braces-regexp
5296 (concat
5297 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5298 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5299 "\\)")
5300 "The regular expression matching a sub- or superscript, forcing braces.")
5302 (defun org-make-link-regexps ()
5303 "Update the link regular expressions.
5304 This should be called after the variable `org-link-types' has changed."
5305 (setq org-link-types-re
5306 (concat
5307 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5308 org-link-re-with-space
5309 (concat
5310 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5311 "\\([^" org-non-link-chars " ]"
5312 "[^" org-non-link-chars "]*"
5313 "[^" org-non-link-chars " ]\\)>?")
5314 org-link-re-with-space2
5315 (concat
5316 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5317 "\\([^" org-non-link-chars " ]"
5318 "[^\t\n\r]*"
5319 "[^" org-non-link-chars " ]\\)>?")
5320 org-link-re-with-space3
5321 (concat
5322 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5323 "\\([^" org-non-link-chars " ]"
5324 "[^\t\n\r]*\\)")
5325 org-angle-link-re
5326 (concat
5327 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5328 "\\([^" org-non-link-chars " ]"
5329 "[^" org-non-link-chars "]*"
5330 "\\)>")
5331 org-plain-link-re
5332 (concat
5333 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5334 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5335 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5336 org-bracket-link-regexp
5337 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5338 org-bracket-link-analytic-regexp
5339 (concat
5340 "\\[\\["
5341 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5342 "\\([^]]+\\)"
5343 "\\]"
5344 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5345 "\\]")
5346 org-bracket-link-analytic-regexp++
5347 (concat
5348 "\\[\\["
5349 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5350 "\\([^]]+\\)"
5351 "\\]"
5352 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5353 "\\]")
5354 org-any-link-re
5355 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5356 org-angle-link-re "\\)\\|\\("
5357 org-plain-link-re "\\)")))
5359 (org-make-link-regexps)
5361 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5362 "Regular expression for fast time stamp matching.")
5363 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5364 "Regular expression for fast time stamp matching.")
5365 (defconst org-ts-regexp0
5366 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5367 "Regular expression matching time strings for analysis.
5368 This one does not require the space after the date, so it can be used
5369 on a string that terminates immediately after the date.")
5370 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5371 "Regular expression matching time strings for analysis.")
5372 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5373 "Regular expression matching time stamps, with groups.")
5374 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5375 "Regular expression matching time stamps (also [..]), with groups.")
5376 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5377 "Regular expression matching a time stamp range.")
5378 (defconst org-tr-regexp-both
5379 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5380 "Regular expression matching a time stamp range.")
5381 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5382 org-ts-regexp "\\)?")
5383 "Regular expression matching a time stamp or time stamp range.")
5384 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5385 org-ts-regexp-both "\\)?")
5386 "Regular expression matching a time stamp or time stamp range.
5387 The time stamps may be either active or inactive.")
5389 (defvar org-emph-face nil)
5391 (defun org-do-emphasis-faces (limit)
5392 "Run through the buffer and add overlays to emphasized strings."
5393 (let (rtn a)
5394 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5395 (if (not (= (char-after (match-beginning 3))
5396 (char-after (match-beginning 4))))
5397 (progn
5398 (setq rtn t)
5399 (setq a (assoc (match-string 3) org-emphasis-alist))
5400 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5401 'face
5402 (nth 1 a))
5403 (and (nth 4 a)
5404 (org-remove-flyspell-overlays-in
5405 (match-beginning 0) (match-end 0)))
5406 (add-text-properties (match-beginning 2) (match-end 2)
5407 '(font-lock-multiline t org-emphasis t))
5408 (when org-hide-emphasis-markers
5409 (add-text-properties (match-end 4) (match-beginning 5)
5410 '(invisible org-link))
5411 (add-text-properties (match-beginning 3) (match-end 3)
5412 '(invisible org-link)))))
5413 (backward-char 1))
5414 rtn))
5416 (defun org-emphasize (&optional char)
5417 "Insert or change an emphasis, i.e. a font like bold or italic.
5418 If there is an active region, change that region to a new emphasis.
5419 If there is no region, just insert the marker characters and position
5420 the cursor between them.
5421 CHAR should be either the marker character, or the first character of the
5422 HTML tag associated with that emphasis. If CHAR is a space, the means
5423 to remove the emphasis of the selected region.
5424 If char is not given (for example in an interactive call) it
5425 will be prompted for."
5426 (interactive)
5427 (let ((eal org-emphasis-alist) e det
5428 (erc org-emphasis-regexp-components)
5429 (prompt "")
5430 (string "") beg end move tag c s)
5431 (if (org-region-active-p)
5432 (setq beg (region-beginning) end (region-end)
5433 string (buffer-substring beg end))
5434 (setq move t))
5436 (while (setq e (pop eal))
5437 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5438 c (aref tag 0))
5439 (push (cons c (string-to-char (car e))) det)
5440 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5441 (substring tag 1)))))
5442 (setq det (nreverse det))
5443 (unless char
5444 (message "%s" (concat "Emphasis marker or tag:" prompt))
5445 (setq char (read-char-exclusive)))
5446 (setq char (or (cdr (assoc char det)) char))
5447 (if (equal char ?\ )
5448 (setq s "" move nil)
5449 (unless (assoc (char-to-string char) org-emphasis-alist)
5450 (error "No such emphasis marker: \"%c\"" char))
5451 (setq s (char-to-string char)))
5452 (while (and (> (length string) 1)
5453 (equal (substring string 0 1) (substring string -1))
5454 (assoc (substring string 0 1) org-emphasis-alist))
5455 (setq string (substring string 1 -1)))
5456 (setq string (concat s string s))
5457 (if beg (delete-region beg end))
5458 (unless (or (bolp)
5459 (string-match (concat "[" (nth 0 erc) "\n]")
5460 (char-to-string (char-before (point)))))
5461 (insert " "))
5462 (unless (or (eobp)
5463 (string-match (concat "[" (nth 1 erc) "\n]")
5464 (char-to-string (char-after (point)))))
5465 (insert " ") (backward-char 1))
5466 (insert string)
5467 (and move (backward-char 1))))
5469 (defconst org-nonsticky-props
5470 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5472 (defsubst org-rear-nonsticky-at (pos)
5473 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5475 (defun org-activate-plain-links (limit)
5476 "Run through the buffer and add overlays to links."
5477 (catch 'exit
5478 (let (f)
5479 (when (re-search-forward (concat org-plain-link-re) limit t)
5480 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5481 (setq f (get-text-property (match-beginning 0) 'face))
5482 (if (or (eq f 'org-tag)
5483 (and (listp f) (memq 'org-tag f)))
5485 (add-text-properties (match-beginning 0) (match-end 0)
5486 (list 'mouse-face 'highlight
5487 'face 'org-link
5488 'keymap org-mouse-map))
5489 (org-rear-nonsticky-at (match-end 0)))
5490 t))))
5492 (defun org-activate-code (limit)
5493 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5494 (progn
5495 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5496 (remove-text-properties (match-beginning 0) (match-end 0)
5497 '(display t invisible t intangible t))
5498 t)))
5500 (defcustom org-src-fontify-natively nil
5501 "When non-nil, fontify code in code blocks."
5502 :type 'boolean
5503 :version "24.1"
5504 :group 'org-appearance
5505 :group 'org-babel)
5507 (defcustom org-allow-promoting-top-level-subtree nil
5508 "When non-nil, allow promoting a top level subtree.
5509 The leading star of the top level headline will be replaced
5510 by a #."
5511 :type 'boolean
5512 :version "24.1"
5513 :group 'org-appearance)
5515 (defun org-fontify-meta-lines-and-blocks (limit)
5516 (condition-case nil
5517 (org-fontify-meta-lines-and-blocks-1 limit)
5518 (error (message "org-mode fontification error"))))
5520 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5521 "Fontify #+ lines and blocks, in the correct ways."
5522 (let ((case-fold-search t))
5523 (if (re-search-forward
5524 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5525 limit t)
5526 (let ((beg (match-beginning 0))
5527 (block-start (match-end 0))
5528 (block-end nil)
5529 (lang (match-string 7))
5530 (beg1 (line-beginning-position 2))
5531 (dc1 (downcase (match-string 2)))
5532 (dc3 (downcase (match-string 3)))
5533 end end1 quoting block-type ovl)
5534 (cond
5535 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5536 ;; a single line of backend-specific content
5537 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5538 (remove-text-properties (match-beginning 0) (match-end 0)
5539 '(display t invisible t intangible t))
5540 (add-text-properties (match-beginning 1) (match-end 3)
5541 '(font-lock-fontified t face org-meta-line))
5542 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5543 '(font-lock-fontified t face org-block))
5544 ; for backend-specific code
5546 ((and (match-end 4) (equal dc3 "+begin"))
5547 ;; Truly a block
5548 (setq block-type (downcase (match-string 5))
5549 quoting (member block-type org-protecting-blocks))
5550 (when (re-search-forward
5551 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5552 nil t) ;; on purpose, we look further than LIMIT
5553 (setq end (min (point-max) (match-end 0))
5554 end1 (min (point-max) (1- (match-beginning 0))))
5555 (setq block-end (match-beginning 0))
5556 (when quoting
5557 (remove-text-properties beg end
5558 '(display t invisible t intangible t)))
5559 (add-text-properties
5560 beg end
5561 '(font-lock-fontified t font-lock-multiline t))
5562 (add-text-properties beg beg1 '(face org-meta-line))
5563 (add-text-properties end1 (min (point-max) (1+ end))
5564 '(face org-meta-line)) ; for end_src
5565 (cond
5566 ((and lang (not (string= lang "")) org-src-fontify-natively)
5567 (org-src-font-lock-fontify-block lang block-start block-end)
5568 ;; remove old background overlays
5569 (mapc (lambda (ov)
5570 (if (eq (overlay-get ov 'face) 'org-block-background)
5571 (delete-overlay ov)))
5572 (overlays-at (/ (+ beg1 block-end) 2)))
5573 ;; add a background overlay
5574 (setq ovl (make-overlay beg1 block-end))
5575 (overlay-put ovl 'face 'org-block-background)
5576 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5577 (quoting
5578 (add-text-properties beg1 (min (point-max) (1+ end1))
5579 '(face org-block))) ; end of source block
5580 ((not org-fontify-quote-and-verse-blocks))
5581 ((string= block-type "quote")
5582 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5583 ((string= block-type "verse")
5584 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5585 (add-text-properties beg beg1 '(face org-block-begin-line))
5586 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5587 '(face org-block-end-line))
5589 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5590 (add-text-properties
5591 beg (match-end 3)
5592 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5593 '(font-lock-fontified t invisible t)
5594 '(font-lock-fontified t face org-document-info-keyword)))
5595 (add-text-properties
5596 (match-beginning 6) (match-end 6)
5597 (if (string-equal dc1 "+title:")
5598 '(font-lock-fontified t face org-document-title)
5599 '(font-lock-fontified t face org-document-info))))
5600 ((or (equal dc1 "+results")
5601 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5602 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5603 "+call:" "+header:" "+headers:" "+name:"))
5604 (and (match-end 4) (equal dc3 "+attr")))
5605 (add-text-properties
5606 beg (match-end 0)
5607 '(font-lock-fontified t face org-meta-line))
5609 ((member dc3 '(" " ""))
5610 (add-text-properties
5611 beg (match-end 0)
5612 '(font-lock-fontified t face font-lock-comment-face)))
5613 ((not (member (char-after beg) '(?\ ?\t)))
5614 ;; just any other in-buffer setting, but not indented
5615 (add-text-properties
5616 beg (match-end 0)
5617 '(font-lock-fontified t face org-meta-line))
5619 (t nil))))))
5621 (defun org-strip-protective-commas (beg end)
5622 "Strip protective commas between BEG and END in the current buffer."
5623 (interactive "r")
5624 (save-excursion
5625 (save-match-data
5626 (goto-char beg)
5627 (let ((front-line (save-excursion
5628 (re-search-forward
5629 "[^[:space:]]" end t)
5630 (goto-char (match-beginning 0))
5631 (current-column))))
5632 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\)" end t)
5633 (goto-char (match-beginning 1))
5634 (when (= (current-column) front-line)
5635 (replace-match "" nil nil nil 1)))))))
5637 (defun org-activate-angle-links (limit)
5638 "Run through the buffer and add overlays to links."
5639 (if (re-search-forward org-angle-link-re limit t)
5640 (progn
5641 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5642 (add-text-properties (match-beginning 0) (match-end 0)
5643 (list 'mouse-face 'highlight
5644 'keymap org-mouse-map))
5645 (org-rear-nonsticky-at (match-end 0))
5646 t)))
5648 (defun org-activate-footnote-links (limit)
5649 "Run through the buffer and add overlays to footnotes."
5650 (let ((fn (org-footnote-next-reference-or-definition limit)))
5651 (when fn
5652 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5653 (org-remove-flyspell-overlays-in beg end)
5654 (add-text-properties beg end
5655 (list 'mouse-face 'highlight
5656 'keymap org-mouse-map
5657 'help-echo
5658 (if (= (point-at-bol) beg)
5659 "Footnote definition"
5660 "Footnote reference")
5661 'font-lock-fontified t
5662 'font-lock-multiline t
5663 'face 'org-footnote))))))
5665 (defun org-activate-bracket-links (limit)
5666 "Run through the buffer and add overlays to bracketed links."
5667 (if (re-search-forward org-bracket-link-regexp limit t)
5668 (let* ((help (concat "LINK: "
5669 (org-match-string-no-properties 1)))
5670 ;; FIXME: above we should remove the escapes.
5671 ;; but that requires another match, protecting match data,
5672 ;; a lot of overhead for font-lock.
5673 (ip (org-maybe-intangible
5674 (list 'invisible 'org-link
5675 'keymap org-mouse-map 'mouse-face 'highlight
5676 'font-lock-multiline t 'help-echo help)))
5677 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5678 'font-lock-multiline t 'help-echo help)))
5679 ;; We need to remove the invisible property here. Table narrowing
5680 ;; may have made some of this invisible.
5681 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5682 (remove-text-properties (match-beginning 0) (match-end 0)
5683 '(invisible nil))
5684 (if (match-end 3)
5685 (progn
5686 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5687 (org-rear-nonsticky-at (match-beginning 3))
5688 (add-text-properties (match-beginning 3) (match-end 3) vp)
5689 (org-rear-nonsticky-at (match-end 3))
5690 (add-text-properties (match-end 3) (match-end 0) ip)
5691 (org-rear-nonsticky-at (match-end 0)))
5692 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5693 (org-rear-nonsticky-at (match-beginning 1))
5694 (add-text-properties (match-beginning 1) (match-end 1) vp)
5695 (org-rear-nonsticky-at (match-end 1))
5696 (add-text-properties (match-end 1) (match-end 0) ip)
5697 (org-rear-nonsticky-at (match-end 0)))
5698 t)))
5700 (defun org-activate-dates (limit)
5701 "Run through the buffer and add overlays to dates."
5702 (if (re-search-forward org-tsr-regexp-both limit t)
5703 (progn
5704 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5705 (add-text-properties (match-beginning 0) (match-end 0)
5706 (list 'mouse-face 'highlight
5707 'keymap org-mouse-map))
5708 (org-rear-nonsticky-at (match-end 0))
5709 (when org-display-custom-times
5710 (if (match-end 3)
5711 (org-display-custom-time (match-beginning 3) (match-end 3)))
5712 (org-display-custom-time (match-beginning 1) (match-end 1)))
5713 t)))
5715 (defvar org-target-link-regexp nil
5716 "Regular expression matching radio targets in plain text.")
5717 (make-variable-buffer-local 'org-target-link-regexp)
5718 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5719 "Regular expression matching a link target.")
5720 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5721 "Regular expression matching a radio target.")
5722 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5723 "Regular expression matching any target.")
5725 (defun org-activate-target-links (limit)
5726 "Run through the buffer and add overlays to target matches."
5727 (when org-target-link-regexp
5728 (let ((case-fold-search t))
5729 (if (re-search-forward org-target-link-regexp limit t)
5730 (progn
5731 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5732 (add-text-properties (match-beginning 0) (match-end 0)
5733 (list 'mouse-face 'highlight
5734 'keymap org-mouse-map
5735 'help-echo "Radio target link"
5736 'org-linked-text t))
5737 (org-rear-nonsticky-at (match-end 0))
5738 t)))))
5740 (defun org-update-radio-target-regexp ()
5741 "Find all radio targets in this file and update the regular expression."
5742 (interactive)
5743 (when (memq 'radio org-activate-links)
5744 (setq org-target-link-regexp
5745 (org-make-target-link-regexp (org-all-targets 'radio)))
5746 (org-restart-font-lock)))
5748 (defun org-hide-wide-columns (limit)
5749 (let (s e)
5750 (setq s (text-property-any (point) (or limit (point-max))
5751 'org-cwidth t))
5752 (when s
5753 (setq e (next-single-property-change s 'org-cwidth))
5754 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5755 (goto-char e)
5756 t)))
5758 (defvar org-latex-and-specials-regexp nil
5759 "Regular expression for highlighting export special stuff.")
5760 (defvar org-match-substring-regexp)
5761 (defvar org-match-substring-with-braces-regexp)
5763 ;; This should be with the exporter code, but we also use if for font-locking
5764 (defconst org-export-html-special-string-regexps
5765 '(("\\\\-" . "&shy;")
5766 ("---\\([^-]\\)" . "&mdash;\\1")
5767 ("--\\([^-]\\)" . "&ndash;\\1")
5768 ("\\.\\.\\." . "&hellip;"))
5769 "Regular expressions for special string conversion.")
5772 (defun org-compute-latex-and-specials-regexp ()
5773 "Compute regular expression for stuff treated specially by exporters."
5774 (if (not org-highlight-latex-fragments-and-specials)
5775 (org-set-local 'org-latex-and-specials-regexp nil)
5776 (require 'org-exp)
5777 (let*
5778 ((matchers (plist-get org-format-latex-options :matchers))
5779 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5780 org-latex-regexps)))
5781 (org-export-allow-BIND nil)
5782 (options (org-combine-plists (org-default-export-plist)
5783 (org-infile-export-plist)))
5784 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5785 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5786 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5787 (org-export-html-expand (plist-get options :expand-quoted-html))
5788 (org-export-with-special-strings (plist-get options :special-strings))
5789 (re-sub
5790 (cond
5791 ((equal org-export-with-sub-superscripts '{})
5792 (list org-match-substring-with-braces-regexp))
5793 (org-export-with-sub-superscripts
5794 (list org-match-substring-regexp))))
5795 (re-latex
5796 (if org-export-with-LaTeX-fragments
5797 (mapcar (lambda (x) (nth 1 x)) latexs)))
5798 (re-macros
5799 (if org-export-with-TeX-macros
5800 (list (concat "\\\\"
5801 (regexp-opt
5802 (append
5804 (delq nil
5805 (mapcar 'car-safe
5806 (append org-entities-user
5807 org-entities)))
5808 (if (boundp 'org-latex-entities)
5809 (mapcar (lambda (x)
5810 (or (car-safe x) x))
5811 org-latex-entities)
5812 nil))
5813 'words))) ; FIXME
5815 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5816 (re-special (if org-export-with-special-strings
5817 (mapcar (lambda (x) (car x))
5818 org-export-html-special-string-regexps)))
5819 (re-rest
5820 (delq nil
5821 (list
5822 (if org-export-html-expand "@<[^>\n]+>")
5823 ))))
5824 (org-set-local
5825 'org-latex-and-specials-regexp
5826 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5827 re-rest) "\\|")))))
5829 (defun org-do-latex-and-special-faces (limit)
5830 "Run through the buffer and add overlays to links."
5831 (when org-latex-and-specials-regexp
5832 (let (rtn d)
5833 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5834 limit t))
5835 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5836 'face))
5837 '(org-code org-verbatim underline)))
5838 (progn
5839 (setq rtn t
5840 d (cond ((member (char-after (1+ (match-beginning 0)))
5841 '(?_ ?^)) 1)
5842 (t 0)))
5843 (font-lock-prepend-text-property
5844 (+ d (match-beginning 0)) (match-end 0)
5845 'face 'org-latex-and-export-specials)
5846 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5847 '(font-lock-multiline t)))))
5848 rtn)))
5850 (defun org-restart-font-lock ()
5851 "Restart `font-lock-mode', to force refontification."
5852 (when (and (boundp 'font-lock-mode) font-lock-mode)
5853 (font-lock-mode -1)
5854 (font-lock-mode 1)))
5856 (defun org-all-targets (&optional radio)
5857 "Return a list of all targets in this file.
5858 With optional argument RADIO, only find radio targets."
5859 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5860 rtn)
5861 (save-excursion
5862 (goto-char (point-min))
5863 (while (re-search-forward re nil t)
5864 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5865 rtn)))
5867 (defun org-make-target-link-regexp (targets)
5868 "Make regular expression matching all strings in TARGETS.
5869 The regular expression finds the targets also if there is a line break
5870 between words."
5871 (and targets
5872 (concat
5873 "\\<\\("
5874 (mapconcat
5875 (lambda (x)
5876 (setq x (regexp-quote x))
5877 (while (string-match " +" x)
5878 (setq x (replace-match "\\s-+" t t x)))
5880 targets
5881 "\\|")
5882 "\\)\\>")))
5884 (defun org-activate-tags (limit)
5885 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5886 (progn
5887 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5888 (add-text-properties (match-beginning 1) (match-end 1)
5889 (list 'mouse-face 'highlight
5890 'keymap org-mouse-map))
5891 (org-rear-nonsticky-at (match-end 1))
5892 t)))
5894 (defun org-outline-level ()
5895 "Compute the outline level of the heading at point.
5896 If this is called at a normal headline, the level is the number of stars.
5897 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5898 (save-excursion
5899 (if (not (condition-case nil
5900 (org-back-to-heading t)
5901 (error nil)))
5903 (looking-at org-outline-regexp)
5904 (1- (- (match-end 0) (match-beginning 0))))))
5906 (defvar org-font-lock-keywords nil)
5908 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5909 "Regular expression matching a property line.")
5911 (defvar org-font-lock-hook nil
5912 "Functions to be called for special font lock stuff.")
5914 (defvar org-font-lock-set-keywords-hook nil
5915 "Functions that can manipulate `org-font-lock-extra-keywords'.
5916 This is called after `org-font-lock-extra-keywords' is defined, but before
5917 it is installed to be used by font lock. This can be useful if something
5918 needs to be inserted at a specific position in the font-lock sequence.")
5920 (defun org-font-lock-hook (limit)
5921 (run-hook-with-args 'org-font-lock-hook limit))
5923 (defun org-set-font-lock-defaults ()
5924 (let* ((em org-fontify-emphasized-text)
5925 (lk org-activate-links)
5926 (org-font-lock-extra-keywords
5927 (list
5928 ;; Call the hook
5929 '(org-font-lock-hook)
5930 ;; Headlines
5931 `(,(if org-fontify-whole-heading-line
5932 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5933 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5934 (1 (org-get-level-face 1))
5935 (2 (org-get-level-face 2))
5936 (3 (org-get-level-face 3)))
5937 ;; Table lines
5938 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5939 (1 'org-table t))
5940 ;; Table internals
5941 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5942 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5943 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5944 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5945 ;; Drawers
5946 (list org-drawer-regexp '(0 'org-special-keyword t))
5947 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5948 ;; Properties
5949 (list org-property-re
5950 '(1 'org-special-keyword t)
5951 '(3 'org-property-value t))
5952 ;; Links
5953 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5954 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5955 (if (memq 'plain lk) '(org-activate-plain-links))
5956 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5957 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5958 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5959 (if (memq 'footnote lk) '(org-activate-footnote-links))
5960 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5961 '(org-hide-wide-columns (0 nil append))
5962 ;; TODO keyword
5963 (list (format org-heading-keyword-regexp-format
5964 org-todo-regexp)
5965 '(2 (org-get-todo-face 2) t))
5966 ;; DONE
5967 (if org-fontify-done-headline
5968 (list (format org-heading-keyword-regexp-format
5969 (concat
5970 "\\(?:"
5971 (mapconcat 'regexp-quote org-done-keywords "\\|")
5972 "\\)"))
5973 '(2 'org-headline-done t))
5974 nil)
5975 ;; Priorities
5976 '(org-font-lock-add-priority-faces)
5977 ;; Tags
5978 '(org-font-lock-add-tag-faces)
5979 ;; Special keywords
5980 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5981 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5982 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5983 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5984 ;; Emphasis
5985 (if em
5986 (if (featurep 'xemacs)
5987 '(org-do-emphasis-faces (0 nil append))
5988 '(org-do-emphasis-faces)))
5989 ;; Checkboxes
5990 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5991 1 'org-checkbox prepend)
5992 (if (cdr (assq 'checkbox org-list-automatic-rules))
5993 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5994 (0 (org-get-checkbox-statistics-face) t)))
5995 ;; Description list items
5996 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5997 1 'org-list-dt prepend)
5998 ;; ARCHIVEd headings
5999 (list (concat
6000 org-outline-regexp-bol
6001 "\\(.*:" org-archive-tag ":.*\\)")
6002 '(1 'org-archived prepend))
6003 ;; Specials
6004 '(org-do-latex-and-special-faces)
6005 '(org-fontify-entities)
6006 '(org-raise-scripts)
6007 ;; Code
6008 '(org-activate-code (1 'org-code t))
6009 ;; COMMENT
6010 (list (format org-heading-keyword-regexp-format
6011 (concat "\\("
6012 org-comment-string "\\|" org-quote-string
6013 "\\)"))
6014 '(2 'org-special-keyword t))
6015 ;; Blocks and meta lines
6016 '(org-fontify-meta-lines-and-blocks)
6018 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6019 (run-hooks 'org-font-lock-set-keywords-hook)
6020 ;; Now set the full font-lock-keywords
6021 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6022 (org-set-local 'font-lock-defaults
6023 '(org-font-lock-keywords t nil nil backward-paragraph))
6024 (kill-local-variable 'font-lock-keywords) nil))
6026 (defun org-toggle-pretty-entities ()
6027 "Toggle the composition display of entities as UTF8 characters."
6028 (interactive)
6029 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6030 (org-restart-font-lock)
6031 (if org-pretty-entities
6032 (message "Entities are displayed as UTF8 characters")
6033 (save-restriction
6034 (widen)
6035 (org-decompose-region (point-min) (point-max))
6036 (message "Entities are displayed plain"))))
6038 (defvar org-custom-properties-overlays nil
6039 "List of overlays used for custom properties.")
6040 (make-variable-buffer-local 'org-custom-properties-overlays)
6042 (defun org-toggle-custom-properties-visibility ()
6043 "Display or hide properties in `org-custom-properties'."
6044 (interactive)
6045 (if org-custom-properties-overlays
6046 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6047 (setq org-custom-properties-overlays nil))
6048 (unless (not org-custom-properties)
6049 (save-excursion
6050 (save-restriction
6051 (widen)
6052 (goto-char (point-min))
6053 (while (re-search-forward org-property-re nil t)
6054 (mapc (lambda(p)
6055 (when (equal p (substring (match-string 1) 1 -1))
6056 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6057 (overlay-put o 'invisible t)
6058 (overlay-put o 'org-custom-property t)
6059 (push o org-custom-properties-overlays))))
6060 org-custom-properties)))))))
6062 (defun org-fontify-entities (limit)
6063 "Find an entity to fontify."
6064 (let (ee)
6065 (when org-pretty-entities
6066 (catch 'match
6067 (while (re-search-forward
6068 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6069 limit t)
6070 (if (and (not (org-in-indented-comment-line))
6071 (setq ee (org-entity-get (match-string 1)))
6072 (= (length (nth 6 ee)) 1))
6073 (let*
6074 ((end (if (equal (match-string 2) "{}")
6075 (match-end 2)
6076 (match-end 1))))
6077 (add-text-properties
6078 (match-beginning 0) end
6079 (list 'font-lock-fontified t))
6080 (compose-region (match-beginning 0) end
6081 (nth 6 ee) nil)
6082 (backward-char 1)
6083 (throw 'match t))))
6084 nil))))
6086 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6087 "Fontify string S like in Org-mode."
6088 (with-temp-buffer
6089 (insert s)
6090 (let ((org-odd-levels-only odd-levels))
6091 (org-mode)
6092 (font-lock-fontify-buffer)
6093 (buffer-string))))
6095 (defvar org-m nil)
6096 (defvar org-l nil)
6097 (defvar org-f nil)
6098 (defun org-get-level-face (n)
6099 "Get the right face for match N in font-lock matching of headlines."
6100 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6101 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6102 (if org-cycle-level-faces
6103 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6104 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6105 (cond
6106 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6107 ((eq n 2) org-f)
6108 (t (if org-level-color-stars-only nil org-f))))
6111 (defun org-get-todo-face (kwd)
6112 "Get the right face for a TODO keyword KWD.
6113 If KWD is a number, get the corresponding match group."
6114 (if (numberp kwd) (setq kwd (match-string kwd)))
6115 (or (org-face-from-face-or-color
6116 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6117 (and (member kwd org-done-keywords) 'org-done)
6118 'org-todo))
6120 (defun org-face-from-face-or-color (context inherit face-or-color)
6121 "Create a face list that inherits INHERIT, but sets the foreground color.
6122 When FACE-OR-COLOR is not a string, just return it."
6123 (if (stringp face-or-color)
6124 (list :inherit inherit
6125 (cdr (assoc context org-faces-easy-properties))
6126 face-or-color)
6127 face-or-color))
6129 (defun org-font-lock-add-tag-faces (limit)
6130 "Add the special tag faces."
6131 (when (and org-tag-faces org-tags-special-faces-re)
6132 (while (re-search-forward org-tags-special-faces-re limit t)
6133 (add-text-properties (match-beginning 1) (match-end 1)
6134 (list 'face (org-get-tag-face 1)
6135 'font-lock-fontified t))
6136 (backward-char 1))))
6138 (defun org-font-lock-add-priority-faces (limit)
6139 "Add the special priority faces."
6140 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6141 (when (save-match-data (org-at-heading-p))
6142 (add-text-properties
6143 (match-beginning 0) (match-end 0)
6144 (list 'face (or (org-face-from-face-or-color
6145 'priority 'org-special-keyword
6146 (cdr (assoc (char-after (match-beginning 1))
6147 org-priority-faces)))
6148 'org-special-keyword)
6149 'font-lock-fontified t)))))
6151 (defun org-get-tag-face (kwd)
6152 "Get the right face for a TODO keyword KWD.
6153 If KWD is a number, get the corresponding match group."
6154 (if (numberp kwd) (setq kwd (match-string kwd)))
6155 (or (org-face-from-face-or-color
6156 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6157 'org-tag))
6159 (defun org-unfontify-region (beg end &optional maybe_loudly)
6160 "Remove fontification and activation overlays from links."
6161 (font-lock-default-unfontify-region beg end)
6162 (let* ((buffer-undo-list t)
6163 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6164 (inhibit-modification-hooks t)
6165 deactivate-mark buffer-file-name buffer-file-truename)
6166 (org-decompose-region beg end)
6167 (remove-text-properties beg end
6168 '(mouse-face t keymap t org-linked-text t
6169 invisible t intangible t
6170 org-no-flyspell t org-emphasis t))
6171 (org-remove-font-lock-display-properties beg end)))
6173 (defconst org-script-display '(((raise -0.3) (height 0.7))
6174 ((raise 0.3) (height 0.7))
6175 ((raise -0.5))
6176 ((raise 0.5)))
6177 "Display properties for showing superscripts and subscripts.")
6179 (defun org-remove-font-lock-display-properties (beg end)
6180 "Remove specific display properties that have been added by font lock.
6181 The will remove the raise properties that are used to show superscripts
6182 and subscripts."
6183 (let (next prop)
6184 (while (< beg end)
6185 (setq next (next-single-property-change beg 'display nil end)
6186 prop (get-text-property beg 'display))
6187 (if (member prop org-script-display)
6188 (put-text-property beg next 'display nil))
6189 (setq beg next))))
6191 (defun org-raise-scripts (limit)
6192 "Add raise properties to sub/superscripts."
6193 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6194 (if (re-search-forward
6195 (if (eq org-use-sub-superscripts t)
6196 org-match-substring-regexp
6197 org-match-substring-with-braces-regexp)
6198 limit t)
6199 (let* ((pos (point)) table-p comment-p
6200 (mpos (match-beginning 3))
6201 (emph-p (get-text-property mpos 'org-emphasis))
6202 (link-p (get-text-property mpos 'mouse-face))
6203 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6204 (goto-char (point-at-bol))
6205 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6206 comment-p (org-looking-at-p "[ \t]*#"))
6207 (goto-char pos)
6208 ;; FIXME: Should we go back one character here, for a_b^c
6209 ;; (goto-char (1- pos)) ;????????????????????
6210 (if (or comment-p emph-p link-p keyw-p)
6212 (put-text-property (match-beginning 3) (match-end 0)
6213 'display
6214 (if (equal (char-after (match-beginning 2)) ?^)
6215 (nth (if table-p 3 1) org-script-display)
6216 (nth (if table-p 2 0) org-script-display)))
6217 (add-text-properties (match-beginning 2) (match-end 2)
6218 (list 'invisible t
6219 'org-dwidth t 'org-dwidth-n 1))
6220 (if (and (eq (char-after (match-beginning 3)) ?{)
6221 (eq (char-before (match-end 3)) ?}))
6222 (progn
6223 (add-text-properties
6224 (match-beginning 3) (1+ (match-beginning 3))
6225 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6226 (add-text-properties
6227 (1- (match-end 3)) (match-end 3)
6228 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6229 t)))))
6231 ;;;; Visibility cycling, including org-goto and indirect buffer
6233 ;;; Cycling
6235 (defvar org-cycle-global-status nil)
6236 (make-variable-buffer-local 'org-cycle-global-status)
6237 (defvar org-cycle-subtree-status nil)
6238 (make-variable-buffer-local 'org-cycle-subtree-status)
6240 ;;;###autoload
6242 (defvar org-inlinetask-min-level)
6244 (defun org-cycle (&optional arg)
6245 "TAB-action and visibility cycling for Org-mode.
6247 This is the command invoked in Org-mode by the TAB key. Its main purpose
6248 is outline visibility cycling, but it also invokes other actions
6249 in special contexts.
6251 - When this function is called with a prefix argument, rotate the entire
6252 buffer through 3 states (global cycling)
6253 1. OVERVIEW: Show only top-level headlines.
6254 2. CONTENTS: Show all headlines of all levels, but no body text.
6255 3. SHOW ALL: Show everything.
6256 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6257 determined by the variable `org-startup-folded', and by any VISIBILITY
6258 properties in the buffer.
6259 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6260 including any drawers.
6262 - When inside a table, re-align the table and move to the next field.
6264 - When point is at the beginning of a headline, rotate the subtree started
6265 by this line through 3 different states (local cycling)
6266 1. FOLDED: Only the main headline is shown.
6267 2. CHILDREN: The main headline and the direct children are shown.
6268 From this state, you can move to one of the children
6269 and zoom in further.
6270 3. SUBTREE: Show the entire subtree, including body text.
6271 If there is no subtree, switch directly from CHILDREN to FOLDED.
6273 - When point is at the beginning of an empty headline and the variable
6274 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6275 of the headline by demoting and promoting it to likely levels. This
6276 speeds up creation document structure by pressing TAB once or several
6277 times right after creating a new headline.
6279 - When there is a numeric prefix, go up to a heading with level ARG, do
6280 a `show-subtree' and return to the previous cursor position. If ARG
6281 is negative, go up that many levels.
6283 - When point is not at the beginning of a headline, execute the global
6284 binding for TAB, which is re-indenting the line. See the option
6285 `org-cycle-emulate-tab' for details.
6287 - Special case: if point is at the beginning of the buffer and there is
6288 no headline in line 1, this function will act as if called with prefix arg
6289 (C-u TAB, same as S-TAB) also when called without prefix arg.
6290 But only if also the variable `org-cycle-global-at-bob' is t."
6291 (interactive "P")
6292 (org-load-modules-maybe)
6293 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6294 (and org-cycle-level-after-item/entry-creation
6295 (or (org-cycle-level)
6296 (org-cycle-item-indentation))))
6297 (let* ((limit-level
6298 (or org-cycle-max-level
6299 (and (boundp 'org-inlinetask-min-level)
6300 org-inlinetask-min-level
6301 (1- org-inlinetask-min-level))))
6302 (nstars (and limit-level
6303 (if org-odd-levels-only
6304 (and limit-level (1- (* limit-level 2)))
6305 limit-level)))
6306 (org-outline-regexp
6307 (if (not (derived-mode-p 'org-mode))
6308 outline-regexp
6309 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6310 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6311 (not (looking-at org-outline-regexp))))
6312 (org-cycle-hook
6313 (if bob-special
6314 (delq 'org-optimize-window-after-visibility-change
6315 (copy-sequence org-cycle-hook))
6316 org-cycle-hook))
6317 (pos (point)))
6319 (if (or bob-special (equal arg '(4)))
6320 ;; special case: use global cycling
6321 (setq arg t))
6323 (cond
6325 ((equal arg '(16))
6326 (setq last-command 'dummy)
6327 (org-set-startup-visibility)
6328 (message "Startup visibility, plus VISIBILITY properties"))
6330 ((equal arg '(64))
6331 (show-all)
6332 (message "Entire buffer visible, including drawers"))
6334 ;; Table: enter it or move to the next field.
6335 ((org-at-table-p 'any)
6336 (if (org-at-table.el-p)
6337 (message "Use C-c ' to edit table.el tables")
6338 (if arg (org-table-edit-field t)
6339 (org-table-justify-field-maybe)
6340 (call-interactively 'org-table-next-field))))
6342 ((run-hook-with-args-until-success
6343 'org-tab-after-check-for-table-hook))
6345 ;; Global cycling: delegate to `org-cycle-internal-global'.
6346 ((eq arg t) (org-cycle-internal-global))
6348 ;; Drawers: delegate to `org-flag-drawer'.
6349 ((and org-drawers org-drawer-regexp
6350 (save-excursion
6351 (beginning-of-line 1)
6352 (looking-at org-drawer-regexp)))
6353 (org-flag-drawer ; toggle block visibility
6354 (not (get-char-property (match-end 0) 'invisible))))
6356 ;; Show-subtree, ARG levels up from here.
6357 ((integerp arg)
6358 (save-excursion
6359 (org-back-to-heading)
6360 (outline-up-heading (if (< arg 0) (- arg)
6361 (- (funcall outline-level) arg)))
6362 (org-show-subtree)))
6364 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6365 ((and (featurep 'org-inlinetask)
6366 (org-inlinetask-at-task-p)
6367 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6368 (org-inlinetask-toggle-visibility))
6370 ((org-try-cdlatex-tab))
6372 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6373 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6374 (save-excursion (beginning-of-line 1)
6375 (looking-at org-outline-regexp)))
6376 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6377 (org-cycle-internal-local))
6379 ;; From there: TAB emulation and template completion.
6380 (buffer-read-only (org-back-to-heading))
6382 ((run-hook-with-args-until-success
6383 'org-tab-after-check-for-cycling-hook))
6385 ((org-try-structure-completion))
6387 ((run-hook-with-args-until-success
6388 'org-tab-before-tab-emulation-hook))
6390 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6391 (or (not (bolp))
6392 (not (looking-at org-outline-regexp))))
6393 (call-interactively (global-key-binding "\t")))
6395 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6396 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6397 (or (and (eq org-cycle-emulate-tab 'white)
6398 (= (match-end 0) (point-at-eol)))
6399 (and (eq org-cycle-emulate-tab 'whitestart)
6400 (>= (match-end 0) pos))))
6402 (eq org-cycle-emulate-tab t))
6403 (call-interactively (global-key-binding "\t")))
6405 (t (save-excursion
6406 (org-back-to-heading)
6407 (org-cycle)))))))
6409 (defun org-cycle-internal-global ()
6410 "Do the global cycling action."
6411 ;; Hack to avoid display of messages for .org attachments in Gnus
6412 (let ((ga (string-match "\\*fontification" (buffer-name))))
6413 (cond
6414 ((and (eq last-command this-command)
6415 (eq org-cycle-global-status 'overview))
6416 ;; We just created the overview - now do table of contents
6417 ;; This can be slow in very large buffers, so indicate action
6418 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6419 (unless ga (message "CONTENTS..."))
6420 (org-content)
6421 (unless ga (message "CONTENTS...done"))
6422 (setq org-cycle-global-status 'contents)
6423 (run-hook-with-args 'org-cycle-hook 'contents))
6425 ((and (eq last-command this-command)
6426 (eq org-cycle-global-status 'contents))
6427 ;; We just showed the table of contents - now show everything
6428 (run-hook-with-args 'org-pre-cycle-hook 'all)
6429 (show-all)
6430 (unless ga (message "SHOW ALL"))
6431 (setq org-cycle-global-status 'all)
6432 (run-hook-with-args 'org-cycle-hook 'all))
6435 ;; Default action: go to overview
6436 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6437 (org-overview)
6438 (unless ga (message "OVERVIEW"))
6439 (setq org-cycle-global-status 'overview)
6440 (run-hook-with-args 'org-cycle-hook 'overview)))))
6442 (defun org-cycle-internal-local ()
6443 "Do the local cycling action."
6444 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6445 ;; First, determine end of headline (EOH), end of subtree or item
6446 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6447 (save-excursion
6448 (if (org-at-item-p)
6449 (progn
6450 (beginning-of-line)
6451 (setq struct (org-list-struct))
6452 (setq eoh (point-at-eol))
6453 (setq eos (org-list-get-item-end-before-blank (point) struct))
6454 (setq has-children (org-list-has-child-p (point) struct)))
6455 (org-back-to-heading)
6456 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6457 (setq eos (save-excursion
6458 (org-end-of-subtree t)
6459 (unless (eobp)
6460 (skip-chars-forward " \t\n"))
6461 (if (eobp) (point) (1- (point)))))
6462 (setq has-children
6463 (or (save-excursion
6464 (let ((level (funcall outline-level)))
6465 (outline-next-heading)
6466 (and (org-at-heading-p t)
6467 (> (funcall outline-level) level))))
6468 (save-excursion
6469 (org-list-search-forward (org-item-beginning-re) eos t)))))
6470 ;; Determine end invisible part of buffer (EOL)
6471 (beginning-of-line 2)
6472 ;; XEmacs doesn't have `next-single-char-property-change'
6473 (if (featurep 'xemacs)
6474 (while (and (not (eobp)) ;; this is like `next-line'
6475 (get-char-property (1- (point)) 'invisible))
6476 (beginning-of-line 2))
6477 (while (and (not (eobp)) ;; this is like `next-line'
6478 (get-char-property (1- (point)) 'invisible))
6479 (goto-char (next-single-char-property-change (point) 'invisible))
6480 (and (eolp) (beginning-of-line 2))))
6481 (setq eol (point)))
6482 ;; Find out what to do next and set `this-command'
6483 (cond
6484 ((= eos eoh)
6485 ;; Nothing is hidden behind this heading
6486 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6487 (message "EMPTY ENTRY")
6488 (setq org-cycle-subtree-status nil)
6489 (save-excursion
6490 (goto-char eos)
6491 (outline-next-heading)
6492 (if (outline-invisible-p) (org-flag-heading nil))))
6493 ((and (or (>= eol eos)
6494 (not (string-match "\\S-" (buffer-substring eol eos))))
6495 (or has-children
6496 (not (setq children-skipped
6497 org-cycle-skip-children-state-if-no-children))))
6498 ;; Entire subtree is hidden in one line: children view
6499 (run-hook-with-args 'org-pre-cycle-hook 'children)
6500 (if (org-at-item-p)
6501 (org-list-set-item-visibility (point-at-bol) struct 'children)
6502 (org-show-entry)
6503 (org-with-limited-levels (show-children))
6504 ;; FIXME: This slows down the func way too much.
6505 ;; How keep drawers hidden in subtree anyway?
6506 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6507 ;; (org-cycle-hide-drawers 'subtree))
6509 ;; Fold every list in subtree to top-level items.
6510 (when (eq org-cycle-include-plain-lists 'integrate)
6511 (save-excursion
6512 (org-back-to-heading)
6513 (while (org-list-search-forward (org-item-beginning-re) eos t)
6514 (beginning-of-line 1)
6515 (let* ((struct (org-list-struct))
6516 (prevs (org-list-prevs-alist struct))
6517 (end (org-list-get-bottom-point struct)))
6518 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6519 (org-list-get-all-items (point) struct prevs))
6520 (goto-char end))))))
6521 (message "CHILDREN")
6522 (save-excursion
6523 (goto-char eos)
6524 (outline-next-heading)
6525 (if (outline-invisible-p) (org-flag-heading nil)))
6526 (setq org-cycle-subtree-status 'children)
6527 (run-hook-with-args 'org-cycle-hook 'children))
6528 ((or children-skipped
6529 (and (eq last-command this-command)
6530 (eq org-cycle-subtree-status 'children)))
6531 ;; We just showed the children, or no children are there,
6532 ;; now show everything.
6533 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6534 (outline-flag-region eoh eos nil)
6535 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6536 (setq org-cycle-subtree-status 'subtree)
6537 (run-hook-with-args 'org-cycle-hook 'subtree))
6539 ;; Default action: hide the subtree.
6540 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6541 (outline-flag-region eoh eos t)
6542 (message "FOLDED")
6543 (setq org-cycle-subtree-status 'folded)
6544 (run-hook-with-args 'org-cycle-hook 'folded)))))
6546 ;;;###autoload
6547 (defun org-global-cycle (&optional arg)
6548 "Cycle the global visibility. For details see `org-cycle'.
6549 With \\[universal-argument] prefix arg, switch to startup visibility.
6550 With a numeric prefix, show all headlines up to that level."
6551 (interactive "P")
6552 (let ((org-cycle-include-plain-lists
6553 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6554 (cond
6555 ((integerp arg)
6556 (show-all)
6557 (hide-sublevels arg)
6558 (setq org-cycle-global-status 'contents))
6559 ((equal arg '(4))
6560 (org-set-startup-visibility)
6561 (message "Startup visibility, plus VISIBILITY properties."))
6563 (org-cycle '(4))))))
6565 (defun org-set-startup-visibility ()
6566 "Set the visibility required by startup options and properties."
6567 (cond
6568 ((eq org-startup-folded t)
6569 (org-cycle '(4)))
6570 ((eq org-startup-folded 'content)
6571 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6572 (org-cycle '(4)) (org-cycle '(4)))))
6573 (unless (eq org-startup-folded 'showeverything)
6574 (if org-hide-block-startup (org-hide-block-all))
6575 (org-set-visibility-according-to-property 'no-cleanup)
6576 (org-cycle-hide-archived-subtrees 'all)
6577 (org-cycle-hide-drawers 'all)
6578 (org-cycle-show-empty-lines t)))
6580 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6581 "Switch subtree visibilities according to :VISIBILITY: property."
6582 (interactive)
6583 (let (org-show-entry-below state)
6584 (save-excursion
6585 (goto-char (point-min))
6586 (while (re-search-forward
6587 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6588 nil t)
6589 (setq state (match-string 1))
6590 (save-excursion
6591 (org-back-to-heading t)
6592 (hide-subtree)
6593 (org-reveal)
6594 (cond
6595 ((equal state '("fold" "folded"))
6596 (hide-subtree))
6597 ((equal state "children")
6598 (org-show-hidden-entry)
6599 (show-children))
6600 ((equal state "content")
6601 (save-excursion
6602 (save-restriction
6603 (org-narrow-to-subtree)
6604 (org-content))))
6605 ((member state '("all" "showall"))
6606 (show-subtree)))))
6607 (unless no-cleanup
6608 (org-cycle-hide-archived-subtrees 'all)
6609 (org-cycle-hide-drawers 'all)
6610 (org-cycle-show-empty-lines 'all)))))
6612 ;; This function uses outline-regexp instead of the more fundamental
6613 ;; org-outline-regexp so that org-cycle-global works outside of Org
6614 ;; buffers, where outline-regexp is needed.
6615 (defun org-overview ()
6616 "Switch to overview mode, showing only top-level headlines.
6617 Really, this shows all headlines with level equal or greater than the level
6618 of the first headline in the buffer. This is important, because if the
6619 first headline is not level one, then (hide-sublevels 1) gives confusing
6620 results."
6621 (interactive)
6622 (let ((level (save-excursion
6623 (goto-char (point-min))
6624 (if (re-search-forward (concat "^" outline-regexp) nil t)
6625 (progn
6626 (goto-char (match-beginning 0))
6627 (funcall outline-level))))))
6628 (and level (hide-sublevels level))))
6630 (defun org-content (&optional arg)
6631 "Show all headlines in the buffer, like a table of contents.
6632 With numerical argument N, show content up to level N."
6633 (interactive "P")
6634 (save-excursion
6635 ;; Visit all headings and show their offspring
6636 (and (integerp arg) (org-overview))
6637 (goto-char (point-max))
6638 (catch 'exit
6639 (while (and (progn (condition-case nil
6640 (outline-previous-visible-heading 1)
6641 (error (goto-char (point-min))))
6643 (looking-at org-outline-regexp))
6644 (if (integerp arg)
6645 (show-children (1- arg))
6646 (show-branches))
6647 (if (bobp) (throw 'exit nil))))))
6650 (defun org-optimize-window-after-visibility-change (state)
6651 "Adjust the window after a change in outline visibility.
6652 This function is the default value of the hook `org-cycle-hook'."
6653 (when (get-buffer-window (current-buffer))
6654 (cond
6655 ((eq state 'content) nil)
6656 ((eq state 'all) nil)
6657 ((eq state 'folded) nil)
6658 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6659 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6661 (defun org-remove-empty-overlays-at (pos)
6662 "Remove outline overlays that do not contain non-white stuff."
6663 (mapc
6664 (lambda (o)
6665 (and (eq 'outline (overlay-get o 'invisible))
6666 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6667 (overlay-end o))))
6668 (delete-overlay o)))
6669 (overlays-at pos)))
6671 (defun org-clean-visibility-after-subtree-move ()
6672 "Fix visibility issues after moving a subtree."
6673 ;; First, find a reasonable region to look at:
6674 ;; Start two siblings above, end three below
6675 (let* ((beg (save-excursion
6676 (and (org-get-last-sibling)
6677 (org-get-last-sibling))
6678 (point)))
6679 (end (save-excursion
6680 (and (org-get-next-sibling)
6681 (org-get-next-sibling)
6682 (org-get-next-sibling))
6683 (if (org-at-heading-p)
6684 (point-at-eol)
6685 (point))))
6686 (level (looking-at "\\*+"))
6687 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6688 (save-excursion
6689 (save-restriction
6690 (narrow-to-region beg end)
6691 (when re
6692 ;; Properly fold already folded siblings
6693 (goto-char (point-min))
6694 (while (re-search-forward re nil t)
6695 (if (and (not (outline-invisible-p))
6696 (save-excursion
6697 (goto-char (point-at-eol)) (outline-invisible-p)))
6698 (hide-entry))))
6699 (org-cycle-show-empty-lines 'overview)
6700 (org-cycle-hide-drawers 'overview)))))
6702 (defun org-cycle-show-empty-lines (state)
6703 "Show empty lines above all visible headlines.
6704 The region to be covered depends on STATE when called through
6705 `org-cycle-hook'. Lisp program can use t for STATE to get the
6706 entire buffer covered. Note that an empty line is only shown if there
6707 are at least `org-cycle-separator-lines' empty lines before the headline."
6708 (when (not (= org-cycle-separator-lines 0))
6709 (save-excursion
6710 (let* ((n (abs org-cycle-separator-lines))
6711 (re (cond
6712 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6713 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6714 (t (let ((ns (number-to-string (- n 2))))
6715 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6716 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6717 beg end b e)
6718 (cond
6719 ((memq state '(overview contents t))
6720 (setq beg (point-min) end (point-max)))
6721 ((memq state '(children folded))
6722 (setq beg (point) end (progn (org-end-of-subtree t t)
6723 (beginning-of-line 2)
6724 (point)))))
6725 (when beg
6726 (goto-char beg)
6727 (while (re-search-forward re end t)
6728 (unless (get-char-property (match-end 1) 'invisible)
6729 (setq e (match-end 1))
6730 (if (< org-cycle-separator-lines 0)
6731 (setq b (save-excursion
6732 (goto-char (match-beginning 0))
6733 (org-back-over-empty-lines)
6734 (if (save-excursion
6735 (goto-char (max (point-min) (1- (point))))
6736 (org-at-heading-p))
6737 (1- (point))
6738 (point))))
6739 (setq b (match-beginning 1)))
6740 (outline-flag-region b e nil)))))))
6741 ;; Never hide empty lines at the end of the file.
6742 (save-excursion
6743 (goto-char (point-max))
6744 (outline-previous-heading)
6745 (outline-end-of-heading)
6746 (if (and (looking-at "[ \t\n]+")
6747 (= (match-end 0) (point-max)))
6748 (outline-flag-region (point) (match-end 0) nil))))
6750 (defun org-show-empty-lines-in-parent ()
6751 "Move to the parent and re-show empty lines before visible headlines."
6752 (save-excursion
6753 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6754 (org-cycle-show-empty-lines context))))
6756 (defun org-files-list ()
6757 "Return `org-agenda-files' list, plus all open org-mode files.
6758 This is useful for operations that need to scan all of a user's
6759 open and agenda-wise Org files."
6760 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6761 (dolist (buf (buffer-list))
6762 (with-current-buffer buf
6763 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6764 (let ((file (expand-file-name (buffer-file-name))))
6765 (unless (member file files)
6766 (push file files))))))
6767 files))
6769 (defsubst org-entry-beginning-position ()
6770 "Return the beginning position of the current entry."
6771 (save-excursion (outline-back-to-heading t) (point)))
6773 (defsubst org-entry-end-position ()
6774 "Return the end position of the current entry."
6775 (save-excursion (outline-next-heading) (point)))
6777 (defun org-cycle-hide-drawers (state)
6778 "Re-hide all drawers after a visibility state change."
6779 (when (and (derived-mode-p 'org-mode)
6780 (not (memq state '(overview folded contents))))
6781 (save-excursion
6782 (let* ((globalp (memq state '(contents all)))
6783 (beg (if globalp (point-min) (point)))
6784 (end (if globalp (point-max)
6785 (if (eq state 'children)
6786 (save-excursion (outline-next-heading) (point))
6787 (org-end-of-subtree t)))))
6788 (goto-char beg)
6789 (while (re-search-forward org-drawer-regexp end t)
6790 (org-flag-drawer t))))))
6792 (defun org-cycle-hide-inline-tasks (state)
6793 "Re-hide inline task when switching to 'contents visibility state."
6794 (when (and (eq state 'contents)
6795 (boundp 'org-inlinetask-min-level)
6796 org-inlinetask-min-level)
6797 (hide-sublevels (1- org-inlinetask-min-level))))
6799 (defun org-flag-drawer (flag)
6800 "When FLAG is non-nil, hide the drawer we are within.
6801 Otherwise make it visible."
6802 (save-excursion
6803 (beginning-of-line 1)
6804 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6805 (let ((b (match-end 0)))
6806 (if (re-search-forward
6807 "^[ \t]*:END:"
6808 (save-excursion (outline-next-heading) (point)) t)
6809 (outline-flag-region b (point-at-eol) flag)
6810 (error ":END: line missing at position %s" b))))))
6812 (defun org-subtree-end-visible-p ()
6813 "Is the end of the current subtree visible?"
6814 (pos-visible-in-window-p
6815 (save-excursion (org-end-of-subtree t) (point))))
6817 (defun org-first-headline-recenter (&optional N)
6818 "Move cursor to the first headline and recenter the headline.
6819 Optional argument N means put the headline into the Nth line of the window."
6820 (goto-char (point-min))
6821 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6822 (beginning-of-line)
6823 (recenter (prefix-numeric-value N))))
6825 ;;; Saving and restoring visibility
6827 (defun org-outline-overlay-data (&optional use-markers)
6828 "Return a list of the locations of all outline overlays.
6829 These are overlays with the `invisible' property value `outline'.
6830 The return value is a list of cons cells, with start and stop
6831 positions for each overlay.
6832 If USE-MARKERS is set, return the positions as markers."
6833 (let (beg end)
6834 (save-excursion
6835 (save-restriction
6836 (widen)
6837 (delq nil
6838 (mapcar (lambda (o)
6839 (when (eq (overlay-get o 'invisible) 'outline)
6840 (setq beg (overlay-start o)
6841 end (overlay-end o))
6842 (and beg end (> end beg)
6843 (if use-markers
6844 (cons (move-marker (make-marker) beg)
6845 (move-marker (make-marker) end))
6846 (cons beg end)))))
6847 (overlays-in (point-min) (point-max))))))))
6849 (defun org-set-outline-overlay-data (data)
6850 "Create visibility overlays for all positions in DATA.
6851 DATA should have been made by `org-outline-overlay-data'."
6852 (let (o)
6853 (save-excursion
6854 (save-restriction
6855 (widen)
6856 (show-all)
6857 (mapc (lambda (c)
6858 (outline-flag-region (car c) (cdr c) t))
6859 data)))))
6861 ;;; Folding of blocks
6863 (defvar org-hide-block-overlays nil
6864 "Overlays hiding blocks.")
6865 (make-variable-buffer-local 'org-hide-block-overlays)
6867 (defun org-block-map (function &optional start end)
6868 "Call FUNCTION at the head of all source blocks in the current buffer.
6869 Optional arguments START and END can be used to limit the range."
6870 (let ((start (or start (point-min)))
6871 (end (or end (point-max))))
6872 (save-excursion
6873 (goto-char start)
6874 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6875 (save-excursion
6876 (save-match-data
6877 (goto-char (match-beginning 0))
6878 (funcall function)))))))
6880 (defun org-hide-block-toggle-all ()
6881 "Toggle the visibility of all blocks in the current buffer."
6882 (org-block-map #'org-hide-block-toggle))
6884 (defun org-hide-block-all ()
6885 "Fold all blocks in the current buffer."
6886 (interactive)
6887 (org-show-block-all)
6888 (org-block-map #'org-hide-block-toggle-maybe))
6890 (defun org-show-block-all ()
6891 "Unfold all blocks in the current buffer."
6892 (interactive)
6893 (mapc 'delete-overlay org-hide-block-overlays)
6894 (setq org-hide-block-overlays nil))
6896 (defun org-hide-block-toggle-maybe ()
6897 "Toggle visibility of block at point."
6898 (interactive)
6899 (let ((case-fold-search t))
6900 (if (save-excursion
6901 (beginning-of-line 1)
6902 (looking-at org-block-regexp))
6903 (progn (org-hide-block-toggle)
6904 t) ;; to signal that we took action
6905 nil))) ;; to signal that we did not
6907 (defun org-hide-block-toggle (&optional force)
6908 "Toggle the visibility of the current block."
6909 (interactive)
6910 (save-excursion
6911 (beginning-of-line)
6912 (if (re-search-forward org-block-regexp nil t)
6913 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6914 (end (match-end 0)) ;; end of entire body
6916 (if (memq t (mapcar (lambda (overlay)
6917 (eq (overlay-get overlay 'invisible)
6918 'org-hide-block))
6919 (overlays-at start)))
6920 (if (or (not force) (eq force 'off))
6921 (mapc (lambda (ov)
6922 (when (member ov org-hide-block-overlays)
6923 (setq org-hide-block-overlays
6924 (delq ov org-hide-block-overlays)))
6925 (when (eq (overlay-get ov 'invisible)
6926 'org-hide-block)
6927 (delete-overlay ov)))
6928 (overlays-at start)))
6929 (setq ov (make-overlay start end))
6930 (overlay-put ov 'invisible 'org-hide-block)
6931 ;; make the block accessible to isearch
6932 (overlay-put
6933 ov 'isearch-open-invisible
6934 (lambda (ov)
6935 (when (member ov org-hide-block-overlays)
6936 (setq org-hide-block-overlays
6937 (delq ov org-hide-block-overlays)))
6938 (when (eq (overlay-get ov 'invisible)
6939 'org-hide-block)
6940 (delete-overlay ov))))
6941 (push ov org-hide-block-overlays)))
6942 (error "Not looking at a source block"))))
6944 ;; org-tab-after-check-for-cycling-hook
6945 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6946 ;; Remove overlays when changing major mode
6947 (add-hook 'org-mode-hook
6948 (lambda () (org-add-hook 'change-major-mode-hook
6949 'org-show-block-all 'append 'local)))
6951 ;;; Org-goto
6953 (defvar org-goto-window-configuration nil)
6954 (defvar org-goto-marker nil)
6955 (defvar org-goto-map
6956 (let ((map (make-sparse-keymap)))
6957 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6958 (while (setq cmd (pop cmds))
6959 (substitute-key-definition cmd cmd map global-map)))
6960 (suppress-keymap map)
6961 (org-defkey map "\C-m" 'org-goto-ret)
6962 (org-defkey map [(return)] 'org-goto-ret)
6963 (org-defkey map [(left)] 'org-goto-left)
6964 (org-defkey map [(right)] 'org-goto-right)
6965 (org-defkey map [(control ?g)] 'org-goto-quit)
6966 (org-defkey map "\C-i" 'org-cycle)
6967 (org-defkey map [(tab)] 'org-cycle)
6968 (org-defkey map [(down)] 'outline-next-visible-heading)
6969 (org-defkey map [(up)] 'outline-previous-visible-heading)
6970 (if org-goto-auto-isearch
6971 (if (fboundp 'define-key-after)
6972 (define-key-after map [t] 'org-goto-local-auto-isearch)
6973 nil)
6974 (org-defkey map "q" 'org-goto-quit)
6975 (org-defkey map "n" 'outline-next-visible-heading)
6976 (org-defkey map "p" 'outline-previous-visible-heading)
6977 (org-defkey map "f" 'outline-forward-same-level)
6978 (org-defkey map "b" 'outline-backward-same-level)
6979 (org-defkey map "u" 'outline-up-heading))
6980 (org-defkey map "/" 'org-occur)
6981 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6982 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6983 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6984 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6985 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6986 map))
6988 (defconst org-goto-help
6989 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6990 RET=jump to location [Q]uit and return to previous location
6991 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6993 (defvar org-goto-start-pos) ; dynamically scoped parameter
6995 ;; FIXME: Docstring does not mention both interfaces
6996 (defun org-goto (&optional alternative-interface)
6997 "Look up a different location in the current file, keeping current visibility.
6999 When you want look-up or go to a different location in a
7000 document, the fastest way is often to fold the entire buffer and
7001 then dive into the tree. This method has the disadvantage, that
7002 the previous location will be folded, which may not be what you
7003 want.
7005 This command works around this by showing a copy of the current
7006 buffer in an indirect buffer, in overview mode. You can dive
7007 into the tree in that copy, use org-occur and incremental search
7008 to find a location. When pressing RET or `Q', the command
7009 returns to the original buffer in which the visibility is still
7010 unchanged. After RET it will also jump to the location selected
7011 in the indirect buffer and expose the headline hierarchy above.
7013 With a prefix argument, use the alternative interface: e.g. if
7014 `org-goto-interface' is 'outline use 'outline-path-completion."
7015 (interactive "P")
7016 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7017 (org-refile-use-outline-path t)
7018 (org-refile-target-verify-function nil)
7019 (interface
7020 (if (not alternative-interface)
7021 org-goto-interface
7022 (if (eq org-goto-interface 'outline)
7023 'outline-path-completion
7024 'outline)))
7025 (org-goto-start-pos (point))
7026 (selected-point
7027 (if (eq interface 'outline)
7028 (car (org-get-location (current-buffer) org-goto-help))
7029 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7030 (org-refile-check-position pa)
7031 (nth 3 pa)))))
7032 (if selected-point
7033 (progn
7034 (org-mark-ring-push org-goto-start-pos)
7035 (goto-char selected-point)
7036 (if (or (outline-invisible-p) (org-invisible-p2))
7037 (org-show-context 'org-goto)))
7038 (message "Quit"))))
7040 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7041 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7042 (defvar org-goto-local-auto-isearch-map) ; defined below
7044 (defun org-get-location (buf help)
7045 "Let the user select a location in the Org-mode buffer BUF.
7046 This function uses a recursive edit. It returns the selected position
7047 or nil."
7048 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7049 (isearch-hide-immediately nil)
7050 (isearch-search-fun-function
7051 (lambda () 'org-goto-local-search-headings))
7052 (org-goto-selected-point org-goto-exit-command)
7053 (pop-up-frames nil)
7054 (special-display-buffer-names nil)
7055 (special-display-regexps nil)
7056 (special-display-function nil))
7057 (save-excursion
7058 (save-window-excursion
7059 (delete-other-windows)
7060 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7061 (org-pop-to-buffer-same-window
7062 (condition-case nil
7063 (make-indirect-buffer (current-buffer) "*org-goto*")
7064 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7065 (with-output-to-temp-buffer "*Help*"
7066 (princ help))
7067 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7068 (setq buffer-read-only nil)
7069 (let ((org-startup-truncated t)
7070 (org-startup-folded nil)
7071 (org-startup-align-all-tables nil))
7072 (org-mode)
7073 (org-overview))
7074 (setq buffer-read-only t)
7075 (if (and (boundp 'org-goto-start-pos)
7076 (integer-or-marker-p org-goto-start-pos))
7077 (let ((org-show-hierarchy-above t)
7078 (org-show-siblings t)
7079 (org-show-following-heading t))
7080 (goto-char org-goto-start-pos)
7081 (and (outline-invisible-p) (org-show-context)))
7082 (goto-char (point-min)))
7083 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7084 (message "Select location and press RET")
7085 (use-local-map org-goto-map)
7086 (recursive-edit)
7088 (kill-buffer "*org-goto*")
7089 (cons org-goto-selected-point org-goto-exit-command)))
7091 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7092 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7093 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7094 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7096 (defun org-goto-local-search-headings (string bound noerror)
7097 "Search and make sure that any matches are in headlines."
7098 (catch 'return
7099 (while (if isearch-forward
7100 (search-forward string bound noerror)
7101 (search-backward string bound noerror))
7102 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7103 (and (member :headline context)
7104 (not (member :tags context))))
7105 (throw 'return (point))))))
7107 (defun org-goto-local-auto-isearch ()
7108 "Start isearch."
7109 (interactive)
7110 (goto-char (point-min))
7111 (let ((keys (this-command-keys)))
7112 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7113 (isearch-mode t)
7114 (isearch-process-search-char (string-to-char keys)))))
7116 (defun org-goto-ret (&optional arg)
7117 "Finish `org-goto' by going to the new location."
7118 (interactive "P")
7119 (setq org-goto-selected-point (point)
7120 org-goto-exit-command 'return)
7121 (throw 'exit nil))
7123 (defun org-goto-left ()
7124 "Finish `org-goto' by going to the new location."
7125 (interactive)
7126 (if (org-at-heading-p)
7127 (progn
7128 (beginning-of-line 1)
7129 (setq org-goto-selected-point (point)
7130 org-goto-exit-command 'left)
7131 (throw 'exit nil))
7132 (error "Not on a heading")))
7134 (defun org-goto-right ()
7135 "Finish `org-goto' by going to the new location."
7136 (interactive)
7137 (if (org-at-heading-p)
7138 (progn
7139 (setq org-goto-selected-point (point)
7140 org-goto-exit-command 'right)
7141 (throw 'exit nil))
7142 (error "Not on a heading")))
7144 (defun org-goto-quit ()
7145 "Finish `org-goto' without cursor motion."
7146 (interactive)
7147 (setq org-goto-selected-point nil)
7148 (setq org-goto-exit-command 'quit)
7149 (throw 'exit nil))
7151 ;;; Indirect buffer display of subtrees
7153 (defvar org-indirect-dedicated-frame nil
7154 "This is the frame being used for indirect tree display.")
7155 (defvar org-last-indirect-buffer nil)
7157 (defun org-tree-to-indirect-buffer (&optional arg)
7158 "Create indirect buffer and narrow it to current subtree.
7159 With numerical prefix ARG, go up to this level and then take that tree.
7160 If ARG is negative, go up that many levels.
7161 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7162 indirect buffer previously made with this command, to avoid proliferation of
7163 indirect buffers. However, when you call the command with a \
7164 \\[universal-argument] prefix, or
7165 when `org-indirect-buffer-display' is `new-frame', the last buffer
7166 is kept so that you can work with several indirect buffers at the same time.
7167 If `org-indirect-buffer-display' is `dedicated-frame', the \
7168 \\[universal-argument] prefix also
7169 requests that a new frame be made for the new buffer, so that the dedicated
7170 frame is not changed."
7171 (interactive "P")
7172 (let ((cbuf (current-buffer))
7173 (cwin (selected-window))
7174 (pos (point))
7175 beg end level heading ibuf)
7176 (save-excursion
7177 (org-back-to-heading t)
7178 (when (numberp arg)
7179 (setq level (org-outline-level))
7180 (if (< arg 0) (setq arg (+ level arg)))
7181 (while (> (setq level (org-outline-level)) arg)
7182 (outline-up-heading 1 t)))
7183 (setq beg (point)
7184 heading (org-get-heading))
7185 (org-end-of-subtree t t)
7186 (if (org-at-heading-p) (backward-char 1))
7187 (setq end (point)))
7188 (if (and (buffer-live-p org-last-indirect-buffer)
7189 (not (eq org-indirect-buffer-display 'new-frame))
7190 (not arg))
7191 (kill-buffer org-last-indirect-buffer))
7192 (setq ibuf (org-get-indirect-buffer cbuf)
7193 org-last-indirect-buffer ibuf)
7194 (cond
7195 ((or (eq org-indirect-buffer-display 'new-frame)
7196 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7197 (select-frame (make-frame))
7198 (delete-other-windows)
7199 (org-pop-to-buffer-same-window ibuf)
7200 (org-set-frame-title heading))
7201 ((eq org-indirect-buffer-display 'dedicated-frame)
7202 (raise-frame
7203 (select-frame (or (and org-indirect-dedicated-frame
7204 (frame-live-p org-indirect-dedicated-frame)
7205 org-indirect-dedicated-frame)
7206 (setq org-indirect-dedicated-frame (make-frame)))))
7207 (delete-other-windows)
7208 (org-pop-to-buffer-same-window ibuf)
7209 (org-set-frame-title (concat "Indirect: " heading)))
7210 ((eq org-indirect-buffer-display 'current-window)
7211 (org-pop-to-buffer-same-window ibuf))
7212 ((eq org-indirect-buffer-display 'other-window)
7213 (pop-to-buffer ibuf))
7214 (t (error "Invalid value")))
7215 (if (featurep 'xemacs)
7216 (save-excursion (org-mode) (turn-on-font-lock)))
7217 (narrow-to-region beg end)
7218 (show-all)
7219 (goto-char pos)
7220 (run-hook-with-args 'org-cycle-hook 'all)
7221 (and (window-live-p cwin) (select-window cwin))))
7223 (defun org-get-indirect-buffer (&optional buffer)
7224 (setq buffer (or buffer (current-buffer)))
7225 (let ((n 1) (base (buffer-name buffer)) bname)
7226 (while (buffer-live-p
7227 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7228 (setq n (1+ n)))
7229 (condition-case nil
7230 (make-indirect-buffer buffer bname 'clone)
7231 (error (make-indirect-buffer buffer bname)))))
7233 (defun org-set-frame-title (title)
7234 "Set the title of the current frame to the string TITLE."
7235 ;; FIXME: how to name a single frame in XEmacs???
7236 (unless (featurep 'xemacs)
7237 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7239 ;;;; Structure editing
7241 ;;; Inserting headlines
7243 (defun org-previous-line-empty-p ()
7244 (save-excursion
7245 (and (not (bobp))
7246 (or (beginning-of-line 0) t)
7247 (save-match-data
7248 (looking-at "[ \t]*$")))))
7250 (defun org-insert-heading (&optional force-heading invisible-ok)
7251 "Insert a new heading or item with same depth at point.
7252 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7253 If point is at the beginning of a headline, insert a sibling before the
7254 current headline. If point is not at the beginning, split the line,
7255 create the new headline with the text in the current line after point
7256 \(but see also the variable `org-M-RET-may-split-line').
7258 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7259 This is important for non-interactive uses of the command."
7260 (interactive "P")
7261 (if (or (= (buffer-size) 0)
7262 (and (not (save-excursion
7263 (and (ignore-errors (org-back-to-heading invisible-ok))
7264 (org-at-heading-p))))
7265 (or force-heading (not (org-in-item-p)))))
7266 (progn
7267 (insert "\n* ")
7268 (run-hooks 'org-insert-heading-hook))
7269 (when (or force-heading (not (org-insert-item)))
7270 (let* ((empty-line-p nil)
7271 (level nil)
7272 (on-heading (org-at-heading-p))
7273 (head (save-excursion
7274 (condition-case nil
7275 (progn
7276 (org-back-to-heading invisible-ok)
7277 (when (and (not on-heading)
7278 (featurep 'org-inlinetask)
7279 (integerp org-inlinetask-min-level)
7280 (>= (length (match-string 0))
7281 org-inlinetask-min-level))
7282 ;; Find a heading level before the inline task
7283 (while (and (setq level (org-up-heading-safe))
7284 (>= level org-inlinetask-min-level)))
7285 (if (org-at-heading-p)
7286 (org-back-to-heading invisible-ok)
7287 (error "This should not happen")))
7288 (setq empty-line-p (org-previous-line-empty-p))
7289 (match-string 0))
7290 (error "*"))))
7291 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7292 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7293 pos hide-previous previous-pos)
7294 (cond
7295 ((and (org-at-heading-p) (bolp)
7296 (or (bobp)
7297 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7298 ;; insert before the current line
7299 (open-line (if blank 2 1)))
7300 ((and (bolp)
7301 (not org-insert-heading-respect-content)
7302 (or (bobp)
7303 (save-excursion
7304 (backward-char 1) (not (outline-invisible-p)))))
7305 ;; insert right here
7306 nil)
7308 ;; somewhere in the line
7309 (save-excursion
7310 (setq previous-pos (point-at-bol))
7311 (end-of-line)
7312 (setq hide-previous (outline-invisible-p)))
7313 (and org-insert-heading-respect-content (org-show-subtree))
7314 (let ((split
7315 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7316 (save-excursion
7317 (let ((p (point)))
7318 (goto-char (point-at-bol))
7319 (and (looking-at org-complex-heading-regexp)
7320 (match-beginning 4)
7321 (> p (match-beginning 4)))))))
7322 tags pos)
7323 (cond
7324 (org-insert-heading-respect-content
7325 (org-end-of-subtree nil t)
7326 (when (featurep 'org-inlinetask)
7327 (while (and (not (eobp))
7328 (looking-at "\\(\\*+\\)[ \t]+")
7329 (>= (length (match-string 1))
7330 org-inlinetask-min-level))
7331 (org-end-of-subtree nil t)))
7332 (or (bolp) (newline))
7333 (or (org-previous-line-empty-p)
7334 (and blank (newline)))
7335 (open-line 1))
7336 ((org-at-heading-p)
7337 (when hide-previous
7338 (show-children)
7339 (org-show-entry))
7340 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7341 (setq tags (and (match-end 2) (match-string 2)))
7342 (and (match-end 1)
7343 (delete-region (match-beginning 1) (match-end 1)))
7344 (setq pos (point-at-bol))
7345 (or split (end-of-line 1))
7346 (delete-horizontal-space)
7347 (if (string-match "\\`\\*+\\'"
7348 (buffer-substring (point-at-bol) (point)))
7349 (insert " "))
7350 (newline (if blank 2 1))
7351 (when tags
7352 (save-excursion
7353 (goto-char pos)
7354 (end-of-line 1)
7355 (insert " " tags)
7356 (org-set-tags nil 'align))))
7358 (or split (end-of-line 1))
7359 (newline (if blank 2 1)))))))
7360 (insert head) (just-one-space)
7361 (setq pos (point))
7362 (end-of-line 1)
7363 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7364 (when (and org-insert-heading-respect-content hide-previous)
7365 (save-excursion
7366 (goto-char previous-pos)
7367 (hide-subtree)))
7368 (run-hooks 'org-insert-heading-hook)))))
7370 (defun org-get-heading (&optional no-tags no-todo)
7371 "Return the heading of the current entry, without the stars.
7372 When NO-TAGS is non-nil, don't include tags.
7373 When NO-TODO is non-nil, don't include TODO keywords."
7374 (save-excursion
7375 (org-back-to-heading t)
7376 (cond
7377 ((and no-tags no-todo)
7378 (looking-at org-complex-heading-regexp)
7379 (match-string 4))
7380 (no-tags
7381 (looking-at (concat org-outline-regexp
7382 "\\(.*?\\)"
7383 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7384 (match-string 1))
7385 (no-todo
7386 (looking-at org-todo-line-regexp)
7387 (match-string 3))
7388 (t (looking-at org-heading-regexp)
7389 (match-string 2)))))
7391 (defun org-heading-components ()
7392 "Return the components of the current heading.
7393 This is a list with the following elements:
7394 - the level as an integer
7395 - the reduced level, different if `org-odd-levels-only' is set.
7396 - the TODO keyword, or nil
7397 - the priority character, like ?A, or nil if no priority is given
7398 - the headline text itself, or the tags string if no headline text
7399 - the tags string, or nil."
7400 (save-excursion
7401 (org-back-to-heading t)
7402 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7403 (list (length (match-string 1))
7404 (org-reduced-level (length (match-string 1)))
7405 (org-match-string-no-properties 2)
7406 (and (match-end 3) (aref (match-string 3) 2))
7407 (org-match-string-no-properties 4)
7408 (org-match-string-no-properties 5)))))
7410 (defun org-get-entry ()
7411 "Get the entry text, after heading, entire subtree."
7412 (save-excursion
7413 (org-back-to-heading t)
7414 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7416 (defun org-insert-heading-after-current ()
7417 "Insert a new heading with same level as current, after current subtree."
7418 (interactive)
7419 (org-back-to-heading)
7420 (org-insert-heading)
7421 (org-move-subtree-down)
7422 (end-of-line 1))
7424 (defun org-insert-heading-respect-content ()
7425 (interactive)
7426 (let ((org-insert-heading-respect-content t))
7427 (org-insert-heading t)))
7429 (defun org-insert-todo-heading-respect-content (&optional force-state)
7430 (interactive "P")
7431 (let ((org-insert-heading-respect-content t))
7432 (org-insert-todo-heading force-state t)))
7434 (defun org-insert-todo-heading (arg &optional force-heading)
7435 "Insert a new heading with the same level and TODO state as current heading.
7436 If the heading has no TODO state, or if the state is DONE, use the first
7437 state (TODO by default). Also with prefix arg, force first state."
7438 (interactive "P")
7439 (when (or force-heading (not (org-insert-item 'checkbox)))
7440 (org-insert-heading force-heading)
7441 (save-excursion
7442 (org-back-to-heading)
7443 (outline-previous-heading)
7444 (looking-at org-todo-line-regexp))
7445 (let*
7446 ((new-mark-x
7447 (if (or arg
7448 (not (match-beginning 2))
7449 (member (match-string 2) org-done-keywords))
7450 (car org-todo-keywords-1)
7451 (match-string 2)))
7452 (new-mark
7454 (run-hook-with-args-until-success
7455 'org-todo-get-default-hook new-mark-x nil)
7456 new-mark-x)))
7457 (beginning-of-line 1)
7458 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7459 (if org-treat-insert-todo-heading-as-state-change
7460 (org-todo new-mark)
7461 (insert new-mark " "))))
7462 (when org-provide-todo-statistics
7463 (org-update-parent-todo-statistics))))
7465 (defun org-insert-subheading (arg)
7466 "Insert a new subheading and demote it.
7467 Works for outline headings and for plain lists alike."
7468 (interactive "P")
7469 (org-insert-heading arg)
7470 (cond
7471 ((org-at-heading-p) (org-do-demote))
7472 ((org-at-item-p) (org-indent-item))))
7474 (defun org-insert-todo-subheading (arg)
7475 "Insert a new subheading with TODO keyword or checkbox and demote it.
7476 Works for outline headings and for plain lists alike."
7477 (interactive "P")
7478 (org-insert-todo-heading arg)
7479 (cond
7480 ((org-at-heading-p) (org-do-demote))
7481 ((org-at-item-p) (org-indent-item))))
7483 ;;; Promotion and Demotion
7485 (defvar org-after-demote-entry-hook nil
7486 "Hook run after an entry has been demoted.
7487 The cursor will be at the beginning of the entry.
7488 When a subtree is being demoted, the hook will be called for each node.")
7490 (defvar org-after-promote-entry-hook nil
7491 "Hook run after an entry has been promoted.
7492 The cursor will be at the beginning of the entry.
7493 When a subtree is being promoted, the hook will be called for each node.")
7495 (defun org-promote-subtree ()
7496 "Promote the entire subtree.
7497 See also `org-promote'."
7498 (interactive)
7499 (save-excursion
7500 (org-with-limited-levels (org-map-tree 'org-promote)))
7501 (org-fix-position-after-promote))
7503 (defun org-demote-subtree ()
7504 "Demote the entire subtree. See `org-demote'.
7505 See also `org-promote'."
7506 (interactive)
7507 (save-excursion
7508 (org-with-limited-levels (org-map-tree 'org-demote)))
7509 (org-fix-position-after-promote))
7512 (defun org-do-promote ()
7513 "Promote the current heading higher up the tree.
7514 If the region is active in `transient-mark-mode', promote all headings
7515 in the region."
7516 (interactive)
7517 (save-excursion
7518 (if (org-region-active-p)
7519 (org-map-region 'org-promote (region-beginning) (region-end))
7520 (org-promote)))
7521 (org-fix-position-after-promote))
7523 (defun org-do-demote ()
7524 "Demote the current heading lower down the tree.
7525 If the region is active in `transient-mark-mode', demote all headings
7526 in the region."
7527 (interactive)
7528 (save-excursion
7529 (if (org-region-active-p)
7530 (org-map-region 'org-demote (region-beginning) (region-end))
7531 (org-demote)))
7532 (org-fix-position-after-promote))
7534 (defun org-fix-position-after-promote ()
7535 "Make sure that after pro/demotion cursor position is right."
7536 (let ((pos (point)))
7537 (when (save-excursion
7538 (beginning-of-line 1)
7539 (looking-at org-todo-line-regexp)
7540 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7541 (cond ((eobp) (insert " "))
7542 ((eolp) (insert " "))
7543 ((equal (char-after) ?\ ) (forward-char 1))))))
7545 (defun org-current-level ()
7546 "Return the level of the current entry, or nil if before the first headline.
7547 The level is the number of stars at the beginning of the headline."
7548 (save-excursion
7549 (org-with-limited-levels
7550 (if (ignore-errors (org-back-to-heading t))
7551 (funcall outline-level)))))
7553 (defun org-get-previous-line-level ()
7554 "Return the outline depth of the last headline before the current line.
7555 Returns 0 for the first headline in the buffer, and nil if before the
7556 first headline."
7557 (let ((current-level (org-current-level))
7558 (prev-level (when (> (line-number-at-pos) 1)
7559 (save-excursion
7560 (beginning-of-line 0)
7561 (org-current-level)))))
7562 (cond ((null current-level) nil) ; Before first headline
7563 ((null prev-level) 0) ; At first headline
7564 (prev-level))))
7566 (defun org-reduced-level (l)
7567 "Compute the effective level of a heading.
7568 This takes into account the setting of `org-odd-levels-only'."
7569 (cond
7570 ((zerop l) 0)
7571 (org-odd-levels-only (1+ (floor (/ l 2))))
7572 (t l)))
7574 (defun org-level-increment ()
7575 "Return the number of stars that will be added or removed at a
7576 time to headlines when structure editing, based on the value of
7577 `org-odd-levels-only'."
7578 (if org-odd-levels-only 2 1))
7580 (defun org-get-valid-level (level &optional change)
7581 "Rectify a level change under the influence of `org-odd-levels-only'
7582 LEVEL is a current level, CHANGE is by how much the level should be
7583 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7584 even level numbers will become the next higher odd number."
7585 (if org-odd-levels-only
7586 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7587 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7588 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7589 (max 1 (+ level (or change 0)))))
7591 (if (boundp 'define-obsolete-function-alias)
7592 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7593 (define-obsolete-function-alias 'org-get-legal-level
7594 'org-get-valid-level)
7595 (define-obsolete-function-alias 'org-get-legal-level
7596 'org-get-valid-level "23.1")))
7598 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7599 ;; ̀org-with-limited-levels'
7600 (defun org-promote ()
7601 "Promote the current heading higher up the tree.
7602 If the region is active in `transient-mark-mode', promote all headings
7603 in the region."
7604 (org-back-to-heading t)
7605 (let* ((level (save-match-data (funcall outline-level)))
7606 (after-change-functions (remove 'flyspell-after-change-function
7607 after-change-functions))
7608 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7609 (diff (abs (- level (length up-head) -1))))
7610 (cond ((and (= level 1) org-called-with-limited-levels
7611 org-allow-promoting-top-level-subtree)
7612 (replace-match "# " nil t))
7613 ((= level 1)
7614 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7615 (t (replace-match up-head nil t)))
7616 ;; Fixup tag positioning
7617 (unless (= level 1)
7618 (and org-auto-align-tags (org-set-tags nil t))
7619 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7620 (run-hooks 'org-after-promote-entry-hook)))
7622 (defun org-demote ()
7623 "Demote the current heading lower down the tree.
7624 If the region is active in `transient-mark-mode', demote all headings
7625 in the region."
7626 (org-back-to-heading t)
7627 (let* ((level (save-match-data (funcall outline-level)))
7628 (after-change-functions (remove 'flyspell-after-change-function
7629 after-change-functions))
7630 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7631 (diff (abs (- level (length down-head) -1))))
7632 (replace-match down-head nil t)
7633 ;; Fixup tag positioning
7634 (and org-auto-align-tags (org-set-tags nil t))
7635 (if org-adapt-indentation (org-fixup-indentation diff))
7636 (run-hooks 'org-after-demote-entry-hook)))
7638 (defun org-cycle-level ()
7639 "Cycle the level of an empty headline through possible states.
7640 This goes first to child, then to parent, level, then up the hierarchy.
7641 After top level, it switches back to sibling level."
7642 (interactive)
7643 (let ((org-adapt-indentation nil))
7644 (when (org-point-at-end-of-empty-headline)
7645 (setq this-command 'org-cycle-level) ; Only needed for caching
7646 (let ((cur-level (org-current-level))
7647 (prev-level (org-get-previous-line-level)))
7648 (cond
7649 ;; If first headline in file, promote to top-level.
7650 ((= prev-level 0)
7651 (loop repeat (/ (- cur-level 1) (org-level-increment))
7652 do (org-do-promote)))
7653 ;; If same level as prev, demote one.
7654 ((= prev-level cur-level)
7655 (org-do-demote))
7656 ;; If parent is top-level, promote to top level if not already.
7657 ((= prev-level 1)
7658 (loop repeat (/ (- cur-level 1) (org-level-increment))
7659 do (org-do-promote)))
7660 ;; If top-level, return to prev-level.
7661 ((= cur-level 1)
7662 (loop repeat (/ (- prev-level 1) (org-level-increment))
7663 do (org-do-demote)))
7664 ;; If less than prev-level, promote one.
7665 ((< cur-level prev-level)
7666 (org-do-promote))
7667 ;; If deeper than prev-level, promote until higher than
7668 ;; prev-level.
7669 ((> cur-level prev-level)
7670 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7671 do (org-do-promote))))
7672 t))))
7674 (defun org-map-tree (fun)
7675 "Call FUN for every heading underneath the current one."
7676 (org-back-to-heading)
7677 (let ((level (funcall outline-level)))
7678 (save-excursion
7679 (funcall fun)
7680 (while (and (progn
7681 (outline-next-heading)
7682 (> (funcall outline-level) level))
7683 (not (eobp)))
7684 (funcall fun)))))
7686 (defun org-map-region (fun beg end)
7687 "Call FUN for every heading between BEG and END."
7688 (let ((org-ignore-region t))
7689 (save-excursion
7690 (setq end (copy-marker end))
7691 (goto-char beg)
7692 (if (and (re-search-forward org-outline-regexp-bol nil t)
7693 (< (point) end))
7694 (funcall fun))
7695 (while (and (progn
7696 (outline-next-heading)
7697 (< (point) end))
7698 (not (eobp)))
7699 (funcall fun)))))
7701 (defvar org-property-end-re) ; silence byte-compiler
7702 (defun org-fixup-indentation (diff)
7703 "Change the indentation in the current entry by DIFF.
7704 However, if any line in the current entry has no indentation, or if it
7705 would end up with no indentation after the change, nothing at all is done."
7706 (save-excursion
7707 (let ((end (save-excursion (outline-next-heading)
7708 (point-marker)))
7709 (prohibit (if (> diff 0)
7710 "^\\S-"
7711 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7712 col)
7713 (unless (save-excursion (end-of-line 1)
7714 (re-search-forward prohibit end t))
7715 (while (and (< (point) end)
7716 (re-search-forward "^[ \t]+" end t))
7717 (goto-char (match-end 0))
7718 (setq col (current-column))
7719 (if (< diff 0) (replace-match ""))
7720 (org-indent-to-column (+ diff col))))
7721 (move-marker end nil))))
7723 (defun org-convert-to-odd-levels ()
7724 "Convert an org-mode file with all levels allowed to one with odd levels.
7725 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7726 level 5 etc."
7727 (interactive)
7728 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7729 (let ((outline-level 'org-outline-level)
7730 (org-odd-levels-only nil) n)
7731 (save-excursion
7732 (goto-char (point-min))
7733 (while (re-search-forward "^\\*\\*+ " nil t)
7734 (setq n (- (length (match-string 0)) 2))
7735 (while (>= (setq n (1- n)) 0)
7736 (org-demote))
7737 (end-of-line 1))))))
7739 (defun org-convert-to-oddeven-levels ()
7740 "Convert an org-mode file with only odd levels to one with odd/even levels.
7741 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7742 file contains a section with an even level, conversion would
7743 destroy the structure of the file. An error is signaled in this
7744 case."
7745 (interactive)
7746 (goto-char (point-min))
7747 ;; First check if there are no even levels
7748 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7749 (org-show-context t)
7750 (error "Not all levels are odd in this file. Conversion not possible"))
7751 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7752 (let ((outline-regexp org-outline-regexp)
7753 (outline-level 'org-outline-level)
7754 (org-odd-levels-only nil) n)
7755 (save-excursion
7756 (goto-char (point-min))
7757 (while (re-search-forward "^\\*\\*+ " nil t)
7758 (setq n (/ (1- (length (match-string 0))) 2))
7759 (while (>= (setq n (1- n)) 0)
7760 (org-promote))
7761 (end-of-line 1))))))
7763 (defun org-tr-level (n)
7764 "Make N odd if required."
7765 (if org-odd-levels-only (1+ (/ n 2)) n))
7767 ;;; Vertical tree motion, cutting and pasting of subtrees
7769 (defun org-move-subtree-up (&optional arg)
7770 "Move the current subtree up past ARG headlines of the same level."
7771 (interactive "p")
7772 (org-move-subtree-down (- (prefix-numeric-value arg))))
7774 (defun org-move-subtree-down (&optional arg)
7775 "Move the current subtree down past ARG headlines of the same level."
7776 (interactive "p")
7777 (setq arg (prefix-numeric-value arg))
7778 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7779 'org-get-last-sibling))
7780 (ins-point (make-marker))
7781 (cnt (abs arg))
7782 (col (current-column))
7783 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7784 ;; Select the tree
7785 (org-back-to-heading)
7786 (setq beg0 (point))
7787 (save-excursion
7788 (setq ne-beg (org-back-over-empty-lines))
7789 (setq beg (point)))
7790 (save-match-data
7791 (save-excursion (outline-end-of-heading)
7792 (setq folded (outline-invisible-p)))
7793 (outline-end-of-subtree))
7794 (outline-next-heading)
7795 (setq ne-end (org-back-over-empty-lines))
7796 (setq end (point))
7797 (goto-char beg0)
7798 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7799 ;; include less whitespace
7800 (save-excursion
7801 (goto-char beg)
7802 (forward-line (- ne-beg ne-end))
7803 (setq beg (point))))
7804 ;; Find insertion point, with error handling
7805 (while (> cnt 0)
7806 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7807 (progn (goto-char beg0)
7808 (error "Cannot move past superior level or buffer limit")))
7809 (setq cnt (1- cnt)))
7810 (if (> arg 0)
7811 ;; Moving forward - still need to move over subtree
7812 (progn (org-end-of-subtree t t)
7813 (save-excursion
7814 (org-back-over-empty-lines)
7815 (or (bolp) (newline)))))
7816 (setq ne-ins (org-back-over-empty-lines))
7817 (move-marker ins-point (point))
7818 (setq txt (buffer-substring beg end))
7819 (org-save-markers-in-region beg end)
7820 (delete-region beg end)
7821 (org-remove-empty-overlays-at beg)
7822 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7823 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7824 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7825 (let ((bbb (point)))
7826 (insert-before-markers txt)
7827 (org-reinstall-markers-in-region bbb)
7828 (move-marker ins-point bbb))
7829 (or (bolp) (insert "\n"))
7830 (setq ins-end (point))
7831 (goto-char ins-point)
7832 (org-skip-whitespace)
7833 (when (and (< arg 0)
7834 (org-first-sibling-p)
7835 (> ne-ins ne-beg))
7836 ;; Move whitespace back to beginning
7837 (save-excursion
7838 (goto-char ins-end)
7839 (let ((kill-whole-line t))
7840 (kill-line (- ne-ins ne-beg)) (point)))
7841 (insert (make-string (- ne-ins ne-beg) ?\n)))
7842 (move-marker ins-point nil)
7843 (if folded
7844 (hide-subtree)
7845 (org-show-entry)
7846 (show-children)
7847 (org-cycle-hide-drawers 'children))
7848 (org-clean-visibility-after-subtree-move)
7849 ;; move back to the initial column we were at
7850 (move-to-column col)))
7852 (defvar org-subtree-clip ""
7853 "Clipboard for cut and paste of subtrees.
7854 This is actually only a copy of the kill, because we use the normal kill
7855 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7857 (defvar org-subtree-clip-folded nil
7858 "Was the last copied subtree folded?
7859 This is used to fold the tree back after pasting.")
7861 (defun org-cut-subtree (&optional n)
7862 "Cut the current subtree into the clipboard.
7863 With prefix arg N, cut this many sequential subtrees.
7864 This is a short-hand for marking the subtree and then cutting it."
7865 (interactive "p")
7866 (org-copy-subtree n 'cut))
7868 (defun org-copy-subtree (&optional n cut force-store-markers)
7869 "Cut the current subtree into the clipboard.
7870 With prefix arg N, cut this many sequential subtrees.
7871 This is a short-hand for marking the subtree and then copying it.
7872 If CUT is non-nil, actually cut the subtree.
7873 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7874 of some markers in the region, even if CUT is non-nil. This is
7875 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7876 (interactive "p")
7877 (let (beg end folded (beg0 (point)))
7878 (if (org-called-interactively-p 'any)
7879 (org-back-to-heading nil) ; take what looks like a subtree
7880 (org-back-to-heading t)) ; take what is really there
7881 (org-back-over-empty-lines)
7882 (setq beg (point))
7883 (skip-chars-forward " \t\r\n")
7884 (save-match-data
7885 (save-excursion (outline-end-of-heading)
7886 (setq folded (outline-invisible-p)))
7887 (condition-case nil
7888 (org-forward-heading-same-level (1- n) t)
7889 (error nil))
7890 (org-end-of-subtree t t))
7891 (org-back-over-empty-lines)
7892 (setq end (point))
7893 (goto-char beg0)
7894 (when (> end beg)
7895 (setq org-subtree-clip-folded folded)
7896 (when (or cut force-store-markers)
7897 (org-save-markers-in-region beg end))
7898 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7899 (setq org-subtree-clip (current-kill 0))
7900 (message "%s: Subtree(s) with %d characters"
7901 (if cut "Cut" "Copied")
7902 (length org-subtree-clip)))))
7904 (defun org-paste-subtree (&optional level tree for-yank)
7905 "Paste the clipboard as a subtree, with modification of headline level.
7906 The entire subtree is promoted or demoted in order to match a new headline
7907 level.
7909 If the cursor is at the beginning of a headline, the same level as
7910 that headline is used to paste the tree
7912 If not, the new level is derived from the *visible* headings
7913 before and after the insertion point, and taken to be the inferior headline
7914 level of the two. So if the previous visible heading is level 3 and the
7915 next is level 4 (or vice versa), level 4 will be used for insertion.
7916 This makes sure that the subtree remains an independent subtree and does
7917 not swallow low level entries.
7919 You can also force a different level, either by using a numeric prefix
7920 argument, or by inserting the heading marker by hand. For example, if the
7921 cursor is after \"*****\", then the tree will be shifted to level 5.
7923 If optional TREE is given, use this text instead of the kill ring.
7925 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7926 move back over whitespace before inserting, and move point to the end of
7927 the inserted text when done."
7928 (interactive "P")
7929 (setq tree (or tree (and kill-ring (current-kill 0))))
7930 (unless (org-kill-is-subtree-p tree)
7931 (error "%s"
7932 (substitute-command-keys
7933 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7934 (org-with-limited-levels
7935 (let* ((visp (not (outline-invisible-p)))
7936 (txt tree)
7937 (^re_ "\\(\\*+\\)[ \t]*")
7938 (old-level (if (string-match org-outline-regexp-bol txt)
7939 (- (match-end 0) (match-beginning 0) 1)
7940 -1))
7941 (force-level (cond (level (prefix-numeric-value level))
7942 ((and (looking-at "[ \t]*$")
7943 (string-match
7944 "^\\*+$" (buffer-substring
7945 (point-at-bol) (point))))
7946 (- (match-end 1) (match-beginning 1)))
7947 ((and (bolp)
7948 (looking-at org-outline-regexp))
7949 (- (match-end 0) (point) 1))))
7950 (previous-level (save-excursion
7951 (condition-case nil
7952 (progn
7953 (outline-previous-visible-heading 1)
7954 (if (looking-at ^re_)
7955 (- (match-end 0) (match-beginning 0) 1)
7957 (error 1))))
7958 (next-level (save-excursion
7959 (condition-case nil
7960 (progn
7961 (or (looking-at org-outline-regexp)
7962 (outline-next-visible-heading 1))
7963 (if (looking-at ^re_)
7964 (- (match-end 0) (match-beginning 0) 1)
7966 (error 1))))
7967 (new-level (or force-level (max previous-level next-level)))
7968 (shift (if (or (= old-level -1)
7969 (= new-level -1)
7970 (= old-level new-level))
7972 (- new-level old-level)))
7973 (delta (if (> shift 0) -1 1))
7974 (func (if (> shift 0) 'org-demote 'org-promote))
7975 (org-odd-levels-only nil)
7976 beg end newend)
7977 ;; Remove the forced level indicator
7978 (if force-level
7979 (delete-region (point-at-bol) (point)))
7980 ;; Paste
7981 (beginning-of-line (if (bolp) 1 2))
7982 (unless for-yank (org-back-over-empty-lines))
7983 (setq beg (point))
7984 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7985 (insert-before-markers txt)
7986 (unless (string-match "\n\\'" txt) (insert "\n"))
7987 (setq newend (point))
7988 (org-reinstall-markers-in-region beg)
7989 (setq end (point))
7990 (goto-char beg)
7991 (skip-chars-forward " \t\n\r")
7992 (setq beg (point))
7993 (if (and (outline-invisible-p) visp)
7994 (save-excursion (outline-show-heading)))
7995 ;; Shift if necessary
7996 (unless (= shift 0)
7997 (save-restriction
7998 (narrow-to-region beg end)
7999 (while (not (= shift 0))
8000 (org-map-region func (point-min) (point-max))
8001 (setq shift (+ delta shift)))
8002 (goto-char (point-min))
8003 (setq newend (point-max))))
8004 (when (or (org-called-interactively-p 'interactive) for-yank)
8005 (message "Clipboard pasted as level %d subtree" new-level))
8006 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8007 kill-ring
8008 (eq org-subtree-clip (current-kill 0))
8009 org-subtree-clip-folded)
8010 ;; The tree was folded before it was killed/copied
8011 (hide-subtree))
8012 (and for-yank (goto-char newend)))))
8014 (defun org-kill-is-subtree-p (&optional txt)
8015 "Check if the current kill is an outline subtree, or a set of trees.
8016 Returns nil if kill does not start with a headline, or if the first
8017 headline level is not the largest headline level in the tree.
8018 So this will actually accept several entries of equal levels as well,
8019 which is OK for `org-paste-subtree'.
8020 If optional TXT is given, check this string instead of the current kill."
8021 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8022 (re (org-get-limited-outline-regexp))
8023 (^re (concat "^" re))
8024 (start-level (and kill
8025 (string-match
8026 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8027 kill)
8028 (- (match-end 2) (match-beginning 2) 1)))
8029 (start (1+ (or (match-beginning 2) -1))))
8030 (if (not start-level)
8031 (progn
8032 nil) ;; does not even start with a heading
8033 (catch 'exit
8034 (while (setq start (string-match ^re kill (1+ start)))
8035 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8036 (throw 'exit nil)))
8037 t))))
8039 (defvar org-markers-to-move nil
8040 "Markers that should be moved with a cut-and-paste operation.
8041 Those markers are stored together with their positions relative to
8042 the start of the region.")
8044 (defun org-save-markers-in-region (beg end)
8045 "Check markers in region.
8046 If these markers are between BEG and END, record their position relative
8047 to BEG, so that after moving the block of text, we can put the markers back
8048 into place.
8049 This function gets called just before an entry or tree gets cut from the
8050 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8051 called immediately, to move the markers with the entries."
8052 (setq org-markers-to-move nil)
8053 (when (featurep 'org-clock)
8054 (org-clock-save-markers-for-cut-and-paste beg end))
8055 (when (featurep 'org-agenda)
8056 (org-agenda-save-markers-for-cut-and-paste beg end)))
8058 (defun org-check-and-save-marker (marker beg end)
8059 "Check if MARKER is between BEG and END.
8060 If yes, remember the marker and the distance to BEG."
8061 (when (and (marker-buffer marker)
8062 (equal (marker-buffer marker) (current-buffer)))
8063 (if (and (>= marker beg) (< marker end))
8064 (push (cons marker (- marker beg)) org-markers-to-move))))
8066 (defun org-reinstall-markers-in-region (beg)
8067 "Move all remembered markers to their position relative to BEG."
8068 (mapc (lambda (x)
8069 (move-marker (car x) (+ beg (cdr x))))
8070 org-markers-to-move)
8071 (setq org-markers-to-move nil))
8073 (defun org-narrow-to-subtree ()
8074 "Narrow buffer to the current subtree."
8075 (interactive)
8076 (save-excursion
8077 (save-match-data
8078 (org-with-limited-levels
8079 (narrow-to-region
8080 (progn (org-back-to-heading t) (point))
8081 (progn (org-end-of-subtree t t)
8082 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8083 (point)))))))
8085 (defun org-narrow-to-block ()
8086 "Narrow buffer to the current block."
8087 (interactive)
8088 (let* ((case-fold-search t)
8089 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8090 "^[ \t]*#\\+end_.*")))
8091 (if blockp
8092 (narrow-to-region (car blockp) (cdr blockp))
8093 (error "Not in a block"))))
8095 (eval-when-compile
8096 (defvar org-property-drawer-re))
8098 (defvar org-property-start-re) ;; defined below
8099 (defun org-clone-subtree-with-time-shift (n &optional shift)
8100 "Clone the task (subtree) at point N times.
8101 The clones will be inserted as siblings.
8103 In interactive use, the user will be prompted for the number of
8104 clones to be produced, and for a time SHIFT, which may be a
8105 repeater as used in time stamps, for example `+3d'.
8107 When a valid repeater is given and the entry contains any time
8108 stamps, the clones will become a sequence in time, with time
8109 stamps in the subtree shifted for each clone produced. If SHIFT
8110 is nil or the empty string, time stamps will be left alone. The
8111 ID property of the original subtree is removed.
8113 If the original subtree did contain time stamps with a repeater,
8114 the following will happen:
8115 - the repeater will be removed in each clone
8116 - an additional clone will be produced, with the current, unshifted
8117 date(s) in the entry.
8118 - the original entry will be placed *after* all the clones, with
8119 repeater intact.
8120 - the start days in the repeater in the original entry will be shifted
8121 to past the last clone.
8122 In this way you can spell out a number of instances of a repeating task,
8123 and still retain the repeater to cover future instances of the task."
8124 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8125 (let (beg end template task idprop
8126 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8127 (drawer-re org-drawer-regexp))
8128 (if (not (and (integerp n) (> n 0)))
8129 (error "Invalid number of replications %s" n))
8130 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8131 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8132 shift)))
8133 (error "Invalid shift specification %s" shift))
8134 (when doshift
8135 (setq shift-n (string-to-number (match-string 1 shift))
8136 shift-what (cdr (assoc (match-string 2 shift)
8137 '(("d" . day) ("w" . week)
8138 ("m" . month) ("y" . year))))))
8139 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8140 (setq nmin 1 nmax n)
8141 (org-back-to-heading t)
8142 (setq beg (point))
8143 (setq idprop (org-entry-get nil "ID"))
8144 (org-end-of-subtree t t)
8145 (or (bolp) (insert "\n"))
8146 (setq end (point))
8147 (setq template (buffer-substring beg end))
8148 (when (and doshift
8149 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8150 (delete-region beg end)
8151 (setq end beg)
8152 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8153 (goto-char end)
8154 (loop for n from nmin to nmax do
8155 ;; prepare clone
8156 (with-temp-buffer
8157 (insert template)
8158 (org-mode)
8159 (goto-char (point-min))
8160 (org-show-subtree)
8161 (and idprop (if org-clone-delete-id
8162 (org-entry-delete nil "ID")
8163 (org-id-get-create t)))
8164 (unless (= n 0)
8165 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8166 (kill-whole-line))
8167 (goto-char (point-min))
8168 (while (re-search-forward drawer-re nil t)
8169 (mapc (lambda (d)
8170 (org-remove-empty-drawer-at d (point))) org-drawers)))
8171 (goto-char (point-min))
8172 (when doshift
8173 (while (re-search-forward org-ts-regexp-both nil t)
8174 (org-timestamp-change (* n shift-n) shift-what))
8175 (unless (= n n-no-remove)
8176 (goto-char (point-min))
8177 (while (re-search-forward org-ts-regexp nil t)
8178 (save-excursion
8179 (goto-char (match-beginning 0))
8180 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8181 (delete-region (match-beginning 1) (match-end 1)))))))
8182 (setq task (buffer-string)))
8183 (insert task))
8184 (goto-char beg)))
8186 ;;; Outline Sorting
8188 (defun org-sort (with-case)
8189 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8190 Optional argument WITH-CASE means sort case-sensitively."
8191 (interactive "P")
8192 (cond
8193 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8194 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8196 (org-call-with-arg 'org-sort-entries with-case))))
8198 (defun org-sort-remove-invisible (s)
8199 (remove-text-properties 0 (length s) org-rm-props s)
8200 (while (string-match org-bracket-link-regexp s)
8201 (setq s (replace-match (if (match-end 2)
8202 (match-string 3 s)
8203 (match-string 1 s)) t t s)))
8206 (defvar org-priority-regexp) ; defined later in the file
8208 (defvar org-after-sorting-entries-or-items-hook nil
8209 "Hook that is run after a bunch of entries or items have been sorted.
8210 When children are sorted, the cursor is in the parent line when this
8211 hook gets called. When a region or a plain list is sorted, the cursor
8212 will be in the first entry of the sorted region/list.")
8214 (defun org-sort-entries
8215 (&optional with-case sorting-type getkey-func compare-func property)
8216 "Sort entries on a certain level of an outline tree.
8217 If there is an active region, the entries in the region are sorted.
8218 Else, if the cursor is before the first entry, sort the top-level items.
8219 Else, the children of the entry at point are sorted.
8221 Sorting can be alphabetically, numerically, by date/time as given by
8222 a time stamp, by a property or by priority.
8224 The command prompts for the sorting type unless it has been given to the
8225 function through the SORTING-TYPE argument, which needs to be a character,
8226 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8227 precise meaning of each character:
8229 n Numerically, by converting the beginning of the entry/item to a number.
8230 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8231 t By date/time, either the first active time stamp in the entry, or, if
8232 none exist, by the first inactive one.
8233 s By the scheduled date/time.
8234 d By deadline date/time.
8235 c By creation time, which is assumed to be the first inactive time stamp
8236 at the beginning of a line.
8237 p By priority according to the cookie.
8238 r By the value of a property.
8240 Capital letters will reverse the sort order.
8242 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8243 called with point at the beginning of the record. It must return either
8244 a string or a number that should serve as the sorting key for that record.
8246 Comparing entries ignores case by default. However, with an optional argument
8247 WITH-CASE, the sorting considers case as well."
8248 (interactive "P")
8249 (let ((case-func (if with-case 'identity 'downcase))
8250 start beg end stars re re2
8251 txt what tmp)
8252 ;; Find beginning and end of region to sort
8253 (cond
8254 ((org-region-active-p)
8255 ;; we will sort the region
8256 (setq end (region-end)
8257 what "region")
8258 (goto-char (region-beginning))
8259 (if (not (org-at-heading-p)) (outline-next-heading))
8260 (setq start (point)))
8261 ((or (org-at-heading-p)
8262 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8263 ;; we will sort the children of the current headline
8264 (org-back-to-heading)
8265 (setq start (point)
8266 end (progn (org-end-of-subtree t t)
8267 (or (bolp) (insert "\n"))
8268 (org-back-over-empty-lines)
8269 (point))
8270 what "children")
8271 (goto-char start)
8272 (show-subtree)
8273 (outline-next-heading))
8275 ;; we will sort the top-level entries in this file
8276 (goto-char (point-min))
8277 (or (org-at-heading-p) (outline-next-heading))
8278 (setq start (point))
8279 (goto-char (point-max))
8280 (beginning-of-line 1)
8281 (when (looking-at ".*?\\S-")
8282 ;; File ends in a non-white line
8283 (end-of-line 1)
8284 (insert "\n"))
8285 (setq end (point-max))
8286 (setq what "top-level")
8287 (goto-char start)
8288 (show-all)))
8290 (setq beg (point))
8291 (if (>= beg end) (error "Nothing to sort"))
8293 (looking-at "\\(\\*+\\)")
8294 (setq stars (match-string 1)
8295 re (concat "^" (regexp-quote stars) " +")
8296 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8297 txt (buffer-substring beg end))
8298 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8299 (if (and (not (equal stars "*")) (string-match re2 txt))
8300 (error "Region to sort contains a level above the first entry"))
8302 (unless sorting-type
8303 (message
8304 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8305 [t]ime [s]cheduled [d]eadline [c]reated
8306 A/N/T/S/D/C/P/O/F means reversed:"
8307 what)
8308 (setq sorting-type (read-char-exclusive))
8310 (and (= (downcase sorting-type) ?f)
8311 (setq getkey-func
8312 (org-icompleting-read "Sort using function: "
8313 obarray 'fboundp t nil nil))
8314 (setq getkey-func (intern getkey-func)))
8316 (and (= (downcase sorting-type) ?r)
8317 (setq property
8318 (org-icompleting-read "Property: "
8319 (mapcar 'list (org-buffer-property-keys t))
8320 nil t))))
8322 (message "Sorting entries...")
8324 (save-restriction
8325 (narrow-to-region start end)
8326 (let ((dcst (downcase sorting-type))
8327 (case-fold-search nil)
8328 (now (current-time)))
8329 (sort-subr
8330 (/= dcst sorting-type)
8331 ;; This function moves to the beginning character of the "record" to
8332 ;; be sorted.
8333 (lambda nil
8334 (if (re-search-forward re nil t)
8335 (goto-char (match-beginning 0))
8336 (goto-char (point-max))))
8337 ;; This function moves to the last character of the "record" being
8338 ;; sorted.
8339 (lambda nil
8340 (save-match-data
8341 (condition-case nil
8342 (outline-forward-same-level 1)
8343 (error
8344 (goto-char (point-max))))))
8345 ;; This function returns the value that gets sorted against.
8346 (lambda nil
8347 (cond
8348 ((= dcst ?n)
8349 (if (looking-at org-complex-heading-regexp)
8350 (string-to-number (match-string 4))
8351 nil))
8352 ((= dcst ?a)
8353 (if (looking-at org-complex-heading-regexp)
8354 (funcall case-func (match-string 4))
8355 nil))
8356 ((= dcst ?t)
8357 (let ((end (save-excursion (outline-next-heading) (point))))
8358 (if (or (re-search-forward org-ts-regexp end t)
8359 (re-search-forward org-ts-regexp-both end t))
8360 (org-time-string-to-seconds (match-string 0))
8361 (org-float-time now))))
8362 ((= dcst ?c)
8363 (let ((end (save-excursion (outline-next-heading) (point))))
8364 (if (re-search-forward
8365 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8366 end t)
8367 (org-time-string-to-seconds (match-string 0))
8368 (org-float-time now))))
8369 ((= dcst ?s)
8370 (let ((end (save-excursion (outline-next-heading) (point))))
8371 (if (re-search-forward org-scheduled-time-regexp end t)
8372 (org-time-string-to-seconds (match-string 1))
8373 (org-float-time now))))
8374 ((= dcst ?d)
8375 (let ((end (save-excursion (outline-next-heading) (point))))
8376 (if (re-search-forward org-deadline-time-regexp end t)
8377 (org-time-string-to-seconds (match-string 1))
8378 (org-float-time now))))
8379 ((= dcst ?p)
8380 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8381 (string-to-char (match-string 2))
8382 org-default-priority))
8383 ((= dcst ?r)
8384 (or (org-entry-get nil property) ""))
8385 ((= dcst ?o)
8386 (if (looking-at org-complex-heading-regexp)
8387 (- 9999 (length (member (match-string 2)
8388 org-todo-keywords-1)))))
8389 ((= dcst ?f)
8390 (if getkey-func
8391 (progn
8392 (setq tmp (funcall getkey-func))
8393 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8394 tmp)
8395 (error "Invalid key function `%s'" getkey-func)))
8396 (t (error "Invalid sorting type `%c'" sorting-type))))
8398 (cond
8399 ((= dcst ?a) 'string<)
8400 ((= dcst ?f) compare-func)
8401 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8402 (run-hooks 'org-after-sorting-entries-or-items-hook)
8403 (message "Sorting entries...done")))
8405 (defun org-do-sort (table what &optional with-case sorting-type)
8406 "Sort TABLE of WHAT according to SORTING-TYPE.
8407 The user will be prompted for the SORTING-TYPE if the call to this
8408 function does not specify it. WHAT is only for the prompt, to indicate
8409 what is being sorted. The sorting key will be extracted from
8410 the car of the elements of the table.
8411 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8412 (unless sorting-type
8413 (message
8414 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8415 what)
8416 (setq sorting-type (read-char-exclusive)))
8417 (let ((dcst (downcase sorting-type))
8418 extractfun comparefun)
8419 ;; Define the appropriate functions
8420 (cond
8421 ((= dcst ?n)
8422 (setq extractfun 'string-to-number
8423 comparefun (if (= dcst sorting-type) '< '>)))
8424 ((= dcst ?a)
8425 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8426 (lambda(x) (downcase (org-sort-remove-invisible x))))
8427 comparefun (if (= dcst sorting-type)
8428 'string<
8429 (lambda (a b) (and (not (string< a b))
8430 (not (string= a b)))))))
8431 ((= dcst ?t)
8432 (setq extractfun
8433 (lambda (x)
8434 (if (or (string-match org-ts-regexp x)
8435 (string-match org-ts-regexp-both x))
8436 (org-float-time
8437 (org-time-string-to-time (match-string 0 x)))
8439 comparefun (if (= dcst sorting-type) '< '>)))
8440 (t (error "Invalid sorting type `%c'" sorting-type)))
8442 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8443 table)
8444 (lambda (a b) (funcall comparefun (car a) (car b))))))
8447 ;;; The orgstruct minor mode
8449 ;; Define a minor mode which can be used in other modes in order to
8450 ;; integrate the org-mode structure editing commands.
8452 ;; This is really a hack, because the org-mode structure commands use
8453 ;; keys which normally belong to the major mode. Here is how it
8454 ;; works: The minor mode defines all the keys necessary to operate the
8455 ;; structure commands, but wraps the commands into a function which
8456 ;; tests if the cursor is currently at a headline or a plain list
8457 ;; item. If that is the case, the structure command is used,
8458 ;; temporarily setting many Org-mode variables like regular
8459 ;; expressions for filling etc. However, when any of those keys is
8460 ;; used at a different location, function uses `key-binding' to look
8461 ;; up if the key has an associated command in another currently active
8462 ;; keymap (minor modes, major mode, global), and executes that
8463 ;; command. There might be problems if any of the keys is otherwise
8464 ;; used as a prefix key.
8466 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8467 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8468 ;; addresses this by checking explicitly for both bindings.
8470 (defvar orgstruct-mode-map (make-sparse-keymap)
8471 "Keymap for the minor `orgstruct-mode'.")
8473 (defvar org-local-vars nil
8474 "List of local variables, for use by `orgstruct-mode'.")
8476 ;;;###autoload
8477 (define-minor-mode orgstruct-mode
8478 "Toggle the minor mode `orgstruct-mode'.
8479 This mode is for using Org-mode structure commands in other
8480 modes. The following keys behave as if Org-mode were active, if
8481 the cursor is on a headline, or on a plain list item (both as
8482 defined by Org-mode).
8484 M-up Move entry/item up
8485 M-down Move entry/item down
8486 M-left Promote
8487 M-right Demote
8488 M-S-up Move entry/item up
8489 M-S-down Move entry/item down
8490 M-S-left Promote subtree
8491 M-S-right Demote subtree
8492 M-q Fill paragraph and items like in Org-mode
8493 C-c ^ Sort entries
8494 C-c - Cycle list bullet
8495 TAB Cycle item visibility
8496 M-RET Insert new heading/item
8497 S-M-RET Insert new TODO heading / Checkbox item
8498 C-c C-c Set tags / toggle checkbox"
8499 nil " OrgStruct" nil
8500 (org-load-modules-maybe)
8501 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8503 ;;;###autoload
8504 (defun turn-on-orgstruct ()
8505 "Unconditionally turn on `orgstruct-mode'."
8506 (orgstruct-mode 1))
8508 (defvar org-fb-vars nil)
8509 (make-variable-buffer-local 'org-fb-vars)
8510 (defun orgstruct++-mode (&optional arg)
8511 "Toggle `orgstruct-mode', the enhanced version of it.
8512 In addition to setting orgstruct-mode, this also exports all
8513 indentation and autofilling variables from org-mode into the
8514 buffer. It will also recognize item context in multiline items."
8515 (interactive "P")
8516 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8517 (if (< arg 1)
8518 (progn (orgstruct-mode -1)
8519 (mapc (lambda(v)
8520 (org-set-local (car v)
8521 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8522 org-fb-vars))
8523 (orgstruct-mode 1)
8524 (setq org-fb-vars nil)
8525 (let (var val)
8526 (mapc
8527 (lambda (x)
8528 (when (string-match
8529 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8530 (symbol-name (car x)))
8531 (setq var (car x) val (nth 1 x))
8532 (push (list var `(quote ,(eval var))) org-fb-vars)
8533 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8534 org-local-vars)
8535 (org-set-local 'orgstruct-is-++ t))))
8537 (defvar orgstruct-is-++ nil
8538 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8539 (make-variable-buffer-local 'orgstruct-is-++)
8541 ;;;###autoload
8542 (defun turn-on-orgstruct++ ()
8543 "Unconditionally turn on `orgstruct++-mode'."
8544 (orgstruct++-mode 1))
8546 (defun orgstruct-error ()
8547 "Error when there is no default binding for a structure key."
8548 (interactive)
8549 (error "This key has no function outside structure elements"))
8551 (defun orgstruct-setup ()
8552 "Setup orgstruct keymaps."
8553 (let ((nfunc 0)
8554 (bindings
8555 (list
8556 '([(meta up)] org-metaup)
8557 '([(meta down)] org-metadown)
8558 '([(meta left)] org-metaleft)
8559 '([(meta right)] org-metaright)
8560 '([(meta shift up)] org-shiftmetaup)
8561 '([(meta shift down)] org-shiftmetadown)
8562 '([(meta shift left)] org-shiftmetaleft)
8563 '([(meta shift right)] org-shiftmetaright)
8564 '([?\e (up)] org-metaup)
8565 '([?\e (down)] org-metadown)
8566 '([?\e (left)] org-metaleft)
8567 '([?\e (right)] org-metaright)
8568 '([?\e (shift up)] org-shiftmetaup)
8569 '([?\e (shift down)] org-shiftmetadown)
8570 '([?\e (shift left)] org-shiftmetaleft)
8571 '([?\e (shift right)] org-shiftmetaright)
8572 '([(shift up)] org-shiftup)
8573 '([(shift down)] org-shiftdown)
8574 '([(shift left)] org-shiftleft)
8575 '([(shift right)] org-shiftright)
8576 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8577 '("\M-q" fill-paragraph)
8578 '("\C-c^" org-sort)
8579 '("\C-c-" org-cycle-list-bullet)))
8580 elt key fun cmd)
8581 (while (setq elt (pop bindings))
8582 (setq nfunc (1+ nfunc))
8583 (setq key (org-key (car elt))
8584 fun (nth 1 elt)
8585 cmd (orgstruct-make-binding fun nfunc key))
8586 (org-defkey orgstruct-mode-map key cmd))
8588 ;; Prevent an error for users who forgot to make autoloads
8589 (require 'org-element)
8591 ;; Special treatment needed for TAB and RET
8592 (org-defkey orgstruct-mode-map [(tab)]
8593 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8594 (org-defkey orgstruct-mode-map "\C-i"
8595 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8597 (org-defkey orgstruct-mode-map "\M-\C-m"
8598 (orgstruct-make-binding 'org-insert-heading 105
8599 "\M-\C-m" [(meta return)]))
8600 (org-defkey orgstruct-mode-map [(meta return)]
8601 (orgstruct-make-binding 'org-insert-heading 106
8602 [(meta return)] "\M-\C-m"))
8604 (org-defkey orgstruct-mode-map [(shift meta return)]
8605 (orgstruct-make-binding 'org-insert-todo-heading 107
8606 [(meta return)] "\M-\C-m"))
8608 (org-defkey orgstruct-mode-map "\e\C-m"
8609 (orgstruct-make-binding 'org-insert-heading 108
8610 "\e\C-m" [?\e (return)]))
8611 (org-defkey orgstruct-mode-map [?\e (return)]
8612 (orgstruct-make-binding 'org-insert-heading 109
8613 [?\e (return)] "\e\C-m"))
8614 (org-defkey orgstruct-mode-map [?\e (shift return)]
8615 (orgstruct-make-binding 'org-insert-todo-heading 110
8616 [?\e (return)] "\e\C-m"))
8618 (unless org-local-vars
8619 (setq org-local-vars (org-get-local-variables)))
8623 (defun orgstruct-make-binding (fun n &rest keys)
8624 "Create a function for binding in the structure minor mode.
8625 FUN is the command to call inside a table. N is used to create a unique
8626 command name. KEYS are keys that should be checked in for a command
8627 to execute outside of tables."
8628 (eval
8629 (list 'defun
8630 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8631 '(arg)
8632 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8633 "Outside of structure, run the binding of `"
8634 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8635 "'.")
8636 '(interactive "p")
8637 (list 'if
8638 `(org-context-p 'headline 'item
8639 (and orgstruct-is-++
8640 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8641 'item-body))
8642 (list 'org-run-like-in-org-mode (list 'quote fun))
8643 (list 'let '(orgstruct-mode)
8644 (list 'call-interactively
8645 (append '(or)
8646 (mapcar (lambda (k)
8647 (list 'key-binding k))
8648 keys)
8649 '('orgstruct-error))))))))
8651 (defun org-contextualize-keys (alist contexts)
8652 "Return valid elements in ALIST depending on CONTEXTS.
8654 `org-agenda-custom-commands' or `org-capture-templates' are the
8655 values used for ALIST, and `org-agenda-custom-commands-contexts'
8656 or `org-capture-templates-contexts' are the associated contexts
8657 definitions."
8658 (let ((contexts
8659 ;; normalize contexts
8660 (mapcar
8661 (lambda(c) (cond ((listp (cadr c))
8662 (list (car c) (car c) (cadr c)))
8663 ((string= "" (cadr c))
8664 (list (car c) (car c) (caddr c)))
8665 (t c))) contexts))
8666 (a alist) c r s)
8667 ;; loop over all commands or templates
8668 (while (setq c (pop a))
8669 (let (vrules repl)
8670 (cond
8671 ((not (assoc (car c) contexts))
8672 (push c r))
8673 ((and (assoc (car c) contexts)
8674 (setq vrules (org-contextualize-validate-key
8675 (car c) contexts)))
8676 (mapc (lambda (vr)
8677 (when (not (equal (car vr) (cadr vr)))
8678 (setq repl vr))) vrules)
8679 (if (not repl) (push c r)
8680 (push (cadr repl) s)
8681 (push
8682 (cons (car c)
8683 (cdr (or (assoc (cadr repl) alist)
8684 (error "Undefined key `%s' as contextual replacement for `%s'"
8685 (cadr repl) (car c)))))
8686 r))))))
8687 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8688 (delq
8690 (delete-dups
8691 (mapcar (lambda (x)
8692 (let ((tpl (car x)))
8693 (when (not (delq
8695 (mapcar (lambda(y)
8696 (equal y tpl)) s))) x)))
8697 (reverse r))))))
8699 (defun org-contextualize-validate-key (key contexts)
8700 "Check CONTEXTS for agenda or capture KEY."
8701 (let (r rr res)
8702 (while (setq r (pop contexts))
8703 (mapc
8704 (lambda (rr)
8705 (when
8706 (and (equal key (car r))
8707 (if (functionp rr) (funcall rr)
8708 (or (and (eq (car rr) 'in-file)
8709 (buffer-file-name)
8710 (string-match (cdr rr) (buffer-file-name)))
8711 (and (eq (car rr) 'in-mode)
8712 (string-match (cdr rr) (symbol-name major-mode)))
8713 (when (and (eq (car rr) 'not-in-file)
8714 (buffer-file-name))
8715 (not (string-match (cdr rr) (buffer-file-name))))
8716 (when (eq (car rr) 'not-in-mode)
8717 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8718 (push r res)))
8719 (car (last r))))
8720 (delete-dups (delq nil res))))
8722 (defun org-context-p (&rest contexts)
8723 "Check if local context is any of CONTEXTS.
8724 Possible values in the list of contexts are `table', `headline', and `item'."
8725 (let ((pos (point)))
8726 (goto-char (point-at-bol))
8727 (prog1 (or (and (memq 'table contexts)
8728 (looking-at "[ \t]*|"))
8729 (and (memq 'headline contexts)
8730 (looking-at org-outline-regexp))
8731 (and (memq 'item contexts)
8732 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8733 (and (memq 'item-body contexts)
8734 (org-in-item-p)))
8735 (goto-char pos))))
8737 (defun org-get-local-variables ()
8738 "Return a list of all local variables in an Org mode buffer."
8739 (let (varlist)
8740 (with-current-buffer (get-buffer-create "*Org tmp*")
8741 (erase-buffer)
8742 (org-mode)
8743 (setq varlist (buffer-local-variables)))
8744 (kill-buffer "*Org tmp*")
8745 (delq nil
8746 (mapcar
8747 (lambda (x)
8748 (setq x
8749 (if (symbolp x)
8750 (list x)
8751 (list (car x) (list 'quote (cdr x)))))
8752 (if (string-match
8753 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8754 (symbol-name (car x)))
8755 x nil))
8756 varlist))))
8758 (defun org-clone-local-variables (from-buffer &optional regexp)
8759 "Clone local variables from FROM-BUFFER.
8760 Optional argument REGEXP selects variables to clone."
8761 (mapc
8762 (lambda (pair)
8763 (and (symbolp (car pair))
8764 (or (null regexp)
8765 (string-match regexp (symbol-name (car pair))))
8766 (set (make-local-variable (car pair))
8767 (cdr pair))))
8768 (buffer-local-variables from-buffer)))
8770 ;;;###autoload
8771 (defun org-run-like-in-org-mode (cmd)
8772 "Run a command, pretending that the current buffer is in Org-mode.
8773 This will temporarily bind local variables that are typically bound in
8774 Org-mode to the values they have in Org-mode, and then interactively
8775 call CMD."
8776 (org-load-modules-maybe)
8777 (unless org-local-vars
8778 (setq org-local-vars (org-get-local-variables)))
8779 (eval (list 'let org-local-vars
8780 (list 'call-interactively (list 'quote cmd)))))
8782 ;;;; Archiving
8784 (defun org-get-category (&optional pos force-refresh)
8785 "Get the category applying to position POS."
8786 (save-match-data
8787 (if force-refresh (org-refresh-category-properties))
8788 (let ((pos (or pos (point))))
8789 (or (get-text-property pos 'org-category)
8790 (progn (org-refresh-category-properties)
8791 (get-text-property pos 'org-category))))))
8793 (defun org-refresh-category-properties ()
8794 "Refresh category text properties in the buffer."
8795 (let ((case-fold-search t)
8796 (inhibit-read-only t)
8797 (def-cat (cond
8798 ((null org-category)
8799 (if buffer-file-name
8800 (file-name-sans-extension
8801 (file-name-nondirectory buffer-file-name))
8802 "???"))
8803 ((symbolp org-category) (symbol-name org-category))
8804 (t org-category)))
8805 beg end cat pos optionp)
8806 (org-unmodified
8807 (save-excursion
8808 (save-restriction
8809 (widen)
8810 (goto-char (point-min))
8811 (put-text-property (point) (point-max) 'org-category def-cat)
8812 (while (re-search-forward
8813 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8814 (setq pos (match-end 0)
8815 optionp (equal (char-after (match-beginning 0)) ?#)
8816 cat (org-trim (match-string 2)))
8817 (if optionp
8818 (setq beg (point-at-bol) end (point-max))
8819 (org-back-to-heading t)
8820 (setq beg (point) end (org-end-of-subtree t t)))
8821 (put-text-property beg end 'org-category cat)
8822 (put-text-property beg end 'org-category-position beg)
8823 (goto-char pos)))))))
8826 ;;;; Link Stuff
8828 ;;; Link abbreviations
8830 (defun org-link-expand-abbrev (link)
8831 "Apply replacements as defined in `org-link-abbrev-alist'."
8832 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8833 (let* ((key (match-string 1 link))
8834 (as (or (assoc key org-link-abbrev-alist-local)
8835 (assoc key org-link-abbrev-alist)))
8836 (tag (and (match-end 2) (match-string 3 link)))
8837 rpl)
8838 (if (not as)
8839 link
8840 (setq rpl (cdr as))
8841 (cond
8842 ((symbolp rpl) (funcall rpl tag))
8843 ((string-match "%(\\([^)]+\\))" rpl)
8844 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8845 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8846 ((string-match "%h" rpl)
8847 (replace-match (url-hexify-string (or tag "")) t t rpl))
8848 (t (concat rpl tag)))))
8849 link))
8851 ;;; Storing and inserting links
8853 (defvar org-insert-link-history nil
8854 "Minibuffer history for links inserted with `org-insert-link'.")
8856 (defvar org-stored-links nil
8857 "Contains the links stored with `org-store-link'.")
8859 (defvar org-store-link-plist nil
8860 "Plist with info about the most recently link created with `org-store-link'.")
8862 (defvar org-link-protocols nil
8863 "Link protocols added to Org-mode using `org-add-link-type'.")
8865 (defvar org-store-link-functions nil
8866 "List of functions that are called to create and store a link.
8867 Each function will be called in turn until one returns a non-nil
8868 value. Each function should check if it is responsible for creating
8869 this link (for example by looking at the major mode).
8870 If not, it must exit and return nil.
8871 If yes, it should return a non-nil value after a calling
8872 `org-store-link-props' with a list of properties and values.
8873 Special properties are:
8875 :type The link prefix, like \"http\". This must be given.
8876 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8877 This is obligatory as well.
8878 :description Optional default description for the second pair
8879 of brackets in an Org-mode link. The user can still change
8880 this when inserting this link into an Org-mode buffer.
8882 In addition to these, any additional properties can be specified
8883 and then used in capture templates.")
8885 (defun org-add-link-type (type &optional follow export)
8886 "Add TYPE to the list of `org-link-types'.
8887 Re-compute all regular expressions depending on `org-link-types'
8889 FOLLOW and EXPORT are two functions.
8891 FOLLOW should take the link path as the single argument and do whatever
8892 is necessary to follow the link, for example find a file or display
8893 a mail message.
8895 EXPORT should format the link path for export to one of the export formats.
8896 It should be a function accepting three arguments:
8898 path the path of the link, the text after the prefix (like \"http:\")
8899 desc the description of the link, if any, or a description added by
8900 org-export-normalize-links if there is none
8901 format the export format, a symbol like `html' or `latex' or `ascii'..
8903 The function may use the FORMAT information to return different values
8904 depending on the format. The return value will be put literally into
8905 the exported file. If the return value is nil, this means Org should
8906 do what it normally does with links which do not have EXPORT defined.
8908 Org-mode has a built-in default for exporting links. If you are happy with
8909 this default, there is no need to define an export function for the link
8910 type. For a simple example of an export function, see `org-bbdb.el'."
8911 (add-to-list 'org-link-types type t)
8912 (org-make-link-regexps)
8913 (if (assoc type org-link-protocols)
8914 (setcdr (assoc type org-link-protocols) (list follow export))
8915 (push (list type follow export) org-link-protocols)))
8917 (defvar org-agenda-buffer-name)
8919 ;;;###autoload
8920 (defun org-store-link (arg)
8921 "\\<org-mode-map>Store an org-link to the current location.
8922 This link is added to `org-stored-links' and can later be inserted
8923 into an org-buffer with \\[org-insert-link].
8925 For some link types, a prefix arg is interpreted:
8926 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8927 For file links, arg negates `org-context-in-file-links'."
8928 (interactive "P")
8929 (org-load-modules-maybe)
8930 (setq org-store-link-plist nil) ; reset
8931 (org-with-limited-levels
8932 (let (link cpltxt desc description search txt custom-id agenda-link)
8933 (cond
8935 ((run-hook-with-args-until-success 'org-store-link-functions)
8936 (setq link (plist-get org-store-link-plist :link)
8937 desc (or (plist-get org-store-link-plist :description) link)))
8939 ((org-src-edit-buffer-p)
8940 (let (label gc)
8941 (while (or (not label)
8942 (save-excursion
8943 (save-restriction
8944 (widen)
8945 (goto-char (point-min))
8946 (re-search-forward
8947 (regexp-quote (format org-coderef-label-format label))
8948 nil t))))
8949 (when label (message "Label exists already") (sit-for 2))
8950 (setq label (read-string "Code line label: " label)))
8951 (end-of-line 1)
8952 (setq link (format org-coderef-label-format label))
8953 (setq gc (- 79 (length link)))
8954 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8955 (insert link)
8956 (setq link (concat "(" label ")") desc nil)))
8958 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8959 ;; We are in the agenda, link to referenced location
8960 (let ((m (or (get-text-property (point) 'org-hd-marker)
8961 (get-text-property (point) 'org-marker))))
8962 (when m
8963 (org-with-point-at m
8964 (setq agenda-link
8965 (if (org-called-interactively-p 'any)
8966 (call-interactively 'org-store-link)
8967 (org-store-link nil)))))))
8969 ((eq major-mode 'calendar-mode)
8970 (let ((cd (calendar-cursor-to-date)))
8971 (setq link
8972 (format-time-string
8973 (car org-time-stamp-formats)
8974 (apply 'encode-time
8975 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8976 nil nil nil))))
8977 (org-store-link-props :type "calendar" :date cd)))
8979 ((eq major-mode 'help-mode)
8980 (setq link (concat "help:" (save-excursion
8981 (goto-char (point-min))
8982 (looking-at "^[^ ]+")
8983 (match-string 0))))
8984 (org-store-link-props :type "help"))
8986 ((eq major-mode 'w3-mode)
8987 (setq cpltxt (if (and (buffer-name)
8988 (not (string-match "Untitled" (buffer-name))))
8989 (buffer-name)
8990 (url-view-url t))
8991 link (url-view-url t))
8992 (org-store-link-props :type "w3" :url (url-view-url t)))
8994 ((eq major-mode 'w3m-mode)
8995 (setq cpltxt (or w3m-current-title w3m-current-url)
8996 link w3m-current-url)
8997 (org-store-link-props :type "w3m" :url (url-view-url t)))
8999 ((setq search (run-hook-with-args-until-success
9000 'org-create-file-search-functions))
9001 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9002 "::" search))
9003 (setq cpltxt (or description link)))
9005 ((eq major-mode 'image-mode)
9006 (setq cpltxt (concat "file:"
9007 (abbreviate-file-name buffer-file-name))
9008 link cpltxt)
9009 (org-store-link-props :type "image" :file buffer-file-name))
9011 ((eq major-mode 'dired-mode)
9012 ;; link to the file in the current line
9013 (let ((file (dired-get-filename nil t)))
9014 (setq file (if file
9015 (abbreviate-file-name
9016 (expand-file-name (dired-get-filename nil t)))
9017 ;; otherwise, no file so use current directory.
9018 default-directory))
9019 (setq cpltxt (concat "file:" file)
9020 link cpltxt)))
9022 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9023 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9024 (cond
9025 ((org-in-regexp "<<\\(.*?\\)>>")
9026 (setq cpltxt
9027 (concat "file:"
9028 (abbreviate-file-name
9029 (buffer-file-name (buffer-base-buffer)))
9030 "::" (match-string 1))
9031 link cpltxt))
9032 ((and (featurep 'org-id)
9033 (or (eq org-link-to-org-use-id t)
9034 (and (org-called-interactively-p 'any)
9035 (or (eq org-link-to-org-use-id 'create-if-interactive)
9036 (and (eq org-link-to-org-use-id
9037 'create-if-interactive-and-no-custom-id)
9038 (not custom-id))))
9039 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
9040 ;; We can make a link using the ID.
9041 (setq link (condition-case nil
9042 (prog1 (org-id-store-link)
9043 (setq desc (plist-get org-store-link-plist :description)))
9044 (error
9045 ;; probably before first headline, link to file only
9046 (concat "file:"
9047 (abbreviate-file-name
9048 (buffer-file-name (buffer-base-buffer))))))))
9050 ;; Just link to current headline
9051 (setq cpltxt (concat "file:"
9052 (abbreviate-file-name
9053 (buffer-file-name (buffer-base-buffer)))))
9054 ;; Add a context search string
9055 (when (org-xor org-context-in-file-links arg)
9056 (setq txt (cond
9057 ((org-at-heading-p) nil)
9058 ((org-region-active-p)
9059 (buffer-substring (region-beginning) (region-end)))))
9060 (when (or (null txt) (string-match "\\S-" txt))
9061 (setq cpltxt
9062 (concat cpltxt "::"
9063 (condition-case nil
9064 (org-make-org-heading-search-string txt)
9065 (error "")))
9066 desc (or (nth 4 (ignore-errors
9067 (org-heading-components))) "NONE"))))
9068 (if (string-match "::\\'" cpltxt)
9069 (setq cpltxt (substring cpltxt 0 -2)))
9070 (setq link cpltxt))))
9072 ((buffer-file-name (buffer-base-buffer))
9073 ;; Just link to this file here.
9074 (setq cpltxt (concat "file:"
9075 (abbreviate-file-name
9076 (buffer-file-name (buffer-base-buffer)))))
9077 ;; Add a context string
9078 (when (org-xor org-context-in-file-links arg)
9079 (setq txt (if (org-region-active-p)
9080 (buffer-substring (region-beginning) (region-end))
9081 (buffer-substring (point-at-bol) (point-at-eol))))
9082 ;; Only use search option if there is some text.
9083 (when (string-match "\\S-" txt)
9084 (setq cpltxt
9085 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9086 desc "NONE")))
9087 (setq link cpltxt))
9089 ((org-called-interactively-p 'interactive)
9090 (error "Cannot link to a buffer which is not visiting a file"))
9092 (t (setq link nil)))
9094 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9095 (setq link (or link cpltxt)
9096 desc (or desc cpltxt))
9097 (if (equal desc "NONE") (setq desc nil))
9099 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9100 (progn
9101 (setq org-stored-links
9102 (cons (list link desc) org-stored-links))
9103 (message "Stored: %s" (or desc link))
9104 (when custom-id
9105 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9106 "::#" custom-id))
9107 (setq org-stored-links
9108 (cons (list link desc) org-stored-links))))
9109 (or agenda-link (and link (org-make-link-string link desc)))))))
9111 (defun org-store-link-props (&rest plist)
9112 "Store link properties, extract names and addresses."
9113 (let (x adr)
9114 (when (setq x (plist-get plist :from))
9115 (setq adr (mail-extract-address-components x))
9116 (setq plist (plist-put plist :fromname (car adr)))
9117 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9118 (when (setq x (plist-get plist :to))
9119 (setq adr (mail-extract-address-components x))
9120 (setq plist (plist-put plist :toname (car adr)))
9121 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9122 (let ((from (plist-get plist :from))
9123 (to (plist-get plist :to)))
9124 (when (and from to org-from-is-user-regexp)
9125 (setq plist
9126 (plist-put plist :fromto
9127 (if (string-match org-from-is-user-regexp from)
9128 (concat "to %t")
9129 (concat "from %f"))))))
9130 (setq org-store-link-plist plist))
9132 (defun org-add-link-props (&rest plist)
9133 "Add these properties to the link property list."
9134 (let (key value)
9135 (while plist
9136 (setq key (pop plist) value (pop plist))
9137 (setq org-store-link-plist
9138 (plist-put org-store-link-plist key value)))))
9140 (defun org-email-link-description (&optional fmt)
9141 "Return the description part of an email link.
9142 This takes information from `org-store-link-plist' and formats it
9143 according to FMT (default from `org-email-link-description-format')."
9144 (setq fmt (or fmt org-email-link-description-format))
9145 (let* ((p org-store-link-plist)
9146 (to (plist-get p :toaddress))
9147 (from (plist-get p :fromaddress))
9148 (table
9149 (list
9150 (cons "%c" (plist-get p :fromto))
9151 (cons "%F" (plist-get p :from))
9152 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9153 (cons "%T" (plist-get p :to))
9154 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9155 (cons "%s" (plist-get p :subject))
9156 (cons "%d" (plist-get p :date))
9157 (cons "%m" (plist-get p :message-id)))))
9158 (when (string-match "%c" fmt)
9159 ;; Check if the user wrote this message
9160 (if (and org-from-is-user-regexp from to
9161 (save-match-data (string-match org-from-is-user-regexp from)))
9162 (setq fmt (replace-match "to %t" t t fmt))
9163 (setq fmt (replace-match "from %f" t t fmt))))
9164 (org-replace-escapes fmt table)))
9166 (defun org-make-org-heading-search-string (&optional string heading)
9167 "Make search string for STRING or current headline."
9168 (interactive)
9169 (let ((s (or string (org-get-heading)))
9170 (lines org-context-in-file-links))
9171 (unless (and string (not heading))
9172 ;; We are using a headline, clean up garbage in there.
9173 (if (string-match org-todo-regexp s)
9174 (setq s (replace-match "" t t s)))
9175 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9176 (setq s (replace-match "" t t s)))
9177 (setq s (org-trim s))
9178 (if (string-match (concat "^\\(" org-quote-string "\\|"
9179 org-comment-string "\\)") s)
9180 (setq s (replace-match "" t t s)))
9181 (while (string-match org-ts-regexp s)
9182 (setq s (replace-match "" t t s))))
9183 (or string (setq s (concat "*" s))) ; Add * for headlines
9184 (when (and string (integerp lines) (> lines 0))
9185 (let ((slines (org-split-string s "\n")))
9186 (when (< lines (length slines))
9187 (setq s (mapconcat
9188 'identity
9189 (reverse (nthcdr (- (length slines) lines)
9190 (reverse slines))) "\n")))))
9191 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9193 (defun org-make-link-string (link &optional description)
9194 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9195 (unless (string-match "\\S-" link)
9196 (error "Empty link"))
9197 (when (and description
9198 (stringp description)
9199 (not (string-match "\\S-" description)))
9200 (setq description nil))
9201 (when (stringp description)
9202 ;; Remove brackets from the description, they are fatal.
9203 (while (string-match "\\[" description)
9204 (setq description (replace-match "{" t t description)))
9205 (while (string-match "\\]" description)
9206 (setq description (replace-match "}" t t description))))
9207 (when (equal link description)
9208 ;; No description needed, it is identical
9209 (setq description nil))
9210 (when (and (not description)
9211 (not (string-match (org-image-file-name-regexp) link))
9212 (not (equal link (org-link-escape link))))
9213 (setq description (org-extract-attributes link)))
9214 (setq link
9215 (cond ((string-match (org-image-file-name-regexp) link) link)
9216 ((string-match org-link-types-re link)
9217 (concat (match-string 1 link)
9218 (org-link-escape (substring link (match-end 1)))))
9219 (t (org-link-escape link))))
9220 (concat "[[" link "]"
9221 (if description (concat "[" description "]") "")
9222 "]"))
9224 (defconst org-link-escape-chars
9225 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9226 "List of characters that should be escaped in link.
9227 This is the list that is used for internal purposes.")
9229 (defconst org-link-escape-chars-browser
9230 '(?\ )
9231 "List of escapes for characters that are problematic in links.
9232 This is the list that is used before handing over to the browser.")
9234 (defun org-link-escape (text &optional table merge)
9235 "Return percent escaped representation of TEXT.
9236 TEXT is a string with the text to escape.
9237 Optional argument TABLE is a list with characters that should be
9238 escaped. When nil, `org-link-escape-chars' is used.
9239 If optional argument MERGE is set, merge TABLE into
9240 `org-link-escape-chars'."
9241 (cond
9242 ((and table merge)
9243 (mapc (lambda (defchr)
9244 (unless (member defchr table)
9245 (setq table (cons defchr table)))) org-link-escape-chars))
9246 ((null table)
9247 (setq table org-link-escape-chars)))
9248 (mapconcat
9249 (lambda (char)
9250 (if (or (member char table)
9251 (and (or (< char 32) (= char 37) (> char 126))
9252 org-url-hexify-p))
9253 (mapconcat (lambda (sequence-element)
9254 (format "%%%.2X" sequence-element))
9255 (or (encode-coding-char char 'utf-8)
9256 (error "Unable to percent escape character: %s"
9257 (char-to-string char))) "")
9258 (char-to-string char))) text ""))
9260 (defun org-link-unescape (str)
9261 "Unhex hexified Unicode strings as returned from the JavaScript function
9262 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9263 (unless (and (null str) (string= "" str))
9264 (let ((pos 0) (case-fold-search t) unhexed)
9265 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9266 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9267 (setq str (replace-match unhexed t t str))
9268 (setq pos (+ pos (length unhexed))))))
9269 str)
9271 (defun org-link-unescape-compound (hex)
9272 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9273 Note: this function also decodes single byte encodings like
9274 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9275 (save-match-data
9276 (let* ((bytes (cdr (split-string hex "%")))
9277 (ret "")
9278 (eat 0)
9279 (sum 0))
9280 (while bytes
9281 (let* ((val (string-to-number (pop bytes) 16))
9282 (shift-xor
9283 (if (= 0 eat)
9284 (cond
9285 ((>= val 252) (cons 6 252))
9286 ((>= val 248) (cons 5 248))
9287 ((>= val 240) (cons 4 240))
9288 ((>= val 224) (cons 3 224))
9289 ((>= val 192) (cons 2 192))
9290 (t (cons 0 0)))
9291 (cons 6 128))))
9292 (if (>= val 192) (setq eat (car shift-xor)))
9293 (setq val (logxor val (cdr shift-xor)))
9294 (setq sum (+ (lsh sum (car shift-xor)) val))
9295 (if (> eat 0) (setq eat (- eat 1)))
9296 (cond
9297 ((= 0 eat) ;multi byte
9298 (setq ret (concat ret (org-char-to-string sum)))
9299 (setq sum 0))
9300 ((not bytes) ; single byte(s)
9301 (setq ret (org-link-unescape-single-byte-sequence hex))))
9302 )) ;; end (while bytes
9303 ret )))
9305 (defun org-link-unescape-single-byte-sequence (hex)
9306 "Unhexify hex-encoded single byte character sequences."
9307 (mapconcat (lambda (byte)
9308 (char-to-string (string-to-number byte 16)))
9309 (cdr (split-string hex "%")) ""))
9311 (defun org-xor (a b)
9312 "Exclusive or."
9313 (if a (not b) b))
9315 (defun org-fixup-message-id-for-http (s)
9316 "Replace special characters in a message id, so it can be used in an http query."
9317 (when (string-match "%" s)
9318 (setq s (mapconcat (lambda (c)
9319 (if (eq c ?%)
9320 "%25"
9321 (char-to-string c)))
9322 s "")))
9323 (while (string-match "<" s)
9324 (setq s (replace-match "%3C" t t s)))
9325 (while (string-match ">" s)
9326 (setq s (replace-match "%3E" t t s)))
9327 (while (string-match "@" s)
9328 (setq s (replace-match "%40" t t s)))
9331 (defun org-link-prettify (link)
9332 "Return a human-readable representation of LINK.
9333 The car of LINK must be a raw link the cdr of LINK must be either
9334 a link description or nil."
9335 (let ((desc (or (cadr link) "<no description>")))
9336 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9337 "<" (car link) ">")))
9339 ;;;###autoload
9340 (defun org-insert-link-global ()
9341 "Insert a link like Org-mode does.
9342 This command can be called in any mode to insert a link in Org-mode syntax."
9343 (interactive)
9344 (org-load-modules-maybe)
9345 (org-run-like-in-org-mode 'org-insert-link))
9347 (defun org-insert-all-links (&optional keep)
9348 "Insert all links in `org-stored-links'."
9349 (interactive "P")
9350 (let ((links (copy-sequence org-stored-links)) l)
9351 (while (setq l (if keep (pop links) (pop org-stored-links)))
9352 (insert "- ")
9353 (org-insert-link nil (car l) (cadr l))
9354 (insert "\n"))))
9356 (defun org-link-fontify-links-to-this-file ()
9357 "Fontify links to the current file in `org-stored-links'."
9358 (let ((f (buffer-file-name)) a b)
9359 (setq a (mapcar (lambda(l)
9360 (let ((ll (car l)))
9361 (when (and (string-match "^file:\\(.+\\)::" ll)
9362 (equal f (expand-file-name (match-string 1 ll))))
9363 ll)))
9364 org-stored-links))
9365 (when (featurep 'org-id)
9366 (setq b (mapcar (lambda(l)
9367 (let ((ll (car l)))
9368 (when (and (string-match "^id:\\(.+\\)$" ll)
9369 (equal f (expand-file-name
9370 (or (org-id-find-id-file
9371 (match-string 1 ll)) ""))))
9372 ll)))
9373 org-stored-links)))
9374 (mapcar (lambda(l)
9375 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9376 (delq nil (append a b)))))
9378 (defvar org-link-links-in-this-file nil)
9379 (defun org-insert-link (&optional complete-file link-location default-description)
9380 "Insert a link. At the prompt, enter the link.
9382 Completion can be used to insert any of the link protocol prefixes like
9383 http or ftp in use.
9385 The history can be used to select a link previously stored with
9386 `org-store-link'. When the empty string is entered (i.e. if you just
9387 press RET at the prompt), the link defaults to the most recently
9388 stored link. As SPC triggers completion in the minibuffer, you need to
9389 use M-SPC or C-q SPC to force the insertion of a space character.
9391 You will also be prompted for a description, and if one is given, it will
9392 be displayed in the buffer instead of the link.
9394 If there is already a link at point, this command will allow you to edit link
9395 and description parts.
9397 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9398 be selected using completion. The path to the file will be relative to the
9399 current directory if the file is in the current directory or a subdirectory.
9400 Otherwise, the link will be the absolute path as completed in the minibuffer
9401 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9402 option `org-link-file-path-type'.
9404 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9405 the current directory or below.
9407 With three \\[universal-argument] prefixes, negate the meaning of
9408 `org-keep-stored-link-after-insertion'.
9410 If `org-make-link-description-function' is non-nil, this function will be
9411 called with the link target, and the result will be the default
9412 link description.
9414 If the LINK-LOCATION parameter is non-nil, this value will be
9415 used as the link location instead of reading one interactively.
9417 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9418 be used as the default description."
9419 (interactive "P")
9420 (let* ((wcf (current-window-configuration))
9421 (origbuf (current-buffer))
9422 (region (if (org-region-active-p)
9423 (buffer-substring (region-beginning) (region-end))))
9424 (remove (and region (list (region-beginning) (region-end))))
9425 (desc region)
9426 tmphist ; byte-compile incorrectly complains about this
9427 (link link-location)
9428 (abbrevs org-link-abbrev-alist-local)
9429 entry file all-prefixes auto-desc)
9430 (cond
9431 (link-location) ; specified by arg, just use it.
9432 ((org-in-regexp org-bracket-link-regexp 1)
9433 ;; We do have a link at point, and we are going to edit it.
9434 (setq remove (list (match-beginning 0) (match-end 0)))
9435 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9436 (setq link (read-string "Link: "
9437 (org-link-unescape
9438 (org-match-string-no-properties 1)))))
9439 ((or (org-in-regexp org-angle-link-re)
9440 (org-in-regexp org-plain-link-re))
9441 ;; Convert to bracket link
9442 (setq remove (list (match-beginning 0) (match-end 0))
9443 link (read-string "Link: "
9444 (org-remove-angle-brackets (match-string 0)))))
9445 ((member complete-file '((4) (16)))
9446 ;; Completing read for file names.
9447 (setq link (org-file-complete-link complete-file)))
9449 ;; Read link, with completion for stored links.
9450 (org-link-fontify-links-to-this-file)
9451 (org-switch-to-buffer-other-window "*Org Links*")
9452 (with-current-buffer "*Org Links*"
9453 (erase-buffer)
9454 (insert "Insert a link.
9455 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9456 (when org-stored-links
9457 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9458 (insert (mapconcat 'org-link-prettify
9459 (reverse org-stored-links) "\n")))
9460 (goto-char (point-min)))
9461 (let ((cw (selected-window)))
9462 (select-window (get-buffer-window "*Org Links*" 'visible))
9463 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9464 (unless (pos-visible-in-window-p (point-max))
9465 (org-fit-window-to-buffer))
9466 (and (window-live-p cw) (select-window cw)))
9467 ;; Fake a link history, containing the stored links.
9468 (setq tmphist (append (mapcar 'car org-stored-links)
9469 org-insert-link-history))
9470 (setq all-prefixes (append (mapcar 'car abbrevs)
9471 (mapcar 'car org-link-abbrev-alist)
9472 org-link-types))
9473 (unwind-protect
9474 (progn
9475 (setq link
9476 (let ((org-completion-use-ido nil)
9477 (org-completion-use-iswitchb nil))
9478 (org-completing-read
9479 "Link: "
9480 (append
9481 (mapcar (lambda (x) (list (concat x ":")))
9482 all-prefixes)
9483 (mapcar 'car org-stored-links)
9484 (mapcar 'cadr org-stored-links))
9485 nil nil nil
9486 'tmphist
9487 (caar org-stored-links))))
9488 (if (not (string-match "\\S-" link))
9489 (error "No link selected"))
9490 (mapc (lambda(l)
9491 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9492 org-stored-links)
9493 (if (or (member link all-prefixes)
9494 (and (equal ":" (substring link -1))
9495 (member (substring link 0 -1) all-prefixes)
9496 (setq link (substring link 0 -1))))
9497 (setq link (with-current-buffer origbuf
9498 (org-link-try-special-completion link)))))
9499 (set-window-configuration wcf)
9500 (kill-buffer "*Org Links*"))
9501 (setq entry (assoc link org-stored-links))
9502 (or entry (push link org-insert-link-history))
9503 (setq desc (or desc (nth 1 entry)))))
9505 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9506 (not org-keep-stored-link-after-insertion))
9507 (setq org-stored-links (delq (assoc link org-stored-links)
9508 org-stored-links)))
9510 (if (string-match org-plain-link-re link)
9511 ;; URL-like link, normalize the use of angular brackets.
9512 (setq link (org-remove-angle-brackets link)))
9514 ;; Check if we are linking to the current file with a search option
9515 ;; If yes, simplify the link by using only the search option.
9516 (when (and buffer-file-name
9517 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9518 (let* ((path (match-string 1 link))
9519 (case-fold-search nil)
9520 (search (match-string 2 link)))
9521 (save-match-data
9522 (if (equal (file-truename buffer-file-name) (file-truename path))
9523 ;; We are linking to this same file, with a search option
9524 (setq link search)))))
9526 ;; Check if we can/should use a relative path. If yes, simplify the link
9527 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9528 (let* ((type (match-string 1 link))
9529 (path (match-string 2 link))
9530 (origpath path)
9531 (case-fold-search nil))
9532 (cond
9533 ((or (eq org-link-file-path-type 'absolute)
9534 (equal complete-file '(16)))
9535 (setq path (abbreviate-file-name (expand-file-name path))))
9536 ((eq org-link-file-path-type 'noabbrev)
9537 (setq path (expand-file-name path)))
9538 ((eq org-link-file-path-type 'relative)
9539 (setq path (file-relative-name path)))
9541 (save-match-data
9542 (if (string-match (concat "^" (regexp-quote
9543 (expand-file-name
9544 (file-name-as-directory
9545 default-directory))))
9546 (expand-file-name path))
9547 ;; We are linking a file with relative path name.
9548 (setq path (substring (expand-file-name path)
9549 (match-end 0)))
9550 (setq path (abbreviate-file-name (expand-file-name path)))))))
9551 (setq link (concat type path))
9552 (if (equal desc origpath)
9553 (setq desc path))))
9555 (if org-make-link-description-function
9556 (setq desc (funcall org-make-link-description-function link desc))
9557 (if default-description (setq desc default-description)
9558 (setq desc (or (and auto-desc desc)
9559 (read-string "Description: " desc)))))
9561 (unless (string-match "\\S-" desc) (setq desc nil))
9562 (if remove (apply 'delete-region remove))
9563 (insert (org-make-link-string link desc))))
9565 (defun org-link-try-special-completion (type)
9566 "If there is completion support for link type TYPE, offer it."
9567 (let ((fun (intern (concat "org-" type "-complete-link"))))
9568 (if (functionp fun)
9569 (funcall fun)
9570 (read-string "Link (no completion support): " (concat type ":")))))
9572 (defun org-file-complete-link (&optional arg)
9573 "Create a file link using completion."
9574 (let (file link)
9575 (setq file (read-file-name "File: "))
9576 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9577 (pwd1 (file-name-as-directory (abbreviate-file-name
9578 (expand-file-name ".")))))
9579 (cond
9580 ((equal arg '(16))
9581 (setq link (concat
9582 "file:"
9583 (abbreviate-file-name (expand-file-name file)))))
9584 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9585 (setq link (concat "file:" (match-string 1 file))))
9586 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9587 (expand-file-name file))
9588 (setq link (concat
9589 "file:" (match-string 1 (expand-file-name file)))))
9590 (t (setq link (concat "file:" file)))))
9591 link))
9593 (defun org-completing-read (&rest args)
9594 "Completing-read with SPACE being a normal character."
9595 (let ((enable-recursive-minibuffers t)
9596 (minibuffer-local-completion-map
9597 (copy-keymap minibuffer-local-completion-map)))
9598 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9599 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9600 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9601 (apply 'org-icompleting-read args)))
9603 (defun org-completing-read-no-i (&rest args)
9604 (let (org-completion-use-ido org-completion-use-iswitchb)
9605 (apply 'org-completing-read args)))
9607 (defun org-iswitchb-completing-read (prompt choices &rest args)
9608 "Use iswitch as a completing-read replacement to choose from choices.
9609 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9610 from."
9611 (let* ((iswitchb-use-virtual-buffers nil)
9612 (iswitchb-make-buflist-hook
9613 (lambda ()
9614 (setq iswitchb-temp-buflist choices))))
9615 (iswitchb-read-buffer prompt)))
9617 (defun org-icompleting-read (&rest args)
9618 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9619 (org-without-partial-completion
9620 (if (and org-completion-use-ido
9621 (fboundp 'ido-completing-read)
9622 (boundp 'ido-mode) ido-mode
9623 (listp (second args)))
9624 (let ((ido-enter-matching-directory nil))
9625 (apply 'ido-completing-read (concat (car args))
9626 (if (consp (car (nth 1 args)))
9627 (mapcar 'car (nth 1 args))
9628 (nth 1 args))
9629 (cddr args)))
9630 (if (and org-completion-use-iswitchb
9631 (boundp 'iswitchb-mode) iswitchb-mode
9632 (listp (second args)))
9633 (apply 'org-iswitchb-completing-read (concat (car args))
9634 (if (consp (car (nth 1 args)))
9635 (mapcar 'car (nth 1 args))
9636 (nth 1 args))
9637 (cddr args))
9638 (apply 'completing-read args)))))
9640 (defun org-extract-attributes (s)
9641 "Extract the attributes cookie from a string and set as text property."
9642 (let (a attr (start 0) key value)
9643 (save-match-data
9644 (when (string-match "{{\\([^}]+\\)}}$" s)
9645 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9646 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9647 (setq key (match-string 1 a) value (match-string 2 a)
9648 start (match-end 0)
9649 attr (plist-put attr (intern key) value))))
9650 (org-add-props s nil 'org-attr attr))
9653 (defun org-extract-attributes-from-string (tag)
9654 (let (key value attr)
9655 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9656 (setq key (match-string 1 tag) value (match-string 2 tag)
9657 tag (replace-match "" t t tag)
9658 attr (plist-put attr (intern key) value)))
9659 (cons tag attr)))
9661 (defun org-attributes-to-string (plist)
9662 "Format a property list into an HTML attribute list."
9663 (let ((s "") key value)
9664 (while plist
9665 (setq key (pop plist) value (pop plist))
9666 (and value
9667 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9670 ;;; Opening/following a link
9672 (defvar org-link-search-failed nil)
9674 (defvar org-open-link-functions nil
9675 "Hook for functions finding a plain text link.
9676 These functions must take a single argument, the link content.
9677 They will be called for links that look like [[link text][description]]
9678 when LINK TEXT does not have a protocol like \"http:\" and does not look
9679 like a filename (e.g. \"./blue.png\").
9681 These functions will be called *before* Org attempts to resolve the
9682 link by doing text searches in the current buffer - so if you want a
9683 link \"[[target]]\" to still find \"<<target>>\", your function should
9684 handle this as a special case.
9686 When the function does handle the link, it must return a non-nil value.
9687 If it decides that it is not responsible for this link, it must return
9688 nil to indicate that that Org-mode can continue with other options
9689 like exact and fuzzy text search.")
9691 (defun org-next-link ()
9692 "Move forward to the next link.
9693 If the link is in hidden text, expose it."
9694 (interactive)
9695 (when (and org-link-search-failed (eq this-command last-command))
9696 (goto-char (point-min))
9697 (message "Link search wrapped back to beginning of buffer"))
9698 (setq org-link-search-failed nil)
9699 (let* ((pos (point))
9700 (ct (org-context))
9701 (a (assoc :link ct)))
9702 (if a (goto-char (nth 2 a)))
9703 (if (re-search-forward org-any-link-re nil t)
9704 (progn
9705 (goto-char (match-beginning 0))
9706 (if (outline-invisible-p) (org-show-context)))
9707 (goto-char pos)
9708 (setq org-link-search-failed t)
9709 (error "No further link found"))))
9711 (defun org-previous-link ()
9712 "Move backward to the previous link.
9713 If the link is in hidden text, expose it."
9714 (interactive)
9715 (when (and org-link-search-failed (eq this-command last-command))
9716 (goto-char (point-max))
9717 (message "Link search wrapped back to end of buffer"))
9718 (setq org-link-search-failed nil)
9719 (let* ((pos (point))
9720 (ct (org-context))
9721 (a (assoc :link ct)))
9722 (if a (goto-char (nth 1 a)))
9723 (if (re-search-backward org-any-link-re nil t)
9724 (progn
9725 (goto-char (match-beginning 0))
9726 (if (outline-invisible-p) (org-show-context)))
9727 (goto-char pos)
9728 (setq org-link-search-failed t)
9729 (error "No further link found"))))
9731 (defun org-translate-link (s)
9732 "Translate a link string if a translation function has been defined."
9733 (if (and org-link-translation-function
9734 (fboundp org-link-translation-function)
9735 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9736 (progn
9737 (setq s (funcall org-link-translation-function
9738 (match-string 1 s) (match-string 2 s)))
9739 (concat (car s) ":" (cdr s)))
9742 (defun org-translate-link-from-planner (type path)
9743 "Translate a link from Emacs Planner syntax so that Org can follow it.
9744 This is still an experimental function, your mileage may vary."
9745 (cond
9746 ((member type '("http" "https" "news" "ftp"))
9747 ;; standard Internet links are the same.
9748 nil)
9749 ((and (equal type "irc") (string-match "^//" path))
9750 ;; Planner has two / at the beginning of an irc link, we have 1.
9751 ;; We should have zero, actually....
9752 (setq path (substring path 1)))
9753 ((and (equal type "lisp") (string-match "^/" path))
9754 ;; Planner has a slash, we do not.
9755 (setq type "elisp" path (substring path 1)))
9756 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9757 ;; A typical message link. Planner has the id after the final slash,
9758 ;; we separate it with a hash mark
9759 (setq path (concat (match-string 1 path) "#"
9760 (org-remove-angle-brackets (match-string 2 path)))))
9762 (cons type path))
9764 (defun org-find-file-at-mouse (ev)
9765 "Open file link or URL at mouse."
9766 (interactive "e")
9767 (mouse-set-point ev)
9768 (org-open-at-point 'in-emacs))
9770 (defun org-open-at-mouse (ev)
9771 "Open file link or URL at mouse.
9772 See the docstring of `org-open-file' for details."
9773 (interactive "e")
9774 (mouse-set-point ev)
9775 (if (eq major-mode 'org-agenda-mode)
9776 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9777 (org-open-at-point))
9779 (defvar org-window-config-before-follow-link nil
9780 "The window configuration before following a link.
9781 This is saved in case the need arises to restore it.")
9783 (defvar org-open-link-marker (make-marker)
9784 "Marker pointing to the location where `org-open-at-point; was called.")
9786 ;;;###autoload
9787 (defun org-open-at-point-global ()
9788 "Follow a link like Org-mode does.
9789 This command can be called in any mode to follow a link that has
9790 Org-mode syntax."
9791 (interactive)
9792 (org-run-like-in-org-mode 'org-open-at-point))
9794 ;;;###autoload
9795 (defun org-open-link-from-string (s &optional arg reference-buffer)
9796 "Open a link in the string S, as if it was in Org-mode."
9797 (interactive "sLink: \nP")
9798 (let ((reference-buffer (or reference-buffer (current-buffer))))
9799 (with-temp-buffer
9800 (let ((org-inhibit-startup (not reference-buffer)))
9801 (org-mode)
9802 (insert s)
9803 (goto-char (point-min))
9804 (when reference-buffer
9805 (setq org-link-abbrev-alist-local
9806 (with-current-buffer reference-buffer
9807 org-link-abbrev-alist-local)))
9808 (org-open-at-point arg reference-buffer)))))
9810 (defvar org-open-at-point-functions nil
9811 "Hook that is run when following a link at point.
9813 Functions in this hook must return t if they identify and follow
9814 a link at point. If they don't find anything interesting at point,
9815 they must return nil.")
9817 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9818 (defun org-open-at-point (&optional arg reference-buffer)
9819 "Open link at or after point.
9820 If there is no link at point, this function will search forward up to
9821 the end of the current line.
9822 Normally, files will be opened by an appropriate application. If the
9823 optional prefix argument ARG is non-nil, Emacs will visit the file.
9824 With a double prefix argument, try to open outside of Emacs, in the
9825 application the system uses for this file type."
9826 (interactive "P")
9827 ;; if in a code block, then open the block's results
9828 (unless (call-interactively #'org-babel-open-src-block-result)
9829 (org-load-modules-maybe)
9830 (move-marker org-open-link-marker (point))
9831 (setq org-window-config-before-follow-link (current-window-configuration))
9832 (org-remove-occur-highlights nil nil t)
9833 (cond
9834 ((and (org-at-heading-p)
9835 (not (org-at-timestamp-p t))
9836 (not (org-in-regexp
9837 (concat org-plain-link-re "\\|"
9838 org-bracket-link-regexp "\\|"
9839 org-angle-link-re "\\|"
9840 "[ \t]:[^ \t\n]+:[ \t]*$")))
9841 (not (get-text-property (point) 'org-linked-text)))
9842 (or (org-offer-links-in-entry arg)
9843 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9844 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9845 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9846 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9847 (not (org-in-regexp org-bracket-link-regexp)))
9848 (org-footnote-action))
9850 (let (type path link line search (pos (point)))
9851 (catch 'match
9852 (save-excursion
9853 (skip-chars-forward "^]\n\r")
9854 (when (org-in-regexp org-bracket-link-regexp 1)
9855 (setq link (org-extract-attributes
9856 (org-link-unescape (org-match-string-no-properties 1))))
9857 (while (string-match " *\n *" link)
9858 (setq link (replace-match " " t t link)))
9859 (setq link (org-link-expand-abbrev link))
9860 (cond
9861 ((or (file-name-absolute-p link)
9862 (string-match "^\\.\\.?/" link))
9863 (setq type "file" path link))
9864 ((string-match org-link-re-with-space3 link)
9865 (setq type (match-string 1 link) path (match-string 2 link)))
9866 ((string-match "^help:+\\(.+\\)" link)
9867 (setq type "help" path (match-string 1 link)))
9868 (t (setq type "thisfile" path link)))
9869 (throw 'match t)))
9871 (when (get-text-property (point) 'org-linked-text)
9872 (setq type "thisfile"
9873 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9874 (1+ (point)) (point))
9875 path (buffer-substring
9876 (or (previous-single-property-change pos 'org-linked-text)
9877 (point-min))
9878 (or (next-single-property-change pos 'org-linked-text)
9879 (point-max))))
9880 (throw 'match t))
9882 (save-excursion
9883 (when (or (org-in-regexp org-angle-link-re)
9884 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9885 (save-match-data (not (looking-back "\\[\\[")))))
9886 (setq type (match-string 1)
9887 path (org-link-unescape (match-string 2)))
9888 (throw 'match t)))
9889 (save-excursion
9890 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9891 (setq type "tags"
9892 path (match-string 1))
9893 (while (string-match ":" path)
9894 (setq path (replace-match "+" t t path)))
9895 (throw 'match t)))
9896 (when (org-in-regexp "<\\([^><\n]+\\)>")
9897 (setq type "tree-match"
9898 path (match-string 1))
9899 (throw 'match t)))
9900 (unless path
9901 (error "No link found"))
9903 ;; switch back to reference buffer
9904 ;; needed when if called in a temporary buffer through
9905 ;; org-open-link-from-string
9906 (with-current-buffer (or reference-buffer (current-buffer))
9908 ;; Remove any trailing spaces in path
9909 (if (string-match " +\\'" path)
9910 (setq path (replace-match "" t t path)))
9911 (if (and org-link-translation-function
9912 (fboundp org-link-translation-function))
9913 ;; Check if we need to translate the link
9914 (let ((tmp (funcall org-link-translation-function type path)))
9915 (setq type (car tmp) path (cdr tmp))))
9917 (cond
9919 ((assoc type org-link-protocols)
9920 (funcall (nth 1 (assoc type org-link-protocols)) path))
9922 ((equal type "help")
9923 (let ((f-or-v (intern path)))
9924 (cond ((fboundp f-or-v)
9925 (describe-function f-or-v))
9926 ((boundp f-or-v)
9927 (describe-variable f-or-v))
9928 (t (error "Not a known function or variable")))))
9930 ((equal type "mailto")
9931 (let ((cmd (car org-link-mailto-program))
9932 (args (cdr org-link-mailto-program)) args1
9933 (address path) (subject "") a)
9934 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9935 (setq address (match-string 1 path)
9936 subject (org-link-escape (match-string 2 path))))
9937 (while args
9938 (cond
9939 ((not (stringp (car args))) (push (pop args) args1))
9940 (t (setq a (pop args))
9941 (if (string-match "%a" a)
9942 (setq a (replace-match address t t a)))
9943 (if (string-match "%s" a)
9944 (setq a (replace-match subject t t a)))
9945 (push a args1))))
9946 (apply cmd (nreverse args1))))
9948 ((member type '("http" "https" "ftp" "news"))
9949 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9950 (org-link-escape
9951 path org-link-escape-chars-browser)
9952 path))))
9954 ((string= type "doi")
9955 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9956 (org-link-escape
9957 path org-link-escape-chars-browser)
9958 path))))
9960 ((member type '("message"))
9961 (browse-url (concat type ":" path)))
9963 ((string= type "tags")
9964 (org-tags-view arg path))
9966 ((string= type "tree-match")
9967 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9969 ((string= type "file")
9970 (if (string-match "::\\([0-9]+\\)\\'" path)
9971 (setq line (string-to-number (match-string 1 path))
9972 path (substring path 0 (match-beginning 0)))
9973 (if (string-match "::\\(.+\\)\\'" path)
9974 (setq search (match-string 1 path)
9975 path (substring path 0 (match-beginning 0)))))
9976 (if (string-match "[*?{]" (file-name-nondirectory path))
9977 (dired path)
9978 (org-open-file path arg line search)))
9980 ((string= type "shell")
9981 (let ((buf (generate-new-buffer "*Org Shell Output"))
9982 (cmd path))
9983 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9984 (string-match org-confirm-shell-link-not-regexp cmd))
9985 (not org-confirm-shell-link-function)
9986 (funcall org-confirm-shell-link-function
9987 (format "Execute \"%s\" in shell? "
9988 (org-add-props cmd nil
9989 'face 'org-warning))))
9990 (progn
9991 (message "Executing %s" cmd)
9992 (shell-command cmd buf)
9993 (if (featurep 'midnight)
9994 (setq clean-buffer-list-kill-buffer-names
9995 (cons buf clean-buffer-list-kill-buffer-names))))
9996 (error "Abort"))))
9998 ((string= type "elisp")
9999 (let ((cmd path))
10000 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10001 (string-match org-confirm-elisp-link-not-regexp cmd))
10002 (not org-confirm-elisp-link-function)
10003 (funcall org-confirm-elisp-link-function
10004 (format "Execute \"%s\" as elisp? "
10005 (org-add-props cmd nil
10006 'face 'org-warning))))
10007 (message "%s => %s" cmd
10008 (if (equal (string-to-char cmd) ?\()
10009 (eval (read cmd))
10010 (call-interactively (read cmd))))
10011 (error "Abort"))))
10013 ((and (string= type "thisfile")
10014 (run-hook-with-args-until-success
10015 'org-open-link-functions path)))
10017 ((string= type "thisfile")
10018 (if arg
10019 (switch-to-buffer-other-window
10020 (org-get-buffer-for-internal-link (current-buffer)))
10021 (org-mark-ring-push))
10022 (let ((cmd `(org-link-search
10023 ,path
10024 ,(cond ((equal arg '(4)) ''occur)
10025 ((equal arg '(16)) ''org-occur))
10026 ,pos)))
10027 (condition-case nil (let ((org-link-search-inhibit-query t))
10028 (eval cmd))
10029 (error (progn (widen) (eval cmd))))))
10031 (t (browse-url-at-point)))))))
10032 (move-marker org-open-link-marker nil)
10033 (run-hook-with-args 'org-follow-link-hook)))
10035 (defun org-offer-links-in-entry (&optional nth zero)
10036 "Offer links in the current entry and follow the selected link.
10037 If there is only one link, follow it immediately as well.
10038 If NTH is an integer, immediately pick the NTH link found.
10039 If ZERO is a string, check also this string for a link, and if
10040 there is one, offer it as link number zero."
10041 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10042 "\\(" org-angle-link-re "\\)\\|"
10043 "\\(" org-plain-link-re "\\)"))
10044 (cnt ?0)
10045 (in-emacs (if (integerp nth) nil nth))
10046 have-zero end links link c)
10047 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10048 (push (match-string 0 zero) links)
10049 (setq cnt (1- cnt) have-zero t))
10050 (save-excursion
10051 (org-back-to-heading t)
10052 (setq end (save-excursion (outline-next-heading) (point)))
10053 (while (re-search-forward re end t)
10054 (push (match-string 0) links))
10055 (setq links (org-uniquify (reverse links))))
10057 (cond
10058 ((null links)
10059 (message "No links"))
10060 ((equal (length links) 1)
10061 (setq link (list (car links))))
10062 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10063 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10064 (t ; we have to select a link
10065 (save-excursion
10066 (save-window-excursion
10067 (delete-other-windows)
10068 (with-output-to-temp-buffer "*Select Link*"
10069 (mapc (lambda (l)
10070 (if (not (string-match org-bracket-link-regexp l))
10071 (princ (format "[%c] %s\n" (incf cnt)
10072 (org-remove-angle-brackets l)))
10073 (if (match-end 3)
10074 (princ (format "[%c] %s (%s)\n" (incf cnt)
10075 (match-string 3 l) (match-string 1 l)))
10076 (princ (format "[%c] %s\n" (incf cnt)
10077 (match-string 1 l))))))
10078 links))
10079 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10080 (message "Select link to open, RET to open all:")
10081 (setq c (read-char-exclusive))
10082 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10083 (when (equal c ?q) (error "Abort"))
10084 (if (equal c ?\C-m)
10085 (setq link links)
10086 (setq nth (- c ?0))
10087 (if have-zero (setq nth (1+ nth)))
10088 (unless (and (integerp nth) (>= (length links) nth))
10089 (error "Invalid link selection"))
10090 (setq link (list (nth (1- nth) links))))))
10091 (if link
10092 (let ((buf (current-buffer)))
10093 (dolist (l link)
10094 (org-open-link-from-string l in-emacs buf))
10096 nil)))
10098 ;; Add special file links that specify the way of opening
10100 (org-add-link-type "file+sys" 'org-open-file-with-system)
10101 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10102 (defun org-open-file-with-system (path)
10103 "Open file at PATH using the system way of opening it."
10104 (org-open-file path 'system))
10105 (defun org-open-file-with-emacs (path)
10106 "Open file at PATH in Emacs."
10107 (org-open-file path 'emacs))
10108 (defun org-remove-file-link-modifiers ()
10109 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10110 (goto-char (point-min))
10111 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10112 (org-if-unprotected
10113 (replace-match "file:" t t))))
10114 (eval-after-load "org-exp"
10115 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10116 'org-remove-file-link-modifiers))
10118 ;;;; Time estimates
10120 (defun org-get-effort (&optional pom)
10121 "Get the effort estimate for the current entry."
10122 (org-entry-get pom org-effort-property))
10124 ;;; File search
10126 (defvar org-create-file-search-functions nil
10127 "List of functions to construct the right search string for a file link.
10128 These functions are called in turn with point at the location to
10129 which the link should point.
10131 A function in the hook should first test if it would like to
10132 handle this file type, for example by checking the `major-mode'
10133 or the file extension. If it decides not to handle this file, it
10134 should just return nil to give other functions a chance. If it
10135 does handle the file, it must return the search string to be used
10136 when following the link. The search string will be part of the
10137 file link, given after a double colon, and `org-open-at-point'
10138 will automatically search for it. If special measures must be
10139 taken to make the search successful, another function should be
10140 added to the companion hook `org-execute-file-search-functions',
10141 which see.
10143 A function in this hook may also use `setq' to set the variable
10144 `description' to provide a suggestion for the descriptive text to
10145 be used for this link when it gets inserted into an Org-mode
10146 buffer with \\[org-insert-link].")
10148 (defvar org-execute-file-search-functions nil
10149 "List of functions to execute a file search triggered by a link.
10151 Functions added to this hook must accept a single argument, the
10152 search string that was part of the file link, the part after the
10153 double colon. The function must first check if it would like to
10154 handle this search, for example by checking the `major-mode' or
10155 the file extension. If it decides not to handle this search, it
10156 should just return nil to give other functions a chance. If it
10157 does handle the search, it must return a non-nil value to keep
10158 other functions from trying.
10160 Each function can access the current prefix argument through the
10161 variable `current-prefix-argument'. Note that a single prefix is
10162 used to force opening a link in Emacs, so it may be good to only
10163 use a numeric or double prefix to guide the search function.
10165 In case this is needed, a function in this hook can also restore
10166 the window configuration before `org-open-at-point' was called using:
10168 (set-window-configuration org-window-config-before-follow-link)")
10170 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10171 (defun org-link-search (s &optional type avoid-pos stealth)
10172 "Search for a link search option.
10173 If S is surrounded by forward slashes, it is interpreted as a
10174 regular expression. In org-mode files, this will create an `org-occur'
10175 sparse tree. In ordinary files, `occur' will be used to list matches.
10176 If the current buffer is in `dired-mode', grep will be used to search
10177 in all files. If AVOID-POS is given, ignore matches near that position.
10179 When optional argument STEALTH is non-nil, do not modify
10180 visibility around point, thus ignoring
10181 `org-show-hierarchy-above', `org-show-following-heading' and
10182 `org-show-siblings' variables."
10183 (let ((case-fold-search t)
10184 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10185 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10186 (append '(("") (" ") ("\t") ("\n"))
10187 org-emphasis-alist)
10188 "\\|") "\\)"))
10189 (pos (point))
10190 (pre nil) (post nil)
10191 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10192 (cond
10193 ;; First check if there are any special search functions
10194 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10195 ;; Now try the builtin stuff
10196 ((and (equal (string-to-char s0) ?#)
10197 (> (length s0) 1)
10198 (save-excursion
10199 (goto-char (point-min))
10200 (and
10201 (re-search-forward
10202 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10203 (setq type 'dedicated
10204 pos (match-beginning 0))))
10205 ;; There is an exact target for this
10206 (goto-char pos)
10207 (org-back-to-heading t)))
10208 ((save-excursion
10209 (goto-char (point-min))
10210 (and
10211 (re-search-forward
10212 (concat "<<" (regexp-quote s0) ">>") nil t)
10213 (setq type 'dedicated
10214 pos (match-beginning 0))))
10215 ;; There is an exact target for this
10216 (goto-char pos))
10217 ((save-excursion
10218 (goto-char (point-min))
10219 (and
10220 (re-search-forward
10221 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10222 (setq type 'dedicated pos (match-beginning 0))))
10223 ;; Found an invisible target.
10224 (goto-char pos))
10225 ((save-excursion
10226 (goto-char (point-min))
10227 (and
10228 (re-search-forward
10229 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10230 (setq type 'dedicated pos (match-beginning 0))))
10231 ;; Found an element with a matching #+name affiliated keyword.
10232 (goto-char pos))
10233 ((and (string-match "^(\\(.*\\))$" s0)
10234 (save-excursion
10235 (goto-char (point-min))
10236 (and
10237 (re-search-forward
10238 (concat "[^[]" (regexp-quote
10239 (format org-coderef-label-format
10240 (match-string 1 s0))))
10241 nil t)
10242 (setq type 'dedicated
10243 pos (1+ (match-beginning 0))))))
10244 ;; There is a coderef target for this
10245 (goto-char pos))
10246 ((string-match "^/\\(.*\\)/$" s)
10247 ;; A regular expression
10248 (cond
10249 ((derived-mode-p 'org-mode)
10250 (org-occur (match-string 1 s)))
10251 ;;((eq major-mode 'dired-mode)
10252 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10253 (t (org-do-occur (match-string 1 s)))))
10254 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10255 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10256 (goto-char (point-min))
10257 (cond
10258 ((let (case-fold-search)
10259 (re-search-forward (format org-complex-heading-regexp-format
10260 (regexp-quote s))
10261 nil t))
10262 ;; OK, found a match
10263 (setq type 'dedicated)
10264 (goto-char (match-beginning 0)))
10265 ((and (not org-link-search-inhibit-query)
10266 (eq org-link-search-must-match-exact-headline 'query-to-create)
10267 (y-or-n-p "No match - create this as a new heading? "))
10268 (goto-char (point-max))
10269 (or (bolp) (newline))
10270 (insert "* " s "\n")
10271 (beginning-of-line 0))
10273 (goto-char pos)
10274 (error "No match"))))
10276 ;; A normal search string
10277 (when (equal (string-to-char s) ?*)
10278 ;; Anchor on headlines, post may include tags.
10279 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10280 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10281 s (substring s 1)))
10282 (remove-text-properties
10283 0 (length s)
10284 '(face nil mouse-face nil keymap nil fontified nil) s)
10285 ;; Make a series of regular expressions to find a match
10286 (setq words (org-split-string s "[ \n\r\t]+")
10288 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10289 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10290 "\\)" markers)
10291 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10292 re2a (concat "[ \t\r\n]" re2a_)
10293 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10294 re4 (concat "[^a-zA-Z_]" re4_)
10296 re1 (concat pre re2 post)
10297 re3 (concat pre (if pre re4_ re4) post)
10298 re5 (concat pre ".*" re4)
10299 re2 (concat pre re2)
10300 re2a (concat pre (if pre re2a_ re2a))
10301 re4 (concat pre (if pre re4_ re4))
10302 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10303 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10304 re5 "\\)"
10306 (cond
10307 ((eq type 'org-occur) (org-occur reall))
10308 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10309 (t (goto-char (point-min))
10310 (setq type 'fuzzy)
10311 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10312 (org-search-not-self 1 re1 nil t)
10313 (org-search-not-self 1 re2 nil t)
10314 (org-search-not-self 1 re2a nil t)
10315 (org-search-not-self 1 re3 nil t)
10316 (org-search-not-self 1 re4 nil t)
10317 (org-search-not-self 1 re5 nil t)
10319 (goto-char (match-beginning 1))
10320 (goto-char pos)
10321 (error "No match"))))))
10322 (and (derived-mode-p 'org-mode)
10323 (not stealth)
10324 (org-show-context 'link-search))
10325 type))
10327 (defun org-search-not-self (group &rest args)
10328 "Execute `re-search-forward', but only accept matches that do not
10329 enclose the position of `org-open-link-marker'."
10330 (let ((m org-open-link-marker))
10331 (catch 'exit
10332 (while (apply 're-search-forward args)
10333 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10334 (goto-char (match-end group))
10335 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10336 (> (match-beginning 0) (marker-position m))
10337 (< (match-end 0) (marker-position m)))
10338 (save-match-data
10339 (or (not (org-in-regexp
10340 org-bracket-link-analytic-regexp 1))
10341 (not (match-end 4)) ; no description
10342 (and (<= (match-beginning 4) (point))
10343 (>= (match-end 4) (point))))))
10344 (throw 'exit (point))))))))
10346 (defun org-get-buffer-for-internal-link (buffer)
10347 "Return a buffer to be used for displaying the link target of internal links."
10348 (cond
10349 ((not org-display-internal-link-with-indirect-buffer)
10350 buffer)
10351 ((string-match "(Clone)$" (buffer-name buffer))
10352 (message "Buffer is already a clone, not making another one")
10353 ;; we also do not modify visibility in this case
10354 buffer)
10355 (t ; make a new indirect buffer for displaying the link
10356 (let* ((bn (buffer-name buffer))
10357 (ibn (concat bn "(Clone)"))
10358 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10359 (with-current-buffer ib (org-overview))
10360 ib))))
10362 (defun org-do-occur (regexp &optional cleanup)
10363 "Call the Emacs command `occur'.
10364 If CLEANUP is non-nil, remove the printout of the regular expression
10365 in the *Occur* buffer. This is useful if the regex is long and not useful
10366 to read."
10367 (occur regexp)
10368 (when cleanup
10369 (let ((cwin (selected-window)) win beg end)
10370 (when (setq win (get-buffer-window "*Occur*"))
10371 (select-window win))
10372 (goto-char (point-min))
10373 (when (re-search-forward "match[a-z]+" nil t)
10374 (setq beg (match-end 0))
10375 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10376 (setq end (1- (match-beginning 0)))))
10377 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10378 (goto-char (point-min))
10379 (select-window cwin))))
10381 ;;; The mark ring for links jumps
10383 (defvar org-mark-ring nil
10384 "Mark ring for positions before jumps in Org-mode.")
10385 (defvar org-mark-ring-last-goto nil
10386 "Last position in the mark ring used to go back.")
10387 ;; Fill and close the ring
10388 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10389 (loop for i from 1 to org-mark-ring-length do
10390 (push (make-marker) org-mark-ring))
10391 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10392 org-mark-ring)
10394 (defun org-mark-ring-push (&optional pos buffer)
10395 "Put the current position or POS into the mark ring and rotate it."
10396 (interactive)
10397 (setq pos (or pos (point)))
10398 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10399 (move-marker (car org-mark-ring)
10400 (or pos (point))
10401 (or buffer (current-buffer)))
10402 (message "%s"
10403 (substitute-command-keys
10404 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10406 (defun org-mark-ring-goto (&optional n)
10407 "Jump to the previous position in the mark ring.
10408 With prefix arg N, jump back that many stored positions. When
10409 called several times in succession, walk through the entire ring.
10410 Org-mode commands jumping to a different position in the current file,
10411 or to another Org-mode file, automatically push the old position
10412 onto the ring."
10413 (interactive "p")
10414 (let (p m)
10415 (if (eq last-command this-command)
10416 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10417 (setq p org-mark-ring))
10418 (setq org-mark-ring-last-goto p)
10419 (setq m (car p))
10420 (org-pop-to-buffer-same-window (marker-buffer m))
10421 (goto-char m)
10422 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10424 (defun org-remove-angle-brackets (s)
10425 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10426 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10428 (defun org-add-angle-brackets (s)
10429 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10430 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10432 (defun org-remove-double-quotes (s)
10433 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10434 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10437 ;;; Following specific links
10439 (defun org-follow-timestamp-link ()
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)))
10445 (setq t1 (time-to-days (org-time-string-to-time t1))
10446 t2 (time-to-days (org-time-string-to-time t2)))
10447 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10448 ((org-at-timestamp-p t)
10449 (org-agenda-list nil (time-to-days (org-time-string-to-time
10450 (substring (match-string 1) 0 10)))
10452 (t (error "This should not happen"))))
10455 ;;; Following file links
10456 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10457 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10458 (declare-function mailcap-mime-info
10459 "mailcap" (string &optional request no-decode))
10460 (defvar org-wait nil)
10461 (defun org-open-file (path &optional in-emacs line search)
10462 "Open the file at PATH.
10463 First, this expands any special file name abbreviations. Then the
10464 configuration variable `org-file-apps' is checked if it contains an
10465 entry for this file type, and if yes, the corresponding command is launched.
10467 If no application is found, Emacs simply visits the file.
10469 With optional prefix argument IN-EMACS, Emacs will visit the file.
10470 With a double \\[universal-argument] \\[universal-argument] \
10471 prefix arg, Org tries to avoid opening in Emacs
10472 and to use an external application to visit the file.
10474 Optional LINE specifies a line to go to, optional SEARCH a string
10475 to search for. If LINE or SEARCH is given, the file will be
10476 opened in Emacs, unless an entry from org-file-apps that makes
10477 use of groups in a regexp matches.
10479 If you want to change the way frames are used when following a
10480 link, please customize `org-link-frame-setup'.
10482 If the file does not exist, an error is thrown."
10483 (let* ((file (if (equal path "")
10484 buffer-file-name
10485 (substitute-in-file-name (expand-file-name path))))
10486 (file-apps (append org-file-apps (org-default-apps)))
10487 (apps (org-remove-if
10488 'org-file-apps-entry-match-against-dlink-p file-apps))
10489 (apps-dlink (org-remove-if-not
10490 'org-file-apps-entry-match-against-dlink-p file-apps))
10491 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10492 (dirp (if remp nil (file-directory-p file)))
10493 (file (if (and dirp org-open-directory-means-index-dot-org)
10494 (concat (file-name-as-directory file) "index.org")
10495 file))
10496 (a-m-a-p (assq 'auto-mode apps))
10497 (dfile (downcase file))
10498 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10499 (link (cond ((and (eq line nil)
10500 (eq search nil))
10501 file)
10502 (line
10503 (concat file "::" (number-to-string line)))
10504 (search
10505 (concat file "::" search))))
10506 (dlink (downcase link))
10507 (old-buffer (current-buffer))
10508 (old-pos (point))
10509 (old-mode major-mode)
10510 ext cmd link-match-data)
10511 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10512 (setq ext (match-string 1 dfile))
10513 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10514 (setq ext (match-string 1 dfile))))
10515 (cond
10516 ((member in-emacs '((16) system))
10517 (setq cmd (cdr (assoc 'system apps))))
10518 (in-emacs (setq cmd 'emacs))
10520 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10521 (and dirp (cdr (assoc 'directory apps)))
10522 ; first, try matching against apps-dlink
10523 ; if we get a match here, store the match data for later
10524 (let ((match (assoc-default dlink apps-dlink
10525 'string-match)))
10526 (if match
10527 (progn (setq link-match-data (match-data))
10528 match)
10529 (progn (setq in-emacs (or in-emacs line search))
10530 nil))) ; if we have no match in apps-dlink,
10531 ; always open the file in emacs if line or search
10532 ; is given (for backwards compatibility)
10533 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10534 'string-match)
10535 (cdr (assoc ext apps))
10536 (cdr (assoc t apps))))))
10537 (when (eq cmd 'system)
10538 (setq cmd (cdr (assoc 'system apps))))
10539 (when (eq cmd 'default)
10540 (setq cmd (cdr (assoc t apps))))
10541 (when (eq cmd 'mailcap)
10542 (require 'mailcap)
10543 (mailcap-parse-mailcaps)
10544 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10545 (command (mailcap-mime-info mime-type)))
10546 (if (stringp command)
10547 (setq cmd command)
10548 (setq cmd 'emacs))))
10549 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10550 (not (file-exists-p file))
10551 (not org-open-non-existing-files))
10552 (error "No such file: %s" file))
10553 (cond
10554 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10555 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10556 (while (string-match "['\"]%s['\"]" cmd)
10557 (setq cmd (replace-match "%s" t t cmd)))
10558 (while (string-match "%s" cmd)
10559 (setq cmd (replace-match
10560 (save-match-data
10561 (shell-quote-argument
10562 (convert-standard-filename file)))
10563 t t cmd)))
10565 ;; Replace "%1", "%2" etc. in command with group matches from regex
10566 (save-match-data
10567 (let ((match-index 1)
10568 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10569 (set-match-data link-match-data)
10570 (while (<= match-index number-of-groups)
10571 (let ((regex (concat "%" (number-to-string match-index)))
10572 (replace-with (match-string match-index dlink)))
10573 (while (string-match regex cmd)
10574 (setq cmd (replace-match replace-with t t cmd))))
10575 (setq match-index (+ match-index 1)))))
10577 (save-window-excursion
10578 (message "Running %s...done" cmd)
10579 (start-process-shell-command cmd nil cmd)
10580 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10581 ((or (stringp cmd)
10582 (eq cmd 'emacs))
10583 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10584 (widen)
10585 (if line (org-goto-line line)
10586 (if search (org-link-search search))))
10587 ((consp cmd)
10588 (let ((file (convert-standard-filename file)))
10589 (save-match-data
10590 (set-match-data link-match-data)
10591 (eval cmd))))
10592 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10593 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10594 (or (not (equal old-buffer (current-buffer)))
10595 (not (equal old-pos (point))))
10596 (org-mark-ring-push old-pos old-buffer))))
10598 (defun org-file-apps-entry-match-against-dlink-p (entry)
10599 "This function returns non-nil if `entry' uses a regular
10600 expression which should be matched against the whole link by
10601 org-open-file.
10603 It assumes that is the case when the entry uses a regular
10604 expression which has at least one grouping construct and the
10605 action is either a lisp form or a command string containing
10606 '%1', i.e. using at least one subexpression match as a
10607 parameter."
10608 (let ((selector (car entry))
10609 (action (cdr entry)))
10610 (if (stringp selector)
10611 (and (> (regexp-opt-depth selector) 0)
10612 (or (and (stringp action)
10613 (string-match "%[0-9]" action))
10614 (consp action)))
10615 nil)))
10617 (defun org-default-apps ()
10618 "Return the default applications for this operating system."
10619 (cond
10620 ((eq system-type 'darwin)
10621 org-file-apps-defaults-macosx)
10622 ((eq system-type 'windows-nt)
10623 org-file-apps-defaults-windowsnt)
10624 (t org-file-apps-defaults-gnu)))
10626 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10627 "Convert extensions to regular expressions in the cars of LIST.
10628 Also, weed out any non-string entries, because the return value is used
10629 only for regexp matching.
10630 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10631 point to the symbol `emacs', indicating that the file should
10632 be opened in Emacs."
10633 (append
10634 (delq nil
10635 (mapcar (lambda (x)
10636 (if (not (stringp (car x)))
10638 (if (string-match "\\W" (car x))
10640 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10641 list))
10642 (if add-auto-mode
10643 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10645 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10646 (defun org-file-remote-p (file)
10647 "Test whether FILE specifies a location on a remote system.
10648 Return non-nil if the location is indeed remote.
10650 For example, the filename \"/user@host:/foo\" specifies a location
10651 on the system \"/user@host:\"."
10652 (cond ((fboundp 'file-remote-p)
10653 (file-remote-p file))
10654 ((fboundp 'tramp-handle-file-remote-p)
10655 (tramp-handle-file-remote-p file))
10656 ((and (boundp 'ange-ftp-name-format)
10657 (string-match (car ange-ftp-name-format) file))
10658 t)))
10661 ;;;; Refiling
10663 (defun org-get-org-file ()
10664 "Read a filename, with default directory `org-directory'."
10665 (let ((default (or org-default-notes-file remember-data-file)))
10666 (read-file-name (format "File name [%s]: " default)
10667 (file-name-as-directory org-directory)
10668 default)))
10670 (defun org-notes-order-reversed-p ()
10671 "Check if the current file should receive notes in reversed order."
10672 (cond
10673 ((not org-reverse-note-order) nil)
10674 ((eq t org-reverse-note-order) t)
10675 ((not (listp org-reverse-note-order)) nil)
10676 (t (catch 'exit
10677 (let ((all org-reverse-note-order)
10678 entry)
10679 (while (setq entry (pop all))
10680 (if (string-match (car entry) buffer-file-name)
10681 (throw 'exit (cdr entry))))
10682 nil)))))
10684 (defvar org-refile-target-table nil
10685 "The list of refile targets, created by `org-refile'.")
10687 (defvar org-agenda-new-buffers nil
10688 "Buffers created to visit agenda files.")
10690 (defvar org-refile-cache nil
10691 "Cache for refile targets.")
10693 (defvar org-refile-markers nil
10694 "All the markers used for caching refile locations.")
10696 (defun org-refile-marker (pos)
10697 "Get a new refile marker, but only if caching is in use."
10698 (if (not org-refile-use-cache)
10700 (let ((m (make-marker)))
10701 (move-marker m pos)
10702 (push m org-refile-markers)
10703 m)))
10705 (defun org-refile-cache-clear ()
10706 "Clear the refile cache and disable all the markers."
10707 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10708 (setq org-refile-markers nil)
10709 (setq org-refile-cache nil)
10710 (message "Refile cache has been cleared"))
10712 (defun org-refile-cache-check-set (set)
10713 "Check if all the markers in the cache still have live buffers."
10714 (let (marker)
10715 (catch 'exit
10716 (while (and set (setq marker (nth 3 (pop set))))
10717 ;; if org-refile-use-outline-path is 'file, marker may be nil
10718 (when (and marker (null (marker-buffer marker)))
10719 (message "not found") (sit-for 3)
10720 (throw 'exit nil)))
10721 t)))
10723 (defun org-refile-cache-put (set &rest identifiers)
10724 "Push the refile targets SET into the cache, under IDENTIFIERS."
10725 (let* ((key (sha1 (prin1-to-string identifiers)))
10726 (entry (assoc key org-refile-cache)))
10727 (if entry
10728 (setcdr entry set)
10729 (push (cons key set) org-refile-cache))))
10731 (defun org-refile-cache-get (&rest identifiers)
10732 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10733 (cond
10734 ((not org-refile-cache) nil)
10735 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10737 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10738 org-refile-cache))))
10739 (and set (org-refile-cache-check-set set) set)))))
10741 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10742 "Produce a table with refile targets."
10743 (let ((case-fold-search nil)
10744 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10745 (entries (or org-refile-targets '((nil . (:level . 1)))))
10746 targets tgs txt re files f desc descre fast-path-p level pos0)
10747 (message "Getting targets...")
10748 (with-current-buffer (or default-buffer (current-buffer))
10749 (while (setq entry (pop entries))
10750 (setq files (car entry) desc (cdr entry))
10751 (setq fast-path-p nil)
10752 (cond
10753 ((null files) (setq files (list (current-buffer))))
10754 ((eq files 'org-agenda-files)
10755 (setq files (org-agenda-files 'unrestricted)))
10756 ((and (symbolp files) (fboundp files))
10757 (setq files (funcall files)))
10758 ((and (symbolp files) (boundp files))
10759 (setq files (symbol-value files))))
10760 (if (stringp files) (setq files (list files)))
10761 (cond
10762 ((eq (car desc) :tag)
10763 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10764 ((eq (car desc) :todo)
10765 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10766 ((eq (car desc) :regexp)
10767 (setq descre (cdr desc)))
10768 ((eq (car desc) :level)
10769 (setq descre (concat "^\\*\\{" (number-to-string
10770 (if org-odd-levels-only
10771 (1- (* 2 (cdr desc)))
10772 (cdr desc)))
10773 "\\}[ \t]")))
10774 ((eq (car desc) :maxlevel)
10775 (setq fast-path-p t)
10776 (setq descre (concat "^\\*\\{1," (number-to-string
10777 (if org-odd-levels-only
10778 (1- (* 2 (cdr desc)))
10779 (cdr desc)))
10780 "\\}[ \t]")))
10781 (t (error "Bad refiling target description %s" desc)))
10782 (while (setq f (pop files))
10783 (with-current-buffer
10784 (if (bufferp f) f (org-get-agenda-file-buffer f))
10786 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10787 (progn
10788 (if (bufferp f) (setq f (buffer-file-name
10789 (buffer-base-buffer f))))
10790 (setq f (and f (expand-file-name f)))
10791 (if (eq org-refile-use-outline-path 'file)
10792 (push (list (file-name-nondirectory f) f nil nil) tgs))
10793 (save-excursion
10794 (save-restriction
10795 (widen)
10796 (goto-char (point-min))
10797 (while (re-search-forward descre nil t)
10798 (goto-char (setq pos0 (point-at-bol)))
10799 (catch 'next
10800 (when org-refile-target-verify-function
10801 (save-match-data
10802 (or (funcall org-refile-target-verify-function)
10803 (throw 'next t))))
10804 (when (and (looking-at org-complex-heading-regexp)
10805 (not (member (match-string 4) excluded-entries))
10806 (match-string 4))
10807 (setq level (org-reduced-level
10808 (- (match-end 1) (match-beginning 1)))
10809 txt (org-link-display-format (match-string 4))
10810 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10811 re (format org-complex-heading-regexp-format
10812 (regexp-quote (match-string 4))))
10813 (when org-refile-use-outline-path
10814 (setq txt (mapconcat
10815 'org-protect-slash
10816 (append
10817 (if (eq org-refile-use-outline-path
10818 'file)
10819 (list (file-name-nondirectory
10820 (buffer-file-name
10821 (buffer-base-buffer))))
10822 (if (eq org-refile-use-outline-path
10823 'full-file-path)
10824 (list (buffer-file-name
10825 (buffer-base-buffer)))))
10826 (org-get-outline-path fast-path-p
10827 level txt)
10828 (list txt))
10829 "/")))
10830 (push (list txt f re (org-refile-marker (point)))
10831 tgs)))
10832 (when (= (point) pos0)
10833 ;; verification function has not moved point
10834 (goto-char (point-at-eol))))))))
10835 (when org-refile-use-cache
10836 (org-refile-cache-put tgs (buffer-file-name) descre))
10837 (setq targets (append tgs targets))
10838 ))))
10839 (message "Getting targets...done")
10840 (nreverse targets)))
10842 (defun org-protect-slash (s)
10843 (while (string-match "/" s)
10844 (setq s (replace-match "\\" t t s)))
10847 (defvar org-olpa (make-vector 20 nil))
10849 (defun org-get-outline-path (&optional fastp level heading)
10850 "Return the outline path to the current entry, as a list.
10852 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10853 routine which makes outline path derivations for an entire file,
10854 avoiding backtracing. Refile target collection makes use of that."
10855 (if fastp
10856 (progn
10857 (if (> level 19)
10858 (error "Outline path failure, more than 19 levels"))
10859 (loop for i from level upto 19 do
10860 (aset org-olpa i nil))
10861 (prog1
10862 (delq nil (append org-olpa nil))
10863 (aset org-olpa level heading)))
10864 (let (rtn case-fold-search)
10865 (save-excursion
10866 (save-restriction
10867 (widen)
10868 (while (org-up-heading-safe)
10869 (when (looking-at org-complex-heading-regexp)
10870 (push (org-match-string-no-properties 4) rtn)))
10871 rtn)))))
10873 (defun org-format-outline-path (path &optional width prefix)
10874 "Format the outline path PATH for display.
10875 Width is the maximum number of characters that is available.
10876 Prefix is a prefix to be included in the returned string,
10877 such as the file name."
10878 (setq width (or width 79))
10879 (if prefix (setq width (- width (length prefix))))
10880 (if (not path)
10881 (or prefix "")
10882 (let* ((nsteps (length path))
10883 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10884 (maxwidth (if (<= total-width width)
10885 10000 ;; everything fits
10886 ;; we need to shorten the level headings
10887 (/ (- width nsteps) nsteps)))
10888 (org-odd-levels-only nil)
10889 (n 0)
10890 (total (1+ (length prefix))))
10891 (setq maxwidth (max maxwidth 10))
10892 (concat prefix
10893 (mapconcat
10894 (lambda (h)
10895 (setq n (1+ n))
10896 (if (and (= n nsteps) (< maxwidth 10000))
10897 (setq maxwidth (- total-width total)))
10898 (if (< (length h) maxwidth)
10899 (progn (setq total (+ total (length h) 1)) h)
10900 (setq h (substring h 0 (- maxwidth 2))
10901 total (+ total maxwidth 1))
10902 (if (string-match "[ \t]+\\'" h)
10903 (setq h (substring h 0 (match-beginning 0))))
10904 (setq h (concat h "..")))
10905 (org-add-props h nil 'face
10906 (nth (% (1- n) org-n-level-faces)
10907 org-level-faces))
10909 path "/")))))
10911 (defun org-display-outline-path (&optional file current)
10912 "Display the current outline path in the echo area."
10913 (interactive "P")
10914 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10915 (case-fold-search nil)
10916 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10917 (if current (setq path (append path
10918 (save-excursion
10919 (org-back-to-heading t)
10920 (if (looking-at org-complex-heading-regexp)
10921 (list (match-string 4)))))))
10922 (message "%s"
10923 (org-format-outline-path
10924 path
10925 (1- (frame-width))
10926 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10928 (defvar org-refile-history nil
10929 "History for refiling operations.")
10931 (defvar org-after-refile-insert-hook nil
10932 "Hook run after `org-refile' has inserted its stuff at the new location.
10933 Note that this is still *before* the stuff will be removed from
10934 the *old* location.")
10936 (defvar org-capture-last-stored-marker)
10937 (defun org-refile (&optional goto default-buffer rfloc)
10938 "Move the entry or entries at point to another heading.
10939 The list of target headings is compiled using the information in
10940 `org-refile-targets', which see.
10942 At the target location, the entry is filed as a subitem of the target
10943 heading. Depending on `org-reverse-note-order', the new subitem will
10944 either be the first or the last subitem.
10946 If there is an active region, all entries in that region will be moved.
10947 However, the region must fulfill the requirement that the first heading
10948 is the first one sets the top-level of the moved text - at most siblings
10949 below it are allowed.
10951 With prefix arg GOTO, the command will only visit the target location
10952 and not actually move anything.
10954 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10955 go to the location where the last refiling operation has put the subtree.
10956 With a prefix argument of `2', refile to the running clock.
10958 RFLOC can be a refile location obtained in a different way.
10960 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10962 If you are using target caching (see `org-refile-use-cache'),
10963 you have to clear the target cache in order to find new targets.
10964 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10965 prefix argument (`C-u C-u C-u C-c C-w')."
10967 (interactive "P")
10968 (if (member goto '(0 (64)))
10969 (org-refile-cache-clear)
10970 (let* ((cbuf (current-buffer))
10971 (regionp (org-region-active-p))
10972 (region-start (and regionp (region-beginning)))
10973 (region-end (and regionp (region-end)))
10974 (region-length (and regionp (- region-end region-start)))
10975 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10976 pos it nbuf file re level reversed)
10977 (setq last-command nil)
10978 (when regionp
10979 (goto-char region-start)
10980 (or (bolp) (goto-char (point-at-bol)))
10981 (setq region-start (point))
10982 (unless (or (org-kill-is-subtree-p
10983 (buffer-substring region-start region-end))
10984 (prog1 org-refile-active-region-within-subtree
10985 (org-toggle-heading)))
10986 (error "The region is not a (sequence of) subtree(s)")))
10987 (if (equal goto '(16))
10988 (org-refile-goto-last-stored)
10989 (when (or
10990 (and (equal goto 2)
10991 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10992 (prog1
10993 (setq it (list (or org-clock-heading "running clock")
10994 (buffer-file-name
10995 (marker-buffer org-clock-hd-marker))
10997 (marker-position org-clock-hd-marker)))
10998 (setq goto nil)))
10999 (setq it (or rfloc
11000 (let (heading-text)
11001 (save-excursion
11002 (unless goto
11003 (org-back-to-heading t)
11004 (setq heading-text
11005 (nth 4 (org-heading-components))))
11006 (org-refile-get-location
11007 (cond (goto "Goto")
11008 (regionp "Refile region to")
11009 (t (concat "Refile subtree \""
11010 heading-text "\" to")))
11011 default-buffer
11012 (and (not (equal '(4) goto))
11013 org-refile-allow-creating-parent-nodes)
11014 goto))))))
11015 (setq file (nth 1 it)
11016 re (nth 2 it)
11017 pos (nth 3 it))
11018 (if (and (not goto)
11020 (equal (buffer-file-name) file)
11021 (if regionp
11022 (and (>= pos region-start)
11023 (<= pos region-end))
11024 (and (>= pos (point))
11025 (< pos (save-excursion
11026 (org-end-of-subtree t t))))))
11027 (error "Cannot refile to position inside the tree or region"))
11029 (setq nbuf (or (find-buffer-visiting file)
11030 (find-file-noselect file)))
11031 (if goto
11032 (progn
11033 (org-pop-to-buffer-same-window nbuf)
11034 (goto-char pos)
11035 (org-show-context 'org-goto))
11036 (if regionp
11037 (progn
11038 (org-kill-new (buffer-substring region-start region-end))
11039 (org-save-markers-in-region region-start region-end))
11040 (org-copy-subtree 1 nil t))
11041 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11042 (find-file-noselect file)))
11043 (setq reversed (org-notes-order-reversed-p))
11044 (save-excursion
11045 (save-restriction
11046 (widen)
11047 (if pos
11048 (progn
11049 (goto-char pos)
11050 (looking-at org-outline-regexp)
11051 (setq level (org-get-valid-level (funcall outline-level) 1))
11052 (goto-char
11053 (if reversed
11054 (or (outline-next-heading) (point-max))
11055 (or (save-excursion (org-get-next-sibling))
11056 (org-end-of-subtree t t)
11057 (point-max)))))
11058 (setq level 1)
11059 (if (not reversed)
11060 (goto-char (point-max))
11061 (goto-char (point-min))
11062 (or (outline-next-heading) (goto-char (point-max)))))
11063 (if (not (bolp)) (newline))
11064 (org-paste-subtree level)
11065 (when org-log-refile
11066 (org-add-log-setup 'refile nil nil 'findpos
11067 org-log-refile)
11068 (unless (eq org-log-refile 'note)
11069 (save-excursion (org-add-log-note))))
11070 (and org-auto-align-tags
11071 (let ((org-loop-over-headlines-in-active-region nil))
11072 (org-set-tags nil t)))
11073 (bookmark-set "org-refile-last-stored")
11074 ;; If we are refiling for capture, make sure that the
11075 ;; last-capture pointers point here
11076 (when (org-bound-and-true-p org-refile-for-capture)
11077 (bookmark-set "org-capture-last-stored-marker")
11078 (move-marker org-capture-last-stored-marker (point)))
11079 (if (fboundp 'deactivate-mark) (deactivate-mark))
11080 (run-hooks 'org-after-refile-insert-hook))))
11081 (if regionp
11082 (delete-region (point) (+ (point) region-length))
11083 (org-cut-subtree))
11084 (when (featurep 'org-inlinetask)
11085 (org-inlinetask-remove-END-maybe))
11086 (setq org-markers-to-move nil)
11087 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
11089 (defun org-refile-goto-last-stored ()
11090 "Go to the location where the last refile was stored."
11091 (interactive)
11092 (bookmark-jump "org-refile-last-stored")
11093 (message "This is the location of the last refile"))
11095 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11096 no-exclude)
11097 "Prompt the user for a refile location, using PROMPT.
11098 PROMPT should not be suffixed with a colon and a space, because
11099 this function appends the default value from
11100 `org-refile-history' automatically, if that is not empty.
11101 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11102 this is used for the GOTO interface."
11103 (let ((org-refile-targets org-refile-targets)
11104 (org-refile-use-outline-path org-refile-use-outline-path)
11105 excluded-entries)
11106 (when (and (derived-mode-p 'org-mode)
11107 (not org-refile-use-cache)
11108 (not no-exclude))
11109 (org-map-tree
11110 (lambda()
11111 (setq excluded-entries
11112 (append excluded-entries (list (org-get-heading t t)))))))
11113 (setq org-refile-target-table
11114 (org-refile-get-targets default-buffer excluded-entries)))
11115 (unless org-refile-target-table
11116 (error "No refile targets"))
11117 (let* ((prompt (concat prompt
11118 (and (car org-refile-history)
11119 (concat " (default " (car org-refile-history) ")"))
11120 ": "))
11121 (cbuf (current-buffer))
11122 (partial-completion-mode nil)
11123 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11124 (cfunc (if (and org-refile-use-outline-path
11125 org-outline-path-complete-in-steps)
11126 'org-olpath-completing-read
11127 'org-icompleting-read))
11128 (extra (if org-refile-use-outline-path "/" ""))
11129 (filename (and cfn (expand-file-name cfn)))
11130 (tbl (mapcar
11131 (lambda (x)
11132 (if (and (not (member org-refile-use-outline-path
11133 '(file full-file-path)))
11134 (not (equal filename (nth 1 x))))
11135 (cons (concat (car x) extra " ("
11136 (file-name-nondirectory (nth 1 x)) ")")
11137 (cdr x))
11138 (cons (concat (car x) extra) (cdr x))))
11139 org-refile-target-table))
11140 (completion-ignore-case t)
11141 pa answ parent-target child parent old-hist)
11142 (setq old-hist org-refile-history)
11143 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11144 nil 'org-refile-history (car org-refile-history)))
11145 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11146 (org-refile-check-position pa)
11147 (if pa
11148 (progn
11149 (when (or (not org-refile-history)
11150 (not (eq old-hist org-refile-history))
11151 (not (equal (car pa) (car org-refile-history))))
11152 (setq org-refile-history
11153 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11154 org-refile-history
11155 (cdr org-refile-history))))
11156 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11157 (pop org-refile-history)))
11159 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11160 (progn
11161 (setq parent (match-string 1 answ)
11162 child (match-string 2 answ))
11163 (setq parent-target (or (assoc parent tbl)
11164 (assoc (concat parent "/") tbl)))
11165 (when (and parent-target
11166 (or (eq new-nodes t)
11167 (and (eq new-nodes 'confirm)
11168 (y-or-n-p (format "Create new node \"%s\"? "
11169 child)))))
11170 (org-refile-new-child parent-target child)))
11171 (error "Invalid target location")))))
11173 (declare-function org-string-nw-p "org-macs.el" (s))
11174 (defun org-refile-check-position (refile-pointer)
11175 "Check if the refile pointer matches the readline to which it points."
11176 (let* ((file (nth 1 refile-pointer))
11177 (re (nth 2 refile-pointer))
11178 (pos (nth 3 refile-pointer))
11179 buffer)
11180 (when (org-string-nw-p re)
11181 (setq buffer (if (markerp pos)
11182 (marker-buffer pos)
11183 (or (find-buffer-visiting file)
11184 (find-file-noselect file))))
11185 (with-current-buffer buffer
11186 (save-excursion
11187 (save-restriction
11188 (widen)
11189 (goto-char pos)
11190 (beginning-of-line 1)
11191 (unless (org-looking-at-p re)
11192 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11194 (defun org-refile-new-child (parent-target child)
11195 "Use refile target PARENT-TARGET to add new CHILD below it."
11196 (unless parent-target
11197 (error "Cannot find parent for new node"))
11198 (let ((file (nth 1 parent-target))
11199 (pos (nth 3 parent-target))
11200 level)
11201 (with-current-buffer (or (find-buffer-visiting file)
11202 (find-file-noselect file))
11203 (save-excursion
11204 (save-restriction
11205 (widen)
11206 (if pos
11207 (goto-char pos)
11208 (goto-char (point-max))
11209 (if (not (bolp)) (newline)))
11210 (when (looking-at org-outline-regexp)
11211 (setq level (funcall outline-level))
11212 (org-end-of-subtree t t))
11213 (org-back-over-empty-lines)
11214 (insert "\n" (make-string
11215 (if pos (org-get-valid-level level 1) 1) ?*)
11216 " " child "\n")
11217 (beginning-of-line 0)
11218 (list (concat (car parent-target) "/" child) file "" (point)))))))
11220 (defun org-olpath-completing-read (prompt collection &rest args)
11221 "Read an outline path like a file name."
11222 (let ((thetable collection)
11223 (org-completion-use-ido nil) ; does not work with ido.
11224 (org-completion-use-iswitchb nil)) ; or iswitchb
11225 (apply
11226 'org-icompleting-read prompt
11227 (lambda (string predicate &optional flag)
11228 (let (rtn r f (l (length string)))
11229 (cond
11230 ((eq flag nil)
11231 ;; try completion
11232 (try-completion string thetable))
11233 ((eq flag t)
11234 ;; all-completions
11235 (setq rtn (all-completions string thetable predicate))
11236 (mapcar
11237 (lambda (x)
11238 (setq r (substring x l))
11239 (if (string-match " ([^)]*)$" x)
11240 (setq f (match-string 0 x))
11241 (setq f ""))
11242 (if (string-match "/" r)
11243 (concat string (substring r 0 (match-end 0)) f)
11245 rtn))
11246 ((eq flag 'lambda)
11247 ;; exact match?
11248 (assoc string thetable)))))
11249 args)))
11251 ;;;; Dynamic blocks
11253 (defun org-find-dblock (name)
11254 "Find the first dynamic block with name NAME in the buffer.
11255 If not found, stay at current position and return nil."
11256 (let ((case-fold-search t) pos)
11257 (save-excursion
11258 (goto-char (point-min))
11259 (setq pos (and (re-search-forward
11260 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11261 (match-beginning 0))))
11262 (if pos (goto-char pos))
11263 pos))
11265 (defconst org-dblock-start-re
11266 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11267 "Matches the start line of a dynamic block, with parameters.")
11269 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11270 "Matches the end of a dynamic block.")
11272 (defun org-create-dblock (plist)
11273 "Create a dynamic block section, with parameters taken from PLIST.
11274 PLIST must contain a :name entry which is used as name of the block."
11275 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11276 (end-of-line 1)
11277 (newline))
11278 (let ((col (current-column))
11279 (name (plist-get plist :name)))
11280 (insert "#+BEGIN: " name)
11281 (while plist
11282 (if (eq (car plist) :name)
11283 (setq plist (cddr plist))
11284 (insert " " (prin1-to-string (pop plist)))))
11285 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11286 (beginning-of-line -2)))
11288 (defun org-prepare-dblock ()
11289 "Prepare dynamic block for refresh.
11290 This empties the block, puts the cursor at the insert position and returns
11291 the property list including an extra property :name with the block name."
11292 (unless (looking-at org-dblock-start-re)
11293 (error "Not at a dynamic block"))
11294 (let* ((begdel (1+ (match-end 0)))
11295 (name (org-no-properties (match-string 1)))
11296 (params (append (list :name name)
11297 (read (concat "(" (match-string 3) ")")))))
11298 (save-excursion
11299 (beginning-of-line 1)
11300 (skip-chars-forward " \t")
11301 (setq params (plist-put params :indentation-column (current-column))))
11302 (unless (re-search-forward org-dblock-end-re nil t)
11303 (error "Dynamic block not terminated"))
11304 (setq params
11305 (append params
11306 (list :content (buffer-substring
11307 begdel (match-beginning 0)))))
11308 (delete-region begdel (match-beginning 0))
11309 (goto-char begdel)
11310 (open-line 1)
11311 params))
11313 (defun org-map-dblocks (&optional command)
11314 "Apply COMMAND to all dynamic blocks in the current buffer.
11315 If COMMAND is not given, use `org-update-dblock'."
11316 (let ((cmd (or command 'org-update-dblock)))
11317 (save-excursion
11318 (goto-char (point-min))
11319 (while (re-search-forward org-dblock-start-re nil t)
11320 (goto-char (match-beginning 0))
11321 (save-excursion
11322 (condition-case nil
11323 (funcall cmd)
11324 (error (message "Error during update of dynamic block"))))
11325 (unless (re-search-forward org-dblock-end-re nil t)
11326 (error "Dynamic block not terminated"))))))
11328 (defun org-dblock-update (&optional arg)
11329 "User command for updating dynamic blocks.
11330 Update the dynamic block at point. With prefix ARG, update all dynamic
11331 blocks in the buffer."
11332 (interactive "P")
11333 (if arg
11334 (org-update-all-dblocks)
11335 (or (looking-at org-dblock-start-re)
11336 (org-beginning-of-dblock))
11337 (org-update-dblock)))
11339 (defun org-update-dblock ()
11340 "Update the dynamic block at point.
11341 This means to empty the block, parse for parameters and then call
11342 the correct writing function."
11343 (interactive)
11344 (save-window-excursion
11345 (let* ((pos (point))
11346 (line (org-current-line))
11347 (params (org-prepare-dblock))
11348 (name (plist-get params :name))
11349 (indent (plist-get params :indentation-column))
11350 (cmd (intern (concat "org-dblock-write:" name))))
11351 (message "Updating dynamic block `%s' at line %d..." name line)
11352 (funcall cmd params)
11353 (message "Updating dynamic block `%s' at line %d...done" name line)
11354 (goto-char pos)
11355 (when (and indent (> indent 0))
11356 (setq indent (make-string indent ?\ ))
11357 (save-excursion
11358 (org-beginning-of-dblock)
11359 (forward-line 1)
11360 (while (not (looking-at org-dblock-end-re))
11361 (insert indent)
11362 (beginning-of-line 2))
11363 (when (looking-at org-dblock-end-re)
11364 (and (looking-at "[ \t]+")
11365 (replace-match ""))
11366 (insert indent)))))))
11368 (defun org-beginning-of-dblock ()
11369 "Find the beginning of the dynamic block at point.
11370 Error if there is no such block at point."
11371 (let ((pos (point))
11372 beg)
11373 (end-of-line 1)
11374 (if (and (re-search-backward org-dblock-start-re nil t)
11375 (setq beg (match-beginning 0))
11376 (re-search-forward org-dblock-end-re nil t)
11377 (> (match-end 0) pos))
11378 (goto-char beg)
11379 (goto-char pos)
11380 (error "Not in a dynamic block"))))
11382 ;;;###autoload
11383 (defun org-update-all-dblocks ()
11384 "Update all dynamic blocks in the buffer.
11385 This function can be used in a hook."
11386 (interactive)
11387 (when (derived-mode-p 'org-mode)
11388 (org-map-dblocks 'org-update-dblock)))
11391 ;;;; Completion
11393 (defconst org-additional-option-like-keywords
11394 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11395 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11396 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11397 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11398 "BEGIN:" "END:"
11399 "ORGTBL" "TBLFM:" "TBLNAME:"
11400 "BEGIN_EXAMPLE" "END_EXAMPLE"
11401 "BEGIN_VERBATIM" "END_VERBATIM"
11402 "BEGIN_QUOTE" "END_QUOTE"
11403 "BEGIN_VERSE" "END_VERSE"
11404 "BEGIN_CENTER" "END_CENTER"
11405 "BEGIN_SRC" "END_SRC"
11406 "BEGIN_RESULT" "END_RESULT"
11407 "BEGIN_lstlisting" "END_lstlisting"
11408 "NAME:" "RESULTS:"
11409 "HEADER:" "HEADERS:"
11410 "COLUMNS:" "PROPERTY:"
11411 "CAPTION:" "LABEL:"
11412 "SETUPFILE:"
11413 "INCLUDE:"
11414 "BIND:"
11415 "MACRO:"))
11417 (defconst org-options-keywords
11418 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11419 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11420 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11421 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11422 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11423 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:"
11424 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11426 (defconst org-additional-option-like-keywords-for-flyspell
11427 (delete-dups
11428 (split-string
11429 (mapconcat (lambda(k)
11430 (replace-regexp-in-string
11431 "_\\|:" " "
11432 (concat k " " (downcase k) " " (upcase k))))
11433 (append org-options-keywords org-additional-option-like-keywords)
11434 " ")
11435 " +" t)))
11437 (defcustom org-structure-template-alist
11439 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11440 "<src lang=\"?\">\n\n</src>")
11441 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11442 "<example>\n?\n</example>")
11443 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11444 "<quote>\n?\n</quote>")
11445 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11446 "<verse>\n?\n</verse>")
11447 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11448 "<center>\n?\n</center>")
11449 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11450 "<literal style=\"latex\">\n?\n</literal>")
11451 ("L" "#+LaTeX: "
11452 "<literal style=\"latex\">?</literal>")
11453 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11454 "<literal style=\"html\">\n?\n</literal>")
11455 ("H" "#+HTML: "
11456 "<literal style=\"html\">?</literal>")
11457 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11458 ("A" "#+ASCII: ")
11459 ("i" "#+INDEX: ?"
11460 "#+INDEX: ?")
11461 ("I" "#+INCLUDE: %file ?"
11462 "<include file=%file markup=\"?\">")
11464 "Structure completion elements.
11465 This is a list of abbreviation keys and values. The value gets inserted
11466 if you type `<' followed by the key and then press the completion key,
11467 usually `M-TAB'. %file will be replaced by a file name after prompting
11468 for the file using completion. The cursor will be placed at the position
11469 of the `?` in the template.
11470 There are two templates for each key, the first uses the original Org syntax,
11471 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11472 the default when the /org-mtags.el/ module has been loaded. See also the
11473 variable `org-mtags-prefer-muse-templates'."
11474 :group 'org-completion
11475 :type '(repeat
11476 (string :tag "Key")
11477 (string :tag "Template")
11478 (string :tag "Muse Template")))
11480 (defun org-try-structure-completion ()
11481 "Try to complete a structure template before point.
11482 This looks for strings like \"<e\" on an otherwise empty line and
11483 expands them."
11484 (let ((l (buffer-substring (point-at-bol) (point)))
11486 (when (and (looking-at "[ \t]*$")
11487 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11488 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11489 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11490 (match-beginning 1)) a)
11491 t)))
11493 (defun org-complete-expand-structure-template (start cell)
11494 "Expand a structure template."
11495 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11496 (rpl (nth (if musep 2 1) cell))
11497 (ind ""))
11498 (delete-region start (point))
11499 (when (string-match "\\`#\\+" rpl)
11500 (cond
11501 ((bolp))
11502 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11503 (setq ind (buffer-substring (point-at-bol) (point))))
11504 (t (newline))))
11505 (setq start (point))
11506 (if (string-match "%file" rpl)
11507 (setq rpl (replace-match
11508 (concat
11509 "\""
11510 (save-match-data
11511 (abbreviate-file-name (read-file-name "Include file: ")))
11512 "\"")
11513 t t rpl)))
11514 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11515 (concat "\n" ind)))
11516 (insert rpl)
11517 (if (re-search-backward "\\?" start t) (delete-char 1))))
11519 ;;;; TODO, DEADLINE, Comments
11521 (defun org-toggle-comment ()
11522 "Change the COMMENT state of an entry."
11523 (interactive)
11524 (save-excursion
11525 (org-back-to-heading)
11526 (let (case-fold-search)
11527 (cond
11528 ((looking-at (format org-heading-keyword-regexp-format
11529 org-comment-string))
11530 (goto-char (match-end 1))
11531 (looking-at (concat " +" org-comment-string))
11532 (replace-match "" t t)
11533 (when (eolp) (insert " ")))
11534 ((looking-at org-outline-regexp)
11535 (goto-char (match-end 0))
11536 (insert org-comment-string " "))))))
11538 (defvar org-last-todo-state-is-todo nil
11539 "This is non-nil when the last TODO state change led to a TODO state.
11540 If the last change removed the TODO tag or switched to DONE, then
11541 this is nil.")
11543 (defvar org-setting-tags nil) ; dynamically skipped
11545 (defvar org-todo-setup-filter-hook nil
11546 "Hook for functions that pre-filter todo specs.
11547 Each function takes a todo spec and returns either nil or the spec
11548 transformed into canonical form." )
11550 (defvar org-todo-get-default-hook nil
11551 "Hook for functions that get a default item for todo.
11552 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11553 nil or a string to be used for the todo mark." )
11555 (defvar org-agenda-headline-snapshot-before-repeat)
11557 (defun org-current-effective-time ()
11558 "Return current time adjusted for `org-extend-today-until' variable."
11559 (let* ((ct (org-current-time))
11560 (dct (decode-time ct))
11561 (ct1
11562 (cond
11563 (org-use-last-clock-out-time-as-effective-time
11564 (or (org-clock-get-last-clock-out-time) ct))
11565 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11566 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11567 (t ct))))
11568 ct1))
11570 (defun org-todo-yesterday (&optional arg)
11571 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11572 (interactive "P")
11573 (if (eq major-mode 'org-agenda-mode)
11574 (apply 'org-agenda-todo-yesterday arg)
11575 (let* ((hour (third (decode-time
11576 (org-current-time))))
11577 (org-extend-today-until (1+ hour)))
11578 (org-todo arg))))
11580 (defun org-todo (&optional arg)
11581 "Change the TODO state of an item.
11582 The state of an item is given by a keyword at the start of the heading,
11583 like
11584 *** TODO Write paper
11585 *** DONE Call mom
11587 The different keywords are specified in the variable `org-todo-keywords'.
11588 By default the available states are \"TODO\" and \"DONE\".
11589 So for this example: when the item starts with TODO, it is changed to DONE.
11590 When it starts with DONE, the DONE is removed. And when neither TODO nor
11591 DONE are present, add TODO at the beginning of the heading.
11593 With \\[universal-argument] prefix arg, use completion to determine the new \
11594 state.
11595 With numeric prefix arg, switch to that state.
11596 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11597 keywords (nextset).
11598 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11599 With a numeric prefix arg of 0, inhibit note taking for the change.
11601 For calling through lisp, arg is also interpreted in the following way:
11602 'none -> empty state
11603 \"\"(empty string) -> switch to empty state
11604 'done -> switch to DONE
11605 'nextset -> switch to the next set of keywords
11606 'previousset -> switch to the previous set of keywords
11607 \"WAITING\" -> switch to the specified keyword, but only if it
11608 really is a member of `org-todo-keywords'."
11609 (interactive "P")
11610 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11611 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11612 'region-start-level 'region))
11613 org-loop-over-headlines-in-active-region)
11614 (org-map-entries
11615 `(org-todo ,arg)
11616 org-loop-over-headlines-in-active-region
11617 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11618 (if (equal arg '(16)) (setq arg 'nextset))
11619 (let ((org-blocker-hook org-blocker-hook)
11620 (case-fold-search nil))
11621 (when (equal arg '(64))
11622 (setq arg nil org-blocker-hook nil))
11623 (when (and org-blocker-hook
11624 (or org-inhibit-blocking
11625 (org-entry-get nil "NOBLOCKING")))
11626 (setq org-blocker-hook nil))
11627 (save-excursion
11628 (catch 'exit
11629 (org-back-to-heading t)
11630 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11631 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11632 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11633 (let* ((match-data (match-data))
11634 (startpos (point-at-bol))
11635 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11636 (org-log-done org-log-done)
11637 (org-log-repeat org-log-repeat)
11638 (org-todo-log-states org-todo-log-states)
11639 (org-inhibit-logging
11640 (if (equal arg 0)
11641 (progn (setq arg nil) 'note) org-inhibit-logging))
11642 (this (match-string 1))
11643 (hl-pos (match-beginning 0))
11644 (head (org-get-todo-sequence-head this))
11645 (ass (assoc head org-todo-kwd-alist))
11646 (interpret (nth 1 ass))
11647 (done-word (nth 3 ass))
11648 (final-done-word (nth 4 ass))
11649 (org-last-state (or this ""))
11650 (completion-ignore-case t)
11651 (member (member this org-todo-keywords-1))
11652 (tail (cdr member))
11653 (org-state (cond
11654 ((and org-todo-key-trigger
11655 (or (and (equal arg '(4))
11656 (eq org-use-fast-todo-selection 'prefix))
11657 (and (not arg) org-use-fast-todo-selection
11658 (not (eq org-use-fast-todo-selection
11659 'prefix)))))
11660 ;; Use fast selection
11661 (org-fast-todo-selection))
11662 ((and (equal arg '(4))
11663 (or (not org-use-fast-todo-selection)
11664 (not org-todo-key-trigger)))
11665 ;; Read a state with completion
11666 (org-icompleting-read
11667 "State: " (mapcar (lambda(x) (list x))
11668 org-todo-keywords-1)
11669 nil t))
11670 ((eq arg 'right)
11671 (if this
11672 (if tail (car tail) nil)
11673 (car org-todo-keywords-1)))
11674 ((eq arg 'left)
11675 (if (equal member org-todo-keywords-1)
11677 (if this
11678 (nth (- (length org-todo-keywords-1)
11679 (length tail) 2)
11680 org-todo-keywords-1)
11681 (org-last org-todo-keywords-1))))
11682 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11683 (setq arg nil))) ; hack to fall back to cycling
11684 (arg
11685 ;; user or caller requests a specific state
11686 (cond
11687 ((equal arg "") nil)
11688 ((eq arg 'none) nil)
11689 ((eq arg 'done) (or done-word (car org-done-keywords)))
11690 ((eq arg 'nextset)
11691 (or (car (cdr (member head org-todo-heads)))
11692 (car org-todo-heads)))
11693 ((eq arg 'previousset)
11694 (let ((org-todo-heads (reverse org-todo-heads)))
11695 (or (car (cdr (member head org-todo-heads)))
11696 (car org-todo-heads))))
11697 ((car (member arg org-todo-keywords-1)))
11698 ((stringp arg)
11699 (error "State `%s' not valid in this file" arg))
11700 ((nth (1- (prefix-numeric-value arg))
11701 org-todo-keywords-1))))
11702 ((null member) (or head (car org-todo-keywords-1)))
11703 ((equal this final-done-word) nil) ;; -> make empty
11704 ((null tail) nil) ;; -> first entry
11705 ((memq interpret '(type priority))
11706 (if (eq this-command last-command)
11707 (car tail)
11708 (if (> (length tail) 0)
11709 (or done-word (car org-done-keywords))
11710 nil)))
11712 (car tail))))
11713 (org-state (or
11714 (run-hook-with-args-until-success
11715 'org-todo-get-default-hook org-state org-last-state)
11716 org-state))
11717 (next (if org-state (concat " " org-state " ") " "))
11718 (change-plist (list :type 'todo-state-change :from this :to org-state
11719 :position startpos))
11720 dolog now-done-p)
11721 (when org-blocker-hook
11722 (setq org-last-todo-state-is-todo
11723 (not (member this org-done-keywords)))
11724 (unless (save-excursion
11725 (save-match-data
11726 (org-with-wide-buffer
11727 (run-hook-with-args-until-failure
11728 'org-blocker-hook change-plist))))
11729 (if (org-called-interactively-p 'interactive)
11730 (error "TODO state change from %s to %s blocked" this org-state)
11731 ;; fail silently
11732 (message "TODO state change from %s to %s blocked" this org-state)
11733 (throw 'exit nil))))
11734 (store-match-data match-data)
11735 (replace-match next t t)
11736 (unless (pos-visible-in-window-p hl-pos)
11737 (message "TODO state changed to %s" (org-trim next)))
11738 (unless head
11739 (setq head (org-get-todo-sequence-head org-state)
11740 ass (assoc head org-todo-kwd-alist)
11741 interpret (nth 1 ass)
11742 done-word (nth 3 ass)
11743 final-done-word (nth 4 ass)))
11744 (when (memq arg '(nextset previousset))
11745 (message "Keyword-Set %d/%d: %s"
11746 (- (length org-todo-sets) -1
11747 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11748 (length org-todo-sets)
11749 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11750 (setq org-last-todo-state-is-todo
11751 (not (member org-state org-done-keywords)))
11752 (setq now-done-p (and (member org-state org-done-keywords)
11753 (not (member this org-done-keywords))))
11754 (and logging (org-local-logging logging))
11755 (when (and (or org-todo-log-states org-log-done)
11756 (not (eq org-inhibit-logging t))
11757 (not (memq arg '(nextset previousset))))
11758 ;; we need to look at recording a time and note
11759 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11760 (nth 2 (assoc this org-todo-log-states))))
11761 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11762 (setq dolog 'time))
11763 (when (and org-state
11764 (member org-state org-not-done-keywords)
11765 (not (member this org-not-done-keywords)))
11766 ;; This is now a todo state and was not one before
11767 ;; If there was a CLOSED time stamp, get rid of it.
11768 (org-add-planning-info nil nil 'closed))
11769 (when (and now-done-p org-log-done)
11770 ;; It is now done, and it was not done before
11771 (org-add-planning-info 'closed (org-current-effective-time))
11772 (if (and (not dolog) (eq 'note org-log-done))
11773 (org-add-log-setup 'done org-state this 'findpos 'note)))
11774 (when (and org-state dolog)
11775 ;; This is a non-nil state, and we need to log it
11776 (org-add-log-setup 'state org-state this 'findpos dolog)))
11777 ;; Fixup tag positioning
11778 (org-todo-trigger-tag-changes org-state)
11779 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11780 (when org-provide-todo-statistics
11781 (org-update-parent-todo-statistics))
11782 (run-hooks 'org-after-todo-state-change-hook)
11783 (if (and arg (not (member org-state org-done-keywords)))
11784 (setq head (org-get-todo-sequence-head org-state)))
11785 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11786 ;; Do we need to trigger a repeat?
11787 (when now-done-p
11788 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11789 ;; This is for the agenda, take a snapshot of the headline.
11790 (save-match-data
11791 (setq org-agenda-headline-snapshot-before-repeat
11792 (org-get-heading))))
11793 (org-auto-repeat-maybe org-state))
11794 ;; Fixup cursor location if close to the keyword
11795 (if (and (outline-on-heading-p)
11796 (not (bolp))
11797 (save-excursion (beginning-of-line 1)
11798 (looking-at org-todo-line-regexp))
11799 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11800 (progn
11801 (goto-char (or (match-end 2) (match-end 1)))
11802 (and (looking-at " ") (just-one-space))))
11803 (when org-trigger-hook
11804 (save-excursion
11805 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11807 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11808 "Block turning an entry into a TODO, using the hierarchy.
11809 This checks whether the current task should be blocked from state
11810 changes. Such blocking occurs when:
11812 1. The task has children which are not all in a completed state.
11814 2. A task has a parent with the property :ORDERED:, and there
11815 are siblings prior to the current task with incomplete
11816 status.
11818 3. The parent of the task is blocked because it has siblings that should
11819 be done first, or is child of a block grandparent TODO entry."
11821 (if (not org-enforce-todo-dependencies)
11822 t ; if locally turned off don't block
11823 (catch 'dont-block
11824 ;; If this is not a todo state change, or if this entry is already DONE,
11825 ;; do not block
11826 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11827 (member (plist-get change-plist :from)
11828 (cons 'done org-done-keywords))
11829 (member (plist-get change-plist :to)
11830 (cons 'todo org-not-done-keywords))
11831 (not (plist-get change-plist :to)))
11832 (throw 'dont-block t))
11833 ;; If this task has children, and any are undone, it's blocked
11834 (save-excursion
11835 (org-back-to-heading t)
11836 (let ((this-level (funcall outline-level)))
11837 (outline-next-heading)
11838 (let ((child-level (funcall outline-level)))
11839 (while (and (not (eobp))
11840 (> child-level this-level))
11841 ;; this todo has children, check whether they are all
11842 ;; completed
11843 (if (and (not (org-entry-is-done-p))
11844 (org-entry-is-todo-p))
11845 (throw 'dont-block nil))
11846 (outline-next-heading)
11847 (setq child-level (funcall outline-level))))))
11848 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11849 ;; any previous siblings are undone, it's blocked
11850 (save-excursion
11851 (org-back-to-heading t)
11852 (let* ((pos (point))
11853 (parent-pos (and (org-up-heading-safe) (point))))
11854 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11855 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11856 (forward-line 1)
11857 (re-search-forward org-not-done-heading-regexp pos t))
11858 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11859 ;; Search further up the hierarchy, to see if an ancestor is blocked
11860 (while t
11861 (goto-char parent-pos)
11862 (if (not (looking-at org-not-done-heading-regexp))
11863 (throw 'dont-block t)) ; do not block, parent is not a TODO
11864 (setq pos (point))
11865 (setq parent-pos (and (org-up-heading-safe) (point)))
11866 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11867 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11868 (forward-line 1)
11869 (re-search-forward org-not-done-heading-regexp pos t))
11870 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11872 (defcustom org-track-ordered-property-with-tag nil
11873 "Should the ORDERED property also be shown as a tag?
11874 The ORDERED property decides if an entry should require subtasks to be
11875 completed in sequence. Since a property is not very visible, setting
11876 this option means that toggling the ORDERED property with the command
11877 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11878 not relevant for the behavior, but it makes things more visible.
11880 Note that toggling the tag with tags commands will not change the property
11881 and therefore not influence behavior!
11883 This can be t, meaning the tag ORDERED should be used, It can also be a
11884 string to select a different tag for this task."
11885 :group 'org-todo
11886 :type '(choice
11887 (const :tag "No tracking" nil)
11888 (const :tag "Track with ORDERED tag" t)
11889 (string :tag "Use other tag")))
11891 (defun org-toggle-ordered-property ()
11892 "Toggle the ORDERED property of the current entry.
11893 For better visibility, you can track the value of this property with a tag.
11894 See variable `org-track-ordered-property-with-tag'."
11895 (interactive)
11896 (let* ((t1 org-track-ordered-property-with-tag)
11897 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11898 (save-excursion
11899 (org-back-to-heading)
11900 (if (org-entry-get nil "ORDERED")
11901 (progn
11902 (org-delete-property "ORDERED")
11903 (and tag (org-toggle-tag tag 'off))
11904 (message "Subtasks can be completed in arbitrary order"))
11905 (org-entry-put nil "ORDERED" "t")
11906 (and tag (org-toggle-tag tag 'on))
11907 (message "Subtasks must be completed in sequence")))))
11909 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11910 (defun org-block-todo-from-checkboxes (change-plist)
11911 "Block turning an entry into a TODO, using checkboxes.
11912 This checks whether the current task should be blocked from state
11913 changes because there are unchecked boxes in this entry."
11914 (if (not org-enforce-todo-checkbox-dependencies)
11915 t ; if locally turned off don't block
11916 (catch 'dont-block
11917 ;; If this is not a todo state change, or if this entry is already DONE,
11918 ;; do not block
11919 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11920 (member (plist-get change-plist :from)
11921 (cons 'done org-done-keywords))
11922 (member (plist-get change-plist :to)
11923 (cons 'todo org-not-done-keywords))
11924 (not (plist-get change-plist :to)))
11925 (throw 'dont-block t))
11926 ;; If this task has checkboxes that are not checked, it's blocked
11927 (save-excursion
11928 (org-back-to-heading t)
11929 (let ((beg (point)) end)
11930 (outline-next-heading)
11931 (setq end (point))
11932 (goto-char beg)
11933 (if (org-list-search-forward
11934 (concat (org-item-beginning-re)
11935 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11936 "\\[[- ]\\]")
11937 end t)
11938 (progn
11939 (if (boundp 'org-blocked-by-checkboxes)
11940 (setq org-blocked-by-checkboxes t))
11941 (throw 'dont-block nil)))))
11942 t))) ; do not block
11944 (defun org-entry-blocked-p ()
11945 "Is the current entry blocked?"
11946 (if (org-entry-get nil "NOBLOCKING")
11947 nil ;; Never block this entry
11948 (not
11949 (run-hook-with-args-until-failure
11950 'org-blocker-hook
11951 (list :type 'todo-state-change
11952 :position (point)
11953 :from 'todo
11954 :to 'done)))))
11956 (defun org-update-statistics-cookies (all)
11957 "Update the statistics cookie, either from TODO or from checkboxes.
11958 This should be called with the cursor in a line with a statistics cookie."
11959 (interactive "P")
11960 (if all
11961 (progn
11962 (org-update-checkbox-count 'all)
11963 (org-map-entries 'org-update-parent-todo-statistics))
11964 (if (not (org-at-heading-p))
11965 (org-update-checkbox-count)
11966 (let ((pos (move-marker (make-marker) (point)))
11967 end l1 l2)
11968 (ignore-errors (org-back-to-heading t))
11969 (if (not (org-at-heading-p))
11970 (org-update-checkbox-count)
11971 (setq l1 (org-outline-level))
11972 (setq end (save-excursion
11973 (outline-next-heading)
11974 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11975 (point)))
11976 (if (and (save-excursion
11977 (re-search-forward
11978 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11979 (not (save-excursion (re-search-forward
11980 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11981 (org-update-checkbox-count)
11982 (if (and l2 (> l2 l1))
11983 (progn
11984 (goto-char end)
11985 (org-update-parent-todo-statistics))
11986 (goto-char pos)
11987 (beginning-of-line 1)
11988 (while (re-search-forward
11989 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11990 (point-at-eol) t)
11991 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11992 (goto-char pos)
11993 (move-marker pos nil)))))
11995 (defvar org-entry-property-inherited-from) ;; defined below
11996 (defun org-update-parent-todo-statistics ()
11997 "Update any statistics cookie in the parent of the current headline.
11998 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11999 the entire subtree and this will travel up the hierarchy and update
12000 statistics everywhere."
12001 (let* ((prop (save-excursion (org-up-heading-safe)
12002 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12003 (recursive (or (not org-hierarchical-todo-statistics)
12004 (and prop (string-match "\\<recursive\\>" prop))))
12005 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12007 (first t)
12008 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12009 level ltoggle l1 new ndel
12010 (cnt-all 0) (cnt-done 0) is-percent kwd
12011 checkbox-beg ov ovs ove cookie-present)
12012 (catch 'exit
12013 (save-excursion
12014 (beginning-of-line 1)
12015 (setq ltoggle (funcall outline-level))
12016 ;; Three situations are to consider:
12018 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12019 ;; to the top-level ancestor on the headline;
12021 ;; 2. If parent has "recursive" property, repeat up to the
12022 ;; headline setting that property, taking inheritance into
12023 ;; account;
12025 ;; 3. Else, move up to direct parent and proceed only once.
12026 (while (and (setq level (org-up-heading-safe))
12027 (or recursive first)
12028 (>= (point) lim))
12029 (setq first nil cookie-present nil)
12030 (unless (and level
12031 (not (string-match
12032 "\\<checkbox\\>"
12033 (downcase (or (org-entry-get nil "COOKIE_DATA")
12034 "")))))
12035 (throw 'exit nil))
12036 (while (re-search-forward box-re (point-at-eol) t)
12037 (setq cnt-all 0 cnt-done 0 cookie-present t)
12038 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12039 (save-match-data
12040 (unless (outline-next-heading) (throw 'exit nil))
12041 (while (and (looking-at org-complex-heading-regexp)
12042 (> (setq l1 (length (match-string 1))) level))
12043 (setq kwd (and (or recursive (= l1 ltoggle))
12044 (match-string 2)))
12045 (if (or (eq org-provide-todo-statistics 'all-headlines)
12046 (and (listp org-provide-todo-statistics)
12047 (or (member kwd org-provide-todo-statistics)
12048 (member kwd org-done-keywords))))
12049 (setq cnt-all (1+ cnt-all))
12050 (if (eq org-provide-todo-statistics t)
12051 (and kwd (setq cnt-all (1+ cnt-all)))))
12052 (and (member kwd org-done-keywords)
12053 (setq cnt-done (1+ cnt-done)))
12054 (outline-next-heading)))
12055 (setq new
12056 (if is-percent
12057 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12058 (format "[%d/%d]" cnt-done cnt-all))
12059 ndel (- (match-end 0) checkbox-beg))
12060 ;; handle overlays when updating cookie from column view
12061 (when (setq ov (car (overlays-at checkbox-beg)))
12062 (setq ovs (overlay-start ov) ove (overlay-end ov))
12063 (delete-overlay ov))
12064 (goto-char checkbox-beg)
12065 (insert new)
12066 (delete-region (point) (+ (point) ndel))
12067 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12068 (when ov (move-overlay ov ovs ove)))
12069 (when cookie-present
12070 (run-hook-with-args 'org-after-todo-statistics-hook
12071 cnt-done (- cnt-all cnt-done))))))
12072 (run-hooks 'org-todo-statistics-hook)))
12074 (defvar org-after-todo-statistics-hook nil
12075 "Hook that is called after a TODO statistics cookie has been updated.
12076 Each function is called with two arguments: the number of not-done entries
12077 and the number of done entries.
12079 For example, the following function, when added to this hook, will switch
12080 an entry to DONE when all children are done, and back to TODO when new
12081 entries are set to a TODO status. Note that this hook is only called
12082 when there is a statistics cookie in the headline!
12084 (defun org-summary-todo (n-done n-not-done)
12085 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12086 (let (org-log-done org-log-states) ; turn off logging
12087 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12090 (defvar org-todo-statistics-hook nil
12091 "Hook that is run whenever Org thinks TODO statistics should be updated.
12092 This hook runs even if there is no statistics cookie present, in which case
12093 `org-after-todo-statistics-hook' would not run.")
12095 (defun org-todo-trigger-tag-changes (state)
12096 "Apply the changes defined in `org-todo-state-tags-triggers'."
12097 (let ((l org-todo-state-tags-triggers)
12098 changes)
12099 (when (or (not state) (equal state ""))
12100 (setq changes (append changes (cdr (assoc "" l)))))
12101 (when (and (stringp state) (> (length state) 0))
12102 (setq changes (append changes (cdr (assoc state l)))))
12103 (when (member state org-not-done-keywords)
12104 (setq changes (append changes (cdr (assoc 'todo l)))))
12105 (when (member state org-done-keywords)
12106 (setq changes (append changes (cdr (assoc 'done l)))))
12107 (dolist (c changes)
12108 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12110 (defun org-local-logging (value)
12111 "Get logging settings from a property VALUE."
12112 (let* (words w a)
12113 ;; directly set the variables, they are already local.
12114 (setq org-log-done nil
12115 org-log-repeat nil
12116 org-todo-log-states nil)
12117 (setq words (org-split-string value))
12118 (while (setq w (pop words))
12119 (cond
12120 ((setq a (assoc w org-startup-options))
12121 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12122 (set (nth 1 a) (nth 2 a))))
12123 ((setq a (org-extract-log-state-settings w))
12124 (and (member (car a) org-todo-keywords-1)
12125 (push a org-todo-log-states)))))))
12127 (defun org-get-todo-sequence-head (kwd)
12128 "Return the head of the TODO sequence to which KWD belongs.
12129 If KWD is not set, check if there is a text property remembering the
12130 right sequence."
12131 (let (p)
12132 (cond
12133 ((not kwd)
12134 (or (get-text-property (point-at-bol) 'org-todo-head)
12135 (progn
12136 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12137 nil (point-at-eol)))
12138 (get-text-property p 'org-todo-head))))
12139 ((not (member kwd org-todo-keywords-1))
12140 (car org-todo-keywords-1))
12141 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12143 (defun org-fast-todo-selection ()
12144 "Fast TODO keyword selection with single keys.
12145 Returns the new TODO keyword, or nil if no state change should occur."
12146 (let* ((fulltable org-todo-key-alist)
12147 (done-keywords org-done-keywords) ;; needed for the faces.
12148 (maxlen (apply 'max (mapcar
12149 (lambda (x)
12150 (if (stringp (car x)) (string-width (car x)) 0))
12151 fulltable)))
12152 (expert nil)
12153 (fwidth (+ maxlen 3 1 3))
12154 (ncol (/ (- (window-width) 4) fwidth))
12155 tg cnt e c tbl
12156 groups ingroup)
12157 (save-excursion
12158 (save-window-excursion
12159 (if expert
12160 (set-buffer (get-buffer-create " *Org todo*"))
12161 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12162 (erase-buffer)
12163 (org-set-local 'org-done-keywords done-keywords)
12164 (setq tbl fulltable cnt 0)
12165 (while (setq e (pop tbl))
12166 (cond
12167 ((equal e '(:startgroup))
12168 (push '() groups) (setq ingroup t)
12169 (when (not (= cnt 0))
12170 (setq cnt 0)
12171 (insert "\n"))
12172 (insert "{ "))
12173 ((equal e '(:endgroup))
12174 (setq ingroup nil cnt 0)
12175 (insert "}\n"))
12176 ((equal e '(:newline))
12177 (when (not (= cnt 0))
12178 (setq cnt 0)
12179 (insert "\n")
12180 (setq e (car tbl))
12181 (while (equal (car tbl) '(:newline))
12182 (insert "\n")
12183 (setq tbl (cdr tbl)))))
12185 (setq tg (car e) c (cdr e))
12186 (if ingroup (push tg (car groups)))
12187 (setq tg (org-add-props tg nil 'face
12188 (org-get-todo-face tg)))
12189 (if (and (= cnt 0) (not ingroup)) (insert " "))
12190 (insert "[" c "] " tg (make-string
12191 (- fwidth 4 (length tg)) ?\ ))
12192 (when (= (setq cnt (1+ cnt)) ncol)
12193 (insert "\n")
12194 (if ingroup (insert " "))
12195 (setq cnt 0)))))
12196 (insert "\n")
12197 (goto-char (point-min))
12198 (if (not expert) (org-fit-window-to-buffer))
12199 (message "[a-z..]:Set [SPC]:clear")
12200 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12201 (cond
12202 ((or (= c ?\C-g)
12203 (and (= c ?q) (not (rassoc c fulltable))))
12204 (setq quit-flag t))
12205 ((= c ?\ ) nil)
12206 ((setq e (rassoc c fulltable) tg (car e))
12208 (t (setq quit-flag t)))))))
12210 (defun org-entry-is-todo-p ()
12211 (member (org-get-todo-state) org-not-done-keywords))
12213 (defun org-entry-is-done-p ()
12214 (member (org-get-todo-state) org-done-keywords))
12216 (defun org-get-todo-state ()
12217 (save-excursion
12218 (org-back-to-heading t)
12219 (and (looking-at org-todo-line-regexp)
12220 (match-end 2)
12221 (match-string 2))))
12223 (defun org-at-date-range-p (&optional inactive-ok)
12224 "Is the cursor inside a date range?"
12225 (interactive)
12226 (save-excursion
12227 (catch 'exit
12228 (let ((pos (point)))
12229 (skip-chars-backward "^[<\r\n")
12230 (skip-chars-backward "<[")
12231 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12232 (>= (match-end 0) pos)
12233 (throw 'exit t))
12234 (skip-chars-backward "^<[\r\n")
12235 (skip-chars-backward "<[")
12236 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12237 (>= (match-end 0) pos)
12238 (throw 'exit t)))
12239 nil)))
12241 (defun org-get-repeat (&optional tagline)
12242 "Check if there is a deadline/schedule with repeater in this entry."
12243 (save-match-data
12244 (save-excursion
12245 (org-back-to-heading t)
12246 (and (re-search-forward (if tagline
12247 (concat tagline "\\s-*" org-repeat-re)
12248 org-repeat-re)
12249 (org-entry-end-position) t)
12250 (match-string-no-properties 1)))))
12252 (defvar org-last-changed-timestamp)
12253 (defvar org-last-inserted-timestamp)
12254 (defvar org-log-post-message)
12255 (defvar org-log-note-purpose)
12256 (defvar org-log-note-how)
12257 (defvar org-log-note-extra)
12258 (defun org-auto-repeat-maybe (done-word)
12259 "Check if the current headline contains a repeated deadline/schedule.
12260 If yes, set TODO state back to what it was and change the base date
12261 of repeating deadline/scheduled time stamps to new date.
12262 This function is run automatically after each state change to a DONE state."
12263 ;; last-state is dynamically scoped into this function
12264 (let* ((repeat (org-get-repeat))
12265 (aa (assoc org-last-state org-todo-kwd-alist))
12266 (interpret (nth 1 aa))
12267 (head (nth 2 aa))
12268 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12269 (msg "Entry repeats: ")
12270 (org-log-done nil)
12271 (org-todo-log-states nil)
12272 re type n what ts time to-state)
12273 (when repeat
12274 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12275 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12276 org-todo-repeat-to-state))
12277 (unless (and to-state (member to-state org-todo-keywords-1))
12278 (setq to-state (if (eq interpret 'type) org-last-state head)))
12279 (org-todo to-state)
12280 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12281 (org-entry-put nil "LAST_REPEAT" (format-time-string
12282 (org-time-stamp-format t t))))
12283 (when org-log-repeat
12284 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12285 (memq 'org-add-log-note post-command-hook))
12286 ;; OK, we are already setup for some record
12287 (if (eq org-log-repeat 'note)
12288 ;; make sure we take a note, not only a time stamp
12289 (setq org-log-note-how 'note))
12290 ;; Set up for taking a record
12291 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12292 org-last-state
12293 'findpos org-log-repeat)))
12294 (org-back-to-heading t)
12295 (org-add-planning-info nil nil 'closed)
12296 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12297 org-deadline-time-regexp "\\)\\|\\("
12298 org-ts-regexp "\\)"))
12299 (while (re-search-forward
12300 re (save-excursion (outline-next-heading) (point)) t)
12301 (setq type (if (match-end 1) org-scheduled-string
12302 (if (match-end 3) org-deadline-string "Plain:"))
12303 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12304 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12305 (setq n (string-to-number (match-string 2 ts))
12306 what (match-string 3 ts))
12307 (if (equal what "w") (setq n (* n 7) what "d"))
12308 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12309 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12310 ;; Preparation, see if we need to modify the start date for the change
12311 (when (match-end 1)
12312 (setq time (save-match-data (org-time-string-to-time ts)))
12313 (cond
12314 ((equal (match-string 1 ts) ".")
12315 ;; Shift starting date to today
12316 (org-timestamp-change
12317 (- (org-today) (time-to-days time))
12318 'day))
12319 ((equal (match-string 1 ts) "+")
12320 (let ((nshiftmax 10) (nshift 0))
12321 (while (or (= nshift 0)
12322 (<= (time-to-days time)
12323 (time-to-days (current-time))))
12324 (when (= (incf nshift) nshiftmax)
12325 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12326 (error "Abort")))
12327 (org-timestamp-change n (cdr (assoc what whata)))
12328 (org-at-timestamp-p t)
12329 (setq ts (match-string 1))
12330 (setq time (save-match-data (org-time-string-to-time ts)))))
12331 (org-timestamp-change (- n) (cdr (assoc what whata)))
12332 ;; rematch, so that we have everything in place for the real shift
12333 (org-at-timestamp-p t)
12334 (setq ts (match-string 1))
12335 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12336 (org-timestamp-change n (cdr (assoc what whata)))
12337 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12338 (setq org-log-post-message msg)
12339 (message "%s" msg))))
12341 (defun org-show-todo-tree (arg)
12342 "Make a compact tree which shows all headlines marked with TODO.
12343 The tree will show the lines where the regexp matches, and all higher
12344 headlines above the match.
12345 With a \\[universal-argument] prefix, prompt for a regexp to match.
12346 With a numeric prefix N, construct a sparse tree for the Nth element
12347 of `org-todo-keywords-1'."
12348 (interactive "P")
12349 (let ((case-fold-search nil)
12350 (kwd-re
12351 (cond ((null arg) org-not-done-regexp)
12352 ((equal arg '(4))
12353 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12354 (mapcar 'list org-todo-keywords-1))))
12355 (concat "\\("
12356 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12357 "\\)\\>")))
12358 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12359 (regexp-quote (nth (1- (prefix-numeric-value arg))
12360 org-todo-keywords-1)))
12361 (t (error "Invalid prefix argument: %s" arg)))))
12362 (message "%d TODO entries found"
12363 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12365 (defun org-deadline (&optional remove time)
12366 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12367 With argument REMOVE, remove any deadline from the item.
12368 With argument TIME, set the deadline at the corresponding date. TIME
12369 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12370 (interactive "P")
12371 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12372 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12373 'region-start-level 'region))
12374 org-loop-over-headlines-in-active-region)
12375 (org-map-entries
12376 `(org-deadline ',remove ,time)
12377 org-loop-over-headlines-in-active-region
12378 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12379 (let* ((old-date (org-entry-get nil "DEADLINE"))
12380 (repeater (and old-date
12381 (string-match
12382 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12383 old-date)
12384 (match-string 1 old-date))))
12385 (if remove
12386 (progn
12387 (when (and old-date org-log-redeadline)
12388 (org-add-log-setup 'deldeadline nil old-date 'findpos
12389 org-log-redeadline))
12390 (org-remove-timestamp-with-keyword org-deadline-string)
12391 (message "Item no longer has a deadline."))
12392 (org-add-planning-info 'deadline time 'closed)
12393 (when (and old-date org-log-redeadline
12394 (not (equal old-date
12395 (substring org-last-inserted-timestamp 1 -1))))
12396 (org-add-log-setup 'redeadline nil old-date 'findpos
12397 org-log-redeadline))
12398 (when repeater
12399 (save-excursion
12400 (org-back-to-heading t)
12401 (when (re-search-forward (concat org-deadline-string " "
12402 org-last-inserted-timestamp)
12403 (save-excursion
12404 (outline-next-heading) (point)) t)
12405 (goto-char (1- (match-end 0)))
12406 (insert " " repeater)
12407 (setq org-last-inserted-timestamp
12408 (concat (substring org-last-inserted-timestamp 0 -1)
12409 " " repeater
12410 (substring org-last-inserted-timestamp -1))))))
12411 (message "Deadline on %s" org-last-inserted-timestamp)))))
12413 (defun org-schedule (&optional remove time)
12414 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12415 With argument REMOVE, remove any scheduling date from the item.
12416 With argument TIME, scheduled at the corresponding date. TIME can
12417 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12418 (interactive "P")
12419 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12420 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12421 'region-start-level 'region))
12422 org-loop-over-headlines-in-active-region)
12423 (org-map-entries
12424 `(org-schedule ',remove ,time)
12425 org-loop-over-headlines-in-active-region
12426 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12427 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12428 (repeater (and old-date
12429 (string-match
12430 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12431 old-date)
12432 (match-string 1 old-date))))
12433 (if remove
12434 (progn
12435 (when (and old-date org-log-reschedule)
12436 (org-add-log-setup 'delschedule nil old-date 'findpos
12437 org-log-reschedule))
12438 (org-remove-timestamp-with-keyword org-scheduled-string)
12439 (message "Item is no longer scheduled."))
12440 (org-add-planning-info 'scheduled time 'closed)
12441 (when (and old-date org-log-reschedule
12442 (not (equal old-date
12443 (substring org-last-inserted-timestamp 1 -1))))
12444 (org-add-log-setup 'reschedule nil old-date 'findpos
12445 org-log-reschedule))
12446 (when repeater
12447 (save-excursion
12448 (org-back-to-heading t)
12449 (when (re-search-forward (concat org-scheduled-string " "
12450 org-last-inserted-timestamp)
12451 (save-excursion
12452 (outline-next-heading) (point)) t)
12453 (goto-char (1- (match-end 0)))
12454 (insert " " repeater)
12455 (setq org-last-inserted-timestamp
12456 (concat (substring org-last-inserted-timestamp 0 -1)
12457 " " repeater
12458 (substring org-last-inserted-timestamp -1))))))
12459 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12461 (defun org-get-scheduled-time (pom &optional inherit)
12462 "Get the scheduled time as a time tuple, of a format suitable
12463 for calling org-schedule with, or if there is no scheduling,
12464 returns nil."
12465 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12466 (when time
12467 (apply 'encode-time (org-parse-time-string time)))))
12469 (defun org-get-deadline-time (pom &optional inherit)
12470 "Get the deadline as a time tuple, of a format suitable for
12471 calling org-deadline with, or if there is no scheduling, returns
12472 nil."
12473 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12474 (when time
12475 (apply 'encode-time (org-parse-time-string time)))))
12477 (defun org-remove-timestamp-with-keyword (keyword)
12478 "Remove all time stamps with KEYWORD in the current entry."
12479 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12480 beg)
12481 (save-excursion
12482 (org-back-to-heading t)
12483 (setq beg (point))
12484 (outline-next-heading)
12485 (while (re-search-backward re beg t)
12486 (replace-match "")
12487 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12488 (equal (char-before) ?\ ))
12489 (backward-delete-char 1)
12490 (if (string-match "^[ \t]*$" (buffer-substring
12491 (point-at-bol) (point-at-eol)))
12492 (delete-region (point-at-bol)
12493 (min (point-max) (1+ (point-at-eol))))))))))
12495 (defun org-add-planning-info (what &optional time &rest remove)
12496 "Insert new timestamp with keyword in the line directly after the headline.
12497 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12498 If non is given, the user is prompted for a date.
12499 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12500 be removed."
12501 (interactive)
12502 (let (org-time-was-given org-end-time-was-given ts
12503 end default-time default-input)
12505 (catch 'exit
12506 (when (and (memq what '(scheduled deadline))
12507 (or (not time)
12508 (and (stringp time)
12509 (string-match "^[-+]+[0-9]" time))))
12510 ;; Try to get a default date/time from existing timestamp
12511 (save-excursion
12512 (org-back-to-heading t)
12513 (setq end (save-excursion (outline-next-heading) (point)))
12514 (when (re-search-forward (if (eq what 'scheduled)
12515 org-scheduled-time-regexp
12516 org-deadline-time-regexp)
12517 end t)
12518 (setq ts (match-string 1)
12519 default-time
12520 (apply 'encode-time (org-parse-time-string ts))
12521 default-input (and ts (org-get-compact-tod ts))))))
12522 (when what
12523 (setq time
12524 (if (stringp time)
12525 ;; This is a string (relative or absolute), set proper date
12526 (apply 'encode-time
12527 (org-read-date-analyze
12528 time default-time (decode-time default-time)))
12529 ;; If necessary, get the time from the user
12530 (or time (org-read-date nil 'to-time nil nil
12531 default-time default-input)))))
12533 (when (and org-insert-labeled-timestamps-at-point
12534 (member what '(scheduled deadline)))
12535 (insert
12536 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12537 (org-insert-time-stamp time org-time-was-given
12538 nil nil nil (list org-end-time-was-given))
12539 (setq what nil))
12540 (save-excursion
12541 (save-restriction
12542 (let (col list elt ts buffer-invisibility-spec)
12543 (org-back-to-heading t)
12544 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12545 (goto-char (match-end 1))
12546 (setq col (current-column))
12547 (goto-char (match-end 0))
12548 (if (eobp) (insert "\n") (forward-char 1))
12549 (when (and (not what)
12550 (not (looking-at
12551 (concat "[ \t]*"
12552 org-keyword-time-not-clock-regexp))))
12553 ;; Nothing to add, nothing to remove...... :-)
12554 (throw 'exit nil))
12555 (if (and (not (looking-at org-outline-regexp))
12556 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12557 "[^\r\n]*"))
12558 (not (equal (match-string 1) org-clock-string)))
12559 (narrow-to-region (match-beginning 0) (match-end 0))
12560 (insert-before-markers "\n")
12561 (backward-char 1)
12562 (narrow-to-region (point) (point))
12563 (and org-adapt-indentation (org-indent-to-column col)))
12564 ;; Check if we have to remove something.
12565 (setq list (cons what remove))
12566 (while list
12567 (setq elt (pop list))
12568 (when (or (and (eq elt 'scheduled)
12569 (re-search-forward org-scheduled-time-regexp nil t))
12570 (and (eq elt 'deadline)
12571 (re-search-forward org-deadline-time-regexp nil t))
12572 (and (eq elt 'closed)
12573 (re-search-forward org-closed-time-regexp nil t)))
12574 (replace-match "")
12575 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12576 (and (looking-at "[ \t]+") (replace-match ""))
12577 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12578 (when what
12579 (insert
12580 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12581 (cond ((eq what 'scheduled) org-scheduled-string)
12582 ((eq what 'deadline) org-deadline-string)
12583 ((eq what 'closed) org-closed-string))
12584 " ")
12585 (setq ts (org-insert-time-stamp
12586 time
12587 (or org-time-was-given
12588 (and (eq what 'closed) org-log-done-with-time))
12589 (eq what 'closed)
12590 nil nil (list org-end-time-was-given)))
12591 (insert
12592 (if (not (or (bolp) (eq (char-before) ?\ )
12593 (memq (char-after) '(32 10))
12594 (eobp))) " " ""))
12595 (end-of-line 1))
12596 (goto-char (point-min))
12597 (widen)
12598 (if (and (looking-at "[ \t]*\n")
12599 (equal (char-before) ?\n))
12600 (delete-region (1- (point)) (point-at-eol)))
12601 ts))))))
12603 (defvar org-log-note-marker (make-marker))
12604 (defvar org-log-note-purpose nil)
12605 (defvar org-log-note-state nil)
12606 (defvar org-log-note-previous-state nil)
12607 (defvar org-log-note-how nil)
12608 (defvar org-log-note-extra nil)
12609 (defvar org-log-note-window-configuration nil)
12610 (defvar org-log-note-return-to (make-marker))
12611 (defvar org-log-note-effective-time nil
12612 "Remembered current time so that dynamically scoped
12613 `org-extend-today-until' affects tha timestamps in state change
12614 log")
12616 (defvar org-log-post-message nil
12617 "Message to be displayed after a log note has been stored.
12618 The auto-repeater uses this.")
12620 (defun org-add-note ()
12621 "Add a note to the current entry.
12622 This is done in the same way as adding a state change note."
12623 (interactive)
12624 (org-add-log-setup 'note nil nil 'findpos nil))
12626 (defvar org-property-end-re)
12627 (defun org-add-log-setup (&optional purpose state prev-state
12628 findpos how extra)
12629 "Set up the post command hook to take a note.
12630 If this is about to TODO state change, the new state is expected in STATE.
12631 When FINDPOS is non-nil, find the correct position for the note in
12632 the current entry. If not, assume that it can be inserted at point.
12633 HOW is an indicator what kind of note should be created.
12634 EXTRA is additional text that will be inserted into the notes buffer."
12635 (let* ((org-log-into-drawer (org-log-into-drawer))
12636 (drawer (cond ((stringp org-log-into-drawer)
12637 org-log-into-drawer)
12638 (org-log-into-drawer "LOGBOOK"))))
12639 (save-restriction
12640 (save-excursion
12641 (when findpos
12642 (org-back-to-heading t)
12643 (narrow-to-region (point) (save-excursion
12644 (outline-next-heading) (point)))
12645 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12646 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12647 "[^\r\n]*\\)?"))
12648 (goto-char (match-end 0))
12649 (cond
12650 (drawer
12651 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12652 nil t)
12653 (progn
12654 (goto-char (match-end 0))
12655 (or org-log-states-order-reversed
12656 (and (re-search-forward org-property-end-re nil t)
12657 (goto-char (1- (match-beginning 0))))))
12658 (insert "\n:" drawer ":\n:END:")
12659 (beginning-of-line 0)
12660 (org-indent-line)
12661 (beginning-of-line 2)
12662 (org-indent-line)
12663 (end-of-line 0)))
12664 ((and org-log-state-notes-insert-after-drawers
12665 (save-excursion
12666 (forward-line) (looking-at org-drawer-regexp)))
12667 (forward-line)
12668 (while (looking-at org-drawer-regexp)
12669 (goto-char (match-end 0))
12670 (re-search-forward org-property-end-re (point-max) t)
12671 (forward-line))
12672 (forward-line -1)))
12673 (unless org-log-states-order-reversed
12674 (and (= (char-after) ?\n) (forward-char 1))
12675 (org-skip-over-state-notes)
12676 (skip-chars-backward " \t\n\r")))
12677 (move-marker org-log-note-marker (point))
12678 (setq org-log-note-purpose purpose
12679 org-log-note-state state
12680 org-log-note-previous-state prev-state
12681 org-log-note-how how
12682 org-log-note-extra extra
12683 org-log-note-effective-time (org-current-effective-time))
12684 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12686 (defun org-skip-over-state-notes ()
12687 "Skip past the list of State notes in an entry."
12688 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12689 (when (ignore-errors (goto-char (org-in-item-p)))
12690 (let* ((struct (org-list-struct))
12691 (prevs (org-list-prevs-alist struct)))
12692 (while (looking-at "[ \t]*- State")
12693 (goto-char (or (org-list-get-next-item (point) struct prevs)
12694 (org-list-get-item-end (point) struct)))))))
12696 (defun org-add-log-note (&optional purpose)
12697 "Pop up a window for taking a note, and add this note later at point."
12698 (remove-hook 'post-command-hook 'org-add-log-note)
12699 (setq org-log-note-window-configuration (current-window-configuration))
12700 (delete-other-windows)
12701 (move-marker org-log-note-return-to (point))
12702 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12703 (goto-char org-log-note-marker)
12704 (org-switch-to-buffer-other-window "*Org Note*")
12705 (erase-buffer)
12706 (if (memq org-log-note-how '(time state))
12707 (let (current-prefix-arg) (org-store-log-note))
12708 (let ((org-inhibit-startup t)) (org-mode))
12709 (insert (format "# Insert note for %s.
12710 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12711 (cond
12712 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12713 ((eq org-log-note-purpose 'done) "closed todo item")
12714 ((eq org-log-note-purpose 'state)
12715 (format "state change from \"%s\" to \"%s\""
12716 (or org-log-note-previous-state "")
12717 (or org-log-note-state "")))
12718 ((eq org-log-note-purpose 'reschedule)
12719 "rescheduling")
12720 ((eq org-log-note-purpose 'delschedule)
12721 "no longer scheduled")
12722 ((eq org-log-note-purpose 'redeadline)
12723 "changing deadline")
12724 ((eq org-log-note-purpose 'deldeadline)
12725 "removing deadline")
12726 ((eq org-log-note-purpose 'refile)
12727 "refiling")
12728 ((eq org-log-note-purpose 'note)
12729 "this entry")
12730 (t (error "This should not happen")))))
12731 (if org-log-note-extra (insert org-log-note-extra))
12732 (org-set-local 'org-finish-function 'org-store-log-note)
12733 (run-hooks 'org-log-buffer-setup-hook)))
12735 (defvar org-note-abort nil) ; dynamically scoped
12736 (defun org-store-log-note ()
12737 "Finish taking a log note, and insert it to where it belongs."
12738 (let ((txt (buffer-string))
12739 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12740 lines ind bul)
12741 (kill-buffer (current-buffer))
12742 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12743 (setq txt (replace-match "" t t txt)))
12744 (if (string-match "\\s-+\\'" txt)
12745 (setq txt (replace-match "" t t txt)))
12746 (setq lines (org-split-string txt "\n"))
12747 (when (and note (string-match "\\S-" note))
12748 (setq note
12749 (org-replace-escapes
12750 note
12751 (list (cons "%u" (user-login-name))
12752 (cons "%U" user-full-name)
12753 (cons "%t" (format-time-string
12754 (org-time-stamp-format 'long 'inactive)
12755 org-log-note-effective-time))
12756 (cons "%T" (format-time-string
12757 (org-time-stamp-format 'long nil)
12758 org-log-note-effective-time))
12759 (cons "%d" (format-time-string
12760 (org-time-stamp-format nil 'inactive)
12761 org-log-note-effective-time))
12762 (cons "%D" (format-time-string
12763 (org-time-stamp-format nil nil)
12764 org-log-note-effective-time))
12765 (cons "%s" (if org-log-note-state
12766 (concat "\"" org-log-note-state "\"")
12767 ""))
12768 (cons "%S" (if org-log-note-previous-state
12769 (concat "\"" org-log-note-previous-state "\"")
12770 "\"\"")))))
12771 (if lines (setq note (concat note " \\\\")))
12772 (push note lines))
12773 (when (or current-prefix-arg org-note-abort)
12774 (when org-log-into-drawer
12775 (org-remove-empty-drawer-at
12776 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12777 org-log-note-marker))
12778 (setq lines nil))
12779 (when lines
12780 (with-current-buffer (marker-buffer org-log-note-marker)
12781 (save-excursion
12782 (goto-char org-log-note-marker)
12783 (move-marker org-log-note-marker nil)
12784 (end-of-line 1)
12785 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12786 (setq ind (save-excursion
12787 (if (ignore-errors (goto-char (org-in-item-p)))
12788 (let ((struct (org-list-struct)))
12789 (org-list-get-ind
12790 (org-list-get-top-point struct) struct))
12791 (skip-chars-backward " \r\t\n")
12792 (cond
12793 ((and (org-at-heading-p)
12794 org-adapt-indentation)
12795 (1+ (org-current-level)))
12796 ((org-at-heading-p) 0)
12797 (t (org-get-indentation))))))
12798 (setq bul (org-list-bullet-string "-"))
12799 (org-indent-line-to ind)
12800 (insert bul (pop lines))
12801 (let ((ind-body (+ (length bul) ind)))
12802 (while lines
12803 (insert "\n")
12804 (org-indent-line-to ind-body)
12805 (insert (pop lines))))
12806 (message "Note stored")
12807 (org-back-to-heading t)
12808 (org-cycle-hide-drawers 'children)))))
12809 (set-window-configuration org-log-note-window-configuration)
12810 (with-current-buffer (marker-buffer org-log-note-return-to)
12811 (goto-char org-log-note-return-to))
12812 (move-marker org-log-note-return-to nil)
12813 (and org-log-post-message (message "%s" org-log-post-message)))
12815 (defun org-remove-empty-drawer-at (drawer pos)
12816 "Remove an empty drawer DRAWER at position POS.
12817 POS may also be a marker."
12818 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12819 (save-excursion
12820 (save-restriction
12821 (widen)
12822 (goto-char pos)
12823 (if (org-in-regexp
12824 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12825 (replace-match ""))))))
12827 (defvar org-ts-type nil)
12828 (defun org-sparse-tree (&optional arg type)
12829 "Create a sparse tree, prompt for the details.
12830 This command can create sparse trees. You first need to select the type
12831 of match used to create the tree:
12833 t Show all TODO entries.
12834 T Show entries with a specific TODO keyword.
12835 m Show entries selected by a tags/property match.
12836 p Enter a property name and its value (both with completion on existing
12837 names/values) and show entries with that property.
12838 r Show entries matching a regular expression (`/' can be used as well).
12839 b Show deadlines and scheduled items before a date.
12840 a Show deadlines and scheduled items after a date.
12841 d Show deadlines due within `org-deadline-warning-days'.
12842 D Show deadlines and scheduled items between a date range."
12843 (interactive "P")
12844 (let (ans kwd value ts-type)
12845 (setq type (or type org-sparse-tree-default-date-type))
12846 (setq org-ts-type type)
12847 (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"
12848 (cond ((eq type 'all) "all timestamps")
12849 ((eq type 'scheduled) "only scheduled")
12850 ((eq type 'deadline) "only deadline")
12851 ((eq type 'active) "only active timestamps")
12852 ((eq type 'inactive) "only inactive timestamps")
12853 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12854 (t "scheduled/deadline")))
12855 (setq ans (read-char-exclusive))
12856 (cond
12857 ((equal ans ?c)
12858 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12859 ((equal ans ?d)
12860 (call-interactively 'org-check-deadlines))
12861 ((equal ans ?b)
12862 (call-interactively 'org-check-before-date))
12863 ((equal ans ?a)
12864 (call-interactively 'org-check-after-date))
12865 ((equal ans ?D)
12866 (call-interactively 'org-check-dates-range))
12867 ((equal ans ?t)
12868 (org-show-todo-tree nil))
12869 ((equal ans ?T)
12870 (org-show-todo-tree '(4)))
12871 ((member ans '(?T ?m))
12872 (call-interactively 'org-match-sparse-tree))
12873 ((member ans '(?p ?P))
12874 (setq kwd (org-icompleting-read "Property: "
12875 (mapcar 'list (org-buffer-property-keys))))
12876 (setq value (org-icompleting-read "Value: "
12877 (mapcar 'list (org-property-values kwd))))
12878 (unless (string-match "\\`{.*}\\'" value)
12879 (setq value (concat "\"" value "\"")))
12880 (org-match-sparse-tree arg (concat kwd "=" value)))
12881 ((member ans '(?r ?R ?/))
12882 (call-interactively 'org-occur))
12883 (t (error "No such sparse tree command \"%c\"" ans)))))
12885 (defvar org-occur-highlights nil
12886 "List of overlays used for occur matches.")
12887 (make-variable-buffer-local 'org-occur-highlights)
12888 (defvar org-occur-parameters nil
12889 "Parameters of the active org-occur calls.
12890 This is a list, each call to org-occur pushes as cons cell,
12891 containing the regular expression and the callback, onto the list.
12892 The list can contain several entries if `org-occur' has been called
12893 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12894 will only contain one set of parameters. When the highlights are
12895 removed (for example with `C-c C-c', or with the next edit (depending
12896 on `org-remove-highlights-with-change'), this variable is emptied
12897 as well.")
12898 (make-variable-buffer-local 'org-occur-parameters)
12900 (defun org-occur (regexp &optional keep-previous callback)
12901 "Make a compact tree which shows all matches of REGEXP.
12902 The tree will show the lines where the regexp matches, and all higher
12903 headlines above the match. It will also show the heading after the match,
12904 to make sure editing the matching entry is easy.
12905 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12906 call to `org-occur' will be kept, to allow stacking of calls to this
12907 command.
12908 If CALLBACK is non-nil, it is a function which is called to confirm
12909 that the match should indeed be shown."
12910 (interactive "sRegexp: \nP")
12911 (when (equal regexp "")
12912 (error "Regexp cannot be empty"))
12913 (unless keep-previous
12914 (org-remove-occur-highlights nil nil t))
12915 (push (cons regexp callback) org-occur-parameters)
12916 (let ((cnt 0))
12917 (save-excursion
12918 (goto-char (point-min))
12919 (if (or (not keep-previous) ; do not want to keep
12920 (not org-occur-highlights)) ; no previous matches
12921 ;; hide everything
12922 (org-overview))
12923 (while (re-search-forward regexp nil t)
12924 (when (or (not callback)
12925 (save-match-data (funcall callback)))
12926 (setq cnt (1+ cnt))
12927 (when org-highlight-sparse-tree-matches
12928 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12929 (org-show-context 'occur-tree))))
12930 (when org-remove-highlights-with-change
12931 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12932 nil 'local))
12933 (unless org-sparse-tree-open-archived-trees
12934 (org-hide-archived-subtrees (point-min) (point-max)))
12935 (run-hooks 'org-occur-hook)
12936 (if (org-called-interactively-p 'interactive)
12937 (message "%d match(es) for regexp %s" cnt regexp))
12938 cnt))
12940 (defun org-occur-next-match (&optional n reset)
12941 "Function for `next-error-function' to find sparse tree matches.
12942 N is the number of matches to move, when negative move backwards.
12943 RESET is entirely ignored - this function always goes back to the
12944 starting point when no match is found."
12945 (let* ((limit (if (< n 0) (point-min) (point-max)))
12946 (search-func (if (< n 0)
12947 'previous-single-char-property-change
12948 'next-single-char-property-change))
12949 (n (abs n))
12950 (pos (point))
12952 (catch 'exit
12953 (while (setq p1 (funcall search-func (point) 'org-type))
12954 (when (equal p1 limit)
12955 (goto-char pos)
12956 (error "No more matches"))
12957 (when (equal (get-char-property p1 'org-type) 'org-occur)
12958 (setq n (1- n))
12959 (when (= n 0)
12960 (goto-char p1)
12961 (throw 'exit (point))))
12962 (goto-char p1))
12963 (goto-char p1)
12964 (error "No more matches"))))
12966 (defun org-show-context (&optional key)
12967 "Make sure point and context are visible.
12968 How much context is shown depends upon the variables
12969 `org-show-hierarchy-above', `org-show-following-heading',
12970 `org-show-entry-below' and `org-show-siblings'."
12971 (let ((heading-p (org-at-heading-p t))
12972 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12973 (following-p (org-get-alist-option org-show-following-heading key))
12974 (entry-p (org-get-alist-option org-show-entry-below key))
12975 (siblings-p (org-get-alist-option org-show-siblings key)))
12976 (catch 'exit
12977 ;; Show heading or entry text
12978 (if (and heading-p (not entry-p))
12979 (org-flag-heading nil) ; only show the heading
12980 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12981 (org-show-hidden-entry))) ; show entire entry
12982 (when following-p
12983 ;; Show next sibling, or heading below text
12984 (save-excursion
12985 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12986 (org-flag-heading nil))))
12987 (when siblings-p (org-show-siblings))
12988 (when hierarchy-p
12989 ;; show all higher headings, possibly with siblings
12990 (save-excursion
12991 (while (and (condition-case nil
12992 (progn (org-up-heading-all 1) t)
12993 (error nil))
12994 (not (bobp)))
12995 (org-flag-heading nil)
12996 (when siblings-p (org-show-siblings))))))))
12998 (defvar org-reveal-start-hook nil
12999 "Hook run before revealing a location.")
13001 (defun org-reveal (&optional siblings)
13002 "Show current entry, hierarchy above it, and the following headline.
13003 This can be used to show a consistent set of context around locations
13004 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13005 not t for the search context.
13007 With optional argument SIBLINGS, on each level of the hierarchy all
13008 siblings are shown. This repairs the tree structure to what it would
13009 look like when opened with hierarchical calls to `org-cycle'.
13010 With double optional argument \\[universal-argument] \\[universal-argument], \
13011 go to the parent and show the
13012 entire tree."
13013 (interactive "P")
13014 (run-hooks 'org-reveal-start-hook)
13015 (let ((org-show-hierarchy-above t)
13016 (org-show-following-heading t)
13017 (org-show-siblings (if siblings t org-show-siblings)))
13018 (org-show-context nil))
13019 (when (equal siblings '(16))
13020 (save-excursion
13021 (when (org-up-heading-safe)
13022 (org-show-subtree)
13023 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13025 (defun org-highlight-new-match (beg end)
13026 "Highlight from BEG to END and mark the highlight is an occur headline."
13027 (let ((ov (make-overlay beg end)))
13028 (overlay-put ov 'face 'secondary-selection)
13029 (overlay-put ov 'org-type 'org-occur)
13030 (push ov org-occur-highlights)))
13032 (defun org-remove-occur-highlights (&optional beg end noremove)
13033 "Remove the occur highlights from the buffer.
13034 BEG and END are ignored. If NOREMOVE is nil, remove this function
13035 from the `before-change-functions' in the current buffer."
13036 (interactive)
13037 (unless org-inhibit-highlight-removal
13038 (mapc 'delete-overlay org-occur-highlights)
13039 (setq org-occur-highlights nil)
13040 (setq org-occur-parameters nil)
13041 (unless noremove
13042 (remove-hook 'before-change-functions
13043 'org-remove-occur-highlights 'local))))
13045 ;;;; Priorities
13047 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13048 "Regular expression matching the priority indicator.")
13050 (defvar org-remove-priority-next-time nil)
13052 (defun org-priority-up ()
13053 "Increase the priority of the current item."
13054 (interactive)
13055 (org-priority 'up))
13057 (defun org-priority-down ()
13058 "Decrease the priority of the current item."
13059 (interactive)
13060 (org-priority 'down))
13062 (defun org-priority (&optional action)
13063 "Change the priority of an item.
13064 ACTION can be `set', `up', `down', or a character."
13065 (interactive)
13066 (unless org-enable-priority-commands
13067 (error "Priority commands are disabled"))
13068 (setq action (or action 'set))
13069 (let (current new news have remove)
13070 (save-excursion
13071 (org-back-to-heading t)
13072 (if (looking-at org-priority-regexp)
13073 (setq current (string-to-char (match-string 2))
13074 have t))
13075 (cond
13076 ((eq action 'remove)
13077 (setq remove t new ?\ ))
13078 ((or (eq action 'set)
13079 (if (featurep 'xemacs) (characterp action) (integerp action)))
13080 (if (not (eq action 'set))
13081 (setq new action)
13082 (message "Priority %c-%c, SPC to remove: "
13083 org-highest-priority org-lowest-priority)
13084 (save-match-data
13085 (setq new (read-char-exclusive))))
13086 (if (and (= (upcase org-highest-priority) org-highest-priority)
13087 (= (upcase org-lowest-priority) org-lowest-priority))
13088 (setq new (upcase new)))
13089 (cond ((equal new ?\ ) (setq remove t))
13090 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13091 (error "Priority must be between `%c' and `%c'"
13092 org-highest-priority org-lowest-priority))))
13093 ((eq action 'up)
13094 (setq new (if have
13095 (1- current) ; normal cycling
13096 ;; last priority was empty
13097 (if (eq last-command this-command)
13098 org-lowest-priority ; wrap around empty to lowest
13099 ;; default
13100 (if org-priority-start-cycle-with-default
13101 org-default-priority
13102 (1- org-default-priority))))))
13103 ((eq action 'down)
13104 (setq new (if have
13105 (1+ current) ; normal cycling
13106 ;; last priority was empty
13107 (if (eq last-command this-command)
13108 org-highest-priority ; wrap around empty to highest
13109 ;; default
13110 (if org-priority-start-cycle-with-default
13111 org-default-priority
13112 (1+ org-default-priority))))))
13113 (t (error "Invalid action")))
13114 (if (or (< (upcase new) org-highest-priority)
13115 (> (upcase new) org-lowest-priority))
13116 (if (and (memq action '(up down))
13117 (not have) (not (eq last-command this-command)))
13118 ;; `new' is from default priority
13119 (error
13120 "The default can not be set, see `org-default-priority' why")
13121 ;; normal cycling: `new' is beyond highest/lowest priority
13122 ;; and is wrapped around to the empty priority
13123 (setq remove t)))
13124 (setq news (format "%c" new))
13125 (if have
13126 (if remove
13127 (replace-match "" t t nil 1)
13128 (replace-match news t t nil 2))
13129 (if remove
13130 (error "No priority cookie found in line")
13131 (let ((case-fold-search nil))
13132 (looking-at org-todo-line-regexp))
13133 (if (match-end 2)
13134 (progn
13135 (goto-char (match-end 2))
13136 (insert " [#" news "]"))
13137 (goto-char (match-beginning 3))
13138 (insert "[#" news "] "))))
13139 (org-preserve-lc (org-set-tags nil 'align)))
13140 (if remove
13141 (message "Priority removed")
13142 (message "Priority of current item set to %s" news))))
13144 (defun org-get-priority (s)
13145 "Find priority cookie and return priority."
13146 (if (functionp org-get-priority-function)
13147 (funcall org-get-priority-function)
13148 (save-match-data
13149 (if (not (string-match org-priority-regexp s))
13150 (* 1000 (- org-lowest-priority org-default-priority))
13151 (* 1000 (- org-lowest-priority
13152 (string-to-char (match-string 2 s))))))))
13154 ;;;; Tags
13156 (defvar org-agenda-archives-mode)
13157 (defvar org-map-continue-from nil
13158 "Position from where mapping should continue.
13159 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13161 (defvar org-scanner-tags nil
13162 "The current tag list while the tags scanner is running.")
13163 (defvar org-trust-scanner-tags nil
13164 "Should `org-get-tags-at' use the tags for the scanner.
13165 This is for internal dynamical scoping only.
13166 When this is non-nil, the function `org-get-tags-at' will return the value
13167 of `org-scanner-tags' instead of building the list by itself. This
13168 can lead to large speed-ups when the tags scanner is used in a file with
13169 many entries, and when the list of tags is retrieved, for example to
13170 obtain a list of properties. Building the tags list for each entry in such
13171 a file becomes an N^2 operation - but with this variable set, it scales
13172 as N.")
13174 (defun org-scan-tags (action matcher todo-only &optional start-level)
13175 "Scan headline tags with inheritance and produce output ACTION.
13177 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13178 or `agenda' to produce an entry list for an agenda view. It can also be
13179 a Lisp form or a function that should be called at each matched headline, in
13180 this case the return value is a list of all return values from these calls.
13182 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13183 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13184 only lines with a not-done TODO keyword are included in the output.
13185 This should be the same variable that was scoped into
13186 and set by `org-make-tags-matcher' when it constructed MATCHER.
13188 START-LEVEL can be a string with asterisks, reducing the scope to
13189 headlines matching this string."
13190 (require 'org-agenda)
13191 (let* ((re (concat "^"
13192 (if start-level
13193 ;; Get the correct level to match
13194 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13195 org-outline-regexp)
13196 " *\\(\\<\\("
13197 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13198 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13199 (props (list 'face 'default
13200 'done-face 'org-agenda-done
13201 'undone-face 'default
13202 'mouse-face 'highlight
13203 'org-not-done-regexp org-not-done-regexp
13204 'org-todo-regexp org-todo-regexp
13205 'org-complex-heading-regexp org-complex-heading-regexp
13206 'help-echo
13207 (format "mouse-2 or RET jump to org file %s"
13208 (abbreviate-file-name
13209 (or (buffer-file-name (buffer-base-buffer))
13210 (buffer-name (buffer-base-buffer)))))))
13211 (case-fold-search nil)
13212 (org-map-continue-from nil)
13213 lspos tags tags-list
13214 (tags-alist (list (cons 0 org-file-tags)))
13215 (llast 0) rtn rtn1 level category i txt
13216 todo marker entry priority)
13217 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13218 (setq action (list 'lambda nil action)))
13219 (save-excursion
13220 (goto-char (point-min))
13221 (when (eq action 'sparse-tree)
13222 (org-overview)
13223 (org-remove-occur-highlights))
13224 (while (re-search-forward re nil t)
13225 (setq org-map-continue-from nil)
13226 (catch :skip
13227 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13228 tags (if (match-end 4) (org-match-string-no-properties 4)))
13229 (goto-char (setq lspos (match-beginning 0)))
13230 (setq level (org-reduced-level (org-outline-level))
13231 category (org-get-category))
13232 (setq i llast llast level)
13233 ;; remove tag lists from same and sublevels
13234 (while (>= i level)
13235 (when (setq entry (assoc i tags-alist))
13236 (setq tags-alist (delete entry tags-alist)))
13237 (setq i (1- i)))
13238 ;; add the next tags
13239 (when tags
13240 (setq tags (org-split-string tags ":")
13241 tags-alist
13242 (cons (cons level tags) tags-alist)))
13243 ;; compile tags for current headline
13244 (setq tags-list
13245 (if org-use-tag-inheritance
13246 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13247 tags)
13248 org-scanner-tags tags-list)
13249 (when org-use-tag-inheritance
13250 (setcdr (car tags-alist)
13251 (mapcar (lambda (x)
13252 (setq x (copy-sequence x))
13253 (org-add-prop-inherited x))
13254 (cdar tags-alist))))
13255 (when (and tags org-use-tag-inheritance
13256 (or (not (eq t org-use-tag-inheritance))
13257 org-tags-exclude-from-inheritance))
13258 ;; selective inheritance, remove uninherited ones
13259 (setcdr (car tags-alist)
13260 (org-remove-uninherited-tags (cdar tags-alist))))
13261 (when (and
13263 ;; eval matcher only when the todo condition is OK
13264 (and (or (not todo-only) (member todo org-not-done-keywords))
13265 (let ((case-fold-search t) (org-trust-scanner-tags t))
13266 (eval matcher)))
13268 ;; Call the skipper, but return t if it does not skip,
13269 ;; so that the `and' form continues evaluating
13270 (progn
13271 (unless (eq action 'sparse-tree) (org-agenda-skip))
13274 ;; Check if timestamps are deselecting this entry
13275 (or (not todo-only)
13276 (and (member todo org-not-done-keywords)
13277 (or (not org-agenda-tags-todo-honor-ignore-options)
13278 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13280 ;; Extra check for the archive tag
13281 ;; FIXME: Does the skipper already do this????
13283 (not (member org-archive-tag tags-list))
13284 ;; we have an archive tag, should we use this anyway?
13285 (or (not org-agenda-skip-archived-trees)
13286 (and (eq action 'agenda) org-agenda-archives-mode))))
13288 ;; select this headline
13289 (cond
13290 ((eq action 'sparse-tree)
13291 (and org-highlight-sparse-tree-matches
13292 (org-get-heading) (match-end 0)
13293 (org-highlight-new-match
13294 (match-beginning 1) (match-end 1)))
13295 (org-show-context 'tags-tree))
13296 ((eq action 'agenda)
13297 (setq txt (org-agenda-format-item
13299 (concat
13300 (if (eq org-tags-match-list-sublevels 'indented)
13301 (make-string (1- level) ?.) "")
13302 (org-get-heading))
13303 level category
13304 tags-list)
13305 priority (org-get-priority txt))
13306 (goto-char lspos)
13307 (setq marker (org-agenda-new-marker))
13308 (org-add-props txt props
13309 'org-marker marker 'org-hd-marker marker 'org-category category
13310 'todo-state todo
13311 'priority priority 'type "tagsmatch")
13312 (push txt rtn))
13313 ((functionp action)
13314 (setq org-map-continue-from nil)
13315 (save-excursion
13316 (setq rtn1 (funcall action))
13317 (push rtn1 rtn)))
13318 (t (error "Invalid action")))
13320 ;; if we are to skip sublevels, jump to end of subtree
13321 (unless org-tags-match-list-sublevels
13322 (org-end-of-subtree t)
13323 (backward-char 1))))
13324 ;; Get the correct position from where to continue
13325 (if org-map-continue-from
13326 (goto-char org-map-continue-from)
13327 (and (= (point) lspos) (end-of-line 1)))))
13328 (when (and (eq action 'sparse-tree)
13329 (not org-sparse-tree-open-archived-trees))
13330 (org-hide-archived-subtrees (point-min) (point-max)))
13331 (nreverse rtn)))
13333 (defun org-remove-uninherited-tags (tags)
13334 "Remove all tags that are not inherited from the list TAGS."
13335 (cond
13336 ((eq org-use-tag-inheritance t)
13337 (if org-tags-exclude-from-inheritance
13338 (org-delete-all org-tags-exclude-from-inheritance tags)
13339 tags))
13340 ((not org-use-tag-inheritance) nil)
13341 ((stringp org-use-tag-inheritance)
13342 (delq nil (mapcar
13343 (lambda (x)
13344 (if (and (string-match org-use-tag-inheritance x)
13345 (not (member x org-tags-exclude-from-inheritance)))
13346 x nil))
13347 tags)))
13348 ((listp org-use-tag-inheritance)
13349 (delq nil (mapcar
13350 (lambda (x)
13351 (if (member x org-use-tag-inheritance) x nil))
13352 tags)))))
13354 (defun org-match-sparse-tree (&optional todo-only match)
13355 "Create a sparse tree according to tags string MATCH.
13356 MATCH can contain positive and negative selection of tags, like
13357 \"+WORK+URGENT-WITHBOSS\".
13358 If optional argument TODO-ONLY is non-nil, only select lines that are
13359 also TODO lines."
13360 (interactive "P")
13361 (org-agenda-prepare-buffers (list (current-buffer)))
13362 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13364 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13366 (defvar org-cached-props nil)
13367 (defun org-cached-entry-get (pom property)
13368 (if (or (eq t org-use-property-inheritance)
13369 (and (stringp org-use-property-inheritance)
13370 (string-match org-use-property-inheritance property))
13371 (and (listp org-use-property-inheritance)
13372 (member property org-use-property-inheritance)))
13373 ;; Caching is not possible, check it directly
13374 (org-entry-get pom property 'inherit)
13375 ;; Get all properties, so that we can do complicated checks easily
13376 (cdr (assoc property (or org-cached-props
13377 (setq org-cached-props
13378 (org-entry-properties pom)))))))
13380 (defun org-global-tags-completion-table (&optional files)
13381 "Return the list of all tags in all agenda buffer/files.
13382 Optional FILES argument is a list of files which can be used
13383 instead of the agenda files."
13384 (save-excursion
13385 (org-uniquify
13386 (delq nil
13387 (apply 'append
13388 (mapcar
13389 (lambda (file)
13390 (set-buffer (find-file-noselect file))
13391 (append (org-get-buffer-tags)
13392 (mapcar (lambda (x) (if (stringp (car-safe x))
13393 (list (car-safe x)) nil))
13394 org-tag-alist)))
13395 (if (and files (car files))
13396 files
13397 (org-agenda-files))))))))
13399 (defun org-make-tags-matcher (match)
13400 "Create the TAGS/TODO matcher form for the selection string MATCH.
13402 The variable `todo-only' is scoped dynamically into this function.
13403 It will be set to t if the matcher restricts matching to TODO entries,
13404 otherwise will not be touched.
13406 Returns a cons of the selection string MATCH and the constructed
13407 lisp form implementing the matcher. The matcher is to be evaluated
13408 at an Org entry, with point on the headline, and returns t if the
13409 entry matches the selection string MATCH. The returned lisp form
13410 references two variables with information about the entry, which
13411 must be bound around the form's evaluation: todo, the TODO keyword
13412 at the entry (or nil of none); and tags-list, the list of all tags
13413 at the entry including inherited ones. Additionally, the category
13414 of the entry (if any) must be specified as the text property
13415 'org-category on the headline.
13417 See also `org-scan-tags'.
13419 (declare (special todo-only))
13420 (unless (boundp 'todo-only)
13421 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13422 (unless match
13423 ;; Get a new match request, with completion
13424 (let ((org-last-tags-completion-table
13425 (org-global-tags-completion-table)))
13426 (setq match (org-completing-read-no-i
13427 "Match: " 'org-tags-completion-function nil nil nil
13428 'org-tags-history))))
13430 ;; Parse the string and create a lisp form
13431 (let ((match0 match)
13432 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13433 minus tag mm
13434 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13435 orterms term orlist re-p str-p level-p level-op time-p
13436 prop-p pn pv po gv rest)
13437 (if (string-match "/+" match)
13438 ;; match contains also a todo-matching request
13439 (progn
13440 (setq tagsmatch (substring match 0 (match-beginning 0))
13441 todomatch (substring match (match-end 0)))
13442 (if (string-match "^!" todomatch)
13443 (setq todo-only t todomatch (substring todomatch 1)))
13444 (if (string-match "^\\s-*$" todomatch)
13445 (setq todomatch nil)))
13446 ;; only matching tags
13447 (setq tagsmatch match todomatch nil))
13449 ;; Make the tags matcher
13450 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13451 (setq tagsmatcher t)
13452 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13453 (while (setq term (pop orterms))
13454 (while (and (equal (substring term -1) "\\") orterms)
13455 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13456 (while (string-match re term)
13457 (setq rest (substring term (match-end 0))
13458 minus (and (match-end 1)
13459 (equal (match-string 1 term) "-"))
13460 tag (save-match-data (replace-regexp-in-string
13461 "\\\\-" "-"
13462 (match-string 2 term)))
13463 re-p (equal (string-to-char tag) ?{)
13464 level-p (match-end 4)
13465 prop-p (match-end 5)
13466 mm (cond
13467 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13468 (level-p
13469 (setq level-op (org-op-to-function (match-string 3 term)))
13470 `(,level-op level ,(string-to-number
13471 (match-string 4 term))))
13472 (prop-p
13473 (setq pn (match-string 5 term)
13474 po (match-string 6 term)
13475 pv (match-string 7 term)
13476 re-p (equal (string-to-char pv) ?{)
13477 str-p (equal (string-to-char pv) ?\")
13478 time-p (save-match-data
13479 (string-match "^\"[[<].*[]>]\"$" pv))
13480 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13481 (if time-p (setq pv (org-matcher-time pv)))
13482 (setq po (org-op-to-function po (if time-p 'time str-p)))
13483 (cond
13484 ((equal pn "CATEGORY")
13485 (setq gv '(get-text-property (point) 'org-category)))
13486 ((equal pn "TODO")
13487 (setq gv 'todo))
13489 (setq gv `(org-cached-entry-get nil ,pn))))
13490 (if re-p
13491 (if (eq po 'org<>)
13492 `(not (string-match ,pv (or ,gv "")))
13493 `(string-match ,pv (or ,gv "")))
13494 (if str-p
13495 `(,po (or ,gv "") ,pv)
13496 `(,po (string-to-number (or ,gv ""))
13497 ,(string-to-number pv) ))))
13498 (t `(member ,tag tags-list)))
13499 mm (if minus (list 'not mm) mm)
13500 term rest)
13501 (push mm tagsmatcher))
13502 (push (if (> (length tagsmatcher) 1)
13503 (cons 'and tagsmatcher)
13504 (car tagsmatcher))
13505 orlist)
13506 (setq tagsmatcher nil))
13507 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13508 (setq tagsmatcher
13509 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13510 ;; Make the todo matcher
13511 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13512 (setq todomatcher t)
13513 (setq orterms (org-split-string todomatch "|") orlist nil)
13514 (while (setq term (pop orterms))
13515 (while (string-match re term)
13516 (setq minus (and (match-end 1)
13517 (equal (match-string 1 term) "-"))
13518 kwd (match-string 2 term)
13519 re-p (equal (string-to-char kwd) ?{)
13520 term (substring term (match-end 0))
13521 mm (if re-p
13522 `(string-match ,(substring kwd 1 -1) todo)
13523 (list 'equal 'todo kwd))
13524 mm (if minus (list 'not mm) mm))
13525 (push mm todomatcher))
13526 (push (if (> (length todomatcher) 1)
13527 (cons 'and todomatcher)
13528 (car todomatcher))
13529 orlist)
13530 (setq todomatcher nil))
13531 (setq todomatcher (if (> (length orlist) 1)
13532 (cons 'or orlist) (car orlist))))
13534 ;; Return the string and lisp forms of the matcher
13535 (setq matcher (if todomatcher
13536 (list 'and tagsmatcher todomatcher)
13537 tagsmatcher))
13538 (when todo-only
13539 (setq matcher (list 'and '(member todo org-not-done-keywords)
13540 matcher)))
13541 (cons match0 matcher)))
13543 (defun org-op-to-function (op &optional stringp)
13544 "Turn an operator into the appropriate function."
13545 (setq op
13546 (cond
13547 ((equal op "<" ) '(< string< org-time<))
13548 ((equal op ">" ) '(> org-string> org-time>))
13549 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13550 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13551 ((member op '("=" "==")) '(= string= org-time=))
13552 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13553 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13555 (defun org<> (a b) (not (= a b)))
13556 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13557 (defun org-string>= (a b) (not (string< a b)))
13558 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13559 (defun org-string<> (a b) (not (string= a b)))
13560 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13561 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13562 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13563 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13564 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13565 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13566 (defun org-2ft (s)
13567 "Convert S to a floating point time.
13568 If S is already a number, just return it. If it is a string, parse
13569 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13570 (cond
13571 ((numberp s) s)
13572 ((stringp s)
13573 (condition-case nil
13574 (float-time (apply 'encode-time (org-parse-time-string s)))
13575 (error 0.)))
13576 (t 0.)))
13578 (defun org-time-today ()
13579 "Time in seconds today at 0:00.
13580 Returns the float number of seconds since the beginning of the
13581 epoch to the beginning of today (00:00)."
13582 (float-time (apply 'encode-time
13583 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13585 (defun org-matcher-time (s)
13586 "Interpret a time comparison value."
13587 (save-match-data
13588 (cond
13589 ((string= s "<now>") (float-time))
13590 ((string= s "<today>") (org-time-today))
13591 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13592 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13593 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13594 (+ (org-time-today)
13595 (* (string-to-number (match-string 1 s))
13596 (cdr (assoc (match-string 2 s)
13597 '(("d" . 86400.0) ("w" . 604800.0)
13598 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13599 (t (org-2ft s)))))
13601 (defun org-match-any-p (re list)
13602 "Does re match any element of list?"
13603 (setq list (mapcar (lambda (x) (string-match re x)) list))
13604 (delq nil list))
13606 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13607 (defvar org-tags-overlay (make-overlay 1 1))
13608 (org-detach-overlay org-tags-overlay)
13610 (defun org-get-local-tags-at (&optional pos)
13611 "Get a list of tags defined in the current headline."
13612 (org-get-tags-at pos 'local))
13614 (defun org-get-local-tags ()
13615 "Get a list of tags defined in the current headline."
13616 (org-get-tags-at nil 'local))
13618 (defun org-get-tags-at (&optional pos local)
13619 "Get a list of all headline tags applicable at POS.
13620 POS defaults to point. If tags are inherited, the list contains
13621 the targets in the same sequence as the headlines appear, i.e.
13622 the tags of the current headline come last.
13623 When LOCAL is non-nil, only return tags from the current headline,
13624 ignore inherited ones."
13625 (interactive)
13626 (if (and org-trust-scanner-tags
13627 (or (not pos) (equal pos (point)))
13628 (not local))
13629 org-scanner-tags
13630 (let (tags ltags lastpos parent)
13631 (save-excursion
13632 (save-restriction
13633 (widen)
13634 (goto-char (or pos (point)))
13635 (save-match-data
13636 (catch 'done
13637 (condition-case nil
13638 (progn
13639 (org-back-to-heading t)
13640 (while (not (equal lastpos (point)))
13641 (setq lastpos (point))
13642 (when (looking-at
13643 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13644 (setq ltags (org-split-string
13645 (org-match-string-no-properties 1) ":"))
13646 (when parent
13647 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13648 (setq tags (append
13649 (if parent
13650 (org-remove-uninherited-tags ltags)
13651 ltags)
13652 tags)))
13653 (or org-use-tag-inheritance (throw 'done t))
13654 (if local (throw 'done t))
13655 (or (org-up-heading-safe) (error nil))
13656 (setq parent t)))
13657 (error nil)))))
13658 (if local
13659 tags
13660 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13662 (defun org-add-prop-inherited (s)
13663 (add-text-properties 0 (length s) '(inherited t) s)
13666 (defun org-toggle-tag (tag &optional onoff)
13667 "Toggle the tag TAG for the current line.
13668 If ONOFF is `on' or `off', don't toggle but set to this state."
13669 (let (res current)
13670 (save-excursion
13671 (org-back-to-heading t)
13672 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13673 (point-at-eol) t)
13674 (progn
13675 (setq current (match-string 1))
13676 (replace-match ""))
13677 (setq current ""))
13678 (setq current (nreverse (org-split-string current ":")))
13679 (cond
13680 ((eq onoff 'on)
13681 (setq res t)
13682 (or (member tag current) (push tag current)))
13683 ((eq onoff 'off)
13684 (or (not (member tag current)) (setq current (delete tag current))))
13685 (t (if (member tag current)
13686 (setq current (delete tag current))
13687 (setq res t)
13688 (push tag current))))
13689 (end-of-line 1)
13690 (if current
13691 (progn
13692 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13693 (org-set-tags nil t))
13694 (delete-horizontal-space))
13695 (run-hooks 'org-after-tags-change-hook))
13696 res))
13698 (defun org-align-tags-here (to-col)
13699 ;; Assumes that this is a headline
13700 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13701 (beginning-of-line 1)
13702 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13703 (< pos (match-beginning 2)))
13704 (progn
13705 (setq tags-l (- (match-end 2) (match-beginning 2)))
13706 (goto-char (match-beginning 1))
13707 (insert " ")
13708 (delete-region (point) (1+ (match-beginning 2)))
13709 (setq ncol (max (current-column)
13710 (1+ col)
13711 (if (> to-col 0)
13712 to-col
13713 (- (abs to-col) tags-l))))
13714 (setq p (point))
13715 (insert (make-string (- ncol (current-column)) ?\ ))
13716 (setq ncol (current-column))
13717 (when indent-tabs-mode (tabify p (point-at-eol)))
13718 (org-move-to-column (min ncol col) t))
13719 (goto-char pos))))
13721 (defun org-set-tags-command (&optional arg just-align)
13722 "Call the set-tags command for the current entry."
13723 (interactive "P")
13724 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13725 (org-set-tags arg just-align)
13726 (save-excursion
13727 (org-back-to-heading t)
13728 (org-set-tags arg just-align))))
13730 (defun org-set-tags-to (data)
13731 "Set the tags of the current entry to DATA, replacing the current tags.
13732 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13733 If DATA is nil or the empty string, any tags will be removed."
13734 (interactive "sTags: ")
13735 (setq data
13736 (cond
13737 ((eq data nil) "")
13738 ((equal data "") "")
13739 ((stringp data)
13740 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13741 ":"))
13742 ((listp data)
13743 (concat ":" (mapconcat 'identity data ":") ":"))))
13744 (when data
13745 (save-excursion
13746 (org-back-to-heading t)
13747 (when (looking-at org-complex-heading-regexp)
13748 (if (match-end 5)
13749 (progn
13750 (goto-char (match-beginning 5))
13751 (insert data)
13752 (delete-region (point) (point-at-eol))
13753 (org-set-tags nil 'align))
13754 (goto-char (point-at-eol))
13755 (insert " " data)
13756 (org-set-tags nil 'align)))
13757 (beginning-of-line 1)
13758 (if (looking-at ".*?\\([ \t]+\\)$")
13759 (delete-region (match-beginning 1) (match-end 1))))))
13761 (defun org-align-all-tags ()
13762 "Align the tags i all headings."
13763 (interactive)
13764 (save-excursion
13765 (or (ignore-errors (org-back-to-heading t))
13766 (outline-next-heading))
13767 (if (org-at-heading-p)
13768 (org-set-tags t)
13769 (message "No headings"))))
13771 (defvar org-indent-indentation-per-level)
13772 (defun org-set-tags (&optional arg just-align)
13773 "Set the tags for the current headline.
13774 With prefix ARG, realign all tags in headings in the current buffer."
13775 (interactive "P")
13776 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13777 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13778 'region-start-level 'region))
13779 org-loop-over-headlines-in-active-region)
13780 (org-map-entries
13781 ;; We don't use ARG and JUST-ALIGN here these args are not
13782 ;; useful when looping over headlines
13783 `(org-set-tags)
13784 org-loop-over-headlines-in-active-region
13785 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13786 (let* ((re org-outline-regexp-bol)
13787 (current (unless arg (org-get-tags-string)))
13788 (col (current-column))
13789 (org-setting-tags t)
13790 table current-tags inherited-tags ; computed below when needed
13791 tags p0 c0 c1 rpl di tc level)
13792 (if arg
13793 (save-excursion
13794 (goto-char (point-min))
13795 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13796 (while (re-search-forward re nil t)
13797 (org-set-tags nil t)
13798 (end-of-line 1)))
13799 (message "All tags realigned to column %d" org-tags-column))
13800 (if just-align
13801 (setq tags current)
13802 ;; Get a new set of tags from the user
13803 (save-excursion
13804 (setq table (append org-tag-persistent-alist
13805 (or org-tag-alist (org-get-buffer-tags))
13806 (and
13807 org-complete-tags-always-offer-all-agenda-tags
13808 (org-global-tags-completion-table
13809 (org-agenda-files))))
13810 org-last-tags-completion-table table
13811 current-tags (org-split-string current ":")
13812 inherited-tags (nreverse
13813 (nthcdr (length current-tags)
13814 (nreverse (org-get-tags-at))))
13815 tags
13816 (if (or (eq t org-use-fast-tag-selection)
13817 (and org-use-fast-tag-selection
13818 (delq nil (mapcar 'cdr table))))
13819 (org-fast-tag-selection
13820 current-tags inherited-tags table
13821 (if org-fast-tag-selection-include-todo
13822 org-todo-key-alist))
13823 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13824 (org-trim
13825 (org-icompleting-read "Tags: "
13826 'org-tags-completion-function
13827 nil nil current 'org-tags-history))))))
13828 (while (string-match "[-+&]+" tags)
13829 ;; No boolean logic, just a list
13830 (setq tags (replace-match ":" t t tags))))
13832 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13834 (if org-tags-sort-function
13835 (setq tags (mapconcat 'identity
13836 (sort (org-split-string
13837 tags (org-re "[^[:alnum:]_@#%]+"))
13838 org-tags-sort-function) ":")))
13840 (if (string-match "\\`[\t ]*\\'" tags)
13841 (setq tags "")
13842 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13843 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13845 ;; Insert new tags at the correct column
13846 (beginning-of-line 1)
13847 (setq level (or (and (looking-at org-outline-regexp)
13848 (- (match-end 0) (point) 1))
13850 (cond
13851 ((and (equal current "") (equal tags "")))
13852 ((re-search-forward
13853 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13854 (point-at-eol) t)
13855 (if (equal tags "")
13856 (setq rpl "")
13857 (goto-char (match-beginning 0))
13858 (setq c0 (current-column)
13859 ;; compute offset for the case of org-indent-mode active
13860 di (if org-indent-mode
13861 (* (1- org-indent-indentation-per-level) (1- level))
13863 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13864 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13865 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13866 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13867 (replace-match rpl t t)
13868 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13869 tags)
13870 (t (error "Tags alignment failed")))
13871 (org-move-to-column col)
13872 (unless just-align
13873 (run-hooks 'org-after-tags-change-hook))))))
13875 (defun org-change-tag-in-region (beg end tag off)
13876 "Add or remove TAG for each entry in the region.
13877 This works in the agenda, and also in an org-mode buffer."
13878 (interactive
13879 (list (region-beginning) (region-end)
13880 (let ((org-last-tags-completion-table
13881 (if (derived-mode-p 'org-mode)
13882 (org-get-buffer-tags)
13883 (org-global-tags-completion-table))))
13884 (org-icompleting-read
13885 "Tag: " 'org-tags-completion-function nil nil nil
13886 'org-tags-history))
13887 (progn
13888 (message "[s]et or [r]emove? ")
13889 (equal (read-char-exclusive) ?r))))
13890 (if (fboundp 'deactivate-mark) (deactivate-mark))
13891 (let ((agendap (equal major-mode 'org-agenda-mode))
13892 l1 l2 m buf pos newhead (cnt 0))
13893 (goto-char end)
13894 (setq l2 (1- (org-current-line)))
13895 (goto-char beg)
13896 (setq l1 (org-current-line))
13897 (loop for l from l1 to l2 do
13898 (org-goto-line l)
13899 (setq m (get-text-property (point) 'org-hd-marker))
13900 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13901 (and agendap m))
13902 (setq buf (if agendap (marker-buffer m) (current-buffer))
13903 pos (if agendap m (point)))
13904 (with-current-buffer buf
13905 (save-excursion
13906 (save-restriction
13907 (goto-char pos)
13908 (setq cnt (1+ cnt))
13909 (org-toggle-tag tag (if off 'off 'on))
13910 (setq newhead (org-get-heading)))))
13911 (and agendap (org-agenda-change-all-lines newhead m))))
13912 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13914 (defun org-tags-completion-function (string predicate &optional flag)
13915 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13916 (confirm (lambda (x) (stringp (car x)))))
13917 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13918 (setq s1 (match-string 1 string)
13919 s2 (match-string 2 string))
13920 (setq s1 "" s2 string))
13921 (cond
13922 ((eq flag nil)
13923 ;; try completion
13924 (setq rtn (try-completion s2 ctable confirm))
13925 (if (stringp rtn)
13926 (setq rtn
13927 (concat s1 s2 (substring rtn (length s2))
13928 (if (and org-add-colon-after-tag-completion
13929 (assoc rtn ctable))
13930 ":" ""))))
13931 rtn)
13932 ((eq flag t)
13933 ;; all-completions
13934 (all-completions s2 ctable confirm)
13936 ((eq flag 'lambda)
13937 ;; exact match?
13938 (assoc s2 ctable)))
13941 (defun org-fast-tag-insert (kwd tags face &optional end)
13942 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13943 (insert (format "%-12s" (concat kwd ":"))
13944 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13945 (or end "")))
13947 (defun org-fast-tag-show-exit (flag)
13948 (save-excursion
13949 (org-goto-line 3)
13950 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13951 (replace-match ""))
13952 (when flag
13953 (end-of-line 1)
13954 (org-move-to-column (- (window-width) 19) t)
13955 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13957 (defun org-set-current-tags-overlay (current prefix)
13958 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13959 (if (featurep 'xemacs)
13960 (org-overlay-display org-tags-overlay (concat prefix s)
13961 'secondary-selection)
13962 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13963 (org-overlay-display org-tags-overlay (concat prefix s)))))
13965 (defvar org-last-tag-selection-key nil)
13966 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13967 "Fast tag selection with single keys.
13968 CURRENT is the current list of tags in the headline, INHERITED is the
13969 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13970 possibly with grouping information. TODO-TABLE is a similar table with
13971 TODO keywords, should these have keys assigned to them.
13972 If the keys are nil, a-z are automatically assigned.
13973 Returns the new tags string, or nil to not change the current settings."
13974 (let* ((fulltable (append table todo-table))
13975 (maxlen (apply 'max (mapcar
13976 (lambda (x)
13977 (if (stringp (car x)) (string-width (car x)) 0))
13978 fulltable)))
13979 (buf (current-buffer))
13980 (expert (eq org-fast-tag-selection-single-key 'expert))
13981 (buffer-tags nil)
13982 (fwidth (+ maxlen 3 1 3))
13983 (ncol (/ (- (window-width) 4) fwidth))
13984 (i-face 'org-done)
13985 (c-face 'org-todo)
13986 tg cnt e c char c1 c2 ntable tbl rtn
13987 ov-start ov-end ov-prefix
13988 (exit-after-next org-fast-tag-selection-single-key)
13989 (done-keywords org-done-keywords)
13990 groups ingroup)
13991 (save-excursion
13992 (beginning-of-line 1)
13993 (if (looking-at
13994 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13995 (setq ov-start (match-beginning 1)
13996 ov-end (match-end 1)
13997 ov-prefix "")
13998 (setq ov-start (1- (point-at-eol))
13999 ov-end (1+ ov-start))
14000 (skip-chars-forward "^\n\r")
14001 (setq ov-prefix
14002 (concat
14003 (buffer-substring (1- (point)) (point))
14004 (if (> (current-column) org-tags-column)
14006 (make-string (- org-tags-column (current-column)) ?\ ))))))
14007 (move-overlay org-tags-overlay ov-start ov-end)
14008 (save-window-excursion
14009 (if expert
14010 (set-buffer (get-buffer-create " *Org tags*"))
14011 (delete-other-windows)
14012 (split-window-vertically)
14013 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14014 (erase-buffer)
14015 (org-set-local 'org-done-keywords done-keywords)
14016 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14017 (org-fast-tag-insert "Current" current c-face "\n\n")
14018 (org-fast-tag-show-exit exit-after-next)
14019 (org-set-current-tags-overlay current ov-prefix)
14020 (setq tbl fulltable char ?a cnt 0)
14021 (while (setq e (pop tbl))
14022 (cond
14023 ((equal (car e) :startgroup)
14024 (push '() groups) (setq ingroup t)
14025 (when (not (= cnt 0))
14026 (setq cnt 0)
14027 (insert "\n"))
14028 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14029 ((equal (car e) :endgroup)
14030 (setq ingroup nil cnt 0)
14031 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14032 ((equal e '(:newline))
14033 (when (not (= cnt 0))
14034 (setq cnt 0)
14035 (insert "\n")
14036 (setq e (car tbl))
14037 (while (equal (car tbl) '(:newline))
14038 (insert "\n")
14039 (setq tbl (cdr tbl)))))
14041 (setq tg (copy-sequence (car e)) c2 nil)
14042 (if (cdr e)
14043 (setq c (cdr e))
14044 ;; automatically assign a character.
14045 (setq c1 (string-to-char
14046 (downcase (substring
14047 tg (if (= (string-to-char tg) ?@) 1 0)))))
14048 (if (or (rassoc c1 ntable) (rassoc c1 table))
14049 (while (or (rassoc char ntable) (rassoc char table))
14050 (setq char (1+ char)))
14051 (setq c2 c1))
14052 (setq c (or c2 char)))
14053 (if ingroup (push tg (car groups)))
14054 (setq tg (org-add-props tg nil 'face
14055 (cond
14056 ((not (assoc tg table))
14057 (org-get-todo-face tg))
14058 ((member tg current) c-face)
14059 ((member tg inherited) i-face))))
14060 (if (and (= cnt 0) (not ingroup)) (insert " "))
14061 (insert "[" c "] " tg (make-string
14062 (- fwidth 4 (length tg)) ?\ ))
14063 (push (cons tg c) ntable)
14064 (when (= (setq cnt (1+ cnt)) ncol)
14065 (insert "\n")
14066 (if ingroup (insert " "))
14067 (setq cnt 0)))))
14068 (setq ntable (nreverse ntable))
14069 (insert "\n")
14070 (goto-char (point-min))
14071 (if (not expert) (org-fit-window-to-buffer))
14072 (setq rtn
14073 (catch 'exit
14074 (while t
14075 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14076 (if (not groups) "no " "")
14077 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14078 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14079 (setq org-last-tag-selection-key c)
14080 (cond
14081 ((= c ?\r) (throw 'exit t))
14082 ((= c ?!)
14083 (setq groups (not groups))
14084 (goto-char (point-min))
14085 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14086 ((= c ?\C-c)
14087 (if (not expert)
14088 (org-fast-tag-show-exit
14089 (setq exit-after-next (not exit-after-next)))
14090 (setq expert nil)
14091 (delete-other-windows)
14092 (set-window-buffer (split-window-vertically) " *Org tags*")
14093 (org-switch-to-buffer-other-window " *Org tags*")
14094 (org-fit-window-to-buffer)))
14095 ((or (= c ?\C-g)
14096 (and (= c ?q) (not (rassoc c ntable))))
14097 (org-detach-overlay org-tags-overlay)
14098 (setq quit-flag t))
14099 ((= c ?\ )
14100 (setq current nil)
14101 (if exit-after-next (setq exit-after-next 'now)))
14102 ((= c ?\t)
14103 (condition-case nil
14104 (setq tg (org-icompleting-read
14105 "Tag: "
14106 (or buffer-tags
14107 (with-current-buffer buf
14108 (org-get-buffer-tags)))))
14109 (quit (setq tg "")))
14110 (when (string-match "\\S-" tg)
14111 (add-to-list 'buffer-tags (list tg))
14112 (if (member tg current)
14113 (setq current (delete tg current))
14114 (push tg current)))
14115 (if exit-after-next (setq exit-after-next 'now)))
14116 ((setq e (rassoc c todo-table) tg (car e))
14117 (with-current-buffer buf
14118 (save-excursion (org-todo tg)))
14119 (if exit-after-next (setq exit-after-next 'now)))
14120 ((setq e (rassoc c ntable) tg (car e))
14121 (if (member tg current)
14122 (setq current (delete tg current))
14123 (loop for g in groups do
14124 (if (member tg g)
14125 (mapc (lambda (x)
14126 (setq current (delete x current)))
14127 g)))
14128 (push tg current))
14129 (if exit-after-next (setq exit-after-next 'now))))
14131 ;; Create a sorted list
14132 (setq current
14133 (sort current
14134 (lambda (a b)
14135 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14136 (if (eq exit-after-next 'now) (throw 'exit t))
14137 (goto-char (point-min))
14138 (beginning-of-line 2)
14139 (delete-region (point) (point-at-eol))
14140 (org-fast-tag-insert "Current" current c-face)
14141 (org-set-current-tags-overlay current ov-prefix)
14142 (while (re-search-forward
14143 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14144 (setq tg (match-string 1))
14145 (add-text-properties
14146 (match-beginning 1) (match-end 1)
14147 (list 'face
14148 (cond
14149 ((member tg current) c-face)
14150 ((member tg inherited) i-face)
14151 (t (get-text-property (match-beginning 1) 'face))))))
14152 (goto-char (point-min)))))
14153 (org-detach-overlay org-tags-overlay)
14154 (if rtn
14155 (mapconcat 'identity current ":")
14156 nil))))
14158 (defun org-get-tags-string ()
14159 "Get the TAGS string in the current headline."
14160 (unless (org-at-heading-p t)
14161 (error "Not on a heading"))
14162 (save-excursion
14163 (beginning-of-line 1)
14164 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14165 (org-match-string-no-properties 1)
14166 "")))
14168 (defun org-get-tags ()
14169 "Get the list of tags specified in the current headline."
14170 (org-split-string (org-get-tags-string) ":"))
14172 (defun org-get-buffer-tags ()
14173 "Get a table of all tags used in the buffer, for completion."
14174 (let (tags)
14175 (save-excursion
14176 (goto-char (point-min))
14177 (while (re-search-forward
14178 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14179 (when (equal (char-after (point-at-bol 0)) ?*)
14180 (mapc (lambda (x) (add-to-list 'tags x))
14181 (org-split-string (org-match-string-no-properties 1) ":")))))
14182 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14183 (mapcar 'list tags)))
14185 ;;;; The mapping API
14187 ;;;###autoload
14188 (defun org-map-entries (func &optional match scope &rest skip)
14189 "Call FUNC at each headline selected by MATCH in SCOPE.
14191 FUNC is a function or a lisp form. The function will be called without
14192 arguments, with the cursor positioned at the beginning of the headline.
14193 The return values of all calls to the function will be collected and
14194 returned as a list.
14196 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14197 does not need to preserve point. After evaluation, the cursor will be
14198 moved to the end of the line (presumably of the headline of the
14199 processed entry) and search continues from there. Under some
14200 circumstances, this may not produce the wanted results. For example,
14201 if you have removed (e.g. archived) the current (sub)tree it could
14202 mean that the next entry will be skipped entirely. In such cases, you
14203 can specify the position from where search should continue by making
14204 FUNC set the variable `org-map-continue-from' to the desired buffer
14205 position.
14207 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14208 Only headlines that are matched by this query will be considered during
14209 the iteration. When MATCH is nil or t, all headlines will be
14210 visited by the iteration.
14212 SCOPE determines the scope of this command. It can be any of:
14214 nil The current buffer, respecting the restriction if any
14215 tree The subtree started with the entry at point
14216 region The entries within the active region, if any
14217 region-start-level
14218 The entries within the active region, but only those at
14219 the same level than the first one.
14220 file The current buffer, without restriction
14221 file-with-archives
14222 The current buffer, and any archives associated with it
14223 agenda All agenda files
14224 agenda-with-archives
14225 All agenda files with any archive files associated with them
14226 \(file1 file2 ...)
14227 If this is a list, all files in the list will be scanned
14229 The remaining args are treated as settings for the skipping facilities of
14230 the scanner. The following items can be given here:
14232 archive skip trees with the archive tag.
14233 comment skip trees with the COMMENT keyword
14234 function or Emacs Lisp form:
14235 will be used as value for `org-agenda-skip-function', so whenever
14236 the function returns t, FUNC will not be called for that
14237 entry and search will continue from the point where the
14238 function leaves it.
14240 If your function needs to retrieve the tags including inherited tags
14241 at the *current* entry, you can use the value of the variable
14242 `org-scanner-tags' which will be much faster than getting the value
14243 with `org-get-tags-at'. If your function gets properties with
14244 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14245 to t around the call to `org-entry-properties' to get the same speedup.
14246 Note that if your function moves around to retrieve tags and properties at
14247 a *different* entry, you cannot use these techniques."
14248 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14249 (not (org-region-active-p)))
14250 (let* ((org-agenda-archives-mode nil) ; just to make sure
14251 (org-agenda-skip-archived-trees (memq 'archive skip))
14252 (org-agenda-skip-comment-trees (memq 'comment skip))
14253 (org-agenda-skip-function
14254 (car (org-delete-all '(comment archive) skip)))
14255 (org-tags-match-list-sublevels t)
14256 (start-level (eq scope 'region-start-level))
14257 matcher file res
14258 org-todo-keywords-for-agenda
14259 org-done-keywords-for-agenda
14260 org-todo-keyword-alist-for-agenda
14261 org-drawers-for-agenda
14262 org-tag-alist-for-agenda
14263 todo-only)
14265 (cond
14266 ((eq match t) (setq matcher t))
14267 ((eq match nil) (setq matcher t))
14268 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14270 (save-excursion
14271 (save-restriction
14272 (cond ((eq scope 'tree)
14273 (org-back-to-heading t)
14274 (org-narrow-to-subtree)
14275 (setq scope nil))
14276 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14277 (org-region-active-p))
14278 ;; If needed, set start-level to a string like "2"
14279 (when start-level
14280 (save-excursion
14281 (goto-char (region-beginning))
14282 (unless (org-at-heading-p) (outline-next-heading))
14283 (setq start-level (org-current-level))))
14284 (narrow-to-region (region-beginning)
14285 (save-excursion
14286 (goto-char (region-end))
14287 (unless (and (bolp) (org-at-heading-p))
14288 (outline-next-heading))
14289 (point)))
14290 (setq scope nil)))
14292 (if (not scope)
14293 (progn
14294 (org-agenda-prepare-buffers
14295 (list (buffer-file-name (current-buffer))))
14296 (setq res (org-scan-tags func matcher todo-only start-level)))
14297 ;; Get the right scope
14298 (cond
14299 ((and scope (listp scope) (symbolp (car scope)))
14300 (setq scope (eval scope)))
14301 ((eq scope 'agenda)
14302 (setq scope (org-agenda-files t)))
14303 ((eq scope 'agenda-with-archives)
14304 (setq scope (org-agenda-files t))
14305 (setq scope (org-add-archive-files scope)))
14306 ((eq scope 'file)
14307 (setq scope (list (buffer-file-name))))
14308 ((eq scope 'file-with-archives)
14309 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14310 (org-agenda-prepare-buffers scope)
14311 (while (setq file (pop scope))
14312 (with-current-buffer (org-find-base-buffer-visiting file)
14313 (save-excursion
14314 (save-restriction
14315 (widen)
14316 (goto-char (point-min))
14317 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14318 res)))
14320 ;;;; Properties
14322 ;;; Setting and retrieving properties
14324 (defconst org-special-properties
14325 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14326 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14327 "The special properties valid in Org-mode.
14329 These are properties that are not defined in the property drawer,
14330 but in some other way.")
14332 (defconst org-default-properties
14333 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14334 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14335 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14336 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14337 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14338 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14339 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14340 "Some properties that are used by Org-mode for various purposes.
14341 Being in this list makes sure that they are offered for completion.")
14343 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14344 "Regular expression matching the first line of a property drawer.")
14346 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14347 "Regular expression matching the last line of a property drawer.")
14349 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14350 "Regular expression matching the first line of a property drawer.")
14352 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14353 "Regular expression matching the first line of a property drawer.")
14355 (defconst org-property-drawer-re
14356 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14357 org-property-end-re "\\)\n?")
14358 "Matches an entire property drawer.")
14360 (defconst org-clock-drawer-re
14361 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14362 org-property-end-re "\\)\n?")
14363 "Matches an entire clock drawer.")
14365 (defsubst org-re-property (property)
14366 "Return a regexp matching a PROPERTY line.
14367 Match group 1 will be set to the value."
14368 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14370 (defsubst org-re-property-keyword (property)
14371 "Return a regexp matching a PROPERTY line, possibly with no
14372 value for the property."
14373 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14375 (defun org-property-action ()
14376 "Do an action on properties."
14377 (interactive)
14378 (let (c)
14379 (org-at-property-p)
14380 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14381 (setq c (read-char-exclusive))
14382 (cond
14383 ((equal c ?s)
14384 (call-interactively 'org-set-property))
14385 ((equal c ?d)
14386 (call-interactively 'org-delete-property))
14387 ((equal c ?D)
14388 (call-interactively 'org-delete-property-globally))
14389 ((equal c ?c)
14390 (call-interactively 'org-compute-property-at-point))
14391 (t (error "No such property action %c" c)))))
14393 (defun org-inc-effort ()
14394 "Increment the value of the effort property in the current entry."
14395 (interactive)
14396 (org-set-effort nil t))
14398 (defun org-set-effort (&optional value increment)
14399 "Set the effort property of the current entry.
14400 With numerical prefix arg, use the nth allowed value, 0 stands for the
14401 10th allowed value.
14403 When INCREMENT is non-nil, set the property to the next allowed value."
14404 (interactive "P")
14405 (if (equal value 0) (setq value 10))
14406 (let* ((completion-ignore-case t)
14407 (prop org-effort-property)
14408 (cur (org-entry-get nil prop))
14409 (allowed (org-property-get-allowed-values nil prop 'table))
14410 (existing (mapcar 'list (org-property-values prop)))
14412 (val (cond
14413 ((stringp value) value)
14414 ((and allowed (integerp value))
14415 (or (car (nth (1- value) allowed))
14416 (car (org-last allowed))))
14417 ((and allowed increment)
14418 (or (caadr (member (list cur) allowed))
14419 (error "Allowed effort values are not set")))
14420 (allowed
14421 (message "Select 1-9,0, [RET%s]: %s"
14422 (if cur (concat "=" cur) "")
14423 (mapconcat 'car allowed " "))
14424 (setq rpl (read-char-exclusive))
14425 (if (equal rpl ?\r)
14427 (setq rpl (- rpl ?0))
14428 (if (equal rpl 0) (setq rpl 10))
14429 (if (and (> rpl 0) (<= rpl (length allowed)))
14430 (car (nth (1- rpl) allowed))
14431 (org-completing-read "Effort: " allowed nil))))
14433 (let (org-completion-use-ido org-completion-use-iswitchb)
14434 (org-completing-read
14435 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14436 (concat "[" cur "]") "")
14437 ": ")
14438 existing nil nil "" nil cur))))))
14439 (unless (equal (org-entry-get nil prop) val)
14440 (org-entry-put nil prop val))
14441 (message "%s is now %s" prop val)))
14443 (defun org-at-property-p ()
14444 "Is cursor inside a property drawer?"
14445 (save-excursion
14446 (beginning-of-line 1)
14447 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14448 (save-match-data ;; Used by calling procedures
14449 (let ((p (point))
14450 (range (unless (org-before-first-heading-p)
14451 (org-get-property-block))))
14452 (and range (<= (car range) p) (< p (cdr range))))))))
14454 (defun org-get-property-block (&optional beg end force)
14455 "Return the (beg . end) range of the body of the property drawer.
14456 BEG and END are the beginning and end of the current subtree, or of
14457 the part before the first headline. If they are not given, they will
14458 be found. If the drawer does not exist and FORCE is non-nil, create
14459 the drawer."
14460 (catch 'exit
14461 (save-excursion
14462 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14463 (progn (org-back-to-heading t) (point))))
14464 (end (or end (and (not (outline-next-heading)) (point-max))
14465 (point))))
14466 (goto-char beg)
14467 (if (re-search-forward org-property-start-re end t)
14468 (setq beg (1+ (match-end 0)))
14469 (if force
14470 (save-excursion
14471 (org-insert-property-drawer)
14472 (setq end (progn (outline-next-heading) (point))))
14473 (throw 'exit nil))
14474 (goto-char beg)
14475 (if (re-search-forward org-property-start-re end t)
14476 (setq beg (1+ (match-end 0)))))
14477 (if (re-search-forward org-property-end-re end t)
14478 (setq end (match-beginning 0))
14479 (or force (throw 'exit nil))
14480 (goto-char beg)
14481 (setq end beg)
14482 (org-indent-line)
14483 (insert ":END:\n"))
14484 (cons beg end)))))
14486 (defun org-entry-properties (&optional pom which specific)
14487 "Get all properties of the entry at point-or-marker POM.
14488 This includes the TODO keyword, the tags, time strings for deadline,
14489 scheduled, and clocking, and any additional properties defined in the
14490 entry. The return value is an alist, keys may occur multiple times
14491 if the property key was used several times.
14492 POM may also be nil, in which case the current entry is used.
14493 If WHICH is nil or `all', get all properties. If WHICH is
14494 `special' or `standard', only get that subclass. If WHICH
14495 is a string only get exactly this property. SPECIFIC can be a string, the
14496 specific property we are interested in. Specifying it can speed
14497 things up because then unnecessary parsing is avoided."
14498 (setq which (or which 'all))
14499 (org-with-point-at pom
14500 (let ((clockstr (substring org-clock-string 0 -1))
14501 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14502 (case-fold-search nil)
14503 beg end range props sum-props key key1 value string clocksum clocksumt)
14504 (save-excursion
14505 (when (condition-case nil
14506 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14507 (error nil))
14508 (setq beg (point))
14509 (setq sum-props (get-text-property (point) 'org-summaries))
14510 (setq clocksum (get-text-property (point) :org-clock-minutes)
14511 clocksumt (get-text-property (point) :org-clock-minutes-today))
14512 (outline-next-heading)
14513 (setq end (point))
14514 (when (memq which '(all special))
14515 ;; Get the special properties, like TODO and tags
14516 (goto-char beg)
14517 (when (and (or (not specific) (string= specific "TODO"))
14518 (looking-at org-todo-line-regexp) (match-end 2))
14519 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14520 (when (and (or (not specific) (string= specific "PRIORITY"))
14521 (looking-at org-priority-regexp))
14522 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14523 (when (or (not specific) (string= specific "FILE"))
14524 (push (cons "FILE" buffer-file-name) props))
14525 (when (and (or (not specific) (string= specific "TAGS"))
14526 (setq value (org-get-tags-string))
14527 (string-match "\\S-" value))
14528 (push (cons "TAGS" value) props))
14529 (when (and (or (not specific) (string= specific "ALLTAGS"))
14530 (setq value (org-get-tags-at)))
14531 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14532 ":"))
14533 props))
14534 (when (or (not specific) (string= specific "BLOCKED"))
14535 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14536 (when (or (not specific)
14537 (member specific
14538 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14539 "TIMESTAMP" "TIMESTAMP_IA")))
14540 (catch 'match
14541 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14542 (setq key (if (match-end 1)
14543 (substring (org-match-string-no-properties 1)
14544 0 -1))
14545 string (if (equal key clockstr)
14546 (org-trim
14547 (buffer-substring-no-properties
14548 (match-beginning 3) (goto-char
14549 (point-at-eol))))
14550 (substring (org-match-string-no-properties 3)
14551 1 -1)))
14552 ;; Get the correct property name from the key. This is
14553 ;; necessary if the user has configured time keywords.
14554 (setq key1 (concat key ":"))
14555 (cond
14556 ((not key)
14557 (setq key
14558 (if (= (char-after (match-beginning 3)) ?\[)
14559 "TIMESTAMP_IA" "TIMESTAMP")))
14560 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14561 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14562 ((equal key1 org-closed-string) (setq key "CLOSED"))
14563 ((equal key1 org-clock-string) (setq key "CLOCK")))
14564 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14565 (progn
14566 (push (cons key string) props)
14567 ;; no need to search further if match is found
14568 (throw 'match t))
14569 (when (or (equal key "CLOCK") (not (assoc key props)))
14570 (push (cons key string) props)))))))
14572 (when (memq which '(all standard))
14573 ;; Get the standard properties, like :PROP: ...
14574 (setq range (org-get-property-block beg end))
14575 (when range
14576 (goto-char (car range))
14577 (while (re-search-forward
14578 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14579 (cdr range) t)
14580 (setq key (org-match-string-no-properties 1)
14581 value (org-trim (or (org-match-string-no-properties 2) "")))
14582 (unless (member key excluded)
14583 (push (cons key (or value "")) props)))))
14584 (if clocksum
14585 (push (cons "CLOCKSUM"
14586 (org-columns-number-to-string (/ (float clocksum) 60.)
14587 'add_times))
14588 props))
14589 (if clocksumt
14590 (push (cons "CLOCKSUM_T"
14591 (org-columns-number-to-string (/ (float clocksumt) 60.)
14592 'add_times))
14593 props))
14594 (unless (assoc "CATEGORY" props)
14595 (push (cons "CATEGORY" (org-get-category)) props))
14596 (append sum-props (nreverse props)))))))
14598 (defun org-entry-get (pom property &optional inherit literal-nil)
14599 "Get value of PROPERTY for entry or content at point-or-marker POM.
14600 If INHERIT is non-nil and the entry does not have the property,
14601 then also check higher levels of the hierarchy.
14602 If INHERIT is the symbol `selective', use inheritance only if the setting
14603 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14604 If the property is present but empty, the return value is the empty string.
14605 If the property is not present at all, nil is returned.
14607 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14608 do not interpret it as the list atom nil. This is used for inheritance
14609 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14610 (org-with-point-at pom
14611 (if (and inherit (if (eq inherit 'selective)
14612 (org-property-inherit-p property)
14614 (org-entry-get-with-inheritance property literal-nil)
14615 (if (member property org-special-properties)
14616 ;; We need a special property. Use `org-entry-properties' to
14617 ;; retrieve it, but specify the wanted property
14618 (cdr (assoc property (org-entry-properties nil 'special property)))
14619 (let* ((range (org-get-property-block))
14620 (props (list (or (assoc property org-file-properties)
14621 (assoc property org-global-properties)
14622 (assoc property org-global-properties-fixed))))
14623 (ap (lambda (key)
14624 (when (re-search-forward
14625 (org-re-property key) (cdr range) t)
14626 (setq props
14627 (org-update-property-plist
14629 (if (match-end 1)
14630 (org-match-string-no-properties 1) "")
14631 props)))))
14632 val)
14633 (when (and range (goto-char (car range)))
14634 (funcall ap property)
14635 (goto-char (car range))
14636 (while (funcall ap (concat property "+")))
14637 (setq val (cdr (assoc property props)))
14638 (when val (if literal-nil val (org-not-nil val)))))))))
14640 (defun org-property-or-variable-value (var &optional inherit)
14641 "Check if there is a property fixing the value of VAR.
14642 If yes, return this value. If not, return the current value of the variable."
14643 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14644 (if (and prop (stringp prop) (string-match "\\S-" prop))
14645 (read prop)
14646 (symbol-value var))))
14648 (defun org-entry-delete (pom property)
14649 "Delete the property PROPERTY from entry at point-or-marker POM."
14650 (org-with-point-at pom
14651 (if (member property org-special-properties)
14652 nil ; cannot delete these properties.
14653 (let ((range (org-get-property-block)))
14654 (if (and range
14655 (goto-char (car range))
14656 (re-search-forward
14657 (org-re-property property)
14658 (cdr range) t))
14659 (progn
14660 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14662 nil)))))
14664 ;; Multi-values properties are properties that contain multiple values
14665 ;; These values are assumed to be single words, separated by whitespace.
14666 (defun org-entry-add-to-multivalued-property (pom property value)
14667 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14668 (let* ((old (org-entry-get pom property))
14669 (values (and old (org-split-string old "[ \t]"))))
14670 (setq value (org-entry-protect-space value))
14671 (unless (member value values)
14672 (setq values (cons value values))
14673 (org-entry-put pom property
14674 (mapconcat 'identity values " ")))))
14676 (defun org-entry-remove-from-multivalued-property (pom property value)
14677 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14678 (let* ((old (org-entry-get pom property))
14679 (values (and old (org-split-string old "[ \t]"))))
14680 (setq value (org-entry-protect-space value))
14681 (when (member value values)
14682 (setq values (delete value values))
14683 (org-entry-put pom property
14684 (mapconcat 'identity values " ")))))
14686 (defun org-entry-member-in-multivalued-property (pom property value)
14687 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14688 (let* ((old (org-entry-get pom property))
14689 (values (and old (org-split-string old "[ \t]"))))
14690 (setq value (org-entry-protect-space value))
14691 (member value values)))
14693 (defun org-entry-get-multivalued-property (pom property)
14694 "Return a list of values in a multivalued property."
14695 (let* ((value (org-entry-get pom property))
14696 (values (and value (org-split-string value "[ \t]"))))
14697 (mapcar 'org-entry-restore-space values)))
14699 (defun org-entry-put-multivalued-property (pom property &rest values)
14700 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14701 VALUES should be a list of strings. Spaces will be protected."
14702 (org-entry-put pom property
14703 (mapconcat 'org-entry-protect-space values " "))
14704 (let* ((value (org-entry-get pom property))
14705 (values (and value (org-split-string value "[ \t]"))))
14706 (mapcar 'org-entry-restore-space values)))
14708 (defun org-entry-protect-space (s)
14709 "Protect spaces and newline in string S."
14710 (while (string-match " " s)
14711 (setq s (replace-match "%20" t t s)))
14712 (while (string-match "\n" s)
14713 (setq s (replace-match "%0A" t t s)))
14716 (defun org-entry-restore-space (s)
14717 "Restore spaces and newline in string S."
14718 (while (string-match "%20" s)
14719 (setq s (replace-match " " t t s)))
14720 (while (string-match "%0A" s)
14721 (setq s (replace-match "\n" t t s)))
14724 (defvar org-entry-property-inherited-from (make-marker)
14725 "Marker pointing to the entry from where a property was inherited.
14726 Each call to `org-entry-get-with-inheritance' will set this marker to the
14727 location of the entry where the inheritance search matched. If there was
14728 no match, the marker will point nowhere.
14729 Note that also `org-entry-get' calls this function, if the INHERIT flag
14730 is set.")
14732 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14733 "Get PROPERTY of entry or content at point, search higher levels if needed.
14734 The search will stop at the first ancestor which has the property defined.
14735 If the value found is \"nil\", return nil to show that the property
14736 should be considered as undefined (this is the meaning of nil here).
14737 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14738 (move-marker org-entry-property-inherited-from nil)
14739 (let (tmp)
14740 (save-excursion
14741 (save-restriction
14742 (widen)
14743 (catch 'ex
14744 (while t
14745 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14746 (or (ignore-errors (org-back-to-heading t))
14747 (goto-char (point-min)))
14748 (move-marker org-entry-property-inherited-from (point))
14749 (throw 'ex tmp))
14750 (or (ignore-errors (org-up-heading-safe))
14751 (throw 'ex nil))))))
14752 (setq tmp (or tmp
14753 (cdr (assoc property org-file-properties))
14754 (cdr (assoc property org-global-properties))
14755 (cdr (assoc property org-global-properties-fixed))))
14756 (if literal-nil tmp (org-not-nil tmp))))
14758 (defvar org-property-changed-functions nil
14759 "Hook called when the value of a property has changed.
14760 Each hook function should accept two arguments, the name of the property
14761 and the new value.")
14763 (defun org-entry-put (pom property value)
14764 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14765 (org-with-point-at pom
14766 (org-back-to-heading t)
14767 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14768 range)
14769 (cond
14770 ((equal property "TODO")
14771 (when (and (stringp value) (string-match "\\S-" value)
14772 (not (member value org-todo-keywords-1)))
14773 (error "\"%s\" is not a valid TODO state" value))
14774 (if (or (not value)
14775 (not (string-match "\\S-" value)))
14776 (setq value 'none))
14777 (org-todo value)
14778 (org-set-tags nil 'align))
14779 ((equal property "PRIORITY")
14780 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14781 (string-to-char value) ?\ ))
14782 (org-set-tags nil 'align))
14783 ((equal property "CLOCKSUM")
14784 (if (not (re-search-forward
14785 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14786 (error "Cannot find a clock log")
14787 (goto-char (- (match-end 1) 2))
14788 (cond
14789 ((eq value 'earlier) (org-timestamp-down))
14790 ((eq value 'later) (org-timestamp-up)))
14791 (org-clock-sum-current-item)))
14792 ((equal property "SCHEDULED")
14793 (if (re-search-forward org-scheduled-time-regexp end t)
14794 (cond
14795 ((eq value 'earlier) (org-timestamp-change -1 'day))
14796 ((eq value 'later) (org-timestamp-change 1 'day))
14797 (t (call-interactively 'org-schedule)))
14798 (call-interactively 'org-schedule)))
14799 ((equal property "DEADLINE")
14800 (if (re-search-forward org-deadline-time-regexp end t)
14801 (cond
14802 ((eq value 'earlier) (org-timestamp-change -1 'day))
14803 ((eq value 'later) (org-timestamp-change 1 'day))
14804 (t (call-interactively 'org-deadline)))
14805 (call-interactively 'org-deadline)))
14806 ((member property org-special-properties)
14807 (error "The %s property can not yet be set with `org-entry-put'"
14808 property))
14809 (t ; a non-special property
14810 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14811 (setq range (org-get-property-block beg end 'force))
14812 (goto-char (car range))
14813 (if (re-search-forward
14814 (org-re-property-keyword property) (cdr range) t)
14815 (progn
14816 (delete-region (match-beginning 0) (match-end 0))
14817 (goto-char (match-beginning 0)))
14818 (goto-char (cdr range))
14819 (insert "\n")
14820 (backward-char 1)
14821 (org-indent-line))
14822 (insert ":" property ":")
14823 (and value (insert " " value))
14824 (org-indent-line)))))
14825 (run-hook-with-args 'org-property-changed-functions property value)))
14827 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14828 "Get all property keys in the current buffer.
14829 With INCLUDE-SPECIALS, also list the special properties that reflect things
14830 like tags and TODO state.
14831 With INCLUDE-DEFAULTS, also include properties that has special meaning
14832 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14833 and others.
14834 With INCLUDE-COLUMNS, also include property names given in COLUMN
14835 formats in the current buffer."
14836 (let (rtn range cfmt s p)
14837 (save-excursion
14838 (save-restriction
14839 (widen)
14840 (goto-char (point-min))
14841 (while (re-search-forward org-property-start-re nil t)
14842 (setq range (org-get-property-block))
14843 (goto-char (car range))
14844 (while (re-search-forward
14845 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14846 (cdr range) t)
14847 (add-to-list 'rtn (org-match-string-no-properties 1)))
14848 (outline-next-heading))))
14850 (when include-specials
14851 (setq rtn (append org-special-properties rtn)))
14853 (when include-defaults
14854 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14855 (add-to-list 'rtn org-effort-property))
14857 (when include-columns
14858 (save-excursion
14859 (save-restriction
14860 (widen)
14861 (goto-char (point-min))
14862 (while (re-search-forward
14863 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14864 nil t)
14865 (setq cfmt (match-string 2) s 0)
14866 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14867 cfmt s)
14868 (setq s (match-end 0)
14869 p (match-string 1 cfmt))
14870 (unless (or (equal p "ITEM")
14871 (member p org-special-properties))
14872 (add-to-list 'rtn (match-string 1 cfmt))))))))
14874 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14876 (defun org-property-values (key)
14877 "Return a list of all values of property KEY in the current buffer."
14878 (save-excursion
14879 (save-restriction
14880 (widen)
14881 (goto-char (point-min))
14882 (let ((re (org-re-property key))
14883 values)
14884 (while (re-search-forward re nil t)
14885 (add-to-list 'values (org-trim (match-string 1))))
14886 (delete "" values)))))
14888 (defun org-insert-property-drawer ()
14889 "Insert a property drawer into the current entry."
14890 (org-back-to-heading t)
14891 (looking-at org-outline-regexp)
14892 (let ((indent (if org-adapt-indentation
14893 (- (match-end 0) (match-beginning 0))
14895 (beg (point))
14896 (re (concat "^[ \t]*" org-keyword-time-regexp))
14897 end hiddenp)
14898 (outline-next-heading)
14899 (setq end (point))
14900 (goto-char beg)
14901 (while (re-search-forward re end t))
14902 (setq hiddenp (outline-invisible-p))
14903 (end-of-line 1)
14904 (and (equal (char-after) ?\n) (forward-char 1))
14905 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14906 (if (member (match-string 1) '("CLOCK:" ":END:"))
14907 ;; just skip this line
14908 (beginning-of-line 2)
14909 ;; Drawer start, find the end
14910 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14911 (beginning-of-line 1)))
14912 (org-skip-over-state-notes)
14913 (skip-chars-backward " \t\n\r")
14914 (if (eq (char-before) ?*) (forward-char 1))
14915 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14916 (beginning-of-line 0)
14917 (org-indent-to-column indent)
14918 (beginning-of-line 2)
14919 (org-indent-to-column indent)
14920 (beginning-of-line 0)
14921 (if hiddenp
14922 (save-excursion
14923 (org-back-to-heading t)
14924 (hide-entry))
14925 (org-flag-drawer t))))
14927 (defun org-insert-drawer (&optional arg drawer)
14928 "Insert a drawer at point.
14930 Optional argument DRAWER, when non-nil, is a string representing
14931 drawer's name. Otherwise, the user is prompted for a name.
14933 If a region is active, insert the drawer around that region
14934 instead.
14936 Point is left between drawer's boundaries."
14937 (interactive "P")
14938 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14939 "LOGBOOK"))
14940 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14941 ;; internally by Org. They are meant to be inserted
14942 ;; automatically.
14943 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14944 ;; Remove system drawers from list. Note: For some reason,
14945 ;; `org-completing-read' ignores the predicate while
14946 ;; `completing-read' handles it fine.
14947 (drawer (if arg "PROPERTIES"
14948 (or drawer
14949 (completing-read
14950 "Drawer: " org-drawers
14951 (lambda (d) (not (member d system-drawers))))))))
14952 (cond
14953 ;; With C-u, fall back on `org-insert-property-drawer'
14954 (arg (org-insert-property-drawer))
14955 ;; With an active region, insert a drawer at point.
14956 ((not (org-region-active-p))
14957 (progn
14958 (unless (bolp) (insert "\n"))
14959 (insert (format ":%s:\n\n:END:\n" drawer))
14960 (forward-line -2)))
14961 ;; Otherwise, insert the drawer at point
14963 (let ((rbeg (region-beginning))
14964 (rend (copy-marker (region-end))))
14965 (unwind-protect
14966 (progn
14967 (goto-char rbeg)
14968 (beginning-of-line)
14969 (when (save-excursion
14970 (re-search-forward org-outline-regexp-bol rend t))
14971 (error "Drawers cannot contain headlines"))
14972 ;; Position point at the beginning of the first
14973 ;; non-blank line in region. Insert drawer's opening
14974 ;; there, then indent it.
14975 (org-skip-whitespace)
14976 (beginning-of-line)
14977 (insert ":" drawer ":\n")
14978 (forward-line -1)
14979 (indent-for-tab-command)
14980 ;; Move point to the beginning of the first blank line
14981 ;; after the last non-blank line in region. Insert
14982 ;; drawer's closing, then indent it.
14983 (goto-char rend)
14984 (skip-chars-backward " \r\t\n")
14985 (insert "\n:END:")
14986 (deactivate-mark t)
14987 (indent-for-tab-command)
14988 (unless (eolp) (insert "\n")))
14989 ;; Clear marker, whatever the outcome of insertion is.
14990 (set-marker rend nil)))))))
14992 (defvar org-property-set-functions-alist nil
14993 "Property set function alist.
14994 Each entry should have the following format:
14996 (PROPERTY . READ-FUNCTION)
14998 The read function will be called with the same argument as
14999 `org-completing-read'.")
15001 (defun org-set-property-function (property)
15002 "Get the function that should be used to set PROPERTY.
15003 This is computed according to `org-property-set-functions-alist'."
15004 (or (cdr (assoc property org-property-set-functions-alist))
15005 'org-completing-read))
15007 (defun org-read-property-value (property)
15008 "Read PROPERTY value from user."
15009 (let* ((completion-ignore-case t)
15010 (allowed (org-property-get-allowed-values nil property 'table))
15011 (cur (org-entry-get nil property))
15012 (prompt (concat property " value"
15013 (if (and cur (string-match "\\S-" cur))
15014 (concat " [" cur "]") "") ": "))
15015 (set-function (org-set-property-function property))
15016 (val (if allowed
15017 (funcall set-function prompt allowed nil
15018 (not (get-text-property 0 'org-unrestricted
15019 (caar allowed))))
15020 (let (org-completion-use-ido org-completion-use-iswitchb)
15021 (funcall set-function prompt
15022 (mapcar 'list (org-property-values property))
15023 nil nil "" nil cur)))))
15024 (if (equal val "")
15026 val)))
15028 (defvar org-last-set-property nil)
15029 (defun org-read-property-name ()
15030 "Read a property name."
15031 (let* ((completion-ignore-case t)
15032 (keys (org-buffer-property-keys nil t t))
15033 (default-prop (or (save-excursion
15034 (save-match-data
15035 (beginning-of-line)
15036 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15037 (null (string= (match-string 1) "END"))
15038 (match-string 1))))
15039 org-last-set-property))
15040 (property (org-icompleting-read
15041 (concat "Property"
15042 (if default-prop (concat " [" default-prop "]") "")
15043 ": ")
15044 (mapcar 'list keys)
15045 nil nil nil nil
15046 default-prop
15048 (if (member property keys)
15049 property
15050 (or (cdr (assoc (downcase property)
15051 (mapcar (lambda (x) (cons (downcase x) x))
15052 keys)))
15053 property))))
15055 (defun org-set-property (property value)
15056 "In the current entry, set PROPERTY to VALUE.
15057 When called interactively, this will prompt for a property name, offering
15058 completion on existing and default properties. And then it will prompt
15059 for a value, offering completion either on allowed values (via an inherited
15060 xxx_ALL property) or on existing values in other instances of this property
15061 in the current file."
15062 (interactive (list nil nil))
15063 (let* ((property (or property (org-read-property-name)))
15064 (value (or value (org-read-property-value property)))
15065 (fn (cdr (assoc property org-properties-postprocess-alist))))
15066 (setq org-last-set-property property)
15067 ;; Possibly postprocess the inserted value:
15068 (when fn (setq value (funcall fn value)))
15069 (unless (equal (org-entry-get nil property) value)
15070 (org-entry-put nil property value))))
15072 (defun org-delete-property (property)
15073 "In the current entry, delete PROPERTY."
15074 (interactive
15075 (let* ((completion-ignore-case t)
15076 (prop (org-icompleting-read "Property: "
15077 (org-entry-properties nil 'standard))))
15078 (list prop)))
15079 (message "Property %s %s" property
15080 (if (org-entry-delete nil property)
15081 "deleted"
15082 "was not present in the entry")))
15084 (defun org-delete-property-globally (property)
15085 "Remove PROPERTY globally, from all entries."
15086 (interactive
15087 (let* ((completion-ignore-case t)
15088 (prop (org-icompleting-read
15089 "Globally remove property: "
15090 (mapcar 'list (org-buffer-property-keys)))))
15091 (list prop)))
15092 (save-excursion
15093 (save-restriction
15094 (widen)
15095 (goto-char (point-min))
15096 (let ((cnt 0))
15097 (while (re-search-forward
15098 (org-re-property property)
15099 nil t)
15100 (setq cnt (1+ cnt))
15101 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15102 (message "Property \"%s\" removed from %d entries" property cnt)))))
15104 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15106 (defun org-compute-property-at-point ()
15107 "Compute the property at point.
15108 This looks for an enclosing column format, extracts the operator and
15109 then applies it to the property in the column format's scope."
15110 (interactive)
15111 (unless (org-at-property-p)
15112 (error "Not at a property"))
15113 (let ((prop (org-match-string-no-properties 2)))
15114 (org-columns-get-format-and-top-level)
15115 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15116 (error "No operator defined for property %s" prop))
15117 (org-columns-compute prop)))
15119 (defvar org-property-allowed-value-functions nil
15120 "Hook for functions supplying allowed values for a specific property.
15121 The functions must take a single argument, the name of the property, and
15122 return a flat list of allowed values. If \":ETC\" is one of
15123 the values, this means that these values are intended as defaults for
15124 completion, but that other values should be allowed too.
15125 The functions must return nil if they are not responsible for this
15126 property.")
15128 (defun org-property-get-allowed-values (pom property &optional table)
15129 "Get allowed values for the property PROPERTY.
15130 When TABLE is non-nil, return an alist that can directly be used for
15131 completion."
15132 (let (vals)
15133 (cond
15134 ((equal property "TODO")
15135 (setq vals (org-with-point-at pom
15136 (append org-todo-keywords-1 '("")))))
15137 ((equal property "PRIORITY")
15138 (let ((n org-lowest-priority))
15139 (while (>= n org-highest-priority)
15140 (push (char-to-string n) vals)
15141 (setq n (1- n)))))
15142 ((member property org-special-properties))
15143 ((setq vals (run-hook-with-args-until-success
15144 'org-property-allowed-value-functions property)))
15146 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15147 (when (and vals (string-match "\\S-" vals))
15148 (setq vals (car (read-from-string (concat "(" vals ")"))))
15149 (setq vals (mapcar (lambda (x)
15150 (cond ((stringp x) x)
15151 ((numberp x) (number-to-string x))
15152 ((symbolp x) (symbol-name x))
15153 (t "???")))
15154 vals)))))
15155 (when (member ":ETC" vals)
15156 (setq vals (remove ":ETC" vals))
15157 (org-add-props (car vals) '(org-unrestricted t)))
15158 (if table (mapcar 'list vals) vals)))
15160 (defun org-property-previous-allowed-value (&optional previous)
15161 "Switch to the next allowed value for this property."
15162 (interactive)
15163 (org-property-next-allowed-value t))
15165 (defun org-property-next-allowed-value (&optional previous)
15166 "Switch to the next allowed value for this property."
15167 (interactive)
15168 (unless (org-at-property-p)
15169 (error "Not at a property"))
15170 (let* ((key (match-string 2))
15171 (value (match-string 3))
15172 (allowed (or (org-property-get-allowed-values (point) key)
15173 (and (member value '("[ ]" "[-]" "[X]"))
15174 '("[ ]" "[X]"))))
15175 nval)
15176 (unless allowed
15177 (error "Allowed values for this property have not been defined"))
15178 (if previous (setq allowed (reverse allowed)))
15179 (if (member value allowed)
15180 (setq nval (car (cdr (member value allowed)))))
15181 (setq nval (or nval (car allowed)))
15182 (if (equal nval value)
15183 (error "Only one allowed value for this property"))
15184 (org-at-property-p)
15185 (replace-match (concat " :" key ": " nval) t t)
15186 (org-indent-line)
15187 (beginning-of-line 1)
15188 (skip-chars-forward " \t")
15189 (run-hook-with-args 'org-property-changed-functions key nval)))
15191 (defun org-find-olp (path &optional this-buffer)
15192 "Return a marker pointing to the entry at outline path OLP.
15193 If anything goes wrong, throw an error.
15194 You can wrap this call to catch the error like this:
15196 (condition-case msg
15197 (org-mobile-locate-entry (match-string 4))
15198 (error (nth 1 msg)))
15200 The return value will then be either a string with the error message,
15201 or a marker if everything is OK.
15203 If THIS-BUFFER is set, the outline path does not contain a file,
15204 only headings."
15205 (let* ((file (if this-buffer buffer-file-name (pop path)))
15206 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15207 (level 1)
15208 (lmin 1)
15209 (lmax 1)
15210 limit re end found pos heading cnt flevel)
15211 (unless buffer (error "File not found :%s" file))
15212 (with-current-buffer buffer
15213 (save-excursion
15214 (save-restriction
15215 (widen)
15216 (setq limit (point-max))
15217 (goto-char (point-min))
15218 (while (setq heading (pop path))
15219 (setq re (format org-complex-heading-regexp-format
15220 (regexp-quote heading)))
15221 (setq cnt 0 pos (point))
15222 (while (re-search-forward re end t)
15223 (setq level (- (match-end 1) (match-beginning 1)))
15224 (if (and (>= level lmin) (<= level lmax))
15225 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15226 (when (= cnt 0) (error "Heading not found on level %d: %s"
15227 lmax heading))
15228 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15229 lmax heading))
15230 (goto-char found)
15231 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15232 (setq end (save-excursion (org-end-of-subtree t t))))
15233 (when (org-at-heading-p)
15234 (move-marker (make-marker) (point))))))))
15236 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15237 "Find node HEADING in BUFFER.
15238 Return a marker to the heading if it was found, or nil if not.
15239 If POS-ONLY is set, return just the position instead of a marker.
15241 The heading text must match exact, but it may have a TODO keyword,
15242 a priority cookie and tags in the standard locations."
15243 (with-current-buffer (or buffer (current-buffer))
15244 (save-excursion
15245 (save-restriction
15246 (widen)
15247 (goto-char (point-min))
15248 (let (case-fold-search)
15249 (if (re-search-forward
15250 (format org-complex-heading-regexp-format
15251 (regexp-quote heading)) nil t)
15252 (if pos-only
15253 (match-beginning 0)
15254 (move-marker (make-marker) (match-beginning 0)))))))))
15256 (defun org-find-exact-heading-in-directory (heading &optional dir)
15257 "Find Org node headline HEADING in all .org files in directory DIR.
15258 When the target headline is found, return a marker to this location."
15259 (let ((files (directory-files (or dir default-directory)
15260 nil "\\`[^.#].*\\.org\\'"))
15261 file visiting m buffer)
15262 (catch 'found
15263 (while (setq file (pop files))
15264 (message "trying %s" file)
15265 (setq visiting (org-find-base-buffer-visiting file))
15266 (setq buffer (or visiting (find-file-noselect file)))
15267 (setq m (org-find-exact-headline-in-buffer
15268 heading buffer))
15269 (when (and (not m) (not visiting)) (kill-buffer buffer))
15270 (and m (throw 'found m))))))
15272 (defun org-find-entry-with-id (ident)
15273 "Locate the entry that contains the ID property with exact value IDENT.
15274 IDENT can be a string, a symbol or a number, this function will search for
15275 the string representation of it.
15276 Return the position where this entry starts, or nil if there is no such entry."
15277 (interactive "sID: ")
15278 (let ((id (cond
15279 ((stringp ident) ident)
15280 ((symbol-name ident) (symbol-name ident))
15281 ((numberp ident) (number-to-string ident))
15282 (t (error "IDENT %s must be a string, symbol or number" ident))))
15283 (case-fold-search nil))
15284 (save-excursion
15285 (save-restriction
15286 (widen)
15287 (goto-char (point-min))
15288 (when (re-search-forward
15289 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15290 nil t)
15291 (org-back-to-heading t)
15292 (point))))))
15294 ;;;; Timestamps
15296 (defvar org-last-changed-timestamp nil)
15297 (defvar org-last-inserted-timestamp nil
15298 "The last time stamp inserted with `org-insert-time-stamp'.")
15299 (defvar org-time-was-given) ; dynamically scoped parameter
15300 (defvar org-end-time-was-given) ; dynamically scoped parameter
15301 (defvar org-ts-what) ; dynamically scoped parameter
15303 (defun org-time-stamp (arg &optional inactive)
15304 "Prompt for a date/time and insert a time stamp.
15305 If the user specifies a time like HH:MM or if this command is
15306 called with at least one prefix argument, the time stamp contains
15307 the date and the time. Otherwise, only the date is be included.
15309 All parts of a date not specified by the user is filled in from
15310 the current date/time. So if you just press return without
15311 typing anything, the time stamp will represent the current
15312 date/time.
15314 If there is already a timestamp at the cursor, it will be
15315 modified.
15317 With two universal prefix arguments, insert an active timestamp
15318 with the current time without prompting the user."
15319 (interactive "P")
15320 (let* ((ts nil)
15321 (default-time
15322 ;; Default time is either today, or, when entering a range,
15323 ;; the range start.
15324 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15325 (save-excursion
15326 (re-search-backward
15327 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15328 (- (point) 20) t)))
15329 (apply 'encode-time (org-parse-time-string (match-string 1)))
15330 (current-time)))
15331 (default-input (and ts (org-get-compact-tod ts)))
15332 (repeater (save-excursion
15333 (save-match-data
15334 (beginning-of-line)
15335 (when (re-search-forward
15336 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15337 (save-excursion (progn (end-of-line) (point))) t)
15338 (match-string 0)))))
15339 org-time-was-given org-end-time-was-given time)
15340 (cond
15341 ((and (org-at-timestamp-p t)
15342 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15343 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15344 (insert "--")
15345 (setq time (let ((this-command this-command))
15346 (org-read-date arg 'totime nil nil
15347 default-time default-input inactive)))
15348 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15349 ((org-at-timestamp-p t)
15350 (setq time (let ((this-command this-command))
15351 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15352 (when (org-at-timestamp-p t) ; just to get the match data
15353 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15354 (replace-match "")
15355 (setq org-last-changed-timestamp
15356 (org-insert-time-stamp
15357 time (or org-time-was-given arg)
15358 inactive nil nil (list org-end-time-was-given)))
15359 (when repeater (goto-char (1- (point))) (insert " " repeater)
15360 (setq org-last-changed-timestamp
15361 (concat (substring org-last-inserted-timestamp 0 -1)
15362 " " repeater ">"))))
15363 (message "Timestamp updated"))
15364 ((equal arg '(16))
15365 (org-insert-time-stamp (current-time) t))
15367 (setq time (let ((this-command this-command))
15368 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15369 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15370 nil nil (list org-end-time-was-given))))))
15372 ;; FIXME: can we use this for something else, like computing time differences?
15373 (defun org-get-compact-tod (s)
15374 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15375 (let* ((t1 (match-string 1 s))
15376 (h1 (string-to-number (match-string 2 s)))
15377 (m1 (string-to-number (match-string 3 s)))
15378 (t2 (and (match-end 4) (match-string 5 s)))
15379 (h2 (and t2 (string-to-number (match-string 6 s))))
15380 (m2 (and t2 (string-to-number (match-string 7 s))))
15381 dh dm)
15382 (if (not t2)
15384 (setq dh (- h2 h1) dm (- m2 m1))
15385 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15386 (concat t1 "+" (number-to-string dh)
15387 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15389 (defun org-time-stamp-inactive (&optional arg)
15390 "Insert an inactive time stamp.
15391 An inactive time stamp is enclosed in square brackets instead of angle
15392 brackets. It is inactive in the sense that it does not trigger agenda entries,
15393 does not link to the calendar and cannot be changed with the S-cursor keys.
15394 So these are more for recording a certain time/date."
15395 (interactive "P")
15396 (org-time-stamp arg 'inactive))
15398 (defvar org-date-ovl (make-overlay 1 1))
15399 (overlay-put org-date-ovl 'face 'org-date-selected)
15400 (org-detach-overlay org-date-ovl)
15402 (defvar org-ans1) ; dynamically scoped parameter
15403 (defvar org-ans2) ; dynamically scoped parameter
15405 (defvar org-plain-time-of-day-regexp) ; defined below
15407 (defvar org-overriding-default-time nil) ; dynamically scoped
15408 (defvar org-read-date-overlay nil)
15409 (defvar org-dcst nil) ; dynamically scoped
15410 (defvar org-read-date-history nil)
15411 (defvar org-read-date-final-answer nil)
15412 (defvar org-read-date-analyze-futurep nil)
15413 (defvar org-read-date-analyze-forced-year nil)
15414 (defvar org-read-date-inactive)
15416 (defun org-read-date (&optional org-with-time to-time from-string prompt
15417 default-time default-input inactive)
15418 "Read a date, possibly a time, and make things smooth for the user.
15419 The prompt will suggest to enter an ISO date, but you can also enter anything
15420 which will at least partially be understood by `parse-time-string'.
15421 Unrecognized parts of the date will default to the current day, month, year,
15422 hour and minute. If this command is called to replace a timestamp at point,
15423 or to enter the second timestamp of a range, the default time is taken
15424 from the existing stamp. Furthermore, the command prefers the future,
15425 so if you are giving a date where the year is not given, and the day-month
15426 combination is already past in the current year, it will assume you
15427 mean next year. For details, see the manual. A few examples:
15429 3-2-5 --> 2003-02-05
15430 feb 15 --> currentyear-02-15
15431 2/15 --> currentyear-02-15
15432 sep 12 9 --> 2009-09-12
15433 12:45 --> today 12:45
15434 22 sept 0:34 --> currentyear-09-22 0:34
15435 12 --> currentyear-currentmonth-12
15436 Fri --> nearest Friday (today or later)
15437 etc.
15439 Furthermore you can specify a relative date by giving, as the *first* thing
15440 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15441 change in days weeks, months, years.
15442 With a single plus or minus, the date is relative to today. With a double
15443 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15444 +4d --> four days from today
15445 +4 --> same as above
15446 +2w --> two weeks from today
15447 ++5 --> five days from default date
15449 The function understands only English month and weekday abbreviations.
15451 While prompting, a calendar is popped up - you can also select the
15452 date with the mouse (button 1). The calendar shows a period of three
15453 months. To scroll it to other months, use the keys `>' and `<'.
15454 If you don't like the calendar, turn it off with
15455 \(setq org-read-date-popup-calendar nil)
15457 With optional argument TO-TIME, the date will immediately be converted
15458 to an internal time.
15459 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15460 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15461 still enter a time, and this function will inform the calling routine
15462 about this change. The calling routine may then choose to change the
15463 format used to insert the time stamp into the buffer to include the time.
15464 With optional argument FROM-STRING, read from this string instead from
15465 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15466 the time/date that is used for everything that is not specified by the
15467 user."
15468 (require 'parse-time)
15469 (let* ((org-time-stamp-rounding-minutes
15470 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15471 (org-dcst org-display-custom-times)
15472 (ct (org-current-time))
15473 (org-def (or org-overriding-default-time default-time ct))
15474 (org-defdecode (decode-time org-def))
15475 (dummy (progn
15476 (when (< (nth 2 org-defdecode) org-extend-today-until)
15477 (setcar (nthcdr 2 org-defdecode) -1)
15478 (setcar (nthcdr 1 org-defdecode) 59)
15479 (setq org-def (apply 'encode-time org-defdecode)
15480 org-defdecode (decode-time org-def)))))
15481 (calendar-frame-setup nil)
15482 (calendar-setup nil)
15483 (calendar-move-hook nil)
15484 (calendar-view-diary-initially-flag nil)
15485 (calendar-view-holidays-initially-flag nil)
15486 (timestr (format-time-string
15487 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15488 (prompt (concat (if prompt (concat prompt " ") "")
15489 (format "Date+time [%s]: " timestr)))
15490 ans (org-ans0 "") org-ans1 org-ans2 final)
15492 (cond
15493 (from-string (setq ans from-string))
15494 (org-read-date-popup-calendar
15495 (save-excursion
15496 (save-window-excursion
15497 (calendar)
15498 (org-eval-in-calendar '(setq cursor-type nil) t)
15499 (unwind-protect
15500 (progn
15501 (calendar-forward-day (- (time-to-days org-def)
15502 (calendar-absolute-from-gregorian
15503 (calendar-current-date))))
15504 (org-eval-in-calendar nil t)
15505 (let* ((old-map (current-local-map))
15506 (map (copy-keymap calendar-mode-map))
15507 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15508 (org-defkey map (kbd "RET") 'org-calendar-select)
15509 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15510 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15511 (org-defkey minibuffer-local-map [(meta shift left)]
15512 (lambda () (interactive)
15513 (org-eval-in-calendar '(calendar-backward-month 1))))
15514 (org-defkey minibuffer-local-map [(meta shift right)]
15515 (lambda () (interactive)
15516 (org-eval-in-calendar '(calendar-forward-month 1))))
15517 (org-defkey minibuffer-local-map [(meta shift up)]
15518 (lambda () (interactive)
15519 (org-eval-in-calendar '(calendar-backward-year 1))))
15520 (org-defkey minibuffer-local-map [(meta shift down)]
15521 (lambda () (interactive)
15522 (org-eval-in-calendar '(calendar-forward-year 1))))
15523 (org-defkey minibuffer-local-map [?\e (shift left)]
15524 (lambda () (interactive)
15525 (org-eval-in-calendar '(calendar-backward-month 1))))
15526 (org-defkey minibuffer-local-map [?\e (shift right)]
15527 (lambda () (interactive)
15528 (org-eval-in-calendar '(calendar-forward-month 1))))
15529 (org-defkey minibuffer-local-map [?\e (shift up)]
15530 (lambda () (interactive)
15531 (org-eval-in-calendar '(calendar-backward-year 1))))
15532 (org-defkey minibuffer-local-map [?\e (shift down)]
15533 (lambda () (interactive)
15534 (org-eval-in-calendar '(calendar-forward-year 1))))
15535 (org-defkey minibuffer-local-map [(shift up)]
15536 (lambda () (interactive)
15537 (org-eval-in-calendar '(calendar-backward-week 1))))
15538 (org-defkey minibuffer-local-map [(shift down)]
15539 (lambda () (interactive)
15540 (org-eval-in-calendar '(calendar-forward-week 1))))
15541 (org-defkey minibuffer-local-map [(shift left)]
15542 (lambda () (interactive)
15543 (org-eval-in-calendar '(calendar-backward-day 1))))
15544 (org-defkey minibuffer-local-map [(shift right)]
15545 (lambda () (interactive)
15546 (org-eval-in-calendar '(calendar-forward-day 1))))
15547 (org-defkey minibuffer-local-map ">"
15548 (lambda () (interactive)
15549 (org-eval-in-calendar '(scroll-calendar-left 1))))
15550 (org-defkey minibuffer-local-map "<"
15551 (lambda () (interactive)
15552 (org-eval-in-calendar '(scroll-calendar-right 1))))
15553 (org-defkey minibuffer-local-map "\C-v"
15554 (lambda () (interactive)
15555 (org-eval-in-calendar
15556 '(calendar-scroll-left-three-months 1))))
15557 (org-defkey minibuffer-local-map "\M-v"
15558 (lambda () (interactive)
15559 (org-eval-in-calendar
15560 '(calendar-scroll-right-three-months 1))))
15561 (run-hooks 'org-read-date-minibuffer-setup-hook)
15562 (unwind-protect
15563 (progn
15564 (use-local-map map)
15565 (setq org-read-date-inactive inactive)
15566 (add-hook 'post-command-hook 'org-read-date-display)
15567 (setq org-ans0 (read-string prompt default-input
15568 'org-read-date-history nil))
15569 ;; org-ans0: from prompt
15570 ;; org-ans1: from mouse click
15571 ;; org-ans2: from calendar motion
15572 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15573 (remove-hook 'post-command-hook 'org-read-date-display)
15574 (use-local-map old-map)
15575 (when org-read-date-overlay
15576 (delete-overlay org-read-date-overlay)
15577 (setq org-read-date-overlay nil)))))
15578 (bury-buffer "*Calendar*")))))
15580 (t ; Naked prompt only
15581 (unwind-protect
15582 (setq ans (read-string prompt default-input
15583 'org-read-date-history timestr))
15584 (when org-read-date-overlay
15585 (delete-overlay org-read-date-overlay)
15586 (setq org-read-date-overlay nil)))))
15588 (setq final (org-read-date-analyze ans org-def org-defdecode))
15590 (when org-read-date-analyze-forced-year
15591 (message "Year was forced into %s"
15592 (if org-read-date-force-compatible-dates
15593 "compatible range (1970-2037)"
15594 "range representable on this machine"))
15595 (ding))
15597 ;; One round trip to get rid of 34th of August and stuff like that....
15598 (setq final (decode-time (apply 'encode-time final)))
15600 (setq org-read-date-final-answer ans)
15602 (if to-time
15603 (apply 'encode-time final)
15604 (if (and (boundp 'org-time-was-given) org-time-was-given)
15605 (format "%04d-%02d-%02d %02d:%02d"
15606 (nth 5 final) (nth 4 final) (nth 3 final)
15607 (nth 2 final) (nth 1 final))
15608 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15610 (defvar org-def)
15611 (defvar org-defdecode)
15612 (defvar org-with-time)
15613 (defun org-read-date-display ()
15614 "Display the current date prompt interpretation in the minibuffer."
15615 (when org-read-date-display-live
15616 (when org-read-date-overlay
15617 (delete-overlay org-read-date-overlay))
15618 (when (minibufferp (current-buffer))
15619 (save-excursion
15620 (end-of-line 1)
15621 (while (not (equal (buffer-substring
15622 (max (point-min) (- (point) 4)) (point))
15623 " "))
15624 (insert " ")))
15625 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15626 " " (or org-ans1 org-ans2)))
15627 (org-end-time-was-given nil)
15628 (f (org-read-date-analyze ans org-def org-defdecode))
15629 (fmts (if org-dcst
15630 org-time-stamp-custom-formats
15631 org-time-stamp-formats))
15632 (fmt (if (or org-with-time
15633 (and (boundp 'org-time-was-given) org-time-was-given))
15634 (cdr fmts)
15635 (car fmts)))
15636 (txt (format-time-string fmt (apply 'encode-time f)))
15637 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15638 (txt (concat "=> " txt)))
15639 (when (and org-end-time-was-given
15640 (string-match org-plain-time-of-day-regexp txt))
15641 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15642 org-end-time-was-given
15643 (substring txt (match-end 0)))))
15644 (when org-read-date-analyze-futurep
15645 (setq txt (concat txt " (=>F)")))
15646 (setq org-read-date-overlay
15647 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15648 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15650 (defun org-read-date-analyze (ans org-def org-defdecode)
15651 "Analyze the combined answer of the date prompt."
15652 ;; FIXME: cleanup and comment
15653 (let ((nowdecode (decode-time (current-time)))
15654 delta deltan deltaw deltadef year month day
15655 hour minute second wday pm h2 m2 tl wday1
15656 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15657 (setq org-read-date-analyze-futurep nil
15658 org-read-date-analyze-forced-year nil)
15659 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15660 (setq ans "+0"))
15662 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15663 (setq ans (replace-match "" t t ans)
15664 deltan (car delta)
15665 deltaw (nth 1 delta)
15666 deltadef (nth 2 delta)))
15668 ;; Check if there is an iso week date in there. If yes, store the
15669 ;; info and postpone interpreting it until the rest of the parsing
15670 ;; is done.
15671 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15672 (setq iso-year (if (match-end 1)
15673 (org-small-year-to-year
15674 (string-to-number (match-string 1 ans))))
15675 iso-weekday (if (match-end 3)
15676 (string-to-number (match-string 3 ans)))
15677 iso-week (string-to-number (match-string 2 ans)))
15678 (setq ans (replace-match "" t t ans)))
15680 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15681 (when (string-match
15682 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15683 (setq year (if (match-end 2)
15684 (string-to-number (match-string 2 ans))
15685 (progn (setq kill-year t)
15686 (string-to-number (format-time-string "%Y"))))
15687 month (string-to-number (match-string 3 ans))
15688 day (string-to-number (match-string 4 ans)))
15689 (if (< year 100) (setq year (+ 2000 year)))
15690 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15691 t nil ans)))
15693 ;; Help matching dotted european dates
15694 (when (string-match
15695 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15696 (setq year (if (match-end 3)
15697 (string-to-number (match-string 3 ans))
15698 (progn (setq kill-year t)
15699 (string-to-number (format-time-string "%Y"))))
15700 day (string-to-number (match-string 1 ans))
15701 month (string-to-number (match-string 2 ans))
15702 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15703 t nil ans)))
15705 ;; Help matching american dates, like 5/30 or 5/30/7
15706 (when (string-match
15707 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15708 (setq year (if (match-end 4)
15709 (string-to-number (match-string 4 ans))
15710 (progn (setq kill-year t)
15711 (string-to-number (format-time-string "%Y"))))
15712 month (string-to-number (match-string 1 ans))
15713 day (string-to-number (match-string 2 ans)))
15714 (if (< year 100) (setq year (+ 2000 year)))
15715 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15716 t nil ans)))
15717 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15718 ;; If there is a time with am/pm, and *no* time without it, we convert
15719 ;; so that matching will be successful.
15720 (loop for i from 1 to 2 do ; twice, for end time as well
15721 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15722 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15723 (setq hour (string-to-number (match-string 1 ans))
15724 minute (if (match-end 3)
15725 (string-to-number (match-string 3 ans))
15727 pm (equal ?p
15728 (string-to-char (downcase (match-string 4 ans)))))
15729 (if (and (= hour 12) (not pm))
15730 (setq hour 0)
15731 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15732 (setq ans (replace-match (format "%02d:%02d" hour minute)
15733 t t ans))))
15735 ;; Check if a time range is given as a duration
15736 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15737 (setq hour (string-to-number (match-string 1 ans))
15738 h2 (+ hour (string-to-number (match-string 3 ans)))
15739 minute (string-to-number (match-string 2 ans))
15740 m2 (+ minute (if (match-end 5) (string-to-number
15741 (match-string 5 ans))0)))
15742 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15743 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15744 t t ans)))
15746 ;; Check if there is a time range
15747 (when (boundp 'org-end-time-was-given)
15748 (setq org-time-was-given nil)
15749 (when (and (string-match org-plain-time-of-day-regexp ans)
15750 (match-end 8))
15751 (setq org-end-time-was-given (match-string 8 ans))
15752 (setq ans (concat (substring ans 0 (match-beginning 7))
15753 (substring ans (match-end 7))))))
15755 (setq tl (parse-time-string ans)
15756 day (or (nth 3 tl) (nth 3 org-defdecode))
15757 month (or (nth 4 tl)
15758 (if (and org-read-date-prefer-future
15759 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15760 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15761 (nth 4 org-defdecode)))
15762 year (or (and (not kill-year) (nth 5 tl))
15763 (if (and org-read-date-prefer-future
15764 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15765 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15766 (nth 5 org-defdecode)))
15767 hour (or (nth 2 tl) (nth 2 org-defdecode))
15768 minute (or (nth 1 tl) (nth 1 org-defdecode))
15769 second (or (nth 0 tl) 0)
15770 wday (nth 6 tl))
15772 (when (and (eq org-read-date-prefer-future 'time)
15773 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15774 (equal day (nth 3 nowdecode))
15775 (equal month (nth 4 nowdecode))
15776 (equal year (nth 5 nowdecode))
15777 (nth 2 tl)
15778 (or (< (nth 2 tl) (nth 2 nowdecode))
15779 (and (= (nth 2 tl) (nth 2 nowdecode))
15780 (nth 1 tl)
15781 (< (nth 1 tl) (nth 1 nowdecode)))))
15782 (setq day (1+ day)
15783 futurep t))
15785 ;; Special date definitions below
15786 (cond
15787 (iso-week
15788 ;; There was an iso week
15789 (require 'cal-iso)
15790 (setq futurep nil)
15791 (setq year (or iso-year year)
15792 day (or iso-weekday wday 1)
15793 wday nil ; to make sure that the trigger below does not match
15794 iso-date (calendar-gregorian-from-absolute
15795 (calendar-absolute-from-iso
15796 (list iso-week day year))))
15797 ; FIXME: Should we also push ISO weeks into the future?
15798 ; (when (and org-read-date-prefer-future
15799 ; (not iso-year)
15800 ; (< (calendar-absolute-from-gregorian iso-date)
15801 ; (time-to-days (current-time))))
15802 ; (setq year (1+ year)
15803 ; iso-date (calendar-gregorian-from-absolute
15804 ; (calendar-absolute-from-iso
15805 ; (list iso-week day year)))))
15806 (setq month (car iso-date)
15807 year (nth 2 iso-date)
15808 day (nth 1 iso-date)))
15809 (deltan
15810 (setq futurep nil)
15811 (unless deltadef
15812 (let ((now (decode-time (current-time))))
15813 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15814 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15815 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15816 ((equal deltaw "m") (setq month (+ month deltan)))
15817 ((equal deltaw "y") (setq year (+ year deltan)))))
15818 ((and wday (not (nth 3 tl)))
15819 ;; Weekday was given, but no day, so pick that day in the week
15820 ;; on or after the derived date.
15821 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15822 (unless (equal wday wday1)
15823 (setq day (+ day (% (- wday wday1 -7) 7))))))
15824 (if (and (boundp 'org-time-was-given)
15825 (nth 2 tl))
15826 (setq org-time-was-given t))
15827 (if (< year 100) (setq year (+ 2000 year)))
15828 ;; Check of the date is representable
15829 (if org-read-date-force-compatible-dates
15830 (progn
15831 (if (< year 1970)
15832 (setq year 1970 org-read-date-analyze-forced-year t))
15833 (if (> year 2037)
15834 (setq year 2037 org-read-date-analyze-forced-year t)))
15835 (condition-case nil
15836 (ignore (encode-time second minute hour day month year))
15837 (error
15838 (setq year (nth 5 org-defdecode))
15839 (setq org-read-date-analyze-forced-year t))))
15840 (setq org-read-date-analyze-futurep futurep)
15841 (list second minute hour day month year)))
15843 (defvar parse-time-weekdays)
15844 (defun org-read-date-get-relative (s today default)
15845 "Check string S for special relative date string.
15846 TODAY and DEFAULT are internal times, for today and for a default.
15847 Return shift list (N what def-flag)
15848 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15849 N is the number of WHATs to shift.
15850 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15851 the DEFAULT date rather than TODAY."
15852 (require 'parse-time)
15853 (when (and
15854 (string-match
15855 (concat
15856 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15857 "\\([0-9]+\\)?"
15858 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15859 "\\([ \t]\\|$\\)") s)
15860 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15861 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15862 (string-to-char (substring (match-string 1 s) -1))
15863 ?+))
15864 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15865 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15866 (what (if (match-end 3) (match-string 3 s) "d"))
15867 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15868 (date (if rel default today))
15869 (wday (nth 6 (decode-time date)))
15870 delta)
15871 (if wday1
15872 (progn
15873 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15874 (if (= dir ?-) (setq delta (- delta 7)))
15875 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15876 (list delta "d" rel))
15877 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15879 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15880 "Turn a user-specified date into the internal representation.
15881 The internal representation needed by the calendar is (month day year).
15882 This is a wrapper to handle the brain-dead convention in calendar that
15883 user function argument order change dependent on argument order."
15884 (if (boundp 'calendar-date-style)
15885 (cond
15886 ((eq calendar-date-style 'american)
15887 (list arg1 arg2 arg3))
15888 ((eq calendar-date-style 'european)
15889 (list arg2 arg1 arg3))
15890 ((eq calendar-date-style 'iso)
15891 (list arg2 arg3 arg1)))
15892 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15893 (if (org-bound-and-true-p european-calendar-style)
15894 (list arg2 arg1 arg3)
15895 (list arg1 arg2 arg3)))))
15897 (defun org-eval-in-calendar (form &optional keepdate)
15898 "Eval FORM in the calendar window and return to current window.
15899 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15900 otherwise stick to the current value of `org-ans2'."
15901 (let ((sf (selected-frame))
15902 (sw (selected-window)))
15903 (select-window (get-buffer-window "*Calendar*" t))
15904 (eval form)
15905 (when (and (not keepdate) (calendar-cursor-to-date))
15906 (let* ((date (calendar-cursor-to-date))
15907 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15908 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15909 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15910 (select-window sw)
15911 (org-select-frame-set-input-focus sf)))
15913 (defun org-calendar-select ()
15914 "Return to `org-read-date' with the date currently selected.
15915 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15916 (interactive)
15917 (when (calendar-cursor-to-date)
15918 (let* ((date (calendar-cursor-to-date))
15919 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15920 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15921 (if (active-minibuffer-window) (exit-minibuffer))))
15923 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15924 "Insert a date stamp for the date given by the internal TIME.
15925 WITH-HM means use the stamp format that includes the time of the day.
15926 INACTIVE means use square brackets instead of angular ones, so that the
15927 stamp will not contribute to the agenda.
15928 PRE and POST are optional strings to be inserted before and after the
15929 stamp.
15930 The command returns the inserted time stamp."
15931 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15932 stamp)
15933 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15934 (insert-before-markers (or pre ""))
15935 (when (listp extra)
15936 (setq extra (car extra))
15937 (if (and (stringp extra)
15938 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15939 (setq extra (format "-%02d:%02d"
15940 (string-to-number (match-string 1 extra))
15941 (string-to-number (match-string 2 extra))))
15942 (setq extra nil)))
15943 (when extra
15944 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15945 (insert-before-markers (setq stamp (format-time-string fmt time)))
15946 (insert-before-markers (or post ""))
15947 (setq org-last-inserted-timestamp stamp)))
15949 (defun org-toggle-time-stamp-overlays ()
15950 "Toggle the use of custom time stamp formats."
15951 (interactive)
15952 (setq org-display-custom-times (not org-display-custom-times))
15953 (unless org-display-custom-times
15954 (let ((p (point-min)) (bmp (buffer-modified-p)))
15955 (while (setq p (next-single-property-change p 'display))
15956 (if (and (get-text-property p 'display)
15957 (eq (get-text-property p 'face) 'org-date))
15958 (remove-text-properties
15959 p (setq p (next-single-property-change p 'display))
15960 '(display t))))
15961 (set-buffer-modified-p bmp)))
15962 (if (featurep 'xemacs)
15963 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15964 (org-restart-font-lock)
15965 (setq org-table-may-need-update t)
15966 (if org-display-custom-times
15967 (message "Time stamps are overlaid with custom format")
15968 (message "Time stamp overlays removed")))
15970 (defun org-display-custom-time (beg end)
15971 "Overlay modified time stamp format over timestamp between BEG and END."
15972 (let* ((ts (buffer-substring beg end))
15973 t1 w1 with-hm tf time str w2 (off 0))
15974 (save-match-data
15975 (setq t1 (org-parse-time-string ts t))
15976 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15977 (setq off (- (match-end 0) (match-beginning 0)))))
15978 (setq end (- end off))
15979 (setq w1 (- end beg)
15980 with-hm (and (nth 1 t1) (nth 2 t1))
15981 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15982 time (org-fix-decoded-time t1)
15983 str (org-add-props
15984 (format-time-string
15985 (substring tf 1 -1) (apply 'encode-time time))
15986 nil 'mouse-face 'highlight)
15987 w2 (length str))
15988 (if (not (= w2 w1))
15989 (add-text-properties (1+ beg) (+ 2 beg)
15990 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15991 (if (featurep 'xemacs)
15992 (progn
15993 (put-text-property beg end 'invisible t)
15994 (put-text-property beg end 'end-glyph (make-glyph str)))
15995 (put-text-property beg end 'display str))))
15997 (defun org-translate-time (string)
15998 "Translate all timestamps in STRING to custom format.
15999 But do this only if the variable `org-display-custom-times' is set."
16000 (when org-display-custom-times
16001 (save-match-data
16002 (let* ((start 0)
16003 (re org-ts-regexp-both)
16004 t1 with-hm inactive tf time str beg end)
16005 (while (setq start (string-match re string start))
16006 (setq beg (match-beginning 0)
16007 end (match-end 0)
16008 t1 (save-match-data
16009 (org-parse-time-string (substring string beg end) t))
16010 with-hm (and (nth 1 t1) (nth 2 t1))
16011 inactive (equal (substring string beg (1+ beg)) "[")
16012 tf (funcall (if with-hm 'cdr 'car)
16013 org-time-stamp-custom-formats)
16014 time (org-fix-decoded-time t1)
16015 str (format-time-string
16016 (concat
16017 (if inactive "[" "<") (substring tf 1 -1)
16018 (if inactive "]" ">"))
16019 (apply 'encode-time time))
16020 string (replace-match str t t string)
16021 start (+ start (length str)))))))
16022 string)
16024 (defun org-fix-decoded-time (time)
16025 "Set 0 instead of nil for the first 6 elements of time.
16026 Don't touch the rest."
16027 (let ((n 0))
16028 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16030 (defun org-days-to-time (timestamp-string)
16031 "Difference between TIMESTAMP-STRING and now in days."
16032 (- (time-to-days (org-time-string-to-time timestamp-string))
16033 (time-to-days (current-time))))
16035 (defun org-deadline-close (timestamp-string &optional ndays)
16036 "Is the time in TIMESTAMP-STRING close to the current date?"
16037 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16038 (and (< (org-days-to-time timestamp-string) ndays)
16039 (not (org-entry-is-done-p))))
16041 (defun org-get-wdays (ts)
16042 "Get the deadline lead time appropriate for timestring TS."
16043 (cond
16044 ((<= org-deadline-warning-days 0)
16045 ;; 0 or negative, enforce this value no matter what
16046 (- org-deadline-warning-days))
16047 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16048 ;; lead time is specified.
16049 (floor (* (string-to-number (match-string 1 ts))
16050 (cdr (assoc (match-string 2 ts)
16051 '(("d" . 1) ("w" . 7)
16052 ("m" . 30.4) ("y" . 365.25)))))))
16053 ;; go for the default.
16054 (t org-deadline-warning-days)))
16056 (defun org-calendar-select-mouse (ev)
16057 "Return to `org-read-date' with the date currently selected.
16058 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16059 (interactive "e")
16060 (mouse-set-point ev)
16061 (when (calendar-cursor-to-date)
16062 (let* ((date (calendar-cursor-to-date))
16063 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16064 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16065 (if (active-minibuffer-window) (exit-minibuffer))))
16067 (defun org-check-deadlines (ndays)
16068 "Check if there are any deadlines due or past due.
16069 A deadline is considered due if it happens within `org-deadline-warning-days'
16070 days from today's date. If the deadline appears in an entry marked DONE,
16071 it is not shown. The prefix arg NDAYS can be used to test that many
16072 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16073 (interactive "P")
16074 (let* ((org-warn-days
16075 (cond
16076 ((equal ndays '(4)) 100000)
16077 (ndays (prefix-numeric-value ndays))
16078 (t (abs org-deadline-warning-days))))
16079 (case-fold-search nil)
16080 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16081 (callback
16082 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16084 (message "%d deadlines past-due or due within %d days"
16085 (org-occur regexp nil callback)
16086 org-warn-days)))
16088 (defsubst org-re-timestamp (type)
16089 "Return a regexp for timestamp TYPE.
16090 Allowed values for TYPE are:
16092 all: all timestamps
16093 active: only active timestamps (<...>)
16094 inactive: only inactive timestamps ([...])
16095 scheduled: only scheduled timestamps
16096 deadline: only deadline timestamps
16098 When TYPE is nil, fall back on returning a regexp that matches
16099 both scheduled and deadline timestamps."
16100 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16101 ((eq type 'active) org-ts-regexp)
16102 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16103 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16104 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16105 ((eq type 'scheduled-or-deadline)
16106 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16108 (defun org-check-before-date (date)
16109 "Check if there are deadlines or scheduled entries before DATE."
16110 (interactive (list (org-read-date)))
16111 (let ((case-fold-search nil)
16112 (regexp (org-re-timestamp org-ts-type))
16113 (callback
16114 (lambda () (time-less-p
16115 (org-time-string-to-time (match-string 1))
16116 (org-time-string-to-time date)))))
16117 (message "%d entries before %s"
16118 (org-occur regexp nil callback) date)))
16120 (defun org-check-after-date (date)
16121 "Check if there are deadlines or scheduled entries after DATE."
16122 (interactive (list (org-read-date)))
16123 (let ((case-fold-search nil)
16124 (regexp (org-re-timestamp org-ts-type))
16125 (callback
16126 (lambda () (not
16127 (time-less-p
16128 (org-time-string-to-time (match-string 1))
16129 (org-time-string-to-time date))))))
16130 (message "%d entries after %s"
16131 (org-occur regexp nil callback) date)))
16133 (defun org-check-dates-range (start-date end-date)
16134 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16135 (interactive (list (org-read-date nil nil nil "Range starts")
16136 (org-read-date nil nil nil "Range end")))
16137 (let ((case-fold-search nil)
16138 (regexp (org-re-timestamp org-ts-type))
16139 (callback
16140 (lambda ()
16141 (let ((match (match-string 1)))
16142 (and
16143 (not (time-less-p
16144 (org-time-string-to-time match)
16145 (org-time-string-to-time start-date)))
16146 (time-less-p
16147 (org-time-string-to-time match)
16148 (org-time-string-to-time end-date)))))))
16149 (message "%d entries between %s and %s"
16150 (org-occur regexp nil callback) start-date end-date)))
16152 (defun org-evaluate-time-range (&optional to-buffer)
16153 "Evaluate a time range by computing the difference between start and end.
16154 Normally the result is just printed in the echo area, but with prefix arg
16155 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16156 If the time range is actually in a table, the result is inserted into the
16157 next column.
16158 For time difference computation, a year is assumed to be exactly 365
16159 days in order to avoid rounding problems."
16160 (interactive "P")
16162 (org-clock-update-time-maybe)
16163 (save-excursion
16164 (unless (org-at-date-range-p t)
16165 (goto-char (point-at-bol))
16166 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16167 (if (not (org-at-date-range-p t))
16168 (error "Not at a time-stamp range, and none found in current line")))
16169 (let* ((ts1 (match-string 1))
16170 (ts2 (match-string 2))
16171 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16172 (match-end (match-end 0))
16173 (time1 (org-time-string-to-time ts1))
16174 (time2 (org-time-string-to-time ts2))
16175 (t1 (org-float-time time1))
16176 (t2 (org-float-time time2))
16177 (diff (abs (- t2 t1)))
16178 (negative (< (- t2 t1) 0))
16179 ;; (ys (floor (* 365 24 60 60)))
16180 (ds (* 24 60 60))
16181 (hs (* 60 60))
16182 (fy "%dy %dd %02d:%02d")
16183 (fy1 "%dy %dd")
16184 (fd "%dd %02d:%02d")
16185 (fd1 "%dd")
16186 (fh "%02d:%02d")
16187 y d h m align)
16188 (if havetime
16189 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16191 d (floor (/ diff ds)) diff (mod diff ds)
16192 h (floor (/ diff hs)) diff (mod diff hs)
16193 m (floor (/ diff 60)))
16194 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16196 d (floor (+ (/ diff ds) 0.5))
16197 h 0 m 0))
16198 (if (not to-buffer)
16199 (message "%s" (org-make-tdiff-string y d h m))
16200 (if (org-at-table-p)
16201 (progn
16202 (goto-char match-end)
16203 (setq align t)
16204 (and (looking-at " *|") (goto-char (match-end 0))))
16205 (goto-char match-end))
16206 (if (looking-at
16207 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16208 (replace-match ""))
16209 (if negative (insert " -"))
16210 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16211 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16212 (insert " " (format fh h m))))
16213 (if align (org-table-align))
16214 (message "Time difference inserted")))))
16216 (defun org-make-tdiff-string (y d h m)
16217 (let ((fmt "")
16218 (l nil))
16219 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16220 l (push y l)))
16221 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16222 l (push d l)))
16223 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16224 l (push h l)))
16225 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16226 l (push m l)))
16227 (apply 'format fmt (nreverse l))))
16229 (defun org-time-string-to-time (s &optional buffer pos)
16230 "Convert a timestamp string into internal time."
16231 (condition-case errdata
16232 (apply 'encode-time (org-parse-time-string s))
16233 (error (error "Bad timestamp `%s'%s\nError was: %s"
16234 s (if (not (and buffer pos))
16236 (format " at %d in buffer `%s'" pos buffer))
16237 (cdr errdata)))))
16239 (defun org-time-string-to-seconds (s)
16240 "Convert a timestamp string to a number of seconds."
16241 (org-float-time (org-time-string-to-time s)))
16243 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16244 "Convert a time stamp to an absolute day number.
16245 If there is a specifier for a cyclic time stamp, get the closest date to
16246 DAYNR.
16247 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16248 The variable date is bound by the calendar when this is called."
16249 (cond
16250 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16251 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16252 daynr
16253 (+ daynr 1000)))
16254 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16255 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16256 (time-to-days (current-time))) (match-string 0 s)
16257 prefer show-all))
16258 (t (time-to-days
16259 (condition-case errdata
16260 (apply 'encode-time (org-parse-time-string s))
16261 (error (error "Bad timestamp `%s'%s\nError was: %s"
16262 s (if (not (and buffer pos))
16264 (format " at %d in buffer `%s'" pos buffer))
16265 (cdr errdata))))))))
16267 (defun org-days-to-iso-week (days)
16268 "Return the iso week number."
16269 (require 'cal-iso)
16270 (car (calendar-iso-from-absolute days)))
16272 (defun org-small-year-to-year (year)
16273 "Convert 2-digit years into 4-digit years.
16274 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16275 The year 2000 cannot be abbreviated. Any year larger than 99
16276 is returned unchanged."
16277 (if (< year 38)
16278 (setq year (+ 2000 year))
16279 (if (< year 100)
16280 (setq year (+ 1900 year))))
16281 year)
16283 (defun org-time-from-absolute (d)
16284 "Return the time corresponding to date D.
16285 D may be an absolute day number, or a calendar-type list (month day year)."
16286 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16287 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16289 (defun org-calendar-holiday ()
16290 "List of holidays, for Diary display in Org-mode."
16291 (require 'holidays)
16292 (let ((hl (funcall
16293 (if (fboundp 'calendar-check-holidays)
16294 'calendar-check-holidays 'check-calendar-holidays) date)))
16295 (if hl (mapconcat 'identity hl "; "))))
16297 (defun org-diary-sexp-entry (sexp entry date)
16298 "Process a SEXP diary ENTRY for DATE."
16299 (require 'diary-lib)
16300 (let ((result (if calendar-debug-sexp
16301 (let ((stack-trace-on-error t))
16302 (eval (car (read-from-string sexp))))
16303 (condition-case nil
16304 (eval (car (read-from-string sexp)))
16305 (error
16306 (beep)
16307 (message "Bad sexp at line %d in %s: %s"
16308 (org-current-line)
16309 (buffer-file-name) sexp)
16310 (sleep-for 2))))))
16311 (cond ((stringp result) (split-string result "; "))
16312 ((and (consp result)
16313 (not (consp (cdr result)))
16314 (stringp (cdr result))) (cdr result))
16315 ((and (consp result)
16316 (stringp (car result))) result)
16317 (result entry))))
16319 (defun org-diary-to-ical-string (frombuf)
16320 "Get iCalendar entries from diary entries in buffer FROMBUF.
16321 This uses the icalendar.el library."
16322 (let* ((tmpdir (if (featurep 'xemacs)
16323 (temp-directory)
16324 temporary-file-directory))
16325 (tmpfile (make-temp-name
16326 (expand-file-name "orgics" tmpdir)))
16327 buf rtn b e)
16328 (with-current-buffer frombuf
16329 (icalendar-export-region (point-min) (point-max) tmpfile)
16330 (setq buf (find-buffer-visiting tmpfile))
16331 (set-buffer buf)
16332 (goto-char (point-min))
16333 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16334 (setq b (match-beginning 0)))
16335 (goto-char (point-max))
16336 (if (re-search-backward "^END:VEVENT" nil t)
16337 (setq e (match-end 0)))
16338 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16339 (kill-buffer buf)
16340 (delete-file tmpfile)
16341 rtn))
16343 (defun org-closest-date (start current change prefer show-all)
16344 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16345 When PREFER is `past', return a date that is either CURRENT or past.
16346 When PREFER is `future', return a date that is either CURRENT or future.
16347 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16348 ;; Make the proper lists from the dates
16349 (catch 'exit
16350 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16351 dn dw sday cday n1 n2 n0
16352 d m y y1 y2 date1 date2 nmonths nm ny m2)
16354 (setq start (org-date-to-gregorian start)
16355 current (org-date-to-gregorian
16356 (if show-all
16357 current
16358 (time-to-days (current-time))))
16359 sday (calendar-absolute-from-gregorian start)
16360 cday (calendar-absolute-from-gregorian current))
16362 (if (<= cday sday) (throw 'exit sday))
16364 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16365 (setq dn (string-to-number (match-string 1 change))
16366 dw (cdr (assoc (match-string 2 change) a1)))
16367 (error "Invalid change specifier: %s" change))
16368 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16369 (cond
16370 ((eq dw 'day)
16371 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16372 n2 (+ n1 dn)))
16373 ((eq dw 'year)
16374 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16375 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16376 (setq date1 (list m d y1)
16377 n1 (calendar-absolute-from-gregorian date1)
16378 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16379 n2 (calendar-absolute-from-gregorian date2)))
16380 ((eq dw 'month)
16381 ;; approx number of month between the two dates
16382 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16383 ;; How often does dn fit in there?
16384 (setq d (nth 1 start) m (car start) y (nth 2 start)
16385 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16386 m (+ m nm)
16387 ny (floor (/ m 12))
16388 y (+ y ny)
16389 m (- m (* ny 12)))
16390 (while (> m 12) (setq m (- m 12) y (1+ y)))
16391 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16392 (setq m2 (+ m dn) y2 y)
16393 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16394 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16395 (while (<= n2 cday)
16396 (setq n1 n2 m m2 y y2)
16397 (setq m2 (+ m dn) y2 y)
16398 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16399 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16400 ;; Make sure n1 is the earlier date
16401 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16402 (if show-all
16403 (cond
16404 ((eq prefer 'past) (if (= cday n2) n2 n1))
16405 ((eq prefer 'future) (if (= cday n1) n1 n2))
16406 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16407 (cond
16408 ((eq prefer 'past) (if (= cday n2) n2 n1))
16409 ((eq prefer 'future) (if (= cday n1) n1 n2))
16410 (t (if (= cday n1) n1 n2)))))))
16412 (defun org-date-to-gregorian (date)
16413 "Turn any specification of DATE into a Gregorian date for the calendar."
16414 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16415 ((and (listp date) (= (length date) 3)) date)
16416 ((stringp date)
16417 (setq date (org-parse-time-string date))
16418 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16419 ((listp date)
16420 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16422 (defun org-parse-time-string (s &optional nodefault)
16423 "Parse the standard Org-mode time string.
16424 This should be a lot faster than the normal `parse-time-string'.
16425 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16426 hour and minute fields will be nil if not given."
16427 (if (string-match org-ts-regexp0 s)
16428 (list 0
16429 (if (or (match-beginning 8) (not nodefault))
16430 (string-to-number (or (match-string 8 s) "0")))
16431 (if (or (match-beginning 7) (not nodefault))
16432 (string-to-number (or (match-string 7 s) "0")))
16433 (string-to-number (match-string 4 s))
16434 (string-to-number (match-string 3 s))
16435 (string-to-number (match-string 2 s))
16436 nil nil nil)
16437 (error "Not a standard Org-mode time string: %s" s)))
16439 (defun org-timestamp-up (&optional arg)
16440 "Increase the date item at the cursor by one.
16441 If the cursor is on the year, change the year. If it is on the month,
16442 the day or the time, change that.
16443 With prefix ARG, change by that many units."
16444 (interactive "p")
16445 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16447 (defun org-timestamp-down (&optional arg)
16448 "Decrease the date item at the cursor by one.
16449 If the cursor is on the year, change the year. If it is on the month,
16450 the day or the time, change that.
16451 With prefix ARG, change by that many units."
16452 (interactive "p")
16453 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16455 (defun org-timestamp-up-day (&optional arg)
16456 "Increase the date in the time stamp by one day.
16457 With prefix ARG, change that many days."
16458 (interactive "p")
16459 (if (and (not (org-at-timestamp-p t))
16460 (org-at-heading-p))
16461 (org-todo 'up)
16462 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16464 (defun org-timestamp-down-day (&optional arg)
16465 "Decrease the date in the time stamp by one day.
16466 With prefix ARG, change that many days."
16467 (interactive "p")
16468 (if (and (not (org-at-timestamp-p t))
16469 (org-at-heading-p))
16470 (org-todo 'down)
16471 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16473 (defun org-at-timestamp-p (&optional inactive-ok)
16474 "Determine if the cursor is in or at a timestamp."
16475 (interactive)
16476 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16477 (pos (point))
16478 (ans (or (looking-at tsr)
16479 (save-excursion
16480 (skip-chars-backward "^[<\n\r\t")
16481 (if (> (point) (point-min)) (backward-char 1))
16482 (and (looking-at tsr)
16483 (> (- (match-end 0) pos) -1))))))
16484 (and ans
16485 (boundp 'org-ts-what)
16486 (setq org-ts-what
16487 (cond
16488 ((= pos (match-beginning 0)) 'bracket)
16489 ;; Point is considered to be "on the bracket" whether
16490 ;; it's really on it or right after it.
16491 ((= pos (1- (match-end 0))) 'bracket)
16492 ((= pos (match-end 0)) 'after)
16493 ((org-pos-in-match-range pos 2) 'year)
16494 ((org-pos-in-match-range pos 3) 'month)
16495 ((org-pos-in-match-range pos 7) 'hour)
16496 ((org-pos-in-match-range pos 8) 'minute)
16497 ((or (org-pos-in-match-range pos 4)
16498 (org-pos-in-match-range pos 5)) 'day)
16499 ((and (> pos (or (match-end 8) (match-end 5)))
16500 (< pos (match-end 0)))
16501 (- pos (or (match-end 8) (match-end 5))))
16502 (t 'day))))
16503 ans))
16505 (defun org-toggle-timestamp-type ()
16506 "Toggle the type (<active> or [inactive]) of a time stamp."
16507 (interactive)
16508 (when (org-at-timestamp-p t)
16509 (let ((beg (match-beginning 0)) (end (match-end 0))
16510 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16511 (save-excursion
16512 (goto-char beg)
16513 (while (re-search-forward "[][<>]" end t)
16514 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16515 t t)))
16516 (message "Timestamp is now %sactive"
16517 (if (equal (char-after beg) ?<) "" "in")))))
16519 (defvar org-clock-history) ; defined in org-clock.el
16520 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16521 (defun org-timestamp-change (n &optional what updown)
16522 "Change the date in the time stamp at point.
16523 The date will be changed by N times WHAT. WHAT can be `day', `month',
16524 `year', `minute', `second'. If WHAT is not given, the cursor position
16525 in the timestamp determines what will be changed."
16526 (let ((origin (point)) origin-cat
16527 with-hm inactive
16528 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16529 org-ts-what
16530 extra rem
16531 ts time time0 fixnext clrgx)
16532 (if (not (org-at-timestamp-p t))
16533 (error "Not at a timestamp"))
16534 (if (and (not what) (eq org-ts-what 'bracket))
16535 (org-toggle-timestamp-type)
16536 ;; Point isn't on brackets. Remember the part of the time-stamp
16537 ;; the point was in. Indeed, size of time-stamps may change,
16538 ;; but point must be kept in the same category nonetheless.
16539 (setq origin-cat org-ts-what)
16540 (if (and (not what) (not (eq org-ts-what 'day))
16541 org-display-custom-times
16542 (get-text-property (point) 'display)
16543 (not (get-text-property (1- (point)) 'display)))
16544 (setq org-ts-what 'day))
16545 (setq org-ts-what (or what org-ts-what)
16546 inactive (= (char-after (match-beginning 0)) ?\[)
16547 ts (match-string 0))
16548 (replace-match "")
16549 (if (string-match
16550 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16552 (setq extra (match-string 1 ts)))
16553 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16554 (setq with-hm t))
16555 (setq time0 (org-parse-time-string ts))
16556 (when (and updown
16557 (eq org-ts-what 'minute)
16558 (not current-prefix-arg))
16559 ;; This looks like s-up and s-down. Change by one rounding step.
16560 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16561 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16562 (setcar (cdr time0) (+ (nth 1 time0)
16563 (if (> n 0) (- rem) (- dm rem))))))
16564 (setq time
16565 (encode-time (or (car time0) 0)
16566 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16567 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16568 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16569 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16570 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16571 (nthcdr 6 time0)))
16572 (when (and (member org-ts-what '(hour minute))
16573 extra
16574 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16575 (setq extra (org-modify-ts-extra
16576 extra
16577 (if (eq org-ts-what 'hour) 2 5)
16578 n dm)))
16579 (when (integerp org-ts-what)
16580 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16581 (if (eq what 'calendar)
16582 (let ((cal-date (org-get-date-from-calendar)))
16583 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16584 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16585 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16586 (setcar time0 (or (car time0) 0))
16587 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16588 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16589 (setq time (apply 'encode-time time0))))
16590 ;; Insert the new time-stamp, and ensure point stays in the same
16591 ;; category as before (i.e. not after the last position in that
16592 ;; category).
16593 (let ((pos (point)))
16594 ;; Stay before inserted string. `save-excursion' is of no use.
16595 (setq org-last-changed-timestamp
16596 (org-insert-time-stamp time with-hm inactive nil nil extra))
16597 (goto-char pos))
16598 (save-match-data
16599 (looking-at org-ts-regexp3)
16600 (goto-char (cond
16601 ;; `day' category ends before `hour' if any, or at
16602 ;; the end of the day name.
16603 ((eq origin-cat 'day)
16604 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16605 ((eq origin-cat 'hour) (min (match-end 7) origin))
16606 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16607 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16608 ;; `year' and `month' have both fixed size: point
16609 ;; couldn't have moved into another part.
16610 (t origin))))
16611 ;; Update clock if on a CLOCK line.
16612 (org-clock-update-time-maybe)
16613 ;; Maybe adjust the closest clock in `org-clock-history'
16614 (when org-clock-adjust-closest
16615 (if (not (and (org-at-clock-log-p)
16616 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16617 org-clock-history))))))
16618 (message "No clock to adjust")
16619 (cond ((save-excursion ; fix previous clock?
16620 (re-search-backward org-ts-regexp0 nil t)
16621 (org-looking-back (concat org-clock-string " \\[")))
16622 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16623 ((save-excursion ; fix next clock?
16624 (re-search-backward org-ts-regexp0 nil t)
16625 (looking-at (concat org-ts-regexp0 "\\] =>")))
16626 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16627 (save-window-excursion
16628 ;; Find closest clock to point, adjust the previous/next one in history
16629 (let* ((p (save-excursion (org-back-to-heading t)))
16630 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16631 (clfixnth
16632 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16633 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16634 (if (not clfixpos)
16635 (message "No clock to adjust")
16636 (save-excursion
16637 (org-goto-marker-or-bmk clfixpos)
16638 (org-show-subtree)
16639 (when (re-search-forward clrgx nil t)
16640 (goto-char (match-beginning 1))
16641 (let (org-clock-adjust-closest)
16642 (org-timestamp-change n org-ts-what updown))
16643 (message "Clock adjusted in %s for heading: %s"
16644 (file-name-nondirectory (buffer-file-name))
16645 (org-get-heading t t)))))))))
16646 ;; Try to recenter the calendar window, if any.
16647 (if (and org-calendar-follow-timestamp-change
16648 (get-buffer-window "*Calendar*" t)
16649 (memq org-ts-what '(day month year)))
16650 (org-recenter-calendar (time-to-days time))))))
16652 (defun org-modify-ts-extra (s pos n dm)
16653 "Change the different parts of the lead-time and repeat fields in timestamp."
16654 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16655 ng h m new rem)
16656 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16657 (cond
16658 ((or (org-pos-in-match-range pos 2)
16659 (org-pos-in-match-range pos 3))
16660 (setq m (string-to-number (match-string 3 s))
16661 h (string-to-number (match-string 2 s)))
16662 (if (org-pos-in-match-range pos 2)
16663 (setq h (+ h n))
16664 (setq n (* dm (org-no-warnings (signum n))))
16665 (when (not (= 0 (setq rem (% m dm))))
16666 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16667 (setq m (+ m n)))
16668 (if (< m 0) (setq m (+ m 60) h (1- h)))
16669 (if (> m 59) (setq m (- m 60) h (1+ h)))
16670 (setq h (min 24 (max 0 h)))
16671 (setq ng 1 new (format "-%02d:%02d" h m)))
16672 ((org-pos-in-match-range pos 6)
16673 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16674 ((org-pos-in-match-range pos 5)
16675 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16677 ((org-pos-in-match-range pos 9)
16678 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16679 ((org-pos-in-match-range pos 8)
16680 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16682 (when ng
16683 (setq s (concat
16684 (substring s 0 (match-beginning ng))
16686 (substring s (match-end ng))))))
16689 (defun org-recenter-calendar (date)
16690 "If the calendar is visible, recenter it to DATE."
16691 (let ((cwin (get-buffer-window "*Calendar*" t)))
16692 (when cwin
16693 (let ((calendar-move-hook nil))
16694 (with-selected-window cwin
16695 (calendar-goto-date (if (listp date) date
16696 (calendar-gregorian-from-absolute date))))))))
16698 (defun org-goto-calendar (&optional arg)
16699 "Go to the Emacs calendar at the current date.
16700 If there is a time stamp in the current line, go to that date.
16701 A prefix ARG can be used to force the current date."
16702 (interactive "P")
16703 (let ((tsr org-ts-regexp) diff
16704 (calendar-move-hook nil)
16705 (calendar-view-holidays-initially-flag nil)
16706 (calendar-view-diary-initially-flag nil))
16707 (if (or (org-at-timestamp-p)
16708 (save-excursion
16709 (beginning-of-line 1)
16710 (looking-at (concat ".*" tsr))))
16711 (let ((d1 (time-to-days (current-time)))
16712 (d2 (time-to-days
16713 (org-time-string-to-time (match-string 1)))))
16714 (setq diff (- d2 d1))))
16715 (calendar)
16716 (calendar-goto-today)
16717 (if (and diff (not arg)) (calendar-forward-day diff))))
16719 (defun org-get-date-from-calendar ()
16720 "Return a list (month day year) of date at point in calendar."
16721 (with-current-buffer "*Calendar*"
16722 (save-match-data
16723 (calendar-cursor-to-date))))
16725 (defun org-date-from-calendar ()
16726 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16727 If there is already a time stamp at the cursor position, update it."
16728 (interactive)
16729 (if (org-at-timestamp-p t)
16730 (org-timestamp-change 0 'calendar)
16731 (let ((cal-date (org-get-date-from-calendar)))
16732 (org-insert-time-stamp
16733 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16735 (defun org-minutes-to-hh:mm-string (m)
16736 "Compute H:MM from a number of minutes."
16737 (let ((h (/ m 60)))
16738 (setq m (- m (* 60 h)))
16739 (format org-time-clocksum-format h m)))
16741 (defun org-hh:mm-string-to-minutes (s)
16742 "Convert a string H:MM to a number of minutes.
16743 If the string is just a number, interpret it as minutes.
16744 In fact, the first hh:mm or number in the string will be taken,
16745 there can be extra stuff in the string.
16746 If no number is found, the return value is 0."
16747 (cond
16748 ((integerp s) s)
16749 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16750 (+ (* (string-to-number (match-string 1 s)) 60)
16751 (string-to-number (match-string 2 s))))
16752 ((string-match "\\([0-9]+\\)" s)
16753 (string-to-number (match-string 1 s)))
16754 (t 0)))
16756 (defcustom org-effort-durations
16757 `(("h" . 60)
16758 ("d" . ,(* 60 8))
16759 ("w" . ,(* 60 8 5))
16760 ("m" . ,(* 60 8 5 4))
16761 ("y" . ,(* 60 8 5 40)))
16762 "Conversion factor to minutes for an effort modifier.
16764 Each entry has the form (MODIFIER . MINUTES).
16766 In an effort string, a number followed by MODIFIER is multiplied
16767 by the specified number of MINUTES to obtain an effort in
16768 minutes.
16770 For example, if the value of this variable is ((\"hours\" . 60)), then an
16771 effort string \"2hours\" is equivalent to 120 minutes."
16772 :group 'org-agenda
16773 :version "24.1"
16774 :type '(alist :key-type (string :tag "Modifier")
16775 :value-type (number :tag "Minutes")))
16777 (defcustom org-image-actual-width t
16778 "Should we use the actual width of images when inlining them?
16780 When set to `t', always use the image width.
16782 When set to a number, use imagemagick (when available) to set
16783 the image's width to this value.
16785 When set to a number in a list, try to get the width from the
16786 #+ATTR.* keyword if it matches a width specification like
16787 width=\"[0-9]+\", and fall back on that number if none is found.
16789 When set to nil, try to get the width from an #+ATTR.* keyword
16790 and fall back on the original width if none is found.
16792 This requires Emacs >= 24.1, build with imagemagick support."
16793 :group 'org-appearance
16794 :version "24.3"
16795 :type '(choice
16796 (const :tag "Use the image width" t)
16797 (integer :tag "Use a number of pixels")
16798 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16799 (const :tag "Use #+ATTR* or don't resize" nil)))
16801 (defun org-duration-string-to-minutes (s &optional output-to-string)
16802 "Convert a duration string S to minutes.
16804 A bare number is interpreted as minutes, modifiers can be set by
16805 customizing `org-effort-durations' (which see).
16807 Entries containing a colon are interpreted as H:MM by
16808 `org-hh:mm-string-to-minutes'."
16809 (let ((result 0)
16810 (re (concat "\\([0-9.]+\\) *\\("
16811 (regexp-opt (mapcar 'car org-effort-durations))
16812 "\\)")))
16813 (while (string-match re s)
16814 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16815 (string-to-number (match-string 1 s))))
16816 (setq s (replace-match "" nil t s)))
16817 (setq result (floor result))
16818 (incf result (org-hh:mm-string-to-minutes s))
16819 (if output-to-string (number-to-string result) result)))
16821 ;;;; Files
16823 (defun org-save-all-org-buffers ()
16824 "Save all Org-mode buffers without user confirmation."
16825 (interactive)
16826 (message "Saving all Org-mode buffers...")
16827 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16828 (when (featurep 'org-id) (org-id-locations-save))
16829 (message "Saving all Org-mode buffers... done"))
16831 (defun org-revert-all-org-buffers ()
16832 "Revert all Org-mode buffers.
16833 Prompt for confirmation when there are unsaved changes.
16834 Be sure you know what you are doing before letting this function
16835 overwrite your changes.
16837 This function is useful in a setup where one tracks org files
16838 with a version control system, to revert on one machine after pulling
16839 changes from another. I believe the procedure must be like this:
16841 1. M-x org-save-all-org-buffers
16842 2. Pull changes from the other machine, resolve conflicts
16843 3. M-x org-revert-all-org-buffers"
16844 (interactive)
16845 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16846 (error "Abort"))
16847 (save-excursion
16848 (save-window-excursion
16849 (mapc
16850 (lambda (b)
16851 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16852 (with-current-buffer b buffer-file-name))
16853 (org-pop-to-buffer-same-window b)
16854 (revert-buffer t 'no-confirm)))
16855 (buffer-list))
16856 (when (and (featurep 'org-id) org-id-track-globally)
16857 (org-id-locations-load)))))
16859 ;;;; Agenda files
16861 ;;;###autoload
16862 (defun org-switchb (&optional arg)
16863 "Switch between Org buffers.
16864 With one prefix argument, restrict available buffers to files.
16865 With two prefix arguments, restrict available buffers to agenda files.
16867 Defaults to `iswitchb' for buffer name completion.
16868 Set `org-completion-use-ido' to make it use ido instead."
16869 (interactive "P")
16870 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16871 ((equal arg '(16)) (org-buffer-list 'agenda))
16872 (t (org-buffer-list))))
16873 (org-completion-use-iswitchb org-completion-use-iswitchb)
16874 (org-completion-use-ido org-completion-use-ido))
16875 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16876 (setq org-completion-use-iswitchb t))
16877 (org-pop-to-buffer-same-window
16878 (org-icompleting-read "Org buffer: "
16879 (mapcar 'list (mapcar 'buffer-name blist))
16880 nil t))))
16882 ;;; Define some older names previously used for this functionality
16883 ;;;###autoload
16884 (defalias 'org-ido-switchb 'org-switchb)
16885 ;;;###autoload
16886 (defalias 'org-iswitchb 'org-switchb)
16888 (defun org-buffer-list (&optional predicate exclude-tmp)
16889 "Return a list of Org buffers.
16890 PREDICATE can be `export', `files' or `agenda'.
16892 export restrict the list to Export buffers.
16893 files restrict the list to buffers visiting Org files.
16894 agenda restrict the list to buffers visiting agenda files.
16896 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16897 (let* ((bfn nil)
16898 (agenda-files (and (eq predicate 'agenda)
16899 (mapcar 'file-truename (org-agenda-files t))))
16900 (filter
16901 (cond
16902 ((eq predicate 'files)
16903 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16904 ((eq predicate 'export)
16905 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16906 ((eq predicate 'agenda)
16907 (lambda (b)
16908 (with-current-buffer b
16909 (and (derived-mode-p 'org-mode)
16910 (setq bfn (buffer-file-name b))
16911 (member (file-truename bfn) agenda-files)))))
16912 (t (lambda (b) (with-current-buffer b
16913 (or (derived-mode-p 'org-mode)
16914 (string-match "\*Org .*Export"
16915 (buffer-name b)))))))))
16916 (delq nil
16917 (mapcar
16918 (lambda(b)
16919 (if (and (funcall filter b)
16920 (or (not exclude-tmp)
16921 (not (string-match "tmp" (buffer-name b)))))
16923 nil))
16924 (buffer-list)))))
16926 (defun org-agenda-files (&optional unrestricted archives)
16927 "Get the list of agenda files.
16928 Optional UNRESTRICTED means return the full list even if a restriction
16929 is currently in place.
16930 When ARCHIVES is t, include all archive files that are really being
16931 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16932 `org-agenda-archives-mode' is t."
16933 (let ((files
16934 (cond
16935 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16936 ((stringp org-agenda-files) (org-read-agenda-file-list))
16937 ((listp org-agenda-files) org-agenda-files)
16938 (t (error "Invalid value of `org-agenda-files'")))))
16939 (setq files (apply 'append
16940 (mapcar (lambda (f)
16941 (if (file-directory-p f)
16942 (directory-files
16943 f t org-agenda-file-regexp)
16944 (list f)))
16945 files)))
16946 (when org-agenda-skip-unavailable-files
16947 (setq files (delq nil
16948 (mapcar (function
16949 (lambda (file)
16950 (and (file-readable-p file) file)))
16951 files))))
16952 (when (or (eq archives t)
16953 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16954 (setq files (org-add-archive-files files)))
16955 files))
16957 (defun org-agenda-file-p (&optional file)
16958 "Return non-nil, if FILE is an agenda file.
16959 If FILE is omitted, use the file associated with the current
16960 buffer."
16961 (member (or file (buffer-file-name))
16962 (org-agenda-files t)))
16964 (defun org-edit-agenda-file-list ()
16965 "Edit the list of agenda files.
16966 Depending on setup, this either uses customize to edit the variable
16967 `org-agenda-files', or it visits the file that is holding the list. In the
16968 latter case, the buffer is set up in a way that saving it automatically kills
16969 the buffer and restores the previous window configuration."
16970 (interactive)
16971 (if (stringp org-agenda-files)
16972 (let ((cw (current-window-configuration)))
16973 (find-file org-agenda-files)
16974 (org-set-local 'org-window-configuration cw)
16975 (org-add-hook 'after-save-hook
16976 (lambda ()
16977 (set-window-configuration
16978 (prog1 org-window-configuration
16979 (kill-buffer (current-buffer))))
16980 (org-install-agenda-files-menu)
16981 (message "New agenda file list installed"))
16982 nil 'local)
16983 (message "%s" (substitute-command-keys
16984 "Edit list and finish with \\[save-buffer]")))
16985 (customize-variable 'org-agenda-files)))
16987 (defun org-store-new-agenda-file-list (list)
16988 "Set new value for the agenda file list and save it correctly."
16989 (if (stringp org-agenda-files)
16990 (let ((fe (org-read-agenda-file-list t)) b u)
16991 (while (setq b (find-buffer-visiting org-agenda-files))
16992 (kill-buffer b))
16993 (with-temp-file org-agenda-files
16994 (insert
16995 (mapconcat
16996 (lambda (f) ;; Keep un-expanded entries.
16997 (if (setq u (assoc f fe))
16998 (cdr u)
17000 list "\n")
17001 "\n")))
17002 (let ((org-mode-hook nil) (org-inhibit-startup t)
17003 (org-insert-mode-line-in-empty-file nil))
17004 (setq org-agenda-files list)
17005 (customize-save-variable 'org-agenda-files org-agenda-files))))
17007 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17008 "Read the list of agenda files from a file.
17009 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17010 filenames, used by `org-store-new-agenda-file-list' to write back
17011 un-expanded file names."
17012 (when (file-directory-p org-agenda-files)
17013 (error "`org-agenda-files' cannot be a single directory"))
17014 (when (stringp org-agenda-files)
17015 (with-temp-buffer
17016 (insert-file-contents org-agenda-files)
17017 (mapcar
17018 (lambda (f)
17019 (let ((e (expand-file-name (substitute-in-file-name f)
17020 org-directory)))
17021 (if pair-with-expansion
17022 (cons e f)
17023 e)))
17024 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17026 ;;;###autoload
17027 (defun org-cycle-agenda-files ()
17028 "Cycle through the files in `org-agenda-files'.
17029 If the current buffer visits an agenda file, find the next one in the list.
17030 If the current buffer does not, find the first agenda file."
17031 (interactive)
17032 (let* ((fs (org-agenda-files t))
17033 (files (append fs (list (car fs))))
17034 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17035 file)
17036 (unless files (error "No agenda files"))
17037 (catch 'exit
17038 (while (setq file (pop files))
17039 (if (equal (file-truename file) tcf)
17040 (when (car files)
17041 (find-file (car files))
17042 (throw 'exit t))))
17043 (find-file (car fs)))
17044 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17046 (defun org-agenda-file-to-front (&optional to-end)
17047 "Move/add the current file to the top of the agenda file list.
17048 If the file is not present in the list, it is added to the front. If it is
17049 present, it is moved there. With optional argument TO-END, add/move to the
17050 end of the list."
17051 (interactive "P")
17052 (let ((org-agenda-skip-unavailable-files nil)
17053 (file-alist (mapcar (lambda (x)
17054 (cons (file-truename x) x))
17055 (org-agenda-files t)))
17056 (ctf (file-truename buffer-file-name))
17057 x had)
17058 (setq x (assoc ctf file-alist) had x)
17060 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17061 (if to-end
17062 (setq file-alist (append (delq x file-alist) (list x)))
17063 (setq file-alist (cons x (delq x file-alist))))
17064 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17065 (org-install-agenda-files-menu)
17066 (message "File %s to %s of agenda file list"
17067 (if had "moved" "added") (if to-end "end" "front"))))
17069 (defun org-remove-file (&optional file)
17070 "Remove current file from the list of files in variable `org-agenda-files'.
17071 These are the files which are being checked for agenda entries.
17072 Optional argument FILE means use this file instead of the current."
17073 (interactive)
17074 (let* ((org-agenda-skip-unavailable-files nil)
17075 (file (or file buffer-file-name))
17076 (true-file (file-truename file))
17077 (afile (abbreviate-file-name file))
17078 (files (delq nil (mapcar
17079 (lambda (x)
17080 (if (equal true-file
17081 (file-truename x))
17082 nil x))
17083 (org-agenda-files t)))))
17084 (if (not (= (length files) (length (org-agenda-files t))))
17085 (progn
17086 (org-store-new-agenda-file-list files)
17087 (org-install-agenda-files-menu)
17088 (message "Removed file: %s" afile))
17089 (message "File was not in list: %s (not removed)" afile))))
17091 (defun org-file-menu-entry (file)
17092 (vector file (list 'find-file file) t))
17094 (defun org-check-agenda-file (file)
17095 "Make sure FILE exists. If not, ask user what to do."
17096 (when (not (file-exists-p file))
17097 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17098 (abbreviate-file-name file))
17099 (let ((r (downcase (read-char-exclusive))))
17100 (cond
17101 ((equal r ?r)
17102 (org-remove-file file)
17103 (throw 'nextfile t))
17104 (t (error "Abort"))))))
17106 (defun org-get-agenda-file-buffer (file)
17107 "Get a buffer visiting FILE. If the buffer needs to be created, add
17108 it to the list of buffers which might be released later."
17109 (let ((buf (org-find-base-buffer-visiting file)))
17110 (if buf
17111 buf ; just return it
17112 ;; Make a new buffer and remember it
17113 (setq buf (find-file-noselect file))
17114 (if buf (push buf org-agenda-new-buffers))
17115 buf)))
17117 (defun org-release-buffers (blist)
17118 "Release all buffers in list, asking the user for confirmation when needed.
17119 When a buffer is unmodified, it is just killed. When modified, it is saved
17120 \(if the user agrees) and then killed."
17121 (let (buf file)
17122 (while (setq buf (pop blist))
17123 (setq file (buffer-file-name buf))
17124 (when (and (buffer-modified-p buf)
17125 file
17126 (y-or-n-p (format "Save file %s? " file)))
17127 (with-current-buffer buf (save-buffer)))
17128 (kill-buffer buf))))
17130 (defun org-agenda-prepare-buffers (files)
17131 "Create buffers for all agenda files, protect archived trees and comments."
17132 (interactive)
17133 (let ((pa '(:org-archived t))
17134 (pc '(:org-comment t))
17135 (pall '(:org-archived t :org-comment t))
17136 (inhibit-read-only t)
17137 (rea (concat ":" org-archive-tag ":"))
17138 bmp file re)
17139 (save-excursion
17140 (save-restriction
17141 (while (setq file (pop files))
17142 (catch 'nextfile
17143 (if (bufferp file)
17144 (set-buffer file)
17145 (org-check-agenda-file file)
17146 (set-buffer (org-get-agenda-file-buffer file)))
17147 (widen)
17148 (setq bmp (buffer-modified-p))
17149 (org-refresh-category-properties)
17150 (setq org-todo-keywords-for-agenda
17151 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17152 (setq org-done-keywords-for-agenda
17153 (append org-done-keywords-for-agenda org-done-keywords))
17154 (setq org-todo-keyword-alist-for-agenda
17155 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17156 (setq org-drawers-for-agenda
17157 (append org-drawers-for-agenda org-drawers))
17158 (setq org-tag-alist-for-agenda
17159 (append org-tag-alist-for-agenda org-tag-alist))
17161 (save-excursion
17162 (remove-text-properties (point-min) (point-max) pall)
17163 (when org-agenda-skip-archived-trees
17164 (goto-char (point-min))
17165 (while (re-search-forward rea nil t)
17166 (if (org-at-heading-p t)
17167 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17168 (goto-char (point-min))
17169 (setq re (format org-heading-keyword-regexp-format
17170 org-comment-string))
17171 (while (re-search-forward re nil t)
17172 (add-text-properties
17173 (match-beginning 0) (org-end-of-subtree t) pc)))
17174 (set-buffer-modified-p bmp)))))
17175 (setq org-todo-keywords-for-agenda
17176 (org-uniquify org-todo-keywords-for-agenda))
17177 (setq org-todo-keyword-alist-for-agenda
17178 (org-uniquify org-todo-keyword-alist-for-agenda)
17179 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17181 ;;;; Embedded LaTeX
17183 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17184 "Keymap for the minor `org-cdlatex-mode'.")
17186 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17187 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17188 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17189 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17190 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17192 (defvar org-cdlatex-texmathp-advice-is-done nil
17193 "Flag remembering if we have applied the advice to texmathp already.")
17195 (define-minor-mode org-cdlatex-mode
17196 "Toggle the minor `org-cdlatex-mode'.
17197 This mode supports entering LaTeX environment and math in LaTeX fragments
17198 in Org-mode.
17199 \\{org-cdlatex-mode-map}"
17200 nil " OCDL" nil
17201 (when org-cdlatex-mode
17202 (require 'cdlatex)
17203 (run-hooks 'cdlatex-mode-hook)
17204 (cdlatex-compute-tables))
17205 (unless org-cdlatex-texmathp-advice-is-done
17206 (setq org-cdlatex-texmathp-advice-is-done t)
17207 (defadvice texmathp (around org-math-always-on activate)
17208 "Always return t in org-mode buffers.
17209 This is because we want to insert math symbols without dollars even outside
17210 the LaTeX math segments. If Orgmode thinks that point is actually inside
17211 an embedded LaTeX fragment, let texmathp do its job.
17212 \\[org-cdlatex-mode-map]"
17213 (interactive)
17214 (let (p)
17215 (cond
17216 ((not (derived-mode-p 'org-mode)) ad-do-it)
17217 ((eq this-command 'cdlatex-math-symbol)
17218 (setq ad-return-value t
17219 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17221 (let ((p (org-inside-LaTeX-fragment-p)))
17222 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17223 (setq ad-return-value t
17224 texmathp-why '("Org-mode embedded math" . 0))
17225 (if p ad-do-it)))))))))
17227 (defun turn-on-org-cdlatex ()
17228 "Unconditionally turn on `org-cdlatex-mode'."
17229 (org-cdlatex-mode 1))
17231 (defun org-inside-LaTeX-fragment-p ()
17232 "Test if point is inside a LaTeX fragment.
17233 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17234 sequence appearing also before point.
17235 Even though the matchers for math are configurable, this function assumes
17236 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17237 delimiters are skipped when they have been removed by customization.
17238 The return value is nil, or a cons cell with the delimiter and the
17239 position of this delimiter.
17241 This function does a reasonably good job, but can locally be fooled by
17242 for example currency specifications. For example it will assume being in
17243 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17244 fragments that are properly closed, but during editing, we have to live
17245 with the uncertainty caused by missing closing delimiters. This function
17246 looks only before point, not after."
17247 (catch 'exit
17248 (let ((pos (point))
17249 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17250 (lim (progn
17251 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17252 (point)))
17253 dd-on str (start 0) m re)
17254 (goto-char pos)
17255 (when dodollar
17256 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17257 re (nth 1 (assoc "$" org-latex-regexps)))
17258 (while (string-match re str start)
17259 (cond
17260 ((= (match-end 0) (length str))
17261 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17262 ((= (match-end 0) (- (length str) 5))
17263 (throw 'exit nil))
17264 (t (setq start (match-end 0))))))
17265 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17266 (goto-char pos)
17267 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17268 (and (match-beginning 2) (throw 'exit nil))
17269 ;; count $$
17270 (while (re-search-backward "\\$\\$" lim t)
17271 (setq dd-on (not dd-on)))
17272 (goto-char pos)
17273 (if dd-on (cons "$$" m))))))
17275 (defun org-inside-latex-macro-p ()
17276 "Is point inside a LaTeX macro or its arguments?"
17277 (save-match-data
17278 (org-in-regexp
17279 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17281 (defun org-try-cdlatex-tab ()
17282 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17283 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17284 - inside a LaTeX fragment, or
17285 - after the first word in a line, where an abbreviation expansion could
17286 insert a LaTeX environment."
17287 (when org-cdlatex-mode
17288 (cond
17289 ;; Before any word on the line: No expansion possible.
17290 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17291 ;; Just after first word on the line: Expand it. Make sure it
17292 ;; cannot happen on headlines, though.
17293 ((save-excursion
17294 (skip-chars-backward "a-zA-Z0-9*")
17295 (skip-chars-backward " \t")
17296 (and (bolp) (not (org-at-heading-p))))
17297 (cdlatex-tab) t)
17298 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17300 (defun org-cdlatex-underscore-caret (&optional arg)
17301 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17302 Revert to the normal definition outside of these fragments."
17303 (interactive "P")
17304 (if (org-inside-LaTeX-fragment-p)
17305 (call-interactively 'cdlatex-sub-superscript)
17306 (let (org-cdlatex-mode)
17307 (call-interactively (key-binding (vector last-input-event))))))
17309 (defun org-cdlatex-math-modify (&optional arg)
17310 "Execute `cdlatex-math-modify' in LaTeX fragments.
17311 Revert to the normal definition outside of these fragments."
17312 (interactive "P")
17313 (if (org-inside-LaTeX-fragment-p)
17314 (call-interactively 'cdlatex-math-modify)
17315 (let (org-cdlatex-mode)
17316 (call-interactively (key-binding (vector last-input-event))))))
17318 (defvar org-latex-fragment-image-overlays nil
17319 "List of overlays carrying the images of latex fragments.")
17320 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17322 (defun org-remove-latex-fragment-image-overlays ()
17323 "Remove all overlays with LaTeX fragment images in current buffer."
17324 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17325 (setq org-latex-fragment-image-overlays nil))
17327 (defun org-preview-latex-fragment (&optional subtree)
17328 "Preview the LaTeX fragment at point, or all locally or globally.
17329 If the cursor is in a LaTeX fragment, create the image and overlay
17330 it over the source code. If there is no fragment at point, display
17331 all fragments in the current text, from one headline to the next. With
17332 prefix SUBTREE, display all fragments in the current subtree. With a
17333 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17334 the cursor is before the first headline,
17335 display all fragments in the buffer.
17336 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17337 (interactive "P")
17338 (unless buffer-file-name
17339 (error "Can't preview LaTeX fragment in a non-file buffer"))
17340 (org-remove-latex-fragment-image-overlays)
17341 (save-excursion
17342 (save-restriction
17343 (let (beg end at msg)
17344 (cond
17345 ((or (equal subtree '(16))
17346 (not (save-excursion
17347 (re-search-backward org-outline-regexp-bol nil t))))
17348 (setq beg (point-min) end (point-max)
17349 msg "Creating images for buffer...%s"))
17350 ((equal subtree '(4))
17351 (org-back-to-heading)
17352 (setq beg (point) end (org-end-of-subtree t)
17353 msg "Creating images for subtree...%s"))
17355 (if (setq at (org-inside-LaTeX-fragment-p))
17356 (goto-char (max (point-min) (- (cdr at) 2)))
17357 (org-back-to-heading))
17358 (setq beg (point) end (progn (outline-next-heading) (point))
17359 msg (if at "Creating image...%s"
17360 "Creating images for entry...%s"))))
17361 (message msg "")
17362 (narrow-to-region beg end)
17363 (goto-char beg)
17364 (org-format-latex
17365 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17366 (file-name-nondirectory
17367 buffer-file-name)))
17368 default-directory 'overlays msg at 'forbuffer
17369 org-latex-create-formula-image-program)
17370 (message msg "done. Use `C-c C-c' to remove images.")))))
17372 (defvar org-latex-regexps
17373 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17374 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17375 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17376 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17377 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17378 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17379 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17380 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17381 "Regular expressions for matching embedded LaTeX.")
17383 (defvar org-export-have-math nil) ;; dynamic scoping
17384 (defun org-format-latex (prefix &optional dir overlays msg at
17385 forbuffer processing-type)
17386 "Replace LaTeX fragments with links to an image, and produce images.
17387 Some of the options can be changed using the variable
17388 `org-format-latex-options'."
17389 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17390 (let* ((prefixnodir (file-name-nondirectory prefix))
17391 (absprefix (expand-file-name prefix dir))
17392 (todir (file-name-directory absprefix))
17393 (opt org-format-latex-options)
17394 (optnew org-format-latex-options)
17395 (matchers (plist-get opt :matchers))
17396 (re-list org-latex-regexps)
17397 (org-format-latex-header-extra
17398 (plist-get (org-infile-export-plist) :latex-header-extra))
17399 (cnt 0) txt hash link beg end re e checkdir
17400 string
17401 m n block-type block linkfile movefile ov)
17402 ;; Check the different regular expressions
17403 (while (setq e (pop re-list))
17404 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17405 block (if block-type "\n\n" ""))
17406 (when (member m matchers)
17407 (goto-char (point-min))
17408 (while (re-search-forward re nil t)
17409 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17410 (not (get-text-property (match-beginning n)
17411 'org-protected))
17412 (or (not overlays)
17413 (not (eq (get-char-property (match-beginning n)
17414 'org-overlay-type)
17415 'org-latex-overlay))))
17416 (setq org-export-have-math t)
17417 (cond
17418 ((eq processing-type 'verbatim)
17419 ;; Leave the text verbatim, just protect it
17420 (add-text-properties (match-beginning n) (match-end n)
17421 '(org-protected t)))
17422 ((eq processing-type 'mathjax)
17423 ;; Prepare for MathJax processing
17424 (setq string (match-string n))
17425 (if (member m '("$" "$1"))
17426 (save-excursion
17427 (delete-region (match-beginning n) (match-end n))
17428 (goto-char (match-beginning n))
17429 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17430 "\\)")
17431 '(org-protected t))))
17432 (add-text-properties (match-beginning n) (match-end n)
17433 '(org-protected t))))
17434 ((or (eq processing-type 'dvipng)
17435 (eq processing-type 'imagemagick))
17436 ;; Process to an image
17437 (setq txt (match-string n)
17438 beg (match-beginning n) end (match-end n)
17439 cnt (1+ cnt))
17440 (let ((face (face-at-point))
17441 (fg (plist-get opt :foreground))
17442 (bg (plist-get opt :background))
17443 print-length print-level) ; make sure full list is printed
17444 (when forbuffer
17445 ; Get the colors from the face at point
17446 (goto-char beg)
17447 (when (eq fg 'auto)
17448 (setq fg (face-attribute face :foreground nil 'default)))
17449 (when (eq bg 'auto)
17450 (setq bg (face-attribute face :background nil 'default)))
17451 (setq optnew (copy-sequence opt))
17452 (plist-put optnew :foreground fg)
17453 (plist-put optnew :background bg))
17454 (setq hash (sha1 (prin1-to-string
17455 (list org-format-latex-header
17456 org-format-latex-header-extra
17457 org-export-latex-default-packages-alist
17458 org-export-latex-packages-alist
17459 org-format-latex-options
17460 forbuffer txt fg bg)))
17461 linkfile (format "%s_%s.png" prefix hash)
17462 movefile (format "%s_%s.png" absprefix hash)))
17463 (setq link (concat block "[[file:" linkfile "]]" block))
17464 (if msg (message msg cnt))
17465 (goto-char beg)
17466 (unless checkdir ; make sure the directory exists
17467 (setq checkdir t)
17468 (or (file-directory-p todir) (make-directory todir t)))
17469 (org-create-formula-image
17470 txt movefile optnew forbuffer processing-type)
17471 (if overlays
17472 (progn
17473 (mapc (lambda (o)
17474 (if (eq (overlay-get o 'org-overlay-type)
17475 'org-latex-overlay)
17476 (delete-overlay o)))
17477 (overlays-in beg end))
17478 (setq ov (make-overlay beg end))
17479 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17480 (if (featurep 'xemacs)
17481 (progn
17482 (overlay-put ov 'invisible t)
17483 (overlay-put
17484 ov 'end-glyph
17485 (make-glyph (vector 'png :file movefile))))
17486 (overlay-put
17487 ov 'display
17488 (list 'image :type 'png :file movefile :ascent 'center)))
17489 (push ov org-latex-fragment-image-overlays)
17490 (goto-char end))
17491 (delete-region beg end)
17492 (insert (org-add-props link
17493 (list 'org-latex-src
17494 (replace-regexp-in-string
17495 "\"" "" txt)
17496 'org-latex-src-embed-type
17497 (if block-type 'paragraph 'character))))))
17498 ((eq processing-type 'mathml)
17499 ;; Process to MathML
17500 (unless (save-match-data (org-format-latex-mathml-available-p))
17501 (error "LaTeX to MathML converter not configured"))
17502 (setq txt (match-string n)
17503 beg (match-beginning n) end (match-end n)
17504 cnt (1+ cnt))
17505 (if msg (message msg cnt))
17506 (goto-char beg)
17507 (delete-region beg end)
17508 (insert (org-format-latex-as-mathml
17509 txt block-type prefix dir)))
17511 (error "Unknown conversion type %s for latex fragments"
17512 processing-type)))))))))
17514 (defun org-create-math-formula (latex-frag &optional mathml-file)
17515 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17516 Use `org-latex-to-mathml-convert-command'. If the conversion is
17517 sucessful, return the portion between \"<math...> </math>\"
17518 elements otherwise return nil. When MATHML-FILE is specified,
17519 write the results in to that file. When invoked as an
17520 interactive command, prompt for LATEX-FRAG, with initial value
17521 set to the current active region and echo the results for user
17522 inspection."
17523 (interactive (list (let ((frag (when (org-region-active-p)
17524 (buffer-substring-no-properties
17525 (region-beginning) (region-end)))))
17526 (read-string "LaTeX Fragment: " frag nil frag))))
17527 (unless latex-frag (error "Invalid latex-frag"))
17528 (let* ((tmp-in-file (file-relative-name
17529 (make-temp-name (expand-file-name "ltxmathml-in"))))
17530 (ignore (write-region latex-frag nil tmp-in-file))
17531 (tmp-out-file (file-relative-name
17532 (make-temp-name (expand-file-name "ltxmathml-out"))))
17533 (cmd (format-spec
17534 org-latex-to-mathml-convert-command
17535 `((?j . ,(shell-quote-argument
17536 (expand-file-name org-latex-to-mathml-jar-file)))
17537 (?I . ,(shell-quote-argument tmp-in-file))
17538 (?o . ,(shell-quote-argument tmp-out-file)))))
17539 mathml shell-command-output)
17540 (when (org-called-interactively-p 'any)
17541 (unless (org-format-latex-mathml-available-p)
17542 (error "LaTeX to MathML converter not configured")))
17543 (message "Running %s" cmd)
17544 (setq shell-command-output (shell-command-to-string cmd))
17545 (setq mathml
17546 (when (file-readable-p tmp-out-file)
17547 (with-current-buffer (find-file-noselect tmp-out-file t)
17548 (goto-char (point-min))
17549 (when (re-search-forward
17550 (concat
17551 (regexp-quote
17552 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17553 "\\(.\\|\n\\)*"
17554 (regexp-quote "</math>")) nil t)
17555 (prog1 (match-string 0) (kill-buffer))))))
17556 (cond
17557 (mathml
17558 (setq mathml
17559 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17560 (when mathml-file
17561 (write-region mathml nil mathml-file))
17562 (when (org-called-interactively-p 'any)
17563 (message mathml)))
17564 ((message "LaTeX to MathML conversion failed")
17565 (message shell-command-output)))
17566 (delete-file tmp-in-file)
17567 (when (file-exists-p tmp-out-file)
17568 (delete-file tmp-out-file))
17569 mathml))
17571 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17572 prefix &optional dir)
17573 "Use `org-create-math-formula' but check local cache first."
17574 (let* ((absprefix (expand-file-name prefix dir))
17575 (print-length nil) (print-level nil)
17576 (formula-id (concat
17577 "formula-"
17578 (sha1
17579 (prin1-to-string
17580 (list latex-frag
17581 org-latex-to-mathml-convert-command)))))
17582 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17583 (formula-cache-dir (file-name-directory formula-cache)))
17585 (unless (file-directory-p formula-cache-dir)
17586 (make-directory formula-cache-dir t))
17588 (unless (file-exists-p formula-cache)
17589 (org-create-math-formula latex-frag formula-cache))
17591 (if (file-exists-p formula-cache)
17592 ;; Successful conversion. Return the link to MathML file.
17593 (org-add-props
17594 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17595 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17596 'org-latex-src-embed-type (if latex-frag-type
17597 'paragraph 'character)))
17598 ;; Failed conversion. Return the LaTeX fragment verbatim
17599 (add-text-properties
17600 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17601 latex-frag)))
17603 (defun org-create-formula-image (string tofile options buffer &optional type)
17604 "Create an image from LaTeX source using dvipng or convert.
17605 This function calls either `org-create-formula-image-with-dvipng'
17606 or `org-create-formula-image-with-imagemagick' depending on the
17607 value of `org-latex-create-formula-image-program' or on the value
17608 of the optional TYPE variable.
17610 Note: ultimately these two function should be combined as they
17611 share a good deal of logic."
17612 (org-check-external-command
17613 "latex" "needed to convert LaTeX fragments to images")
17614 (funcall
17615 (case (or type org-latex-create-formula-image-program)
17616 ('dvipng
17617 (org-check-external-command
17618 "dvipng" "needed to convert LaTeX fragments to images")
17619 #'org-create-formula-image-with-dvipng)
17620 ('imagemagick
17621 (org-check-external-command
17622 "convert" "you need to install imagemagick")
17623 #'org-create-formula-image-with-imagemagick)
17624 (t (error
17625 "invalid value of `org-latex-create-formula-image-program'")))
17626 string tofile options buffer))
17628 ;; This function borrows from Ganesh Swami's latex2png.el
17629 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17630 "This calls dvipng."
17631 (require 'org-latex)
17632 (let* ((tmpdir (if (featurep 'xemacs)
17633 (temp-directory)
17634 temporary-file-directory))
17635 (texfilebase (make-temp-name
17636 (expand-file-name "orgtex" tmpdir)))
17637 (texfile (concat texfilebase ".tex"))
17638 (dvifile (concat texfilebase ".dvi"))
17639 (pngfile (concat texfilebase ".png"))
17640 (fnh (if (featurep 'xemacs)
17641 (font-height (face-font 'default))
17642 (face-attribute 'default :height nil)))
17643 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17644 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17645 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17646 "Black"))
17647 (bg (or (plist-get options (if buffer :background :html-background))
17648 "Transparent")))
17649 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17650 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17651 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17652 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17653 (with-temp-file texfile
17654 (insert (org-splice-latex-header
17655 org-format-latex-header
17656 org-export-latex-default-packages-alist
17657 org-export-latex-packages-alist t
17658 org-format-latex-header-extra))
17659 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17660 (require 'org-latex)
17661 (org-export-latex-fix-inputenc))
17662 (let ((dir default-directory))
17663 (condition-case nil
17664 (progn
17665 (cd tmpdir)
17666 (call-process "latex" nil nil nil texfile))
17667 (error nil))
17668 (cd dir))
17669 (if (not (file-exists-p dvifile))
17670 (progn (message "Failed to create dvi file from %s" texfile) nil)
17671 (condition-case nil
17672 (if (featurep 'xemacs)
17673 (call-process "dvipng" nil nil nil
17674 "-fg" fg "-bg" bg
17675 "-T" "tight"
17676 "-o" pngfile
17677 dvifile)
17678 (call-process "dvipng" nil nil nil
17679 "-fg" fg "-bg" bg
17680 "-D" dpi
17681 ;;"-x" scale "-y" scale
17682 "-T" "tight"
17683 "-o" pngfile
17684 dvifile))
17685 (error nil))
17686 (if (not (file-exists-p pngfile))
17687 (if org-format-latex-signal-error
17688 (error "Failed to create png file from %s" texfile)
17689 (message "Failed to create png file from %s" texfile)
17690 nil)
17691 ;; Use the requested file name and clean up
17692 (copy-file pngfile tofile 'replace)
17693 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17694 (if (file-exists-p (concat texfilebase e))
17695 (delete-file (concat texfilebase e))))
17696 pngfile))))
17698 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17699 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17700 "This calls convert, which is included into imagemagick."
17701 (require 'org-latex)
17702 (let* ((tmpdir (if (featurep 'xemacs)
17703 (temp-directory)
17704 temporary-file-directory))
17705 (texfilebase (make-temp-name
17706 (expand-file-name "orgtex" tmpdir)))
17707 (texfile (concat texfilebase ".tex"))
17708 (pdffile (concat texfilebase ".pdf"))
17709 (pngfile (concat texfilebase ".png"))
17710 (fnh (if (featurep 'xemacs)
17711 (font-height (face-font 'default))
17712 (face-attribute 'default :height nil)))
17713 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17714 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17715 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17716 "black"))
17717 (bg (or (plist-get options (if buffer :background :html-background))
17718 "white")))
17719 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17720 (setq fg (org-latex-color-format fg)))
17721 (if (eq bg 'default) (setq bg (org-latex-color :background))
17722 (setq bg (org-latex-color-format
17723 (if (string= bg "Transparent") "white" bg))))
17724 (with-temp-file texfile
17725 (insert (org-splice-latex-header
17726 org-format-latex-header
17727 org-export-latex-default-packages-alist
17728 org-export-latex-packages-alist t
17729 org-format-latex-header-extra))
17730 (insert "\n\\begin{document}\n"
17731 "\\definecolor{fg}{rgb}{" fg "}\n"
17732 "\\definecolor{bg}{rgb}{" bg "}\n"
17733 "\n\\pagecolor{bg}\n"
17734 "\n{\\color{fg}\n"
17735 string
17736 "\n}\n"
17737 "\n\\end{document}\n" )
17738 (require 'org-latex)
17739 (org-export-latex-fix-inputenc))
17740 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17741 (condition-case nil
17742 (progn
17743 (cd tmpdir)
17744 (setq cmds org-latex-to-pdf-process)
17745 (while cmds
17746 (setq latex-frags-cmds (pop cmds))
17747 (if (listp latex-frags-cmds)
17748 (setq cmds nil)
17749 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17750 (while latex-frags-cmds
17751 (setq cmd (pop latex-frags-cmds))
17752 (while (string-match "%b" cmd)
17753 (setq cmd (replace-match
17754 (save-match-data
17755 (shell-quote-argument texfile))
17756 t t cmd)))
17757 (while (string-match "%f" cmd)
17758 (setq cmd (replace-match
17759 (save-match-data
17760 (shell-quote-argument (file-name-nondirectory texfile)))
17761 t t cmd)))
17762 (while (string-match "%o" cmd)
17763 (setq cmd (replace-match
17764 (save-match-data
17765 (shell-quote-argument (file-name-directory texfile)))
17766 t t cmd)))
17767 (setq cmd (split-string cmd))
17768 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17769 (error nil))
17770 (cd dir))
17771 (if (not (file-exists-p pdffile))
17772 (progn (message "Failed to create pdf file from %s" texfile) nil)
17773 (condition-case nil
17774 (if (featurep 'xemacs)
17775 (call-process "convert" nil nil nil
17776 "-density" "96"
17777 "-trim"
17778 "-antialias"
17779 pdffile
17780 "-quality" "100"
17781 ;; "-sharpen" "0x1.0"
17782 pngfile)
17783 (call-process "convert" nil nil nil
17784 "-density" dpi
17785 "-trim"
17786 "-antialias"
17787 pdffile
17788 "-quality" "100"
17789 ; "-sharpen" "0x1.0"
17790 pngfile))
17791 (error nil))
17792 (if (not (file-exists-p pngfile))
17793 (if org-format-latex-signal-error
17794 (error "Failed to create png file from %s" texfile)
17795 (message "Failed to create png file from %s" texfile)
17796 nil)
17797 ;; Use the requested file name and clean up
17798 (copy-file pngfile tofile 'replace)
17799 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17800 (if (file-exists-p (concat texfilebase e))
17801 (delete-file (concat texfilebase e))))
17802 pngfile))))
17804 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17805 "Fill a LaTeX header template TPL.
17806 In the template, the following place holders will be recognized:
17808 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17809 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17810 [PACKAGES] \\usepackage statements for PKG
17811 [NO-PACKAGES] do not include PKG
17812 [EXTRA] the string EXTRA
17813 [NO-EXTRA] do not include EXTRA
17815 For backward compatibility, if both the positive and the negative place
17816 holder is missing, the positive one (without the \"NO-\") will be
17817 assumed to be present at the end of the template.
17818 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17819 EXTRA is a string.
17820 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17821 (let (rpl (end ""))
17822 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17823 (setq rpl (if (or (match-end 1) (not def-pkg))
17824 "" (org-latex-packages-to-string def-pkg snippets-p t))
17825 tpl (replace-match rpl t t tpl))
17826 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17828 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17829 (setq rpl (if (or (match-end 1) (not pkg))
17830 "" (org-latex-packages-to-string pkg snippets-p t))
17831 tpl (replace-match rpl t t tpl))
17832 (if pkg (setq end
17833 (concat end "\n"
17834 (org-latex-packages-to-string pkg snippets-p)))))
17836 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17837 (setq rpl (if (or (match-end 1) (not extra))
17838 "" (concat extra "\n"))
17839 tpl (replace-match rpl t t tpl))
17840 (if (and extra (string-match "\\S-" extra))
17841 (setq end (concat end "\n" extra))))
17843 (if (string-match "\\S-" end)
17844 (concat tpl "\n" end)
17845 tpl)))
17847 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17848 "Turn an alist of packages into a string with the \\usepackage macros."
17849 (setq pkg (mapconcat (lambda(p)
17850 (cond
17851 ((stringp p) p)
17852 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17853 (format "%% Package %s omitted" (cadr p)))
17854 ((equal "" (car p))
17855 (format "\\usepackage{%s}" (cadr p)))
17857 (format "\\usepackage[%s]{%s}"
17858 (car p) (cadr p)))))
17860 "\n"))
17861 (if newline (concat pkg "\n") pkg))
17863 (defun org-dvipng-color (attr)
17864 "Return a RGB color specification for dvipng."
17865 (apply 'format "rgb %s %s %s"
17866 (mapcar 'org-normalize-color
17867 (if (featurep 'xemacs)
17868 (color-rgb-components
17869 (face-property 'default
17870 (cond ((eq attr :foreground) 'foreground)
17871 ((eq attr :background) 'background))))
17872 (color-values (face-attribute 'default attr nil))))))
17874 (defun org-dvipng-color-format (color-name)
17875 "Convert COLOR-NAME to a RGB color value for dvipng."
17876 (apply 'format "rgb %s %s %s"
17877 (mapcar 'org-normalize-color
17878 (color-values color-name))))
17880 (defun org-latex-color (attr)
17881 "Return a RGB color for the LaTeX color package."
17882 (apply 'format "%s,%s,%s"
17883 (mapcar 'org-normalize-color
17884 (if (featurep 'xemacs)
17885 (color-rgb-components
17886 (face-property 'default
17887 (cond ((eq attr :foreground) 'foreground)
17888 ((eq attr :background) 'background))))
17889 (color-values (face-attribute 'default attr nil))))))
17891 (defun org-latex-color-format (color-name)
17892 "Convert COLOR-NAME to a RGB color value."
17893 (apply 'format "%s,%s,%s"
17894 (mapcar 'org-normalize-color
17895 (color-values color-name))))
17897 (defun org-normalize-color (value)
17898 "Return string to be used as color value for an RGB component."
17899 (format "%g" (/ value 65535.0)))
17901 ;; Image display
17904 (defvar org-inline-image-overlays nil)
17905 (make-variable-buffer-local 'org-inline-image-overlays)
17907 (defun org-toggle-inline-images (&optional include-linked)
17908 "Toggle the display of inline images.
17909 INCLUDE-LINKED is passed to `org-display-inline-images'."
17910 (interactive "P")
17911 (if org-inline-image-overlays
17912 (progn
17913 (org-remove-inline-images)
17914 (message "Inline image display turned off"))
17915 (org-display-inline-images include-linked)
17916 (if (and (org-called-interactively-p)
17917 org-inline-image-overlays)
17918 (message "%d images displayed inline"
17919 (length org-inline-image-overlays))
17920 (message "No images to display inline"))))
17922 (defun org-redisplay-inline-images ()
17923 "Refresh the display of inline images."
17924 (interactive)
17925 (if (not org-inline-image-overlays)
17926 (org-toggle-inline-images)
17927 (org-toggle-inline-images)
17928 (org-toggle-inline-images)))
17930 (defun org-display-inline-images (&optional include-linked refresh beg end)
17931 "Display inline images.
17932 Normally only links without a description part are inlined, because this
17933 is how it will work for export. When INCLUDE-LINKED is set, also links
17934 with a description part will be inlined. This can be nice for a quick
17935 look at those images, but it does not reflect what exported files will look
17936 like.
17937 When REFRESH is set, refresh existing images between BEG and END.
17938 This will create new image displays only if necessary.
17939 BEG and END default to the buffer boundaries."
17940 (interactive "P")
17941 (unless refresh
17942 (org-remove-inline-images)
17943 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17944 (save-excursion
17945 (save-restriction
17946 (widen)
17947 (setq beg (or beg (point-min)) end (or end (point-max)))
17948 (goto-char beg)
17949 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17950 (substring (org-image-file-name-regexp) 0 -2)
17951 "\\)\\]" (if include-linked "" "\\]")))
17952 old file ov img type attrwidth width)
17953 (while (re-search-forward re end t)
17954 (setq old (get-char-property-and-overlay (match-beginning 1)
17955 'org-image-overlay)
17956 file (expand-file-name
17957 (concat (or (match-string 3) "") (match-string 4))))
17958 (when (image-type-available-p 'imagemagick)
17959 (setq attrwidth (if (or (listp org-image-actual-width)
17960 (null org-image-actual-width))
17961 (save-excursion
17962 (save-match-data
17963 (move-beginning-of-line 0)
17964 (if (looking-at "#\\+ATTR.*width=\"\\([^\"]+\\)\"")
17965 (string-to-number (match-string 1))))))
17966 width (cond ((eq org-image-actual-width t) nil)
17967 ((null org-image-actual-width) attrwidth)
17968 ((numberp org-image-actual-width)
17969 org-image-actual-width)
17970 ((listp org-image-actual-width)
17971 (or attrwidth (car org-image-actual-width))))
17972 type (if width 'imagemagick)))
17973 (when (file-exists-p file)
17974 (if (and (car-safe old) refresh)
17975 (image-refresh (overlay-get (cdr old) 'display))
17976 (setq img (save-match-data (create-image file type nil :width width)))
17977 (when img
17978 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17979 (overlay-put ov 'display img)
17980 (overlay-put ov 'face 'default)
17981 (overlay-put ov 'org-image-overlay t)
17982 (overlay-put ov 'modification-hooks
17983 (list 'org-display-inline-modification-hook))
17984 (push ov org-inline-image-overlays)))))))))
17986 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17987 "Remove inline-display overlay if a corresponding region is modified."
17988 (let ((inhibit-modification-hooks t))
17989 (when (and ov after)
17990 (delete ov org-inline-image-overlays)
17991 (delete-overlay ov))))
17993 (defun org-remove-inline-images ()
17994 "Remove inline display of images."
17995 (interactive)
17996 (mapc 'delete-overlay org-inline-image-overlays)
17997 (setq org-inline-image-overlays nil))
17999 ;;;; Key bindings
18001 ;; Outline functions from `outline-mode-prefix-map'
18002 ;; that can be remapped in Org:
18003 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18004 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18005 (define-key org-mode-map [remap outline-forward-same-level]
18006 'org-forward-heading-same-level)
18007 (define-key org-mode-map [remap outline-backward-same-level]
18008 'org-backward-heading-same-level)
18009 (define-key org-mode-map [remap show-branches]
18010 'org-kill-note-or-show-branches)
18011 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18012 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18013 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18015 ;; Outline functions from `outline-mode-prefix-map' that can not
18016 ;; be remapped in Org:
18018 ;; - the column "key binding" shows whether the Outline function is still
18019 ;; available in Org mode on the same key that it has been bound to in
18020 ;; Outline mode:
18021 ;; - "overridden": key used for a different functionality in Org mode
18022 ;; - else: key still bound to the same Outline function in Org mode
18024 ;; | Outline function | key binding | Org replacement |
18025 ;; |------------------------------------+-------------+-----------------------|
18026 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18027 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18028 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18029 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18030 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18031 ;; | `show-entry' | overridden | no replacement |
18032 ;; | `show-children' | `C-c C-i' | visibility cycling |
18033 ;; | `show-branches' | `C-c C-k' | still same function |
18034 ;; | `show-subtree' | overridden | visibility cycling |
18035 ;; | `show-all' | overridden | no replacement |
18036 ;; | `hide-subtree' | overridden | visibility cycling |
18037 ;; | `hide-body' | overridden | no replacement |
18038 ;; | `hide-entry' | overridden | visibility cycling |
18039 ;; | `hide-leaves' | overridden | no replacement |
18040 ;; | `hide-sublevels' | overridden | no replacement |
18041 ;; | `hide-other' | overridden | no replacement |
18043 ;; Make `C-c C-x' a prefix key
18044 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18046 ;; TAB key with modifiers
18047 (org-defkey org-mode-map "\C-i" 'org-cycle)
18048 (org-defkey org-mode-map [(tab)] 'org-cycle)
18049 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18050 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18051 ;; The following line is necessary under Suse GNU/Linux
18052 (unless (featurep 'xemacs)
18053 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18054 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18055 (define-key org-mode-map [backtab] 'org-shifttab)
18057 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18058 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18059 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18061 ;; Cursor keys with modifiers
18062 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18063 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18064 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18065 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18067 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18068 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18069 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18070 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18072 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18073 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18074 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18075 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18077 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18078 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18079 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18080 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18082 ;; Babel keys
18083 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18084 (mapc (lambda (pair)
18085 (define-key org-babel-map (car pair) (cdr pair)))
18086 org-babel-key-bindings)
18088 ;;; Extra keys for tty access.
18089 ;; We only set them when really needed because otherwise the
18090 ;; menus don't show the simple keys
18092 (when (or org-use-extra-keys
18093 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18094 (not window-system))
18095 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18096 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18097 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18098 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18099 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18100 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18101 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18102 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18103 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18104 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18105 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18106 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18107 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18108 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18109 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18110 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18111 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18112 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18113 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18114 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18115 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18116 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18117 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18118 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18119 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18120 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18121 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18122 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18124 ;; All the other keys
18126 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18127 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18128 (if (boundp 'narrow-map)
18129 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18130 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18131 (if (boundp 'narrow-map)
18132 (org-defkey narrow-map "b" 'org-narrow-to-block)
18133 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18134 (if (boundp 'narrow-map)
18135 (org-defkey narrow-map "e" 'org-narrow-to-element)
18136 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18137 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18138 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18139 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18140 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18141 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18142 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18143 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18144 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18145 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18146 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18147 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18148 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18149 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18150 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18151 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18152 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18153 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18154 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18155 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18156 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18157 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18158 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18159 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18160 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18161 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18162 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18163 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18164 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18165 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18166 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18167 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18168 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18169 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18170 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18171 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18172 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18173 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18174 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18175 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18176 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18177 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18178 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18179 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18180 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18181 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18182 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18183 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18184 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18185 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18186 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18187 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18188 (org-defkey org-mode-map "\C-c^" 'org-sort)
18189 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18190 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18191 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18192 (org-defkey org-mode-map "\C-m" 'org-return)
18193 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18194 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18195 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18196 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18197 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18198 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18199 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18200 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18201 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18202 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18203 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18204 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18205 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18206 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18207 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18208 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18209 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18210 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18211 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18212 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18213 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18214 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18215 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18217 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
18218 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18219 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18220 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18222 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18223 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18224 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18225 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18226 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18227 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18228 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18229 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18230 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18231 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18232 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18233 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18234 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18235 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18236 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18237 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18238 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18239 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18240 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18241 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18242 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18243 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18245 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18246 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18247 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18248 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18249 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18251 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18253 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18255 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18256 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18258 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18261 (when (featurep 'xemacs)
18262 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18265 (defconst org-speed-commands-default
18267 ("Outline Navigation")
18268 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18269 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18270 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18271 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18272 ("u" . (org-speed-move-safe 'outline-up-heading))
18273 ("j" . org-goto)
18274 ("g" . (org-refile t))
18275 ("Outline Visibility")
18276 ("c" . org-cycle)
18277 ("C" . org-shifttab)
18278 (" " . org-display-outline-path)
18279 (":" . org-columns)
18280 ("Outline Structure Editing")
18281 ("U" . org-shiftmetaup)
18282 ("D" . org-shiftmetadown)
18283 ("r" . org-metaright)
18284 ("l" . org-metaleft)
18285 ("R" . org-shiftmetaright)
18286 ("L" . org-shiftmetaleft)
18287 ("i" . (progn (forward-char 1) (call-interactively
18288 'org-insert-heading-respect-content)))
18289 ("^" . org-sort)
18290 ("w" . org-refile)
18291 ("a" . org-archive-subtree-default-with-confirmation)
18292 ("." . org-mark-subtree)
18293 ("#" . org-toggle-comment)
18294 ("Clock Commands")
18295 ("I" . org-clock-in)
18296 ("O" . org-clock-out)
18297 ("Meta Data Editing")
18298 ("t" . org-todo)
18299 ("0" . (org-priority ?\ ))
18300 ("1" . (org-priority ?A))
18301 ("2" . (org-priority ?B))
18302 ("3" . (org-priority ?C))
18303 (";" . org-set-tags-command)
18304 ("e" . org-set-effort)
18305 ("E" . org-inc-effort)
18306 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18307 (org-entry-put (point) "APPT_WARNTIME" m)))
18308 ("Agenda Views etc")
18309 ("v" . org-agenda)
18310 ("/" . org-sparse-tree)
18311 ("Misc")
18312 ("o" . org-open-at-point)
18313 ("?" . org-speed-command-help)
18314 ("<" . (org-agenda-set-restriction-lock 'subtree))
18315 (">" . (org-agenda-remove-restriction-lock))
18317 "The default speed commands.")
18319 (defun org-print-speed-command (e)
18320 (if (> (length (car e)) 1)
18321 (progn
18322 (princ "\n")
18323 (princ (car e))
18324 (princ "\n")
18325 (princ (make-string (length (car e)) ?-))
18326 (princ "\n"))
18327 (princ (car e))
18328 (princ " ")
18329 (if (symbolp (cdr e))
18330 (princ (symbol-name (cdr e)))
18331 (prin1 (cdr e)))
18332 (princ "\n")))
18334 (defun org-speed-command-help ()
18335 "Show the available speed commands."
18336 (interactive)
18337 (if (not org-use-speed-commands)
18338 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18339 (with-output-to-temp-buffer "*Help*"
18340 (princ "User-defined Speed commands\n===========================\n")
18341 (mapc 'org-print-speed-command org-speed-commands-user)
18342 (princ "\n")
18343 (princ "Built-in Speed commands\n=======================\n")
18344 (mapc 'org-print-speed-command org-speed-commands-default))
18345 (with-current-buffer "*Help*"
18346 (setq truncate-lines t))))
18348 (defun org-speed-move-safe (cmd)
18349 "Execute CMD, but make sure that the cursor always ends up in a headline.
18350 If not, return to the original position and throw an error."
18351 (interactive)
18352 (let ((pos (point)))
18353 (call-interactively cmd)
18354 (unless (and (bolp) (org-at-heading-p))
18355 (goto-char pos)
18356 (error "Boundary reached while executing %s" cmd))))
18358 (defvar org-self-insert-command-undo-counter 0)
18360 (defvar org-table-auto-blank-field) ; defined in org-table.el
18361 (defvar org-speed-command nil)
18363 (defun org-speed-command-default-hook (keys)
18364 "Hook for activating single-letter speed commands.
18365 `org-speed-commands-default' specifies a minimal command set.
18366 Use `org-speed-commands-user' for further customization."
18367 (when (or (and (bolp) (looking-at org-outline-regexp))
18368 (and (functionp org-use-speed-commands)
18369 (funcall org-use-speed-commands)))
18370 (cdr (assoc keys (append org-speed-commands-user
18371 org-speed-commands-default)))))
18373 (defun org-babel-speed-command-hook (keys)
18374 "Hook for activating single-letter code block commands."
18375 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18376 (cdr (assoc keys org-babel-key-bindings))))
18378 (defcustom org-speed-command-hook
18379 '(org-speed-command-default-hook org-babel-speed-command-hook)
18380 "Hook for activating speed commands at strategic locations.
18381 Hook functions are called in sequence until a valid handler is
18382 found.
18384 Each hook takes a single argument, a user-pressed command key
18385 which is also a `self-insert-command' from the global map.
18387 Within the hook, examine the cursor position and the command key
18388 and return nil or a valid handler as appropriate. Handler could
18389 be one of an interactive command, a function, or a form.
18391 Set `org-use-speed-commands' to non-nil value to enable this
18392 hook. The default setting is `org-speed-command-default-hook'."
18393 :group 'org-structure
18394 :version "24.1"
18395 :type 'hook)
18397 (defun org-self-insert-command (N)
18398 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18399 If the cursor is in a table looking at whitespace, the whitespace is
18400 overwritten, and the table is not marked as requiring realignment."
18401 (interactive "p")
18402 (org-check-before-invisible-edit 'insert)
18403 (cond
18404 ((and org-use-speed-commands
18405 (setq org-speed-command
18406 (run-hook-with-args-until-success
18407 'org-speed-command-hook (this-command-keys))))
18408 (cond
18409 ((commandp org-speed-command)
18410 (setq this-command org-speed-command)
18411 (call-interactively org-speed-command))
18412 ((functionp org-speed-command)
18413 (funcall org-speed-command))
18414 ((and org-speed-command (listp org-speed-command))
18415 (eval org-speed-command))
18416 (t (let (org-use-speed-commands)
18417 (call-interactively 'org-self-insert-command)))))
18418 ((and
18419 (org-table-p)
18420 (progn
18421 ;; check if we blank the field, and if that triggers align
18422 (and (featurep 'org-table) org-table-auto-blank-field
18423 (member last-command
18424 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18425 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18426 ;; got extra space, this field does not determine column width
18427 (let (org-table-may-need-update) (org-table-blank-field))
18428 ;; no extra space, this field may determine column width
18429 (org-table-blank-field)))
18431 (eq N 1)
18432 (looking-at "[^|\n]* |"))
18433 (let (org-table-may-need-update)
18434 (goto-char (1- (match-end 0)))
18435 (backward-delete-char 1)
18436 (goto-char (match-beginning 0))
18437 (self-insert-command N)))
18439 (setq org-table-may-need-update t)
18440 (self-insert-command N)
18441 (org-fix-tags-on-the-fly)
18442 (if org-self-insert-cluster-for-undo
18443 (if (not (eq last-command 'org-self-insert-command))
18444 (setq org-self-insert-command-undo-counter 1)
18445 (if (>= org-self-insert-command-undo-counter 20)
18446 (setq org-self-insert-command-undo-counter 1)
18447 (and (> org-self-insert-command-undo-counter 0)
18448 buffer-undo-list (listp buffer-undo-list)
18449 (not (cadr buffer-undo-list)) ; remove nil entry
18450 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18451 (setq org-self-insert-command-undo-counter
18452 (1+ org-self-insert-command-undo-counter))))))))
18454 (defun org-check-before-invisible-edit (kind)
18455 "Check is editing if kind KIND would be dangerous with invisible text around.
18456 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18457 ;; First, try to get out of here as quickly as possible, to reduce overhead
18458 (if (and org-catch-invisible-edits
18459 (or (not (boundp 'visible-mode)) (not visible-mode))
18460 (or (get-char-property (point) 'invisible)
18461 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18462 ;; OK, we need to take a closer look
18463 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18464 (invisible-before-point (if (bobp) nil (get-char-property
18465 (1- (point)) 'invisible)))
18466 (border-and-ok-direction
18468 ;; Check if we are acting predictably before invisible text
18469 (and invisible-at-point (not invisible-before-point)
18470 (memq kind '(insert delete-backward)))
18471 ;; Check if we are acting predictably after invisible text
18472 ;; This works not well, and I have turned it off. It seems
18473 ;; better to always show and stop after invisible text.
18474 ;; (and (not invisible-at-point) invisible-before-point
18475 ;; (memq kind '(insert delete)))
18477 (when (or (memq invisible-at-point '(outline org-hide-block t))
18478 (memq invisible-before-point '(outline org-hide-block t)))
18479 (if (eq org-catch-invisible-edits 'error)
18480 (error "Editing in invisible areas is prohibited - make visible first"))
18481 (if (and org-custom-properties-overlays
18482 (y-or-n-p "Display invisible properties in this buffer? "))
18483 (org-toggle-custom-properties-visibility)
18484 ;; Make the area visible
18485 (save-excursion
18486 (if invisible-before-point
18487 (goto-char (previous-single-char-property-change
18488 (point) 'invisible)))
18489 (org-cycle))
18490 (cond
18491 ((eq org-catch-invisible-edits 'show)
18492 ;; That's it, we do the edit after showing
18493 (message
18494 "Unfolding invisible region around point before editing")
18495 (sit-for 1))
18496 ((and (eq org-catch-invisible-edits 'smart)
18497 border-and-ok-direction)
18498 (message "Unfolding invisible region around point before editing"))
18500 ;; Don't do the edit, make the user repeat it in full visibility
18501 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18503 (defun org-fix-tags-on-the-fly ()
18504 (when (and (equal (char-after (point-at-bol)) ?*)
18505 (org-at-heading-p))
18506 (org-align-tags-here org-tags-column)))
18508 (defun org-delete-backward-char (N)
18509 "Like `delete-backward-char', insert whitespace at field end in tables.
18510 When deleting backwards, in tables this function will insert whitespace in
18511 front of the next \"|\" separator, to keep the table aligned. The table will
18512 still be marked for re-alignment if the field did fill the entire column,
18513 because, in this case the deletion might narrow the column."
18514 (interactive "p")
18515 (org-check-before-invisible-edit 'delete-backward)
18516 (if (and (org-table-p)
18517 (eq N 1)
18518 (string-match "|" (buffer-substring (point-at-bol) (point)))
18519 (looking-at ".*?|"))
18520 (let ((pos (point))
18521 (noalign (looking-at "[^|\n\r]* |"))
18522 (c org-table-may-need-update))
18523 (backward-delete-char N)
18524 (if (not overwrite-mode)
18525 (progn
18526 (skip-chars-forward "^|")
18527 (insert " ")
18528 (goto-char (1- pos))))
18529 ;; noalign: if there were two spaces at the end, this field
18530 ;; does not determine the width of the column.
18531 (if noalign (setq org-table-may-need-update c)))
18532 (backward-delete-char N)
18533 (org-fix-tags-on-the-fly)))
18535 (defun org-delete-char (N)
18536 "Like `delete-char', but insert whitespace at field end in tables.
18537 When deleting characters, in tables this function will insert whitespace in
18538 front of the next \"|\" separator, to keep the table aligned. The table will
18539 still be marked for re-alignment if the field did fill the entire column,
18540 because, in this case the deletion might narrow the column."
18541 (interactive "p")
18542 (org-check-before-invisible-edit 'delete)
18543 (if (and (org-table-p)
18544 (not (bolp))
18545 (not (= (char-after) ?|))
18546 (eq N 1))
18547 (if (looking-at ".*?|")
18548 (let ((pos (point))
18549 (noalign (looking-at "[^|\n\r]* |"))
18550 (c org-table-may-need-update))
18551 (replace-match (concat
18552 (substring (match-string 0) 1 -1)
18553 " |"))
18554 (goto-char pos)
18555 ;; noalign: if there were two spaces at the end, this field
18556 ;; does not determine the width of the column.
18557 (if noalign (setq org-table-may-need-update c)))
18558 (delete-char N))
18559 (delete-char N)
18560 (org-fix-tags-on-the-fly)))
18562 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18563 (put 'org-self-insert-command 'delete-selection t)
18564 (put 'orgtbl-self-insert-command 'delete-selection t)
18565 (put 'org-delete-char 'delete-selection 'supersede)
18566 (put 'org-delete-backward-char 'delete-selection 'supersede)
18567 (put 'org-yank 'delete-selection 'yank)
18569 ;; Make `flyspell-mode' delay after some commands
18570 (put 'org-self-insert-command 'flyspell-delayed t)
18571 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18572 (put 'org-delete-char 'flyspell-delayed t)
18573 (put 'org-delete-backward-char 'flyspell-delayed t)
18575 ;; Make pabbrev-mode expand after org-mode commands
18576 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18577 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18579 ;; How to do this: Measure non-white length of current string
18580 ;; If equal to column width, we should realign.
18582 (defun org-remap (map &rest commands)
18583 "In MAP, remap the functions given in COMMANDS.
18584 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18585 (let (new old)
18586 (while commands
18587 (setq old (pop commands) new (pop commands))
18588 (if (fboundp 'command-remapping)
18589 (org-defkey map (vector 'remap old) new)
18590 (substitute-key-definition old new map global-map)))))
18592 (when (eq org-enable-table-editor 'optimized)
18593 ;; If the user wants maximum table support, we need to hijack
18594 ;; some standard editing functions
18595 (org-remap org-mode-map
18596 'self-insert-command 'org-self-insert-command
18597 'delete-char 'org-delete-char
18598 'delete-backward-char 'org-delete-backward-char)
18599 (org-defkey org-mode-map "|" 'org-force-self-insert))
18601 (defvar org-ctrl-c-ctrl-c-hook nil
18602 "Hook for functions attaching themselves to `C-c C-c'.
18604 This can be used to add additional functionality to the C-c C-c
18605 key which executes context-dependent commands. This hook is run
18606 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18607 run after the last test.
18609 Each function will be called with no arguments. The function
18610 must check if the context is appropriate for it to act. If yes,
18611 it should do its thing and then return a non-nil value. If the
18612 context is wrong, just do nothing and return nil.")
18614 (defvar org-ctrl-c-ctrl-c-final-hook nil
18615 "Hook for functions attaching themselves to `C-c C-c'.
18617 This can be used to add additional functionality to the C-c C-c
18618 key which executes context-dependent commands. This hook is run
18619 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18620 before the first test.
18622 Each function will be called with no arguments. The function
18623 must check if the context is appropriate for it to act. If yes,
18624 it should do its thing and then return a non-nil value. If the
18625 context is wrong, just do nothing and return nil.")
18627 (defvar org-tab-first-hook nil
18628 "Hook for functions to attach themselves to TAB.
18629 See `org-ctrl-c-ctrl-c-hook' for more information.
18630 This hook runs as the first action when TAB is pressed, even before
18631 `org-cycle' messes around with the `outline-regexp' to cater for
18632 inline tasks and plain list item folding.
18633 If any function in this hook returns t, any other actions that
18634 would have been caused by TAB (such as table field motion or visibility
18635 cycling) will not occur.")
18637 (defvar org-tab-after-check-for-table-hook nil
18638 "Hook for functions to attach themselves to TAB.
18639 See `org-ctrl-c-ctrl-c-hook' for more information.
18640 This hook runs after it has been established that the cursor is not in a
18641 table, but before checking if the cursor is in a headline or if global cycling
18642 should be done.
18643 If any function in this hook returns t, not other actions like visibility
18644 cycling will be done.")
18646 (defvar org-tab-after-check-for-cycling-hook nil
18647 "Hook for functions to attach themselves to TAB.
18648 See `org-ctrl-c-ctrl-c-hook' for more information.
18649 This hook runs after it has been established that not table field motion and
18650 not visibility should be done because of current context. This is probably
18651 the place where a package like yasnippets can hook in.")
18653 (defvar org-tab-before-tab-emulation-hook nil
18654 "Hook for functions to attach themselves to TAB.
18655 See `org-ctrl-c-ctrl-c-hook' for more information.
18656 This hook runs after every other options for TAB have been exhausted, but
18657 before indentation and \t insertion takes place.")
18659 (defvar org-metaleft-hook nil
18660 "Hook for functions attaching themselves to `M-left'.
18661 See `org-ctrl-c-ctrl-c-hook' for more information.")
18662 (defvar org-metaright-hook nil
18663 "Hook for functions attaching themselves to `M-right'.
18664 See `org-ctrl-c-ctrl-c-hook' for more information.")
18665 (defvar org-metaup-hook nil
18666 "Hook for functions attaching themselves to `M-up'.
18667 See `org-ctrl-c-ctrl-c-hook' for more information.")
18668 (defvar org-metadown-hook nil
18669 "Hook for functions attaching themselves to `M-down'.
18670 See `org-ctrl-c-ctrl-c-hook' for more information.")
18671 (defvar org-shiftmetaleft-hook nil
18672 "Hook for functions attaching themselves to `M-S-left'.
18673 See `org-ctrl-c-ctrl-c-hook' for more information.")
18674 (defvar org-shiftmetaright-hook nil
18675 "Hook for functions attaching themselves to `M-S-right'.
18676 See `org-ctrl-c-ctrl-c-hook' for more information.")
18677 (defvar org-shiftmetaup-hook nil
18678 "Hook for functions attaching themselves to `M-S-up'.
18679 See `org-ctrl-c-ctrl-c-hook' for more information.")
18680 (defvar org-shiftmetadown-hook nil
18681 "Hook for functions attaching themselves to `M-S-down'.
18682 See `org-ctrl-c-ctrl-c-hook' for more information.")
18683 (defvar org-metareturn-hook nil
18684 "Hook for functions attaching themselves to `M-RET'.
18685 See `org-ctrl-c-ctrl-c-hook' for more information.")
18686 (defvar org-shiftup-hook nil
18687 "Hook for functions attaching themselves to `S-up'.
18688 See `org-ctrl-c-ctrl-c-hook' for more information.")
18689 (defvar org-shiftup-final-hook nil
18690 "Hook for functions attaching themselves to `S-up'.
18691 This one runs after all other options except shift-select have been excluded.
18692 See `org-ctrl-c-ctrl-c-hook' for more information.")
18693 (defvar org-shiftdown-hook nil
18694 "Hook for functions attaching themselves to `S-down'.
18695 See `org-ctrl-c-ctrl-c-hook' for more information.")
18696 (defvar org-shiftdown-final-hook nil
18697 "Hook for functions attaching themselves to `S-down'.
18698 This one runs after all other options except shift-select have been excluded.
18699 See `org-ctrl-c-ctrl-c-hook' for more information.")
18700 (defvar org-shiftleft-hook nil
18701 "Hook for functions attaching themselves to `S-left'.
18702 See `org-ctrl-c-ctrl-c-hook' for more information.")
18703 (defvar org-shiftleft-final-hook nil
18704 "Hook for functions attaching themselves to `S-left'.
18705 This one runs after all other options except shift-select have been excluded.
18706 See `org-ctrl-c-ctrl-c-hook' for more information.")
18707 (defvar org-shiftright-hook nil
18708 "Hook for functions attaching themselves to `S-right'.
18709 See `org-ctrl-c-ctrl-c-hook' for more information.")
18710 (defvar org-shiftright-final-hook nil
18711 "Hook for functions attaching themselves to `S-right'.
18712 This one runs after all other options except shift-select have been excluded.
18713 See `org-ctrl-c-ctrl-c-hook' for more information.")
18715 (defun org-modifier-cursor-error ()
18716 "Throw an error, a modified cursor command was applied in wrong context."
18717 (error "This command is active in special context like tables, headlines or items"))
18719 (defun org-shiftselect-error ()
18720 "Throw an error because Shift-Cursor command was applied in wrong context."
18721 (if (and (boundp 'shift-select-mode) shift-select-mode)
18722 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18723 (error "This command works only in special context like headlines or timestamps")))
18725 (defun org-call-for-shift-select (cmd)
18726 (let ((this-command-keys-shift-translated t))
18727 (call-interactively cmd)))
18729 (defun org-shifttab (&optional arg)
18730 "Global visibility cycling or move to previous table field.
18731 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18732 on context.
18733 See the individual commands for more information."
18734 (interactive "P")
18735 (cond
18736 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18737 ((integerp arg)
18738 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18739 (message "Content view to level: %d" arg)
18740 (org-content (prefix-numeric-value arg2))
18741 (setq org-cycle-global-status 'overview)))
18742 (t (call-interactively 'org-global-cycle))))
18744 (defun org-shiftmetaleft ()
18745 "Promote subtree or delete table column.
18746 Calls `org-promote-subtree', `org-outdent-item-tree', or
18747 `org-table-delete-column', depending on context. See the
18748 individual commands for more information."
18749 (interactive)
18750 (cond
18751 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18752 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18753 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18754 ((if (not (org-region-active-p)) (org-at-item-p)
18755 (save-excursion (goto-char (region-beginning))
18756 (org-at-item-p)))
18757 (call-interactively 'org-outdent-item-tree))
18758 (t (org-modifier-cursor-error))))
18760 (defun org-shiftmetaright ()
18761 "Demote subtree or insert table column.
18762 Calls `org-demote-subtree', `org-indent-item-tree', or
18763 `org-table-insert-column', depending on context. See the
18764 individual commands for more information."
18765 (interactive)
18766 (cond
18767 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18768 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18769 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18770 ((if (not (org-region-active-p)) (org-at-item-p)
18771 (save-excursion (goto-char (region-beginning))
18772 (org-at-item-p)))
18773 (call-interactively 'org-indent-item-tree))
18774 (t (org-modifier-cursor-error))))
18776 (defun org-shiftmetaup (&optional arg)
18777 "Move subtree up or kill table row.
18778 Calls `org-move-subtree-up' or `org-table-kill-row' or
18779 `org-move-item-up' or `org-timestamp-up', depending on context.
18780 See the individual commands for more information."
18781 (interactive "P")
18782 (cond
18783 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18784 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18785 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18786 ((org-at-item-p) (call-interactively 'org-move-item-up))
18787 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18788 (call-interactively 'org-timestamp-up)))
18789 (t (org-modifier-cursor-error))))
18791 (defun org-shiftmetadown (&optional arg)
18792 "Move subtree down or insert table row.
18793 Calls `org-move-subtree-down' or `org-table-insert-row' or
18794 `org-move-item-down' or `org-timestamp-up', depending on context.
18795 See the individual commands for more information."
18796 (interactive "P")
18797 (cond
18798 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18799 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18800 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18801 ((org-at-item-p) (call-interactively 'org-move-item-down))
18802 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18803 (call-interactively 'org-timestamp-down)))
18804 (t (org-modifier-cursor-error))))
18806 (defsubst org-hidden-tree-error ()
18807 (error
18808 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18810 (defun org-metaleft (&optional arg)
18811 "Promote heading or move table column to left.
18812 Calls `org-do-promote' or `org-table-move-column', depending on context.
18813 With no specific context, calls the Emacs default `backward-word'.
18814 See the individual commands for more information."
18815 (interactive "P")
18816 (cond
18817 ((run-hook-with-args-until-success 'org-metaleft-hook))
18818 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18819 ((org-with-limited-levels
18820 (or (org-at-heading-p)
18821 (and (org-region-active-p)
18822 (save-excursion
18823 (goto-char (region-beginning))
18824 (org-at-heading-p)))))
18825 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18826 (call-interactively 'org-do-promote))
18827 ;; At an inline task.
18828 ((org-at-heading-p)
18829 (call-interactively 'org-inlinetask-promote))
18830 ((or (org-at-item-p)
18831 (and (org-region-active-p)
18832 (save-excursion
18833 (goto-char (region-beginning))
18834 (org-at-item-p))))
18835 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18836 (call-interactively 'org-outdent-item))
18837 (t (call-interactively 'backward-word))))
18839 (defun org-metaright (&optional arg)
18840 "Demote a subtree, a list item or move table column to right.
18841 In front of a drawer or a block keyword, indent it correctly.
18842 With no specific context, calls the Emacs default `forward-word'.
18843 See the individual commands for more information."
18844 (interactive "P")
18845 (cond
18846 ((run-hook-with-args-until-success 'org-metaright-hook))
18847 ((org-at-table-p) (call-interactively 'org-table-move-column))
18848 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18849 ((org-at-block-p) (call-interactively 'org-indent-block))
18850 ((org-with-limited-levels
18851 (or (org-at-heading-p)
18852 (and (org-region-active-p)
18853 (save-excursion
18854 (goto-char (region-beginning))
18855 (org-at-heading-p)))))
18856 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18857 (call-interactively 'org-do-demote))
18858 ;; At an inline task.
18859 ((org-at-heading-p)
18860 (call-interactively 'org-inlinetask-demote))
18861 ((or (org-at-item-p)
18862 (and (org-region-active-p)
18863 (save-excursion
18864 (goto-char (region-beginning))
18865 (org-at-item-p))))
18866 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18867 (call-interactively 'org-indent-item))
18868 (t (call-interactively 'forward-word))))
18870 (defun org-check-for-hidden (what)
18871 "Check if there are hidden headlines/items in the current visual line.
18872 WHAT can be either `headlines' or `items'. If the current line is
18873 an outline or item heading and it has a folded subtree below it,
18874 this function returns t, nil otherwise."
18875 (let ((re (cond
18876 ((eq what 'headlines) org-outline-regexp-bol)
18877 ((eq what 'items) (org-item-beginning-re))
18878 (t (error "This should not happen"))))
18879 beg end)
18880 (save-excursion
18881 (catch 'exit
18882 (unless (org-region-active-p)
18883 (setq beg (point-at-bol))
18884 (beginning-of-line 2)
18885 (while (and (not (eobp)) ;; this is like `next-line'
18886 (get-char-property (1- (point)) 'invisible))
18887 (beginning-of-line 2))
18888 (setq end (point))
18889 (goto-char beg)
18890 (goto-char (point-at-eol))
18891 (setq end (max end (point)))
18892 (while (re-search-forward re end t)
18893 (if (get-char-property (match-beginning 0) 'invisible)
18894 (throw 'exit t))))
18895 nil))))
18897 (autoload 'org-element-at-point "org-element")
18899 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18900 (declare-function org-element-type "org-element" (element))
18901 (declare-function org-element-context "org-element" ())
18902 (declare-function org-element-contents "org-element" (element))
18903 (declare-function org-element-property "org-element" (property element))
18904 (declare-function org-element-paragraph-parser "org-element" (limit))
18905 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18906 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18907 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18908 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18909 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18911 (defun org-metaup (&optional arg)
18912 "Move subtree up or move table row up.
18913 Calls `org-move-subtree-up' or `org-table-move-row' or
18914 `org-move-item-up', depending on context. See the individual commands
18915 for more information."
18916 (interactive "P")
18917 (cond
18918 ((run-hook-with-args-until-success 'org-metaup-hook))
18919 ((org-region-active-p)
18920 (let* ((a (min (region-beginning) (region-end)))
18921 (b (1- (max (region-beginning) (region-end))))
18922 (c (save-excursion (goto-char a)
18923 (move-beginning-of-line 0)))
18924 (d (save-excursion (goto-char a)
18925 (move-end-of-line 0) (point))))
18926 (transpose-regions a b c d)
18927 (goto-char c)))
18928 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18929 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18930 ((org-at-item-p) (call-interactively 'org-move-item-up))
18931 (t (org-drag-element-backward))))
18933 (defun org-metadown (&optional arg)
18934 "Move subtree down or move table row down.
18935 Calls `org-move-subtree-down' or `org-table-move-row' or
18936 `org-move-item-down', depending on context. See the individual
18937 commands for more information."
18938 (interactive "P")
18939 (cond
18940 ((run-hook-with-args-until-success 'org-metadown-hook))
18941 ((org-region-active-p)
18942 (let* ((a (min (region-beginning) (region-end)))
18943 (b (max (region-beginning) (region-end)))
18944 (c (save-excursion (goto-char b)
18945 (move-beginning-of-line 1)))
18946 (d (save-excursion (goto-char b)
18947 (move-end-of-line 1) (1+ (point)))))
18948 (transpose-regions a b c d)
18949 (goto-char d)))
18950 ((org-at-table-p) (call-interactively 'org-table-move-row))
18951 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18952 ((org-at-item-p) (call-interactively 'org-move-item-down))
18953 (t (org-drag-element-forward))))
18955 (defun org-shiftup (&optional arg)
18956 "Increase item in timestamp or increase priority of current headline.
18957 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18958 depending on context. See the individual commands for more information."
18959 (interactive "P")
18960 (cond
18961 ((run-hook-with-args-until-success 'org-shiftup-hook))
18962 ((and org-support-shift-select (org-region-active-p))
18963 (org-call-for-shift-select 'previous-line))
18964 ((org-at-timestamp-p t)
18965 (call-interactively (if org-edit-timestamp-down-means-later
18966 'org-timestamp-down 'org-timestamp-up)))
18967 ((and (not (eq org-support-shift-select 'always))
18968 org-enable-priority-commands
18969 (org-at-heading-p))
18970 (call-interactively 'org-priority-up))
18971 ((and (not org-support-shift-select) (org-at-item-p))
18972 (call-interactively 'org-previous-item))
18973 ((org-clocktable-try-shift 'up arg))
18974 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18975 (org-support-shift-select
18976 (org-call-for-shift-select 'previous-line))
18977 (t (org-shiftselect-error))))
18979 (defun org-shiftdown (&optional arg)
18980 "Decrease item in timestamp or decrease priority of current headline.
18981 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18982 depending on context. See the individual commands for more information."
18983 (interactive "P")
18984 (cond
18985 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18986 ((and org-support-shift-select (org-region-active-p))
18987 (org-call-for-shift-select 'next-line))
18988 ((org-at-timestamp-p t)
18989 (call-interactively (if org-edit-timestamp-down-means-later
18990 'org-timestamp-up 'org-timestamp-down)))
18991 ((and (not (eq org-support-shift-select 'always))
18992 org-enable-priority-commands
18993 (org-at-heading-p))
18994 (call-interactively 'org-priority-down))
18995 ((and (not org-support-shift-select) (org-at-item-p))
18996 (call-interactively 'org-next-item))
18997 ((org-clocktable-try-shift 'down arg))
18998 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18999 (org-support-shift-select
19000 (org-call-for-shift-select 'next-line))
19001 (t (org-shiftselect-error))))
19003 (defun org-shiftright (&optional arg)
19004 "Cycle the thing at point or in the current line, depending on context.
19005 Depending on context, this does one of the following:
19007 - switch a timestamp at point one day into the future
19008 - on a headline, switch to the next TODO keyword.
19009 - on an item, switch entire list to the next bullet type
19010 - on a property line, switch to the next allowed value
19011 - on a clocktable definition line, move time block into the future"
19012 (interactive "P")
19013 (cond
19014 ((run-hook-with-args-until-success 'org-shiftright-hook))
19015 ((and org-support-shift-select (org-region-active-p))
19016 (org-call-for-shift-select 'forward-char))
19017 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19018 ((and (not (eq org-support-shift-select 'always))
19019 (org-at-heading-p))
19020 (let ((org-inhibit-logging
19021 (not org-treat-S-cursor-todo-selection-as-state-change))
19022 (org-inhibit-blocking
19023 (not org-treat-S-cursor-todo-selection-as-state-change)))
19024 (org-call-with-arg 'org-todo 'right)))
19025 ((or (and org-support-shift-select
19026 (not (eq org-support-shift-select 'always))
19027 (org-at-item-bullet-p))
19028 (and (not org-support-shift-select) (org-at-item-p)))
19029 (org-call-with-arg 'org-cycle-list-bullet nil))
19030 ((and (not (eq org-support-shift-select 'always))
19031 (org-at-property-p))
19032 (call-interactively 'org-property-next-allowed-value))
19033 ((org-clocktable-try-shift 'right arg))
19034 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19035 (org-support-shift-select
19036 (org-call-for-shift-select 'forward-char))
19037 (t (org-shiftselect-error))))
19039 (defun org-shiftleft (&optional arg)
19040 "Cycle the thing at point or in the current line, depending on context.
19041 Depending on context, this does one of the following:
19043 - switch a timestamp at point one day into the past
19044 - on a headline, switch to the previous TODO keyword.
19045 - on an item, switch entire list to the previous bullet type
19046 - on a property line, switch to the previous allowed value
19047 - on a clocktable definition line, move time block into the past"
19048 (interactive "P")
19049 (cond
19050 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19051 ((and org-support-shift-select (org-region-active-p))
19052 (org-call-for-shift-select 'backward-char))
19053 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19054 ((and (not (eq org-support-shift-select 'always))
19055 (org-at-heading-p))
19056 (let ((org-inhibit-logging
19057 (not org-treat-S-cursor-todo-selection-as-state-change))
19058 (org-inhibit-blocking
19059 (not org-treat-S-cursor-todo-selection-as-state-change)))
19060 (org-call-with-arg 'org-todo 'left)))
19061 ((or (and org-support-shift-select
19062 (not (eq org-support-shift-select 'always))
19063 (org-at-item-bullet-p))
19064 (and (not org-support-shift-select) (org-at-item-p)))
19065 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19066 ((and (not (eq org-support-shift-select 'always))
19067 (org-at-property-p))
19068 (call-interactively 'org-property-previous-allowed-value))
19069 ((org-clocktable-try-shift 'left arg))
19070 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19071 (org-support-shift-select
19072 (org-call-for-shift-select 'backward-char))
19073 (t (org-shiftselect-error))))
19075 (defun org-shiftcontrolright ()
19076 "Switch to next TODO set."
19077 (interactive)
19078 (cond
19079 ((and org-support-shift-select (org-region-active-p))
19080 (org-call-for-shift-select 'forward-word))
19081 ((and (not (eq org-support-shift-select 'always))
19082 (org-at-heading-p))
19083 (org-call-with-arg 'org-todo 'nextset))
19084 (org-support-shift-select
19085 (org-call-for-shift-select 'forward-word))
19086 (t (org-shiftselect-error))))
19088 (defun org-shiftcontrolleft ()
19089 "Switch to previous TODO set."
19090 (interactive)
19091 (cond
19092 ((and org-support-shift-select (org-region-active-p))
19093 (org-call-for-shift-select 'backward-word))
19094 ((and (not (eq org-support-shift-select 'always))
19095 (org-at-heading-p))
19096 (org-call-with-arg 'org-todo 'previousset))
19097 (org-support-shift-select
19098 (org-call-for-shift-select 'backward-word))
19099 (t (org-shiftselect-error))))
19101 (defun org-shiftcontrolup ()
19102 "Change timestamps synchronously up in CLOCK log lines."
19103 (interactive)
19104 (cond ((and (not org-support-shift-select)
19105 (org-at-clock-log-p)
19106 (org-at-timestamp-p t))
19107 (org-clock-timestamps-up))
19108 (t (org-shiftselect-error))))
19110 (defun org-shiftcontroldown ()
19111 "Change timestamps synchronously down in CLOCK log lines."
19112 (interactive)
19113 (cond ((and (not org-support-shift-select)
19114 (org-at-clock-log-p)
19115 (org-at-timestamp-p t))
19116 (org-clock-timestamps-down))
19117 (t (org-shiftselect-error))))
19119 (defun org-ctrl-c-ret ()
19120 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19121 (interactive)
19122 (cond
19123 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19124 (t (call-interactively 'org-insert-heading))))
19126 (defun org-find-visible ()
19127 (let ((s (point)))
19128 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19129 (get-char-property s 'invisible)))
19131 (defun org-find-invisible ()
19132 (let ((s (point)))
19133 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19134 (not (get-char-property s 'invisible))))
19137 (defun org-copy-visible (beg end)
19138 "Copy the visible parts of the region."
19139 (interactive "r")
19140 (let (snippets s)
19141 (save-excursion
19142 (save-restriction
19143 (narrow-to-region beg end)
19144 (setq s (goto-char (point-min)))
19145 (while (not (= (point) (point-max)))
19146 (goto-char (org-find-invisible))
19147 (push (buffer-substring s (point)) snippets)
19148 (setq s (goto-char (org-find-visible))))))
19149 (kill-new (apply 'concat (nreverse snippets)))))
19151 (defun org-copy-special ()
19152 "Copy region in table or copy current subtree.
19153 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19154 See the individual commands for more information."
19155 (interactive)
19156 (call-interactively
19157 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19159 (defun org-cut-special ()
19160 "Cut region in table or cut current subtree.
19161 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19162 See the individual commands for more information."
19163 (interactive)
19164 (call-interactively
19165 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19167 (defun org-paste-special (arg)
19168 "Paste rectangular region into table, or past subtree relative to level.
19169 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19170 See the individual commands for more information."
19171 (interactive "P")
19172 (if (org-at-table-p)
19173 (org-table-paste-rectangle)
19174 (org-paste-subtree arg)))
19176 (defun org-edit-special (&optional arg)
19177 "Call a special editor for the stuff at point.
19178 When at a table, call the formula editor with `org-table-edit-formulas'.
19179 When at the first line of an src example, call `org-edit-src-code'.
19180 When in an #+include line, visit the include file. Otherwise call
19181 `ffap' to visit the file at point."
19182 (interactive)
19183 ;; possibly prep session before editing source
19184 (when arg
19185 (let* ((info (org-babel-get-src-block-info))
19186 (lang (nth 0 info))
19187 (params (nth 2 info))
19188 (session (cdr (assoc :session params))))
19189 (when (and info session) ;; we are in a source-code block with a session
19190 (funcall
19191 (intern (concat "org-babel-prep-session:" lang)) session params))))
19192 (cond ;; proceed with `org-edit-special'
19193 ((save-excursion
19194 (beginning-of-line 1)
19195 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19196 (find-file (org-trim (match-string 1))))
19197 ((org-edit-src-code))
19198 ((org-edit-fixed-width-region))
19199 ((org-at-table.el-p)
19200 (org-edit-src-code))
19201 ((or (org-at-table-p)
19202 (save-excursion
19203 (beginning-of-line 1)
19204 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19205 (call-interactively 'org-table-edit-formulas))
19206 (t (call-interactively 'ffap))))
19208 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19209 (defun org-ctrl-c-ctrl-c (&optional arg)
19210 "Set tags in headline, or update according to changed information at point.
19212 This command does many different things, depending on context:
19214 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19215 this is what we do.
19217 - If the cursor is on a statistics cookie, update it.
19219 - If the cursor is in a headline, prompt for tags and insert them
19220 into the current line, aligned to `org-tags-column'. When called
19221 with prefix arg, realign all tags in the current buffer.
19223 - If the cursor is in one of the special #+KEYWORD lines, this
19224 triggers scanning the buffer for these lines and updating the
19225 information.
19227 - If the cursor is inside a table, realign the table. This command
19228 works even if the automatic table editor has been turned off.
19230 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19231 the entire table.
19233 - If the cursor is at a footnote reference or definition, jump to
19234 the corresponding definition or references, respectively.
19236 - If the cursor is a the beginning of a dynamic block, update it.
19238 - If the current buffer is a capture buffer, close note and file it.
19240 - If the cursor is on a <<<target>>>, update radio targets and
19241 corresponding links in this buffer.
19243 - If the cursor is on a numbered item in a plain list, renumber the
19244 ordered list.
19246 - If the cursor is on a checkbox, toggle it.
19248 - If the cursor is on a code block, evaluate it. The variable
19249 `org-confirm-babel-evaluate' can be used to control prompting
19250 before code block evaluation, by default every code block
19251 evaluation requires confirmation. Code block evaluation can be
19252 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19253 (interactive "P")
19254 (let ((org-enable-table-editor t))
19255 (cond
19256 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19257 org-occur-highlights
19258 org-latex-fragment-image-overlays)
19259 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19260 (org-remove-occur-highlights)
19261 (org-remove-latex-fragment-image-overlays)
19262 (message "Temporary highlights/overlays removed from current buffer"))
19263 ((and (local-variable-p 'org-finish-function (current-buffer))
19264 (fboundp org-finish-function))
19265 (funcall org-finish-function))
19266 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19267 ((org-in-regexp org-ts-regexp-both)
19268 (org-timestamp-change 0 'day))
19269 ((or (looking-at org-property-start-re)
19270 (org-at-property-p))
19271 (call-interactively 'org-property-action))
19272 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19273 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19274 (or (org-at-heading-p) (org-at-item-p)))
19275 (call-interactively 'org-update-statistics-cookies))
19276 ((org-at-heading-p) (call-interactively 'org-set-tags))
19277 ((org-at-table.el-p)
19278 (message "Use C-c ' to edit table.el tables"))
19279 ((org-at-table-p)
19280 (org-table-maybe-eval-formula)
19281 (if arg
19282 (call-interactively 'org-table-recalculate)
19283 (org-table-maybe-recalculate-line))
19284 (call-interactively 'org-table-align)
19285 (orgtbl-send-table 'maybe))
19286 ((or (org-footnote-at-reference-p)
19287 (org-footnote-at-definition-p))
19288 (call-interactively 'org-footnote-action))
19289 ((org-at-item-checkbox-p)
19290 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19291 ;; list only if at top item.
19292 (let* ((cbox (match-string 1))
19293 (struct (org-list-struct))
19294 (old-struct (copy-tree struct))
19295 (parents (org-list-parents-alist struct))
19296 (orderedp (org-entry-get nil "ORDERED"))
19297 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19298 block-item)
19299 ;; Use a light version of `org-toggle-checkbox' to avoid
19300 ;; computing list structure twice.
19301 (let ((new-box (cond
19302 ((equal arg '(16)) "[-]")
19303 ((equal arg '(4)) nil)
19304 ((equal "[X]" cbox) "[ ]")
19305 (t "[X]"))))
19306 (if (and firstp arg)
19307 ;; If at first item of sub-list, remove check-box from
19308 ;; every item at the same level.
19309 (mapc
19310 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19311 (org-list-get-all-items
19312 (point-at-bol) struct (org-list-prevs-alist struct)))
19313 (org-list-set-checkbox (point-at-bol) struct new-box)))
19314 ;; Replicate `org-list-write-struct', while grabbing a return
19315 ;; value from `org-list-struct-fix-box'.
19316 (org-list-struct-fix-ind struct parents 2)
19317 (org-list-struct-fix-item-end struct)
19318 (let ((prevs (org-list-prevs-alist struct)))
19319 (org-list-struct-fix-bul struct prevs)
19320 (org-list-struct-fix-ind struct parents)
19321 (setq block-item
19322 (org-list-struct-fix-box struct parents prevs orderedp)))
19323 (org-list-struct-apply-struct struct old-struct)
19324 (org-update-checkbox-count-maybe)
19325 (when block-item
19326 (message
19327 "Checkboxes were removed due to unchecked box at line %d"
19328 (org-current-line block-item)))
19329 (when firstp (org-list-send-list 'maybe))))
19330 ((org-at-item-p)
19331 ;; Cursor at an item: repair list. Do checkbox related actions
19332 ;; only if function was called with an argument. Send list only
19333 ;; if at top item.
19334 (let* ((struct (org-list-struct))
19335 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19336 old-struct)
19337 (when arg
19338 (setq old-struct (copy-tree struct))
19339 (if firstp
19340 ;; If at first item of sub-list, add check-box to every
19341 ;; item at the same level.
19342 (mapc
19343 (lambda (pos)
19344 (unless (org-list-get-checkbox pos struct)
19345 (org-list-set-checkbox pos struct "[ ]")))
19346 (org-list-get-all-items
19347 (point-at-bol) struct (org-list-prevs-alist struct)))
19348 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19349 (org-list-write-struct
19350 struct (org-list-parents-alist struct) old-struct)
19351 (when arg (org-update-checkbox-count-maybe))
19352 (when firstp (org-list-send-list 'maybe))))
19353 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19354 ;; Dynamic block
19355 (beginning-of-line 1)
19356 (save-excursion (org-update-dblock)))
19357 ((save-excursion
19358 (let ((case-fold-search t))
19359 (beginning-of-line 1)
19360 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19361 (cond
19362 ((or (equal (match-string 1) "TBLFM")
19363 (equal (match-string 1) "tblfm"))
19364 ;; Recalculate the table before this line
19365 (save-excursion
19366 (beginning-of-line 1)
19367 (skip-chars-backward " \r\n\t")
19368 (if (org-at-table-p)
19369 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19371 (let ((org-inhibit-startup-visibility-stuff t)
19372 (org-startup-align-all-tables nil))
19373 (when (boundp 'org-table-coordinate-overlays)
19374 (mapc 'delete-overlay org-table-coordinate-overlays)
19375 (setq org-table-coordinate-overlays nil))
19376 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19377 (message "Local setup has been refreshed"))))
19378 ((org-clock-update-time-maybe))
19380 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19381 (error "C-c C-c can do nothing useful at this location"))))))
19383 (defun org-mode-restart ()
19384 "Restart Org-mode, to scan again for special lines.
19385 Also updates the keyword regular expressions."
19386 (interactive)
19387 (org-mode)
19388 (message "Org-mode restarted"))
19390 (defun org-kill-note-or-show-branches ()
19391 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19392 (interactive)
19393 (if (not org-finish-function)
19394 (progn
19395 (hide-subtree)
19396 (call-interactively 'show-branches))
19397 (let ((org-note-abort t))
19398 (funcall org-finish-function))))
19400 (defun org-return (&optional indent)
19401 "Goto next table row or insert a newline.
19402 Calls `org-table-next-row' or `newline', depending on context.
19403 See the individual commands for more information."
19404 (interactive)
19405 (let (org-ts-what)
19406 (cond
19407 ((or (bobp) (org-in-src-block-p))
19408 (if indent (newline-and-indent) (newline)))
19409 ((org-at-table-p)
19410 (org-table-justify-field-maybe)
19411 (call-interactively 'org-table-next-row))
19412 ;; when `newline-and-indent' is called within a list, make sure
19413 ;; text moved stays inside the item.
19414 ((and (org-in-item-p) indent)
19415 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19416 (progn
19417 (save-match-data (newline))
19418 (org-indent-line-to (length (match-string 0))))
19419 (let ((ind (org-get-indentation)))
19420 (newline)
19421 (if (org-looking-back org-list-end-re)
19422 (org-indent-line)
19423 (org-indent-line-to ind)))))
19424 ((and org-return-follows-link
19425 (org-at-timestamp-p t)
19426 (not (eq org-ts-what 'after)))
19427 (org-follow-timestamp-link))
19428 ((and org-return-follows-link
19429 (let ((tprop (get-text-property (point) 'face)))
19430 (or (eq tprop 'org-link)
19431 (and (listp tprop) (memq 'org-link tprop)))))
19432 (call-interactively 'org-open-at-point))
19433 ((and (org-at-heading-p)
19434 (looking-at
19435 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19436 (org-show-entry)
19437 (end-of-line 1)
19438 (newline))
19439 (t (if indent (newline-and-indent) (newline))))))
19441 (defun org-return-indent ()
19442 "Goto next table row or insert a newline and indent.
19443 Calls `org-table-next-row' or `newline-and-indent', depending on
19444 context. See the individual commands for more information."
19445 (interactive)
19446 (org-return t))
19448 (defun org-ctrl-c-star ()
19449 "Compute table, or change heading status of lines.
19450 Calls `org-table-recalculate' or `org-toggle-heading',
19451 depending on context."
19452 (interactive)
19453 (cond
19454 ((org-at-table-p)
19455 (call-interactively 'org-table-recalculate))
19457 ;; Convert all lines in region to list items
19458 (call-interactively 'org-toggle-heading))))
19460 (defun org-ctrl-c-minus ()
19461 "Insert separator line in table or modify bullet status of line.
19462 Also turns a plain line or a region of lines into list items.
19463 Calls `org-table-insert-hline', `org-toggle-item', or
19464 `org-cycle-list-bullet', depending on context."
19465 (interactive)
19466 (cond
19467 ((org-at-table-p)
19468 (call-interactively 'org-table-insert-hline))
19469 ((org-region-active-p)
19470 (call-interactively 'org-toggle-item))
19471 ((org-in-item-p)
19472 (call-interactively 'org-cycle-list-bullet))
19474 (call-interactively 'org-toggle-item))))
19476 (defun org-toggle-item (arg)
19477 "Convert headings or normal lines to items, items to normal lines.
19478 If there is no active region, only the current line is considered.
19480 If the first non blank line in the region is an headline, convert
19481 all headlines to items, shifting text accordingly.
19483 If it is an item, convert all items to normal lines.
19485 If it is normal text, change region into an item. With a prefix
19486 argument ARG, change each line in region into an item."
19487 (interactive "P")
19488 (let ((shift-text
19489 (function
19490 ;; Shift text in current section to IND, from point to END.
19491 ;; The function leaves point to END line.
19492 (lambda (ind end)
19493 (let ((min-i 1000) (end (copy-marker end)))
19494 ;; First determine the minimum indentation (MIN-I) of
19495 ;; the text.
19496 (save-excursion
19497 (catch 'exit
19498 (while (< (point) end)
19499 (let ((i (org-get-indentation)))
19500 (cond
19501 ;; Skip blank lines and inline tasks.
19502 ((looking-at "^[ \t]*$"))
19503 ((looking-at org-outline-regexp-bol))
19504 ;; We can't find less than 0 indentation.
19505 ((zerop i) (throw 'exit (setq min-i 0)))
19506 ((< i min-i) (setq min-i i))))
19507 (forward-line))))
19508 ;; Then indent each line so that a line indented to
19509 ;; MIN-I becomes indented to IND. Ignore blank lines
19510 ;; and inline tasks in the process.
19511 (let ((delta (- ind min-i)))
19512 (while (< (point) end)
19513 (unless (or (looking-at "^[ \t]*$")
19514 (looking-at org-outline-regexp-bol))
19515 (org-indent-line-to (+ (org-get-indentation) delta)))
19516 (forward-line)))))))
19517 (skip-blanks
19518 (function
19519 ;; Return beginning of first non-blank line, starting from
19520 ;; line at POS.
19521 (lambda (pos)
19522 (save-excursion
19523 (goto-char pos)
19524 (skip-chars-forward " \r\t\n")
19525 (point-at-bol)))))
19526 beg end)
19527 ;; Determine boundaries of changes.
19528 (if (org-region-active-p)
19529 (setq beg (funcall skip-blanks (region-beginning))
19530 end (copy-marker (region-end)))
19531 (setq beg (funcall skip-blanks (point-at-bol))
19532 end (copy-marker (point-at-eol))))
19533 ;; Depending on the starting line, choose an action on the text
19534 ;; between BEG and END.
19535 (org-with-limited-levels
19536 (save-excursion
19537 (goto-char beg)
19538 (cond
19539 ;; Case 1. Start at an item: de-itemize. Note that it only
19540 ;; happens when a region is active: `org-ctrl-c-minus'
19541 ;; would call `org-cycle-list-bullet' otherwise.
19542 ((org-at-item-p)
19543 (while (< (point) end)
19544 (when (org-at-item-p)
19545 (skip-chars-forward " \t")
19546 (delete-region (point) (match-end 0)))
19547 (forward-line)))
19548 ;; Case 2. Start at an heading: convert to items.
19549 ((org-at-heading-p)
19550 (let* ((bul (org-list-bullet-string "-"))
19551 (bul-len (length bul))
19552 ;; Indentation of the first heading. It should be
19553 ;; relative to the indentation of its parent, if any.
19554 (start-ind (save-excursion
19555 (cond
19556 ((not org-adapt-indentation) 0)
19557 ((not (outline-previous-heading)) 0)
19558 (t (length (match-string 0))))))
19559 ;; Level of first heading. Further headings will be
19560 ;; compared to it to determine hierarchy in the list.
19561 (ref-level (org-reduced-level (org-outline-level))))
19562 (while (< (point) end)
19563 (let* ((level (org-reduced-level (org-outline-level)))
19564 (delta (max 0 (- level ref-level))))
19565 ;; If current headline is less indented than the first
19566 ;; one, set it as reference, in order to preserve
19567 ;; subtrees.
19568 (when (< level ref-level) (setq ref-level level))
19569 (replace-match bul t t)
19570 (org-indent-line-to (+ start-ind (* delta bul-len)))
19571 ;; Ensure all text down to END (or SECTION-END) belongs
19572 ;; to the newly created item.
19573 (let ((section-end (save-excursion
19574 (or (outline-next-heading) (point)))))
19575 (forward-line)
19576 (funcall shift-text
19577 (+ start-ind (* (1+ delta) bul-len))
19578 (min end section-end)))))))
19579 ;; Case 3. Normal line with ARG: turn each non-item line into
19580 ;; an item.
19581 (arg
19582 (while (< (point) end)
19583 (unless (or (org-at-heading-p) (org-at-item-p))
19584 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19585 (replace-match
19586 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19587 (forward-line)))
19588 ;; Case 4. Normal line without ARG: make the first line of
19589 ;; region an item, and shift indentation of others
19590 ;; lines to set them as item's body.
19591 (t (let* ((bul (org-list-bullet-string "-"))
19592 (bul-len (length bul))
19593 (ref-ind (org-get-indentation)))
19594 (skip-chars-forward " \t")
19595 (insert bul)
19596 (forward-line)
19597 (while (< (point) end)
19598 ;; Ensure that lines less indented than first one
19599 ;; still get included in item body.
19600 (funcall shift-text
19601 (+ ref-ind bul-len)
19602 (min end (save-excursion (or (outline-next-heading)
19603 (point)))))
19604 (forward-line)))))))))
19606 (defun org-toggle-heading (&optional nstars)
19607 "Convert headings to normal text, or items or text to headings.
19608 If there is no active region, only the current line is considered.
19610 With a \\[universal-argument] prefix, convert the whole list at
19611 point into heading.
19613 In a region:
19615 - If the first non blank line is an headline, remove the stars
19616 from all headlines in the region.
19618 - If it is a normal line turn each and every normal line (i.e. not an
19619 heading or an item) in the region into a heading.
19621 - If it is a plain list item, turn all plain list items into headings.
19623 When converting a line into a heading, the number of stars is chosen
19624 such that the lines become children of the current entry. However,
19625 when a prefix argument is given, its value determines the number of
19626 stars to add."
19627 (interactive "P")
19628 (let ((skip-blanks
19629 (function
19630 ;; Return beginning of first non-blank line, starting from
19631 ;; line at POS.
19632 (lambda (pos)
19633 (save-excursion
19634 (goto-char pos)
19635 (while (org-at-comment-p) (forward-line))
19636 (skip-chars-forward " \r\t\n")
19637 (point-at-bol)))))
19638 beg end toggled)
19639 ;; Determine boundaries of changes. If a universal prefix has
19640 ;; been given, put the list in a region. If region ends at a bol,
19641 ;; do not consider the last line to be in the region.
19643 (when (and current-prefix-arg (org-at-item-p))
19644 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19645 (org-mark-element))
19647 (if (org-region-active-p)
19648 (setq beg (funcall skip-blanks (region-beginning))
19649 end (copy-marker (save-excursion
19650 (goto-char (region-end))
19651 (if (bolp) (point) (point-at-eol)))))
19652 (setq beg (funcall skip-blanks (point-at-bol))
19653 end (copy-marker (point-at-eol))))
19654 ;; Ensure inline tasks don't count as headings.
19655 (org-with-limited-levels
19656 (save-excursion
19657 (goto-char beg)
19658 (cond
19659 ;; Case 1. Started at an heading: de-star headings.
19660 ((org-at-heading-p)
19661 (while (< (point) end)
19662 (when (org-at-heading-p t)
19663 (looking-at org-outline-regexp) (replace-match "")
19664 (setq toggled t))
19665 (forward-line)))
19666 ;; Case 2. Started at an item: change items into headlines.
19667 ;; One star will be added by `org-list-to-subtree'.
19668 ((org-at-item-p)
19669 (let* ((stars (make-string
19670 (if nstars
19671 ;; subtract the star that will be added again by
19672 ;; `org-list-to-subtree'
19673 (1- (prefix-numeric-value current-prefix-arg))
19674 (or (org-current-level) 0))
19675 ?*))
19676 (add-stars
19677 (cond (nstars "") ; stars from prefix only
19678 ((equal stars "") "") ; before first heading
19679 (org-odd-levels-only "*") ; inside heading, odd
19680 (t "")))) ; inside heading, oddeven
19681 (while (< (point) end)
19682 (when (org-at-item-p)
19683 ;; Pay attention to cases when region ends before list.
19684 (let* ((struct (org-list-struct))
19685 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19686 (save-restriction
19687 (narrow-to-region (point) list-end)
19688 (insert
19689 (org-list-to-subtree
19690 (org-list-parse-list t)
19691 '(:istart (concat stars add-stars (funcall get-stars depth))
19692 :icount (concat stars add-stars (funcall get-stars depth)))))))
19693 (setq toggled t))
19694 (forward-line))))
19695 ;; Case 3. Started at normal text: make every line an heading,
19696 ;; skipping headlines and items.
19697 (t (let* ((stars (make-string
19698 (if nstars
19699 (prefix-numeric-value current-prefix-arg)
19700 (or (org-current-level) 0))
19701 ?*))
19702 (add-stars
19703 (cond (nstars "") ; stars from prefix only
19704 ((equal stars "") "*") ; before first heading
19705 (org-odd-levels-only "**") ; inside heading, odd
19706 (t "*"))) ; inside heading, oddeven
19707 (rpl (concat stars add-stars " ")))
19708 (while (< (point) end)
19709 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19710 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19711 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19712 (forward-line)))))))
19713 (unless toggled (message "Cannot toggle heading from here"))))
19715 (defun org-meta-return (&optional arg)
19716 "Insert a new heading or wrap a region in a table.
19717 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19718 See the individual commands for more information."
19719 (interactive "P")
19720 (cond
19721 ((run-hook-with-args-until-success 'org-metareturn-hook))
19722 ((or (org-at-drawer-p) (org-at-property-p))
19723 (newline-and-indent))
19724 ((org-at-table-p)
19725 (call-interactively 'org-table-wrap-region))
19726 (t (call-interactively 'org-insert-heading))))
19728 ;;; Menu entries
19730 ;; Define the Org-mode menus
19731 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19732 '("Tbl"
19733 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19734 ["Next Field" org-cycle (org-at-table-p)]
19735 ["Previous Field" org-shifttab (org-at-table-p)]
19736 ["Next Row" org-return (org-at-table-p)]
19737 "--"
19738 ["Blank Field" org-table-blank-field (org-at-table-p)]
19739 ["Edit Field" org-table-edit-field (org-at-table-p)]
19740 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19741 "--"
19742 ("Column"
19743 ["Move Column Left" org-metaleft (org-at-table-p)]
19744 ["Move Column Right" org-metaright (org-at-table-p)]
19745 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19746 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19747 ("Row"
19748 ["Move Row Up" org-metaup (org-at-table-p)]
19749 ["Move Row Down" org-metadown (org-at-table-p)]
19750 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19751 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19752 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19753 "--"
19754 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19755 ("Rectangle"
19756 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19757 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19758 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19759 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19760 "--"
19761 ("Calculate"
19762 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19763 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19764 ["Edit Formulas" org-edit-special (org-at-table-p)]
19765 "--"
19766 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19767 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19768 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19769 "--"
19770 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19771 "--"
19772 ["Sum Column/Rectangle" org-table-sum
19773 (or (org-at-table-p) (org-region-active-p))]
19774 ["Which Column?" org-table-current-column (org-at-table-p)])
19775 ["Debug Formulas"
19776 org-table-toggle-formula-debugger
19777 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19778 ["Show Col/Row Numbers"
19779 org-table-toggle-coordinate-overlays
19780 :style toggle
19781 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19782 "--"
19783 ["Create" org-table-create (and (not (org-at-table-p))
19784 org-enable-table-editor)]
19785 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19786 ["Import from File" org-table-import (not (org-at-table-p))]
19787 ["Export to File" org-table-export (org-at-table-p)]
19788 "--"
19789 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19791 (easy-menu-define org-org-menu org-mode-map "Org menu"
19792 '("Org"
19793 ("Show/Hide"
19794 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19795 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19796 ["Sparse Tree..." org-sparse-tree t]
19797 ["Reveal Context" org-reveal t]
19798 ["Show All" show-all t]
19799 "--"
19800 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19801 "--"
19802 ["New Heading" org-insert-heading t]
19803 ("Navigate Headings"
19804 ["Up" outline-up-heading t]
19805 ["Next" outline-next-visible-heading t]
19806 ["Previous" outline-previous-visible-heading t]
19807 ["Next Same Level" outline-forward-same-level t]
19808 ["Previous Same Level" outline-backward-same-level t]
19809 "--"
19810 ["Jump" org-goto t])
19811 ("Edit Structure"
19812 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19813 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19814 "--"
19815 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19816 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19817 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19818 "--"
19819 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19820 "--"
19821 ["Copy visible text" org-copy-visible t]
19822 "--"
19823 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19824 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19825 ["Demote Heading" org-metaright (not (org-at-table-p))]
19826 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19827 "--"
19828 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19829 "--"
19830 ["Convert to odd levels" org-convert-to-odd-levels t]
19831 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19832 ("Editing"
19833 ["Emphasis..." org-emphasize t]
19834 ["Edit Source Example" org-edit-special t]
19835 "--"
19836 ["Footnote new/jump" org-footnote-action t]
19837 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19838 ("Archive"
19839 ["Archive (default method)" org-archive-subtree-default t]
19840 "--"
19841 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19842 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19843 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19845 "--"
19846 ("Hyperlinks"
19847 ["Store Link (Global)" org-store-link t]
19848 ["Find existing link to here" org-occur-link-in-agenda-files t]
19849 ["Insert Link" org-insert-link t]
19850 ["Follow Link" org-open-at-point t]
19851 "--"
19852 ["Next link" org-next-link t]
19853 ["Previous link" org-previous-link t]
19854 "--"
19855 ["Descriptive Links"
19856 org-toggle-link-display
19857 :style radio
19858 :selected org-descriptive-links
19860 ["Literal Links"
19861 org-toggle-link-display
19862 :style radio
19863 :selected (not org-descriptive-links)])
19864 "--"
19865 ("TODO Lists"
19866 ["TODO/DONE/-" org-todo t]
19867 ("Select keyword"
19868 ["Next keyword" org-shiftright (org-at-heading-p)]
19869 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19870 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19871 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19872 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19873 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19874 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19875 "--"
19876 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19877 :selected org-enforce-todo-dependencies :style toggle :active t]
19878 "Settings for tree at point"
19879 ["Do Children sequentially" org-toggle-ordered-property :style radio
19880 :selected (org-entry-get nil "ORDERED")
19881 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19882 ["Do Children parallel" org-toggle-ordered-property :style radio
19883 :selected (not (org-entry-get nil "ORDERED"))
19884 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19885 "--"
19886 ["Set Priority" org-priority t]
19887 ["Priority Up" org-shiftup t]
19888 ["Priority Down" org-shiftdown t]
19889 "--"
19890 ["Get news from all feeds" org-feed-update-all t]
19891 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19892 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19893 ("TAGS and Properties"
19894 ["Set Tags" org-set-tags-command t]
19895 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19896 "--"
19897 ["Set property" org-set-property t]
19898 ["Column view of properties" org-columns t]
19899 ["Insert Column View DBlock" org-insert-columns-dblock t])
19900 ("Dates and Scheduling"
19901 ["Timestamp" org-time-stamp t]
19902 ["Timestamp (inactive)" org-time-stamp-inactive t]
19903 ("Change Date"
19904 ["1 Day Later" org-shiftright t]
19905 ["1 Day Earlier" org-shiftleft t]
19906 ["1 ... Later" org-shiftup t]
19907 ["1 ... Earlier" org-shiftdown t])
19908 ["Compute Time Range" org-evaluate-time-range t]
19909 ["Schedule Item" org-schedule t]
19910 ["Deadline" org-deadline t]
19911 "--"
19912 ["Custom time format" org-toggle-time-stamp-overlays
19913 :style radio :selected org-display-custom-times]
19914 "--"
19915 ["Goto Calendar" org-goto-calendar t]
19916 ["Date from Calendar" org-date-from-calendar t]
19917 "--"
19918 ["Start/Restart Timer" org-timer-start t]
19919 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19920 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19921 ["Insert Timer String" org-timer t]
19922 ["Insert Timer Item" org-timer-item t])
19923 ("Logging work"
19924 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19925 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19926 ["Clock out" org-clock-out t]
19927 ["Clock cancel" org-clock-cancel t]
19928 "--"
19929 ["Mark as default task" org-clock-mark-default-task t]
19930 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19931 ["Goto running clock" org-clock-goto t]
19932 "--"
19933 ["Display times" org-clock-display t]
19934 ["Create clock table" org-clock-report t]
19935 "--"
19936 ["Record DONE time"
19937 (progn (setq org-log-done (not org-log-done))
19938 (message "Switching to %s will %s record a timestamp"
19939 (car org-done-keywords)
19940 (if org-log-done "automatically" "not")))
19941 :style toggle :selected org-log-done])
19942 "--"
19943 ["Agenda Command..." org-agenda t]
19944 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19945 ("File List for Agenda")
19946 ("Special views current file"
19947 ["TODO Tree" org-show-todo-tree t]
19948 ["Check Deadlines" org-check-deadlines t]
19949 ["Timeline" org-timeline t]
19950 ["Tags/Property tree" org-match-sparse-tree t])
19951 "--"
19952 ["Export/Publish..." org-export t]
19953 ("LaTeX"
19954 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19955 :selected org-cdlatex-mode]
19956 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19957 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19958 ["Modify math symbol" org-cdlatex-math-modify
19959 (org-inside-LaTeX-fragment-p)]
19960 ["Insert citation" org-reftex-citation t]
19961 "--"
19962 ["Template for BEAMER" (progn (require 'org-beamer)
19963 (org-insert-beamer-options-template)) t])
19964 "--"
19965 ("MobileOrg"
19966 ["Push Files and Views" org-mobile-push t]
19967 ["Get Captured and Flagged" org-mobile-pull t]
19968 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19969 "--"
19970 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19971 "--"
19972 ("Documentation"
19973 ["Show Version" org-version t]
19974 ["Info Documentation" org-info t])
19975 ("Customize"
19976 ["Browse Org Group" org-customize t]
19977 "--"
19978 ["Expand This Menu" org-create-customize-menu
19979 (fboundp 'customize-menu-create)])
19980 ["Send bug report" org-submit-bug-report t]
19981 "--"
19982 ("Refresh/Reload"
19983 ["Refresh setup current buffer" org-mode-restart t]
19984 ["Reload Org (after update)" org-reload t]
19985 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19988 (defun org-info (&optional node)
19989 "Read documentation for Org-mode in the info system.
19990 With optional NODE, go directly to that node."
19991 (interactive)
19992 (info (format "(org)%s" (or node ""))))
19994 ;;;###autoload
19995 (defun org-submit-bug-report ()
19996 "Submit a bug report on Org-mode via mail.
19998 Don't hesitate to report any problems or inaccurate documentation.
20000 If you don't have setup sending mail from (X)Emacs, please copy the
20001 output buffer into your mail program, as it gives us important
20002 information about your Org-mode version and configuration."
20003 (interactive)
20004 (require 'reporter)
20005 (org-load-modules-maybe)
20006 (org-require-autoloaded-modules)
20007 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20008 (reporter-submit-bug-report
20009 "emacs-orgmode@gnu.org"
20010 (org-version nil 'full)
20011 (let (list)
20012 (save-window-excursion
20013 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20014 (delete-other-windows)
20015 (erase-buffer)
20016 (insert "You are about to submit a bug report to the Org-mode mailing list.
20018 We would like to add your full Org-mode and Outline configuration to the
20019 bug report. This greatly simplifies the work of the maintainer and
20020 other experts on the mailing list.
20022 HOWEVER, some variables you have customized may contain private
20023 information. The names of customers, colleagues, or friends, might
20024 appear in the form of file names, tags, todo states, or search strings.
20025 If you answer yes to the prompt, you might want to check and remove
20026 such private information before sending the email.")
20027 (add-text-properties (point-min) (point-max) '(face org-warning))
20028 (when (yes-or-no-p "Include your Org-mode configuration ")
20029 (mapatoms
20030 (lambda (v)
20031 (and (boundp v)
20032 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20033 (or (and (symbol-value v)
20034 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20035 (and
20036 (get v 'custom-type) (get v 'standard-value)
20037 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20038 (push v list)))))
20039 (kill-buffer (get-buffer "*Warn about privacy*"))
20040 list))
20041 nil nil
20042 "Remember to cover the basics, that is, what you expected to happen and
20043 what in fact did happen. You don't know how to make a good report? See
20045 http://orgmode.org/manual/Feedback.html#Feedback
20047 Your bug report will be posted to the Org-mode mailing list.
20048 ------------------------------------------------------------------------")
20049 (save-excursion
20050 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20051 (replace-match "\\1Bug: \\3 [\\2]")))))
20054 (defun org-install-agenda-files-menu ()
20055 (let ((bl (buffer-list)))
20056 (save-excursion
20057 (while bl
20058 (set-buffer (pop bl))
20059 (if (derived-mode-p 'org-mode) (setq bl nil)))
20060 (when (derived-mode-p 'org-mode)
20061 (easy-menu-change
20062 '("Org") "File List for Agenda"
20063 (append
20064 (list
20065 ["Edit File List" (org-edit-agenda-file-list) t]
20066 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20067 ["Remove Current File from List" org-remove-file t]
20068 ["Cycle through agenda files" org-cycle-agenda-files t]
20069 ["Occur in all agenda files" org-occur-in-agenda-files t]
20070 "--")
20071 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20073 ;;;; Documentation
20075 ;;;###autoload
20076 (defun org-require-autoloaded-modules ()
20077 (interactive)
20078 (mapc 'require
20079 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20080 org-docbook org-exp org-html org-icalendar
20081 org-id org-latex
20082 org-publish org-remember org-table
20083 org-timer org-xoxo)))
20085 ;;;###autoload
20086 (defun org-reload (&optional uncompiled)
20087 "Reload all org lisp files.
20088 With prefix arg UNCOMPILED, load the uncompiled versions."
20089 (interactive "P")
20090 (require 'find-func)
20091 (let* ((file-re "^org\\(-.*\\)?\\.el")
20092 (dir-org (file-name-directory (org-find-library-dir "org")))
20093 (dir-org-contrib (ignore-errors
20094 (file-name-directory
20095 (org-find-library-dir "org-contribdir"))))
20096 (babel-files
20097 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
20098 (append (list nil "comint" "eval" "exp" "keys"
20099 "lob" "ref" "table" "tangle")
20100 (delq nil
20101 (mapcar
20102 (lambda (lang)
20103 (when (cdr lang) (symbol-name (car lang))))
20104 org-babel-load-languages)))))
20105 (files
20106 (append babel-files
20107 (and dir-org-contrib
20108 (directory-files dir-org-contrib t file-re))
20109 (directory-files dir-org t file-re)))
20110 (remove-re (concat (if (featurep 'xemacs)
20111 "org-colview" "org-colview-xemacs")
20112 "\\'")))
20113 (setq files (mapcar 'file-name-sans-extension files))
20114 (setq files (mapcar
20115 (lambda (x) (if (string-match remove-re x) nil x))
20116 files))
20117 (setq files (delq nil files))
20118 (mapc
20119 (lambda (f)
20120 (when (featurep (intern (file-name-nondirectory f)))
20121 (if (and (not uncompiled)
20122 (file-exists-p (concat f ".elc")))
20123 (load (concat f ".elc") nil nil 'nosuffix)
20124 (load (concat f ".el") nil nil 'nosuffix))))
20125 files)
20126 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20127 (org-version nil 'full 'message))
20129 ;;;###autoload
20130 (defun org-customize ()
20131 "Call the customize function with org as argument."
20132 (interactive)
20133 (org-load-modules-maybe)
20134 (org-require-autoloaded-modules)
20135 (customize-browse 'org))
20137 (defun org-create-customize-menu ()
20138 "Create a full customization menu for Org-mode, insert it into the menu."
20139 (interactive)
20140 (org-load-modules-maybe)
20141 (org-require-autoloaded-modules)
20142 (if (fboundp 'customize-menu-create)
20143 (progn
20144 (easy-menu-change
20145 '("Org") "Customize"
20146 `(["Browse Org group" org-customize t]
20147 "--"
20148 ,(customize-menu-create 'org)
20149 ["Set" Custom-set t]
20150 ["Save" Custom-save t]
20151 ["Reset to Current" Custom-reset-current t]
20152 ["Reset to Saved" Custom-reset-saved t]
20153 ["Reset to Standard Settings" Custom-reset-standard t]))
20154 (message "\"Org\"-menu now contains full customization menu"))
20155 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20157 ;;;; Miscellaneous stuff
20159 ;;; Generally useful functions
20161 (defun org-get-at-bol (property)
20162 "Get text property PROPERTY at beginning of line."
20163 (get-text-property (point-at-bol) property))
20165 (defun org-find-text-property-in-string (prop s)
20166 "Return the first non-nil value of property PROP in string S."
20167 (or (get-text-property 0 prop s)
20168 (get-text-property (or (next-single-property-change 0 prop s) 0)
20169 prop s)))
20171 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20172 "Display the given MESSAGE as a warning."
20173 (if (fboundp 'display-warning)
20174 (display-warning 'org message
20175 (if (featurep 'xemacs) 'warning :warning))
20176 (let ((buf (get-buffer-create "*Org warnings*")))
20177 (with-current-buffer buf
20178 (goto-char (point-max))
20179 (insert "Warning (Org): " message)
20180 (unless (bolp)
20181 (newline)))
20182 (display-buffer buf)
20183 (sit-for 0))))
20185 (defun org-eval (form)
20186 "Eval FORM and return result."
20187 (condition-case error
20188 (eval form)
20189 (error (format "%%![Error: %s]" error))))
20191 (defun org-in-clocktable-p ()
20192 "Check if the cursor is in a clocktable."
20193 (let ((pos (point)) start)
20194 (save-excursion
20195 (end-of-line 1)
20196 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20197 (setq start (match-beginning 0))
20198 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20199 (>= (match-end 0) pos)
20200 start))))
20202 (defun org-in-commented-line ()
20203 "Is point in a line starting with `#'?"
20204 (equal (char-after (point-at-bol)) ?#))
20206 (defun org-in-indented-comment-line ()
20207 "Is point in a line starting with `#' after some white space?"
20208 (save-excursion
20209 (save-match-data
20210 (goto-char (point-at-bol))
20211 (looking-at "[ \t]*#"))))
20213 (defun org-in-verbatim-emphasis ()
20214 (save-match-data
20215 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20217 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20218 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20219 (if (and marker (marker-buffer marker)
20220 (buffer-live-p (marker-buffer marker)))
20221 (progn
20222 (org-pop-to-buffer-same-window (marker-buffer marker))
20223 (if (or (> marker (point-max)) (< marker (point-min)))
20224 (widen))
20225 (goto-char marker)
20226 (org-show-context 'org-goto))
20227 (if bookmark
20228 (bookmark-jump bookmark)
20229 (error "Cannot find location"))))
20231 (defun org-quote-csv-field (s)
20232 "Quote field for inclusion in CSV material."
20233 (if (string-match "[\",]" s)
20234 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20237 (defun org-force-self-insert (N)
20238 "Needed to enforce self-insert under remapping."
20239 (interactive "p")
20240 (self-insert-command N))
20242 (defun org-string-width (s)
20243 "Compute width of string, ignoring invisible characters.
20244 This ignores character with invisibility property `org-link', and also
20245 characters with property `org-cwidth', because these will become invisible
20246 upon the next fontification round."
20247 (let (b l)
20248 (when (or (eq t buffer-invisibility-spec)
20249 (assq 'org-link buffer-invisibility-spec))
20250 (while (setq b (text-property-any 0 (length s)
20251 'invisible 'org-link s))
20252 (setq s (concat (substring s 0 b)
20253 (substring s (or (next-single-property-change
20254 b 'invisible s) (length s)))))))
20255 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20256 (setq s (concat (substring s 0 b)
20257 (substring s (or (next-single-property-change
20258 b 'org-cwidth s) (length s))))))
20259 (setq l (string-width s) b -1)
20260 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20261 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20264 (defun org-shorten-string (s maxlength)
20265 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20266 If the string is shorter or has length MAXLENGTH, just return the
20267 original string. If it is longer, the functions finds a space in the
20268 string, breaks this string off at that locations and adds three dots
20269 as ellipsis. Including the ellipsis, the string will not be longer
20270 than MAXLENGTH. If finding a good breaking point in the string does
20271 not work, the string is just chopped off in the middle of a word
20272 if necessary."
20273 (if (<= (length s) maxlength)
20275 (let* ((n (max (- maxlength 4) 1))
20276 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20277 (if (string-match re s)
20278 (concat (match-string 1 s) "...")
20279 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20281 (defun org-get-indentation (&optional line)
20282 "Get the indentation of the current line, interpreting tabs.
20283 When LINE is given, assume it represents a line and compute its indentation."
20284 (if line
20285 (if (string-match "^ *" (org-remove-tabs line))
20286 (match-end 0))
20287 (save-excursion
20288 (beginning-of-line 1)
20289 (skip-chars-forward " \t")
20290 (current-column))))
20292 (defun org-get-string-indentation (s)
20293 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20294 (let ((n -1) (i 0) (w tab-width) c)
20295 (catch 'exit
20296 (while (< (setq n (1+ n)) (length s))
20297 (setq c (aref s n))
20298 (cond ((= c ?\ ) (setq i (1+ i)))
20299 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20300 (t (throw 'exit t)))))
20303 (defun org-remove-tabs (s &optional width)
20304 "Replace tabulators in S with spaces.
20305 Assumes that s is a single line, starting in column 0."
20306 (setq width (or width tab-width))
20307 (while (string-match "\t" s)
20308 (setq s (replace-match
20309 (make-string
20310 (- (* width (/ (+ (match-beginning 0) width) width))
20311 (match-beginning 0)) ?\ )
20312 t t s)))
20315 (defun org-fix-indentation (line ind)
20316 "Fix indentation in LINE.
20317 IND is a cons cell with target and minimum indentation.
20318 If the current indentation in LINE is smaller than the minimum,
20319 leave it alone. If it is larger than ind, set it to the target."
20320 (let* ((l (org-remove-tabs line))
20321 (i (org-get-indentation l))
20322 (i1 (car ind)) (i2 (cdr ind)))
20323 (if (>= i i2) (setq l (substring line i2)))
20324 (if (> i1 0)
20325 (concat (make-string i1 ?\ ) l)
20326 l)))
20328 (defun org-remove-indentation (code &optional n)
20329 "Remove the maximum common indentation from the lines in CODE.
20330 N may optionally be the number of spaces to remove."
20331 (with-temp-buffer
20332 (insert code)
20333 (org-do-remove-indentation n)
20334 (buffer-string)))
20336 (defun org-do-remove-indentation (&optional n)
20337 "Remove the maximum common indentation from the buffer."
20338 (untabify (point-min) (point-max))
20339 (let ((min 10000) re)
20340 (if n
20341 (setq min n)
20342 (goto-char (point-min))
20343 (while (re-search-forward "^ *[^ \n]" nil t)
20344 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20345 (unless (or (= min 0) (= min 10000))
20346 (setq re (format "^ \\{%d\\}" min))
20347 (goto-char (point-min))
20348 (while (re-search-forward re nil t)
20349 (replace-match "")
20350 (end-of-line 1))
20351 min)))
20353 (defun org-fill-template (template alist)
20354 "Find each %key of ALIST in TEMPLATE and replace it."
20355 (let ((case-fold-search nil)
20356 entry key value)
20357 (setq alist (sort (copy-sequence alist)
20358 (lambda (a b) (< (length (car a)) (length (car b))))))
20359 (while (setq entry (pop alist))
20360 (setq template
20361 (replace-regexp-in-string
20362 (concat "%" (regexp-quote (car entry)))
20363 (or (cdr entry) "") template t t)))
20364 template))
20366 (defun org-base-buffer (buffer)
20367 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20368 (if (not buffer)
20369 buffer
20370 (or (buffer-base-buffer buffer)
20371 buffer)))
20373 (defun org-trim (s)
20374 "Remove whitespace at beginning and end of string."
20375 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20376 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20379 (defun org-wrap (string &optional width lines)
20380 "Wrap string to either a number of lines, or a width in characters.
20381 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20382 that costs. If there is a word longer than WIDTH, the text is actually
20383 wrapped to the length of that word.
20384 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20385 many lines, whatever width that takes.
20386 The return value is a list of lines, without newlines at the end."
20387 (let* ((words (org-split-string string "[ \t\n]+"))
20388 (maxword (apply 'max (mapcar 'org-string-width words)))
20389 w ll)
20390 (cond (width
20391 (org-do-wrap words (max maxword width)))
20392 (lines
20393 (setq w maxword)
20394 (setq ll (org-do-wrap words maxword))
20395 (if (<= (length ll) lines)
20397 (setq ll words)
20398 (while (> (length ll) lines)
20399 (setq w (1+ w))
20400 (setq ll (org-do-wrap words w)))
20401 ll))
20402 (t (error "Cannot wrap this")))))
20404 (defun org-do-wrap (words width)
20405 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20406 (let (lines line)
20407 (while words
20408 (setq line (pop words))
20409 (while (and words (< (+ (length line) (length (car words))) width))
20410 (setq line (concat line " " (pop words))))
20411 (setq lines (push line lines)))
20412 (nreverse lines)))
20414 (defun org-split-string (string &optional separators)
20415 "Splits STRING into substrings at SEPARATORS.
20416 No empty strings are returned if there are matches at the beginning
20417 and end of string."
20418 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20419 (start 0)
20420 notfirst
20421 (list nil))
20422 (while (and (string-match rexp string
20423 (if (and notfirst
20424 (= start (match-beginning 0))
20425 (< start (length string)))
20426 (1+ start) start))
20427 (< (match-beginning 0) (length string)))
20428 (setq notfirst t)
20429 (or (eq (match-beginning 0) 0)
20430 (and (eq (match-beginning 0) (match-end 0))
20431 (eq (match-beginning 0) start))
20432 (setq list
20433 (cons (substring string start (match-beginning 0))
20434 list)))
20435 (setq start (match-end 0)))
20436 (or (eq start (length string))
20437 (setq list
20438 (cons (substring string start)
20439 list)))
20440 (nreverse list)))
20442 (defun org-quote-vert (s)
20443 "Replace \"|\" with \"\\vert\"."
20444 (while (string-match "|" s)
20445 (setq s (replace-match "\\vert" t t s)))
20448 (defun org-uuidgen-p (s)
20449 "Is S an ID created by UUIDGEN?"
20450 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20452 (defun org-in-src-block-p nil
20453 "Whether point is in a code source block."
20454 (let (ov)
20455 (when (setq ov (overlays-at (point)))
20456 (memq 'org-block-background
20457 (overlay-properties
20458 (car ov))))))
20460 (defun org-context ()
20461 "Return a list of contexts of the current cursor position.
20462 If several contexts apply, all are returned.
20463 Each context entry is a list with a symbol naming the context, and
20464 two positions indicating start and end of the context. Possible
20465 contexts are:
20467 :headline anywhere in a headline
20468 :headline-stars on the leading stars in a headline
20469 :todo-keyword on a TODO keyword (including DONE) in a headline
20470 :tags on the TAGS in a headline
20471 :priority on the priority cookie in a headline
20472 :item on the first line of a plain list item
20473 :item-bullet on the bullet/number of a plain list item
20474 :checkbox on the checkbox in a plain list item
20475 :table in an org-mode table
20476 :table-special on a special filed in a table
20477 :table-table in a table.el table
20478 :clocktable in a clocktable
20479 :src-block in a source block
20480 :link on a hyperlink
20481 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20482 :target on a <<target>>
20483 :radio-target on a <<<radio-target>>>
20484 :latex-fragment on a LaTeX fragment
20485 :latex-preview on a LaTeX fragment with overlaid preview image
20487 This function expects the position to be visible because it uses font-lock
20488 faces as a help to recognize the following contexts: :table-special, :link,
20489 and :keyword."
20490 (let* ((f (get-text-property (point) 'face))
20491 (faces (if (listp f) f (list f)))
20492 (case-fold-search t)
20493 (p (point)) clist o)
20494 ;; First the large context
20495 (cond
20496 ((org-at-heading-p t)
20497 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20498 (when (progn
20499 (beginning-of-line 1)
20500 (looking-at org-todo-line-tags-regexp))
20501 (push (org-point-in-group p 1 :headline-stars) clist)
20502 (push (org-point-in-group p 2 :todo-keyword) clist)
20503 (push (org-point-in-group p 4 :tags) clist))
20504 (goto-char p)
20505 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20506 (if (looking-at "\\[#[A-Z0-9]\\]")
20507 (push (org-point-in-group p 0 :priority) clist)))
20509 ((org-at-item-p)
20510 (push (org-point-in-group p 2 :item-bullet) clist)
20511 (push (list :item (point-at-bol)
20512 (save-excursion (org-end-of-item) (point)))
20513 clist)
20514 (and (org-at-item-checkbox-p)
20515 (push (org-point-in-group p 0 :checkbox) clist)))
20517 ((org-at-table-p)
20518 (push (list :table (org-table-begin) (org-table-end)) clist)
20519 (if (memq 'org-formula faces)
20520 (push (list :table-special
20521 (previous-single-property-change p 'face)
20522 (next-single-property-change p 'face)) clist)))
20523 ((org-at-table-p 'any)
20524 (push (list :table-table) clist)))
20525 (goto-char p)
20527 (let ((case-fold-search t))
20528 ;; New the "medium" contexts: clocktables, source blocks
20529 (cond ((org-in-clocktable-p)
20530 (push (list :clocktable
20531 (and (or (looking-at "#\\+BEGIN: clocktable")
20532 (search-backward "#+BEGIN: clocktable" nil t))
20533 (match-beginning 0))
20534 (and (re-search-forward "#\\+END:?" nil t)
20535 (match-end 0))) clist))
20536 ((org-in-src-block-p)
20537 (push (list :src-block
20538 (and (or (looking-at "#\\+BEGIN_SRC")
20539 (search-backward "#+BEGIN_SRC" nil t))
20540 (match-beginning 0))
20541 (and (search-forward "#+END_SRC" nil t)
20542 (match-beginning 0))) clist))))
20543 (goto-char p)
20545 ;; Now the small context
20546 (cond
20547 ((org-at-timestamp-p)
20548 (push (org-point-in-group p 0 :timestamp) clist))
20549 ((memq 'org-link faces)
20550 (push (list :link
20551 (previous-single-property-change p 'face)
20552 (next-single-property-change p 'face)) clist))
20553 ((memq 'org-special-keyword faces)
20554 (push (list :keyword
20555 (previous-single-property-change p 'face)
20556 (next-single-property-change p 'face)) clist))
20557 ((org-at-target-p)
20558 (push (org-point-in-group p 0 :target) clist)
20559 (goto-char (1- (match-beginning 0)))
20560 (if (looking-at org-radio-target-regexp)
20561 (push (org-point-in-group p 0 :radio-target) clist))
20562 (goto-char p))
20563 ((setq o (car (delq nil
20564 (mapcar
20565 (lambda (x)
20566 (if (memq x org-latex-fragment-image-overlays) x))
20567 (overlays-at (point))))))
20568 (push (list :latex-fragment
20569 (overlay-start o) (overlay-end o)) clist)
20570 (push (list :latex-preview
20571 (overlay-start o) (overlay-end o)) clist))
20572 ((org-inside-LaTeX-fragment-p)
20573 ;; FIXME: positions wrong.
20574 (push (list :latex-fragment (point) (point)) clist)))
20576 (setq clist (nreverse (delq nil clist)))
20577 clist))
20579 ;; FIXME: Compare with at-regexp-p Do we need both?
20580 (defun org-in-regexp (re &optional nlines visually)
20581 "Check if point is inside a match of regexp.
20582 Normally only the current line is checked, but you can include NLINES extra
20583 lines both before and after point into the search.
20584 If VISUALLY is set, require that the cursor is not after the match but
20585 really on, so that the block visually is on the match."
20586 (catch 'exit
20587 (let ((pos (point))
20588 (eol (point-at-eol (+ 1 (or nlines 0))))
20589 (inc (if visually 1 0)))
20590 (save-excursion
20591 (beginning-of-line (- 1 (or nlines 0)))
20592 (while (re-search-forward re eol t)
20593 (if (and (<= (match-beginning 0) pos)
20594 (>= (+ inc (match-end 0)) pos))
20595 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20597 (defun org-at-regexp-p (regexp)
20598 "Is point inside a match of REGEXP in the current line?"
20599 (catch 'exit
20600 (save-excursion
20601 (let ((pos (point)) (end (point-at-eol)))
20602 (beginning-of-line 1)
20603 (while (re-search-forward regexp end t)
20604 (if (and (<= (match-beginning 0) pos)
20605 (>= (match-end 0) pos))
20606 (throw 'exit t)))
20607 nil))))
20609 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20610 "Non-nil when point is between matches of START-RE and END-RE.
20612 Also return a non-nil value when point is on one of the matches.
20614 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20615 buffer positions. Default values are the positions of headlines
20616 surrounding the point.
20618 The functions returns a cons cell whose car (resp. cdr) is the
20619 position before START-RE (resp. after END-RE)."
20620 (save-match-data
20621 (let ((pos (point))
20622 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20623 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20624 beg end)
20625 (save-excursion
20626 ;; Point is on a block when on START-RE or if START-RE can be
20627 ;; found before it...
20628 (and (or (org-at-regexp-p start-re)
20629 (re-search-backward start-re limit-up t))
20630 (setq beg (match-beginning 0))
20631 ;; ... and END-RE after it...
20632 (goto-char (match-end 0))
20633 (re-search-forward end-re limit-down t)
20634 (> (setq end (match-end 0)) pos)
20635 ;; ... without another START-RE in-between.
20636 (goto-char (match-beginning 0))
20637 (not (re-search-backward start-re (1+ beg) t))
20638 ;; Return value.
20639 (cons beg end))))))
20641 (defun org-in-block-p (names)
20642 "Non-nil when point belongs to a block whose name belongs to NAMES.
20644 NAMES is a list of strings containing names of blocks.
20646 Return first block name matched, or nil. Beware that in case of
20647 nested blocks, the returned name may not belong to the closest
20648 block from point."
20649 (save-match-data
20650 (catch 'exit
20651 (let ((case-fold-search t)
20652 (lim-up (save-excursion (outline-previous-heading)))
20653 (lim-down (save-excursion (outline-next-heading))))
20654 (mapc (lambda (name)
20655 (let ((n (regexp-quote name)))
20656 (when (org-between-regexps-p
20657 (concat "^[ \t]*#\\+begin_" n)
20658 (concat "^[ \t]*#\\+end_" n)
20659 lim-up lim-down)
20660 (throw 'exit n))))
20661 names))
20662 nil)))
20664 (defun org-occur-in-agenda-files (regexp &optional nlines)
20665 "Call `multi-occur' with buffers for all agenda files."
20666 (interactive "sOrg-files matching: \np")
20667 (let* ((files (org-agenda-files))
20668 (tnames (mapcar 'file-truename files))
20669 (extra org-agenda-text-search-extra-files)
20671 (when (eq (car extra) 'agenda-archives)
20672 (setq extra (cdr extra))
20673 (setq files (org-add-archive-files files)))
20674 (while (setq f (pop extra))
20675 (unless (member (file-truename f) tnames)
20676 (add-to-list 'files f 'append)
20677 (add-to-list 'tnames (file-truename f) 'append)))
20678 (multi-occur
20679 (mapcar (lambda (x)
20680 (with-current-buffer
20681 (or (get-file-buffer x) (find-file-noselect x))
20682 (widen)
20683 (current-buffer)))
20684 files)
20685 regexp)))
20687 (if (boundp 'occur-mode-find-occurrence-hook)
20688 ;; Emacs 23
20689 (add-hook 'occur-mode-find-occurrence-hook
20690 (lambda ()
20691 (when (derived-mode-p 'org-mode)
20692 (org-reveal))))
20693 ;; Emacs 22
20694 (defadvice occur-mode-goto-occurrence
20695 (after org-occur-reveal activate)
20696 (and (derived-mode-p 'org-mode) (org-reveal)))
20697 (defadvice occur-mode-goto-occurrence-other-window
20698 (after org-occur-reveal activate)
20699 (and (derived-mode-p 'org-mode) (org-reveal)))
20700 (defadvice occur-mode-display-occurrence
20701 (after org-occur-reveal activate)
20702 (when (derived-mode-p 'org-mode)
20703 (let ((pos (occur-mode-find-occurrence)))
20704 (with-current-buffer (marker-buffer pos)
20705 (save-excursion
20706 (goto-char pos)
20707 (org-reveal)))))))
20709 (defun org-occur-link-in-agenda-files ()
20710 "Create a link and search for it in the agendas.
20711 The link is not stored in `org-stored-links', it is just created
20712 for the search purpose."
20713 (interactive)
20714 (let ((link (condition-case nil
20715 (org-store-link nil)
20716 (error "Unable to create a link to here"))))
20717 (org-occur-in-agenda-files (regexp-quote link))))
20719 (defun org-uniquify (list)
20720 "Remove duplicate elements from LIST."
20721 (let (res)
20722 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20723 res))
20725 (defun org-delete-all (elts list)
20726 "Remove all elements in ELTS from LIST."
20727 (while elts
20728 (setq list (delete (pop elts) list)))
20729 list)
20731 (defun org-count (cl-item cl-seq)
20732 "Count the number of occurrences of ITEM in SEQ.
20733 Taken from `count' in cl-seq.el with all keyword arguments removed."
20734 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20735 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20736 (while (< cl-start cl-end)
20737 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20738 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20739 (setq cl-start (1+ cl-start)))
20740 cl-count))
20742 (defun org-remove-if (predicate seq)
20743 "Remove everything from SEQ that fulfills PREDICATE."
20744 (let (res e)
20745 (while seq
20746 (setq e (pop seq))
20747 (if (not (funcall predicate e)) (push e res)))
20748 (nreverse res)))
20750 (defun org-remove-if-not (predicate seq)
20751 "Remove everything from SEQ that does not fulfill PREDICATE."
20752 (let (res e)
20753 (while seq
20754 (setq e (pop seq))
20755 (if (funcall predicate e) (push e res)))
20756 (nreverse res)))
20758 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20759 "Reduce two-argument FUNCTION across SEQ.
20760 Taken from `reduce' in cl-seq.el with all keyword arguments but
20761 \":initial-value\" removed."
20762 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20763 (cadr (memq :initial-value cl-keys)))
20764 (cl-seq (pop cl-seq))
20765 (t (funcall cl-func)))))
20766 (while cl-seq
20767 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20768 cl-accum))
20770 (defun org-back-over-empty-lines ()
20771 "Move backwards over whitespace, to the beginning of the first empty line.
20772 Returns the number of empty lines passed."
20773 (let ((pos (point)))
20774 (if (cdr (assoc 'heading org-blank-before-new-entry))
20775 (skip-chars-backward " \t\n\r")
20776 (unless (eobp)
20777 (forward-line -1)))
20778 (beginning-of-line 2)
20779 (goto-char (min (point) pos))
20780 (count-lines (point) pos)))
20782 (defun org-skip-whitespace ()
20783 (skip-chars-forward " \t\n\r"))
20785 (defun org-point-in-group (point group &optional context)
20786 "Check if POINT is in match-group GROUP.
20787 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20788 match. If the match group does not exist or point is not inside it,
20789 return nil."
20790 (and (match-beginning group)
20791 (>= point (match-beginning group))
20792 (<= point (match-end group))
20793 (if context
20794 (list context (match-beginning group) (match-end group))
20795 t)))
20797 (defun org-switch-to-buffer-other-window (&rest args)
20798 "Switch to buffer in a second window on the current frame.
20799 In particular, do not allow pop-up frames.
20800 Returns the newly created buffer."
20801 (let (pop-up-frames special-display-buffer-names special-display-regexps
20802 special-display-function)
20803 (apply 'switch-to-buffer-other-window args)))
20805 (defun org-combine-plists (&rest plists)
20806 "Create a single property list from all plists in PLISTS.
20807 The process starts by copying the first list, and then setting properties
20808 from the other lists. Settings in the last list are the most significant
20809 ones and overrule settings in the other lists."
20810 (let ((rtn (copy-sequence (pop plists)))
20811 p v ls)
20812 (while plists
20813 (setq ls (pop plists))
20814 (while ls
20815 (setq p (pop ls) v (pop ls))
20816 (setq rtn (plist-put rtn p v))))
20817 rtn))
20819 (defun org-replace-escapes (string table)
20820 "Replace %-escapes in STRING with values in TABLE.
20821 TABLE is an association list with keys like \"%a\" and string values.
20822 The sequences in STRING may contain normal field width and padding information,
20823 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20824 so values can contain further %-escapes if they are define later in TABLE."
20825 (let ((tbl (copy-alist table))
20826 (case-fold-search nil)
20827 (pchg 0)
20828 e re rpl)
20829 (while (setq e (pop tbl))
20830 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20831 (when (and (cdr e) (string-match re (cdr e)))
20832 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20833 (safe "SREF"))
20834 (add-text-properties 0 3 (list 'sref sref) safe)
20835 (setcdr e (replace-match safe t t (cdr e)))))
20836 (while (string-match re string)
20837 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20838 (cdr e)))
20839 (setq string (replace-match rpl t t string))))
20840 (while (setq pchg (next-property-change pchg string))
20841 (let ((sref (get-text-property pchg 'sref string)))
20842 (when (and sref (string-match "SREF" string pchg))
20843 (setq string (replace-match sref t t string)))))
20844 string))
20846 (defun org-sublist (list start end)
20847 "Return a section of LIST, from START to END.
20848 Counting starts at 1."
20849 (let (rtn (c start))
20850 (setq list (nthcdr (1- start) list))
20851 (while (and list (<= c end))
20852 (push (pop list) rtn)
20853 (setq c (1+ c)))
20854 (nreverse rtn)))
20856 (defun org-find-base-buffer-visiting (file)
20857 "Like `find-buffer-visiting' but always return the base buffer and
20858 not an indirect buffer."
20859 (let ((buf (or (get-file-buffer file)
20860 (find-buffer-visiting file))))
20861 (if buf
20862 (or (buffer-base-buffer buf) buf)
20863 nil)))
20865 (defun org-image-file-name-regexp (&optional extensions)
20866 "Return regexp matching the file names of images.
20867 If EXTENSIONS is given, only match these."
20868 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20869 (image-file-name-regexp)
20870 (let ((image-file-name-extensions
20871 (or extensions
20872 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20873 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20874 (concat "\\."
20875 (regexp-opt (nconc (mapcar 'upcase
20876 image-file-name-extensions)
20877 image-file-name-extensions)
20879 "\\'"))))
20881 (defun org-file-image-p (file &optional extensions)
20882 "Return non-nil if FILE is an image."
20883 (save-match-data
20884 (string-match (org-image-file-name-regexp extensions) file)))
20886 (defun org-get-cursor-date ()
20887 "Return the date at cursor in as a time.
20888 This works in the calendar and in the agenda, anywhere else it just
20889 returns the current time."
20890 (let (date day defd)
20891 (cond
20892 ((eq major-mode 'calendar-mode)
20893 (setq date (calendar-cursor-to-date)
20894 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20895 ((eq major-mode 'org-agenda-mode)
20896 (setq day (get-text-property (point) 'day))
20897 (if day
20898 (setq date (calendar-gregorian-from-absolute day)
20899 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20900 (nth 2 date))))))
20901 (or defd (current-time))))
20903 (defvar org-agenda-action-marker (make-marker)
20904 "Marker pointing to the entry for the next agenda action.")
20906 (defun org-mark-entry-for-agenda-action ()
20907 "Mark the current entry as target of an agenda action.
20908 Agenda actions are actions executed from the agenda with the key `k',
20909 which make use of the date at the cursor."
20910 (interactive)
20911 (move-marker org-agenda-action-marker
20912 (save-excursion (org-back-to-heading t) (point))
20913 (current-buffer))
20914 (message
20915 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20917 (defun org-mark-subtree (&optional up)
20918 "Mark the current subtree.
20919 This puts point at the start of the current subtree, and mark at
20920 the end. If a numeric prefix UP is given, move up into the
20921 hierarchy of headlines by UP levels before marking the subtree."
20922 (interactive "P")
20923 (org-with-limited-levels
20924 (cond ((org-at-heading-p) (beginning-of-line))
20925 ((org-before-first-heading-p) (error "Not in a subtree"))
20926 (t (outline-previous-visible-heading 1))))
20927 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20928 (if (org-called-interactively-p 'any)
20929 (call-interactively 'org-mark-element)
20930 (org-mark-element)))
20933 ;;; Macros
20935 ;; Macros are expanded with `org-macro-replace-all', which relies
20936 ;; internally on `org-macro-expand'.
20938 ;; Templates for expansion are stored in the buffer-local variable
20939 ;; `org-macro-templates'. This variable is updated by
20940 ;; `org-macro-initialize-templates'.
20943 (defvar org-macro-templates nil
20944 "Alist containing all macro templates in current buffer.
20945 Associations are in the shape of (NAME . TEMPLATE) where NAME
20946 stands for macro's name and template for its replacement value,
20947 both as strings. This is an internal variable. Do not set it
20948 directly, use instead:
20950 #+MACRO: name template")
20951 (make-variable-buffer-local 'org-macro-templates)
20953 (defun org-macro-expand (macro)
20954 "Return expanded MACRO, as a string.
20955 MACRO is an object, obtained, for example, with
20956 `org-element-context'. Return nil if no template was found."
20957 (let ((template
20958 (cdr (assoc-string (org-element-property :key macro)
20959 org-macro-templates
20960 ;; Macro names are case-insensitive.
20961 t))))
20962 (when template
20963 (let ((value (replace-regexp-in-string
20964 "\\$[0-9]+"
20965 (lambda (arg)
20966 (or (nth (1- (string-to-number (substring arg 1)))
20967 (org-element-property :args macro))
20968 ;; No argument provided: remove
20969 ;; place-holder.
20970 ""))
20971 template)))
20972 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
20973 (when (string-match "\\`(eval\\>" value)
20974 (setq value (eval (read value))))
20975 ;; Return string.
20976 (format "%s" (or value ""))))))
20978 (defun org-macro-replace-all ()
20979 "Replace all macros in current buffer by their expansion."
20980 (save-excursion
20981 (goto-char (point-min))
20982 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
20983 (let ((object (org-element-context)))
20984 (when (eq (org-element-type object) 'macro)
20985 (let ((value (org-macro-expand object)))
20986 (when value
20987 (delete-region
20988 (org-element-property :begin object)
20989 ;; Preserve white spaces after the macro.
20990 (progn (goto-char (org-element-property :end object))
20991 (skip-chars-backward " \t")
20992 (point)))
20993 ;; Leave point before replacement in case of recursive
20994 ;; expansions.
20995 (save-excursion (insert value)))))))))
20997 (defun org-macro-initialize-templates ()
20998 "Collect macro templates defined in current buffer.
20999 Templates are stored in buffer-local variable
21000 `org-macro-templates'. In addition to buffer-defined macros, the
21001 function installs the following ones: \"property\", \"date\",
21002 \"time\". and, if appropriate, \"input-file\" and
21003 \"modification-time\"."
21004 (let ((case-fold-search t)
21005 (set-template
21006 (lambda (cell)
21007 ;; Add CELL to `org-macro-templates' if there's no
21008 ;; association matching its name already. Otherwise,
21009 ;; replace old association with the new one in that
21010 ;; variable.
21011 (let ((old-template (assoc (car cell) org-macro-templates)))
21012 (if old-template (setcdr old-template (cdr cell))
21013 (push cell org-macro-templates))))))
21014 ;; Install buffer-local macros.
21015 (org-with-wide-buffer
21016 (goto-char (point-min))
21017 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21018 (let ((element (org-element-at-point)))
21019 (when (eq (org-element-type element) 'keyword)
21020 (let ((value (org-element-property :value element)))
21021 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21022 (funcall set-template
21023 (cons (match-string 1 value)
21024 (or (match-string 2 value) "")))))))))
21025 ;; Install hard-coded macros.
21026 (mapc (lambda (cell) (funcall set-template cell))
21027 (list
21028 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21029 (cons "date" "(eval (format-time-string \"$1\"))")
21030 (cons "time" "(eval (format-time-string \"$1\"))")))
21031 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21032 (when (and visited-file (file-exists-p visited-file))
21033 (mapc (lambda (cell) (funcall set-template cell))
21034 (list
21035 (cons "input-file" (file-name-nondirectory visited-file))
21036 (cons "modification-time"
21037 (format "(eval (format-time-string \"$1\" '%s))"
21038 (prin1-to-string
21039 (nth 5 (file-attributes visited-file)))))))))))
21042 ;;; Indentation
21044 (defun org-indent-line ()
21045 "Indent line depending on context."
21046 (interactive)
21047 (let* ((pos (point))
21048 (itemp (org-at-item-p))
21049 (case-fold-search t)
21050 (org-drawer-regexp (or org-drawer-regexp "\000"))
21051 (inline-task-p (and (featurep 'org-inlinetask)
21052 (org-inlinetask-in-task-p)))
21053 (inline-re (and inline-task-p
21054 (org-inlinetask-outline-regexp)))
21055 column)
21056 (if (and orgstruct-is-++ (eq pos (point)))
21057 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21058 (indent-according-to-mode))
21059 (beginning-of-line 1)
21060 (cond
21061 ;; Headings
21062 ((looking-at org-outline-regexp) (setq column 0))
21063 ;; Included files
21064 ((looking-at "#\\+include:") (setq column 0))
21065 ;; Footnote definition
21066 ((looking-at org-footnote-definition-re) (setq column 0))
21067 ;; Literal examples
21068 ((looking-at "[ \t]*:\\( \\|$\\)")
21069 (setq column (org-get-indentation))) ; do nothing
21070 ;; Lists
21071 ((ignore-errors (goto-char (org-in-item-p)))
21072 (setq column (if itemp
21073 (org-get-indentation)
21074 (org-list-item-body-column (point))))
21075 (goto-char pos))
21076 ;; Drawers
21077 ((and (looking-at "[ \t]*:END:")
21078 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21079 (save-excursion
21080 (goto-char (1- (match-beginning 1)))
21081 (setq column (current-column))))
21082 ;; Special blocks
21083 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21084 (save-excursion
21085 (re-search-backward
21086 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21087 (setq column (org-get-indentation (match-string 0))))
21088 ((and (not (looking-at "[ \t]*#\\+begin_"))
21089 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21090 (save-excursion
21091 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21092 (setq column
21093 (cond ((equal (downcase (match-string 1)) "src")
21094 ;; src blocks: let `org-edit-src-exit' handle them
21095 (org-get-indentation))
21096 ((equal (downcase (match-string 1)) "example")
21097 (max (org-get-indentation)
21098 (org-get-indentation (match-string 0))))
21100 (org-get-indentation (match-string 0))))))
21101 ;; This line has nothing special, look at the previous relevant
21102 ;; line to compute indentation
21104 (beginning-of-line 0)
21105 (while (and (not (bobp))
21106 (not (looking-at org-drawer-regexp))
21107 ;; When point started in an inline task, do not move
21108 ;; above task starting line.
21109 (not (and inline-task-p (looking-at inline-re)))
21110 ;; Skip drawers, blocks, empty lines, verbatim,
21111 ;; comments, tables, footnotes definitions, lists,
21112 ;; inline tasks.
21113 (or (and (looking-at "[ \t]*:END:")
21114 (re-search-backward org-drawer-regexp nil t))
21115 (and (looking-at "[ \t]*#\\+end_")
21116 (re-search-backward "[ \t]*#\\+begin_"nil t))
21117 (looking-at "[ \t]*[\n:#|]")
21118 (looking-at org-footnote-definition-re)
21119 (and (ignore-errors (goto-char (org-in-item-p)))
21120 (goto-char
21121 (org-list-get-top-point (org-list-struct))))
21122 (and (not inline-task-p)
21123 (featurep 'org-inlinetask)
21124 (org-inlinetask-in-task-p)
21125 (or (org-inlinetask-goto-beginning) t))))
21126 (beginning-of-line 0))
21127 (cond
21128 ;; There was an heading above.
21129 ((looking-at "\\*+[ \t]+")
21130 (if (not org-adapt-indentation)
21131 (setq column 0)
21132 (goto-char (match-end 0))
21133 (setq column (current-column))))
21134 ;; A drawer had started and is unfinished
21135 ((looking-at org-drawer-regexp)
21136 (goto-char (1- (match-beginning 1)))
21137 (setq column (current-column)))
21138 ;; Else, nothing noticeable found: get indentation and go on.
21139 (t (setq column (org-get-indentation))))))
21140 ;; Now apply indentation and move cursor accordingly
21141 (goto-char pos)
21142 (if (<= (current-column) (current-indentation))
21143 (org-indent-line-to column)
21144 (save-excursion (org-indent-line-to column)))
21145 ;; Special polishing for properties, see `org-property-format'
21146 (setq column (current-column))
21147 (beginning-of-line 1)
21148 (if (looking-at
21149 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21150 (replace-match (concat (match-string 1)
21151 (format org-property-format
21152 (match-string 2) (match-string 3)))
21153 t t))
21154 (org-move-to-column column))))
21156 (defun org-indent-drawer ()
21157 "Indent the drawer at point."
21158 (interactive)
21159 (let ((p (point))
21160 (e (and (save-excursion (re-search-forward ":END:" nil t))
21161 (match-end 0)))
21162 (folded
21163 (save-excursion
21164 (end-of-line)
21165 (when (overlays-at (point))
21166 (member 'invisible (overlay-properties
21167 (car (overlays-at (point)))))))))
21168 (when folded (org-cycle))
21169 (indent-for-tab-command)
21170 (while (and (move-beginning-of-line 2) (< (point) e))
21171 (indent-for-tab-command))
21172 (goto-char p)
21173 (when folded (org-cycle)))
21174 (message "Drawer at point indented"))
21176 (defun org-indent-block ()
21177 "Indent the block at point."
21178 (interactive)
21179 (let ((p (point))
21180 (case-fold-search t)
21181 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21182 (match-end 0)))
21183 (folded
21184 (save-excursion
21185 (end-of-line)
21186 (when (overlays-at (point))
21187 (member 'invisible (overlay-properties
21188 (car (overlays-at (point)))))))))
21189 (when folded (org-cycle))
21190 (indent-for-tab-command)
21191 (while (and (move-beginning-of-line 2) (< (point) e))
21192 (indent-for-tab-command))
21193 (goto-char p)
21194 (when folded (org-cycle)))
21195 (message "Block at point indented"))
21197 (defun org-indent-region (start end)
21198 "Indent region."
21199 (interactive "r")
21200 (save-excursion
21201 (let ((line-end (org-current-line end)))
21202 (goto-char start)
21203 (while (< (org-current-line) line-end)
21204 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21205 (t (call-interactively 'org-indent-line)))
21206 (move-beginning-of-line 2)))))
21209 ;;; Filling
21211 ;; We use our own fill-paragraph and auto-fill functions.
21213 ;; `org-fill-paragraph' relies on adaptive filling and context
21214 ;; checking. Appropriate `fill-prefix' is computed with
21215 ;; `org-adaptive-fill-function'.
21217 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21218 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21219 ;; `org-adaptive-fill-function' value. Internally,
21220 ;; `org-comment-line-break-function' breaks the line.
21222 ;; `org-setup-filling' installs filling and auto-filling related
21223 ;; variables during `org-mode' initialization.
21225 (defun org-setup-filling ()
21226 (interactive)
21227 ;; Prevent auto-fill from inserting unwanted new items.
21228 (when (boundp 'fill-nobreak-predicate)
21229 (org-set-local
21230 'fill-nobreak-predicate
21231 (org-uniquify
21232 (append fill-nobreak-predicate
21233 '(org-fill-paragraph-separate-nobreak-p
21234 org-fill-line-break-nobreak-p)))))
21235 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21236 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21237 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21238 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21240 (defvar org-element-paragraph-separate) ; org-element.el
21241 (defun org-fill-paragraph-separate-nobreak-p ()
21242 "Non-nil when a line break at point would insert a new item."
21243 (looking-at (substring org-element-paragraph-separate 1)))
21245 (defun org-fill-line-break-nobreak-p ()
21246 "Non-nil when a line break at point would create an Org line break."
21247 (save-excursion
21248 (skip-chars-backward "[ \t]")
21249 (skip-chars-backward "\\\\")
21250 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21252 (declare-function message-in-body-p "message" ())
21253 (defvar org-element--affiliated-re) ; From org-element.el
21254 (defun org-adaptive-fill-function ()
21255 "Compute a fill prefix for the current line.
21256 Return fill prefix, as a string, or nil if current line isn't
21257 meant to be filled."
21258 (org-with-wide-buffer
21259 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21260 ;; FIXME: This is really the job of orgstruct++-mode
21261 (let* ((p (line-beginning-position))
21262 (element (save-excursion (beginning-of-line)
21263 (org-element-at-point)))
21264 (type (org-element-type element))
21265 (post-affiliated
21266 (save-excursion
21267 (goto-char (org-element-property :begin element))
21268 (while (looking-at org-element--affiliated-re) (forward-line))
21269 (point))))
21270 (unless (< p post-affiliated)
21271 (case type
21272 (comment (looking-at "[ \t]*# ?") (match-string 0))
21273 (footnote-definition "")
21274 ((item plain-list)
21275 (make-string (org-list-item-body-column post-affiliated) ? ))
21276 (paragraph
21277 ;; Fill prefix is usually the same as the current line,
21278 ;; except if the paragraph is at the beginning of an item.
21279 (let ((parent (org-element-property :parent element)))
21280 (cond ((eq (org-element-type parent) 'item)
21281 (make-string (org-list-item-body-column
21282 (org-element-property :begin parent))
21283 ? ))
21284 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21285 (match-string 0))
21286 (t ""))))
21287 (comment-block
21288 ;; Only fill contents if P is within block boundaries.
21289 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21290 (forward-line)
21291 (point)))
21292 (cend (save-excursion
21293 (goto-char (org-element-property :end element))
21294 (skip-chars-backward " \r\t\n")
21295 (line-beginning-position))))
21296 (when (and (>= p cbeg) (< p cend))
21297 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21298 (match-string 0)
21299 ""))))))))))
21301 (declare-function message-goto-body "message" ())
21302 (defvar message-cite-prefix-regexp) ; From message.el
21303 (defvar org-element-all-objects) ; From org-element.el
21304 (defun org-fill-paragraph (&optional justify)
21305 "Fill element at point, when applicable.
21307 This function only applies to comment blocks, comments, example
21308 blocks and paragraphs. Also, as a special case, re-align table
21309 when point is at one.
21311 If JUSTIFY is non-nil (interactively, with prefix argument),
21312 justify as well. If `sentence-end-double-space' is non-nil, then
21313 period followed by one space does not end a sentence, so don't
21314 break a line there. The variable `fill-column' controls the
21315 width for filling.
21317 For convenience, when point is at a plain list, an item or
21318 a footnote definition, try to fill the first paragraph within."
21319 ;; Falls back on message-fill-paragraph when necessary
21320 (interactive)
21321 (if (and (derived-mode-p 'message-mode)
21322 (or (not (message-in-body-p))
21323 (save-excursion (move-beginning-of-line 1)
21324 (looking-at message-cite-prefix-regexp))))
21325 (let ((fill-paragraph-function
21326 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21327 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21328 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21329 (paragraph-separate
21330 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21331 (fill-paragraph nil))
21332 (save-excursion
21333 ;; Move to end of line in order to get the first paragraph
21334 ;; within a plain list or a footnote definition.
21335 (end-of-line)
21336 (let ((element (org-element-at-point)))
21337 ;; First check if point is in a blank line at the beginning of
21338 ;; the buffer. In that case, ignore filling.
21339 (if (< (point) (org-element-property :begin element)) t
21340 (case (org-element-type element)
21341 ;; Align Org tables, leave table.el tables as-is.
21342 (table-row (org-table-align) t)
21343 (table
21344 (when (eq (org-element-property :type element) 'org)
21345 (org-table-align))
21347 (paragraph
21348 ;; Paragraphs may contain `line-break' type objects.
21349 (let ((beg (max (point-min)
21350 (org-element-property :contents-begin element)))
21351 (end (min (point-max)
21352 (org-element-property :contents-end element))))
21353 ;; Do nothing if point is at an affiliated keyword.
21354 (if (< (point) beg) t
21355 (when (derived-mode-p 'message-mode)
21356 ;; In `message-mode', do not fill following
21357 ;; citation in current paragraph nor text before
21358 ;; message body.
21359 (let ((body-start (save-excursion (message-goto-body))))
21360 (when body-start (setq beg (max body-start beg))))
21361 (when (save-excursion
21362 (re-search-forward
21363 (concat "^" message-cite-prefix-regexp) end t))
21364 (setq end (match-beginning 0))))
21365 ;; Fill paragraph, taking line breaks into
21366 ;; consideration. For that, slice the paragraph
21367 ;; using line breaks as separators, and fill the
21368 ;; parts in reverse order to avoid messing with
21369 ;; markers.
21370 (save-excursion
21371 (goto-char end)
21372 (mapc
21373 (lambda (pos)
21374 (fill-region-as-paragraph pos (point) justify)
21375 (goto-char pos))
21376 ;; Find the list of ending positions for line
21377 ;; breaks in the current paragraph. Add paragraph
21378 ;; beginning to include first slice.
21379 (nreverse
21380 (cons
21382 (org-element-map
21383 (org-element--parse-objects
21384 beg end nil org-element-all-objects)
21385 'line-break
21386 (lambda (lb) (org-element-property :end lb)))))))
21387 t)))
21388 ;; Contents of `comment-block' type elements should be
21389 ;; filled as plain text, but only if point is within block
21390 ;; markers.
21391 (comment-block
21392 (let* ((case-fold-search t)
21393 (beg (save-excursion
21394 (goto-char (org-element-property :begin element))
21395 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21396 (forward-line)
21397 (point)))
21398 (end (save-excursion
21399 (goto-char (org-element-property :end element))
21400 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21401 (line-beginning-position))))
21402 (when (and (>= (point) beg) (< (point) end))
21403 (fill-region-as-paragraph
21404 (save-excursion
21405 (end-of-line)
21406 (re-search-backward "^[ \t]*$" beg 'move)
21407 (line-beginning-position))
21408 (save-excursion
21409 (beginning-of-line)
21410 (re-search-forward "^[ \t]*$" end 'move)
21411 (line-beginning-position))
21412 justify)))
21414 ;; Fill comments.
21415 (comment (fill-comment-paragraph justify))
21416 ;; Ignore every other element.
21417 (otherwise t)))))))
21419 (defun org-auto-fill-function ()
21420 "Auto-fill function."
21421 ;; Check if auto-filling is meaningful.
21422 (let ((fc (current-fill-column)))
21423 (when (and fc (> (current-column) fc))
21424 (let ((fill-prefix (org-adaptive-fill-function)))
21425 (when fill-prefix (do-auto-fill))))))
21427 (defun org-comment-line-break-function (&optional soft)
21428 "Break line at point and indent, continuing comment if within one.
21429 The inserted newline is marked hard if variable
21430 `use-hard-newlines' is true, unless optional argument SOFT is
21431 non-nil."
21432 (if soft (insert-and-inherit ?\n) (newline 1))
21433 (save-excursion (forward-char -1) (delete-horizontal-space))
21434 (delete-horizontal-space)
21435 (indent-to-left-margin)
21436 (insert-before-markers-and-inherit fill-prefix))
21439 ;;; Comments
21441 ;; Org comments syntax is quite complex. It requires the entire line
21442 ;; to be just a comment. Also, even with the right syntax at the
21443 ;; beginning of line, some some elements (i.e. verse-block or
21444 ;; example-block) don't accept comments. Usual Emacs comment commands
21445 ;; cannot cope with those requirements. Therefore, Org replaces them.
21447 ;; Org still relies on `comment-dwim', but cannot trust
21448 ;; `comment-only-p'. So, `comment-region-function' and
21449 ;; `uncomment-region-function' both point
21450 ;; to`org-comment-or-uncomment-region'. Eventually,
21451 ;; `org-insert-comment' takes care of insertion of comments at the
21452 ;; beginning of line.
21454 ;; `org-setup-comments-handling' install comments related variables
21455 ;; during `org-mode' initialization.
21457 (defun org-setup-comments-handling ()
21458 (interactive)
21459 (org-set-local 'comment-use-syntax nil)
21460 (org-set-local 'comment-start "# ")
21461 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21462 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21463 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21464 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21466 (defun org-insert-comment ()
21467 "Insert an empty comment above current line.
21468 If the line is empty, insert comment at its beginning."
21469 (beginning-of-line)
21470 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21471 (org-indent-line)
21472 (insert "# "))
21474 (defvar comment-empty-lines) ; From newcomment.el.
21475 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21476 "Comment or uncomment each non-blank line in the region.
21477 Uncomment each non-blank line between BEG and END if it only
21478 contains commented lines. Otherwise, comment them."
21479 (save-restriction
21480 ;; Restrict region
21481 (narrow-to-region (save-excursion (goto-char beg)
21482 (skip-chars-forward " \r\t\n" end)
21483 (line-beginning-position))
21484 (save-excursion (goto-char end)
21485 (skip-chars-backward " \r\t\n" beg)
21486 (line-end-position)))
21487 (let ((uncommentp
21488 ;; UNCOMMENTP is non-nil when every non blank line between
21489 ;; BEG and END is a comment.
21490 (save-excursion
21491 (goto-char (point-min))
21492 (while (and (not (eobp))
21493 (let ((element (org-element-at-point)))
21494 (and (eq (org-element-type element) 'comment)
21495 (goto-char (min (point-max)
21496 (org-element-property
21497 :end element)))))))
21498 (eobp))))
21499 (if uncommentp
21500 ;; Only blank lines and comments in region: uncomment it.
21501 (save-excursion
21502 (goto-char (point-min))
21503 (while (not (eobp))
21504 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21505 (replace-match "" nil nil nil 1))
21506 (forward-line)))
21507 ;; Comment each line in region.
21508 (let ((min-indent (point-max)))
21509 ;; First find the minimum indentation across all lines.
21510 (save-excursion
21511 (goto-char (point-min))
21512 (while (and (not (eobp)) (not (zerop min-indent)))
21513 (unless (looking-at "[ \t]*$")
21514 (setq min-indent (min min-indent (current-indentation))))
21515 (forward-line)))
21516 ;; Then loop over all lines.
21517 (save-excursion
21518 (goto-char (point-min))
21519 (while (not (eobp))
21520 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21521 (org-move-to-column min-indent t)
21522 (insert comment-start))
21523 (forward-line))))))))
21526 ;;; Other stuff.
21528 (defun org-toggle-fixed-width-section (arg)
21529 "Toggle the fixed-width export.
21530 If there is no active region, the QUOTE keyword at the current headline is
21531 inserted or removed. When present, it causes the text between this headline
21532 and the next to be exported as fixed-width text, and unmodified.
21533 If there is an active region, this command adds or removes a colon as the
21534 first character of this line. If the first character of a line is a colon,
21535 this line is also exported in fixed-width font."
21536 (interactive "P")
21537 (let* ((cc 0)
21538 (regionp (org-region-active-p))
21539 (beg (if regionp (region-beginning) (point)))
21540 (end (if regionp (region-end)))
21541 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21542 (case-fold-search nil)
21543 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21544 off)
21545 (if regionp
21546 (save-excursion
21547 (goto-char beg)
21548 (setq cc (current-column))
21549 (beginning-of-line 1)
21550 (setq off (looking-at re))
21551 (while (> nlines 0)
21552 (setq nlines (1- nlines))
21553 (beginning-of-line 1)
21554 (cond
21555 (arg
21556 (org-move-to-column cc t)
21557 (insert ": \n")
21558 (forward-line -1))
21559 ((and off (looking-at re))
21560 (replace-match "" t t nil 1))
21561 ((not off) (org-move-to-column cc t) (insert ": ")))
21562 (forward-line 1)))
21563 (save-excursion
21564 (org-back-to-heading)
21565 (cond
21566 ((looking-at (format org-heading-keyword-regexp-format
21567 org-quote-string))
21568 (goto-char (match-end 1))
21569 (looking-at (concat " +" org-quote-string))
21570 (replace-match "" t t)
21571 (when (eolp) (insert " ")))
21572 ((looking-at org-outline-regexp)
21573 (goto-char (match-end 0))
21574 (insert org-quote-string " ")))))))
21576 (defun org-reftex-citation ()
21577 "Use reftex-citation to insert a citation into the buffer.
21578 This looks for a line like
21580 #+BIBLIOGRAPHY: foo plain option:-d
21582 and derives from it that foo.bib is the bibliography file relevant
21583 for this document. It then installs the necessary environment for RefTeX
21584 to work in this buffer and calls `reftex-citation' to insert a citation
21585 into the buffer.
21587 Export of such citations to both LaTeX and HTML is handled by the contributed
21588 package org-exp-bibtex by Taru Karttunen."
21589 (interactive)
21590 (let ((reftex-docstruct-symbol 'rds)
21591 (reftex-cite-format "\\cite{%l}")
21592 rds bib)
21593 (save-excursion
21594 (save-restriction
21595 (widen)
21596 (let ((case-fold-search t)
21597 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21598 (if (not (save-excursion
21599 (or (re-search-forward re nil t)
21600 (re-search-backward re nil t))))
21601 (error "No bibliography defined in file")
21602 (setq bib (concat (match-string 1) ".bib")
21603 rds (list (list 'bib bib)))))))
21604 (call-interactively 'reftex-citation)))
21606 ;;;; Functions extending outline functionality
21608 (defun org-beginning-of-line (&optional arg)
21609 "Go to the beginning of the current line. If that is invisible, continue
21610 to a visible line beginning. This makes the function of C-a more intuitive.
21611 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21612 first attempt, and only move to after the tags when the cursor is already
21613 beyond the end of the headline."
21614 (interactive "P")
21615 (let ((pos (point))
21616 (special (if (consp org-special-ctrl-a/e)
21617 (car org-special-ctrl-a/e)
21618 org-special-ctrl-a/e))
21619 refpos)
21620 (if (org-bound-and-true-p line-move-visual)
21621 (beginning-of-visual-line 1)
21622 (beginning-of-line 1))
21623 (if (and arg (fboundp 'move-beginning-of-line))
21624 (call-interactively 'move-beginning-of-line)
21625 (if (bobp)
21627 (backward-char 1)
21628 (if (org-truely-invisible-p)
21629 (while (and (not (bobp)) (org-truely-invisible-p))
21630 (backward-char 1)
21631 (beginning-of-line 1))
21632 (forward-char 1))))
21633 (when special
21634 (cond
21635 ((and (looking-at org-complex-heading-regexp)
21636 (= (char-after (match-end 1)) ?\ ))
21637 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21638 (point-at-eol)))
21639 (goto-char
21640 (if (eq special t)
21641 (cond ((> pos refpos) refpos)
21642 ((= pos (point)) refpos)
21643 (t (point)))
21644 (cond ((> pos (point)) (point))
21645 ((not (eq last-command this-command)) (point))
21646 (t refpos)))))
21647 ((org-at-item-p)
21648 ;; Being at an item and not looking at an the item means point
21649 ;; was previously moved to beginning of a visual line, which
21650 ;; doesn't contain the item. Therefore, do nothing special,
21651 ;; just stay here.
21652 (when (looking-at org-list-full-item-re)
21653 ;; Set special position at first white space character after
21654 ;; bullet, and check-box, if any.
21655 (let ((after-bullet
21656 (let ((box (match-end 3)))
21657 (if (not box) (match-end 1)
21658 (let ((after (char-after box)))
21659 (if (and after (= after ? )) (1+ box) box))))))
21660 ;; Special case: Move point to special position when
21661 ;; currently after it or at beginning of line.
21662 (if (eq special t)
21663 (when (or (> pos after-bullet) (= (point) pos))
21664 (goto-char after-bullet))
21665 ;; Reversed case: Move point to special position when
21666 ;; point was already at beginning of line and command is
21667 ;; repeated.
21668 (when (and (= (point) pos) (eq last-command this-command))
21669 (goto-char after-bullet))))))))
21670 (org-no-warnings
21671 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21673 (defun org-end-of-line (&optional arg)
21674 "Go to the end of the line.
21675 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21676 first attempt, and only move to after the tags when the cursor is already
21677 beyond the end of the headline."
21678 (interactive "P")
21679 (let ((special (if (consp org-special-ctrl-a/e)
21680 (cdr org-special-ctrl-a/e)
21681 org-special-ctrl-a/e)))
21682 (cond
21683 ((or (not special) arg
21684 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21685 (call-interactively
21686 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21687 ((fboundp 'move-end-of-line) 'move-end-of-line)
21688 (t 'end-of-line))))
21689 ((org-at-heading-p)
21690 (let ((pos (point)))
21691 (beginning-of-line 1)
21692 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21693 (if (eq special t)
21694 (if (or (< pos (match-beginning 1))
21695 (= pos (match-end 0)))
21696 (goto-char (match-beginning 1))
21697 (goto-char (match-end 0)))
21698 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21699 (goto-char (match-end 0))
21700 (goto-char (match-beginning 1))))
21701 (call-interactively (if (fboundp 'move-end-of-line)
21702 'move-end-of-line
21703 'end-of-line)))))
21704 ((org-at-drawer-p)
21705 (move-end-of-line 1)
21706 (when (overlays-at (1- (point))) (backward-char 1)))
21707 ;; At an item: Move before any hidden text.
21708 (t (call-interactively
21709 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21710 ((fboundp 'move-end-of-line) 'move-end-of-line)
21711 (t 'end-of-line)))))
21712 (org-no-warnings
21713 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21715 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21716 (define-key org-mode-map "\C-e" 'org-end-of-line)
21718 (defun org-backward-sentence (&optional arg)
21719 "Go to beginning of sentence, or beginning of table field.
21720 This will call `backward-sentence' or `org-table-beginning-of-field',
21721 depending on context."
21722 (interactive "P")
21723 (cond
21724 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21725 (t (call-interactively 'backward-sentence))))
21727 (defun org-forward-sentence (&optional arg)
21728 "Go to end of sentence, or end of table field.
21729 This will call `forward-sentence' or `org-table-end-of-field',
21730 depending on context."
21731 (interactive "P")
21732 (cond
21733 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21734 (t (call-interactively 'forward-sentence))))
21736 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21737 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21739 (defun org-kill-line (&optional arg)
21740 "Kill line, to tags or end of line."
21741 (interactive "P")
21742 (cond
21743 ((or (not org-special-ctrl-k)
21744 (bolp)
21745 (not (org-at-heading-p)))
21746 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21747 org-ctrl-k-protect-subtree)
21748 (if (or (eq org-ctrl-k-protect-subtree 'error)
21749 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21750 (error "C-k aborted - would kill hidden subtree")))
21751 (call-interactively
21752 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21753 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21754 (kill-region (point) (match-beginning 1))
21755 (org-set-tags nil t))
21756 (t (kill-region (point) (point-at-eol)))))
21758 (define-key org-mode-map "\C-k" 'org-kill-line)
21760 (defun org-yank (&optional arg)
21761 "Yank. If the kill is a subtree, treat it specially.
21762 This command will look at the current kill and check if is a single
21763 subtree, or a series of subtrees[1]. If it passes the test, and if the
21764 cursor is at the beginning of a line or after the stars of a currently
21765 empty headline, then the yank is handled specially. How exactly depends
21766 on the value of the following variables, both set by default.
21768 org-yank-folded-subtrees
21769 When set, the subtree(s) will be folded after insertion, but only
21770 if doing so would now swallow text after the yanked text.
21772 org-yank-adjusted-subtrees
21773 When set, the subtree will be promoted or demoted in order to
21774 fit into the local outline tree structure, which means that the level
21775 will be adjusted so that it becomes the smaller one of the two
21776 *visible* surrounding headings.
21778 Any prefix to this command will cause `yank' to be called directly with
21779 no special treatment. In particular, a simple \\[universal-argument] prefix \
21780 will just
21781 plainly yank the text as it is.
21783 \[1] The test checks if the first non-white line is a heading
21784 and if there are no other headings with fewer stars."
21785 (interactive "P")
21786 (org-yank-generic 'yank arg))
21788 (defun org-yank-generic (command arg)
21789 "Perform some yank-like command.
21791 This function implements the behavior described in the `org-yank'
21792 documentation. However, it has been generalized to work for any
21793 interactive command with similar behavior."
21795 ;; pretend to be command COMMAND
21796 (setq this-command command)
21798 (if arg
21799 (call-interactively command)
21801 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21802 (and (org-kill-is-subtree-p)
21803 (or (bolp)
21804 (and (looking-at "[ \t]*$")
21805 (string-match
21806 "\\`\\*+\\'"
21807 (buffer-substring (point-at-bol) (point)))))))
21808 swallowp)
21809 (cond
21810 ((and subtreep org-yank-folded-subtrees)
21811 (let ((beg (point))
21812 end)
21813 (if (and subtreep org-yank-adjusted-subtrees)
21814 (org-paste-subtree nil nil 'for-yank)
21815 (call-interactively command))
21817 (setq end (point))
21818 (goto-char beg)
21819 (when (and (bolp) subtreep
21820 (not (setq swallowp
21821 (org-yank-folding-would-swallow-text beg end))))
21822 (org-with-limited-levels
21823 (or (looking-at org-outline-regexp)
21824 (re-search-forward org-outline-regexp-bol end t))
21825 (while (and (< (point) end) (looking-at org-outline-regexp))
21826 (hide-subtree)
21827 (org-cycle-show-empty-lines 'folded)
21828 (condition-case nil
21829 (outline-forward-same-level 1)
21830 (error (goto-char end))))))
21831 (when swallowp
21832 (message
21833 "Inserted text not folded because that would swallow text"))
21835 (goto-char end)
21836 (skip-chars-forward " \t\n\r")
21837 (beginning-of-line 1)
21838 (push-mark beg 'nomsg)))
21839 ((and subtreep org-yank-adjusted-subtrees)
21840 (let ((beg (point-at-bol)))
21841 (org-paste-subtree nil nil 'for-yank)
21842 (push-mark beg 'nomsg)))
21844 (call-interactively command))))))
21846 (defun org-yank-folding-would-swallow-text (beg end)
21847 "Would hide-subtree at BEG swallow any text after END?"
21848 (let (level)
21849 (org-with-limited-levels
21850 (save-excursion
21851 (goto-char beg)
21852 (when (or (looking-at org-outline-regexp)
21853 (re-search-forward org-outline-regexp-bol end t))
21854 (setq level (org-outline-level)))
21855 (goto-char end)
21856 (skip-chars-forward " \t\r\n\v\f")
21857 (if (or (eobp)
21858 (and (bolp) (looking-at org-outline-regexp)
21859 (<= (org-outline-level) level)))
21860 nil ; Nothing would be swallowed
21861 t))))) ; something would swallow
21863 (define-key org-mode-map "\C-y" 'org-yank)
21865 (defun org-truely-invisible-p ()
21866 "Check if point is at a character currently not visible.
21867 This version does not only check the character property, but also
21868 `visible-mode'."
21869 ;; Early versions of noutline don't have `outline-invisible-p'.
21870 (if (org-bound-and-true-p visible-mode)
21872 (outline-invisible-p)))
21874 (defun org-invisible-p2 ()
21875 "Check if point is at a character currently not visible."
21876 (save-excursion
21877 (if (and (eolp) (not (bobp))) (backward-char 1))
21878 ;; Early versions of noutline don't have `outline-invisible-p'.
21879 (outline-invisible-p)))
21881 (defun org-back-to-heading (&optional invisible-ok)
21882 "Call `outline-back-to-heading', but provide a better error message."
21883 (condition-case nil
21884 (outline-back-to-heading invisible-ok)
21885 (error (error "Before first headline at position %d in buffer %s"
21886 (point) (current-buffer)))))
21888 (defun org-before-first-heading-p ()
21889 "Before first heading?"
21890 (save-excursion
21891 (end-of-line)
21892 (null (re-search-backward org-outline-regexp-bol nil t))))
21894 (defun org-at-heading-p (&optional ignored)
21895 (outline-on-heading-p t))
21896 ;; Compatibility alias with Org versions < 7.8.03
21897 (defalias 'org-on-heading-p 'org-at-heading-p)
21899 (defun org-at-comment-p nil
21900 "Is cursor in a line starting with a # character?"
21901 (save-excursion
21902 (beginning-of-line)
21903 (looking-at "^#")))
21905 (defun org-at-drawer-p nil
21906 "Is cursor at a drawer keyword?"
21907 (save-excursion
21908 (move-beginning-of-line 1)
21909 (looking-at org-drawer-regexp)))
21911 (defun org-at-block-p nil
21912 "Is cursor at a block keyword?"
21913 (save-excursion
21914 (move-beginning-of-line 1)
21915 (looking-at org-block-regexp)))
21917 (defun org-point-at-end-of-empty-headline ()
21918 "If point is at the end of an empty headline, return t, else nil.
21919 If the heading only contains a TODO keyword, it is still still considered
21920 empty."
21921 (and (looking-at "[ \t]*$")
21922 (when org-todo-line-regexp
21923 (save-excursion
21924 (beginning-of-line 1)
21925 (let ((case-fold-search nil))
21926 (looking-at org-todo-line-regexp)
21927 (string= (match-string 3) ""))))))
21929 (defun org-at-heading-or-item-p ()
21930 (or (org-at-heading-p) (org-at-item-p)))
21932 (defun org-at-target-p ()
21933 (or (org-in-regexp org-radio-target-regexp)
21934 (org-in-regexp org-target-regexp)))
21935 ;; Compatibility alias with Org versions < 7.8.03
21936 (defalias 'org-on-target-p 'org-at-target-p)
21938 (defun org-up-heading-all (arg)
21939 "Move to the heading line of which the present line is a subheading.
21940 This function considers both visible and invisible heading lines.
21941 With argument, move up ARG levels."
21942 (if (fboundp 'outline-up-heading-all)
21943 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21944 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21946 (defun org-up-heading-safe ()
21947 "Move to the heading line of which the present line is a subheading.
21948 This version will not throw an error. It will return the level of the
21949 headline found, or nil if no higher level is found.
21951 Also, this function will be a lot faster than `outline-up-heading',
21952 because it relies on stars being the outline starters. This can really
21953 make a significant difference in outlines with very many siblings."
21954 (let (start-level re)
21955 (org-back-to-heading t)
21956 (setq start-level (funcall outline-level))
21957 (if (equal start-level 1)
21959 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21960 (if (re-search-backward re nil t)
21961 (funcall outline-level)))))
21963 (defun org-first-sibling-p ()
21964 "Is this heading the first child of its parents?"
21965 (interactive)
21966 (let ((re org-outline-regexp-bol)
21967 level l)
21968 (unless (org-at-heading-p t)
21969 (error "Not at a heading"))
21970 (setq level (funcall outline-level))
21971 (save-excursion
21972 (if (not (re-search-backward re nil t))
21974 (setq l (funcall outline-level))
21975 (< l level)))))
21977 (defun org-goto-sibling (&optional previous)
21978 "Goto the next sibling, even if it is invisible.
21979 When PREVIOUS is set, go to the previous sibling instead. Returns t
21980 when a sibling was found. When none is found, return nil and don't
21981 move point."
21982 (let ((fun (if previous 're-search-backward 're-search-forward))
21983 (pos (point))
21984 (re org-outline-regexp-bol)
21985 level l)
21986 (when (condition-case nil (org-back-to-heading t) (error nil))
21987 (setq level (funcall outline-level))
21988 (catch 'exit
21989 (or previous (forward-char 1))
21990 (while (funcall fun re nil t)
21991 (setq l (funcall outline-level))
21992 (when (< l level) (goto-char pos) (throw 'exit nil))
21993 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21994 (goto-char pos)
21995 nil))))
21997 (defun org-show-siblings ()
21998 "Show all siblings of the current headline."
21999 (save-excursion
22000 (while (org-goto-sibling) (org-flag-heading nil)))
22001 (save-excursion
22002 (while (org-goto-sibling 'previous)
22003 (org-flag-heading nil))))
22005 (defun org-goto-first-child ()
22006 "Goto the first child, even if it is invisible.
22007 Return t when a child was found. Otherwise don't move point and
22008 return nil."
22009 (let (level (pos (point)) (re org-outline-regexp-bol))
22010 (when (condition-case nil (org-back-to-heading t) (error nil))
22011 (setq level (outline-level))
22012 (forward-char 1)
22013 (if (and (re-search-forward re nil t) (> (outline-level) level))
22014 (progn (goto-char (match-beginning 0)) t)
22015 (goto-char pos) nil))))
22017 (defun org-show-hidden-entry ()
22018 "Show an entry where even the heading is hidden."
22019 (save-excursion
22020 (org-show-entry)))
22022 (defun org-flag-heading (flag &optional entry)
22023 "Flag the current heading. FLAG non-nil means make invisible.
22024 When ENTRY is non-nil, show the entire entry."
22025 (save-excursion
22026 (org-back-to-heading t)
22027 ;; Check if we should show the entire entry
22028 (if entry
22029 (progn
22030 (org-show-entry)
22031 (save-excursion
22032 (and (outline-next-heading)
22033 (org-flag-heading nil))))
22034 (outline-flag-region (max (point-min) (1- (point)))
22035 (save-excursion (outline-end-of-heading) (point))
22036 flag))))
22038 (defun org-get-next-sibling ()
22039 "Move to next heading of the same level, and return point.
22040 If there is no such heading, return nil.
22041 This is like outline-next-sibling, but invisible headings are ok."
22042 (let ((level (funcall outline-level)))
22043 (outline-next-heading)
22044 (while (and (not (eobp)) (> (funcall outline-level) level))
22045 (outline-next-heading))
22046 (if (or (eobp) (< (funcall outline-level) level))
22048 (point))))
22050 (defun org-get-last-sibling ()
22051 "Move to previous heading of the same level, and return point.
22052 If there is no such heading, return nil."
22053 (let ((opoint (point))
22054 (level (funcall outline-level)))
22055 (outline-previous-heading)
22056 (when (and (/= (point) opoint) (outline-on-heading-p t))
22057 (while (and (> (funcall outline-level) level)
22058 (not (bobp)))
22059 (outline-previous-heading))
22060 (if (< (funcall outline-level) level)
22062 (point)))))
22064 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22065 "Goto to the end of a subtree."
22066 ;; This contains an exact copy of the original function, but it uses
22067 ;; `org-back-to-heading', to make it work also in invisible
22068 ;; trees. And is uses an invisible-ok argument.
22069 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22070 ;; Furthermore, when used inside Org, finding the end of a large subtree
22071 ;; with many children and grandchildren etc, this can be much faster
22072 ;; than the outline version.
22073 (org-back-to-heading invisible-ok)
22074 (let ((first t)
22075 (level (funcall outline-level)))
22076 (if (and (derived-mode-p 'org-mode) (< level 1000))
22077 ;; A true heading (not a plain list item), in Org-mode
22078 ;; This means we can easily find the end by looking
22079 ;; only for the right number of stars. Using a regexp to do
22080 ;; this is so much faster than using a Lisp loop.
22081 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22082 (forward-char 1)
22083 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22084 ;; something else, do it the slow way
22085 (while (and (not (eobp))
22086 (or first (> (funcall outline-level) level)))
22087 (setq first nil)
22088 (outline-next-heading)))
22089 (unless to-heading
22090 (if (memq (preceding-char) '(?\n ?\^M))
22091 (progn
22092 ;; Go to end of line before heading
22093 (forward-char -1)
22094 (if (memq (preceding-char) '(?\n ?\^M))
22095 ;; leave blank line before heading
22096 (forward-char -1))))))
22097 (point))
22099 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22100 "Use Org version in org-mode, for dramatic speed-up."
22101 (if (derived-mode-p 'org-mode)
22102 (progn
22103 (org-end-of-subtree nil t)
22104 (unless (eobp) (backward-char 1)))
22105 ad-do-it))
22107 (defun org-end-of-meta-data-and-drawers ()
22108 "Jump to the first text after meta data and drawers in the current entry.
22109 This will move over empty lines, lines with planning time stamps,
22110 clocking lines, and drawers."
22111 (org-back-to-heading t)
22112 (let ((end (save-excursion (outline-next-heading) (point)))
22113 (re (concat "\\(" org-drawer-regexp "\\)"
22114 "\\|" "[ \t]*" org-keyword-time-regexp)))
22115 (forward-line 1)
22116 (while (re-search-forward re end t)
22117 (if (not (match-end 1))
22118 ;; empty or planning line
22119 (forward-line 1)
22120 ;; a drawer, find the end
22121 (re-search-forward "^[ \t]*:END:" end 'move)
22122 (forward-line 1)))
22123 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22124 (point)))
22126 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22127 "Move forward to the arg'th subheading at same level as this one.
22128 Stop at the first and last subheadings of a superior heading.
22129 Normally this only looks at visible headings, but when INVISIBLE-OK is
22130 non-nil it will also look at invisible ones."
22131 (interactive "p")
22132 (org-back-to-heading invisible-ok)
22133 (org-at-heading-p)
22134 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22135 (re (format "^\\*\\{1,%d\\} " level))
22137 (forward-char 1)
22138 (while (> arg 0)
22139 (while (and (re-search-forward re nil 'move)
22140 (setq l (- (match-end 0) (match-beginning 0) 1))
22141 (= l level)
22142 (not invisible-ok)
22143 (progn (backward-char 1) (outline-invisible-p)))
22144 (if (< l level) (setq arg 1)))
22145 (setq arg (1- arg)))
22146 (beginning-of-line 1)))
22148 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22149 "Move backward to the arg'th subheading at same level as this one.
22150 Stop at the first and last subheadings of a superior heading."
22151 (interactive "p")
22152 (org-back-to-heading)
22153 (org-at-heading-p)
22154 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22155 (re (format "^\\*\\{1,%d\\} " level))
22157 (while (> arg 0)
22158 (while (and (re-search-backward re nil 'move)
22159 (setq l (- (match-end 0) (match-beginning 0) 1))
22160 (= l level)
22161 (not invisible-ok)
22162 (outline-invisible-p))
22163 (if (< l level) (setq arg 1)))
22164 (setq arg (1- arg)))))
22166 ;;;###autoload
22167 (defun org-forward-element ()
22168 "Move forward by one element.
22169 Move to the next element at the same level, when possible."
22170 (interactive)
22171 (cond ((eobp) (error "Cannot move further down"))
22172 ((org-with-limited-levels (org-at-heading-p))
22173 (let ((origin (point)))
22174 (org-forward-heading-same-level 1)
22175 (unless (org-with-limited-levels (org-at-heading-p))
22176 (goto-char origin)
22177 (error "Cannot move further down"))))
22179 (let* ((elem (org-element-at-point))
22180 (end (org-element-property :end elem))
22181 (parent (org-element-property :parent elem)))
22182 (if (and parent (= (org-element-property :contents-end parent) end))
22183 (goto-char (org-element-property :end parent))
22184 (goto-char end))))))
22186 ;;;###autoload
22187 (defun org-backward-element ()
22188 "Move backward by one element.
22189 Move to the previous element at the same level, when possible."
22190 (interactive)
22191 (cond ((bobp) (error "Cannot move further up"))
22192 ((org-with-limited-levels (org-at-heading-p))
22193 ;; At an headline, move to the previous one, if any, or stay
22194 ;; here.
22195 (let ((origin (point)))
22196 (org-backward-heading-same-level 1)
22197 (unless (org-with-limited-levels (org-at-heading-p))
22198 (goto-char origin)
22199 (error "Cannot move further up"))))
22201 (let* ((trail (org-element-at-point 'keep-trail))
22202 (elem (car trail))
22203 (prev-elem (nth 1 trail))
22204 (beg (org-element-property :begin elem)))
22205 (cond
22206 ;; Move to beginning of current element if point isn't
22207 ;; there already.
22208 ((/= (point) beg) (goto-char beg))
22209 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22210 ((org-before-first-heading-p) (goto-char (point-min)))
22211 (t (org-back-to-heading)))))))
22213 ;;;###autoload
22214 (defun org-up-element ()
22215 "Move to upper element."
22216 (interactive)
22217 (if (org-with-limited-levels (org-at-heading-p))
22218 (unless (org-up-heading-safe) (error "No surrounding element"))
22219 (let* ((elem (org-element-at-point))
22220 (parent (org-element-property :parent elem)))
22221 (if parent (goto-char (org-element-property :begin parent))
22222 (if (org-with-limited-levels (org-before-first-heading-p))
22223 (error "No surrounding element")
22224 (org-with-limited-levels (org-back-to-heading)))))))
22226 ;;;###autoload
22227 (defvar org-element-greater-elements)
22228 (defun org-down-element ()
22229 "Move to inner element."
22230 (interactive)
22231 (let ((element (org-element-at-point)))
22232 (cond
22233 ((memq (org-element-type element) '(plain-list table))
22234 (goto-char (org-element-property :contents-begin element))
22235 (forward-char))
22236 ((memq (org-element-type element) org-element-greater-elements)
22237 ;; If contents are hidden, first disclose them.
22238 (when (org-element-property :hiddenp element) (org-cycle))
22239 (goto-char (or (org-element-property :contents-begin element)
22240 (error "No content for this element"))))
22241 (t (error "No inner element")))))
22243 ;;;###autoload
22244 (defun org-drag-element-backward ()
22245 "Move backward element at point."
22246 (interactive)
22247 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22248 (let* ((trail (org-element-at-point 'keep-trail))
22249 (elem (car trail))
22250 (prev-elem (nth 1 trail)))
22251 ;; Error out if no previous element or previous element is
22252 ;; a parent of the current one.
22253 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22254 (error "Cannot drag element backward")
22255 (let ((pos (point)))
22256 (org-element-swap-A-B prev-elem elem)
22257 (goto-char (+ (org-element-property :begin prev-elem)
22258 (- pos (org-element-property :begin elem)))))))))
22260 ;;;###autoload
22261 (defun org-drag-element-forward ()
22262 "Move forward element at point."
22263 (interactive)
22264 (let* ((pos (point))
22265 (elem (org-element-at-point)))
22266 (when (= (point-max) (org-element-property :end elem))
22267 (error "Cannot drag element forward"))
22268 (goto-char (org-element-property :end elem))
22269 (let ((next-elem (org-element-at-point)))
22270 (when (or (org-element-nested-p elem next-elem)
22271 (and (eq (org-element-type next-elem) 'headline)
22272 (not (eq (org-element-type elem) 'headline))))
22273 (goto-char pos)
22274 (error "Cannot drag element forward"))
22275 ;; Compute new position of point: it's shifted by NEXT-ELEM
22276 ;; body's length (without final blanks) and by the length of
22277 ;; blanks between ELEM and NEXT-ELEM.
22278 (let ((size-next (- (save-excursion
22279 (goto-char (org-element-property :end next-elem))
22280 (skip-chars-backward " \r\t\n")
22281 (forward-line)
22282 ;; Small correction if buffer doesn't end
22283 ;; with a newline character.
22284 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22285 (org-element-property :begin next-elem)))
22286 (size-blank (- (org-element-property :end elem)
22287 (save-excursion
22288 (goto-char (org-element-property :end elem))
22289 (skip-chars-backward " \r\t\n")
22290 (forward-line)
22291 (point)))))
22292 (org-element-swap-A-B elem next-elem)
22293 (goto-char (+ pos size-next size-blank))))))
22295 ;;;###autoload
22296 (defun org-mark-element ()
22297 "Put point at beginning of this element, mark at end.
22299 Interactively, if this command is repeated or (in Transient Mark
22300 mode) if the mark is active, it marks the next element after the
22301 ones already marked."
22302 (interactive)
22303 (let (deactivate-mark)
22304 (if (and (org-called-interactively-p 'any)
22305 (or (and (eq last-command this-command) (mark t))
22306 (and transient-mark-mode mark-active)))
22307 (set-mark
22308 (save-excursion
22309 (goto-char (mark))
22310 (goto-char (org-element-property :end (org-element-at-point)))))
22311 (let ((element (org-element-at-point)))
22312 (end-of-line)
22313 (push-mark (org-element-property :end element) t t)
22314 (goto-char (org-element-property :begin element))))))
22316 ;;;###autoload
22317 (defun org-narrow-to-element ()
22318 "Narrow buffer to current element."
22319 (interactive)
22320 (let ((elem (org-element-at-point)))
22321 (cond
22322 ((eq (car elem) 'headline)
22323 (narrow-to-region
22324 (org-element-property :begin elem)
22325 (org-element-property :end elem)))
22326 ((memq (car elem) org-element-greater-elements)
22327 (narrow-to-region
22328 (org-element-property :contents-begin elem)
22329 (org-element-property :contents-end elem)))
22331 (narrow-to-region
22332 (org-element-property :begin elem)
22333 (org-element-property :end elem))))))
22335 ;;;###autoload
22336 (defun org-transpose-element ()
22337 "Transpose current and previous elements, keeping blank lines between.
22338 Point is moved after both elements."
22339 (interactive)
22340 (org-skip-whitespace)
22341 (let ((end (org-element-property :end (org-element-at-point))))
22342 (org-drag-element-backward)
22343 (goto-char end)))
22345 ;;;###autoload
22346 (defun org-unindent-buffer ()
22347 "Un-indent the visible part of the buffer.
22348 Relative indentation (between items, inside blocks, etc.) isn't
22349 modified."
22350 (interactive)
22351 (unless (eq major-mode 'org-mode)
22352 (error "Cannot un-indent a buffer not in Org mode"))
22353 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22354 unindent-tree ; For byte-compiler.
22355 (unindent-tree
22356 (function
22357 (lambda (contents)
22358 (mapc
22359 (lambda (element)
22360 (if (memq (org-element-type element) '(headline section))
22361 (funcall unindent-tree (org-element-contents element))
22362 (save-excursion
22363 (save-restriction
22364 (narrow-to-region
22365 (org-element-property :begin element)
22366 (org-element-property :end element))
22367 (org-do-remove-indentation)))))
22368 (reverse contents))))))
22369 (funcall unindent-tree (org-element-contents parse-tree))))
22371 (defun org-show-subtree ()
22372 "Show everything after this heading at deeper levels."
22373 (interactive)
22374 (outline-flag-region
22375 (point)
22376 (save-excursion
22377 (org-end-of-subtree t t))
22378 nil))
22380 (defun org-show-entry ()
22381 "Show the body directly following this heading.
22382 Show the heading too, if it is currently invisible."
22383 (interactive)
22384 (save-excursion
22385 (condition-case nil
22386 (progn
22387 (org-back-to-heading t)
22388 (outline-flag-region
22389 (max (point-min) (1- (point)))
22390 (save-excursion
22391 (if (re-search-forward
22392 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22393 (match-beginning 1)
22394 (point-max)))
22395 nil)
22396 (org-cycle-hide-drawers 'children))
22397 (error nil))))
22399 (defun org-make-options-regexp (kwds &optional extra)
22400 "Make a regular expression for keyword lines."
22401 (concat
22402 "^#\\+\\("
22403 (mapconcat 'regexp-quote kwds "\\|")
22404 (if extra (concat "\\|" extra))
22405 "\\):[ \t]*\\(.*\\)"))
22407 ;; Make isearch reveal the necessary context
22408 (defun org-isearch-end ()
22409 "Reveal context after isearch exits."
22410 (when isearch-success ; only if search was successful
22411 (if (featurep 'xemacs)
22412 ;; Under XEmacs, the hook is run in the correct place,
22413 ;; we directly show the context.
22414 (org-show-context 'isearch)
22415 ;; In Emacs the hook runs *before* restoring the overlays.
22416 ;; So we have to use a one-time post-command-hook to do this.
22417 ;; (Emacs 22 has a special variable, see function `org-mode')
22418 (unless (and (boundp 'isearch-mode-end-hook-quit)
22419 isearch-mode-end-hook-quit)
22420 ;; Only when the isearch was not quitted.
22421 (org-add-hook 'post-command-hook 'org-isearch-post-command
22422 'append 'local)))))
22424 (defun org-isearch-post-command ()
22425 "Remove self from hook, and show context."
22426 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22427 (org-show-context 'isearch))
22430 ;;;; Integration with and fixes for other packages
22432 ;;; Imenu support
22434 (defvar org-imenu-markers nil
22435 "All markers currently used by Imenu.")
22436 (make-variable-buffer-local 'org-imenu-markers)
22438 (defun org-imenu-new-marker (&optional pos)
22439 "Return a new marker for use by Imenu, and remember the marker."
22440 (let ((m (make-marker)))
22441 (move-marker m (or pos (point)))
22442 (push m org-imenu-markers)
22445 (defun org-imenu-get-tree ()
22446 "Produce the index for Imenu."
22447 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22448 (setq org-imenu-markers nil)
22449 (let* ((n org-imenu-depth)
22450 (re (concat "^" (org-get-limited-outline-regexp)))
22451 (subs (make-vector (1+ n) nil))
22452 (last-level 0)
22453 m level head)
22454 (save-excursion
22455 (save-restriction
22456 (widen)
22457 (goto-char (point-max))
22458 (while (re-search-backward re nil t)
22459 (setq level (org-reduced-level (funcall outline-level)))
22460 (when (and (<= level n)
22461 (looking-at org-complex-heading-regexp))
22462 (setq head (org-link-display-format
22463 (org-match-string-no-properties 4))
22464 m (org-imenu-new-marker))
22465 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22466 (if (>= level last-level)
22467 (push (cons head m) (aref subs level))
22468 (push (cons head (aref subs (1+ level))) (aref subs level))
22469 (loop for i from (1+ level) to n do (aset subs i nil)))
22470 (setq last-level level)))))
22471 (aref subs 1)))
22473 (eval-after-load "imenu"
22474 '(progn
22475 (add-hook 'imenu-after-jump-hook
22476 (lambda ()
22477 (if (derived-mode-p 'org-mode)
22478 (org-show-context 'org-goto))))))
22480 (defun org-link-display-format (link)
22481 "Replace a link with either the description, or the link target
22482 if no description is present"
22483 (save-match-data
22484 (if (string-match org-bracket-link-analytic-regexp link)
22485 (replace-match (if (match-end 5)
22486 (match-string 5 link)
22487 (concat (match-string 1 link)
22488 (match-string 3 link)))
22489 nil t link)
22490 link)))
22492 (defun org-toggle-link-display ()
22493 "Toggle the literal or descriptive display of links."
22494 (interactive)
22495 (if org-descriptive-links
22496 (progn (org-remove-from-invisibility-spec '(org-link))
22497 (org-restart-font-lock)
22498 (setq org-descriptive-links nil))
22499 (progn (add-to-invisibility-spec '(org-link))
22500 (org-restart-font-lock)
22501 (setq org-descriptive-links t))))
22503 ;; Speedbar support
22505 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22506 "Overlay marking the agenda restriction line in speedbar.")
22507 (overlay-put org-speedbar-restriction-lock-overlay
22508 'face 'org-agenda-restriction-lock)
22509 (overlay-put org-speedbar-restriction-lock-overlay
22510 'help-echo "Agendas are currently limited to this item.")
22511 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22513 (defun org-speedbar-set-agenda-restriction ()
22514 "Restrict future agenda commands to the location at point in speedbar.
22515 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22516 (interactive)
22517 (require 'org-agenda)
22518 (let (p m tp np dir txt)
22519 (cond
22520 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22521 'org-imenu t))
22522 (setq m (get-text-property p 'org-imenu-marker))
22523 (with-current-buffer (marker-buffer m)
22524 (goto-char m)
22525 (org-agenda-set-restriction-lock 'subtree)))
22526 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22527 'speedbar-function 'speedbar-find-file))
22528 (setq tp (previous-single-property-change
22529 (1+ p) 'speedbar-function)
22530 np (next-single-property-change
22531 tp 'speedbar-function)
22532 dir (speedbar-line-directory)
22533 txt (buffer-substring-no-properties (or tp (point-min))
22534 (or np (point-max))))
22535 (with-current-buffer (find-file-noselect
22536 (let ((default-directory dir))
22537 (expand-file-name txt)))
22538 (unless (derived-mode-p 'org-mode)
22539 (error "Cannot restrict to non-Org-mode file"))
22540 (org-agenda-set-restriction-lock 'file)))
22541 (t (error "Don't know how to restrict Org-mode's agenda")))
22542 (move-overlay org-speedbar-restriction-lock-overlay
22543 (point-at-bol) (point-at-eol))
22544 (setq current-prefix-arg nil)
22545 (org-agenda-maybe-redo)))
22547 (eval-after-load "speedbar"
22548 '(progn
22549 (speedbar-add-supported-extension ".org")
22550 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22551 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22552 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22553 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22554 (add-hook 'speedbar-visiting-tag-hook
22555 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22557 ;;; Fixes and Hacks for problems with other packages
22559 ;; Make flyspell not check words in links, to not mess up our keymap
22560 (defun org-mode-flyspell-verify ()
22561 "Don't let flyspell put overlays at active buttons, or on
22562 {todo,all-time,additional-option-like}-keywords."
22563 (let ((pos (max (1- (point)) (point-min)))
22564 (word (thing-at-point 'word)))
22565 (and (not (get-text-property pos 'keymap))
22566 (not (get-text-property pos 'org-no-flyspell))
22567 (not (member word org-todo-keywords-1))
22568 (not (member word org-all-time-keywords))
22569 (not (member word org-options-keywords))
22570 (not (member word (mapcar 'car org-startup-options)))
22571 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22573 (defun org-remove-flyspell-overlays-in (beg end)
22574 "Remove flyspell overlays in region."
22575 (and (org-bound-and-true-p flyspell-mode)
22576 (fboundp 'flyspell-delete-region-overlays)
22577 (flyspell-delete-region-overlays beg end))
22578 (add-text-properties beg end '(org-no-flyspell t)))
22580 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22581 (eval-after-load "bookmark"
22582 '(if (boundp 'bookmark-after-jump-hook)
22583 ;; We can use the hook
22584 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22585 ;; Hook not available, use advice
22586 (defadvice bookmark-jump (after org-make-visible activate)
22587 "Make the position visible."
22588 (org-bookmark-jump-unhide))))
22590 ;; Make sure saveplace shows the location if it was hidden
22591 (eval-after-load "saveplace"
22592 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22593 "Make the position visible."
22594 (org-bookmark-jump-unhide)))
22596 ;; Make sure ecb shows the location if it was hidden
22597 (eval-after-load "ecb"
22598 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22599 "Make hierarchy visible when jumping into location from ECB tree buffer."
22600 (if (derived-mode-p 'org-mode)
22601 (org-show-context))))
22603 (defun org-bookmark-jump-unhide ()
22604 "Unhide the current position, to show the bookmark location."
22605 (and (derived-mode-p 'org-mode)
22606 (or (outline-invisible-p)
22607 (save-excursion (goto-char (max (point-min) (1- (point))))
22608 (outline-invisible-p)))
22609 (org-show-context 'bookmark-jump)))
22611 ;; Make session.el ignore our circular variable
22612 (eval-after-load "session"
22613 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22615 ;;;; Experimental code
22617 (defun org-closed-in-range ()
22618 "Sparse tree of items closed in a certain time range.
22619 Still experimental, may disappear in the future."
22620 (interactive)
22621 ;; Get the time interval from the user.
22622 (let* ((time1 (org-float-time
22623 (org-read-date nil 'to-time nil "Starting date: ")))
22624 (time2 (org-float-time
22625 (org-read-date nil 'to-time nil "End date:")))
22626 ;; callback function
22627 (callback (lambda ()
22628 (let ((time
22629 (org-float-time
22630 (apply 'encode-time
22631 (org-parse-time-string
22632 (match-string 1))))))
22633 ;; check if time in interval
22634 (and (>= time time1) (<= time time2))))))
22635 ;; make tree, check each match with the callback
22636 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22638 ;;;; Finish up
22640 (provide 'org)
22642 (run-hooks 'org-load-hook)
22644 ;;; org.el ends here