guard invocation of org-mode and suppress warning from byte-compiler
[org-mode.git] / lisp / org.el
blob835e42227716da2091a935cb4ff563cd5fbb5784
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
82 (when (fboundp 'defvaralias)
83 (unless (boundp 'calendar-view-holidays-initially-flag)
84 (defvaralias 'calendar-view-holidays-initially-flag
85 'view-calendar-holidays-initially))
86 (unless (boundp 'calendar-view-diary-initially-flag)
87 (defvaralias 'calendar-view-diary-initially-flag
88 'view-diary-entries-initially))
89 (unless (boundp 'diary-fancy-buffer)
90 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
92 (require 'outline)
93 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
94 ;; Other stuff we need.
95 (require 'time-date)
96 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
97 (require 'easymenu)
98 (require 'overlay)
100 (require 'org-macs)
101 (require 'org-entities)
102 (require 'org-compat)
103 (require 'org-faces)
104 (require 'org-list)
105 (require 'org-pcomplete)
106 (require 'org-src)
107 (require 'org-footnote)
109 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
110 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
111 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
112 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
113 (declare-function org-at-clock-log-p "org-clock" ())
114 (declare-function org-clock-timestamps-up "org-clock" ())
115 (declare-function org-clock-timestamps-down "org-clock" ())
117 ;; babel
118 (require 'ob)
119 (require 'ob-table)
120 (require 'ob-lob)
121 (require 'ob-ref)
122 (require 'ob-tangle)
123 (require 'ob-comint)
124 (require 'ob-keys)
126 ;; load languages based on value of `org-babel-load-languages'
127 (defvar org-babel-load-languages)
128 ;;;###autoload
129 (defun org-babel-do-load-languages (sym value)
130 "Load the languages defined in `org-babel-load-languages'."
131 (set-default sym value)
132 (mapc (lambda (pair)
133 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
134 (if active
135 (progn
136 (require (intern (concat "ob-" lang))))
137 (progn
138 (funcall 'fmakunbound
139 (intern (concat "org-babel-execute:" lang)))
140 (funcall 'fmakunbound
141 (intern (concat "org-babel-expand-body:" lang)))))))
142 org-babel-load-languages))
144 (defcustom org-babel-load-languages '((emacs-lisp . t))
145 "Languages which can be evaluated in Org-mode buffers.
146 This list can be used to load support for any of the languages
147 below, note that each language will depend on a different set of
148 system executables and/or Emacs modes. When a language is
149 \"loaded\", then code blocks in that language can be evaluated
150 with `org-babel-execute-src-block' bound by default to C-c
151 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
152 be set to remove code block evaluation from the C-c C-c
153 keybinding. By default only Emacs Lisp (which has no
154 requirements) is loaded."
155 :group 'org-babel
156 :set 'org-babel-do-load-languages
157 :version "24.1"
158 :type '(alist :tag "Babel Languages"
159 :key-type
160 (choice
161 (const :tag "Awk" awk)
162 (const :tag "C" C)
163 (const :tag "R" R)
164 (const :tag "Asymptote" asymptote)
165 (const :tag "Calc" calc)
166 (const :tag "Clojure" clojure)
167 (const :tag "CSS" css)
168 (const :tag "Ditaa" ditaa)
169 (const :tag "Dot" dot)
170 (const :tag "Emacs Lisp" emacs-lisp)
171 (const :tag "Fortran" fortran)
172 (const :tag "Gnuplot" gnuplot)
173 (const :tag "Haskell" haskell)
174 (const :tag "IO" io)
175 (const :tag "Java" java)
176 (const :tag "Javascript" js)
177 (const :tag "LaTeX" latex)
178 (const :tag "Ledger" ledger)
179 (const :tag "Lilypond" lilypond)
180 (const :tag "Maxima" maxima)
181 (const :tag "Matlab" matlab)
182 (const :tag "Mscgen" mscgen)
183 (const :tag "Ocaml" ocaml)
184 (const :tag "Octave" octave)
185 (const :tag "Org" org)
186 (const :tag "Perl" perl)
187 (const :tag "Pico Lisp" picolisp)
188 (const :tag "PlantUML" plantuml)
189 (const :tag "Python" python)
190 (const :tag "Ruby" ruby)
191 (const :tag "Sass" sass)
192 (const :tag "Scala" scala)
193 (const :tag "Scheme" scheme)
194 (const :tag "Screen" screen)
195 (const :tag "Shell Script" sh)
196 (const :tag "Shen" shen)
197 (const :tag "Sql" sql)
198 (const :tag "Sqlite" sqlite))
199 :value-type (boolean :tag "Activate" :value t)))
201 ;;;; Customization variables
202 (defcustom org-clone-delete-id nil
203 "Remove ID property of clones of a subtree.
204 When non-nil, clones of a subtree don't inherit the ID property.
205 Otherwise they inherit the ID property with a new unique
206 identifier."
207 :type 'boolean
208 :version "24.1"
209 :group 'org-id)
211 ;;; Version
212 (eval-when-compile
213 (defun org-release () "N/A")
214 (defun org-git-version () "N/A !!check installation!!")
215 (and (load (concat (org-find-library-dir "org") "../UTILITIES/org-fixup.el")
216 'noerror 'nomessage 'nosuffix)
217 (with-no-warnings (org-fixup))))
218 ;;;###autoload
219 (defun org-version (&optional here)
220 "Show the org-mode version in the echo area.
221 With prefix arg HERE, insert it at point."
222 (interactive "P")
223 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
224 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
225 (org-version (org-release))
226 (git-version (org-git-version))
227 (version (format "Org-mode version %s (%s @ %s)"
228 org-version
229 git-version
230 (if org-install-dir
231 (if (string= org-dir org-install-dir)
232 org-install-dir
233 (concat "mixed installation! " org-install-dir " and " org-dir))
234 "org-install.el can not be found!"))))
235 (if (org-called-interactively-p 'interactive)
236 (if here
237 (insert version)
238 (message version))
239 org-version)))
241 ;;; Compatibility constants
243 ;;; The custom variables
245 (defgroup org nil
246 "Outline-based notes management and organizer."
247 :tag "Org"
248 :group 'outlines
249 :group 'calendar)
251 (defcustom org-mode-hook nil
252 "Mode hook for Org-mode, run after the mode was turned on."
253 :group 'org
254 :type 'hook)
256 (defcustom org-load-hook nil
257 "Hook that is run after org.el has been loaded."
258 :group 'org
259 :type 'hook)
261 (defcustom org-log-buffer-setup-hook nil
262 "Hook that is run after an Org log buffer is created."
263 :group 'org
264 :version "24.1"
265 :type 'hook)
267 (defvar org-modules) ; defined below
268 (defvar org-modules-loaded nil
269 "Have the modules been loaded already?")
271 (defun org-load-modules-maybe (&optional force)
272 "Load all extensions listed in `org-modules'."
273 (when (or force (not org-modules-loaded))
274 (mapc (lambda (ext)
275 (condition-case nil (require ext)
276 (error (message "Problems while trying to load feature `%s'" ext))))
277 org-modules)
278 (setq org-modules-loaded t)))
280 (defun org-set-modules (var value)
281 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
282 (set var value)
283 (when (featurep 'org)
284 (org-load-modules-maybe 'force)))
286 (when (org-bound-and-true-p org-modules)
287 (let ((a (member 'org-infojs org-modules)))
288 (and a (setcar a 'org-jsinfo))))
290 (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)
291 "Modules that should always be loaded together with org.el.
292 If a description starts with <C>, the file is not part of Emacs
293 and loading it will require that you have downloaded and properly installed
294 the org-mode distribution.
296 You can also use this system to load external packages (i.e. neither Org
297 core modules, nor modules from the CONTRIB directory). Just add symbols
298 to the end of the list. If the package is called org-xyz.el, then you need
299 to add the symbol `xyz', and the package must have a call to
301 (provide 'org-xyz)"
302 :group 'org
303 :set 'org-set-modules
304 :type
305 '(set :greedy t
306 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
307 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
308 (const :tag " crypt: Encryption of subtrees" org-crypt)
309 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
310 (const :tag " docview: Links to doc-view buffers" org-docview)
311 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
312 (const :tag " id: Global IDs for identifying entries" org-id)
313 (const :tag " info: Links to Info nodes" org-info)
314 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
315 (const :tag " habit: Track your consistency with habits" org-habit)
316 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
317 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
318 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
319 (const :tag " mew Links to Mew folders/messages" org-mew)
320 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
321 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
322 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
323 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
324 (const :tag " vm: Links to VM folders/messages" org-vm)
325 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
326 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
327 (const :tag " mouse: Additional mouse support" org-mouse)
328 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
330 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
331 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
332 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
333 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
334 (const :tag "C collector: Collect properties into tables" org-collector)
335 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
336 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
337 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
338 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
339 (const :tag "C eval: Include command output as text" org-eval)
340 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
341 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
342 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
343 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
344 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
346 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
348 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
349 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
350 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
351 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
352 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
353 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
354 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
355 (const :tag "C mtags: Support for muse-like tags" org-mtags)
356 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
357 (const :tag "C registry: A registry for Org-mode links" org-registry)
358 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
359 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
360 (const :tag "C secretary: Team management with org-mode" org-secretary)
361 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
362 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
363 (const :tag "C track: Keep up with Org-mode development" org-track)
364 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
365 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
366 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
368 (defcustom org-support-shift-select nil
369 "Non-nil means make shift-cursor commands select text when possible.
371 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
372 start selecting a region, or enlarge regions started in this way.
373 In Org-mode, in special contexts, these same keys are used for
374 other purposes, important enough to compete with shift selection.
375 Org tries to balance these needs by supporting `shift-select-mode'
376 outside these special contexts, under control of this variable.
378 The default of this variable is nil, to avoid confusing behavior. Shifted
379 cursor keys will then execute Org commands in the following contexts:
380 - on a headline, changing TODO state (left/right) and priority (up/down)
381 - on a time stamp, changing the time
382 - in a plain list item, changing the bullet type
383 - in a property definition line, switching between allowed values
384 - in the BEGIN line of a clock table (changing the time block).
385 Outside these contexts, the commands will throw an error.
387 When this variable is t and the cursor is not in a special
388 context, Org-mode will support shift-selection for making and
389 enlarging regions. To make this more effective, the bullet
390 cycling will no longer happen anywhere in an item line, but only
391 if the cursor is exactly on the bullet.
393 If you set this variable to the symbol `always', then the keys
394 will not be special in headlines, property lines, and item lines,
395 to make shift selection work there as well. If this is what you
396 want, you can use the following alternative commands: `C-c C-t'
397 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
398 can be used to switch TODO sets, `C-c -' to cycle item bullet
399 types, and properties can be edited by hand or in column view.
401 However, when the cursor is on a timestamp, shift-cursor commands
402 will still edit the time stamp - this is just too good to give up.
404 XEmacs user should have this variable set to nil, because
405 `shift-select-mode' is in Emacs 23 or later only."
406 :group 'org
407 :type '(choice
408 (const :tag "Never" nil)
409 (const :tag "When outside special context" t)
410 (const :tag "Everywhere except timestamps" always)))
412 (defcustom org-loop-over-headlines-in-active-region nil
413 "Shall some commands act upon headlines in the active region?
415 When set to `t', some commands will be performed in all headlines
416 within the active region.
418 When set to `start-level', some commands will be performed in all
419 headlines within the active region, provided that these headlines
420 are of the same level than the first one.
422 When set to a string, those commands will be performed on the
423 matching headlines within the active region. Such string must be
424 a tags/property/todo match as it is used in the agenda tags view.
426 The list of commands is: `org-schedule', `org-deadline',
427 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
428 `org-archive-to-archive-sibling'. The archiving commands skip
429 already archived entries."
430 :type '(choice (const :tag "Don't loop" nil)
431 (const :tag "All headlines in active region" t)
432 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
433 (string :tag "Tags/Property/Todo matcher"))
434 :version "24.1"
435 :group 'org-todo
436 :group 'org-archive)
438 (defgroup org-startup nil
439 "Options concerning startup of Org-mode."
440 :tag "Org Startup"
441 :group 'org)
443 (defcustom org-startup-folded t
444 "Non-nil means entering Org-mode will switch to OVERVIEW.
445 This can also be configured on a per-file basis by adding one of
446 the following lines anywhere in the buffer:
448 #+STARTUP: fold (or `overview', this is equivalent)
449 #+STARTUP: nofold (or `showall', this is equivalent)
450 #+STARTUP: content
451 #+STARTUP: showeverything"
452 :group 'org-startup
453 :type '(choice
454 (const :tag "nofold: show all" nil)
455 (const :tag "fold: overview" t)
456 (const :tag "content: all headlines" content)
457 (const :tag "show everything, even drawers" showeverything)))
459 (defcustom org-startup-truncated t
460 "Non-nil means entering Org-mode will set `truncate-lines'.
461 This is useful since some lines containing links can be very long and
462 uninteresting. Also tables look terrible when wrapped."
463 :group 'org-startup
464 :type 'boolean)
466 (defcustom org-startup-indented nil
467 "Non-nil means turn on `org-indent-mode' on startup.
468 This can also be configured on a per-file basis by adding one of
469 the following lines anywhere in the buffer:
471 #+STARTUP: indent
472 #+STARTUP: noindent"
473 :group 'org-structure
474 :type '(choice
475 (const :tag "Not" nil)
476 (const :tag "Globally (slow on startup in large files)" t)))
478 (defcustom org-use-sub-superscripts t
479 "Non-nil means interpret \"_\" and \"^\" for export.
480 When this option is turned on, you can use TeX-like syntax for sub- and
481 superscripts. Several characters after \"_\" or \"^\" will be
482 considered as a single item - so grouping with {} is normally not
483 needed. For example, the following things will be parsed as single
484 sub- or superscripts.
486 10^24 or 10^tau several digits will be considered 1 item.
487 10^-12 or 10^-tau a leading sign with digits or a word
488 x^2-y^3 will be read as x^2 - y^3, because items are
489 terminated by almost any nonword/nondigit char.
490 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
492 Still, ambiguity is possible - so when in doubt use {} to enclose the
493 sub/superscript. If you set this variable to the symbol `{}',
494 the braces are *required* in order to trigger interpretations as
495 sub/superscript. This can be helpful in documents that need \"_\"
496 frequently in plain text.
498 Not all export backends support this, but HTML does.
500 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
501 :group 'org-startup
502 :group 'org-export-translation
503 :version "24.1"
504 :type '(choice
505 (const :tag "Always interpret" t)
506 (const :tag "Only with braces" {})
507 (const :tag "Never interpret" nil)))
509 (if (fboundp 'defvaralias)
510 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
513 (defcustom org-startup-with-beamer-mode nil
514 "Non-nil means turn on `org-beamer-mode' on startup.
515 This can also be configured on a per-file basis by adding one of
516 the following lines anywhere in the buffer:
518 #+STARTUP: beamer"
519 :group 'org-startup
520 :version "24.1"
521 :type 'boolean)
523 (defcustom org-startup-align-all-tables nil
524 "Non-nil means align all tables when visiting a file.
525 This is useful when the column width in tables is forced with <N> cookies
526 in table fields. Such tables will look correct only after the first re-align.
527 This can also be configured on a per-file basis by adding one of
528 the following lines anywhere in the buffer:
529 #+STARTUP: align
530 #+STARTUP: noalign"
531 :group 'org-startup
532 :type 'boolean)
534 (defcustom org-startup-with-inline-images nil
535 "Non-nil means show inline images when loading a new Org file.
536 This can also be configured on a per-file basis by adding one of
537 the following lines anywhere in the buffer:
538 #+STARTUP: inlineimages
539 #+STARTUP: noinlineimages"
540 :group 'org-startup
541 :version "24.1"
542 :type 'boolean)
544 (defcustom org-insert-mode-line-in-empty-file nil
545 "Non-nil means insert the first line setting Org-mode in empty files.
546 When the function `org-mode' is called interactively in an empty file, this
547 normally means that the file name does not automatically trigger Org-mode.
548 To ensure that the file will always be in Org-mode in the future, a
549 line enforcing Org-mode will be inserted into the buffer, if this option
550 has been set."
551 :group 'org-startup
552 :type 'boolean)
554 (defcustom org-replace-disputed-keys nil
555 "Non-nil means use alternative key bindings for some keys.
556 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
557 These keys are also used by other packages like shift-selection-mode'
558 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
559 If you want to use Org-mode together with one of these other modes,
560 or more generally if you would like to move some Org-mode commands to
561 other keys, set this variable and configure the keys with the variable
562 `org-disputed-keys'.
564 This option is only relevant at load-time of Org-mode, and must be set
565 *before* org.el is loaded. Changing it requires a restart of Emacs to
566 become effective."
567 :group 'org-startup
568 :type 'boolean)
570 (defcustom org-use-extra-keys nil
571 "Non-nil means use extra key sequence definitions for certain commands.
572 This happens automatically if you run XEmacs or if `window-system'
573 is nil. This variable lets you do the same manually. You must
574 set it before loading org.
576 Example: on Carbon Emacs 22 running graphically, with an external
577 keyboard on a Powerbook, the default way of setting M-left might
578 not work for either Alt or ESC. Setting this variable will make
579 it work for ESC."
580 :group 'org-startup
581 :type 'boolean)
583 (if (fboundp 'defvaralias)
584 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
586 (defcustom org-disputed-keys
587 '(([(shift up)] . [(meta p)])
588 ([(shift down)] . [(meta n)])
589 ([(shift left)] . [(meta -)])
590 ([(shift right)] . [(meta +)])
591 ([(control shift right)] . [(meta shift +)])
592 ([(control shift left)] . [(meta shift -)]))
593 "Keys for which Org-mode and other modes compete.
594 This is an alist, cars are the default keys, second element specifies
595 the alternative to use when `org-replace-disputed-keys' is t.
597 Keys can be specified in any syntax supported by `define-key'.
598 The value of this option takes effect only at Org-mode's startup,
599 therefore you'll have to restart Emacs to apply it after changing."
600 :group 'org-startup
601 :type 'alist)
603 (defun org-key (key)
604 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
605 Or return the original if not disputed.
606 Also apply the translations defined in `org-xemacs-key-equivalents'."
607 (when org-replace-disputed-keys
608 (let* ((nkey (key-description key))
609 (x (org-find-if (lambda (x)
610 (equal (key-description (car x)) nkey))
611 org-disputed-keys)))
612 (setq key (if x (cdr x) key))))
613 (when (featurep 'xemacs)
614 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
615 key)
617 (defun org-find-if (predicate seq)
618 (catch 'exit
619 (while seq
620 (if (funcall predicate (car seq))
621 (throw 'exit (car seq))
622 (pop seq)))))
624 (defun org-defkey (keymap key def)
625 "Define a key, possibly translated, as returned by `org-key'."
626 (define-key keymap (org-key key) def))
628 (defcustom org-ellipsis nil
629 "The ellipsis to use in the Org-mode outline.
630 When nil, just use the standard three dots. When a string, use that instead,
631 When a face, use the standard 3 dots, but with the specified face.
632 The change affects only Org-mode (which will then use its own display table).
633 Changing this requires executing `M-x org-mode' in a buffer to become
634 effective."
635 :group 'org-startup
636 :type '(choice (const :tag "Default" nil)
637 (face :tag "Face" :value org-warning)
638 (string :tag "String" :value "...#")))
640 (defvar org-display-table nil
641 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
643 (defgroup org-keywords nil
644 "Keywords in Org-mode."
645 :tag "Org Keywords"
646 :group 'org)
648 (defcustom org-deadline-string "DEADLINE:"
649 "String to mark deadline entries.
650 A deadline is this string, followed by a time stamp. Should be a word,
651 terminated by a colon. You can insert a schedule keyword and
652 a timestamp with \\[org-deadline].
653 Changes become only effective after restarting Emacs."
654 :group 'org-keywords
655 :type 'string)
657 (defcustom org-scheduled-string "SCHEDULED:"
658 "String to mark scheduled TODO entries.
659 A schedule is this string, followed by a time stamp. Should be a word,
660 terminated by a colon. You can insert a schedule keyword and
661 a timestamp with \\[org-schedule].
662 Changes become only effective after restarting Emacs."
663 :group 'org-keywords
664 :type 'string)
666 (defcustom org-closed-string "CLOSED:"
667 "String used as the prefix for timestamps logging closing a TODO entry."
668 :group 'org-keywords
669 :type 'string)
671 (defcustom org-clock-string "CLOCK:"
672 "String used as prefix for timestamps clocking work hours on an item."
673 :group 'org-keywords
674 :type 'string)
676 (defcustom org-comment-string "COMMENT"
677 "Entries starting with this keyword will never be exported.
678 An entry can be toggled between COMMENT and normal with
679 \\[org-toggle-comment].
680 Changes become only effective after restarting Emacs."
681 :group 'org-keywords
682 :type 'string)
684 (defcustom org-quote-string "QUOTE"
685 "Entries starting with this keyword will be exported in fixed-width font.
686 Quoting applies only to the text in the entry following the headline, and does
687 not extend beyond the next headline, even if that is lower level.
688 An entry can be toggled between QUOTE and normal with
689 \\[org-toggle-fixed-width-section]."
690 :group 'org-keywords
691 :type 'string)
693 (defconst org-repeat-re
694 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
695 "Regular expression for specifying repeated events.
696 After a match, group 1 contains the repeat expression.")
698 (defgroup org-structure nil
699 "Options concerning the general structure of Org-mode files."
700 :tag "Org Structure"
701 :group 'org)
703 (defgroup org-reveal-location nil
704 "Options about how to make context of a location visible."
705 :tag "Org Reveal Location"
706 :group 'org-structure)
708 (defconst org-context-choice
709 '(choice
710 (const :tag "Always" t)
711 (const :tag "Never" nil)
712 (repeat :greedy t :tag "Individual contexts"
713 (cons
714 (choice :tag "Context"
715 (const agenda)
716 (const org-goto)
717 (const occur-tree)
718 (const tags-tree)
719 (const link-search)
720 (const mark-goto)
721 (const bookmark-jump)
722 (const isearch)
723 (const default))
724 (boolean))))
725 "Contexts for the reveal options.")
727 (defcustom org-show-hierarchy-above '((default . t))
728 "Non-nil means show full hierarchy when revealing a location.
729 Org-mode often shows locations in an org-mode file which might have
730 been invisible before. When this is set, the hierarchy of headings
731 above the exposed location is shown.
732 Turning this off for example for sparse trees makes them very compact.
733 Instead of t, this can also be an alist specifying this option for different
734 contexts. Valid contexts are
735 agenda when exposing an entry from the agenda
736 org-goto when using the command `org-goto' on key C-c C-j
737 occur-tree when using the command `org-occur' on key C-c /
738 tags-tree when constructing a sparse tree based on tags matches
739 link-search when exposing search matches associated with a link
740 mark-goto when exposing the jump goal of a mark
741 bookmark-jump when exposing a bookmark location
742 isearch when exiting from an incremental search
743 default default for all contexts not set explicitly"
744 :group 'org-reveal-location
745 :type org-context-choice)
747 (defcustom org-show-following-heading '((default . nil))
748 "Non-nil means show following heading when revealing a location.
749 Org-mode often shows locations in an org-mode file which might have
750 been invisible before. When this is set, the heading following the
751 match is shown.
752 Turning this off for example for sparse trees makes them very compact,
753 but makes it harder to edit the location of the match. In such a case,
754 use the command \\[org-reveal] to show more context.
755 Instead of t, this can also be an alist specifying this option for different
756 contexts. See `org-show-hierarchy-above' for valid contexts."
757 :group 'org-reveal-location
758 :type org-context-choice)
760 (defcustom org-show-siblings '((default . nil) (isearch t))
761 "Non-nil means show all sibling heading when revealing a location.
762 Org-mode often shows locations in an org-mode file which might have
763 been invisible before. When this is set, the sibling of the current entry
764 heading are all made visible. If `org-show-hierarchy-above' is t,
765 the same happens on each level of the hierarchy above the current entry.
767 By default this is on for the isearch context, off for all other contexts.
768 Turning this off for example for sparse trees makes them very compact,
769 but makes it harder to edit the location of the match. In such a case,
770 use the command \\[org-reveal] to show more context.
771 Instead of t, this can also be an alist specifying this option for different
772 contexts. See `org-show-hierarchy-above' for valid contexts."
773 :group 'org-reveal-location
774 :type org-context-choice)
776 (defcustom org-show-entry-below '((default . nil))
777 "Non-nil means show the entry below a headline when revealing a location.
778 Org-mode often shows locations in an org-mode file which might have
779 been invisible before. When this is set, the text below the headline that is
780 exposed is also shown.
782 By default this is off for all contexts.
783 Instead of t, this can also be an alist specifying this option for different
784 contexts. See `org-show-hierarchy-above' for valid contexts."
785 :group 'org-reveal-location
786 :type org-context-choice)
788 (defcustom org-indirect-buffer-display 'other-window
789 "How should indirect tree buffers be displayed?
790 This applies to indirect buffers created with the commands
791 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
792 Valid values are:
793 current-window Display in the current window
794 other-window Just display in another window.
795 dedicated-frame Create one new frame, and re-use it each time.
796 new-frame Make a new frame each time. Note that in this case
797 previously-made indirect buffers are kept, and you need to
798 kill these buffers yourself."
799 :group 'org-structure
800 :group 'org-agenda-windows
801 :type '(choice
802 (const :tag "In current window" current-window)
803 (const :tag "In current frame, other window" other-window)
804 (const :tag "Each time a new frame" new-frame)
805 (const :tag "One dedicated frame" dedicated-frame)))
807 (defcustom org-use-speed-commands nil
808 "Non-nil means activate single letter commands at beginning of a headline.
809 This may also be a function to test for appropriate locations where speed
810 commands should be active."
811 :group 'org-structure
812 :type '(choice
813 (const :tag "Never" nil)
814 (const :tag "At beginning of headline stars" t)
815 (function)))
817 (defcustom org-speed-commands-user nil
818 "Alist of additional speed commands.
819 This list will be checked before `org-speed-commands-default'
820 when the variable `org-use-speed-commands' is non-nil
821 and when the cursor is at the beginning of a headline.
822 The car if each entry is a string with a single letter, which must
823 be assigned to `self-insert-command' in the global map.
824 The cdr is either a command to be called interactively, a function
825 to be called, or a form to be evaluated.
826 An entry that is just a list with a single string will be interpreted
827 as a descriptive headline that will be added when listing the speed
828 commands in the Help buffer using the `?' speed command."
829 :group 'org-structure
830 :type '(repeat :value ("k" . ignore)
831 (choice :value ("k" . ignore)
832 (list :tag "Descriptive Headline" (string :tag "Headline"))
833 (cons :tag "Letter and Command"
834 (string :tag "Command letter")
835 (choice
836 (function)
837 (sexp))))))
839 (defgroup org-cycle nil
840 "Options concerning visibility cycling in Org-mode."
841 :tag "Org Cycle"
842 :group 'org-structure)
844 (defcustom org-cycle-skip-children-state-if-no-children t
845 "Non-nil means skip CHILDREN state in entries that don't have any."
846 :group 'org-cycle
847 :type 'boolean)
849 (defcustom org-cycle-max-level nil
850 "Maximum level which should still be subject to visibility cycling.
851 Levels higher than this will, for cycling, be treated as text, not a headline.
852 When `org-odd-levels-only' is set, a value of N in this variable actually
853 means 2N-1 stars as the limiting headline.
854 When nil, cycle all levels.
855 Note that the limiting level of cycling is also influenced by
856 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
857 `org-inlinetask-min-level' is, cycling will be limited to levels one less
858 than its value."
859 :group 'org-cycle
860 :type '(choice
861 (const :tag "No limit" nil)
862 (integer :tag "Maximum level")))
864 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
865 "Names of drawers. Drawers are not opened by cycling on the headline above.
866 Drawers only open with a TAB on the drawer line itself. A drawer looks like
867 this:
868 :DRAWERNAME:
869 .....
870 :END:
871 The drawer \"PROPERTIES\" is special for capturing properties through
872 the property API.
874 Drawers can be defined on the per-file basis with a line like:
876 #+DRAWERS: HIDDEN STATE PROPERTIES"
877 :group 'org-structure
878 :group 'org-cycle
879 :type '(repeat (string :tag "Drawer Name")))
881 (defcustom org-hide-block-startup nil
882 "Non-nil means entering Org-mode will fold all blocks.
883 This can also be set in on a per-file basis with
885 #+STARTUP: hideblocks
886 #+STARTUP: showblocks"
887 :group 'org-startup
888 :group 'org-cycle
889 :type 'boolean)
891 (defcustom org-cycle-global-at-bob nil
892 "Cycle globally if cursor is at beginning of buffer and not at a headline.
893 This makes it possible to do global cycling without having to use S-TAB or
894 \\[universal-argument] TAB. For this special case to work, the first line \
895 of the buffer
896 must not be a headline - it may be empty or some other text. When used in
897 this way, `org-cycle-hook' is disables temporarily, to make sure the
898 cursor stays at the beginning of the buffer.
899 When this option is nil, don't do anything special at the beginning
900 of the buffer."
901 :group 'org-cycle
902 :type 'boolean)
904 (defcustom org-cycle-level-after-item/entry-creation t
905 "Non-nil means cycle entry level or item indentation in new empty entries.
907 When the cursor is at the end of an empty headline, i.e with only stars
908 and maybe a TODO keyword, TAB will then switch the entry to become a child,
909 and then all possible ancestor states, before returning to the original state.
910 This makes data entry extremely fast: M-RET to create a new headline,
911 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
913 When the cursor is at the end of an empty plain list item, one TAB will
914 make it a subitem, two or more tabs will back up to make this an item
915 higher up in the item hierarchy."
916 :group 'org-cycle
917 :type 'boolean)
919 (defcustom org-cycle-emulate-tab t
920 "Where should `org-cycle' emulate TAB.
921 nil Never
922 white Only in completely white lines
923 whitestart Only at the beginning of lines, before the first non-white char
924 t Everywhere except in headlines
925 exc-hl-bol Everywhere except at the start of a headline
926 If TAB is used in a place where it does not emulate TAB, the current subtree
927 visibility is cycled."
928 :group 'org-cycle
929 :type '(choice (const :tag "Never" nil)
930 (const :tag "Only in completely white lines" white)
931 (const :tag "Before first char in a line" whitestart)
932 (const :tag "Everywhere except in headlines" t)
933 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
936 (defcustom org-cycle-separator-lines 2
937 "Number of empty lines needed to keep an empty line between collapsed trees.
938 If you leave an empty line between the end of a subtree and the following
939 headline, this empty line is hidden when the subtree is folded.
940 Org-mode will leave (exactly) one empty line visible if the number of
941 empty lines is equal or larger to the number given in this variable.
942 So the default 2 means at least 2 empty lines after the end of a subtree
943 are needed to produce free space between a collapsed subtree and the
944 following headline.
946 If the number is negative, and the number of empty lines is at least -N,
947 all empty lines are shown.
949 Special case: when 0, never leave empty lines in collapsed view."
950 :group 'org-cycle
951 :type 'integer)
952 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
954 (defcustom org-pre-cycle-hook nil
955 "Hook that is run before visibility cycling is happening.
956 The function(s) in this hook must accept a single argument which indicates
957 the new state that will be set right after running this hook. The
958 argument is a symbol. Before a global state change, it can have the values
959 `overview', `content', or `all'. Before a local state change, it can have
960 the values `folded', `children', or `subtree'."
961 :group 'org-cycle
962 :type 'hook)
964 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
965 org-cycle-hide-drawers
966 org-cycle-show-empty-lines
967 org-optimize-window-after-visibility-change)
968 "Hook that is run after `org-cycle' has changed the buffer visibility.
969 The function(s) in this hook must accept a single argument which indicates
970 the new state that was set by the most recent `org-cycle' command. The
971 argument is a symbol. After a global state change, it can have the values
972 `overview', `content', or `all'. After a local state change, it can have
973 the values `folded', `children', or `subtree'."
974 :group 'org-cycle
975 :type 'hook)
977 (defgroup org-edit-structure nil
978 "Options concerning structure editing in Org-mode."
979 :tag "Org Edit Structure"
980 :group 'org-structure)
982 (defcustom org-odd-levels-only nil
983 "Non-nil means skip even levels and only use odd levels for the outline.
984 This has the effect that two stars are being added/taken away in
985 promotion/demotion commands. It also influences how levels are
986 handled by the exporters.
987 Changing it requires restart of `font-lock-mode' to become effective
988 for fontification also in regions already fontified.
989 You may also set this on a per-file basis by adding one of the following
990 lines to the buffer:
992 #+STARTUP: odd
993 #+STARTUP: oddeven"
994 :group 'org-edit-structure
995 :group 'org-appearance
996 :type 'boolean)
998 (defcustom org-adapt-indentation t
999 "Non-nil means adapt indentation to outline node level.
1001 When this variable is set, Org assumes that you write outlines by
1002 indenting text in each node to align with the headline (after the stars).
1003 The following issues are influenced by this variable:
1005 - When this is set and the *entire* text in an entry is indented, the
1006 indentation is increased by one space in a demotion command, and
1007 decreased by one in a promotion command. If any line in the entry
1008 body starts with text at column 0, indentation is not changed at all.
1010 - Property drawers and planning information is inserted indented when
1011 this variable s set. When nil, they will not be indented.
1013 - TAB indents a line relative to context. The lines below a headline
1014 will be indented when this variable is set.
1016 Note that this is all about true indentation, by adding and removing
1017 space characters. See also `org-indent.el' which does level-dependent
1018 indentation in a virtual way, i.e. at display time in Emacs."
1019 :group 'org-edit-structure
1020 :type 'boolean)
1022 (defcustom org-special-ctrl-a/e nil
1023 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1025 When t, `C-a' will bring back the cursor to the beginning of the
1026 headline text, i.e. after the stars and after a possible TODO
1027 keyword. In an item, this will be the position after bullet and
1028 check-box, if any. When the cursor is already at that position,
1029 another `C-a' will bring it to the beginning of the line.
1031 `C-e' will jump to the end of the headline, ignoring the presence
1032 of tags in the headline. A second `C-e' will then jump to the
1033 true end of the line, after any tags. This also means that, when
1034 this variable is non-nil, `C-e' also will never jump beyond the
1035 end of the heading of a folded section, i.e. not after the
1036 ellipses.
1038 When set to the symbol `reversed', the first `C-a' or `C-e' works
1039 normally, going to the true line boundary first. Only a directly
1040 following, identical keypress will bring the cursor to the
1041 special positions.
1043 This may also be a cons cell where the behavior for `C-a' and
1044 `C-e' is set separately."
1045 :group 'org-edit-structure
1046 :type '(choice
1047 (const :tag "off" nil)
1048 (const :tag "on: after stars/bullet and before tags first" t)
1049 (const :tag "reversed: true line boundary first" reversed)
1050 (cons :tag "Set C-a and C-e separately"
1051 (choice :tag "Special C-a"
1052 (const :tag "off" nil)
1053 (const :tag "on: after stars/bullet first" t)
1054 (const :tag "reversed: before stars/bullet first" reversed))
1055 (choice :tag "Special C-e"
1056 (const :tag "off" nil)
1057 (const :tag "on: before tags first" t)
1058 (const :tag "reversed: after tags first" reversed)))))
1059 (if (fboundp 'defvaralias)
1060 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1062 (defcustom org-special-ctrl-k nil
1063 "Non-nil means `C-k' will behave specially in headlines.
1064 When nil, `C-k' will call the default `kill-line' command.
1065 When t, the following will happen while the cursor is in the headline:
1067 - When the cursor is at the beginning of a headline, kill the entire
1068 line and possible the folded subtree below the line.
1069 - When in the middle of the headline text, kill the headline up to the tags.
1070 - When after the headline text, kill the tags."
1071 :group 'org-edit-structure
1072 :type 'boolean)
1074 (defcustom org-ctrl-k-protect-subtree nil
1075 "Non-nil means, do not delete a hidden subtree with C-k.
1076 When set to the symbol `error', simply throw an error when C-k is
1077 used to kill (part-of) a headline that has hidden text behind it.
1078 Any other non-nil value will result in a query to the user, if it is
1079 OK to kill that hidden subtree. When nil, kill without remorse."
1080 :group 'org-edit-structure
1081 :version "24.1"
1082 :type '(choice
1083 (const :tag "Do not protect hidden subtrees" nil)
1084 (const :tag "Protect hidden subtrees with a security query" t)
1085 (const :tag "Never kill a hidden subtree with C-k" error)))
1087 (defcustom org-catch-invisible-edits nil
1088 "Check if in invisible region before inserting or deleting a character.
1089 Valid values are:
1091 nil Do not check, so just do invisible edits.
1092 error Throw an error and do nothing.
1093 show Make point visible, and do the requested edit.
1094 show-and-error Make point visible, then throw an error and abort the edit.
1095 smart Make point visible, and do insertion/deletion if it is
1096 adjacent to visible text and the change feels predictable.
1097 Never delete a previously invisible character or add in the
1098 middle or right after an invisible region. Basically, this
1099 allows insertion and backward-delete right before ellipses.
1100 FIXME: maybe in this case we should not even show?"
1101 :group 'org-edit-structure
1102 :version "24.1"
1103 :type '(choice
1104 (const :tag "Do not check" nil)
1105 (const :tag "Throw error when trying to edit" error)
1106 (const :tag "Unhide, but do not do the edit" show-and-error)
1107 (const :tag "Show invisible part and do the edit" show)
1108 (const :tag "Be smart and do the right thing" smart)))
1110 (defcustom org-yank-folded-subtrees t
1111 "Non-nil means when yanking subtrees, fold them.
1112 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1113 it starts with a heading and all other headings in it are either children
1114 or siblings, then fold all the subtrees. However, do this only if no
1115 text after the yank would be swallowed into a folded tree by this action."
1116 :group 'org-edit-structure
1117 :type 'boolean)
1119 (defcustom org-yank-adjusted-subtrees nil
1120 "Non-nil means when yanking subtrees, adjust the level.
1121 With this setting, `org-paste-subtree' is used to insert the subtree, see
1122 this function for details."
1123 :group 'org-edit-structure
1124 :type 'boolean)
1126 (defcustom org-M-RET-may-split-line '((default . t))
1127 "Non-nil means M-RET will split the line at the cursor position.
1128 When nil, it will go to the end of the line before making a
1129 new line.
1130 You may also set this option in a different way for different
1131 contexts. Valid contexts are:
1133 headline when creating a new headline
1134 item when creating a new item
1135 table in a table field
1136 default the value to be used for all contexts not explicitly
1137 customized"
1138 :group 'org-structure
1139 :group 'org-table
1140 :type '(choice
1141 (const :tag "Always" t)
1142 (const :tag "Never" nil)
1143 (repeat :greedy t :tag "Individual contexts"
1144 (cons
1145 (choice :tag "Context"
1146 (const headline)
1147 (const item)
1148 (const table)
1149 (const default))
1150 (boolean)))))
1153 (defcustom org-insert-heading-respect-content nil
1154 "Non-nil means insert new headings after the current subtree.
1155 When nil, the new heading is created directly after the current line.
1156 The commands \\[org-insert-heading-respect-content] and
1157 \\[org-insert-todo-heading-respect-content] turn this variable on
1158 for the duration of the command."
1159 :group 'org-structure
1160 :type 'boolean)
1162 (defcustom org-blank-before-new-entry '((heading . auto)
1163 (plain-list-item . auto))
1164 "Should `org-insert-heading' leave a blank line before new heading/item?
1165 The value is an alist, with `heading' and `plain-list-item' as CAR,
1166 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1167 which case Org will look at the surrounding headings/items and try to
1168 make an intelligent decision whether to insert a blank line or not.
1170 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1171 set, the setting here is ignored and no empty line is inserted, to avoid
1172 breaking the list structure."
1173 :group 'org-edit-structure
1174 :type '(list
1175 (cons (const heading)
1176 (choice (const :tag "Never" nil)
1177 (const :tag "Always" t)
1178 (const :tag "Auto" auto)))
1179 (cons (const plain-list-item)
1180 (choice (const :tag "Never" nil)
1181 (const :tag "Always" t)
1182 (const :tag "Auto" auto)))))
1184 (defcustom org-insert-heading-hook nil
1185 "Hook being run after inserting a new heading."
1186 :group 'org-edit-structure
1187 :type 'hook)
1189 (defcustom org-enable-fixed-width-editor t
1190 "Non-nil means lines starting with \":\" are treated as fixed-width.
1191 This currently only means they are never auto-wrapped.
1192 When nil, such lines will be treated like ordinary lines.
1193 See also the QUOTE keyword."
1194 :group 'org-edit-structure
1195 :type 'boolean)
1197 (defcustom org-goto-auto-isearch t
1198 "Non-nil means typing characters in `org-goto' starts incremental search."
1199 :group 'org-edit-structure
1200 :type 'boolean)
1202 (defgroup org-sparse-trees nil
1203 "Options concerning sparse trees in Org-mode."
1204 :tag "Org Sparse Trees"
1205 :group 'org-structure)
1207 (defcustom org-highlight-sparse-tree-matches t
1208 "Non-nil means highlight all matches that define a sparse tree.
1209 The highlights will automatically disappear the next time the buffer is
1210 changed by an edit command."
1211 :group 'org-sparse-trees
1212 :type 'boolean)
1214 (defcustom org-remove-highlights-with-change t
1215 "Non-nil means any change to the buffer will remove temporary highlights.
1216 Such highlights are created by `org-occur' and `org-clock-display'.
1217 When nil, `C-c C-c needs to be used to get rid of the highlights.
1218 The highlights created by `org-preview-latex-fragment' always need
1219 `C-c C-c' to be removed."
1220 :group 'org-sparse-trees
1221 :group 'org-time
1222 :type 'boolean)
1225 (defcustom org-occur-hook '(org-first-headline-recenter)
1226 "Hook that is run after `org-occur' has constructed a sparse tree.
1227 This can be used to recenter the window to show as much of the structure
1228 as possible."
1229 :group 'org-sparse-trees
1230 :type 'hook)
1232 (defgroup org-imenu-and-speedbar nil
1233 "Options concerning imenu and speedbar in Org-mode."
1234 :tag "Org Imenu and Speedbar"
1235 :group 'org-structure)
1237 (defcustom org-imenu-depth 2
1238 "The maximum level for Imenu access to Org-mode headlines.
1239 This also applied for speedbar access."
1240 :group 'org-imenu-and-speedbar
1241 :type 'integer)
1243 (defgroup org-table nil
1244 "Options concerning tables in Org-mode."
1245 :tag "Org Table"
1246 :group 'org)
1248 (defcustom org-enable-table-editor 'optimized
1249 "Non-nil means lines starting with \"|\" are handled by the table editor.
1250 When nil, such lines will be treated like ordinary lines.
1252 When equal to the symbol `optimized', the table editor will be optimized to
1253 do the following:
1254 - Automatic overwrite mode in front of whitespace in table fields.
1255 This makes the structure of the table stay in tact as long as the edited
1256 field does not exceed the column width.
1257 - Minimize the number of realigns. Normally, the table is aligned each time
1258 TAB or RET are pressed to move to another field. With optimization this
1259 happens only if changes to a field might have changed the column width.
1260 Optimization requires replacing the functions `self-insert-command',
1261 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1262 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1263 very good at guessing when a re-align will be necessary, but you can always
1264 force one with \\[org-ctrl-c-ctrl-c].
1266 If you would like to use the optimized version in Org-mode, but the
1267 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1269 This variable can be used to turn on and off the table editor during a session,
1270 but in order to toggle optimization, a restart is required.
1272 See also the variable `org-table-auto-blank-field'."
1273 :group 'org-table
1274 :type '(choice
1275 (const :tag "off" nil)
1276 (const :tag "on" t)
1277 (const :tag "on, optimized" optimized)))
1279 (defcustom org-self-insert-cluster-for-undo t
1280 "Non-nil means cluster self-insert commands for undo when possible.
1281 If this is set, then, like in the Emacs command loop, 20 consecutive
1282 characters will be undone together.
1283 This is configurable, because there is some impact on typing performance."
1284 :group 'org-table
1285 :type 'boolean)
1287 (defcustom org-table-tab-recognizes-table.el t
1288 "Non-nil means TAB will automatically notice a table.el table.
1289 When it sees such a table, it moves point into it and - if necessary -
1290 calls `table-recognize-table'."
1291 :group 'org-table-editing
1292 :type 'boolean)
1294 (defgroup org-link nil
1295 "Options concerning links in Org-mode."
1296 :tag "Org Link"
1297 :group 'org)
1299 (defvar org-link-abbrev-alist-local nil
1300 "Buffer-local version of `org-link-abbrev-alist', which see.
1301 The value of this is taken from the #+LINK lines.")
1302 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1304 (defcustom org-link-abbrev-alist nil
1305 "Alist of link abbreviations.
1306 The car of each element is a string, to be replaced at the start of a link.
1307 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1308 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1310 [[linkkey:tag][description]]
1312 The 'linkkey' must be a word word, starting with a letter, followed
1313 by letters, numbers, '-' or '_'.
1315 If REPLACE is a string, the tag will simply be appended to create the link.
1316 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1317 the placeholder \"%h\" will cause a url-encoded version of the tag to
1318 be inserted at that point (see the function `url-hexify-string').
1320 REPLACE may also be a function that will be called with the tag as the
1321 only argument to create the link, which should be returned as a string.
1323 See the manual for examples."
1324 :group 'org-link
1325 :type '(repeat
1326 (cons
1327 (string :tag "Protocol")
1328 (choice
1329 (string :tag "Format")
1330 (function)))))
1332 (defcustom org-descriptive-links t
1333 "Non-nil means Org will display descriptive links.
1334 E.g. [[http://orgmode.org][Org website]] will be displayed as
1335 \"Org Website\", hiding the link itself and just displaying its
1336 description. When set to `nil', Org will display the full links
1337 literally.
1339 You can interactively set the value of this variable by calling
1340 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1341 :group 'org-link
1342 :type 'boolean)
1344 (defcustom org-link-file-path-type 'adaptive
1345 "How the path name in file links should be stored.
1346 Valid values are:
1348 relative Relative to the current directory, i.e. the directory of the file
1349 into which the link is being inserted.
1350 absolute Absolute path, if possible with ~ for home directory.
1351 noabbrev Absolute path, no abbreviation of home directory.
1352 adaptive Use relative path for files in the current directory and sub-
1353 directories of it. For other files, use an absolute path."
1354 :group 'org-link
1355 :type '(choice
1356 (const relative)
1357 (const absolute)
1358 (const noabbrev)
1359 (const adaptive)))
1361 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1362 "Types of links that should be activated in Org-mode files.
1363 This is a list of symbols, each leading to the activation of a certain link
1364 type. In principle, it does not hurt to turn on most link types - there may
1365 be a small gain when turning off unused link types. The types are:
1367 bracket The recommended [[link][description]] or [[link]] links with hiding.
1368 angle Links in angular brackets that may contain whitespace like
1369 <bbdb:Carsten Dominik>.
1370 plain Plain links in normal text, no whitespace, like http://google.com.
1371 radio Text that is matched by a radio target, see manual for details.
1372 tag Tag settings in a headline (link to tag search).
1373 date Time stamps (link to calendar).
1374 footnote Footnote labels.
1376 Changing this variable requires a restart of Emacs to become effective."
1377 :group 'org-link
1378 :type '(set :greedy t
1379 (const :tag "Double bracket links" bracket)
1380 (const :tag "Angular bracket links" angle)
1381 (const :tag "Plain text links" plain)
1382 (const :tag "Radio target matches" radio)
1383 (const :tag "Tags" tag)
1384 (const :tag "Timestamps" date)
1385 (const :tag "Footnotes" footnote)))
1387 (defcustom org-make-link-description-function nil
1388 "Function to use to generate link descriptions from links.
1389 If nil the link location will be used. This function must take
1390 two parameters; the first is the link and the second the
1391 description `org-insert-link' has generated, and should return the
1392 description to use."
1393 :group 'org-link
1394 :type 'function)
1396 (defgroup org-link-store nil
1397 "Options concerning storing links in Org-mode."
1398 :tag "Org Store Link"
1399 :group 'org-link)
1401 (defcustom org-email-link-description-format "Email %c: %.30s"
1402 "Format of the description part of a link to an email or usenet message.
1403 The following %-escapes will be replaced by corresponding information:
1405 %F full \"From\" field
1406 %f name, taken from \"From\" field, address if no name
1407 %T full \"To\" field
1408 %t first name in \"To\" field, address if no name
1409 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1410 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1411 %s subject
1412 %d date
1413 %m message-id.
1415 You may use normal field width specification between the % and the letter.
1416 This is for example useful to limit the length of the subject.
1418 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1419 :group 'org-link-store
1420 :type 'string)
1422 (defcustom org-from-is-user-regexp
1423 (let (r1 r2)
1424 (when (and user-mail-address (not (string= user-mail-address "")))
1425 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1426 (when (and user-full-name (not (string= user-full-name "")))
1427 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1428 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1429 "Regexp matched against the \"From:\" header of an email or usenet message.
1430 It should match if the message is from the user him/herself."
1431 :group 'org-link-store
1432 :type 'regexp)
1434 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1435 "Non-nil means storing a link to an Org file will use entry IDs.
1437 Note that before this variable is even considered, org-id must be loaded,
1438 so please customize `org-modules' and turn it on.
1440 The variable can have the following values:
1442 t Create an ID if needed to make a link to the current entry.
1444 create-if-interactive
1445 If `org-store-link' is called directly (interactively, as a user
1446 command), do create an ID to support the link. But when doing the
1447 job for remember, only use the ID if it already exists. The
1448 purpose of this setting is to avoid proliferation of unwanted
1449 IDs, just because you happen to be in an Org file when you
1450 call `org-remember' that automatically and preemptively
1451 creates a link. If you do want to get an ID link in a remember
1452 template to an entry not having an ID, create it first by
1453 explicitly creating a link to it, using `C-c C-l' first.
1455 create-if-interactive-and-no-custom-id
1456 Like create-if-interactive, but do not create an ID if there is
1457 a CUSTOM_ID property defined in the entry. This is the default.
1459 use-existing
1460 Use existing ID, do not create one.
1462 nil Never use an ID to make a link, instead link using a text search for
1463 the headline text."
1464 :group 'org-link-store
1465 :type '(choice
1466 (const :tag "Create ID to make link" t)
1467 (const :tag "Create if storing link interactively"
1468 create-if-interactive)
1469 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1470 create-if-interactive-and-no-custom-id)
1471 (const :tag "Only use existing" use-existing)
1472 (const :tag "Do not use ID to create link" nil)))
1474 (defcustom org-context-in-file-links t
1475 "Non-nil means file links from `org-store-link' contain context.
1476 A search string will be added to the file name with :: as separator and
1477 used to find the context when the link is activated by the command
1478 `org-open-at-point'. When this option is t, the entire active region
1479 will be placed in the search string of the file link. If set to a
1480 positive integer, only the first n lines of context will be stored.
1482 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1483 negates this setting for the duration of the command."
1484 :group 'org-link-store
1485 :type '(choice boolean integer))
1487 (defcustom org-keep-stored-link-after-insertion nil
1488 "Non-nil means keep link in list for entire session.
1490 The command `org-store-link' adds a link pointing to the current
1491 location to an internal list. These links accumulate during a session.
1492 The command `org-insert-link' can be used to insert links into any
1493 Org-mode file (offering completion for all stored links). When this
1494 option is nil, every link which has been inserted once using \\[org-insert-link]
1495 will be removed from the list, to make completing the unused links
1496 more efficient."
1497 :group 'org-link-store
1498 :type 'boolean)
1500 (defgroup org-link-follow nil
1501 "Options concerning following links in Org-mode."
1502 :tag "Org Follow Link"
1503 :group 'org-link)
1505 (defcustom org-link-translation-function nil
1506 "Function to translate links with different syntax to Org syntax.
1507 This can be used to translate links created for example by the Planner
1508 or emacs-wiki packages to Org syntax.
1509 The function must accept two parameters, a TYPE containing the link
1510 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1511 which is everything after the link protocol. It should return a cons
1512 with possibly modified values of type and path.
1513 Org contains a function for this, so if you set this variable to
1514 `org-translate-link-from-planner', you should be able follow many
1515 links created by planner."
1516 :group 'org-link-follow
1517 :type 'function)
1519 (defcustom org-follow-link-hook nil
1520 "Hook that is run after a link has been followed."
1521 :group 'org-link-follow
1522 :type 'hook)
1524 (defcustom org-tab-follows-link nil
1525 "Non-nil means on links TAB will follow the link.
1526 Needs to be set before org.el is loaded.
1527 This really should not be used, it does not make sense, and the
1528 implementation is bad."
1529 :group 'org-link-follow
1530 :type 'boolean)
1532 (defcustom org-return-follows-link nil
1533 "Non-nil means on links RET will follow the link."
1534 :group 'org-link-follow
1535 :type 'boolean)
1537 (defcustom org-mouse-1-follows-link
1538 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1539 "Non-nil means mouse-1 on a link will follow the link.
1540 A longer mouse click will still set point. Does not work on XEmacs.
1541 Needs to be set before org.el is loaded."
1542 :group 'org-link-follow
1543 :type 'boolean)
1545 (defcustom org-mark-ring-length 4
1546 "Number of different positions to be recorded in the ring.
1547 Changing this requires a restart of Emacs to work correctly."
1548 :group 'org-link-follow
1549 :type 'integer)
1551 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1552 "Non-nil means internal links in Org files must exactly match a headline.
1553 When nil, the link search tries to match a phrase with all words
1554 in the search text."
1555 :group 'org-link-follow
1556 :version "24.1"
1557 :type '(choice
1558 (const :tag "Use fuzzy text search" nil)
1559 (const :tag "Match only exact headline" t)
1560 (const :tag "Match exact headline or query to create it"
1561 query-to-create)))
1563 (defcustom org-link-frame-setup
1564 '((vm . vm-visit-folder-other-frame)
1565 (vm-imap . vm-visit-imap-folder-other-frame)
1566 (gnus . org-gnus-no-new-news)
1567 (file . find-file-other-window)
1568 (wl . wl-other-frame))
1569 "Setup the frame configuration for following links.
1570 When following a link with Emacs, it may often be useful to display
1571 this link in another window or frame. This variable can be used to
1572 set this up for the different types of links.
1573 For VM, use any of
1574 `vm-visit-folder'
1575 `vm-visit-folder-other-window'
1576 `vm-visit-folder-other-frame'
1577 For Gnus, use any of
1578 `gnus'
1579 `gnus-other-frame'
1580 `org-gnus-no-new-news'
1581 For FILE, use any of
1582 `find-file'
1583 `find-file-other-window'
1584 `find-file-other-frame'
1585 For Wanderlust use any of
1586 `wl'
1587 `wl-other-frame'
1588 For the calendar, use the variable `calendar-setup'.
1589 For BBDB, it is currently only possible to display the matches in
1590 another window."
1591 :group 'org-link-follow
1592 :type '(list
1593 (cons (const vm)
1594 (choice
1595 (const vm-visit-folder)
1596 (const vm-visit-folder-other-window)
1597 (const vm-visit-folder-other-frame)))
1598 (cons (const gnus)
1599 (choice
1600 (const gnus)
1601 (const gnus-other-frame)
1602 (const org-gnus-no-new-news)))
1603 (cons (const file)
1604 (choice
1605 (const find-file)
1606 (const find-file-other-window)
1607 (const find-file-other-frame)))
1608 (cons (const wl)
1609 (choice
1610 (const wl)
1611 (const wl-other-frame)))))
1613 (defcustom org-display-internal-link-with-indirect-buffer nil
1614 "Non-nil means use indirect buffer to display infile links.
1615 Activating internal links (from one location in a file to another location
1616 in the same file) normally just jumps to the location. When the link is
1617 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1618 is displayed in
1619 another window. When this option is set, the other window actually displays
1620 an indirect buffer clone of the current buffer, to avoid any visibility
1621 changes to the current buffer."
1622 :group 'org-link-follow
1623 :type 'boolean)
1625 (defcustom org-open-non-existing-files nil
1626 "Non-nil means `org-open-file' will open non-existing files.
1627 When nil, an error will be generated.
1628 This variable applies only to external applications because they
1629 might choke on non-existing files. If the link is to a file that
1630 will be opened in Emacs, the variable is ignored."
1631 :group 'org-link-follow
1632 :type 'boolean)
1634 (defcustom org-open-directory-means-index-dot-org nil
1635 "Non-nil means a link to a directory really means to index.org.
1636 When nil, following a directory link will run dired or open a finder/explorer
1637 window on that directory."
1638 :group 'org-link-follow
1639 :type 'boolean)
1641 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1642 "Function and arguments to call for following mailto links.
1643 This is a list with the first element being a Lisp function, and the
1644 remaining elements being arguments to the function. In string arguments,
1645 %a will be replaced by the address, and %s will be replaced by the subject
1646 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1647 :group 'org-link-follow
1648 :type '(choice
1649 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1650 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1651 (const :tag "message-mail" (message-mail "%a" "%s"))
1652 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1654 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1655 "Non-nil means ask for confirmation before executing shell links.
1656 Shell links can be dangerous: just think about a link
1658 [[shell:rm -rf ~/*][Google Search]]
1660 This link would show up in your Org-mode document as \"Google Search\",
1661 but really it would remove your entire home directory.
1662 Therefore we advise against setting this variable to nil.
1663 Just change it to `y-or-n-p' if you want to confirm with a
1664 single keystroke rather than having to type \"yes\"."
1665 :group 'org-link-follow
1666 :type '(choice
1667 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1668 (const :tag "with y-or-n (faster)" y-or-n-p)
1669 (const :tag "no confirmation (dangerous)" nil)))
1670 (put 'org-confirm-shell-link-function
1671 'safe-local-variable
1672 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1674 (defcustom org-confirm-shell-link-not-regexp ""
1675 "A regexp to skip confirmation for shell links."
1676 :group 'org-link-follow
1677 :version "24.1"
1678 :type 'regexp)
1680 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1681 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1682 Elisp links can be dangerous: just think about a link
1684 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1686 This link would show up in your Org-mode document as \"Google Search\",
1687 but really it would remove your entire home directory.
1688 Therefore we advise against setting this variable to nil.
1689 Just change it to `y-or-n-p' if you want to confirm with a
1690 single keystroke rather than having to type \"yes\"."
1691 :group 'org-link-follow
1692 :type '(choice
1693 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1694 (const :tag "with y-or-n (faster)" y-or-n-p)
1695 (const :tag "no confirmation (dangerous)" nil)))
1696 (put 'org-confirm-shell-link-function
1697 'safe-local-variable
1698 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1700 (defcustom org-confirm-elisp-link-not-regexp ""
1701 "A regexp to skip confirmation for Elisp links."
1702 :group 'org-link-follow
1703 :version "24.1"
1704 :type 'regexp)
1706 (defconst org-file-apps-defaults-gnu
1707 '((remote . emacs)
1708 (system . mailcap)
1709 (t . mailcap))
1710 "Default file applications on a UNIX or GNU/Linux system.
1711 See `org-file-apps'.")
1713 (defconst org-file-apps-defaults-macosx
1714 '((remote . emacs)
1715 (t . "open %s")
1716 (system . "open %s")
1717 ("ps.gz" . "gv %s")
1718 ("eps.gz" . "gv %s")
1719 ("dvi" . "xdvi %s")
1720 ("fig" . "xfig %s"))
1721 "Default file applications on a MacOS X system.
1722 The system \"open\" is known as a default, but we use X11 applications
1723 for some files for which the OS does not have a good default.
1724 See `org-file-apps'.")
1726 (defconst org-file-apps-defaults-windowsnt
1727 (list
1728 '(remote . emacs)
1729 (cons t
1730 (list (if (featurep 'xemacs)
1731 'mswindows-shell-execute
1732 'w32-shell-execute)
1733 "open" 'file))
1734 (cons 'system
1735 (list (if (featurep 'xemacs)
1736 'mswindows-shell-execute
1737 'w32-shell-execute)
1738 "open" 'file)))
1739 "Default file applications on a Windows NT system.
1740 The system \"open\" is used for most files.
1741 See `org-file-apps'.")
1743 (defcustom org-file-apps
1745 (auto-mode . emacs)
1746 ("\\.mm\\'" . default)
1747 ("\\.x?html?\\'" . default)
1748 ("\\.pdf\\'" . default)
1750 "External applications for opening `file:path' items in a document.
1751 Org-mode uses system defaults for different file types, but
1752 you can use this variable to set the application for a given file
1753 extension. The entries in this list are cons cells where the car identifies
1754 files and the cdr the corresponding command. Possible values for the
1755 file identifier are
1756 \"string\" A string as a file identifier can be interpreted in different
1757 ways, depending on its contents:
1759 - Alphanumeric characters only:
1760 Match links with this file extension.
1761 Example: (\"pdf\" . \"evince %s\")
1762 to open PDFs with evince.
1764 - Regular expression: Match links where the
1765 filename matches the regexp. If you want to
1766 use groups here, use shy groups.
1768 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1769 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1770 to open *.html and *.xhtml with firefox.
1772 - Regular expression which contains (non-shy) groups:
1773 Match links where the whole link, including \"::\", and
1774 anything after that, matches the regexp.
1775 In a custom command string, %1, %2, etc. are replaced with
1776 the parts of the link that were matched by the groups.
1777 For backwards compatibility, if a command string is given
1778 that does not use any of the group matches, this case is
1779 handled identically to the second one (i.e. match against
1780 file name only).
1781 In a custom lisp form, you can access the group matches with
1782 (match-string n link).
1784 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1785 to open [[file:document.pdf::5]] with evince at page 5.
1787 `directory' Matches a directory
1788 `remote' Matches a remote file, accessible through tramp or efs.
1789 Remote files most likely should be visited through Emacs
1790 because external applications cannot handle such paths.
1791 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1792 so all files Emacs knows how to handle. Using this with
1793 command `emacs' will open most files in Emacs. Beware that this
1794 will also open html files inside Emacs, unless you add
1795 (\"html\" . default) to the list as well.
1796 t Default for files not matched by any of the other options.
1797 `system' The system command to open files, like `open' on Windows
1798 and Mac OS X, and mailcap under GNU/Linux. This is the command
1799 that will be selected if you call `C-c C-o' with a double
1800 \\[universal-argument] \\[universal-argument] prefix.
1802 Possible values for the command are:
1803 `emacs' The file will be visited by the current Emacs process.
1804 `default' Use the default application for this file type, which is the
1805 association for t in the list, most likely in the system-specific
1806 part.
1807 This can be used to overrule an unwanted setting in the
1808 system-specific variable.
1809 `system' Use the system command for opening files, like \"open\".
1810 This command is specified by the entry whose car is `system'.
1811 Most likely, the system-specific version of this variable
1812 does define this command, but you can overrule/replace it
1813 here.
1814 string A command to be executed by a shell; %s will be replaced
1815 by the path to the file.
1816 sexp A Lisp form which will be evaluated. The file path will
1817 be available in the Lisp variable `file'.
1818 For more examples, see the system specific constants
1819 `org-file-apps-defaults-macosx'
1820 `org-file-apps-defaults-windowsnt'
1821 `org-file-apps-defaults-gnu'."
1822 :group 'org-link-follow
1823 :type '(repeat
1824 (cons (choice :value ""
1825 (string :tag "Extension")
1826 (const :tag "System command to open files" system)
1827 (const :tag "Default for unrecognized files" t)
1828 (const :tag "Remote file" remote)
1829 (const :tag "Links to a directory" directory)
1830 (const :tag "Any files that have Emacs modes"
1831 auto-mode))
1832 (choice :value ""
1833 (const :tag "Visit with Emacs" emacs)
1834 (const :tag "Use default" default)
1835 (const :tag "Use the system command" system)
1836 (string :tag "Command")
1837 (sexp :tag "Lisp form")))))
1841 (defgroup org-refile nil
1842 "Options concerning refiling entries in Org-mode."
1843 :tag "Org Refile"
1844 :group 'org)
1846 (defcustom org-directory "~/org"
1847 "Directory with org files.
1848 This is just a default location to look for Org files. There is no need
1849 at all to put your files into this directory. It is only used in the
1850 following situations:
1852 1. When a remember template specifies a target file that is not an
1853 absolute path. The path will then be interpreted relative to
1854 `org-directory'
1855 2. When a remember note is filed away in an interactive way (when exiting the
1856 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1857 with `org-directory' as the default path."
1858 :group 'org-refile
1859 :group 'org-remember
1860 :type 'directory)
1862 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1863 "Default target for storing notes.
1864 Used as a fall back file for org-remember.el and org-capture.el, for
1865 templates that do not specify a target file."
1866 :group 'org-refile
1867 :group 'org-remember
1868 :type '(choice
1869 (const :tag "Default from remember-data-file" nil)
1870 file))
1872 (defcustom org-goto-interface 'outline
1873 "The default interface to be used for `org-goto'.
1874 Allowed values are:
1875 outline The interface shows an outline of the relevant file
1876 and the correct heading is found by moving through
1877 the outline or by searching with incremental search.
1878 outline-path-completion Headlines in the current buffer are offered via
1879 completion. This is the interface also used by
1880 the refile command."
1881 :group 'org-refile
1882 :type '(choice
1883 (const :tag "Outline" outline)
1884 (const :tag "Outline-path-completion" outline-path-completion)))
1886 (defcustom org-goto-max-level 5
1887 "Maximum target level when running `org-goto' with refile interface."
1888 :group 'org-refile
1889 :type 'integer)
1891 (defcustom org-reverse-note-order nil
1892 "Non-nil means store new notes at the beginning of a file or entry.
1893 When nil, new notes will be filed to the end of a file or entry.
1894 This can also be a list with cons cells of regular expressions that
1895 are matched against file names, and values."
1896 :group 'org-remember
1897 :group 'org-refile
1898 :type '(choice
1899 (const :tag "Reverse always" t)
1900 (const :tag "Reverse never" nil)
1901 (repeat :tag "By file name regexp"
1902 (cons regexp boolean))))
1904 (defcustom org-log-refile nil
1905 "Information to record when a task is refiled.
1907 Possible values are:
1909 nil Don't add anything
1910 time Add a time stamp to the task
1911 note Prompt for a note and add it with template `org-log-note-headings'
1913 This option can also be set with on a per-file-basis with
1915 #+STARTUP: nologrefile
1916 #+STARTUP: logrefile
1917 #+STARTUP: lognoterefile
1919 You can have local logging settings for a subtree by setting the LOGGING
1920 property to one or more of these keywords.
1922 When bulk-refiling from the agenda, the value `note' is forbidden and
1923 will temporarily be changed to `time'."
1924 :group 'org-refile
1925 :group 'org-progress
1926 :version "24.1"
1927 :type '(choice
1928 (const :tag "No logging" nil)
1929 (const :tag "Record timestamp" time)
1930 (const :tag "Record timestamp with note." note)))
1932 (defcustom org-refile-targets nil
1933 "Targets for refiling entries with \\[org-refile].
1934 This is a list of cons cells. Each cell contains:
1935 - a specification of the files to be considered, either a list of files,
1936 or a symbol whose function or variable value will be used to retrieve
1937 a file name or a list of file names. If you use `org-agenda-files' for
1938 that, all agenda files will be scanned for targets. Nil means consider
1939 headings in the current buffer.
1940 - A specification of how to find candidate refile targets. This may be
1941 any of:
1942 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1943 This tag has to be present in all target headlines, inheritance will
1944 not be considered.
1945 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1946 todo keyword.
1947 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1948 headlines that are refiling targets.
1949 - a cons cell (:level . N). Any headline of level N is considered a target.
1950 Note that, when `org-odd-levels-only' is set, level corresponds to
1951 order in hierarchy, not to the number of stars.
1952 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1953 Note that, when `org-odd-levels-only' is set, level corresponds to
1954 order in hierarchy, not to the number of stars.
1956 Each element of this list generates a set of possible targets.
1957 The union of these sets is presented (with completion) to
1958 the user by `org-refile'.
1960 You can set the variable `org-refile-target-verify-function' to a function
1961 to verify each headline found by the simple criteria above.
1963 When this variable is nil, all top-level headlines in the current buffer
1964 are used, equivalent to the value `((nil . (:level . 1))'."
1965 :group 'org-refile
1966 :type '(repeat
1967 (cons
1968 (choice :value org-agenda-files
1969 (const :tag "All agenda files" org-agenda-files)
1970 (const :tag "Current buffer" nil)
1971 (function) (variable) (file))
1972 (choice :tag "Identify target headline by"
1973 (cons :tag "Specific tag" (const :value :tag) (string))
1974 (cons :tag "TODO keyword" (const :value :todo) (string))
1975 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1976 (cons :tag "Level number" (const :value :level) (integer))
1977 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1979 (defcustom org-refile-target-verify-function nil
1980 "Function to verify if the headline at point should be a refile target.
1981 The function will be called without arguments, with point at the
1982 beginning of the headline. It should return t and leave point
1983 where it is if the headline is a valid target for refiling.
1985 If the target should not be selected, the function must return nil.
1986 In addition to this, it may move point to a place from where the search
1987 should be continued. For example, the function may decide that the entire
1988 subtree of the current entry should be excluded and move point to the end
1989 of the subtree."
1990 :group 'org-refile
1991 :type 'function)
1993 (defcustom org-refile-use-cache nil
1994 "Non-nil means cache refile targets to speed up the process.
1995 The cache for a particular file will be updated automatically when
1996 the buffer has been killed, or when any of the marker used for flagging
1997 refile targets no longer points at a live buffer.
1998 If you have added new entries to a buffer that might themselves be targets,
1999 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2000 find that easier, `C-u C-u C-u C-c C-w'."
2001 :group 'org-refile
2002 :version "24.1"
2003 :type 'boolean)
2005 (defcustom org-refile-use-outline-path nil
2006 "Non-nil means provide refile targets as paths.
2007 So a level 3 headline will be available as level1/level2/level3.
2009 When the value is `file', also include the file name (without directory)
2010 into the path. In this case, you can also stop the completion after
2011 the file name, to get entries inserted as top level in the file.
2013 When `full-file-path', include the full file path."
2014 :group 'org-refile
2015 :type '(choice
2016 (const :tag "Not" nil)
2017 (const :tag "Yes" t)
2018 (const :tag "Start with file name" file)
2019 (const :tag "Start with full file path" full-file-path)))
2021 (defcustom org-outline-path-complete-in-steps t
2022 "Non-nil means complete the outline path in hierarchical steps.
2023 When Org-mode uses the refile interface to select an outline path
2024 \(see variable `org-refile-use-outline-path'), the completion of
2025 the path can be done is a single go, or if can be done in steps down
2026 the headline hierarchy. Going in steps is probably the best if you
2027 do not use a special completion package like `ido' or `icicles'.
2028 However, when using these packages, going in one step can be very
2029 fast, while still showing the whole path to the entry."
2030 :group 'org-refile
2031 :type 'boolean)
2033 (defcustom org-refile-allow-creating-parent-nodes nil
2034 "Non-nil means allow to create new nodes as refile targets.
2035 New nodes are then created by adding \"/new node name\" to the completion
2036 of an existing node. When the value of this variable is `confirm',
2037 new node creation must be confirmed by the user (recommended)
2038 When nil, the completion must match an existing entry.
2040 Note that, if the new heading is not seen by the criteria
2041 listed in `org-refile-targets', multiple instances of the same
2042 heading would be created by trying again to file under the new
2043 heading."
2044 :group 'org-refile
2045 :type '(choice
2046 (const :tag "Never" nil)
2047 (const :tag "Always" t)
2048 (const :tag "Prompt for confirmation" confirm)))
2050 (defcustom org-refile-active-region-within-subtree nil
2051 "Non-nil means also refile active region within a subtree.
2053 By default `org-refile' doesn't allow refiling regions if they
2054 don't contain a set of subtrees, but it might be convenient to
2055 do so sometimes: in that case, the first line of the region is
2056 converted to a headline before refiling."
2057 :group 'org-refile
2058 :version "24.1"
2059 :type 'boolean)
2061 (defgroup org-todo nil
2062 "Options concerning TODO items in Org-mode."
2063 :tag "Org TODO"
2064 :group 'org)
2066 (defgroup org-progress nil
2067 "Options concerning Progress logging in Org-mode."
2068 :tag "Org Progress"
2069 :group 'org-time)
2071 (defvar org-todo-interpretation-widgets
2072 '((:tag "Sequence (cycling hits every state)" sequence)
2073 (:tag "Type (cycling directly to DONE)" type))
2074 "The available interpretation symbols for customizing `org-todo-keywords'.
2075 Interested libraries should add to this list.")
2077 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2078 "List of TODO entry keyword sequences and their interpretation.
2079 \\<org-mode-map>This is a list of sequences.
2081 Each sequence starts with a symbol, either `sequence' or `type',
2082 indicating if the keywords should be interpreted as a sequence of
2083 action steps, or as different types of TODO items. The first
2084 keywords are states requiring action - these states will select a headline
2085 for inclusion into the global TODO list Org-mode produces. If one of
2086 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2087 signify that no further action is necessary. If \"|\" is not found,
2088 the last keyword is treated as the only DONE state of the sequence.
2090 The command \\[org-todo] cycles an entry through these states, and one
2091 additional state where no keyword is present. For details about this
2092 cycling, see the manual.
2094 TODO keywords and interpretation can also be set on a per-file basis with
2095 the special #+SEQ_TODO and #+TYP_TODO lines.
2097 Each keyword can optionally specify a character for fast state selection
2098 \(in combination with the variable `org-use-fast-todo-selection')
2099 and specifiers for state change logging, using the same syntax
2100 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2101 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2102 indicates to record a time stamp each time this state is selected.
2104 Each keyword may also specify if a timestamp or a note should be
2105 recorded when entering or leaving the state, by adding additional
2106 characters in the parenthesis after the keyword. This looks like this:
2107 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2108 record only the time of the state change. With X and Y being either
2109 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2110 Y when leaving the state if and only if the *target* state does not
2111 define X. You may omit any of the fast-selection key or X or /Y,
2112 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2114 For backward compatibility, this variable may also be just a list
2115 of keywords - in this case the interpretation (sequence or type) will be
2116 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2117 :group 'org-todo
2118 :group 'org-keywords
2119 :type '(choice
2120 (repeat :tag "Old syntax, just keywords"
2121 (string :tag "Keyword"))
2122 (repeat :tag "New syntax"
2123 (cons
2124 (choice
2125 :tag "Interpretation"
2126 ;;Quick and dirty way to see
2127 ;;`org-todo-interpretations'. This takes the
2128 ;;place of item arguments
2129 :convert-widget
2130 (lambda (widget)
2131 (widget-put widget
2132 :args (mapcar
2133 #'(lambda (x)
2134 (widget-convert
2135 (cons 'const x)))
2136 org-todo-interpretation-widgets))
2137 widget))
2138 (repeat
2139 (string :tag "Keyword"))))))
2141 (defvar org-todo-keywords-1 nil
2142 "All TODO and DONE keywords active in a buffer.")
2143 (make-variable-buffer-local 'org-todo-keywords-1)
2144 (defvar org-todo-keywords-for-agenda nil)
2145 (defvar org-done-keywords-for-agenda nil)
2146 (defvar org-drawers-for-agenda nil)
2147 (defvar org-todo-keyword-alist-for-agenda nil)
2148 (defvar org-tag-alist-for-agenda nil)
2149 (defvar org-agenda-contributing-files nil)
2150 (defvar org-not-done-keywords nil)
2151 (make-variable-buffer-local 'org-not-done-keywords)
2152 (defvar org-done-keywords nil)
2153 (make-variable-buffer-local 'org-done-keywords)
2154 (defvar org-todo-heads nil)
2155 (make-variable-buffer-local 'org-todo-heads)
2156 (defvar org-todo-sets nil)
2157 (make-variable-buffer-local 'org-todo-sets)
2158 (defvar org-todo-log-states nil)
2159 (make-variable-buffer-local 'org-todo-log-states)
2160 (defvar org-todo-kwd-alist nil)
2161 (make-variable-buffer-local 'org-todo-kwd-alist)
2162 (defvar org-todo-key-alist nil)
2163 (make-variable-buffer-local 'org-todo-key-alist)
2164 (defvar org-todo-key-trigger nil)
2165 (make-variable-buffer-local 'org-todo-key-trigger)
2167 (defcustom org-todo-interpretation 'sequence
2168 "Controls how TODO keywords are interpreted.
2169 This variable is in principle obsolete and is only used for
2170 backward compatibility, if the interpretation of todo keywords is
2171 not given already in `org-todo-keywords'. See that variable for
2172 more information."
2173 :group 'org-todo
2174 :group 'org-keywords
2175 :type '(choice (const sequence)
2176 (const type)))
2178 (defcustom org-use-fast-todo-selection t
2179 "Non-nil means use the fast todo selection scheme with C-c C-t.
2180 This variable describes if and under what circumstances the cycling
2181 mechanism for TODO keywords will be replaced by a single-key, direct
2182 selection scheme.
2184 When nil, fast selection is never used.
2186 When the symbol `prefix', it will be used when `org-todo' is called with
2187 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2188 in an agenda buffer.
2190 When t, fast selection is used by default. In this case, the prefix
2191 argument forces cycling instead.
2193 In all cases, the special interface is only used if access keys have actually
2194 been assigned by the user, i.e. if keywords in the configuration are followed
2195 by a letter in parenthesis, like TODO(t)."
2196 :group 'org-todo
2197 :type '(choice
2198 (const :tag "Never" nil)
2199 (const :tag "By default" t)
2200 (const :tag "Only with C-u C-c C-t" prefix)))
2202 (defcustom org-provide-todo-statistics t
2203 "Non-nil means update todo statistics after insert and toggle.
2204 ALL-HEADLINES means update todo statistics by including headlines
2205 with no TODO keyword as well, counting them as not done.
2206 A list of TODO keywords means the same, but skip keywords that are
2207 not in this list.
2209 When this is set, todo statistics is updated in the parent of the
2210 current entry each time a todo state is changed."
2211 :group 'org-todo
2212 :type '(choice
2213 (const :tag "Yes, only for TODO entries" t)
2214 (const :tag "Yes, including all entries" 'all-headlines)
2215 (repeat :tag "Yes, for TODOs in this list"
2216 (string :tag "TODO keyword"))
2217 (other :tag "No TODO statistics" nil)))
2219 (defcustom org-hierarchical-todo-statistics t
2220 "Non-nil means TODO statistics covers just direct children.
2221 When nil, all entries in the subtree are considered.
2222 This has only an effect if `org-provide-todo-statistics' is set.
2223 To set this to nil for only a single subtree, use a COOKIE_DATA
2224 property and include the word \"recursive\" into the value."
2225 :group 'org-todo
2226 :type 'boolean)
2228 (defcustom org-after-todo-state-change-hook nil
2229 "Hook which is run after the state of a TODO item was changed.
2230 The new state (a string with a TODO keyword, or nil) is available in the
2231 Lisp variable `org-state'."
2232 :group 'org-todo
2233 :type 'hook)
2235 (defvar org-blocker-hook nil
2236 "Hook for functions that are allowed to block a state change.
2238 Each function gets as its single argument a property list, see
2239 `org-trigger-hook' for more information about this list.
2241 If any of the functions in this hook returns nil, the state change
2242 is blocked.")
2244 (defvar org-trigger-hook nil
2245 "Hook for functions that are triggered by a state change.
2247 Each function gets as its single argument a property list with at least
2248 the following elements:
2250 (:type type-of-change :position pos-at-entry-start
2251 :from old-state :to new-state)
2253 Depending on the type, more properties may be present.
2255 This mechanism is currently implemented for:
2257 TODO state changes
2258 ------------------
2259 :type todo-state-change
2260 :from previous state (keyword as a string), or nil, or a symbol
2261 'todo' or 'done', to indicate the general type of state.
2262 :to new state, like in :from")
2264 (defcustom org-enforce-todo-dependencies nil
2265 "Non-nil means undone TODO entries will block switching the parent to DONE.
2266 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2267 be blocked if any prior sibling is not yet done.
2268 Finally, if the parent is blocked because of ordered siblings of its own,
2269 the child will also be blocked."
2270 :set (lambda (var val)
2271 (set var val)
2272 (if val
2273 (add-hook 'org-blocker-hook
2274 'org-block-todo-from-children-or-siblings-or-parent)
2275 (remove-hook 'org-blocker-hook
2276 'org-block-todo-from-children-or-siblings-or-parent)))
2277 :group 'org-todo
2278 :type 'boolean)
2280 (defcustom org-enforce-todo-checkbox-dependencies nil
2281 "Non-nil means unchecked boxes will block switching the parent to DONE.
2282 When this is nil, checkboxes have no influence on switching TODO states.
2283 When non-nil, you first need to check off all check boxes before the TODO
2284 entry can be switched to DONE.
2285 This variable needs to be set before org.el is loaded, and you need to
2286 restart Emacs after a change to make the change effective. The only way
2287 to change is while Emacs is running is through the customize interface."
2288 :set (lambda (var val)
2289 (set var val)
2290 (if val
2291 (add-hook 'org-blocker-hook
2292 'org-block-todo-from-checkboxes)
2293 (remove-hook 'org-blocker-hook
2294 'org-block-todo-from-checkboxes)))
2295 :group 'org-todo
2296 :type 'boolean)
2298 (defcustom org-treat-insert-todo-heading-as-state-change nil
2299 "Non-nil means inserting a TODO heading is treated as state change.
2300 So when the command \\[org-insert-todo-heading] is used, state change
2301 logging will apply if appropriate. When nil, the new TODO item will
2302 be inserted directly, and no logging will take place."
2303 :group 'org-todo
2304 :type 'boolean)
2306 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2307 "Non-nil means switching TODO states with S-cursor counts as state change.
2308 This is the default behavior. However, setting this to nil allows a
2309 convenient way to select a TODO state and bypass any logging associated
2310 with that."
2311 :group 'org-todo
2312 :type 'boolean)
2314 (defcustom org-todo-state-tags-triggers nil
2315 "Tag changes that should be triggered by TODO state changes.
2316 This is a list. Each entry is
2318 (state-change (tag . flag) .......)
2320 State-change can be a string with a state, and empty string to indicate the
2321 state that has no TODO keyword, or it can be one of the symbols `todo'
2322 or `done', meaning any not-done or done state, respectively."
2323 :group 'org-todo
2324 :group 'org-tags
2325 :type '(repeat
2326 (cons (choice :tag "When changing to"
2327 (const :tag "Not-done state" todo)
2328 (const :tag "Done state" done)
2329 (string :tag "State"))
2330 (repeat
2331 (cons :tag "Tag action"
2332 (string :tag "Tag")
2333 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2335 (defcustom org-log-done nil
2336 "Information to record when a task moves to the DONE state.
2338 Possible values are:
2340 nil Don't add anything, just change the keyword
2341 time Add a time stamp to the task
2342 note Prompt for a note and add it with template `org-log-note-headings'
2344 This option can also be set with on a per-file-basis with
2346 #+STARTUP: nologdone
2347 #+STARTUP: logdone
2348 #+STARTUP: lognotedone
2350 You can have local logging settings for a subtree by setting the LOGGING
2351 property to one or more of these keywords."
2352 :group 'org-todo
2353 :group 'org-progress
2354 :type '(choice
2355 (const :tag "No logging" nil)
2356 (const :tag "Record CLOSED timestamp" time)
2357 (const :tag "Record CLOSED timestamp with note." note)))
2359 ;; Normalize old uses of org-log-done.
2360 (cond
2361 ((eq org-log-done t) (setq org-log-done 'time))
2362 ((and (listp org-log-done) (memq 'done org-log-done))
2363 (setq org-log-done 'note)))
2365 (defcustom org-log-reschedule nil
2366 "Information to record when the scheduling date of a tasks is modified.
2368 Possible values are:
2370 nil Don't add anything, just change the date
2371 time Add a time stamp to the task
2372 note Prompt for a note and add it with template `org-log-note-headings'
2374 This option can also be set with on a per-file-basis with
2376 #+STARTUP: nologreschedule
2377 #+STARTUP: logreschedule
2378 #+STARTUP: lognotereschedule"
2379 :group 'org-todo
2380 :group 'org-progress
2381 :type '(choice
2382 (const :tag "No logging" nil)
2383 (const :tag "Record timestamp" time)
2384 (const :tag "Record timestamp with note." note)))
2386 (defcustom org-log-redeadline nil
2387 "Information to record when the deadline date of a tasks is modified.
2389 Possible values are:
2391 nil Don't add anything, just change the date
2392 time Add a time stamp to the task
2393 note Prompt for a note and add it with template `org-log-note-headings'
2395 This option can also be set with on a per-file-basis with
2397 #+STARTUP: nologredeadline
2398 #+STARTUP: logredeadline
2399 #+STARTUP: lognoteredeadline
2401 You can have local logging settings for a subtree by setting the LOGGING
2402 property to one or more of these keywords."
2403 :group 'org-todo
2404 :group 'org-progress
2405 :type '(choice
2406 (const :tag "No logging" nil)
2407 (const :tag "Record timestamp" time)
2408 (const :tag "Record timestamp with note." note)))
2410 (defcustom org-log-note-clock-out nil
2411 "Non-nil means record a note when clocking out of an item.
2412 This can also be configured on a per-file basis by adding one of
2413 the following lines anywhere in the buffer:
2415 #+STARTUP: lognoteclock-out
2416 #+STARTUP: nolognoteclock-out"
2417 :group 'org-todo
2418 :group 'org-progress
2419 :type 'boolean)
2421 (defcustom org-log-done-with-time t
2422 "Non-nil means the CLOSED time stamp will contain date and time.
2423 When nil, only the date will be recorded."
2424 :group 'org-progress
2425 :type 'boolean)
2427 (defcustom org-log-note-headings
2428 '((done . "CLOSING NOTE %t")
2429 (state . "State %-12s from %-12S %t")
2430 (note . "Note taken on %t")
2431 (reschedule . "Rescheduled from %S on %t")
2432 (delschedule . "Not scheduled, was %S on %t")
2433 (redeadline . "New deadline from %S on %t")
2434 (deldeadline . "Removed deadline, was %S on %t")
2435 (refile . "Refiled on %t")
2436 (clock-out . ""))
2437 "Headings for notes added to entries.
2438 The value is an alist, with the car being a symbol indicating the note
2439 context, and the cdr is the heading to be used. The heading may also be the
2440 empty string.
2441 %t in the heading will be replaced by a time stamp.
2442 %T will be an active time stamp instead the default inactive one
2443 %d will be replaced by a short-format time stamp.
2444 %D will be replaced by an active short-format time stamp.
2445 %s will be replaced by the new TODO state, in double quotes.
2446 %S will be replaced by the old TODO state, in double quotes.
2447 %u will be replaced by the user name.
2448 %U will be replaced by the full user name.
2450 In fact, it is not a good idea to change the `state' entry, because
2451 agenda log mode depends on the format of these entries."
2452 :group 'org-todo
2453 :group 'org-progress
2454 :type '(list :greedy t
2455 (cons (const :tag "Heading when closing an item" done) string)
2456 (cons (const :tag
2457 "Heading when changing todo state (todo sequence only)"
2458 state) string)
2459 (cons (const :tag "Heading when just taking a note" note) string)
2460 (cons (const :tag "Heading when clocking out" clock-out) string)
2461 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2462 (cons (const :tag "Heading when rescheduling" reschedule) string)
2463 (cons (const :tag "Heading when changing deadline" redeadline) string)
2464 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2465 (cons (const :tag "Heading when refiling" refile) string)))
2467 (unless (assq 'note org-log-note-headings)
2468 (push '(note . "%t") org-log-note-headings))
2470 (defcustom org-log-into-drawer nil
2471 "Non-nil means insert state change notes and time stamps into a drawer.
2472 When nil, state changes notes will be inserted after the headline and
2473 any scheduling and clock lines, but not inside a drawer.
2475 The value of this variable should be the name of the drawer to use.
2476 LOGBOOK is proposed as the default drawer for this purpose, you can
2477 also set this to a string to define the drawer of your choice.
2479 A value of t is also allowed, representing \"LOGBOOK\".
2481 If this variable is set, `org-log-state-notes-insert-after-drawers'
2482 will be ignored.
2484 You can set the property LOG_INTO_DRAWER to overrule this setting for
2485 a subtree."
2486 :group 'org-todo
2487 :group 'org-progress
2488 :type '(choice
2489 (const :tag "Not into a drawer" nil)
2490 (const :tag "LOGBOOK" t)
2491 (string :tag "Other")))
2493 (if (fboundp 'defvaralias)
2494 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2496 (defun org-log-into-drawer ()
2497 "Return the value of `org-log-into-drawer', but let properties overrule.
2498 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2499 used instead of the default value."
2500 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2501 (cond
2502 ((or (not p) (equal p "nil")) org-log-into-drawer)
2503 ((equal p "t") "LOGBOOK")
2504 (t p))))
2506 (defcustom org-log-state-notes-insert-after-drawers nil
2507 "Non-nil means insert state change notes after any drawers in entry.
2508 Only the drawers that *immediately* follow the headline and the
2509 deadline/scheduled line are skipped.
2510 When nil, insert notes right after the heading and perhaps the line
2511 with deadline/scheduling if present.
2513 This variable will have no effect if `org-log-into-drawer' is
2514 set."
2515 :group 'org-todo
2516 :group 'org-progress
2517 :type 'boolean)
2519 (defcustom org-log-states-order-reversed t
2520 "Non-nil means the latest state note will be directly after heading.
2521 When nil, the state change notes will be ordered according to time."
2522 :group 'org-todo
2523 :group 'org-progress
2524 :type 'boolean)
2526 (defcustom org-todo-repeat-to-state nil
2527 "The TODO state to which a repeater should return the repeating task.
2528 By default this is the first task in a TODO sequence, or the previous state
2529 in a TODO_TYP set. But you can specify another task here.
2530 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2531 :group 'org-todo
2532 :version "24.1"
2533 :type '(choice (const :tag "Head of sequence" nil)
2534 (string :tag "Specific state")))
2536 (defcustom org-log-repeat 'time
2537 "Non-nil means record moving through the DONE state when triggering repeat.
2538 An auto-repeating task is immediately switched back to TODO when
2539 marked DONE. If you are not logging state changes (by adding \"@\"
2540 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2541 record a closing note, there will be no record of the task moving
2542 through DONE. This variable forces taking a note anyway.
2544 nil Don't force a record
2545 time Record a time stamp
2546 note Record a note
2548 This option can also be set with on a per-file-basis with
2550 #+STARTUP: logrepeat
2551 #+STARTUP: lognoterepeat
2552 #+STARTUP: nologrepeat
2554 You can have local logging settings for a subtree by setting the LOGGING
2555 property to one or more of these keywords."
2556 :group 'org-todo
2557 :group 'org-progress
2558 :type '(choice
2559 (const :tag "Don't force a record" nil)
2560 (const :tag "Force recording the DONE state" time)
2561 (const :tag "Force recording a note with the DONE state" note)))
2564 (defgroup org-priorities nil
2565 "Priorities in Org-mode."
2566 :tag "Org Priorities"
2567 :group 'org-todo)
2569 (defcustom org-enable-priority-commands t
2570 "Non-nil means priority commands are active.
2571 When nil, these commands will be disabled, so that you never accidentally
2572 set a priority."
2573 :group 'org-priorities
2574 :type 'boolean)
2576 (defcustom org-highest-priority ?A
2577 "The highest priority of TODO items. A character like ?A, ?B etc.
2578 Must have a smaller ASCII number than `org-lowest-priority'."
2579 :group 'org-priorities
2580 :type 'character)
2582 (defcustom org-lowest-priority ?C
2583 "The lowest priority of TODO items. A character like ?A, ?B etc.
2584 Must have a larger ASCII number than `org-highest-priority'."
2585 :group 'org-priorities
2586 :type 'character)
2588 (defcustom org-default-priority ?B
2589 "The default priority of TODO items.
2590 This is the priority an item gets if no explicit priority is given.
2591 When starting to cycle on an empty priority the first step in the cycle
2592 depends on `org-priority-start-cycle-with-default'. The resulting first
2593 step priority must not exceed the range from `org-highest-priority' to
2594 `org-lowest-priority' which means that `org-default-priority' has to be
2595 in this range exclusive or inclusive the range boundaries. Else the
2596 first step refuses to set the default and the second will fall back
2597 to (depending on the command used) the highest or lowest priority."
2598 :group 'org-priorities
2599 :type 'character)
2601 (defcustom org-priority-start-cycle-with-default t
2602 "Non-nil means start with default priority when starting to cycle.
2603 When this is nil, the first step in the cycle will be (depending on the
2604 command used) one higher or lower than the default priority.
2605 See also `org-default-priority'."
2606 :group 'org-priorities
2607 :type 'boolean)
2609 (defcustom org-get-priority-function nil
2610 "Function to extract the priority from a string.
2611 The string is normally the headline. If this is nil Org computes the
2612 priority from the priority cookie like [#A] in the headline. It returns
2613 an integer, increasing by 1000 for each priority level.
2614 The user can set a different function here, which should take a string
2615 as an argument and return the numeric priority."
2616 :group 'org-priorities
2617 :version "24.1"
2618 :type 'function)
2620 (defgroup org-time nil
2621 "Options concerning time stamps and deadlines in Org-mode."
2622 :tag "Org Time"
2623 :group 'org)
2625 (defcustom org-insert-labeled-timestamps-at-point nil
2626 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2627 When nil, these labeled time stamps are forces into the second line of an
2628 entry, just after the headline. When scheduling from the global TODO list,
2629 the time stamp will always be forced into the second line."
2630 :group 'org-time
2631 :type 'boolean)
2633 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2634 "Formats for `format-time-string' which are used for time stamps.
2635 It is not recommended to change this constant.")
2637 (defcustom org-time-stamp-rounding-minutes '(0 5)
2638 "Number of minutes to round time stamps to.
2639 These are two values, the first applies when first creating a time stamp.
2640 The second applies when changing it with the commands `S-up' and `S-down'.
2641 When changing the time stamp, this means that it will change in steps
2642 of N minutes, as given by the second value.
2644 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2645 numbers should be factors of 60, so for example 5, 10, 15.
2647 When this is larger than 1, you can still force an exact time stamp by using
2648 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2649 and by using a prefix arg to `S-up/down' to specify the exact number
2650 of minutes to shift."
2651 :group 'org-time
2652 :get #'(lambda (var) ; Make sure both elements are there
2653 (if (integerp (default-value var))
2654 (list (default-value var) 5)
2655 (default-value var)))
2656 :type '(list
2657 (integer :tag "when inserting times")
2658 (integer :tag "when modifying times")))
2660 ;; Normalize old customizations of this variable.
2661 (when (integerp org-time-stamp-rounding-minutes)
2662 (setq org-time-stamp-rounding-minutes
2663 (list org-time-stamp-rounding-minutes
2664 org-time-stamp-rounding-minutes)))
2666 (defcustom org-display-custom-times nil
2667 "Non-nil means overlay custom formats over all time stamps.
2668 The formats are defined through the variable `org-time-stamp-custom-formats'.
2669 To turn this on on a per-file basis, insert anywhere in the file:
2670 #+STARTUP: customtime"
2671 :group 'org-time
2672 :set 'set-default
2673 :type 'sexp)
2674 (make-variable-buffer-local 'org-display-custom-times)
2676 (defcustom org-time-stamp-custom-formats
2677 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2678 "Custom formats for time stamps. See `format-time-string' for the syntax.
2679 These are overlaid over the default ISO format if the variable
2680 `org-display-custom-times' is set. Time like %H:%M should be at the
2681 end of the second format. The custom formats are also honored by export
2682 commands, if custom time display is turned on at the time of export."
2683 :group 'org-time
2684 :type 'sexp)
2686 (defun org-time-stamp-format (&optional long inactive)
2687 "Get the right format for a time string."
2688 (let ((f (if long (cdr org-time-stamp-formats)
2689 (car org-time-stamp-formats))))
2690 (if inactive
2691 (concat "[" (substring f 1 -1) "]")
2692 f)))
2694 (defcustom org-time-clocksum-format "%d:%02d"
2695 "The format string used when creating CLOCKSUM lines.
2696 This is also used when org-mode generates a time duration."
2697 :group 'org-time
2698 :type 'string)
2700 (defcustom org-time-clocksum-use-fractional nil
2701 "If non-nil, \\[org-clock-display] uses fractional times.
2702 org-mode generates a time duration."
2703 :group 'org-time
2704 :type 'boolean)
2706 (defcustom org-time-clocksum-fractional-format "%.2f"
2707 "The format string used when creating CLOCKSUM lines, or when
2708 org-mode generates a time duration."
2709 :group 'org-time
2710 :type 'string)
2712 (defcustom org-deadline-warning-days 14
2713 "No. of days before expiration during which a deadline becomes active.
2714 This variable governs the display in sparse trees and in the agenda.
2715 When 0 or negative, it means use this number (the absolute value of it)
2716 even if a deadline has a different individual lead time specified.
2718 Custom commands can set this variable in the options section."
2719 :group 'org-time
2720 :group 'org-agenda-daily/weekly
2721 :type 'integer)
2723 (defcustom org-read-date-prefer-future t
2724 "Non-nil means assume future for incomplete date input from user.
2725 This affects the following situations:
2726 1. The user gives a month but not a year.
2727 For example, if it is April and you enter \"feb 2\", this will be read
2728 as Feb 2, *next* year. \"May 5\", however, will be this year.
2729 2. The user gives a day, but no month.
2730 For example, if today is the 15th, and you enter \"3\", Org-mode will
2731 read this as the third of *next* month. However, if you enter \"17\",
2732 it will be considered as *this* month.
2734 If you set this variable to the symbol `time', then also the following
2735 will work:
2737 3. If the user gives a time, but no day. If the time is before now,
2738 to will be interpreted as tomorrow.
2740 Currently none of this works for ISO week specifications.
2742 When this option is nil, the current day, month and year will always be
2743 used as defaults.
2745 See also `org-agenda-jump-prefer-future'."
2746 :group 'org-time
2747 :type '(choice
2748 (const :tag "Never" nil)
2749 (const :tag "Check month and day" t)
2750 (const :tag "Check month, day, and time" time)))
2752 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2753 "Should the agenda jump command prefer the future for incomplete dates?
2754 The default is to do the same as configured in `org-read-date-prefer-future'.
2755 But you can also set a deviating value here.
2756 This may t or nil, or the symbol `org-read-date-prefer-future'."
2757 :group 'org-agenda
2758 :group 'org-time
2759 :version "24.1"
2760 :type '(choice
2761 (const :tag "Use org-read-date-prefer-future"
2762 org-read-date-prefer-future)
2763 (const :tag "Never" nil)
2764 (const :tag "Always" t)))
2766 (defcustom org-read-date-force-compatible-dates t
2767 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2769 Depending on the system Emacs is running on, certain dates cannot
2770 be represented with the type used internally to represent time.
2771 Dates between 1970-1-1 and 2038-1-1 can always be represented
2772 correctly. Some systems allow for earlier dates, some for later,
2773 some for both. One way to find out it to insert any date into an
2774 Org buffer, putting the cursor on the year and hitting S-up and
2775 S-down to test the range.
2777 When this variable is set to t, the date/time prompt will not let
2778 you specify dates outside the 1970-2037 range, so it is certain that
2779 these dates will work in whatever version of Emacs you are
2780 running, and also that you can move a file from one Emacs implementation
2781 to another. WHenever Org is forcing the year for you, it will display
2782 a message and beep.
2784 When this variable is nil, Org will check if the date is
2785 representable in the specific Emacs implementation you are using.
2786 If not, it will force a year, usually the current year, and beep
2787 to remind you. Currently this setting is not recommended because
2788 the likelihood that you will open your Org files in an Emacs that
2789 has limited date range is not negligible.
2791 A workaround for this problem is to use diary sexp dates for time
2792 stamps outside of this range."
2793 :group 'org-time
2794 :version "24.1"
2795 :type 'boolean)
2797 (defcustom org-read-date-display-live t
2798 "Non-nil means display current interpretation of date prompt live.
2799 This display will be in an overlay, in the minibuffer."
2800 :group 'org-time
2801 :type 'boolean)
2803 (defcustom org-read-date-popup-calendar t
2804 "Non-nil means pop up a calendar when prompting for a date.
2805 In the calendar, the date can be selected with mouse-1. However, the
2806 minibuffer will also be active, and you can simply enter the date as well.
2807 When nil, only the minibuffer will be available."
2808 :group 'org-time
2809 :type 'boolean)
2810 (if (fboundp 'defvaralias)
2811 (defvaralias 'org-popup-calendar-for-date-prompt
2812 'org-read-date-popup-calendar))
2814 (defcustom org-read-date-minibuffer-setup-hook nil
2815 "Hook to be used to set up keys for the date/time interface.
2816 Add key definitions to `minibuffer-local-map', which will be a temporary
2817 copy."
2818 :group 'org-time
2819 :type 'hook)
2821 (defcustom org-extend-today-until 0
2822 "The hour when your day really ends. Must be an integer.
2823 This has influence for the following applications:
2824 - When switching the agenda to \"today\". It it is still earlier than
2825 the time given here, the day recognized as TODAY is actually yesterday.
2826 - When a date is read from the user and it is still before the time given
2827 here, the current date and time will be assumed to be yesterday, 23:59.
2828 Also, timestamps inserted in remember templates follow this rule.
2830 IMPORTANT: This is a feature whose implementation is and likely will
2831 remain incomplete. Really, it is only here because past midnight seems to
2832 be the favorite working time of John Wiegley :-)"
2833 :group 'org-time
2834 :type 'integer)
2836 (defcustom org-use-effective-time nil
2837 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2838 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2839 \"effective time\" of any timestamps between midnight and 8am will be
2840 23:59 of the previous day."
2841 :group 'org-time
2842 :version "24.1"
2843 :type 'boolean)
2845 (defcustom org-edit-timestamp-down-means-later nil
2846 "Non-nil means S-down will increase the time in a time stamp.
2847 When nil, S-up will increase."
2848 :group 'org-time
2849 :type 'boolean)
2851 (defcustom org-calendar-follow-timestamp-change t
2852 "Non-nil means make the calendar window follow timestamp changes.
2853 When a timestamp is modified and the calendar window is visible, it will be
2854 moved to the new date."
2855 :group 'org-time
2856 :type 'boolean)
2858 (defgroup org-tags nil
2859 "Options concerning tags in Org-mode."
2860 :tag "Org Tags"
2861 :group 'org)
2863 (defcustom org-tag-alist nil
2864 "List of tags allowed in Org-mode files.
2865 When this list is nil, Org-mode will base TAG input on what is already in the
2866 buffer.
2867 The value of this variable is an alist, the car of each entry must be a
2868 keyword as a string, the cdr may be a character that is used to select
2869 that tag through the fast-tag-selection interface.
2870 See the manual for details."
2871 :group 'org-tags
2872 :type '(repeat
2873 (choice
2874 (cons (string :tag "Tag name")
2875 (character :tag "Access char"))
2876 (list :tag "Start radio group"
2877 (const :startgroup)
2878 (option (string :tag "Group description")))
2879 (list :tag "End radio group"
2880 (const :endgroup)
2881 (option (string :tag "Group description")))
2882 (const :tag "New line" (:newline)))))
2884 (defcustom org-tag-persistent-alist nil
2885 "List of tags that will always appear in all Org-mode files.
2886 This is in addition to any in buffer settings or customizations
2887 of `org-tag-alist'.
2888 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2889 The value of this variable is an alist, the car of each entry must be a
2890 keyword as a string, the cdr may be a character that is used to select
2891 that tag through the fast-tag-selection interface.
2892 See the manual for details.
2893 To disable these tags on a per-file basis, insert anywhere in the file:
2894 #+STARTUP: noptag"
2895 :group 'org-tags
2896 :type '(repeat
2897 (choice
2898 (cons (string :tag "Tag name")
2899 (character :tag "Access char"))
2900 (const :tag "Start radio group" (:startgroup))
2901 (const :tag "End radio group" (:endgroup))
2902 (const :tag "New line" (:newline)))))
2904 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2905 "If non-nil, always offer completion for all tags of all agenda files.
2906 Instead of customizing this variable directly, you might want to
2907 set it locally for capture buffers, because there no list of
2908 tags in that file can be created dynamically (there are none).
2910 (add-hook 'org-capture-mode-hook
2911 (lambda ()
2912 (set (make-local-variable
2913 'org-complete-tags-always-offer-all-agenda-tags)
2914 t)))"
2915 :group 'org-tags
2916 :version "24.1"
2917 :type 'boolean)
2919 (defvar org-file-tags nil
2920 "List of tags that can be inherited by all entries in the file.
2921 The tags will be inherited if the variable `org-use-tag-inheritance'
2922 says they should be.
2923 This variable is populated from #+FILETAGS lines.")
2925 (defcustom org-use-fast-tag-selection 'auto
2926 "Non-nil means use fast tag selection scheme.
2927 This is a special interface to select and deselect tags with single keys.
2928 When nil, fast selection is never used.
2929 When the symbol `auto', fast selection is used if and only if selection
2930 characters for tags have been configured, either through the variable
2931 `org-tag-alist' or through a #+TAGS line in the buffer.
2932 When t, fast selection is always used and selection keys are assigned
2933 automatically if necessary."
2934 :group 'org-tags
2935 :type '(choice
2936 (const :tag "Always" t)
2937 (const :tag "Never" nil)
2938 (const :tag "When selection characters are configured" 'auto)))
2940 (defcustom org-fast-tag-selection-single-key nil
2941 "Non-nil means fast tag selection exits after first change.
2942 When nil, you have to press RET to exit it.
2943 During fast tag selection, you can toggle this flag with `C-c'.
2944 This variable can also have the value `expert'. In this case, the window
2945 displaying the tags menu is not even shown, until you press C-c again."
2946 :group 'org-tags
2947 :type '(choice
2948 (const :tag "No" nil)
2949 (const :tag "Yes" t)
2950 (const :tag "Expert" expert)))
2952 (defvar org-fast-tag-selection-include-todo nil
2953 "Non-nil means fast tags selection interface will also offer TODO states.
2954 This is an undocumented feature, you should not rely on it.")
2956 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2957 "The column to which tags should be indented in a headline.
2958 If this number is positive, it specifies the column. If it is negative,
2959 it means that the tags should be flushright to that column. For example,
2960 -80 works well for a normal 80 character screen.
2961 When 0, place tags directly after headline text, with only one space in
2962 between."
2963 :group 'org-tags
2964 :type 'integer)
2966 (defcustom org-auto-align-tags t
2967 "Non-nil keeps tags aligned when modifying headlines.
2968 Some operations (i.e. demoting) change the length of a headline and
2969 therefore shift the tags around. With this option turned on, after
2970 each such operation the tags are again aligned to `org-tags-column'."
2971 :group 'org-tags
2972 :type 'boolean)
2974 (defcustom org-use-tag-inheritance t
2975 "Non-nil means tags in levels apply also for sublevels.
2976 When nil, only the tags directly given in a specific line apply there.
2977 This may also be a list of tags that should be inherited, or a regexp that
2978 matches tags that should be inherited. Additional control is possible
2979 with the variable `org-tags-exclude-from-inheritance' which gives an
2980 explicit list of tags to be excluded from inheritance., even if the value of
2981 `org-use-tag-inheritance' would select it for inheritance.
2983 If this option is t, a match early-on in a tree can lead to a large
2984 number of matches in the subtree when constructing the agenda or creating
2985 a sparse tree. If you only want to see the first match in a tree during
2986 a search, check out the variable `org-tags-match-list-sublevels'."
2987 :group 'org-tags
2988 :type '(choice
2989 (const :tag "Not" nil)
2990 (const :tag "Always" t)
2991 (repeat :tag "Specific tags" (string :tag "Tag"))
2992 (regexp :tag "Tags matched by regexp")))
2994 (defcustom org-tags-exclude-from-inheritance nil
2995 "List of tags that should never be inherited.
2996 This is a way to exclude a few tags from inheritance. For way to do
2997 the opposite, to actively allow inheritance for selected tags,
2998 see the variable `org-use-tag-inheritance'."
2999 :group 'org-tags
3000 :type '(repeat (string :tag "Tag")))
3002 (defun org-tag-inherit-p (tag)
3003 "Check if TAG is one that should be inherited."
3004 (cond
3005 ((member tag org-tags-exclude-from-inheritance) nil)
3006 ((eq org-use-tag-inheritance t) t)
3007 ((not org-use-tag-inheritance) nil)
3008 ((stringp org-use-tag-inheritance)
3009 (string-match org-use-tag-inheritance tag))
3010 ((listp org-use-tag-inheritance)
3011 (member tag org-use-tag-inheritance))
3012 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3014 (defcustom org-tags-match-list-sublevels t
3015 "Non-nil means list also sublevels of headlines matching a search.
3016 This variable applies to tags/property searches, and also to stuck
3017 projects because this search is based on a tags match as well.
3019 When set to the symbol `indented', sublevels are indented with
3020 leading dots.
3022 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3023 the sublevels of a headline matching a tag search often also match
3024 the same search. Listing all of them can create very long lists.
3025 Setting this variable to nil causes subtrees of a match to be skipped.
3027 This variable is semi-obsolete and probably should always be true. It
3028 is better to limit inheritance to certain tags using the variables
3029 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3030 :group 'org-tags
3031 :type '(choice
3032 (const :tag "No, don't list them" nil)
3033 (const :tag "Yes, do list them" t)
3034 (const :tag "List them, indented with leading dots" indented)))
3036 (defcustom org-tags-sort-function nil
3037 "When set, tags are sorted using this function as a comparator."
3038 :group 'org-tags
3039 :type '(choice
3040 (const :tag "No sorting" nil)
3041 (const :tag "Alphabetical" string<)
3042 (const :tag "Reverse alphabetical" string>)
3043 (function :tag "Custom function" nil)))
3045 (defvar org-tags-history nil
3046 "History of minibuffer reads for tags.")
3047 (defvar org-last-tags-completion-table nil
3048 "The last used completion table for tags.")
3049 (defvar org-after-tags-change-hook nil
3050 "Hook that is run after the tags in a line have changed.")
3052 (defgroup org-properties nil
3053 "Options concerning properties in Org-mode."
3054 :tag "Org Properties"
3055 :group 'org)
3057 (defcustom org-property-format "%-10s %s"
3058 "How property key/value pairs should be formatted by `indent-line'.
3059 When `indent-line' hits a property definition, it will format the line
3060 according to this format, mainly to make sure that the values are
3061 lined-up with respect to each other."
3062 :group 'org-properties
3063 :type 'string)
3065 (defcustom org-properties-postprocess-alist nil
3066 "Alist of properties and functions to adjust inserted values.
3067 Elements of this alist must be of the form
3069 ([string] [function])
3071 where [string] must be a property name and [function] must be a
3072 lambda expression: this lambda expression must take one argument,
3073 the value to adjust, and return the new value as a string.
3075 For example, this element will allow the property \"Remaining\"
3076 to be updated wrt the relation between the \"Effort\" property
3077 and the clock summary:
3079 ((\"Remaining\" (lambda(value)
3080 (let ((clocksum (org-clock-sum-current-item))
3081 (effort (org-duration-string-to-minutes
3082 (org-entry-get (point) \"Effort\"))))
3083 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3084 :group 'org-properties
3085 :version "24.1"
3086 :type '(alist :key-type (string :tag "Property")
3087 :value-type (function :tag "Function")))
3089 (defcustom org-use-property-inheritance nil
3090 "Non-nil means properties apply also for sublevels.
3092 This setting is chiefly used during property searches. Turning it on can
3093 cause significant overhead when doing a search, which is why it is not
3094 on by default.
3096 When nil, only the properties directly given in the current entry count.
3097 When t, every property is inherited. The value may also be a list of
3098 properties that should have inheritance, or a regular expression matching
3099 properties that should be inherited.
3101 However, note that some special properties use inheritance under special
3102 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3103 and the properties ending in \"_ALL\" when they are used as descriptor
3104 for valid values of a property.
3106 Note for programmers:
3107 When querying an entry with `org-entry-get', you can control if inheritance
3108 should be used. By default, `org-entry-get' looks only at the local
3109 properties. You can request inheritance by setting the inherit argument
3110 to t (to force inheritance) or to `selective' (to respect the setting
3111 in this variable)."
3112 :group 'org-properties
3113 :type '(choice
3114 (const :tag "Not" nil)
3115 (const :tag "Always" t)
3116 (repeat :tag "Specific properties" (string :tag "Property"))
3117 (regexp :tag "Properties matched by regexp")))
3119 (defun org-property-inherit-p (property)
3120 "Check if PROPERTY is one that should be inherited."
3121 (cond
3122 ((eq org-use-property-inheritance t) t)
3123 ((not org-use-property-inheritance) nil)
3124 ((stringp org-use-property-inheritance)
3125 (string-match org-use-property-inheritance property))
3126 ((listp org-use-property-inheritance)
3127 (member property org-use-property-inheritance))
3128 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3130 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3131 "The default column format, if no other format has been defined.
3132 This variable can be set on the per-file basis by inserting a line
3134 #+COLUMNS: %25ITEM ....."
3135 :group 'org-properties
3136 :type 'string)
3138 (defcustom org-columns-ellipses ".."
3139 "The ellipses to be used when a field in column view is truncated.
3140 When this is the empty string, as many characters as possible are shown,
3141 but then there will be no visual indication that the field has been truncated.
3142 When this is a string of length N, the last N characters of a truncated
3143 field are replaced by this string. If the column is narrower than the
3144 ellipses string, only part of the ellipses string will be shown."
3145 :group 'org-properties
3146 :type 'string)
3148 (defcustom org-columns-modify-value-for-display-function nil
3149 "Function that modifies values for display in column view.
3150 For example, it can be used to cut out a certain part from a time stamp.
3151 The function must take 2 arguments:
3153 column-title The title of the column (*not* the property name)
3154 value The value that should be modified.
3156 The function should return the value that should be displayed,
3157 or nil if the normal value should be used."
3158 :group 'org-properties
3159 :type 'function)
3161 (defcustom org-effort-property "Effort"
3162 "The property that is being used to keep track of effort estimates.
3163 Effort estimates given in this property need to have the format H:MM."
3164 :group 'org-properties
3165 :group 'org-progress
3166 :type '(string :tag "Property"))
3168 (defconst org-global-properties-fixed
3169 '(("VISIBILITY_ALL" . "folded children content all")
3170 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3171 "List of property/value pairs that can be inherited by any entry.
3173 These are fixed values, for the preset properties. The user variable
3174 that can be used to add to this list is `org-global-properties'.
3176 The entries in this list are cons cells where the car is a property
3177 name and cdr is a string with the value. If the value represents
3178 multiple items like an \"_ALL\" property, separate the items by
3179 spaces.")
3181 (defcustom org-global-properties nil
3182 "List of property/value pairs that can be inherited by any entry.
3184 This list will be combined with the constant `org-global-properties-fixed'.
3186 The entries in this list are cons cells where the car is a property
3187 name and cdr is a string with the value.
3189 You can set buffer-local values for the same purpose in the variable
3190 `org-file-properties' this by adding lines like
3192 #+PROPERTY: NAME VALUE"
3193 :group 'org-properties
3194 :type '(repeat
3195 (cons (string :tag "Property")
3196 (string :tag "Value"))))
3198 (defvar org-file-properties nil
3199 "List of property/value pairs that can be inherited by any entry.
3200 Valid for the current buffer.
3201 This variable is populated from #+PROPERTY lines.")
3202 (make-variable-buffer-local 'org-file-properties)
3204 (defgroup org-agenda nil
3205 "Options concerning agenda views in Org-mode."
3206 :tag "Org Agenda"
3207 :group 'org)
3209 (defvar org-category nil
3210 "Variable used by org files to set a category for agenda display.
3211 Such files should use a file variable to set it, for example
3213 # -*- mode: org; org-category: \"ELisp\"
3215 or contain a special line
3217 #+CATEGORY: ELisp
3219 If the file does not specify a category, then file's base name
3220 is used instead.")
3221 (make-variable-buffer-local 'org-category)
3222 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3224 (defcustom org-agenda-files nil
3225 "The files to be used for agenda display.
3226 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3227 \\[org-remove-file]. You can also use customize to edit the list.
3229 If an entry is a directory, all files in that directory that are matched by
3230 `org-agenda-file-regexp' will be part of the file list.
3232 If the value of the variable is not a list but a single file name, then
3233 the list of agenda files is actually stored and maintained in that file, one
3234 agenda file per line. In this file paths can be given relative to
3235 `org-directory'. Tilde expansion and environment variable substitution
3236 are also made."
3237 :group 'org-agenda
3238 :type '(choice
3239 (repeat :tag "List of files and directories" file)
3240 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3242 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3243 "Regular expression to match files for `org-agenda-files'.
3244 If any element in the list in that variable contains a directory instead
3245 of a normal file, all files in that directory that are matched by this
3246 regular expression will be included."
3247 :group 'org-agenda
3248 :type 'regexp)
3250 (defcustom org-agenda-text-search-extra-files nil
3251 "List of extra files to be searched by text search commands.
3252 These files will be search in addition to the agenda files by the
3253 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3254 Note that these files will only be searched for text search commands,
3255 not for the other agenda views like todo lists, tag searches or the weekly
3256 agenda. This variable is intended to list notes and possibly archive files
3257 that should also be searched by these two commands.
3258 In fact, if the first element in the list is the symbol `agenda-archives',
3259 than all archive files of all agenda files will be added to the search
3260 scope."
3261 :group 'org-agenda
3262 :type '(set :greedy t
3263 (const :tag "Agenda Archives" agenda-archives)
3264 (repeat :inline t (file))))
3266 (if (fboundp 'defvaralias)
3267 (defvaralias 'org-agenda-multi-occur-extra-files
3268 'org-agenda-text-search-extra-files))
3270 (defcustom org-agenda-skip-unavailable-files nil
3271 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3272 A nil value means to remove them, after a query, from the list."
3273 :group 'org-agenda
3274 :type 'boolean)
3276 (defcustom org-calendar-to-agenda-key [?c]
3277 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3278 The command `org-calendar-goto-agenda' will be bound to this key. The
3279 default is the character `c' because then `c' can be used to switch back and
3280 forth between agenda and calendar."
3281 :group 'org-agenda
3282 :type 'sexp)
3284 (defcustom org-calendar-agenda-action-key [?k]
3285 "The key to be installed in `calendar-mode-map' for agenda-action.
3286 The command `org-agenda-action' will be bound to this key. The
3287 default is the character `k' because we use the same key in the agenda."
3288 :group 'org-agenda
3289 :type 'sexp)
3291 (defcustom org-calendar-insert-diary-entry-key [?i]
3292 "The key to be installed in `calendar-mode-map' for adding diary entries.
3293 This option is irrelevant until `org-agenda-diary-file' has been configured
3294 to point to an Org-mode file. When that is the case, the command
3295 `org-agenda-diary-entry' will be bound to the key given here, by default
3296 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3297 if you want to continue doing this, you need to change this to a different
3298 key."
3299 :group 'org-agenda
3300 :type 'sexp)
3302 (defcustom org-agenda-diary-file 'diary-file
3303 "File to which to add new entries with the `i' key in agenda and calendar.
3304 When this is the symbol `diary-file', the functionality in the Emacs
3305 calendar will be used to add entries to the `diary-file'. But when this
3306 points to a file, `org-agenda-diary-entry' will be used instead."
3307 :group 'org-agenda
3308 :type '(choice
3309 (const :tag "The standard Emacs diary file" diary-file)
3310 (file :tag "Special Org file diary entries")))
3312 (eval-after-load "calendar"
3313 '(progn
3314 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3315 'org-calendar-goto-agenda)
3316 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3317 'org-agenda-action)
3318 (add-hook 'calendar-mode-hook
3319 (lambda ()
3320 (unless (eq org-agenda-diary-file 'diary-file)
3321 (define-key calendar-mode-map
3322 org-calendar-insert-diary-entry-key
3323 'org-agenda-diary-entry))))))
3325 (defgroup org-latex nil
3326 "Options for embedding LaTeX code into Org-mode."
3327 :tag "Org LaTeX"
3328 :group 'org)
3330 (defcustom org-format-latex-options
3331 '(:foreground default :background default :scale 1.0
3332 :html-foreground "Black" :html-background "Transparent"
3333 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3334 "Options for creating images from LaTeX fragments.
3335 This is a property list with the following properties:
3336 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3337 `default' means use the foreground of the default face.
3338 :background the background color, or \"Transparent\".
3339 `default' means use the background of the default face.
3340 :scale a scaling factor for the size of the images, to get more pixels
3341 :html-foreground, :html-background, :html-scale
3342 the same numbers for HTML export.
3343 :matchers a list indicating which matchers should be used to
3344 find LaTeX fragments. Valid members of this list are:
3345 \"begin\" find environments
3346 \"$1\" find single characters surrounded by $.$
3347 \"$\" find math expressions surrounded by $...$
3348 \"$$\" find math expressions surrounded by $$....$$
3349 \"\\(\" find math expressions surrounded by \\(...\\)
3350 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3351 :group 'org-latex
3352 :type 'plist)
3354 (defcustom org-format-latex-signal-error t
3355 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3356 When nil, just push out a message."
3357 :group 'org-latex
3358 :version "24.1"
3359 :type 'boolean)
3361 (defcustom org-latex-to-mathml-jar-file nil
3362 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3363 Use this to specify additional executable file say a jar file.
3365 When using MathToWeb as the converter, specify the full-path to
3366 your mathtoweb.jar file."
3367 :group 'org-latex
3368 :version "24.1"
3369 :type '(choice
3370 (const :tag "None" nil)
3371 (file :tag "JAR file" :must-match t)))
3373 (defcustom org-latex-to-mathml-convert-command nil
3374 "Command to convert LaTeX fragments to MathML.
3375 Replace format-specifiers in the command as noted below and use
3376 `shell-command' to convert LaTeX to MathML.
3377 %j: Executable file in fully expanded form as specified by
3378 `org-latex-to-mathml-jar-file'.
3379 %I: Input LaTeX file in fully expanded form
3380 %o: Output MathML file
3381 This command is used by `org-create-math-formula'.
3383 When using MathToWeb as the converter, set this to
3384 \"java -jar %j -unicode -force -df %o %I\"."
3385 :group 'org-latex
3386 :version "24.1"
3387 :type '(choice
3388 (const :tag "None" nil)
3389 (string :tag "\nShell command")))
3391 (defcustom org-latex-create-formula-image-program 'dvipng
3392 "Program to convert LaTeX fragments with.
3394 dvipng Process the LaTeX fragments to dvi file, then convert
3395 dvi files to png files using dvipng.
3396 This will also include processing of non-math environments.
3397 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3398 to convert pdf files to png files"
3399 :group 'org-latex
3400 :version "24.1"
3401 :type '(choice
3402 (const :tag "dvipng" dvipng)
3403 (const :tag "imagemagick" imagemagick)))
3405 (defun org-format-latex-mathml-available-p ()
3406 "Return t if `org-latex-to-mathml-convert-command' is usable."
3407 (save-match-data
3408 (when (and (boundp 'org-latex-to-mathml-convert-command)
3409 org-latex-to-mathml-convert-command)
3410 (let ((executable (car (split-string
3411 org-latex-to-mathml-convert-command))))
3412 (when (executable-find executable)
3413 (if (string-match
3414 "%j" org-latex-to-mathml-convert-command)
3415 (file-readable-p org-latex-to-mathml-jar-file)
3416 t))))))
3418 (defcustom org-format-latex-header "\\documentclass{article}
3419 \\usepackage[usenames]{color}
3420 \\usepackage{amsmath}
3421 \\usepackage[mathscr]{eucal}
3422 \\pagestyle{empty} % do not remove
3423 \[PACKAGES]
3424 \[DEFAULT-PACKAGES]
3425 % The settings below are copied from fullpage.sty
3426 \\setlength{\\textwidth}{\\paperwidth}
3427 \\addtolength{\\textwidth}{-3cm}
3428 \\setlength{\\oddsidemargin}{1.5cm}
3429 \\addtolength{\\oddsidemargin}{-2.54cm}
3430 \\setlength{\\evensidemargin}{\\oddsidemargin}
3431 \\setlength{\\textheight}{\\paperheight}
3432 \\addtolength{\\textheight}{-\\headheight}
3433 \\addtolength{\\textheight}{-\\headsep}
3434 \\addtolength{\\textheight}{-\\footskip}
3435 \\addtolength{\\textheight}{-3cm}
3436 \\setlength{\\topmargin}{1.5cm}
3437 \\addtolength{\\topmargin}{-2.54cm}"
3438 "The document header used for processing LaTeX fragments.
3439 It is imperative that this header make sure that no page number
3440 appears on the page. The package defined in the variables
3441 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3442 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3443 will be appended."
3444 :group 'org-latex
3445 :type 'string)
3447 (defvar org-format-latex-header-extra nil)
3449 (defun org-set-packages-alist (var val)
3450 "Set the packages alist and make sure it has 3 elements per entry."
3451 (set var (mapcar (lambda (x)
3452 (if (and (consp x) (= (length x) 2))
3453 (list (car x) (nth 1 x) t)
3455 val)))
3457 (defun org-get-packages-alist (var)
3459 "Get the packages alist and make sure it has 3 elements per entry."
3460 (mapcar (lambda (x)
3461 (if (and (consp x) (= (length x) 2))
3462 (list (car x) (nth 1 x) t)
3464 (default-value var)))
3466 ;; The following variables are defined here because is it also used
3467 ;; when formatting latex fragments. Originally it was part of the
3468 ;; LaTeX exporter, which is why the name includes "export".
3469 (defcustom org-export-latex-default-packages-alist
3470 '(("AUTO" "inputenc" t)
3471 ("T1" "fontenc" t)
3472 ("" "fixltx2e" nil)
3473 ("" "graphicx" t)
3474 ("" "longtable" nil)
3475 ("" "float" nil)
3476 ("" "wrapfig" nil)
3477 ("" "soul" t)
3478 ("" "textcomp" t)
3479 ("" "marvosym" t)
3480 ("" "wasysym" t)
3481 ("" "latexsym" t)
3482 ("" "amssymb" t)
3483 ("" "hyperref" nil)
3484 "\\tolerance=1000"
3486 "Alist of default packages to be inserted in the header.
3487 Change this only if one of the packages here causes an incompatibility
3488 with another package you are using.
3489 The packages in this list are needed by one part or another of Org-mode
3490 to function properly.
3492 - inputenc, fontenc: for basic font and character selection
3493 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3494 for interpreting the entities in `org-entities'. You can skip some of these
3495 packages if you don't use any of the symbols in it.
3496 - graphicx: for including images
3497 - float, wrapfig: for figure placement
3498 - longtable: for long tables
3499 - hyperref: for cross references
3501 Therefore you should not modify this variable unless you know what you
3502 are doing. The one reason to change it anyway is that you might be loading
3503 some other package that conflicts with one of the default packages.
3504 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3505 If SNIPPET-FLAG is t, the package also needs to be included when
3506 compiling LaTeX snippets into images for inclusion into HTML."
3507 :group 'org-export-latex
3508 :set 'org-set-packages-alist
3509 :get 'org-get-packages-alist
3510 :version "24.1"
3511 :type '(repeat
3512 (choice
3513 (list :tag "options/package pair"
3514 (string :tag "options")
3515 (string :tag "package")
3516 (boolean :tag "Snippet"))
3517 (string :tag "A line of LaTeX"))))
3519 (defcustom org-export-latex-packages-alist nil
3520 "Alist of packages to be inserted in every LaTeX header.
3521 These will be inserted after `org-export-latex-default-packages-alist'.
3522 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3523 SNIPPET-FLAG, when t, indicates that this package is also needed when
3524 turning LaTeX snippets into images for inclusion into HTML.
3525 Make sure that you only list packages here which:
3526 - you want in every file
3527 - do not conflict with the default packages in
3528 `org-export-latex-default-packages-alist'
3529 - do not conflict with the setup in `org-format-latex-header'."
3530 :group 'org-export-latex
3531 :set 'org-set-packages-alist
3532 :get 'org-get-packages-alist
3533 :type '(repeat
3534 (choice
3535 (list :tag "options/package pair"
3536 (string :tag "options")
3537 (string :tag "package")
3538 (boolean :tag "Snippet"))
3539 (string :tag "A line of LaTeX"))))
3542 (defgroup org-appearance nil
3543 "Settings for Org-mode appearance."
3544 :tag "Org Appearance"
3545 :group 'org)
3547 (defcustom org-level-color-stars-only nil
3548 "Non-nil means fontify only the stars in each headline.
3549 When nil, the entire headline is fontified.
3550 Changing it requires restart of `font-lock-mode' to become effective
3551 also in regions already fontified."
3552 :group 'org-appearance
3553 :type 'boolean)
3555 (defcustom org-hide-leading-stars nil
3556 "Non-nil means hide the first N-1 stars in a headline.
3557 This works by using the face `org-hide' for these stars. This
3558 face is white for a light background, and black for a dark
3559 background. You may have to customize the face `org-hide' to
3560 make this work.
3561 Changing it requires restart of `font-lock-mode' to become effective
3562 also in regions already fontified.
3563 You may also set this on a per-file basis by adding one of the following
3564 lines to the buffer:
3566 #+STARTUP: hidestars
3567 #+STARTUP: showstars"
3568 :group 'org-appearance
3569 :type 'boolean)
3571 (defcustom org-hidden-keywords nil
3572 "List of symbols corresponding to keywords to be hidden the org buffer.
3573 For example, a value '(title) for this list will make the document's title
3574 appear in the buffer without the initial #+TITLE: keyword."
3575 :group 'org-appearance
3576 :version "24.1"
3577 :type '(set (const :tag "#+AUTHOR" author)
3578 (const :tag "#+DATE" date)
3579 (const :tag "#+EMAIL" email)
3580 (const :tag "#+TITLE" title)))
3582 (defcustom org-fontify-done-headline nil
3583 "Non-nil means change the face of a headline if it is marked DONE.
3584 Normally, only the TODO/DONE keyword indicates the state of a headline.
3585 When this is non-nil, the headline after the keyword is set to the
3586 `org-headline-done' as an additional indication."
3587 :group 'org-appearance
3588 :type 'boolean)
3590 (defcustom org-fontify-emphasized-text t
3591 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3592 Changing this variable requires a restart of Emacs to take effect."
3593 :group 'org-appearance
3594 :type 'boolean)
3596 (defcustom org-fontify-whole-heading-line nil
3597 "Non-nil means fontify the whole line for headings.
3598 This is useful when setting a background color for the
3599 org-level-* faces."
3600 :group 'org-appearance
3601 :type 'boolean)
3603 (defcustom org-highlight-latex-fragments-and-specials nil
3604 "Non-nil means fontify what is treated specially by the exporters."
3605 :group 'org-appearance
3606 :type 'boolean)
3608 (defcustom org-hide-emphasis-markers nil
3609 "Non-nil mean font-lock should hide the emphasis marker characters."
3610 :group 'org-appearance
3611 :type 'boolean)
3613 (defcustom org-pretty-entities nil
3614 "Non-nil means show entities as UTF8 characters.
3615 When nil, the \\name form remains in the buffer."
3616 :group 'org-appearance
3617 :version "24.1"
3618 :type 'boolean)
3620 (defcustom org-pretty-entities-include-sub-superscripts t
3621 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3622 :group 'org-appearance
3623 :version "24.1"
3624 :type 'boolean)
3626 (defvar org-emph-re nil
3627 "Regular expression for matching emphasis.
3628 After a match, the match groups contain these elements:
3629 0 The match of the full regular expression, including the characters
3630 before and after the proper match
3631 1 The character before the proper match, or empty at beginning of line
3632 2 The proper match, including the leading and trailing markers
3633 3 The leading marker like * or /, indicating the type of highlighting
3634 4 The text between the emphasis markers, not including the markers
3635 5 The character after the match, empty at the end of a line")
3636 (defvar org-verbatim-re nil
3637 "Regular expression for matching verbatim text.")
3638 (defvar org-emphasis-regexp-components) ; defined just below
3639 (defvar org-emphasis-alist) ; defined just below
3640 (defun org-set-emph-re (var val)
3641 "Set variable and compute the emphasis regular expression."
3642 (set var val)
3643 (when (and (boundp 'org-emphasis-alist)
3644 (boundp 'org-emphasis-regexp-components)
3645 org-emphasis-alist org-emphasis-regexp-components)
3646 (let* ((e org-emphasis-regexp-components)
3647 (pre (car e))
3648 (post (nth 1 e))
3649 (border (nth 2 e))
3650 (body (nth 3 e))
3651 (nl (nth 4 e))
3652 (body1 (concat body "*?"))
3653 (markers (mapconcat 'car org-emphasis-alist ""))
3654 (vmarkers (mapconcat
3655 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3656 org-emphasis-alist "")))
3657 ;; make sure special characters appear at the right position in the class
3658 (if (string-match "\\^" markers)
3659 (setq markers (concat (replace-match "" t t markers) "^")))
3660 (if (string-match "-" markers)
3661 (setq markers (concat (replace-match "" t t markers) "-")))
3662 (if (string-match "\\^" vmarkers)
3663 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3664 (if (string-match "-" vmarkers)
3665 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3666 (if (> nl 0)
3667 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3668 (int-to-string nl) "\\}")))
3669 ;; Make the regexp
3670 (setq org-emph-re
3671 (concat "\\([" pre "]\\|^\\)"
3672 "\\("
3673 "\\([" markers "]\\)"
3674 "\\("
3675 "[^" border "]\\|"
3676 "[^" border "]"
3677 body1
3678 "[^" border "]"
3679 "\\)"
3680 "\\3\\)"
3681 "\\([" post "]\\|$\\)"))
3682 (setq org-verbatim-re
3683 (concat "\\([" pre "]\\|^\\)"
3684 "\\("
3685 "\\([" vmarkers "]\\)"
3686 "\\("
3687 "[^" border "]\\|"
3688 "[^" border "]"
3689 body1
3690 "[^" border "]"
3691 "\\)"
3692 "\\3\\)"
3693 "\\([" post "]\\|$\\)")))))
3695 (defcustom org-emphasis-regexp-components
3696 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3697 "Components used to build the regular expression for emphasis.
3698 This is a list with five entries. Terminology: In an emphasis string
3699 like \" *strong word* \", we call the initial space PREMATCH, the final
3700 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3701 and \"trong wor\" is the body. The different components in this variable
3702 specify what is allowed/forbidden in each part:
3704 pre Chars allowed as prematch. Beginning of line will be allowed too.
3705 post Chars allowed as postmatch. End of line will be allowed too.
3706 border The chars *forbidden* as border characters.
3707 body-regexp A regexp like \".\" to match a body character. Don't use
3708 non-shy groups here, and don't allow newline here.
3709 newline The maximum number of newlines allowed in an emphasis exp.
3711 Use customize to modify this, or restart Emacs after changing it."
3712 :group 'org-appearance
3713 :set 'org-set-emph-re
3714 :type '(list
3715 (sexp :tag "Allowed chars in pre ")
3716 (sexp :tag "Allowed chars in post ")
3717 (sexp :tag "Forbidden chars in border ")
3718 (sexp :tag "Regexp for body ")
3719 (integer :tag "number of newlines allowed")
3720 (option (boolean :tag "Please ignore this button"))))
3722 (defcustom org-emphasis-alist
3723 `(("*" bold "<b>" "</b>")
3724 ("/" italic "<i>" "</i>")
3725 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3726 ("=" org-code "<code>" "</code>" verbatim)
3727 ("~" org-verbatim "<code>" "</code>" verbatim)
3728 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3729 "<del>" "</del>")
3731 "Special syntax for emphasized text.
3732 Text starting and ending with a special character will be emphasized, for
3733 example *bold*, _underlined_ and /italic/. This variable sets the marker
3734 characters, the face to be used by font-lock for highlighting in Org-mode
3735 Emacs buffers, and the HTML tags to be used for this.
3736 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3737 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3738 Use customize to modify this, or restart Emacs after changing it."
3739 :group 'org-appearance
3740 :set 'org-set-emph-re
3741 :type '(repeat
3742 (list
3743 (string :tag "Marker character")
3744 (choice
3745 (face :tag "Font-lock-face")
3746 (plist :tag "Face property list"))
3747 (string :tag "HTML start tag")
3748 (string :tag "HTML end tag")
3749 (option (const verbatim)))))
3751 (defvar org-protecting-blocks
3752 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3753 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3754 This is needed for font-lock setup.")
3756 ;;; Miscellaneous options
3758 (defgroup org-completion nil
3759 "Completion in Org-mode."
3760 :tag "Org Completion"
3761 :group 'org)
3763 (defcustom org-completion-use-ido nil
3764 "Non-nil means use ido completion wherever possible.
3765 Note that `ido-mode' must be active for this variable to be relevant.
3766 If you decide to turn this variable on, you might well want to turn off
3767 `org-outline-path-complete-in-steps'.
3768 See also `org-completion-use-iswitchb'."
3769 :group 'org-completion
3770 :type 'boolean)
3772 (defcustom org-completion-use-iswitchb nil
3773 "Non-nil means use iswitchb completion wherever possible.
3774 Note that `iswitchb-mode' must be active for this variable to be relevant.
3775 If you decide to turn this variable on, you might well want to turn off
3776 `org-outline-path-complete-in-steps'.
3777 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3778 :group 'org-completion
3779 :type 'boolean)
3781 (defcustom org-completion-fallback-command 'hippie-expand
3782 "The expansion command called by \\[pcomplete] in normal context.
3783 Normal means, no org-mode-specific context."
3784 :group 'org-completion
3785 :type 'function)
3787 ;;; Functions and variables from their packages
3788 ;; Declared here to avoid compiler warnings
3790 ;; XEmacs only
3791 (defvar outline-mode-menu-heading)
3792 (defvar outline-mode-menu-show)
3793 (defvar outline-mode-menu-hide)
3794 (defvar zmacs-regions) ; XEmacs regions
3796 ;; Emacs only
3797 (defvar mark-active)
3799 ;; Various packages
3800 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3801 (declare-function calendar-forward-day "cal-move" (arg))
3802 (declare-function calendar-goto-date "cal-move" (date))
3803 (declare-function calendar-goto-today "cal-move" ())
3804 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3805 (defvar calc-embedded-close-formula)
3806 (defvar calc-embedded-open-formula)
3807 (declare-function cdlatex-tab "ext:cdlatex" ())
3808 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3809 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3810 (defvar font-lock-unfontify-region-function)
3811 (declare-function iswitchb-read-buffer "iswitchb"
3812 (prompt &optional default require-match start matches-set))
3813 (defvar iswitchb-temp-buflist)
3814 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3815 (defvar org-agenda-tags-todo-honor-ignore-options)
3816 (declare-function org-agenda-skip "org-agenda" ())
3817 (declare-function
3818 org-agenda-format-item "org-agenda"
3819 (extra txt &optional category tags dotime noprefix remove-re habitp))
3820 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3821 (declare-function org-agenda-change-all-lines "org-agenda"
3822 (newhead hdmarker &optional fixface just-this))
3823 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3824 (declare-function org-agenda-maybe-redo "org-agenda" ())
3825 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3826 (beg end))
3827 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3828 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3829 "org-agenda" (&optional end))
3830 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3831 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3832 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3833 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3834 (declare-function org-indent-mode "org-indent" (&optional arg))
3835 (declare-function parse-time-string "parse-time" (string))
3836 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3837 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3838 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3839 (defvar remember-data-file)
3840 (defvar texmathp-why)
3841 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3842 (declare-function table--at-cell-p "table" (position &optional object at-column))
3844 (defvar w3m-current-url)
3845 (defvar w3m-current-title)
3847 (defvar org-latex-regexps)
3849 ;;; Autoload and prepare some org modules
3851 ;; Some table stuff that needs to be defined here, because it is used
3852 ;; by the functions setting up org-mode or checking for table context.
3854 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3855 "Detect an org-type or table-type table.")
3856 (defconst org-table-line-regexp "^[ \t]*|"
3857 "Detect an org-type table line.")
3858 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3859 "Detect an org-type table line.")
3860 (defconst org-table-hline-regexp "^[ \t]*|-"
3861 "Detect an org-type table hline.")
3862 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3863 "Detect a table-type table hline.")
3864 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3865 "Detect the first line outside a table when searching from within it.
3866 This works for both table types.")
3868 ;; Autoload the functions in org-table.el that are needed by functions here.
3870 (eval-and-compile
3871 (org-autoload "org-table"
3872 '(org-table-align org-table-begin org-table-blank-field
3873 org-table-convert org-table-convert-region org-table-copy-down
3874 org-table-copy-region org-table-create
3875 org-table-create-or-convert-from-region
3876 org-table-create-with-table.el org-table-current-dline
3877 org-table-cut-region org-table-delete-column org-table-edit-field
3878 org-table-edit-formulas org-table-end org-table-eval-formula
3879 org-table-export org-table-field-info
3880 org-table-get-stored-formulas org-table-goto-column
3881 org-table-hline-and-move org-table-import org-table-insert-column
3882 org-table-insert-hline org-table-insert-row org-table-iterate
3883 org-table-justify-field-maybe org-table-kill-row
3884 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3885 org-table-move-column org-table-move-column-left
3886 org-table-move-column-right org-table-move-row
3887 org-table-move-row-down org-table-move-row-up
3888 org-table-next-field org-table-next-row org-table-paste-rectangle
3889 org-table-previous-field org-table-recalculate
3890 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3891 org-table-toggle-coordinate-overlays
3892 org-table-toggle-formula-debugger org-table-wrap-region
3893 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3894 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3895 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3897 (defun org-at-table-p (&optional table-type)
3898 "Return t if the cursor is inside an org-type table.
3899 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3900 (if org-enable-table-editor
3901 (save-excursion
3902 (beginning-of-line 1)
3903 (looking-at (if table-type org-table-any-line-regexp
3904 org-table-line-regexp)))
3905 nil))
3906 (defsubst org-table-p () (org-at-table-p))
3908 (defun org-at-table.el-p ()
3909 "Return t if and only if we are at a table.el table."
3910 (and (org-at-table-p 'any)
3911 (save-excursion
3912 (goto-char (org-table-begin 'any))
3913 (looking-at org-table1-hline-regexp))))
3914 (defun org-table-recognize-table.el ()
3915 "If there is a table.el table nearby, recognize it and move into it."
3916 (if org-table-tab-recognizes-table.el
3917 (if (org-at-table.el-p)
3918 (progn
3919 (beginning-of-line 1)
3920 (if (looking-at org-table-dataline-regexp)
3922 (if (looking-at org-table1-hline-regexp)
3923 (progn
3924 (beginning-of-line 2)
3925 (if (looking-at org-table-any-border-regexp)
3926 (beginning-of-line -1)))))
3927 (if (re-search-forward "|" (org-table-end t) t)
3928 (progn
3929 (require 'table)
3930 (if (table--at-cell-p (point))
3932 (message "recognizing table.el table...")
3933 (table-recognize-table)
3934 (message "recognizing table.el table...done")))
3935 (error "This should not happen"))
3937 nil)
3938 nil))
3940 (defun org-at-table-hline-p ()
3941 "Return t if the cursor is inside a hline in a table."
3942 (if org-enable-table-editor
3943 (save-excursion
3944 (beginning-of-line 1)
3945 (looking-at org-table-hline-regexp))
3946 nil))
3948 (defvar org-table-clean-did-remove-column nil)
3950 (defun org-table-map-tables (function &optional quietly)
3951 "Apply FUNCTION to the start of all tables in the buffer."
3952 (save-excursion
3953 (save-restriction
3954 (widen)
3955 (goto-char (point-min))
3956 (while (re-search-forward org-table-any-line-regexp nil t)
3957 (unless quietly
3958 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3959 (beginning-of-line 1)
3960 (when (and (looking-at org-table-line-regexp)
3961 ;; Exclude tables in src/example/verbatim/clocktable blocks
3962 (not (org-in-block-p '("src" "example"))))
3963 (save-excursion (funcall function))
3964 (or (looking-at org-table-line-regexp)
3965 (forward-char 1)))
3966 (re-search-forward org-table-any-border-regexp nil 1))))
3967 (unless quietly (message "Mapping tables: done")))
3969 ;; Declare and autoload functions from org-exp.el & Co
3971 (declare-function org-default-export-plist "org-exp")
3972 (declare-function org-infile-export-plist "org-exp")
3973 (declare-function org-get-current-options "org-exp")
3974 (eval-and-compile
3975 (org-autoload "org-exp"
3976 '(org-export org-export-visible
3977 org-insert-export-options-template
3978 org-table-clean-before-export))
3979 (org-autoload "org-ascii"
3980 '(org-export-as-ascii org-export-ascii-preprocess
3981 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3982 org-export-region-as-ascii))
3983 (org-autoload "org-latex"
3984 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3985 org-replace-region-by-latex org-export-region-as-latex
3986 org-export-as-latex org-export-as-pdf
3987 org-export-as-pdf-and-open))
3988 (org-autoload "org-html"
3989 '(org-export-as-html-and-open
3990 org-export-as-html-batch org-export-as-html-to-buffer
3991 org-replace-region-by-html org-export-region-as-html
3992 org-export-as-html))
3993 (org-autoload "org-docbook"
3994 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3995 org-replace-region-by-docbook org-export-region-as-docbook
3996 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3997 org-export-as-docbook))
3998 (org-autoload "org-icalendar"
3999 '(org-export-icalendar-this-file
4000 org-export-icalendar-all-agenda-files
4001 org-export-icalendar-combine-agenda-files))
4002 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4003 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4005 ;; Declare and autoload functions from org-agenda.el
4007 (eval-and-compile
4008 (org-autoload "org-agenda"
4009 '(org-agenda org-agenda-list org-search-view
4010 org-todo-list org-tags-view org-agenda-list-stuck-projects
4011 org-diary org-agenda-to-appt
4012 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4014 ;; Autoload org-remember
4016 (eval-and-compile
4017 (org-autoload "org-remember"
4018 '(org-remember-insinuate org-remember-annotation
4019 org-remember-apply-template org-remember org-remember-handler)))
4021 (eval-and-compile
4022 (org-autoload "org-capture"
4023 '(org-capture org-capture-insert-template-here
4024 org-capture-import-remember-templates)))
4026 ;; Autoload org-clock.el
4028 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4029 (beg end))
4030 (declare-function org-clock-update-mode-line "org-clock" ())
4031 (declare-function org-resolve-clocks "org-clock"
4032 (&optional also-non-dangling-p prompt last-valid))
4033 (defvar org-clock-start-time)
4034 (defvar org-clock-marker (make-marker)
4035 "Marker recording the last clock-in.")
4036 (defvar org-clock-hd-marker (make-marker)
4037 "Marker recording the last clock-in, but the headline position.")
4038 (defvar org-clock-heading ""
4039 "The heading of the current clock entry.")
4040 (defun org-clock-is-active ()
4041 "Return non-nil if clock is currently running.
4042 The return value is actually the clock marker."
4043 (marker-buffer org-clock-marker))
4045 (eval-and-compile
4046 (org-autoload
4047 "org-clock"
4048 '(org-clock-in org-clock-out org-clock-cancel
4049 org-clock-goto org-clock-sum org-clock-display
4050 org-clock-remove-overlays org-clock-report
4051 org-clocktable-shift org-dblock-write:clocktable
4052 org-get-clocktable org-resolve-clocks)))
4054 (defun org-clock-update-time-maybe ()
4055 "If this is a CLOCK line, update it and return t.
4056 Otherwise, return nil."
4057 (interactive)
4058 (save-excursion
4059 (beginning-of-line 1)
4060 (skip-chars-forward " \t")
4061 (when (looking-at org-clock-string)
4062 (let ((re (concat "[ \t]*" org-clock-string
4063 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4064 "\\([ \t]*=>.*\\)?\\)?"))
4065 ts te h m s neg)
4066 (cond
4067 ((not (looking-at re))
4068 nil)
4069 ((not (match-end 2))
4070 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4071 (> org-clock-marker (point))
4072 (<= org-clock-marker (point-at-eol)))
4073 ;; The clock is running here
4074 (setq org-clock-start-time
4075 (apply 'encode-time
4076 (org-parse-time-string (match-string 1))))
4077 (org-clock-update-mode-line)))
4079 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4080 (end-of-line 1)
4081 (setq ts (match-string 1)
4082 te (match-string 3))
4083 (setq s (- (org-float-time
4084 (apply 'encode-time (org-parse-time-string te)))
4085 (org-float-time
4086 (apply 'encode-time (org-parse-time-string ts))))
4087 neg (< s 0)
4088 s (abs s)
4089 h (floor (/ s 3600))
4090 s (- s (* 3600 h))
4091 m (floor (/ s 60))
4092 s (- s (* 60 s)))
4093 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4094 t))))))
4096 (defun org-check-running-clock ()
4097 "Check if the current buffer contains the running clock.
4098 If yes, offer to stop it and to save the buffer with the changes."
4099 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4100 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4101 (buffer-name))))
4102 (org-clock-out)
4103 (when (y-or-n-p "Save changed buffer?")
4104 (save-buffer))))
4106 (defun org-clocktable-try-shift (dir n)
4107 "Check if this line starts a clock table, if yes, shift the time block."
4108 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4109 (org-clocktable-shift dir n)))
4111 ;; Autoload org-timer.el
4113 (eval-and-compile
4114 (org-autoload
4115 "org-timer"
4116 '(org-timer-start org-timer org-timer-item
4117 org-timer-change-times-in-region
4118 org-timer-set-timer
4119 org-timer-reset-timers
4120 org-timer-show-remaining-time)))
4122 ;; Autoload org-feed.el
4124 (eval-and-compile
4125 (org-autoload
4126 "org-feed"
4127 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4130 ;; Autoload org-indent.el
4132 ;; Define the variable already here, to make sure we have it.
4133 (defvar org-indent-mode nil
4134 "Non-nil if Org-Indent mode is enabled.
4135 Use the command `org-indent-mode' to change this variable.")
4137 (eval-and-compile
4138 (org-autoload
4139 "org-indent"
4140 '(org-indent-mode)))
4142 ;; Autoload org-mobile.el
4144 (eval-and-compile
4145 (org-autoload
4146 "org-mobile"
4147 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4149 ;; Autoload archiving code
4150 ;; The stuff that is needed for cycling and tags has to be defined here.
4152 (defgroup org-archive nil
4153 "Options concerning archiving in Org-mode."
4154 :tag "Org Archive"
4155 :group 'org-structure)
4157 (defcustom org-archive-location "%s_archive::"
4158 "The location where subtrees should be archived.
4160 The value of this variable is a string, consisting of two parts,
4161 separated by a double-colon. The first part is a filename and
4162 the second part is a headline.
4164 When the filename is omitted, archiving happens in the same file.
4165 %s in the filename will be replaced by the current file
4166 name (without the directory part). Archiving to a different file
4167 is useful to keep archived entries from contributing to the
4168 Org-mode Agenda.
4170 The archived entries will be filed as subtrees of the specified
4171 headline. When the headline is omitted, the subtrees are simply
4172 filed away at the end of the file, as top-level entries. Also in
4173 the heading you can use %s to represent the file name, this can be
4174 useful when using the same archive for a number of different files.
4176 Here are a few examples:
4177 \"%s_archive::\"
4178 If the current file is Projects.org, archive in file
4179 Projects.org_archive, as top-level trees. This is the default.
4181 \"::* Archived Tasks\"
4182 Archive in the current file, under the top-level headline
4183 \"* Archived Tasks\".
4185 \"~/org/archive.org::\"
4186 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4188 \"~/org/archive.org::* From %s\"
4189 Archive in file ~/org/archive.org (absolute path), under headlines
4190 \"From FILENAME\" where file name is the current file name.
4192 \"~/org/datetree.org::datetree/* Finished Tasks\"
4193 The \"datetree/\" string is special, signifying to archive
4194 items to the datetree. Items are placed in either the CLOSED
4195 date of the item, or the current date if there is no CLOSED date.
4196 The heading will be a subentry to the current date. There doesn't
4197 need to be a heading, but there always needs to be a slash after
4198 datetree. For example, to store archived items directly in the
4199 datetree, use \"~/org/datetree.org::datetree/\".
4201 \"basement::** Finished Tasks\"
4202 Archive in file ./basement (relative path), as level 3 trees
4203 below the level 2 heading \"** Finished Tasks\".
4205 You may set this option on a per-file basis by adding to the buffer a
4206 line like
4208 #+ARCHIVE: basement::** Finished Tasks
4210 You may also define it locally for a subtree by setting an ARCHIVE property
4211 in the entry. If such a property is found in an entry, or anywhere up
4212 the hierarchy, it will be used."
4213 :group 'org-archive
4214 :type 'string)
4216 (defcustom org-archive-tag "ARCHIVE"
4217 "The tag that marks a subtree as archived.
4218 An archived subtree does not open during visibility cycling, and does
4219 not contribute to the agenda listings.
4220 After changing this, font-lock must be restarted in the relevant buffers to
4221 get the proper fontification."
4222 :group 'org-archive
4223 :group 'org-keywords
4224 :type 'string)
4226 (defcustom org-agenda-skip-archived-trees t
4227 "Non-nil means the agenda will skip any items located in archived trees.
4228 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4229 variable is no longer recommended, you should leave it at the value t.
4230 Instead, use the key `v' to cycle the archives-mode in the agenda."
4231 :group 'org-archive
4232 :group 'org-agenda-skip
4233 :type 'boolean)
4235 (defcustom org-columns-skip-archived-trees t
4236 "Non-nil means ignore archived trees when creating column view."
4237 :group 'org-archive
4238 :group 'org-properties
4239 :type 'boolean)
4241 (defcustom org-cycle-open-archived-trees nil
4242 "Non-nil means `org-cycle' will open archived trees.
4243 An archived tree is a tree marked with the tag ARCHIVE.
4244 When nil, archived trees will stay folded. You can still open them with
4245 normal outline commands like `show-all', but not with the cycling commands."
4246 :group 'org-archive
4247 :group 'org-cycle
4248 :type 'boolean)
4250 (defcustom org-sparse-tree-open-archived-trees nil
4251 "Non-nil means sparse tree construction shows matches in archived trees.
4252 When nil, matches in these trees are highlighted, but the trees are kept in
4253 collapsed state."
4254 :group 'org-archive
4255 :group 'org-sparse-trees
4256 :type 'boolean)
4258 (defun org-cycle-hide-archived-subtrees (state)
4259 "Re-hide all archived subtrees after a visibility state change."
4260 (when (and (not org-cycle-open-archived-trees)
4261 (not (memq state '(overview folded))))
4262 (save-excursion
4263 (let* ((globalp (memq state '(contents all)))
4264 (beg (if globalp (point-min) (point)))
4265 (end (if globalp (point-max) (org-end-of-subtree t))))
4266 (org-hide-archived-subtrees beg end)
4267 (goto-char beg)
4268 (if (looking-at (concat ".*:" org-archive-tag ":"))
4269 (message "%s" (substitute-command-keys
4270 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4272 (defun org-force-cycle-archived ()
4273 "Cycle subtree even if it is archived."
4274 (interactive)
4275 (setq this-command 'org-cycle)
4276 (let ((org-cycle-open-archived-trees t))
4277 (call-interactively 'org-cycle)))
4279 (defun org-hide-archived-subtrees (beg end)
4280 "Re-hide all archived subtrees after a visibility state change."
4281 (save-excursion
4282 (let* ((re (concat ":" org-archive-tag ":")))
4283 (goto-char beg)
4284 (while (re-search-forward re end t)
4285 (when (org-at-heading-p)
4286 (org-flag-subtree t)
4287 (org-end-of-subtree t))))))
4289 (defun org-flag-subtree (flag)
4290 (save-excursion
4291 (org-back-to-heading t)
4292 (outline-end-of-heading)
4293 (outline-flag-region (point)
4294 (progn (org-end-of-subtree t) (point))
4295 flag)))
4297 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4299 (eval-and-compile
4300 (org-autoload "org-archive"
4301 '(org-add-archive-files org-archive-subtree
4302 org-archive-to-archive-sibling org-toggle-archive-tag
4303 org-archive-subtree-default
4304 org-archive-subtree-default-with-confirmation)))
4306 ;; Autoload Column View Code
4308 (declare-function org-columns-number-to-string "org-colview")
4309 (declare-function org-columns-get-format-and-top-level "org-colview")
4310 (declare-function org-columns-compute "org-colview")
4312 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4313 '(org-columns-number-to-string org-columns-get-format-and-top-level
4314 org-columns-compute org-agenda-columns org-columns-remove-overlays
4315 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4317 ;; Autoload ID code
4319 (declare-function org-id-store-link "org-id")
4320 (declare-function org-id-locations-load "org-id")
4321 (declare-function org-id-locations-save "org-id")
4322 (defvar org-id-track-globally)
4323 (org-autoload "org-id"
4324 '(org-id-get-create org-id-new org-id-copy org-id-get
4325 org-id-get-with-outline-path-completion
4326 org-id-get-with-outline-drilling org-id-store-link
4327 org-id-goto org-id-find org-id-store-link))
4329 ;; Autoload Plotting Code
4331 (org-autoload "org-plot"
4332 '(org-plot/gnuplot))
4334 ;;; Variables for pre-computed regular expressions, all buffer local
4336 (defvar org-drawer-regexp nil
4337 "Matches first line of a hidden block.")
4338 (make-variable-buffer-local 'org-drawer-regexp)
4339 (defvar org-todo-regexp nil
4340 "Matches any of the TODO state keywords.")
4341 (make-variable-buffer-local 'org-todo-regexp)
4342 (defvar org-not-done-regexp nil
4343 "Matches any of the TODO state keywords except the last one.")
4344 (make-variable-buffer-local 'org-not-done-regexp)
4345 (defvar org-not-done-heading-regexp nil
4346 "Matches a TODO headline that is not done.")
4347 (make-variable-buffer-local 'org-not-done-regexp)
4348 (defvar org-todo-line-regexp nil
4349 "Matches a headline and puts TODO state into group 2 if present.")
4350 (make-variable-buffer-local 'org-todo-line-regexp)
4351 (defvar org-complex-heading-regexp nil
4352 "Matches a headline and puts everything into groups:
4353 group 1: the stars
4354 group 2: The todo keyword, maybe
4355 group 3: Priority cookie
4356 group 4: True headline
4357 group 5: Tags")
4358 (make-variable-buffer-local 'org-complex-heading-regexp)
4359 (defvar org-complex-heading-regexp-format nil
4360 "Printf format to make regexp to match an exact headline.
4361 This regexp will match the headline of any node which has the
4362 exact headline text that is put into the format, but may have any
4363 TODO state, priority and tags.")
4364 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4365 (defvar org-todo-line-tags-regexp nil
4366 "Matches a headline and puts TODO state into group 2 if present.
4367 Also put tags into group 4 if tags are present.")
4368 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4369 (defvar org-ds-keyword-length 12
4370 "Maximum length of the Deadline and SCHEDULED keywords.")
4371 (make-variable-buffer-local 'org-ds-keyword-length)
4372 (defvar org-deadline-regexp nil
4373 "Matches the DEADLINE keyword.")
4374 (make-variable-buffer-local 'org-deadline-regexp)
4375 (defvar org-deadline-time-regexp nil
4376 "Matches the DEADLINE keyword together with a time stamp.")
4377 (make-variable-buffer-local 'org-deadline-time-regexp)
4378 (defvar org-deadline-line-regexp nil
4379 "Matches the DEADLINE keyword and the rest of the line.")
4380 (make-variable-buffer-local 'org-deadline-line-regexp)
4381 (defvar org-scheduled-regexp nil
4382 "Matches the SCHEDULED keyword.")
4383 (make-variable-buffer-local 'org-scheduled-regexp)
4384 (defvar org-scheduled-time-regexp nil
4385 "Matches the SCHEDULED keyword together with a time stamp.")
4386 (make-variable-buffer-local 'org-scheduled-time-regexp)
4387 (defvar org-closed-time-regexp nil
4388 "Matches the CLOSED keyword together with a time stamp.")
4389 (make-variable-buffer-local 'org-closed-time-regexp)
4391 (defvar org-keyword-time-regexp nil
4392 "Matches any of the 4 keywords, together with the time stamp.")
4393 (make-variable-buffer-local 'org-keyword-time-regexp)
4394 (defvar org-keyword-time-not-clock-regexp nil
4395 "Matches any of the 3 keywords, together with the time stamp.")
4396 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4397 (defvar org-maybe-keyword-time-regexp nil
4398 "Matches a timestamp, possibly preceded by a keyword.")
4399 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4400 (defvar org-planning-or-clock-line-re nil
4401 "Matches a line with planning or clock info.")
4402 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4403 (defvar org-all-time-keywords nil
4404 "List of time keywords.")
4405 (make-variable-buffer-local 'org-all-time-keywords)
4407 (defconst org-plain-time-of-day-regexp
4408 (concat
4409 "\\(\\<[012]?[0-9]"
4410 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4411 "\\(--?"
4412 "\\(\\<[012]?[0-9]"
4413 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4414 "\\)?")
4415 "Regular expression to match a plain time or time range.
4416 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4417 groups carry important information:
4418 0 the full match
4419 1 the first time, range or not
4420 8 the second time, if it is a range.")
4422 (defconst org-plain-time-extension-regexp
4423 (concat
4424 "\\(\\<[012]?[0-9]"
4425 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4426 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4427 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4428 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4429 groups carry important information:
4430 0 the full match
4431 7 hours of duration
4432 9 minutes of duration")
4434 (defconst org-stamp-time-of-day-regexp
4435 (concat
4436 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4437 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4438 "\\(--?"
4439 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4440 "Regular expression to match a timestamp time or time range.
4441 After a match, the following groups carry important information:
4442 0 the full match
4443 1 date plus weekday, for back referencing to make sure both times are on the same day
4444 2 the first time, range or not
4445 4 the second time, if it is a range.")
4447 (defconst org-startup-options
4448 '(("fold" org-startup-folded t)
4449 ("overview" org-startup-folded t)
4450 ("nofold" org-startup-folded nil)
4451 ("showall" org-startup-folded nil)
4452 ("showeverything" org-startup-folded showeverything)
4453 ("content" org-startup-folded content)
4454 ("indent" org-startup-indented t)
4455 ("noindent" org-startup-indented nil)
4456 ("hidestars" org-hide-leading-stars t)
4457 ("showstars" org-hide-leading-stars nil)
4458 ("odd" org-odd-levels-only t)
4459 ("oddeven" org-odd-levels-only nil)
4460 ("align" org-startup-align-all-tables t)
4461 ("noalign" org-startup-align-all-tables nil)
4462 ("inlineimages" org-startup-with-inline-images t)
4463 ("noinlineimages" org-startup-with-inline-images nil)
4464 ("customtime" org-display-custom-times t)
4465 ("logdone" org-log-done time)
4466 ("lognotedone" org-log-done note)
4467 ("nologdone" org-log-done nil)
4468 ("lognoteclock-out" org-log-note-clock-out t)
4469 ("nolognoteclock-out" org-log-note-clock-out nil)
4470 ("logrepeat" org-log-repeat state)
4471 ("lognoterepeat" org-log-repeat note)
4472 ("nologrepeat" org-log-repeat nil)
4473 ("logreschedule" org-log-reschedule time)
4474 ("lognotereschedule" org-log-reschedule note)
4475 ("nologreschedule" org-log-reschedule nil)
4476 ("logredeadline" org-log-redeadline time)
4477 ("lognoteredeadline" org-log-redeadline note)
4478 ("nologredeadline" org-log-redeadline nil)
4479 ("logrefile" org-log-refile time)
4480 ("lognoterefile" org-log-refile note)
4481 ("nologrefile" org-log-refile nil)
4482 ("fninline" org-footnote-define-inline t)
4483 ("nofninline" org-footnote-define-inline nil)
4484 ("fnlocal" org-footnote-section nil)
4485 ("fnauto" org-footnote-auto-label t)
4486 ("fnprompt" org-footnote-auto-label nil)
4487 ("fnconfirm" org-footnote-auto-label confirm)
4488 ("fnplain" org-footnote-auto-label plain)
4489 ("fnadjust" org-footnote-auto-adjust t)
4490 ("nofnadjust" org-footnote-auto-adjust nil)
4491 ("constcgs" constants-unit-system cgs)
4492 ("constSI" constants-unit-system SI)
4493 ("noptag" org-tag-persistent-alist nil)
4494 ("hideblocks" org-hide-block-startup t)
4495 ("nohideblocks" org-hide-block-startup nil)
4496 ("beamer" org-startup-with-beamer-mode t)
4497 ("entitiespretty" org-pretty-entities t)
4498 ("entitiesplain" org-pretty-entities nil))
4499 "Variable associated with STARTUP options for org-mode.
4500 Each element is a list of three items: The startup options as written
4501 in the #+STARTUP line, the corresponding variable, and the value to
4502 set this variable to if the option is found. An optional forth element PUSH
4503 means to push this value onto the list in the variable.")
4505 (defun org-update-property-plist (key val props)
4506 "Update PROPS with KEY and VAL."
4507 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4508 (key (if appending (substring key 0 (- (length key) 1)) key))
4509 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4510 (previous (cdr (assoc key props))))
4511 (if appending
4512 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4513 (cons (cons key val) remainder))))
4515 (defconst org-block-regexp
4516 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4517 "Regular expression for hiding blocks.")
4518 (defconst org-heading-keyword-regexp-format
4519 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4520 "Printf format for a regexp matching an headline with some keyword.
4521 This regexp will match the headline of any node which has the
4522 exact keyword that is put into the format. The keyword isn't in
4523 any group by default, but the stars and the body are.")
4524 (defconst org-heading-keyword-maybe-regexp-format
4525 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4526 "Printf format for a regexp matching an headline, possibly with some keyword.
4527 This regexp can match any headline with the specified keyword, or
4528 without a keyword. The keyword isn't in any group by default,
4529 but the stars and the body are.")
4531 (defun org-set-regexps-and-options ()
4532 "Precompute regular expressions for current buffer."
4533 (when (derived-mode-p 'org-mode)
4534 (org-set-local 'org-todo-kwd-alist nil)
4535 (org-set-local 'org-todo-key-alist nil)
4536 (org-set-local 'org-todo-key-trigger nil)
4537 (org-set-local 'org-todo-keywords-1 nil)
4538 (org-set-local 'org-done-keywords nil)
4539 (org-set-local 'org-todo-heads nil)
4540 (org-set-local 'org-todo-sets nil)
4541 (org-set-local 'org-todo-log-states nil)
4542 (org-set-local 'org-file-properties nil)
4543 (org-set-local 'org-file-tags nil)
4544 (let ((re (org-make-options-regexp
4545 '("CATEGORY" "TODO" "COLUMNS"
4546 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4547 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4548 "OPTIONS")
4549 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4550 (splitre "[ \t]+")
4551 (scripts org-use-sub-superscripts)
4552 kwds kws0 kwsa key log value cat arch tags const links hw dws
4553 tail sep kws1 prio props ftags drawers beamer-p
4554 ext-setup-or-nil setup-contents (start 0))
4555 (save-excursion
4556 (save-restriction
4557 (widen)
4558 (goto-char (point-min))
4559 (while (or (and ext-setup-or-nil
4560 (string-match re ext-setup-or-nil start)
4561 (setq start (match-end 0)))
4562 (and (setq ext-setup-or-nil nil start 0)
4563 (re-search-forward re nil t)))
4564 (setq key (upcase (match-string 1 ext-setup-or-nil))
4565 value (org-match-string-no-properties 2 ext-setup-or-nil))
4566 (if (stringp value) (setq value (org-trim value)))
4567 (cond
4568 ((equal key "CATEGORY")
4569 (setq cat value))
4570 ((member key '("SEQ_TODO" "TODO"))
4571 (push (cons 'sequence (org-split-string value splitre)) kwds))
4572 ((equal key "TYP_TODO")
4573 (push (cons 'type (org-split-string value splitre)) kwds))
4574 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4575 ;; general TODO-like setup
4576 (push (cons (intern (downcase (match-string 1 key)))
4577 (org-split-string value splitre)) kwds))
4578 ((equal key "TAGS")
4579 (setq tags (append tags (if tags '("\\n") nil)
4580 (org-split-string value splitre))))
4581 ((equal key "COLUMNS")
4582 (org-set-local 'org-columns-default-format value))
4583 ((equal key "LINK")
4584 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4585 (push (cons (match-string 1 value)
4586 (org-trim (match-string 2 value)))
4587 links)))
4588 ((equal key "PRIORITIES")
4589 (setq prio (org-split-string value " +")))
4590 ((equal key "PROPERTY")
4591 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4592 (setq props (org-update-property-plist (match-string 1 value)
4593 (match-string 2 value)
4594 props))))
4595 ((equal key "FILETAGS")
4596 (when (string-match "\\S-" value)
4597 (setq ftags
4598 (append
4599 ftags
4600 (apply 'append
4601 (mapcar (lambda (x) (org-split-string x ":"))
4602 (org-split-string value)))))))
4603 ((equal key "DRAWERS")
4604 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4605 ((equal key "CONSTANTS")
4606 (setq const (append const (org-split-string value splitre))))
4607 ((equal key "STARTUP")
4608 (let ((opts (org-split-string value splitre))
4609 l var val)
4610 (while (setq l (pop opts))
4611 (when (setq l (assoc l org-startup-options))
4612 (setq var (nth 1 l) val (nth 2 l))
4613 (if (not (nth 3 l))
4614 (set (make-local-variable var) val)
4615 (if (not (listp (symbol-value var)))
4616 (set (make-local-variable var) nil))
4617 (set (make-local-variable var) (symbol-value var))
4618 (add-to-list var val))))))
4619 ((equal key "ARCHIVE")
4620 (setq arch value)
4621 (remove-text-properties 0 (length arch)
4622 '(face t fontified t) arch))
4623 ((equal key "LATEX_CLASS")
4624 (setq beamer-p (equal value "beamer")))
4625 ((equal key "OPTIONS")
4626 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4627 (setq scripts (read (match-string 2 value)))))
4628 ((equal key "SETUPFILE")
4629 (setq setup-contents (org-file-contents
4630 (expand-file-name
4631 (org-remove-double-quotes value))
4632 'noerror))
4633 (if (not ext-setup-or-nil)
4634 (setq ext-setup-or-nil setup-contents start 0)
4635 (setq ext-setup-or-nil
4636 (concat (substring ext-setup-or-nil 0 start)
4637 "\n" setup-contents "\n"
4638 (substring ext-setup-or-nil start)))))))
4639 ;; search for property blocks
4640 (goto-char (point-min))
4641 (while (re-search-forward org-block-regexp nil t)
4642 (when (equal "PROPERTY" (upcase (match-string 1)))
4643 (setq value (replace-regexp-in-string
4644 "[\n\r]" " " (match-string 4)))
4645 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4646 (setq props (org-update-property-plist (match-string 1 value)
4647 (match-string 2 value)
4648 props)))))))
4649 (org-set-local 'org-use-sub-superscripts scripts)
4650 (when cat
4651 (org-set-local 'org-category (intern cat))
4652 (push (cons "CATEGORY" cat) props))
4653 (when prio
4654 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4655 (setq prio (mapcar 'string-to-char prio))
4656 (org-set-local 'org-highest-priority (nth 0 prio))
4657 (org-set-local 'org-lowest-priority (nth 1 prio))
4658 (org-set-local 'org-default-priority (nth 2 prio)))
4659 (and props (org-set-local 'org-file-properties (nreverse props)))
4660 (and ftags (org-set-local 'org-file-tags
4661 (mapcar 'org-add-prop-inherited ftags)))
4662 (and drawers (org-set-local 'org-drawers drawers))
4663 (and arch (org-set-local 'org-archive-location arch))
4664 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4665 ;; Process the TODO keywords
4666 (unless kwds
4667 ;; Use the global values as if they had been given locally.
4668 (setq kwds (default-value 'org-todo-keywords))
4669 (if (stringp (car kwds))
4670 (setq kwds (list (cons org-todo-interpretation
4671 (default-value 'org-todo-keywords)))))
4672 (setq kwds (reverse kwds)))
4673 (setq kwds (nreverse kwds))
4674 (let (inter kws kw)
4675 (while (setq kws (pop kwds))
4676 (let ((kws (or
4677 (run-hook-with-args-until-success
4678 'org-todo-setup-filter-hook kws)
4679 kws)))
4680 (setq inter (pop kws) sep (member "|" kws)
4681 kws0 (delete "|" (copy-sequence kws))
4682 kwsa nil
4683 kws1 (mapcar
4684 (lambda (x)
4685 ;; 1 2
4686 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4687 (progn
4688 (setq kw (match-string 1 x)
4689 key (and (match-end 2) (match-string 2 x))
4690 log (org-extract-log-state-settings x))
4691 (push (cons kw (and key (string-to-char key))) kwsa)
4692 (and log (push log org-todo-log-states))
4694 (error "Invalid TODO keyword %s" x)))
4695 kws0)
4696 kwsa (if kwsa (append '((:startgroup))
4697 (nreverse kwsa)
4698 '((:endgroup))))
4699 hw (car kws1)
4700 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4701 tail (list inter hw (car dws) (org-last dws))))
4702 (add-to-list 'org-todo-heads hw 'append)
4703 (push kws1 org-todo-sets)
4704 (setq org-done-keywords (append org-done-keywords dws nil))
4705 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4706 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4707 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4708 (setq org-todo-sets (nreverse org-todo-sets)
4709 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4710 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4711 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4712 ;; Process the constants
4713 (when const
4714 (let (e cst)
4715 (while (setq e (pop const))
4716 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4717 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4718 (setq org-table-formula-constants-local cst)))
4720 ;; Process the tags.
4721 (when tags
4722 (let (e tgs)
4723 (while (setq e (pop tags))
4724 (cond
4725 ((equal e "{") (push '(:startgroup) tgs))
4726 ((equal e "}") (push '(:endgroup) tgs))
4727 ((equal e "\\n") (push '(:newline) tgs))
4728 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4729 (push (cons (match-string 1 e)
4730 (string-to-char (match-string 2 e)))
4731 tgs))
4732 (t (push (list e) tgs))))
4733 (org-set-local 'org-tag-alist nil)
4734 (while (setq e (pop tgs))
4735 (or (and (stringp (car e))
4736 (assoc (car e) org-tag-alist))
4737 (push e org-tag-alist)))))
4739 ;; Compute the regular expressions and other local variables.
4740 ;; Using `org-outline-regexp-bol' would complicate them much,
4741 ;; because of the fixed white space at the end of that string.
4742 (if (not org-done-keywords)
4743 (setq org-done-keywords (and org-todo-keywords-1
4744 (list (org-last org-todo-keywords-1)))))
4745 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4746 (length org-scheduled-string)
4747 (length org-clock-string)
4748 (length org-closed-string)))
4749 org-drawer-regexp
4750 (concat "^[ \t]*:\\("
4751 (mapconcat 'regexp-quote org-drawers "\\|")
4752 "\\):[ \t]*$")
4753 org-not-done-keywords
4754 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4755 org-todo-regexp
4756 (concat "\\("
4757 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4758 "\\)")
4759 org-not-done-regexp
4760 (concat "\\("
4761 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4762 "\\)")
4763 org-not-done-heading-regexp
4764 (format org-heading-keyword-regexp-format org-not-done-regexp)
4765 org-todo-line-regexp
4766 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4767 org-complex-heading-regexp
4768 (concat "^\\(\\*+\\)"
4769 "\\(?: +" org-todo-regexp "\\)?"
4770 "\\(?: +\\(\\[#.\\]\\)\\)?"
4771 "\\(?: +\\(.*?\\)\\)?"
4772 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4773 "[ \t]*$")
4774 org-complex-heading-regexp-format
4775 (concat "^\\(\\*+\\)"
4776 "\\(?: +" org-todo-regexp "\\)?"
4777 "\\(?: +\\(\\[#.\\]\\)\\)?"
4778 "\\(?: +"
4779 ;; Stats cookies can be stuck to body.
4780 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4781 "\\(%s\\)"
4782 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4783 "\\)"
4784 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4785 "[ \t]*$")
4786 org-todo-line-tags-regexp
4787 (concat "^\\(\\*+\\)"
4788 "\\(?: +" org-todo-regexp "\\)?"
4789 "\\(?: +\\(.*?\\)\\)?"
4790 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4791 "[ \t]*$")
4792 org-deadline-regexp (concat "\\<" org-deadline-string)
4793 org-deadline-time-regexp
4794 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4795 org-deadline-line-regexp
4796 (concat "\\<\\(" org-deadline-string "\\).*")
4797 org-scheduled-regexp
4798 (concat "\\<" org-scheduled-string)
4799 org-scheduled-time-regexp
4800 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4801 org-closed-time-regexp
4802 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4803 org-keyword-time-regexp
4804 (concat "\\<\\(" org-scheduled-string
4805 "\\|" org-deadline-string
4806 "\\|" org-closed-string
4807 "\\|" org-clock-string "\\)"
4808 " *[[<]\\([^]>]+\\)[]>]")
4809 org-keyword-time-not-clock-regexp
4810 (concat "\\<\\(" org-scheduled-string
4811 "\\|" org-deadline-string
4812 "\\|" org-closed-string
4813 "\\)"
4814 " *[[<]\\([^]>]+\\)[]>]")
4815 org-maybe-keyword-time-regexp
4816 (concat "\\(\\<\\(" org-scheduled-string
4817 "\\|" org-deadline-string
4818 "\\|" org-closed-string
4819 "\\|" org-clock-string "\\)\\)?"
4820 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4821 org-planning-or-clock-line-re
4822 (concat "^[ \t]*\\("
4823 org-scheduled-string "\\|"
4824 org-deadline-string "\\|"
4825 org-closed-string "\\|"
4826 org-clock-string "\\)")
4827 org-all-time-keywords
4828 (mapcar (lambda (w) (substring w 0 -1))
4829 (list org-scheduled-string org-deadline-string
4830 org-clock-string org-closed-string))
4832 (org-compute-latex-and-specials-regexp)
4833 (org-set-font-lock-defaults))))
4835 (defun org-file-contents (file &optional noerror)
4836 "Return the contents of FILE, as a string."
4837 (if (or (not file)
4838 (not (file-readable-p file)))
4839 (if noerror
4840 (progn
4841 (message "Cannot read file \"%s\"" file)
4842 (ding) (sit-for 2)
4844 (error "Cannot read file \"%s\"" file))
4845 (with-temp-buffer
4846 (insert-file-contents file)
4847 (buffer-string))))
4849 (defun org-extract-log-state-settings (x)
4850 "Extract the log state setting from a TODO keyword string.
4851 This will extract info from a string like \"WAIT(w@/!)\"."
4852 (let (kw key log1 log2)
4853 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4854 (setq kw (match-string 1 x)
4855 key (and (match-end 2) (match-string 2 x))
4856 log1 (and (match-end 3) (match-string 3 x))
4857 log2 (and (match-end 4) (match-string 4 x)))
4858 (and (or log1 log2)
4859 (list kw
4860 (and log1 (if (equal log1 "!") 'time 'note))
4861 (and log2 (if (equal log2 "!") 'time 'note)))))))
4863 (defun org-remove-keyword-keys (list)
4864 "Remove a pair of parenthesis at the end of each string in LIST."
4865 (mapcar (lambda (x)
4866 (if (string-match "(.*)$" x)
4867 (substring x 0 (match-beginning 0))
4869 list))
4871 (defun org-assign-fast-keys (alist)
4872 "Assign fast keys to a keyword-key alist.
4873 Respect keys that are already there."
4874 (let (new e (alt ?0))
4875 (while (setq e (pop alist))
4876 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4877 (cdr e)) ;; Key already assigned.
4878 (push e new)
4879 (let ((clist (string-to-list (downcase (car e))))
4880 (used (append new alist)))
4881 (when (= (car clist) ?@)
4882 (pop clist))
4883 (while (and clist (rassoc (car clist) used))
4884 (pop clist))
4885 (unless clist
4886 (while (rassoc alt used)
4887 (incf alt)))
4888 (push (cons (car e) (or (car clist) alt)) new))))
4889 (nreverse new)))
4891 ;;; Some variables used in various places
4893 (defvar org-window-configuration nil
4894 "Used in various places to store a window configuration.")
4895 (defvar org-selected-window nil
4896 "Used in various places to store a window configuration.")
4897 (defvar org-finish-function nil
4898 "Function to be called when `C-c C-c' is used.
4899 This is for getting out of special buffers like remember.")
4902 ;; FIXME: Occasionally check by commenting these, to make sure
4903 ;; no other functions uses these, forgetting to let-bind them.
4904 (with-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4905 (defvar org-last-state)
4906 (with-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4908 ;; Defined somewhere in this file, but used before definition.
4909 (defvar org-entities) ;; defined in org-entities.el
4910 (defvar org-struct-menu)
4911 (defvar org-org-menu)
4912 (defvar org-tbl-menu)
4914 ;;;; Define the Org-mode
4916 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4917 (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"))
4920 ;; We use a before-change function to check if a table might need
4921 ;; an update.
4922 (defvar org-table-may-need-update t
4923 "Indicates that a table might need an update.
4924 This variable is set by `org-before-change-function'.
4925 `org-table-align' sets it back to nil.")
4926 (defun org-before-change-function (beg end)
4927 "Every change indicates that a table might need an update."
4928 (setq org-table-may-need-update t))
4929 (defvar org-mode-map)
4930 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4931 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4932 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4933 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4934 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4935 (defvar org-table-buffer-is-an nil)
4937 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4938 ;; some places -- e.g. see the macro org-with-limited-levels.
4940 ;; In Org buffers, the value of `outline-regexp' is that of
4941 ;; `org-outline-regexp'. The only function still directly relying on
4942 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4943 ;; job when `orgstruct-mode' is active.
4944 (defvar org-outline-regexp "\\*+ "
4945 "Regexp to match Org headlines.")
4946 (defconst org-outline-regexp-bol "^\\*+ "
4947 "Regexp to match Org headlines.
4948 This is similar to `org-outline-regexp' but additionally makes
4949 sure that we are at the beginning of the line.")
4951 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4952 "Matches an headline, putting stars and text into groups.
4953 Stars are put in group 1 and the trimmed body in group 2.")
4955 (defvar bidi-paragraph-direction)
4956 (defvar buffer-face-mode-face)
4958 ;;;###autoload
4959 (define-derived-mode org-mode outline-mode "Org"
4960 "Outline-based notes management and organizer, alias
4961 \"Carsten's outline-mode for keeping track of everything.\"
4963 Org-mode develops organizational tasks around a NOTES file which
4964 contains information about projects as plain text. Org-mode is
4965 implemented on top of outline-mode, which is ideal to keep the content
4966 of large files well structured. It supports ToDo items, deadlines and
4967 time stamps, which magically appear in the diary listing of the Emacs
4968 calendar. Tables are easily created with a built-in table editor.
4969 Plain text URL-like links connect to websites, emails (VM), Usenet
4970 messages (Gnus), BBDB entries, and any files related to the project.
4971 For printing and sharing of notes, an Org-mode file (or a part of it)
4972 can be exported as a structured ASCII or HTML file.
4974 The following commands are available:
4976 \\{org-mode-map}"
4978 ;; Get rid of Outline menus, they are not needed
4979 ;; Need to do this here because define-derived-mode sets up
4980 ;; the keymap so late. Still, it is a waste to call this each time
4981 ;; we switch another buffer into org-mode.
4982 (if (featurep 'xemacs)
4983 (when (boundp 'outline-mode-menu-heading)
4984 ;; Assume this is Greg's port, it uses easymenu
4985 (easy-menu-remove outline-mode-menu-heading)
4986 (easy-menu-remove outline-mode-menu-show)
4987 (easy-menu-remove outline-mode-menu-hide))
4988 (define-key org-mode-map [menu-bar headings] 'undefined)
4989 (define-key org-mode-map [menu-bar hide] 'undefined)
4990 (define-key org-mode-map [menu-bar show] 'undefined))
4992 (org-load-modules-maybe)
4993 (easy-menu-add org-org-menu)
4994 (easy-menu-add org-tbl-menu)
4995 (org-install-agenda-files-menu)
4996 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4997 (add-to-invisibility-spec '(org-cwidth))
4998 (add-to-invisibility-spec '(org-hide-block . t))
4999 (when (featurep 'xemacs)
5000 (org-set-local 'line-move-ignore-invisible t))
5001 (org-set-local 'outline-regexp org-outline-regexp)
5002 (org-set-local 'outline-level 'org-outline-level)
5003 (setq bidi-paragraph-direction 'left-to-right)
5004 (when (and org-ellipsis
5005 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5006 (fboundp 'make-glyph-code))
5007 (unless org-display-table
5008 (setq org-display-table (make-display-table)))
5009 (set-display-table-slot
5010 org-display-table 4
5011 (vconcat (mapcar
5012 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5013 org-ellipsis)))
5014 (if (stringp org-ellipsis) org-ellipsis "..."))))
5015 (setq buffer-display-table org-display-table))
5016 (org-set-regexps-and-options)
5017 (when (and org-tag-faces (not org-tags-special-faces-re))
5018 ;; tag faces set outside customize.... force initialization.
5019 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5020 ;; Calc embedded
5021 (org-set-local 'calc-embedded-open-mode "# ")
5022 (modify-syntax-entry ?@ "w")
5023 (if org-startup-truncated (setq truncate-lines t))
5024 (org-set-local 'font-lock-unfontify-region-function
5025 'org-unfontify-region)
5026 ;; Activate before-change-function
5027 (org-set-local 'org-table-may-need-update t)
5028 (org-add-hook 'before-change-functions 'org-before-change-function nil
5029 'local)
5030 ;; Check for running clock before killing a buffer
5031 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5032 ;; Paragraphs and auto-filling
5033 (org-set-autofill-regexps)
5034 (setq indent-line-function 'org-indent-line-function)
5035 (org-update-radio-target-regexp)
5036 ;; Beginning/end of defun
5037 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5038 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5039 ;; Next error for sparse trees
5040 (org-set-local 'next-error-function 'org-occur-next-match)
5041 ;; Make sure dependence stuff works reliably, even for users who set it
5042 ;; too late :-(
5043 (if org-enforce-todo-dependencies
5044 (add-hook 'org-blocker-hook
5045 'org-block-todo-from-children-or-siblings-or-parent)
5046 (remove-hook 'org-blocker-hook
5047 'org-block-todo-from-children-or-siblings-or-parent))
5048 (if org-enforce-todo-checkbox-dependencies
5049 (add-hook 'org-blocker-hook
5050 'org-block-todo-from-checkboxes)
5051 (remove-hook 'org-blocker-hook
5052 'org-block-todo-from-checkboxes))
5054 ;; Comment characters
5055 (org-set-local 'comment-start "#")
5056 (org-set-local 'comment-padding " ")
5058 ;; Align options lines
5059 (org-set-local
5060 'align-mode-rules-list
5061 '((org-in-buffer-settings
5062 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5063 (modes . '(org-mode)))))
5065 ;; Imenu
5066 (org-set-local 'imenu-create-index-function
5067 'org-imenu-get-tree)
5069 ;; Make isearch reveal context
5070 (if (or (featurep 'xemacs)
5071 (not (boundp 'outline-isearch-open-invisible-function)))
5072 ;; Emacs 21 and XEmacs make use of the hook
5073 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5074 ;; Emacs 22 deals with this through a special variable
5075 (org-set-local 'outline-isearch-open-invisible-function
5076 (lambda (&rest ignore) (org-show-context 'isearch))))
5078 ;; Turn on org-beamer-mode?
5079 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5081 ;; Setup the pcomplete hooks
5082 (set (make-local-variable 'pcomplete-command-completion-function)
5083 'org-pcomplete-initial)
5084 (set (make-local-variable 'pcomplete-command-name-function)
5085 'org-command-at-point)
5086 (set (make-local-variable 'pcomplete-default-completion-function)
5087 'ignore)
5088 (set (make-local-variable 'pcomplete-parse-arguments-function)
5089 'org-parse-arguments)
5090 (set (make-local-variable 'pcomplete-termination-string) "")
5091 (when (>= emacs-major-version 23)
5092 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5094 ;; If empty file that did not turn on org-mode automatically, make it to.
5095 (if (and org-insert-mode-line-in-empty-file
5096 (org-called-interactively-p 'any)
5097 (= (point-min) (point-max)))
5098 (insert "# -*- mode: org -*-\n\n"))
5099 (unless org-inhibit-startup
5100 (when org-startup-align-all-tables
5101 (let ((bmp (buffer-modified-p)))
5102 (org-table-map-tables 'org-table-align 'quietly)
5103 (set-buffer-modified-p bmp)))
5104 (when org-startup-with-inline-images
5105 (org-display-inline-images))
5106 (when org-startup-indented
5107 (require 'org-indent)
5108 (org-indent-mode 1))
5109 (unless org-inhibit-startup-visibility-stuff
5110 (org-set-startup-visibility))))
5112 (when (fboundp 'abbrev-table-put)
5113 (abbrev-table-put org-mode-abbrev-table
5114 :parents (list text-mode-abbrev-table)))
5116 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5118 (defun org-current-time ()
5119 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5120 (if (> (car org-time-stamp-rounding-minutes) 1)
5121 (let ((r (car org-time-stamp-rounding-minutes))
5122 (time (decode-time)))
5123 (apply 'encode-time
5124 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5125 (nthcdr 2 time))))
5126 (current-time)))
5128 (defun org-today ()
5129 "Return today date, considering `org-extend-today-until'."
5130 (time-to-days
5131 (time-subtract (current-time)
5132 (list 0 (* 3600 org-extend-today-until) 0))))
5134 ;;;; Font-Lock stuff, including the activators
5136 (defvar org-mouse-map (make-sparse-keymap))
5137 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5138 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5139 (when org-mouse-1-follows-link
5140 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5141 (when org-tab-follows-link
5142 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5143 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5145 (require 'font-lock)
5147 (defconst org-non-link-chars "]\t\n\r<>")
5148 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5149 "shell" "elisp" "doi" "message"))
5150 (defvar org-link-types-re nil
5151 "Matches a link that has a url-like prefix like \"http:\"")
5152 (defvar org-link-re-with-space nil
5153 "Matches a link with spaces, optional angular brackets around it.")
5154 (defvar org-link-re-with-space2 nil
5155 "Matches a link with spaces, optional angular brackets around it.")
5156 (defvar org-link-re-with-space3 nil
5157 "Matches a link with spaces, only for internal part in bracket links.")
5158 (defvar org-angle-link-re nil
5159 "Matches link with angular brackets, spaces are allowed.")
5160 (defvar org-plain-link-re nil
5161 "Matches plain link, without spaces.")
5162 (defvar org-bracket-link-regexp nil
5163 "Matches a link in double brackets.")
5164 (defvar org-bracket-link-analytic-regexp nil
5165 "Regular expression used to analyze links.
5166 Here is what the match groups contain after a match:
5167 1: http:
5168 2: http
5169 3: path
5170 4: [desc]
5171 5: desc")
5172 (defvar org-bracket-link-analytic-regexp++ nil
5173 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5174 (defvar org-any-link-re nil
5175 "Regular expression matching any link.")
5177 (defcustom org-match-sexp-depth 3
5178 "Number of stacked braces for sub/superscript matching.
5179 This has to be set before loading org.el to be effective."
5180 :group 'org-export-translation ; ??????????????????????????/
5181 :type 'integer)
5183 (defun org-create-multibrace-regexp (left right n)
5184 "Create a regular expression which will match a balanced sexp.
5185 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5186 as single character strings.
5187 The regexp returned will match the entire expression including the
5188 delimiters. It will also define a single group which contains the
5189 match except for the outermost delimiters. The maximum depth of
5190 stacked delimiters is N. Escaping delimiters is not possible."
5191 (let* ((nothing (concat "[^" left right "]*?"))
5192 (or "\\|")
5193 (re nothing)
5194 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5195 (while (> n 1)
5196 (setq n (1- n)
5197 re (concat re or next)
5198 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5199 (concat left "\\(" re "\\)" right)))
5201 (defvar org-match-substring-regexp
5202 (concat
5203 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5204 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5205 "\\|"
5206 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5207 "\\|"
5208 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5209 "The regular expression matching a sub- or superscript.")
5211 (defvar org-match-substring-with-braces-regexp
5212 (concat
5213 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5214 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5215 "\\)")
5216 "The regular expression matching a sub- or superscript, forcing braces.")
5218 (defun org-make-link-regexps ()
5219 "Update the link regular expressions.
5220 This should be called after the variable `org-link-types' has changed."
5221 (setq org-link-types-re
5222 (concat
5223 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5224 org-link-re-with-space
5225 (concat
5226 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5227 "\\([^" org-non-link-chars " ]"
5228 "[^" org-non-link-chars "]*"
5229 "[^" org-non-link-chars " ]\\)>?")
5230 org-link-re-with-space2
5231 (concat
5232 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5233 "\\([^" org-non-link-chars " ]"
5234 "[^\t\n\r]*"
5235 "[^" org-non-link-chars " ]\\)>?")
5236 org-link-re-with-space3
5237 (concat
5238 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5239 "\\([^" org-non-link-chars " ]"
5240 "[^\t\n\r]*\\)")
5241 org-angle-link-re
5242 (concat
5243 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5244 "\\([^" org-non-link-chars " ]"
5245 "[^" org-non-link-chars "]*"
5246 "\\)>")
5247 org-plain-link-re
5248 (concat
5249 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5250 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5251 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5252 org-bracket-link-regexp
5253 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5254 org-bracket-link-analytic-regexp
5255 (concat
5256 "\\[\\["
5257 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5258 "\\([^]]+\\)"
5259 "\\]"
5260 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5261 "\\]")
5262 org-bracket-link-analytic-regexp++
5263 (concat
5264 "\\[\\["
5265 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5266 "\\([^]]+\\)"
5267 "\\]"
5268 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5269 "\\]")
5270 org-any-link-re
5271 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5272 org-angle-link-re "\\)\\|\\("
5273 org-plain-link-re "\\)")))
5275 (org-make-link-regexps)
5277 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5278 "Regular expression for fast time stamp matching.")
5279 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5280 "Regular expression for fast time stamp matching.")
5281 (defconst org-ts-regexp0
5282 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5283 "Regular expression matching time strings for analysis.
5284 This one does not require the space after the date, so it can be used
5285 on a string that terminates immediately after the date.")
5286 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5287 "Regular expression matching time strings for analysis.")
5288 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5289 "Regular expression matching time stamps, with groups.")
5290 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5291 "Regular expression matching time stamps (also [..]), with groups.")
5292 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5293 "Regular expression matching a time stamp range.")
5294 (defconst org-tr-regexp-both
5295 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5296 "Regular expression matching a time stamp range.")
5297 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5298 org-ts-regexp "\\)?")
5299 "Regular expression matching a time stamp or time stamp range.")
5300 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5301 org-ts-regexp-both "\\)?")
5302 "Regular expression matching a time stamp or time stamp range.
5303 The time stamps may be either active or inactive.")
5305 (defvar org-emph-face nil)
5307 (defun org-do-emphasis-faces (limit)
5308 "Run through the buffer and add overlays to emphasized strings."
5309 (let (rtn a)
5310 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5311 (if (not (= (char-after (match-beginning 3))
5312 (char-after (match-beginning 4))))
5313 (progn
5314 (setq rtn t)
5315 (setq a (assoc (match-string 3) org-emphasis-alist))
5316 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5317 'face
5318 (nth 1 a))
5319 (and (nth 4 a)
5320 (org-remove-flyspell-overlays-in
5321 (match-beginning 0) (match-end 0)))
5322 (add-text-properties (match-beginning 2) (match-end 2)
5323 '(font-lock-multiline t org-emphasis t))
5324 (when org-hide-emphasis-markers
5325 (add-text-properties (match-end 4) (match-beginning 5)
5326 '(invisible org-link))
5327 (add-text-properties (match-beginning 3) (match-end 3)
5328 '(invisible org-link)))))
5329 (backward-char 1))
5330 rtn))
5332 (defun org-emphasize (&optional char)
5333 "Insert or change an emphasis, i.e. a font like bold or italic.
5334 If there is an active region, change that region to a new emphasis.
5335 If there is no region, just insert the marker characters and position
5336 the cursor between them.
5337 CHAR should be either the marker character, or the first character of the
5338 HTML tag associated with that emphasis. If CHAR is a space, the means
5339 to remove the emphasis of the selected region.
5340 If char is not given (for example in an interactive call) it
5341 will be prompted for."
5342 (interactive)
5343 (let ((eal org-emphasis-alist) e det
5344 (erc org-emphasis-regexp-components)
5345 (prompt "")
5346 (string "") beg end move tag c s)
5347 (if (org-region-active-p)
5348 (setq beg (region-beginning) end (region-end)
5349 string (buffer-substring beg end))
5350 (setq move t))
5352 (while (setq e (pop eal))
5353 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5354 c (aref tag 0))
5355 (push (cons c (string-to-char (car e))) det)
5356 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5357 (substring tag 1)))))
5358 (setq det (nreverse det))
5359 (unless char
5360 (message "%s" (concat "Emphasis marker or tag:" prompt))
5361 (setq char (read-char-exclusive)))
5362 (setq char (or (cdr (assoc char det)) char))
5363 (if (equal char ?\ )
5364 (setq s "" move nil)
5365 (unless (assoc (char-to-string char) org-emphasis-alist)
5366 (error "No such emphasis marker: \"%c\"" char))
5367 (setq s (char-to-string char)))
5368 (while (and (> (length string) 1)
5369 (equal (substring string 0 1) (substring string -1))
5370 (assoc (substring string 0 1) org-emphasis-alist))
5371 (setq string (substring string 1 -1)))
5372 (setq string (concat s string s))
5373 (if beg (delete-region beg end))
5374 (unless (or (bolp)
5375 (string-match (concat "[" (nth 0 erc) "\n]")
5376 (char-to-string (char-before (point)))))
5377 (insert " "))
5378 (unless (or (eobp)
5379 (string-match (concat "[" (nth 1 erc) "\n]")
5380 (char-to-string (char-after (point)))))
5381 (insert " ") (backward-char 1))
5382 (insert string)
5383 (and move (backward-char 1))))
5385 (defconst org-nonsticky-props
5386 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5388 (defsubst org-rear-nonsticky-at (pos)
5389 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5391 (defun org-activate-plain-links (limit)
5392 "Run through the buffer and add overlays to links."
5393 (catch 'exit
5394 (let (f)
5395 (if (re-search-forward org-plain-link-re limit t)
5396 (progn
5397 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5398 (setq f (get-text-property (match-beginning 0) 'face))
5399 (if (or (eq f 'org-tag)
5400 (and (listp f) (memq 'org-tag f)))
5402 (add-text-properties (match-beginning 0) (match-end 0)
5403 (list 'mouse-face 'highlight
5404 'face 'org-link
5405 'keymap org-mouse-map))
5406 (org-rear-nonsticky-at (match-end 0)))
5407 t)))))
5409 (defun org-activate-code (limit)
5410 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5411 (progn
5412 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5413 (remove-text-properties (match-beginning 0) (match-end 0)
5414 '(display t invisible t intangible t))
5415 t)))
5417 (defcustom org-src-fontify-natively nil
5418 "When non-nil, fontify code in code blocks."
5419 :type 'boolean
5420 :version "24.1"
5421 :group 'org-appearance
5422 :group 'org-babel)
5424 (defcustom org-src-prevent-auto-filling nil
5425 "When non-nil, prevent auto-filling in src blocks."
5426 :type 'boolean
5427 :version "24.1"
5428 :group 'org-appearance
5429 :group 'org-babel)
5431 (defcustom org-allow-promoting-top-level-subtree nil
5432 "When non-nil, allow promoting a top level subtree.
5433 The leading star of the top level headline will be replaced
5434 by a #."
5435 :type 'boolean
5436 :version "24.1"
5437 :group 'org-appearance)
5439 (defun org-fontify-meta-lines-and-blocks (limit)
5440 (condition-case nil
5441 (org-fontify-meta-lines-and-blocks-1 limit)
5442 (error (message "org-mode fontification error"))))
5444 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5445 "Fontify #+ lines and blocks, in the correct ways."
5446 (let ((case-fold-search t))
5447 (if (re-search-forward
5448 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5449 limit t)
5450 (let ((beg (match-beginning 0))
5451 (block-start (match-end 0))
5452 (block-end nil)
5453 (lang (match-string 7))
5454 (beg1 (line-beginning-position 2))
5455 (dc1 (downcase (match-string 2)))
5456 (dc3 (downcase (match-string 3)))
5457 end end1 quoting block-type ovl)
5458 (cond
5459 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5460 ;; a single line of backend-specific content
5461 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5462 (remove-text-properties (match-beginning 0) (match-end 0)
5463 '(display t invisible t intangible t))
5464 (add-text-properties (match-beginning 1) (match-end 3)
5465 '(font-lock-fontified t face org-meta-line))
5466 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5467 '(font-lock-fontified t face org-block))
5468 ; for backend-specific code
5470 ((and (match-end 4) (equal dc3 "begin"))
5471 ;; Truly a block
5472 (setq block-type (downcase (match-string 5))
5473 quoting (member block-type org-protecting-blocks))
5474 (when (re-search-forward
5475 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5476 nil t) ;; on purpose, we look further than LIMIT
5477 (setq end (min (point-max) (match-end 0))
5478 end1 (min (point-max) (1- (match-beginning 0))))
5479 (setq block-end (match-beginning 0))
5480 (when quoting
5481 (remove-text-properties beg end
5482 '(display t invisible t intangible t)))
5483 (add-text-properties
5484 beg end
5485 '(font-lock-fontified t font-lock-multiline t))
5486 (add-text-properties beg beg1 '(face org-meta-line))
5487 (add-text-properties end1 (min (point-max) (1+ end))
5488 '(face org-meta-line)) ; for end_src
5489 (cond
5490 ((and lang (not (string= lang "")) org-src-fontify-natively)
5491 (org-src-font-lock-fontify-block lang block-start block-end)
5492 ;; remove old background overlays
5493 (mapc (lambda (ov)
5494 (if (eq (overlay-get ov 'face) 'org-block-background)
5495 (delete-overlay ov)))
5496 (overlays-at (/ (+ beg1 block-end) 2)))
5497 ;; add a background overlay
5498 (setq ovl (make-overlay beg1 block-end))
5499 (overlay-put ovl 'face 'org-block-background)
5500 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5501 (quoting
5502 (add-text-properties beg1 (min (point-max) (1+ end1))
5503 '(face org-block))) ; end of source block
5504 ((not org-fontify-quote-and-verse-blocks))
5505 ((string= block-type "quote")
5506 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5507 ((string= block-type "verse")
5508 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5509 (add-text-properties beg beg1 '(face org-block-begin-line))
5510 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5511 '(face org-block-end-line))
5513 ((member dc1 '("title:" "author:" "email:" "date:"))
5514 (add-text-properties
5515 beg (match-end 3)
5516 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5517 '(font-lock-fontified t invisible t)
5518 '(font-lock-fontified t face org-document-info-keyword)))
5519 (add-text-properties
5520 (match-beginning 6) (match-end 6)
5521 (if (string-equal dc1 "title:")
5522 '(font-lock-fontified t face org-document-title)
5523 '(font-lock-fontified t face org-document-info))))
5524 ((not (member (char-after beg) '(?\ ?\t)))
5525 ;; just any other in-buffer setting, but not indented
5526 (add-text-properties
5527 beg (match-end 0)
5528 '(font-lock-fontified t face org-meta-line))
5530 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5531 "orgtbl:" "tblfm:" "tblname:" "results:"
5532 "call:" "header:" "headers:" "name:"))
5533 (and (match-end 4) (equal dc3 "attr")))
5534 (add-text-properties
5535 beg (match-end 0)
5536 '(font-lock-fontified t face org-meta-line))
5538 ((member dc3 '(" " ""))
5539 (add-text-properties
5540 beg (match-end 0)
5541 '(font-lock-fontified t face font-lock-comment-face)))
5542 (t nil))))))
5544 (defun org-strip-protective-commas (beg end)
5545 "Strip protective commas between BEG and END in the current buffer."
5546 (interactive "r")
5547 (save-excursion
5548 (save-match-data
5549 (goto-char beg)
5550 (let ((front-line (save-excursion
5551 (re-search-forward
5552 "[^[:space:]]" end t)
5553 (goto-char (match-beginning 0))
5554 (current-column))))
5555 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5556 (goto-char (match-beginning 1))
5557 (when (= (current-column) front-line)
5558 (replace-match "" nil nil nil 1)))))))
5560 (defun org-activate-angle-links (limit)
5561 "Run through the buffer and add overlays to links."
5562 (if (re-search-forward org-angle-link-re limit t)
5563 (progn
5564 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5565 (add-text-properties (match-beginning 0) (match-end 0)
5566 (list 'mouse-face 'highlight
5567 'keymap org-mouse-map))
5568 (org-rear-nonsticky-at (match-end 0))
5569 t)))
5571 (defun org-activate-footnote-links (limit)
5572 "Run through the buffer and add overlays to footnotes."
5573 (let ((fn (org-footnote-next-reference-or-definition limit)))
5574 (when fn
5575 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5576 (org-remove-flyspell-overlays-in beg end)
5577 (add-text-properties beg end
5578 (list 'mouse-face 'highlight
5579 'keymap org-mouse-map
5580 'help-echo
5581 (if (= (point-at-bol) beg)
5582 "Footnote definition"
5583 "Footnote reference")
5584 'font-lock-fontified t
5585 'font-lock-multiline t
5586 'face 'org-footnote))))))
5588 (defun org-activate-bracket-links (limit)
5589 "Run through the buffer and add overlays to bracketed links."
5590 (if (re-search-forward org-bracket-link-regexp limit t)
5591 (let* ((help (concat "LINK: "
5592 (org-match-string-no-properties 1)))
5593 ;; FIXME: above we should remove the escapes.
5594 ;; but that requires another match, protecting match data,
5595 ;; a lot of overhead for font-lock.
5596 (ip (org-maybe-intangible
5597 (list 'invisible 'org-link
5598 'keymap org-mouse-map 'mouse-face 'highlight
5599 'font-lock-multiline t 'help-echo help)))
5600 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5601 'font-lock-multiline t 'help-echo help)))
5602 ;; We need to remove the invisible property here. Table narrowing
5603 ;; may have made some of this invisible.
5604 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5605 (remove-text-properties (match-beginning 0) (match-end 0)
5606 '(invisible nil))
5607 (if (match-end 3)
5608 (progn
5609 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5610 (org-rear-nonsticky-at (match-beginning 3))
5611 (add-text-properties (match-beginning 3) (match-end 3) vp)
5612 (org-rear-nonsticky-at (match-end 3))
5613 (add-text-properties (match-end 3) (match-end 0) ip)
5614 (org-rear-nonsticky-at (match-end 0)))
5615 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5616 (org-rear-nonsticky-at (match-beginning 1))
5617 (add-text-properties (match-beginning 1) (match-end 1) vp)
5618 (org-rear-nonsticky-at (match-end 1))
5619 (add-text-properties (match-end 1) (match-end 0) ip)
5620 (org-rear-nonsticky-at (match-end 0)))
5621 t)))
5623 (defun org-activate-dates (limit)
5624 "Run through the buffer and add overlays to dates."
5625 (if (re-search-forward org-tsr-regexp-both limit t)
5626 (progn
5627 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5628 (add-text-properties (match-beginning 0) (match-end 0)
5629 (list 'mouse-face 'highlight
5630 'keymap org-mouse-map))
5631 (org-rear-nonsticky-at (match-end 0))
5632 (when org-display-custom-times
5633 (if (match-end 3)
5634 (org-display-custom-time (match-beginning 3) (match-end 3)))
5635 (org-display-custom-time (match-beginning 1) (match-end 1)))
5636 t)))
5638 (defvar org-target-link-regexp nil
5639 "Regular expression matching radio targets in plain text.")
5640 (make-variable-buffer-local 'org-target-link-regexp)
5641 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5642 "Regular expression matching a link target.")
5643 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5644 "Regular expression matching a radio target.")
5645 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5646 "Regular expression matching any target.")
5648 (defun org-activate-target-links (limit)
5649 "Run through the buffer and add overlays to target matches."
5650 (when org-target-link-regexp
5651 (let ((case-fold-search t))
5652 (if (re-search-forward org-target-link-regexp limit t)
5653 (progn
5654 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5655 (add-text-properties (match-beginning 0) (match-end 0)
5656 (list 'mouse-face 'highlight
5657 'keymap org-mouse-map
5658 'help-echo "Radio target link"
5659 'org-linked-text t))
5660 (org-rear-nonsticky-at (match-end 0))
5661 t)))))
5663 (defun org-update-radio-target-regexp ()
5664 "Find all radio targets in this file and update the regular expression."
5665 (interactive)
5666 (when (memq 'radio org-activate-links)
5667 (setq org-target-link-regexp
5668 (org-make-target-link-regexp (org-all-targets 'radio)))
5669 (org-restart-font-lock)))
5671 (defun org-hide-wide-columns (limit)
5672 (let (s e)
5673 (setq s (text-property-any (point) (or limit (point-max))
5674 'org-cwidth t))
5675 (when s
5676 (setq e (next-single-property-change s 'org-cwidth))
5677 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5678 (goto-char e)
5679 t)))
5681 (defvar org-latex-and-specials-regexp nil
5682 "Regular expression for highlighting export special stuff.")
5683 (defvar org-match-substring-regexp)
5684 (defvar org-match-substring-with-braces-regexp)
5686 ;; This should be with the exporter code, but we also use if for font-locking
5687 (defconst org-export-html-special-string-regexps
5688 '(("\\\\-" . "&shy;")
5689 ("---\\([^-]\\)" . "&mdash;\\1")
5690 ("--\\([^-]\\)" . "&ndash;\\1")
5691 ("\\.\\.\\." . "&hellip;"))
5692 "Regular expressions for special string conversion.")
5695 (defun org-compute-latex-and-specials-regexp ()
5696 "Compute regular expression for stuff treated specially by exporters."
5697 (if (not org-highlight-latex-fragments-and-specials)
5698 (org-set-local 'org-latex-and-specials-regexp nil)
5699 (require 'org-exp)
5700 (let*
5701 ((matchers (plist-get org-format-latex-options :matchers))
5702 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5703 org-latex-regexps)))
5704 (org-export-allow-BIND nil)
5705 (options (org-combine-plists (org-default-export-plist)
5706 (org-infile-export-plist)))
5707 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5708 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5709 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5710 (org-export-html-expand (plist-get options :expand-quoted-html))
5711 (org-export-with-special-strings (plist-get options :special-strings))
5712 (re-sub
5713 (cond
5714 ((equal org-export-with-sub-superscripts '{})
5715 (list org-match-substring-with-braces-regexp))
5716 (org-export-with-sub-superscripts
5717 (list org-match-substring-regexp))
5718 (t nil)))
5719 (re-latex
5720 (if org-export-with-LaTeX-fragments
5721 (mapcar (lambda (x) (nth 1 x)) latexs)))
5722 (re-macros
5723 (if org-export-with-TeX-macros
5724 (list (concat "\\\\"
5725 (regexp-opt
5726 (append
5728 (delq nil
5729 (mapcar 'car-safe
5730 (append org-entities-user
5731 org-entities)))
5732 (if (boundp 'org-latex-entities)
5733 (mapcar (lambda (x)
5734 (or (car-safe x) x))
5735 org-latex-entities)
5736 nil))
5737 'words))) ; FIXME
5739 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5740 (re-special (if org-export-with-special-strings
5741 (mapcar (lambda (x) (car x))
5742 org-export-html-special-string-regexps)))
5743 (re-rest
5744 (delq nil
5745 (list
5746 (if org-export-html-expand "@<[^>\n]+>")
5747 ))))
5748 (org-set-local
5749 'org-latex-and-specials-regexp
5750 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5751 re-rest) "\\|")))))
5753 (defun org-do-latex-and-special-faces (limit)
5754 "Run through the buffer and add overlays to links."
5755 (when org-latex-and-specials-regexp
5756 (let (rtn d)
5757 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5758 limit t))
5759 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5760 'face))
5761 '(org-code org-verbatim underline)))
5762 (progn
5763 (setq rtn t
5764 d (cond ((member (char-after (1+ (match-beginning 0)))
5765 '(?_ ?^)) 1)
5766 (t 0)))
5767 (font-lock-prepend-text-property
5768 (+ d (match-beginning 0)) (match-end 0)
5769 'face 'org-latex-and-export-specials)
5770 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5771 '(font-lock-multiline t)))))
5772 rtn)))
5774 (defun org-restart-font-lock ()
5775 "Restart `font-lock-mode', to force refontification."
5776 (when (and (boundp 'font-lock-mode) font-lock-mode)
5777 (font-lock-mode -1)
5778 (font-lock-mode 1)))
5780 (defun org-all-targets (&optional radio)
5781 "Return a list of all targets in this file.
5782 With optional argument RADIO, only find radio targets."
5783 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5784 rtn)
5785 (save-excursion
5786 (goto-char (point-min))
5787 (while (re-search-forward re nil t)
5788 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5789 rtn)))
5791 (defun org-make-target-link-regexp (targets)
5792 "Make regular expression matching all strings in TARGETS.
5793 The regular expression finds the targets also if there is a line break
5794 between words."
5795 (and targets
5796 (concat
5797 "\\<\\("
5798 (mapconcat
5799 (lambda (x)
5800 (setq x (regexp-quote x))
5801 (while (string-match " +" x)
5802 (setq x (replace-match "\\s-+" t t x)))
5804 targets
5805 "\\|")
5806 "\\)\\>")))
5808 (defun org-activate-tags (limit)
5809 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5810 (progn
5811 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5812 (add-text-properties (match-beginning 1) (match-end 1)
5813 (list 'mouse-face 'highlight
5814 'keymap org-mouse-map))
5815 (org-rear-nonsticky-at (match-end 1))
5816 t)))
5818 (defun org-outline-level ()
5819 "Compute the outline level of the heading at point.
5820 This function assumes that the cursor is at the beginning of a line matched
5821 by `outline-regexp'. Otherwise it returns garbage.
5822 If this is called at a normal headline, the level is the number of stars.
5823 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5824 (save-excursion
5825 (looking-at org-outline-regexp)
5826 (1- (- (match-end 0) (match-beginning 0)))))
5828 (defvar org-font-lock-keywords nil)
5830 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5831 "Regular expression matching a property line.")
5833 (defvar org-font-lock-hook nil
5834 "Functions to be called for special font lock stuff.")
5836 (defvar org-font-lock-set-keywords-hook nil
5837 "Functions that can manipulate `org-font-lock-extra-keywords'.
5838 This is called after `org-font-lock-extra-keywords' is defined, but before
5839 it is installed to be used by font lock. This can be useful if something
5840 needs to be inserted at a specific position in the font-lock sequence.")
5842 (defun org-font-lock-hook (limit)
5843 (run-hook-with-args 'org-font-lock-hook limit))
5845 (defun org-set-font-lock-defaults ()
5846 (let* ((em org-fontify-emphasized-text)
5847 (lk org-activate-links)
5848 (org-font-lock-extra-keywords
5849 (list
5850 ;; Call the hook
5851 '(org-font-lock-hook)
5852 ;; Headlines
5853 `(,(if org-fontify-whole-heading-line
5854 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5855 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5856 (1 (org-get-level-face 1))
5857 (2 (org-get-level-face 2))
5858 (3 (org-get-level-face 3)))
5859 ;; Table lines
5860 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5861 (1 'org-table t))
5862 ;; Table internals
5863 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5864 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5865 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5866 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5867 ;; Drawers
5868 (list org-drawer-regexp '(0 'org-special-keyword t))
5869 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5870 ;; Properties
5871 (list org-property-re
5872 '(1 'org-special-keyword t)
5873 '(3 'org-property-value t))
5874 ;; Links
5875 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5876 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5877 (if (memq 'plain lk) '(org-activate-plain-links))
5878 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5879 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5880 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5881 (if (memq 'footnote lk) '(org-activate-footnote-links))
5882 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5883 '(org-hide-wide-columns (0 nil append))
5884 ;; TODO keyword
5885 (list (format org-heading-keyword-regexp-format
5886 org-todo-regexp)
5887 '(2 (org-get-todo-face 2) t))
5888 ;; DONE
5889 (if org-fontify-done-headline
5890 (list (format org-heading-keyword-regexp-format
5891 (concat
5892 "\\(?:"
5893 (mapconcat 'regexp-quote org-done-keywords "\\|")
5894 "\\)"))
5895 '(2 'org-headline-done t))
5896 nil)
5897 ;; Priorities
5898 '(org-font-lock-add-priority-faces)
5899 ;; Tags
5900 '(org-font-lock-add-tag-faces)
5901 ;; Special keywords
5902 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5903 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5904 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5905 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5906 ;; Emphasis
5907 (if em
5908 (if (featurep 'xemacs)
5909 '(org-do-emphasis-faces (0 nil append))
5910 '(org-do-emphasis-faces)))
5911 ;; Checkboxes
5912 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5913 1 'org-checkbox prepend)
5914 (if (cdr (assq 'checkbox org-list-automatic-rules))
5915 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5916 (0 (org-get-checkbox-statistics-face) t)))
5917 ;; Description list items
5918 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5919 1 'org-list-dt prepend)
5920 ;; ARCHIVEd headings
5921 (list (concat
5922 org-outline-regexp-bol
5923 "\\(.*:" org-archive-tag ":.*\\)")
5924 '(1 'org-archived prepend))
5925 ;; Specials
5926 '(org-do-latex-and-special-faces)
5927 '(org-fontify-entities)
5928 '(org-raise-scripts)
5929 ;; Code
5930 '(org-activate-code (1 'org-code t))
5931 ;; COMMENT
5932 (list (format org-heading-keyword-regexp-format
5933 (concat "\\("
5934 org-comment-string "\\|" org-quote-string
5935 "\\)"))
5936 '(2 'org-special-keyword t))
5937 '("^#.*" (0 'font-lock-comment-face t))
5938 ;; Blocks and meta lines
5939 '(org-fontify-meta-lines-and-blocks)
5941 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5942 (run-hooks 'org-font-lock-set-keywords-hook)
5943 ;; Now set the full font-lock-keywords
5944 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5945 (org-set-local 'font-lock-defaults
5946 '(org-font-lock-keywords t nil nil backward-paragraph))
5947 (kill-local-variable 'font-lock-keywords) nil))
5949 (defun org-toggle-pretty-entities ()
5950 "Toggle the composition display of entities as UTF8 characters."
5951 (interactive)
5952 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5953 (org-restart-font-lock)
5954 (if org-pretty-entities
5955 (message "Entities are displayed as UTF8 characters")
5956 (save-restriction
5957 (widen)
5958 (org-decompose-region (point-min) (point-max))
5959 (message "Entities are displayed plain"))))
5961 (defun org-fontify-entities (limit)
5962 "Find an entity to fontify."
5963 (let (ee)
5964 (when org-pretty-entities
5965 (catch 'match
5966 (while (re-search-forward
5967 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5968 limit t)
5969 (if (and (not (org-in-indented-comment-line))
5970 (setq ee (org-entity-get (match-string 1)))
5971 (= (length (nth 6 ee)) 1))
5972 (let*
5973 ((end (if (equal (match-string 2) "{}")
5974 (match-end 2)
5975 (match-end 1))))
5976 (add-text-properties
5977 (match-beginning 0) end
5978 (list 'font-lock-fontified t))
5979 (compose-region (match-beginning 0) end
5980 (nth 6 ee) nil)
5981 (backward-char 1)
5982 (throw 'match t))))
5983 nil))))
5985 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5986 "Fontify string S like in Org-mode."
5987 (with-temp-buffer
5988 (insert s)
5989 (let ((org-odd-levels-only odd-levels))
5990 (org-mode)
5991 (font-lock-fontify-buffer)
5992 (buffer-string))))
5994 (defvar org-m nil)
5995 (defvar org-l nil)
5996 (defvar org-f nil)
5997 (defun org-get-level-face (n)
5998 "Get the right face for match N in font-lock matching of headlines."
5999 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6000 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6001 (if org-cycle-level-faces
6002 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6003 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6004 (cond
6005 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6006 ((eq n 2) org-f)
6007 (t (if org-level-color-stars-only nil org-f))))
6010 (defun org-get-todo-face (kwd)
6011 "Get the right face for a TODO keyword KWD.
6012 If KWD is a number, get the corresponding match group."
6013 (if (numberp kwd) (setq kwd (match-string kwd)))
6014 (or (org-face-from-face-or-color
6015 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6016 (and (member kwd org-done-keywords) 'org-done)
6017 'org-todo))
6019 (defun org-face-from-face-or-color (context inherit face-or-color)
6020 "Create a face list that inherits INHERIT, but sets the foreground color.
6021 When FACE-OR-COLOR is not a string, just return it."
6022 (if (stringp face-or-color)
6023 (list :inherit inherit
6024 (cdr (assoc context org-faces-easy-properties))
6025 face-or-color)
6026 face-or-color))
6028 (defun org-font-lock-add-tag-faces (limit)
6029 "Add the special tag faces."
6030 (when (and org-tag-faces org-tags-special-faces-re)
6031 (while (re-search-forward org-tags-special-faces-re limit t)
6032 (add-text-properties (match-beginning 1) (match-end 1)
6033 (list 'face (org-get-tag-face 1)
6034 'font-lock-fontified t))
6035 (backward-char 1))))
6037 (defun org-font-lock-add-priority-faces (limit)
6038 "Add the special priority faces."
6039 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6040 (add-text-properties
6041 (match-beginning 0) (match-end 0)
6042 (list 'face (or (org-face-from-face-or-color
6043 'priority 'org-special-keyword
6044 (cdr (assoc (char-after (match-beginning 1))
6045 org-priority-faces)))
6046 'org-special-keyword)
6047 'font-lock-fontified t))))
6049 (defun org-get-tag-face (kwd)
6050 "Get the right face for a TODO keyword KWD.
6051 If KWD is a number, get the corresponding match group."
6052 (if (numberp kwd) (setq kwd (match-string kwd)))
6053 (or (org-face-from-face-or-color
6054 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6055 'org-tag))
6057 (defun org-unfontify-region (beg end &optional maybe_loudly)
6058 "Remove fontification and activation overlays from links."
6059 (font-lock-default-unfontify-region beg end)
6060 (let* ((buffer-undo-list t)
6061 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6062 (inhibit-modification-hooks t)
6063 deactivate-mark buffer-file-name buffer-file-truename)
6064 (org-decompose-region beg end)
6065 (remove-text-properties beg end
6066 '(mouse-face t keymap t org-linked-text t
6067 invisible t intangible t
6068 org-no-flyspell t org-emphasis t))
6069 (org-remove-font-lock-display-properties beg end)))
6071 (defconst org-script-display '(((raise -0.3) (height 0.7))
6072 ((raise 0.3) (height 0.7))
6073 ((raise -0.5))
6074 ((raise 0.5)))
6075 "Display properties for showing superscripts and subscripts.")
6077 (defun org-remove-font-lock-display-properties (beg end)
6078 "Remove specific display properties that have been added by font lock.
6079 The will remove the raise properties that are used to show superscripts
6080 and subscripts."
6081 (let (next prop)
6082 (while (< beg end)
6083 (setq next (next-single-property-change beg 'display nil end)
6084 prop (get-text-property beg 'display))
6085 (if (member prop org-script-display)
6086 (put-text-property beg next 'display nil))
6087 (setq beg next))))
6089 (defun org-raise-scripts (limit)
6090 "Add raise properties to sub/superscripts."
6091 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6092 (if (re-search-forward
6093 (if (eq org-use-sub-superscripts t)
6094 org-match-substring-regexp
6095 org-match-substring-with-braces-regexp)
6096 limit t)
6097 (let* ((pos (point)) table-p comment-p
6098 (mpos (match-beginning 3))
6099 (emph-p (get-text-property mpos 'org-emphasis))
6100 (link-p (get-text-property mpos 'mouse-face))
6101 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6102 (goto-char (point-at-bol))
6103 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6104 comment-p (org-looking-at-p "[ \t]*#"))
6105 (goto-char pos)
6106 ;; FIXME: Should we go back one character here, for a_b^c
6107 ;; (goto-char (1- pos)) ;????????????????????
6108 (if (or comment-p emph-p link-p keyw-p)
6110 (put-text-property (match-beginning 3) (match-end 0)
6111 'display
6112 (if (equal (char-after (match-beginning 2)) ?^)
6113 (nth (if table-p 3 1) org-script-display)
6114 (nth (if table-p 2 0) org-script-display)))
6115 (add-text-properties (match-beginning 2) (match-end 2)
6116 (list 'invisible t
6117 'org-dwidth t 'org-dwidth-n 1))
6118 (if (and (eq (char-after (match-beginning 3)) ?{)
6119 (eq (char-before (match-end 3)) ?}))
6120 (progn
6121 (add-text-properties
6122 (match-beginning 3) (1+ (match-beginning 3))
6123 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6124 (add-text-properties
6125 (1- (match-end 3)) (match-end 3)
6126 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6127 t)))))
6129 ;;;; Visibility cycling, including org-goto and indirect buffer
6131 ;;; Cycling
6133 (defvar org-cycle-global-status nil)
6134 (make-variable-buffer-local 'org-cycle-global-status)
6135 (defvar org-cycle-subtree-status nil)
6136 (make-variable-buffer-local 'org-cycle-subtree-status)
6138 ;;;###autoload
6140 (defvar org-inlinetask-min-level)
6142 (defun org-cycle (&optional arg)
6143 "TAB-action and visibility cycling for Org-mode.
6145 This is the command invoked in Org-mode by the TAB key. Its main purpose
6146 is outline visibility cycling, but it also invokes other actions
6147 in special contexts.
6149 - When this function is called with a prefix argument, rotate the entire
6150 buffer through 3 states (global cycling)
6151 1. OVERVIEW: Show only top-level headlines.
6152 2. CONTENTS: Show all headlines of all levels, but no body text.
6153 3. SHOW ALL: Show everything.
6154 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6155 determined by the variable `org-startup-folded', and by any VISIBILITY
6156 properties in the buffer.
6157 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6158 including any drawers.
6160 - When inside a table, re-align the table and move to the next field.
6162 - When point is at the beginning of a headline, rotate the subtree started
6163 by this line through 3 different states (local cycling)
6164 1. FOLDED: Only the main headline is shown.
6165 2. CHILDREN: The main headline and the direct children are shown.
6166 From this state, you can move to one of the children
6167 and zoom in further.
6168 3. SUBTREE: Show the entire subtree, including body text.
6169 If there is no subtree, switch directly from CHILDREN to FOLDED.
6171 - When point is at the beginning of an empty headline and the variable
6172 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6173 of the headline by demoting and promoting it to likely levels. This
6174 speeds up creation document structure by pressing TAB once or several
6175 times right after creating a new headline.
6177 - When there is a numeric prefix, go up to a heading with level ARG, do
6178 a `show-subtree' and return to the previous cursor position. If ARG
6179 is negative, go up that many levels.
6181 - When point is not at the beginning of a headline, execute the global
6182 binding for TAB, which is re-indenting the line. See the option
6183 `org-cycle-emulate-tab' for details.
6185 - Special case: if point is at the beginning of the buffer and there is
6186 no headline in line 1, this function will act as if called with prefix arg
6187 (C-u TAB, same as S-TAB) also when called without prefix arg.
6188 But only if also the variable `org-cycle-global-at-bob' is t."
6189 (interactive "P")
6190 (org-load-modules-maybe)
6191 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6192 (and org-cycle-level-after-item/entry-creation
6193 (or (org-cycle-level)
6194 (org-cycle-item-indentation))))
6195 (let* ((limit-level
6196 (or org-cycle-max-level
6197 (and (boundp 'org-inlinetask-min-level)
6198 org-inlinetask-min-level
6199 (1- org-inlinetask-min-level))))
6200 (nstars (and limit-level
6201 (if org-odd-levels-only
6202 (and limit-level (1- (* limit-level 2)))
6203 limit-level)))
6204 (org-outline-regexp
6205 (if (not (derived-mode-p 'org-mode))
6206 outline-regexp
6207 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6208 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6209 (not (looking-at org-outline-regexp))))
6210 (org-cycle-hook
6211 (if bob-special
6212 (delq 'org-optimize-window-after-visibility-change
6213 (copy-sequence org-cycle-hook))
6214 org-cycle-hook))
6215 (pos (point)))
6217 (if (or bob-special (equal arg '(4)))
6218 ;; special case: use global cycling
6219 (setq arg t))
6221 (cond
6223 ((equal arg '(16))
6224 (setq last-command 'dummy)
6225 (org-set-startup-visibility)
6226 (message "Startup visibility, plus VISIBILITY properties"))
6228 ((equal arg '(64))
6229 (show-all)
6230 (message "Entire buffer visible, including drawers"))
6232 ;; Table: enter it or move to the next field.
6233 ((org-at-table-p 'any)
6234 (if (org-at-table.el-p)
6235 (message "Use C-c ' to edit table.el tables")
6236 (if arg (org-table-edit-field t)
6237 (org-table-justify-field-maybe)
6238 (call-interactively 'org-table-next-field))))
6240 ((run-hook-with-args-until-success
6241 'org-tab-after-check-for-table-hook))
6243 ;; Global cycling: delegate to `org-cycle-internal-global'.
6244 ((eq arg t) (org-cycle-internal-global))
6246 ;; Drawers: delegate to `org-flag-drawer'.
6247 ((and org-drawers org-drawer-regexp
6248 (save-excursion
6249 (beginning-of-line 1)
6250 (looking-at org-drawer-regexp)))
6251 (org-flag-drawer ; toggle block visibility
6252 (not (get-char-property (match-end 0) 'invisible))))
6254 ;; Show-subtree, ARG levels up from here.
6255 ((integerp arg)
6256 (save-excursion
6257 (org-back-to-heading)
6258 (outline-up-heading (if (< arg 0) (- arg)
6259 (- (funcall outline-level) arg)))
6260 (org-show-subtree)))
6262 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6263 ((and (featurep 'org-inlinetask)
6264 (org-inlinetask-at-task-p)
6265 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6266 (org-inlinetask-toggle-visibility))
6268 ((org-try-cdlatex-tab))
6270 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6271 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6272 (save-excursion (beginning-of-line 1)
6273 (looking-at org-outline-regexp)))
6274 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6275 (org-cycle-internal-local))
6277 ;; From there: TAB emulation and template completion.
6278 (buffer-read-only (org-back-to-heading))
6280 ((run-hook-with-args-until-success
6281 'org-tab-after-check-for-cycling-hook))
6283 ((org-try-structure-completion))
6285 ((run-hook-with-args-until-success
6286 'org-tab-before-tab-emulation-hook))
6288 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6289 (or (not (bolp))
6290 (not (looking-at org-outline-regexp))))
6291 (call-interactively (global-key-binding "\t")))
6293 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6294 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6295 (or (and (eq org-cycle-emulate-tab 'white)
6296 (= (match-end 0) (point-at-eol)))
6297 (and (eq org-cycle-emulate-tab 'whitestart)
6298 (>= (match-end 0) pos))))
6300 (eq org-cycle-emulate-tab t))
6301 (call-interactively (global-key-binding "\t")))
6303 (t (save-excursion
6304 (org-back-to-heading)
6305 (org-cycle)))))))
6307 (defun org-cycle-internal-global ()
6308 "Do the global cycling action."
6309 ;; Hack to avoid display of messages for .org attachments in Gnus
6310 (let ((ga (string-match "\\*fontification" (buffer-name))))
6311 (cond
6312 ((and (eq last-command this-command)
6313 (eq org-cycle-global-status 'overview))
6314 ;; We just created the overview - now do table of contents
6315 ;; This can be slow in very large buffers, so indicate action
6316 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6317 (unless ga (message "CONTENTS..."))
6318 (org-content)
6319 (unless ga (message "CONTENTS...done"))
6320 (setq org-cycle-global-status 'contents)
6321 (run-hook-with-args 'org-cycle-hook 'contents))
6323 ((and (eq last-command this-command)
6324 (eq org-cycle-global-status 'contents))
6325 ;; We just showed the table of contents - now show everything
6326 (run-hook-with-args 'org-pre-cycle-hook 'all)
6327 (show-all)
6328 (unless ga (message "SHOW ALL"))
6329 (setq org-cycle-global-status 'all)
6330 (run-hook-with-args 'org-cycle-hook 'all))
6333 ;; Default action: go to overview
6334 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6335 (org-overview)
6336 (unless ga (message "OVERVIEW"))
6337 (setq org-cycle-global-status 'overview)
6338 (run-hook-with-args 'org-cycle-hook 'overview)))))
6340 (defun org-cycle-internal-local ()
6341 "Do the local cycling action."
6342 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6343 ;; First, determine end of headline (EOH), end of subtree or item
6344 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6345 (save-excursion
6346 (if (org-at-item-p)
6347 (progn
6348 (beginning-of-line)
6349 (setq struct (org-list-struct))
6350 (setq eoh (point-at-eol))
6351 (setq eos (org-list-get-item-end-before-blank (point) struct))
6352 (setq has-children (org-list-has-child-p (point) struct)))
6353 (org-back-to-heading)
6354 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6355 (setq eos (save-excursion
6356 (org-end-of-subtree t)
6357 (unless (eobp)
6358 (skip-chars-forward " \t\n"))
6359 (if (eobp) (point) (1- (point)))))
6360 (setq has-children
6361 (or (save-excursion
6362 (let ((level (funcall outline-level)))
6363 (outline-next-heading)
6364 (and (org-at-heading-p t)
6365 (> (funcall outline-level) level))))
6366 (save-excursion
6367 (org-list-search-forward (org-item-beginning-re) eos t)))))
6368 ;; Determine end invisible part of buffer (EOL)
6369 (beginning-of-line 2)
6370 ;; XEmacs doesn't have `next-single-char-property-change'
6371 (if (featurep 'xemacs)
6372 (while (and (not (eobp)) ;; this is like `next-line'
6373 (get-char-property (1- (point)) 'invisible))
6374 (beginning-of-line 2))
6375 (while (and (not (eobp)) ;; this is like `next-line'
6376 (get-char-property (1- (point)) 'invisible))
6377 (goto-char (next-single-char-property-change (point) 'invisible))
6378 (and (eolp) (beginning-of-line 2))))
6379 (setq eol (point)))
6380 ;; Find out what to do next and set `this-command'
6381 (cond
6382 ((= eos eoh)
6383 ;; Nothing is hidden behind this heading
6384 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6385 (message "EMPTY ENTRY")
6386 (setq org-cycle-subtree-status nil)
6387 (save-excursion
6388 (goto-char eos)
6389 (outline-next-heading)
6390 (if (outline-invisible-p) (org-flag-heading nil))))
6391 ((and (or (>= eol eos)
6392 (not (string-match "\\S-" (buffer-substring eol eos))))
6393 (or has-children
6394 (not (setq children-skipped
6395 org-cycle-skip-children-state-if-no-children))))
6396 ;; Entire subtree is hidden in one line: children view
6397 (run-hook-with-args 'org-pre-cycle-hook 'children)
6398 (if (org-at-item-p)
6399 (org-list-set-item-visibility (point-at-bol) struct 'children)
6400 (org-show-entry)
6401 (org-with-limited-levels (show-children))
6402 ;; FIXME: This slows down the func way too much.
6403 ;; How keep drawers hidden in subtree anyway?
6404 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6405 ;; (org-cycle-hide-drawers 'subtree))
6407 ;; Fold every list in subtree to top-level items.
6408 (when (eq org-cycle-include-plain-lists 'integrate)
6409 (save-excursion
6410 (org-back-to-heading)
6411 (while (org-list-search-forward (org-item-beginning-re) eos t)
6412 (beginning-of-line 1)
6413 (let* ((struct (org-list-struct))
6414 (prevs (org-list-prevs-alist struct))
6415 (end (org-list-get-bottom-point struct)))
6416 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6417 (org-list-get-all-items (point) struct prevs))
6418 (goto-char end))))))
6419 (message "CHILDREN")
6420 (save-excursion
6421 (goto-char eos)
6422 (outline-next-heading)
6423 (if (outline-invisible-p) (org-flag-heading nil)))
6424 (setq org-cycle-subtree-status 'children)
6425 (run-hook-with-args 'org-cycle-hook 'children))
6426 ((or children-skipped
6427 (and (eq last-command this-command)
6428 (eq org-cycle-subtree-status 'children)))
6429 ;; We just showed the children, or no children are there,
6430 ;; now show everything.
6431 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6432 (outline-flag-region eoh eos nil)
6433 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6434 (setq org-cycle-subtree-status 'subtree)
6435 (run-hook-with-args 'org-cycle-hook 'subtree))
6437 ;; Default action: hide the subtree.
6438 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6439 (outline-flag-region eoh eos t)
6440 (message "FOLDED")
6441 (setq org-cycle-subtree-status 'folded)
6442 (run-hook-with-args 'org-cycle-hook 'folded)))))
6444 ;;;###autoload
6445 (defun org-global-cycle (&optional arg)
6446 "Cycle the global visibility. For details see `org-cycle'.
6447 With \\[universal-argument] prefix arg, switch to startup visibility.
6448 With a numeric prefix, show all headlines up to that level."
6449 (interactive "P")
6450 (let ((org-cycle-include-plain-lists
6451 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6452 (cond
6453 ((integerp arg)
6454 (show-all)
6455 (hide-sublevels arg)
6456 (setq org-cycle-global-status 'contents))
6457 ((equal arg '(4))
6458 (org-set-startup-visibility)
6459 (message "Startup visibility, plus VISIBILITY properties."))
6461 (org-cycle '(4))))))
6463 (defun org-set-startup-visibility ()
6464 "Set the visibility required by startup options and properties."
6465 (cond
6466 ((eq org-startup-folded t)
6467 (org-cycle '(4)))
6468 ((eq org-startup-folded 'content)
6469 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6470 (org-cycle '(4)) (org-cycle '(4)))))
6471 (unless (eq org-startup-folded 'showeverything)
6472 (if org-hide-block-startup (org-hide-block-all))
6473 (org-set-visibility-according-to-property 'no-cleanup)
6474 (org-cycle-hide-archived-subtrees 'all)
6475 (org-cycle-hide-drawers 'all)
6476 (org-cycle-show-empty-lines t)))
6478 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6479 "Switch subtree visibilities according to :VISIBILITY: property."
6480 (interactive)
6481 (let (org-show-entry-below state)
6482 (save-excursion
6483 (goto-char (point-min))
6484 (while (re-search-forward
6485 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6486 nil t)
6487 (setq state (match-string 1))
6488 (save-excursion
6489 (org-back-to-heading t)
6490 (hide-subtree)
6491 (org-reveal)
6492 (cond
6493 ((equal state '("fold" "folded"))
6494 (hide-subtree))
6495 ((equal state "children")
6496 (org-show-hidden-entry)
6497 (show-children))
6498 ((equal state "content")
6499 (save-excursion
6500 (save-restriction
6501 (org-narrow-to-subtree)
6502 (org-content))))
6503 ((member state '("all" "showall"))
6504 (show-subtree)))))
6505 (unless no-cleanup
6506 (org-cycle-hide-archived-subtrees 'all)
6507 (org-cycle-hide-drawers 'all)
6508 (org-cycle-show-empty-lines 'all)))))
6510 ;; This function uses outline-regexp instead of the more fundamental
6511 ;; org-outline-regexp so that org-cycle-global works outside of Org
6512 ;; buffers, where outline-regexp is needed.
6513 (defun org-overview ()
6514 "Switch to overview mode, showing only top-level headlines.
6515 Really, this shows all headlines with level equal or greater than the level
6516 of the first headline in the buffer. This is important, because if the
6517 first headline is not level one, then (hide-sublevels 1) gives confusing
6518 results."
6519 (interactive)
6520 (let ((level (save-excursion
6521 (goto-char (point-min))
6522 (if (re-search-forward (concat "^" outline-regexp) nil t)
6523 (progn
6524 (goto-char (match-beginning 0))
6525 (funcall outline-level))))))
6526 (and level (hide-sublevels level))))
6528 (defun org-content (&optional arg)
6529 "Show all headlines in the buffer, like a table of contents.
6530 With numerical argument N, show content up to level N."
6531 (interactive "P")
6532 (save-excursion
6533 ;; Visit all headings and show their offspring
6534 (and (integerp arg) (org-overview))
6535 (goto-char (point-max))
6536 (catch 'exit
6537 (while (and (progn (condition-case nil
6538 (outline-previous-visible-heading 1)
6539 (error (goto-char (point-min))))
6541 (looking-at org-outline-regexp))
6542 (if (integerp arg)
6543 (show-children (1- arg))
6544 (show-branches))
6545 (if (bobp) (throw 'exit nil))))))
6548 (defun org-optimize-window-after-visibility-change (state)
6549 "Adjust the window after a change in outline visibility.
6550 This function is the default value of the hook `org-cycle-hook'."
6551 (when (get-buffer-window (current-buffer))
6552 (cond
6553 ((eq state 'content) nil)
6554 ((eq state 'all) nil)
6555 ((eq state 'folded) nil)
6556 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6557 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6559 (defun org-remove-empty-overlays-at (pos)
6560 "Remove outline overlays that do not contain non-white stuff."
6561 (mapc
6562 (lambda (o)
6563 (and (eq 'outline (overlay-get o 'invisible))
6564 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6565 (overlay-end o))))
6566 (delete-overlay o)))
6567 (overlays-at pos)))
6569 (defun org-clean-visibility-after-subtree-move ()
6570 "Fix visibility issues after moving a subtree."
6571 ;; First, find a reasonable region to look at:
6572 ;; Start two siblings above, end three below
6573 (let* ((beg (save-excursion
6574 (and (org-get-last-sibling)
6575 (org-get-last-sibling))
6576 (point)))
6577 (end (save-excursion
6578 (and (org-get-next-sibling)
6579 (org-get-next-sibling)
6580 (org-get-next-sibling))
6581 (if (org-at-heading-p)
6582 (point-at-eol)
6583 (point))))
6584 (level (looking-at "\\*+"))
6585 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6586 (save-excursion
6587 (save-restriction
6588 (narrow-to-region beg end)
6589 (when re
6590 ;; Properly fold already folded siblings
6591 (goto-char (point-min))
6592 (while (re-search-forward re nil t)
6593 (if (and (not (outline-invisible-p))
6594 (save-excursion
6595 (goto-char (point-at-eol)) (outline-invisible-p)))
6596 (hide-entry))))
6597 (org-cycle-show-empty-lines 'overview)
6598 (org-cycle-hide-drawers 'overview)))))
6600 (defun org-cycle-show-empty-lines (state)
6601 "Show empty lines above all visible headlines.
6602 The region to be covered depends on STATE when called through
6603 `org-cycle-hook'. Lisp program can use t for STATE to get the
6604 entire buffer covered. Note that an empty line is only shown if there
6605 are at least `org-cycle-separator-lines' empty lines before the headline."
6606 (when (not (= org-cycle-separator-lines 0))
6607 (save-excursion
6608 (let* ((n (abs org-cycle-separator-lines))
6609 (re (cond
6610 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6611 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6612 (t (let ((ns (number-to-string (- n 2))))
6613 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6614 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6615 beg end b e)
6616 (cond
6617 ((memq state '(overview contents t))
6618 (setq beg (point-min) end (point-max)))
6619 ((memq state '(children folded))
6620 (setq beg (point) end (progn (org-end-of-subtree t t)
6621 (beginning-of-line 2)
6622 (point)))))
6623 (when beg
6624 (goto-char beg)
6625 (while (re-search-forward re end t)
6626 (unless (get-char-property (match-end 1) 'invisible)
6627 (setq e (match-end 1))
6628 (if (< org-cycle-separator-lines 0)
6629 (setq b (save-excursion
6630 (goto-char (match-beginning 0))
6631 (org-back-over-empty-lines)
6632 (if (save-excursion
6633 (goto-char (max (point-min) (1- (point))))
6634 (org-at-heading-p))
6635 (1- (point))
6636 (point))))
6637 (setq b (match-beginning 1)))
6638 (outline-flag-region b e nil)))))))
6639 ;; Never hide empty lines at the end of the file.
6640 (save-excursion
6641 (goto-char (point-max))
6642 (outline-previous-heading)
6643 (outline-end-of-heading)
6644 (if (and (looking-at "[ \t\n]+")
6645 (= (match-end 0) (point-max)))
6646 (outline-flag-region (point) (match-end 0) nil))))
6648 (defun org-show-empty-lines-in-parent ()
6649 "Move to the parent and re-show empty lines before visible headlines."
6650 (save-excursion
6651 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6652 (org-cycle-show-empty-lines context))))
6654 (defun org-files-list ()
6655 "Return `org-agenda-files' list, plus all open org-mode files.
6656 This is useful for operations that need to scan all of a user's
6657 open and agenda-wise Org files."
6658 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6659 (dolist (buf (buffer-list))
6660 (with-current-buffer buf
6661 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6662 (let ((file (expand-file-name (buffer-file-name))))
6663 (unless (member file files)
6664 (push file files))))))
6665 files))
6667 (defsubst org-entry-beginning-position ()
6668 "Return the beginning position of the current entry."
6669 (save-excursion (outline-back-to-heading t) (point)))
6671 (defsubst org-entry-end-position ()
6672 "Return the end position of the current entry."
6673 (save-excursion (outline-next-heading) (point)))
6675 (defun org-cycle-hide-drawers (state)
6676 "Re-hide all drawers after a visibility state change."
6677 (when (and (derived-mode-p 'org-mode)
6678 (not (memq state '(overview folded contents))))
6679 (save-excursion
6680 (let* ((globalp (memq state '(contents all)))
6681 (beg (if globalp (point-min) (point)))
6682 (end (if globalp (point-max)
6683 (if (eq state 'children)
6684 (save-excursion (outline-next-heading) (point))
6685 (org-end-of-subtree t)))))
6686 (goto-char beg)
6687 (while (re-search-forward org-drawer-regexp end t)
6688 (org-flag-drawer t))))))
6690 (defun org-flag-drawer (flag)
6691 (save-excursion
6692 (beginning-of-line 1)
6693 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6694 (let ((b (match-end 0)))
6695 (if (re-search-forward
6696 "^[ \t]*:END:"
6697 (save-excursion (outline-next-heading) (point)) t)
6698 (outline-flag-region b (point-at-eol) flag)
6699 (error ":END: line missing at position %s" b))))))
6701 (defun org-subtree-end-visible-p ()
6702 "Is the end of the current subtree visible?"
6703 (pos-visible-in-window-p
6704 (save-excursion (org-end-of-subtree t) (point))))
6706 (defun org-first-headline-recenter (&optional N)
6707 "Move cursor to the first headline and recenter the headline.
6708 Optional argument N means put the headline into the Nth line of the window."
6709 (goto-char (point-min))
6710 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6711 (beginning-of-line)
6712 (recenter (prefix-numeric-value N))))
6714 ;;; Saving and restoring visibility
6716 (defun org-outline-overlay-data (&optional use-markers)
6717 "Return a list of the locations of all outline overlays.
6718 These are overlays with the `invisible' property value `outline'.
6719 The return value is a list of cons cells, with start and stop
6720 positions for each overlay.
6721 If USE-MARKERS is set, return the positions as markers."
6722 (let (beg end)
6723 (save-excursion
6724 (save-restriction
6725 (widen)
6726 (delq nil
6727 (mapcar (lambda (o)
6728 (when (eq (overlay-get o 'invisible) 'outline)
6729 (setq beg (overlay-start o)
6730 end (overlay-end o))
6731 (and beg end (> end beg)
6732 (if use-markers
6733 (cons (move-marker (make-marker) beg)
6734 (move-marker (make-marker) end))
6735 (cons beg end)))))
6736 (overlays-in (point-min) (point-max))))))))
6738 (defun org-set-outline-overlay-data (data)
6739 "Create visibility overlays for all positions in DATA.
6740 DATA should have been made by `org-outline-overlay-data'."
6741 (let (o)
6742 (save-excursion
6743 (save-restriction
6744 (widen)
6745 (show-all)
6746 (mapc (lambda (c)
6747 (outline-flag-region (car c) (cdr c) t))
6748 data)))))
6750 ;;; Folding of blocks
6752 (defvar org-hide-block-overlays nil
6753 "Overlays hiding blocks.")
6754 (make-variable-buffer-local 'org-hide-block-overlays)
6756 (defun org-block-map (function &optional start end)
6757 "Call FUNCTION at the head of all source blocks in the current buffer.
6758 Optional arguments START and END can be used to limit the range."
6759 (let ((start (or start (point-min)))
6760 (end (or end (point-max))))
6761 (save-excursion
6762 (goto-char start)
6763 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6764 (save-excursion
6765 (save-match-data
6766 (goto-char (match-beginning 0))
6767 (funcall function)))))))
6769 (defun org-hide-block-toggle-all ()
6770 "Toggle the visibility of all blocks in the current buffer."
6771 (org-block-map #'org-hide-block-toggle))
6773 (defun org-hide-block-all ()
6774 "Fold all blocks in the current buffer."
6775 (interactive)
6776 (org-show-block-all)
6777 (org-block-map #'org-hide-block-toggle-maybe))
6779 (defun org-show-block-all ()
6780 "Unfold all blocks in the current buffer."
6781 (interactive)
6782 (mapc 'delete-overlay org-hide-block-overlays)
6783 (setq org-hide-block-overlays nil))
6785 (defun org-hide-block-toggle-maybe ()
6786 "Toggle visibility of block at point."
6787 (interactive)
6788 (let ((case-fold-search t))
6789 (if (save-excursion
6790 (beginning-of-line 1)
6791 (looking-at org-block-regexp))
6792 (progn (org-hide-block-toggle)
6793 t) ;; to signal that we took action
6794 nil))) ;; to signal that we did not
6796 (defun org-hide-block-toggle (&optional force)
6797 "Toggle the visibility of the current block."
6798 (interactive)
6799 (save-excursion
6800 (beginning-of-line)
6801 (if (re-search-forward org-block-regexp nil t)
6802 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6803 (end (match-end 0)) ;; end of entire body
6805 (if (memq t (mapcar (lambda (overlay)
6806 (eq (overlay-get overlay 'invisible)
6807 'org-hide-block))
6808 (overlays-at start)))
6809 (if (or (not force) (eq force 'off))
6810 (mapc (lambda (ov)
6811 (when (member ov org-hide-block-overlays)
6812 (setq org-hide-block-overlays
6813 (delq ov org-hide-block-overlays)))
6814 (when (eq (overlay-get ov 'invisible)
6815 'org-hide-block)
6816 (delete-overlay ov)))
6817 (overlays-at start)))
6818 (setq ov (make-overlay start end))
6819 (overlay-put ov 'invisible 'org-hide-block)
6820 ;; make the block accessible to isearch
6821 (overlay-put
6822 ov 'isearch-open-invisible
6823 (lambda (ov)
6824 (when (member ov org-hide-block-overlays)
6825 (setq org-hide-block-overlays
6826 (delq ov org-hide-block-overlays)))
6827 (when (eq (overlay-get ov 'invisible)
6828 'org-hide-block)
6829 (delete-overlay ov))))
6830 (push ov org-hide-block-overlays)))
6831 (error "Not looking at a source block"))))
6833 ;; org-tab-after-check-for-cycling-hook
6834 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6835 ;; Remove overlays when changing major mode
6836 (add-hook 'org-mode-hook
6837 (lambda () (org-add-hook 'change-major-mode-hook
6838 'org-show-block-all 'append 'local)))
6840 ;;; Org-goto
6842 (defvar org-goto-window-configuration nil)
6843 (defvar org-goto-marker nil)
6844 (defvar org-goto-map
6845 (let ((map (make-sparse-keymap)))
6846 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6847 (while (setq cmd (pop cmds))
6848 (substitute-key-definition cmd cmd map global-map)))
6849 (suppress-keymap map)
6850 (org-defkey map "\C-m" 'org-goto-ret)
6851 (org-defkey map [(return)] 'org-goto-ret)
6852 (org-defkey map [(left)] 'org-goto-left)
6853 (org-defkey map [(right)] 'org-goto-right)
6854 (org-defkey map [(control ?g)] 'org-goto-quit)
6855 (org-defkey map "\C-i" 'org-cycle)
6856 (org-defkey map [(tab)] 'org-cycle)
6857 (org-defkey map [(down)] 'outline-next-visible-heading)
6858 (org-defkey map [(up)] 'outline-previous-visible-heading)
6859 (if org-goto-auto-isearch
6860 (if (fboundp 'define-key-after)
6861 (define-key-after map [t] 'org-goto-local-auto-isearch)
6862 nil)
6863 (org-defkey map "q" 'org-goto-quit)
6864 (org-defkey map "n" 'outline-next-visible-heading)
6865 (org-defkey map "p" 'outline-previous-visible-heading)
6866 (org-defkey map "f" 'outline-forward-same-level)
6867 (org-defkey map "b" 'outline-backward-same-level)
6868 (org-defkey map "u" 'outline-up-heading))
6869 (org-defkey map "/" 'org-occur)
6870 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6871 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6872 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6873 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6874 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6875 map))
6877 (defconst org-goto-help
6878 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6879 RET=jump to location [Q]uit and return to previous location
6880 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6882 (defvar org-goto-start-pos) ; dynamically scoped parameter
6884 ;; FIXME: Docstring does not mention both interfaces
6885 (defun org-goto (&optional alternative-interface)
6886 "Look up a different location in the current file, keeping current visibility.
6888 When you want look-up or go to a different location in a
6889 document, the fastest way is often to fold the entire buffer and
6890 then dive into the tree. This method has the disadvantage, that
6891 the previous location will be folded, which may not be what you
6892 want.
6894 This command works around this by showing a copy of the current
6895 buffer in an indirect buffer, in overview mode. You can dive
6896 into the tree in that copy, use org-occur and incremental search
6897 to find a location. When pressing RET or `Q', the command
6898 returns to the original buffer in which the visibility is still
6899 unchanged. After RET it will also jump to the location selected
6900 in the indirect buffer and expose the headline hierarchy above.
6902 With a prefix argument, use the alternative interface: e.g. if
6903 `org-goto-interface' is 'outline use 'outline-path-completion."
6904 (interactive "P")
6905 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6906 (org-refile-use-outline-path t)
6907 (org-refile-target-verify-function nil)
6908 (interface
6909 (if (not alternative-interface)
6910 org-goto-interface
6911 (if (eq org-goto-interface 'outline)
6912 'outline-path-completion
6913 'outline)))
6914 (org-goto-start-pos (point))
6915 (selected-point
6916 (if (eq interface 'outline)
6917 (car (org-get-location (current-buffer) org-goto-help))
6918 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6919 (org-refile-check-position pa)
6920 (nth 3 pa)))))
6921 (if selected-point
6922 (progn
6923 (org-mark-ring-push org-goto-start-pos)
6924 (goto-char selected-point)
6925 (if (or (outline-invisible-p) (org-invisible-p2))
6926 (org-show-context 'org-goto)))
6927 (message "Quit"))))
6929 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6930 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6931 (defvar org-goto-local-auto-isearch-map) ; defined below
6933 (defun org-get-location (buf help)
6934 "Let the user select a location in the Org-mode buffer BUF.
6935 This function uses a recursive edit. It returns the selected position
6936 or nil."
6937 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6938 (isearch-hide-immediately nil)
6939 (isearch-search-fun-function
6940 (lambda () 'org-goto-local-search-headings))
6941 (org-goto-selected-point org-goto-exit-command)
6942 (pop-up-frames nil)
6943 (special-display-buffer-names nil)
6944 (special-display-regexps nil)
6945 (special-display-function nil))
6946 (save-excursion
6947 (save-window-excursion
6948 (delete-other-windows)
6949 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6950 (org-pop-to-buffer-same-window
6951 (condition-case nil
6952 (make-indirect-buffer (current-buffer) "*org-goto*")
6953 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6954 (with-output-to-temp-buffer "*Help*"
6955 (princ help))
6956 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6957 (setq buffer-read-only nil)
6958 (let ((org-startup-truncated t)
6959 (org-startup-folded nil)
6960 (org-startup-align-all-tables nil))
6961 (org-mode)
6962 (org-overview))
6963 (setq buffer-read-only t)
6964 (if (and (boundp 'org-goto-start-pos)
6965 (integer-or-marker-p org-goto-start-pos))
6966 (let ((org-show-hierarchy-above t)
6967 (org-show-siblings t)
6968 (org-show-following-heading t))
6969 (goto-char org-goto-start-pos)
6970 (and (outline-invisible-p) (org-show-context)))
6971 (goto-char (point-min)))
6972 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6973 (message "Select location and press RET")
6974 (use-local-map org-goto-map)
6975 (recursive-edit)
6977 (kill-buffer "*org-goto*")
6978 (cons org-goto-selected-point org-goto-exit-command)))
6980 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6981 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6982 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6983 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6985 (defun org-goto-local-search-headings (string bound noerror)
6986 "Search and make sure that any matches are in headlines."
6987 (catch 'return
6988 (while (if isearch-forward
6989 (search-forward string bound noerror)
6990 (search-backward string bound noerror))
6991 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6992 (and (member :headline context)
6993 (not (member :tags context))))
6994 (throw 'return (point))))))
6996 (defun org-goto-local-auto-isearch ()
6997 "Start isearch."
6998 (interactive)
6999 (goto-char (point-min))
7000 (let ((keys (this-command-keys)))
7001 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7002 (isearch-mode t)
7003 (isearch-process-search-char (string-to-char keys)))))
7005 (defun org-goto-ret (&optional arg)
7006 "Finish `org-goto' by going to the new location."
7007 (interactive "P")
7008 (setq org-goto-selected-point (point)
7009 org-goto-exit-command 'return)
7010 (throw 'exit nil))
7012 (defun org-goto-left ()
7013 "Finish `org-goto' by going to the new location."
7014 (interactive)
7015 (if (org-at-heading-p)
7016 (progn
7017 (beginning-of-line 1)
7018 (setq org-goto-selected-point (point)
7019 org-goto-exit-command 'left)
7020 (throw 'exit nil))
7021 (error "Not on a heading")))
7023 (defun org-goto-right ()
7024 "Finish `org-goto' by going to the new location."
7025 (interactive)
7026 (if (org-at-heading-p)
7027 (progn
7028 (setq org-goto-selected-point (point)
7029 org-goto-exit-command 'right)
7030 (throw 'exit nil))
7031 (error "Not on a heading")))
7033 (defun org-goto-quit ()
7034 "Finish `org-goto' without cursor motion."
7035 (interactive)
7036 (setq org-goto-selected-point nil)
7037 (setq org-goto-exit-command 'quit)
7038 (throw 'exit nil))
7040 ;;; Indirect buffer display of subtrees
7042 (defvar org-indirect-dedicated-frame nil
7043 "This is the frame being used for indirect tree display.")
7044 (defvar org-last-indirect-buffer nil)
7046 (defun org-tree-to-indirect-buffer (&optional arg)
7047 "Create indirect buffer and narrow it to current subtree.
7048 With numerical prefix ARG, go up to this level and then take that tree.
7049 If ARG is negative, go up that many levels.
7050 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7051 indirect buffer previously made with this command, to avoid proliferation of
7052 indirect buffers. However, when you call the command with a \
7053 \\[universal-argument] prefix, or
7054 when `org-indirect-buffer-display' is `new-frame', the last buffer
7055 is kept so that you can work with several indirect buffers at the same time.
7056 If `org-indirect-buffer-display' is `dedicated-frame', the \
7057 \\[universal-argument] prefix also
7058 requests that a new frame be made for the new buffer, so that the dedicated
7059 frame is not changed."
7060 (interactive "P")
7061 (let ((cbuf (current-buffer))
7062 (cwin (selected-window))
7063 (pos (point))
7064 beg end level heading ibuf)
7065 (save-excursion
7066 (org-back-to-heading t)
7067 (when (numberp arg)
7068 (setq level (org-outline-level))
7069 (if (< arg 0) (setq arg (+ level arg)))
7070 (while (> (setq level (org-outline-level)) arg)
7071 (outline-up-heading 1 t)))
7072 (setq beg (point)
7073 heading (org-get-heading))
7074 (org-end-of-subtree t t)
7075 (if (org-at-heading-p) (backward-char 1))
7076 (setq end (point)))
7077 (if (and (buffer-live-p org-last-indirect-buffer)
7078 (not (eq org-indirect-buffer-display 'new-frame))
7079 (not arg))
7080 (kill-buffer org-last-indirect-buffer))
7081 (setq ibuf (org-get-indirect-buffer cbuf)
7082 org-last-indirect-buffer ibuf)
7083 (cond
7084 ((or (eq org-indirect-buffer-display 'new-frame)
7085 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7086 (select-frame (make-frame))
7087 (delete-other-windows)
7088 (org-pop-to-buffer-same-window ibuf)
7089 (org-set-frame-title heading))
7090 ((eq org-indirect-buffer-display 'dedicated-frame)
7091 (raise-frame
7092 (select-frame (or (and org-indirect-dedicated-frame
7093 (frame-live-p org-indirect-dedicated-frame)
7094 org-indirect-dedicated-frame)
7095 (setq org-indirect-dedicated-frame (make-frame)))))
7096 (delete-other-windows)
7097 (org-pop-to-buffer-same-window ibuf)
7098 (org-set-frame-title (concat "Indirect: " heading)))
7099 ((eq org-indirect-buffer-display 'current-window)
7100 (org-pop-to-buffer-same-window ibuf))
7101 ((eq org-indirect-buffer-display 'other-window)
7102 (pop-to-buffer ibuf))
7103 (t (error "Invalid value")))
7104 (if (featurep 'xemacs)
7105 (save-excursion (org-mode) (turn-on-font-lock)))
7106 (narrow-to-region beg end)
7107 (show-all)
7108 (goto-char pos)
7109 (run-hook-with-args 'org-cycle-hook 'all)
7110 (and (window-live-p cwin) (select-window cwin))))
7112 (defun org-get-indirect-buffer (&optional buffer)
7113 (setq buffer (or buffer (current-buffer)))
7114 (let ((n 1) (base (buffer-name buffer)) bname)
7115 (while (buffer-live-p
7116 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7117 (setq n (1+ n)))
7118 (condition-case nil
7119 (make-indirect-buffer buffer bname 'clone)
7120 (error (make-indirect-buffer buffer bname)))))
7122 (defun org-set-frame-title (title)
7123 "Set the title of the current frame to the string TITLE."
7124 ;; FIXME: how to name a single frame in XEmacs???
7125 (unless (featurep 'xemacs)
7126 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7128 ;;;; Structure editing
7130 ;;; Inserting headlines
7132 (defun org-previous-line-empty-p ()
7133 (save-excursion
7134 (and (not (bobp))
7135 (or (beginning-of-line 0) t)
7136 (save-match-data
7137 (looking-at "[ \t]*$")))))
7139 (defun org-insert-heading (&optional force-heading invisible-ok)
7140 "Insert a new heading or item with same depth at point.
7141 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7142 If point is at the beginning of a headline, insert a sibling before the
7143 current headline. If point is not at the beginning, split the line,
7144 create the new headline with the text in the current line after point
7145 \(but see also the variable `org-M-RET-may-split-line').
7147 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7148 This is important for non-interactive uses of the command."
7149 (interactive "P")
7150 (if (or (= (buffer-size) 0)
7151 (and (not (save-excursion
7152 (and (ignore-errors (org-back-to-heading invisible-ok))
7153 (org-at-heading-p))))
7154 (or force-heading (not (org-in-item-p)))))
7155 (progn
7156 (insert "\n* ")
7157 (run-hooks 'org-insert-heading-hook))
7158 (when (or force-heading (not (org-insert-item)))
7159 (let* ((empty-line-p nil)
7160 (level nil)
7161 (on-heading (org-at-heading-p))
7162 (head (save-excursion
7163 (condition-case nil
7164 (progn
7165 (org-back-to-heading invisible-ok)
7166 (when (and (not on-heading)
7167 (featurep 'org-inlinetask)
7168 (integerp org-inlinetask-min-level)
7169 (>= (length (match-string 0))
7170 org-inlinetask-min-level))
7171 ;; Find a heading level before the inline task
7172 (while (and (setq level (org-up-heading-safe))
7173 (>= level org-inlinetask-min-level)))
7174 (if (org-at-heading-p)
7175 (org-back-to-heading invisible-ok)
7176 (error "This should not happen")))
7177 (setq empty-line-p (org-previous-line-empty-p))
7178 (match-string 0))
7179 (error "*"))))
7180 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7181 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7182 pos hide-previous previous-pos)
7183 (cond
7184 ((and (org-at-heading-p) (bolp)
7185 (or (bobp)
7186 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7187 ;; insert before the current line
7188 (open-line (if blank 2 1)))
7189 ((and (bolp)
7190 (not org-insert-heading-respect-content)
7191 (or (bobp)
7192 (save-excursion
7193 (backward-char 1) (not (outline-invisible-p)))))
7194 ;; insert right here
7195 nil)
7197 ;; somewhere in the line
7198 (save-excursion
7199 (setq previous-pos (point-at-bol))
7200 (end-of-line)
7201 (setq hide-previous (outline-invisible-p)))
7202 (and org-insert-heading-respect-content (org-show-subtree))
7203 (let ((split
7204 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7205 (save-excursion
7206 (let ((p (point)))
7207 (goto-char (point-at-bol))
7208 (and (looking-at org-complex-heading-regexp)
7209 (match-beginning 4)
7210 (> p (match-beginning 4)))))))
7211 tags pos)
7212 (cond
7213 (org-insert-heading-respect-content
7214 (org-end-of-subtree nil t)
7215 (when (featurep 'org-inlinetask)
7216 (while (and (not (eobp))
7217 (looking-at "\\(\\*+\\)[ \t]+")
7218 (>= (length (match-string 1))
7219 org-inlinetask-min-level))
7220 (org-end-of-subtree nil t)))
7221 (or (bolp) (newline))
7222 (or (org-previous-line-empty-p)
7223 (and blank (newline)))
7224 (open-line 1))
7225 ((org-at-heading-p)
7226 (when hide-previous
7227 (show-children)
7228 (org-show-entry))
7229 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7230 (setq tags (and (match-end 2) (match-string 2)))
7231 (and (match-end 1)
7232 (delete-region (match-beginning 1) (match-end 1)))
7233 (setq pos (point-at-bol))
7234 (or split (end-of-line 1))
7235 (delete-horizontal-space)
7236 (if (string-match "\\`\\*+\\'"
7237 (buffer-substring (point-at-bol) (point)))
7238 (insert " "))
7239 (newline (if blank 2 1))
7240 (when tags
7241 (save-excursion
7242 (goto-char pos)
7243 (end-of-line 1)
7244 (insert " " tags)
7245 (org-set-tags nil 'align))))
7247 (or split (end-of-line 1))
7248 (newline (if blank 2 1)))))))
7249 (insert head) (just-one-space)
7250 (setq pos (point))
7251 (end-of-line 1)
7252 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7253 (when (and org-insert-heading-respect-content hide-previous)
7254 (save-excursion
7255 (goto-char previous-pos)
7256 (hide-subtree)))
7257 (run-hooks 'org-insert-heading-hook)))))
7259 (defun org-get-heading (&optional no-tags no-todo)
7260 "Return the heading of the current entry, without the stars.
7261 When NO-TAGS is non-nil, don't include tags.
7262 When NO-TODO is non-nil, don't include TODO keywords."
7263 (save-excursion
7264 (org-back-to-heading t)
7265 (cond
7266 ((and no-tags no-todo)
7267 (looking-at org-complex-heading-regexp)
7268 (match-string 4))
7269 (no-tags
7270 (looking-at (concat org-outline-regexp
7271 "\\(.*?\\)"
7272 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7273 (match-string 1))
7274 (no-todo
7275 (looking-at org-todo-line-regexp)
7276 (match-string 3))
7277 (t (looking-at org-heading-regexp)
7278 (match-string 2)))))
7280 (defun org-heading-components ()
7281 "Return the components of the current heading.
7282 This is a list with the following elements:
7283 - the level as an integer
7284 - the reduced level, different if `org-odd-levels-only' is set.
7285 - the TODO keyword, or nil
7286 - the priority character, like ?A, or nil if no priority is given
7287 - the headline text itself, or the tags string if no headline text
7288 - the tags string, or nil."
7289 (save-excursion
7290 (org-back-to-heading t)
7291 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7292 (list (length (match-string 1))
7293 (org-reduced-level (length (match-string 1)))
7294 (org-match-string-no-properties 2)
7295 (and (match-end 3) (aref (match-string 3) 2))
7296 (org-match-string-no-properties 4)
7297 (org-match-string-no-properties 5)))))
7299 (defun org-get-entry ()
7300 "Get the entry text, after heading, entire subtree."
7301 (save-excursion
7302 (org-back-to-heading t)
7303 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7305 (defun org-insert-heading-after-current ()
7306 "Insert a new heading with same level as current, after current subtree."
7307 (interactive)
7308 (org-back-to-heading)
7309 (org-insert-heading)
7310 (org-move-subtree-down)
7311 (end-of-line 1))
7313 (defun org-insert-heading-respect-content ()
7314 (interactive)
7315 (let ((org-insert-heading-respect-content t))
7316 (org-insert-heading t)))
7318 (defun org-insert-todo-heading-respect-content (&optional force-state)
7319 (interactive "P")
7320 (let ((org-insert-heading-respect-content t))
7321 (org-insert-todo-heading force-state t)))
7323 (defun org-insert-todo-heading (arg &optional force-heading)
7324 "Insert a new heading with the same level and TODO state as current heading.
7325 If the heading has no TODO state, or if the state is DONE, use the first
7326 state (TODO by default). Also with prefix arg, force first state."
7327 (interactive "P")
7328 (when (or force-heading (not (org-insert-item 'checkbox)))
7329 (org-insert-heading force-heading)
7330 (save-excursion
7331 (org-back-to-heading)
7332 (outline-previous-heading)
7333 (looking-at org-todo-line-regexp))
7334 (let*
7335 ((new-mark-x
7336 (if (or arg
7337 (not (match-beginning 2))
7338 (member (match-string 2) org-done-keywords))
7339 (car org-todo-keywords-1)
7340 (match-string 2)))
7341 (new-mark
7343 (run-hook-with-args-until-success
7344 'org-todo-get-default-hook new-mark-x nil)
7345 new-mark-x)))
7346 (beginning-of-line 1)
7347 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7348 (if org-treat-insert-todo-heading-as-state-change
7349 (org-todo new-mark)
7350 (insert new-mark " "))))
7351 (when org-provide-todo-statistics
7352 (org-update-parent-todo-statistics))))
7354 (defun org-insert-subheading (arg)
7355 "Insert a new subheading and demote it.
7356 Works for outline headings and for plain lists alike."
7357 (interactive "P")
7358 (org-insert-heading arg)
7359 (cond
7360 ((org-at-heading-p) (org-do-demote))
7361 ((org-at-item-p) (org-indent-item))))
7363 (defun org-insert-todo-subheading (arg)
7364 "Insert a new subheading with TODO keyword or checkbox and demote it.
7365 Works for outline headings and for plain lists alike."
7366 (interactive "P")
7367 (org-insert-todo-heading arg)
7368 (cond
7369 ((org-at-heading-p) (org-do-demote))
7370 ((org-at-item-p) (org-indent-item))))
7372 ;;; Promotion and Demotion
7374 (defvar org-after-demote-entry-hook nil
7375 "Hook run after an entry has been demoted.
7376 The cursor will be at the beginning of the entry.
7377 When a subtree is being demoted, the hook will be called for each node.")
7379 (defvar org-after-promote-entry-hook nil
7380 "Hook run after an entry has been promoted.
7381 The cursor will be at the beginning of the entry.
7382 When a subtree is being promoted, the hook will be called for each node.")
7384 (defun org-promote-subtree ()
7385 "Promote the entire subtree.
7386 See also `org-promote'."
7387 (interactive)
7388 (save-excursion
7389 (org-with-limited-levels (org-map-tree 'org-promote)))
7390 (org-fix-position-after-promote))
7392 (defun org-demote-subtree ()
7393 "Demote the entire subtree. See `org-demote'.
7394 See also `org-promote'."
7395 (interactive)
7396 (save-excursion
7397 (org-with-limited-levels (org-map-tree 'org-demote)))
7398 (org-fix-position-after-promote))
7401 (defun org-do-promote ()
7402 "Promote the current heading higher up the tree.
7403 If the region is active in `transient-mark-mode', promote all headings
7404 in the region."
7405 (interactive)
7406 (save-excursion
7407 (if (org-region-active-p)
7408 (org-map-region 'org-promote (region-beginning) (region-end))
7409 (org-promote)))
7410 (org-fix-position-after-promote))
7412 (defun org-do-demote ()
7413 "Demote the current heading lower down the tree.
7414 If the region is active in `transient-mark-mode', demote all headings
7415 in the region."
7416 (interactive)
7417 (save-excursion
7418 (if (org-region-active-p)
7419 (org-map-region 'org-demote (region-beginning) (region-end))
7420 (org-demote)))
7421 (org-fix-position-after-promote))
7423 (defun org-fix-position-after-promote ()
7424 "Make sure that after pro/demotion cursor position is right."
7425 (let ((pos (point)))
7426 (when (save-excursion
7427 (beginning-of-line 1)
7428 (looking-at org-todo-line-regexp)
7429 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7430 (cond ((eobp) (insert " "))
7431 ((eolp) (insert " "))
7432 ((equal (char-after) ?\ ) (forward-char 1))))))
7434 (defun org-current-level ()
7435 "Return the level of the current entry, or nil if before the first headline.
7436 The level is the number of stars at the beginning of the headline."
7437 (save-excursion
7438 (org-with-limited-levels
7439 (if (ignore-errors (org-back-to-heading t))
7440 (funcall outline-level)))))
7442 (defun org-get-previous-line-level ()
7443 "Return the outline depth of the last headline before the current line.
7444 Returns 0 for the first headline in the buffer, and nil if before the
7445 first headline."
7446 (let ((current-level (org-current-level))
7447 (prev-level (when (> (line-number-at-pos) 1)
7448 (save-excursion
7449 (beginning-of-line 0)
7450 (org-current-level)))))
7451 (cond ((null current-level) nil) ; Before first headline
7452 ((null prev-level) 0) ; At first headline
7453 (prev-level))))
7455 (defun org-reduced-level (l)
7456 "Compute the effective level of a heading.
7457 This takes into account the setting of `org-odd-levels-only'."
7458 (cond
7459 ((zerop l) 0)
7460 (org-odd-levels-only (1+ (floor (/ l 2))))
7461 (t l)))
7463 (defun org-level-increment ()
7464 "Return the number of stars that will be added or removed at a
7465 time to headlines when structure editing, based on the value of
7466 `org-odd-levels-only'."
7467 (if org-odd-levels-only 2 1))
7469 (defun org-get-valid-level (level &optional change)
7470 "Rectify a level change under the influence of `org-odd-levels-only'
7471 LEVEL is a current level, CHANGE is by how much the level should be
7472 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7473 even level numbers will become the next higher odd number."
7474 (if org-odd-levels-only
7475 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7476 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7477 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7478 (max 1 (+ level (or change 0)))))
7480 (if (boundp 'define-obsolete-function-alias)
7481 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7482 (define-obsolete-function-alias 'org-get-legal-level
7483 'org-get-valid-level)
7484 (define-obsolete-function-alias 'org-get-legal-level
7485 'org-get-valid-level "23.1")))
7487 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7488 ;; ̀org-with-limited-levels'
7489 (defun org-promote ()
7490 "Promote the current heading higher up the tree.
7491 If the region is active in `transient-mark-mode', promote all headings
7492 in the region."
7493 (org-back-to-heading t)
7494 (let* ((level (save-match-data (funcall outline-level)))
7495 (after-change-functions (remove 'flyspell-after-change-function
7496 after-change-functions))
7497 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7498 (diff (abs (- level (length up-head) -1))))
7499 (cond ((and (= level 1) org-called-with-limited-levels
7500 org-allow-promoting-top-level-subtree)
7501 (replace-match "# " nil t))
7502 ((= level 1)
7503 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7504 (t (replace-match up-head nil t)))
7505 ;; Fixup tag positioning
7506 (unless (= level 1)
7507 (and org-auto-align-tags (org-set-tags nil t))
7508 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7509 (run-hooks 'org-after-promote-entry-hook)))
7511 (defun org-demote ()
7512 "Demote the current heading lower down the tree.
7513 If the region is active in `transient-mark-mode', demote all headings
7514 in the region."
7515 (org-back-to-heading t)
7516 (let* ((level (save-match-data (funcall outline-level)))
7517 (after-change-functions (remove 'flyspell-after-change-function
7518 after-change-functions))
7519 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7520 (diff (abs (- level (length down-head) -1))))
7521 (replace-match down-head nil t)
7522 ;; Fixup tag positioning
7523 (and org-auto-align-tags (org-set-tags nil t))
7524 (if org-adapt-indentation (org-fixup-indentation diff))
7525 (run-hooks 'org-after-demote-entry-hook)))
7527 (defun org-cycle-level ()
7528 "Cycle the level of an empty headline through possible states.
7529 This goes first to child, then to parent, level, then up the hierarchy.
7530 After top level, it switches back to sibling level."
7531 (interactive)
7532 (let ((org-adapt-indentation nil))
7533 (when (org-point-at-end-of-empty-headline)
7534 (setq this-command 'org-cycle-level) ; Only needed for caching
7535 (let ((cur-level (org-current-level))
7536 (prev-level (org-get-previous-line-level)))
7537 (cond
7538 ;; If first headline in file, promote to top-level.
7539 ((= prev-level 0)
7540 (loop repeat (/ (- cur-level 1) (org-level-increment))
7541 do (org-do-promote)))
7542 ;; If same level as prev, demote one.
7543 ((= prev-level cur-level)
7544 (org-do-demote))
7545 ;; If parent is top-level, promote to top level if not already.
7546 ((= prev-level 1)
7547 (loop repeat (/ (- cur-level 1) (org-level-increment))
7548 do (org-do-promote)))
7549 ;; If top-level, return to prev-level.
7550 ((= cur-level 1)
7551 (loop repeat (/ (- prev-level 1) (org-level-increment))
7552 do (org-do-demote)))
7553 ;; If less than prev-level, promote one.
7554 ((< cur-level prev-level)
7555 (org-do-promote))
7556 ;; If deeper than prev-level, promote until higher than
7557 ;; prev-level.
7558 ((> cur-level prev-level)
7559 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7560 do (org-do-promote))))
7561 t))))
7563 (defun org-map-tree (fun)
7564 "Call FUN for every heading underneath the current one."
7565 (org-back-to-heading)
7566 (let ((level (funcall outline-level)))
7567 (save-excursion
7568 (funcall fun)
7569 (while (and (progn
7570 (outline-next-heading)
7571 (> (funcall outline-level) level))
7572 (not (eobp)))
7573 (funcall fun)))))
7575 (defun org-map-region (fun beg end)
7576 "Call FUN for every heading between BEG and END."
7577 (let ((org-ignore-region t))
7578 (save-excursion
7579 (setq end (copy-marker end))
7580 (goto-char beg)
7581 (if (and (re-search-forward org-outline-regexp-bol nil t)
7582 (< (point) end))
7583 (funcall fun))
7584 (while (and (progn
7585 (outline-next-heading)
7586 (< (point) end))
7587 (not (eobp)))
7588 (funcall fun)))))
7590 (defvar org-property-end-re) ; silence byte-compiler
7591 (defun org-fixup-indentation (diff)
7592 "Change the indentation in the current entry by DIFF.
7593 However, if any line in the current entry has no indentation, or if it
7594 would end up with no indentation after the change, nothing at all is done."
7595 (save-excursion
7596 (let ((end (save-excursion (outline-next-heading)
7597 (point-marker)))
7598 (prohibit (if (> diff 0)
7599 "^\\S-"
7600 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7601 col)
7602 (unless (save-excursion (end-of-line 1)
7603 (re-search-forward prohibit end t))
7604 (while (and (< (point) end)
7605 (re-search-forward "^[ \t]+" end t))
7606 (goto-char (match-end 0))
7607 (setq col (current-column))
7608 (if (< diff 0) (replace-match ""))
7609 (org-indent-to-column (+ diff col))))
7610 (move-marker end nil))))
7612 (defun org-convert-to-odd-levels ()
7613 "Convert an org-mode file with all levels allowed to one with odd levels.
7614 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7615 level 5 etc."
7616 (interactive)
7617 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7618 (let ((outline-level 'org-outline-level)
7619 (org-odd-levels-only nil) n)
7620 (save-excursion
7621 (goto-char (point-min))
7622 (while (re-search-forward "^\\*\\*+ " nil t)
7623 (setq n (- (length (match-string 0)) 2))
7624 (while (>= (setq n (1- n)) 0)
7625 (org-demote))
7626 (end-of-line 1))))))
7628 (defun org-convert-to-oddeven-levels ()
7629 "Convert an org-mode file with only odd levels to one with odd/even levels.
7630 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7631 file contains a section with an even level, conversion would
7632 destroy the structure of the file. An error is signaled in this
7633 case."
7634 (interactive)
7635 (goto-char (point-min))
7636 ;; First check if there are no even levels
7637 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7638 (org-show-context t)
7639 (error "Not all levels are odd in this file. Conversion not possible"))
7640 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7641 (let ((outline-regexp org-outline-regexp)
7642 (outline-level 'org-outline-level)
7643 (org-odd-levels-only nil) n)
7644 (save-excursion
7645 (goto-char (point-min))
7646 (while (re-search-forward "^\\*\\*+ " nil t)
7647 (setq n (/ (1- (length (match-string 0))) 2))
7648 (while (>= (setq n (1- n)) 0)
7649 (org-promote))
7650 (end-of-line 1))))))
7652 (defun org-tr-level (n)
7653 "Make N odd if required."
7654 (if org-odd-levels-only (1+ (/ n 2)) n))
7656 ;;; Vertical tree motion, cutting and pasting of subtrees
7658 (defun org-move-subtree-up (&optional arg)
7659 "Move the current subtree up past ARG headlines of the same level."
7660 (interactive "p")
7661 (org-move-subtree-down (- (prefix-numeric-value arg))))
7663 (defun org-move-subtree-down (&optional arg)
7664 "Move the current subtree down past ARG headlines of the same level."
7665 (interactive "p")
7666 (setq arg (prefix-numeric-value arg))
7667 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7668 'org-get-last-sibling))
7669 (ins-point (make-marker))
7670 (cnt (abs arg))
7671 (col (current-column))
7672 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7673 ;; Select the tree
7674 (org-back-to-heading)
7675 (setq beg0 (point))
7676 (save-excursion
7677 (setq ne-beg (org-back-over-empty-lines))
7678 (setq beg (point)))
7679 (save-match-data
7680 (save-excursion (outline-end-of-heading)
7681 (setq folded (outline-invisible-p)))
7682 (outline-end-of-subtree))
7683 (outline-next-heading)
7684 (setq ne-end (org-back-over-empty-lines))
7685 (setq end (point))
7686 (goto-char beg0)
7687 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7688 ;; include less whitespace
7689 (save-excursion
7690 (goto-char beg)
7691 (forward-line (- ne-beg ne-end))
7692 (setq beg (point))))
7693 ;; Find insertion point, with error handling
7694 (while (> cnt 0)
7695 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7696 (progn (goto-char beg0)
7697 (error "Cannot move past superior level or buffer limit")))
7698 (setq cnt (1- cnt)))
7699 (if (> arg 0)
7700 ;; Moving forward - still need to move over subtree
7701 (progn (org-end-of-subtree t t)
7702 (save-excursion
7703 (org-back-over-empty-lines)
7704 (or (bolp) (newline)))))
7705 (setq ne-ins (org-back-over-empty-lines))
7706 (move-marker ins-point (point))
7707 (setq txt (buffer-substring beg end))
7708 (org-save-markers-in-region beg end)
7709 (delete-region beg end)
7710 (org-remove-empty-overlays-at beg)
7711 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7712 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7713 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7714 (let ((bbb (point)))
7715 (insert-before-markers txt)
7716 (org-reinstall-markers-in-region bbb)
7717 (move-marker ins-point bbb))
7718 (or (bolp) (insert "\n"))
7719 (setq ins-end (point))
7720 (goto-char ins-point)
7721 (org-skip-whitespace)
7722 (when (and (< arg 0)
7723 (org-first-sibling-p)
7724 (> ne-ins ne-beg))
7725 ;; Move whitespace back to beginning
7726 (save-excursion
7727 (goto-char ins-end)
7728 (let ((kill-whole-line t))
7729 (kill-line (- ne-ins ne-beg)) (point)))
7730 (insert (make-string (- ne-ins ne-beg) ?\n)))
7731 (move-marker ins-point nil)
7732 (if folded
7733 (hide-subtree)
7734 (org-show-entry)
7735 (show-children)
7736 (org-cycle-hide-drawers 'children))
7737 (org-clean-visibility-after-subtree-move)
7738 ;; move back to the initial column we were at
7739 (move-to-column col)))
7741 (defvar org-subtree-clip ""
7742 "Clipboard for cut and paste of subtrees.
7743 This is actually only a copy of the kill, because we use the normal kill
7744 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7746 (defvar org-subtree-clip-folded nil
7747 "Was the last copied subtree folded?
7748 This is used to fold the tree back after pasting.")
7750 (defun org-cut-subtree (&optional n)
7751 "Cut the current subtree into the clipboard.
7752 With prefix arg N, cut this many sequential subtrees.
7753 This is a short-hand for marking the subtree and then cutting it."
7754 (interactive "p")
7755 (org-copy-subtree n 'cut))
7757 (defun org-copy-subtree (&optional n cut force-store-markers)
7758 "Cut the current subtree into the clipboard.
7759 With prefix arg N, cut this many sequential subtrees.
7760 This is a short-hand for marking the subtree and then copying it.
7761 If CUT is non-nil, actually cut the subtree.
7762 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7763 of some markers in the region, even if CUT is non-nil. This is
7764 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7765 (interactive "p")
7766 (let (beg end folded (beg0 (point)))
7767 (if (org-called-interactively-p 'any)
7768 (org-back-to-heading nil) ; take what looks like a subtree
7769 (org-back-to-heading t)) ; take what is really there
7770 (org-back-over-empty-lines)
7771 (setq beg (point))
7772 (skip-chars-forward " \t\r\n")
7773 (save-match-data
7774 (save-excursion (outline-end-of-heading)
7775 (setq folded (outline-invisible-p)))
7776 (condition-case nil
7777 (org-forward-same-level (1- n) t)
7778 (error nil))
7779 (org-end-of-subtree t t))
7780 (org-back-over-empty-lines)
7781 (setq end (point))
7782 (goto-char beg0)
7783 (when (> end beg)
7784 (setq org-subtree-clip-folded folded)
7785 (when (or cut force-store-markers)
7786 (org-save-markers-in-region beg end))
7787 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7788 (setq org-subtree-clip (current-kill 0))
7789 (message "%s: Subtree(s) with %d characters"
7790 (if cut "Cut" "Copied")
7791 (length org-subtree-clip)))))
7793 (defun org-paste-subtree (&optional level tree for-yank)
7794 "Paste the clipboard as a subtree, with modification of headline level.
7795 The entire subtree is promoted or demoted in order to match a new headline
7796 level.
7798 If the cursor is at the beginning of a headline, the same level as
7799 that headline is used to paste the tree
7801 If not, the new level is derived from the *visible* headings
7802 before and after the insertion point, and taken to be the inferior headline
7803 level of the two. So if the previous visible heading is level 3 and the
7804 next is level 4 (or vice versa), level 4 will be used for insertion.
7805 This makes sure that the subtree remains an independent subtree and does
7806 not swallow low level entries.
7808 You can also force a different level, either by using a numeric prefix
7809 argument, or by inserting the heading marker by hand. For example, if the
7810 cursor is after \"*****\", then the tree will be shifted to level 5.
7812 If optional TREE is given, use this text instead of the kill ring.
7814 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7815 move back over whitespace before inserting, and move point to the end of
7816 the inserted text when done."
7817 (interactive "P")
7818 (setq tree (or tree (and kill-ring (current-kill 0))))
7819 (unless (org-kill-is-subtree-p tree)
7820 (error "%s"
7821 (substitute-command-keys
7822 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7823 (org-with-limited-levels
7824 (let* ((visp (not (outline-invisible-p)))
7825 (txt tree)
7826 (^re_ "\\(\\*+\\)[ \t]*")
7827 (old-level (if (string-match org-outline-regexp-bol txt)
7828 (- (match-end 0) (match-beginning 0) 1)
7829 -1))
7830 (force-level (cond (level (prefix-numeric-value level))
7831 ((and (looking-at "[ \t]*$")
7832 (string-match
7833 "^\\*+$" (buffer-substring
7834 (point-at-bol) (point))))
7835 (- (match-end 1) (match-beginning 1)))
7836 ((and (bolp)
7837 (looking-at org-outline-regexp))
7838 (- (match-end 0) (point) 1))
7839 (t nil)))
7840 (previous-level (save-excursion
7841 (condition-case nil
7842 (progn
7843 (outline-previous-visible-heading 1)
7844 (if (looking-at ^re_)
7845 (- (match-end 0) (match-beginning 0) 1)
7847 (error 1))))
7848 (next-level (save-excursion
7849 (condition-case nil
7850 (progn
7851 (or (looking-at org-outline-regexp)
7852 (outline-next-visible-heading 1))
7853 (if (looking-at ^re_)
7854 (- (match-end 0) (match-beginning 0) 1)
7856 (error 1))))
7857 (new-level (or force-level (max previous-level next-level)))
7858 (shift (if (or (= old-level -1)
7859 (= new-level -1)
7860 (= old-level new-level))
7862 (- new-level old-level)))
7863 (delta (if (> shift 0) -1 1))
7864 (func (if (> shift 0) 'org-demote 'org-promote))
7865 (org-odd-levels-only nil)
7866 beg end newend)
7867 ;; Remove the forced level indicator
7868 (if force-level
7869 (delete-region (point-at-bol) (point)))
7870 ;; Paste
7871 (beginning-of-line (if (bolp) 1 2))
7872 (unless for-yank (org-back-over-empty-lines))
7873 (setq beg (point))
7874 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7875 (insert-before-markers txt)
7876 (unless (string-match "\n\\'" txt) (insert "\n"))
7877 (setq newend (point))
7878 (org-reinstall-markers-in-region beg)
7879 (setq end (point))
7880 (goto-char beg)
7881 (skip-chars-forward " \t\n\r")
7882 (setq beg (point))
7883 (if (and (outline-invisible-p) visp)
7884 (save-excursion (outline-show-heading)))
7885 ;; Shift if necessary
7886 (unless (= shift 0)
7887 (save-restriction
7888 (narrow-to-region beg end)
7889 (while (not (= shift 0))
7890 (org-map-region func (point-min) (point-max))
7891 (setq shift (+ delta shift)))
7892 (goto-char (point-min))
7893 (setq newend (point-max))))
7894 (when (or (org-called-interactively-p 'interactive) for-yank)
7895 (message "Clipboard pasted as level %d subtree" new-level))
7896 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7897 kill-ring
7898 (eq org-subtree-clip (current-kill 0))
7899 org-subtree-clip-folded)
7900 ;; The tree was folded before it was killed/copied
7901 (hide-subtree))
7902 (and for-yank (goto-char newend)))))
7904 (defun org-kill-is-subtree-p (&optional txt)
7905 "Check if the current kill is an outline subtree, or a set of trees.
7906 Returns nil if kill does not start with a headline, or if the first
7907 headline level is not the largest headline level in the tree.
7908 So this will actually accept several entries of equal levels as well,
7909 which is OK for `org-paste-subtree'.
7910 If optional TXT is given, check this string instead of the current kill."
7911 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7912 (re (org-get-limited-outline-regexp))
7913 (^re (concat "^" re))
7914 (start-level (and kill
7915 (string-match
7916 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7917 kill)
7918 (- (match-end 2) (match-beginning 2) 1)))
7919 (start (1+ (or (match-beginning 2) -1))))
7920 (if (not start-level)
7921 (progn
7922 nil) ;; does not even start with a heading
7923 (catch 'exit
7924 (while (setq start (string-match ^re kill (1+ start)))
7925 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7926 (throw 'exit nil)))
7927 t))))
7929 (defvar org-markers-to-move nil
7930 "Markers that should be moved with a cut-and-paste operation.
7931 Those markers are stored together with their positions relative to
7932 the start of the region.")
7934 (defun org-save-markers-in-region (beg end)
7935 "Check markers in region.
7936 If these markers are between BEG and END, record their position relative
7937 to BEG, so that after moving the block of text, we can put the markers back
7938 into place.
7939 This function gets called just before an entry or tree gets cut from the
7940 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7941 called immediately, to move the markers with the entries."
7942 (setq org-markers-to-move nil)
7943 (when (featurep 'org-clock)
7944 (org-clock-save-markers-for-cut-and-paste beg end))
7945 (when (featurep 'org-agenda)
7946 (org-agenda-save-markers-for-cut-and-paste beg end)))
7948 (defun org-check-and-save-marker (marker beg end)
7949 "Check if MARKER is between BEG and END.
7950 If yes, remember the marker and the distance to BEG."
7951 (when (and (marker-buffer marker)
7952 (equal (marker-buffer marker) (current-buffer)))
7953 (if (and (>= marker beg) (< marker end))
7954 (push (cons marker (- marker beg)) org-markers-to-move))))
7956 (defun org-reinstall-markers-in-region (beg)
7957 "Move all remembered markers to their position relative to BEG."
7958 (mapc (lambda (x)
7959 (move-marker (car x) (+ beg (cdr x))))
7960 org-markers-to-move)
7961 (setq org-markers-to-move nil))
7963 (defun org-narrow-to-subtree ()
7964 "Narrow buffer to the current subtree."
7965 (interactive)
7966 (save-excursion
7967 (save-match-data
7968 (org-with-limited-levels
7969 (narrow-to-region
7970 (progn (org-back-to-heading t) (point))
7971 (progn (org-end-of-subtree t t)
7972 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7973 (point)))))))
7975 (defun org-narrow-to-block ()
7976 "Narrow buffer to the current block."
7977 (interactive)
7978 (let* ((case-fold-search t)
7979 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7980 "^[ \t]*#\\+end_.*")))
7981 (if blockp
7982 (narrow-to-region (car blockp) (cdr blockp))
7983 (error "Not in a block"))))
7985 (eval-when-compile
7986 (defvar org-property-drawer-re))
7988 (defvar org-property-start-re) ;; defined below
7989 (defun org-clone-subtree-with-time-shift (n &optional shift)
7990 "Clone the task (subtree) at point N times.
7991 The clones will be inserted as siblings.
7993 In interactive use, the user will be prompted for the number of
7994 clones to be produced, and for a time SHIFT, which may be a
7995 repeater as used in time stamps, for example `+3d'.
7997 When a valid repeater is given and the entry contains any time
7998 stamps, the clones will become a sequence in time, with time
7999 stamps in the subtree shifted for each clone produced. If SHIFT
8000 is nil or the empty string, time stamps will be left alone. The
8001 ID property of the original subtree is removed.
8003 If the original subtree did contain time stamps with a repeater,
8004 the following will happen:
8005 - the repeater will be removed in each clone
8006 - an additional clone will be produced, with the current, unshifted
8007 date(s) in the entry.
8008 - the original entry will be placed *after* all the clones, with
8009 repeater intact.
8010 - the start days in the repeater in the original entry will be shifted
8011 to past the last clone.
8012 In this way you can spell out a number of instances of a repeating task,
8013 and still retain the repeater to cover future instances of the task."
8014 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8015 (let (beg end template task idprop
8016 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8017 (drawer-re org-drawer-regexp))
8018 (if (not (and (integerp n) (> n 0)))
8019 (error "Invalid number of replications %s" n))
8020 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8021 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8022 shift)))
8023 (error "Invalid shift specification %s" shift))
8024 (when doshift
8025 (setq shift-n (string-to-number (match-string 1 shift))
8026 shift-what (cdr (assoc (match-string 2 shift)
8027 '(("d" . day) ("w" . week)
8028 ("m" . month) ("y" . year))))))
8029 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8030 (setq nmin 1 nmax n)
8031 (org-back-to-heading t)
8032 (setq beg (point))
8033 (setq idprop (org-entry-get nil "ID"))
8034 (org-end-of-subtree t t)
8035 (or (bolp) (insert "\n"))
8036 (setq end (point))
8037 (setq template (buffer-substring beg end))
8038 (when (and doshift
8039 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8040 (delete-region beg end)
8041 (setq end beg)
8042 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8043 (goto-char end)
8044 (loop for n from nmin to nmax do
8045 ;; prepare clone
8046 (with-temp-buffer
8047 (insert template)
8048 (org-mode)
8049 (goto-char (point-min))
8050 (org-show-subtree)
8051 (and idprop (if org-clone-delete-id
8052 (org-entry-delete nil "ID")
8053 (org-id-get-create t)))
8054 (unless (= n 0)
8055 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8056 (kill-whole-line))
8057 (goto-char (point-min))
8058 (while (re-search-forward drawer-re nil t)
8059 (mapc (lambda (d)
8060 (org-remove-empty-drawer-at d (point))) org-drawers)))
8061 (goto-char (point-min))
8062 (when doshift
8063 (while (re-search-forward org-ts-regexp-both nil t)
8064 (org-timestamp-change (* n shift-n) shift-what))
8065 (unless (= n n-no-remove)
8066 (goto-char (point-min))
8067 (while (re-search-forward org-ts-regexp nil t)
8068 (save-excursion
8069 (goto-char (match-beginning 0))
8070 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8071 (delete-region (match-beginning 1) (match-end 1)))))))
8072 (setq task (buffer-string)))
8073 (insert task))
8074 (goto-char beg)))
8076 ;;; Outline Sorting
8078 (defun org-sort (with-case)
8079 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8080 Optional argument WITH-CASE means sort case-sensitively."
8081 (interactive "P")
8082 (cond
8083 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8084 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8086 (org-call-with-arg 'org-sort-entries with-case))))
8088 (defun org-sort-remove-invisible (s)
8089 (remove-text-properties 0 (length s) org-rm-props s)
8090 (while (string-match org-bracket-link-regexp s)
8091 (setq s (replace-match (if (match-end 2)
8092 (match-string 3 s)
8093 (match-string 1 s)) t t s)))
8096 (defvar org-priority-regexp) ; defined later in the file
8098 (defvar org-after-sorting-entries-or-items-hook nil
8099 "Hook that is run after a bunch of entries or items have been sorted.
8100 When children are sorted, the cursor is in the parent line when this
8101 hook gets called. When a region or a plain list is sorted, the cursor
8102 will be in the first entry of the sorted region/list.")
8104 (defun org-sort-entries
8105 (&optional with-case sorting-type getkey-func compare-func property)
8106 "Sort entries on a certain level of an outline tree.
8107 If there is an active region, the entries in the region are sorted.
8108 Else, if the cursor is before the first entry, sort the top-level items.
8109 Else, the children of the entry at point are sorted.
8111 Sorting can be alphabetically, numerically, by date/time as given by
8112 a time stamp, by a property or by priority.
8114 The command prompts for the sorting type unless it has been given to the
8115 function through the SORTING-TYPE argument, which needs to be a character,
8116 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8117 precise meaning of each character:
8119 n Numerically, by converting the beginning of the entry/item to a number.
8120 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8121 t By date/time, either the first active time stamp in the entry, or, if
8122 none exist, by the first inactive one.
8123 s By the scheduled date/time.
8124 d By deadline date/time.
8125 c By creation time, which is assumed to be the first inactive time stamp
8126 at the beginning of a line.
8127 p By priority according to the cookie.
8128 r By the value of a property.
8130 Capital letters will reverse the sort order.
8132 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8133 called with point at the beginning of the record. It must return either
8134 a string or a number that should serve as the sorting key for that record.
8136 Comparing entries ignores case by default. However, with an optional argument
8137 WITH-CASE, the sorting considers case as well."
8138 (interactive "P")
8139 (let ((case-func (if with-case 'identity 'downcase))
8140 start beg end stars re re2
8141 txt what tmp)
8142 ;; Find beginning and end of region to sort
8143 (cond
8144 ((org-region-active-p)
8145 ;; we will sort the region
8146 (setq end (region-end)
8147 what "region")
8148 (goto-char (region-beginning))
8149 (if (not (org-at-heading-p)) (outline-next-heading))
8150 (setq start (point)))
8151 ((or (org-at-heading-p)
8152 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8153 ;; we will sort the children of the current headline
8154 (org-back-to-heading)
8155 (setq start (point)
8156 end (progn (org-end-of-subtree t t)
8157 (or (bolp) (insert "\n"))
8158 (org-back-over-empty-lines)
8159 (point))
8160 what "children")
8161 (goto-char start)
8162 (show-subtree)
8163 (outline-next-heading))
8165 ;; we will sort the top-level entries in this file
8166 (goto-char (point-min))
8167 (or (org-at-heading-p) (outline-next-heading))
8168 (setq start (point))
8169 (goto-char (point-max))
8170 (beginning-of-line 1)
8171 (when (looking-at ".*?\\S-")
8172 ;; File ends in a non-white line
8173 (end-of-line 1)
8174 (insert "\n"))
8175 (setq end (point-max))
8176 (setq what "top-level")
8177 (goto-char start)
8178 (show-all)))
8180 (setq beg (point))
8181 (if (>= beg end) (error "Nothing to sort"))
8183 (looking-at "\\(\\*+\\)")
8184 (setq stars (match-string 1)
8185 re (concat "^" (regexp-quote stars) " +")
8186 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8187 txt (buffer-substring beg end))
8188 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8189 (if (and (not (equal stars "*")) (string-match re2 txt))
8190 (error "Region to sort contains a level above the first entry"))
8192 (unless sorting-type
8193 (message
8194 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8195 [t]ime [s]cheduled [d]eadline [c]reated
8196 A/N/T/S/D/C/P/O/F means reversed:"
8197 what)
8198 (setq sorting-type (read-char-exclusive))
8200 (and (= (downcase sorting-type) ?f)
8201 (setq getkey-func
8202 (org-icompleting-read "Sort using function: "
8203 obarray 'fboundp t nil nil))
8204 (setq getkey-func (intern getkey-func)))
8206 (and (= (downcase sorting-type) ?r)
8207 (setq property
8208 (org-icompleting-read "Property: "
8209 (mapcar 'list (org-buffer-property-keys t))
8210 nil t))))
8212 (message "Sorting entries...")
8214 (save-restriction
8215 (narrow-to-region start end)
8216 (let ((dcst (downcase sorting-type))
8217 (case-fold-search nil)
8218 (now (current-time)))
8219 (sort-subr
8220 (/= dcst sorting-type)
8221 ;; This function moves to the beginning character of the "record" to
8222 ;; be sorted.
8223 (lambda nil
8224 (if (re-search-forward re nil t)
8225 (goto-char (match-beginning 0))
8226 (goto-char (point-max))))
8227 ;; This function moves to the last character of the "record" being
8228 ;; sorted.
8229 (lambda nil
8230 (save-match-data
8231 (condition-case nil
8232 (outline-forward-same-level 1)
8233 (error
8234 (goto-char (point-max))))))
8235 ;; This function returns the value that gets sorted against.
8236 (lambda nil
8237 (cond
8238 ((= dcst ?n)
8239 (if (looking-at org-complex-heading-regexp)
8240 (string-to-number (match-string 4))
8241 nil))
8242 ((= dcst ?a)
8243 (if (looking-at org-complex-heading-regexp)
8244 (funcall case-func (match-string 4))
8245 nil))
8246 ((= dcst ?t)
8247 (let ((end (save-excursion (outline-next-heading) (point))))
8248 (if (or (re-search-forward org-ts-regexp end t)
8249 (re-search-forward org-ts-regexp-both end t))
8250 (org-time-string-to-seconds (match-string 0))
8251 (org-float-time now))))
8252 ((= dcst ?c)
8253 (let ((end (save-excursion (outline-next-heading) (point))))
8254 (if (re-search-forward
8255 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8256 end t)
8257 (org-time-string-to-seconds (match-string 0))
8258 (org-float-time now))))
8259 ((= dcst ?s)
8260 (let ((end (save-excursion (outline-next-heading) (point))))
8261 (if (re-search-forward org-scheduled-time-regexp end t)
8262 (org-time-string-to-seconds (match-string 1))
8263 (org-float-time now))))
8264 ((= dcst ?d)
8265 (let ((end (save-excursion (outline-next-heading) (point))))
8266 (if (re-search-forward org-deadline-time-regexp end t)
8267 (org-time-string-to-seconds (match-string 1))
8268 (org-float-time now))))
8269 ((= dcst ?p)
8270 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8271 (string-to-char (match-string 2))
8272 org-default-priority))
8273 ((= dcst ?r)
8274 (or (org-entry-get nil property) ""))
8275 ((= dcst ?o)
8276 (if (looking-at org-complex-heading-regexp)
8277 (- 9999 (length (member (match-string 2)
8278 org-todo-keywords-1)))))
8279 ((= dcst ?f)
8280 (if getkey-func
8281 (progn
8282 (setq tmp (funcall getkey-func))
8283 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8284 tmp)
8285 (error "Invalid key function `%s'" getkey-func)))
8286 (t (error "Invalid sorting type `%c'" sorting-type))))
8288 (cond
8289 ((= dcst ?a) 'string<)
8290 ((= dcst ?f) compare-func)
8291 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8292 (t nil)))))
8293 (run-hooks 'org-after-sorting-entries-or-items-hook)
8294 (message "Sorting entries...done")))
8296 (defun org-do-sort (table what &optional with-case sorting-type)
8297 "Sort TABLE of WHAT according to SORTING-TYPE.
8298 The user will be prompted for the SORTING-TYPE if the call to this
8299 function does not specify it. WHAT is only for the prompt, to indicate
8300 what is being sorted. The sorting key will be extracted from
8301 the car of the elements of the table.
8302 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8303 (unless sorting-type
8304 (message
8305 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8306 what)
8307 (setq sorting-type (read-char-exclusive)))
8308 (let ((dcst (downcase sorting-type))
8309 extractfun comparefun)
8310 ;; Define the appropriate functions
8311 (cond
8312 ((= dcst ?n)
8313 (setq extractfun 'string-to-number
8314 comparefun (if (= dcst sorting-type) '< '>)))
8315 ((= dcst ?a)
8316 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8317 (lambda(x) (downcase (org-sort-remove-invisible x))))
8318 comparefun (if (= dcst sorting-type)
8319 'string<
8320 (lambda (a b) (and (not (string< a b))
8321 (not (string= a b)))))))
8322 ((= dcst ?t)
8323 (setq extractfun
8324 (lambda (x)
8325 (if (or (string-match org-ts-regexp x)
8326 (string-match org-ts-regexp-both x))
8327 (org-float-time
8328 (org-time-string-to-time (match-string 0 x)))
8330 comparefun (if (= dcst sorting-type) '< '>)))
8331 (t (error "Invalid sorting type `%c'" sorting-type)))
8333 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8334 table)
8335 (lambda (a b) (funcall comparefun (car a) (car b))))))
8338 ;;; The orgstruct minor mode
8340 ;; Define a minor mode which can be used in other modes in order to
8341 ;; integrate the org-mode structure editing commands.
8343 ;; This is really a hack, because the org-mode structure commands use
8344 ;; keys which normally belong to the major mode. Here is how it
8345 ;; works: The minor mode defines all the keys necessary to operate the
8346 ;; structure commands, but wraps the commands into a function which
8347 ;; tests if the cursor is currently at a headline or a plain list
8348 ;; item. If that is the case, the structure command is used,
8349 ;; temporarily setting many Org-mode variables like regular
8350 ;; expressions for filling etc. However, when any of those keys is
8351 ;; used at a different location, function uses `key-binding' to look
8352 ;; up if the key has an associated command in another currently active
8353 ;; keymap (minor modes, major mode, global), and executes that
8354 ;; command. There might be problems if any of the keys is otherwise
8355 ;; used as a prefix key.
8357 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8358 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8359 ;; addresses this by checking explicitly for both bindings.
8361 (defvar orgstruct-mode-map (make-sparse-keymap)
8362 "Keymap for the minor `orgstruct-mode'.")
8364 (defvar org-local-vars nil
8365 "List of local variables, for use by `orgstruct-mode'.")
8367 ;;;###autoload
8368 (define-minor-mode orgstruct-mode
8369 "Toggle the minor mode `orgstruct-mode'.
8370 This mode is for using Org-mode structure commands in other
8371 modes. The following keys behave as if Org-mode were active, if
8372 the cursor is on a headline, or on a plain list item (both as
8373 defined by Org-mode).
8375 M-up Move entry/item up
8376 M-down Move entry/item down
8377 M-left Promote
8378 M-right Demote
8379 M-S-up Move entry/item up
8380 M-S-down Move entry/item down
8381 M-S-left Promote subtree
8382 M-S-right Demote subtree
8383 M-q Fill paragraph and items like in Org-mode
8384 C-c ^ Sort entries
8385 C-c - Cycle list bullet
8386 TAB Cycle item visibility
8387 M-RET Insert new heading/item
8388 S-M-RET Insert new TODO heading / Checkbox item
8389 C-c C-c Set tags / toggle checkbox"
8390 nil " OrgStruct" nil
8391 (org-load-modules-maybe)
8392 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8394 ;;;###autoload
8395 (defun turn-on-orgstruct ()
8396 "Unconditionally turn on `orgstruct-mode'."
8397 (orgstruct-mode 1))
8399 (defvar org-fb-vars nil)
8400 (make-variable-buffer-local 'org-fb-vars)
8401 (defun orgstruct++-mode (&optional arg)
8402 "Toggle `orgstruct-mode', the enhanced version of it.
8403 In addition to setting orgstruct-mode, this also exports all
8404 indentation and autofilling variables from org-mode into the
8405 buffer. It will also recognize item context in multiline items."
8406 (interactive "P")
8407 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8408 (if (< arg 1)
8409 (progn (orgstruct-mode -1)
8410 (mapc (lambda(v)
8411 (org-set-local (car v)
8412 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8413 org-fb-vars))
8414 (orgstruct-mode 1)
8415 (setq org-fb-vars nil)
8416 (let (var val)
8417 (mapc
8418 (lambda (x)
8419 (when (string-match
8420 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8421 (symbol-name (car x)))
8422 (setq var (car x) val (nth 1 x))
8423 (push (list var `(quote ,(eval var))) org-fb-vars)
8424 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8425 org-local-vars)
8426 (org-set-local 'orgstruct-is-++ t))))
8428 (defvar orgstruct-is-++ nil
8429 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8430 (make-variable-buffer-local 'orgstruct-is-++)
8432 ;;;###autoload
8433 (defun turn-on-orgstruct++ ()
8434 "Unconditionally turn on `orgstruct++-mode'."
8435 (orgstruct++-mode 1))
8437 (defun orgstruct-error ()
8438 "Error when there is no default binding for a structure key."
8439 (interactive)
8440 (error "This key has no function outside structure elements"))
8442 (defun orgstruct-setup ()
8443 "Setup orgstruct keymaps."
8444 (let ((nfunc 0)
8445 (bindings
8446 (list
8447 '([(meta up)] org-metaup)
8448 '([(meta down)] org-metadown)
8449 '([(meta left)] org-metaleft)
8450 '([(meta right)] org-metaright)
8451 '([(meta shift up)] org-shiftmetaup)
8452 '([(meta shift down)] org-shiftmetadown)
8453 '([(meta shift left)] org-shiftmetaleft)
8454 '([(meta shift right)] org-shiftmetaright)
8455 '([?\e (up)] org-metaup)
8456 '([?\e (down)] org-metadown)
8457 '([?\e (left)] org-metaleft)
8458 '([?\e (right)] org-metaright)
8459 '([?\e (shift up)] org-shiftmetaup)
8460 '([?\e (shift down)] org-shiftmetadown)
8461 '([?\e (shift left)] org-shiftmetaleft)
8462 '([?\e (shift right)] org-shiftmetaright)
8463 '([(shift up)] org-shiftup)
8464 '([(shift down)] org-shiftdown)
8465 '([(shift left)] org-shiftleft)
8466 '([(shift right)] org-shiftright)
8467 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8468 '("\M-q" fill-paragraph)
8469 '("\C-c^" org-sort)
8470 '("\C-c-" org-cycle-list-bullet)))
8471 elt key fun cmd)
8472 (while (setq elt (pop bindings))
8473 (setq nfunc (1+ nfunc))
8474 (setq key (org-key (car elt))
8475 fun (nth 1 elt)
8476 cmd (orgstruct-make-binding fun nfunc key))
8477 (org-defkey orgstruct-mode-map key cmd))
8479 ;; Special treatment needed for TAB and RET
8480 (org-defkey orgstruct-mode-map [(tab)]
8481 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8482 (org-defkey orgstruct-mode-map "\C-i"
8483 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8485 (org-defkey orgstruct-mode-map "\M-\C-m"
8486 (orgstruct-make-binding 'org-insert-heading 105
8487 "\M-\C-m" [(meta return)]))
8488 (org-defkey orgstruct-mode-map [(meta return)]
8489 (orgstruct-make-binding 'org-insert-heading 106
8490 [(meta return)] "\M-\C-m"))
8492 (org-defkey orgstruct-mode-map [(shift meta return)]
8493 (orgstruct-make-binding 'org-insert-todo-heading 107
8494 [(meta return)] "\M-\C-m"))
8496 (org-defkey orgstruct-mode-map "\e\C-m"
8497 (orgstruct-make-binding 'org-insert-heading 108
8498 "\e\C-m" [?\e (return)]))
8499 (org-defkey orgstruct-mode-map [?\e (return)]
8500 (orgstruct-make-binding 'org-insert-heading 109
8501 [?\e (return)] "\e\C-m"))
8502 (org-defkey orgstruct-mode-map [?\e (shift return)]
8503 (orgstruct-make-binding 'org-insert-todo-heading 110
8504 [?\e (return)] "\e\C-m"))
8506 (unless org-local-vars
8507 (setq org-local-vars (org-get-local-variables)))
8511 (defun orgstruct-make-binding (fun n &rest keys)
8512 "Create a function for binding in the structure minor mode.
8513 FUN is the command to call inside a table. N is used to create a unique
8514 command name. KEYS are keys that should be checked in for a command
8515 to execute outside of tables."
8516 (eval
8517 (list 'defun
8518 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8519 '(arg)
8520 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8521 "Outside of structure, run the binding of `"
8522 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8523 "'.")
8524 '(interactive "p")
8525 (list 'if
8526 `(org-context-p 'headline 'item
8527 (and orgstruct-is-++
8528 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8529 'item-body))
8530 (list 'org-run-like-in-org-mode (list 'quote fun))
8531 (list 'let '(orgstruct-mode)
8532 (list 'call-interactively
8533 (append '(or)
8534 (mapcar (lambda (k)
8535 (list 'key-binding k))
8536 keys)
8537 '('orgstruct-error))))))))
8539 (defun org-context-p (&rest contexts)
8540 "Check if local context is any of CONTEXTS.
8541 Possible values in the list of contexts are `table', `headline', and `item'."
8542 (let ((pos (point)))
8543 (goto-char (point-at-bol))
8544 (prog1 (or (and (memq 'table contexts)
8545 (looking-at "[ \t]*|"))
8546 (and (memq 'headline contexts)
8547 (looking-at org-outline-regexp))
8548 (and (memq 'item contexts)
8549 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8550 (and (memq 'item-body contexts)
8551 (org-in-item-p)))
8552 (goto-char pos))))
8554 (defun org-get-local-variables ()
8555 "Return a list of all local variables in an org-mode buffer."
8556 (let (varlist)
8557 (with-current-buffer (get-buffer-create "*Org tmp*")
8558 (erase-buffer)
8559 (org-mode)
8560 (setq varlist (buffer-local-variables)))
8561 (kill-buffer "*Org tmp*")
8562 (delq nil
8563 (mapcar
8564 (lambda (x)
8565 (setq x
8566 (if (symbolp x)
8567 (list x)
8568 (list (car x) (list 'quote (cdr x)))))
8569 (if (string-match
8570 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8571 (symbol-name (car x)))
8572 x nil))
8573 varlist))))
8575 (defun org-clone-local-variables (from-buffer &optional regexp)
8576 "Clone local variables from FROM-BUFFER.
8577 Optional argument REGEXP selects variables to clone."
8578 (mapc
8579 (lambda (pair)
8580 (and (symbolp (car pair))
8581 (or (null regexp)
8582 (string-match regexp (symbol-name (car pair))))
8583 (set (make-local-variable (car pair))
8584 (cdr pair))))
8585 (buffer-local-variables from-buffer)))
8587 ;;;###autoload
8588 (defun org-run-like-in-org-mode (cmd)
8589 "Run a command, pretending that the current buffer is in Org-mode.
8590 This will temporarily bind local variables that are typically bound in
8591 Org-mode to the values they have in Org-mode, and then interactively
8592 call CMD."
8593 (org-load-modules-maybe)
8594 (unless org-local-vars
8595 (setq org-local-vars (org-get-local-variables)))
8596 (eval (list 'let org-local-vars
8597 (list 'call-interactively (list 'quote cmd)))))
8599 ;;;; Archiving
8601 (defun org-get-category (&optional pos force-refresh)
8602 "Get the category applying to position POS."
8603 (save-match-data
8604 (if force-refresh (org-refresh-category-properties))
8605 (let ((pos (or pos (point))))
8606 (or (get-text-property pos 'org-category)
8607 (progn (org-refresh-category-properties)
8608 (get-text-property pos 'org-category))))))
8610 (defun org-refresh-category-properties ()
8611 "Refresh category text properties in the buffer."
8612 (let ((inhibit-read-only t)
8613 (def-cat (cond
8614 ((null org-category)
8615 (if buffer-file-name
8616 (file-name-sans-extension
8617 (file-name-nondirectory buffer-file-name))
8618 "???"))
8619 ((symbolp org-category) (symbol-name org-category))
8620 (t org-category)))
8621 beg end cat pos optionp)
8622 (org-unmodified
8623 (save-excursion
8624 (save-restriction
8625 (widen)
8626 (goto-char (point-min))
8627 (put-text-property (point) (point-max) 'org-category def-cat)
8628 (while (re-search-forward
8629 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8630 (setq pos (match-end 0)
8631 optionp (equal (char-after (match-beginning 0)) ?#)
8632 cat (org-trim (match-string 2)))
8633 (if optionp
8634 (setq beg (point-at-bol) end (point-max))
8635 (org-back-to-heading t)
8636 (setq beg (point) end (org-end-of-subtree t t)))
8637 (put-text-property beg end 'org-category cat)
8638 (put-text-property beg end 'org-category-position beg)
8639 (goto-char pos)))))))
8642 ;;;; Link Stuff
8644 ;;; Link abbreviations
8646 (defun org-link-expand-abbrev (link)
8647 "Apply replacements as defined in `org-link-abbrev-alist'."
8648 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8649 (let* ((key (match-string 1 link))
8650 (as (or (assoc key org-link-abbrev-alist-local)
8651 (assoc key org-link-abbrev-alist)))
8652 (tag (and (match-end 2) (match-string 3 link)))
8653 rpl)
8654 (if (not as)
8655 link
8656 (setq rpl (cdr as))
8657 (cond
8658 ((symbolp rpl) (funcall rpl tag))
8659 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8660 ((string-match "%h" rpl)
8661 (replace-match (url-hexify-string (or tag "")) t t rpl))
8662 (t (concat rpl tag)))))
8663 link))
8665 ;;; Storing and inserting links
8667 (defvar org-insert-link-history nil
8668 "Minibuffer history for links inserted with `org-insert-link'.")
8670 (defvar org-stored-links nil
8671 "Contains the links stored with `org-store-link'.")
8673 (defvar org-store-link-plist nil
8674 "Plist with info about the most recently link created with `org-store-link'.")
8676 (defvar org-link-protocols nil
8677 "Link protocols added to Org-mode using `org-add-link-type'.")
8679 (defvar org-store-link-functions nil
8680 "List of functions that are called to create and store a link.
8681 Each function will be called in turn until one returns a non-nil
8682 value. Each function should check if it is responsible for creating
8683 this link (for example by looking at the major mode).
8684 If not, it must exit and return nil.
8685 If yes, it should return a non-nil value after a calling
8686 `org-store-link-props' with a list of properties and values.
8687 Special properties are:
8689 :type The link prefix, like \"http\". This must be given.
8690 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8691 This is obligatory as well.
8692 :description Optional default description for the second pair
8693 of brackets in an Org-mode link. The user can still change
8694 this when inserting this link into an Org-mode buffer.
8696 In addition to these, any additional properties can be specified
8697 and then used in remember templates.")
8699 (defun org-add-link-type (type &optional follow export)
8700 "Add TYPE to the list of `org-link-types'.
8701 Re-compute all regular expressions depending on `org-link-types'
8703 FOLLOW and EXPORT are two functions.
8705 FOLLOW should take the link path as the single argument and do whatever
8706 is necessary to follow the link, for example find a file or display
8707 a mail message.
8709 EXPORT should format the link path for export to one of the export formats.
8710 It should be a function accepting three arguments:
8712 path the path of the link, the text after the prefix (like \"http:\")
8713 desc the description of the link, if any, or a description added by
8714 org-export-normalize-links if there is none
8715 format the export format, a symbol like `html' or `latex' or `ascii'..
8717 The function may use the FORMAT information to return different values
8718 depending on the format. The return value will be put literally into
8719 the exported file. If the return value is nil, this means Org should
8720 do what it normally does with links which do not have EXPORT defined.
8722 Org-mode has a built-in default for exporting links. If you are happy with
8723 this default, there is no need to define an export function for the link
8724 type. For a simple example of an export function, see `org-bbdb.el'."
8725 (add-to-list 'org-link-types type t)
8726 (org-make-link-regexps)
8727 (if (assoc type org-link-protocols)
8728 (setcdr (assoc type org-link-protocols) (list follow export))
8729 (push (list type follow export) org-link-protocols)))
8731 (defvar org-agenda-buffer-name)
8733 ;;;###autoload
8734 (defun org-store-link (arg)
8735 "\\<org-mode-map>Store an org-link to the current location.
8736 This link is added to `org-stored-links' and can later be inserted
8737 into an org-buffer with \\[org-insert-link].
8739 For some link types, a prefix arg is interpreted:
8740 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8741 For file links, arg negates `org-context-in-file-links'."
8742 (interactive "P")
8743 (org-load-modules-maybe)
8744 (setq org-store-link-plist nil) ; reset
8745 (org-with-limited-levels
8746 (let (link cpltxt desc description search txt custom-id agenda-link)
8747 (cond
8749 ((run-hook-with-args-until-success 'org-store-link-functions)
8750 (setq link (plist-get org-store-link-plist :link)
8751 desc (or (plist-get org-store-link-plist :description) link)))
8753 ((org-src-edit-buffer-p)
8754 (let (label gc)
8755 (while (or (not label)
8756 (save-excursion
8757 (save-restriction
8758 (widen)
8759 (goto-char (point-min))
8760 (re-search-forward
8761 (regexp-quote (format org-coderef-label-format label))
8762 nil t))))
8763 (when label (message "Label exists already") (sit-for 2))
8764 (setq label (read-string "Code line label: " label)))
8765 (end-of-line 1)
8766 (setq link (format org-coderef-label-format label))
8767 (setq gc (- 79 (length link)))
8768 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8769 (insert link)
8770 (setq link (concat "(" label ")") desc nil)))
8772 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8773 ;; We are in the agenda, link to referenced location
8774 (let ((m (or (get-text-property (point) 'org-hd-marker)
8775 (get-text-property (point) 'org-marker))))
8776 (when m
8777 (org-with-point-at m
8778 (setq agenda-link
8779 (if (org-called-interactively-p 'any)
8780 (call-interactively 'org-store-link)
8781 (org-store-link nil)))))))
8783 ((eq major-mode 'calendar-mode)
8784 (let ((cd (calendar-cursor-to-date)))
8785 (setq link
8786 (format-time-string
8787 (car org-time-stamp-formats)
8788 (apply 'encode-time
8789 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8790 nil nil nil))))
8791 (org-store-link-props :type "calendar" :date cd)))
8793 ((eq major-mode 'w3-mode)
8794 (setq cpltxt (if (and (buffer-name)
8795 (not (string-match "Untitled" (buffer-name))))
8796 (buffer-name)
8797 (url-view-url t))
8798 link (org-make-link (url-view-url t)))
8799 (org-store-link-props :type "w3" :url (url-view-url t)))
8801 ((eq major-mode 'w3m-mode)
8802 (setq cpltxt (or w3m-current-title w3m-current-url)
8803 link (org-make-link w3m-current-url))
8804 (org-store-link-props :type "w3m" :url (url-view-url t)))
8806 ((setq search (run-hook-with-args-until-success
8807 'org-create-file-search-functions))
8808 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8809 "::" search))
8810 (setq cpltxt (or description link)))
8812 ((eq major-mode 'image-mode)
8813 (setq cpltxt (concat "file:"
8814 (abbreviate-file-name buffer-file-name))
8815 link (org-make-link cpltxt))
8816 (org-store-link-props :type "image" :file buffer-file-name))
8818 ((eq major-mode 'dired-mode)
8819 ;; link to the file in the current line
8820 (let ((file (dired-get-filename nil t)))
8821 (setq file (if file
8822 (abbreviate-file-name
8823 (expand-file-name (dired-get-filename nil t)))
8824 ;; otherwise, no file so use current directory.
8825 default-directory))
8826 (setq cpltxt (concat "file:" file)
8827 link (org-make-link cpltxt))))
8829 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8830 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8831 (cond
8832 ((org-in-regexp "<<\\(.*?\\)>>")
8833 (setq cpltxt
8834 (concat "file:"
8835 (abbreviate-file-name
8836 (buffer-file-name (buffer-base-buffer)))
8837 "::" (match-string 1))
8838 link (org-make-link cpltxt)))
8839 ((and (featurep 'org-id)
8840 (or (eq org-link-to-org-use-id t)
8841 (and (eq org-link-to-org-use-id 'create-if-interactive)
8842 (org-called-interactively-p 'any))
8843 (and (eq org-link-to-org-use-id
8844 'create-if-interactive-and-no-custom-id)
8845 (org-called-interactively-p 'any)
8846 (not custom-id))
8847 (and org-link-to-org-use-id
8848 (org-entry-get nil "ID"))))
8849 ;; We can make a link using the ID.
8850 (setq link (condition-case nil
8851 (prog1 (org-id-store-link)
8852 (setq desc (plist-get org-store-link-plist
8853 :description)))
8854 (error
8855 ;; probably before first headline, link to file only
8856 (concat "file:"
8857 (abbreviate-file-name
8858 (buffer-file-name (buffer-base-buffer))))))))
8860 ;; Just link to current headline
8861 (setq cpltxt (concat "file:"
8862 (abbreviate-file-name
8863 (buffer-file-name (buffer-base-buffer)))))
8864 ;; Add a context search string
8865 (when (org-xor org-context-in-file-links arg)
8866 (setq txt (cond
8867 ((org-at-heading-p) nil)
8868 ((org-region-active-p)
8869 (buffer-substring (region-beginning) (region-end)))
8870 (t nil)))
8871 (when (or (null txt) (string-match "\\S-" txt))
8872 (setq cpltxt
8873 (concat cpltxt "::"
8874 (condition-case nil
8875 (org-make-org-heading-search-string txt)
8876 (error "")))
8877 desc (or (nth 4 (ignore-errors
8878 (org-heading-components))) "NONE"))))
8879 (if (string-match "::\\'" cpltxt)
8880 (setq cpltxt (substring cpltxt 0 -2)))
8881 (setq link (org-make-link cpltxt)))))
8883 ((buffer-file-name (buffer-base-buffer))
8884 ;; Just link to this file here.
8885 (setq cpltxt (concat "file:"
8886 (abbreviate-file-name
8887 (buffer-file-name (buffer-base-buffer)))))
8888 ;; Add a context string
8889 (when (org-xor org-context-in-file-links arg)
8890 (setq txt (if (org-region-active-p)
8891 (buffer-substring (region-beginning) (region-end))
8892 (buffer-substring (point-at-bol) (point-at-eol))))
8893 ;; Only use search option if there is some text.
8894 (when (string-match "\\S-" txt)
8895 (setq cpltxt
8896 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8897 desc "NONE")))
8898 (setq link (org-make-link cpltxt)))
8900 ((org-called-interactively-p 'interactive)
8901 (error "Cannot link to a buffer which is not visiting a file"))
8903 (t (setq link nil)))
8905 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8906 (setq link (or link cpltxt)
8907 desc (or desc cpltxt))
8908 (if (equal desc "NONE") (setq desc nil))
8910 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8911 (progn
8912 (setq org-stored-links
8913 (cons (list link desc) org-stored-links))
8914 (message "Stored: %s" (or desc link))
8915 (when custom-id
8916 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8917 "::#" custom-id))
8918 (setq org-stored-links
8919 (cons (list link desc) org-stored-links))))
8920 (or agenda-link (and link (org-make-link-string link desc)))))))
8922 (defun org-store-link-props (&rest plist)
8923 "Store link properties, extract names and addresses."
8924 (let (x adr)
8925 (when (setq x (plist-get plist :from))
8926 (setq adr (mail-extract-address-components x))
8927 (setq plist (plist-put plist :fromname (car adr)))
8928 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8929 (when (setq x (plist-get plist :to))
8930 (setq adr (mail-extract-address-components x))
8931 (setq plist (plist-put plist :toname (car adr)))
8932 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8933 (let ((from (plist-get plist :from))
8934 (to (plist-get plist :to)))
8935 (when (and from to org-from-is-user-regexp)
8936 (setq plist
8937 (plist-put plist :fromto
8938 (if (string-match org-from-is-user-regexp from)
8939 (concat "to %t")
8940 (concat "from %f"))))))
8941 (setq org-store-link-plist plist))
8943 (defun org-add-link-props (&rest plist)
8944 "Add these properties to the link property list."
8945 (let (key value)
8946 (while plist
8947 (setq key (pop plist) value (pop plist))
8948 (setq org-store-link-plist
8949 (plist-put org-store-link-plist key value)))))
8951 (defun org-email-link-description (&optional fmt)
8952 "Return the description part of an email link.
8953 This takes information from `org-store-link-plist' and formats it
8954 according to FMT (default from `org-email-link-description-format')."
8955 (setq fmt (or fmt org-email-link-description-format))
8956 (let* ((p org-store-link-plist)
8957 (to (plist-get p :toaddress))
8958 (from (plist-get p :fromaddress))
8959 (table
8960 (list
8961 (cons "%c" (plist-get p :fromto))
8962 (cons "%F" (plist-get p :from))
8963 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8964 (cons "%T" (plist-get p :to))
8965 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8966 (cons "%s" (plist-get p :subject))
8967 (cons "%d" (plist-get p :date))
8968 (cons "%m" (plist-get p :message-id)))))
8969 (when (string-match "%c" fmt)
8970 ;; Check if the user wrote this message
8971 (if (and org-from-is-user-regexp from to
8972 (save-match-data (string-match org-from-is-user-regexp from)))
8973 (setq fmt (replace-match "to %t" t t fmt))
8974 (setq fmt (replace-match "from %f" t t fmt))))
8975 (org-replace-escapes fmt table)))
8977 (defun org-make-org-heading-search-string (&optional string heading)
8978 "Make search string for STRING or current headline."
8979 (interactive)
8980 (let ((s (or string (org-get-heading)))
8981 (lines org-context-in-file-links))
8982 (unless (and string (not heading))
8983 ;; We are using a headline, clean up garbage in there.
8984 (if (string-match org-todo-regexp s)
8985 (setq s (replace-match "" t t s)))
8986 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8987 (setq s (replace-match "" t t s)))
8988 (setq s (org-trim s))
8989 (if (string-match (concat "^\\(" org-quote-string "\\|"
8990 org-comment-string "\\)") s)
8991 (setq s (replace-match "" t t s)))
8992 (while (string-match org-ts-regexp s)
8993 (setq s (replace-match "" t t s))))
8994 (or string (setq s (concat "*" s))) ; Add * for headlines
8995 (when (and string (integerp lines) (> lines 0))
8996 (let ((slines (org-split-string s "\n")))
8997 (when (< lines (length slines))
8998 (setq s (mapconcat
8999 'identity
9000 (reverse (nthcdr (- (length slines) lines)
9001 (reverse slines))) "\n")))))
9002 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9004 (defun org-make-link (&rest strings)
9005 "Concatenate STRINGS."
9006 (apply 'concat strings))
9008 (defun org-make-link-string (link &optional description)
9009 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9010 (unless (string-match "\\S-" link)
9011 (error "Empty link"))
9012 (when (and description
9013 (stringp description)
9014 (not (string-match "\\S-" description)))
9015 (setq description nil))
9016 (when (stringp description)
9017 ;; Remove brackets from the description, they are fatal.
9018 (while (string-match "\\[" description)
9019 (setq description (replace-match "{" t t description)))
9020 (while (string-match "\\]" description)
9021 (setq description (replace-match "}" t t description))))
9022 (when (equal link description)
9023 ;; No description needed, it is identical
9024 (setq description nil))
9025 (when (and (not description)
9026 (not (string-match (org-image-file-name-regexp) link))
9027 (not (equal link (org-link-escape link))))
9028 (setq description (org-extract-attributes link)))
9029 (setq link
9030 (cond ((string-match (org-image-file-name-regexp) link) link)
9031 ((string-match org-link-types-re link)
9032 (concat (match-string 1 link)
9033 (org-link-escape (substring link (match-end 1)))))
9034 (t (org-link-escape link))))
9035 (concat "[[" link "]"
9036 (if description (concat "[" description "]") "")
9037 "]"))
9039 (defconst org-link-escape-chars
9040 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9041 "List of characters that should be escaped in link.
9042 This is the list that is used for internal purposes.")
9044 (defvar org-url-encoding-use-url-hexify nil)
9046 (defconst org-link-escape-chars-browser
9047 '(?\ )
9048 "List of escapes for characters that are problematic in links.
9049 This is the list that is used before handing over to the browser.")
9051 (defun org-link-escape (text &optional table merge)
9052 "Return percent escaped representation of TEXT.
9053 TEXT is a string with the text to escape.
9054 Optional argument TABLE is a list with characters that should be
9055 escaped. When nil, `org-link-escape-chars' is used.
9056 If optional argument MERGE is set, merge TABLE into
9057 `org-link-escape-chars'."
9058 (if (and org-url-encoding-use-url-hexify (not table))
9059 (url-hexify-string text)
9060 (cond
9061 ((and table merge)
9062 (mapc (lambda (defchr)
9063 (unless (member defchr table)
9064 (setq table (cons defchr table)))) org-link-escape-chars))
9065 ((null table)
9066 (setq table org-link-escape-chars)))
9067 (mapconcat
9068 (lambda (char)
9069 (if (or (member char table)
9070 (< char 32) (= char 37) (> char 126))
9071 (mapconcat (lambda (sequence-element)
9072 (format "%%%.2X" sequence-element))
9073 (or (encode-coding-char char 'utf-8)
9074 (error "Unable to percent escape character: %s"
9075 (char-to-string char))) "")
9076 (char-to-string char))) text "")))
9078 (defun org-link-unescape (str)
9079 "Unhex hexified Unicode strings as returned from the JavaScript function
9080 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9081 (unless (and (null str) (string= "" str))
9082 (let ((pos 0) (case-fold-search t) unhexed)
9083 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9084 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9085 (setq str (replace-match unhexed t t str))
9086 (setq pos (+ pos (length unhexed))))))
9087 str)
9089 (defun org-link-unescape-compound (hex)
9090 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9091 Note: this function also decodes single byte encodings like
9092 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9093 (save-match-data
9094 (let* ((bytes (cdr (split-string hex "%")))
9095 (ret "")
9096 (eat 0)
9097 (sum 0))
9098 (while bytes
9099 (let* ((val (string-to-number (pop bytes) 16))
9100 (shift-xor
9101 (if (= 0 eat)
9102 (cond
9103 ((>= val 252) (cons 6 252))
9104 ((>= val 248) (cons 5 248))
9105 ((>= val 240) (cons 4 240))
9106 ((>= val 224) (cons 3 224))
9107 ((>= val 192) (cons 2 192))
9108 (t (cons 0 0)))
9109 (cons 6 128))))
9110 (if (>= val 192) (setq eat (car shift-xor)))
9111 (setq val (logxor val (cdr shift-xor)))
9112 (setq sum (+ (lsh sum (car shift-xor)) val))
9113 (if (> eat 0) (setq eat (- eat 1)))
9114 (cond
9115 ((= 0 eat) ;multi byte
9116 (setq ret (concat ret (org-char-to-string sum)))
9117 (setq sum 0))
9118 ((not bytes) ; single byte(s)
9119 (setq ret (org-link-unescape-single-byte-sequence hex))))
9120 )) ;; end (while bytes
9121 ret )))
9123 (defun org-link-unescape-single-byte-sequence (hex)
9124 "Unhexify hex-encoded single byte character sequences."
9125 (mapconcat (lambda (byte)
9126 (char-to-string (string-to-number byte 16)))
9127 (cdr (split-string hex "%")) ""))
9129 (defun org-xor (a b)
9130 "Exclusive or."
9131 (if a (not b) b))
9133 (defun org-fixup-message-id-for-http (s)
9134 "Replace special characters in a message id, so it can be used in an http query."
9135 (when (string-match "%" s)
9136 (setq s (mapconcat (lambda (c)
9137 (if (eq c ?%)
9138 "%25"
9139 (char-to-string c)))
9140 s "")))
9141 (while (string-match "<" s)
9142 (setq s (replace-match "%3C" t t s)))
9143 (while (string-match ">" s)
9144 (setq s (replace-match "%3E" t t s)))
9145 (while (string-match "@" s)
9146 (setq s (replace-match "%40" t t s)))
9149 (defun org-link-prettify (link)
9150 "Return a human-readable representation of LINK.
9151 The car of LINK must be a raw link the cdr of LINK must be either
9152 a link description or nil."
9153 (let ((desc (or (cadr link) "<no description>")))
9154 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9155 "[[" (car link) "]]")))
9157 ;;;###autoload
9158 (defun org-insert-link-global ()
9159 "Insert a link like Org-mode does.
9160 This command can be called in any mode to insert a link in Org-mode syntax."
9161 (interactive)
9162 (org-load-modules-maybe)
9163 (org-run-like-in-org-mode 'org-insert-link))
9165 (defun org-insert-link (&optional complete-file link-location default-description)
9166 "Insert a link. At the prompt, enter the link.
9168 Completion can be used to insert any of the link protocol prefixes like
9169 http or ftp in use.
9171 The history can be used to select a link previously stored with
9172 `org-store-link'. When the empty string is entered (i.e. if you just
9173 press RET at the prompt), the link defaults to the most recently
9174 stored link. As SPC triggers completion in the minibuffer, you need to
9175 use M-SPC or C-q SPC to force the insertion of a space character.
9177 You will also be prompted for a description, and if one is given, it will
9178 be displayed in the buffer instead of the link.
9180 If there is already a link at point, this command will allow you to edit link
9181 and description parts.
9183 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9184 be selected using completion. The path to the file will be relative to the
9185 current directory if the file is in the current directory or a subdirectory.
9186 Otherwise, the link will be the absolute path as completed in the minibuffer
9187 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9188 option `org-link-file-path-type'.
9190 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9191 the current directory or below.
9193 With three \\[universal-argument] prefixes, negate the meaning of
9194 `org-keep-stored-link-after-insertion'.
9196 If `org-make-link-description-function' is non-nil, this function will be
9197 called with the link target, and the result will be the default
9198 link description.
9200 If the LINK-LOCATION parameter is non-nil, this value will be
9201 used as the link location instead of reading one interactively.
9203 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9204 be used as the default description."
9205 (interactive "P")
9206 (let* ((wcf (current-window-configuration))
9207 (region (if (org-region-active-p)
9208 (buffer-substring (region-beginning) (region-end))))
9209 (remove (and region (list (region-beginning) (region-end))))
9210 (desc region)
9211 tmphist ; byte-compile incorrectly complains about this
9212 (link link-location)
9213 entry file all-prefixes)
9214 (cond
9215 (link-location) ; specified by arg, just use it.
9216 ((org-in-regexp org-bracket-link-regexp 1)
9217 ;; We do have a link at point, and we are going to edit it.
9218 (setq remove (list (match-beginning 0) (match-end 0)))
9219 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9220 (setq link (read-string "Link: "
9221 (org-link-unescape
9222 (org-match-string-no-properties 1)))))
9223 ((or (org-in-regexp org-angle-link-re)
9224 (org-in-regexp org-plain-link-re))
9225 ;; Convert to bracket link
9226 (setq remove (list (match-beginning 0) (match-end 0))
9227 link (read-string "Link: "
9228 (org-remove-angle-brackets (match-string 0)))))
9229 ((member complete-file '((4) (16)))
9230 ;; Completing read for file names.
9231 (setq link (org-file-complete-link complete-file)))
9233 ;; Read link, with completion for stored links.
9234 (with-output-to-temp-buffer "*Org Links*"
9235 (princ "Insert a link.
9236 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9237 (when org-stored-links
9238 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9239 (princ (mapconcat 'org-link-prettify
9240 (reverse org-stored-links) "\n"))))
9241 (let ((cw (selected-window)))
9242 (select-window (get-buffer-window "*Org Links*" 'visible))
9243 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9244 (unless (pos-visible-in-window-p (point-max))
9245 (org-fit-window-to-buffer))
9246 (and (window-live-p cw) (select-window cw)))
9247 ;; Fake a link history, containing the stored links.
9248 (setq tmphist (append (mapcar 'car org-stored-links)
9249 org-insert-link-history))
9250 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9251 (mapcar 'car org-link-abbrev-alist)
9252 org-link-types))
9253 (unwind-protect
9254 (progn
9255 (setq link
9256 (let ((org-completion-use-ido nil)
9257 (org-completion-use-iswitchb nil))
9258 (org-completing-read
9259 "Link: "
9260 (append
9261 (mapcar (lambda (x) (list (concat x ":")))
9262 all-prefixes)
9263 (mapcar 'car org-stored-links))
9264 nil nil nil
9265 'tmphist
9266 (car (car org-stored-links)))))
9267 (if (not (string-match "\\S-" link))
9268 (error "No link selected"))
9269 (if (or (member link all-prefixes)
9270 (and (equal ":" (substring link -1))
9271 (member (substring link 0 -1) all-prefixes)
9272 (setq link (substring link 0 -1))))
9273 (setq link (org-link-try-special-completion link))))
9274 (set-window-configuration wcf)
9275 (kill-buffer "*Org Links*"))
9276 (setq entry (assoc link org-stored-links))
9277 (or entry (push link org-insert-link-history))
9278 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9279 (not org-keep-stored-link-after-insertion))
9280 (setq org-stored-links (delq (assoc link org-stored-links)
9281 org-stored-links)))
9282 (setq desc (or desc (nth 1 entry)))))
9284 (if (string-match org-plain-link-re link)
9285 ;; URL-like link, normalize the use of angular brackets.
9286 (setq link (org-make-link (org-remove-angle-brackets link))))
9288 ;; Check if we are linking to the current file with a search option
9289 ;; If yes, simplify the link by using only the search option.
9290 (when (and buffer-file-name
9291 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9292 (let* ((path (match-string 1 link))
9293 (case-fold-search nil)
9294 (search (match-string 2 link)))
9295 (save-match-data
9296 (if (equal (file-truename buffer-file-name) (file-truename path))
9297 ;; We are linking to this same file, with a search option
9298 (setq link search)))))
9300 ;; Check if we can/should use a relative path. If yes, simplify the link
9301 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9302 (let* ((type (match-string 1 link))
9303 (path (match-string 2 link))
9304 (origpath path)
9305 (case-fold-search nil))
9306 (cond
9307 ((or (eq org-link-file-path-type 'absolute)
9308 (equal complete-file '(16)))
9309 (setq path (abbreviate-file-name (expand-file-name path))))
9310 ((eq org-link-file-path-type 'noabbrev)
9311 (setq path (expand-file-name path)))
9312 ((eq org-link-file-path-type 'relative)
9313 (setq path (file-relative-name path)))
9315 (save-match-data
9316 (if (string-match (concat "^" (regexp-quote
9317 (expand-file-name
9318 (file-name-as-directory
9319 default-directory))))
9320 (expand-file-name path))
9321 ;; We are linking a file with relative path name.
9322 (setq path (substring (expand-file-name path)
9323 (match-end 0)))
9324 (setq path (abbreviate-file-name (expand-file-name path)))))))
9325 (setq link (concat type path))
9326 (if (equal desc origpath)
9327 (setq desc path))))
9329 (if org-make-link-description-function
9330 (setq desc (funcall org-make-link-description-function link desc))
9331 (if default-description (setq desc default-description)))
9333 (setq desc (read-string "Description: " desc))
9334 (unless (string-match "\\S-" desc) (setq desc nil))
9335 (if remove (apply 'delete-region remove))
9336 (insert (org-make-link-string link desc))))
9338 (defun org-link-try-special-completion (type)
9339 "If there is completion support for link type TYPE, offer it."
9340 (let ((fun (intern (concat "org-" type "-complete-link"))))
9341 (if (functionp fun)
9342 (funcall fun)
9343 (read-string "Link (no completion support): " (concat type ":")))))
9345 (defun org-file-complete-link (&optional arg)
9346 "Create a file link using completion."
9347 (let (file link)
9348 (setq file (read-file-name "File: "))
9349 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9350 (pwd1 (file-name-as-directory (abbreviate-file-name
9351 (expand-file-name ".")))))
9352 (cond
9353 ((equal arg '(16))
9354 (setq link (org-make-link
9355 "file:"
9356 (abbreviate-file-name (expand-file-name file)))))
9357 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9358 (setq link (org-make-link "file:" (match-string 1 file))))
9359 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9360 (expand-file-name file))
9361 (setq link (org-make-link
9362 "file:" (match-string 1 (expand-file-name file)))))
9363 (t (setq link (org-make-link "file:" file)))))
9364 link))
9366 (defun org-completing-read (&rest args)
9367 "Completing-read with SPACE being a normal character."
9368 (let ((enable-recursive-minibuffers t)
9369 (minibuffer-local-completion-map
9370 (copy-keymap minibuffer-local-completion-map)))
9371 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9372 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9373 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9374 (apply 'org-icompleting-read args)))
9376 (defun org-completing-read-no-i (&rest args)
9377 (let (org-completion-use-ido org-completion-use-iswitchb)
9378 (apply 'org-completing-read args)))
9380 (defun org-iswitchb-completing-read (prompt choices &rest args)
9381 "Use iswitch as a completing-read replacement to choose from choices.
9382 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9383 from."
9384 (let* ((iswitchb-use-virtual-buffers nil)
9385 (iswitchb-make-buflist-hook
9386 (lambda ()
9387 (setq iswitchb-temp-buflist choices))))
9388 (iswitchb-read-buffer prompt)))
9390 (defun org-icompleting-read (&rest args)
9391 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9392 (org-without-partial-completion
9393 (if (and org-completion-use-ido
9394 (fboundp 'ido-completing-read)
9395 (boundp 'ido-mode) ido-mode
9396 (listp (second args)))
9397 (let ((ido-enter-matching-directory nil))
9398 (apply 'ido-completing-read (concat (car args))
9399 (if (consp (car (nth 1 args)))
9400 (mapcar 'car (nth 1 args))
9401 (nth 1 args))
9402 (cddr args)))
9403 (if (and org-completion-use-iswitchb
9404 (boundp 'iswitchb-mode) iswitchb-mode
9405 (listp (second args)))
9406 (apply 'org-iswitchb-completing-read (concat (car args))
9407 (if (consp (car (nth 1 args)))
9408 (mapcar 'car (nth 1 args))
9409 (nth 1 args))
9410 (cddr args))
9411 (apply 'completing-read args)))))
9413 (defun org-extract-attributes (s)
9414 "Extract the attributes cookie from a string and set as text property."
9415 (let (a attr (start 0) key value)
9416 (save-match-data
9417 (when (string-match "{{\\([^}]+\\)}}$" s)
9418 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9419 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9420 (setq key (match-string 1 a) value (match-string 2 a)
9421 start (match-end 0)
9422 attr (plist-put attr (intern key) value))))
9423 (org-add-props s nil 'org-attr attr))
9426 (defun org-extract-attributes-from-string (tag)
9427 (let (key value attr)
9428 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9429 (setq key (match-string 1 tag) value (match-string 2 tag)
9430 tag (replace-match "" t t tag)
9431 attr (plist-put attr (intern key) value)))
9432 (cons tag attr)))
9434 (defun org-attributes-to-string (plist)
9435 "Format a property list into an HTML attribute list."
9436 (let ((s "") key value)
9437 (while plist
9438 (setq key (pop plist) value (pop plist))
9439 (and value
9440 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9443 ;;; Opening/following a link
9445 (defvar org-link-search-failed nil)
9447 (defvar org-open-link-functions nil
9448 "Hook for functions finding a plain text link.
9449 These functions must take a single argument, the link content.
9450 They will be called for links that look like [[link text][description]]
9451 when LINK TEXT does not have a protocol like \"http:\" and does not look
9452 like a filename (e.g. \"./blue.png\").
9454 These functions will be called *before* Org attempts to resolve the
9455 link by doing text searches in the current buffer - so if you want a
9456 link \"[[target]]\" to still find \"<<target>>\", your function should
9457 handle this as a special case.
9459 When the function does handle the link, it must return a non-nil value.
9460 If it decides that it is not responsible for this link, it must return
9461 nil to indicate that that Org-mode can continue with other options
9462 like exact and fuzzy text search.")
9464 (defun org-next-link ()
9465 "Move forward to the next link.
9466 If the link is in hidden text, expose it."
9467 (interactive)
9468 (when (and org-link-search-failed (eq this-command last-command))
9469 (goto-char (point-min))
9470 (message "Link search wrapped back to beginning of buffer"))
9471 (setq org-link-search-failed nil)
9472 (let* ((pos (point))
9473 (ct (org-context))
9474 (a (assoc :link ct)))
9475 (if a (goto-char (nth 2 a)))
9476 (if (re-search-forward org-any-link-re nil t)
9477 (progn
9478 (goto-char (match-beginning 0))
9479 (if (outline-invisible-p) (org-show-context)))
9480 (goto-char pos)
9481 (setq org-link-search-failed t)
9482 (error "No further link found"))))
9484 (defun org-previous-link ()
9485 "Move backward to the previous link.
9486 If the link is in hidden text, expose it."
9487 (interactive)
9488 (when (and org-link-search-failed (eq this-command last-command))
9489 (goto-char (point-max))
9490 (message "Link search wrapped back to end of buffer"))
9491 (setq org-link-search-failed nil)
9492 (let* ((pos (point))
9493 (ct (org-context))
9494 (a (assoc :link ct)))
9495 (if a (goto-char (nth 1 a)))
9496 (if (re-search-backward org-any-link-re nil t)
9497 (progn
9498 (goto-char (match-beginning 0))
9499 (if (outline-invisible-p) (org-show-context)))
9500 (goto-char pos)
9501 (setq org-link-search-failed t)
9502 (error "No further link found"))))
9504 (defun org-translate-link (s)
9505 "Translate a link string if a translation function has been defined."
9506 (if (and org-link-translation-function
9507 (fboundp org-link-translation-function)
9508 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9509 (progn
9510 (setq s (funcall org-link-translation-function
9511 (match-string 1 s) (match-string 2 s)))
9512 (concat (car s) ":" (cdr s)))
9515 (defun org-translate-link-from-planner (type path)
9516 "Translate a link from Emacs Planner syntax so that Org can follow it.
9517 This is still an experimental function, your mileage may vary."
9518 (cond
9519 ((member type '("http" "https" "news" "ftp"))
9520 ;; standard Internet links are the same.
9521 nil)
9522 ((and (equal type "irc") (string-match "^//" path))
9523 ;; Planner has two / at the beginning of an irc link, we have 1.
9524 ;; We should have zero, actually....
9525 (setq path (substring path 1)))
9526 ((and (equal type "lisp") (string-match "^/" path))
9527 ;; Planner has a slash, we do not.
9528 (setq type "elisp" path (substring path 1)))
9529 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9530 ;; A typical message link. Planner has the id after the final slash,
9531 ;; we separate it with a hash mark
9532 (setq path (concat (match-string 1 path) "#"
9533 (org-remove-angle-brackets (match-string 2 path)))))
9535 (cons type path))
9537 (defun org-find-file-at-mouse (ev)
9538 "Open file link or URL at mouse."
9539 (interactive "e")
9540 (mouse-set-point ev)
9541 (org-open-at-point 'in-emacs))
9543 (defun org-open-at-mouse (ev)
9544 "Open file link or URL at mouse.
9545 See the docstring of `org-open-file' for details."
9546 (interactive "e")
9547 (mouse-set-point ev)
9548 (if (eq major-mode 'org-agenda-mode)
9549 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9550 (org-open-at-point))
9552 (defvar org-window-config-before-follow-link nil
9553 "The window configuration before following a link.
9554 This is saved in case the need arises to restore it.")
9556 (defvar org-open-link-marker (make-marker)
9557 "Marker pointing to the location where `org-open-at-point; was called.")
9559 ;;;###autoload
9560 (defun org-open-at-point-global ()
9561 "Follow a link like Org-mode does.
9562 This command can be called in any mode to follow a link that has
9563 Org-mode syntax."
9564 (interactive)
9565 (org-run-like-in-org-mode 'org-open-at-point))
9567 ;;;###autoload
9568 (defun org-open-link-from-string (s &optional arg reference-buffer)
9569 "Open a link in the string S, as if it was in Org-mode."
9570 (interactive "sLink: \nP")
9571 (let ((reference-buffer (or reference-buffer (current-buffer))))
9572 (with-temp-buffer
9573 (let ((org-inhibit-startup (not reference-buffer)))
9574 (org-mode)
9575 (insert s)
9576 (goto-char (point-min))
9577 (when reference-buffer
9578 (setq org-link-abbrev-alist-local
9579 (with-current-buffer reference-buffer
9580 org-link-abbrev-alist-local)))
9581 (org-open-at-point arg reference-buffer)))))
9583 (defvar org-open-at-point-functions nil
9584 "Hook that is run when following a link at point.
9586 Functions in this hook must return t if they identify and follow
9587 a link at point. If they don't find anything interesting at point,
9588 they must return nil.")
9590 (defun org-open-at-point (&optional arg reference-buffer)
9591 "Open link at or after point.
9592 If there is no link at point, this function will search forward up to
9593 the end of the current line.
9594 Normally, files will be opened by an appropriate application. If the
9595 optional prefix argument ARG is non-nil, Emacs will visit the file.
9596 With a double prefix argument, try to open outside of Emacs, in the
9597 application the system uses for this file type."
9598 (interactive "P")
9599 ;; if in a code block, then open the block's results
9600 (unless (call-interactively #'org-babel-open-src-block-result)
9601 (org-load-modules-maybe)
9602 (move-marker org-open-link-marker (point))
9603 (setq org-window-config-before-follow-link (current-window-configuration))
9604 (org-remove-occur-highlights nil nil t)
9605 (cond
9606 ((and (org-at-heading-p)
9607 (not (org-in-regexp
9608 (concat org-plain-link-re "\\|"
9609 org-bracket-link-regexp "\\|"
9610 org-angle-link-re "\\|"
9611 "[ \t]:[^ \t\n]+:[ \t]*$")))
9612 (not (get-text-property (point) 'org-linked-text)))
9613 (or (org-offer-links-in-entry arg)
9614 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9615 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9616 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9617 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9618 (not (org-in-regexp org-bracket-link-regexp)))
9619 (org-footnote-action))
9621 (let (type path link line search (pos (point)))
9622 (catch 'match
9623 (save-excursion
9624 (skip-chars-forward "^]\n\r")
9625 (when (org-in-regexp org-bracket-link-regexp 1)
9626 (setq link (org-extract-attributes
9627 (org-link-unescape (org-match-string-no-properties 1))))
9628 (while (string-match " *\n *" link)
9629 (setq link (replace-match " " t t link)))
9630 (setq link (org-link-expand-abbrev link))
9631 (cond
9632 ((or (file-name-absolute-p link)
9633 (string-match "^\\.\\.?/" link))
9634 (setq type "file" path link))
9635 ((string-match org-link-re-with-space3 link)
9636 (setq type (match-string 1 link) path (match-string 2 link)))
9637 (t (setq type "thisfile" path link)))
9638 (throw 'match t)))
9640 (when (get-text-property (point) 'org-linked-text)
9641 (setq type "thisfile"
9642 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9643 (1+ (point)) (point))
9644 path (buffer-substring
9645 (or (previous-single-property-change pos 'org-linked-text)
9646 (point-min))
9647 (or (next-single-property-change pos 'org-linked-text)
9648 (point-max))))
9649 (throw 'match t))
9651 (save-excursion
9652 (when (or (org-in-regexp org-angle-link-re)
9653 (org-in-regexp org-plain-link-re))
9654 (setq type (match-string 1)
9655 path (org-link-unescape (match-string 2)))
9656 (throw 'match t)))
9657 (save-excursion
9658 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9659 (setq type "tags"
9660 path (match-string 1))
9661 (while (string-match ":" path)
9662 (setq path (replace-match "+" t t path)))
9663 (throw 'match t)))
9664 (when (org-in-regexp "<\\([^><\n]+\\)>")
9665 (setq type "tree-match"
9666 path (match-string 1))
9667 (throw 'match t)))
9668 (unless path
9669 (error "No link found"))
9671 ;; switch back to reference buffer
9672 ;; needed when if called in a temporary buffer through
9673 ;; org-open-link-from-string
9674 (with-current-buffer (or reference-buffer (current-buffer))
9676 ;; Remove any trailing spaces in path
9677 (if (string-match " +\\'" path)
9678 (setq path (replace-match "" t t path)))
9679 (if (and org-link-translation-function
9680 (fboundp org-link-translation-function))
9681 ;; Check if we need to translate the link
9682 (let ((tmp (funcall org-link-translation-function type path)))
9683 (setq type (car tmp) path (cdr tmp))))
9685 (cond
9687 ((assoc type org-link-protocols)
9688 (funcall (nth 1 (assoc type org-link-protocols)) path))
9690 ((equal type "mailto")
9691 (let ((cmd (car org-link-mailto-program))
9692 (args (cdr org-link-mailto-program)) args1
9693 (address path) (subject "") a)
9694 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9695 (setq address (match-string 1 path)
9696 subject (org-link-escape (match-string 2 path))))
9697 (while args
9698 (cond
9699 ((not (stringp (car args))) (push (pop args) args1))
9700 (t (setq a (pop args))
9701 (if (string-match "%a" a)
9702 (setq a (replace-match address t t a)))
9703 (if (string-match "%s" a)
9704 (setq a (replace-match subject t t a)))
9705 (push a args1))))
9706 (apply cmd (nreverse args1))))
9708 ((member type '("http" "https" "ftp" "news"))
9709 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9710 (org-link-escape
9711 path org-link-escape-chars-browser)
9712 path))))
9714 ((string= type "doi")
9715 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9716 (org-link-escape
9717 path org-link-escape-chars-browser)
9718 path))))
9720 ((member type '("message"))
9721 (browse-url (concat type ":" path)))
9723 ((string= type "tags")
9724 (org-tags-view arg path))
9726 ((string= type "tree-match")
9727 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9729 ((string= type "file")
9730 (if (string-match "::\\([0-9]+\\)\\'" path)
9731 (setq line (string-to-number (match-string 1 path))
9732 path (substring path 0 (match-beginning 0)))
9733 (if (string-match "::\\(.+\\)\\'" path)
9734 (setq search (match-string 1 path)
9735 path (substring path 0 (match-beginning 0)))))
9736 (if (string-match "[*?{]" (file-name-nondirectory path))
9737 (dired path)
9738 (org-open-file path arg line search)))
9740 ((string= type "shell")
9741 (let ((cmd path))
9742 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9743 (string-match org-confirm-shell-link-not-regexp cmd))
9744 (not org-confirm-shell-link-function)
9745 (funcall org-confirm-shell-link-function
9746 (format "Execute \"%s\" in shell? "
9747 (org-add-props cmd nil
9748 'face 'org-warning))))
9749 (progn
9750 (message "Executing %s" cmd)
9751 (shell-command cmd))
9752 (error "Abort"))))
9754 ((string= type "elisp")
9755 (let ((cmd path))
9756 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9757 (string-match org-confirm-elisp-link-not-regexp cmd))
9758 (not org-confirm-elisp-link-function)
9759 (funcall org-confirm-elisp-link-function
9760 (format "Execute \"%s\" as elisp? "
9761 (org-add-props cmd nil
9762 'face 'org-warning))))
9763 (message "%s => %s" cmd
9764 (if (equal (string-to-char cmd) ?\()
9765 (eval (read cmd))
9766 (call-interactively (read cmd))))
9767 (error "Abort"))))
9769 ((and (string= type "thisfile")
9770 (run-hook-with-args-until-success
9771 'org-open-link-functions path)))
9773 ((string= type "thisfile")
9774 (if arg
9775 (switch-to-buffer-other-window
9776 (org-get-buffer-for-internal-link (current-buffer)))
9777 (org-mark-ring-push))
9778 (let ((cmd `(org-link-search
9779 ,path
9780 ,(cond ((equal arg '(4)) ''occur)
9781 ((equal arg '(16)) ''org-occur)
9782 (t nil))
9783 ,pos)))
9784 (condition-case nil (let ((org-link-search-inhibit-query t))
9785 (eval cmd))
9786 (error (progn (widen) (eval cmd))))))
9789 (browse-url-at-point)))))))
9790 (move-marker org-open-link-marker nil)
9791 (run-hook-with-args 'org-follow-link-hook)))
9793 (defun org-offer-links-in-entry (&optional nth zero)
9794 "Offer links in the current entry and follow the selected link.
9795 If there is only one link, follow it immediately as well.
9796 If NTH is an integer, immediately pick the NTH link found.
9797 If ZERO is a string, check also this string for a link, and if
9798 there is one, offer it as link number zero."
9799 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9800 "\\(" org-angle-link-re "\\)\\|"
9801 "\\(" org-plain-link-re "\\)"))
9802 (cnt ?0)
9803 (in-emacs (if (integerp nth) nil nth))
9804 have-zero end links link c)
9805 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9806 (push (match-string 0 zero) links)
9807 (setq cnt (1- cnt) have-zero t))
9808 (save-excursion
9809 (org-back-to-heading t)
9810 (setq end (save-excursion (outline-next-heading) (point)))
9811 (while (re-search-forward re end t)
9812 (push (match-string 0) links))
9813 (setq links (org-uniquify (reverse links))))
9815 (cond
9816 ((null links)
9817 (message "No links"))
9818 ((equal (length links) 1)
9819 (setq link (list (car links))))
9820 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9821 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9822 (t ; we have to select a link
9823 (save-excursion
9824 (save-window-excursion
9825 (delete-other-windows)
9826 (with-output-to-temp-buffer "*Select Link*"
9827 (mapc (lambda (l)
9828 (if (not (string-match org-bracket-link-regexp l))
9829 (princ (format "[%c] %s\n" (incf cnt)
9830 (org-remove-angle-brackets l)))
9831 (if (match-end 3)
9832 (princ (format "[%c] %s (%s)\n" (incf cnt)
9833 (match-string 3 l) (match-string 1 l)))
9834 (princ (format "[%c] %s\n" (incf cnt)
9835 (match-string 1 l))))))
9836 links))
9837 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9838 (message "Select link to open, RET to open all:")
9839 (setq c (read-char-exclusive))
9840 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9841 (when (equal c ?q) (error "Abort"))
9842 (if (equal c ?\C-m)
9843 (setq link links)
9844 (setq nth (- c ?0))
9845 (if have-zero (setq nth (1+ nth)))
9846 (unless (and (integerp nth) (>= (length links) nth))
9847 (error "Invalid link selection"))
9848 (setq link (list (nth (1- nth) links))))))
9849 (if link
9850 (let ((buf (current-buffer)))
9851 (dolist (l link)
9852 (org-open-link-from-string l in-emacs buf))
9854 nil)))
9856 ;; Add special file links that specify the way of opening
9858 (org-add-link-type "file+sys" 'org-open-file-with-system)
9859 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9860 (defun org-open-file-with-system (path)
9861 "Open file at PATH using the system way of opening it."
9862 (org-open-file path 'system))
9863 (defun org-open-file-with-emacs (path)
9864 "Open file at PATH in Emacs."
9865 (org-open-file path 'emacs))
9866 (defun org-remove-file-link-modifiers ()
9867 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9868 (goto-char (point-min))
9869 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9870 (org-if-unprotected
9871 (replace-match "file:" t t))))
9872 (eval-after-load "org-exp"
9873 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9874 'org-remove-file-link-modifiers))
9876 ;;;; Time estimates
9878 (defun org-get-effort (&optional pom)
9879 "Get the effort estimate for the current entry."
9880 (org-entry-get pom org-effort-property))
9882 ;;; File search
9884 (defvar org-create-file-search-functions nil
9885 "List of functions to construct the right search string for a file link.
9886 These functions are called in turn with point at the location to
9887 which the link should point.
9889 A function in the hook should first test if it would like to
9890 handle this file type, for example by checking the `major-mode'
9891 or the file extension. If it decides not to handle this file, it
9892 should just return nil to give other functions a chance. If it
9893 does handle the file, it must return the search string to be used
9894 when following the link. The search string will be part of the
9895 file link, given after a double colon, and `org-open-at-point'
9896 will automatically search for it. If special measures must be
9897 taken to make the search successful, another function should be
9898 added to the companion hook `org-execute-file-search-functions',
9899 which see.
9901 A function in this hook may also use `setq' to set the variable
9902 `description' to provide a suggestion for the descriptive text to
9903 be used for this link when it gets inserted into an Org-mode
9904 buffer with \\[org-insert-link].")
9906 (defvar org-execute-file-search-functions nil
9907 "List of functions to execute a file search triggered by a link.
9909 Functions added to this hook must accept a single argument, the
9910 search string that was part of the file link, the part after the
9911 double colon. The function must first check if it would like to
9912 handle this search, for example by checking the `major-mode' or
9913 the file extension. If it decides not to handle this search, it
9914 should just return nil to give other functions a chance. If it
9915 does handle the search, it must return a non-nil value to keep
9916 other functions from trying.
9918 Each function can access the current prefix argument through the
9919 variable `current-prefix-argument'. Note that a single prefix is
9920 used to force opening a link in Emacs, so it may be good to only
9921 use a numeric or double prefix to guide the search function.
9923 In case this is needed, a function in this hook can also restore
9924 the window configuration before `org-open-at-point' was called using:
9926 (set-window-configuration org-window-config-before-follow-link)")
9928 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9929 (defun org-link-search (s &optional type avoid-pos stealth)
9930 "Search for a link search option.
9931 If S is surrounded by forward slashes, it is interpreted as a
9932 regular expression. In org-mode files, this will create an `org-occur'
9933 sparse tree. In ordinary files, `occur' will be used to list matches.
9934 If the current buffer is in `dired-mode', grep will be used to search
9935 in all files. If AVOID-POS is given, ignore matches near that position.
9937 When optional argument STEALTH is non-nil, do not modify
9938 visibility around point, thus ignoring
9939 `org-show-hierarchy-above', `org-show-following-heading' and
9940 `org-show-siblings' variables."
9941 (let ((case-fold-search t)
9942 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9943 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9944 (append '(("") (" ") ("\t") ("\n"))
9945 org-emphasis-alist)
9946 "\\|") "\\)"))
9947 (pos (point))
9948 (pre nil) (post nil)
9949 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9950 (cond
9951 ;; First check if there are any special search functions
9952 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9953 ;; Now try the builtin stuff
9954 ((and (equal (string-to-char s0) ?#)
9955 (> (length s0) 1)
9956 (save-excursion
9957 (goto-char (point-min))
9958 (and
9959 (re-search-forward
9960 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9961 (setq type 'dedicated
9962 pos (match-beginning 0))))
9963 ;; There is an exact target for this
9964 (goto-char pos)
9965 (org-back-to-heading t)))
9966 ((save-excursion
9967 (goto-char (point-min))
9968 (and
9969 (re-search-forward
9970 (concat "<<" (regexp-quote s0) ">>") nil t)
9971 (setq type 'dedicated
9972 pos (match-beginning 0))))
9973 ;; There is an exact target for this
9974 (goto-char pos))
9975 ((save-excursion
9976 (goto-char (point-min))
9977 (and
9978 (re-search-forward
9979 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9980 (setq type 'dedicated pos (match-beginning 0))))
9981 ;; Found an invisible target.
9982 (goto-char pos))
9983 ((save-excursion
9984 (goto-char (point-min))
9985 (and
9986 (re-search-forward
9987 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9988 (setq type 'dedicated pos (match-beginning 0))))
9989 ;; Found an element with a matching #+name affiliated keyword.
9990 (goto-char pos))
9991 ((and (string-match "^(\\(.*\\))$" s0)
9992 (save-excursion
9993 (goto-char (point-min))
9994 (and
9995 (re-search-forward
9996 (concat "[^[]" (regexp-quote
9997 (format org-coderef-label-format
9998 (match-string 1 s0))))
9999 nil t)
10000 (setq type 'dedicated
10001 pos (1+ (match-beginning 0))))))
10002 ;; There is a coderef target for this
10003 (goto-char pos))
10004 ((string-match "^/\\(.*\\)/$" s)
10005 ;; A regular expression
10006 (cond
10007 ((derived-mode-p 'org-mode)
10008 (org-occur (match-string 1 s)))
10009 ;;((eq major-mode 'dired-mode)
10010 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10011 (t (org-do-occur (match-string 1 s)))))
10012 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10013 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10014 (goto-char (point-min))
10015 (cond
10016 ((let (case-fold-search)
10017 (re-search-forward (format org-complex-heading-regexp-format
10018 (regexp-quote s))
10019 nil t))
10020 ;; OK, found a match
10021 (setq type 'dedicated)
10022 (goto-char (match-beginning 0)))
10023 ((and (not org-link-search-inhibit-query)
10024 (eq org-link-search-must-match-exact-headline 'query-to-create)
10025 (y-or-n-p "No match - create this as a new heading? "))
10026 (goto-char (point-max))
10027 (or (bolp) (newline))
10028 (insert "* " s "\n")
10029 (beginning-of-line 0))
10031 (goto-char pos)
10032 (error "No match"))))
10034 ;; A normal search string
10035 (when (equal (string-to-char s) ?*)
10036 ;; Anchor on headlines, post may include tags.
10037 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10038 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10039 s (substring s 1)))
10040 (remove-text-properties
10041 0 (length s)
10042 '(face nil mouse-face nil keymap nil fontified nil) s)
10043 ;; Make a series of regular expressions to find a match
10044 (setq words (org-split-string s "[ \n\r\t]+")
10046 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10047 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10048 "\\)" markers)
10049 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10050 re2a (concat "[ \t\r\n]" re2a_)
10051 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10052 re4 (concat "[^a-zA-Z_]" re4_)
10054 re1 (concat pre re2 post)
10055 re3 (concat pre (if pre re4_ re4) post)
10056 re5 (concat pre ".*" re4)
10057 re2 (concat pre re2)
10058 re2a (concat pre (if pre re2a_ re2a))
10059 re4 (concat pre (if pre re4_ re4))
10060 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10061 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10062 re5 "\\)"
10064 (cond
10065 ((eq type 'org-occur) (org-occur reall))
10066 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10067 (t (goto-char (point-min))
10068 (setq type 'fuzzy)
10069 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10070 (org-search-not-self 1 re1 nil t)
10071 (org-search-not-self 1 re2 nil t)
10072 (org-search-not-self 1 re2a nil t)
10073 (org-search-not-self 1 re3 nil t)
10074 (org-search-not-self 1 re4 nil t)
10075 (org-search-not-self 1 re5 nil t)
10077 (goto-char (match-beginning 1))
10078 (goto-char pos)
10079 (error "No match"))))))
10080 (and (derived-mode-p 'org-mode)
10081 (not stealth)
10082 (org-show-context 'link-search))
10083 type))
10085 (defun org-search-not-self (group &rest args)
10086 "Execute `re-search-forward', but only accept matches that do not
10087 enclose the position of `org-open-link-marker'."
10088 (let ((m org-open-link-marker))
10089 (catch 'exit
10090 (while (apply 're-search-forward args)
10091 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10092 (goto-char (match-end group))
10093 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10094 (> (match-beginning 0) (marker-position m))
10095 (< (match-end 0) (marker-position m)))
10096 (save-match-data
10097 (or (not (org-in-regexp
10098 org-bracket-link-analytic-regexp 1))
10099 (not (match-end 4)) ; no description
10100 (and (<= (match-beginning 4) (point))
10101 (>= (match-end 4) (point))))))
10102 (throw 'exit (point))))))))
10104 (defun org-get-buffer-for-internal-link (buffer)
10105 "Return a buffer to be used for displaying the link target of internal links."
10106 (cond
10107 ((not org-display-internal-link-with-indirect-buffer)
10108 buffer)
10109 ((string-match "(Clone)$" (buffer-name buffer))
10110 (message "Buffer is already a clone, not making another one")
10111 ;; we also do not modify visibility in this case
10112 buffer)
10113 (t ; make a new indirect buffer for displaying the link
10114 (let* ((bn (buffer-name buffer))
10115 (ibn (concat bn "(Clone)"))
10116 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10117 (with-current-buffer ib (org-overview))
10118 ib))))
10120 (defun org-do-occur (regexp &optional cleanup)
10121 "Call the Emacs command `occur'.
10122 If CLEANUP is non-nil, remove the printout of the regular expression
10123 in the *Occur* buffer. This is useful if the regex is long and not useful
10124 to read."
10125 (occur regexp)
10126 (when cleanup
10127 (let ((cwin (selected-window)) win beg end)
10128 (when (setq win (get-buffer-window "*Occur*"))
10129 (select-window win))
10130 (goto-char (point-min))
10131 (when (re-search-forward "match[a-z]+" nil t)
10132 (setq beg (match-end 0))
10133 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10134 (setq end (1- (match-beginning 0)))))
10135 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10136 (goto-char (point-min))
10137 (select-window cwin))))
10139 ;;; The mark ring for links jumps
10141 (defvar org-mark-ring nil
10142 "Mark ring for positions before jumps in Org-mode.")
10143 (defvar org-mark-ring-last-goto nil
10144 "Last position in the mark ring used to go back.")
10145 ;; Fill and close the ring
10146 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10147 (loop for i from 1 to org-mark-ring-length do
10148 (push (make-marker) org-mark-ring))
10149 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10150 org-mark-ring)
10152 (defun org-mark-ring-push (&optional pos buffer)
10153 "Put the current position or POS into the mark ring and rotate it."
10154 (interactive)
10155 (setq pos (or pos (point)))
10156 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10157 (move-marker (car org-mark-ring)
10158 (or pos (point))
10159 (or buffer (current-buffer)))
10160 (message "%s"
10161 (substitute-command-keys
10162 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10164 (defun org-mark-ring-goto (&optional n)
10165 "Jump to the previous position in the mark ring.
10166 With prefix arg N, jump back that many stored positions. When
10167 called several times in succession, walk through the entire ring.
10168 Org-mode commands jumping to a different position in the current file,
10169 or to another Org-mode file, automatically push the old position
10170 onto the ring."
10171 (interactive "p")
10172 (let (p m)
10173 (if (eq last-command this-command)
10174 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10175 (setq p org-mark-ring))
10176 (setq org-mark-ring-last-goto p)
10177 (setq m (car p))
10178 (org-pop-to-buffer-same-window (marker-buffer m))
10179 (goto-char m)
10180 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10182 (defun org-remove-angle-brackets (s)
10183 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10184 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10186 (defun org-add-angle-brackets (s)
10187 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10188 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10190 (defun org-remove-double-quotes (s)
10191 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10192 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10195 ;;; Following specific links
10197 (defun org-follow-timestamp-link ()
10198 (cond
10199 ((org-at-date-range-p t)
10200 (let ((org-agenda-start-on-weekday)
10201 (t1 (match-string 1))
10202 (t2 (match-string 2)))
10203 (setq t1 (time-to-days (org-time-string-to-time t1))
10204 t2 (time-to-days (org-time-string-to-time t2)))
10205 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10206 ((org-at-timestamp-p t)
10207 (org-agenda-list nil (time-to-days (org-time-string-to-time
10208 (substring (match-string 1) 0 10)))
10210 (t (error "This should not happen"))))
10213 ;;; Following file links
10214 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10215 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10216 (declare-function mailcap-mime-info
10217 "mailcap" (string &optional request no-decode))
10218 (defvar org-wait nil)
10219 (defun org-open-file (path &optional in-emacs line search)
10220 "Open the file at PATH.
10221 First, this expands any special file name abbreviations. Then the
10222 configuration variable `org-file-apps' is checked if it contains an
10223 entry for this file type, and if yes, the corresponding command is launched.
10225 If no application is found, Emacs simply visits the file.
10227 With optional prefix argument IN-EMACS, Emacs will visit the file.
10228 With a double \\[universal-argument] \\[universal-argument] \
10229 prefix arg, Org tries to avoid opening in Emacs
10230 and to use an external application to visit the file.
10232 Optional LINE specifies a line to go to, optional SEARCH a string
10233 to search for. If LINE or SEARCH is given, the file will be
10234 opened in Emacs, unless an entry from org-file-apps that makes
10235 use of groups in a regexp matches.
10237 If you want to change the way frames are used when following a
10238 link, please customize `org-link-frame-setup'.
10240 If the file does not exist, an error is thrown."
10241 (let* ((file (if (equal path "")
10242 buffer-file-name
10243 (substitute-in-file-name (expand-file-name path))))
10244 (file-apps (append org-file-apps (org-default-apps)))
10245 (apps (org-remove-if
10246 'org-file-apps-entry-match-against-dlink-p file-apps))
10247 (apps-dlink (org-remove-if-not
10248 'org-file-apps-entry-match-against-dlink-p file-apps))
10249 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10250 (dirp (if remp nil (file-directory-p file)))
10251 (file (if (and dirp org-open-directory-means-index-dot-org)
10252 (concat (file-name-as-directory file) "index.org")
10253 file))
10254 (a-m-a-p (assq 'auto-mode apps))
10255 (dfile (downcase file))
10256 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10257 (link (cond ((and (eq line nil)
10258 (eq search nil))
10259 file)
10260 (line
10261 (concat file "::" (number-to-string line)))
10262 (search
10263 (concat file "::" search))))
10264 (dlink (downcase link))
10265 (old-buffer (current-buffer))
10266 (old-pos (point))
10267 (old-mode major-mode)
10268 ext cmd link-match-data)
10269 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10270 (setq ext (match-string 1 dfile))
10271 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10272 (setq ext (match-string 1 dfile))))
10273 (cond
10274 ((member in-emacs '((16) system))
10275 (setq cmd (cdr (assoc 'system apps))))
10276 (in-emacs (setq cmd 'emacs))
10278 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10279 (and dirp (cdr (assoc 'directory apps)))
10280 ; first, try matching against apps-dlink
10281 ; if we get a match here, store the match data for later
10282 (let ((match (assoc-default dlink apps-dlink
10283 'string-match)))
10284 (if match
10285 (progn (setq link-match-data (match-data))
10286 match)
10287 (progn (setq in-emacs (or in-emacs line search))
10288 nil))) ; if we have no match in apps-dlink,
10289 ; always open the file in emacs if line or search
10290 ; is given (for backwards compatibility)
10291 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10292 'string-match)
10293 (cdr (assoc ext apps))
10294 (cdr (assoc t apps))))))
10295 (when (eq cmd 'system)
10296 (setq cmd (cdr (assoc 'system apps))))
10297 (when (eq cmd 'default)
10298 (setq cmd (cdr (assoc t apps))))
10299 (when (eq cmd 'mailcap)
10300 (require 'mailcap)
10301 (mailcap-parse-mailcaps)
10302 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10303 (command (mailcap-mime-info mime-type)))
10304 (if (stringp command)
10305 (setq cmd command)
10306 (setq cmd 'emacs))))
10307 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10308 (not (file-exists-p file))
10309 (not org-open-non-existing-files))
10310 (error "No such file: %s" file))
10311 (cond
10312 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10313 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10314 (while (string-match "['\"]%s['\"]" cmd)
10315 (setq cmd (replace-match "%s" t t cmd)))
10316 (while (string-match "%s" cmd)
10317 (setq cmd (replace-match
10318 (save-match-data
10319 (shell-quote-argument
10320 (convert-standard-filename file)))
10321 t t cmd)))
10323 ;; Replace "%1", "%2" etc. in command with group matches from regex
10324 (save-match-data
10325 (let ((match-index 1)
10326 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10327 (set-match-data link-match-data)
10328 (while (<= match-index number-of-groups)
10329 (let ((regex (concat "%" (number-to-string match-index)))
10330 (replace-with (match-string match-index dlink)))
10331 (while (string-match regex cmd)
10332 (setq cmd (replace-match replace-with t t cmd))))
10333 (setq match-index (+ match-index 1)))))
10335 (save-window-excursion
10336 (start-process-shell-command cmd nil cmd)
10337 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10339 ((or (stringp cmd)
10340 (eq cmd 'emacs))
10341 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10342 (widen)
10343 (if line (org-goto-line line)
10344 (if search (org-link-search search))))
10345 ((consp cmd)
10346 (let ((file (convert-standard-filename file)))
10347 (save-match-data
10348 (set-match-data link-match-data)
10349 (eval cmd))))
10350 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10351 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10352 (or (not (equal old-buffer (current-buffer)))
10353 (not (equal old-pos (point))))
10354 (org-mark-ring-push old-pos old-buffer))))
10356 (defun org-file-apps-entry-match-against-dlink-p (entry)
10357 "This function returns non-nil if `entry' uses a regular
10358 expression which should be matched against the whole link by
10359 org-open-file.
10361 It assumes that is the case when the entry uses a regular
10362 expression which has at least one grouping construct and the
10363 action is either a lisp form or a command string containing
10364 '%1', i.e. using at least one subexpression match as a
10365 parameter."
10366 (let ((selector (car entry))
10367 (action (cdr entry)))
10368 (if (stringp selector)
10369 (and (> (regexp-opt-depth selector) 0)
10370 (or (and (stringp action)
10371 (string-match "%[0-9]" action))
10372 (consp action)))
10373 nil)))
10375 (defun org-default-apps ()
10376 "Return the default applications for this operating system."
10377 (cond
10378 ((eq system-type 'darwin)
10379 org-file-apps-defaults-macosx)
10380 ((eq system-type 'windows-nt)
10381 org-file-apps-defaults-windowsnt)
10382 (t org-file-apps-defaults-gnu)))
10384 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10385 "Convert extensions to regular expressions in the cars of LIST.
10386 Also, weed out any non-string entries, because the return value is used
10387 only for regexp matching.
10388 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10389 point to the symbol `emacs', indicating that the file should
10390 be opened in Emacs."
10391 (append
10392 (delq nil
10393 (mapcar (lambda (x)
10394 (if (not (stringp (car x)))
10396 (if (string-match "\\W" (car x))
10398 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10399 list))
10400 (if add-auto-mode
10401 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10403 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10404 (defun org-file-remote-p (file)
10405 "Test whether FILE specifies a location on a remote system.
10406 Return non-nil if the location is indeed remote.
10408 For example, the filename \"/user@host:/foo\" specifies a location
10409 on the system \"/user@host:\"."
10410 (cond ((fboundp 'file-remote-p)
10411 (file-remote-p file))
10412 ((fboundp 'tramp-handle-file-remote-p)
10413 (tramp-handle-file-remote-p file))
10414 ((and (boundp 'ange-ftp-name-format)
10415 (string-match (car ange-ftp-name-format) file))
10417 (t nil)))
10420 ;;;; Refiling
10422 (defun org-get-org-file ()
10423 "Read a filename, with default directory `org-directory'."
10424 (let ((default (or org-default-notes-file remember-data-file)))
10425 (read-file-name (format "File name [%s]: " default)
10426 (file-name-as-directory org-directory)
10427 default)))
10429 (defun org-notes-order-reversed-p ()
10430 "Check if the current file should receive notes in reversed order."
10431 (cond
10432 ((not org-reverse-note-order) nil)
10433 ((eq t org-reverse-note-order) t)
10434 ((not (listp org-reverse-note-order)) nil)
10435 (t (catch 'exit
10436 (let ((all org-reverse-note-order)
10437 entry)
10438 (while (setq entry (pop all))
10439 (if (string-match (car entry) buffer-file-name)
10440 (throw 'exit (cdr entry))))
10441 nil)))))
10443 (defvar org-refile-target-table nil
10444 "The list of refile targets, created by `org-refile'.")
10446 (defvar org-agenda-new-buffers nil
10447 "Buffers created to visit agenda files.")
10449 (defvar org-refile-cache nil
10450 "Cache for refile targets.")
10452 (defvar org-refile-markers nil
10453 "All the markers used for caching refile locations.")
10455 (defun org-refile-marker (pos)
10456 "Get a new refile marker, but only if caching is in use."
10457 (if (not org-refile-use-cache)
10459 (let ((m (make-marker)))
10460 (move-marker m pos)
10461 (push m org-refile-markers)
10462 m)))
10464 (defun org-refile-cache-clear ()
10465 "Clear the refile cache and disable all the markers."
10466 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10467 (setq org-refile-markers nil)
10468 (setq org-refile-cache nil)
10469 (message "Refile cache has been cleared"))
10471 (defun org-refile-cache-check-set (set)
10472 "Check if all the markers in the cache still have live buffers."
10473 (let (marker)
10474 (catch 'exit
10475 (while (and set (setq marker (nth 3 (pop set))))
10476 ;; if org-refile-use-outline-path is 'file, marker may be nil
10477 (when (and marker (null (marker-buffer marker)))
10478 (message "not found") (sit-for 3)
10479 (throw 'exit nil)))
10480 t)))
10482 (defun org-refile-cache-put (set &rest identifiers)
10483 "Push the refile targets SET into the cache, under IDENTIFIERS."
10484 (let* ((key (sha1 (prin1-to-string identifiers)))
10485 (entry (assoc key org-refile-cache)))
10486 (if entry
10487 (setcdr entry set)
10488 (push (cons key set) org-refile-cache))))
10490 (defun org-refile-cache-get (&rest identifiers)
10491 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10492 (cond
10493 ((not org-refile-cache) nil)
10494 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10496 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10497 org-refile-cache))))
10498 (and set (org-refile-cache-check-set set) set)))))
10500 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10501 "Produce a table with refile targets."
10502 (let ((case-fold-search nil)
10503 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10504 (entries (or org-refile-targets '((nil . (:level . 1)))))
10505 targets tgs txt re files f desc descre fast-path-p level pos0)
10506 (message "Getting targets...")
10507 (with-current-buffer (or default-buffer (current-buffer))
10508 (while (setq entry (pop entries))
10509 (setq files (car entry) desc (cdr entry))
10510 (setq fast-path-p nil)
10511 (cond
10512 ((null files) (setq files (list (current-buffer))))
10513 ((eq files 'org-agenda-files)
10514 (setq files (org-agenda-files 'unrestricted)))
10515 ((and (symbolp files) (fboundp files))
10516 (setq files (funcall files)))
10517 ((and (symbolp files) (boundp files))
10518 (setq files (symbol-value files))))
10519 (if (stringp files) (setq files (list files)))
10520 (cond
10521 ((eq (car desc) :tag)
10522 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10523 ((eq (car desc) :todo)
10524 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10525 ((eq (car desc) :regexp)
10526 (setq descre (cdr desc)))
10527 ((eq (car desc) :level)
10528 (setq descre (concat "^\\*\\{" (number-to-string
10529 (if org-odd-levels-only
10530 (1- (* 2 (cdr desc)))
10531 (cdr desc)))
10532 "\\}[ \t]")))
10533 ((eq (car desc) :maxlevel)
10534 (setq fast-path-p t)
10535 (setq descre (concat "^\\*\\{1," (number-to-string
10536 (if org-odd-levels-only
10537 (1- (* 2 (cdr desc)))
10538 (cdr desc)))
10539 "\\}[ \t]")))
10540 (t (error "Bad refiling target description %s" desc)))
10541 (while (setq f (pop files))
10542 (with-current-buffer
10543 (if (bufferp f) f (org-get-agenda-file-buffer f))
10545 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10546 (progn
10547 (if (bufferp f) (setq f (buffer-file-name
10548 (buffer-base-buffer f))))
10549 (setq f (and f (expand-file-name f)))
10550 (if (eq org-refile-use-outline-path 'file)
10551 (push (list (file-name-nondirectory f) f nil nil) tgs))
10552 (save-excursion
10553 (save-restriction
10554 (widen)
10555 (goto-char (point-min))
10556 (while (re-search-forward descre nil t)
10557 (goto-char (setq pos0 (point-at-bol)))
10558 (catch 'next
10559 (when org-refile-target-verify-function
10560 (save-match-data
10561 (or (funcall org-refile-target-verify-function)
10562 (throw 'next t))))
10563 (when (and (looking-at org-complex-heading-regexp)
10564 (not (member (match-string 4) excluded-entries))
10565 (match-string 4))
10566 (setq level (org-reduced-level
10567 (- (match-end 1) (match-beginning 1)))
10568 txt (org-link-display-format (match-string 4))
10569 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10570 re (format org-complex-heading-regexp-format
10571 (regexp-quote (match-string 4))))
10572 (when org-refile-use-outline-path
10573 (setq txt (mapconcat
10574 'org-protect-slash
10575 (append
10576 (if (eq org-refile-use-outline-path
10577 'file)
10578 (list (file-name-nondirectory
10579 (buffer-file-name
10580 (buffer-base-buffer))))
10581 (if (eq org-refile-use-outline-path
10582 'full-file-path)
10583 (list (buffer-file-name
10584 (buffer-base-buffer)))))
10585 (org-get-outline-path fast-path-p
10586 level txt)
10587 (list txt))
10588 "/")))
10589 (push (list txt f re (org-refile-marker (point)))
10590 tgs)))
10591 (when (= (point) pos0)
10592 ;; verification function has not moved point
10593 (goto-char (point-at-eol))))))))
10594 (when org-refile-use-cache
10595 (org-refile-cache-put tgs (buffer-file-name) descre))
10596 (setq targets (append tgs targets))
10597 ))))
10598 (message "Getting targets...done")
10599 (nreverse targets)))
10601 (defun org-protect-slash (s)
10602 (while (string-match "/" s)
10603 (setq s (replace-match "\\" t t s)))
10606 (defvar org-olpa (make-vector 20 nil))
10608 (defun org-get-outline-path (&optional fastp level heading)
10609 "Return the outline path to the current entry, as a list.
10611 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10612 routine which makes outline path derivations for an entire file,
10613 avoiding backtracing. Refile target collection makes use of that."
10614 (if fastp
10615 (progn
10616 (if (> level 19)
10617 (error "Outline path failure, more than 19 levels"))
10618 (loop for i from level upto 19 do
10619 (aset org-olpa i nil))
10620 (prog1
10621 (delq nil (append org-olpa nil))
10622 (aset org-olpa level heading)))
10623 (let (rtn case-fold-search)
10624 (save-excursion
10625 (save-restriction
10626 (widen)
10627 (while (org-up-heading-safe)
10628 (when (looking-at org-complex-heading-regexp)
10629 (push (org-match-string-no-properties 4) rtn)))
10630 rtn)))))
10632 (defun org-format-outline-path (path &optional width prefix)
10633 "Format the outline path PATH for display.
10634 Width is the maximum number of characters that is available.
10635 Prefix is a prefix to be included in the returned string,
10636 such as the file name."
10637 (setq width (or width 79))
10638 (if prefix (setq width (- width (length prefix))))
10639 (if (not path)
10640 (or prefix "")
10641 (let* ((nsteps (length path))
10642 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10643 (maxwidth (if (<= total-width width)
10644 10000 ;; everything fits
10645 ;; we need to shorten the level headings
10646 (/ (- width nsteps) nsteps)))
10647 (org-odd-levels-only nil)
10648 (n 0)
10649 (total (1+ (length prefix))))
10650 (setq maxwidth (max maxwidth 10))
10651 (concat prefix
10652 (mapconcat
10653 (lambda (h)
10654 (setq n (1+ n))
10655 (if (and (= n nsteps) (< maxwidth 10000))
10656 (setq maxwidth (- total-width total)))
10657 (if (< (length h) maxwidth)
10658 (progn (setq total (+ total (length h) 1)) h)
10659 (setq h (substring h 0 (- maxwidth 2))
10660 total (+ total maxwidth 1))
10661 (if (string-match "[ \t]+\\'" h)
10662 (setq h (substring h 0 (match-beginning 0))))
10663 (setq h (concat h "..")))
10664 (org-add-props h nil 'face
10665 (nth (% (1- n) org-n-level-faces)
10666 org-level-faces))
10668 path "/")))))
10670 (defun org-display-outline-path (&optional file current)
10671 "Display the current outline path in the echo area."
10672 (interactive "P")
10673 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10674 (case-fold-search nil)
10675 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10676 (if current (setq path (append path
10677 (save-excursion
10678 (org-back-to-heading t)
10679 (if (looking-at org-complex-heading-regexp)
10680 (list (match-string 4)))))))
10681 (message "%s"
10682 (org-format-outline-path
10683 path
10684 (1- (frame-width))
10685 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10687 (defvar org-refile-history nil
10688 "History for refiling operations.")
10690 (defvar org-after-refile-insert-hook nil
10691 "Hook run after `org-refile' has inserted its stuff at the new location.
10692 Note that this is still *before* the stuff will be removed from
10693 the *old* location.")
10695 (defvar org-capture-last-stored-marker)
10696 (defun org-refile (&optional goto default-buffer rfloc)
10697 "Move the entry or entries at point to another heading.
10698 The list of target headings is compiled using the information in
10699 `org-refile-targets', which see.
10701 At the target location, the entry is filed as a subitem of the target
10702 heading. Depending on `org-reverse-note-order', the new subitem will
10703 either be the first or the last subitem.
10705 If there is an active region, all entries in that region will be moved.
10706 However, the region must fulfill the requirement that the first heading
10707 is the first one sets the top-level of the moved text - at most siblings
10708 below it are allowed.
10710 With prefix arg GOTO, the command will only visit the target location
10711 and not actually move anything.
10713 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10714 go to the location where the last refiling operation has put the subtree.
10715 With a prefix argument of `2', refile to the running clock.
10717 RFLOC can be a refile location obtained in a different way.
10719 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10721 If you are using target caching (see `org-refile-use-cache'),
10722 you have to clear the target cache in order to find new targets.
10723 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10724 prefix argument (`C-u C-u C-u C-c C-w')."
10726 (interactive "P")
10727 (if (member goto '(0 (64)))
10728 (org-refile-cache-clear)
10729 (let* ((cbuf (current-buffer))
10730 (regionp (org-region-active-p))
10731 (region-start (and regionp (region-beginning)))
10732 (region-end (and regionp (region-end)))
10733 (region-length (and regionp (- region-end region-start)))
10734 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10735 pos it nbuf file re level reversed)
10736 (setq last-command nil)
10737 (when regionp
10738 (goto-char region-start)
10739 (or (bolp) (goto-char (point-at-bol)))
10740 (setq region-start (point))
10741 (unless (or (org-kill-is-subtree-p
10742 (buffer-substring region-start region-end))
10743 (prog1 org-refile-active-region-within-subtree
10744 (org-toggle-heading)))
10745 (error "The region is not a (sequence of) subtree(s)")))
10746 (if (equal goto '(16))
10747 (org-refile-goto-last-stored)
10748 (when (or
10749 (and (equal goto 2)
10750 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10751 (prog1
10752 (setq it (list (or org-clock-heading "running clock")
10753 (buffer-file-name
10754 (marker-buffer org-clock-hd-marker))
10756 (marker-position org-clock-hd-marker)))
10757 (setq goto nil)))
10758 (setq it (or rfloc
10759 (let (heading-text)
10760 (save-excursion
10761 (unless goto
10762 (org-back-to-heading t)
10763 (setq heading-text
10764 (nth 4 (org-heading-components))))
10765 (org-refile-get-location
10766 (cond (goto "Goto")
10767 (regionp "Refile region to")
10768 (t (concat "Refile subtree \""
10769 heading-text "\" to")))
10770 default-buffer
10771 (and (not (equal '(4) goto))
10772 org-refile-allow-creating-parent-nodes)
10773 goto))))))
10774 (setq file (nth 1 it)
10775 re (nth 2 it)
10776 pos (nth 3 it))
10777 (if (and (not goto)
10779 (equal (buffer-file-name) file)
10780 (if regionp
10781 (and (>= pos region-start)
10782 (<= pos region-end))
10783 (and (>= pos (point))
10784 (< pos (save-excursion
10785 (org-end-of-subtree t t))))))
10786 (error "Cannot refile to position inside the tree or region"))
10788 (setq nbuf (or (find-buffer-visiting file)
10789 (find-file-noselect file)))
10790 (if goto
10791 (progn
10792 (org-pop-to-buffer-same-window nbuf)
10793 (goto-char pos)
10794 (org-show-context 'org-goto))
10795 (if regionp
10796 (progn
10797 (org-kill-new (buffer-substring region-start region-end))
10798 (org-save-markers-in-region region-start region-end))
10799 (org-copy-subtree 1 nil t))
10800 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10801 (find-file-noselect file)))
10802 (setq reversed (org-notes-order-reversed-p))
10803 (save-excursion
10804 (save-restriction
10805 (widen)
10806 (if pos
10807 (progn
10808 (goto-char pos)
10809 (looking-at org-outline-regexp)
10810 (setq level (org-get-valid-level (funcall outline-level) 1))
10811 (goto-char
10812 (if reversed
10813 (or (outline-next-heading) (point-max))
10814 (or (save-excursion (org-get-next-sibling))
10815 (org-end-of-subtree t t)
10816 (point-max)))))
10817 (setq level 1)
10818 (if (not reversed)
10819 (goto-char (point-max))
10820 (goto-char (point-min))
10821 (or (outline-next-heading) (goto-char (point-max)))))
10822 (if (not (bolp)) (newline))
10823 (org-paste-subtree level)
10824 (when org-log-refile
10825 (org-add-log-setup 'refile nil nil 'findpos
10826 org-log-refile)
10827 (unless (eq org-log-refile 'note)
10828 (save-excursion (org-add-log-note))))
10829 (and org-auto-align-tags (org-set-tags nil t))
10830 (bookmark-set "org-refile-last-stored")
10831 ;; If we are refiling for capture, make sure that the
10832 ;; last-capture pointers point here
10833 (when (org-bound-and-true-p org-refile-for-capture)
10834 (bookmark-set "org-capture-last-stored-marker")
10835 (move-marker org-capture-last-stored-marker (point)))
10836 (if (fboundp 'deactivate-mark) (deactivate-mark))
10837 (run-hooks 'org-after-refile-insert-hook))))
10838 (if regionp
10839 (delete-region (point) (+ (point) region-length))
10840 (org-cut-subtree))
10841 (when (featurep 'org-inlinetask)
10842 (org-inlinetask-remove-END-maybe))
10843 (setq org-markers-to-move nil)
10844 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10846 (defun org-refile-goto-last-stored ()
10847 "Go to the location where the last refile was stored."
10848 (interactive)
10849 (bookmark-jump "org-refile-last-stored")
10850 (message "This is the location of the last refile"))
10852 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10853 no-exclude)
10854 "Prompt the user for a refile location, using PROMPT.
10855 PROMPT should not be suffixed with a colon and a space, because
10856 this function appends the default value from
10857 `org-refile-history' automatically, if that is not empty.
10858 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10859 this is used for the GOTO interface."
10860 (let ((org-refile-targets org-refile-targets)
10861 (org-refile-use-outline-path org-refile-use-outline-path)
10862 excluded-entries)
10863 (when (and (derived-mode-p 'org-mode)
10864 (not org-refile-use-cache)
10865 (not no-exclude))
10866 (org-map-tree
10867 (lambda()
10868 (setq excluded-entries
10869 (append excluded-entries (list (org-get-heading t t)))))))
10870 (setq org-refile-target-table
10871 (org-refile-get-targets default-buffer excluded-entries)))
10872 (unless org-refile-target-table
10873 (error "No refile targets"))
10874 (let* ((prompt (concat prompt
10875 (and (car org-refile-history)
10876 (concat " (default " (car org-refile-history) ")"))
10877 ": "))
10878 (cbuf (current-buffer))
10879 (partial-completion-mode nil)
10880 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10881 (cfunc (if (and org-refile-use-outline-path
10882 org-outline-path-complete-in-steps)
10883 'org-olpath-completing-read
10884 'org-icompleting-read))
10885 (extra (if org-refile-use-outline-path "/" ""))
10886 (filename (and cfn (expand-file-name cfn)))
10887 (tbl (mapcar
10888 (lambda (x)
10889 (if (and (not (member org-refile-use-outline-path
10890 '(file full-file-path)))
10891 (not (equal filename (nth 1 x))))
10892 (cons (concat (car x) extra " ("
10893 (file-name-nondirectory (nth 1 x)) ")")
10894 (cdr x))
10895 (cons (concat (car x) extra) (cdr x))))
10896 org-refile-target-table))
10897 (completion-ignore-case t)
10898 pa answ parent-target child parent old-hist)
10899 (setq old-hist org-refile-history)
10900 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10901 nil 'org-refile-history (car org-refile-history)))
10902 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10903 (org-refile-check-position pa)
10904 (if pa
10905 (progn
10906 (when (or (not org-refile-history)
10907 (not (eq old-hist org-refile-history))
10908 (not (equal (car pa) (car org-refile-history))))
10909 (setq org-refile-history
10910 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10911 org-refile-history
10912 (cdr org-refile-history))))
10913 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10914 (pop org-refile-history)))
10916 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10917 (progn
10918 (setq parent (match-string 1 answ)
10919 child (match-string 2 answ))
10920 (setq parent-target (or (assoc parent tbl)
10921 (assoc (concat parent "/") tbl)))
10922 (when (and parent-target
10923 (or (eq new-nodes t)
10924 (and (eq new-nodes 'confirm)
10925 (y-or-n-p (format "Create new node \"%s\"? "
10926 child)))))
10927 (org-refile-new-child parent-target child)))
10928 (error "Invalid target location")))))
10930 (declare-function org-string-nw-p "org-macs.el" (s))
10931 (defun org-refile-check-position (refile-pointer)
10932 "Check if the refile pointer matches the readline to which it points."
10933 (let* ((file (nth 1 refile-pointer))
10934 (re (nth 2 refile-pointer))
10935 (pos (nth 3 refile-pointer))
10936 buffer)
10937 (when (org-string-nw-p re)
10938 (setq buffer (if (markerp pos)
10939 (marker-buffer pos)
10940 (or (find-buffer-visiting file)
10941 (find-file-noselect file))))
10942 (with-current-buffer buffer
10943 (save-excursion
10944 (save-restriction
10945 (widen)
10946 (goto-char pos)
10947 (beginning-of-line 1)
10948 (unless (org-looking-at-p re)
10949 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10951 (defun org-refile-new-child (parent-target child)
10952 "Use refile target PARENT-TARGET to add new CHILD below it."
10953 (unless parent-target
10954 (error "Cannot find parent for new node"))
10955 (let ((file (nth 1 parent-target))
10956 (pos (nth 3 parent-target))
10957 level)
10958 (with-current-buffer (or (find-buffer-visiting file)
10959 (find-file-noselect file))
10960 (save-excursion
10961 (save-restriction
10962 (widen)
10963 (if pos
10964 (goto-char pos)
10965 (goto-char (point-max))
10966 (if (not (bolp)) (newline)))
10967 (when (looking-at org-outline-regexp)
10968 (setq level (funcall outline-level))
10969 (org-end-of-subtree t t))
10970 (org-back-over-empty-lines)
10971 (insert "\n" (make-string
10972 (if pos (org-get-valid-level level 1) 1) ?*)
10973 " " child "\n")
10974 (beginning-of-line 0)
10975 (list (concat (car parent-target) "/" child) file "" (point)))))))
10977 (defun org-olpath-completing-read (prompt collection &rest args)
10978 "Read an outline path like a file name."
10979 (let ((thetable collection)
10980 (org-completion-use-ido nil) ; does not work with ido.
10981 (org-completion-use-iswitchb nil)) ; or iswitchb
10982 (apply
10983 'org-icompleting-read prompt
10984 (lambda (string predicate &optional flag)
10985 (let (rtn r f (l (length string)))
10986 (cond
10987 ((eq flag nil)
10988 ;; try completion
10989 (try-completion string thetable))
10990 ((eq flag t)
10991 ;; all-completions
10992 (setq rtn (all-completions string thetable predicate))
10993 (mapcar
10994 (lambda (x)
10995 (setq r (substring x l))
10996 (if (string-match " ([^)]*)$" x)
10997 (setq f (match-string 0 x))
10998 (setq f ""))
10999 (if (string-match "/" r)
11000 (concat string (substring r 0 (match-end 0)) f)
11002 rtn))
11003 ((eq flag 'lambda)
11004 ;; exact match?
11005 (assoc string thetable)))))
11006 args)))
11008 ;;;; Dynamic blocks
11010 (defun org-find-dblock (name)
11011 "Find the first dynamic block with name NAME in the buffer.
11012 If not found, stay at current position and return nil."
11013 (let (pos)
11014 (save-excursion
11015 (goto-char (point-min))
11016 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
11017 nil t)
11018 (match-beginning 0))))
11019 (if pos (goto-char pos))
11020 pos))
11022 (defconst org-dblock-start-re
11023 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11024 "Matches the start line of a dynamic block, with parameters.")
11026 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
11027 "Matches the end of a dynamic block.")
11029 (defun org-create-dblock (plist)
11030 "Create a dynamic block section, with parameters taken from PLIST.
11031 PLIST must contain a :name entry which is used as name of the block."
11032 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11033 (end-of-line 1)
11034 (newline))
11035 (let ((col (current-column))
11036 (name (plist-get plist :name)))
11037 (insert "#+BEGIN: " name)
11038 (while plist
11039 (if (eq (car plist) :name)
11040 (setq plist (cddr plist))
11041 (insert " " (prin1-to-string (pop plist)))))
11042 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11043 (beginning-of-line -2)))
11045 (defun org-prepare-dblock ()
11046 "Prepare dynamic block for refresh.
11047 This empties the block, puts the cursor at the insert position and returns
11048 the property list including an extra property :name with the block name."
11049 (unless (looking-at org-dblock-start-re)
11050 (error "Not at a dynamic block"))
11051 (let* ((begdel (1+ (match-end 0)))
11052 (name (org-no-properties (match-string 1)))
11053 (params (append (list :name name)
11054 (read (concat "(" (match-string 3) ")")))))
11055 (save-excursion
11056 (beginning-of-line 1)
11057 (skip-chars-forward " \t")
11058 (setq params (plist-put params :indentation-column (current-column))))
11059 (unless (re-search-forward org-dblock-end-re nil t)
11060 (error "Dynamic block not terminated"))
11061 (setq params
11062 (append params
11063 (list :content (buffer-substring
11064 begdel (match-beginning 0)))))
11065 (delete-region begdel (match-beginning 0))
11066 (goto-char begdel)
11067 (open-line 1)
11068 params))
11070 (defun org-map-dblocks (&optional command)
11071 "Apply COMMAND to all dynamic blocks in the current buffer.
11072 If COMMAND is not given, use `org-update-dblock'."
11073 (let ((cmd (or command 'org-update-dblock)))
11074 (save-excursion
11075 (goto-char (point-min))
11076 (while (re-search-forward org-dblock-start-re nil t)
11077 (goto-char (match-beginning 0))
11078 (save-excursion
11079 (condition-case nil
11080 (funcall cmd)
11081 (error (message "Error during update of dynamic block"))))
11082 (unless (re-search-forward org-dblock-end-re nil t)
11083 (error "Dynamic block not terminated"))))))
11085 (defun org-dblock-update (&optional arg)
11086 "User command for updating dynamic blocks.
11087 Update the dynamic block at point. With prefix ARG, update all dynamic
11088 blocks in the buffer."
11089 (interactive "P")
11090 (if arg
11091 (org-update-all-dblocks)
11092 (or (looking-at org-dblock-start-re)
11093 (org-beginning-of-dblock))
11094 (org-update-dblock)))
11096 (defun org-update-dblock ()
11097 "Update the dynamic block at point.
11098 This means to empty the block, parse for parameters and then call
11099 the correct writing function."
11100 (interactive)
11101 (save-window-excursion
11102 (let* ((pos (point))
11103 (line (org-current-line))
11104 (params (org-prepare-dblock))
11105 (name (plist-get params :name))
11106 (indent (plist-get params :indentation-column))
11107 (cmd (intern (concat "org-dblock-write:" name))))
11108 (message "Updating dynamic block `%s' at line %d..." name line)
11109 (funcall cmd params)
11110 (message "Updating dynamic block `%s' at line %d...done" name line)
11111 (goto-char pos)
11112 (when (and indent (> indent 0))
11113 (setq indent (make-string indent ?\ ))
11114 (save-excursion
11115 (org-beginning-of-dblock)
11116 (forward-line 1)
11117 (while (not (looking-at org-dblock-end-re))
11118 (insert indent)
11119 (beginning-of-line 2))
11120 (when (looking-at org-dblock-end-re)
11121 (and (looking-at "[ \t]+")
11122 (replace-match ""))
11123 (insert indent)))))))
11125 (defun org-beginning-of-dblock ()
11126 "Find the beginning of the dynamic block at point.
11127 Error if there is no such block at point."
11128 (let ((pos (point))
11129 beg)
11130 (end-of-line 1)
11131 (if (and (re-search-backward org-dblock-start-re nil t)
11132 (setq beg (match-beginning 0))
11133 (re-search-forward org-dblock-end-re nil t)
11134 (> (match-end 0) pos))
11135 (goto-char beg)
11136 (goto-char pos)
11137 (error "Not in a dynamic block"))))
11139 ;;;###autoload
11140 (defun org-update-all-dblocks ()
11141 "Update all dynamic blocks in the buffer.
11142 This function can be used in a hook."
11143 (interactive)
11144 (when (derived-mode-p 'org-mode)
11145 (org-map-dblocks 'org-update-dblock)))
11148 ;;;; Completion
11150 (defconst org-additional-option-like-keywords
11151 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11152 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11153 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11154 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11155 "BEGIN:" "END:"
11156 "ORGTBL" "TBLFM:" "TBLNAME:"
11157 "BEGIN_EXAMPLE" "END_EXAMPLE"
11158 "BEGIN_QUOTE" "END_QUOTE"
11159 "BEGIN_VERSE" "END_VERSE"
11160 "BEGIN_CENTER" "END_CENTER"
11161 "BEGIN_SRC" "END_SRC"
11162 "BEGIN_RESULT" "END_RESULT"
11163 "NAME:" "RESULTS:"
11164 "HEADER:" "HEADERS:"
11165 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11166 "CAPTION:" "LABEL:"
11167 "SETUPFILE:"
11168 "INCLUDE:"
11169 "BIND:"
11170 "MACRO:"))
11172 (defcustom org-structure-template-alist
11174 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11175 "<src lang=\"?\">\n\n</src>")
11176 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11177 "<example>\n?\n</example>")
11178 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11179 "<quote>\n?\n</quote>")
11180 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11181 "<verse>\n?\n</verse>")
11182 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11183 "<center>\n?\n</center>")
11184 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11185 "<literal style=\"latex\">\n?\n</literal>")
11186 ("L" "#+LaTeX: "
11187 "<literal style=\"latex\">?</literal>")
11188 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11189 "<literal style=\"html\">\n?\n</literal>")
11190 ("H" "#+HTML: "
11191 "<literal style=\"html\">?</literal>")
11192 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11193 ("A" "#+ASCII: ")
11194 ("i" "#+INDEX: ?"
11195 "#+INDEX: ?")
11196 ("I" "#+INCLUDE %file ?"
11197 "<include file=%file markup=\"?\">")
11199 "Structure completion elements.
11200 This is a list of abbreviation keys and values. The value gets inserted
11201 if you type `<' followed by the key and then press the completion key,
11202 usually `M-TAB'. %file will be replaced by a file name after prompting
11203 for the file using completion. The cursor will be placed at the position
11204 of the `?` in the template.
11205 There are two templates for each key, the first uses the original Org syntax,
11206 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11207 the default when the /org-mtags.el/ module has been loaded. See also the
11208 variable `org-mtags-prefer-muse-templates'."
11209 :group 'org-completion
11210 :type '(repeat
11211 (string :tag "Key")
11212 (string :tag "Template")
11213 (string :tag "Muse Template")))
11215 (defun org-try-structure-completion ()
11216 "Try to complete a structure template before point.
11217 This looks for strings like \"<e\" on an otherwise empty line and
11218 expands them."
11219 (let ((l (buffer-substring (point-at-bol) (point)))
11221 (when (and (looking-at "[ \t]*$")
11222 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11223 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11224 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11225 (match-beginning 1)) a)
11226 t)))
11228 (defun org-complete-expand-structure-template (start cell)
11229 "Expand a structure template."
11230 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11231 (rpl (nth (if musep 2 1) cell))
11232 (ind ""))
11233 (delete-region start (point))
11234 (when (string-match "\\`#\\+" rpl)
11235 (cond
11236 ((bolp))
11237 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11238 (setq ind (buffer-substring (point-at-bol) (point))))
11239 (t (newline))))
11240 (setq start (point))
11241 (if (string-match "%file" rpl)
11242 (setq rpl (replace-match
11243 (concat
11244 "\""
11245 (save-match-data
11246 (abbreviate-file-name (read-file-name "Include file: ")))
11247 "\"")
11248 t t rpl)))
11249 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11250 (concat "\n" ind)))
11251 (insert rpl)
11252 (if (re-search-backward "\\?" start t) (delete-char 1))))
11254 ;;;; TODO, DEADLINE, Comments
11256 (defun org-toggle-comment ()
11257 "Change the COMMENT state of an entry."
11258 (interactive)
11259 (save-excursion
11260 (org-back-to-heading)
11261 (let (case-fold-search)
11262 (cond
11263 ((looking-at (format org-heading-keyword-regexp-format
11264 org-comment-string))
11265 (goto-char (match-end 1))
11266 (looking-at (concat " +" org-comment-string))
11267 (replace-match "" t t)
11268 (when (eolp) (insert " ")))
11269 ((looking-at org-outline-regexp)
11270 (goto-char (match-end 0))
11271 (insert org-comment-string " "))))))
11273 (defvar org-last-todo-state-is-todo nil
11274 "This is non-nil when the last TODO state change led to a TODO state.
11275 If the last change removed the TODO tag or switched to DONE, then
11276 this is nil.")
11278 (defvar org-setting-tags nil) ; dynamically skipped
11280 (defvar org-todo-setup-filter-hook nil
11281 "Hook for functions that pre-filter todo specs.
11282 Each function takes a todo spec and returns either nil or the spec
11283 transformed into canonical form." )
11285 (defvar org-todo-get-default-hook nil
11286 "Hook for functions that get a default item for todo.
11287 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11288 nil or a string to be used for the todo mark." )
11290 (defvar org-agenda-headline-snapshot-before-repeat)
11292 (defun org-current-effective-time ()
11293 "Return current time adjusted for `org-extend-today-until' variable"
11294 (let* ((ct (org-current-time))
11295 (dct (decode-time ct))
11296 (ct1
11297 (if (and org-use-effective-time
11298 (< (nth 2 dct) org-extend-today-until))
11299 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11300 ct)))
11301 ct1))
11303 (defun org-todo-yesterday (&optional arg)
11304 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11305 (interactive "P")
11306 (if (eq major-mode 'org-agenda-mode)
11307 (apply 'org-agenda-todo-yesterday arg)
11308 (let* ((hour (third (decode-time
11309 (org-current-time))))
11310 (org-extend-today-until (1+ hour)))
11311 (org-todo arg))))
11313 (defun org-todo (&optional arg)
11314 "Change the TODO state of an item.
11315 The state of an item is given by a keyword at the start of the heading,
11316 like
11317 *** TODO Write paper
11318 *** DONE Call mom
11320 The different keywords are specified in the variable `org-todo-keywords'.
11321 By default the available states are \"TODO\" and \"DONE\".
11322 So for this example: when the item starts with TODO, it is changed to DONE.
11323 When it starts with DONE, the DONE is removed. And when neither TODO nor
11324 DONE are present, add TODO at the beginning of the heading.
11326 With \\[universal-argument] prefix arg, use completion to determine the new \
11327 state.
11328 With numeric prefix arg, switch to that state.
11329 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11330 keywords (nextset).
11331 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11332 With a numeric prefix arg of 0, inhibit note taking for the change.
11334 For calling through lisp, arg is also interpreted in the following way:
11335 'none -> empty state
11336 \"\"(empty string) -> switch to empty state
11337 'done -> switch to DONE
11338 'nextset -> switch to the next set of keywords
11339 'previousset -> switch to the previous set of keywords
11340 \"WAITING\" -> switch to the specified keyword, but only if it
11341 really is a member of `org-todo-keywords'."
11342 (interactive "P")
11343 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11344 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11345 'region-start-level 'region))
11346 org-loop-over-headlines-in-active-region)
11347 (org-map-entries
11348 `(org-todo ,arg)
11349 org-loop-over-headlines-in-active-region
11350 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11351 (if (equal arg '(16)) (setq arg 'nextset))
11352 (let ((org-blocker-hook org-blocker-hook)
11353 (case-fold-search nil))
11354 (when (equal arg '(64))
11355 (setq arg nil org-blocker-hook nil))
11356 (when (and org-blocker-hook
11357 (or org-inhibit-blocking
11358 (org-entry-get nil "NOBLOCKING")))
11359 (setq org-blocker-hook nil))
11360 (save-excursion
11361 (catch 'exit
11362 (org-back-to-heading t)
11363 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11364 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11365 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11366 (let* ((match-data (match-data))
11367 (startpos (point-at-bol))
11368 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11369 (org-log-done org-log-done)
11370 (org-log-repeat org-log-repeat)
11371 (org-todo-log-states org-todo-log-states)
11372 (org-inhibit-logging
11373 (if (equal arg 0)
11374 (progn (setq arg nil) 'note) org-inhibit-logging))
11375 (this (match-string 1))
11376 (hl-pos (match-beginning 0))
11377 (head (org-get-todo-sequence-head this))
11378 (ass (assoc head org-todo-kwd-alist))
11379 (interpret (nth 1 ass))
11380 (done-word (nth 3 ass))
11381 (final-done-word (nth 4 ass))
11382 (org-last-state (or this ""))
11383 (completion-ignore-case t)
11384 (member (member this org-todo-keywords-1))
11385 (tail (cdr member))
11386 (org-state (cond
11387 ((and org-todo-key-trigger
11388 (or (and (equal arg '(4))
11389 (eq org-use-fast-todo-selection 'prefix))
11390 (and (not arg) org-use-fast-todo-selection
11391 (not (eq org-use-fast-todo-selection
11392 'prefix)))))
11393 ;; Use fast selection
11394 (org-fast-todo-selection))
11395 ((and (equal arg '(4))
11396 (or (not org-use-fast-todo-selection)
11397 (not org-todo-key-trigger)))
11398 ;; Read a state with completion
11399 (org-icompleting-read
11400 "State: " (mapcar (lambda(x) (list x))
11401 org-todo-keywords-1)
11402 nil t))
11403 ((eq arg 'right)
11404 (if this
11405 (if tail (car tail) nil)
11406 (car org-todo-keywords-1)))
11407 ((eq arg 'left)
11408 (if (equal member org-todo-keywords-1)
11410 (if this
11411 (nth (- (length org-todo-keywords-1)
11412 (length tail) 2)
11413 org-todo-keywords-1)
11414 (org-last org-todo-keywords-1))))
11415 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11416 (setq arg nil))) ; hack to fall back to cycling
11417 (arg
11418 ;; user or caller requests a specific state
11419 (cond
11420 ((equal arg "") nil)
11421 ((eq arg 'none) nil)
11422 ((eq arg 'done) (or done-word (car org-done-keywords)))
11423 ((eq arg 'nextset)
11424 (or (car (cdr (member head org-todo-heads)))
11425 (car org-todo-heads)))
11426 ((eq arg 'previousset)
11427 (let ((org-todo-heads (reverse org-todo-heads)))
11428 (or (car (cdr (member head org-todo-heads)))
11429 (car org-todo-heads))))
11430 ((car (member arg org-todo-keywords-1)))
11431 ((stringp arg)
11432 (error "State `%s' not valid in this file" arg))
11433 ((nth (1- (prefix-numeric-value arg))
11434 org-todo-keywords-1))))
11435 ((null member) (or head (car org-todo-keywords-1)))
11436 ((equal this final-done-word) nil) ;; -> make empty
11437 ((null tail) nil) ;; -> first entry
11438 ((memq interpret '(type priority))
11439 (if (eq this-command last-command)
11440 (car tail)
11441 (if (> (length tail) 0)
11442 (or done-word (car org-done-keywords))
11443 nil)))
11445 (car tail))))
11446 (org-state (or
11447 (run-hook-with-args-until-success
11448 'org-todo-get-default-hook org-state org-last-state)
11449 org-state))
11450 (next (if org-state (concat " " org-state " ") " "))
11451 (change-plist (list :type 'todo-state-change :from this :to org-state
11452 :position startpos))
11453 dolog now-done-p)
11454 (when org-blocker-hook
11455 (setq org-last-todo-state-is-todo
11456 (not (member this org-done-keywords)))
11457 (unless (save-excursion
11458 (save-match-data
11459 (org-with-wide-buffer
11460 (run-hook-with-args-until-failure
11461 'org-blocker-hook change-plist))))
11462 (if (org-called-interactively-p 'interactive)
11463 (error "TODO state change from %s to %s blocked" this org-state)
11464 ;; fail silently
11465 (message "TODO state change from %s to %s blocked" this org-state)
11466 (throw 'exit nil))))
11467 (store-match-data match-data)
11468 (replace-match next t t)
11469 (unless (pos-visible-in-window-p hl-pos)
11470 (message "TODO state changed to %s" (org-trim next)))
11471 (unless head
11472 (setq head (org-get-todo-sequence-head org-state)
11473 ass (assoc head org-todo-kwd-alist)
11474 interpret (nth 1 ass)
11475 done-word (nth 3 ass)
11476 final-done-word (nth 4 ass)))
11477 (when (memq arg '(nextset previousset))
11478 (message "Keyword-Set %d/%d: %s"
11479 (- (length org-todo-sets) -1
11480 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11481 (length org-todo-sets)
11482 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11483 (setq org-last-todo-state-is-todo
11484 (not (member org-state org-done-keywords)))
11485 (setq now-done-p (and (member org-state org-done-keywords)
11486 (not (member this org-done-keywords))))
11487 (and logging (org-local-logging logging))
11488 (when (and (or org-todo-log-states org-log-done)
11489 (not (eq org-inhibit-logging t))
11490 (not (memq arg '(nextset previousset))))
11491 ;; we need to look at recording a time and note
11492 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11493 (nth 2 (assoc this org-todo-log-states))))
11494 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11495 (setq dolog 'time))
11496 (when (and org-state
11497 (member org-state org-not-done-keywords)
11498 (not (member this org-not-done-keywords)))
11499 ;; This is now a todo state and was not one before
11500 ;; If there was a CLOSED time stamp, get rid of it.
11501 (org-add-planning-info nil nil 'closed))
11502 (when (and now-done-p org-log-done)
11503 ;; It is now done, and it was not done before
11504 (org-add-planning-info 'closed (org-current-effective-time))
11505 (if (and (not dolog) (eq 'note org-log-done))
11506 (org-add-log-setup 'done org-state this 'findpos 'note)))
11507 (when (and org-state dolog)
11508 ;; This is a non-nil state, and we need to log it
11509 (org-add-log-setup 'state org-state this 'findpos dolog)))
11510 ;; Fixup tag positioning
11511 (org-todo-trigger-tag-changes org-state)
11512 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11513 (when org-provide-todo-statistics
11514 (org-update-parent-todo-statistics))
11515 (run-hooks 'org-after-todo-state-change-hook)
11516 (if (and arg (not (member org-state org-done-keywords)))
11517 (setq head (org-get-todo-sequence-head org-state)))
11518 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11519 ;; Do we need to trigger a repeat?
11520 (when now-done-p
11521 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11522 ;; This is for the agenda, take a snapshot of the headline.
11523 (save-match-data
11524 (setq org-agenda-headline-snapshot-before-repeat
11525 (org-get-heading))))
11526 (org-auto-repeat-maybe org-state))
11527 ;; Fixup cursor location if close to the keyword
11528 (if (and (outline-on-heading-p)
11529 (not (bolp))
11530 (save-excursion (beginning-of-line 1)
11531 (looking-at org-todo-line-regexp))
11532 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11533 (progn
11534 (goto-char (or (match-end 2) (match-end 1)))
11535 (and (looking-at " ") (just-one-space))))
11536 (when org-trigger-hook
11537 (save-excursion
11538 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11540 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11541 "Block turning an entry into a TODO, using the hierarchy.
11542 This checks whether the current task should be blocked from state
11543 changes. Such blocking occurs when:
11545 1. The task has children which are not all in a completed state.
11547 2. A task has a parent with the property :ORDERED:, and there
11548 are siblings prior to the current task with incomplete
11549 status.
11551 3. The parent of the task is blocked because it has siblings that should
11552 be done first, or is child of a block grandparent TODO entry."
11554 (if (not org-enforce-todo-dependencies)
11555 t ; if locally turned off don't block
11556 (catch 'dont-block
11557 ;; If this is not a todo state change, or if this entry is already DONE,
11558 ;; do not block
11559 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11560 (member (plist-get change-plist :from)
11561 (cons 'done org-done-keywords))
11562 (member (plist-get change-plist :to)
11563 (cons 'todo org-not-done-keywords))
11564 (not (plist-get change-plist :to)))
11565 (throw 'dont-block t))
11566 ;; If this task has children, and any are undone, it's blocked
11567 (save-excursion
11568 (org-back-to-heading t)
11569 (let ((this-level (funcall outline-level)))
11570 (outline-next-heading)
11571 (let ((child-level (funcall outline-level)))
11572 (while (and (not (eobp))
11573 (> child-level this-level))
11574 ;; this todo has children, check whether they are all
11575 ;; completed
11576 (if (and (not (org-entry-is-done-p))
11577 (org-entry-is-todo-p))
11578 (throw 'dont-block nil))
11579 (outline-next-heading)
11580 (setq child-level (funcall outline-level))))))
11581 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11582 ;; any previous siblings are undone, it's blocked
11583 (save-excursion
11584 (org-back-to-heading t)
11585 (let* ((pos (point))
11586 (parent-pos (and (org-up-heading-safe) (point))))
11587 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11588 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11589 (forward-line 1)
11590 (re-search-forward org-not-done-heading-regexp pos t))
11591 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11592 ;; Search further up the hierarchy, to see if an ancestor is blocked
11593 (while t
11594 (goto-char parent-pos)
11595 (if (not (looking-at org-not-done-heading-regexp))
11596 (throw 'dont-block t)) ; do not block, parent is not a TODO
11597 (setq pos (point))
11598 (setq parent-pos (and (org-up-heading-safe) (point)))
11599 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11600 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11601 (forward-line 1)
11602 (re-search-forward org-not-done-heading-regexp pos t))
11603 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11605 (defcustom org-track-ordered-property-with-tag nil
11606 "Should the ORDERED property also be shown as a tag?
11607 The ORDERED property decides if an entry should require subtasks to be
11608 completed in sequence. Since a property is not very visible, setting
11609 this option means that toggling the ORDERED property with the command
11610 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11611 not relevant for the behavior, but it makes things more visible.
11613 Note that toggling the tag with tags commands will not change the property
11614 and therefore not influence behavior!
11616 This can be t, meaning the tag ORDERED should be used, It can also be a
11617 string to select a different tag for this task."
11618 :group 'org-todo
11619 :type '(choice
11620 (const :tag "No tracking" nil)
11621 (const :tag "Track with ORDERED tag" t)
11622 (string :tag "Use other tag")))
11624 (defun org-toggle-ordered-property ()
11625 "Toggle the ORDERED property of the current entry.
11626 For better visibility, you can track the value of this property with a tag.
11627 See variable `org-track-ordered-property-with-tag'."
11628 (interactive)
11629 (let* ((t1 org-track-ordered-property-with-tag)
11630 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11631 (save-excursion
11632 (org-back-to-heading)
11633 (if (org-entry-get nil "ORDERED")
11634 (progn
11635 (org-delete-property "ORDERED")
11636 (and tag (org-toggle-tag tag 'off))
11637 (message "Subtasks can be completed in arbitrary order"))
11638 (org-entry-put nil "ORDERED" "t")
11639 (and tag (org-toggle-tag tag 'on))
11640 (message "Subtasks must be completed in sequence")))))
11642 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11643 (defun org-block-todo-from-checkboxes (change-plist)
11644 "Block turning an entry into a TODO, using checkboxes.
11645 This checks whether the current task should be blocked from state
11646 changes because there are unchecked boxes in this entry."
11647 (if (not org-enforce-todo-checkbox-dependencies)
11648 t ; if locally turned off don't block
11649 (catch 'dont-block
11650 ;; If this is not a todo state change, or if this entry is already DONE,
11651 ;; do not block
11652 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11653 (member (plist-get change-plist :from)
11654 (cons 'done org-done-keywords))
11655 (member (plist-get change-plist :to)
11656 (cons 'todo org-not-done-keywords))
11657 (not (plist-get change-plist :to)))
11658 (throw 'dont-block t))
11659 ;; If this task has checkboxes that are not checked, it's blocked
11660 (save-excursion
11661 (org-back-to-heading t)
11662 (let ((beg (point)) end)
11663 (outline-next-heading)
11664 (setq end (point))
11665 (goto-char beg)
11666 (if (org-list-search-forward
11667 (concat (org-item-beginning-re)
11668 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11669 "\\[[- ]\\]")
11670 end t)
11671 (progn
11672 (if (boundp 'org-blocked-by-checkboxes)
11673 (setq org-blocked-by-checkboxes t))
11674 (throw 'dont-block nil)))))
11675 t))) ; do not block
11677 (defun org-entry-blocked-p ()
11678 "Is the current entry blocked?"
11679 (if (org-entry-get nil "NOBLOCKING")
11680 nil ;; Never block this entry
11681 (not
11682 (run-hook-with-args-until-failure
11683 'org-blocker-hook
11684 (list :type 'todo-state-change
11685 :position (point)
11686 :from 'todo
11687 :to 'done)))))
11689 (defun org-update-statistics-cookies (all)
11690 "Update the statistics cookie, either from TODO or from checkboxes.
11691 This should be called with the cursor in a line with a statistics cookie."
11692 (interactive "P")
11693 (if all
11694 (progn
11695 (org-update-checkbox-count 'all)
11696 (org-map-entries 'org-update-parent-todo-statistics))
11697 (if (not (org-at-heading-p))
11698 (org-update-checkbox-count)
11699 (let ((pos (move-marker (make-marker) (point)))
11700 end l1 l2)
11701 (ignore-errors (org-back-to-heading t))
11702 (if (not (org-at-heading-p))
11703 (org-update-checkbox-count)
11704 (setq l1 (org-outline-level))
11705 (setq end (save-excursion
11706 (outline-next-heading)
11707 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11708 (point)))
11709 (if (and (save-excursion
11710 (re-search-forward
11711 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11712 (not (save-excursion (re-search-forward
11713 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11714 (org-update-checkbox-count)
11715 (if (and l2 (> l2 l1))
11716 (progn
11717 (goto-char end)
11718 (org-update-parent-todo-statistics))
11719 (goto-char pos)
11720 (beginning-of-line 1)
11721 (while (re-search-forward
11722 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11723 (point-at-eol) t)
11724 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11725 (goto-char pos)
11726 (move-marker pos nil)))))
11728 (defvar org-entry-property-inherited-from) ;; defined below
11729 (defun org-update-parent-todo-statistics ()
11730 "Update any statistics cookie in the parent of the current headline.
11731 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11732 the entire subtree and this will travel up the hierarchy and update
11733 statistics everywhere."
11734 (let* ((prop (save-excursion (org-up-heading-safe)
11735 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11736 (recursive (or (not org-hierarchical-todo-statistics)
11737 (and prop (string-match "\\<recursive\\>" prop))))
11738 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11740 (first t)
11741 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11742 level ltoggle l1 new ndel
11743 (cnt-all 0) (cnt-done 0) is-percent kwd
11744 checkbox-beg ov ovs ove cookie-present)
11745 (catch 'exit
11746 (save-excursion
11747 (beginning-of-line 1)
11748 (setq ltoggle (funcall outline-level))
11749 ;; Three situations are to consider:
11751 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11752 ;; to the top-level ancestor on the headline;
11754 ;; 2. If parent has "recursive" property, repeat up to the
11755 ;; headline setting that property, taking inheritance into
11756 ;; account;
11758 ;; 3. Else, move up to direct parent and proceed only once.
11759 (while (and (setq level (org-up-heading-safe))
11760 (or recursive first)
11761 (>= (point) lim))
11762 (setq first nil cookie-present nil)
11763 (unless (and level
11764 (not (string-match
11765 "\\<checkbox\\>"
11766 (downcase (or (org-entry-get nil "COOKIE_DATA")
11767 "")))))
11768 (throw 'exit nil))
11769 (while (re-search-forward box-re (point-at-eol) t)
11770 (setq cnt-all 0 cnt-done 0 cookie-present t)
11771 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11772 (save-match-data
11773 (unless (outline-next-heading) (throw 'exit nil))
11774 (while (and (looking-at org-complex-heading-regexp)
11775 (> (setq l1 (length (match-string 1))) level))
11776 (setq kwd (and (or recursive (= l1 ltoggle))
11777 (match-string 2)))
11778 (if (or (eq org-provide-todo-statistics 'all-headlines)
11779 (and (listp org-provide-todo-statistics)
11780 (or (member kwd org-provide-todo-statistics)
11781 (member kwd org-done-keywords))))
11782 (setq cnt-all (1+ cnt-all))
11783 (if (eq org-provide-todo-statistics t)
11784 (and kwd (setq cnt-all (1+ cnt-all)))))
11785 (and (member kwd org-done-keywords)
11786 (setq cnt-done (1+ cnt-done)))
11787 (outline-next-heading)))
11788 (setq new
11789 (if is-percent
11790 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11791 (format "[%d/%d]" cnt-done cnt-all))
11792 ndel (- (match-end 0) checkbox-beg))
11793 ;; handle overlays when updating cookie from column view
11794 (when (setq ov (car (overlays-at checkbox-beg)))
11795 (setq ovs (overlay-start ov) ove (overlay-end ov))
11796 (delete-overlay ov))
11797 (goto-char checkbox-beg)
11798 (insert new)
11799 (delete-region (point) (+ (point) ndel))
11800 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11801 (when ov (move-overlay ov ovs ove)))
11802 (when cookie-present
11803 (run-hook-with-args 'org-after-todo-statistics-hook
11804 cnt-done (- cnt-all cnt-done))))))
11805 (run-hooks 'org-todo-statistics-hook)))
11807 (defvar org-after-todo-statistics-hook nil
11808 "Hook that is called after a TODO statistics cookie has been updated.
11809 Each function is called with two arguments: the number of not-done entries
11810 and the number of done entries.
11812 For example, the following function, when added to this hook, will switch
11813 an entry to DONE when all children are done, and back to TODO when new
11814 entries are set to a TODO status. Note that this hook is only called
11815 when there is a statistics cookie in the headline!
11817 (defun org-summary-todo (n-done n-not-done)
11818 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11819 (let (org-log-done org-log-states) ; turn off logging
11820 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11823 (defvar org-todo-statistics-hook nil
11824 "Hook that is run whenever Org thinks TODO statistics should be updated.
11825 This hook runs even if there is no statistics cookie present, in which case
11826 `org-after-todo-statistics-hook' would not run.")
11828 (defun org-todo-trigger-tag-changes (state)
11829 "Apply the changes defined in `org-todo-state-tags-triggers'."
11830 (let ((l org-todo-state-tags-triggers)
11831 changes)
11832 (when (or (not state) (equal state ""))
11833 (setq changes (append changes (cdr (assoc "" l)))))
11834 (when (and (stringp state) (> (length state) 0))
11835 (setq changes (append changes (cdr (assoc state l)))))
11836 (when (member state org-not-done-keywords)
11837 (setq changes (append changes (cdr (assoc 'todo l)))))
11838 (when (member state org-done-keywords)
11839 (setq changes (append changes (cdr (assoc 'done l)))))
11840 (dolist (c changes)
11841 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11843 (defun org-local-logging (value)
11844 "Get logging settings from a property VALUE."
11845 (let* (words w a)
11846 ;; directly set the variables, they are already local.
11847 (setq org-log-done nil
11848 org-log-repeat nil
11849 org-todo-log-states nil)
11850 (setq words (org-split-string value))
11851 (while (setq w (pop words))
11852 (cond
11853 ((setq a (assoc w org-startup-options))
11854 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11855 (set (nth 1 a) (nth 2 a))))
11856 ((setq a (org-extract-log-state-settings w))
11857 (and (member (car a) org-todo-keywords-1)
11858 (push a org-todo-log-states)))))))
11860 (defun org-get-todo-sequence-head (kwd)
11861 "Return the head of the TODO sequence to which KWD belongs.
11862 If KWD is not set, check if there is a text property remembering the
11863 right sequence."
11864 (let (p)
11865 (cond
11866 ((not kwd)
11867 (or (get-text-property (point-at-bol) 'org-todo-head)
11868 (progn
11869 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11870 nil (point-at-eol)))
11871 (get-text-property p 'org-todo-head))))
11872 ((not (member kwd org-todo-keywords-1))
11873 (car org-todo-keywords-1))
11874 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11876 (defun org-fast-todo-selection ()
11877 "Fast TODO keyword selection with single keys.
11878 Returns the new TODO keyword, or nil if no state change should occur."
11879 (let* ((fulltable org-todo-key-alist)
11880 (done-keywords org-done-keywords) ;; needed for the faces.
11881 (maxlen (apply 'max (mapcar
11882 (lambda (x)
11883 (if (stringp (car x)) (string-width (car x)) 0))
11884 fulltable)))
11885 (expert nil)
11886 (fwidth (+ maxlen 3 1 3))
11887 (ncol (/ (- (window-width) 4) fwidth))
11888 tg cnt e c tbl
11889 groups ingroup)
11890 (save-excursion
11891 (save-window-excursion
11892 (if expert
11893 (set-buffer (get-buffer-create " *Org todo*"))
11894 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11895 (erase-buffer)
11896 (org-set-local 'org-done-keywords done-keywords)
11897 (setq tbl fulltable cnt 0)
11898 (while (setq e (pop tbl))
11899 (cond
11900 ((equal e '(:startgroup))
11901 (push '() groups) (setq ingroup t)
11902 (when (not (= cnt 0))
11903 (setq cnt 0)
11904 (insert "\n"))
11905 (insert "{ "))
11906 ((equal e '(:endgroup))
11907 (setq ingroup nil cnt 0)
11908 (insert "}\n"))
11909 ((equal e '(:newline))
11910 (when (not (= cnt 0))
11911 (setq cnt 0)
11912 (insert "\n")
11913 (setq e (car tbl))
11914 (while (equal (car tbl) '(:newline))
11915 (insert "\n")
11916 (setq tbl (cdr tbl)))))
11918 (setq tg (car e) c (cdr e))
11919 (if ingroup (push tg (car groups)))
11920 (setq tg (org-add-props tg nil 'face
11921 (org-get-todo-face tg)))
11922 (if (and (= cnt 0) (not ingroup)) (insert " "))
11923 (insert "[" c "] " tg (make-string
11924 (- fwidth 4 (length tg)) ?\ ))
11925 (when (= (setq cnt (1+ cnt)) ncol)
11926 (insert "\n")
11927 (if ingroup (insert " "))
11928 (setq cnt 0)))))
11929 (insert "\n")
11930 (goto-char (point-min))
11931 (if (not expert) (org-fit-window-to-buffer))
11932 (message "[a-z..]:Set [SPC]:clear")
11933 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11934 (cond
11935 ((or (= c ?\C-g)
11936 (and (= c ?q) (not (rassoc c fulltable))))
11937 (setq quit-flag t))
11938 ((= c ?\ ) nil)
11939 ((setq e (rassoc c fulltable) tg (car e))
11941 (t (setq quit-flag t)))))))
11943 (defun org-entry-is-todo-p ()
11944 (member (org-get-todo-state) org-not-done-keywords))
11946 (defun org-entry-is-done-p ()
11947 (member (org-get-todo-state) org-done-keywords))
11949 (defun org-get-todo-state ()
11950 (save-excursion
11951 (org-back-to-heading t)
11952 (and (looking-at org-todo-line-regexp)
11953 (match-end 2)
11954 (match-string 2))))
11956 (defun org-at-date-range-p (&optional inactive-ok)
11957 "Is the cursor inside a date range?"
11958 (interactive)
11959 (save-excursion
11960 (catch 'exit
11961 (let ((pos (point)))
11962 (skip-chars-backward "^[<\r\n")
11963 (skip-chars-backward "<[")
11964 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11965 (>= (match-end 0) pos)
11966 (throw 'exit t))
11967 (skip-chars-backward "^<[\r\n")
11968 (skip-chars-backward "<[")
11969 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11970 (>= (match-end 0) pos)
11971 (throw 'exit t)))
11972 nil)))
11974 (defun org-get-repeat (&optional tagline)
11975 "Check if there is a deadline/schedule with repeater in this entry."
11976 (save-match-data
11977 (save-excursion
11978 (org-back-to-heading t)
11979 (and (re-search-forward (if tagline
11980 (concat tagline "\\s-*" org-repeat-re)
11981 org-repeat-re)
11982 (org-entry-end-position) t)
11983 (match-string-no-properties 1)))))
11985 (defvar org-last-changed-timestamp)
11986 (defvar org-last-inserted-timestamp)
11987 (defvar org-log-post-message)
11988 (defvar org-log-note-purpose)
11989 (defvar org-log-note-how)
11990 (defvar org-log-note-extra)
11991 (defun org-auto-repeat-maybe (done-word)
11992 "Check if the current headline contains a repeated deadline/schedule.
11993 If yes, set TODO state back to what it was and change the base date
11994 of repeating deadline/scheduled time stamps to new date.
11995 This function is run automatically after each state change to a DONE state."
11996 ;; last-state is dynamically scoped into this function
11997 (let* ((repeat (org-get-repeat))
11998 (aa (assoc org-last-state org-todo-kwd-alist))
11999 (interpret (nth 1 aa))
12000 (head (nth 2 aa))
12001 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12002 (msg "Entry repeats: ")
12003 (org-log-done nil)
12004 (org-todo-log-states nil)
12005 re type n what ts time to-state)
12006 (when repeat
12007 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12008 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12009 org-todo-repeat-to-state))
12010 (unless (and to-state (member to-state org-todo-keywords-1))
12011 (setq to-state (if (eq interpret 'type) org-last-state head)))
12012 (org-todo to-state)
12013 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12014 (org-entry-put nil "LAST_REPEAT" (format-time-string
12015 (org-time-stamp-format t t))))
12016 (when org-log-repeat
12017 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12018 (memq 'org-add-log-note post-command-hook))
12019 ;; OK, we are already setup for some record
12020 (if (eq org-log-repeat 'note)
12021 ;; make sure we take a note, not only a time stamp
12022 (setq org-log-note-how 'note))
12023 ;; Set up for taking a record
12024 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12025 org-last-state
12026 'findpos org-log-repeat)))
12027 (org-back-to-heading t)
12028 (org-add-planning-info nil nil 'closed)
12029 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12030 org-deadline-time-regexp "\\)\\|\\("
12031 org-ts-regexp "\\)"))
12032 (while (re-search-forward
12033 re (save-excursion (outline-next-heading) (point)) t)
12034 (setq type (if (match-end 1) org-scheduled-string
12035 (if (match-end 3) org-deadline-string "Plain:"))
12036 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12037 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12038 (setq n (string-to-number (match-string 2 ts))
12039 what (match-string 3 ts))
12040 (if (equal what "w") (setq n (* n 7) what "d"))
12041 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12042 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12043 ;; Preparation, see if we need to modify the start date for the change
12044 (when (match-end 1)
12045 (setq time (save-match-data (org-time-string-to-time ts)))
12046 (cond
12047 ((equal (match-string 1 ts) ".")
12048 ;; Shift starting date to today
12049 (org-timestamp-change
12050 (- (org-today) (time-to-days time))
12051 'day))
12052 ((equal (match-string 1 ts) "+")
12053 (let ((nshiftmax 10) (nshift 0))
12054 (while (or (= nshift 0)
12055 (<= (time-to-days time)
12056 (time-to-days (current-time))))
12057 (when (= (incf nshift) nshiftmax)
12058 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12059 (error "Abort")))
12060 (org-timestamp-change n (cdr (assoc what whata)))
12061 (org-at-timestamp-p t)
12062 (setq ts (match-string 1))
12063 (setq time (save-match-data (org-time-string-to-time ts)))))
12064 (org-timestamp-change (- n) (cdr (assoc what whata)))
12065 ;; rematch, so that we have everything in place for the real shift
12066 (org-at-timestamp-p t)
12067 (setq ts (match-string 1))
12068 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12069 (org-timestamp-change n (cdr (assoc what whata)))
12070 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12071 (setq org-log-post-message msg)
12072 (message "%s" msg))))
12074 (defun org-show-todo-tree (arg)
12075 "Make a compact tree which shows all headlines marked with TODO.
12076 The tree will show the lines where the regexp matches, and all higher
12077 headlines above the match.
12078 With a \\[universal-argument] prefix, prompt for a regexp to match.
12079 With a numeric prefix N, construct a sparse tree for the Nth element
12080 of `org-todo-keywords-1'."
12081 (interactive "P")
12082 (let ((case-fold-search nil)
12083 (kwd-re
12084 (cond ((null arg) org-not-done-regexp)
12085 ((equal arg '(4))
12086 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12087 (mapcar 'list org-todo-keywords-1))))
12088 (concat "\\("
12089 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12090 "\\)\\>")))
12091 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12092 (regexp-quote (nth (1- (prefix-numeric-value arg))
12093 org-todo-keywords-1)))
12094 (t (error "Invalid prefix argument: %s" arg)))))
12095 (message "%d TODO entries found"
12096 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12098 (defun org-deadline (&optional remove time)
12099 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12100 With argument REMOVE, remove any deadline from the item.
12101 With argument TIME, set the deadline at the corresponding date. TIME
12102 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12103 (interactive "P")
12104 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12105 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12106 'region-start-level 'region))
12107 org-loop-over-headlines-in-active-region)
12108 (org-map-entries
12109 `(org-deadline ',remove ,time)
12110 org-loop-over-headlines-in-active-region
12111 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12112 (let* ((old-date (org-entry-get nil "DEADLINE"))
12113 (repeater (and old-date
12114 (string-match
12115 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12116 old-date)
12117 (match-string 1 old-date))))
12118 (if remove
12119 (progn
12120 (when (and old-date org-log-redeadline)
12121 (org-add-log-setup 'deldeadline nil old-date 'findpos
12122 org-log-redeadline))
12123 (org-remove-timestamp-with-keyword org-deadline-string)
12124 (message "Item no longer has a deadline."))
12125 (org-add-planning-info 'deadline time 'closed)
12126 (when (and old-date org-log-redeadline
12127 (not (equal old-date
12128 (substring org-last-inserted-timestamp 1 -1))))
12129 (org-add-log-setup 'redeadline nil old-date 'findpos
12130 org-log-redeadline))
12131 (when repeater
12132 (save-excursion
12133 (org-back-to-heading t)
12134 (when (re-search-forward (concat org-deadline-string " "
12135 org-last-inserted-timestamp)
12136 (save-excursion
12137 (outline-next-heading) (point)) t)
12138 (goto-char (1- (match-end 0)))
12139 (insert " " repeater)
12140 (setq org-last-inserted-timestamp
12141 (concat (substring org-last-inserted-timestamp 0 -1)
12142 " " repeater
12143 (substring org-last-inserted-timestamp -1))))))
12144 (message "Deadline on %s" org-last-inserted-timestamp)))))
12146 (defun org-schedule (&optional remove time)
12147 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12148 With argument REMOVE, remove any scheduling date from the item.
12149 With argument TIME, scheduled at the corresponding date. TIME can
12150 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12151 (interactive "P")
12152 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12153 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12154 'region-start-level 'region))
12155 org-loop-over-headlines-in-active-region)
12156 (org-map-entries
12157 `(org-schedule ',remove ,time)
12158 org-loop-over-headlines-in-active-region
12159 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12160 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12161 (repeater (and old-date
12162 (string-match
12163 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12164 old-date)
12165 (match-string 1 old-date))))
12166 (if remove
12167 (progn
12168 (when (and old-date org-log-reschedule)
12169 (org-add-log-setup 'delschedule nil old-date 'findpos
12170 org-log-reschedule))
12171 (org-remove-timestamp-with-keyword org-scheduled-string)
12172 (message "Item is no longer scheduled."))
12173 (org-add-planning-info 'scheduled time 'closed)
12174 (when (and old-date org-log-reschedule
12175 (not (equal old-date
12176 (substring org-last-inserted-timestamp 1 -1))))
12177 (org-add-log-setup 'reschedule nil old-date 'findpos
12178 org-log-reschedule))
12179 (when repeater
12180 (save-excursion
12181 (org-back-to-heading t)
12182 (when (re-search-forward (concat org-scheduled-string " "
12183 org-last-inserted-timestamp)
12184 (save-excursion
12185 (outline-next-heading) (point)) t)
12186 (goto-char (1- (match-end 0)))
12187 (insert " " repeater)
12188 (setq org-last-inserted-timestamp
12189 (concat (substring org-last-inserted-timestamp 0 -1)
12190 " " repeater
12191 (substring org-last-inserted-timestamp -1))))))
12192 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12194 (defun org-get-scheduled-time (pom &optional inherit)
12195 "Get the scheduled time as a time tuple, of a format suitable
12196 for calling org-schedule with, or if there is no scheduling,
12197 returns nil."
12198 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12199 (when time
12200 (apply 'encode-time (org-parse-time-string time)))))
12202 (defun org-get-deadline-time (pom &optional inherit)
12203 "Get the deadline as a time tuple, of a format suitable for
12204 calling org-deadline with, or if there is no scheduling, returns
12205 nil."
12206 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12207 (when time
12208 (apply 'encode-time (org-parse-time-string time)))))
12210 (defun org-remove-timestamp-with-keyword (keyword)
12211 "Remove all time stamps with KEYWORD in the current entry."
12212 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12213 beg)
12214 (save-excursion
12215 (org-back-to-heading t)
12216 (setq beg (point))
12217 (outline-next-heading)
12218 (while (re-search-backward re beg t)
12219 (replace-match "")
12220 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12221 (equal (char-before) ?\ ))
12222 (backward-delete-char 1)
12223 (if (string-match "^[ \t]*$" (buffer-substring
12224 (point-at-bol) (point-at-eol)))
12225 (delete-region (point-at-bol)
12226 (min (point-max) (1+ (point-at-eol))))))))))
12228 (defun org-add-planning-info (what &optional time &rest remove)
12229 "Insert new timestamp with keyword in the line directly after the headline.
12230 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12231 If non is given, the user is prompted for a date.
12232 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12233 be removed."
12234 (interactive)
12235 (let (org-time-was-given org-end-time-was-given ts
12236 end default-time default-input)
12238 (catch 'exit
12239 (when (and (memq what '(scheduled deadline))
12240 (or (not time)
12241 (and (stringp time)
12242 (string-match "^[-+]+[0-9]" time))))
12243 ;; Try to get a default date/time from existing timestamp
12244 (save-excursion
12245 (org-back-to-heading t)
12246 (setq end (save-excursion (outline-next-heading) (point)))
12247 (when (re-search-forward (if (eq what 'scheduled)
12248 org-scheduled-time-regexp
12249 org-deadline-time-regexp)
12250 end t)
12251 (setq ts (match-string 1)
12252 default-time
12253 (apply 'encode-time (org-parse-time-string ts))
12254 default-input (and ts (org-get-compact-tod ts))))))
12255 (when what
12256 (setq time
12257 (if (stringp time)
12258 ;; This is a string (relative or absolute), set proper date
12259 (apply 'encode-time
12260 (org-read-date-analyze
12261 time default-time (decode-time default-time)))
12262 ;; If necessary, get the time from the user
12263 (or time (org-read-date nil 'to-time nil nil
12264 default-time default-input)))))
12266 (when (and org-insert-labeled-timestamps-at-point
12267 (member what '(scheduled deadline)))
12268 (insert
12269 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12270 (org-insert-time-stamp time org-time-was-given
12271 nil nil nil (list org-end-time-was-given))
12272 (setq what nil))
12273 (save-excursion
12274 (save-restriction
12275 (let (col list elt ts buffer-invisibility-spec)
12276 (org-back-to-heading t)
12277 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12278 (goto-char (match-end 1))
12279 (setq col (current-column))
12280 (goto-char (match-end 0))
12281 (if (eobp) (insert "\n") (forward-char 1))
12282 (when (and (not what)
12283 (not (looking-at
12284 (concat "[ \t]*"
12285 org-keyword-time-not-clock-regexp))))
12286 ;; Nothing to add, nothing to remove...... :-)
12287 (throw 'exit nil))
12288 (if (and (not (looking-at org-outline-regexp))
12289 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12290 "[^\r\n]*"))
12291 (not (equal (match-string 1) org-clock-string)))
12292 (narrow-to-region (match-beginning 0) (match-end 0))
12293 (insert-before-markers "\n")
12294 (backward-char 1)
12295 (narrow-to-region (point) (point))
12296 (and org-adapt-indentation (org-indent-to-column col)))
12297 ;; Check if we have to remove something.
12298 (setq list (cons what remove))
12299 (while list
12300 (setq elt (pop list))
12301 (when (or (and (eq elt 'scheduled)
12302 (re-search-forward org-scheduled-time-regexp nil t))
12303 (and (eq elt 'deadline)
12304 (re-search-forward org-deadline-time-regexp nil t))
12305 (and (eq elt 'closed)
12306 (re-search-forward org-closed-time-regexp nil t)))
12307 (replace-match "")
12308 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12309 (and (looking-at "[ \t]+") (replace-match ""))
12310 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12311 (when what
12312 (insert
12313 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12314 (cond ((eq what 'scheduled) org-scheduled-string)
12315 ((eq what 'deadline) org-deadline-string)
12316 ((eq what 'closed) org-closed-string))
12317 " ")
12318 (setq ts (org-insert-time-stamp
12319 time
12320 (or org-time-was-given
12321 (and (eq what 'closed) org-log-done-with-time))
12322 (eq what 'closed)
12323 nil nil (list org-end-time-was-given)))
12324 (insert
12325 (if (not (or (bolp) (eq (char-before) ?\ )
12326 (memq (char-after) '(32 10))
12327 (eobp))) " " ""))
12328 (end-of-line 1))
12329 (goto-char (point-min))
12330 (widen)
12331 (if (and (looking-at "[ \t]*\n")
12332 (equal (char-before) ?\n))
12333 (delete-region (1- (point)) (point-at-eol)))
12334 ts))))))
12336 (defvar org-log-note-marker (make-marker))
12337 (defvar org-log-note-purpose nil)
12338 (defvar org-log-note-state nil)
12339 (defvar org-log-note-previous-state nil)
12340 (defvar org-log-note-how nil)
12341 (defvar org-log-note-extra nil)
12342 (defvar org-log-note-window-configuration nil)
12343 (defvar org-log-note-return-to (make-marker))
12344 (defvar org-log-note-effective-time nil
12345 "Remembered current time so that dynamically scoped
12346 `org-extend-today-until' affects tha timestamps in state change
12347 log")
12349 (defvar org-log-post-message nil
12350 "Message to be displayed after a log note has been stored.
12351 The auto-repeater uses this.")
12353 (defun org-add-note ()
12354 "Add a note to the current entry.
12355 This is done in the same way as adding a state change note."
12356 (interactive)
12357 (org-add-log-setup 'note nil nil 'findpos nil))
12359 (defvar org-property-end-re)
12360 (defun org-add-log-setup (&optional purpose state prev-state
12361 findpos how extra)
12362 "Set up the post command hook to take a note.
12363 If this is about to TODO state change, the new state is expected in STATE.
12364 When FINDPOS is non-nil, find the correct position for the note in
12365 the current entry. If not, assume that it can be inserted at point.
12366 HOW is an indicator what kind of note should be created.
12367 EXTRA is additional text that will be inserted into the notes buffer."
12368 (let* ((org-log-into-drawer (org-log-into-drawer))
12369 (drawer (cond ((stringp org-log-into-drawer)
12370 org-log-into-drawer)
12371 (org-log-into-drawer "LOGBOOK")
12372 (t nil))))
12373 (save-restriction
12374 (save-excursion
12375 (when findpos
12376 (org-back-to-heading t)
12377 (narrow-to-region (point) (save-excursion
12378 (outline-next-heading) (point)))
12379 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12380 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12381 "[^\r\n]*\\)?"))
12382 (goto-char (match-end 0))
12383 (cond
12384 (drawer
12385 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12386 nil t)
12387 (progn
12388 (goto-char (match-end 0))
12389 (or org-log-states-order-reversed
12390 (and (re-search-forward org-property-end-re nil t)
12391 (goto-char (1- (match-beginning 0))))))
12392 (insert "\n:" drawer ":\n:END:")
12393 (beginning-of-line 0)
12394 (org-indent-line-function)
12395 (beginning-of-line 2)
12396 (org-indent-line-function)
12397 (end-of-line 0)))
12398 ((and org-log-state-notes-insert-after-drawers
12399 (save-excursion
12400 (forward-line) (looking-at org-drawer-regexp)))
12401 (forward-line)
12402 (while (looking-at org-drawer-regexp)
12403 (goto-char (match-end 0))
12404 (re-search-forward org-property-end-re (point-max) t)
12405 (forward-line))
12406 (forward-line -1)))
12407 (unless org-log-states-order-reversed
12408 (and (= (char-after) ?\n) (forward-char 1))
12409 (org-skip-over-state-notes)
12410 (skip-chars-backward " \t\n\r")))
12411 (move-marker org-log-note-marker (point))
12412 (setq org-log-note-purpose purpose
12413 org-log-note-state state
12414 org-log-note-previous-state prev-state
12415 org-log-note-how how
12416 org-log-note-extra extra
12417 org-log-note-effective-time (org-current-effective-time))
12418 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12420 (defun org-skip-over-state-notes ()
12421 "Skip past the list of State notes in an entry."
12422 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12423 (when (ignore-errors (goto-char (org-in-item-p)))
12424 (let* ((struct (org-list-struct))
12425 (prevs (org-list-prevs-alist struct)))
12426 (while (looking-at "[ \t]*- State")
12427 (goto-char (or (org-list-get-next-item (point) struct prevs)
12428 (org-list-get-item-end (point) struct)))))))
12430 (defun org-add-log-note (&optional purpose)
12431 "Pop up a window for taking a note, and add this note later at point."
12432 (remove-hook 'post-command-hook 'org-add-log-note)
12433 (setq org-log-note-window-configuration (current-window-configuration))
12434 (delete-other-windows)
12435 (move-marker org-log-note-return-to (point))
12436 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12437 (goto-char org-log-note-marker)
12438 (org-switch-to-buffer-other-window "*Org Note*")
12439 (erase-buffer)
12440 (if (memq org-log-note-how '(time state))
12441 (let (current-prefix-arg) (org-store-log-note))
12442 (let ((org-inhibit-startup t)) (org-mode))
12443 (insert (format "# Insert note for %s.
12444 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12445 (cond
12446 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12447 ((eq org-log-note-purpose 'done) "closed todo item")
12448 ((eq org-log-note-purpose 'state)
12449 (format "state change from \"%s\" to \"%s\""
12450 (or org-log-note-previous-state "")
12451 (or org-log-note-state "")))
12452 ((eq org-log-note-purpose 'reschedule)
12453 "rescheduling")
12454 ((eq org-log-note-purpose 'delschedule)
12455 "no longer scheduled")
12456 ((eq org-log-note-purpose 'redeadline)
12457 "changing deadline")
12458 ((eq org-log-note-purpose 'deldeadline)
12459 "removing deadline")
12460 ((eq org-log-note-purpose 'refile)
12461 "refiling")
12462 ((eq org-log-note-purpose 'note)
12463 "this entry")
12464 (t (error "This should not happen")))))
12465 (if org-log-note-extra (insert org-log-note-extra))
12466 (org-set-local 'org-finish-function 'org-store-log-note)
12467 (run-hooks 'org-log-buffer-setup-hook)))
12469 (defvar org-note-abort nil) ; dynamically scoped
12470 (defun org-store-log-note ()
12471 "Finish taking a log note, and insert it to where it belongs."
12472 (let ((txt (buffer-string))
12473 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12474 lines ind bul)
12475 (kill-buffer (current-buffer))
12476 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12477 (setq txt (replace-match "" t t txt)))
12478 (if (string-match "\\s-+\\'" txt)
12479 (setq txt (replace-match "" t t txt)))
12480 (setq lines (org-split-string txt "\n"))
12481 (when (and note (string-match "\\S-" note))
12482 (setq note
12483 (org-replace-escapes
12484 note
12485 (list (cons "%u" (user-login-name))
12486 (cons "%U" user-full-name)
12487 (cons "%t" (format-time-string
12488 (org-time-stamp-format 'long 'inactive)
12489 org-log-note-effective-time))
12490 (cons "%T" (format-time-string
12491 (org-time-stamp-format 'long nil)
12492 org-log-note-effective-time))
12493 (cons "%d" (format-time-string
12494 (org-time-stamp-format nil 'inactive)
12495 org-log-note-effective-time))
12496 (cons "%D" (format-time-string
12497 (org-time-stamp-format nil nil)
12498 org-log-note-effective-time))
12499 (cons "%s" (if org-log-note-state
12500 (concat "\"" org-log-note-state "\"")
12501 ""))
12502 (cons "%S" (if org-log-note-previous-state
12503 (concat "\"" org-log-note-previous-state "\"")
12504 "\"\"")))))
12505 (if lines (setq note (concat note " \\\\")))
12506 (push note lines))
12507 (when (or current-prefix-arg org-note-abort)
12508 (when org-log-into-drawer
12509 (org-remove-empty-drawer-at
12510 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12511 org-log-note-marker))
12512 (setq lines nil))
12513 (when lines
12514 (with-current-buffer (marker-buffer org-log-note-marker)
12515 (save-excursion
12516 (goto-char org-log-note-marker)
12517 (move-marker org-log-note-marker nil)
12518 (end-of-line 1)
12519 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12520 (setq ind (save-excursion
12521 (if (ignore-errors (goto-char (org-in-item-p)))
12522 (let ((struct (org-list-struct)))
12523 (org-list-get-ind
12524 (org-list-get-top-point struct) struct))
12525 (skip-chars-backward " \r\t\n")
12526 (cond
12527 ((and (org-at-heading-p)
12528 org-adapt-indentation)
12529 (1+ (org-current-level)))
12530 ((org-at-heading-p) 0)
12531 (t (org-get-indentation))))))
12532 (setq bul (org-list-bullet-string "-"))
12533 (org-indent-line-to ind)
12534 (insert bul (pop lines))
12535 (let ((ind-body (+ (length bul) ind)))
12536 (while lines
12537 (insert "\n")
12538 (org-indent-line-to ind-body)
12539 (insert (pop lines))))
12540 (message "Note stored")
12541 (org-back-to-heading t)
12542 (org-cycle-hide-drawers 'children)))))
12543 (set-window-configuration org-log-note-window-configuration)
12544 (with-current-buffer (marker-buffer org-log-note-return-to)
12545 (goto-char org-log-note-return-to))
12546 (move-marker org-log-note-return-to nil)
12547 (and org-log-post-message (message "%s" org-log-post-message)))
12549 (defun org-remove-empty-drawer-at (drawer pos)
12550 "Remove an empty drawer DRAWER at position POS.
12551 POS may also be a marker."
12552 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12553 (save-excursion
12554 (save-restriction
12555 (widen)
12556 (goto-char pos)
12557 (if (org-in-regexp
12558 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12559 (replace-match ""))))))
12561 (defun org-sparse-tree (&optional arg)
12562 "Create a sparse tree, prompt for the details.
12563 This command can create sparse trees. You first need to select the type
12564 of match used to create the tree:
12566 t Show all TODO entries.
12567 T Show entries with a specific TODO keyword.
12568 m Show entries selected by a tags/property match.
12569 p Enter a property name and its value (both with completion on existing
12570 names/values) and show entries with that property.
12571 r Show entries matching a regular expression (`/' can be used as well)
12572 d Show deadlines due within `org-deadline-warning-days'.
12573 b Show deadlines and scheduled items before a date.
12574 a Show deadlines and scheduled items after a date."
12575 (interactive "P")
12576 (let (ans kwd value)
12577 (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")
12578 (setq ans (read-char-exclusive))
12579 (cond
12580 ((equal ans ?d)
12581 (call-interactively 'org-check-deadlines))
12582 ((equal ans ?b)
12583 (call-interactively 'org-check-before-date))
12584 ((equal ans ?a)
12585 (call-interactively 'org-check-after-date))
12586 ((equal ans ?D)
12587 (call-interactively 'org-check-dates-range))
12588 ((equal ans ?t)
12589 (org-show-todo-tree nil))
12590 ((equal ans ?T)
12591 (org-show-todo-tree '(4)))
12592 ((member ans '(?T ?m))
12593 (call-interactively 'org-match-sparse-tree))
12594 ((member ans '(?p ?P))
12595 (setq kwd (org-icompleting-read "Property: "
12596 (mapcar 'list (org-buffer-property-keys))))
12597 (setq value (org-icompleting-read "Value: "
12598 (mapcar 'list (org-property-values kwd))))
12599 (unless (string-match "\\`{.*}\\'" value)
12600 (setq value (concat "\"" value "\"")))
12601 (org-match-sparse-tree arg (concat kwd "=" value)))
12602 ((member ans '(?r ?R ?/))
12603 (call-interactively 'org-occur))
12604 (t (error "No such sparse tree command \"%c\"" ans)))))
12606 (defvar org-occur-highlights nil
12607 "List of overlays used for occur matches.")
12608 (make-variable-buffer-local 'org-occur-highlights)
12609 (defvar org-occur-parameters nil
12610 "Parameters of the active org-occur calls.
12611 This is a list, each call to org-occur pushes as cons cell,
12612 containing the regular expression and the callback, onto the list.
12613 The list can contain several entries if `org-occur' has been called
12614 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12615 will only contain one set of parameters. When the highlights are
12616 removed (for example with `C-c C-c', or with the next edit (depending
12617 on `org-remove-highlights-with-change'), this variable is emptied
12618 as well.")
12619 (make-variable-buffer-local 'org-occur-parameters)
12621 (defun org-occur (regexp &optional keep-previous callback)
12622 "Make a compact tree which shows all matches of REGEXP.
12623 The tree will show the lines where the regexp matches, and all higher
12624 headlines above the match. It will also show the heading after the match,
12625 to make sure editing the matching entry is easy.
12626 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12627 call to `org-occur' will be kept, to allow stacking of calls to this
12628 command.
12629 If CALLBACK is non-nil, it is a function which is called to confirm
12630 that the match should indeed be shown."
12631 (interactive "sRegexp: \nP")
12632 (when (equal regexp "")
12633 (error "Regexp cannot be empty"))
12634 (unless keep-previous
12635 (org-remove-occur-highlights nil nil t))
12636 (push (cons regexp callback) org-occur-parameters)
12637 (let ((cnt 0))
12638 (save-excursion
12639 (goto-char (point-min))
12640 (if (or (not keep-previous) ; do not want to keep
12641 (not org-occur-highlights)) ; no previous matches
12642 ;; hide everything
12643 (org-overview))
12644 (while (re-search-forward regexp nil t)
12645 (when (or (not callback)
12646 (save-match-data (funcall callback)))
12647 (setq cnt (1+ cnt))
12648 (when org-highlight-sparse-tree-matches
12649 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12650 (org-show-context 'occur-tree))))
12651 (when org-remove-highlights-with-change
12652 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12653 nil 'local))
12654 (unless org-sparse-tree-open-archived-trees
12655 (org-hide-archived-subtrees (point-min) (point-max)))
12656 (run-hooks 'org-occur-hook)
12657 (if (org-called-interactively-p 'interactive)
12658 (message "%d match(es) for regexp %s" cnt regexp))
12659 cnt))
12661 (defun org-occur-next-match (&optional n reset)
12662 "Function for `next-error-function' to find sparse tree matches.
12663 N is the number of matches to move, when negative move backwards.
12664 RESET is entirely ignored - this function always goes back to the
12665 starting point when no match is found."
12666 (let* ((limit (if (< n 0) (point-min) (point-max)))
12667 (search-func (if (< n 0)
12668 'previous-single-char-property-change
12669 'next-single-char-property-change))
12670 (n (abs n))
12671 (pos (point))
12673 (catch 'exit
12674 (while (setq p1 (funcall search-func (point) 'org-type))
12675 (when (equal p1 limit)
12676 (goto-char pos)
12677 (error "No more matches"))
12678 (when (equal (get-char-property p1 'org-type) 'org-occur)
12679 (setq n (1- n))
12680 (when (= n 0)
12681 (goto-char p1)
12682 (throw 'exit (point))))
12683 (goto-char p1))
12684 (goto-char p1)
12685 (error "No more matches"))))
12687 (defun org-show-context (&optional key)
12688 "Make sure point and context are visible.
12689 How much context is shown depends upon the variables
12690 `org-show-hierarchy-above', `org-show-following-heading',
12691 `org-show-entry-below' and `org-show-siblings'."
12692 (let ((heading-p (org-at-heading-p t))
12693 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12694 (following-p (org-get-alist-option org-show-following-heading key))
12695 (entry-p (org-get-alist-option org-show-entry-below key))
12696 (siblings-p (org-get-alist-option org-show-siblings key)))
12697 (catch 'exit
12698 ;; Show heading or entry text
12699 (if (and heading-p (not entry-p))
12700 (org-flag-heading nil) ; only show the heading
12701 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12702 (org-show-hidden-entry))) ; show entire entry
12703 (when following-p
12704 ;; Show next sibling, or heading below text
12705 (save-excursion
12706 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12707 (org-flag-heading nil))))
12708 (when siblings-p (org-show-siblings))
12709 (when hierarchy-p
12710 ;; show all higher headings, possibly with siblings
12711 (save-excursion
12712 (while (and (condition-case nil
12713 (progn (org-up-heading-all 1) t)
12714 (error nil))
12715 (not (bobp)))
12716 (org-flag-heading nil)
12717 (when siblings-p (org-show-siblings))))))))
12719 (defvar org-reveal-start-hook nil
12720 "Hook run before revealing a location.")
12722 (defun org-reveal (&optional siblings)
12723 "Show current entry, hierarchy above it, and the following headline.
12724 This can be used to show a consistent set of context around locations
12725 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12726 not t for the search context.
12728 With optional argument SIBLINGS, on each level of the hierarchy all
12729 siblings are shown. This repairs the tree structure to what it would
12730 look like when opened with hierarchical calls to `org-cycle'.
12731 With double optional argument \\[universal-argument] \\[universal-argument], \
12732 go to the parent and show the
12733 entire tree."
12734 (interactive "P")
12735 (run-hooks 'org-reveal-start-hook)
12736 (let ((org-show-hierarchy-above t)
12737 (org-show-following-heading t)
12738 (org-show-siblings (if siblings t org-show-siblings)))
12739 (org-show-context nil))
12740 (when (equal siblings '(16))
12741 (save-excursion
12742 (when (org-up-heading-safe)
12743 (org-show-subtree)
12744 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12746 (defun org-highlight-new-match (beg end)
12747 "Highlight from BEG to END and mark the highlight is an occur headline."
12748 (let ((ov (make-overlay beg end)))
12749 (overlay-put ov 'face 'secondary-selection)
12750 (overlay-put ov 'org-type 'org-occur)
12751 (push ov org-occur-highlights)))
12753 (defun org-remove-occur-highlights (&optional beg end noremove)
12754 "Remove the occur highlights from the buffer.
12755 BEG and END are ignored. If NOREMOVE is nil, remove this function
12756 from the `before-change-functions' in the current buffer."
12757 (interactive)
12758 (unless org-inhibit-highlight-removal
12759 (mapc 'delete-overlay org-occur-highlights)
12760 (setq org-occur-highlights nil)
12761 (setq org-occur-parameters nil)
12762 (unless noremove
12763 (remove-hook 'before-change-functions
12764 'org-remove-occur-highlights 'local))))
12766 ;;;; Priorities
12768 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12769 "Regular expression matching the priority indicator.")
12771 (defvar org-remove-priority-next-time nil)
12773 (defun org-priority-up ()
12774 "Increase the priority of the current item."
12775 (interactive)
12776 (org-priority 'up))
12778 (defun org-priority-down ()
12779 "Decrease the priority of the current item."
12780 (interactive)
12781 (org-priority 'down))
12783 (defun org-priority (&optional action)
12784 "Change the priority of an item by ARG.
12785 ACTION can be `set', `up', `down', or a character."
12786 (interactive)
12787 (unless org-enable-priority-commands
12788 (error "Priority commands are disabled"))
12789 (setq action (or action 'set))
12790 (let (current new news have remove)
12791 (save-excursion
12792 (org-back-to-heading t)
12793 (if (looking-at org-priority-regexp)
12794 (setq current (string-to-char (match-string 2))
12795 have t))
12796 (cond
12797 ((eq action 'remove)
12798 (setq remove t new ?\ ))
12799 ((or (eq action 'set)
12800 (if (featurep 'xemacs) (characterp action) (integerp action)))
12801 (if (not (eq action 'set))
12802 (setq new action)
12803 (message "Priority %c-%c, SPC to remove: "
12804 org-highest-priority org-lowest-priority)
12805 (save-match-data
12806 (setq new (read-char-exclusive))))
12807 (if (and (= (upcase org-highest-priority) org-highest-priority)
12808 (= (upcase org-lowest-priority) org-lowest-priority))
12809 (setq new (upcase new)))
12810 (cond ((equal new ?\ ) (setq remove t))
12811 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12812 (error "Priority must be between `%c' and `%c'"
12813 org-highest-priority org-lowest-priority))))
12814 ((eq action 'up)
12815 (setq new (if have
12816 (1- current) ; normal cycling
12817 ;; last priority was empty
12818 (if (eq last-command this-command)
12819 org-lowest-priority ; wrap around empty to lowest
12820 ;; default
12821 (if org-priority-start-cycle-with-default
12822 org-default-priority
12823 (1- org-default-priority))))))
12824 ((eq action 'down)
12825 (setq new (if have
12826 (1+ current) ; normal cycling
12827 ;; last priority was empty
12828 (if (eq last-command this-command)
12829 org-highest-priority ; wrap around empty to highest
12830 ;; default
12831 (if org-priority-start-cycle-with-default
12832 org-default-priority
12833 (1+ org-default-priority))))))
12834 (t (error "Invalid action")))
12835 (if (or (< (upcase new) org-highest-priority)
12836 (> (upcase new) org-lowest-priority))
12837 (if (and (memq action '(up down))
12838 (not have) (not (eq last-command this-command)))
12839 ;; `new' is from default priority
12840 (error
12841 "The default can not be set, see `org-default-priority' why")
12842 ;; normal cycling: `new' is beyond highest/lowest priority
12843 ;; and is wrapped around to the empty priority
12844 (setq remove t)))
12845 (setq news (format "%c" new))
12846 (if have
12847 (if remove
12848 (replace-match "" t t nil 1)
12849 (replace-match news t t nil 2))
12850 (if remove
12851 (error "No priority cookie found in line")
12852 (let ((case-fold-search nil))
12853 (looking-at org-todo-line-regexp))
12854 (if (match-end 2)
12855 (progn
12856 (goto-char (match-end 2))
12857 (insert " [#" news "]"))
12858 (goto-char (match-beginning 3))
12859 (insert "[#" news "] "))))
12860 (org-preserve-lc (org-set-tags nil 'align)))
12861 (if remove
12862 (message "Priority removed")
12863 (message "Priority of current item set to %s" news))))
12865 (defun org-get-priority (s)
12866 "Find priority cookie and return priority."
12867 (if (functionp org-get-priority-function)
12868 (funcall org-get-priority-function)
12869 (save-match-data
12870 (if (not (string-match org-priority-regexp s))
12871 (* 1000 (- org-lowest-priority org-default-priority))
12872 (* 1000 (- org-lowest-priority
12873 (string-to-char (match-string 2 s))))))))
12875 ;;;; Tags
12877 (defvar org-agenda-archives-mode)
12878 (defvar org-map-continue-from nil
12879 "Position from where mapping should continue.
12880 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12882 (defvar org-scanner-tags nil
12883 "The current tag list while the tags scanner is running.")
12884 (defvar org-trust-scanner-tags nil
12885 "Should `org-get-tags-at' use the tags for the scanner.
12886 This is for internal dynamical scoping only.
12887 When this is non-nil, the function `org-get-tags-at' will return the value
12888 of `org-scanner-tags' instead of building the list by itself. This
12889 can lead to large speed-ups when the tags scanner is used in a file with
12890 many entries, and when the list of tags is retrieved, for example to
12891 obtain a list of properties. Building the tags list for each entry in such
12892 a file becomes an N^2 operation - but with this variable set, it scales
12893 as N.")
12895 (defun org-scan-tags (action matcher todo-only &optional start-level)
12896 "Scan headline tags with inheritance and produce output ACTION.
12898 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12899 or `agenda' to produce an entry list for an agenda view. It can also be
12900 a Lisp form or a function that should be called at each matched headline, in
12901 this case the return value is a list of all return values from these calls.
12903 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12904 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12905 only lines with a not-done TODO keyword are included in the output.
12906 This should be the same variable that was scoped into
12907 and set by `org-make-tags-matcher' when it constructed MATCHER.
12909 START-LEVEL can be a string with asterisks, reducing the scope to
12910 headlines matching this string."
12911 (require 'org-agenda)
12912 (let* ((re (concat "^"
12913 (if start-level
12914 ;; Get the correct level to match
12915 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12916 org-outline-regexp)
12917 " *\\(\\<\\("
12918 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12919 (org-re
12920 (if todo-only
12921 "\\>\\)\\)[ \t]+\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"
12922 "\\>\\)\\)? *\\([^ ].*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))))
12923 (props (list 'face 'default
12924 'done-face 'org-agenda-done
12925 'undone-face 'default
12926 'mouse-face 'highlight
12927 'org-not-done-regexp org-not-done-regexp
12928 'org-todo-regexp org-todo-regexp
12929 'org-complex-heading-regexp org-complex-heading-regexp
12930 'help-echo
12931 (format "mouse-2 or RET jump to org file %s"
12932 (abbreviate-file-name
12933 (or (buffer-file-name (buffer-base-buffer))
12934 (buffer-name (buffer-base-buffer)))))))
12935 (case-fold-search nil)
12936 (org-map-continue-from nil)
12937 lspos tags tags-list
12938 (tags-alist (list (cons 0 org-file-tags)))
12939 (llast 0) rtn rtn1 level category i txt
12940 todo marker entry priority)
12941 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12942 (setq action (list 'lambda nil action)))
12943 (save-excursion
12944 (goto-char (point-min))
12945 (when (eq action 'sparse-tree)
12946 (org-overview)
12947 (org-remove-occur-highlights))
12948 (while (re-search-forward re nil t)
12949 (setq org-map-continue-from nil)
12950 (catch :skip
12951 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12952 tags (if (match-end 4) (org-match-string-no-properties 4)))
12953 (goto-char (setq lspos (match-beginning 0)))
12954 (setq level (org-reduced-level (funcall outline-level))
12955 category (org-get-category))
12956 (setq i llast llast level)
12957 ;; remove tag lists from same and sublevels
12958 (while (>= i level)
12959 (when (setq entry (assoc i tags-alist))
12960 (setq tags-alist (delete entry tags-alist)))
12961 (setq i (1- i)))
12962 ;; add the next tags
12963 (when tags
12964 (setq tags (org-split-string tags ":")
12965 tags-alist
12966 (cons (cons level tags) tags-alist)))
12967 ;; compile tags for current headline
12968 (setq tags-list
12969 (if org-use-tag-inheritance
12970 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12971 tags)
12972 org-scanner-tags tags-list)
12973 (when org-use-tag-inheritance
12974 (setcdr (car tags-alist)
12975 (mapcar (lambda (x)
12976 (setq x (copy-sequence x))
12977 (org-add-prop-inherited x))
12978 (cdar tags-alist))))
12979 (when (and tags org-use-tag-inheritance
12980 (or (not (eq t org-use-tag-inheritance))
12981 org-tags-exclude-from-inheritance))
12982 ;; selective inheritance, remove uninherited ones
12983 (setcdr (car tags-alist)
12984 (org-remove-uninherited-tags (cdar tags-alist))))
12985 (when (and
12987 ;; eval matcher only when the todo condition is OK
12988 (and (or (not todo-only) (member todo org-not-done-keywords))
12989 (let ((case-fold-search t) (org-trust-scanner-tags t))
12990 (eval matcher)))
12992 ;; Call the skipper, but return t if it does not skip,
12993 ;; so that the `and' form continues evaluating
12994 (progn
12995 (unless (eq action 'sparse-tree) (org-agenda-skip))
12998 ;; Check if timestamps are deselecting this entry
12999 (or (not todo-only)
13000 (and (member todo org-not-done-keywords)
13001 (or (not org-agenda-tags-todo-honor-ignore-options)
13002 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13004 ;; Extra check for the archive tag
13005 ;; FIXME: Does the skipper already do this????
13007 (not (member org-archive-tag tags-list))
13008 ;; we have an archive tag, should we use this anyway?
13009 (or (not org-agenda-skip-archived-trees)
13010 (and (eq action 'agenda) org-agenda-archives-mode))))
13012 ;; select this headline
13014 (cond
13015 ((eq action 'sparse-tree)
13016 (and org-highlight-sparse-tree-matches
13017 (org-get-heading) (match-end 0)
13018 (org-highlight-new-match
13019 (match-beginning 1) (match-end 1)))
13020 (org-show-context 'tags-tree))
13021 ((eq action 'agenda)
13022 (setq txt (org-agenda-format-item
13024 (concat
13025 (if (eq org-tags-match-list-sublevels 'indented)
13026 (make-string (1- level) ?.) "")
13027 (org-get-heading))
13028 category
13029 tags-list)
13030 priority (org-get-priority txt))
13031 (goto-char lspos)
13032 (setq marker (org-agenda-new-marker))
13033 (org-add-props txt props
13034 'org-marker marker 'org-hd-marker marker 'org-category category
13035 'todo-state todo
13036 'priority priority 'type "tagsmatch")
13037 (push txt rtn))
13038 ((functionp action)
13039 (setq org-map-continue-from nil)
13040 (save-excursion
13041 (setq rtn1 (funcall action))
13042 (push rtn1 rtn)))
13043 (t (error "Invalid action")))
13045 ;; if we are to skip sublevels, jump to end of subtree
13046 (unless org-tags-match-list-sublevels
13047 (org-end-of-subtree t)
13048 (backward-char 1))))
13049 ;; Get the correct position from where to continue
13050 (if org-map-continue-from
13051 (goto-char org-map-continue-from)
13052 (and (= (point) lspos) (end-of-line 1)))))
13053 (when (and (eq action 'sparse-tree)
13054 (not org-sparse-tree-open-archived-trees))
13055 (org-hide-archived-subtrees (point-min) (point-max)))
13056 (nreverse rtn)))
13058 (defun org-remove-uninherited-tags (tags)
13059 "Remove all tags that are not inherited from the list TAGS."
13060 (cond
13061 ((eq org-use-tag-inheritance t)
13062 (if org-tags-exclude-from-inheritance
13063 (org-delete-all org-tags-exclude-from-inheritance tags)
13064 tags))
13065 ((not org-use-tag-inheritance) nil)
13066 ((stringp org-use-tag-inheritance)
13067 (delq nil (mapcar
13068 (lambda (x)
13069 (if (and (string-match org-use-tag-inheritance x)
13070 (not (member x org-tags-exclude-from-inheritance)))
13071 x nil))
13072 tags)))
13073 ((listp org-use-tag-inheritance)
13074 (delq nil (mapcar
13075 (lambda (x)
13076 (if (member x org-use-tag-inheritance) x nil))
13077 tags)))))
13079 (defun org-match-sparse-tree (&optional todo-only match)
13080 "Create a sparse tree according to tags string MATCH.
13081 MATCH can contain positive and negative selection of tags, like
13082 \"+WORK+URGENT-WITHBOSS\".
13083 If optional argument TODO-ONLY is non-nil, only select lines that are
13084 also TODO lines."
13085 (interactive "P")
13086 (org-prepare-agenda-buffers (list (current-buffer)))
13087 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13089 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13091 (defvar org-cached-props nil)
13092 (defun org-cached-entry-get (pom property)
13093 (if (or (eq t org-use-property-inheritance)
13094 (and (stringp org-use-property-inheritance)
13095 (string-match org-use-property-inheritance property))
13096 (and (listp org-use-property-inheritance)
13097 (member property org-use-property-inheritance)))
13098 ;; Caching is not possible, check it directly
13099 (org-entry-get pom property 'inherit)
13100 ;; Get all properties, so that we can do complicated checks easily
13101 (cdr (assoc property (or org-cached-props
13102 (setq org-cached-props
13103 (org-entry-properties pom)))))))
13105 (defun org-global-tags-completion-table (&optional files)
13106 "Return the list of all tags in all agenda buffer/files.
13107 Optional FILES argument is a list of files to which can be used
13108 instead of the agenda files."
13109 (save-excursion
13110 (org-uniquify
13111 (delq nil
13112 (apply 'append
13113 (mapcar
13114 (lambda (file)
13115 (set-buffer (find-file-noselect file))
13116 (append (org-get-buffer-tags)
13117 (mapcar (lambda (x) (if (stringp (car-safe x))
13118 (list (car-safe x)) nil))
13119 org-tag-alist)))
13120 (if (and files (car files))
13121 files
13122 (org-agenda-files))))))))
13124 (defun org-make-tags-matcher (match)
13125 "Create the TAGS/TODO matcher form for the selection string MATCH.
13127 The variable `todo-only' is scoped dynamically into this function; it will be
13128 set to t if the matcher restricts matching to TODO entries,
13129 otherwise will not be touched.
13131 Returns a cons of the selection string MATCH and the constructed
13132 lisp form implementing the matcher. The matcher is to be
13133 evaluated at an Org entry, with point on the headline,
13134 and returns t if the entry matches the
13135 selection string MATCH. The returned lisp form references
13136 two variables with information about the entry, which must be
13137 bound around the form's evaluation: todo, the TODO keyword at the
13138 entry (or nil of none); and tags-list, the list of all tags at the
13139 entry including inherited ones. Additionally, the category
13140 of the entry (if any) must be specified as the text property
13141 'org-category on the headline.
13143 See also `org-scan-tags'.
13145 (declare (special todo-only))
13146 (unless (boundp 'todo-only)
13147 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13148 (unless match
13149 ;; Get a new match request, with completion
13150 (let ((org-last-tags-completion-table
13151 (org-global-tags-completion-table)))
13152 (setq match (org-completing-read-no-i
13153 "Match: " 'org-tags-completion-function nil nil nil
13154 'org-tags-history))))
13156 ;; Parse the string and create a lisp form
13157 (let ((match0 match)
13158 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13159 minus tag mm
13160 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13161 orterms term orlist re-p str-p level-p level-op time-p
13162 prop-p pn pv po gv rest)
13163 (if (string-match "/+" match)
13164 ;; match contains also a todo-matching request
13165 (progn
13166 (setq tagsmatch (substring match 0 (match-beginning 0))
13167 todomatch (substring match (match-end 0)))
13168 (if (string-match "^!" todomatch)
13169 (setq todo-only t todomatch (substring todomatch 1)))
13170 (if (string-match "^\\s-*$" todomatch)
13171 (setq todomatch nil)))
13172 ;; only matching tags
13173 (setq tagsmatch match todomatch nil))
13175 ;; Make the tags matcher
13176 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13177 (setq tagsmatcher t)
13178 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13179 (while (setq term (pop orterms))
13180 (while (and (equal (substring term -1) "\\") orterms)
13181 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13182 (while (string-match re term)
13183 (setq rest (substring term (match-end 0))
13184 minus (and (match-end 1)
13185 (equal (match-string 1 term) "-"))
13186 tag (save-match-data (replace-regexp-in-string
13187 "\\\\-" "-"
13188 (match-string 2 term)))
13189 re-p (equal (string-to-char tag) ?{)
13190 level-p (match-end 4)
13191 prop-p (match-end 5)
13192 mm (cond
13193 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13194 (level-p
13195 (setq level-op (org-op-to-function (match-string 3 term)))
13196 `(,level-op level ,(string-to-number
13197 (match-string 4 term))))
13198 (prop-p
13199 (setq pn (match-string 5 term)
13200 po (match-string 6 term)
13201 pv (match-string 7 term)
13202 re-p (equal (string-to-char pv) ?{)
13203 str-p (equal (string-to-char pv) ?\")
13204 time-p (save-match-data
13205 (string-match "^\"[[<].*[]>]\"$" pv))
13206 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13207 (if time-p (setq pv (org-matcher-time pv)))
13208 (setq po (org-op-to-function po (if time-p 'time str-p)))
13209 (cond
13210 ((equal pn "CATEGORY")
13211 (setq gv '(get-text-property (point) 'org-category)))
13212 ((equal pn "TODO")
13213 (setq gv 'todo))
13215 (setq gv `(org-cached-entry-get nil ,pn))))
13216 (if re-p
13217 (if (eq po 'org<>)
13218 `(not (string-match ,pv (or ,gv "")))
13219 `(string-match ,pv (or ,gv "")))
13220 (if str-p
13221 `(,po (or ,gv "") ,pv)
13222 `(,po (string-to-number (or ,gv ""))
13223 ,(string-to-number pv) ))))
13224 (t `(member ,tag tags-list)))
13225 mm (if minus (list 'not mm) mm)
13226 term rest)
13227 (push mm tagsmatcher))
13228 (push (if (> (length tagsmatcher) 1)
13229 (cons 'and tagsmatcher)
13230 (car tagsmatcher))
13231 orlist)
13232 (setq tagsmatcher nil))
13233 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13234 (setq tagsmatcher
13235 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13236 ;; Make the todo matcher
13237 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13238 (setq todomatcher t)
13239 (setq orterms (org-split-string todomatch "|") orlist nil)
13240 (while (setq term (pop orterms))
13241 (while (string-match re term)
13242 (setq minus (and (match-end 1)
13243 (equal (match-string 1 term) "-"))
13244 kwd (match-string 2 term)
13245 re-p (equal (string-to-char kwd) ?{)
13246 term (substring term (match-end 0))
13247 mm (if re-p
13248 `(string-match ,(substring kwd 1 -1) todo)
13249 (list 'equal 'todo kwd))
13250 mm (if minus (list 'not mm) mm))
13251 (push mm todomatcher))
13252 (push (if (> (length todomatcher) 1)
13253 (cons 'and todomatcher)
13254 (car todomatcher))
13255 orlist)
13256 (setq todomatcher nil))
13257 (setq todomatcher (if (> (length orlist) 1)
13258 (cons 'or orlist) (car orlist))))
13260 ;; Return the string and lisp forms of the matcher
13261 (setq matcher (if todomatcher
13262 (list 'and tagsmatcher todomatcher)
13263 tagsmatcher))
13264 (when todo-only
13265 (setq matcher (list 'and '(member todo org-not-done-keywords)
13266 matcher)))
13267 (cons match0 matcher)))
13269 (defun org-op-to-function (op &optional stringp)
13270 "Turn an operator into the appropriate function."
13271 (setq op
13272 (cond
13273 ((equal op "<" ) '(< string< org-time<))
13274 ((equal op ">" ) '(> org-string> org-time>))
13275 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13276 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13277 ((member op '("=" "==")) '(= string= org-time=))
13278 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13279 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13281 (defun org<> (a b) (not (= a b)))
13282 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13283 (defun org-string>= (a b) (not (string< a b)))
13284 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13285 (defun org-string<> (a b) (not (string= a b)))
13286 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13287 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13288 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13289 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13290 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13291 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13292 (defun org-2ft (s)
13293 "Convert S to a floating point time.
13294 If S is already a number, just return it. If it is a string, parse
13295 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13296 (cond
13297 ((numberp s) s)
13298 ((stringp s)
13299 (condition-case nil
13300 (float-time (apply 'encode-time (org-parse-time-string s)))
13301 (error 0.)))
13302 (t 0.)))
13304 (defun org-time-today ()
13305 "Time in seconds today at 0:00.
13306 Returns the float number of seconds since the beginning of the
13307 epoch to the beginning of today (00:00)."
13308 (float-time (apply 'encode-time
13309 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13311 (defun org-matcher-time (s)
13312 "Interpret a time comparison value."
13313 (save-match-data
13314 (cond
13315 ((string= s "<now>") (float-time))
13316 ((string= s "<today>") (org-time-today))
13317 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13318 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13319 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13320 (+ (org-time-today)
13321 (* (string-to-number (match-string 1 s))
13322 (cdr (assoc (match-string 2 s)
13323 '(("d" . 86400.0) ("w" . 604800.0)
13324 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13325 (t (org-2ft s)))))
13327 (defun org-match-any-p (re list)
13328 "Does re match any element of list?"
13329 (setq list (mapcar (lambda (x) (string-match re x)) list))
13330 (delq nil list))
13332 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13333 (defvar org-tags-overlay (make-overlay 1 1))
13334 (org-detach-overlay org-tags-overlay)
13336 (defun org-get-local-tags-at (&optional pos)
13337 "Get a list of tags defined in the current headline."
13338 (org-get-tags-at pos 'local))
13340 (defun org-get-local-tags ()
13341 "Get a list of tags defined in the current headline."
13342 (org-get-tags-at nil 'local))
13344 (defun org-get-tags-at (&optional pos local)
13345 "Get a list of all headline tags applicable at POS.
13346 POS defaults to point. If tags are inherited, the list contains
13347 the targets in the same sequence as the headlines appear, i.e.
13348 the tags of the current headline come last.
13349 When LOCAL is non-nil, only return tags from the current headline,
13350 ignore inherited ones."
13351 (interactive)
13352 (if (and org-trust-scanner-tags
13353 (or (not pos) (equal pos (point)))
13354 (not local))
13355 org-scanner-tags
13356 (let (tags ltags lastpos parent)
13357 (save-excursion
13358 (save-restriction
13359 (widen)
13360 (goto-char (or pos (point)))
13361 (save-match-data
13362 (catch 'done
13363 (condition-case nil
13364 (progn
13365 (org-back-to-heading t)
13366 (while (not (equal lastpos (point)))
13367 (setq lastpos (point))
13368 (when (looking-at
13369 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13370 (setq ltags (org-split-string
13371 (org-match-string-no-properties 1) ":"))
13372 (when parent
13373 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13374 (setq tags (append
13375 (if parent
13376 (org-remove-uninherited-tags ltags)
13377 ltags)
13378 tags)))
13379 (or org-use-tag-inheritance (throw 'done t))
13380 (if local (throw 'done t))
13381 (or (org-up-heading-safe) (error nil))
13382 (setq parent t)))
13383 (error nil)))))
13384 (if local
13385 tags
13386 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13388 (defun org-add-prop-inherited (s)
13389 (add-text-properties 0 (length s) '(inherited t) s)
13392 (defun org-toggle-tag (tag &optional onoff)
13393 "Toggle the tag TAG for the current line.
13394 If ONOFF is `on' or `off', don't toggle but set to this state."
13395 (let (res current)
13396 (save-excursion
13397 (org-back-to-heading t)
13398 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13399 (point-at-eol) t)
13400 (progn
13401 (setq current (match-string 1))
13402 (replace-match ""))
13403 (setq current ""))
13404 (setq current (nreverse (org-split-string current ":")))
13405 (cond
13406 ((eq onoff 'on)
13407 (setq res t)
13408 (or (member tag current) (push tag current)))
13409 ((eq onoff 'off)
13410 (or (not (member tag current)) (setq current (delete tag current))))
13411 (t (if (member tag current)
13412 (setq current (delete tag current))
13413 (setq res t)
13414 (push tag current))))
13415 (end-of-line 1)
13416 (if current
13417 (progn
13418 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13419 (org-set-tags nil t))
13420 (delete-horizontal-space))
13421 (run-hooks 'org-after-tags-change-hook))
13422 res))
13424 (defun org-align-tags-here (to-col)
13425 ;; Assumes that this is a headline
13426 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13427 (beginning-of-line 1)
13428 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13429 (< pos (match-beginning 2)))
13430 (progn
13431 (setq tags-l (- (match-end 2) (match-beginning 2)))
13432 (goto-char (match-beginning 1))
13433 (insert " ")
13434 (delete-region (point) (1+ (match-beginning 2)))
13435 (setq ncol (max (current-column)
13436 (1+ col)
13437 (if (> to-col 0)
13438 to-col
13439 (- (abs to-col) tags-l))))
13440 (setq p (point))
13441 (insert (make-string (- ncol (current-column)) ?\ ))
13442 (setq ncol (current-column))
13443 (when indent-tabs-mode (tabify p (point-at-eol)))
13444 (org-move-to-column (min ncol col) t))
13445 (goto-char pos))))
13447 (defun org-set-tags-command (&optional arg just-align)
13448 "Call the set-tags command for the current entry."
13449 (interactive "P")
13450 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13451 (org-set-tags arg just-align)
13452 (save-excursion
13453 (org-back-to-heading t)
13454 (org-set-tags arg just-align))))
13456 (defun org-set-tags-to (data)
13457 "Set the tags of the current entry to DATA, replacing the current tags.
13458 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13459 If DATA is nil or the empty string, any tags will be removed."
13460 (interactive "sTags: ")
13461 (setq data
13462 (cond
13463 ((eq data nil) "")
13464 ((equal data "") "")
13465 ((stringp data)
13466 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13467 ":"))
13468 ((listp data)
13469 (concat ":" (mapconcat 'identity data ":") ":"))
13470 (t nil)))
13471 (when data
13472 (save-excursion
13473 (org-back-to-heading t)
13474 (when (looking-at org-complex-heading-regexp)
13475 (if (match-end 5)
13476 (progn
13477 (goto-char (match-beginning 5))
13478 (insert data)
13479 (delete-region (point) (point-at-eol))
13480 (org-set-tags nil 'align))
13481 (goto-char (point-at-eol))
13482 (insert " " data)
13483 (org-set-tags nil 'align)))
13484 (beginning-of-line 1)
13485 (if (looking-at ".*?\\([ \t]+\\)$")
13486 (delete-region (match-beginning 1) (match-end 1))))))
13488 (defun org-align-all-tags ()
13489 "Align the tags i all headings."
13490 (interactive)
13491 (save-excursion
13492 (or (ignore-errors (org-back-to-heading t))
13493 (outline-next-heading))
13494 (if (org-at-heading-p)
13495 (org-set-tags t)
13496 (message "No headings"))))
13498 (defvar org-indent-indentation-per-level)
13499 (defun org-set-tags (&optional arg just-align)
13500 "Set the tags for the current headline.
13501 With prefix ARG, realign all tags in headings in the current buffer."
13502 (interactive "P")
13503 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13504 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13505 'region-start-level 'region))
13506 org-loop-over-headlines-in-active-region)
13507 (org-map-entries
13508 ;; We don't use ARG and JUST-ALIGN here these args are not
13509 ;; useful when looping over headlines
13510 `(org-set-tags)
13511 org-loop-over-headlines-in-active-region
13512 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13513 (let* ((re org-outline-regexp-bol)
13514 (current (unless arg (org-get-tags-string)))
13515 (col (current-column))
13516 (org-setting-tags t)
13517 table current-tags inherited-tags ; computed below when needed
13518 tags p0 c0 c1 rpl di tc level)
13519 (if arg
13520 (save-excursion
13521 (goto-char (point-min))
13522 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13523 (while (re-search-forward re nil t)
13524 (org-set-tags nil t)
13525 (end-of-line 1)))
13526 (message "All tags realigned to column %d" org-tags-column))
13527 (if just-align
13528 (setq tags current)
13529 ;; Get a new set of tags from the user
13530 (save-excursion
13531 (setq table (append org-tag-persistent-alist
13532 (or org-tag-alist (org-get-buffer-tags))
13533 (and
13534 org-complete-tags-always-offer-all-agenda-tags
13535 (org-global-tags-completion-table
13536 (org-agenda-files))))
13537 org-last-tags-completion-table table
13538 current-tags (org-split-string current ":")
13539 inherited-tags (nreverse
13540 (nthcdr (length current-tags)
13541 (nreverse (org-get-tags-at))))
13542 tags
13543 (if (or (eq t org-use-fast-tag-selection)
13544 (and org-use-fast-tag-selection
13545 (delq nil (mapcar 'cdr table))))
13546 (org-fast-tag-selection
13547 current-tags inherited-tags table
13548 (if org-fast-tag-selection-include-todo
13549 org-todo-key-alist))
13550 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13551 (org-trim
13552 (org-icompleting-read "Tags: "
13553 'org-tags-completion-function
13554 nil nil current 'org-tags-history))))))
13555 (while (string-match "[-+&]+" tags)
13556 ;; No boolean logic, just a list
13557 (setq tags (replace-match ":" t t tags))))
13559 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13561 (if org-tags-sort-function
13562 (setq tags (mapconcat 'identity
13563 (sort (org-split-string
13564 tags (org-re "[^[:alnum:]_@#%]+"))
13565 org-tags-sort-function) ":")))
13567 (if (string-match "\\`[\t ]*\\'" tags)
13568 (setq tags "")
13569 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13570 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13572 ;; Insert new tags at the correct column
13573 (beginning-of-line 1)
13574 (setq level (or (and (looking-at org-outline-regexp)
13575 (- (match-end 0) (point) 1))
13577 (cond
13578 ((and (equal current "") (equal tags "")))
13579 ((re-search-forward
13580 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13581 (point-at-eol) t)
13582 (if (equal tags "")
13583 (setq rpl "")
13584 (goto-char (match-beginning 0))
13585 (setq c0 (current-column)
13586 ;; compute offset for the case of org-indent-mode active
13587 di (if org-indent-mode
13588 (* (1- org-indent-indentation-per-level) (1- level))
13590 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13591 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13592 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13593 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13594 (replace-match rpl t t)
13595 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13596 tags)
13597 (t (error "Tags alignment failed")))
13598 (org-move-to-column col)
13599 (unless just-align
13600 (run-hooks 'org-after-tags-change-hook))))))
13602 (defun org-change-tag-in-region (beg end tag off)
13603 "Add or remove TAG for each entry in the region.
13604 This works in the agenda, and also in an org-mode buffer."
13605 (interactive
13606 (list (region-beginning) (region-end)
13607 (let ((org-last-tags-completion-table
13608 (if (derived-mode-p 'org-mode)
13609 (org-get-buffer-tags)
13610 (org-global-tags-completion-table))))
13611 (org-icompleting-read
13612 "Tag: " 'org-tags-completion-function nil nil nil
13613 'org-tags-history))
13614 (progn
13615 (message "[s]et or [r]emove? ")
13616 (equal (read-char-exclusive) ?r))))
13617 (if (fboundp 'deactivate-mark) (deactivate-mark))
13618 (let ((agendap (equal major-mode 'org-agenda-mode))
13619 l1 l2 m buf pos newhead (cnt 0))
13620 (goto-char end)
13621 (setq l2 (1- (org-current-line)))
13622 (goto-char beg)
13623 (setq l1 (org-current-line))
13624 (loop for l from l1 to l2 do
13625 (org-goto-line l)
13626 (setq m (get-text-property (point) 'org-hd-marker))
13627 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13628 (and agendap m))
13629 (setq buf (if agendap (marker-buffer m) (current-buffer))
13630 pos (if agendap m (point)))
13631 (with-current-buffer buf
13632 (save-excursion
13633 (save-restriction
13634 (goto-char pos)
13635 (setq cnt (1+ cnt))
13636 (org-toggle-tag tag (if off 'off 'on))
13637 (setq newhead (org-get-heading)))))
13638 (and agendap (org-agenda-change-all-lines newhead m))))
13639 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13641 (defun org-tags-completion-function (string predicate &optional flag)
13642 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13643 (confirm (lambda (x) (stringp (car x)))))
13644 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13645 (setq s1 (match-string 1 string)
13646 s2 (match-string 2 string))
13647 (setq s1 "" s2 string))
13648 (cond
13649 ((eq flag nil)
13650 ;; try completion
13651 (setq rtn (try-completion s2 ctable confirm))
13652 (if (stringp rtn)
13653 (setq rtn
13654 (concat s1 s2 (substring rtn (length s2))
13655 (if (and org-add-colon-after-tag-completion
13656 (assoc rtn ctable))
13657 ":" ""))))
13658 rtn)
13659 ((eq flag t)
13660 ;; all-completions
13661 (all-completions s2 ctable confirm)
13663 ((eq flag 'lambda)
13664 ;; exact match?
13665 (assoc s2 ctable)))
13668 (defun org-fast-tag-insert (kwd tags face &optional end)
13669 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13670 (insert (format "%-12s" (concat kwd ":"))
13671 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13672 (or end "")))
13674 (defun org-fast-tag-show-exit (flag)
13675 (save-excursion
13676 (org-goto-line 3)
13677 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13678 (replace-match ""))
13679 (when flag
13680 (end-of-line 1)
13681 (org-move-to-column (- (window-width) 19) t)
13682 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13684 (defun org-set-current-tags-overlay (current prefix)
13685 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13686 (if (featurep 'xemacs)
13687 (org-overlay-display org-tags-overlay (concat prefix s)
13688 'secondary-selection)
13689 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13690 (org-overlay-display org-tags-overlay (concat prefix s)))))
13692 (defvar org-last-tag-selection-key nil)
13693 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13694 "Fast tag selection with single keys.
13695 CURRENT is the current list of tags in the headline, INHERITED is the
13696 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13697 possibly with grouping information. TODO-TABLE is a similar table with
13698 TODO keywords, should these have keys assigned to them.
13699 If the keys are nil, a-z are automatically assigned.
13700 Returns the new tags string, or nil to not change the current settings."
13701 (let* ((fulltable (append table todo-table))
13702 (maxlen (apply 'max (mapcar
13703 (lambda (x)
13704 (if (stringp (car x)) (string-width (car x)) 0))
13705 fulltable)))
13706 (buf (current-buffer))
13707 (expert (eq org-fast-tag-selection-single-key 'expert))
13708 (buffer-tags nil)
13709 (fwidth (+ maxlen 3 1 3))
13710 (ncol (/ (- (window-width) 4) fwidth))
13711 (i-face 'org-done)
13712 (c-face 'org-todo)
13713 tg cnt e c char c1 c2 ntable tbl rtn
13714 ov-start ov-end ov-prefix
13715 (exit-after-next org-fast-tag-selection-single-key)
13716 (done-keywords org-done-keywords)
13717 groups ingroup)
13718 (save-excursion
13719 (beginning-of-line 1)
13720 (if (looking-at
13721 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13722 (setq ov-start (match-beginning 1)
13723 ov-end (match-end 1)
13724 ov-prefix "")
13725 (setq ov-start (1- (point-at-eol))
13726 ov-end (1+ ov-start))
13727 (skip-chars-forward "^\n\r")
13728 (setq ov-prefix
13729 (concat
13730 (buffer-substring (1- (point)) (point))
13731 (if (> (current-column) org-tags-column)
13733 (make-string (- org-tags-column (current-column)) ?\ ))))))
13734 (move-overlay org-tags-overlay ov-start ov-end)
13735 (save-window-excursion
13736 (if expert
13737 (set-buffer (get-buffer-create " *Org tags*"))
13738 (delete-other-windows)
13739 (split-window-vertically)
13740 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13741 (erase-buffer)
13742 (org-set-local 'org-done-keywords done-keywords)
13743 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13744 (org-fast-tag-insert "Current" current c-face "\n\n")
13745 (org-fast-tag-show-exit exit-after-next)
13746 (org-set-current-tags-overlay current ov-prefix)
13747 (setq tbl fulltable char ?a cnt 0)
13748 (while (setq e (pop tbl))
13749 (cond
13750 ((equal (car e) :startgroup)
13751 (push '() groups) (setq ingroup t)
13752 (when (not (= cnt 0))
13753 (setq cnt 0)
13754 (insert "\n"))
13755 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13756 ((equal (car e) :endgroup)
13757 (setq ingroup nil cnt 0)
13758 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13759 ((equal e '(:newline))
13760 (when (not (= cnt 0))
13761 (setq cnt 0)
13762 (insert "\n")
13763 (setq e (car tbl))
13764 (while (equal (car tbl) '(:newline))
13765 (insert "\n")
13766 (setq tbl (cdr tbl)))))
13768 (setq tg (copy-sequence (car e)) c2 nil)
13769 (if (cdr e)
13770 (setq c (cdr e))
13771 ;; automatically assign a character.
13772 (setq c1 (string-to-char
13773 (downcase (substring
13774 tg (if (= (string-to-char tg) ?@) 1 0)))))
13775 (if (or (rassoc c1 ntable) (rassoc c1 table))
13776 (while (or (rassoc char ntable) (rassoc char table))
13777 (setq char (1+ char)))
13778 (setq c2 c1))
13779 (setq c (or c2 char)))
13780 (if ingroup (push tg (car groups)))
13781 (setq tg (org-add-props tg nil 'face
13782 (cond
13783 ((not (assoc tg table))
13784 (org-get-todo-face tg))
13785 ((member tg current) c-face)
13786 ((member tg inherited) i-face)
13787 (t nil))))
13788 (if (and (= cnt 0) (not ingroup)) (insert " "))
13789 (insert "[" c "] " tg (make-string
13790 (- fwidth 4 (length tg)) ?\ ))
13791 (push (cons tg c) ntable)
13792 (when (= (setq cnt (1+ cnt)) ncol)
13793 (insert "\n")
13794 (if ingroup (insert " "))
13795 (setq cnt 0)))))
13796 (setq ntable (nreverse ntable))
13797 (insert "\n")
13798 (goto-char (point-min))
13799 (if (not expert) (org-fit-window-to-buffer))
13800 (setq rtn
13801 (catch 'exit
13802 (while t
13803 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13804 (if (not groups) "no " "")
13805 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13806 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13807 (setq org-last-tag-selection-key c)
13808 (cond
13809 ((= c ?\r) (throw 'exit t))
13810 ((= c ?!)
13811 (setq groups (not groups))
13812 (goto-char (point-min))
13813 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13814 ((= c ?\C-c)
13815 (if (not expert)
13816 (org-fast-tag-show-exit
13817 (setq exit-after-next (not exit-after-next)))
13818 (setq expert nil)
13819 (delete-other-windows)
13820 (set-window-buffer (split-window-vertically) " *Org tags*")
13821 (org-switch-to-buffer-other-window " *Org tags*")
13822 (org-fit-window-to-buffer)))
13823 ((or (= c ?\C-g)
13824 (and (= c ?q) (not (rassoc c ntable))))
13825 (org-detach-overlay org-tags-overlay)
13826 (setq quit-flag t))
13827 ((= c ?\ )
13828 (setq current nil)
13829 (if exit-after-next (setq exit-after-next 'now)))
13830 ((= c ?\t)
13831 (condition-case nil
13832 (setq tg (org-icompleting-read
13833 "Tag: "
13834 (or buffer-tags
13835 (with-current-buffer buf
13836 (org-get-buffer-tags)))))
13837 (quit (setq tg "")))
13838 (when (string-match "\\S-" tg)
13839 (add-to-list 'buffer-tags (list tg))
13840 (if (member tg current)
13841 (setq current (delete tg current))
13842 (push tg current)))
13843 (if exit-after-next (setq exit-after-next 'now)))
13844 ((setq e (rassoc c todo-table) tg (car e))
13845 (with-current-buffer buf
13846 (save-excursion (org-todo tg)))
13847 (if exit-after-next (setq exit-after-next 'now)))
13848 ((setq e (rassoc c ntable) tg (car e))
13849 (if (member tg current)
13850 (setq current (delete tg current))
13851 (loop for g in groups do
13852 (if (member tg g)
13853 (mapc (lambda (x)
13854 (setq current (delete x current)))
13855 g)))
13856 (push tg current))
13857 (if exit-after-next (setq exit-after-next 'now))))
13859 ;; Create a sorted list
13860 (setq current
13861 (sort current
13862 (lambda (a b)
13863 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13864 (if (eq exit-after-next 'now) (throw 'exit t))
13865 (goto-char (point-min))
13866 (beginning-of-line 2)
13867 (delete-region (point) (point-at-eol))
13868 (org-fast-tag-insert "Current" current c-face)
13869 (org-set-current-tags-overlay current ov-prefix)
13870 (while (re-search-forward
13871 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13872 (setq tg (match-string 1))
13873 (add-text-properties
13874 (match-beginning 1) (match-end 1)
13875 (list 'face
13876 (cond
13877 ((member tg current) c-face)
13878 ((member tg inherited) i-face)
13879 (t (get-text-property (match-beginning 1) 'face))))))
13880 (goto-char (point-min)))))
13881 (org-detach-overlay org-tags-overlay)
13882 (if rtn
13883 (mapconcat 'identity current ":")
13884 nil))))
13886 (defun org-get-tags-string ()
13887 "Get the TAGS string in the current headline."
13888 (unless (org-at-heading-p t)
13889 (error "Not on a heading"))
13890 (save-excursion
13891 (beginning-of-line 1)
13892 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13893 (org-match-string-no-properties 1)
13894 "")))
13896 (defun org-get-tags ()
13897 "Get the list of tags specified in the current headline."
13898 (org-split-string (org-get-tags-string) ":"))
13900 (defun org-get-buffer-tags ()
13901 "Get a table of all tags used in the buffer, for completion."
13902 (let (tags)
13903 (save-excursion
13904 (goto-char (point-min))
13905 (while (re-search-forward
13906 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13907 (when (equal (char-after (point-at-bol 0)) ?*)
13908 (mapc (lambda (x) (add-to-list 'tags x))
13909 (org-split-string (org-match-string-no-properties 1) ":")))))
13910 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13911 (mapcar 'list tags)))
13913 ;;;; The mapping API
13915 ;;;###autoload
13916 (defun org-map-entries (func &optional match scope &rest skip)
13917 "Call FUNC at each headline selected by MATCH in SCOPE.
13919 FUNC is a function or a lisp form. The function will be called without
13920 arguments, with the cursor positioned at the beginning of the headline.
13921 The return values of all calls to the function will be collected and
13922 returned as a list.
13924 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13925 does not need to preserve point. After evaluation, the cursor will be
13926 moved to the end of the line (presumably of the headline of the
13927 processed entry) and search continues from there. Under some
13928 circumstances, this may not produce the wanted results. For example,
13929 if you have removed (e.g. archived) the current (sub)tree it could
13930 mean that the next entry will be skipped entirely. In such cases, you
13931 can specify the position from where search should continue by making
13932 FUNC set the variable `org-map-continue-from' to the desired buffer
13933 position.
13935 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13936 Only headlines that are matched by this query will be considered during
13937 the iteration. When MATCH is nil or t, all headlines will be
13938 visited by the iteration.
13940 SCOPE determines the scope of this command. It can be any of:
13942 nil The current buffer, respecting the restriction if any
13943 tree The subtree started with the entry at point
13944 region The entries within the active region, if any
13945 region-start-level
13946 The entries within the active region, but only those at
13947 the same level than the first one.
13948 file The current buffer, without restriction
13949 file-with-archives
13950 The current buffer, and any archives associated with it
13951 agenda All agenda files
13952 agenda-with-archives
13953 All agenda files with any archive files associated with them
13954 \(file1 file2 ...)
13955 If this is a list, all files in the list will be scanned
13957 The remaining args are treated as settings for the skipping facilities of
13958 the scanner. The following items can be given here:
13960 archive skip trees with the archive tag.
13961 comment skip trees with the COMMENT keyword
13962 function or Emacs Lisp form:
13963 will be used as value for `org-agenda-skip-function', so whenever
13964 the function returns t, FUNC will not be called for that
13965 entry and search will continue from the point where the
13966 function leaves it.
13968 If your function needs to retrieve the tags including inherited tags
13969 at the *current* entry, you can use the value of the variable
13970 `org-scanner-tags' which will be much faster than getting the value
13971 with `org-get-tags-at'. If your function gets properties with
13972 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13973 to t around the call to `org-entry-properties' to get the same speedup.
13974 Note that if your function moves around to retrieve tags and properties at
13975 a *different* entry, you cannot use these techniques."
13976 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13977 (not (org-region-active-p)))
13978 (let* ((org-agenda-archives-mode nil) ; just to make sure
13979 (org-agenda-skip-archived-trees (memq 'archive skip))
13980 (org-agenda-skip-comment-trees (memq 'comment skip))
13981 (org-agenda-skip-function
13982 (car (org-delete-all '(comment archive) skip)))
13983 (org-tags-match-list-sublevels t)
13984 (start-level (eq scope 'region-start-level))
13985 matcher file res
13986 org-todo-keywords-for-agenda
13987 org-done-keywords-for-agenda
13988 org-todo-keyword-alist-for-agenda
13989 org-drawers-for-agenda
13990 org-tag-alist-for-agenda
13991 todo-only)
13993 (cond
13994 ((eq match t) (setq matcher t))
13995 ((eq match nil) (setq matcher t))
13996 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13998 (save-excursion
13999 (save-restriction
14000 (cond ((eq scope 'tree)
14001 (org-back-to-heading t)
14002 (org-narrow-to-subtree)
14003 (setq scope nil))
14004 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14005 (org-region-active-p))
14006 ;; If needed, set start-level to a string like "2"
14007 (when start-level
14008 (save-excursion
14009 (goto-char (region-beginning))
14010 (unless (org-at-heading-p) (outline-next-heading))
14011 (setq start-level (org-current-level))))
14012 (narrow-to-region (region-beginning)
14013 (save-excursion
14014 (goto-char (region-end))
14015 (unless (and (bolp) (org-at-heading-p))
14016 (outline-next-heading))
14017 (point)))
14018 (setq scope nil)))
14020 (if (not scope)
14021 (progn
14022 (org-prepare-agenda-buffers
14023 (list (buffer-file-name (current-buffer))))
14024 (setq res (org-scan-tags func matcher todo-only start-level)))
14025 ;; Get the right scope
14026 (cond
14027 ((and scope (listp scope) (symbolp (car scope)))
14028 (setq scope (eval scope)))
14029 ((eq scope 'agenda)
14030 (setq scope (org-agenda-files t)))
14031 ((eq scope 'agenda-with-archives)
14032 (setq scope (org-agenda-files t))
14033 (setq scope (org-add-archive-files scope)))
14034 ((eq scope 'file)
14035 (setq scope (list (buffer-file-name))))
14036 ((eq scope 'file-with-archives)
14037 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14038 (org-prepare-agenda-buffers scope)
14039 (while (setq file (pop scope))
14040 (with-current-buffer (org-find-base-buffer-visiting file)
14041 (save-excursion
14042 (save-restriction
14043 (widen)
14044 (goto-char (point-min))
14045 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14046 res)))
14048 ;;;; Properties
14050 ;;; Setting and retrieving properties
14052 (defconst org-special-properties
14053 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14054 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
14055 "The special properties valid in Org-mode.
14057 These are properties that are not defined in the property drawer,
14058 but in some other way.")
14060 (defconst org-default-properties
14061 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14062 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14063 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14064 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14065 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14066 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14067 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14068 "Some properties that are used by Org-mode for various purposes.
14069 Being in this list makes sure that they are offered for completion.")
14071 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14072 "Regular expression matching the first line of a property drawer.")
14074 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14075 "Regular expression matching the last line of a property drawer.")
14077 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14078 "Regular expression matching the first line of a property drawer.")
14080 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14081 "Regular expression matching the first line of a property drawer.")
14083 (defconst org-property-drawer-re
14084 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14085 org-property-end-re "\\)\n?")
14086 "Matches an entire property drawer.")
14088 (defconst org-clock-drawer-re
14089 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14090 org-property-end-re "\\)\n?")
14091 "Matches an entire clock drawer.")
14093 (defsubst org-re-property (property)
14094 "Return a regexp matching PROPERTY.
14095 Match group 1 will be set to the value "
14096 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14098 (defun org-property-action ()
14099 "Do an action on properties."
14100 (interactive)
14101 (let (c)
14102 (org-at-property-p)
14103 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14104 (setq c (read-char-exclusive))
14105 (cond
14106 ((equal c ?s)
14107 (call-interactively 'org-set-property))
14108 ((equal c ?d)
14109 (call-interactively 'org-delete-property))
14110 ((equal c ?D)
14111 (call-interactively 'org-delete-property-globally))
14112 ((equal c ?c)
14113 (call-interactively 'org-compute-property-at-point))
14114 (t (error "No such property action %c" c)))))
14116 (defun org-set-effort (&optional value)
14117 "Set the effort property of the current entry.
14118 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14119 allowed value."
14120 (interactive "P")
14121 (if (equal value 0) (setq value 10))
14122 (let* ((completion-ignore-case t)
14123 (prop org-effort-property)
14124 (cur (org-entry-get nil prop))
14125 (allowed (org-property-get-allowed-values nil prop 'table))
14126 (existing (mapcar 'list (org-property-values prop)))
14128 (val (cond
14129 ((stringp value) value)
14130 ((and allowed (integerp value))
14131 (or (car (nth (1- value) allowed))
14132 (car (org-last allowed))))
14133 (allowed
14134 (message "Select 1-9,0, [RET%s]: %s"
14135 (if cur (concat "=" cur) "")
14136 (mapconcat 'car allowed " "))
14137 (setq rpl (read-char-exclusive))
14138 (if (equal rpl ?\r)
14140 (setq rpl (- rpl ?0))
14141 (if (equal rpl 0) (setq rpl 10))
14142 (if (and (> rpl 0) (<= rpl (length allowed)))
14143 (car (nth (1- rpl) allowed))
14144 (org-completing-read "Effort: " allowed nil))))
14146 (let (org-completion-use-ido org-completion-use-iswitchb)
14147 (org-completing-read
14148 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14149 (concat "[" cur "]") "")
14150 ": ")
14151 existing nil nil "" nil cur))))))
14152 (unless (equal (org-entry-get nil prop) val)
14153 (org-entry-put nil prop val))
14154 (message "%s is now %s" prop val)))
14156 (defun org-at-property-p ()
14157 "Is cursor inside a property drawer?"
14158 (save-excursion
14159 (beginning-of-line 1)
14160 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14161 (save-match-data ;; Used by calling procedures
14162 (let ((p (point))
14163 (range (unless (org-before-first-heading-p)
14164 (org-get-property-block))))
14165 (and range (<= (car range) p) (< p (cdr range))))))))
14167 (defun org-get-property-block (&optional beg end force)
14168 "Return the (beg . end) range of the body of the property drawer.
14169 BEG and END can be beginning and end of subtree, if not given
14170 they will be found.
14171 If the drawer does not exist and FORCE is non-nil, create the drawer."
14172 (catch 'exit
14173 (save-excursion
14174 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14175 (end (or end (progn (outline-next-heading) (point)))))
14176 (goto-char beg)
14177 (if (re-search-forward org-property-start-re end t)
14178 (setq beg (1+ (match-end 0)))
14179 (if force
14180 (save-excursion
14181 (org-insert-property-drawer)
14182 (setq end (progn (outline-next-heading) (point))))
14183 (throw 'exit nil))
14184 (goto-char beg)
14185 (if (re-search-forward org-property-start-re end t)
14186 (setq beg (1+ (match-end 0)))))
14187 (if (re-search-forward org-property-end-re end t)
14188 (setq end (match-beginning 0))
14189 (or force (throw 'exit nil))
14190 (goto-char beg)
14191 (setq end beg)
14192 (org-indent-line-function)
14193 (insert ":END:\n"))
14194 (cons beg end)))))
14196 (defun org-entry-properties (&optional pom which specific)
14197 "Get all properties of the entry at point-or-marker POM.
14198 This includes the TODO keyword, the tags, time strings for deadline,
14199 scheduled, and clocking, and any additional properties defined in the
14200 entry. The return value is an alist, keys may occur multiple times
14201 if the property key was used several times.
14202 POM may also be nil, in which case the current entry is used.
14203 If WHICH is nil or `all', get all properties. If WHICH is
14204 `special' or `standard', only get that subclass. If WHICH
14205 is a string only get exactly this property. SPECIFIC can be a string, the
14206 specific property we are interested in. Specifying it can speed
14207 things up because then unnecessary parsing is avoided."
14208 (setq which (or which 'all))
14209 (org-with-point-at pom
14210 (let ((clockstr (substring org-clock-string 0 -1))
14211 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14212 (case-fold-search nil)
14213 beg end range props sum-props key key1 value string clocksum)
14214 (save-excursion
14215 (when (condition-case nil
14216 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14217 (error nil))
14218 (setq beg (point))
14219 (setq sum-props (get-text-property (point) 'org-summaries))
14220 (setq clocksum (get-text-property (point) :org-clock-minutes))
14221 (outline-next-heading)
14222 (setq end (point))
14223 (when (memq which '(all special))
14224 ;; Get the special properties, like TODO and tags
14225 (goto-char beg)
14226 (when (and (or (not specific) (string= specific "TODO"))
14227 (looking-at org-todo-line-regexp) (match-end 2))
14228 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14229 (when (and (or (not specific) (string= specific "PRIORITY"))
14230 (looking-at org-priority-regexp))
14231 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14232 (when (or (not specific) (string= specific "FILE"))
14233 (push (cons "FILE" buffer-file-name) props))
14234 (when (and (or (not specific) (string= specific "TAGS"))
14235 (setq value (org-get-tags-string))
14236 (string-match "\\S-" value))
14237 (push (cons "TAGS" value) props))
14238 (when (and (or (not specific) (string= specific "ALLTAGS"))
14239 (setq value (org-get-tags-at)))
14240 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14241 ":"))
14242 props))
14243 (when (or (not specific) (string= specific "BLOCKED"))
14244 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14245 (when (or (not specific)
14246 (member specific
14247 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14248 "TIMESTAMP" "TIMESTAMP_IA")))
14249 (catch 'match
14250 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14251 (setq key (if (match-end 1)
14252 (substring (org-match-string-no-properties 1)
14253 0 -1))
14254 string (if (equal key clockstr)
14255 (org-no-properties
14256 (org-trim
14257 (buffer-substring
14258 (match-beginning 3) (goto-char
14259 (point-at-eol)))))
14260 (substring (org-match-string-no-properties 3)
14261 1 -1)))
14262 ;; Get the correct property name from the key. This is
14263 ;; necessary if the user has configured time keywords.
14264 (setq key1 (concat key ":"))
14265 (cond
14266 ((not key)
14267 (setq key
14268 (if (= (char-after (match-beginning 3)) ?\[)
14269 "TIMESTAMP_IA" "TIMESTAMP")))
14270 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14271 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14272 ((equal key1 org-closed-string) (setq key "CLOSED"))
14273 ((equal key1 org-clock-string) (setq key "CLOCK")))
14274 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14275 (progn
14276 (push (cons key string) props)
14277 ;; no need to search further if match is found
14278 (throw 'match t))
14279 (when (or (equal key "CLOCK") (not (assoc key props)))
14280 (push (cons key string) props))))))
14283 (when (memq which '(all standard))
14284 ;; Get the standard properties, like :PROP: ...
14285 (setq range (org-get-property-block beg end))
14286 (when range
14287 (goto-char (car range))
14288 (while (re-search-forward
14289 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14290 (cdr range) t)
14291 (setq key (org-match-string-no-properties 1)
14292 value (org-trim (or (org-match-string-no-properties 2) "")))
14293 (unless (member key excluded)
14294 (push (cons key (or value "")) props)))))
14295 (if clocksum
14296 (push (cons "CLOCKSUM"
14297 (org-columns-number-to-string (/ (float clocksum) 60.)
14298 'add_times))
14299 props))
14300 (unless (assoc "CATEGORY" props)
14301 (push (cons "CATEGORY" (org-get-category)) props))
14302 (append sum-props (nreverse props)))))))
14304 (defun org-entry-get (pom property &optional inherit literal-nil)
14305 "Get value of PROPERTY for entry at point-or-marker POM.
14306 If INHERIT is non-nil and the entry does not have the property,
14307 then also check higher levels of the hierarchy.
14308 If INHERIT is the symbol `selective', use inheritance only if the setting
14309 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14310 If the property is present but empty, the return value is the empty string.
14311 If the property is not present at all, nil is returned.
14313 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14314 do not interpret it as the list atom nil. This is used for inheritance
14315 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14316 (org-with-point-at pom
14317 (if (and inherit (if (eq inherit 'selective)
14318 (org-property-inherit-p property)
14320 (org-entry-get-with-inheritance property literal-nil)
14321 (if (member property org-special-properties)
14322 ;; We need a special property. Use `org-entry-properties' to
14323 ;; retrieve it, but specify the wanted property
14324 (cdr (assoc property (org-entry-properties nil 'special property)))
14325 (let ((range (unless (org-before-first-heading-p)
14326 (org-get-property-block)))
14327 (props (list (or (assoc property org-file-properties)
14328 (assoc property org-global-properties)
14329 (assoc property org-global-properties-fixed))))
14330 val)
14331 (flet ((ap (key)
14332 (when (re-search-forward
14333 (org-re-property key) (cdr range) t)
14334 (setq props
14335 (org-update-property-plist
14337 (if (match-end 1)
14338 (org-match-string-no-properties 1) "")
14339 props)))))
14340 (when (and range (goto-char (car range)))
14341 (ap property)
14342 (goto-char (car range))
14343 (while (ap (concat property "+")))
14344 (setq val (cdr (assoc property props)))
14345 (when val (if literal-nil val (org-not-nil val))))))))))
14347 (defun org-property-or-variable-value (var &optional inherit)
14348 "Check if there is a property fixing the value of VAR.
14349 If yes, return this value. If not, return the current value of the variable."
14350 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14351 (if (and prop (stringp prop) (string-match "\\S-" prop))
14352 (read prop)
14353 (symbol-value var))))
14355 (defun org-entry-delete (pom property)
14356 "Delete the property PROPERTY from entry at point-or-marker POM."
14357 (org-with-point-at pom
14358 (if (member property org-special-properties)
14359 nil ; cannot delete these properties.
14360 (let ((range (org-get-property-block)))
14361 (if (and range
14362 (goto-char (car range))
14363 (re-search-forward
14364 (org-re-property property)
14365 (cdr range) t))
14366 (progn
14367 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14369 nil)))))
14371 ;; Multi-values properties are properties that contain multiple values
14372 ;; These values are assumed to be single words, separated by whitespace.
14373 (defun org-entry-add-to-multivalued-property (pom property value)
14374 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14375 (let* ((old (org-entry-get pom property))
14376 (values (and old (org-split-string old "[ \t]"))))
14377 (setq value (org-entry-protect-space value))
14378 (unless (member value values)
14379 (setq values (cons value values))
14380 (org-entry-put pom property
14381 (mapconcat 'identity values " ")))))
14383 (defun org-entry-remove-from-multivalued-property (pom property value)
14384 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14385 (let* ((old (org-entry-get pom property))
14386 (values (and old (org-split-string old "[ \t]"))))
14387 (setq value (org-entry-protect-space value))
14388 (when (member value values)
14389 (setq values (delete value values))
14390 (org-entry-put pom property
14391 (mapconcat 'identity values " ")))))
14393 (defun org-entry-member-in-multivalued-property (pom property value)
14394 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14395 (let* ((old (org-entry-get pom property))
14396 (values (and old (org-split-string old "[ \t]"))))
14397 (setq value (org-entry-protect-space value))
14398 (member value values)))
14400 (defun org-entry-get-multivalued-property (pom property)
14401 "Return a list of values in a multivalued property."
14402 (let* ((value (org-entry-get pom property))
14403 (values (and value (org-split-string value "[ \t]"))))
14404 (mapcar 'org-entry-restore-space values)))
14406 (defun org-entry-put-multivalued-property (pom property &rest values)
14407 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14408 VALUES should be a list of strings. Spaces will be protected."
14409 (org-entry-put pom property
14410 (mapconcat 'org-entry-protect-space values " "))
14411 (let* ((value (org-entry-get pom property))
14412 (values (and value (org-split-string value "[ \t]"))))
14413 (mapcar 'org-entry-restore-space values)))
14415 (defun org-entry-protect-space (s)
14416 "Protect spaces and newline in string S."
14417 (while (string-match " " s)
14418 (setq s (replace-match "%20" t t s)))
14419 (while (string-match "\n" s)
14420 (setq s (replace-match "%0A" t t s)))
14423 (defun org-entry-restore-space (s)
14424 "Restore spaces and newline in string S."
14425 (while (string-match "%20" s)
14426 (setq s (replace-match " " t t s)))
14427 (while (string-match "%0A" s)
14428 (setq s (replace-match "\n" t t s)))
14431 (defvar org-entry-property-inherited-from (make-marker)
14432 "Marker pointing to the entry from where a property was inherited.
14433 Each call to `org-entry-get-with-inheritance' will set this marker to the
14434 location of the entry where the inheritance search matched. If there was
14435 no match, the marker will point nowhere.
14436 Note that also `org-entry-get' calls this function, if the INHERIT flag
14437 is set.")
14439 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14440 "Get entry property, and search higher levels if not present.
14441 The search will stop at the first ancestor which has the property defined.
14442 If the value found is \"nil\", return nil to show that the property
14443 should be considered as undefined (this is the meaning of nil here).
14444 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14445 (move-marker org-entry-property-inherited-from nil)
14446 (let (tmp)
14447 (unless (org-before-first-heading-p)
14448 (save-excursion
14449 (save-restriction
14450 (widen)
14451 (catch 'ex
14452 (while t
14453 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14454 (org-back-to-heading t)
14455 (move-marker org-entry-property-inherited-from (point))
14456 (throw 'ex tmp))
14457 (or (org-up-heading-safe) (throw 'ex nil)))))))
14458 (setq tmp (or tmp
14459 (cdr (assoc property org-file-properties))
14460 (cdr (assoc property org-global-properties))
14461 (cdr (assoc property org-global-properties-fixed))))
14462 (if literal-nil tmp (org-not-nil tmp))))
14464 (defvar org-property-changed-functions nil
14465 "Hook called when the value of a property has changed.
14466 Each hook function should accept two arguments, the name of the property
14467 and the new value.")
14469 (defun org-entry-put (pom property value)
14470 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14471 (org-with-point-at pom
14472 (org-back-to-heading t)
14473 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14474 range)
14475 (cond
14476 ((equal property "TODO")
14477 (when (and (stringp value) (string-match "\\S-" value)
14478 (not (member value org-todo-keywords-1)))
14479 (error "\"%s\" is not a valid TODO state" value))
14480 (if (or (not value)
14481 (not (string-match "\\S-" value)))
14482 (setq value 'none))
14483 (org-todo value)
14484 (org-set-tags nil 'align))
14485 ((equal property "PRIORITY")
14486 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14487 (string-to-char value) ?\ ))
14488 (org-set-tags nil 'align))
14489 ((equal property "SCHEDULED")
14490 (if (re-search-forward org-scheduled-time-regexp end t)
14491 (cond
14492 ((eq value 'earlier) (org-timestamp-change -1 'day))
14493 ((eq value 'later) (org-timestamp-change 1 'day))
14494 (t (call-interactively 'org-schedule)))
14495 (call-interactively 'org-schedule)))
14496 ((equal property "DEADLINE")
14497 (if (re-search-forward org-deadline-time-regexp end t)
14498 (cond
14499 ((eq value 'earlier) (org-timestamp-change -1 'day))
14500 ((eq value 'later) (org-timestamp-change 1 'day))
14501 (t (call-interactively 'org-deadline)))
14502 (call-interactively 'org-deadline)))
14503 ((member property org-special-properties)
14504 (error "The %s property can not yet be set with `org-entry-put'"
14505 property))
14506 (t ; a non-special property
14507 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14508 (setq range (org-get-property-block beg end 'force))
14509 (goto-char (car range))
14510 (if (re-search-forward
14511 (org-re-property property) (cdr range) t)
14512 (progn
14513 (delete-region (match-beginning 0) (match-end 0))
14514 (goto-char (match-beginning 0)))
14515 (goto-char (cdr range))
14516 (insert "\n")
14517 (backward-char 1)
14518 (org-indent-line-function))
14519 (insert ":" property ":")
14520 (and value (insert " " value))
14521 (org-indent-line-function)))))
14522 (run-hook-with-args 'org-property-changed-functions property value)))
14524 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14525 "Get all property keys in the current buffer.
14526 With INCLUDE-SPECIALS, also list the special properties that reflect things
14527 like tags and TODO state.
14528 With INCLUDE-DEFAULTS, also include properties that has special meaning
14529 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14530 and others.
14531 With INCLUDE-COLUMNS, also include property names given in COLUMN
14532 formats in the current buffer."
14533 (let (rtn range cfmt s p)
14534 (save-excursion
14535 (save-restriction
14536 (widen)
14537 (goto-char (point-min))
14538 (while (re-search-forward org-property-start-re nil t)
14539 (setq range (org-get-property-block))
14540 (goto-char (car range))
14541 (while (re-search-forward
14542 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14543 (cdr range) t)
14544 (add-to-list 'rtn (org-match-string-no-properties 1)))
14545 (outline-next-heading))))
14547 (when include-specials
14548 (setq rtn (append org-special-properties rtn)))
14550 (when include-defaults
14551 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14552 (add-to-list 'rtn org-effort-property))
14554 (when include-columns
14555 (save-excursion
14556 (save-restriction
14557 (widen)
14558 (goto-char (point-min))
14559 (while (re-search-forward
14560 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14561 nil t)
14562 (setq cfmt (match-string 2) s 0)
14563 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14564 cfmt s)
14565 (setq s (match-end 0)
14566 p (match-string 1 cfmt))
14567 (unless (or (equal p "ITEM")
14568 (member p org-special-properties))
14569 (add-to-list 'rtn (match-string 1 cfmt))))))))
14571 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14573 (defun org-property-values (key)
14574 "Return a list of all values of property KEY in the current buffer."
14575 (save-excursion
14576 (save-restriction
14577 (widen)
14578 (goto-char (point-min))
14579 (let ((re (org-re-property key))
14580 values)
14581 (while (re-search-forward re nil t)
14582 (add-to-list 'values (org-trim (match-string 1))))
14583 (delete "" values)))))
14585 (defun org-insert-property-drawer ()
14586 "Insert a property drawer into the current entry."
14587 (org-back-to-heading t)
14588 (looking-at org-outline-regexp)
14589 (let ((indent (if org-adapt-indentation
14590 (- (match-end 0) (match-beginning 0))
14592 (beg (point))
14593 (re (concat "^[ \t]*" org-keyword-time-regexp))
14594 end hiddenp)
14595 (outline-next-heading)
14596 (setq end (point))
14597 (goto-char beg)
14598 (while (re-search-forward re end t))
14599 (setq hiddenp (outline-invisible-p))
14600 (end-of-line 1)
14601 (and (equal (char-after) ?\n) (forward-char 1))
14602 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14603 (if (member (match-string 1) '("CLOCK:" ":END:"))
14604 ;; just skip this line
14605 (beginning-of-line 2)
14606 ;; Drawer start, find the end
14607 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14608 (beginning-of-line 1)))
14609 (org-skip-over-state-notes)
14610 (skip-chars-backward " \t\n\r")
14611 (if (eq (char-before) ?*) (forward-char 1))
14612 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14613 (beginning-of-line 0)
14614 (org-indent-to-column indent)
14615 (beginning-of-line 2)
14616 (org-indent-to-column indent)
14617 (beginning-of-line 0)
14618 (if hiddenp
14619 (save-excursion
14620 (org-back-to-heading t)
14621 (hide-entry))
14622 (org-flag-drawer t))))
14624 (defun org-insert-drawer (&optional arg drawer)
14625 "Insert a drawer at point.
14627 Optional argument DRAWER, when non-nil, is a string representing
14628 drawer's name. Otherwise, the user is prompted for a name.
14630 If a region is active, insert the drawer around that region
14631 instead.
14633 Point is left between drawer's boundaries."
14634 (interactive "P")
14635 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14636 "LOGBOOK"))
14637 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14638 ;; internally by Org. They are meant to be inserted
14639 ;; automatically.
14640 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14641 ;; Remove system drawers from list. Note: For some reason,
14642 ;; `org-completing-read' ignores the predicate while
14643 ;; `completing-read' handles it fine.
14644 (drawer (if arg "PROPERTIES"
14645 (or drawer
14646 (completing-read
14647 "Drawer: " org-drawers
14648 (lambda (d) (not (member d system-drawers))))))))
14649 (cond
14650 ;; With C-u, fall back on `org-insert-property-drawer'
14651 (arg (org-insert-property-drawer))
14652 ;; With an active region, insert a drawer at point.
14653 ((not (org-region-active-p))
14654 (progn
14655 (unless (bolp) (insert "\n"))
14656 (insert (format ":%s:\n\n:END:\n" drawer))
14657 (forward-line -2)))
14658 ;; Otherwise, insert the drawer at point
14660 (let ((rbeg (region-beginning))
14661 (rend (copy-marker (region-end))))
14662 (unwind-protect
14663 (progn
14664 (goto-char rbeg)
14665 (beginning-of-line)
14666 (when (save-excursion
14667 (re-search-forward org-outline-regexp-bol rend t))
14668 (error "Drawers cannot contain headlines"))
14669 ;; Position point at the beginning of the first
14670 ;; non-blank line in region. Insert drawer's opening
14671 ;; there, then indent it.
14672 (org-skip-whitespace)
14673 (beginning-of-line)
14674 (insert ":" drawer ":\n")
14675 (forward-line -1)
14676 (indent-for-tab-command)
14677 ;; Move point to the beginning of the first blank line
14678 ;; after the last non-blank line in region. Insert
14679 ;; drawer's closing, then indent it.
14680 (goto-char rend)
14681 (skip-chars-backward " \r\t\n")
14682 (insert "\n:END:")
14683 (indent-for-tab-command)
14684 (unless (eolp) (insert "\n")))
14685 ;; Clear marker, whatever the outcome of insertion is.
14686 (set-marker rend nil)))))))
14688 (defvar org-property-set-functions-alist nil
14689 "Property set function alist.
14690 Each entry should have the following format:
14692 (PROPERTY . READ-FUNCTION)
14694 The read function will be called with the same argument as
14695 `org-completing-read'.")
14697 (defun org-set-property-function (property)
14698 "Get the function that should be used to set PROPERTY.
14699 This is computed according to `org-property-set-functions-alist'."
14700 (or (cdr (assoc property org-property-set-functions-alist))
14701 'org-completing-read))
14703 (defun org-read-property-value (property)
14704 "Read PROPERTY value from user."
14705 (let* ((completion-ignore-case t)
14706 (allowed (org-property-get-allowed-values nil property 'table))
14707 (cur (org-entry-get nil property))
14708 (prompt (concat property " value"
14709 (if (and cur (string-match "\\S-" cur))
14710 (concat " [" cur "]") "") ": "))
14711 (set-function (org-set-property-function property))
14712 (val (if allowed
14713 (funcall set-function prompt allowed nil
14714 (not (get-text-property 0 'org-unrestricted
14715 (caar allowed))))
14716 (let (org-completion-use-ido org-completion-use-iswitchb)
14717 (funcall set-function prompt
14718 (mapcar 'list (org-property-values property))
14719 nil nil "" nil cur)))))
14720 (if (equal val "")
14722 val)))
14724 (defvar org-last-set-property nil)
14725 (defun org-read-property-name ()
14726 "Read a property name."
14727 (let* ((completion-ignore-case t)
14728 (keys (org-buffer-property-keys nil t t))
14729 (default-prop (or (save-excursion
14730 (save-match-data
14731 (beginning-of-line)
14732 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14733 (null (string= (match-string 1) "END"))
14734 (match-string 1))))
14735 org-last-set-property))
14736 (property (org-icompleting-read
14737 (concat "Property"
14738 (if default-prop (concat " [" default-prop "]") "")
14739 ": ")
14740 (mapcar 'list keys)
14741 nil nil nil nil
14742 default-prop
14744 (if (member property keys)
14745 property
14746 (or (cdr (assoc (downcase property)
14747 (mapcar (lambda (x) (cons (downcase x) x))
14748 keys)))
14749 property))))
14751 (defun org-set-property (property value)
14752 "In the current entry, set PROPERTY to VALUE.
14753 When called interactively, this will prompt for a property name, offering
14754 completion on existing and default properties. And then it will prompt
14755 for a value, offering completion either on allowed values (via an inherited
14756 xxx_ALL property) or on existing values in other instances of this property
14757 in the current file."
14758 (interactive (list nil nil))
14759 (let* ((property (or property (org-read-property-name)))
14760 (value (or value (org-read-property-value property)))
14761 (fn (cdr (assoc property org-properties-postprocess-alist))))
14762 (setq org-last-set-property property)
14763 ;; Possibly postprocess the inserted value:
14764 (when fn (setq value (funcall fn value)))
14765 (unless (equal (org-entry-get nil property) value)
14766 (org-entry-put nil property value))))
14768 (defun org-delete-property (property)
14769 "In the current entry, delete PROPERTY."
14770 (interactive
14771 (let* ((completion-ignore-case t)
14772 (prop (org-icompleting-read "Property: "
14773 (org-entry-properties nil 'standard))))
14774 (list prop)))
14775 (message "Property %s %s" property
14776 (if (org-entry-delete nil property)
14777 "deleted"
14778 "was not present in the entry")))
14780 (defun org-delete-property-globally (property)
14781 "Remove PROPERTY globally, from all entries."
14782 (interactive
14783 (let* ((completion-ignore-case t)
14784 (prop (org-icompleting-read
14785 "Globally remove property: "
14786 (mapcar 'list (org-buffer-property-keys)))))
14787 (list prop)))
14788 (save-excursion
14789 (save-restriction
14790 (widen)
14791 (goto-char (point-min))
14792 (let ((cnt 0))
14793 (while (re-search-forward
14794 (org-re-property property)
14795 nil t)
14796 (setq cnt (1+ cnt))
14797 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14798 (message "Property \"%s\" removed from %d entries" property cnt)))))
14800 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14802 (defun org-compute-property-at-point ()
14803 "Compute the property at point.
14804 This looks for an enclosing column format, extracts the operator and
14805 then applies it to the property in the column format's scope."
14806 (interactive)
14807 (unless (org-at-property-p)
14808 (error "Not at a property"))
14809 (let ((prop (org-match-string-no-properties 2)))
14810 (org-columns-get-format-and-top-level)
14811 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14812 (error "No operator defined for property %s" prop))
14813 (org-columns-compute prop)))
14815 (defvar org-property-allowed-value-functions nil
14816 "Hook for functions supplying allowed values for a specific property.
14817 The functions must take a single argument, the name of the property, and
14818 return a flat list of allowed values. If \":ETC\" is one of
14819 the values, this means that these values are intended as defaults for
14820 completion, but that other values should be allowed too.
14821 The functions must return nil if they are not responsible for this
14822 property.")
14824 (defun org-property-get-allowed-values (pom property &optional table)
14825 "Get allowed values for the property PROPERTY.
14826 When TABLE is non-nil, return an alist that can directly be used for
14827 completion."
14828 (let (vals)
14829 (cond
14830 ((equal property "TODO")
14831 (setq vals (org-with-point-at pom
14832 (append org-todo-keywords-1 '("")))))
14833 ((equal property "PRIORITY")
14834 (let ((n org-lowest-priority))
14835 (while (>= n org-highest-priority)
14836 (push (char-to-string n) vals)
14837 (setq n (1- n)))))
14838 ((member property org-special-properties))
14839 ((setq vals (run-hook-with-args-until-success
14840 'org-property-allowed-value-functions property)))
14842 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14843 (when (and vals (string-match "\\S-" vals))
14844 (setq vals (car (read-from-string (concat "(" vals ")"))))
14845 (setq vals (mapcar (lambda (x)
14846 (cond ((stringp x) x)
14847 ((numberp x) (number-to-string x))
14848 ((symbolp x) (symbol-name x))
14849 (t "???")))
14850 vals)))))
14851 (when (member ":ETC" vals)
14852 (setq vals (remove ":ETC" vals))
14853 (org-add-props (car vals) '(org-unrestricted t)))
14854 (if table (mapcar 'list vals) vals)))
14856 (defun org-property-previous-allowed-value (&optional previous)
14857 "Switch to the next allowed value for this property."
14858 (interactive)
14859 (org-property-next-allowed-value t))
14861 (defun org-property-next-allowed-value (&optional previous)
14862 "Switch to the next allowed value for this property."
14863 (interactive)
14864 (unless (org-at-property-p)
14865 (error "Not at a property"))
14866 (let* ((key (match-string 2))
14867 (value (match-string 3))
14868 (allowed (or (org-property-get-allowed-values (point) key)
14869 (and (member value '("[ ]" "[-]" "[X]"))
14870 '("[ ]" "[X]"))))
14871 nval)
14872 (unless allowed
14873 (error "Allowed values for this property have not been defined"))
14874 (if previous (setq allowed (reverse allowed)))
14875 (if (member value allowed)
14876 (setq nval (car (cdr (member value allowed)))))
14877 (setq nval (or nval (car allowed)))
14878 (if (equal nval value)
14879 (error "Only one allowed value for this property"))
14880 (org-at-property-p)
14881 (replace-match (concat " :" key ": " nval) t t)
14882 (org-indent-line-function)
14883 (beginning-of-line 1)
14884 (skip-chars-forward " \t")
14885 (run-hook-with-args 'org-property-changed-functions key nval)))
14887 (defun org-find-olp (path &optional this-buffer)
14888 "Return a marker pointing to the entry at outline path OLP.
14889 If anything goes wrong, throw an error.
14890 You can wrap this call to catch the error like this:
14892 (condition-case msg
14893 (org-mobile-locate-entry (match-string 4))
14894 (error (nth 1 msg)))
14896 The return value will then be either a string with the error message,
14897 or a marker if everything is OK.
14899 If THIS-BUFFER is set, the outline path does not contain a file,
14900 only headings."
14901 (let* ((file (if this-buffer buffer-file-name (pop path)))
14902 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14903 (level 1)
14904 (lmin 1)
14905 (lmax 1)
14906 limit re end found pos heading cnt flevel)
14907 (unless buffer (error "File not found :%s" file))
14908 (with-current-buffer buffer
14909 (save-excursion
14910 (save-restriction
14911 (widen)
14912 (setq limit (point-max))
14913 (goto-char (point-min))
14914 (while (setq heading (pop path))
14915 (setq re (format org-complex-heading-regexp-format
14916 (regexp-quote heading)))
14917 (setq cnt 0 pos (point))
14918 (while (re-search-forward re end t)
14919 (setq level (- (match-end 1) (match-beginning 1)))
14920 (if (and (>= level lmin) (<= level lmax))
14921 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14922 (when (= cnt 0) (error "Heading not found on level %d: %s"
14923 lmax heading))
14924 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14925 lmax heading))
14926 (goto-char found)
14927 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14928 (setq end (save-excursion (org-end-of-subtree t t))))
14929 (when (org-at-heading-p)
14930 (move-marker (make-marker) (point))))))))
14932 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14933 "Find node HEADING in BUFFER.
14934 Return a marker to the heading if it was found, or nil if not.
14935 If POS-ONLY is set, return just the position instead of a marker.
14937 The heading text must match exact, but it may have a TODO keyword,
14938 a priority cookie and tags in the standard locations."
14939 (with-current-buffer (or buffer (current-buffer))
14940 (save-excursion
14941 (save-restriction
14942 (widen)
14943 (goto-char (point-min))
14944 (let (case-fold-search)
14945 (if (re-search-forward
14946 (format org-complex-heading-regexp-format
14947 (regexp-quote heading)) nil t)
14948 (if pos-only
14949 (match-beginning 0)
14950 (move-marker (make-marker) (match-beginning 0)))))))))
14952 (defun org-find-exact-heading-in-directory (heading &optional dir)
14953 "Find Org node headline HEADING in all .org files in directory DIR.
14954 When the target headline is found, return a marker to this location."
14955 (let ((files (directory-files (or dir default-directory)
14956 nil "\\`[^.#].*\\.org\\'"))
14957 file visiting m buffer)
14958 (catch 'found
14959 (while (setq file (pop files))
14960 (message "trying %s" file)
14961 (setq visiting (org-find-base-buffer-visiting file))
14962 (setq buffer (or visiting (find-file-noselect file)))
14963 (setq m (org-find-exact-headline-in-buffer
14964 heading buffer))
14965 (when (and (not m) (not visiting)) (kill-buffer buffer))
14966 (and m (throw 'found m))))))
14968 (defun org-find-entry-with-id (ident)
14969 "Locate the entry that contains the ID property with exact value IDENT.
14970 IDENT can be a string, a symbol or a number, this function will search for
14971 the string representation of it.
14972 Return the position where this entry starts, or nil if there is no such entry."
14973 (interactive "sID: ")
14974 (let ((id (cond
14975 ((stringp ident) ident)
14976 ((symbol-name ident) (symbol-name ident))
14977 ((numberp ident) (number-to-string ident))
14978 (t (error "IDENT %s must be a string, symbol or number" ident))))
14979 (case-fold-search nil))
14980 (save-excursion
14981 (save-restriction
14982 (widen)
14983 (goto-char (point-min))
14984 (when (re-search-forward
14985 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14986 nil t)
14987 (org-back-to-heading t)
14988 (point))))))
14990 ;;;; Timestamps
14992 (defvar org-last-changed-timestamp nil)
14993 (defvar org-last-inserted-timestamp nil
14994 "The last time stamp inserted with `org-insert-time-stamp'.")
14995 (defvar org-time-was-given) ; dynamically scoped parameter
14996 (defvar org-end-time-was-given) ; dynamically scoped parameter
14997 (defvar org-ts-what) ; dynamically scoped parameter
14999 (defun org-time-stamp (arg &optional inactive)
15000 "Prompt for a date/time and insert a time stamp.
15001 If the user specifies a time like HH:MM, or if this command is called
15002 with a prefix argument, the time stamp will contain date and time.
15003 Otherwise, only the date will be included. All parts of a date not
15004 specified by the user will be filled in from the current date/time.
15005 So if you press just return without typing anything, the time stamp
15006 will represent the current date/time. If there is already a timestamp
15007 at the cursor, it will be modified."
15008 (interactive "P")
15009 (let* ((ts nil)
15010 (default-time
15011 ;; Default time is either today, or, when entering a range,
15012 ;; the range start.
15013 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15014 (save-excursion
15015 (re-search-backward
15016 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15017 (- (point) 20) t)))
15018 (apply 'encode-time (org-parse-time-string (match-string 1)))
15019 (current-time)))
15020 (default-input (and ts (org-get-compact-tod ts)))
15021 (repeater (save-excursion
15022 (save-match-data
15023 (beginning-of-line)
15024 (when (re-search-forward
15025 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15026 (save-excursion (progn (end-of-line) (point))) t)
15027 (match-string 0)))))
15028 org-time-was-given org-end-time-was-given time)
15029 (cond
15030 ((and (org-at-timestamp-p t)
15031 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15032 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15033 (insert "--")
15034 (setq time (let ((this-command this-command))
15035 (org-read-date arg 'totime nil nil
15036 default-time default-input inactive)))
15037 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15038 ((org-at-timestamp-p t)
15039 (setq time (let ((this-command this-command))
15040 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15041 (when (org-at-timestamp-p t) ; just to get the match data
15042 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15043 (replace-match "")
15044 (setq org-last-changed-timestamp
15045 (org-insert-time-stamp
15046 time (or org-time-was-given arg)
15047 inactive nil nil (list org-end-time-was-given)))
15048 (when repeater (goto-char (1- (point))) (insert " " repeater)
15049 (setq org-last-changed-timestamp
15050 (concat (substring org-last-inserted-timestamp 0 -1)
15051 " " repeater ">"))))
15052 (message "Timestamp updated"))
15054 (setq time (let ((this-command this-command))
15055 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15056 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15057 nil nil (list org-end-time-was-given))))))
15059 ;; FIXME: can we use this for something else, like computing time differences?
15060 (defun org-get-compact-tod (s)
15061 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15062 (let* ((t1 (match-string 1 s))
15063 (h1 (string-to-number (match-string 2 s)))
15064 (m1 (string-to-number (match-string 3 s)))
15065 (t2 (and (match-end 4) (match-string 5 s)))
15066 (h2 (and t2 (string-to-number (match-string 6 s))))
15067 (m2 (and t2 (string-to-number (match-string 7 s))))
15068 dh dm)
15069 (if (not t2)
15071 (setq dh (- h2 h1) dm (- m2 m1))
15072 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15073 (concat t1 "+" (number-to-string dh)
15074 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15076 (defun org-time-stamp-inactive (&optional arg)
15077 "Insert an inactive time stamp.
15078 An inactive time stamp is enclosed in square brackets instead of angle
15079 brackets. It is inactive in the sense that it does not trigger agenda entries,
15080 does not link to the calendar and cannot be changed with the S-cursor keys.
15081 So these are more for recording a certain time/date."
15082 (interactive "P")
15083 (org-time-stamp arg 'inactive))
15085 (defvar org-date-ovl (make-overlay 1 1))
15086 (overlay-put org-date-ovl 'face 'org-date-selected)
15087 (org-detach-overlay org-date-ovl)
15089 (defvar org-ans1) ; dynamically scoped parameter
15090 (defvar org-ans2) ; dynamically scoped parameter
15092 (defvar org-plain-time-of-day-regexp) ; defined below
15094 (defvar org-overriding-default-time nil) ; dynamically scoped
15095 (defvar org-read-date-overlay nil)
15096 (defvar org-dcst nil) ; dynamically scoped
15097 (defvar org-read-date-history nil)
15098 (defvar org-read-date-final-answer nil)
15099 (defvar org-read-date-analyze-futurep nil)
15100 (defvar org-read-date-analyze-forced-year nil)
15101 (defvar org-read-date-inactive)
15103 (defun org-read-date (&optional org-with-time to-time from-string prompt
15104 default-time default-input inactive)
15105 "Read a date, possibly a time, and make things smooth for the user.
15106 The prompt will suggest to enter an ISO date, but you can also enter anything
15107 which will at least partially be understood by `parse-time-string'.
15108 Unrecognized parts of the date will default to the current day, month, year,
15109 hour and minute. If this command is called to replace a timestamp at point,
15110 or to enter the second timestamp of a range, the default time is taken
15111 from the existing stamp. Furthermore, the command prefers the future,
15112 so if you are giving a date where the year is not given, and the day-month
15113 combination is already past in the current year, it will assume you
15114 mean next year. For details, see the manual. A few examples:
15116 3-2-5 --> 2003-02-05
15117 feb 15 --> currentyear-02-15
15118 2/15 --> currentyear-02-15
15119 sep 12 9 --> 2009-09-12
15120 12:45 --> today 12:45
15121 22 sept 0:34 --> currentyear-09-22 0:34
15122 12 --> currentyear-currentmonth-12
15123 Fri --> nearest Friday (today or later)
15124 etc.
15126 Furthermore you can specify a relative date by giving, as the *first* thing
15127 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15128 change in days weeks, months, years.
15129 With a single plus or minus, the date is relative to today. With a double
15130 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15131 +4d --> four days from today
15132 +4 --> same as above
15133 +2w --> two weeks from today
15134 ++5 --> five days from default date
15136 The function understands only English month and weekday abbreviations.
15138 While prompting, a calendar is popped up - you can also select the
15139 date with the mouse (button 1). The calendar shows a period of three
15140 months. To scroll it to other months, use the keys `>' and `<'.
15141 If you don't like the calendar, turn it off with
15142 \(setq org-read-date-popup-calendar nil)
15144 With optional argument TO-TIME, the date will immediately be converted
15145 to an internal time.
15146 With an optional argument WITH-TIME, the prompt will suggest to also
15147 insert a time. Note that when WITH-TIME is not set, you can still
15148 enter a time, and this function will inform the calling routine about
15149 this change. The calling routine may then choose to change the format
15150 used to insert the time stamp into the buffer to include the time.
15151 With optional argument FROM-STRING, read from this string instead from
15152 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15153 the time/date that is used for everything that is not specified by the
15154 user."
15155 (require 'parse-time)
15156 (let* ((org-time-stamp-rounding-minutes
15157 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15158 (org-dcst org-display-custom-times)
15159 (ct (org-current-time))
15160 (org-def (or org-overriding-default-time default-time ct))
15161 (org-defdecode (decode-time org-def))
15162 (dummy (progn
15163 (when (< (nth 2 org-defdecode) org-extend-today-until)
15164 (setcar (nthcdr 2 org-defdecode) -1)
15165 (setcar (nthcdr 1 org-defdecode) 59)
15166 (setq org-def (apply 'encode-time org-defdecode)
15167 org-defdecode (decode-time org-def)))))
15168 (calendar-frame-setup nil)
15169 (calendar-setup nil)
15170 (calendar-move-hook nil)
15171 (calendar-view-diary-initially-flag nil)
15172 (calendar-view-holidays-initially-flag nil)
15173 (timestr (format-time-string
15174 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15175 (prompt (concat (if prompt (concat prompt " ") "")
15176 (format "Date+time [%s]: " timestr)))
15177 ans (org-ans0 "") org-ans1 org-ans2 final)
15179 (cond
15180 (from-string (setq ans from-string))
15181 (org-read-date-popup-calendar
15182 (save-excursion
15183 (save-window-excursion
15184 (calendar)
15185 (org-eval-in-calendar '(setq cursor-type nil) t)
15186 (unwind-protect
15187 (progn
15188 (calendar-forward-day (- (time-to-days org-def)
15189 (calendar-absolute-from-gregorian
15190 (calendar-current-date))))
15191 (org-eval-in-calendar nil t)
15192 (let* ((old-map (current-local-map))
15193 (map (copy-keymap calendar-mode-map))
15194 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15195 (org-defkey map (kbd "RET") 'org-calendar-select)
15196 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15197 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15198 (org-defkey minibuffer-local-map [(meta shift left)]
15199 (lambda () (interactive)
15200 (org-eval-in-calendar '(calendar-backward-month 1))))
15201 (org-defkey minibuffer-local-map [(meta shift right)]
15202 (lambda () (interactive)
15203 (org-eval-in-calendar '(calendar-forward-month 1))))
15204 (org-defkey minibuffer-local-map [(meta shift up)]
15205 (lambda () (interactive)
15206 (org-eval-in-calendar '(calendar-backward-year 1))))
15207 (org-defkey minibuffer-local-map [(meta shift down)]
15208 (lambda () (interactive)
15209 (org-eval-in-calendar '(calendar-forward-year 1))))
15210 (org-defkey minibuffer-local-map [?\e (shift left)]
15211 (lambda () (interactive)
15212 (org-eval-in-calendar '(calendar-backward-month 1))))
15213 (org-defkey minibuffer-local-map [?\e (shift right)]
15214 (lambda () (interactive)
15215 (org-eval-in-calendar '(calendar-forward-month 1))))
15216 (org-defkey minibuffer-local-map [?\e (shift up)]
15217 (lambda () (interactive)
15218 (org-eval-in-calendar '(calendar-backward-year 1))))
15219 (org-defkey minibuffer-local-map [?\e (shift down)]
15220 (lambda () (interactive)
15221 (org-eval-in-calendar '(calendar-forward-year 1))))
15222 (org-defkey minibuffer-local-map [(shift up)]
15223 (lambda () (interactive)
15224 (org-eval-in-calendar '(calendar-backward-week 1))))
15225 (org-defkey minibuffer-local-map [(shift down)]
15226 (lambda () (interactive)
15227 (org-eval-in-calendar '(calendar-forward-week 1))))
15228 (org-defkey minibuffer-local-map [(shift left)]
15229 (lambda () (interactive)
15230 (org-eval-in-calendar '(calendar-backward-day 1))))
15231 (org-defkey minibuffer-local-map [(shift right)]
15232 (lambda () (interactive)
15233 (org-eval-in-calendar '(calendar-forward-day 1))))
15234 (org-defkey minibuffer-local-map ">"
15235 (lambda () (interactive)
15236 (org-eval-in-calendar '(scroll-calendar-left 1))))
15237 (org-defkey minibuffer-local-map "<"
15238 (lambda () (interactive)
15239 (org-eval-in-calendar '(scroll-calendar-right 1))))
15240 (org-defkey minibuffer-local-map "\C-v"
15241 (lambda () (interactive)
15242 (org-eval-in-calendar
15243 '(calendar-scroll-left-three-months 1))))
15244 (org-defkey minibuffer-local-map "\M-v"
15245 (lambda () (interactive)
15246 (org-eval-in-calendar
15247 '(calendar-scroll-right-three-months 1))))
15248 (run-hooks 'org-read-date-minibuffer-setup-hook)
15249 (unwind-protect
15250 (progn
15251 (use-local-map map)
15252 (setq org-read-date-inactive inactive)
15253 (add-hook 'post-command-hook 'org-read-date-display)
15254 (setq org-ans0 (read-string prompt default-input
15255 'org-read-date-history nil))
15256 ;; org-ans0: from prompt
15257 ;; org-ans1: from mouse click
15258 ;; org-ans2: from calendar motion
15259 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15260 (remove-hook 'post-command-hook 'org-read-date-display)
15261 (use-local-map old-map)
15262 (when org-read-date-overlay
15263 (delete-overlay org-read-date-overlay)
15264 (setq org-read-date-overlay nil)))))
15265 (bury-buffer "*Calendar*")))))
15267 (t ; Naked prompt only
15268 (unwind-protect
15269 (setq ans (read-string prompt default-input
15270 'org-read-date-history timestr))
15271 (when org-read-date-overlay
15272 (delete-overlay org-read-date-overlay)
15273 (setq org-read-date-overlay nil)))))
15275 (setq final (org-read-date-analyze ans org-def org-defdecode))
15277 (when org-read-date-analyze-forced-year
15278 (message "Year was forced into %s"
15279 (if org-read-date-force-compatible-dates
15280 "compatible range (1970-2037)"
15281 "range representable on this machine"))
15282 (ding))
15284 ;; One round trip to get rid of 34th of August and stuff like that....
15285 (setq final (decode-time (apply 'encode-time final)))
15287 (setq org-read-date-final-answer ans)
15289 (if to-time
15290 (apply 'encode-time final)
15291 (if (and (boundp 'org-time-was-given) org-time-was-given)
15292 (format "%04d-%02d-%02d %02d:%02d"
15293 (nth 5 final) (nth 4 final) (nth 3 final)
15294 (nth 2 final) (nth 1 final))
15295 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15297 (defvar org-def)
15298 (defvar org-defdecode)
15299 (defvar org-with-time)
15300 (defun org-read-date-display ()
15301 "Display the current date prompt interpretation in the minibuffer."
15302 (when org-read-date-display-live
15303 (when org-read-date-overlay
15304 (delete-overlay org-read-date-overlay))
15305 (when (minibufferp (current-buffer))
15306 (save-excursion
15307 (end-of-line 1)
15308 (while (not (equal (buffer-substring
15309 (max (point-min) (- (point) 4)) (point))
15310 " "))
15311 (insert " ")))
15312 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15313 " " (or org-ans1 org-ans2)))
15314 (org-end-time-was-given nil)
15315 (f (org-read-date-analyze ans org-def org-defdecode))
15316 (fmts (if org-dcst
15317 org-time-stamp-custom-formats
15318 org-time-stamp-formats))
15319 (fmt (if (or org-with-time
15320 (and (boundp 'org-time-was-given) org-time-was-given))
15321 (cdr fmts)
15322 (car fmts)))
15323 (txt (format-time-string fmt (apply 'encode-time f)))
15324 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15325 (txt (concat "=> " txt)))
15326 (when (and org-end-time-was-given
15327 (string-match org-plain-time-of-day-regexp txt))
15328 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15329 org-end-time-was-given
15330 (substring txt (match-end 0)))))
15331 (when org-read-date-analyze-futurep
15332 (setq txt (concat txt " (=>F)")))
15333 (setq org-read-date-overlay
15334 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15335 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15337 (defun org-read-date-analyze (ans org-def org-defdecode)
15338 "Analyze the combined answer of the date prompt."
15339 ;; FIXME: cleanup and comment
15340 (let ((nowdecode (decode-time (current-time)))
15341 delta deltan deltaw deltadef year month day
15342 hour minute second wday pm h2 m2 tl wday1
15343 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15344 (setq org-read-date-analyze-futurep nil
15345 org-read-date-analyze-forced-year nil)
15346 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15347 (setq ans "+0"))
15349 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15350 (setq ans (replace-match "" t t ans)
15351 deltan (car delta)
15352 deltaw (nth 1 delta)
15353 deltadef (nth 2 delta)))
15355 ;; Check if there is an iso week date in there
15356 ;; If yes, store the info and postpone interpreting it until the rest
15357 ;; of the parsing is done
15358 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15359 (setq iso-year (if (match-end 1)
15360 (org-small-year-to-year
15361 (string-to-number (match-string 1 ans))))
15362 iso-weekday (if (match-end 3)
15363 (string-to-number (match-string 3 ans)))
15364 iso-week (string-to-number (match-string 2 ans)))
15365 (setq ans (replace-match "" t t ans)))
15367 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15368 (when (string-match
15369 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15370 (setq year (if (match-end 2)
15371 (string-to-number (match-string 2 ans))
15372 (progn (setq kill-year t)
15373 (string-to-number (format-time-string "%Y"))))
15374 month (string-to-number (match-string 3 ans))
15375 day (string-to-number (match-string 4 ans)))
15376 (if (< year 100) (setq year (+ 2000 year)))
15377 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15378 t nil ans)))
15380 ;; Help matching dotted european dates
15381 (when (string-match
15382 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15383 (setq year (if (match-end 3)
15384 (string-to-number (match-string 3 ans))
15385 (progn (setq kill-year t)
15386 (string-to-number (format-time-string "%Y"))))
15387 day (string-to-number (match-string 1 ans))
15388 month (string-to-number (match-string 2 ans))
15389 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15390 t nil ans)))
15392 ;; Help matching american dates, like 5/30 or 5/30/7
15393 (when (string-match
15394 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15395 (setq year (if (match-end 4)
15396 (string-to-number (match-string 4 ans))
15397 (progn (setq kill-year t)
15398 (string-to-number (format-time-string "%Y"))))
15399 month (string-to-number (match-string 1 ans))
15400 day (string-to-number (match-string 2 ans)))
15401 (if (< year 100) (setq year (+ 2000 year)))
15402 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15403 t nil ans)))
15404 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15405 ;; If there is a time with am/pm, and *no* time without it, we convert
15406 ;; so that matching will be successful.
15407 (loop for i from 1 to 2 do ; twice, for end time as well
15408 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15409 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15410 (setq hour (string-to-number (match-string 1 ans))
15411 minute (if (match-end 3)
15412 (string-to-number (match-string 3 ans))
15414 pm (equal ?p
15415 (string-to-char (downcase (match-string 4 ans)))))
15416 (if (and (= hour 12) (not pm))
15417 (setq hour 0)
15418 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15419 (setq ans (replace-match (format "%02d:%02d" hour minute)
15420 t t ans))))
15422 ;; Check if a time range is given as a duration
15423 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15424 (setq hour (string-to-number (match-string 1 ans))
15425 h2 (+ hour (string-to-number (match-string 3 ans)))
15426 minute (string-to-number (match-string 2 ans))
15427 m2 (+ minute (if (match-end 5) (string-to-number
15428 (match-string 5 ans))0)))
15429 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15430 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15431 t t ans)))
15433 ;; Check if there is a time range
15434 (when (boundp 'org-end-time-was-given)
15435 (setq org-time-was-given nil)
15436 (when (and (string-match org-plain-time-of-day-regexp ans)
15437 (match-end 8))
15438 (setq org-end-time-was-given (match-string 8 ans))
15439 (setq ans (concat (substring ans 0 (match-beginning 7))
15440 (substring ans (match-end 7))))))
15442 (setq tl (parse-time-string ans)
15443 day (or (nth 3 tl) (nth 3 org-defdecode))
15444 month (or (nth 4 tl)
15445 (if (and org-read-date-prefer-future
15446 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15447 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15448 (nth 4 org-defdecode)))
15449 year (or (and (not kill-year) (nth 5 tl))
15450 (if (and org-read-date-prefer-future
15451 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15452 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15453 (nth 5 org-defdecode)))
15454 hour (or (nth 2 tl) (nth 2 org-defdecode))
15455 minute (or (nth 1 tl) (nth 1 org-defdecode))
15456 second (or (nth 0 tl) 0)
15457 wday (nth 6 tl))
15459 (when (and (eq org-read-date-prefer-future 'time)
15460 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15461 (equal day (nth 3 nowdecode))
15462 (equal month (nth 4 nowdecode))
15463 (equal year (nth 5 nowdecode))
15464 (nth 2 tl)
15465 (or (< (nth 2 tl) (nth 2 nowdecode))
15466 (and (= (nth 2 tl) (nth 2 nowdecode))
15467 (nth 1 tl)
15468 (< (nth 1 tl) (nth 1 nowdecode)))))
15469 (setq day (1+ day)
15470 futurep t))
15472 ;; Special date definitions below
15473 (cond
15474 (iso-week
15475 ;; There was an iso week
15476 (require 'cal-iso)
15477 (setq futurep nil)
15478 (setq year (or iso-year year)
15479 day (or iso-weekday wday 1)
15480 wday nil ; to make sure that the trigger below does not match
15481 iso-date (calendar-gregorian-from-absolute
15482 (calendar-absolute-from-iso
15483 (list iso-week day year))))
15484 ; FIXME: Should we also push ISO weeks into the future?
15485 ; (when (and org-read-date-prefer-future
15486 ; (not iso-year)
15487 ; (< (calendar-absolute-from-gregorian iso-date)
15488 ; (time-to-days (current-time))))
15489 ; (setq year (1+ year)
15490 ; iso-date (calendar-gregorian-from-absolute
15491 ; (calendar-absolute-from-iso
15492 ; (list iso-week day year)))))
15493 (setq month (car iso-date)
15494 year (nth 2 iso-date)
15495 day (nth 1 iso-date)))
15496 (deltan
15497 (setq futurep nil)
15498 (unless deltadef
15499 (let ((now (decode-time (current-time))))
15500 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15501 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15502 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15503 ((equal deltaw "m") (setq month (+ month deltan)))
15504 ((equal deltaw "y") (setq year (+ year deltan)))))
15505 ((and wday (not (nth 3 tl)))
15506 (setq futurep nil)
15507 ;; Weekday was given, but no day, so pick that day in the week
15508 ;; on or after the derived date.
15509 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15510 (unless (equal wday wday1)
15511 (setq day (+ day (% (- wday wday1 -7) 7))))))
15512 (if (and (boundp 'org-time-was-given)
15513 (nth 2 tl))
15514 (setq org-time-was-given t))
15515 (if (< year 100) (setq year (+ 2000 year)))
15516 ;; Check of the date is representable
15517 (if org-read-date-force-compatible-dates
15518 (progn
15519 (if (< year 1970)
15520 (setq year 1970 org-read-date-analyze-forced-year t))
15521 (if (> year 2037)
15522 (setq year 2037 org-read-date-analyze-forced-year t)))
15523 (condition-case nil
15524 (ignore (encode-time second minute hour day month year))
15525 (error
15526 (setq year (nth 5 org-defdecode))
15527 (setq org-read-date-analyze-forced-year t))))
15528 (setq org-read-date-analyze-futurep futurep)
15529 (list second minute hour day month year)))
15531 (defvar parse-time-weekdays)
15532 (defun org-read-date-get-relative (s today default)
15533 "Check string S for special relative date string.
15534 TODAY and DEFAULT are internal times, for today and for a default.
15535 Return shift list (N what def-flag)
15536 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15537 N is the number of WHATs to shift.
15538 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15539 the DEFAULT date rather than TODAY."
15540 (require 'parse-time)
15541 (when (and
15542 (string-match
15543 (concat
15544 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15545 "\\([0-9]+\\)?"
15546 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15547 "\\([ \t]\\|$\\)") s)
15548 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15549 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15550 (string-to-char (substring (match-string 1 s) -1))
15551 ?+))
15552 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15553 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15554 (what (if (match-end 3) (match-string 3 s) "d"))
15555 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15556 (date (if rel default today))
15557 (wday (nth 6 (decode-time date)))
15558 delta)
15559 (if wday1
15560 (progn
15561 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15562 (if (= dir ?-) (setq delta (- delta 7)))
15563 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15564 (list delta "d" rel))
15565 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15567 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15568 "Turn a user-specified date into the internal representation.
15569 The internal representation needed by the calendar is (month day year).
15570 This is a wrapper to handle the brain-dead convention in calendar that
15571 user function argument order change dependent on argument order."
15572 (if (boundp 'calendar-date-style)
15573 (cond
15574 ((eq calendar-date-style 'american)
15575 (list arg1 arg2 arg3))
15576 ((eq calendar-date-style 'european)
15577 (list arg2 arg1 arg3))
15578 ((eq calendar-date-style 'iso)
15579 (list arg2 arg3 arg1)))
15580 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15581 (if (org-bound-and-true-p european-calendar-style)
15582 (list arg2 arg1 arg3)
15583 (list arg1 arg2 arg3)))))
15585 (defun org-eval-in-calendar (form &optional keepdate)
15586 "Eval FORM in the calendar window and return to current window.
15587 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15588 otherwise stick to the current value of `org-ans2'."
15589 (let ((sf (selected-frame))
15590 (sw (selected-window)))
15591 (select-window (get-buffer-window "*Calendar*" t))
15592 (eval form)
15593 (when (and (not keepdate) (calendar-cursor-to-date))
15594 (let* ((date (calendar-cursor-to-date))
15595 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15596 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15597 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15598 (select-window sw)
15599 (org-select-frame-set-input-focus sf)))
15601 (defun org-calendar-select ()
15602 "Return to `org-read-date' with the date currently selected.
15603 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15604 (interactive)
15605 (when (calendar-cursor-to-date)
15606 (let* ((date (calendar-cursor-to-date))
15607 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15608 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15609 (if (active-minibuffer-window) (exit-minibuffer))))
15611 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15612 "Insert a date stamp for the date given by the internal TIME.
15613 WITH-HM means use the stamp format that includes the time of the day.
15614 INACTIVE means use square brackets instead of angular ones, so that the
15615 stamp will not contribute to the agenda.
15616 PRE and POST are optional strings to be inserted before and after the
15617 stamp.
15618 The command returns the inserted time stamp."
15619 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15620 stamp)
15621 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15622 (insert-before-markers (or pre ""))
15623 (when (listp extra)
15624 (setq extra (car extra))
15625 (if (and (stringp extra)
15626 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15627 (setq extra (format "-%02d:%02d"
15628 (string-to-number (match-string 1 extra))
15629 (string-to-number (match-string 2 extra))))
15630 (setq extra nil)))
15631 (when extra
15632 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15633 (insert-before-markers (setq stamp (format-time-string fmt time)))
15634 (insert-before-markers (or post ""))
15635 (setq org-last-inserted-timestamp stamp)))
15637 (defun org-toggle-time-stamp-overlays ()
15638 "Toggle the use of custom time stamp formats."
15639 (interactive)
15640 (setq org-display-custom-times (not org-display-custom-times))
15641 (unless org-display-custom-times
15642 (let ((p (point-min)) (bmp (buffer-modified-p)))
15643 (while (setq p (next-single-property-change p 'display))
15644 (if (and (get-text-property p 'display)
15645 (eq (get-text-property p 'face) 'org-date))
15646 (remove-text-properties
15647 p (setq p (next-single-property-change p 'display))
15648 '(display t))))
15649 (set-buffer-modified-p bmp)))
15650 (if (featurep 'xemacs)
15651 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15652 (org-restart-font-lock)
15653 (setq org-table-may-need-update t)
15654 (if org-display-custom-times
15655 (message "Time stamps are overlaid with custom format")
15656 (message "Time stamp overlays removed")))
15658 (defun org-display-custom-time (beg end)
15659 "Overlay modified time stamp format over timestamp between BEG and END."
15660 (let* ((ts (buffer-substring beg end))
15661 t1 w1 with-hm tf time str w2 (off 0))
15662 (save-match-data
15663 (setq t1 (org-parse-time-string ts t))
15664 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15665 (setq off (- (match-end 0) (match-beginning 0)))))
15666 (setq end (- end off))
15667 (setq w1 (- end beg)
15668 with-hm (and (nth 1 t1) (nth 2 t1))
15669 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15670 time (org-fix-decoded-time t1)
15671 str (org-add-props
15672 (format-time-string
15673 (substring tf 1 -1) (apply 'encode-time time))
15674 nil 'mouse-face 'highlight)
15675 w2 (length str))
15676 (if (not (= w2 w1))
15677 (add-text-properties (1+ beg) (+ 2 beg)
15678 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15679 (if (featurep 'xemacs)
15680 (progn
15681 (put-text-property beg end 'invisible t)
15682 (put-text-property beg end 'end-glyph (make-glyph str)))
15683 (put-text-property beg end 'display str))))
15685 (defun org-translate-time (string)
15686 "Translate all timestamps in STRING to custom format.
15687 But do this only if the variable `org-display-custom-times' is set."
15688 (when org-display-custom-times
15689 (save-match-data
15690 (let* ((start 0)
15691 (re org-ts-regexp-both)
15692 t1 with-hm inactive tf time str beg end)
15693 (while (setq start (string-match re string start))
15694 (setq beg (match-beginning 0)
15695 end (match-end 0)
15696 t1 (save-match-data
15697 (org-parse-time-string (substring string beg end) t))
15698 with-hm (and (nth 1 t1) (nth 2 t1))
15699 inactive (equal (substring string beg (1+ beg)) "[")
15700 tf (funcall (if with-hm 'cdr 'car)
15701 org-time-stamp-custom-formats)
15702 time (org-fix-decoded-time t1)
15703 str (format-time-string
15704 (concat
15705 (if inactive "[" "<") (substring tf 1 -1)
15706 (if inactive "]" ">"))
15707 (apply 'encode-time time))
15708 string (replace-match str t t string)
15709 start (+ start (length str)))))))
15710 string)
15712 (defun org-fix-decoded-time (time)
15713 "Set 0 instead of nil for the first 6 elements of time.
15714 Don't touch the rest."
15715 (let ((n 0))
15716 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15718 (defun org-days-to-time (timestamp-string)
15719 "Difference between TIMESTAMP-STRING and now in days."
15720 (- (time-to-days (org-time-string-to-time timestamp-string))
15721 (time-to-days (current-time))))
15723 (defun org-deadline-close (timestamp-string &optional ndays)
15724 "Is the time in TIMESTAMP-STRING close to the current date?"
15725 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15726 (and (< (org-days-to-time timestamp-string) ndays)
15727 (not (org-entry-is-done-p))))
15729 (defun org-get-wdays (ts)
15730 "Get the deadline lead time appropriate for timestring TS."
15731 (cond
15732 ((<= org-deadline-warning-days 0)
15733 ;; 0 or negative, enforce this value no matter what
15734 (- org-deadline-warning-days))
15735 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15736 ;; lead time is specified.
15737 (floor (* (string-to-number (match-string 1 ts))
15738 (cdr (assoc (match-string 2 ts)
15739 '(("d" . 1) ("w" . 7)
15740 ("m" . 30.4) ("y" . 365.25)))))))
15741 ;; go for the default.
15742 (t org-deadline-warning-days)))
15744 (defun org-calendar-select-mouse (ev)
15745 "Return to `org-read-date' with the date currently selected.
15746 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15747 (interactive "e")
15748 (mouse-set-point ev)
15749 (when (calendar-cursor-to-date)
15750 (let* ((date (calendar-cursor-to-date))
15751 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15752 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15753 (if (active-minibuffer-window) (exit-minibuffer))))
15755 (defun org-check-deadlines (ndays)
15756 "Check if there are any deadlines due or past due.
15757 A deadline is considered due if it happens within `org-deadline-warning-days'
15758 days from today's date. If the deadline appears in an entry marked DONE,
15759 it is not shown. The prefix arg NDAYS can be used to test that many
15760 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15761 (interactive "P")
15762 (let* ((org-warn-days
15763 (cond
15764 ((equal ndays '(4)) 100000)
15765 (ndays (prefix-numeric-value ndays))
15766 (t (abs org-deadline-warning-days))))
15767 (case-fold-search nil)
15768 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15769 (callback
15770 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15772 (message "%d deadlines past-due or due within %d days"
15773 (org-occur regexp nil callback)
15774 org-warn-days)))
15776 (defun org-check-before-date (date)
15777 "Check if there are deadlines or scheduled entries before DATE."
15778 (interactive (list (org-read-date)))
15779 (let ((case-fold-search nil)
15780 (regexp (concat "\\<\\(" org-deadline-string
15781 "\\|" org-scheduled-string
15782 "\\) *<\\([^>]+\\)>"))
15783 (callback
15784 (lambda () (time-less-p
15785 (org-time-string-to-time (match-string 2))
15786 (org-time-string-to-time date)))))
15787 (message "%d entries before %s"
15788 (org-occur regexp nil callback) date)))
15790 (defun org-check-after-date (date)
15791 "Check if there are deadlines or scheduled entries after DATE."
15792 (interactive (list (org-read-date)))
15793 (let ((case-fold-search nil)
15794 (regexp (concat "\\<\\(" org-deadline-string
15795 "\\|" org-scheduled-string
15796 "\\) *<\\([^>]+\\)>"))
15797 (callback
15798 (lambda () (not
15799 (time-less-p
15800 (org-time-string-to-time (match-string 2))
15801 (org-time-string-to-time date))))))
15802 (message "%d entries after %s"
15803 (org-occur regexp nil callback) date)))
15805 (defun org-check-dates-range (start-date end-date)
15806 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15807 (interactive (list (org-read-date nil nil nil "Range starts")
15808 (org-read-date nil nil nil "Range end")))
15809 (let ((case-fold-search nil)
15810 (regexp (concat "\\<\\(" org-deadline-string
15811 "\\|" org-scheduled-string
15812 "\\) *<\\([^>]+\\)>"))
15813 (callback
15814 (lambda ()
15815 (let ((match (match-string 2)))
15816 (and
15817 (not (time-less-p
15818 (org-time-string-to-time match)
15819 (org-time-string-to-time start-date)))
15820 (time-less-p
15821 (org-time-string-to-time match)
15822 (org-time-string-to-time end-date)))))))
15823 (message "%d entries between %s and %s"
15824 (org-occur regexp nil callback) start-date end-date)))
15826 (defun org-evaluate-time-range (&optional to-buffer)
15827 "Evaluate a time range by computing the difference between start and end.
15828 Normally the result is just printed in the echo area, but with prefix arg
15829 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15830 If the time range is actually in a table, the result is inserted into the
15831 next column.
15832 For time difference computation, a year is assumed to be exactly 365
15833 days in order to avoid rounding problems."
15834 (interactive "P")
15836 (org-clock-update-time-maybe)
15837 (save-excursion
15838 (unless (org-at-date-range-p t)
15839 (goto-char (point-at-bol))
15840 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15841 (if (not (org-at-date-range-p t))
15842 (error "Not at a time-stamp range, and none found in current line")))
15843 (let* ((ts1 (match-string 1))
15844 (ts2 (match-string 2))
15845 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15846 (match-end (match-end 0))
15847 (time1 (org-time-string-to-time ts1))
15848 (time2 (org-time-string-to-time ts2))
15849 (t1 (org-float-time time1))
15850 (t2 (org-float-time time2))
15851 (diff (abs (- t2 t1)))
15852 (negative (< (- t2 t1) 0))
15853 ;; (ys (floor (* 365 24 60 60)))
15854 (ds (* 24 60 60))
15855 (hs (* 60 60))
15856 (fy "%dy %dd %02d:%02d")
15857 (fy1 "%dy %dd")
15858 (fd "%dd %02d:%02d")
15859 (fd1 "%dd")
15860 (fh "%02d:%02d")
15861 y d h m align)
15862 (if havetime
15863 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15865 d (floor (/ diff ds)) diff (mod diff ds)
15866 h (floor (/ diff hs)) diff (mod diff hs)
15867 m (floor (/ diff 60)))
15868 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15870 d (floor (+ (/ diff ds) 0.5))
15871 h 0 m 0))
15872 (if (not to-buffer)
15873 (message "%s" (org-make-tdiff-string y d h m))
15874 (if (org-at-table-p)
15875 (progn
15876 (goto-char match-end)
15877 (setq align t)
15878 (and (looking-at " *|") (goto-char (match-end 0))))
15879 (goto-char match-end))
15880 (if (looking-at
15881 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15882 (replace-match ""))
15883 (if negative (insert " -"))
15884 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15885 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15886 (insert " " (format fh h m))))
15887 (if align (org-table-align))
15888 (message "Time difference inserted")))))
15890 (defun org-make-tdiff-string (y d h m)
15891 (let ((fmt "")
15892 (l nil))
15893 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15894 l (push y l)))
15895 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15896 l (push d l)))
15897 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15898 l (push h l)))
15899 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15900 l (push m l)))
15901 (apply 'format fmt (nreverse l))))
15903 (defun org-time-string-to-time (s &optional buffer pos)
15904 (condition-case errdata
15905 (apply 'encode-time (org-parse-time-string s))
15906 (error (error "Bad timestamp `%s'%s\nError was: %s"
15907 s (if (not (and buffer pos))
15909 (format " at %d in buffer `%s'" pos buffer))
15910 (cdr errdata)))))
15912 (defun org-time-string-to-seconds (s)
15913 (org-float-time (org-time-string-to-time s)))
15915 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15916 "Convert a time stamp to an absolute day number.
15917 If there is a specifier for a cyclic time stamp, get the closest date to
15918 DAYNR.
15919 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15920 The variable date is bound by the calendar when this is called."
15921 (cond
15922 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15923 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15924 daynr
15925 (+ daynr 1000)))
15926 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
15927 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15928 (time-to-days (current-time))) (match-string 0 s)
15929 prefer show-all))
15930 (t (time-to-days
15931 (condition-case errdata
15932 (apply 'encode-time (org-parse-time-string s))
15933 (error (error "Bad timestamp `%s'%s\nError was: %s"
15934 s (if (not (and buffer pos))
15936 (format " at %d in buffer `%s'" pos buffer))
15937 (cdr errdata))))))))
15939 (defun org-days-to-iso-week (days)
15940 "Return the iso week number."
15941 (require 'cal-iso)
15942 (car (calendar-iso-from-absolute days)))
15944 (defun org-small-year-to-year (year)
15945 "Convert 2-digit years into 4-digit years.
15946 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15947 The year 2000 cannot be abbreviated. Any year larger than 99
15948 is returned unchanged."
15949 (if (< year 38)
15950 (setq year (+ 2000 year))
15951 (if (< year 100)
15952 (setq year (+ 1900 year))))
15953 year)
15955 (defun org-time-from-absolute (d)
15956 "Return the time corresponding to date D.
15957 D may be an absolute day number, or a calendar-type list (month day year)."
15958 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15959 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15961 (defun org-calendar-holiday ()
15962 "List of holidays, for Diary display in Org-mode."
15963 (require 'holidays)
15964 (let ((hl (funcall
15965 (if (fboundp 'calendar-check-holidays)
15966 'calendar-check-holidays 'check-calendar-holidays) date)))
15967 (if hl (mapconcat 'identity hl "; "))))
15969 (defun org-diary-sexp-entry (sexp entry date)
15970 "Process a SEXP diary ENTRY for DATE."
15971 (require 'diary-lib)
15972 (let ((result (if calendar-debug-sexp
15973 (let ((stack-trace-on-error t))
15974 (eval (car (read-from-string sexp))))
15975 (condition-case nil
15976 (eval (car (read-from-string sexp)))
15977 (error
15978 (beep)
15979 (message "Bad sexp at line %d in %s: %s"
15980 (org-current-line)
15981 (buffer-file-name) sexp)
15982 (sleep-for 2))))))
15983 (cond ((stringp result) (split-string result "; "))
15984 ((and (consp result)
15985 (not (consp (cdr result)))
15986 (stringp (cdr result))) (cdr result))
15987 ((and (consp result)
15988 (stringp (car result))) result)
15989 (result entry)
15990 (t nil))))
15992 (defun org-diary-to-ical-string (frombuf)
15993 "Get iCalendar entries from diary entries in buffer FROMBUF.
15994 This uses the icalendar.el library."
15995 (let* ((tmpdir (if (featurep 'xemacs)
15996 (temp-directory)
15997 temporary-file-directory))
15998 (tmpfile (make-temp-name
15999 (expand-file-name "orgics" tmpdir)))
16000 buf rtn b e)
16001 (with-current-buffer frombuf
16002 (icalendar-export-region (point-min) (point-max) tmpfile)
16003 (setq buf (find-buffer-visiting tmpfile))
16004 (set-buffer buf)
16005 (goto-char (point-min))
16006 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16007 (setq b (match-beginning 0)))
16008 (goto-char (point-max))
16009 (if (re-search-backward "^END:VEVENT" nil t)
16010 (setq e (match-end 0)))
16011 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16012 (kill-buffer buf)
16013 (delete-file tmpfile)
16014 rtn))
16016 (defun org-closest-date (start current change prefer show-all)
16017 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16018 When PREFER is `past', return a date that is either CURRENT or past.
16019 When PREFER is `future', return a date that is either CURRENT or future.
16020 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16021 ;; Make the proper lists from the dates
16022 (catch 'exit
16023 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16024 dn dw sday cday n1 n2 n0
16025 d m y y1 y2 date1 date2 nmonths nm ny m2)
16027 (setq start (org-date-to-gregorian start)
16028 current (org-date-to-gregorian
16029 (if show-all
16030 current
16031 (time-to-days (current-time))))
16032 sday (calendar-absolute-from-gregorian start)
16033 cday (calendar-absolute-from-gregorian current))
16035 (if (<= cday sday) (throw 'exit sday))
16037 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16038 (setq dn (string-to-number (match-string 1 change))
16039 dw (cdr (assoc (match-string 2 change) a1)))
16040 (error "Invalid change specifier: %s" change))
16041 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16042 (cond
16043 ((eq dw 'day)
16044 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16045 n2 (+ n1 dn)))
16046 ((eq dw 'year)
16047 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16048 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16049 (setq date1 (list m d y1)
16050 n1 (calendar-absolute-from-gregorian date1)
16051 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16052 n2 (calendar-absolute-from-gregorian date2)))
16053 ((eq dw 'month)
16054 ;; approx number of month between the two dates
16055 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16056 ;; How often does dn fit in there?
16057 (setq d (nth 1 start) m (car start) y (nth 2 start)
16058 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16059 m (+ m nm)
16060 ny (floor (/ m 12))
16061 y (+ y ny)
16062 m (- m (* ny 12)))
16063 (while (> m 12) (setq m (- m 12) y (1+ y)))
16064 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16065 (setq m2 (+ m dn) y2 y)
16066 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16067 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16068 (while (<= n2 cday)
16069 (setq n1 n2 m m2 y y2)
16070 (setq m2 (+ m dn) y2 y)
16071 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16072 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16073 ;; Make sure n1 is the earlier date
16074 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16075 (if show-all
16076 (cond
16077 ((eq prefer 'past) (if (= cday n2) n2 n1))
16078 ((eq prefer 'future) (if (= cday n1) n1 n2))
16079 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16080 (cond
16081 ((eq prefer 'past) (if (= cday n2) n2 n1))
16082 ((eq prefer 'future) (if (= cday n1) n1 n2))
16083 (t (if (= cday n1) n1 n2)))))))
16085 (defun org-date-to-gregorian (date)
16086 "Turn any specification of DATE into a Gregorian date for the calendar."
16087 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16088 ((and (listp date) (= (length date) 3)) date)
16089 ((stringp date)
16090 (setq date (org-parse-time-string date))
16091 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16092 ((listp date)
16093 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16095 (defun org-parse-time-string (s &optional nodefault)
16096 "Parse the standard Org-mode time string.
16097 This should be a lot faster than the normal `parse-time-string'.
16098 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16099 hour and minute fields will be nil if not given."
16100 (if (string-match org-ts-regexp0 s)
16101 (list 0
16102 (if (or (match-beginning 8) (not nodefault))
16103 (string-to-number (or (match-string 8 s) "0")))
16104 (if (or (match-beginning 7) (not nodefault))
16105 (string-to-number (or (match-string 7 s) "0")))
16106 (string-to-number (match-string 4 s))
16107 (string-to-number (match-string 3 s))
16108 (string-to-number (match-string 2 s))
16109 nil nil nil)
16110 (error "Not a standard Org-mode time string: %s" s)))
16112 (defun org-timestamp-up (&optional arg)
16113 "Increase the date item at the cursor by one.
16114 If the cursor is on the year, change the year. If it is on the month,
16115 the day or the time, change that.
16116 With prefix ARG, change by that many units."
16117 (interactive "p")
16118 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16120 (defun org-timestamp-down (&optional arg)
16121 "Decrease the date item at the cursor by one.
16122 If the cursor is on the year, change the year. If it is on the month,
16123 the day or the time, change that.
16124 With prefix ARG, change by that many units."
16125 (interactive "p")
16126 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16128 (defun org-timestamp-up-day (&optional arg)
16129 "Increase the date in the time stamp by one day.
16130 With prefix ARG, change that many days."
16131 (interactive "p")
16132 (if (and (not (org-at-timestamp-p t))
16133 (org-at-heading-p))
16134 (org-todo 'up)
16135 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16137 (defun org-timestamp-down-day (&optional arg)
16138 "Decrease the date in the time stamp by one day.
16139 With prefix ARG, change that many days."
16140 (interactive "p")
16141 (if (and (not (org-at-timestamp-p t))
16142 (org-at-heading-p))
16143 (org-todo 'down)
16144 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16146 (defun org-at-timestamp-p (&optional inactive-ok)
16147 "Determine if the cursor is in or at a timestamp."
16148 (interactive)
16149 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16150 (pos (point))
16151 (ans (or (looking-at tsr)
16152 (save-excursion
16153 (skip-chars-backward "^[<\n\r\t")
16154 (if (> (point) (point-min)) (backward-char 1))
16155 (and (looking-at tsr)
16156 (> (- (match-end 0) pos) -1))))))
16157 (and ans
16158 (boundp 'org-ts-what)
16159 (setq org-ts-what
16160 (cond
16161 ((= pos (match-beginning 0)) 'bracket)
16162 ;; Point is considered to be "on the bracket" whether
16163 ;; it's really on it or right after it.
16164 ((or (= pos (1- (match-end 0)))
16165 (= pos (match-end 0))) 'bracket)
16166 ((org-pos-in-match-range pos 2) 'year)
16167 ((org-pos-in-match-range pos 3) 'month)
16168 ((org-pos-in-match-range pos 7) 'hour)
16169 ((org-pos-in-match-range pos 8) 'minute)
16170 ((or (org-pos-in-match-range pos 4)
16171 (org-pos-in-match-range pos 5)) 'day)
16172 ((and (> pos (or (match-end 8) (match-end 5)))
16173 (< pos (match-end 0)))
16174 (- pos (or (match-end 8) (match-end 5))))
16175 (t 'day))))
16176 ans))
16178 (defun org-toggle-timestamp-type ()
16179 "Toggle the type (<active> or [inactive]) of a time stamp."
16180 (interactive)
16181 (when (org-at-timestamp-p t)
16182 (let ((beg (match-beginning 0)) (end (match-end 0))
16183 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16184 (save-excursion
16185 (goto-char beg)
16186 (while (re-search-forward "[][<>]" end t)
16187 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16188 t t)))
16189 (message "Timestamp is now %sactive"
16190 (if (equal (char-after beg) ?<) "" "in")))))
16192 (defun org-timestamp-change (n &optional what updown)
16193 "Change the date in the time stamp at point.
16194 The date will be changed by N times WHAT. WHAT can be `day', `month',
16195 `year', `minute', `second'. If WHAT is not given, the cursor position
16196 in the timestamp determines what will be changed."
16197 (let ((origin (point)) origin-cat
16198 with-hm inactive
16199 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16200 org-ts-what
16201 extra rem
16202 ts time time0)
16203 (if (not (org-at-timestamp-p t))
16204 (error "Not at a timestamp"))
16205 (if (and (not what) (eq org-ts-what 'bracket))
16206 (org-toggle-timestamp-type)
16207 ;; Point isn't on brackets. Remember the part of the time-stamp
16208 ;; the point was in. Indeed, size of time-stamps may change,
16209 ;; but point must be kept in the same category nonetheless.
16210 (setq origin-cat org-ts-what)
16211 (if (and (not what) (not (eq org-ts-what 'day))
16212 org-display-custom-times
16213 (get-text-property (point) 'display)
16214 (not (get-text-property (1- (point)) 'display)))
16215 (setq org-ts-what 'day))
16216 (setq org-ts-what (or what org-ts-what)
16217 inactive (= (char-after (match-beginning 0)) ?\[)
16218 ts (match-string 0))
16219 (replace-match "")
16220 (if (string-match
16221 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16223 (setq extra (match-string 1 ts)))
16224 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16225 (setq with-hm t))
16226 (setq time0 (org-parse-time-string ts))
16227 (when (and updown
16228 (eq org-ts-what 'minute)
16229 (not current-prefix-arg))
16230 ;; This looks like s-up and s-down. Change by one rounding step.
16231 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16232 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16233 (setcar (cdr time0) (+ (nth 1 time0)
16234 (if (> n 0) (- rem) (- dm rem))))))
16235 (setq time
16236 (encode-time (or (car time0) 0)
16237 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16238 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16239 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16240 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16241 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16242 (nthcdr 6 time0)))
16243 (when (and (member org-ts-what '(hour minute))
16244 extra
16245 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16246 (setq extra (org-modify-ts-extra
16247 extra
16248 (if (eq org-ts-what 'hour) 2 5)
16249 n dm)))
16250 (when (integerp org-ts-what)
16251 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16252 (if (eq what 'calendar)
16253 (let ((cal-date (org-get-date-from-calendar)))
16254 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16255 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16256 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16257 (setcar time0 (or (car time0) 0))
16258 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16259 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16260 (setq time (apply 'encode-time time0))))
16261 ;; Insert the new time-stamp, and ensure point stays in the same
16262 ;; category as before (i.e. not after the last position in that
16263 ;; category).
16264 (let ((pos (point)))
16265 ;; Stay before inserted string. `save-excursion' is of no use.
16266 (setq org-last-changed-timestamp
16267 (org-insert-time-stamp time with-hm inactive nil nil extra))
16268 (goto-char pos))
16269 (save-match-data
16270 (looking-at org-ts-regexp3)
16271 (goto-char (cond
16272 ;; `day' category ends before `hour' if any, or at
16273 ;; the end of the day name.
16274 ((eq origin-cat 'day)
16275 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16276 ((eq origin-cat 'hour) (min (match-end 7) origin))
16277 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16278 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16279 ;; `year' and `month' have both fixed size: point
16280 ;; couldn't have moved into another part.
16281 (t origin))))
16282 ;; Update clock if on a CLOCK line.
16283 (org-clock-update-time-maybe)
16284 ;; Try to recenter the calendar window, if any.
16285 (if (and org-calendar-follow-timestamp-change
16286 (get-buffer-window "*Calendar*" t)
16287 (memq org-ts-what '(day month year)))
16288 (org-recenter-calendar (time-to-days time))))))
16290 (defun org-modify-ts-extra (s pos n dm)
16291 "Change the different parts of the lead-time and repeat fields in timestamp."
16292 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16293 ng h m new rem)
16294 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16295 (cond
16296 ((or (org-pos-in-match-range pos 2)
16297 (org-pos-in-match-range pos 3))
16298 (setq m (string-to-number (match-string 3 s))
16299 h (string-to-number (match-string 2 s)))
16300 (if (org-pos-in-match-range pos 2)
16301 (setq h (+ h n))
16302 (setq n (* dm (org-no-warnings (signum n))))
16303 (when (not (= 0 (setq rem (% m dm))))
16304 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16305 (setq m (+ m n)))
16306 (if (< m 0) (setq m (+ m 60) h (1- h)))
16307 (if (> m 59) (setq m (- m 60) h (1+ h)))
16308 (setq h (min 24 (max 0 h)))
16309 (setq ng 1 new (format "-%02d:%02d" h m)))
16310 ((org-pos-in-match-range pos 6)
16311 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16312 ((org-pos-in-match-range pos 5)
16313 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16315 ((org-pos-in-match-range pos 9)
16316 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16317 ((org-pos-in-match-range pos 8)
16318 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16320 (when ng
16321 (setq s (concat
16322 (substring s 0 (match-beginning ng))
16324 (substring s (match-end ng))))))
16327 (defun org-recenter-calendar (date)
16328 "If the calendar is visible, recenter it to DATE."
16329 (let ((cwin (get-buffer-window "*Calendar*" t)))
16330 (when cwin
16331 (let ((calendar-move-hook nil))
16332 (with-selected-window cwin
16333 (calendar-goto-date (if (listp date) date
16334 (calendar-gregorian-from-absolute date))))))))
16336 (defun org-goto-calendar (&optional arg)
16337 "Go to the Emacs calendar at the current date.
16338 If there is a time stamp in the current line, go to that date.
16339 A prefix ARG can be used to force the current date."
16340 (interactive "P")
16341 (let ((tsr org-ts-regexp) diff
16342 (calendar-move-hook nil)
16343 (calendar-view-holidays-initially-flag nil)
16344 (calendar-view-diary-initially-flag nil))
16345 (if (or (org-at-timestamp-p)
16346 (save-excursion
16347 (beginning-of-line 1)
16348 (looking-at (concat ".*" tsr))))
16349 (let ((d1 (time-to-days (current-time)))
16350 (d2 (time-to-days
16351 (org-time-string-to-time (match-string 1)))))
16352 (setq diff (- d2 d1))))
16353 (calendar)
16354 (calendar-goto-today)
16355 (if (and diff (not arg)) (calendar-forward-day diff))))
16357 (defun org-get-date-from-calendar ()
16358 "Return a list (month day year) of date at point in calendar."
16359 (with-current-buffer "*Calendar*"
16360 (save-match-data
16361 (calendar-cursor-to-date))))
16363 (defun org-date-from-calendar ()
16364 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16365 If there is already a time stamp at the cursor position, update it."
16366 (interactive)
16367 (if (org-at-timestamp-p t)
16368 (org-timestamp-change 0 'calendar)
16369 (let ((cal-date (org-get-date-from-calendar)))
16370 (org-insert-time-stamp
16371 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16373 (defun org-minutes-to-hh:mm-string (m)
16374 "Compute H:MM from a number of minutes."
16375 (let ((h (/ m 60)))
16376 (setq m (- m (* 60 h)))
16377 (format org-time-clocksum-format h m)))
16379 (defun org-hh:mm-string-to-minutes (s)
16380 "Convert a string H:MM to a number of minutes.
16381 If the string is just a number, interpret it as minutes.
16382 In fact, the first hh:mm or number in the string will be taken,
16383 there can be extra stuff in the string.
16384 If no number is found, the return value is 0."
16385 (cond
16386 ((integerp s) s)
16387 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16388 (+ (* (string-to-number (match-string 1 s)) 60)
16389 (string-to-number (match-string 2 s))))
16390 ((string-match "\\([0-9]+\\)" s)
16391 (string-to-number (match-string 1 s)))
16392 (t 0)))
16394 (defcustom org-effort-durations
16395 `(("h" . 60)
16396 ("d" . ,(* 60 8))
16397 ("w" . ,(* 60 8 5))
16398 ("m" . ,(* 60 8 5 4))
16399 ("y" . ,(* 60 8 5 40)))
16400 "Conversion factor to minutes for an effort modifier.
16402 Each entry has the form (MODIFIER . MINUTES).
16404 In an effort string, a number followed by MODIFIER is multiplied
16405 by the specified number of MINUTES to obtain an effort in
16406 minutes.
16408 For example, if the value of this variable is ((\"hours\" . 60)), then an
16409 effort string \"2hours\" is equivalent to 120 minutes."
16410 :group 'org-agenda
16411 :version "24.1"
16412 :type '(alist :key-type (string :tag "Modifier")
16413 :value-type (number :tag "Minutes")))
16415 (defun org-duration-string-to-minutes (s &optional output-to-string)
16416 "Convert a duration string S to minutes.
16418 A bare number is interpreted as minutes, modifiers can be set by
16419 customizing `org-effort-durations' (which see).
16421 Entries containing a colon are interpreted as H:MM by
16422 `org-hh:mm-string-to-minutes'."
16423 (let ((result 0)
16424 (re (concat "\\([0-9.]+\\) *\\("
16425 (regexp-opt (mapcar 'car org-effort-durations))
16426 "\\)")))
16427 (while (string-match re s)
16428 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16429 (string-to-number (match-string 1 s))))
16430 (setq s (replace-match "" nil t s)))
16431 (setq result (floor result))
16432 (incf result (org-hh:mm-string-to-minutes s))
16433 (if output-to-string (number-to-string result) result)))
16435 ;;;; Files
16437 (defun org-save-all-org-buffers ()
16438 "Save all Org-mode buffers without user confirmation."
16439 (interactive)
16440 (message "Saving all Org-mode buffers...")
16441 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16442 (when (featurep 'org-id) (org-id-locations-save))
16443 (message "Saving all Org-mode buffers... done"))
16445 (defun org-revert-all-org-buffers ()
16446 "Revert all Org-mode buffers.
16447 Prompt for confirmation when there are unsaved changes.
16448 Be sure you know what you are doing before letting this function
16449 overwrite your changes.
16451 This function is useful in a setup where one tracks org files
16452 with a version control system, to revert on one machine after pulling
16453 changes from another. I believe the procedure must be like this:
16455 1. M-x org-save-all-org-buffers
16456 2. Pull changes from the other machine, resolve conflicts
16457 3. M-x org-revert-all-org-buffers"
16458 (interactive)
16459 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16460 (error "Abort"))
16461 (save-excursion
16462 (save-window-excursion
16463 (mapc
16464 (lambda (b)
16465 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16466 (with-current-buffer b buffer-file-name))
16467 (org-pop-to-buffer-same-window b)
16468 (revert-buffer t 'no-confirm)))
16469 (buffer-list))
16470 (when (and (featurep 'org-id) org-id-track-globally)
16471 (org-id-locations-load)))))
16473 ;;;; Agenda files
16475 ;;;###autoload
16476 (defun org-switchb (&optional arg)
16477 "Switch between Org buffers.
16478 With one prefix argument, restrict available buffers to files.
16479 With two prefix arguments, restrict available buffers to agenda files.
16481 Defaults to `iswitchb' for buffer name completion.
16482 Set `org-completion-use-ido' to make it use ido instead."
16483 (interactive "P")
16484 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16485 ((equal arg '(16)) (org-buffer-list 'agenda))
16486 (t (org-buffer-list))))
16487 (org-completion-use-iswitchb org-completion-use-iswitchb)
16488 (org-completion-use-ido org-completion-use-ido))
16489 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16490 (setq org-completion-use-iswitchb t))
16491 (org-pop-to-buffer-same-window
16492 (org-icompleting-read "Org buffer: "
16493 (mapcar 'list (mapcar 'buffer-name blist))
16494 nil t))))
16496 ;;; Define some older names previously used for this functionality
16497 ;;;###autoload
16498 (defalias 'org-ido-switchb 'org-switchb)
16499 ;;;###autoload
16500 (defalias 'org-iswitchb 'org-switchb)
16502 (defun org-buffer-list (&optional predicate exclude-tmp)
16503 "Return a list of Org buffers.
16504 PREDICATE can be `export', `files' or `agenda'.
16506 export restrict the list to Export buffers.
16507 files restrict the list to buffers visiting Org files.
16508 agenda restrict the list to buffers visiting agenda files.
16510 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16511 (let* ((bfn nil)
16512 (agenda-files (and (eq predicate 'agenda)
16513 (mapcar 'file-truename (org-agenda-files t))))
16514 (filter
16515 (cond
16516 ((eq predicate 'files)
16517 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16518 ((eq predicate 'export)
16519 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16520 ((eq predicate 'agenda)
16521 (lambda (b)
16522 (with-current-buffer b
16523 (and (derived-mode-p 'org-mode)
16524 (setq bfn (buffer-file-name b))
16525 (member (file-truename bfn) agenda-files)))))
16526 (t (lambda (b) (with-current-buffer b
16527 (or (derived-mode-p 'org-mode)
16528 (string-match "\*Org .*Export"
16529 (buffer-name b)))))))))
16530 (delq nil
16531 (mapcar
16532 (lambda(b)
16533 (if (and (funcall filter b)
16534 (or (not exclude-tmp)
16535 (not (string-match "tmp" (buffer-name b)))))
16537 nil))
16538 (buffer-list)))))
16540 (defun org-agenda-files (&optional unrestricted archives)
16541 "Get the list of agenda files.
16542 Optional UNRESTRICTED means return the full list even if a restriction
16543 is currently in place.
16544 When ARCHIVES is t, include all archive files that are really being
16545 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16546 `org-agenda-archives-mode' is t."
16547 (let ((files
16548 (cond
16549 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16550 ((stringp org-agenda-files) (org-read-agenda-file-list))
16551 ((listp org-agenda-files) org-agenda-files)
16552 (t (error "Invalid value of `org-agenda-files'")))))
16553 (setq files (apply 'append
16554 (mapcar (lambda (f)
16555 (if (file-directory-p f)
16556 (directory-files
16557 f t org-agenda-file-regexp)
16558 (list f)))
16559 files)))
16560 (when org-agenda-skip-unavailable-files
16561 (setq files (delq nil
16562 (mapcar (function
16563 (lambda (file)
16564 (and (file-readable-p file) file)))
16565 files))))
16566 (when (or (eq archives t)
16567 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16568 (setq files (org-add-archive-files files)))
16569 files))
16571 (defun org-agenda-file-p (&optional file)
16572 "Return non-nil, if FILE is an agenda file.
16573 If FILE is omitted, use the file associated with the current
16574 buffer."
16575 (member (or file (buffer-file-name))
16576 (org-agenda-files t)))
16578 (defun org-edit-agenda-file-list ()
16579 "Edit the list of agenda files.
16580 Depending on setup, this either uses customize to edit the variable
16581 `org-agenda-files', or it visits the file that is holding the list. In the
16582 latter case, the buffer is set up in a way that saving it automatically kills
16583 the buffer and restores the previous window configuration."
16584 (interactive)
16585 (if (stringp org-agenda-files)
16586 (let ((cw (current-window-configuration)))
16587 (find-file org-agenda-files)
16588 (org-set-local 'org-window-configuration cw)
16589 (org-add-hook 'after-save-hook
16590 (lambda ()
16591 (set-window-configuration
16592 (prog1 org-window-configuration
16593 (kill-buffer (current-buffer))))
16594 (org-install-agenda-files-menu)
16595 (message "New agenda file list installed"))
16596 nil 'local)
16597 (message "%s" (substitute-command-keys
16598 "Edit list and finish with \\[save-buffer]")))
16599 (customize-variable 'org-agenda-files)))
16601 (defun org-store-new-agenda-file-list (list)
16602 "Set new value for the agenda file list and save it correctly."
16603 (if (stringp org-agenda-files)
16604 (let ((fe (org-read-agenda-file-list t)) b u)
16605 (while (setq b (find-buffer-visiting org-agenda-files))
16606 (kill-buffer b))
16607 (with-temp-file org-agenda-files
16608 (insert
16609 (mapconcat
16610 (lambda (f) ;; Keep un-expanded entries.
16611 (if (setq u (assoc f fe))
16612 (cdr u)
16614 list "\n")
16615 "\n")))
16616 (let ((org-mode-hook nil) (org-inhibit-startup t)
16617 (org-insert-mode-line-in-empty-file nil))
16618 (setq org-agenda-files list)
16619 (customize-save-variable 'org-agenda-files org-agenda-files))))
16621 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16622 "Read the list of agenda files from a file.
16623 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16624 filenames, used by `org-store-new-agenda-file-list' to write back
16625 un-expanded file names."
16626 (when (file-directory-p org-agenda-files)
16627 (error "`org-agenda-files' cannot be a single directory"))
16628 (when (stringp org-agenda-files)
16629 (with-temp-buffer
16630 (insert-file-contents org-agenda-files)
16631 (mapcar
16632 (lambda (f)
16633 (let ((e (expand-file-name (substitute-in-file-name f)
16634 org-directory)))
16635 (if pair-with-expansion
16636 (cons e f)
16637 e)))
16638 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16640 ;;;###autoload
16641 (defun org-cycle-agenda-files ()
16642 "Cycle through the files in `org-agenda-files'.
16643 If the current buffer visits an agenda file, find the next one in the list.
16644 If the current buffer does not, find the first agenda file."
16645 (interactive)
16646 (let* ((fs (org-agenda-files t))
16647 (files (append fs (list (car fs))))
16648 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16649 file)
16650 (unless files (error "No agenda files"))
16651 (catch 'exit
16652 (while (setq file (pop files))
16653 (if (equal (file-truename file) tcf)
16654 (when (car files)
16655 (find-file (car files))
16656 (throw 'exit t))))
16657 (find-file (car fs)))
16658 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16660 (defun org-agenda-file-to-front (&optional to-end)
16661 "Move/add the current file to the top of the agenda file list.
16662 If the file is not present in the list, it is added to the front. If it is
16663 present, it is moved there. With optional argument TO-END, add/move to the
16664 end of the list."
16665 (interactive "P")
16666 (let ((org-agenda-skip-unavailable-files nil)
16667 (file-alist (mapcar (lambda (x)
16668 (cons (file-truename x) x))
16669 (org-agenda-files t)))
16670 (ctf (file-truename buffer-file-name))
16671 x had)
16672 (setq x (assoc ctf file-alist) had x)
16674 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16675 (if to-end
16676 (setq file-alist (append (delq x file-alist) (list x)))
16677 (setq file-alist (cons x (delq x file-alist))))
16678 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16679 (org-install-agenda-files-menu)
16680 (message "File %s to %s of agenda file list"
16681 (if had "moved" "added") (if to-end "end" "front"))))
16683 (defun org-remove-file (&optional file)
16684 "Remove current file from the list of files in variable `org-agenda-files'.
16685 These are the files which are being checked for agenda entries.
16686 Optional argument FILE means use this file instead of the current."
16687 (interactive)
16688 (let* ((org-agenda-skip-unavailable-files nil)
16689 (file (or file buffer-file-name))
16690 (true-file (file-truename file))
16691 (afile (abbreviate-file-name file))
16692 (files (delq nil (mapcar
16693 (lambda (x)
16694 (if (equal true-file
16695 (file-truename x))
16696 nil x))
16697 (org-agenda-files t)))))
16698 (if (not (= (length files) (length (org-agenda-files t))))
16699 (progn
16700 (org-store-new-agenda-file-list files)
16701 (org-install-agenda-files-menu)
16702 (message "Removed file: %s" afile))
16703 (message "File was not in list: %s (not removed)" afile))))
16705 (defun org-file-menu-entry (file)
16706 (vector file (list 'find-file file) t))
16708 (defun org-check-agenda-file (file)
16709 "Make sure FILE exists. If not, ask user what to do."
16710 (when (not (file-exists-p file))
16711 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16712 (abbreviate-file-name file))
16713 (let ((r (downcase (read-char-exclusive))))
16714 (cond
16715 ((equal r ?r)
16716 (org-remove-file file)
16717 (throw 'nextfile t))
16718 (t (error "Abort"))))))
16720 (defun org-get-agenda-file-buffer (file)
16721 "Get a buffer visiting FILE. If the buffer needs to be created, add
16722 it to the list of buffers which might be released later."
16723 (let ((buf (org-find-base-buffer-visiting file)))
16724 (if buf
16725 buf ; just return it
16726 ;; Make a new buffer and remember it
16727 (setq buf (find-file-noselect file))
16728 (if buf (push buf org-agenda-new-buffers))
16729 buf)))
16731 (defun org-release-buffers (blist)
16732 "Release all buffers in list, asking the user for confirmation when needed.
16733 When a buffer is unmodified, it is just killed. When modified, it is saved
16734 \(if the user agrees) and then killed."
16735 (let (buf file)
16736 (while (setq buf (pop blist))
16737 (setq file (buffer-file-name buf))
16738 (when (and (buffer-modified-p buf)
16739 file
16740 (y-or-n-p (format "Save file %s? " file)))
16741 (with-current-buffer buf (save-buffer)))
16742 (kill-buffer buf))))
16744 (defun org-prepare-agenda-buffers (files)
16745 "Create buffers for all agenda files, protect archived trees and comments."
16746 (interactive)
16747 (let ((pa '(:org-archived t))
16748 (pc '(:org-comment t))
16749 (pall '(:org-archived t :org-comment t))
16750 (inhibit-read-only t)
16751 (rea (concat ":" org-archive-tag ":"))
16752 bmp file re)
16753 (save-excursion
16754 (save-restriction
16755 (while (setq file (pop files))
16756 (catch 'nextfile
16757 (if (bufferp file)
16758 (set-buffer file)
16759 (org-check-agenda-file file)
16760 (set-buffer (org-get-agenda-file-buffer file)))
16761 (widen)
16762 (setq bmp (buffer-modified-p))
16763 (org-refresh-category-properties)
16764 (setq org-todo-keywords-for-agenda
16765 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16766 (setq org-done-keywords-for-agenda
16767 (append org-done-keywords-for-agenda org-done-keywords))
16768 (setq org-todo-keyword-alist-for-agenda
16769 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16770 (setq org-drawers-for-agenda
16771 (append org-drawers-for-agenda org-drawers))
16772 (setq org-tag-alist-for-agenda
16773 (append org-tag-alist-for-agenda org-tag-alist))
16775 (save-excursion
16776 (remove-text-properties (point-min) (point-max) pall)
16777 (when org-agenda-skip-archived-trees
16778 (goto-char (point-min))
16779 (while (re-search-forward rea nil t)
16780 (if (org-at-heading-p t)
16781 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16782 (goto-char (point-min))
16783 (setq re (format org-heading-keyword-regexp-format
16784 org-comment-string))
16785 (while (re-search-forward re nil t)
16786 (add-text-properties
16787 (match-beginning 0) (org-end-of-subtree t) pc)))
16788 (set-buffer-modified-p bmp)))))
16789 (setq org-todo-keywords-for-agenda
16790 (org-uniquify org-todo-keywords-for-agenda))
16791 (setq org-todo-keyword-alist-for-agenda
16792 (org-uniquify org-todo-keyword-alist-for-agenda)
16793 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16795 ;;;; Embedded LaTeX
16797 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16798 "Keymap for the minor `org-cdlatex-mode'.")
16800 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16801 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16802 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16803 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16804 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16806 (defvar org-cdlatex-texmathp-advice-is-done nil
16807 "Flag remembering if we have applied the advice to texmathp already.")
16809 (define-minor-mode org-cdlatex-mode
16810 "Toggle the minor `org-cdlatex-mode'.
16811 This mode supports entering LaTeX environment and math in LaTeX fragments
16812 in Org-mode.
16813 \\{org-cdlatex-mode-map}"
16814 nil " OCDL" nil
16815 (when org-cdlatex-mode
16816 (require 'cdlatex)
16817 (run-hooks 'cdlatex-mode-hook)
16818 (cdlatex-compute-tables))
16819 (unless org-cdlatex-texmathp-advice-is-done
16820 (setq org-cdlatex-texmathp-advice-is-done t)
16821 (defadvice texmathp (around org-math-always-on activate)
16822 "Always return t in org-mode buffers.
16823 This is because we want to insert math symbols without dollars even outside
16824 the LaTeX math segments. If Orgmode thinks that point is actually inside
16825 an embedded LaTeX fragment, let texmathp do its job.
16826 \\[org-cdlatex-mode-map]"
16827 (interactive)
16828 (let (p)
16829 (cond
16830 ((not (derived-mode-p 'org-mode)) ad-do-it)
16831 ((eq this-command 'cdlatex-math-symbol)
16832 (setq ad-return-value t
16833 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16835 (let ((p (org-inside-LaTeX-fragment-p)))
16836 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16837 (setq ad-return-value t
16838 texmathp-why '("Org-mode embedded math" . 0))
16839 (if p ad-do-it)))))))))
16841 (defun turn-on-org-cdlatex ()
16842 "Unconditionally turn on `org-cdlatex-mode'."
16843 (org-cdlatex-mode 1))
16845 (defun org-inside-LaTeX-fragment-p ()
16846 "Test if point is inside a LaTeX fragment.
16847 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16848 sequence appearing also before point.
16849 Even though the matchers for math are configurable, this function assumes
16850 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16851 delimiters are skipped when they have been removed by customization.
16852 The return value is nil, or a cons cell with the delimiter and the
16853 position of this delimiter.
16855 This function does a reasonably good job, but can locally be fooled by
16856 for example currency specifications. For example it will assume being in
16857 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16858 fragments that are properly closed, but during editing, we have to live
16859 with the uncertainty caused by missing closing delimiters. This function
16860 looks only before point, not after."
16861 (catch 'exit
16862 (let ((pos (point))
16863 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16864 (lim (progn
16865 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16866 (point)))
16867 dd-on str (start 0) m re)
16868 (goto-char pos)
16869 (when dodollar
16870 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16871 re (nth 1 (assoc "$" org-latex-regexps)))
16872 (while (string-match re str start)
16873 (cond
16874 ((= (match-end 0) (length str))
16875 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16876 ((= (match-end 0) (- (length str) 5))
16877 (throw 'exit nil))
16878 (t (setq start (match-end 0))))))
16879 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16880 (goto-char pos)
16881 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16882 (and (match-beginning 2) (throw 'exit nil))
16883 ;; count $$
16884 (while (re-search-backward "\\$\\$" lim t)
16885 (setq dd-on (not dd-on)))
16886 (goto-char pos)
16887 (if dd-on (cons "$$" m))))))
16889 (defun org-inside-latex-macro-p ()
16890 "Is point inside a LaTeX macro or its arguments?"
16891 (save-match-data
16892 (org-in-regexp
16893 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16895 (defun org-try-cdlatex-tab ()
16896 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16897 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16898 - inside a LaTeX fragment, or
16899 - after the first word in a line, where an abbreviation expansion could
16900 insert a LaTeX environment."
16901 (when org-cdlatex-mode
16902 (cond
16903 ;; Before any word on the line: No expansion possible.
16904 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16905 ;; Just after first word on the line: Expand it. Make sure it
16906 ;; cannot happen on headlines, though.
16907 ((save-excursion
16908 (skip-chars-backward "a-zA-Z0-9*")
16909 (skip-chars-backward " \t")
16910 (and (bolp) (not (org-at-heading-p))))
16911 (cdlatex-tab) t)
16912 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16914 (defun org-cdlatex-underscore-caret (&optional arg)
16915 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16916 Revert to the normal definition outside of these fragments."
16917 (interactive "P")
16918 (if (org-inside-LaTeX-fragment-p)
16919 (call-interactively 'cdlatex-sub-superscript)
16920 (let (org-cdlatex-mode)
16921 (call-interactively (key-binding (vector last-input-event))))))
16923 (defun org-cdlatex-math-modify (&optional arg)
16924 "Execute `cdlatex-math-modify' in LaTeX fragments.
16925 Revert to the normal definition outside of these fragments."
16926 (interactive "P")
16927 (if (org-inside-LaTeX-fragment-p)
16928 (call-interactively 'cdlatex-math-modify)
16929 (let (org-cdlatex-mode)
16930 (call-interactively (key-binding (vector last-input-event))))))
16932 (defvar org-latex-fragment-image-overlays nil
16933 "List of overlays carrying the images of latex fragments.")
16934 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16936 (defun org-remove-latex-fragment-image-overlays ()
16937 "Remove all overlays with LaTeX fragment images in current buffer."
16938 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16939 (setq org-latex-fragment-image-overlays nil))
16941 (defun org-preview-latex-fragment (&optional subtree)
16942 "Preview the LaTeX fragment at point, or all locally or globally.
16943 If the cursor is in a LaTeX fragment, create the image and overlay
16944 it over the source code. If there is no fragment at point, display
16945 all fragments in the current text, from one headline to the next. With
16946 prefix SUBTREE, display all fragments in the current subtree. With a
16947 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16948 the cursor is before the first headline,
16949 display all fragments in the buffer.
16950 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16951 (interactive "P")
16952 (unless buffer-file-name
16953 (error "Can't preview LaTeX fragment in a non-file buffer"))
16954 (org-remove-latex-fragment-image-overlays)
16955 (save-excursion
16956 (save-restriction
16957 (let (beg end at msg)
16958 (cond
16959 ((or (equal subtree '(16))
16960 (not (save-excursion
16961 (re-search-backward org-outline-regexp-bol nil t))))
16962 (setq beg (point-min) end (point-max)
16963 msg "Creating images for buffer...%s"))
16964 ((equal subtree '(4))
16965 (org-back-to-heading)
16966 (setq beg (point) end (org-end-of-subtree t)
16967 msg "Creating images for subtree...%s"))
16969 (if (setq at (org-inside-LaTeX-fragment-p))
16970 (goto-char (max (point-min) (- (cdr at) 2)))
16971 (org-back-to-heading))
16972 (setq beg (point) end (progn (outline-next-heading) (point))
16973 msg (if at "Creating image...%s"
16974 "Creating images for entry...%s"))))
16975 (message msg "")
16976 (narrow-to-region beg end)
16977 (goto-char beg)
16978 (org-format-latex
16979 (concat "ltxpng/" (file-name-sans-extension
16980 (file-name-nondirectory
16981 buffer-file-name)))
16982 default-directory 'overlays msg at 'forbuffer
16983 org-latex-create-formula-image-program)
16984 (message msg "done. Use `C-c C-c' to remove images.")))))
16986 (defvar org-latex-regexps
16987 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16988 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16989 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16990 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16991 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16992 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16993 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16994 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16995 "Regular expressions for matching embedded LaTeX.")
16997 (defvar org-export-have-math nil) ;; dynamic scoping
16998 (defun org-format-latex (prefix &optional dir overlays msg at
16999 forbuffer processing-type)
17000 "Replace LaTeX fragments with links to an image, and produce images.
17001 Some of the options can be changed using the variable
17002 `org-format-latex-options'."
17003 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17004 (let* ((prefixnodir (file-name-nondirectory prefix))
17005 (absprefix (expand-file-name prefix dir))
17006 (todir (file-name-directory absprefix))
17007 (opt org-format-latex-options)
17008 (matchers (plist-get opt :matchers))
17009 (re-list org-latex-regexps)
17010 (org-format-latex-header-extra
17011 (plist-get (org-infile-export-plist) :latex-header-extra))
17012 (cnt 0) txt hash link beg end re e checkdir
17013 executables-checked string
17014 m n block-type block linkfile movefile ov)
17015 ;; Check the different regular expressions
17016 (while (setq e (pop re-list))
17017 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17018 block (if block-type "\n\n" ""))
17019 (when (member m matchers)
17020 (goto-char (point-min))
17021 (while (re-search-forward re nil t)
17022 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17023 (not (get-text-property (match-beginning n)
17024 'org-protected))
17025 (or (not overlays)
17026 (not (eq (get-char-property (match-beginning n)
17027 'org-overlay-type)
17028 'org-latex-overlay))))
17029 (setq org-export-have-math t)
17030 (cond
17031 ((eq processing-type 'verbatim)
17032 ;; Leave the text verbatim, just protect it
17033 (add-text-properties (match-beginning n) (match-end n)
17034 '(org-protected t)))
17035 ((eq processing-type 'mathjax)
17036 ;; Prepare for MathJax processing
17037 (setq string (match-string n))
17038 (if (member m '("$" "$1"))
17039 (save-excursion
17040 (delete-region (match-beginning n) (match-end n))
17041 (goto-char (match-beginning n))
17042 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17043 "\\)")
17044 '(org-protected t))))
17045 (add-text-properties (match-beginning n) (match-end n)
17046 '(org-protected t))))
17047 ((or (eq processing-type 'dvipng)
17048 (eq processing-type 'imagemagick))
17049 ;; Process to an image
17050 (setq txt (match-string n)
17051 beg (match-beginning n) end (match-end n)
17052 cnt (1+ cnt))
17053 (let (print-length print-level) ; make sure full list is printed
17054 (setq hash (sha1 (prin1-to-string
17055 (list org-format-latex-header
17056 org-format-latex-header-extra
17057 org-export-latex-default-packages-alist
17058 org-export-latex-packages-alist
17059 org-format-latex-options
17060 forbuffer txt)))
17061 linkfile (format "%s_%s.png" prefix hash)
17062 movefile (format "%s_%s.png" absprefix hash)))
17063 (setq link (concat block "[[file:" linkfile "]]" block))
17064 (if msg (message msg cnt))
17065 (goto-char beg)
17066 (unless checkdir ; make sure the directory exists
17067 (setq checkdir t)
17068 (or (file-directory-p todir) (make-directory todir t)))
17069 (cond
17070 ((eq processing-type 'dvipng)
17071 (unless executables-checked
17072 (org-check-external-command
17073 "latex" "needed to convert LaTeX fragments to images")
17074 (org-check-external-command
17075 "dvipng" "needed to convert LaTeX fragments to images")
17076 (setq executables-checked t))
17077 (unless (file-exists-p movefile)
17078 (org-create-formula-image-with-dvipng
17079 txt movefile opt forbuffer)))
17080 ((eq processing-type 'imagemagick)
17081 (unless executables-checked
17082 (org-check-external-command
17083 "convert" "you need to install imagemagick")
17084 (setq executables-checked t))
17085 (unless (file-exists-p movefile)
17086 (org-create-formula-image-with-imagemagick
17087 txt movefile opt forbuffer))))
17088 (if overlays
17089 (progn
17090 (mapc (lambda (o)
17091 (if (eq (overlay-get o 'org-overlay-type)
17092 'org-latex-overlay)
17093 (delete-overlay o)))
17094 (overlays-in beg end))
17095 (setq ov (make-overlay beg end))
17096 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17097 (if (featurep 'xemacs)
17098 (progn
17099 (overlay-put ov 'invisible t)
17100 (overlay-put
17101 ov 'end-glyph
17102 (make-glyph (vector 'png :file movefile))))
17103 (overlay-put
17104 ov 'display
17105 (list 'image :type 'png :file movefile :ascent 'center)))
17106 (push ov org-latex-fragment-image-overlays)
17107 (goto-char end))
17108 (delete-region beg end)
17109 (insert (org-add-props link
17110 (list 'org-latex-src
17111 (replace-regexp-in-string
17112 "\"" "" txt)
17113 'org-latex-src-embed-type
17114 (if block-type 'paragraph 'character))))))
17115 ((eq processing-type 'mathml)
17116 ;; Process to MathML
17117 (unless executables-checked
17118 (unless (save-match-data (org-format-latex-mathml-available-p))
17119 (error "LaTeX to MathML converter not configured"))
17120 (setq executables-checked t))
17121 (setq txt (match-string n)
17122 beg (match-beginning n) end (match-end n)
17123 cnt (1+ cnt))
17124 (if msg (message msg cnt))
17125 (goto-char beg)
17126 (delete-region beg end)
17127 (insert (org-format-latex-as-mathml
17128 txt block-type prefix dir)))
17130 (error "Unknown conversion type %s for latex fragments"
17131 processing-type)))))))))
17133 (defun org-create-math-formula (latex-frag &optional mathml-file)
17134 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17135 Use `org-latex-to-mathml-convert-command'. If the conversion is
17136 sucessful, return the portion between \"<math...> </math>\"
17137 elements otherwise return nil. When MATHML-FILE is specified,
17138 write the results in to that file. When invoked as an
17139 interactive command, prompt for LATEX-FRAG, with initial value
17140 set to the current active region and echo the results for user
17141 inspection."
17142 (interactive (list (let ((frag (when (region-active-p)
17143 (buffer-substring-no-properties
17144 (region-beginning) (region-end)))))
17145 (read-string "LaTeX Fragment: " frag nil frag))))
17146 (unless latex-frag (error "Invalid latex-frag"))
17147 (let* ((tmp-in-file (file-relative-name
17148 (make-temp-name (expand-file-name "ltxmathml-in"))))
17149 (ignore (write-region latex-frag nil tmp-in-file))
17150 (tmp-out-file (file-relative-name
17151 (make-temp-name (expand-file-name "ltxmathml-out"))))
17152 (cmd (format-spec
17153 org-latex-to-mathml-convert-command
17154 `((?j . ,(shell-quote-argument
17155 (expand-file-name org-latex-to-mathml-jar-file)))
17156 (?I . ,(shell-quote-argument tmp-in-file))
17157 (?o . ,(shell-quote-argument tmp-out-file)))))
17158 mathml shell-command-output)
17159 (when (org-called-interactively-p 'any)
17160 (unless (org-format-latex-mathml-available-p)
17161 (error "LaTeX to MathML converter not configured")))
17162 (message "Running %s" cmd)
17163 (setq shell-command-output (shell-command-to-string cmd))
17164 (setq mathml
17165 (when (file-readable-p tmp-out-file)
17166 (with-current-buffer (find-file-noselect tmp-out-file t)
17167 (goto-char (point-min))
17168 (when (re-search-forward
17169 (concat
17170 (regexp-quote
17171 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17172 "\\(.\\|\n\\)*"
17173 (regexp-quote "</math>")) nil t)
17174 (prog1 (match-string 0) (kill-buffer))))))
17175 (cond
17176 (mathml
17177 (setq mathml
17178 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17179 (when mathml-file
17180 (write-region mathml nil mathml-file))
17181 (when (org-called-interactively-p 'any)
17182 (message mathml)))
17183 ((message "LaTeX to MathML conversion failed")
17184 (message shell-command-output)))
17185 (delete-file tmp-in-file)
17186 (when (file-exists-p tmp-out-file)
17187 (delete-file tmp-out-file))
17188 mathml))
17190 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17191 prefix &optional dir)
17192 "Use `org-create-math-formula' but check local cache first."
17193 (let* ((absprefix (expand-file-name prefix dir))
17194 (print-length nil) (print-level nil)
17195 (formula-id (concat
17196 "formula-"
17197 (sha1
17198 (prin1-to-string
17199 (list latex-frag
17200 org-latex-to-mathml-convert-command)))))
17201 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17202 (formula-cache-dir (file-name-directory formula-cache)))
17204 (unless (file-directory-p formula-cache-dir)
17205 (make-directory formula-cache-dir t))
17207 (unless (file-exists-p formula-cache)
17208 (org-create-math-formula latex-frag formula-cache))
17210 (if (file-exists-p formula-cache)
17211 ;; Successful conversion. Return the link to MathML file.
17212 (org-add-props
17213 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17214 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17215 'org-latex-src-embed-type (if latex-frag-type
17216 'paragraph 'character)))
17217 ;; Failed conversion. Return the LaTeX fragment verbatim
17218 (add-text-properties
17219 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17220 latex-frag)))
17222 ;; This function borrows from Ganesh Swami's latex2png.el
17223 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17224 "This calls dvipng."
17225 (require 'org-latex)
17226 (let* ((tmpdir (if (featurep 'xemacs)
17227 (temp-directory)
17228 temporary-file-directory))
17229 (texfilebase (make-temp-name
17230 (expand-file-name "orgtex" tmpdir)))
17231 (texfile (concat texfilebase ".tex"))
17232 (dvifile (concat texfilebase ".dvi"))
17233 (pngfile (concat texfilebase ".png"))
17234 (fnh (if (featurep 'xemacs)
17235 (font-height (face-font 'default))
17236 (face-attribute 'default :height nil)))
17237 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17238 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17239 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17240 "Black"))
17241 (bg (or (plist-get options (if buffer :background :html-background))
17242 "Transparent")))
17243 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17244 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17245 (with-temp-file texfile
17246 (insert (org-splice-latex-header
17247 org-format-latex-header
17248 org-export-latex-default-packages-alist
17249 org-export-latex-packages-alist t
17250 org-format-latex-header-extra))
17251 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17252 (require 'org-latex)
17253 (org-export-latex-fix-inputenc))
17254 (let ((dir default-directory))
17255 (condition-case nil
17256 (progn
17257 (cd tmpdir)
17258 (call-process "latex" nil nil nil texfile))
17259 (error nil))
17260 (cd dir))
17261 (if (not (file-exists-p dvifile))
17262 (progn (message "Failed to create dvi file from %s" texfile) nil)
17263 (condition-case nil
17264 (if (featurep 'xemacs)
17265 (call-process "dvipng" nil nil nil
17266 "-fg" fg "-bg" bg
17267 "-T" "tight"
17268 "-o" pngfile
17269 dvifile)
17270 (call-process "dvipng" nil nil nil
17271 "-fg" fg "-bg" bg
17272 "-D" dpi
17273 ;;"-x" scale "-y" scale
17274 "-T" "tight"
17275 "-o" pngfile
17276 dvifile))
17277 (error nil))
17278 (if (not (file-exists-p pngfile))
17279 (if org-format-latex-signal-error
17280 (error "Failed to create png file from %s" texfile)
17281 (message "Failed to create png file from %s" texfile)
17282 nil)
17283 ;; Use the requested file name and clean up
17284 (copy-file pngfile tofile 'replace)
17285 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17286 (if (file-exists-p (concat texfilebase e))
17287 (delete-file (concat texfilebase e))))
17288 pngfile))))
17290 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17291 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17292 "This calls convert, which is included into imagemagick."
17293 (require 'org-latex)
17294 (let* ((tmpdir (if (featurep 'xemacs)
17295 (temp-directory)
17296 temporary-file-directory))
17297 (texfilebase (make-temp-name
17298 (expand-file-name "orgtex" tmpdir)))
17299 (texfile (concat texfilebase ".tex"))
17300 (pdffile (concat texfilebase ".pdf"))
17301 (pngfile (concat texfilebase ".png"))
17302 (fnh (if (featurep 'xemacs)
17303 (font-height (face-font 'default))
17304 (face-attribute 'default :height nil)))
17305 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17306 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17307 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17308 "black"))
17309 (bg (or (plist-get options (if buffer :background :html-background))
17310 "white")))
17311 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17312 (setq fg (org-latex-color-format fg)))
17313 (if (eq bg 'default) (setq bg (org-latex-color :background))
17314 (setq bg (org-latex-color-format
17315 (if (string= bg "Transparent")(setq bg "white")))))
17316 (with-temp-file texfile
17317 (insert (org-splice-latex-header
17318 org-format-latex-header
17319 org-export-latex-default-packages-alist
17320 org-export-latex-packages-alist t
17321 org-format-latex-header-extra))
17322 (insert "\n\\begin{document}\n"
17323 "\\definecolor{fg}{rgb}{" fg "}\n"
17324 "\\definecolor{bg}{rgb}{" bg "}\n"
17325 "\n\\pagecolor{bg}\n"
17326 "\n{\\color{fg}\n"
17327 string
17328 "\n}\n"
17329 "\n\\end{document}\n" )
17330 (require 'org-latex)
17331 (org-export-latex-fix-inputenc))
17332 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17333 (condition-case nil
17334 (progn
17335 (cd tmpdir)
17336 (setq cmds org-latex-to-pdf-process)
17337 (while cmds
17338 (setq latex-frags-cmds (pop cmds))
17339 (if (listp latex-frags-cmds)
17340 (setq cmds nil)
17341 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17342 (while latex-frags-cmds
17343 (setq cmd (pop latex-frags-cmds))
17344 (while (string-match "%b" cmd)
17345 (setq cmd (replace-match
17346 (save-match-data
17347 (shell-quote-argument texfile))
17348 t t cmd)))
17349 (while (string-match "%f" cmd)
17350 (setq cmd (replace-match
17351 (save-match-data
17352 (shell-quote-argument (file-name-nondirectory texfile)))
17353 t t cmd)))
17354 (while (string-match "%o" cmd)
17355 (setq cmd (replace-match
17356 (save-match-data
17357 (shell-quote-argument (file-name-directory texfile)))
17358 t t cmd)))
17359 (setq cmd (split-string cmd))
17360 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17361 (error nil))
17362 (cd dir))
17363 (if (not (file-exists-p pdffile))
17364 (progn (message "Failed to create pdf file from %s" texfile) nil)
17365 (condition-case nil
17366 (if (featurep 'xemacs)
17367 (call-process "convert" nil nil nil
17368 "-density" "96"
17369 "-trim"
17370 "-antialias"
17371 pdffile
17372 "-quality" "100"
17373 ;; "-sharpen" "0x1.0"
17374 pngfile)
17375 (call-process "convert" nil nil nil
17376 "-density" dpi
17377 "-trim"
17378 "-antialias"
17379 pdffile
17380 "-quality" "100"
17381 ; "-sharpen" "0x1.0"
17382 pngfile))
17383 (error nil))
17384 (if (not (file-exists-p pngfile))
17385 (if org-format-latex-signal-error
17386 (error "Failed to create png file from %s" texfile)
17387 (message "Failed to create png file from %s" texfile)
17388 nil)
17389 ;; Use the requested file name and clean up
17390 (copy-file pngfile tofile 'replace)
17391 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17392 (if (file-exists-p (concat texfilebase e))
17393 (delete-file (concat texfilebase e))))
17394 pngfile))))
17396 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17397 "Fill a LaTeX header template TPL.
17398 In the template, the following place holders will be recognized:
17400 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17401 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17402 [PACKAGES] \\usepackage statements for PKG
17403 [NO-PACKAGES] do not include PKG
17404 [EXTRA] the string EXTRA
17405 [NO-EXTRA] do not include EXTRA
17407 For backward compatibility, if both the positive and the negative place
17408 holder is missing, the positive one (without the \"NO-\") will be
17409 assumed to be present at the end of the template.
17410 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17411 EXTRA is a string.
17412 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17413 (let (rpl (end ""))
17414 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17415 (setq rpl (if (or (match-end 1) (not def-pkg))
17416 "" (org-latex-packages-to-string def-pkg snippets-p t))
17417 tpl (replace-match rpl t t tpl))
17418 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17420 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17421 (setq rpl (if (or (match-end 1) (not pkg))
17422 "" (org-latex-packages-to-string pkg snippets-p t))
17423 tpl (replace-match rpl t t tpl))
17424 (if pkg (setq end
17425 (concat end "\n"
17426 (org-latex-packages-to-string pkg snippets-p)))))
17428 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17429 (setq rpl (if (or (match-end 1) (not extra))
17430 "" (concat extra "\n"))
17431 tpl (replace-match rpl t t tpl))
17432 (if (and extra (string-match "\\S-" extra))
17433 (setq end (concat end "\n" extra))))
17435 (if (string-match "\\S-" end)
17436 (concat tpl "\n" end)
17437 tpl)))
17439 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17440 "Turn an alist of packages into a string with the \\usepackage macros."
17441 (setq pkg (mapconcat (lambda(p)
17442 (cond
17443 ((stringp p) p)
17444 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17445 (format "%% Package %s omitted" (cadr p)))
17446 ((equal "" (car p))
17447 (format "\\usepackage{%s}" (cadr p)))
17449 (format "\\usepackage[%s]{%s}"
17450 (car p) (cadr p)))))
17452 "\n"))
17453 (if newline (concat pkg "\n") pkg))
17455 (defun org-dvipng-color (attr)
17456 "Return a RGB color specification for dvipng."
17457 (apply 'format "rgb %s %s %s"
17458 (mapcar 'org-normalize-color
17459 (if (featurep 'xemacs)
17460 (color-rgb-components
17461 (face-property 'default
17462 (cond ((eq attr :foreground) 'foreground)
17463 ((eq attr :background) 'background))))
17464 (color-values (face-attribute 'default attr nil))))))
17466 (defun org-latex-color (attr)
17467 "Return a RGB color for the LaTeX color package."
17468 (apply 'format "%s,%s,%s"
17469 (mapcar 'org-normalize-color
17470 (if (featurep 'xemacs)
17471 (color-rgb-components
17472 (face-property 'default
17473 (cond ((eq attr :foreground) 'foreground)
17474 ((eq attr :background) 'background))))
17475 (color-values (face-attribute 'default attr nil))))))
17477 (defun org-latex-color-format (color-name)
17478 "Convert COLOR-NAME to a RGB color value."
17479 (apply 'format "%s,%s,%s"
17480 (mapcar 'org-normalize-color
17481 (color-values color-name))))
17483 (defun org-normalize-color (value)
17484 "Return string to be used as color value for an RGB component."
17485 (format "%g" (/ value 65535.0)))
17487 ;; Image display
17490 (defvar org-inline-image-overlays nil)
17491 (make-variable-buffer-local 'org-inline-image-overlays)
17493 (defun org-toggle-inline-images (&optional include-linked)
17494 "Toggle the display of inline images.
17495 INCLUDE-LINKED is passed to `org-display-inline-images'."
17496 (interactive "P")
17497 (if org-inline-image-overlays
17498 (progn
17499 (org-remove-inline-images)
17500 (message "Inline image display turned off"))
17501 (org-display-inline-images include-linked)
17502 (if org-inline-image-overlays
17503 (message "%d images displayed inline"
17504 (length org-inline-image-overlays))
17505 (message "No images to display inline"))))
17507 (defun org-display-inline-images (&optional include-linked refresh beg end)
17508 "Display inline images.
17509 Normally only links without a description part are inlined, because this
17510 is how it will work for export. When INCLUDE-LINKED is set, also links
17511 with a description part will be inlined. This can be nice for a quick
17512 look at those images, but it does not reflect what exported files will look
17513 like.
17514 When REFRESH is set, refresh existing images between BEG and END.
17515 This will create new image displays only if necessary.
17516 BEG and END default to the buffer boundaries."
17517 (interactive "P")
17518 (unless refresh
17519 (org-remove-inline-images)
17520 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17521 (save-excursion
17522 (save-restriction
17523 (widen)
17524 (setq beg (or beg (point-min)) end (or end (point-max)))
17525 (goto-char beg)
17526 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17527 (substring (org-image-file-name-regexp) 0 -2)
17528 "\\)\\]" (if include-linked "" "\\]")))
17529 old file ov img)
17530 (while (re-search-forward re end t)
17531 (setq old (get-char-property-and-overlay (match-beginning 1)
17532 'org-image-overlay))
17533 (setq file (expand-file-name
17534 (concat (or (match-string 3) "") (match-string 4))))
17535 (when (file-exists-p file)
17536 (if (and (car-safe old) refresh)
17537 (image-refresh (overlay-get (cdr old) 'display))
17538 (setq img (save-match-data (create-image file)))
17539 (when img
17540 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17541 (overlay-put ov 'display img)
17542 (overlay-put ov 'face 'default)
17543 (overlay-put ov 'org-image-overlay t)
17544 (overlay-put ov 'modification-hooks
17545 (list 'org-display-inline-modification-hook))
17546 (push ov org-inline-image-overlays)))))))))
17548 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17549 "Remove inline-display overlay if a corresponding region is modified."
17550 (let ((inhibit-modification-hooks t))
17551 (when (and ov after)
17552 (delete ov org-inline-image-overlays)
17553 (delete-overlay ov))))
17555 (defun org-remove-inline-images ()
17556 "Remove inline display of images."
17557 (interactive)
17558 (mapc 'delete-overlay org-inline-image-overlays)
17559 (setq org-inline-image-overlays nil))
17561 ;;;; Key bindings
17563 ;; Outline functions from `outline-mode-prefix-map'
17564 ;; that can be remapped in Org:
17565 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17566 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17567 (define-key org-mode-map [remap outline-forward-same-level]
17568 'org-forward-same-level)
17569 (define-key org-mode-map [remap outline-backward-same-level]
17570 'org-backward-same-level)
17571 (define-key org-mode-map [remap show-branches]
17572 'org-kill-note-or-show-branches)
17573 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17574 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17575 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17577 ;; Outline functions from `outline-mode-prefix-map'
17578 ;; that can not be remapped in Org:
17579 ;; - the column "key binding" shows whether the Outline function is still
17580 ;; available in Org mode on the same key that it has been bound to in
17581 ;; Outline mode:
17582 ;; - "overridden": key used for a different functionality in Org mode
17583 ;; - else: key still bound to the same Outline function in Org mode
17584 ;; | Outline function | key binding | Org replacement |
17585 ;; |------------------------------------+-------------+-----------------------|
17586 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17587 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17588 ;; | `show-children' | `C-c C-i' | visibility cycling |
17589 ;; | `hide-subtree' | overridden | visibility cycling |
17590 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17591 ;; | `hide-body' | overridden | no replacement |
17592 ;; | `show-all' | overridden | no replacement |
17593 ;; | `hide-entry' | overridden | visibility cycling |
17594 ;; | `show-entry' | overridden | no replacement |
17595 ;; | `hide-leaves' | overridden | no replacement |
17596 ;; | `hide-sublevels' | overridden | no replacement |
17597 ;; | `hide-other' | overridden | no replacement |
17598 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17599 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17601 ;; Make `C-c C-x' a prefix key
17602 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17604 ;; TAB key with modifiers
17605 (org-defkey org-mode-map "\C-i" 'org-cycle)
17606 (org-defkey org-mode-map [(tab)] 'org-cycle)
17607 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17608 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17609 ;; The following line is necessary under Suse GNU/Linux
17610 (unless (featurep 'xemacs)
17611 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17612 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17613 (define-key org-mode-map [backtab] 'org-shifttab)
17615 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17616 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17617 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17619 ;; Cursor keys with modifiers
17620 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17621 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17622 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17623 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17625 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17626 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17627 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17628 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17630 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17631 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17632 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17633 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17635 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17636 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17637 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17638 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17640 ;; Babel keys
17641 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17642 (mapc (lambda (pair)
17643 (define-key org-babel-map (car pair) (cdr pair)))
17644 org-babel-key-bindings)
17646 ;;; Extra keys for tty access.
17647 ;; We only set them when really needed because otherwise the
17648 ;; menus don't show the simple keys
17650 (when (or org-use-extra-keys
17651 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17652 (not window-system))
17653 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17654 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17655 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17656 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17657 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17658 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17659 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17660 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17661 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17662 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17663 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17664 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17665 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17666 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17667 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17668 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17669 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17670 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17671 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17672 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17673 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17674 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17675 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17676 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17677 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17678 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17679 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17680 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17682 ;; All the other keys
17684 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17685 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17686 (if (boundp 'narrow-map)
17687 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17688 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17689 (if (boundp 'narrow-map)
17690 (org-defkey narrow-map "b" 'org-narrow-to-block)
17691 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17692 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17693 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17694 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17695 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17696 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17697 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17698 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17699 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17700 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17701 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17702 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17703 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17704 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17705 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17706 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17707 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17708 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17709 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17710 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17711 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17712 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17713 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17714 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17715 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17716 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17717 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17718 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17719 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17720 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17721 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17722 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17723 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17724 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17725 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17726 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17727 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17728 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17729 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17730 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17731 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17732 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17733 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17734 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17735 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17736 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17737 (org-defkey org-mode-map "\C-c^" 'org-sort)
17738 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17739 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17740 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17741 (org-defkey org-mode-map "\C-m" 'org-return)
17742 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17743 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17744 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17745 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17746 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17747 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17748 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17749 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17750 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17751 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17752 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17753 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17754 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17755 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17756 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17757 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17758 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17759 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17760 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17761 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17762 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17763 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17764 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17766 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17767 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17768 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17769 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17771 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17772 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17773 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17774 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17775 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17776 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17777 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17778 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17779 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17780 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17781 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17782 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17783 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17784 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17785 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17786 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17787 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17788 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17790 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17791 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17792 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17793 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17794 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17796 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17798 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17800 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17801 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17803 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17806 (when (featurep 'xemacs)
17807 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17810 (defconst org-speed-commands-default
17812 ("Outline Navigation")
17813 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17814 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17815 ("f" . (org-speed-move-safe 'org-forward-same-level))
17816 ("b" . (org-speed-move-safe 'org-backward-same-level))
17817 ("u" . (org-speed-move-safe 'outline-up-heading))
17818 ("j" . org-goto)
17819 ("g" . (org-refile t))
17820 ("Outline Visibility")
17821 ("c" . org-cycle)
17822 ("C" . org-shifttab)
17823 (" " . org-display-outline-path)
17824 ("Outline Structure Editing")
17825 ("U" . org-shiftmetaup)
17826 ("D" . org-shiftmetadown)
17827 ("r" . org-metaright)
17828 ("l" . org-metaleft)
17829 ("R" . org-shiftmetaright)
17830 ("L" . org-shiftmetaleft)
17831 ("i" . (progn (forward-char 1) (call-interactively
17832 'org-insert-heading-respect-content)))
17833 ("^" . org-sort)
17834 ("w" . org-refile)
17835 ("a" . org-archive-subtree-default-with-confirmation)
17836 ("." . org-mark-subtree)
17837 ("Clock Commands")
17838 ("I" . org-clock-in)
17839 ("O" . org-clock-out)
17840 ("Meta Data Editing")
17841 ("t" . org-todo)
17842 ("0" . (org-priority ?\ ))
17843 ("1" . (org-priority ?A))
17844 ("2" . (org-priority ?B))
17845 ("3" . (org-priority ?C))
17846 (";" . org-set-tags-command)
17847 ("e" . org-set-effort)
17848 ("Agenda Views etc")
17849 ("v" . org-agenda)
17850 ("/" . org-sparse-tree)
17851 ("Misc")
17852 ("o" . org-open-at-point)
17853 ("?" . org-speed-command-help)
17854 ("<" . (org-agenda-set-restriction-lock 'subtree))
17855 (">" . (org-agenda-remove-restriction-lock))
17857 "The default speed commands.")
17859 (defun org-print-speed-command (e)
17860 (if (> (length (car e)) 1)
17861 (progn
17862 (princ "\n")
17863 (princ (car e))
17864 (princ "\n")
17865 (princ (make-string (length (car e)) ?-))
17866 (princ "\n"))
17867 (princ (car e))
17868 (princ " ")
17869 (if (symbolp (cdr e))
17870 (princ (symbol-name (cdr e)))
17871 (prin1 (cdr e)))
17872 (princ "\n")))
17874 (defun org-speed-command-help ()
17875 "Show the available speed commands."
17876 (interactive)
17877 (if (not org-use-speed-commands)
17878 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17879 (with-output-to-temp-buffer "*Help*"
17880 (princ "User-defined Speed commands\n===========================\n")
17881 (mapc 'org-print-speed-command org-speed-commands-user)
17882 (princ "\n")
17883 (princ "Built-in Speed commands\n=======================\n")
17884 (mapc 'org-print-speed-command org-speed-commands-default))
17885 (with-current-buffer "*Help*"
17886 (setq truncate-lines t))))
17888 (defun org-speed-move-safe (cmd)
17889 "Execute CMD, but make sure that the cursor always ends up in a headline.
17890 If not, return to the original position and throw an error."
17891 (interactive)
17892 (let ((pos (point)))
17893 (call-interactively cmd)
17894 (unless (and (bolp) (org-at-heading-p))
17895 (goto-char pos)
17896 (error "Boundary reached while executing %s" cmd))))
17898 (defvar org-self-insert-command-undo-counter 0)
17900 (defvar org-table-auto-blank-field) ; defined in org-table.el
17901 (defvar org-speed-command nil)
17903 (defun org-speed-command-default-hook (keys)
17904 "Hook for activating single-letter speed commands.
17905 `org-speed-commands-default' specifies a minimal command set.
17906 Use `org-speed-commands-user' for further customization."
17907 (when (or (and (bolp) (looking-at org-outline-regexp))
17908 (and (functionp org-use-speed-commands)
17909 (funcall org-use-speed-commands)))
17910 (cdr (assoc keys (append org-speed-commands-user
17911 org-speed-commands-default)))))
17913 (defun org-babel-speed-command-hook (keys)
17914 "Hook for activating single-letter code block commands."
17915 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17916 (cdr (assoc keys org-babel-key-bindings))))
17918 (defcustom org-speed-command-hook
17919 '(org-speed-command-default-hook org-babel-speed-command-hook)
17920 "Hook for activating speed commands at strategic locations.
17921 Hook functions are called in sequence until a valid handler is
17922 found.
17924 Each hook takes a single argument, a user-pressed command key
17925 which is also a `self-insert-command' from the global map.
17927 Within the hook, examine the cursor position and the command key
17928 and return nil or a valid handler as appropriate. Handler could
17929 be one of an interactive command, a function, or a form.
17931 Set `org-use-speed-commands' to non-nil value to enable this
17932 hook. The default setting is `org-speed-command-default-hook'."
17933 :group 'org-structure
17934 :version "24.1"
17935 :type 'hook)
17937 (defun org-self-insert-command (N)
17938 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17939 If the cursor is in a table looking at whitespace, the whitespace is
17940 overwritten, and the table is not marked as requiring realignment."
17941 (interactive "p")
17942 (org-check-before-invisible-edit 'insert)
17943 (cond
17944 ((and org-use-speed-commands
17945 (setq org-speed-command
17946 (run-hook-with-args-until-success
17947 'org-speed-command-hook (this-command-keys))))
17948 (cond
17949 ((commandp org-speed-command)
17950 (setq this-command org-speed-command)
17951 (call-interactively org-speed-command))
17952 ((functionp org-speed-command)
17953 (funcall org-speed-command))
17954 ((and org-speed-command (listp org-speed-command))
17955 (eval org-speed-command))
17956 (t (let (org-use-speed-commands)
17957 (call-interactively 'org-self-insert-command)))))
17958 ((and
17959 (org-table-p)
17960 (progn
17961 ;; check if we blank the field, and if that triggers align
17962 (and (featurep 'org-table) org-table-auto-blank-field
17963 (member last-command
17964 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17965 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17966 ;; got extra space, this field does not determine column width
17967 (let (org-table-may-need-update) (org-table-blank-field))
17968 ;; no extra space, this field may determine column width
17969 (org-table-blank-field)))
17971 (eq N 1)
17972 (looking-at "[^|\n]* |"))
17973 (let (org-table-may-need-update)
17974 (goto-char (1- (match-end 0)))
17975 (backward-delete-char 1)
17976 (goto-char (match-beginning 0))
17977 (self-insert-command N)))
17979 (setq org-table-may-need-update t)
17980 (self-insert-command N)
17981 (org-fix-tags-on-the-fly)
17982 (if org-self-insert-cluster-for-undo
17983 (if (not (eq last-command 'org-self-insert-command))
17984 (setq org-self-insert-command-undo-counter 1)
17985 (if (>= org-self-insert-command-undo-counter 20)
17986 (setq org-self-insert-command-undo-counter 1)
17987 (and (> org-self-insert-command-undo-counter 0)
17988 buffer-undo-list (listp buffer-undo-list)
17989 (not (cadr buffer-undo-list)) ; remove nil entry
17990 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17991 (setq org-self-insert-command-undo-counter
17992 (1+ org-self-insert-command-undo-counter))))))))
17994 (defun org-check-before-invisible-edit (kind)
17995 "Check is editing if kind KIND would be dangerous with invisible text around.
17996 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17997 ;; First, try to get out of here as quickly as possible, to reduce overhead
17998 (if (and org-catch-invisible-edits
17999 (or (not (boundp 'visible-mode)) (not visible-mode))
18000 (or (get-char-property (point) 'invisible)
18001 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18002 ;; OK, we need to take a closer look
18003 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18004 (invisible-before-point (if (bobp) nil (get-char-property
18005 (1- (point)) 'invisible)))
18006 (border-and-ok-direction
18008 ;; Check if we are acting predictably before invisible text
18009 (and invisible-at-point (not invisible-before-point)
18010 (memq kind '(insert delete-backward)))
18011 ;; Check if we are acting predictably after invisible text
18012 ;; This works not well, and I have turned it off. It seems
18013 ;; better to always show and stop after invisible text.
18014 ;; (and (not invisible-at-point) invisible-before-point
18015 ;; (memq kind '(insert delete)))
18018 (when (or (memq invisible-at-point '(outline org-hide-block))
18019 (memq invisible-before-point '(outline org-hide-block)))
18020 (if (eq org-catch-invisible-edits 'error)
18021 (error "Editing in invisible areas is prohibited - make visible first"))
18022 ;; Make the area visible
18023 (save-excursion
18024 (if invisible-before-point
18025 (goto-char (previous-single-char-property-change
18026 (point) 'invisible)))
18027 (org-cycle))
18028 (cond
18029 ((eq org-catch-invisible-edits 'show)
18030 ;; That's it, we do the edit after showing
18031 (message
18032 "Unfolding invisible region around point before editing")
18033 (sit-for 1))
18034 ((and (eq org-catch-invisible-edits 'smart)
18035 border-and-ok-direction)
18036 (message "Unfolding invisible region around point before editing"))
18038 ;; Don't do the edit, make the user repeat it in full visibility
18039 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
18041 (defun org-fix-tags-on-the-fly ()
18042 (when (and (equal (char-after (point-at-bol)) ?*)
18043 (org-at-heading-p))
18044 (org-align-tags-here org-tags-column)))
18046 (defun org-delete-backward-char (N)
18047 "Like `delete-backward-char', insert whitespace at field end in tables.
18048 When deleting backwards, in tables this function will insert whitespace in
18049 front of the next \"|\" separator, to keep the table aligned. The table will
18050 still be marked for re-alignment if the field did fill the entire column,
18051 because, in this case the deletion might narrow the column."
18052 (interactive "p")
18053 (org-check-before-invisible-edit 'delete-backward)
18054 (if (and (org-table-p)
18055 (eq N 1)
18056 (string-match "|" (buffer-substring (point-at-bol) (point)))
18057 (looking-at ".*?|"))
18058 (let ((pos (point))
18059 (noalign (looking-at "[^|\n\r]* |"))
18060 (c org-table-may-need-update))
18061 (backward-delete-char N)
18062 (if (not overwrite-mode)
18063 (progn
18064 (skip-chars-forward "^|")
18065 (insert " ")
18066 (goto-char (1- pos))))
18067 ;; noalign: if there were two spaces at the end, this field
18068 ;; does not determine the width of the column.
18069 (if noalign (setq org-table-may-need-update c)))
18070 (backward-delete-char N)
18071 (org-fix-tags-on-the-fly)))
18073 (defun org-delete-char (N)
18074 "Like `delete-char', but insert whitespace at field end in tables.
18075 When deleting characters, in tables this function will insert whitespace in
18076 front of the next \"|\" separator, to keep the table aligned. The table will
18077 still be marked for re-alignment if the field did fill the entire column,
18078 because, in this case the deletion might narrow the column."
18079 (interactive "p")
18080 (org-check-before-invisible-edit 'delete)
18081 (if (and (org-table-p)
18082 (not (bolp))
18083 (not (= (char-after) ?|))
18084 (eq N 1))
18085 (if (looking-at ".*?|")
18086 (let ((pos (point))
18087 (noalign (looking-at "[^|\n\r]* |"))
18088 (c org-table-may-need-update))
18089 (replace-match (concat
18090 (substring (match-string 0) 1 -1)
18091 " |"))
18092 (goto-char pos)
18093 ;; noalign: if there were two spaces at the end, this field
18094 ;; does not determine the width of the column.
18095 (if noalign (setq org-table-may-need-update c)))
18096 (delete-char N))
18097 (delete-char N)
18098 (org-fix-tags-on-the-fly)))
18100 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18101 (put 'org-self-insert-command 'delete-selection t)
18102 (put 'orgtbl-self-insert-command 'delete-selection t)
18103 (put 'org-delete-char 'delete-selection 'supersede)
18104 (put 'org-delete-backward-char 'delete-selection 'supersede)
18105 (put 'org-yank 'delete-selection 'yank)
18107 ;; Make `flyspell-mode' delay after some commands
18108 (put 'org-self-insert-command 'flyspell-delayed t)
18109 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18110 (put 'org-delete-char 'flyspell-delayed t)
18111 (put 'org-delete-backward-char 'flyspell-delayed t)
18113 ;; Make pabbrev-mode expand after org-mode commands
18114 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18115 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18117 ;; How to do this: Measure non-white length of current string
18118 ;; If equal to column width, we should realign.
18120 (defun org-remap (map &rest commands)
18121 "In MAP, remap the functions given in COMMANDS.
18122 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18123 (let (new old)
18124 (while commands
18125 (setq old (pop commands) new (pop commands))
18126 (if (fboundp 'command-remapping)
18127 (org-defkey map (vector 'remap old) new)
18128 (substitute-key-definition old new map global-map)))))
18130 (when (eq org-enable-table-editor 'optimized)
18131 ;; If the user wants maximum table support, we need to hijack
18132 ;; some standard editing functions
18133 (org-remap org-mode-map
18134 'self-insert-command 'org-self-insert-command
18135 'delete-char 'org-delete-char
18136 'delete-backward-char 'org-delete-backward-char)
18137 (org-defkey org-mode-map "|" 'org-force-self-insert))
18139 (defvar org-ctrl-c-ctrl-c-hook nil
18140 "Hook for functions attaching themselves to `C-c C-c'.
18142 This can be used to add additional functionality to the C-c C-c
18143 key which executes context-dependent commands. This hook is run
18144 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18145 run after the last test.
18147 Each function will be called with no arguments. The function
18148 must check if the context is appropriate for it to act. If yes,
18149 it should do its thing and then return a non-nil value. If the
18150 context is wrong, just do nothing and return nil.")
18152 (defvar org-ctrl-c-ctrl-c-final-hook nil
18153 "Hook for functions attaching themselves to `C-c C-c'.
18155 This can be used to add additional functionality to the C-c C-c
18156 key which executes context-dependent commands. This hook is run
18157 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18158 before the first test.
18160 Each function will be called with no arguments. The function
18161 must check if the context is appropriate for it to act. If yes,
18162 it should do its thing and then return a non-nil value. If the
18163 context is wrong, just do nothing and return nil.")
18165 (defvar org-tab-first-hook nil
18166 "Hook for functions to attach themselves to TAB.
18167 See `org-ctrl-c-ctrl-c-hook' for more information.
18168 This hook runs as the first action when TAB is pressed, even before
18169 `org-cycle' messes around with the `outline-regexp' to cater for
18170 inline tasks and plain list item folding.
18171 If any function in this hook returns t, any other actions that
18172 would have been caused by TAB (such as table field motion or visibility
18173 cycling) will not occur.")
18175 (defvar org-tab-after-check-for-table-hook nil
18176 "Hook for functions to attach themselves to TAB.
18177 See `org-ctrl-c-ctrl-c-hook' for more information.
18178 This hook runs after it has been established that the cursor is not in a
18179 table, but before checking if the cursor is in a headline or if global cycling
18180 should be done.
18181 If any function in this hook returns t, not other actions like visibility
18182 cycling will be done.")
18184 (defvar org-tab-after-check-for-cycling-hook nil
18185 "Hook for functions to attach themselves to TAB.
18186 See `org-ctrl-c-ctrl-c-hook' for more information.
18187 This hook runs after it has been established that not table field motion and
18188 not visibility should be done because of current context. This is probably
18189 the place where a package like yasnippets can hook in.")
18191 (defvar org-tab-before-tab-emulation-hook nil
18192 "Hook for functions to attach themselves to TAB.
18193 See `org-ctrl-c-ctrl-c-hook' for more information.
18194 This hook runs after every other options for TAB have been exhausted, but
18195 before indentation and \t insertion takes place.")
18197 (defvar org-metaleft-hook nil
18198 "Hook for functions attaching themselves to `M-left'.
18199 See `org-ctrl-c-ctrl-c-hook' for more information.")
18200 (defvar org-metaright-hook nil
18201 "Hook for functions attaching themselves to `M-right'.
18202 See `org-ctrl-c-ctrl-c-hook' for more information.")
18203 (defvar org-metaup-hook nil
18204 "Hook for functions attaching themselves to `M-up'.
18205 See `org-ctrl-c-ctrl-c-hook' for more information.")
18206 (defvar org-metadown-hook nil
18207 "Hook for functions attaching themselves to `M-down'.
18208 See `org-ctrl-c-ctrl-c-hook' for more information.")
18209 (defvar org-shiftmetaleft-hook nil
18210 "Hook for functions attaching themselves to `M-S-left'.
18211 See `org-ctrl-c-ctrl-c-hook' for more information.")
18212 (defvar org-shiftmetaright-hook nil
18213 "Hook for functions attaching themselves to `M-S-right'.
18214 See `org-ctrl-c-ctrl-c-hook' for more information.")
18215 (defvar org-shiftmetaup-hook nil
18216 "Hook for functions attaching themselves to `M-S-up'.
18217 See `org-ctrl-c-ctrl-c-hook' for more information.")
18218 (defvar org-shiftmetadown-hook nil
18219 "Hook for functions attaching themselves to `M-S-down'.
18220 See `org-ctrl-c-ctrl-c-hook' for more information.")
18221 (defvar org-metareturn-hook nil
18222 "Hook for functions attaching themselves to `M-RET'.
18223 See `org-ctrl-c-ctrl-c-hook' for more information.")
18224 (defvar org-shiftup-hook nil
18225 "Hook for functions attaching themselves to `S-up'.
18226 See `org-ctrl-c-ctrl-c-hook' for more information.")
18227 (defvar org-shiftup-final-hook nil
18228 "Hook for functions attaching themselves to `S-up'.
18229 This one runs after all other options except shift-select have been excluded.
18230 See `org-ctrl-c-ctrl-c-hook' for more information.")
18231 (defvar org-shiftdown-hook nil
18232 "Hook for functions attaching themselves to `S-down'.
18233 See `org-ctrl-c-ctrl-c-hook' for more information.")
18234 (defvar org-shiftdown-final-hook nil
18235 "Hook for functions attaching themselves to `S-down'.
18236 This one runs after all other options except shift-select have been excluded.
18237 See `org-ctrl-c-ctrl-c-hook' for more information.")
18238 (defvar org-shiftleft-hook nil
18239 "Hook for functions attaching themselves to `S-left'.
18240 See `org-ctrl-c-ctrl-c-hook' for more information.")
18241 (defvar org-shiftleft-final-hook nil
18242 "Hook for functions attaching themselves to `S-left'.
18243 This one runs after all other options except shift-select have been excluded.
18244 See `org-ctrl-c-ctrl-c-hook' for more information.")
18245 (defvar org-shiftright-hook nil
18246 "Hook for functions attaching themselves to `S-right'.
18247 See `org-ctrl-c-ctrl-c-hook' for more information.")
18248 (defvar org-shiftright-final-hook nil
18249 "Hook for functions attaching themselves to `S-right'.
18250 This one runs after all other options except shift-select have been excluded.
18251 See `org-ctrl-c-ctrl-c-hook' for more information.")
18253 (defun org-modifier-cursor-error ()
18254 "Throw an error, a modified cursor command was applied in wrong context."
18255 (error "This command is active in special context like tables, headlines or items"))
18257 (defun org-shiftselect-error ()
18258 "Throw an error because Shift-Cursor command was applied in wrong context."
18259 (if (and (boundp 'shift-select-mode) shift-select-mode)
18260 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18261 (error "This command works only in special context like headlines or timestamps")))
18263 (defun org-call-for-shift-select (cmd)
18264 (let ((this-command-keys-shift-translated t))
18265 (call-interactively cmd)))
18267 (defun org-shifttab (&optional arg)
18268 "Global visibility cycling or move to previous table field.
18269 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18270 on context.
18271 See the individual commands for more information."
18272 (interactive "P")
18273 (cond
18274 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18275 ((integerp arg)
18276 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18277 (message "Content view to level: %d" arg)
18278 (org-content (prefix-numeric-value arg2))
18279 (setq org-cycle-global-status 'overview)))
18280 (t (call-interactively 'org-global-cycle))))
18282 (defun org-shiftmetaleft ()
18283 "Promote subtree or delete table column.
18284 Calls `org-promote-subtree', `org-outdent-item-tree', or
18285 `org-table-delete-column', depending on context. See the
18286 individual commands for more information."
18287 (interactive)
18288 (cond
18289 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18290 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18291 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18292 ((if (not (org-region-active-p)) (org-at-item-p)
18293 (save-excursion (goto-char (region-beginning))
18294 (org-at-item-p)))
18295 (call-interactively 'org-outdent-item-tree))
18296 (t (org-modifier-cursor-error))))
18298 (defun org-shiftmetaright ()
18299 "Demote subtree or insert table column.
18300 Calls `org-demote-subtree', `org-indent-item-tree', or
18301 `org-table-insert-column', depending on context. See the
18302 individual commands for more information."
18303 (interactive)
18304 (cond
18305 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18306 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18307 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18308 ((if (not (org-region-active-p)) (org-at-item-p)
18309 (save-excursion (goto-char (region-beginning))
18310 (org-at-item-p)))
18311 (call-interactively 'org-indent-item-tree))
18312 (t (org-modifier-cursor-error))))
18314 (defun org-shiftmetaup (&optional arg)
18315 "Move subtree up or kill table row.
18316 Calls `org-move-subtree-up' or `org-table-kill-row' or
18317 `org-move-item-up' depending on context. See the individual commands
18318 for more information."
18319 (interactive "P")
18320 (cond
18321 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18322 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18323 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18324 ((org-at-item-p) (call-interactively 'org-move-item-up))
18325 (t (org-modifier-cursor-error))))
18327 (defun org-shiftmetadown (&optional arg)
18328 "Move subtree down or insert table row.
18329 Calls `org-move-subtree-down' or `org-table-insert-row' or
18330 `org-move-item-down', depending on context. See the individual
18331 commands for more information."
18332 (interactive "P")
18333 (cond
18334 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18335 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18336 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18337 ((org-at-item-p) (call-interactively 'org-move-item-down))
18338 (t (org-modifier-cursor-error))))
18340 (defsubst org-hidden-tree-error ()
18341 (error
18342 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18344 (defun org-metaleft (&optional arg)
18345 "Promote heading or move table column to left.
18346 Calls `org-do-promote' or `org-table-move-column', depending on context.
18347 With no specific context, calls the Emacs default `backward-word'.
18348 See the individual commands for more information."
18349 (interactive "P")
18350 (cond
18351 ((run-hook-with-args-until-success 'org-metaleft-hook))
18352 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18353 ((org-with-limited-levels
18354 (or (org-at-heading-p)
18355 (and (org-region-active-p)
18356 (save-excursion
18357 (goto-char (region-beginning))
18358 (org-at-heading-p)))))
18359 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18360 (call-interactively 'org-do-promote))
18361 ;; At an inline task.
18362 ((org-at-heading-p)
18363 (call-interactively 'org-inlinetask-promote))
18364 ((or (org-at-item-p)
18365 (and (org-region-active-p)
18366 (save-excursion
18367 (goto-char (region-beginning))
18368 (org-at-item-p))))
18369 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18370 (call-interactively 'org-outdent-item))
18371 (t (call-interactively 'backward-word))))
18373 (defun org-metaright (&optional arg)
18374 "Demote a subtree, a list item or move table column to right.
18375 In front of a drawer or a block keyword, indent it correctly.
18376 With no specific context, calls the Emacs default `forward-word'.
18377 See the individual commands for more information."
18378 (interactive "P")
18379 (cond
18380 ((run-hook-with-args-until-success 'org-metaright-hook))
18381 ((org-at-table-p) (call-interactively 'org-table-move-column))
18382 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18383 ((org-at-block-p) (call-interactively 'org-indent-block))
18384 ((org-with-limited-levels
18385 (or (org-at-heading-p)
18386 (and (org-region-active-p)
18387 (save-excursion
18388 (goto-char (region-beginning))
18389 (org-at-heading-p)))))
18390 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18391 (call-interactively 'org-do-demote))
18392 ;; At an inline task.
18393 ((org-at-heading-p)
18394 (call-interactively 'org-inlinetask-demote))
18395 ((or (org-at-item-p)
18396 (and (org-region-active-p)
18397 (save-excursion
18398 (goto-char (region-beginning))
18399 (org-at-item-p))))
18400 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18401 (call-interactively 'org-indent-item))
18402 (t (call-interactively 'forward-word))))
18404 (defun org-check-for-hidden (what)
18405 "Check if there are hidden headlines/items in the current visual line.
18406 WHAT can be either `headlines' or `items'. If the current line is
18407 an outline or item heading and it has a folded subtree below it,
18408 this function returns t, nil otherwise."
18409 (let ((re (cond
18410 ((eq what 'headlines) org-outline-regexp-bol)
18411 ((eq what 'items) (org-item-beginning-re))
18412 (t (error "This should not happen"))))
18413 beg end)
18414 (save-excursion
18415 (catch 'exit
18416 (unless (org-region-active-p)
18417 (setq beg (point-at-bol))
18418 (beginning-of-line 2)
18419 (while (and (not (eobp)) ;; this is like `next-line'
18420 (get-char-property (1- (point)) 'invisible))
18421 (beginning-of-line 2))
18422 (setq end (point))
18423 (goto-char beg)
18424 (goto-char (point-at-eol))
18425 (setq end (max end (point)))
18426 (while (re-search-forward re end t)
18427 (if (get-char-property (match-beginning 0) 'invisible)
18428 (throw 'exit t))))
18429 nil))))
18431 (defun org-metaup (&optional arg)
18432 "Move subtree up or move table row up.
18433 Calls `org-move-subtree-up' or `org-table-move-row' or
18434 `org-move-item-up', depending on context. See the individual commands
18435 for more information."
18436 (interactive "P")
18437 (cond
18438 ((run-hook-with-args-until-success 'org-metaup-hook))
18439 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18440 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18441 ((org-at-item-p) (call-interactively 'org-move-item-up))
18442 (t (transpose-lines 1) (beginning-of-line -1))))
18444 (defun org-metadown (&optional arg)
18445 "Move subtree down or move table row down.
18446 Calls `org-move-subtree-down' or `org-table-move-row' or
18447 `org-move-item-down', depending on context. See the individual
18448 commands for more information."
18449 (interactive "P")
18450 (cond
18451 ((run-hook-with-args-until-success 'org-metadown-hook))
18452 ((org-at-table-p) (call-interactively 'org-table-move-row))
18453 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18454 ((org-at-item-p) (call-interactively 'org-move-item-down))
18455 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18457 (defun org-shiftup (&optional arg)
18458 "Increase item in timestamp or increase priority of current headline.
18459 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18460 depending on context. See the individual commands for more information."
18461 (interactive "P")
18462 (cond
18463 ((run-hook-with-args-until-success 'org-shiftup-hook))
18464 ((and org-support-shift-select (org-region-active-p))
18465 (org-call-for-shift-select 'previous-line))
18466 ((org-at-timestamp-p t)
18467 (call-interactively (if org-edit-timestamp-down-means-later
18468 'org-timestamp-down 'org-timestamp-up)))
18469 ((and (not (eq org-support-shift-select 'always))
18470 org-enable-priority-commands
18471 (org-at-heading-p))
18472 (call-interactively 'org-priority-up))
18473 ((and (not org-support-shift-select) (org-at-item-p))
18474 (call-interactively 'org-previous-item))
18475 ((org-clocktable-try-shift 'up arg))
18476 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18477 (org-support-shift-select
18478 (org-call-for-shift-select 'previous-line))
18479 (t (org-shiftselect-error))))
18481 (defun org-shiftdown (&optional arg)
18482 "Decrease item in timestamp or decrease priority of current headline.
18483 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18484 depending on context. See the individual commands for more information."
18485 (interactive "P")
18486 (cond
18487 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18488 ((and org-support-shift-select (org-region-active-p))
18489 (org-call-for-shift-select 'next-line))
18490 ((org-at-timestamp-p t)
18491 (call-interactively (if org-edit-timestamp-down-means-later
18492 'org-timestamp-up 'org-timestamp-down)))
18493 ((and (not (eq org-support-shift-select 'always))
18494 org-enable-priority-commands
18495 (org-at-heading-p))
18496 (call-interactively 'org-priority-down))
18497 ((and (not org-support-shift-select) (org-at-item-p))
18498 (call-interactively 'org-next-item))
18499 ((org-clocktable-try-shift 'down arg))
18500 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18501 (org-support-shift-select
18502 (org-call-for-shift-select 'next-line))
18503 (t (org-shiftselect-error))))
18505 (defun org-shiftright (&optional arg)
18506 "Cycle the thing at point or in the current line, depending on context.
18507 Depending on context, this does one of the following:
18509 - switch a timestamp at point one day into the future
18510 - on a headline, switch to the next TODO keyword.
18511 - on an item, switch entire list to the next bullet type
18512 - on a property line, switch to the next allowed value
18513 - on a clocktable definition line, move time block into the future"
18514 (interactive "P")
18515 (cond
18516 ((run-hook-with-args-until-success 'org-shiftright-hook))
18517 ((and org-support-shift-select (org-region-active-p))
18518 (org-call-for-shift-select 'forward-char))
18519 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18520 ((and (not (eq org-support-shift-select 'always))
18521 (org-at-heading-p))
18522 (let ((org-inhibit-logging
18523 (not org-treat-S-cursor-todo-selection-as-state-change))
18524 (org-inhibit-blocking
18525 (not org-treat-S-cursor-todo-selection-as-state-change)))
18526 (org-call-with-arg 'org-todo 'right)))
18527 ((or (and org-support-shift-select
18528 (not (eq org-support-shift-select 'always))
18529 (org-at-item-bullet-p))
18530 (and (not org-support-shift-select) (org-at-item-p)))
18531 (org-call-with-arg 'org-cycle-list-bullet nil))
18532 ((and (not (eq org-support-shift-select 'always))
18533 (org-at-property-p))
18534 (call-interactively 'org-property-next-allowed-value))
18535 ((org-clocktable-try-shift 'right arg))
18536 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18537 (org-support-shift-select
18538 (org-call-for-shift-select 'forward-char))
18539 (t (org-shiftselect-error))))
18541 (defun org-shiftleft (&optional arg)
18542 "Cycle the thing at point or in the current line, depending on context.
18543 Depending on context, this does one of the following:
18545 - switch a timestamp at point one day into the past
18546 - on a headline, switch to the previous TODO keyword.
18547 - on an item, switch entire list to the previous bullet type
18548 - on a property line, switch to the previous allowed value
18549 - on a clocktable definition line, move time block into the past"
18550 (interactive "P")
18551 (cond
18552 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18553 ((and org-support-shift-select (org-region-active-p))
18554 (org-call-for-shift-select 'backward-char))
18555 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18556 ((and (not (eq org-support-shift-select 'always))
18557 (org-at-heading-p))
18558 (let ((org-inhibit-logging
18559 (not org-treat-S-cursor-todo-selection-as-state-change))
18560 (org-inhibit-blocking
18561 (not org-treat-S-cursor-todo-selection-as-state-change)))
18562 (org-call-with-arg 'org-todo 'left)))
18563 ((or (and org-support-shift-select
18564 (not (eq org-support-shift-select 'always))
18565 (org-at-item-bullet-p))
18566 (and (not org-support-shift-select) (org-at-item-p)))
18567 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18568 ((and (not (eq org-support-shift-select 'always))
18569 (org-at-property-p))
18570 (call-interactively 'org-property-previous-allowed-value))
18571 ((org-clocktable-try-shift 'left arg))
18572 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18573 (org-support-shift-select
18574 (org-call-for-shift-select 'backward-char))
18575 (t (org-shiftselect-error))))
18577 (defun org-shiftcontrolright ()
18578 "Switch to next TODO set."
18579 (interactive)
18580 (cond
18581 ((and org-support-shift-select (org-region-active-p))
18582 (org-call-for-shift-select 'forward-word))
18583 ((and (not (eq org-support-shift-select 'always))
18584 (org-at-heading-p))
18585 (org-call-with-arg 'org-todo 'nextset))
18586 (org-support-shift-select
18587 (org-call-for-shift-select 'forward-word))
18588 (t (org-shiftselect-error))))
18590 (defun org-shiftcontrolleft ()
18591 "Switch to previous TODO set."
18592 (interactive)
18593 (cond
18594 ((and org-support-shift-select (org-region-active-p))
18595 (org-call-for-shift-select 'backward-word))
18596 ((and (not (eq org-support-shift-select 'always))
18597 (org-at-heading-p))
18598 (org-call-with-arg 'org-todo 'previousset))
18599 (org-support-shift-select
18600 (org-call-for-shift-select 'backward-word))
18601 (t (org-shiftselect-error))))
18603 (defun org-shiftcontrolup ()
18604 "Change timestamps synchronously up in CLOCK log lines."
18605 (interactive)
18606 (cond ((and (not org-support-shift-select)
18607 (org-at-clock-log-p)
18608 (org-at-timestamp-p t))
18609 (org-clock-timestamps-up))
18610 (t (org-shiftselect-error))))
18612 (defun org-shiftcontroldown ()
18613 "Change timestamps synchronously down in CLOCK log lines."
18614 (interactive)
18615 (cond ((and (not org-support-shift-select)
18616 (org-at-clock-log-p)
18617 (org-at-timestamp-p t))
18618 (org-clock-timestamps-down))
18619 (t (org-shiftselect-error))))
18621 (defun org-ctrl-c-ret ()
18622 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18623 (interactive)
18624 (cond
18625 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18626 (t (call-interactively 'org-insert-heading))))
18628 (defun org-find-visible ()
18629 (let ((s (point)))
18630 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18631 (get-char-property s 'invisible)))
18633 (defun org-find-invisible ()
18634 (let ((s (point)))
18635 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18636 (not (get-char-property s 'invisible))))
18639 (defun org-copy-visible (beg end)
18640 "Copy the visible parts of the region."
18641 (interactive "r")
18642 (let (snippets s)
18643 (save-excursion
18644 (save-restriction
18645 (narrow-to-region beg end)
18646 (setq s (goto-char (point-min)))
18647 (while (not (= (point) (point-max)))
18648 (goto-char (org-find-invisible))
18649 (push (buffer-substring s (point)) snippets)
18650 (setq s (goto-char (org-find-visible))))))
18651 (kill-new (apply 'concat (nreverse snippets)))))
18653 (defun org-copy-special ()
18654 "Copy region in table or copy current subtree.
18655 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18656 See the individual commands for more information."
18657 (interactive)
18658 (call-interactively
18659 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18661 (defun org-cut-special ()
18662 "Cut region in table or cut current subtree.
18663 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18664 See the individual commands for more information."
18665 (interactive)
18666 (call-interactively
18667 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18669 (defun org-paste-special (arg)
18670 "Paste rectangular region into table, or past subtree relative to level.
18671 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18672 See the individual commands for more information."
18673 (interactive "P")
18674 (if (org-at-table-p)
18675 (org-table-paste-rectangle)
18676 (org-paste-subtree arg)))
18678 (defun org-edit-special (&optional arg)
18679 "Call a special editor for the stuff at point.
18680 When at a table, call the formula editor with `org-table-edit-formulas'.
18681 When at the first line of an src example, call `org-edit-src-code'.
18682 When in an #+include line, visit the include file. Otherwise call
18683 `ffap' to visit the file at point."
18684 (interactive)
18685 ;; possibly prep session before editing source
18686 (when arg
18687 (let* ((info (org-babel-get-src-block-info))
18688 (lang (nth 0 info))
18689 (params (nth 2 info))
18690 (session (cdr (assoc :session params))))
18691 (when (and info session) ;; we are in a source-code block with a session
18692 (funcall
18693 (intern (concat "org-babel-prep-session:" lang)) session params))))
18694 (cond ;; proceed with `org-edit-special'
18695 ((save-excursion
18696 (beginning-of-line 1)
18697 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18698 (find-file (org-trim (match-string 1))))
18699 ((org-edit-src-code))
18700 ((org-edit-fixed-width-region))
18701 ((org-at-table.el-p)
18702 (org-edit-src-code))
18703 ((or (org-at-table-p)
18704 (save-excursion
18705 (beginning-of-line 1)
18706 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18707 (call-interactively 'org-table-edit-formulas))
18708 (t (call-interactively 'ffap))))
18710 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18711 (defun org-ctrl-c-ctrl-c (&optional arg)
18712 "Set tags in headline, or update according to changed information at point.
18714 This command does many different things, depending on context:
18716 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18717 this is what we do.
18719 - If the cursor is on a statistics cookie, update it.
18721 - If the cursor is in a headline, prompt for tags and insert them
18722 into the current line, aligned to `org-tags-column'. When called
18723 with prefix arg, realign all tags in the current buffer.
18725 - If the cursor is in one of the special #+KEYWORD lines, this
18726 triggers scanning the buffer for these lines and updating the
18727 information.
18729 - If the cursor is inside a table, realign the table. This command
18730 works even if the automatic table editor has been turned off.
18732 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18733 the entire table.
18735 - If the cursor is at a footnote reference or definition, jump to
18736 the corresponding definition or references, respectively.
18738 - If the cursor is a the beginning of a dynamic block, update it.
18740 - If the current buffer is a capture buffer, close note and file it.
18742 - If the cursor is on a <<<target>>>, update radio targets and
18743 corresponding links in this buffer.
18745 - If the cursor is on a numbered item in a plain list, renumber the
18746 ordered list.
18748 - If the cursor is on a checkbox, toggle it.
18750 - If the cursor is on a code block, evaluate it. The variable
18751 `org-confirm-babel-evaluate' can be used to control prompting
18752 before code block evaluation, by default every code block
18753 evaluation requires confirmation. Code block evaluation can be
18754 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18755 (interactive "P")
18756 (let ((org-enable-table-editor t))
18757 (cond
18758 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18759 org-occur-highlights
18760 org-latex-fragment-image-overlays)
18761 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18762 (org-remove-occur-highlights)
18763 (org-remove-latex-fragment-image-overlays)
18764 (message "Temporary highlights/overlays removed from current buffer"))
18765 ((and (local-variable-p 'org-finish-function (current-buffer))
18766 (fboundp org-finish-function))
18767 (funcall org-finish-function))
18768 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18769 ((org-in-regexp org-ts-regexp-both)
18770 (org-timestamp-change 0 'day))
18771 ((or (looking-at org-property-start-re)
18772 (org-at-property-p))
18773 (call-interactively 'org-property-action))
18774 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18775 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18776 (or (org-at-heading-p) (org-at-item-p)))
18777 (call-interactively 'org-update-statistics-cookies))
18778 ((org-at-heading-p) (call-interactively 'org-set-tags))
18779 ((org-at-table.el-p)
18780 (message "Use C-c ' to edit table.el tables"))
18781 ((org-at-table-p)
18782 (org-table-maybe-eval-formula)
18783 (if arg
18784 (call-interactively 'org-table-recalculate)
18785 (org-table-maybe-recalculate-line))
18786 (call-interactively 'org-table-align)
18787 (orgtbl-send-table 'maybe))
18788 ((or (org-footnote-at-reference-p)
18789 (org-footnote-at-definition-p))
18790 (call-interactively 'org-footnote-action))
18791 ((org-at-item-checkbox-p)
18792 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18793 ;; list only if at top item.
18794 (let* ((cbox (match-string 1))
18795 (struct (org-list-struct))
18796 (old-struct (copy-tree struct))
18797 (parents (org-list-parents-alist struct))
18798 (orderedp (org-entry-get nil "ORDERED"))
18799 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18800 block-item)
18801 ;; Use a light version of `org-toggle-checkbox' to avoid
18802 ;; computing list structure twice.
18803 (let ((new-box (cond
18804 ((equal arg '(16)) "[-]")
18805 ((equal arg '(4)) nil)
18806 ((equal "[X]" cbox) "[ ]")
18807 (t "[X]"))))
18808 (if (and firstp arg)
18809 ;; If at first item of sub-list, remove check-box from
18810 ;; every item at the same level.
18811 (mapc
18812 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18813 (org-list-get-all-items
18814 (point-at-bol) struct (org-list-prevs-alist struct)))
18815 (org-list-set-checkbox (point-at-bol) struct new-box)))
18816 ;; Replicate `org-list-write-struct', while grabbing a return
18817 ;; value from `org-list-struct-fix-box'.
18818 (org-list-struct-fix-ind struct parents 2)
18819 (org-list-struct-fix-item-end struct)
18820 (let ((prevs (org-list-prevs-alist struct)))
18821 (org-list-struct-fix-bul struct prevs)
18822 (org-list-struct-fix-ind struct parents)
18823 (setq block-item
18824 (org-list-struct-fix-box struct parents prevs orderedp)))
18825 (org-list-struct-apply-struct struct old-struct)
18826 (org-update-checkbox-count-maybe)
18827 (when block-item
18828 (message
18829 "Checkboxes were removed due to unchecked box at line %d"
18830 (org-current-line block-item)))
18831 (when firstp (org-list-send-list 'maybe))))
18832 ((org-at-item-p)
18833 ;; Cursor at an item: repair list. Do checkbox related actions
18834 ;; only if function was called with an argument. Send list only
18835 ;; if at top item.
18836 (let* ((struct (org-list-struct))
18837 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18838 old-struct)
18839 (when arg
18840 (setq old-struct (copy-tree struct))
18841 (if firstp
18842 ;; If at first item of sub-list, add check-box to every
18843 ;; item at the same level.
18844 (mapc
18845 (lambda (pos)
18846 (unless (org-list-get-checkbox pos struct)
18847 (org-list-set-checkbox pos struct "[ ]")))
18848 (org-list-get-all-items
18849 (point-at-bol) struct (org-list-prevs-alist struct)))
18850 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18851 (org-list-write-struct
18852 struct (org-list-parents-alist struct) old-struct)
18853 (when arg (org-update-checkbox-count-maybe))
18854 (when firstp (org-list-send-list 'maybe))))
18855 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18856 ;; Dynamic block
18857 (beginning-of-line 1)
18858 (save-excursion (org-update-dblock)))
18859 ((save-excursion
18860 (let ((case-fold-search t))
18861 (beginning-of-line 1)
18862 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
18863 (cond
18864 ((or (equal (match-string 1) "TBLFM")
18865 (equal (match-string 1) "tblfm"))
18866 ;; Recalculate the table before this line
18867 (save-excursion
18868 (beginning-of-line 1)
18869 (skip-chars-backward " \r\n\t")
18870 (if (org-at-table-p)
18871 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18873 (let ((org-inhibit-startup-visibility-stuff t)
18874 (org-startup-align-all-tables nil))
18875 (when (boundp 'org-table-coordinate-overlays)
18876 (mapc 'delete-overlay org-table-coordinate-overlays)
18877 (setq org-table-coordinate-overlays nil))
18878 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18879 (message "Local setup has been refreshed"))))
18880 ((org-clock-update-time-maybe))
18882 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18883 (error "C-c C-c can do nothing useful at this location"))))))
18885 (defun org-mode-restart ()
18886 "Restart Org-mode, to scan again for special lines.
18887 Also updates the keyword regular expressions."
18888 (interactive)
18889 (org-mode)
18890 (message "Org-mode restarted"))
18892 (defun org-kill-note-or-show-branches ()
18893 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18894 (interactive)
18895 (if (not org-finish-function)
18896 (progn
18897 (hide-subtree)
18898 (call-interactively 'show-branches))
18899 (let ((org-note-abort t))
18900 (funcall org-finish-function))))
18902 (defun org-return (&optional indent)
18903 "Goto next table row or insert a newline.
18904 Calls `org-table-next-row' or `newline', depending on context.
18905 See the individual commands for more information."
18906 (interactive)
18907 (cond
18908 ((or (bobp) (org-in-src-block-p))
18909 (if indent (newline-and-indent) (newline)))
18910 ((org-at-table-p)
18911 (org-table-justify-field-maybe)
18912 (call-interactively 'org-table-next-row))
18913 ;; when `newline-and-indent' is called within a list, make sure
18914 ;; text moved stays inside the item.
18915 ((and (org-in-item-p) indent)
18916 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18917 (progn
18918 (save-match-data (newline))
18919 (org-indent-line-to (length (match-string 0))))
18920 (let ((ind (org-get-indentation)))
18921 (newline)
18922 (if (org-looking-back org-list-end-re)
18923 (org-indent-line-function)
18924 (org-indent-line-to ind)))))
18925 ((and org-return-follows-link
18926 (let ((tprop (get-text-property (point) 'face)))
18927 (or (eq tprop 'org-link)
18928 (and (listp tprop) (memq 'org-link tprop)))))
18929 (call-interactively 'org-open-at-point))
18930 ((and (org-at-heading-p)
18931 (looking-at
18932 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18933 (org-show-entry)
18934 (end-of-line 1)
18935 (newline))
18936 (t (if indent (newline-and-indent) (newline)))))
18938 (defun org-return-indent ()
18939 "Goto next table row or insert a newline and indent.
18940 Calls `org-table-next-row' or `newline-and-indent', depending on
18941 context. See the individual commands for more information."
18942 (interactive)
18943 (org-return t))
18945 (defun org-ctrl-c-star ()
18946 "Compute table, or change heading status of lines.
18947 Calls `org-table-recalculate' or `org-toggle-heading',
18948 depending on context."
18949 (interactive)
18950 (cond
18951 ((org-at-table-p)
18952 (call-interactively 'org-table-recalculate))
18954 ;; Convert all lines in region to list items
18955 (call-interactively 'org-toggle-heading))))
18957 (defun org-ctrl-c-minus ()
18958 "Insert separator line in table or modify bullet status of line.
18959 Also turns a plain line or a region of lines into list items.
18960 Calls `org-table-insert-hline', `org-toggle-item', or
18961 `org-cycle-list-bullet', depending on context."
18962 (interactive)
18963 (cond
18964 ((org-at-table-p)
18965 (call-interactively 'org-table-insert-hline))
18966 ((org-region-active-p)
18967 (call-interactively 'org-toggle-item))
18968 ((org-in-item-p)
18969 (call-interactively 'org-cycle-list-bullet))
18971 (call-interactively 'org-toggle-item))))
18973 (defun org-toggle-item (arg)
18974 "Convert headings or normal lines to items, items to normal lines.
18975 If there is no active region, only the current line is considered.
18977 If the first non blank line in the region is an headline, convert
18978 all headlines to items, shifting text accordingly.
18980 If it is an item, convert all items to normal lines.
18982 If it is normal text, change region into an item. With a prefix
18983 argument ARG, change each line in region into an item."
18984 (interactive "P")
18985 (let ((shift-text
18986 (function
18987 ;; Shift text in current section to IND, from point to END.
18988 ;; The function leaves point to END line.
18989 (lambda (ind end)
18990 (let ((min-i 1000) (end (copy-marker end)))
18991 ;; First determine the minimum indentation (MIN-I) of
18992 ;; the text.
18993 (save-excursion
18994 (catch 'exit
18995 (while (< (point) end)
18996 (let ((i (org-get-indentation)))
18997 (cond
18998 ;; Skip blank lines and inline tasks.
18999 ((looking-at "^[ \t]*$"))
19000 ((looking-at org-outline-regexp-bol))
19001 ;; We can't find less than 0 indentation.
19002 ((zerop i) (throw 'exit (setq min-i 0)))
19003 ((< i min-i) (setq min-i i))))
19004 (forward-line))))
19005 ;; Then indent each line so that a line indented to
19006 ;; MIN-I becomes indented to IND. Ignore blank lines
19007 ;; and inline tasks in the process.
19008 (let ((delta (- ind min-i)))
19009 (while (< (point) end)
19010 (unless (or (looking-at "^[ \t]*$")
19011 (looking-at org-outline-regexp-bol))
19012 (org-indent-line-to (+ (org-get-indentation) delta)))
19013 (forward-line)))))))
19014 (skip-blanks
19015 (function
19016 ;; Return beginning of first non-blank line, starting from
19017 ;; line at POS.
19018 (lambda (pos)
19019 (save-excursion
19020 (goto-char pos)
19021 (skip-chars-forward " \r\t\n")
19022 (point-at-bol)))))
19023 beg end)
19024 ;; Determine boundaries of changes.
19025 (if (org-region-active-p)
19026 (setq beg (funcall skip-blanks (region-beginning))
19027 end (copy-marker (region-end)))
19028 (setq beg (funcall skip-blanks (point-at-bol))
19029 end (copy-marker (point-at-eol))))
19030 ;; Depending on the starting line, choose an action on the text
19031 ;; between BEG and END.
19032 (org-with-limited-levels
19033 (save-excursion
19034 (goto-char beg)
19035 (cond
19036 ;; Case 1. Start at an item: de-itemize. Note that it only
19037 ;; happens when a region is active: `org-ctrl-c-minus'
19038 ;; would call `org-cycle-list-bullet' otherwise.
19039 ((org-at-item-p)
19040 (while (< (point) end)
19041 (when (org-at-item-p)
19042 (skip-chars-forward " \t")
19043 (delete-region (point) (match-end 0)))
19044 (forward-line)))
19045 ;; Case 2. Start at an heading: convert to items.
19046 ((org-at-heading-p)
19047 (let* ((bul (org-list-bullet-string "-"))
19048 (bul-len (length bul))
19049 ;; Indentation of the first heading. It should be
19050 ;; relative to the indentation of its parent, if any.
19051 (start-ind (save-excursion
19052 (cond
19053 ((not org-adapt-indentation) 0)
19054 ((not (outline-previous-heading)) 0)
19055 (t (length (match-string 0))))))
19056 ;; Level of first heading. Further headings will be
19057 ;; compared to it to determine hierarchy in the list.
19058 (ref-level (org-reduced-level (org-outline-level))))
19059 (while (< (point) end)
19060 (let* ((level (org-reduced-level (org-outline-level)))
19061 (delta (max 0 (- level ref-level))))
19062 ;; If current headline is less indented than the first
19063 ;; one, set it as reference, in order to preserve
19064 ;; subtrees.
19065 (when (< level ref-level) (setq ref-level level))
19066 (replace-match bul t t)
19067 (org-indent-line-to (+ start-ind (* delta bul-len)))
19068 ;; Ensure all text down to END (or SECTION-END) belongs
19069 ;; to the newly created item.
19070 (let ((section-end (save-excursion
19071 (or (outline-next-heading) (point)))))
19072 (forward-line)
19073 (funcall shift-text
19074 (+ start-ind (* (1+ delta) bul-len))
19075 (min end section-end)))))))
19076 ;; Case 3. Normal line with ARG: turn each non-item line into
19077 ;; an item.
19078 (arg
19079 (while (< (point) end)
19080 (unless (or (org-at-heading-p) (org-at-item-p))
19081 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19082 (replace-match
19083 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19084 (forward-line)))
19085 ;; Case 4. Normal line without ARG: make the first line of
19086 ;; region an item, and shift indentation of others
19087 ;; lines to set them as item's body.
19088 (t (let* ((bul (org-list-bullet-string "-"))
19089 (bul-len (length bul))
19090 (ref-ind (org-get-indentation)))
19091 (skip-chars-forward " \t")
19092 (insert bul)
19093 (forward-line)
19094 (while (< (point) end)
19095 ;; Ensure that lines less indented than first one
19096 ;; still get included in item body.
19097 (funcall shift-text
19098 (+ ref-ind bul-len)
19099 (min end (save-excursion (or (outline-next-heading)
19100 (point)))))
19101 (forward-line)))))))))
19103 (defun org-toggle-heading (&optional nstars)
19104 "Convert headings to normal text, or items or text to headings.
19105 If there is no active region, only the current line is considered.
19107 With a \\[universal-argument] prefix, convert the whole list at
19108 point into heading.
19110 In a region:
19112 - If the first non blank line is an headline, remove the stars
19113 from all headlines in the region.
19115 - If it is a normal line turn each and every normal line (i.e. not an
19116 heading or an item) in the region into a heading.
19118 - If it is a plain list item, turn all plain list items into headings.
19120 When converting a line into a heading, the number of stars is chosen
19121 such that the lines become children of the current entry. However,
19122 when a prefix argument is given, its value determines the number of
19123 stars to add."
19124 (interactive "P")
19125 (let ((skip-blanks
19126 (function
19127 ;; Return beginning of first non-blank line, starting from
19128 ;; line at POS.
19129 (lambda (pos)
19130 (save-excursion
19131 (goto-char pos)
19132 (skip-chars-forward " \r\t\n")
19133 (point-at-bol)))))
19134 beg end)
19135 ;; Determine boundaries of changes. If a universal prefix has
19136 ;; been given, put the list in a region. If region ends at a bol,
19137 ;; do not consider the last line to be in the region.
19139 (when (and current-prefix-arg (org-at-item-p))
19140 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19141 (org-mark-list))
19143 (if (org-region-active-p)
19144 (setq beg (funcall skip-blanks (region-beginning))
19145 end (copy-marker (save-excursion
19146 (goto-char (region-end))
19147 (if (bolp) (point) (point-at-eol)))))
19148 (setq beg (funcall skip-blanks (point-at-bol))
19149 end (copy-marker (point-at-eol))))
19150 ;; Ensure inline tasks don't count as headings.
19151 (org-with-limited-levels
19152 (save-excursion
19153 (goto-char beg)
19154 (cond
19155 ;; Case 1. Started at an heading: de-star headings.
19156 ((org-at-heading-p)
19157 (while (< (point) end)
19158 (when (org-at-heading-p t)
19159 (looking-at org-outline-regexp) (replace-match ""))
19160 (forward-line)))
19161 ;; Case 2. Started at an item: change items into headlines.
19162 ;; One star will be added by `org-list-to-subtree'.
19163 ((org-at-item-p)
19164 (let* ((stars (make-string
19165 (if nstars
19166 ;; subtract the star that will be added again by
19167 ;; `org-list-to-subtree'
19168 (1- (prefix-numeric-value current-prefix-arg))
19169 (or (org-current-level) 0))
19170 ?*))
19171 (add-stars
19172 (cond (nstars "") ; stars from prefix only
19173 ((equal stars "") "") ; before first heading
19174 (org-odd-levels-only "*") ; inside heading, odd
19175 (t "")))) ; inside heading, oddeven
19176 (while (< (point) end)
19177 (when (org-at-item-p)
19178 ;; Pay attention to cases when region ends before list.
19179 (let* ((struct (org-list-struct))
19180 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19181 (save-restriction
19182 (narrow-to-region (point) list-end)
19183 (insert
19184 (org-list-to-subtree
19185 (org-list-parse-list t)
19186 '(:istart (concat stars add-stars (funcall get-stars depth))
19187 :icount (concat stars add-stars (funcall get-stars depth))))))))
19188 (forward-line))))
19189 ;; Case 3. Started at normal text: make every line an heading,
19190 ;; skipping headlines and items.
19191 (t (let* ((stars (make-string
19192 (if nstars
19193 (prefix-numeric-value current-prefix-arg)
19194 (or (org-current-level) 0))
19195 ?*))
19196 (add-stars
19197 (cond (nstars "") ; stars from prefix only
19198 ((equal stars "") "*") ; before first heading
19199 (org-odd-levels-only "**") ; inside heading, odd
19200 (t "*"))) ; inside heading, oddeven
19201 (rpl (concat stars add-stars " ")))
19202 (while (< (point) end)
19203 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
19204 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19205 (replace-match (concat rpl (match-string 2))))
19206 (forward-line)))))))))
19208 (defun org-meta-return (&optional arg)
19209 "Insert a new heading or wrap a region in a table.
19210 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19211 See the individual commands for more information."
19212 (interactive "P")
19213 (cond
19214 ((run-hook-with-args-until-success 'org-metareturn-hook))
19215 ((or (org-at-drawer-p) (org-at-property-p))
19216 (newline-and-indent))
19217 ((org-at-table-p)
19218 (call-interactively 'org-table-wrap-region))
19219 (t (call-interactively 'org-insert-heading))))
19221 ;;; Menu entries
19223 ;; Define the Org-mode menus
19224 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19225 '("Tbl"
19226 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19227 ["Next Field" org-cycle (org-at-table-p)]
19228 ["Previous Field" org-shifttab (org-at-table-p)]
19229 ["Next Row" org-return (org-at-table-p)]
19230 "--"
19231 ["Blank Field" org-table-blank-field (org-at-table-p)]
19232 ["Edit Field" org-table-edit-field (org-at-table-p)]
19233 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19234 "--"
19235 ("Column"
19236 ["Move Column Left" org-metaleft (org-at-table-p)]
19237 ["Move Column Right" org-metaright (org-at-table-p)]
19238 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19239 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19240 ("Row"
19241 ["Move Row Up" org-metaup (org-at-table-p)]
19242 ["Move Row Down" org-metadown (org-at-table-p)]
19243 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19244 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19245 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19246 "--"
19247 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19248 ("Rectangle"
19249 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19250 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19251 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19252 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19253 "--"
19254 ("Calculate"
19255 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19256 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19257 ["Edit Formulas" org-edit-special (org-at-table-p)]
19258 "--"
19259 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19260 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19261 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19262 "--"
19263 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19264 "--"
19265 ["Sum Column/Rectangle" org-table-sum
19266 (or (org-at-table-p) (org-region-active-p))]
19267 ["Which Column?" org-table-current-column (org-at-table-p)])
19268 ["Debug Formulas"
19269 org-table-toggle-formula-debugger
19270 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19271 ["Show Col/Row Numbers"
19272 org-table-toggle-coordinate-overlays
19273 :style toggle
19274 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19275 "--"
19276 ["Create" org-table-create (and (not (org-at-table-p))
19277 org-enable-table-editor)]
19278 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19279 ["Import from File" org-table-import (not (org-at-table-p))]
19280 ["Export to File" org-table-export (org-at-table-p)]
19281 "--"
19282 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19284 (easy-menu-define org-org-menu org-mode-map "Org menu"
19285 '("Org"
19286 ("Show/Hide"
19287 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19288 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19289 ["Sparse Tree..." org-sparse-tree t]
19290 ["Reveal Context" org-reveal t]
19291 ["Show All" show-all t]
19292 "--"
19293 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19294 "--"
19295 ["New Heading" org-insert-heading t]
19296 ("Navigate Headings"
19297 ["Up" outline-up-heading t]
19298 ["Next" outline-next-visible-heading t]
19299 ["Previous" outline-previous-visible-heading t]
19300 ["Next Same Level" outline-forward-same-level t]
19301 ["Previous Same Level" outline-backward-same-level t]
19302 "--"
19303 ["Jump" org-goto t])
19304 ("Edit Structure"
19305 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19306 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19307 "--"
19308 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19309 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19310 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19311 "--"
19312 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19313 "--"
19314 ["Copy visible text" org-copy-visible t]
19315 "--"
19316 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19317 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19318 ["Demote Heading" org-metaright (not (org-at-table-p))]
19319 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19320 "--"
19321 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19322 "--"
19323 ["Convert to odd levels" org-convert-to-odd-levels t]
19324 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19325 ("Editing"
19326 ["Emphasis..." org-emphasize t]
19327 ["Edit Source Example" org-edit-special t]
19328 "--"
19329 ["Footnote new/jump" org-footnote-action t]
19330 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19331 ("Archive"
19332 ["Archive (default method)" org-archive-subtree-default t]
19333 "--"
19334 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19335 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19336 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19338 "--"
19339 ("Hyperlinks"
19340 ["Store Link (Global)" org-store-link t]
19341 ["Find existing link to here" org-occur-link-in-agenda-files t]
19342 ["Insert Link" org-insert-link t]
19343 ["Follow Link" org-open-at-point t]
19344 "--"
19345 ["Next link" org-next-link t]
19346 ["Previous link" org-previous-link t]
19347 "--"
19348 ["Descriptive Links"
19349 org-toggle-link-display
19350 :style radio
19351 :selected org-descriptive-links
19353 ["Literal Links"
19354 org-toggle-link-display
19355 :style radio
19356 :selected (not org-descriptive-links)])
19357 "--"
19358 ("TODO Lists"
19359 ["TODO/DONE/-" org-todo t]
19360 ("Select keyword"
19361 ["Next keyword" org-shiftright (org-at-heading-p)]
19362 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19363 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19364 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19365 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19366 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19367 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19368 "--"
19369 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19370 :selected org-enforce-todo-dependencies :style toggle :active t]
19371 "Settings for tree at point"
19372 ["Do Children sequentially" org-toggle-ordered-property :style radio
19373 :selected (org-entry-get nil "ORDERED")
19374 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19375 ["Do Children parallel" org-toggle-ordered-property :style radio
19376 :selected (not (org-entry-get nil "ORDERED"))
19377 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19378 "--"
19379 ["Set Priority" org-priority t]
19380 ["Priority Up" org-shiftup t]
19381 ["Priority Down" org-shiftdown t]
19382 "--"
19383 ["Get news from all feeds" org-feed-update-all t]
19384 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19385 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19386 ("TAGS and Properties"
19387 ["Set Tags" org-set-tags-command t]
19388 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19389 "--"
19390 ["Set property" org-set-property t]
19391 ["Column view of properties" org-columns t]
19392 ["Insert Column View DBlock" org-insert-columns-dblock t])
19393 ("Dates and Scheduling"
19394 ["Timestamp" org-time-stamp t]
19395 ["Timestamp (inactive)" org-time-stamp-inactive t]
19396 ("Change Date"
19397 ["1 Day Later" org-shiftright t]
19398 ["1 Day Earlier" org-shiftleft t]
19399 ["1 ... Later" org-shiftup t]
19400 ["1 ... Earlier" org-shiftdown t])
19401 ["Compute Time Range" org-evaluate-time-range t]
19402 ["Schedule Item" org-schedule t]
19403 ["Deadline" org-deadline t]
19404 "--"
19405 ["Custom time format" org-toggle-time-stamp-overlays
19406 :style radio :selected org-display-custom-times]
19407 "--"
19408 ["Goto Calendar" org-goto-calendar t]
19409 ["Date from Calendar" org-date-from-calendar t]
19410 "--"
19411 ["Start/Restart Timer" org-timer-start t]
19412 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19413 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19414 ["Insert Timer String" org-timer t]
19415 ["Insert Timer Item" org-timer-item t])
19416 ("Logging work"
19417 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19418 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19419 ["Clock out" org-clock-out t]
19420 ["Clock cancel" org-clock-cancel t]
19421 "--"
19422 ["Mark as default task" org-clock-mark-default-task t]
19423 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19424 ["Goto running clock" org-clock-goto t]
19425 "--"
19426 ["Display times" org-clock-display t]
19427 ["Create clock table" org-clock-report t]
19428 "--"
19429 ["Record DONE time"
19430 (progn (setq org-log-done (not org-log-done))
19431 (message "Switching to %s will %s record a timestamp"
19432 (car org-done-keywords)
19433 (if org-log-done "automatically" "not")))
19434 :style toggle :selected org-log-done])
19435 "--"
19436 ["Agenda Command..." org-agenda t]
19437 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19438 ("File List for Agenda")
19439 ("Special views current file"
19440 ["TODO Tree" org-show-todo-tree t]
19441 ["Check Deadlines" org-check-deadlines t]
19442 ["Timeline" org-timeline t]
19443 ["Tags/Property tree" org-match-sparse-tree t])
19444 "--"
19445 ["Export/Publish..." org-export t]
19446 ("LaTeX"
19447 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19448 :selected org-cdlatex-mode]
19449 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19450 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19451 ["Modify math symbol" org-cdlatex-math-modify
19452 (org-inside-LaTeX-fragment-p)]
19453 ["Insert citation" org-reftex-citation t]
19454 "--"
19455 ["Template for BEAMER" (progn (require 'org-beamer)
19456 (org-insert-beamer-options-template)) t])
19457 "--"
19458 ("MobileOrg"
19459 ["Push Files and Views" org-mobile-push t]
19460 ["Get Captured and Flagged" org-mobile-pull t]
19461 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19462 "--"
19463 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19464 "--"
19465 ("Documentation"
19466 ["Show Version" org-version t]
19467 ["Info Documentation" org-info t])
19468 ("Customize"
19469 ["Browse Org Group" org-customize t]
19470 "--"
19471 ["Expand This Menu" org-create-customize-menu
19472 (fboundp 'customize-menu-create)])
19473 ["Send bug report" org-submit-bug-report t]
19474 "--"
19475 ("Refresh/Reload"
19476 ["Refresh setup current buffer" org-mode-restart t]
19477 ["Reload Org (after update)" org-reload t]
19478 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19481 (defun org-info (&optional node)
19482 "Read documentation for Org-mode in the info system.
19483 With optional NODE, go directly to that node."
19484 (interactive)
19485 (info (format "(org)%s" (or node ""))))
19487 ;;;###autoload
19488 (defun org-submit-bug-report ()
19489 "Submit a bug report on Org-mode via mail.
19491 Don't hesitate to report any problems or inaccurate documentation.
19493 If you don't have setup sending mail from (X)Emacs, please copy the
19494 output buffer into your mail program, as it gives us important
19495 information about your Org-mode version and configuration."
19496 (interactive)
19497 (require 'reporter)
19498 (org-load-modules-maybe)
19499 (org-require-autoloaded-modules)
19500 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19501 (reporter-submit-bug-report
19502 "emacs-orgmode@gnu.org"
19503 (org-version)
19504 (let (list)
19505 (save-window-excursion
19506 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19507 (delete-other-windows)
19508 (erase-buffer)
19509 (insert "You are about to submit a bug report to the Org-mode mailing list.
19511 We would like to add your full Org-mode and Outline configuration to the
19512 bug report. This greatly simplifies the work of the maintainer and
19513 other experts on the mailing list.
19515 HOWEVER, some variables you have customized may contain private
19516 information. The names of customers, colleagues, or friends, might
19517 appear in the form of file names, tags, todo states, or search strings.
19518 If you answer yes to the prompt, you might want to check and remove
19519 such private information before sending the email.")
19520 (add-text-properties (point-min) (point-max) '(face org-warning))
19521 (when (yes-or-no-p "Include your Org-mode configuration ")
19522 (mapatoms
19523 (lambda (v)
19524 (and (boundp v)
19525 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19526 (or (and (symbol-value v)
19527 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19528 (and
19529 (get v 'custom-type) (get v 'standard-value)
19530 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19531 (push v list)))))
19532 (kill-buffer (get-buffer "*Warn about privacy*"))
19533 list))
19534 nil nil
19535 "Remember to cover the basics, that is, what you expected to happen and
19536 what in fact did happen. You don't know how to make a good report? See
19538 http://orgmode.org/manual/Feedback.html#Feedback
19540 Your bug report will be posted to the Org-mode mailing list.
19541 ------------------------------------------------------------------------")
19542 (save-excursion
19543 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19544 (replace-match "\\1Bug: \\3 [\\2]")))))
19547 (defun org-install-agenda-files-menu ()
19548 (let ((bl (buffer-list)))
19549 (save-excursion
19550 (while bl
19551 (set-buffer (pop bl))
19552 (if (derived-mode-p 'org-mode) (setq bl nil)))
19553 (when (derived-mode-p 'org-mode)
19554 (easy-menu-change
19555 '("Org") "File List for Agenda"
19556 (append
19557 (list
19558 ["Edit File List" (org-edit-agenda-file-list) t]
19559 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19560 ["Remove Current File from List" org-remove-file t]
19561 ["Cycle through agenda files" org-cycle-agenda-files t]
19562 ["Occur in all agenda files" org-occur-in-agenda-files t]
19563 "--")
19564 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19566 ;;;; Documentation
19568 ;;;###autoload
19569 (defun org-require-autoloaded-modules ()
19570 (interactive)
19571 (mapc 'require
19572 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19573 org-docbook org-exp org-html org-icalendar
19574 org-id org-latex
19575 org-publish org-remember org-table
19576 org-timer org-xoxo)))
19578 ;;;###autoload
19579 (defun org-reload (&optional uncompiled)
19580 "Reload all org lisp files.
19581 With prefix arg UNCOMPILED, load the uncompiled versions."
19582 (interactive "P")
19583 (require 'find-func)
19584 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19585 (dir-org (file-name-directory (org-find-library-dir "org")))
19586 (dir-org-contrib (ignore-errors
19587 (file-name-directory
19588 (org-find-library-dir "org-contribdir"))))
19589 (babel-files
19590 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19591 (append (list nil "comint" "eval" "exp" "keys"
19592 "lob" "ref" "table" "tangle")
19593 (delq nil
19594 (mapcar
19595 (lambda (lang)
19596 (when (cdr lang) (symbol-name (car lang))))
19597 org-babel-load-languages)))))
19598 (files
19599 (append (directory-files dir-org t file-re)
19600 babel-files
19601 (and dir-org-contrib
19602 (directory-files dir-org-contrib t file-re))))
19603 (remove-re (concat (if (featurep 'xemacs)
19604 "org-colview" "org-colview-xemacs")
19605 "\\'")))
19606 (setq files (mapcar 'file-name-sans-extension files))
19607 (setq files (mapcar
19608 (lambda (x) (if (string-match remove-re x) nil x))
19609 files))
19610 (setq files (delq nil files))
19611 (mapc
19612 (lambda (f)
19613 (when (featurep (intern (file-name-nondirectory f)))
19614 (if (and (not uncompiled)
19615 (file-exists-p (concat f ".elc")))
19616 (load (concat f ".elc") nil nil t)
19617 (load (concat f ".el") nil nil t))))
19618 files))
19619 (org-version))
19621 ;;;###autoload
19622 (defun org-customize ()
19623 "Call the customize function with org as argument."
19624 (interactive)
19625 (org-load-modules-maybe)
19626 (org-require-autoloaded-modules)
19627 (customize-browse 'org))
19629 (defun org-create-customize-menu ()
19630 "Create a full customization menu for Org-mode, insert it into the menu."
19631 (interactive)
19632 (org-load-modules-maybe)
19633 (org-require-autoloaded-modules)
19634 (if (fboundp 'customize-menu-create)
19635 (progn
19636 (easy-menu-change
19637 '("Org") "Customize"
19638 `(["Browse Org group" org-customize t]
19639 "--"
19640 ,(customize-menu-create 'org)
19641 ["Set" Custom-set t]
19642 ["Save" Custom-save t]
19643 ["Reset to Current" Custom-reset-current t]
19644 ["Reset to Saved" Custom-reset-saved t]
19645 ["Reset to Standard Settings" Custom-reset-standard t]))
19646 (message "\"Org\"-menu now contains full customization menu"))
19647 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19649 ;;;; Miscellaneous stuff
19651 ;;; Generally useful functions
19653 (defun org-get-at-bol (property)
19654 "Get text property PROPERTY at beginning of line."
19655 (get-text-property (point-at-bol) property))
19657 (defun org-find-text-property-in-string (prop s)
19658 "Return the first non-nil value of property PROP in string S."
19659 (or (get-text-property 0 prop s)
19660 (get-text-property (or (next-single-property-change 0 prop s) 0)
19661 prop s)))
19663 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19664 "Display the given MESSAGE as a warning."
19665 (if (fboundp 'display-warning)
19666 (display-warning 'org message
19667 (if (featurep 'xemacs) 'warning :warning))
19668 (let ((buf (get-buffer-create "*Org warnings*")))
19669 (with-current-buffer buf
19670 (goto-char (point-max))
19671 (insert "Warning (Org): " message)
19672 (unless (bolp)
19673 (newline)))
19674 (display-buffer buf)
19675 (sit-for 0))))
19677 (defun org-eval (form)
19678 "Eval FORM and return result."
19679 (condition-case error
19680 (eval form)
19681 (error (format "%%![Error: %s]" error))))
19683 (defun org-in-clocktable-p ()
19684 "Check if the cursor is in a clocktable."
19685 (let ((pos (point)) start)
19686 (save-excursion
19687 (end-of-line 1)
19688 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19689 (setq start (match-beginning 0))
19690 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19691 (>= (match-end 0) pos)
19692 start))))
19694 (defun org-in-commented-line ()
19695 "Is point in a line starting with `#'?"
19696 (equal (char-after (point-at-bol)) ?#))
19698 (defun org-in-indented-comment-line ()
19699 "Is point in a line starting with `#' after some white space?"
19700 (save-excursion
19701 (save-match-data
19702 (goto-char (point-at-bol))
19703 (looking-at "[ \t]*#"))))
19705 (defun org-in-verbatim-emphasis ()
19706 (save-match-data
19707 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19709 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19710 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19711 (if (and marker (marker-buffer marker)
19712 (buffer-live-p (marker-buffer marker)))
19713 (progn
19714 (org-pop-to-buffer-same-window (marker-buffer marker))
19715 (if (or (> marker (point-max)) (< marker (point-min)))
19716 (widen))
19717 (goto-char marker)
19718 (org-show-context 'org-goto))
19719 (if bookmark
19720 (bookmark-jump bookmark)
19721 (error "Cannot find location"))))
19723 (defun org-quote-csv-field (s)
19724 "Quote field for inclusion in CSV material."
19725 (if (string-match "[\",]" s)
19726 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19729 (defun org-force-self-insert (N)
19730 "Needed to enforce self-insert under remapping."
19731 (interactive "p")
19732 (self-insert-command N))
19734 (defun org-string-width (s)
19735 "Compute width of string, ignoring invisible characters.
19736 This ignores character with invisibility property `org-link', and also
19737 characters with property `org-cwidth', because these will become invisible
19738 upon the next fontification round."
19739 (let (b l)
19740 (when (or (eq t buffer-invisibility-spec)
19741 (assq 'org-link buffer-invisibility-spec))
19742 (while (setq b (text-property-any 0 (length s)
19743 'invisible 'org-link s))
19744 (setq s (concat (substring s 0 b)
19745 (substring s (or (next-single-property-change
19746 b 'invisible s) (length s)))))))
19747 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19748 (setq s (concat (substring s 0 b)
19749 (substring s (or (next-single-property-change
19750 b 'org-cwidth s) (length s))))))
19751 (setq l (string-width s) b -1)
19752 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19753 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19756 (defun org-shorten-string (s maxlength)
19757 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19758 If the string is shorter or has length MAXLENGTH, just return the
19759 original string. If it is longer, the functions finds a space in the
19760 string, breaks this string off at that locations and adds three dots
19761 as ellipsis. Including the ellipsis, the string will not be longer
19762 than MAXLENGTH. If finding a good breaking point in the string does
19763 not work, the string is just chopped off in the middle of a word
19764 if necessary."
19765 (if (<= (length s) maxlength)
19767 (let* ((n (max (- maxlength 4) 1))
19768 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19769 (if (string-match re s)
19770 (concat (match-string 1 s) "...")
19771 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19773 (defun org-get-indentation (&optional line)
19774 "Get the indentation of the current line, interpreting tabs.
19775 When LINE is given, assume it represents a line and compute its indentation."
19776 (if line
19777 (if (string-match "^ *" (org-remove-tabs line))
19778 (match-end 0))
19779 (save-excursion
19780 (beginning-of-line 1)
19781 (skip-chars-forward " \t")
19782 (current-column))))
19784 (defun org-get-string-indentation (s)
19785 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19786 (let ((n -1) (i 0) (w tab-width) c)
19787 (catch 'exit
19788 (while (< (setq n (1+ n)) (length s))
19789 (setq c (aref s n))
19790 (cond ((= c ?\ ) (setq i (1+ i)))
19791 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19792 (t (throw 'exit t)))))
19795 (defun org-remove-tabs (s &optional width)
19796 "Replace tabulators in S with spaces.
19797 Assumes that s is a single line, starting in column 0."
19798 (setq width (or width tab-width))
19799 (while (string-match "\t" s)
19800 (setq s (replace-match
19801 (make-string
19802 (- (* width (/ (+ (match-beginning 0) width) width))
19803 (match-beginning 0)) ?\ )
19804 t t s)))
19807 (defun org-fix-indentation (line ind)
19808 "Fix indentation in LINE.
19809 IND is a cons cell with target and minimum indentation.
19810 If the current indentation in LINE is smaller than the minimum,
19811 leave it alone. If it is larger than ind, set it to the target."
19812 (let* ((l (org-remove-tabs line))
19813 (i (org-get-indentation l))
19814 (i1 (car ind)) (i2 (cdr ind)))
19815 (if (>= i i2) (setq l (substring line i2)))
19816 (if (> i1 0)
19817 (concat (make-string i1 ?\ ) l)
19818 l)))
19820 (defun org-remove-indentation (code &optional n)
19821 "Remove the maximum common indentation from the lines in CODE.
19822 N may optionally be the number of spaces to remove."
19823 (with-temp-buffer
19824 (insert code)
19825 (org-do-remove-indentation n)
19826 (buffer-string)))
19828 (defun org-do-remove-indentation (&optional n)
19829 "Remove the maximum common indentation from the buffer."
19830 (untabify (point-min) (point-max))
19831 (let ((min 10000) re)
19832 (if n
19833 (setq min n)
19834 (goto-char (point-min))
19835 (while (re-search-forward "^ *[^ \n]" nil t)
19836 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19837 (unless (or (= min 0) (= min 10000))
19838 (setq re (format "^ \\{%d\\}" min))
19839 (goto-char (point-min))
19840 (while (re-search-forward re nil t)
19841 (replace-match "")
19842 (end-of-line 1))
19843 min)))
19845 (defun org-fill-template (template alist)
19846 "Find each %key of ALIST in TEMPLATE and replace it."
19847 (let ((case-fold-search nil)
19848 entry key value)
19849 (setq alist (sort (copy-sequence alist)
19850 (lambda (a b) (< (length (car a)) (length (car b))))))
19851 (while (setq entry (pop alist))
19852 (setq template
19853 (replace-regexp-in-string
19854 (concat "%" (regexp-quote (car entry)))
19855 (cdr entry) template t t)))
19856 template))
19858 (defun org-base-buffer (buffer)
19859 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19860 (if (not buffer)
19861 buffer
19862 (or (buffer-base-buffer buffer)
19863 buffer)))
19865 (defun org-trim (s)
19866 "Remove whitespace at beginning and end of string."
19867 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19868 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19871 (defun org-wrap (string &optional width lines)
19872 "Wrap string to either a number of lines, or a width in characters.
19873 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19874 that costs. If there is a word longer than WIDTH, the text is actually
19875 wrapped to the length of that word.
19876 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19877 many lines, whatever width that takes.
19878 The return value is a list of lines, without newlines at the end."
19879 (let* ((words (org-split-string string "[ \t\n]+"))
19880 (maxword (apply 'max (mapcar 'org-string-width words)))
19881 w ll)
19882 (cond (width
19883 (org-do-wrap words (max maxword width)))
19884 (lines
19885 (setq w maxword)
19886 (setq ll (org-do-wrap words maxword))
19887 (if (<= (length ll) lines)
19889 (setq ll words)
19890 (while (> (length ll) lines)
19891 (setq w (1+ w))
19892 (setq ll (org-do-wrap words w)))
19893 ll))
19894 (t (error "Cannot wrap this")))))
19896 (defun org-do-wrap (words width)
19897 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19898 (let (lines line)
19899 (while words
19900 (setq line (pop words))
19901 (while (and words (< (+ (length line) (length (car words))) width))
19902 (setq line (concat line " " (pop words))))
19903 (setq lines (push line lines)))
19904 (nreverse lines)))
19906 (defun org-split-string (string &optional separators)
19907 "Splits STRING into substrings at SEPARATORS.
19908 No empty strings are returned if there are matches at the beginning
19909 and end of string."
19910 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19911 (start 0)
19912 notfirst
19913 (list nil))
19914 (while (and (string-match rexp string
19915 (if (and notfirst
19916 (= start (match-beginning 0))
19917 (< start (length string)))
19918 (1+ start) start))
19919 (< (match-beginning 0) (length string)))
19920 (setq notfirst t)
19921 (or (eq (match-beginning 0) 0)
19922 (and (eq (match-beginning 0) (match-end 0))
19923 (eq (match-beginning 0) start))
19924 (setq list
19925 (cons (substring string start (match-beginning 0))
19926 list)))
19927 (setq start (match-end 0)))
19928 (or (eq start (length string))
19929 (setq list
19930 (cons (substring string start)
19931 list)))
19932 (nreverse list)))
19934 (defun org-quote-vert (s)
19935 "Replace \"|\" with \"\\vert\"."
19936 (while (string-match "|" s)
19937 (setq s (replace-match "\\vert" t t s)))
19940 (defun org-uuidgen-p (s)
19941 "Is S an ID created by UUIDGEN?"
19942 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19944 (defun org-in-src-block-p nil
19945 "Whether point is in a code source block."
19946 (let (ov)
19947 (when (setq ov (overlays-at (point)))
19948 (memq 'org-block-background
19949 (overlay-properties
19950 (car ov))))))
19952 (defun org-context ()
19953 "Return a list of contexts of the current cursor position.
19954 If several contexts apply, all are returned.
19955 Each context entry is a list with a symbol naming the context, and
19956 two positions indicating start and end of the context. Possible
19957 contexts are:
19959 :headline anywhere in a headline
19960 :headline-stars on the leading stars in a headline
19961 :todo-keyword on a TODO keyword (including DONE) in a headline
19962 :tags on the TAGS in a headline
19963 :priority on the priority cookie in a headline
19964 :item on the first line of a plain list item
19965 :item-bullet on the bullet/number of a plain list item
19966 :checkbox on the checkbox in a plain list item
19967 :table in an org-mode table
19968 :table-special on a special filed in a table
19969 :table-table in a table.el table
19970 :clocktable in a clocktable
19971 :src-block in a source block
19972 :link on a hyperlink
19973 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19974 :target on a <<target>>
19975 :radio-target on a <<<radio-target>>>
19976 :latex-fragment on a LaTeX fragment
19977 :latex-preview on a LaTeX fragment with overlaid preview image
19979 This function expects the position to be visible because it uses font-lock
19980 faces as a help to recognize the following contexts: :table-special, :link,
19981 and :keyword."
19982 (let* ((f (get-text-property (point) 'face))
19983 (faces (if (listp f) f (list f)))
19984 (case-fold-search t)
19985 (p (point)) clist o)
19986 ;; First the large context
19987 (cond
19988 ((org-at-heading-p t)
19989 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19990 (when (progn
19991 (beginning-of-line 1)
19992 (looking-at org-todo-line-tags-regexp))
19993 (push (org-point-in-group p 1 :headline-stars) clist)
19994 (push (org-point-in-group p 2 :todo-keyword) clist)
19995 (push (org-point-in-group p 4 :tags) clist))
19996 (goto-char p)
19997 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19998 (if (looking-at "\\[#[A-Z0-9]\\]")
19999 (push (org-point-in-group p 0 :priority) clist)))
20001 ((org-at-item-p)
20002 (push (org-point-in-group p 2 :item-bullet) clist)
20003 (push (list :item (point-at-bol)
20004 (save-excursion (org-end-of-item) (point)))
20005 clist)
20006 (and (org-at-item-checkbox-p)
20007 (push (org-point-in-group p 0 :checkbox) clist)))
20009 ((org-at-table-p)
20010 (push (list :table (org-table-begin) (org-table-end)) clist)
20011 (if (memq 'org-formula faces)
20012 (push (list :table-special
20013 (previous-single-property-change p 'face)
20014 (next-single-property-change p 'face)) clist)))
20015 ((org-at-table-p 'any)
20016 (push (list :table-table) clist)))
20017 (goto-char p)
20019 ;; New the "medium" contexts: clocktables, source blocks
20020 (cond ((org-in-clocktable-p)
20021 (push (list :clocktable
20022 (and (or (looking-at "#\\+BEGIN: clocktable")
20023 (search-backward "#+BEGIN: clocktable" nil t))
20024 (match-beginning 0))
20025 (and (re-search-forward "#\\+END:?" nil t)
20026 (match-end 0))) clist))
20027 ((org-in-src-block-p)
20028 (push (list :src-block
20029 (and (or (looking-at "#\\+BEGIN_SRC")
20030 (search-backward "#+BEGIN_SRC" nil t))
20031 (match-beginning 0))
20032 (and (search-forward "#+END_SRC" nil t)
20033 (match-beginning 0))) clist)))
20034 (goto-char p)
20036 ;; Now the small context
20037 (cond
20038 ((org-at-timestamp-p)
20039 (push (org-point-in-group p 0 :timestamp) clist))
20040 ((memq 'org-link faces)
20041 (push (list :link
20042 (previous-single-property-change p 'face)
20043 (next-single-property-change p 'face)) clist))
20044 ((memq 'org-special-keyword faces)
20045 (push (list :keyword
20046 (previous-single-property-change p 'face)
20047 (next-single-property-change p 'face)) clist))
20048 ((org-at-target-p)
20049 (push (org-point-in-group p 0 :target) clist)
20050 (goto-char (1- (match-beginning 0)))
20051 (if (looking-at org-radio-target-regexp)
20052 (push (org-point-in-group p 0 :radio-target) clist))
20053 (goto-char p))
20054 ((setq o (car (delq nil
20055 (mapcar
20056 (lambda (x)
20057 (if (memq x org-latex-fragment-image-overlays) x))
20058 (overlays-at (point))))))
20059 (push (list :latex-fragment
20060 (overlay-start o) (overlay-end o)) clist)
20061 (push (list :latex-preview
20062 (overlay-start o) (overlay-end o)) clist))
20063 ((org-inside-LaTeX-fragment-p)
20064 ;; FIXME: positions wrong.
20065 (push (list :latex-fragment (point) (point)) clist)))
20067 (setq clist (nreverse (delq nil clist)))
20068 clist))
20070 ;; FIXME: Compare with at-regexp-p Do we need both?
20071 (defun org-in-regexp (re &optional nlines visually)
20072 "Check if point is inside a match of regexp.
20073 Normally only the current line is checked, but you can include NLINES extra
20074 lines both before and after point into the search.
20075 If VISUALLY is set, require that the cursor is not after the match but
20076 really on, so that the block visually is on the match."
20077 (catch 'exit
20078 (let ((pos (point))
20079 (eol (point-at-eol (+ 1 (or nlines 0))))
20080 (inc (if visually 1 0)))
20081 (save-excursion
20082 (beginning-of-line (- 1 (or nlines 0)))
20083 (while (re-search-forward re eol t)
20084 (if (and (<= (match-beginning 0) pos)
20085 (>= (+ inc (match-end 0)) pos))
20086 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20088 (defun org-at-regexp-p (regexp)
20089 "Is point inside a match of REGEXP in the current line?"
20090 (catch 'exit
20091 (save-excursion
20092 (let ((pos (point)) (end (point-at-eol)))
20093 (beginning-of-line 1)
20094 (while (re-search-forward regexp end t)
20095 (if (and (<= (match-beginning 0) pos)
20096 (>= (match-end 0) pos))
20097 (throw 'exit t)))
20098 nil))))
20100 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20101 "Non-nil when point is between matches of START-RE and END-RE.
20103 Also return a non-nil value when point is on one of the matches.
20105 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20106 buffer positions. Default values are the positions of headlines
20107 surrounding the point.
20109 The functions returns a cons cell whose car (resp. cdr) is the
20110 position before START-RE (resp. after END-RE)."
20111 (save-match-data
20112 (let ((pos (point))
20113 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20114 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20115 beg end)
20116 (save-excursion
20117 ;; Point is on a block when on START-RE or if START-RE can be
20118 ;; found before it...
20119 (and (or (org-at-regexp-p start-re)
20120 (re-search-backward start-re limit-up t))
20121 (setq beg (match-beginning 0))
20122 ;; ... and END-RE after it...
20123 (goto-char (match-end 0))
20124 (re-search-forward end-re limit-down t)
20125 (> (setq end (match-end 0)) pos)
20126 ;; ... without another START-RE in-between.
20127 (goto-char (match-beginning 0))
20128 (not (re-search-backward start-re (1+ beg) t))
20129 ;; Return value.
20130 (cons beg end))))))
20132 (defun org-in-block-p (names)
20133 "Non-nil when point belongs to a block whose name belongs to NAMES.
20135 NAMES is a list of strings containing names of blocks.
20137 Return first block name matched, or nil. Beware that in case of
20138 nested blocks, the returned name may not belong to the closest
20139 block from point."
20140 (save-match-data
20141 (catch 'exit
20142 (let ((case-fold-search t)
20143 (lim-up (save-excursion (outline-previous-heading)))
20144 (lim-down (save-excursion (outline-next-heading))))
20145 (mapc (lambda (name)
20146 (let ((n (regexp-quote name)))
20147 (when (org-between-regexps-p
20148 (concat "^[ \t]*#\\+begin_" n)
20149 (concat "^[ \t]*#\\+end_" n)
20150 lim-up lim-down)
20151 (throw 'exit n))))
20152 names))
20153 nil)))
20155 (defun org-occur-in-agenda-files (regexp &optional nlines)
20156 "Call `multi-occur' with buffers for all agenda files."
20157 (interactive "sOrg-files matching: \np")
20158 (let* ((files (org-agenda-files))
20159 (tnames (mapcar 'file-truename files))
20160 (extra org-agenda-text-search-extra-files)
20162 (when (eq (car extra) 'agenda-archives)
20163 (setq extra (cdr extra))
20164 (setq files (org-add-archive-files files)))
20165 (while (setq f (pop extra))
20166 (unless (member (file-truename f) tnames)
20167 (add-to-list 'files f 'append)
20168 (add-to-list 'tnames (file-truename f) 'append)))
20169 (multi-occur
20170 (mapcar (lambda (x)
20171 (with-current-buffer
20172 (or (get-file-buffer x) (find-file-noselect x))
20173 (widen)
20174 (current-buffer)))
20175 files)
20176 regexp)))
20178 (if (boundp 'occur-mode-find-occurrence-hook)
20179 ;; Emacs 23
20180 (add-hook 'occur-mode-find-occurrence-hook
20181 (lambda ()
20182 (when (derived-mode-p 'org-mode)
20183 (org-reveal))))
20184 ;; Emacs 22
20185 (defadvice occur-mode-goto-occurrence
20186 (after org-occur-reveal activate)
20187 (and (derived-mode-p 'org-mode) (org-reveal)))
20188 (defadvice occur-mode-goto-occurrence-other-window
20189 (after org-occur-reveal activate)
20190 (and (derived-mode-p 'org-mode) (org-reveal)))
20191 (defadvice occur-mode-display-occurrence
20192 (after org-occur-reveal activate)
20193 (when (derived-mode-p 'org-mode)
20194 (let ((pos (occur-mode-find-occurrence)))
20195 (with-current-buffer (marker-buffer pos)
20196 (save-excursion
20197 (goto-char pos)
20198 (org-reveal)))))))
20200 (defun org-occur-link-in-agenda-files ()
20201 "Create a link and search for it in the agendas.
20202 The link is not stored in `org-stored-links', it is just created
20203 for the search purpose."
20204 (interactive)
20205 (let ((link (condition-case nil
20206 (org-store-link nil)
20207 (error "Unable to create a link to here"))))
20208 (org-occur-in-agenda-files (regexp-quote link))))
20210 (defun org-uniquify (list)
20211 "Remove duplicate elements from LIST."
20212 (let (res)
20213 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20214 res))
20216 (defun org-delete-all (elts list)
20217 "Remove all elements in ELTS from LIST."
20218 (while elts
20219 (setq list (delete (pop elts) list)))
20220 list)
20222 (defun org-count (cl-item cl-seq)
20223 "Count the number of occurrences of ITEM in SEQ.
20224 Taken from `count' in cl-seq.el with all keyword arguments removed."
20225 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20226 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20227 (while (< cl-start cl-end)
20228 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20229 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20230 (setq cl-start (1+ cl-start)))
20231 cl-count))
20233 (defun org-remove-if (predicate seq)
20234 "Remove everything from SEQ that fulfills PREDICATE."
20235 (let (res e)
20236 (while seq
20237 (setq e (pop seq))
20238 (if (not (funcall predicate e)) (push e res)))
20239 (nreverse res)))
20241 (defun org-remove-if-not (predicate seq)
20242 "Remove everything from SEQ that does not fulfill PREDICATE."
20243 (let (res e)
20244 (while seq
20245 (setq e (pop seq))
20246 (if (funcall predicate e) (push e res)))
20247 (nreverse res)))
20249 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20250 "Reduce two-argument FUNCTION across SEQ.
20251 Taken from `reduce' in cl-seq.el with all keyword arguments but
20252 \":initial-value\" removed."
20253 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20254 (cadr (memq :initial-value cl-keys)))
20255 (cl-seq (pop cl-seq))
20256 (t (funcall cl-func)))))
20257 (while cl-seq
20258 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20259 cl-accum))
20261 (defun org-back-over-empty-lines ()
20262 "Move backwards over whitespace, to the beginning of the first empty line.
20263 Returns the number of empty lines passed."
20264 (let ((pos (point)))
20265 (if (cdr (assoc 'heading org-blank-before-new-entry))
20266 (skip-chars-backward " \t\n\r")
20267 (unless (eobp)
20268 (forward-line -1)))
20269 (beginning-of-line 2)
20270 (goto-char (min (point) pos))
20271 (count-lines (point) pos)))
20273 (defun org-skip-whitespace ()
20274 (skip-chars-forward " \t\n\r"))
20276 (defun org-point-in-group (point group &optional context)
20277 "Check if POINT is in match-group GROUP.
20278 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20279 match. If the match group does not exist or point is not inside it,
20280 return nil."
20281 (and (match-beginning group)
20282 (>= point (match-beginning group))
20283 (<= point (match-end group))
20284 (if context
20285 (list context (match-beginning group) (match-end group))
20286 t)))
20288 (defun org-switch-to-buffer-other-window (&rest args)
20289 "Switch to buffer in a second window on the current frame.
20290 In particular, do not allow pop-up frames.
20291 Returns the newly created buffer."
20292 (let (pop-up-frames special-display-buffer-names special-display-regexps
20293 special-display-function)
20294 (apply 'switch-to-buffer-other-window args)))
20296 (defun org-combine-plists (&rest plists)
20297 "Create a single property list from all plists in PLISTS.
20298 The process starts by copying the first list, and then setting properties
20299 from the other lists. Settings in the last list are the most significant
20300 ones and overrule settings in the other lists."
20301 (let ((rtn (copy-sequence (pop plists)))
20302 p v ls)
20303 (while plists
20304 (setq ls (pop plists))
20305 (while ls
20306 (setq p (pop ls) v (pop ls))
20307 (setq rtn (plist-put rtn p v))))
20308 rtn))
20310 (defun org-move-line-down (arg)
20311 "Move the current line down. With prefix argument, move it past ARG lines."
20312 (interactive "p")
20313 (let ((col (current-column))
20314 beg end pos)
20315 (beginning-of-line 1) (setq beg (point))
20316 (beginning-of-line 2) (setq end (point))
20317 (beginning-of-line (+ 1 arg))
20318 (setq pos (move-marker (make-marker) (point)))
20319 (insert (delete-and-extract-region beg end))
20320 (goto-char pos)
20321 (org-move-to-column col)))
20323 (defun org-move-line-up (arg)
20324 "Move the current line up. With prefix argument, move it past ARG lines."
20325 (interactive "p")
20326 (let ((col (current-column))
20327 beg end pos)
20328 (beginning-of-line 1) (setq beg (point))
20329 (beginning-of-line 2) (setq end (point))
20330 (beginning-of-line (- arg))
20331 (setq pos (move-marker (make-marker) (point)))
20332 (insert (delete-and-extract-region beg end))
20333 (goto-char pos)
20334 (org-move-to-column col)))
20336 (defun org-replace-escapes (string table)
20337 "Replace %-escapes in STRING with values in TABLE.
20338 TABLE is an association list with keys like \"%a\" and string values.
20339 The sequences in STRING may contain normal field width and padding information,
20340 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20341 so values can contain further %-escapes if they are define later in TABLE."
20342 (let ((tbl (copy-alist table))
20343 (case-fold-search nil)
20344 (pchg 0)
20345 e re rpl)
20346 (while (setq e (pop tbl))
20347 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20348 (when (and (cdr e) (string-match re (cdr e)))
20349 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20350 (safe "SREF"))
20351 (add-text-properties 0 3 (list 'sref sref) safe)
20352 (setcdr e (replace-match safe t t (cdr e)))))
20353 (while (string-match re string)
20354 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20355 (cdr e)))
20356 (setq string (replace-match rpl t t string))))
20357 (while (setq pchg (next-property-change pchg string))
20358 (let ((sref (get-text-property pchg 'sref string)))
20359 (when (and sref (string-match "SREF" string pchg))
20360 (setq string (replace-match sref t t string)))))
20361 string))
20363 (defun org-sublist (list start end)
20364 "Return a section of LIST, from START to END.
20365 Counting starts at 1."
20366 (let (rtn (c start))
20367 (setq list (nthcdr (1- start) list))
20368 (while (and list (<= c end))
20369 (push (pop list) rtn)
20370 (setq c (1+ c)))
20371 (nreverse rtn)))
20373 (defun org-find-base-buffer-visiting (file)
20374 "Like `find-buffer-visiting' but always return the base buffer and
20375 not an indirect buffer."
20376 (let ((buf (or (get-file-buffer file)
20377 (find-buffer-visiting file))))
20378 (if buf
20379 (or (buffer-base-buffer buf) buf)
20380 nil)))
20382 (defun org-image-file-name-regexp (&optional extensions)
20383 "Return regexp matching the file names of images.
20384 If EXTENSIONS is given, only match these."
20385 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20386 (image-file-name-regexp)
20387 (let ((image-file-name-extensions
20388 (or extensions
20389 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20390 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20391 (concat "\\."
20392 (regexp-opt (nconc (mapcar 'upcase
20393 image-file-name-extensions)
20394 image-file-name-extensions)
20396 "\\'"))))
20398 (defun org-file-image-p (file &optional extensions)
20399 "Return non-nil if FILE is an image."
20400 (save-match-data
20401 (string-match (org-image-file-name-regexp extensions) file)))
20403 (defun org-get-cursor-date ()
20404 "Return the date at cursor in as a time.
20405 This works in the calendar and in the agenda, anywhere else it just
20406 returns the current time."
20407 (let (date day defd)
20408 (cond
20409 ((eq major-mode 'calendar-mode)
20410 (setq date (calendar-cursor-to-date)
20411 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20412 ((eq major-mode 'org-agenda-mode)
20413 (setq day (get-text-property (point) 'day))
20414 (if day
20415 (setq date (calendar-gregorian-from-absolute day)
20416 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20417 (nth 2 date))))))
20418 (or defd (current-time))))
20420 (defvar org-agenda-action-marker (make-marker)
20421 "Marker pointing to the entry for the next agenda action.")
20423 (defun org-mark-entry-for-agenda-action ()
20424 "Mark the current entry as target of an agenda action.
20425 Agenda actions are actions executed from the agenda with the key `k',
20426 which make use of the date at the cursor."
20427 (interactive)
20428 (move-marker org-agenda-action-marker
20429 (save-excursion (org-back-to-heading t) (point))
20430 (current-buffer))
20431 (message
20432 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20434 (defun org-mark-subtree ()
20435 "Mark the current subtree.
20436 This puts point at the start of the current subtree, and mark at the end.
20438 If point is in an inline task, mark that task instead."
20439 (interactive)
20440 (let ((inline-task-p
20441 (and (featurep 'org-inlinetask)
20442 (org-inlinetask-in-task-p)))
20443 (beg))
20444 ;; Get beginning of subtree
20445 (cond
20446 (inline-task-p (org-inlinetask-goto-beginning))
20447 ((org-at-heading-p) (beginning-of-line))
20448 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20449 (setq beg (point))
20450 ;; Get end of it
20451 (if inline-task-p
20452 (org-inlinetask-goto-end)
20453 (org-end-of-subtree))
20454 ;; Mark zone
20455 (push-mark (point) nil t)
20456 (goto-char beg)))
20458 ;;; Paragraph filling stuff.
20459 ;; We want this to be just right, so use the full arsenal.
20461 (defun org-indent-line-function ()
20462 "Indent line depending on context."
20463 (interactive)
20464 (let* ((pos (point))
20465 (itemp (org-at-item-p))
20466 (case-fold-search t)
20467 (org-drawer-regexp (or org-drawer-regexp "\000"))
20468 (inline-task-p (and (featurep 'org-inlinetask)
20469 (org-inlinetask-in-task-p)))
20470 (inline-re (and inline-task-p
20471 (org-inlinetask-outline-regexp)))
20472 column)
20473 (beginning-of-line 1)
20474 (cond
20475 ;; Comments
20476 ((looking-at "# ") (setq column 0))
20477 ;; Headings
20478 ((looking-at org-outline-regexp) (setq column 0))
20479 ;; Included files
20480 ((looking-at "#\\+include:") (setq column 0))
20481 ;; Footnote definition
20482 ((looking-at org-footnote-definition-re) (setq column 0))
20483 ;; Literal examples
20484 ((looking-at "[ \t]*:\\( \\|$\\)")
20485 (setq column (org-get-indentation))) ; do nothing
20486 ;; Lists
20487 ((ignore-errors (goto-char (org-in-item-p)))
20488 (setq column (if itemp
20489 (org-get-indentation)
20490 (org-list-item-body-column (point))))
20491 (goto-char pos))
20492 ;; Drawers
20493 ((and (looking-at "[ \t]*:END:")
20494 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20495 (save-excursion
20496 (goto-char (1- (match-beginning 1)))
20497 (setq column (current-column))))
20498 ;; Special blocks
20499 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20500 (save-excursion
20501 (re-search-backward
20502 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20503 (setq column (org-get-indentation (match-string 0))))
20504 ((and (not (looking-at "[ \t]*#\\+begin_"))
20505 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20506 (save-excursion
20507 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20508 (setq column
20509 (cond ((equal (downcase (match-string 1)) "src")
20510 ;; src blocks: let `org-edit-src-exit' handle them
20511 (org-get-indentation))
20512 ((equal (downcase (match-string 1)) "example")
20513 (max (org-get-indentation)
20514 (org-get-indentation (match-string 0))))
20516 (org-get-indentation (match-string 0))))))
20517 ;; This line has nothing special, look at the previous relevant
20518 ;; line to compute indentation
20520 (beginning-of-line 0)
20521 (while (and (not (bobp))
20522 (not (looking-at org-drawer-regexp))
20523 ;; When point started in an inline task, do not move
20524 ;; above task starting line.
20525 (not (and inline-task-p (looking-at inline-re)))
20526 ;; Skip drawers, blocks, empty lines, verbatim,
20527 ;; comments, tables, footnotes definitions, lists,
20528 ;; inline tasks.
20529 (or (and (looking-at "[ \t]*:END:")
20530 (re-search-backward org-drawer-regexp nil t))
20531 (and (looking-at "[ \t]*#\\+end_")
20532 (re-search-backward "[ \t]*#\\+begin_"nil t))
20533 (looking-at "[ \t]*[\n:#|]")
20534 (looking-at org-footnote-definition-re)
20535 (and (ignore-errors (goto-char (org-in-item-p)))
20536 (goto-char
20537 (org-list-get-top-point (org-list-struct))))
20538 (and (not inline-task-p)
20539 (featurep 'org-inlinetask)
20540 (org-inlinetask-in-task-p)
20541 (or (org-inlinetask-goto-beginning) t))))
20542 (beginning-of-line 0))
20543 (cond
20544 ;; There was an heading above.
20545 ((looking-at "\\*+[ \t]+")
20546 (if (not org-adapt-indentation)
20547 (setq column 0)
20548 (goto-char (match-end 0))
20549 (setq column (current-column))))
20550 ;; A drawer had started and is unfinished
20551 ((looking-at org-drawer-regexp)
20552 (goto-char (1- (match-beginning 1)))
20553 (setq column (current-column)))
20554 ;; Else, nothing noticeable found: get indentation and go on.
20555 (t (setq column (org-get-indentation))))))
20556 ;; Now apply indentation and move cursor accordingly
20557 (goto-char pos)
20558 (if (<= (current-column) (current-indentation))
20559 (org-indent-line-to column)
20560 (save-excursion (org-indent-line-to column)))
20561 ;; Special polishing for properties, see `org-property-format'
20562 (setq column (current-column))
20563 (beginning-of-line 1)
20564 (if (looking-at
20565 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20566 (replace-match (concat (match-string 1)
20567 (format org-property-format
20568 (match-string 2) (match-string 3)))
20569 t t))
20570 (org-move-to-column column)
20571 (when (and orgstruct-is-++ (eq pos (point)))
20572 (org-let org-fb-vars
20573 '(indent-according-to-mode)))))
20575 (defun org-indent-drawer ()
20576 "Indent the drawer at point."
20577 (interactive)
20578 (let ((p (point))
20579 (e (and (save-excursion (re-search-forward ":END:" nil t))
20580 (match-end 0)))
20581 (folded
20582 (save-excursion
20583 (end-of-line)
20584 (when (overlays-at (point))
20585 (member 'invisible (overlay-properties
20586 (car (overlays-at (point)))))))))
20587 (when folded (org-cycle))
20588 (indent-for-tab-command)
20589 (while (and (move-beginning-of-line 2) (< (point) e))
20590 (indent-for-tab-command))
20591 (goto-char p)
20592 (when folded (org-cycle)))
20593 (message "Drawer at point indented"))
20595 (defun org-indent-block ()
20596 "Indent the block at point."
20597 (interactive)
20598 (let ((p (point))
20599 (case-fold-search t)
20600 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20601 (match-end 0)))
20602 (folded
20603 (save-excursion
20604 (end-of-line)
20605 (when (overlays-at (point))
20606 (member 'invisible (overlay-properties
20607 (car (overlays-at (point)))))))))
20608 (when folded (org-cycle))
20609 (indent-for-tab-command)
20610 (while (and (move-beginning-of-line 2) (< (point) e))
20611 (indent-for-tab-command))
20612 (goto-char p)
20613 (when folded (org-cycle)))
20614 (message "Block at point indented"))
20616 ;; For reference, this is the default value of adaptive-fill-regexp
20617 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20618 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20619 "Variable to store copy of `adaptive-fill-regexp'.
20620 Since `adaptive-fill-regexp' is set to never match, we need to
20621 store a backup of its value before entering `org-mode' so that
20622 the functionality can be provided as a fall-back.")
20624 (defun org-set-autofill-regexps ()
20625 (interactive)
20626 ;; In the paragraph separator we include headlines, because filling
20627 ;; text in a line directly attached to a headline would otherwise
20628 ;; fill the headline as well.
20629 (org-set-local 'comment-start-skip "^#+[ \t]*")
20630 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20631 ;; The paragraph starter includes hand-formatted lists.
20632 (org-set-local
20633 'paragraph-start
20634 (concat
20635 "\f" "\\|"
20636 "[ ]*$" "\\|"
20637 org-outline-regexp "\\|"
20638 "[ \t]*#" "\\|"
20639 (org-item-re) "\\|"
20640 "[ \t]*[:|]" "\\|"
20641 "\\$\\$" "\\|"
20642 "\\\\\\(begin\\|end\\|[][]\\)"))
20643 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20644 ;; But only if the user has not turned off tables or fixed-width regions
20645 (org-set-local
20646 'auto-fill-inhibit-regexp
20647 (concat org-outline-regexp
20648 "\\|#\\+"
20649 "\\|[ \t]*" org-keyword-time-regexp
20650 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20651 (concat
20652 "\\|[ \t]*["
20653 (if org-enable-table-editor "|" "")
20654 (if org-enable-fixed-width-editor ":" "")
20655 "]"))))
20656 ;; We use our own fill-paragraph function, to make sure that tables
20657 ;; and fixed-width regions are not wrapped. That function will pass
20658 ;; through to `fill-paragraph' when appropriate.
20659 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20660 ;; Prevent auto-fill from inserting unwanted new items.
20661 (if (boundp 'fill-nobreak-predicate)
20662 (org-set-local
20663 'fill-nobreak-predicate
20664 (org-uniquify
20665 (append fill-nobreak-predicate
20666 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20667 ;; Adaptive filling: To get full control, first make sure that
20668 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20669 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20670 (org-set-local 'org-adaptive-fill-regexp-backup
20671 adaptive-fill-regexp))
20672 (org-set-local 'adaptive-fill-regexp "\000")
20673 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20674 (org-set-local 'adaptive-fill-function
20675 'org-adaptive-fill-function)
20676 (org-set-local
20677 'align-mode-rules-list
20678 '((org-in-buffer-settings
20679 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20680 (modes . '(org-mode))))))
20682 (defun org-fill-item-nobreak-p ()
20683 "Non-nil when a line break at point would insert a new item."
20684 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20686 (defun org-fill-line-break-nobreak-p ()
20687 "Non-nil when a line break at point would create an Org line break."
20688 (save-excursion
20689 (skip-chars-backward "[ \t]")
20690 (skip-chars-backward "\\\\")
20691 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20693 (defun org-fill-paragraph (&optional justify)
20694 "Re-align a table, pass through to fill-paragraph if no table."
20695 (let ((table-p (org-at-table-p))
20696 (table.el-p (org-at-table.el-p))
20697 (itemp (org-in-item-p)))
20698 (cond ((and (equal (char-after (point-at-bol)) ?*)
20699 (save-excursion (goto-char (point-at-bol))
20700 (looking-at org-outline-regexp)))
20701 t) ; skip headlines
20702 (table.el-p t) ; skip table.el tables
20703 (table-p (org-table-align) t) ; align Org tables
20704 (itemp ; align text in items
20705 (let* ((struct (save-excursion (goto-char itemp)
20706 (org-list-struct)))
20707 (parents (org-list-parents-alist struct))
20708 (children (org-list-get-children itemp struct parents))
20709 beg end prev next prefix)
20710 ;; Determine in which part of item point is: before
20711 ;; first child, after last child, between two
20712 ;; sub-lists, or simply in item if there's no child.
20713 (cond
20714 ((not children)
20715 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20716 beg itemp
20717 end (org-list-get-item-end itemp struct)))
20718 ((< (point) (setq next (car children)))
20719 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20720 beg itemp
20721 end next))
20722 ((> (point) (setq prev (car (last children))))
20723 (setq beg (org-list-get-item-end prev struct)
20724 end (org-list-get-item-end itemp struct)
20725 prefix (save-excursion
20726 (goto-char beg)
20727 (skip-chars-forward " \t")
20728 (make-string (current-column) ?\ ))))
20729 (t (catch 'exit
20730 (while (setq next (pop children))
20731 (if (> (point) next)
20732 (setq prev next)
20733 (setq beg (org-list-get-item-end prev struct)
20734 end next
20735 prefix (save-excursion
20736 (goto-char beg)
20737 (skip-chars-forward " \t")
20738 (make-string (current-column) ?\ )))
20739 (throw 'exit nil))))))
20740 ;; Use `fill-paragraph' with buffer narrowed to item
20741 ;; without any child, and with our computed PREFIX.
20742 (flet ((fill-context-prefix (from to &optional flr) prefix))
20743 (save-restriction
20744 (narrow-to-region beg end)
20745 (save-excursion (fill-paragraph justify)))) t))
20746 ;; Special case where point is not in a list but is on
20747 ;; a paragraph adjacent to a list: make sure this paragraph
20748 ;; doesn't get merged with the end of the list by narrowing
20749 ;; buffer first.
20750 ((and (derived-mode-p 'org-mode)
20751 (save-excursion (forward-paragraph -1)
20752 (setq itemp (org-in-item-p))))
20753 (let ((struct (save-excursion (goto-char itemp)
20754 (org-list-struct))))
20755 (save-restriction
20756 (narrow-to-region (org-list-get-bottom-point struct)
20757 (save-excursion (forward-paragraph 1)
20758 (point)))
20759 (fill-paragraph justify) t)))
20760 ;; Don't fill schedule/deadline line before a paragraph
20761 ;; This only makes sense in real org-mode buffers
20762 ((and (eq major-mode 'org-mode)
20763 (save-excursion (forward-paragraph -1)
20764 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20765 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$")))))
20766 (save-restriction
20767 (narrow-to-region (1+ (match-end 0))
20768 (save-excursion (forward-paragraph 1) (point)))
20769 (fill-paragraph justify) t))
20770 ;; Else fall back on fill-paragraph-function as possibly
20771 ;; defined in `org-fb-vars'
20772 (orgstruct-is-++
20773 (org-let org-fb-vars
20774 '(fill-paragraph justify)))
20775 (t nil))))
20777 (defun org-adaptive-fill-function ()
20778 "Return a fill prefix for org-mode files."
20779 (let (itemp)
20780 (save-excursion
20781 (cond
20782 ;; Comment line
20783 ((looking-at "#[ \t]+")
20784 (match-string-no-properties 0))
20785 ;; Plain list item
20786 ((org-at-item-p)
20787 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20788 ;; Point is in a list after `backward-paragraph': original
20789 ;; point wasn't in the list, or filling would have been taken
20790 ;; care of by `org-auto-fill-function', but the list and the
20791 ;; real paragraph are not separated by a blank line. Thus, move
20792 ;; point after the list to go back to real paragraph and
20793 ;; determine fill-prefix.
20794 ((setq itemp (org-in-item-p))
20795 (goto-char itemp)
20796 (let* ((struct (org-list-struct))
20797 (bottom (org-list-get-bottom-point struct)))
20798 (goto-char bottom)
20799 (make-string (org-get-indentation) ?\ )))
20800 ;; Other text
20801 ((looking-at org-adaptive-fill-regexp-backup)
20802 (match-string-no-properties 0))))))
20804 (defun org-auto-fill-function ()
20805 "Auto-fill function."
20806 (unless (and org-src-prevent-auto-filling (org-in-src-block-p))
20807 (let (itemp prefix)
20808 ;; When in a list, compute an appropriate fill-prefix and make
20809 ;; sure it will be used by `do-auto-fill'.
20810 (cond ((setq itemp (org-in-item-p))
20811 (progn
20812 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20813 (flet ((fill-context-prefix (from to &optional flr) prefix))
20814 (do-auto-fill))))
20815 (orgstruct-is-++
20816 (org-let org-fb-vars
20817 '(do-auto-fill)))
20818 (t (do-auto-fill))))))
20820 ;;; Other stuff.
20822 (defun org-toggle-fixed-width-section (arg)
20823 "Toggle the fixed-width export.
20824 If there is no active region, the QUOTE keyword at the current headline is
20825 inserted or removed. When present, it causes the text between this headline
20826 and the next to be exported as fixed-width text, and unmodified.
20827 If there is an active region, this command adds or removes a colon as the
20828 first character of this line. If the first character of a line is a colon,
20829 this line is also exported in fixed-width font."
20830 (interactive "P")
20831 (let* ((cc 0)
20832 (regionp (org-region-active-p))
20833 (beg (if regionp (region-beginning) (point)))
20834 (end (if regionp (region-end)))
20835 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20836 (case-fold-search nil)
20837 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20838 off)
20839 (if regionp
20840 (save-excursion
20841 (goto-char beg)
20842 (setq cc (current-column))
20843 (beginning-of-line 1)
20844 (setq off (looking-at re))
20845 (while (> nlines 0)
20846 (setq nlines (1- nlines))
20847 (beginning-of-line 1)
20848 (cond
20849 (arg
20850 (org-move-to-column cc t)
20851 (insert ": \n")
20852 (forward-line -1))
20853 ((and off (looking-at re))
20854 (replace-match "" t t nil 1))
20855 ((not off) (org-move-to-column cc t) (insert ": ")))
20856 (forward-line 1)))
20857 (save-excursion
20858 (org-back-to-heading)
20859 (cond
20860 ((looking-at (format org-heading-keyword-regexp-format
20861 org-quote-string))
20862 (goto-char (match-end 1))
20863 (looking-at (concat " +" org-quote-string))
20864 (replace-match "" t t)
20865 (when (eolp) (insert " ")))
20866 ((looking-at org-outline-regexp)
20867 (goto-char (match-end 0))
20868 (insert org-quote-string " ")))))))
20870 (defun org-reftex-citation ()
20871 "Use reftex-citation to insert a citation into the buffer.
20872 This looks for a line like
20874 #+BIBLIOGRAPHY: foo plain option:-d
20876 and derives from it that foo.bib is the bibliography file relevant
20877 for this document. It then installs the necessary environment for RefTeX
20878 to work in this buffer and calls `reftex-citation' to insert a citation
20879 into the buffer.
20881 Export of such citations to both LaTeX and HTML is handled by the contributed
20882 package org-exp-bibtex by Taru Karttunen."
20883 (interactive)
20884 (let ((reftex-docstruct-symbol 'rds)
20885 (reftex-cite-format "\\cite{%l}")
20886 rds bib)
20887 (save-excursion
20888 (save-restriction
20889 (widen)
20890 (let ((case-fold-search t)
20891 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20892 (if (not (save-excursion
20893 (or (re-search-forward re nil t)
20894 (re-search-backward re nil t))))
20895 (error "No bibliography defined in file")
20896 (setq bib (concat (match-string 1) ".bib")
20897 rds (list (list 'bib bib)))))))
20898 (call-interactively 'reftex-citation)))
20900 ;;;; Functions extending outline functionality
20902 (defun org-beginning-of-line (&optional arg)
20903 "Go to the beginning of the current line. If that is invisible, continue
20904 to a visible line beginning. This makes the function of C-a more intuitive.
20905 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20906 first attempt, and only move to after the tags when the cursor is already
20907 beyond the end of the headline."
20908 (interactive "P")
20909 (let ((pos (point))
20910 (special (if (consp org-special-ctrl-a/e)
20911 (car org-special-ctrl-a/e)
20912 org-special-ctrl-a/e))
20913 refpos)
20914 (if (org-bound-and-true-p line-move-visual)
20915 (beginning-of-visual-line 1)
20916 (beginning-of-line 1))
20917 (if (and arg (fboundp 'move-beginning-of-line))
20918 (call-interactively 'move-beginning-of-line)
20919 (if (bobp)
20921 (backward-char 1)
20922 (if (org-truely-invisible-p)
20923 (while (and (not (bobp)) (org-truely-invisible-p))
20924 (backward-char 1)
20925 (beginning-of-line 1))
20926 (forward-char 1))))
20927 (when special
20928 (cond
20929 ((and (looking-at org-complex-heading-regexp)
20930 (= (char-after (match-end 1)) ?\ ))
20931 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20932 (point-at-eol)))
20933 (goto-char
20934 (if (eq special t)
20935 (cond ((> pos refpos) refpos)
20936 ((= pos (point)) refpos)
20937 (t (point)))
20938 (cond ((> pos (point)) (point))
20939 ((not (eq last-command this-command)) (point))
20940 (t refpos)))))
20941 ((org-at-item-p)
20942 ;; Being at an item and not looking at an the item means point
20943 ;; was previously moved to beginning of a visual line, which
20944 ;; doesn't contain the item. Therefore, do nothing special,
20945 ;; just stay here.
20946 (when (looking-at org-list-full-item-re)
20947 ;; Set special position at first white space character after
20948 ;; bullet, and check-box, if any.
20949 (let ((after-bullet
20950 (let ((box (match-end 3)))
20951 (if (not box) (match-end 1)
20952 (let ((after (char-after box)))
20953 (if (and after (= after ? )) (1+ box) box))))))
20954 ;; Special case: Move point to special position when
20955 ;; currently after it or at beginning of line.
20956 (if (eq special t)
20957 (when (or (> pos after-bullet) (= (point) pos))
20958 (goto-char after-bullet))
20959 ;; Reversed case: Move point to special position when
20960 ;; point was already at beginning of line and command is
20961 ;; repeated.
20962 (when (and (= (point) pos) (eq last-command this-command))
20963 (goto-char after-bullet))))))))
20964 (org-no-warnings
20965 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20967 (defun org-end-of-line (&optional arg)
20968 "Go to the end of the line.
20969 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20970 first attempt, and only move to after the tags when the cursor is already
20971 beyond the end of the headline."
20972 (interactive "P")
20973 (let ((special (if (consp org-special-ctrl-a/e)
20974 (cdr org-special-ctrl-a/e)
20975 org-special-ctrl-a/e)))
20976 (cond
20977 ((or (not special) arg
20978 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20979 (call-interactively
20980 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20981 ((fboundp 'move-end-of-line) 'move-end-of-line)
20982 (t 'end-of-line))))
20983 ((org-at-heading-p)
20984 (let ((pos (point)))
20985 (beginning-of-line 1)
20986 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20987 (if (eq special t)
20988 (if (or (< pos (match-beginning 1))
20989 (= pos (match-end 0)))
20990 (goto-char (match-beginning 1))
20991 (goto-char (match-end 0)))
20992 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20993 (goto-char (match-end 0))
20994 (goto-char (match-beginning 1))))
20995 (call-interactively (if (fboundp 'move-end-of-line)
20996 'move-end-of-line
20997 'end-of-line)))))
20998 ((org-at-drawer-p)
20999 (move-end-of-line 1)
21000 (when (overlays-at (1- (point))) (backward-char 1)))
21001 ;; At an item: Move before any hidden text.
21002 (t (call-interactively
21003 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21004 ((fboundp 'move-end-of-line) 'move-end-of-line)
21005 (t 'end-of-line)))))
21006 (org-no-warnings
21007 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21009 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21010 (define-key org-mode-map "\C-e" 'org-end-of-line)
21012 (defun org-backward-sentence (&optional arg)
21013 "Go to beginning of sentence, or beginning of table field.
21014 This will call `backward-sentence' or `org-table-beginning-of-field',
21015 depending on context."
21016 (interactive "P")
21017 (cond
21018 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21019 (t (call-interactively 'backward-sentence))))
21021 (defun org-forward-sentence (&optional arg)
21022 "Go to end of sentence, or end of table field.
21023 This will call `forward-sentence' or `org-table-end-of-field',
21024 depending on context."
21025 (interactive "P")
21026 (cond
21027 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21028 (t (call-interactively 'forward-sentence))))
21030 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21031 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21033 (defun org-kill-line (&optional arg)
21034 "Kill line, to tags or end of line."
21035 (interactive "P")
21036 (cond
21037 ((or (not org-special-ctrl-k)
21038 (bolp)
21039 (not (org-at-heading-p)))
21040 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21041 org-ctrl-k-protect-subtree)
21042 (if (or (eq org-ctrl-k-protect-subtree 'error)
21043 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21044 (error "C-k aborted - would kill hidden subtree")))
21045 (call-interactively
21046 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21047 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21048 (kill-region (point) (match-beginning 1))
21049 (org-set-tags nil t))
21050 (t (kill-region (point) (point-at-eol)))))
21052 (define-key org-mode-map "\C-k" 'org-kill-line)
21054 (defun org-yank (&optional arg)
21055 "Yank. If the kill is a subtree, treat it specially.
21056 This command will look at the current kill and check if is a single
21057 subtree, or a series of subtrees[1]. If it passes the test, and if the
21058 cursor is at the beginning of a line or after the stars of a currently
21059 empty headline, then the yank is handled specially. How exactly depends
21060 on the value of the following variables, both set by default.
21062 org-yank-folded-subtrees
21063 When set, the subtree(s) will be folded after insertion, but only
21064 if doing so would now swallow text after the yanked text.
21066 org-yank-adjusted-subtrees
21067 When set, the subtree will be promoted or demoted in order to
21068 fit into the local outline tree structure, which means that the level
21069 will be adjusted so that it becomes the smaller one of the two
21070 *visible* surrounding headings.
21072 Any prefix to this command will cause `yank' to be called directly with
21073 no special treatment. In particular, a simple \\[universal-argument] prefix \
21074 will just
21075 plainly yank the text as it is.
21077 \[1] The test checks if the first non-white line is a heading
21078 and if there are no other headings with fewer stars."
21079 (interactive "P")
21080 (org-yank-generic 'yank arg))
21082 (defun org-yank-generic (command arg)
21083 "Perform some yank-like command.
21085 This function implements the behavior described in the `org-yank'
21086 documentation. However, it has been generalized to work for any
21087 interactive command with similar behavior."
21089 ;; pretend to be command COMMAND
21090 (setq this-command command)
21092 (if arg
21093 (call-interactively command)
21095 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21096 (and (org-kill-is-subtree-p)
21097 (or (bolp)
21098 (and (looking-at "[ \t]*$")
21099 (string-match
21100 "\\`\\*+\\'"
21101 (buffer-substring (point-at-bol) (point)))))))
21102 swallowp)
21103 (cond
21104 ((and subtreep org-yank-folded-subtrees)
21105 (let ((beg (point))
21106 end)
21107 (if (and subtreep org-yank-adjusted-subtrees)
21108 (org-paste-subtree nil nil 'for-yank)
21109 (call-interactively command))
21111 (setq end (point))
21112 (goto-char beg)
21113 (when (and (bolp) subtreep
21114 (not (setq swallowp
21115 (org-yank-folding-would-swallow-text beg end))))
21116 (org-with-limited-levels
21117 (or (looking-at org-outline-regexp)
21118 (re-search-forward org-outline-regexp-bol end t))
21119 (while (and (< (point) end) (looking-at org-outline-regexp))
21120 (hide-subtree)
21121 (org-cycle-show-empty-lines 'folded)
21122 (condition-case nil
21123 (outline-forward-same-level 1)
21124 (error (goto-char end))))))
21125 (when swallowp
21126 (message
21127 "Inserted text not folded because that would swallow text"))
21129 (goto-char end)
21130 (skip-chars-forward " \t\n\r")
21131 (beginning-of-line 1)
21132 (push-mark beg 'nomsg)))
21133 ((and subtreep org-yank-adjusted-subtrees)
21134 (let ((beg (point-at-bol)))
21135 (org-paste-subtree nil nil 'for-yank)
21136 (push-mark beg 'nomsg)))
21138 (call-interactively command))))))
21140 (defun org-yank-folding-would-swallow-text (beg end)
21141 "Would hide-subtree at BEG swallow any text after END?"
21142 (let (level)
21143 (org-with-limited-levels
21144 (save-excursion
21145 (goto-char beg)
21146 (when (or (looking-at org-outline-regexp)
21147 (re-search-forward org-outline-regexp-bol end t))
21148 (setq level (org-outline-level)))
21149 (goto-char end)
21150 (skip-chars-forward " \t\r\n\v\f")
21151 (if (or (eobp)
21152 (and (bolp) (looking-at org-outline-regexp)
21153 (<= (org-outline-level) level)))
21154 nil ; Nothing would be swallowed
21155 t))))) ; something would swallow
21157 (define-key org-mode-map "\C-y" 'org-yank)
21159 (defun org-truely-invisible-p ()
21160 "Check if point is at a character currently not visible.
21161 This version does not only check the character property, but also
21162 `visible-mode'."
21163 ;; Early versions of noutline don't have `outline-invisible-p'.
21164 (if (org-bound-and-true-p visible-mode)
21166 (outline-invisible-p)))
21168 (defun org-invisible-p2 ()
21169 "Check if point is at a character currently not visible."
21170 (save-excursion
21171 (if (and (eolp) (not (bobp))) (backward-char 1))
21172 ;; Early versions of noutline don't have `outline-invisible-p'.
21173 (outline-invisible-p)))
21175 (defun org-back-to-heading (&optional invisible-ok)
21176 "Call `outline-back-to-heading', but provide a better error message."
21177 (condition-case nil
21178 (outline-back-to-heading invisible-ok)
21179 (error (error "Before first headline at position %d in buffer %s"
21180 (point) (current-buffer)))))
21182 (defun org-beginning-of-defun ()
21183 "Go to the beginning of the subtree, i.e. back to the heading."
21184 (org-back-to-heading))
21185 (defun org-end-of-defun ()
21186 "Go to the end of the subtree."
21187 (org-end-of-subtree nil t))
21189 (defun org-before-first-heading-p ()
21190 "Before first heading?"
21191 (save-excursion
21192 (end-of-line)
21193 (null (re-search-backward org-outline-regexp-bol nil t))))
21195 (defun org-at-heading-p (&optional ignored)
21196 (outline-on-heading-p t))
21197 ;; Compatibility alias with Org versions < 7.8.03
21198 (defalias 'org-on-heading-p 'org-at-heading-p)
21200 (defun org-at-drawer-p nil
21201 "Is cursor at a drawer keyword?"
21202 (save-excursion
21203 (move-beginning-of-line 1)
21204 (looking-at org-drawer-regexp)))
21206 (defun org-at-block-p nil
21207 "Is cursor at a block keyword?"
21208 (save-excursion
21209 (move-beginning-of-line 1)
21210 (looking-at org-block-regexp)))
21212 (defun org-point-at-end-of-empty-headline ()
21213 "If point is at the end of an empty headline, return t, else nil.
21214 If the heading only contains a TODO keyword, it is still still considered
21215 empty."
21216 (and (looking-at "[ \t]*$")
21217 (when org-todo-line-regexp
21218 (save-excursion
21219 (beginning-of-line 1)
21220 (let ((case-fold-search nil))
21221 (looking-at org-todo-line-regexp)
21222 (string= (match-string 3) ""))))))
21224 (defun org-at-heading-or-item-p ()
21225 (or (org-at-heading-p) (org-at-item-p)))
21227 (defun org-at-target-p ()
21228 (or (org-in-regexp org-radio-target-regexp)
21229 (org-in-regexp org-target-regexp)))
21230 ;; Compatibility alias with Org versions < 7.8.03
21231 (defalias 'org-on-target-p 'org-at-target-p)
21233 (defun org-up-heading-all (arg)
21234 "Move to the heading line of which the present line is a subheading.
21235 This function considers both visible and invisible heading lines.
21236 With argument, move up ARG levels."
21237 (if (fboundp 'outline-up-heading-all)
21238 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21239 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21241 (defun org-up-heading-safe ()
21242 "Move to the heading line of which the present line is a subheading.
21243 This version will not throw an error. It will return the level of the
21244 headline found, or nil if no higher level is found.
21246 Also, this function will be a lot faster than `outline-up-heading',
21247 because it relies on stars being the outline starters. This can really
21248 make a significant difference in outlines with very many siblings."
21249 (let (start-level re)
21250 (org-back-to-heading t)
21251 (setq start-level (funcall outline-level))
21252 (if (equal start-level 1)
21254 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21255 (if (re-search-backward re nil t)
21256 (funcall outline-level)))))
21258 (defun org-first-sibling-p ()
21259 "Is this heading the first child of its parents?"
21260 (interactive)
21261 (let ((re org-outline-regexp-bol)
21262 level l)
21263 (unless (org-at-heading-p t)
21264 (error "Not at a heading"))
21265 (setq level (funcall outline-level))
21266 (save-excursion
21267 (if (not (re-search-backward re nil t))
21269 (setq l (funcall outline-level))
21270 (< l level)))))
21272 (defun org-goto-sibling (&optional previous)
21273 "Goto the next sibling, even if it is invisible.
21274 When PREVIOUS is set, go to the previous sibling instead. Returns t
21275 when a sibling was found. When none is found, return nil and don't
21276 move point."
21277 (let ((fun (if previous 're-search-backward 're-search-forward))
21278 (pos (point))
21279 (re org-outline-regexp-bol)
21280 level l)
21281 (when (condition-case nil (org-back-to-heading t) (error nil))
21282 (setq level (funcall outline-level))
21283 (catch 'exit
21284 (or previous (forward-char 1))
21285 (while (funcall fun re nil t)
21286 (setq l (funcall outline-level))
21287 (when (< l level) (goto-char pos) (throw 'exit nil))
21288 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21289 (goto-char pos)
21290 nil))))
21292 (defun org-show-siblings ()
21293 "Show all siblings of the current headline."
21294 (save-excursion
21295 (while (org-goto-sibling) (org-flag-heading nil)))
21296 (save-excursion
21297 (while (org-goto-sibling 'previous)
21298 (org-flag-heading nil))))
21300 (defun org-goto-first-child ()
21301 "Goto the first child, even if it is invisible.
21302 Return t when a child was found. Otherwise don't move point and
21303 return nil."
21304 (let (level (pos (point)) (re org-outline-regexp-bol))
21305 (when (condition-case nil (org-back-to-heading t) (error nil))
21306 (setq level (outline-level))
21307 (forward-char 1)
21308 (if (and (re-search-forward re nil t) (> (outline-level) level))
21309 (progn (goto-char (match-beginning 0)) t)
21310 (goto-char pos) nil))))
21312 (defun org-show-hidden-entry ()
21313 "Show an entry where even the heading is hidden."
21314 (save-excursion
21315 (org-show-entry)))
21317 (defun org-flag-heading (flag &optional entry)
21318 "Flag the current heading. FLAG non-nil means make invisible.
21319 When ENTRY is non-nil, show the entire entry."
21320 (save-excursion
21321 (org-back-to-heading t)
21322 ;; Check if we should show the entire entry
21323 (if entry
21324 (progn
21325 (org-show-entry)
21326 (save-excursion
21327 (and (outline-next-heading)
21328 (org-flag-heading nil))))
21329 (outline-flag-region (max (point-min) (1- (point)))
21330 (save-excursion (outline-end-of-heading) (point))
21331 flag))))
21333 (defun org-get-next-sibling ()
21334 "Move to next heading of the same level, and return point.
21335 If there is no such heading, return nil.
21336 This is like outline-next-sibling, but invisible headings are ok."
21337 (let ((level (funcall outline-level)))
21338 (outline-next-heading)
21339 (while (and (not (eobp)) (> (funcall outline-level) level))
21340 (outline-next-heading))
21341 (if (or (eobp) (< (funcall outline-level) level))
21343 (point))))
21345 (defun org-get-last-sibling ()
21346 "Move to previous heading of the same level, and return point.
21347 If there is no such heading, return nil."
21348 (let ((opoint (point))
21349 (level (funcall outline-level)))
21350 (outline-previous-heading)
21351 (when (and (/= (point) opoint) (outline-on-heading-p t))
21352 (while (and (> (funcall outline-level) level)
21353 (not (bobp)))
21354 (outline-previous-heading))
21355 (if (< (funcall outline-level) level)
21357 (point)))))
21359 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21360 ;; This contains an exact copy of the original function, but it uses
21361 ;; `org-back-to-heading', to make it work also in invisible
21362 ;; trees. And is uses an invisible-OK argument.
21363 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21364 ;; Furthermore, when used inside Org, finding the end of a large subtree
21365 ;; with many children and grandchildren etc, this can be much faster
21366 ;; than the outline version.
21367 (org-back-to-heading invisible-OK)
21368 (let ((first t)
21369 (level (funcall outline-level)))
21370 (if (and (derived-mode-p 'org-mode) (< level 1000))
21371 ;; A true heading (not a plain list item), in Org-mode
21372 ;; This means we can easily find the end by looking
21373 ;; only for the right number of stars. Using a regexp to do
21374 ;; this is so much faster than using a Lisp loop.
21375 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21376 (forward-char 1)
21377 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21378 ;; something else, do it the slow way
21379 (while (and (not (eobp))
21380 (or first (> (funcall outline-level) level)))
21381 (setq first nil)
21382 (outline-next-heading)))
21383 (unless to-heading
21384 (if (memq (preceding-char) '(?\n ?\^M))
21385 (progn
21386 ;; Go to end of line before heading
21387 (forward-char -1)
21388 (if (memq (preceding-char) '(?\n ?\^M))
21389 ;; leave blank line before heading
21390 (forward-char -1))))))
21391 (point))
21393 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21394 "Use Org version in org-mode, for dramatic speed-up."
21395 (if (derived-mode-p 'org-mode)
21396 (progn
21397 (org-end-of-subtree nil t)
21398 (unless (eobp) (backward-char 1)))
21399 ad-do-it))
21401 (defun org-end-of-meta-data-and-drawers ()
21402 "Jump to the first text after meta data and drawers in the current entry.
21403 This will move over empty lines, lines with planning time stamps,
21404 clocking lines, and drawers."
21405 (org-back-to-heading t)
21406 (let ((end (save-excursion (outline-next-heading) (point)))
21407 (re (concat "\\(" org-drawer-regexp "\\)"
21408 "\\|" "[ \t]*" org-keyword-time-regexp)))
21409 (forward-line 1)
21410 (while (re-search-forward re end t)
21411 (if (not (match-end 1))
21412 ;; empty or planning line
21413 (forward-line 1)
21414 ;; a drawer, find the end
21415 (re-search-forward "^[ \t]*:END:" end 'move)
21416 (forward-line 1)))
21417 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21418 (point)))
21420 (defun org-forward-same-level (arg &optional invisible-ok)
21421 "Move forward to the arg'th subheading at same level as this one.
21422 Stop at the first and last subheadings of a superior heading.
21423 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21424 it wil also look at invisible ones."
21425 (interactive "p")
21426 (org-back-to-heading invisible-ok)
21427 (org-at-heading-p)
21428 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21429 (re (format "^\\*\\{1,%d\\} " level))
21431 (forward-char 1)
21432 (while (> arg 0)
21433 (while (and (re-search-forward re nil 'move)
21434 (setq l (- (match-end 0) (match-beginning 0) 1))
21435 (= l level)
21436 (not invisible-ok)
21437 (progn (backward-char 1) (outline-invisible-p)))
21438 (if (< l level) (setq arg 1)))
21439 (setq arg (1- arg)))
21440 (beginning-of-line 1)))
21442 (defun org-backward-same-level (arg &optional invisible-ok)
21443 "Move backward to the arg'th subheading at same level as this one.
21444 Stop at the first and last subheadings of a superior heading."
21445 (interactive "p")
21446 (org-back-to-heading)
21447 (org-at-heading-p)
21448 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21449 (re (format "^\\*\\{1,%d\\} " level))
21451 (while (> arg 0)
21452 (while (and (re-search-backward re nil 'move)
21453 (setq l (- (match-end 0) (match-beginning 0) 1))
21454 (= l level)
21455 (not invisible-ok)
21456 (outline-invisible-p))
21457 (if (< l level) (setq arg 1)))
21458 (setq arg (1- arg)))))
21460 (defun org-show-subtree ()
21461 "Show everything after this heading at deeper levels."
21462 (interactive)
21463 (outline-flag-region
21464 (point)
21465 (save-excursion
21466 (org-end-of-subtree t t))
21467 nil))
21469 (defun org-show-entry ()
21470 "Show the body directly following this heading.
21471 Show the heading too, if it is currently invisible."
21472 (interactive)
21473 (save-excursion
21474 (condition-case nil
21475 (progn
21476 (org-back-to-heading t)
21477 (outline-flag-region
21478 (max (point-min) (1- (point)))
21479 (save-excursion
21480 (if (re-search-forward
21481 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21482 (match-beginning 1)
21483 (point-max)))
21484 nil)
21485 (org-cycle-hide-drawers 'children))
21486 (error nil))))
21488 (defun org-make-options-regexp (kwds &optional extra)
21489 "Make a regular expression for keyword lines."
21490 (concat
21492 "#?[ \t]*\\+\\("
21493 (mapconcat 'regexp-quote kwds "\\|")
21494 (if extra (concat "\\|" extra))
21495 "\\):[ \t]*"
21496 "\\(.*\\)"))
21498 ;; Make isearch reveal the necessary context
21499 (defun org-isearch-end ()
21500 "Reveal context after isearch exits."
21501 (when isearch-success ; only if search was successful
21502 (if (featurep 'xemacs)
21503 ;; Under XEmacs, the hook is run in the correct place,
21504 ;; we directly show the context.
21505 (org-show-context 'isearch)
21506 ;; In Emacs the hook runs *before* restoring the overlays.
21507 ;; So we have to use a one-time post-command-hook to do this.
21508 ;; (Emacs 22 has a special variable, see function `org-mode')
21509 (unless (and (boundp 'isearch-mode-end-hook-quit)
21510 isearch-mode-end-hook-quit)
21511 ;; Only when the isearch was not quitted.
21512 (org-add-hook 'post-command-hook 'org-isearch-post-command
21513 'append 'local)))))
21515 (defun org-isearch-post-command ()
21516 "Remove self from hook, and show context."
21517 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21518 (org-show-context 'isearch))
21521 ;;;; Integration with and fixes for other packages
21523 ;;; Imenu support
21525 (defvar org-imenu-markers nil
21526 "All markers currently used by Imenu.")
21527 (make-variable-buffer-local 'org-imenu-markers)
21529 (defun org-imenu-new-marker (&optional pos)
21530 "Return a new marker for use by Imenu, and remember the marker."
21531 (let ((m (make-marker)))
21532 (move-marker m (or pos (point)))
21533 (push m org-imenu-markers)
21536 (defun org-imenu-get-tree ()
21537 "Produce the index for Imenu."
21538 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21539 (setq org-imenu-markers nil)
21540 (let* ((n org-imenu-depth)
21541 (re (concat "^" (org-get-limited-outline-regexp)))
21542 (subs (make-vector (1+ n) nil))
21543 (last-level 0)
21544 m level head)
21545 (save-excursion
21546 (save-restriction
21547 (widen)
21548 (goto-char (point-max))
21549 (while (re-search-backward re nil t)
21550 (setq level (org-reduced-level (funcall outline-level)))
21551 (when (and (<= level n)
21552 (looking-at org-complex-heading-regexp))
21553 (setq head (org-link-display-format
21554 (org-match-string-no-properties 4))
21555 m (org-imenu-new-marker))
21556 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21557 (if (>= level last-level)
21558 (push (cons head m) (aref subs level))
21559 (push (cons head (aref subs (1+ level))) (aref subs level))
21560 (loop for i from (1+ level) to n do (aset subs i nil)))
21561 (setq last-level level)))))
21562 (aref subs 1)))
21564 (eval-after-load "imenu"
21565 '(progn
21566 (add-hook 'imenu-after-jump-hook
21567 (lambda ()
21568 (if (derived-mode-p 'org-mode)
21569 (org-show-context 'org-goto))))))
21571 (defun org-link-display-format (link)
21572 "Replace a link with either the description, or the link target
21573 if no description is present"
21574 (save-match-data
21575 (if (string-match org-bracket-link-analytic-regexp link)
21576 (replace-match (if (match-end 5)
21577 (match-string 5 link)
21578 (concat (match-string 1 link)
21579 (match-string 3 link)))
21580 nil t link)
21581 link)))
21583 (defun org-toggle-link-display ()
21584 "Toggle the literal or descriptive display of links."
21585 (interactive)
21586 (if org-descriptive-links
21587 (progn (org-remove-from-invisibility-spec '(org-link))
21588 (org-restart-font-lock)
21589 (setq org-descriptive-links nil))
21590 (progn (add-to-invisibility-spec '(org-link))
21591 (org-restart-font-lock)
21592 (setq org-descriptive-links t))))
21594 ;; Speedbar support
21596 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21597 "Overlay marking the agenda restriction line in speedbar.")
21598 (overlay-put org-speedbar-restriction-lock-overlay
21599 'face 'org-agenda-restriction-lock)
21600 (overlay-put org-speedbar-restriction-lock-overlay
21601 'help-echo "Agendas are currently limited to this item.")
21602 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21604 (defun org-speedbar-set-agenda-restriction ()
21605 "Restrict future agenda commands to the location at point in speedbar.
21606 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21607 (interactive)
21608 (require 'org-agenda)
21609 (let (p m tp np dir txt)
21610 (cond
21611 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21612 'org-imenu t))
21613 (setq m (get-text-property p 'org-imenu-marker))
21614 (with-current-buffer (marker-buffer m)
21615 (goto-char m)
21616 (org-agenda-set-restriction-lock 'subtree)))
21617 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21618 'speedbar-function 'speedbar-find-file))
21619 (setq tp (previous-single-property-change
21620 (1+ p) 'speedbar-function)
21621 np (next-single-property-change
21622 tp 'speedbar-function)
21623 dir (speedbar-line-directory)
21624 txt (buffer-substring-no-properties (or tp (point-min))
21625 (or np (point-max))))
21626 (with-current-buffer (find-file-noselect
21627 (let ((default-directory dir))
21628 (expand-file-name txt)))
21629 (unless (derived-mode-p 'org-mode)
21630 (error "Cannot restrict to non-Org-mode file"))
21631 (org-agenda-set-restriction-lock 'file)))
21632 (t (error "Don't know how to restrict Org-mode's agenda")))
21633 (move-overlay org-speedbar-restriction-lock-overlay
21634 (point-at-bol) (point-at-eol))
21635 (setq current-prefix-arg nil)
21636 (org-agenda-maybe-redo)))
21638 (eval-after-load "speedbar"
21639 '(progn
21640 (speedbar-add-supported-extension ".org")
21641 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21642 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21643 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21644 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21645 (add-hook 'speedbar-visiting-tag-hook
21646 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
21648 ;;; Fixes and Hacks for problems with other packages
21650 ;; Make flyspell not check words in links, to not mess up our keymap
21651 (defun org-mode-flyspell-verify ()
21652 "Don't let flyspell put overlays at active buttons, or on
21653 {todo,all-time,additional-option-like}-keywords."
21654 (let ((pos (max (1- (point)) (point-min)))
21655 (word (thing-at-point 'word)))
21656 (and (not (get-text-property pos 'keymap))
21657 (not (get-text-property pos 'org-no-flyspell))
21658 (not (member word org-todo-keywords-1))
21659 (not (member word org-all-time-keywords))
21660 (not (member word org-additional-option-like-keywords)))))
21662 (defun org-remove-flyspell-overlays-in (beg end)
21663 "Remove flyspell overlays in region."
21664 (and (org-bound-and-true-p flyspell-mode)
21665 (fboundp 'flyspell-delete-region-overlays)
21666 (flyspell-delete-region-overlays beg end))
21667 (add-text-properties beg end '(org-no-flyspell t)))
21669 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21670 (eval-after-load "bookmark"
21671 '(if (boundp 'bookmark-after-jump-hook)
21672 ;; We can use the hook
21673 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21674 ;; Hook not available, use advice
21675 (defadvice bookmark-jump (after org-make-visible activate)
21676 "Make the position visible."
21677 (org-bookmark-jump-unhide))))
21679 ;; Make sure saveplace shows the location if it was hidden
21680 (eval-after-load "saveplace"
21681 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21682 "Make the position visible."
21683 (org-bookmark-jump-unhide)))
21685 ;; Make sure ecb shows the location if it was hidden
21686 (eval-after-load "ecb"
21687 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21688 "Make hierarchy visible when jumping into location from ECB tree buffer."
21689 (if (derived-mode-p 'org-mode)
21690 (org-show-context))))
21692 (defun org-bookmark-jump-unhide ()
21693 "Unhide the current position, to show the bookmark location."
21694 (and (derived-mode-p 'org-mode)
21695 (or (outline-invisible-p)
21696 (save-excursion (goto-char (max (point-min) (1- (point))))
21697 (outline-invisible-p)))
21698 (org-show-context 'bookmark-jump)))
21700 ;; Make session.el ignore our circular variable
21701 (eval-after-load "session"
21702 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21704 ;;;; Experimental code
21706 (defun org-closed-in-range ()
21707 "Sparse tree of items closed in a certain time range.
21708 Still experimental, may disappear in the future."
21709 (interactive)
21710 ;; Get the time interval from the user.
21711 (let* ((time1 (org-float-time
21712 (org-read-date nil 'to-time nil "Starting date: ")))
21713 (time2 (org-float-time
21714 (org-read-date nil 'to-time nil "End date:")))
21715 ;; callback function
21716 (callback (lambda ()
21717 (let ((time
21718 (org-float-time
21719 (apply 'encode-time
21720 (org-parse-time-string
21721 (match-string 1))))))
21722 ;; check if time in interval
21723 (and (>= time time1) (<= time time2))))))
21724 ;; make tree, check each match with the callback
21725 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21727 ;;;; Finish up
21729 (provide 'org)
21731 (run-hooks 'org-load-hook)
21733 ;;; org.el ends here