org.el: Fix indentation of a property line starting at the beginning of a line.
[org-mode.git] / lisp / org.el
blob2a0160d36107b5657aa7075fd66f381a5e66393a
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 (org-check-version)
213 ;;;###autoload
214 (defun org-version (&optional here full message)
215 "Show the org-mode version in the echo area.
216 With prefix arg HERE, insert it at point."
217 (interactive "P")
218 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
219 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
220 (org-trash (or
221 (and (fboundp 'org-release) (fboundp 'org-git-version))
222 (load (concat org-dir "org-version.el")
223 'noerror 'nomessage 'nosuffix)))
224 (org-version (org-release))
225 (git-version (org-git-version))
226 (version (format "Org-mode version %s (%s @ %s)"
227 org-version
228 git-version
229 (if org-install-dir
230 (if (string= org-dir org-install-dir)
231 org-install-dir
232 (concat "mixed installation! " org-install-dir " and " org-dir))
233 "org-install.el can not be found!")))
234 (_version (if full version org-version)))
235 (if (org-called-interactively-p 'interactive)
236 (if here
237 (insert version)
238 (message version))
239 (if message (message _version))
240 _version)))
242 ;;; Compatibility constants
244 ;;; The custom variables
246 (defgroup org nil
247 "Outline-based notes management and organizer."
248 :tag "Org"
249 :group 'outlines
250 :group 'calendar)
252 (defcustom org-mode-hook nil
253 "Mode hook for Org-mode, run after the mode was turned on."
254 :group 'org
255 :type 'hook)
257 (defcustom org-load-hook nil
258 "Hook that is run after org.el has been loaded."
259 :group 'org
260 :type 'hook)
262 (defcustom org-log-buffer-setup-hook nil
263 "Hook that is run after an Org log buffer is created."
264 :group 'org
265 :version "24.1"
266 :type 'hook)
268 (defvar org-modules) ; defined below
269 (defvar org-modules-loaded nil
270 "Have the modules been loaded already?")
272 (defun org-load-modules-maybe (&optional force)
273 "Load all extensions listed in `org-modules'."
274 (when (or force (not org-modules-loaded))
275 (mapc (lambda (ext)
276 (condition-case nil (require ext)
277 (error (message "Problems while trying to load feature `%s'" ext))))
278 org-modules)
279 (setq org-modules-loaded t)))
281 (defun org-set-modules (var value)
282 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
283 (set var value)
284 (when (featurep 'org)
285 (org-load-modules-maybe 'force)))
287 (when (org-bound-and-true-p org-modules)
288 (let ((a (member 'org-infojs org-modules)))
289 (and a (setcar a 'org-jsinfo))))
291 (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)
292 "Modules that should always be loaded together with org.el.
293 If a description starts with <C>, the file is not part of Emacs
294 and loading it will require that you have downloaded and properly installed
295 the org-mode distribution.
297 You can also use this system to load external packages (i.e. neither Org
298 core modules, nor modules from the CONTRIB directory). Just add symbols
299 to the end of the list. If the package is called org-xyz.el, then you need
300 to add the symbol `xyz', and the package must have a call to
302 (provide 'org-xyz)"
303 :group 'org
304 :set 'org-set-modules
305 :type
306 '(set :greedy t
307 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
308 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
309 (const :tag " crypt: Encryption of subtrees" org-crypt)
310 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
311 (const :tag " docview: Links to doc-view buffers" org-docview)
312 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
313 (const :tag " id: Global IDs for identifying entries" org-id)
314 (const :tag " info: Links to Info nodes" org-info)
315 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
316 (const :tag " habit: Track your consistency with habits" org-habit)
317 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
318 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
319 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
320 (const :tag " mew Links to Mew folders/messages" org-mew)
321 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
322 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
323 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
324 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
325 (const :tag " vm: Links to VM folders/messages" org-vm)
326 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
327 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
328 (const :tag " mouse: Additional mouse support" org-mouse)
329 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
331 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
332 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
333 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
334 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
335 (const :tag "C collector: Collect properties into tables" org-collector)
336 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
337 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
338 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
339 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
340 (const :tag "C eval: Include command output as text" org-eval)
341 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
342 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
343 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
344 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
345 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
347 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
349 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
350 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
351 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
352 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
353 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
354 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
355 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
356 (const :tag "C mtags: Support for muse-like tags" org-mtags)
357 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
358 (const :tag "C registry: A registry for Org-mode links" org-registry)
359 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
360 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
361 (const :tag "C secretary: Team management with org-mode" org-secretary)
362 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
363 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
364 (const :tag "C track: Keep up with Org-mode development" org-track)
365 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
366 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
367 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
369 (defcustom org-support-shift-select nil
370 "Non-nil means make shift-cursor commands select text when possible.
372 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
373 start selecting a region, or enlarge regions started in this way.
374 In Org-mode, in special contexts, these same keys are used for
375 other purposes, important enough to compete with shift selection.
376 Org tries to balance these needs by supporting `shift-select-mode'
377 outside these special contexts, under control of this variable.
379 The default of this variable is nil, to avoid confusing behavior. Shifted
380 cursor keys will then execute Org commands in the following contexts:
381 - on a headline, changing TODO state (left/right) and priority (up/down)
382 - on a time stamp, changing the time
383 - in a plain list item, changing the bullet type
384 - in a property definition line, switching between allowed values
385 - in the BEGIN line of a clock table (changing the time block).
386 Outside these contexts, the commands will throw an error.
388 When this variable is t and the cursor is not in a special
389 context, Org-mode will support shift-selection for making and
390 enlarging regions. To make this more effective, the bullet
391 cycling will no longer happen anywhere in an item line, but only
392 if the cursor is exactly on the bullet.
394 If you set this variable to the symbol `always', then the keys
395 will not be special in headlines, property lines, and item lines,
396 to make shift selection work there as well. If this is what you
397 want, you can use the following alternative commands: `C-c C-t'
398 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
399 can be used to switch TODO sets, `C-c -' to cycle item bullet
400 types, and properties can be edited by hand or in column view.
402 However, when the cursor is on a timestamp, shift-cursor commands
403 will still edit the time stamp - this is just too good to give up.
405 XEmacs user should have this variable set to nil, because
406 `shift-select-mode' is in Emacs 23 or later only."
407 :group 'org
408 :type '(choice
409 (const :tag "Never" nil)
410 (const :tag "When outside special context" t)
411 (const :tag "Everywhere except timestamps" always)))
413 (defcustom org-loop-over-headlines-in-active-region nil
414 "Shall some commands act upon headlines in the active region?
416 When set to `t', some commands will be performed in all headlines
417 within the active region.
419 When set to `start-level', some commands will be performed in all
420 headlines within the active region, provided that these headlines
421 are of the same level than the first one.
423 When set to a string, those commands will be performed on the
424 matching headlines within the active region. Such string must be
425 a tags/property/todo match as it is used in the agenda tags view.
427 The list of commands is: `org-schedule', `org-deadline',
428 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
429 `org-archive-to-archive-sibling'. The archiving commands skip
430 already archived entries."
431 :type '(choice (const :tag "Don't loop" nil)
432 (const :tag "All headlines in active region" t)
433 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
434 (string :tag "Tags/Property/Todo matcher"))
435 :version "24.1"
436 :group 'org-todo
437 :group 'org-archive)
439 (defgroup org-startup nil
440 "Options concerning startup of Org-mode."
441 :tag "Org Startup"
442 :group 'org)
444 (defcustom org-startup-folded t
445 "Non-nil means entering Org-mode will switch to OVERVIEW.
446 This can also be configured on a per-file basis by adding one of
447 the following lines anywhere in the buffer:
449 #+STARTUP: fold (or `overview', this is equivalent)
450 #+STARTUP: nofold (or `showall', this is equivalent)
451 #+STARTUP: content
452 #+STARTUP: showeverything"
453 :group 'org-startup
454 :type '(choice
455 (const :tag "nofold: show all" nil)
456 (const :tag "fold: overview" t)
457 (const :tag "content: all headlines" content)
458 (const :tag "show everything, even drawers" showeverything)))
460 (defcustom org-startup-truncated t
461 "Non-nil means entering Org-mode will set `truncate-lines'.
462 This is useful since some lines containing links can be very long and
463 uninteresting. Also tables look terrible when wrapped."
464 :group 'org-startup
465 :type 'boolean)
467 (defcustom org-startup-indented nil
468 "Non-nil means turn on `org-indent-mode' on startup.
469 This can also be configured on a per-file basis by adding one of
470 the following lines anywhere in the buffer:
472 #+STARTUP: indent
473 #+STARTUP: noindent"
474 :group 'org-structure
475 :type '(choice
476 (const :tag "Not" nil)
477 (const :tag "Globally (slow on startup in large files)" t)))
479 (defcustom org-use-sub-superscripts t
480 "Non-nil means interpret \"_\" and \"^\" for export.
481 When this option is turned on, you can use TeX-like syntax for sub- and
482 superscripts. Several characters after \"_\" or \"^\" will be
483 considered as a single item - so grouping with {} is normally not
484 needed. For example, the following things will be parsed as single
485 sub- or superscripts.
487 10^24 or 10^tau several digits will be considered 1 item.
488 10^-12 or 10^-tau a leading sign with digits or a word
489 x^2-y^3 will be read as x^2 - y^3, because items are
490 terminated by almost any nonword/nondigit char.
491 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
493 Still, ambiguity is possible - so when in doubt use {} to enclose the
494 sub/superscript. If you set this variable to the symbol `{}',
495 the braces are *required* in order to trigger interpretations as
496 sub/superscript. This can be helpful in documents that need \"_\"
497 frequently in plain text.
499 Not all export backends support this, but HTML does.
501 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
502 :group 'org-startup
503 :group 'org-export-translation
504 :version "24.1"
505 :type '(choice
506 (const :tag "Always interpret" t)
507 (const :tag "Only with braces" {})
508 (const :tag "Never interpret" nil)))
510 (if (fboundp 'defvaralias)
511 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
514 (defcustom org-startup-with-beamer-mode nil
515 "Non-nil means turn on `org-beamer-mode' on startup.
516 This can also be configured on a per-file basis by adding one of
517 the following lines anywhere in the buffer:
519 #+STARTUP: beamer"
520 :group 'org-startup
521 :version "24.1"
522 :type 'boolean)
524 (defcustom org-startup-align-all-tables nil
525 "Non-nil means align all tables when visiting a file.
526 This is useful when the column width in tables is forced with <N> cookies
527 in table fields. Such tables will look correct only after the first re-align.
528 This can also be configured on a per-file basis by adding one of
529 the following lines anywhere in the buffer:
530 #+STARTUP: align
531 #+STARTUP: noalign"
532 :group 'org-startup
533 :type 'boolean)
535 (defcustom org-startup-with-inline-images nil
536 "Non-nil means show inline images when loading a new Org file.
537 This can also be configured on a per-file basis by adding one of
538 the following lines anywhere in the buffer:
539 #+STARTUP: inlineimages
540 #+STARTUP: noinlineimages"
541 :group 'org-startup
542 :version "24.1"
543 :type 'boolean)
545 (defcustom org-insert-mode-line-in-empty-file nil
546 "Non-nil means insert the first line setting Org-mode in empty files.
547 When the function `org-mode' is called interactively in an empty file, this
548 normally means that the file name does not automatically trigger Org-mode.
549 To ensure that the file will always be in Org-mode in the future, a
550 line enforcing Org-mode will be inserted into the buffer, if this option
551 has been set."
552 :group 'org-startup
553 :type 'boolean)
555 (defcustom org-replace-disputed-keys nil
556 "Non-nil means use alternative key bindings for some keys.
557 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
558 These keys are also used by other packages like shift-selection-mode'
559 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
560 If you want to use Org-mode together with one of these other modes,
561 or more generally if you would like to move some Org-mode commands to
562 other keys, set this variable and configure the keys with the variable
563 `org-disputed-keys'.
565 This option is only relevant at load-time of Org-mode, and must be set
566 *before* org.el is loaded. Changing it requires a restart of Emacs to
567 become effective."
568 :group 'org-startup
569 :type 'boolean)
571 (defcustom org-use-extra-keys nil
572 "Non-nil means use extra key sequence definitions for certain commands.
573 This happens automatically if you run XEmacs or if `window-system'
574 is nil. This variable lets you do the same manually. You must
575 set it before loading org.
577 Example: on Carbon Emacs 22 running graphically, with an external
578 keyboard on a Powerbook, the default way of setting M-left might
579 not work for either Alt or ESC. Setting this variable will make
580 it work for ESC."
581 :group 'org-startup
582 :type 'boolean)
584 (if (fboundp 'defvaralias)
585 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
587 (defcustom org-disputed-keys
588 '(([(shift up)] . [(meta p)])
589 ([(shift down)] . [(meta n)])
590 ([(shift left)] . [(meta -)])
591 ([(shift right)] . [(meta +)])
592 ([(control shift right)] . [(meta shift +)])
593 ([(control shift left)] . [(meta shift -)]))
594 "Keys for which Org-mode and other modes compete.
595 This is an alist, cars are the default keys, second element specifies
596 the alternative to use when `org-replace-disputed-keys' is t.
598 Keys can be specified in any syntax supported by `define-key'.
599 The value of this option takes effect only at Org-mode's startup,
600 therefore you'll have to restart Emacs to apply it after changing."
601 :group 'org-startup
602 :type 'alist)
604 (defun org-key (key)
605 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
606 Or return the original if not disputed.
607 Also apply the translations defined in `org-xemacs-key-equivalents'."
608 (when org-replace-disputed-keys
609 (let* ((nkey (key-description key))
610 (x (org-find-if (lambda (x)
611 (equal (key-description (car x)) nkey))
612 org-disputed-keys)))
613 (setq key (if x (cdr x) key))))
614 (when (featurep 'xemacs)
615 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
616 key)
618 (defun org-find-if (predicate seq)
619 (catch 'exit
620 (while seq
621 (if (funcall predicate (car seq))
622 (throw 'exit (car seq))
623 (pop seq)))))
625 (defun org-defkey (keymap key def)
626 "Define a key, possibly translated, as returned by `org-key'."
627 (define-key keymap (org-key key) def))
629 (defcustom org-ellipsis nil
630 "The ellipsis to use in the Org-mode outline.
631 When nil, just use the standard three dots. When a string, use that instead,
632 When a face, use the standard 3 dots, but with the specified face.
633 The change affects only Org-mode (which will then use its own display table).
634 Changing this requires executing `M-x org-mode' in a buffer to become
635 effective."
636 :group 'org-startup
637 :type '(choice (const :tag "Default" nil)
638 (face :tag "Face" :value org-warning)
639 (string :tag "String" :value "...#")))
641 (defvar org-display-table nil
642 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
644 (defgroup org-keywords nil
645 "Keywords in Org-mode."
646 :tag "Org Keywords"
647 :group 'org)
649 (defcustom org-deadline-string "DEADLINE:"
650 "String to mark deadline entries.
651 A deadline is this string, followed by a time stamp. Should be a word,
652 terminated by a colon. You can insert a schedule keyword and
653 a timestamp with \\[org-deadline].
654 Changes become only effective after restarting Emacs."
655 :group 'org-keywords
656 :type 'string)
658 (defcustom org-scheduled-string "SCHEDULED:"
659 "String to mark scheduled TODO entries.
660 A schedule is this string, followed by a time stamp. Should be a word,
661 terminated by a colon. You can insert a schedule keyword and
662 a timestamp with \\[org-schedule].
663 Changes become only effective after restarting Emacs."
664 :group 'org-keywords
665 :type 'string)
667 (defcustom org-closed-string "CLOSED:"
668 "String used as the prefix for timestamps logging closing a TODO entry."
669 :group 'org-keywords
670 :type 'string)
672 (defcustom org-clock-string "CLOCK:"
673 "String used as prefix for timestamps clocking work hours on an item."
674 :group 'org-keywords
675 :type 'string)
677 (defcustom org-comment-string "COMMENT"
678 "Entries starting with this keyword will never be exported.
679 An entry can be toggled between COMMENT and normal with
680 \\[org-toggle-comment].
681 Changes become only effective after restarting Emacs."
682 :group 'org-keywords
683 :type 'string)
685 (defcustom org-quote-string "QUOTE"
686 "Entries starting with this keyword will be exported in fixed-width font.
687 Quoting applies only to the text in the entry following the headline, and does
688 not extend beyond the next headline, even if that is lower level.
689 An entry can be toggled between QUOTE and normal with
690 \\[org-toggle-fixed-width-section]."
691 :group 'org-keywords
692 :type 'string)
694 (defconst org-repeat-re
695 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
696 "Regular expression for specifying repeated events.
697 After a match, group 1 contains the repeat expression.")
699 (defgroup org-structure nil
700 "Options concerning the general structure of Org-mode files."
701 :tag "Org Structure"
702 :group 'org)
704 (defgroup org-reveal-location nil
705 "Options about how to make context of a location visible."
706 :tag "Org Reveal Location"
707 :group 'org-structure)
709 (defconst org-context-choice
710 '(choice
711 (const :tag "Always" t)
712 (const :tag "Never" nil)
713 (repeat :greedy t :tag "Individual contexts"
714 (cons
715 (choice :tag "Context"
716 (const agenda)
717 (const org-goto)
718 (const occur-tree)
719 (const tags-tree)
720 (const link-search)
721 (const mark-goto)
722 (const bookmark-jump)
723 (const isearch)
724 (const default))
725 (boolean))))
726 "Contexts for the reveal options.")
728 (defcustom org-show-hierarchy-above '((default . t))
729 "Non-nil means show full hierarchy when revealing a location.
730 Org-mode often shows locations in an org-mode file which might have
731 been invisible before. When this is set, the hierarchy of headings
732 above the exposed location is shown.
733 Turning this off for example for sparse trees makes them very compact.
734 Instead of t, this can also be an alist specifying this option for different
735 contexts. Valid contexts are
736 agenda when exposing an entry from the agenda
737 org-goto when using the command `org-goto' on key C-c C-j
738 occur-tree when using the command `org-occur' on key C-c /
739 tags-tree when constructing a sparse tree based on tags matches
740 link-search when exposing search matches associated with a link
741 mark-goto when exposing the jump goal of a mark
742 bookmark-jump when exposing a bookmark location
743 isearch when exiting from an incremental search
744 default default for all contexts not set explicitly"
745 :group 'org-reveal-location
746 :type org-context-choice)
748 (defcustom org-show-following-heading '((default . nil))
749 "Non-nil means show following heading when revealing a location.
750 Org-mode often shows locations in an org-mode file which might have
751 been invisible before. When this is set, the heading following the
752 match is shown.
753 Turning this off for example for sparse trees makes them very compact,
754 but makes it harder to edit the location of the match. In such a case,
755 use the command \\[org-reveal] to show more context.
756 Instead of t, this can also be an alist specifying this option for different
757 contexts. See `org-show-hierarchy-above' for valid contexts."
758 :group 'org-reveal-location
759 :type org-context-choice)
761 (defcustom org-show-siblings '((default . nil) (isearch t))
762 "Non-nil means show all sibling heading when revealing a location.
763 Org-mode often shows locations in an org-mode file which might have
764 been invisible before. When this is set, the sibling of the current entry
765 heading are all made visible. If `org-show-hierarchy-above' is t,
766 the same happens on each level of the hierarchy above the current entry.
768 By default this is on for the isearch context, off for all other contexts.
769 Turning this off for example for sparse trees makes them very compact,
770 but makes it harder to edit the location of the match. In such a case,
771 use the command \\[org-reveal] to show more context.
772 Instead of t, this can also be an alist specifying this option for different
773 contexts. See `org-show-hierarchy-above' for valid contexts."
774 :group 'org-reveal-location
775 :type org-context-choice)
777 (defcustom org-show-entry-below '((default . nil))
778 "Non-nil means show the entry below a headline when revealing a location.
779 Org-mode often shows locations in an org-mode file which might have
780 been invisible before. When this is set, the text below the headline that is
781 exposed is also shown.
783 By default this is off for all contexts.
784 Instead of t, this can also be an alist specifying this option for different
785 contexts. See `org-show-hierarchy-above' for valid contexts."
786 :group 'org-reveal-location
787 :type org-context-choice)
789 (defcustom org-indirect-buffer-display 'other-window
790 "How should indirect tree buffers be displayed?
791 This applies to indirect buffers created with the commands
792 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
793 Valid values are:
794 current-window Display in the current window
795 other-window Just display in another window.
796 dedicated-frame Create one new frame, and re-use it each time.
797 new-frame Make a new frame each time. Note that in this case
798 previously-made indirect buffers are kept, and you need to
799 kill these buffers yourself."
800 :group 'org-structure
801 :group 'org-agenda-windows
802 :type '(choice
803 (const :tag "In current window" current-window)
804 (const :tag "In current frame, other window" other-window)
805 (const :tag "Each time a new frame" new-frame)
806 (const :tag "One dedicated frame" dedicated-frame)))
808 (defcustom org-use-speed-commands nil
809 "Non-nil means activate single letter commands at beginning of a headline.
810 This may also be a function to test for appropriate locations where speed
811 commands should be active."
812 :group 'org-structure
813 :type '(choice
814 (const :tag "Never" nil)
815 (const :tag "At beginning of headline stars" t)
816 (function)))
818 (defcustom org-speed-commands-user nil
819 "Alist of additional speed commands.
820 This list will be checked before `org-speed-commands-default'
821 when the variable `org-use-speed-commands' is non-nil
822 and when the cursor is at the beginning of a headline.
823 The car if each entry is a string with a single letter, which must
824 be assigned to `self-insert-command' in the global map.
825 The cdr is either a command to be called interactively, a function
826 to be called, or a form to be evaluated.
827 An entry that is just a list with a single string will be interpreted
828 as a descriptive headline that will be added when listing the speed
829 commands in the Help buffer using the `?' speed command."
830 :group 'org-structure
831 :type '(repeat :value ("k" . ignore)
832 (choice :value ("k" . ignore)
833 (list :tag "Descriptive Headline" (string :tag "Headline"))
834 (cons :tag "Letter and Command"
835 (string :tag "Command letter")
836 (choice
837 (function)
838 (sexp))))))
840 (defgroup org-cycle nil
841 "Options concerning visibility cycling in Org-mode."
842 :tag "Org Cycle"
843 :group 'org-structure)
845 (defcustom org-cycle-skip-children-state-if-no-children t
846 "Non-nil means skip CHILDREN state in entries that don't have any."
847 :group 'org-cycle
848 :type 'boolean)
850 (defcustom org-cycle-max-level nil
851 "Maximum level which should still be subject to visibility cycling.
852 Levels higher than this will, for cycling, be treated as text, not a headline.
853 When `org-odd-levels-only' is set, a value of N in this variable actually
854 means 2N-1 stars as the limiting headline.
855 When nil, cycle all levels.
856 Note that the limiting level of cycling is also influenced by
857 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
858 `org-inlinetask-min-level' is, cycling will be limited to levels one less
859 than its value."
860 :group 'org-cycle
861 :type '(choice
862 (const :tag "No limit" nil)
863 (integer :tag "Maximum level")))
865 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
866 "Names of drawers. Drawers are not opened by cycling on the headline above.
867 Drawers only open with a TAB on the drawer line itself. A drawer looks like
868 this:
869 :DRAWERNAME:
870 .....
871 :END:
872 The drawer \"PROPERTIES\" is special for capturing properties through
873 the property API.
875 Drawers can be defined on the per-file basis with a line like:
877 #+DRAWERS: HIDDEN STATE PROPERTIES"
878 :group 'org-structure
879 :group 'org-cycle
880 :type '(repeat (string :tag "Drawer Name")))
882 (defcustom org-hide-block-startup nil
883 "Non-nil means entering Org-mode will fold all blocks.
884 This can also be set in on a per-file basis with
886 #+STARTUP: hideblocks
887 #+STARTUP: showblocks"
888 :group 'org-startup
889 :group 'org-cycle
890 :type 'boolean)
892 (defcustom org-cycle-global-at-bob nil
893 "Cycle globally if cursor is at beginning of buffer and not at a headline.
894 This makes it possible to do global cycling without having to use S-TAB or
895 \\[universal-argument] TAB. For this special case to work, the first line \
896 of the buffer
897 must not be a headline - it may be empty or some other text. When used in
898 this way, `org-cycle-hook' is disables temporarily, to make sure the
899 cursor stays at the beginning of the buffer.
900 When this option is nil, don't do anything special at the beginning
901 of the buffer."
902 :group 'org-cycle
903 :type 'boolean)
905 (defcustom org-cycle-level-after-item/entry-creation t
906 "Non-nil means cycle entry level or item indentation in new empty entries.
908 When the cursor is at the end of an empty headline, i.e with only stars
909 and maybe a TODO keyword, TAB will then switch the entry to become a child,
910 and then all possible ancestor states, before returning to the original state.
911 This makes data entry extremely fast: M-RET to create a new headline,
912 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
914 When the cursor is at the end of an empty plain list item, one TAB will
915 make it a subitem, two or more tabs will back up to make this an item
916 higher up in the item hierarchy."
917 :group 'org-cycle
918 :type 'boolean)
920 (defcustom org-cycle-emulate-tab t
921 "Where should `org-cycle' emulate TAB.
922 nil Never
923 white Only in completely white lines
924 whitestart Only at the beginning of lines, before the first non-white char
925 t Everywhere except in headlines
926 exc-hl-bol Everywhere except at the start of a headline
927 If TAB is used in a place where it does not emulate TAB, the current subtree
928 visibility is cycled."
929 :group 'org-cycle
930 :type '(choice (const :tag "Never" nil)
931 (const :tag "Only in completely white lines" white)
932 (const :tag "Before first char in a line" whitestart)
933 (const :tag "Everywhere except in headlines" t)
934 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
937 (defcustom org-cycle-separator-lines 2
938 "Number of empty lines needed to keep an empty line between collapsed trees.
939 If you leave an empty line between the end of a subtree and the following
940 headline, this empty line is hidden when the subtree is folded.
941 Org-mode will leave (exactly) one empty line visible if the number of
942 empty lines is equal or larger to the number given in this variable.
943 So the default 2 means at least 2 empty lines after the end of a subtree
944 are needed to produce free space between a collapsed subtree and the
945 following headline.
947 If the number is negative, and the number of empty lines is at least -N,
948 all empty lines are shown.
950 Special case: when 0, never leave empty lines in collapsed view."
951 :group 'org-cycle
952 :type 'integer)
953 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
955 (defcustom org-pre-cycle-hook nil
956 "Hook that is run before visibility cycling is happening.
957 The function(s) in this hook must accept a single argument which indicates
958 the new state that will be set right after running this hook. The
959 argument is a symbol. Before a global state change, it can have the values
960 `overview', `content', or `all'. Before a local state change, it can have
961 the values `folded', `children', or `subtree'."
962 :group 'org-cycle
963 :type 'hook)
965 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
966 org-cycle-hide-drawers
967 org-cycle-show-empty-lines
968 org-optimize-window-after-visibility-change)
969 "Hook that is run after `org-cycle' has changed the buffer visibility.
970 The function(s) in this hook must accept a single argument which indicates
971 the new state that was set by the most recent `org-cycle' command. The
972 argument is a symbol. After a global state change, it can have the values
973 `overview', `content', or `all'. After a local state change, it can have
974 the values `folded', `children', or `subtree'."
975 :group 'org-cycle
976 :type 'hook)
978 (defgroup org-edit-structure nil
979 "Options concerning structure editing in Org-mode."
980 :tag "Org Edit Structure"
981 :group 'org-structure)
983 (defcustom org-odd-levels-only nil
984 "Non-nil means skip even levels and only use odd levels for the outline.
985 This has the effect that two stars are being added/taken away in
986 promotion/demotion commands. It also influences how levels are
987 handled by the exporters.
988 Changing it requires restart of `font-lock-mode' to become effective
989 for fontification also in regions already fontified.
990 You may also set this on a per-file basis by adding one of the following
991 lines to the buffer:
993 #+STARTUP: odd
994 #+STARTUP: oddeven"
995 :group 'org-edit-structure
996 :group 'org-appearance
997 :type 'boolean)
999 (defcustom org-adapt-indentation t
1000 "Non-nil means adapt indentation to outline node level.
1002 When this variable is set, Org assumes that you write outlines by
1003 indenting text in each node to align with the headline (after the stars).
1004 The following issues are influenced by this variable:
1006 - When this is set and the *entire* text in an entry is indented, the
1007 indentation is increased by one space in a demotion command, and
1008 decreased by one in a promotion command. If any line in the entry
1009 body starts with text at column 0, indentation is not changed at all.
1011 - Property drawers and planning information is inserted indented when
1012 this variable s set. When nil, they will not be indented.
1014 - TAB indents a line relative to context. The lines below a headline
1015 will be indented when this variable is set.
1017 Note that this is all about true indentation, by adding and removing
1018 space characters. See also `org-indent.el' which does level-dependent
1019 indentation in a virtual way, i.e. at display time in Emacs."
1020 :group 'org-edit-structure
1021 :type 'boolean)
1023 (defcustom org-special-ctrl-a/e nil
1024 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1026 When t, `C-a' will bring back the cursor to the beginning of the
1027 headline text, i.e. after the stars and after a possible TODO
1028 keyword. In an item, this will be the position after bullet and
1029 check-box, if any. When the cursor is already at that position,
1030 another `C-a' will bring it to the beginning of the line.
1032 `C-e' will jump to the end of the headline, ignoring the presence
1033 of tags in the headline. A second `C-e' will then jump to the
1034 true end of the line, after any tags. This also means that, when
1035 this variable is non-nil, `C-e' also will never jump beyond the
1036 end of the heading of a folded section, i.e. not after the
1037 ellipses.
1039 When set to the symbol `reversed', the first `C-a' or `C-e' works
1040 normally, going to the true line boundary first. Only a directly
1041 following, identical keypress will bring the cursor to the
1042 special positions.
1044 This may also be a cons cell where the behavior for `C-a' and
1045 `C-e' is set separately."
1046 :group 'org-edit-structure
1047 :type '(choice
1048 (const :tag "off" nil)
1049 (const :tag "on: after stars/bullet and before tags first" t)
1050 (const :tag "reversed: true line boundary first" reversed)
1051 (cons :tag "Set C-a and C-e separately"
1052 (choice :tag "Special C-a"
1053 (const :tag "off" nil)
1054 (const :tag "on: after stars/bullet first" t)
1055 (const :tag "reversed: before stars/bullet first" reversed))
1056 (choice :tag "Special C-e"
1057 (const :tag "off" nil)
1058 (const :tag "on: before tags first" t)
1059 (const :tag "reversed: after tags first" reversed)))))
1060 (if (fboundp 'defvaralias)
1061 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1063 (defcustom org-special-ctrl-k nil
1064 "Non-nil means `C-k' will behave specially in headlines.
1065 When nil, `C-k' will call the default `kill-line' command.
1066 When t, the following will happen while the cursor is in the headline:
1068 - When the cursor is at the beginning of a headline, kill the entire
1069 line and possible the folded subtree below the line.
1070 - When in the middle of the headline text, kill the headline up to the tags.
1071 - When after the headline text, kill the tags."
1072 :group 'org-edit-structure
1073 :type 'boolean)
1075 (defcustom org-ctrl-k-protect-subtree nil
1076 "Non-nil means, do not delete a hidden subtree with C-k.
1077 When set to the symbol `error', simply throw an error when C-k is
1078 used to kill (part-of) a headline that has hidden text behind it.
1079 Any other non-nil value will result in a query to the user, if it is
1080 OK to kill that hidden subtree. When nil, kill without remorse."
1081 :group 'org-edit-structure
1082 :version "24.1"
1083 :type '(choice
1084 (const :tag "Do not protect hidden subtrees" nil)
1085 (const :tag "Protect hidden subtrees with a security query" t)
1086 (const :tag "Never kill a hidden subtree with C-k" error)))
1088 (defcustom org-catch-invisible-edits nil
1089 "Check if in invisible region before inserting or deleting a character.
1090 Valid values are:
1092 nil Do not check, so just do invisible edits.
1093 error Throw an error and do nothing.
1094 show Make point visible, and do the requested edit.
1095 show-and-error Make point visible, then throw an error and abort the edit.
1096 smart Make point visible, and do insertion/deletion if it is
1097 adjacent to visible text and the change feels predictable.
1098 Never delete a previously invisible character or add in the
1099 middle or right after an invisible region. Basically, this
1100 allows insertion and backward-delete right before ellipses.
1101 FIXME: maybe in this case we should not even show?"
1102 :group 'org-edit-structure
1103 :version "24.1"
1104 :type '(choice
1105 (const :tag "Do not check" nil)
1106 (const :tag "Throw error when trying to edit" error)
1107 (const :tag "Unhide, but do not do the edit" show-and-error)
1108 (const :tag "Show invisible part and do the edit" show)
1109 (const :tag "Be smart and do the right thing" smart)))
1111 (defcustom org-yank-folded-subtrees t
1112 "Non-nil means when yanking subtrees, fold them.
1113 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1114 it starts with a heading and all other headings in it are either children
1115 or siblings, then fold all the subtrees. However, do this only if no
1116 text after the yank would be swallowed into a folded tree by this action."
1117 :group 'org-edit-structure
1118 :type 'boolean)
1120 (defcustom org-yank-adjusted-subtrees nil
1121 "Non-nil means when yanking subtrees, adjust the level.
1122 With this setting, `org-paste-subtree' is used to insert the subtree, see
1123 this function for details."
1124 :group 'org-edit-structure
1125 :type 'boolean)
1127 (defcustom org-M-RET-may-split-line '((default . t))
1128 "Non-nil means M-RET will split the line at the cursor position.
1129 When nil, it will go to the end of the line before making a
1130 new line.
1131 You may also set this option in a different way for different
1132 contexts. Valid contexts are:
1134 headline when creating a new headline
1135 item when creating a new item
1136 table in a table field
1137 default the value to be used for all contexts not explicitly
1138 customized"
1139 :group 'org-structure
1140 :group 'org-table
1141 :type '(choice
1142 (const :tag "Always" t)
1143 (const :tag "Never" nil)
1144 (repeat :greedy t :tag "Individual contexts"
1145 (cons
1146 (choice :tag "Context"
1147 (const headline)
1148 (const item)
1149 (const table)
1150 (const default))
1151 (boolean)))))
1154 (defcustom org-insert-heading-respect-content nil
1155 "Non-nil means insert new headings after the current subtree.
1156 When nil, the new heading is created directly after the current line.
1157 The commands \\[org-insert-heading-respect-content] and
1158 \\[org-insert-todo-heading-respect-content] turn this variable on
1159 for the duration of the command."
1160 :group 'org-structure
1161 :type 'boolean)
1163 (defcustom org-blank-before-new-entry '((heading . auto)
1164 (plain-list-item . auto))
1165 "Should `org-insert-heading' leave a blank line before new heading/item?
1166 The value is an alist, with `heading' and `plain-list-item' as CAR,
1167 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1168 which case Org will look at the surrounding headings/items and try to
1169 make an intelligent decision whether to insert a blank line or not.
1171 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1172 set, the setting here is ignored and no empty line is inserted, to avoid
1173 breaking the list structure."
1174 :group 'org-edit-structure
1175 :type '(list
1176 (cons (const heading)
1177 (choice (const :tag "Never" nil)
1178 (const :tag "Always" t)
1179 (const :tag "Auto" auto)))
1180 (cons (const plain-list-item)
1181 (choice (const :tag "Never" nil)
1182 (const :tag "Always" t)
1183 (const :tag "Auto" auto)))))
1185 (defcustom org-insert-heading-hook nil
1186 "Hook being run after inserting a new heading."
1187 :group 'org-edit-structure
1188 :type 'hook)
1190 (defcustom org-enable-fixed-width-editor t
1191 "Non-nil means lines starting with \":\" are treated as fixed-width.
1192 This currently only means they are never auto-wrapped.
1193 When nil, such lines will be treated like ordinary lines.
1194 See also the QUOTE keyword."
1195 :group 'org-edit-structure
1196 :type 'boolean)
1198 (defcustom org-goto-auto-isearch t
1199 "Non-nil means typing characters in `org-goto' starts incremental search."
1200 :group 'org-edit-structure
1201 :type 'boolean)
1203 (defgroup org-sparse-trees nil
1204 "Options concerning sparse trees in Org-mode."
1205 :tag "Org Sparse Trees"
1206 :group 'org-structure)
1208 (defcustom org-highlight-sparse-tree-matches t
1209 "Non-nil means highlight all matches that define a sparse tree.
1210 The highlights will automatically disappear the next time the buffer is
1211 changed by an edit command."
1212 :group 'org-sparse-trees
1213 :type 'boolean)
1215 (defcustom org-remove-highlights-with-change t
1216 "Non-nil means any change to the buffer will remove temporary highlights.
1217 Such highlights are created by `org-occur' and `org-clock-display'.
1218 When nil, `C-c C-c needs to be used to get rid of the highlights.
1219 The highlights created by `org-preview-latex-fragment' always need
1220 `C-c C-c' to be removed."
1221 :group 'org-sparse-trees
1222 :group 'org-time
1223 :type 'boolean)
1226 (defcustom org-occur-hook '(org-first-headline-recenter)
1227 "Hook that is run after `org-occur' has constructed a sparse tree.
1228 This can be used to recenter the window to show as much of the structure
1229 as possible."
1230 :group 'org-sparse-trees
1231 :type 'hook)
1233 (defgroup org-imenu-and-speedbar nil
1234 "Options concerning imenu and speedbar in Org-mode."
1235 :tag "Org Imenu and Speedbar"
1236 :group 'org-structure)
1238 (defcustom org-imenu-depth 2
1239 "The maximum level for Imenu access to Org-mode headlines.
1240 This also applied for speedbar access."
1241 :group 'org-imenu-and-speedbar
1242 :type 'integer)
1244 (defgroup org-table nil
1245 "Options concerning tables in Org-mode."
1246 :tag "Org Table"
1247 :group 'org)
1249 (defcustom org-enable-table-editor 'optimized
1250 "Non-nil means lines starting with \"|\" are handled by the table editor.
1251 When nil, such lines will be treated like ordinary lines.
1253 When equal to the symbol `optimized', the table editor will be optimized to
1254 do the following:
1255 - Automatic overwrite mode in front of whitespace in table fields.
1256 This makes the structure of the table stay in tact as long as the edited
1257 field does not exceed the column width.
1258 - Minimize the number of realigns. Normally, the table is aligned each time
1259 TAB or RET are pressed to move to another field. With optimization this
1260 happens only if changes to a field might have changed the column width.
1261 Optimization requires replacing the functions `self-insert-command',
1262 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1263 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1264 very good at guessing when a re-align will be necessary, but you can always
1265 force one with \\[org-ctrl-c-ctrl-c].
1267 If you would like to use the optimized version in Org-mode, but the
1268 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1270 This variable can be used to turn on and off the table editor during a session,
1271 but in order to toggle optimization, a restart is required.
1273 See also the variable `org-table-auto-blank-field'."
1274 :group 'org-table
1275 :type '(choice
1276 (const :tag "off" nil)
1277 (const :tag "on" t)
1278 (const :tag "on, optimized" optimized)))
1280 (defcustom org-self-insert-cluster-for-undo t
1281 "Non-nil means cluster self-insert commands for undo when possible.
1282 If this is set, then, like in the Emacs command loop, 20 consecutive
1283 characters will be undone together.
1284 This is configurable, because there is some impact on typing performance."
1285 :group 'org-table
1286 :type 'boolean)
1288 (defcustom org-table-tab-recognizes-table.el t
1289 "Non-nil means TAB will automatically notice a table.el table.
1290 When it sees such a table, it moves point into it and - if necessary -
1291 calls `table-recognize-table'."
1292 :group 'org-table-editing
1293 :type 'boolean)
1295 (defgroup org-link nil
1296 "Options concerning links in Org-mode."
1297 :tag "Org Link"
1298 :group 'org)
1300 (defvar org-link-abbrev-alist-local nil
1301 "Buffer-local version of `org-link-abbrev-alist', which see.
1302 The value of this is taken from the #+LINK lines.")
1303 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1305 (defcustom org-link-abbrev-alist nil
1306 "Alist of link abbreviations.
1307 The car of each element is a string, to be replaced at the start of a link.
1308 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1309 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1311 [[linkkey:tag][description]]
1313 The 'linkkey' must be a word word, starting with a letter, followed
1314 by letters, numbers, '-' or '_'.
1316 If REPLACE is a string, the tag will simply be appended to create the link.
1317 If the string contains \"%s\", the tag will be inserted there. If the string
1318 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1319 at that point (see the function `url-hexify-string'). If the string contains
1320 the specifier \"%(my-function)\", then the custom function `my-function' will
1321 be invoked: this function takes the tag as its only argument and must return
1322 a string.
1324 REPLACE may also be a function that will be called with the tag as the
1325 only argument to create the link, which should be returned as a string.
1327 See the manual for examples."
1328 :group 'org-link
1329 :type '(repeat
1330 (cons
1331 (string :tag "Protocol")
1332 (choice
1333 (string :tag "Format")
1334 (function)))))
1336 (defcustom org-descriptive-links t
1337 "Non-nil means Org will display descriptive links.
1338 E.g. [[http://orgmode.org][Org website]] will be displayed as
1339 \"Org Website\", hiding the link itself and just displaying its
1340 description. When set to `nil', Org will display the full links
1341 literally.
1343 You can interactively set the value of this variable by calling
1344 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1345 :group 'org-link
1346 :type 'boolean)
1348 (defcustom org-link-file-path-type 'adaptive
1349 "How the path name in file links should be stored.
1350 Valid values are:
1352 relative Relative to the current directory, i.e. the directory of the file
1353 into which the link is being inserted.
1354 absolute Absolute path, if possible with ~ for home directory.
1355 noabbrev Absolute path, no abbreviation of home directory.
1356 adaptive Use relative path for files in the current directory and sub-
1357 directories of it. For other files, use an absolute path."
1358 :group 'org-link
1359 :type '(choice
1360 (const relative)
1361 (const absolute)
1362 (const noabbrev)
1363 (const adaptive)))
1365 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1366 "Types of links that should be activated in Org-mode files.
1367 This is a list of symbols, each leading to the activation of a certain link
1368 type. In principle, it does not hurt to turn on most link types - there may
1369 be a small gain when turning off unused link types. The types are:
1371 bracket The recommended [[link][description]] or [[link]] links with hiding.
1372 angle Links in angular brackets that may contain whitespace like
1373 <bbdb:Carsten Dominik>.
1374 plain Plain links in normal text, no whitespace, like http://google.com.
1375 radio Text that is matched by a radio target, see manual for details.
1376 tag Tag settings in a headline (link to tag search).
1377 date Time stamps (link to calendar).
1378 footnote Footnote labels.
1380 Changing this variable requires a restart of Emacs to become effective."
1381 :group 'org-link
1382 :type '(set :greedy t
1383 (const :tag "Double bracket links" bracket)
1384 (const :tag "Angular bracket links" angle)
1385 (const :tag "Plain text links" plain)
1386 (const :tag "Radio target matches" radio)
1387 (const :tag "Tags" tag)
1388 (const :tag "Timestamps" date)
1389 (const :tag "Footnotes" footnote)))
1391 (defcustom org-make-link-description-function nil
1392 "Function to use to generate link descriptions from links.
1393 If nil the link location will be used. This function must take
1394 two parameters; the first is the link and the second the
1395 description `org-insert-link' has generated, and should return the
1396 description to use."
1397 :group 'org-link
1398 :type 'function)
1400 (defgroup org-link-store nil
1401 "Options concerning storing links in Org-mode."
1402 :tag "Org Store Link"
1403 :group 'org-link)
1405 (defcustom org-email-link-description-format "Email %c: %.30s"
1406 "Format of the description part of a link to an email or usenet message.
1407 The following %-escapes will be replaced by corresponding information:
1409 %F full \"From\" field
1410 %f name, taken from \"From\" field, address if no name
1411 %T full \"To\" field
1412 %t first name in \"To\" field, address if no name
1413 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1414 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1415 %s subject
1416 %d date
1417 %m message-id.
1419 You may use normal field width specification between the % and the letter.
1420 This is for example useful to limit the length of the subject.
1422 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1423 :group 'org-link-store
1424 :type 'string)
1426 (defcustom org-from-is-user-regexp
1427 (let (r1 r2)
1428 (when (and user-mail-address (not (string= user-mail-address "")))
1429 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1430 (when (and user-full-name (not (string= user-full-name "")))
1431 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1432 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1433 "Regexp matched against the \"From:\" header of an email or usenet message.
1434 It should match if the message is from the user him/herself."
1435 :group 'org-link-store
1436 :type 'regexp)
1438 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1439 "Non-nil means storing a link to an Org file will use entry IDs.
1441 Note that before this variable is even considered, org-id must be loaded,
1442 so please customize `org-modules' and turn it on.
1444 The variable can have the following values:
1446 t Create an ID if needed to make a link to the current entry.
1448 create-if-interactive
1449 If `org-store-link' is called directly (interactively, as a user
1450 command), do create an ID to support the link. But when doing the
1451 job for remember, only use the ID if it already exists. The
1452 purpose of this setting is to avoid proliferation of unwanted
1453 IDs, just because you happen to be in an Org file when you
1454 call `org-remember' that automatically and preemptively
1455 creates a link. If you do want to get an ID link in a remember
1456 template to an entry not having an ID, create it first by
1457 explicitly creating a link to it, using `C-c C-l' first.
1459 create-if-interactive-and-no-custom-id
1460 Like create-if-interactive, but do not create an ID if there is
1461 a CUSTOM_ID property defined in the entry. This is the default.
1463 use-existing
1464 Use existing ID, do not create one.
1466 nil Never use an ID to make a link, instead link using a text search for
1467 the headline text."
1468 :group 'org-link-store
1469 :type '(choice
1470 (const :tag "Create ID to make link" t)
1471 (const :tag "Create if storing link interactively"
1472 create-if-interactive)
1473 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1474 create-if-interactive-and-no-custom-id)
1475 (const :tag "Only use existing" use-existing)
1476 (const :tag "Do not use ID to create link" nil)))
1478 (defcustom org-context-in-file-links t
1479 "Non-nil means file links from `org-store-link' contain context.
1480 A search string will be added to the file name with :: as separator and
1481 used to find the context when the link is activated by the command
1482 `org-open-at-point'. When this option is t, the entire active region
1483 will be placed in the search string of the file link. If set to a
1484 positive integer, only the first n lines of context will be stored.
1486 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1487 negates this setting for the duration of the command."
1488 :group 'org-link-store
1489 :type '(choice boolean integer))
1491 (defcustom org-keep-stored-link-after-insertion nil
1492 "Non-nil means keep link in list for entire session.
1494 The command `org-store-link' adds a link pointing to the current
1495 location to an internal list. These links accumulate during a session.
1496 The command `org-insert-link' can be used to insert links into any
1497 Org-mode file (offering completion for all stored links). When this
1498 option is nil, every link which has been inserted once using \\[org-insert-link]
1499 will be removed from the list, to make completing the unused links
1500 more efficient."
1501 :group 'org-link-store
1502 :type 'boolean)
1504 (defgroup org-link-follow nil
1505 "Options concerning following links in Org-mode."
1506 :tag "Org Follow Link"
1507 :group 'org-link)
1509 (defcustom org-link-translation-function nil
1510 "Function to translate links with different syntax to Org syntax.
1511 This can be used to translate links created for example by the Planner
1512 or emacs-wiki packages to Org syntax.
1513 The function must accept two parameters, a TYPE containing the link
1514 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1515 which is everything after the link protocol. It should return a cons
1516 with possibly modified values of type and path.
1517 Org contains a function for this, so if you set this variable to
1518 `org-translate-link-from-planner', you should be able follow many
1519 links created by planner."
1520 :group 'org-link-follow
1521 :type 'function)
1523 (defcustom org-follow-link-hook nil
1524 "Hook that is run after a link has been followed."
1525 :group 'org-link-follow
1526 :type 'hook)
1528 (defcustom org-tab-follows-link nil
1529 "Non-nil means on links TAB will follow the link.
1530 Needs to be set before org.el is loaded.
1531 This really should not be used, it does not make sense, and the
1532 implementation is bad."
1533 :group 'org-link-follow
1534 :type 'boolean)
1536 (defcustom org-return-follows-link nil
1537 "Non-nil means on links RET will follow the link."
1538 :group 'org-link-follow
1539 :type 'boolean)
1541 (defcustom org-mouse-1-follows-link
1542 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1543 "Non-nil means mouse-1 on a link will follow the link.
1544 A longer mouse click will still set point. Does not work on XEmacs.
1545 Needs to be set before org.el is loaded."
1546 :group 'org-link-follow
1547 :type 'boolean)
1549 (defcustom org-mark-ring-length 4
1550 "Number of different positions to be recorded in the ring.
1551 Changing this requires a restart of Emacs to work correctly."
1552 :group 'org-link-follow
1553 :type 'integer)
1555 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1556 "Non-nil means internal links in Org files must exactly match a headline.
1557 When nil, the link search tries to match a phrase with all words
1558 in the search text."
1559 :group 'org-link-follow
1560 :version "24.1"
1561 :type '(choice
1562 (const :tag "Use fuzzy text search" nil)
1563 (const :tag "Match only exact headline" t)
1564 (const :tag "Match exact headline or query to create it"
1565 query-to-create)))
1567 (defcustom org-link-frame-setup
1568 '((vm . vm-visit-folder-other-frame)
1569 (vm-imap . vm-visit-imap-folder-other-frame)
1570 (gnus . org-gnus-no-new-news)
1571 (file . find-file-other-window)
1572 (wl . wl-other-frame))
1573 "Setup the frame configuration for following links.
1574 When following a link with Emacs, it may often be useful to display
1575 this link in another window or frame. This variable can be used to
1576 set this up for the different types of links.
1577 For VM, use any of
1578 `vm-visit-folder'
1579 `vm-visit-folder-other-window'
1580 `vm-visit-folder-other-frame'
1581 For Gnus, use any of
1582 `gnus'
1583 `gnus-other-frame'
1584 `org-gnus-no-new-news'
1585 For FILE, use any of
1586 `find-file'
1587 `find-file-other-window'
1588 `find-file-other-frame'
1589 For Wanderlust use any of
1590 `wl'
1591 `wl-other-frame'
1592 For the calendar, use the variable `calendar-setup'.
1593 For BBDB, it is currently only possible to display the matches in
1594 another window."
1595 :group 'org-link-follow
1596 :type '(list
1597 (cons (const vm)
1598 (choice
1599 (const vm-visit-folder)
1600 (const vm-visit-folder-other-window)
1601 (const vm-visit-folder-other-frame)))
1602 (cons (const gnus)
1603 (choice
1604 (const gnus)
1605 (const gnus-other-frame)
1606 (const org-gnus-no-new-news)))
1607 (cons (const file)
1608 (choice
1609 (const find-file)
1610 (const find-file-other-window)
1611 (const find-file-other-frame)))
1612 (cons (const wl)
1613 (choice
1614 (const wl)
1615 (const wl-other-frame)))))
1617 (defcustom org-display-internal-link-with-indirect-buffer nil
1618 "Non-nil means use indirect buffer to display infile links.
1619 Activating internal links (from one location in a file to another location
1620 in the same file) normally just jumps to the location. When the link is
1621 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1622 is displayed in
1623 another window. When this option is set, the other window actually displays
1624 an indirect buffer clone of the current buffer, to avoid any visibility
1625 changes to the current buffer."
1626 :group 'org-link-follow
1627 :type 'boolean)
1629 (defcustom org-open-non-existing-files nil
1630 "Non-nil means `org-open-file' will open non-existing files.
1631 When nil, an error will be generated.
1632 This variable applies only to external applications because they
1633 might choke on non-existing files. If the link is to a file that
1634 will be opened in Emacs, the variable is ignored."
1635 :group 'org-link-follow
1636 :type 'boolean)
1638 (defcustom org-open-directory-means-index-dot-org nil
1639 "Non-nil means a link to a directory really means to index.org.
1640 When nil, following a directory link will run dired or open a finder/explorer
1641 window on that directory."
1642 :group 'org-link-follow
1643 :type 'boolean)
1645 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1646 "Function and arguments to call for following mailto links.
1647 This is a list with the first element being a Lisp function, and the
1648 remaining elements being arguments to the function. In string arguments,
1649 %a will be replaced by the address, and %s will be replaced by the subject
1650 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1651 :group 'org-link-follow
1652 :type '(choice
1653 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1654 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1655 (const :tag "message-mail" (message-mail "%a" "%s"))
1656 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1658 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1659 "Non-nil means ask for confirmation before executing shell links.
1660 Shell links can be dangerous: just think about a link
1662 [[shell:rm -rf ~/*][Google Search]]
1664 This link would show up in your Org-mode document as \"Google Search\",
1665 but really it would remove your entire home directory.
1666 Therefore we advise against setting this variable to nil.
1667 Just change it to `y-or-n-p' if you want to confirm with a
1668 single keystroke rather than having to type \"yes\"."
1669 :group 'org-link-follow
1670 :type '(choice
1671 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1672 (const :tag "with y-or-n (faster)" y-or-n-p)
1673 (const :tag "no confirmation (dangerous)" nil)))
1674 (put 'org-confirm-shell-link-function
1675 'safe-local-variable
1676 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1678 (defcustom org-confirm-shell-link-not-regexp ""
1679 "A regexp to skip confirmation for shell links."
1680 :group 'org-link-follow
1681 :version "24.1"
1682 :type 'regexp)
1684 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1685 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1686 Elisp links can be dangerous: just think about a link
1688 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1690 This link would show up in your Org-mode document as \"Google Search\",
1691 but really it would remove your entire home directory.
1692 Therefore we advise against setting this variable to nil.
1693 Just change it to `y-or-n-p' if you want to confirm with a
1694 single keystroke rather than having to type \"yes\"."
1695 :group 'org-link-follow
1696 :type '(choice
1697 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1698 (const :tag "with y-or-n (faster)" y-or-n-p)
1699 (const :tag "no confirmation (dangerous)" nil)))
1700 (put 'org-confirm-shell-link-function
1701 'safe-local-variable
1702 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1704 (defcustom org-confirm-elisp-link-not-regexp ""
1705 "A regexp to skip confirmation for Elisp links."
1706 :group 'org-link-follow
1707 :version "24.1"
1708 :type 'regexp)
1710 (defconst org-file-apps-defaults-gnu
1711 '((remote . emacs)
1712 (system . mailcap)
1713 (t . mailcap))
1714 "Default file applications on a UNIX or GNU/Linux system.
1715 See `org-file-apps'.")
1717 (defconst org-file-apps-defaults-macosx
1718 '((remote . emacs)
1719 (t . "open %s")
1720 (system . "open %s")
1721 ("ps.gz" . "gv %s")
1722 ("eps.gz" . "gv %s")
1723 ("dvi" . "xdvi %s")
1724 ("fig" . "xfig %s"))
1725 "Default file applications on a MacOS X system.
1726 The system \"open\" is known as a default, but we use X11 applications
1727 for some files for which the OS does not have a good default.
1728 See `org-file-apps'.")
1730 (defconst org-file-apps-defaults-windowsnt
1731 (list
1732 '(remote . emacs)
1733 (cons t
1734 (list (if (featurep 'xemacs)
1735 'mswindows-shell-execute
1736 'w32-shell-execute)
1737 "open" 'file))
1738 (cons 'system
1739 (list (if (featurep 'xemacs)
1740 'mswindows-shell-execute
1741 'w32-shell-execute)
1742 "open" 'file)))
1743 "Default file applications on a Windows NT system.
1744 The system \"open\" is used for most files.
1745 See `org-file-apps'.")
1747 (defcustom org-file-apps
1749 (auto-mode . emacs)
1750 ("\\.mm\\'" . default)
1751 ("\\.x?html?\\'" . default)
1752 ("\\.pdf\\'" . default)
1754 "External applications for opening `file:path' items in a document.
1755 Org-mode uses system defaults for different file types, but
1756 you can use this variable to set the application for a given file
1757 extension. The entries in this list are cons cells where the car identifies
1758 files and the cdr the corresponding command. Possible values for the
1759 file identifier are
1760 \"string\" A string as a file identifier can be interpreted in different
1761 ways, depending on its contents:
1763 - Alphanumeric characters only:
1764 Match links with this file extension.
1765 Example: (\"pdf\" . \"evince %s\")
1766 to open PDFs with evince.
1768 - Regular expression: Match links where the
1769 filename matches the regexp. If you want to
1770 use groups here, use shy groups.
1772 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1773 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1774 to open *.html and *.xhtml with firefox.
1776 - Regular expression which contains (non-shy) groups:
1777 Match links where the whole link, including \"::\", and
1778 anything after that, matches the regexp.
1779 In a custom command string, %1, %2, etc. are replaced with
1780 the parts of the link that were matched by the groups.
1781 For backwards compatibility, if a command string is given
1782 that does not use any of the group matches, this case is
1783 handled identically to the second one (i.e. match against
1784 file name only).
1785 In a custom lisp form, you can access the group matches with
1786 (match-string n link).
1788 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1789 to open [[file:document.pdf::5]] with evince at page 5.
1791 `directory' Matches a directory
1792 `remote' Matches a remote file, accessible through tramp or efs.
1793 Remote files most likely should be visited through Emacs
1794 because external applications cannot handle such paths.
1795 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1796 so all files Emacs knows how to handle. Using this with
1797 command `emacs' will open most files in Emacs. Beware that this
1798 will also open html files inside Emacs, unless you add
1799 (\"html\" . default) to the list as well.
1800 t Default for files not matched by any of the other options.
1801 `system' The system command to open files, like `open' on Windows
1802 and Mac OS X, and mailcap under GNU/Linux. This is the command
1803 that will be selected if you call `C-c C-o' with a double
1804 \\[universal-argument] \\[universal-argument] prefix.
1806 Possible values for the command are:
1807 `emacs' The file will be visited by the current Emacs process.
1808 `default' Use the default application for this file type, which is the
1809 association for t in the list, most likely in the system-specific
1810 part.
1811 This can be used to overrule an unwanted setting in the
1812 system-specific variable.
1813 `system' Use the system command for opening files, like \"open\".
1814 This command is specified by the entry whose car is `system'.
1815 Most likely, the system-specific version of this variable
1816 does define this command, but you can overrule/replace it
1817 here.
1818 string A command to be executed by a shell; %s will be replaced
1819 by the path to the file.
1820 sexp A Lisp form which will be evaluated. The file path will
1821 be available in the Lisp variable `file'.
1822 For more examples, see the system specific constants
1823 `org-file-apps-defaults-macosx'
1824 `org-file-apps-defaults-windowsnt'
1825 `org-file-apps-defaults-gnu'."
1826 :group 'org-link-follow
1827 :type '(repeat
1828 (cons (choice :value ""
1829 (string :tag "Extension")
1830 (const :tag "System command to open files" system)
1831 (const :tag "Default for unrecognized files" t)
1832 (const :tag "Remote file" remote)
1833 (const :tag "Links to a directory" directory)
1834 (const :tag "Any files that have Emacs modes"
1835 auto-mode))
1836 (choice :value ""
1837 (const :tag "Visit with Emacs" emacs)
1838 (const :tag "Use default" default)
1839 (const :tag "Use the system command" system)
1840 (string :tag "Command")
1841 (sexp :tag "Lisp form")))))
1843 (defcustom org-doi-server-url "http://dx.doi.org/"
1844 "The URL of the DOI server."
1845 :type 'string
1846 :version "24.2"
1847 :group 'org-link-follow)
1849 (defgroup org-refile nil
1850 "Options concerning refiling entries in Org-mode."
1851 :tag "Org Refile"
1852 :group 'org)
1854 (defcustom org-directory "~/org"
1855 "Directory with org files.
1856 This is just a default location to look for Org files. There is no need
1857 at all to put your files into this directory. It is only used in the
1858 following situations:
1860 1. When a remember template specifies a target file that is not an
1861 absolute path. The path will then be interpreted relative to
1862 `org-directory'
1863 2. When a remember note is filed away in an interactive way (when exiting the
1864 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1865 with `org-directory' as the default path."
1866 :group 'org-refile
1867 :group 'org-remember
1868 :type 'directory)
1870 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1871 "Default target for storing notes.
1872 Used as a fall back file for org-remember.el and org-capture.el, for
1873 templates that do not specify a target file."
1874 :group 'org-refile
1875 :group 'org-remember
1876 :type '(choice
1877 (const :tag "Default from remember-data-file" nil)
1878 file))
1880 (defcustom org-goto-interface 'outline
1881 "The default interface to be used for `org-goto'.
1882 Allowed values are:
1883 outline The interface shows an outline of the relevant file
1884 and the correct heading is found by moving through
1885 the outline or by searching with incremental search.
1886 outline-path-completion Headlines in the current buffer are offered via
1887 completion. This is the interface also used by
1888 the refile command."
1889 :group 'org-refile
1890 :type '(choice
1891 (const :tag "Outline" outline)
1892 (const :tag "Outline-path-completion" outline-path-completion)))
1894 (defcustom org-goto-max-level 5
1895 "Maximum target level when running `org-goto' with refile interface."
1896 :group 'org-refile
1897 :type 'integer)
1899 (defcustom org-reverse-note-order nil
1900 "Non-nil means store new notes at the beginning of a file or entry.
1901 When nil, new notes will be filed to the end of a file or entry.
1902 This can also be a list with cons cells of regular expressions that
1903 are matched against file names, and values."
1904 :group 'org-remember
1905 :group 'org-refile
1906 :type '(choice
1907 (const :tag "Reverse always" t)
1908 (const :tag "Reverse never" nil)
1909 (repeat :tag "By file name regexp"
1910 (cons regexp boolean))))
1912 (defcustom org-log-refile nil
1913 "Information to record when a task is refiled.
1915 Possible values are:
1917 nil Don't add anything
1918 time Add a time stamp to the task
1919 note Prompt for a note and add it with template `org-log-note-headings'
1921 This option can also be set with on a per-file-basis with
1923 #+STARTUP: nologrefile
1924 #+STARTUP: logrefile
1925 #+STARTUP: lognoterefile
1927 You can have local logging settings for a subtree by setting the LOGGING
1928 property to one or more of these keywords.
1930 When bulk-refiling from the agenda, the value `note' is forbidden and
1931 will temporarily be changed to `time'."
1932 :group 'org-refile
1933 :group 'org-progress
1934 :version "24.1"
1935 :type '(choice
1936 (const :tag "No logging" nil)
1937 (const :tag "Record timestamp" time)
1938 (const :tag "Record timestamp with note." note)))
1940 (defcustom org-refile-targets nil
1941 "Targets for refiling entries with \\[org-refile].
1942 This is a list of cons cells. Each cell contains:
1943 - a specification of the files to be considered, either a list of files,
1944 or a symbol whose function or variable value will be used to retrieve
1945 a file name or a list of file names. If you use `org-agenda-files' for
1946 that, all agenda files will be scanned for targets. Nil means consider
1947 headings in the current buffer.
1948 - A specification of how to find candidate refile targets. This may be
1949 any of:
1950 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1951 This tag has to be present in all target headlines, inheritance will
1952 not be considered.
1953 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1954 todo keyword.
1955 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1956 headlines that are refiling targets.
1957 - a cons cell (:level . N). Any headline of level N is considered a target.
1958 Note that, when `org-odd-levels-only' is set, level corresponds to
1959 order in hierarchy, not to the number of stars.
1960 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1961 Note that, when `org-odd-levels-only' is set, level corresponds to
1962 order in hierarchy, not to the number of stars.
1964 Each element of this list generates a set of possible targets.
1965 The union of these sets is presented (with completion) to
1966 the user by `org-refile'.
1968 You can set the variable `org-refile-target-verify-function' to a function
1969 to verify each headline found by the simple criteria above.
1971 When this variable is nil, all top-level headlines in the current buffer
1972 are used, equivalent to the value `((nil . (:level . 1))'."
1973 :group 'org-refile
1974 :type '(repeat
1975 (cons
1976 (choice :value org-agenda-files
1977 (const :tag "All agenda files" org-agenda-files)
1978 (const :tag "Current buffer" nil)
1979 (function) (variable) (file))
1980 (choice :tag "Identify target headline by"
1981 (cons :tag "Specific tag" (const :value :tag) (string))
1982 (cons :tag "TODO keyword" (const :value :todo) (string))
1983 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1984 (cons :tag "Level number" (const :value :level) (integer))
1985 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1987 (defcustom org-refile-target-verify-function nil
1988 "Function to verify if the headline at point should be a refile target.
1989 The function will be called without arguments, with point at the
1990 beginning of the headline. It should return t and leave point
1991 where it is if the headline is a valid target for refiling.
1993 If the target should not be selected, the function must return nil.
1994 In addition to this, it may move point to a place from where the search
1995 should be continued. For example, the function may decide that the entire
1996 subtree of the current entry should be excluded and move point to the end
1997 of the subtree."
1998 :group 'org-refile
1999 :type 'function)
2001 (defcustom org-refile-use-cache nil
2002 "Non-nil means cache refile targets to speed up the process.
2003 The cache for a particular file will be updated automatically when
2004 the buffer has been killed, or when any of the marker used for flagging
2005 refile targets no longer points at a live buffer.
2006 If you have added new entries to a buffer that might themselves be targets,
2007 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2008 find that easier, `C-u C-u C-u C-c C-w'."
2009 :group 'org-refile
2010 :version "24.1"
2011 :type 'boolean)
2013 (defcustom org-refile-use-outline-path nil
2014 "Non-nil means provide refile targets as paths.
2015 So a level 3 headline will be available as level1/level2/level3.
2017 When the value is `file', also include the file name (without directory)
2018 into the path. In this case, you can also stop the completion after
2019 the file name, to get entries inserted as top level in the file.
2021 When `full-file-path', include the full file path."
2022 :group 'org-refile
2023 :type '(choice
2024 (const :tag "Not" nil)
2025 (const :tag "Yes" t)
2026 (const :tag "Start with file name" file)
2027 (const :tag "Start with full file path" full-file-path)))
2029 (defcustom org-outline-path-complete-in-steps t
2030 "Non-nil means complete the outline path in hierarchical steps.
2031 When Org-mode uses the refile interface to select an outline path
2032 \(see variable `org-refile-use-outline-path'), the completion of
2033 the path can be done is a single go, or if can be done in steps down
2034 the headline hierarchy. Going in steps is probably the best if you
2035 do not use a special completion package like `ido' or `icicles'.
2036 However, when using these packages, going in one step can be very
2037 fast, while still showing the whole path to the entry."
2038 :group 'org-refile
2039 :type 'boolean)
2041 (defcustom org-refile-allow-creating-parent-nodes nil
2042 "Non-nil means allow to create new nodes as refile targets.
2043 New nodes are then created by adding \"/new node name\" to the completion
2044 of an existing node. When the value of this variable is `confirm',
2045 new node creation must be confirmed by the user (recommended)
2046 When nil, the completion must match an existing entry.
2048 Note that, if the new heading is not seen by the criteria
2049 listed in `org-refile-targets', multiple instances of the same
2050 heading would be created by trying again to file under the new
2051 heading."
2052 :group 'org-refile
2053 :type '(choice
2054 (const :tag "Never" nil)
2055 (const :tag "Always" t)
2056 (const :tag "Prompt for confirmation" confirm)))
2058 (defcustom org-refile-active-region-within-subtree nil
2059 "Non-nil means also refile active region within a subtree.
2061 By default `org-refile' doesn't allow refiling regions if they
2062 don't contain a set of subtrees, but it might be convenient to
2063 do so sometimes: in that case, the first line of the region is
2064 converted to a headline before refiling."
2065 :group 'org-refile
2066 :version "24.1"
2067 :type 'boolean)
2069 (defgroup org-todo nil
2070 "Options concerning TODO items in Org-mode."
2071 :tag "Org TODO"
2072 :group 'org)
2074 (defgroup org-progress nil
2075 "Options concerning Progress logging in Org-mode."
2076 :tag "Org Progress"
2077 :group 'org-time)
2079 (defvar org-todo-interpretation-widgets
2080 '((:tag "Sequence (cycling hits every state)" sequence)
2081 (:tag "Type (cycling directly to DONE)" type))
2082 "The available interpretation symbols for customizing `org-todo-keywords'.
2083 Interested libraries should add to this list.")
2085 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2086 "List of TODO entry keyword sequences and their interpretation.
2087 \\<org-mode-map>This is a list of sequences.
2089 Each sequence starts with a symbol, either `sequence' or `type',
2090 indicating if the keywords should be interpreted as a sequence of
2091 action steps, or as different types of TODO items. The first
2092 keywords are states requiring action - these states will select a headline
2093 for inclusion into the global TODO list Org-mode produces. If one of
2094 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2095 signify that no further action is necessary. If \"|\" is not found,
2096 the last keyword is treated as the only DONE state of the sequence.
2098 The command \\[org-todo] cycles an entry through these states, and one
2099 additional state where no keyword is present. For details about this
2100 cycling, see the manual.
2102 TODO keywords and interpretation can also be set on a per-file basis with
2103 the special #+SEQ_TODO and #+TYP_TODO lines.
2105 Each keyword can optionally specify a letter for fast state selection
2106 \(in combination with the variable `org-use-fast-todo-selection')
2107 and specifiers for state change logging, using the same syntax that
2108 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2109 the WAIT state can be selected with the \"w\" letter. \"WAIT(w!)\"
2110 indicates to record a time stamp each time this state is selected.
2112 Each keyword may also specify if a timestamp or a note should be
2113 recorded when entering or leaving the state, by adding additional
2114 characters in the parenthesis after the keyword. This looks like this:
2115 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2116 record only the time of the state change. With X and Y being either
2117 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2118 Y when leaving the state if and only if the *target* state does not
2119 define X. You may omit any of the fast-selection key or X or /Y,
2120 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2122 For backward compatibility, this variable may also be just a list
2123 of keywords. In this case the interpretation (sequence or type) will be
2124 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2125 :group 'org-todo
2126 :group 'org-keywords
2127 :type '(choice
2128 (repeat :tag "Old syntax, just keywords"
2129 (string :tag "Keyword"))
2130 (repeat :tag "New syntax"
2131 (cons
2132 (choice
2133 :tag "Interpretation"
2134 ;;Quick and dirty way to see
2135 ;;`org-todo-interpretations'. This takes the
2136 ;;place of item arguments
2137 :convert-widget
2138 (lambda (widget)
2139 (widget-put widget
2140 :args (mapcar
2141 #'(lambda (x)
2142 (widget-convert
2143 (cons 'const x)))
2144 org-todo-interpretation-widgets))
2145 widget))
2146 (repeat
2147 (string :tag "Keyword"))))))
2149 (defvar org-todo-keywords-1 nil
2150 "All TODO and DONE keywords active in a buffer.")
2151 (make-variable-buffer-local 'org-todo-keywords-1)
2152 (defvar org-todo-keywords-for-agenda nil)
2153 (defvar org-done-keywords-for-agenda nil)
2154 (defvar org-drawers-for-agenda nil)
2155 (defvar org-todo-keyword-alist-for-agenda nil)
2156 (defvar org-tag-alist-for-agenda nil)
2157 (defvar org-agenda-contributing-files nil)
2158 (defvar org-not-done-keywords nil)
2159 (make-variable-buffer-local 'org-not-done-keywords)
2160 (defvar org-done-keywords nil)
2161 (make-variable-buffer-local 'org-done-keywords)
2162 (defvar org-todo-heads nil)
2163 (make-variable-buffer-local 'org-todo-heads)
2164 (defvar org-todo-sets nil)
2165 (make-variable-buffer-local 'org-todo-sets)
2166 (defvar org-todo-log-states nil)
2167 (make-variable-buffer-local 'org-todo-log-states)
2168 (defvar org-todo-kwd-alist nil)
2169 (make-variable-buffer-local 'org-todo-kwd-alist)
2170 (defvar org-todo-key-alist nil)
2171 (make-variable-buffer-local 'org-todo-key-alist)
2172 (defvar org-todo-key-trigger nil)
2173 (make-variable-buffer-local 'org-todo-key-trigger)
2175 (defcustom org-todo-interpretation 'sequence
2176 "Controls how TODO keywords are interpreted.
2177 This variable is in principle obsolete and is only used for
2178 backward compatibility, if the interpretation of todo keywords is
2179 not given already in `org-todo-keywords'. See that variable for
2180 more information."
2181 :group 'org-todo
2182 :group 'org-keywords
2183 :type '(choice (const sequence)
2184 (const type)))
2186 (defcustom org-use-fast-todo-selection t
2187 "Non-nil means use the fast todo selection scheme with C-c C-t.
2188 This variable describes if and under what circumstances the cycling
2189 mechanism for TODO keywords will be replaced by a single-key, direct
2190 selection scheme.
2192 When nil, fast selection is never used.
2194 When the symbol `prefix', it will be used when `org-todo' is called
2195 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2196 `C-u t' in an agenda buffer.
2198 When t, fast selection is used by default. In this case, the prefix
2199 argument forces cycling instead.
2201 In all cases, the special interface is only used if access keys have
2202 actually been assigned by the user, i.e. if keywords in the configuration
2203 are followed by a letter in parenthesis, like TODO(t)."
2204 :group 'org-todo
2205 :type '(choice
2206 (const :tag "Never" nil)
2207 (const :tag "By default" t)
2208 (const :tag "Only with C-u C-c C-t" prefix)))
2210 (defcustom org-provide-todo-statistics t
2211 "Non-nil means update todo statistics after insert and toggle.
2212 ALL-HEADLINES means update todo statistics by including headlines
2213 with no TODO keyword as well, counting them as not done.
2214 A list of TODO keywords means the same, but skip keywords that are
2215 not in this list.
2217 When this is set, todo statistics is updated in the parent of the
2218 current entry each time a todo state is changed."
2219 :group 'org-todo
2220 :type '(choice
2221 (const :tag "Yes, only for TODO entries" t)
2222 (const :tag "Yes, including all entries" 'all-headlines)
2223 (repeat :tag "Yes, for TODOs in this list"
2224 (string :tag "TODO keyword"))
2225 (other :tag "No TODO statistics" nil)))
2227 (defcustom org-hierarchical-todo-statistics t
2228 "Non-nil means TODO statistics covers just direct children.
2229 When nil, all entries in the subtree are considered.
2230 This has only an effect if `org-provide-todo-statistics' is set.
2231 To set this to nil for only a single subtree, use a COOKIE_DATA
2232 property and include the word \"recursive\" into the value."
2233 :group 'org-todo
2234 :type 'boolean)
2236 (defcustom org-after-todo-state-change-hook nil
2237 "Hook which is run after the state of a TODO item was changed.
2238 The new state (a string with a TODO keyword, or nil) is available in the
2239 Lisp variable `org-state'."
2240 :group 'org-todo
2241 :type 'hook)
2243 (defvar org-blocker-hook nil
2244 "Hook for functions that are allowed to block a state change.
2246 Each function gets as its single argument a property list, see
2247 `org-trigger-hook' for more information about this list.
2249 If any of the functions in this hook returns nil, the state change
2250 is blocked.")
2252 (defvar org-trigger-hook nil
2253 "Hook for functions that are triggered by a state change.
2255 Each function gets as its single argument a property list with at least
2256 the following elements:
2258 (:type type-of-change :position pos-at-entry-start
2259 :from old-state :to new-state)
2261 Depending on the type, more properties may be present.
2263 This mechanism is currently implemented for:
2265 TODO state changes
2266 ------------------
2267 :type todo-state-change
2268 :from previous state (keyword as a string), or nil, or a symbol
2269 'todo' or 'done', to indicate the general type of state.
2270 :to new state, like in :from")
2272 (defcustom org-enforce-todo-dependencies nil
2273 "Non-nil means undone TODO entries will block switching the parent to DONE.
2274 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2275 be blocked if any prior sibling is not yet done.
2276 Finally, if the parent is blocked because of ordered siblings of its own,
2277 the child will also be blocked."
2278 :set (lambda (var val)
2279 (set var val)
2280 (if val
2281 (add-hook 'org-blocker-hook
2282 'org-block-todo-from-children-or-siblings-or-parent)
2283 (remove-hook 'org-blocker-hook
2284 'org-block-todo-from-children-or-siblings-or-parent)))
2285 :group 'org-todo
2286 :type 'boolean)
2288 (defcustom org-enforce-todo-checkbox-dependencies nil
2289 "Non-nil means unchecked boxes will block switching the parent to DONE.
2290 When this is nil, checkboxes have no influence on switching TODO states.
2291 When non-nil, you first need to check off all check boxes before the TODO
2292 entry can be switched to DONE.
2293 This variable needs to be set before org.el is loaded, and you need to
2294 restart Emacs after a change to make the change effective. The only way
2295 to change is while Emacs is running is through the customize interface."
2296 :set (lambda (var val)
2297 (set var val)
2298 (if val
2299 (add-hook 'org-blocker-hook
2300 'org-block-todo-from-checkboxes)
2301 (remove-hook 'org-blocker-hook
2302 'org-block-todo-from-checkboxes)))
2303 :group 'org-todo
2304 :type 'boolean)
2306 (defcustom org-treat-insert-todo-heading-as-state-change nil
2307 "Non-nil means inserting a TODO heading is treated as state change.
2308 So when the command \\[org-insert-todo-heading] is used, state change
2309 logging will apply if appropriate. When nil, the new TODO item will
2310 be inserted directly, and no logging will take place."
2311 :group 'org-todo
2312 :type 'boolean)
2314 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2315 "Non-nil means switching TODO states with S-cursor counts as state change.
2316 This is the default behavior. However, setting this to nil allows a
2317 convenient way to select a TODO state and bypass any logging associated
2318 with that."
2319 :group 'org-todo
2320 :type 'boolean)
2322 (defcustom org-todo-state-tags-triggers nil
2323 "Tag changes that should be triggered by TODO state changes.
2324 This is a list. Each entry is
2326 (state-change (tag . flag) .......)
2328 State-change can be a string with a state, and empty string to indicate the
2329 state that has no TODO keyword, or it can be one of the symbols `todo'
2330 or `done', meaning any not-done or done state, respectively."
2331 :group 'org-todo
2332 :group 'org-tags
2333 :type '(repeat
2334 (cons (choice :tag "When changing to"
2335 (const :tag "Not-done state" todo)
2336 (const :tag "Done state" done)
2337 (string :tag "State"))
2338 (repeat
2339 (cons :tag "Tag action"
2340 (string :tag "Tag")
2341 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2343 (defcustom org-log-done nil
2344 "Information to record when a task moves to the DONE state.
2346 Possible values are:
2348 nil Don't add anything, just change the keyword
2349 time Add a time stamp to the task
2350 note Prompt for a note and add it with template `org-log-note-headings'
2352 This option can also be set with on a per-file-basis with
2354 #+STARTUP: nologdone
2355 #+STARTUP: logdone
2356 #+STARTUP: lognotedone
2358 You can have local logging settings for a subtree by setting the LOGGING
2359 property to one or more of these keywords."
2360 :group 'org-todo
2361 :group 'org-progress
2362 :type '(choice
2363 (const :tag "No logging" nil)
2364 (const :tag "Record CLOSED timestamp" time)
2365 (const :tag "Record CLOSED timestamp with note." note)))
2367 ;; Normalize old uses of org-log-done.
2368 (cond
2369 ((eq org-log-done t) (setq org-log-done 'time))
2370 ((and (listp org-log-done) (memq 'done org-log-done))
2371 (setq org-log-done 'note)))
2373 (defcustom org-log-reschedule nil
2374 "Information to record when the scheduling date of a tasks is modified.
2376 Possible values are:
2378 nil Don't add anything, just change the date
2379 time Add a time stamp to the task
2380 note Prompt for a note and add it with template `org-log-note-headings'
2382 This option can also be set with on a per-file-basis with
2384 #+STARTUP: nologreschedule
2385 #+STARTUP: logreschedule
2386 #+STARTUP: lognotereschedule"
2387 :group 'org-todo
2388 :group 'org-progress
2389 :type '(choice
2390 (const :tag "No logging" nil)
2391 (const :tag "Record timestamp" time)
2392 (const :tag "Record timestamp with note." note)))
2394 (defcustom org-log-redeadline nil
2395 "Information to record when the deadline date of a tasks is modified.
2397 Possible values are:
2399 nil Don't add anything, just change the date
2400 time Add a time stamp to the task
2401 note Prompt for a note and add it with template `org-log-note-headings'
2403 This option can also be set with on a per-file-basis with
2405 #+STARTUP: nologredeadline
2406 #+STARTUP: logredeadline
2407 #+STARTUP: lognoteredeadline
2409 You can have local logging settings for a subtree by setting the LOGGING
2410 property to one or more of these keywords."
2411 :group 'org-todo
2412 :group 'org-progress
2413 :type '(choice
2414 (const :tag "No logging" nil)
2415 (const :tag "Record timestamp" time)
2416 (const :tag "Record timestamp with note." note)))
2418 (defcustom org-log-note-clock-out nil
2419 "Non-nil means record a note when clocking out of an item.
2420 This can also be configured on a per-file basis by adding one of
2421 the following lines anywhere in the buffer:
2423 #+STARTUP: lognoteclock-out
2424 #+STARTUP: nolognoteclock-out"
2425 :group 'org-todo
2426 :group 'org-progress
2427 :type 'boolean)
2429 (defcustom org-log-done-with-time t
2430 "Non-nil means the CLOSED time stamp will contain date and time.
2431 When nil, only the date will be recorded."
2432 :group 'org-progress
2433 :type 'boolean)
2435 (defcustom org-log-note-headings
2436 '((done . "CLOSING NOTE %t")
2437 (state . "State %-12s from %-12S %t")
2438 (note . "Note taken on %t")
2439 (reschedule . "Rescheduled from %S on %t")
2440 (delschedule . "Not scheduled, was %S on %t")
2441 (redeadline . "New deadline from %S on %t")
2442 (deldeadline . "Removed deadline, was %S on %t")
2443 (refile . "Refiled on %t")
2444 (clock-out . ""))
2445 "Headings for notes added to entries.
2446 The value is an alist, with the car being a symbol indicating the note
2447 context, and the cdr is the heading to be used. The heading may also be the
2448 empty string.
2449 %t in the heading will be replaced by a time stamp.
2450 %T will be an active time stamp instead the default inactive one
2451 %d will be replaced by a short-format time stamp.
2452 %D will be replaced by an active short-format time stamp.
2453 %s will be replaced by the new TODO state, in double quotes.
2454 %S will be replaced by the old TODO state, in double quotes.
2455 %u will be replaced by the user name.
2456 %U will be replaced by the full user name.
2458 In fact, it is not a good idea to change the `state' entry, because
2459 agenda log mode depends on the format of these entries."
2460 :group 'org-todo
2461 :group 'org-progress
2462 :type '(list :greedy t
2463 (cons (const :tag "Heading when closing an item" done) string)
2464 (cons (const :tag
2465 "Heading when changing todo state (todo sequence only)"
2466 state) string)
2467 (cons (const :tag "Heading when just taking a note" note) string)
2468 (cons (const :tag "Heading when clocking out" clock-out) string)
2469 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2470 (cons (const :tag "Heading when rescheduling" reschedule) string)
2471 (cons (const :tag "Heading when changing deadline" redeadline) string)
2472 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2473 (cons (const :tag "Heading when refiling" refile) string)))
2475 (unless (assq 'note org-log-note-headings)
2476 (push '(note . "%t") org-log-note-headings))
2478 (defcustom org-log-into-drawer nil
2479 "Non-nil means insert state change notes and time stamps into a drawer.
2480 When nil, state changes notes will be inserted after the headline and
2481 any scheduling and clock lines, but not inside a drawer.
2483 The value of this variable should be the name of the drawer to use.
2484 LOGBOOK is proposed as the default drawer for this purpose, you can
2485 also set this to a string to define the drawer of your choice.
2487 A value of t is also allowed, representing \"LOGBOOK\".
2489 If this variable is set, `org-log-state-notes-insert-after-drawers'
2490 will be ignored.
2492 You can set the property LOG_INTO_DRAWER to overrule this setting for
2493 a subtree."
2494 :group 'org-todo
2495 :group 'org-progress
2496 :type '(choice
2497 (const :tag "Not into a drawer" nil)
2498 (const :tag "LOGBOOK" t)
2499 (string :tag "Other")))
2501 (if (fboundp 'defvaralias)
2502 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2504 (defun org-log-into-drawer ()
2505 "Return the value of `org-log-into-drawer', but let properties overrule.
2506 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2507 used instead of the default value."
2508 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2509 (cond
2510 ((or (not p) (equal p "nil")) org-log-into-drawer)
2511 ((equal p "t") "LOGBOOK")
2512 (t p))))
2514 (defcustom org-log-state-notes-insert-after-drawers nil
2515 "Non-nil means insert state change notes after any drawers in entry.
2516 Only the drawers that *immediately* follow the headline and the
2517 deadline/scheduled line are skipped.
2518 When nil, insert notes right after the heading and perhaps the line
2519 with deadline/scheduling if present.
2521 This variable will have no effect if `org-log-into-drawer' is
2522 set."
2523 :group 'org-todo
2524 :group 'org-progress
2525 :type 'boolean)
2527 (defcustom org-log-states-order-reversed t
2528 "Non-nil means the latest state note will be directly after heading.
2529 When nil, the state change notes will be ordered according to time."
2530 :group 'org-todo
2531 :group 'org-progress
2532 :type 'boolean)
2534 (defcustom org-todo-repeat-to-state nil
2535 "The TODO state to which a repeater should return the repeating task.
2536 By default this is the first task in a TODO sequence, or the previous state
2537 in a TODO_TYP set. But you can specify another task here.
2538 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2539 :group 'org-todo
2540 :version "24.1"
2541 :type '(choice (const :tag "Head of sequence" nil)
2542 (string :tag "Specific state")))
2544 (defcustom org-log-repeat 'time
2545 "Non-nil means record moving through the DONE state when triggering repeat.
2546 An auto-repeating task is immediately switched back to TODO when
2547 marked DONE. If you are not logging state changes (by adding \"@\"
2548 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2549 record a closing note, there will be no record of the task moving
2550 through DONE. This variable forces taking a note anyway.
2552 nil Don't force a record
2553 time Record a time stamp
2554 note Record a note
2556 This option can also be set with on a per-file-basis with
2558 #+STARTUP: logrepeat
2559 #+STARTUP: lognoterepeat
2560 #+STARTUP: nologrepeat
2562 You can have local logging settings for a subtree by setting the LOGGING
2563 property to one or more of these keywords."
2564 :group 'org-todo
2565 :group 'org-progress
2566 :type '(choice
2567 (const :tag "Don't force a record" nil)
2568 (const :tag "Force recording the DONE state" time)
2569 (const :tag "Force recording a note with the DONE state" note)))
2572 (defgroup org-priorities nil
2573 "Priorities in Org-mode."
2574 :tag "Org Priorities"
2575 :group 'org-todo)
2577 (defcustom org-enable-priority-commands t
2578 "Non-nil means priority commands are active.
2579 When nil, these commands will be disabled, so that you never accidentally
2580 set a priority."
2581 :group 'org-priorities
2582 :type 'boolean)
2584 (defcustom org-highest-priority ?A
2585 "The highest priority of TODO items. A character like ?A, ?B etc.
2586 Must have a smaller ASCII number than `org-lowest-priority'."
2587 :group 'org-priorities
2588 :type 'character)
2590 (defcustom org-lowest-priority ?C
2591 "The lowest priority of TODO items. A character like ?A, ?B etc.
2592 Must have a larger ASCII number than `org-highest-priority'."
2593 :group 'org-priorities
2594 :type 'character)
2596 (defcustom org-default-priority ?B
2597 "The default priority of TODO items.
2598 This is the priority an item gets if no explicit priority is given.
2599 When starting to cycle on an empty priority the first step in the cycle
2600 depends on `org-priority-start-cycle-with-default'. The resulting first
2601 step priority must not exceed the range from `org-highest-priority' to
2602 `org-lowest-priority' which means that `org-default-priority' has to be
2603 in this range exclusive or inclusive the range boundaries. Else the
2604 first step refuses to set the default and the second will fall back
2605 to (depending on the command used) the highest or lowest priority."
2606 :group 'org-priorities
2607 :type 'character)
2609 (defcustom org-priority-start-cycle-with-default t
2610 "Non-nil means start with default priority when starting to cycle.
2611 When this is nil, the first step in the cycle will be (depending on the
2612 command used) one higher or lower than the default priority.
2613 See also `org-default-priority'."
2614 :group 'org-priorities
2615 :type 'boolean)
2617 (defcustom org-get-priority-function nil
2618 "Function to extract the priority from a string.
2619 The string is normally the headline. If this is nil Org computes the
2620 priority from the priority cookie like [#A] in the headline. It returns
2621 an integer, increasing by 1000 for each priority level.
2622 The user can set a different function here, which should take a string
2623 as an argument and return the numeric priority."
2624 :group 'org-priorities
2625 :version "24.1"
2626 :type 'function)
2628 (defgroup org-time nil
2629 "Options concerning time stamps and deadlines in Org-mode."
2630 :tag "Org Time"
2631 :group 'org)
2633 (defcustom org-insert-labeled-timestamps-at-point nil
2634 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2635 When nil, these labeled time stamps are forces into the second line of an
2636 entry, just after the headline. When scheduling from the global TODO list,
2637 the time stamp will always be forced into the second line."
2638 :group 'org-time
2639 :type 'boolean)
2641 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2642 "Formats for `format-time-string' which are used for time stamps.
2643 It is not recommended to change this constant.")
2645 (defcustom org-time-stamp-rounding-minutes '(0 5)
2646 "Number of minutes to round time stamps to.
2647 These are two values, the first applies when first creating a time stamp.
2648 The second applies when changing it with the commands `S-up' and `S-down'.
2649 When changing the time stamp, this means that it will change in steps
2650 of N minutes, as given by the second value.
2652 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2653 numbers should be factors of 60, so for example 5, 10, 15.
2655 When this is larger than 1, you can still force an exact time stamp by using
2656 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2657 and by using a prefix arg to `S-up/down' to specify the exact number
2658 of minutes to shift."
2659 :group 'org-time
2660 :get #'(lambda (var) ; Make sure both elements are there
2661 (if (integerp (default-value var))
2662 (list (default-value var) 5)
2663 (default-value var)))
2664 :type '(list
2665 (integer :tag "when inserting times")
2666 (integer :tag "when modifying times")))
2668 ;; Normalize old customizations of this variable.
2669 (when (integerp org-time-stamp-rounding-minutes)
2670 (setq org-time-stamp-rounding-minutes
2671 (list org-time-stamp-rounding-minutes
2672 org-time-stamp-rounding-minutes)))
2674 (defcustom org-display-custom-times nil
2675 "Non-nil means overlay custom formats over all time stamps.
2676 The formats are defined through the variable `org-time-stamp-custom-formats'.
2677 To turn this on on a per-file basis, insert anywhere in the file:
2678 #+STARTUP: customtime"
2679 :group 'org-time
2680 :set 'set-default
2681 :type 'sexp)
2682 (make-variable-buffer-local 'org-display-custom-times)
2684 (defcustom org-time-stamp-custom-formats
2685 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2686 "Custom formats for time stamps. See `format-time-string' for the syntax.
2687 These are overlaid over the default ISO format if the variable
2688 `org-display-custom-times' is set. Time like %H:%M should be at the
2689 end of the second format. The custom formats are also honored by export
2690 commands, if custom time display is turned on at the time of export."
2691 :group 'org-time
2692 :type 'sexp)
2694 (defun org-time-stamp-format (&optional long inactive)
2695 "Get the right format for a time string."
2696 (let ((f (if long (cdr org-time-stamp-formats)
2697 (car org-time-stamp-formats))))
2698 (if inactive
2699 (concat "[" (substring f 1 -1) "]")
2700 f)))
2702 (defcustom org-time-clocksum-format "%d:%02d"
2703 "The format string used when creating CLOCKSUM lines.
2704 This is also used when org-mode generates a time duration."
2705 :group 'org-time
2706 :type 'string)
2708 (defcustom org-time-clocksum-use-fractional nil
2709 "If non-nil, \\[org-clock-display] uses fractional times.
2710 org-mode generates a time duration."
2711 :group 'org-time
2712 :type 'boolean)
2714 (defcustom org-time-clocksum-fractional-format "%.2f"
2715 "The format string used when creating CLOCKSUM lines, or when
2716 org-mode generates a time duration."
2717 :group 'org-time
2718 :type 'string)
2720 (defcustom org-deadline-warning-days 14
2721 "No. of days before expiration during which a deadline becomes active.
2722 This variable governs the display in sparse trees and in the agenda.
2723 When 0 or negative, it means use this number (the absolute value of it)
2724 even if a deadline has a different individual lead time specified.
2726 Custom commands can set this variable in the options section."
2727 :group 'org-time
2728 :group 'org-agenda-daily/weekly
2729 :type 'integer)
2731 (defcustom org-read-date-prefer-future t
2732 "Non-nil means assume future for incomplete date input from user.
2733 This affects the following situations:
2734 1. The user gives a month but not a year.
2735 For example, if it is April and you enter \"feb 2\", this will be read
2736 as Feb 2, *next* year. \"May 5\", however, will be this year.
2737 2. The user gives a day, but no month.
2738 For example, if today is the 15th, and you enter \"3\", Org-mode will
2739 read this as the third of *next* month. However, if you enter \"17\",
2740 it will be considered as *this* month.
2742 If you set this variable to the symbol `time', then also the following
2743 will work:
2745 3. If the user gives a time, but no day. If the time is before now,
2746 to will be interpreted as tomorrow.
2748 Currently none of this works for ISO week specifications.
2750 When this option is nil, the current day, month and year will always be
2751 used as defaults.
2753 See also `org-agenda-jump-prefer-future'."
2754 :group 'org-time
2755 :type '(choice
2756 (const :tag "Never" nil)
2757 (const :tag "Check month and day" t)
2758 (const :tag "Check month, day, and time" time)))
2760 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2761 "Should the agenda jump command prefer the future for incomplete dates?
2762 The default is to do the same as configured in `org-read-date-prefer-future'.
2763 But you can also set a deviating value here.
2764 This may t or nil, or the symbol `org-read-date-prefer-future'."
2765 :group 'org-agenda
2766 :group 'org-time
2767 :version "24.1"
2768 :type '(choice
2769 (const :tag "Use org-read-date-prefer-future"
2770 org-read-date-prefer-future)
2771 (const :tag "Never" nil)
2772 (const :tag "Always" t)))
2774 (defcustom org-read-date-force-compatible-dates t
2775 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2777 Depending on the system Emacs is running on, certain dates cannot
2778 be represented with the type used internally to represent time.
2779 Dates between 1970-1-1 and 2038-1-1 can always be represented
2780 correctly. Some systems allow for earlier dates, some for later,
2781 some for both. One way to find out it to insert any date into an
2782 Org buffer, putting the cursor on the year and hitting S-up and
2783 S-down to test the range.
2785 When this variable is set to t, the date/time prompt will not let
2786 you specify dates outside the 1970-2037 range, so it is certain that
2787 these dates will work in whatever version of Emacs you are
2788 running, and also that you can move a file from one Emacs implementation
2789 to another. WHenever Org is forcing the year for you, it will display
2790 a message and beep.
2792 When this variable is nil, Org will check if the date is
2793 representable in the specific Emacs implementation you are using.
2794 If not, it will force a year, usually the current year, and beep
2795 to remind you. Currently this setting is not recommended because
2796 the likelihood that you will open your Org files in an Emacs that
2797 has limited date range is not negligible.
2799 A workaround for this problem is to use diary sexp dates for time
2800 stamps outside of this range."
2801 :group 'org-time
2802 :version "24.1"
2803 :type 'boolean)
2805 (defcustom org-read-date-display-live t
2806 "Non-nil means display current interpretation of date prompt live.
2807 This display will be in an overlay, in the minibuffer."
2808 :group 'org-time
2809 :type 'boolean)
2811 (defcustom org-read-date-popup-calendar t
2812 "Non-nil means pop up a calendar when prompting for a date.
2813 In the calendar, the date can be selected with mouse-1. However, the
2814 minibuffer will also be active, and you can simply enter the date as well.
2815 When nil, only the minibuffer will be available."
2816 :group 'org-time
2817 :type 'boolean)
2818 (if (fboundp 'defvaralias)
2819 (defvaralias 'org-popup-calendar-for-date-prompt
2820 'org-read-date-popup-calendar))
2822 (defcustom org-read-date-minibuffer-setup-hook nil
2823 "Hook to be used to set up keys for the date/time interface.
2824 Add key definitions to `minibuffer-local-map', which will be a temporary
2825 copy."
2826 :group 'org-time
2827 :type 'hook)
2829 (defcustom org-extend-today-until 0
2830 "The hour when your day really ends. Must be an integer.
2831 This has influence for the following applications:
2832 - When switching the agenda to \"today\". It it is still earlier than
2833 the time given here, the day recognized as TODAY is actually yesterday.
2834 - When a date is read from the user and it is still before the time given
2835 here, the current date and time will be assumed to be yesterday, 23:59.
2836 Also, timestamps inserted in remember templates follow this rule.
2838 IMPORTANT: This is a feature whose implementation is and likely will
2839 remain incomplete. Really, it is only here because past midnight seems to
2840 be the favorite working time of John Wiegley :-)"
2841 :group 'org-time
2842 :type 'integer)
2844 (defcustom org-use-effective-time nil
2845 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2846 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2847 \"effective time\" of any timestamps between midnight and 8am will be
2848 23:59 of the previous day."
2849 :group 'org-time
2850 :version "24.1"
2851 :type 'boolean)
2853 (defcustom org-edit-timestamp-down-means-later nil
2854 "Non-nil means S-down will increase the time in a time stamp.
2855 When nil, S-up will increase."
2856 :group 'org-time
2857 :type 'boolean)
2859 (defcustom org-calendar-follow-timestamp-change t
2860 "Non-nil means make the calendar window follow timestamp changes.
2861 When a timestamp is modified and the calendar window is visible, it will be
2862 moved to the new date."
2863 :group 'org-time
2864 :type 'boolean)
2866 (defgroup org-tags nil
2867 "Options concerning tags in Org-mode."
2868 :tag "Org Tags"
2869 :group 'org)
2871 (defcustom org-tag-alist nil
2872 "List of tags allowed in Org-mode files.
2873 When this list is nil, Org-mode will base TAG input on what is already in the
2874 buffer.
2875 The value of this variable is an alist, the car of each entry must be a
2876 keyword as a string, the cdr may be a character that is used to select
2877 that tag through the fast-tag-selection interface.
2878 See the manual for details."
2879 :group 'org-tags
2880 :type '(repeat
2881 (choice
2882 (cons (string :tag "Tag name")
2883 (character :tag "Access char"))
2884 (list :tag "Start radio group"
2885 (const :startgroup)
2886 (option (string :tag "Group description")))
2887 (list :tag "End radio group"
2888 (const :endgroup)
2889 (option (string :tag "Group description")))
2890 (const :tag "New line" (:newline)))))
2892 (defcustom org-tag-persistent-alist nil
2893 "List of tags that will always appear in all Org-mode files.
2894 This is in addition to any in buffer settings or customizations
2895 of `org-tag-alist'.
2896 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2897 The value of this variable is an alist, the car of each entry must be a
2898 keyword as a string, the cdr may be a character that is used to select
2899 that tag through the fast-tag-selection interface.
2900 See the manual for details.
2901 To disable these tags on a per-file basis, insert anywhere in the file:
2902 #+STARTUP: noptag"
2903 :group 'org-tags
2904 :type '(repeat
2905 (choice
2906 (cons (string :tag "Tag name")
2907 (character :tag "Access char"))
2908 (const :tag "Start radio group" (:startgroup))
2909 (const :tag "End radio group" (:endgroup))
2910 (const :tag "New line" (:newline)))))
2912 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2913 "If non-nil, always offer completion for all tags of all agenda files.
2914 Instead of customizing this variable directly, you might want to
2915 set it locally for capture buffers, because there no list of
2916 tags in that file can be created dynamically (there are none).
2918 (add-hook 'org-capture-mode-hook
2919 (lambda ()
2920 (set (make-local-variable
2921 'org-complete-tags-always-offer-all-agenda-tags)
2922 t)))"
2923 :group 'org-tags
2924 :version "24.1"
2925 :type 'boolean)
2927 (defvar org-file-tags nil
2928 "List of tags that can be inherited by all entries in the file.
2929 The tags will be inherited if the variable `org-use-tag-inheritance'
2930 says they should be.
2931 This variable is populated from #+FILETAGS lines.")
2933 (defcustom org-use-fast-tag-selection 'auto
2934 "Non-nil means use fast tag selection scheme.
2935 This is a special interface to select and deselect tags with single keys.
2936 When nil, fast selection is never used.
2937 When the symbol `auto', fast selection is used if and only if selection
2938 characters for tags have been configured, either through the variable
2939 `org-tag-alist' or through a #+TAGS line in the buffer.
2940 When t, fast selection is always used and selection keys are assigned
2941 automatically if necessary."
2942 :group 'org-tags
2943 :type '(choice
2944 (const :tag "Always" t)
2945 (const :tag "Never" nil)
2946 (const :tag "When selection characters are configured" 'auto)))
2948 (defcustom org-fast-tag-selection-single-key nil
2949 "Non-nil means fast tag selection exits after first change.
2950 When nil, you have to press RET to exit it.
2951 During fast tag selection, you can toggle this flag with `C-c'.
2952 This variable can also have the value `expert'. In this case, the window
2953 displaying the tags menu is not even shown, until you press C-c again."
2954 :group 'org-tags
2955 :type '(choice
2956 (const :tag "No" nil)
2957 (const :tag "Yes" t)
2958 (const :tag "Expert" expert)))
2960 (defvar org-fast-tag-selection-include-todo nil
2961 "Non-nil means fast tags selection interface will also offer TODO states.
2962 This is an undocumented feature, you should not rely on it.")
2964 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2965 "The column to which tags should be indented in a headline.
2966 If this number is positive, it specifies the column. If it is negative,
2967 it means that the tags should be flushright to that column. For example,
2968 -80 works well for a normal 80 character screen.
2969 When 0, place tags directly after headline text, with only one space in
2970 between."
2971 :group 'org-tags
2972 :type 'integer)
2974 (defcustom org-auto-align-tags t
2975 "Non-nil keeps tags aligned when modifying headlines.
2976 Some operations (i.e. demoting) change the length of a headline and
2977 therefore shift the tags around. With this option turned on, after
2978 each such operation the tags are again aligned to `org-tags-column'."
2979 :group 'org-tags
2980 :type 'boolean)
2982 (defcustom org-use-tag-inheritance t
2983 "Non-nil means tags in levels apply also for sublevels.
2984 When nil, only the tags directly given in a specific line apply there.
2985 This may also be a list of tags that should be inherited, or a regexp that
2986 matches tags that should be inherited. Additional control is possible
2987 with the variable `org-tags-exclude-from-inheritance' which gives an
2988 explicit list of tags to be excluded from inheritance., even if the value of
2989 `org-use-tag-inheritance' would select it for inheritance.
2991 If this option is t, a match early-on in a tree can lead to a large
2992 number of matches in the subtree when constructing the agenda or creating
2993 a sparse tree. If you only want to see the first match in a tree during
2994 a search, check out the variable `org-tags-match-list-sublevels'."
2995 :group 'org-tags
2996 :type '(choice
2997 (const :tag "Not" nil)
2998 (const :tag "Always" t)
2999 (repeat :tag "Specific tags" (string :tag "Tag"))
3000 (regexp :tag "Tags matched by regexp")))
3002 (defcustom org-tags-exclude-from-inheritance nil
3003 "List of tags that should never be inherited.
3004 This is a way to exclude a few tags from inheritance. For way to do
3005 the opposite, to actively allow inheritance for selected tags,
3006 see the variable `org-use-tag-inheritance'."
3007 :group 'org-tags
3008 :type '(repeat (string :tag "Tag")))
3010 (defun org-tag-inherit-p (tag)
3011 "Check if TAG is one that should be inherited."
3012 (cond
3013 ((member tag org-tags-exclude-from-inheritance) nil)
3014 ((eq org-use-tag-inheritance t) t)
3015 ((not org-use-tag-inheritance) nil)
3016 ((stringp org-use-tag-inheritance)
3017 (string-match org-use-tag-inheritance tag))
3018 ((listp org-use-tag-inheritance)
3019 (member tag org-use-tag-inheritance))
3020 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3022 (defcustom org-tags-match-list-sublevels t
3023 "Non-nil means list also sublevels of headlines matching a search.
3024 This variable applies to tags/property searches, and also to stuck
3025 projects because this search is based on a tags match as well.
3027 When set to the symbol `indented', sublevels are indented with
3028 leading dots.
3030 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3031 the sublevels of a headline matching a tag search often also match
3032 the same search. Listing all of them can create very long lists.
3033 Setting this variable to nil causes subtrees of a match to be skipped.
3035 This variable is semi-obsolete and probably should always be true. It
3036 is better to limit inheritance to certain tags using the variables
3037 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3038 :group 'org-tags
3039 :type '(choice
3040 (const :tag "No, don't list them" nil)
3041 (const :tag "Yes, do list them" t)
3042 (const :tag "List them, indented with leading dots" indented)))
3044 (defcustom org-tags-sort-function nil
3045 "When set, tags are sorted using this function as a comparator."
3046 :group 'org-tags
3047 :type '(choice
3048 (const :tag "No sorting" nil)
3049 (const :tag "Alphabetical" string<)
3050 (const :tag "Reverse alphabetical" string>)
3051 (function :tag "Custom function" nil)))
3053 (defvar org-tags-history nil
3054 "History of minibuffer reads for tags.")
3055 (defvar org-last-tags-completion-table nil
3056 "The last used completion table for tags.")
3057 (defvar org-after-tags-change-hook nil
3058 "Hook that is run after the tags in a line have changed.")
3060 (defgroup org-properties nil
3061 "Options concerning properties in Org-mode."
3062 :tag "Org Properties"
3063 :group 'org)
3065 (defcustom org-property-format "%-10s %s"
3066 "How property key/value pairs should be formatted by `indent-line'.
3067 When `indent-line' hits a property definition, it will format the line
3068 according to this format, mainly to make sure that the values are
3069 lined-up with respect to each other."
3070 :group 'org-properties
3071 :type 'string)
3073 (defcustom org-properties-postprocess-alist nil
3074 "Alist of properties and functions to adjust inserted values.
3075 Elements of this alist must be of the form
3077 ([string] [function])
3079 where [string] must be a property name and [function] must be a
3080 lambda expression: this lambda expression must take one argument,
3081 the value to adjust, and return the new value as a string.
3083 For example, this element will allow the property \"Remaining\"
3084 to be updated wrt the relation between the \"Effort\" property
3085 and the clock summary:
3087 ((\"Remaining\" (lambda(value)
3088 (let ((clocksum (org-clock-sum-current-item))
3089 (effort (org-duration-string-to-minutes
3090 (org-entry-get (point) \"Effort\"))))
3091 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3092 :group 'org-properties
3093 :version "24.1"
3094 :type '(alist :key-type (string :tag "Property")
3095 :value-type (function :tag "Function")))
3097 (defcustom org-use-property-inheritance nil
3098 "Non-nil means properties apply also for sublevels.
3100 This setting is chiefly used during property searches. Turning it on can
3101 cause significant overhead when doing a search, which is why it is not
3102 on by default.
3104 When nil, only the properties directly given in the current entry count.
3105 When t, every property is inherited. The value may also be a list of
3106 properties that should have inheritance, or a regular expression matching
3107 properties that should be inherited.
3109 However, note that some special properties use inheritance under special
3110 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3111 and the properties ending in \"_ALL\" when they are used as descriptor
3112 for valid values of a property.
3114 Note for programmers:
3115 When querying an entry with `org-entry-get', you can control if inheritance
3116 should be used. By default, `org-entry-get' looks only at the local
3117 properties. You can request inheritance by setting the inherit argument
3118 to t (to force inheritance) or to `selective' (to respect the setting
3119 in this variable)."
3120 :group 'org-properties
3121 :type '(choice
3122 (const :tag "Not" nil)
3123 (const :tag "Always" t)
3124 (repeat :tag "Specific properties" (string :tag "Property"))
3125 (regexp :tag "Properties matched by regexp")))
3127 (defun org-property-inherit-p (property)
3128 "Check if PROPERTY is one that should be inherited."
3129 (cond
3130 ((eq org-use-property-inheritance t) t)
3131 ((not org-use-property-inheritance) nil)
3132 ((stringp org-use-property-inheritance)
3133 (string-match org-use-property-inheritance property))
3134 ((listp org-use-property-inheritance)
3135 (member property org-use-property-inheritance))
3136 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3138 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3139 "The default column format, if no other format has been defined.
3140 This variable can be set on the per-file basis by inserting a line
3142 #+COLUMNS: %25ITEM ....."
3143 :group 'org-properties
3144 :type 'string)
3146 (defcustom org-columns-ellipses ".."
3147 "The ellipses to be used when a field in column view is truncated.
3148 When this is the empty string, as many characters as possible are shown,
3149 but then there will be no visual indication that the field has been truncated.
3150 When this is a string of length N, the last N characters of a truncated
3151 field are replaced by this string. If the column is narrower than the
3152 ellipses string, only part of the ellipses string will be shown."
3153 :group 'org-properties
3154 :type 'string)
3156 (defcustom org-columns-modify-value-for-display-function nil
3157 "Function that modifies values for display in column view.
3158 For example, it can be used to cut out a certain part from a time stamp.
3159 The function must take 2 arguments:
3161 column-title The title of the column (*not* the property name)
3162 value The value that should be modified.
3164 The function should return the value that should be displayed,
3165 or nil if the normal value should be used."
3166 :group 'org-properties
3167 :type 'function)
3169 (defcustom org-effort-property "Effort"
3170 "The property that is being used to keep track of effort estimates.
3171 Effort estimates given in this property need to have the format H:MM."
3172 :group 'org-properties
3173 :group 'org-progress
3174 :type '(string :tag "Property"))
3176 (defconst org-global-properties-fixed
3177 '(("VISIBILITY_ALL" . "folded children content all")
3178 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3179 "List of property/value pairs that can be inherited by any entry.
3181 These are fixed values, for the preset properties. The user variable
3182 that can be used to add to this list is `org-global-properties'.
3184 The entries in this list are cons cells where the car is a property
3185 name and cdr is a string with the value. If the value represents
3186 multiple items like an \"_ALL\" property, separate the items by
3187 spaces.")
3189 (defcustom org-global-properties nil
3190 "List of property/value pairs that can be inherited by any entry.
3192 This list will be combined with the constant `org-global-properties-fixed'.
3194 The entries in this list are cons cells where the car is a property
3195 name and cdr is a string with the value.
3197 You can set buffer-local values for the same purpose in the variable
3198 `org-file-properties' this by adding lines like
3200 #+PROPERTY: NAME VALUE"
3201 :group 'org-properties
3202 :type '(repeat
3203 (cons (string :tag "Property")
3204 (string :tag "Value"))))
3206 (defvar org-file-properties nil
3207 "List of property/value pairs that can be inherited by any entry.
3208 Valid for the current buffer.
3209 This variable is populated from #+PROPERTY lines.")
3210 (make-variable-buffer-local 'org-file-properties)
3212 (defgroup org-agenda nil
3213 "Options concerning agenda views in Org-mode."
3214 :tag "Org Agenda"
3215 :group 'org)
3217 (defvar org-category nil
3218 "Variable used by org files to set a category for agenda display.
3219 Such files should use a file variable to set it, for example
3221 # -*- mode: org; org-category: \"ELisp\"
3223 or contain a special line
3225 #+CATEGORY: ELisp
3227 If the file does not specify a category, then file's base name
3228 is used instead.")
3229 (make-variable-buffer-local 'org-category)
3230 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3232 (defcustom org-agenda-files nil
3233 "The files to be used for agenda display.
3234 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3235 \\[org-remove-file]. You can also use customize to edit the list.
3237 If an entry is a directory, all files in that directory that are matched by
3238 `org-agenda-file-regexp' will be part of the file list.
3240 If the value of the variable is not a list but a single file name, then
3241 the list of agenda files is actually stored and maintained in that file, one
3242 agenda file per line. In this file paths can be given relative to
3243 `org-directory'. Tilde expansion and environment variable substitution
3244 are also made."
3245 :group 'org-agenda
3246 :type '(choice
3247 (repeat :tag "List of files and directories" file)
3248 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3250 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3251 "Regular expression to match files for `org-agenda-files'.
3252 If any element in the list in that variable contains a directory instead
3253 of a normal file, all files in that directory that are matched by this
3254 regular expression will be included."
3255 :group 'org-agenda
3256 :type 'regexp)
3258 (defcustom org-agenda-text-search-extra-files nil
3259 "List of extra files to be searched by text search commands.
3260 These files will be search in addition to the agenda files by the
3261 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3262 Note that these files will only be searched for text search commands,
3263 not for the other agenda views like todo lists, tag searches or the weekly
3264 agenda. This variable is intended to list notes and possibly archive files
3265 that should also be searched by these two commands.
3266 In fact, if the first element in the list is the symbol `agenda-archives',
3267 than all archive files of all agenda files will be added to the search
3268 scope."
3269 :group 'org-agenda
3270 :type '(set :greedy t
3271 (const :tag "Agenda Archives" agenda-archives)
3272 (repeat :inline t (file))))
3274 (if (fboundp 'defvaralias)
3275 (defvaralias 'org-agenda-multi-occur-extra-files
3276 'org-agenda-text-search-extra-files))
3278 (defcustom org-agenda-skip-unavailable-files nil
3279 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3280 A nil value means to remove them, after a query, from the list."
3281 :group 'org-agenda
3282 :type 'boolean)
3284 (defcustom org-calendar-to-agenda-key [?c]
3285 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3286 The command `org-calendar-goto-agenda' will be bound to this key. The
3287 default is the character `c' because then `c' can be used to switch back and
3288 forth between agenda and calendar."
3289 :group 'org-agenda
3290 :type 'sexp)
3292 (defcustom org-calendar-agenda-action-key [?k]
3293 "The key to be installed in `calendar-mode-map' for agenda-action.
3294 The command `org-agenda-action' will be bound to this key. The
3295 default is the character `k' because we use the same key in the agenda."
3296 :group 'org-agenda
3297 :type 'sexp)
3299 (defcustom org-calendar-insert-diary-entry-key [?i]
3300 "The key to be installed in `calendar-mode-map' for adding diary entries.
3301 This option is irrelevant until `org-agenda-diary-file' has been configured
3302 to point to an Org-mode file. When that is the case, the command
3303 `org-agenda-diary-entry' will be bound to the key given here, by default
3304 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3305 if you want to continue doing this, you need to change this to a different
3306 key."
3307 :group 'org-agenda
3308 :type 'sexp)
3310 (defcustom org-agenda-diary-file 'diary-file
3311 "File to which to add new entries with the `i' key in agenda and calendar.
3312 When this is the symbol `diary-file', the functionality in the Emacs
3313 calendar will be used to add entries to the `diary-file'. But when this
3314 points to a file, `org-agenda-diary-entry' will be used instead."
3315 :group 'org-agenda
3316 :type '(choice
3317 (const :tag "The standard Emacs diary file" diary-file)
3318 (file :tag "Special Org file diary entries")))
3320 (eval-after-load "calendar"
3321 '(progn
3322 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3323 'org-calendar-goto-agenda)
3324 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3325 'org-agenda-action)
3326 (add-hook 'calendar-mode-hook
3327 (lambda ()
3328 (unless (eq org-agenda-diary-file 'diary-file)
3329 (define-key calendar-mode-map
3330 org-calendar-insert-diary-entry-key
3331 'org-agenda-diary-entry))))))
3333 (defgroup org-latex nil
3334 "Options for embedding LaTeX code into Org-mode."
3335 :tag "Org LaTeX"
3336 :group 'org)
3338 (defcustom org-format-latex-options
3339 '(:foreground default :background default :scale 1.0
3340 :html-foreground "Black" :html-background "Transparent"
3341 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3342 "Options for creating images from LaTeX fragments.
3343 This is a property list with the following properties:
3344 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3345 `default' means use the foreground of the default face.
3346 :background the background color, or \"Transparent\".
3347 `default' means use the background of the default face.
3348 :scale a scaling factor for the size of the images, to get more pixels
3349 :html-foreground, :html-background, :html-scale
3350 the same numbers for HTML export.
3351 :matchers a list indicating which matchers should be used to
3352 find LaTeX fragments. Valid members of this list are:
3353 \"begin\" find environments
3354 \"$1\" find single characters surrounded by $.$
3355 \"$\" find math expressions surrounded by $...$
3356 \"$$\" find math expressions surrounded by $$....$$
3357 \"\\(\" find math expressions surrounded by \\(...\\)
3358 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3359 :group 'org-latex
3360 :type 'plist)
3362 (defcustom org-format-latex-signal-error t
3363 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3364 When nil, just push out a message."
3365 :group 'org-latex
3366 :version "24.1"
3367 :type 'boolean)
3369 (defcustom org-latex-to-mathml-jar-file nil
3370 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3371 Use this to specify additional executable file say a jar file.
3373 When using MathToWeb as the converter, specify the full-path to
3374 your mathtoweb.jar file."
3375 :group 'org-latex
3376 :version "24.1"
3377 :type '(choice
3378 (const :tag "None" nil)
3379 (file :tag "JAR file" :must-match t)))
3381 (defcustom org-latex-to-mathml-convert-command nil
3382 "Command to convert LaTeX fragments to MathML.
3383 Replace format-specifiers in the command as noted below and use
3384 `shell-command' to convert LaTeX to MathML.
3385 %j: Executable file in fully expanded form as specified by
3386 `org-latex-to-mathml-jar-file'.
3387 %I: Input LaTeX file in fully expanded form
3388 %o: Output MathML file
3389 This command is used by `org-create-math-formula'.
3391 When using MathToWeb as the converter, set this to
3392 \"java -jar %j -unicode -force -df %o %I\"."
3393 :group 'org-latex
3394 :version "24.1"
3395 :type '(choice
3396 (const :tag "None" nil)
3397 (string :tag "\nShell command")))
3399 (defcustom org-latex-create-formula-image-program 'dvipng
3400 "Program to convert LaTeX fragments with.
3402 dvipng Process the LaTeX fragments to dvi file, then convert
3403 dvi files to png files using dvipng.
3404 This will also include processing of non-math environments.
3405 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3406 to convert pdf files to png files"
3407 :group 'org-latex
3408 :version "24.1"
3409 :type '(choice
3410 (const :tag "dvipng" dvipng)
3411 (const :tag "imagemagick" imagemagick)))
3413 (defun org-format-latex-mathml-available-p ()
3414 "Return t if `org-latex-to-mathml-convert-command' is usable."
3415 (save-match-data
3416 (when (and (boundp 'org-latex-to-mathml-convert-command)
3417 org-latex-to-mathml-convert-command)
3418 (let ((executable (car (split-string
3419 org-latex-to-mathml-convert-command))))
3420 (when (executable-find executable)
3421 (if (string-match
3422 "%j" org-latex-to-mathml-convert-command)
3423 (file-readable-p org-latex-to-mathml-jar-file)
3424 t))))))
3426 (defcustom org-format-latex-header "\\documentclass{article}
3427 \\usepackage[usenames]{color}
3428 \\usepackage{amsmath}
3429 \\usepackage[mathscr]{eucal}
3430 \\pagestyle{empty} % do not remove
3431 \[PACKAGES]
3432 \[DEFAULT-PACKAGES]
3433 % The settings below are copied from fullpage.sty
3434 \\setlength{\\textwidth}{\\paperwidth}
3435 \\addtolength{\\textwidth}{-3cm}
3436 \\setlength{\\oddsidemargin}{1.5cm}
3437 \\addtolength{\\oddsidemargin}{-2.54cm}
3438 \\setlength{\\evensidemargin}{\\oddsidemargin}
3439 \\setlength{\\textheight}{\\paperheight}
3440 \\addtolength{\\textheight}{-\\headheight}
3441 \\addtolength{\\textheight}{-\\headsep}
3442 \\addtolength{\\textheight}{-\\footskip}
3443 \\addtolength{\\textheight}{-3cm}
3444 \\setlength{\\topmargin}{1.5cm}
3445 \\addtolength{\\topmargin}{-2.54cm}"
3446 "The document header used for processing LaTeX fragments.
3447 It is imperative that this header make sure that no page number
3448 appears on the page. The package defined in the variables
3449 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3450 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3451 will be appended."
3452 :group 'org-latex
3453 :type 'string)
3455 (defvar org-format-latex-header-extra nil)
3457 (defun org-set-packages-alist (var val)
3458 "Set the packages alist and make sure it has 3 elements per entry."
3459 (set var (mapcar (lambda (x)
3460 (if (and (consp x) (= (length x) 2))
3461 (list (car x) (nth 1 x) t)
3463 val)))
3465 (defun org-get-packages-alist (var)
3467 "Get the packages alist and make sure it has 3 elements per entry."
3468 (mapcar (lambda (x)
3469 (if (and (consp x) (= (length x) 2))
3470 (list (car x) (nth 1 x) t)
3472 (default-value var)))
3474 ;; The following variables are defined here because is it also used
3475 ;; when formatting latex fragments. Originally it was part of the
3476 ;; LaTeX exporter, which is why the name includes "export".
3477 (defcustom org-export-latex-default-packages-alist
3478 '(("AUTO" "inputenc" t)
3479 ("T1" "fontenc" t)
3480 ("" "fixltx2e" nil)
3481 ("" "graphicx" t)
3482 ("" "longtable" nil)
3483 ("" "float" nil)
3484 ("" "wrapfig" nil)
3485 ("" "soul" t)
3486 ("" "textcomp" t)
3487 ("" "marvosym" t)
3488 ("" "wasysym" t)
3489 ("" "latexsym" t)
3490 ("" "amssymb" t)
3491 ("" "hyperref" nil)
3492 "\\tolerance=1000"
3494 "Alist of default packages to be inserted in the header.
3495 Change this only if one of the packages here causes an incompatibility
3496 with another package you are using.
3497 The packages in this list are needed by one part or another of Org-mode
3498 to function properly.
3500 - inputenc, fontenc: for basic font and character selection
3501 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3502 for interpreting the entities in `org-entities'. You can skip some of these
3503 packages if you don't use any of the symbols in it.
3504 - graphicx: for including images
3505 - float, wrapfig: for figure placement
3506 - longtable: for long tables
3507 - hyperref: for cross references
3509 Therefore you should not modify this variable unless you know what you
3510 are doing. The one reason to change it anyway is that you might be loading
3511 some other package that conflicts with one of the default packages.
3512 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3513 If SNIPPET-FLAG is t, the package also needs to be included when
3514 compiling LaTeX snippets into images for inclusion into HTML."
3515 :group 'org-export-latex
3516 :set 'org-set-packages-alist
3517 :get 'org-get-packages-alist
3518 :version "24.1"
3519 :type '(repeat
3520 (choice
3521 (list :tag "options/package pair"
3522 (string :tag "options")
3523 (string :tag "package")
3524 (boolean :tag "Snippet"))
3525 (string :tag "A line of LaTeX"))))
3527 (defcustom org-export-latex-packages-alist nil
3528 "Alist of packages to be inserted in every LaTeX header.
3529 These will be inserted after `org-export-latex-default-packages-alist'.
3530 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3531 SNIPPET-FLAG, when t, indicates that this package is also needed when
3532 turning LaTeX snippets into images for inclusion into HTML.
3533 Make sure that you only list packages here which:
3534 - you want in every file
3535 - do not conflict with the default packages in
3536 `org-export-latex-default-packages-alist'
3537 - do not conflict with the setup in `org-format-latex-header'."
3538 :group 'org-export-latex
3539 :set 'org-set-packages-alist
3540 :get 'org-get-packages-alist
3541 :type '(repeat
3542 (choice
3543 (list :tag "options/package pair"
3544 (string :tag "options")
3545 (string :tag "package")
3546 (boolean :tag "Snippet"))
3547 (string :tag "A line of LaTeX"))))
3550 (defgroup org-appearance nil
3551 "Settings for Org-mode appearance."
3552 :tag "Org Appearance"
3553 :group 'org)
3555 (defcustom org-level-color-stars-only nil
3556 "Non-nil means fontify only the stars in each headline.
3557 When nil, the entire headline is fontified.
3558 Changing it requires restart of `font-lock-mode' to become effective
3559 also in regions already fontified."
3560 :group 'org-appearance
3561 :type 'boolean)
3563 (defcustom org-hide-leading-stars nil
3564 "Non-nil means hide the first N-1 stars in a headline.
3565 This works by using the face `org-hide' for these stars. This
3566 face is white for a light background, and black for a dark
3567 background. You may have to customize the face `org-hide' to
3568 make this work.
3569 Changing it requires restart of `font-lock-mode' to become effective
3570 also in regions already fontified.
3571 You may also set this on a per-file basis by adding one of the following
3572 lines to the buffer:
3574 #+STARTUP: hidestars
3575 #+STARTUP: showstars"
3576 :group 'org-appearance
3577 :type 'boolean)
3579 (defcustom org-hidden-keywords nil
3580 "List of symbols corresponding to keywords to be hidden the org buffer.
3581 For example, a value '(title) for this list will make the document's title
3582 appear in the buffer without the initial #+TITLE: keyword."
3583 :group 'org-appearance
3584 :version "24.1"
3585 :type '(set (const :tag "#+AUTHOR" author)
3586 (const :tag "#+DATE" date)
3587 (const :tag "#+EMAIL" email)
3588 (const :tag "#+TITLE" title)))
3590 (defcustom org-fontify-done-headline nil
3591 "Non-nil means change the face of a headline if it is marked DONE.
3592 Normally, only the TODO/DONE keyword indicates the state of a headline.
3593 When this is non-nil, the headline after the keyword is set to the
3594 `org-headline-done' as an additional indication."
3595 :group 'org-appearance
3596 :type 'boolean)
3598 (defcustom org-fontify-emphasized-text t
3599 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3600 Changing this variable requires a restart of Emacs to take effect."
3601 :group 'org-appearance
3602 :type 'boolean)
3604 (defcustom org-fontify-whole-heading-line nil
3605 "Non-nil means fontify the whole line for headings.
3606 This is useful when setting a background color for the
3607 org-level-* faces."
3608 :group 'org-appearance
3609 :type 'boolean)
3611 (defcustom org-highlight-latex-fragments-and-specials nil
3612 "Non-nil means fontify what is treated specially by the exporters."
3613 :group 'org-appearance
3614 :type 'boolean)
3616 (defcustom org-hide-emphasis-markers nil
3617 "Non-nil mean font-lock should hide the emphasis marker characters."
3618 :group 'org-appearance
3619 :type 'boolean)
3621 (defcustom org-pretty-entities nil
3622 "Non-nil means show entities as UTF8 characters.
3623 When nil, the \\name form remains in the buffer."
3624 :group 'org-appearance
3625 :version "24.1"
3626 :type 'boolean)
3628 (defcustom org-pretty-entities-include-sub-superscripts t
3629 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3630 :group 'org-appearance
3631 :version "24.1"
3632 :type 'boolean)
3634 (defvar org-emph-re nil
3635 "Regular expression for matching emphasis.
3636 After a match, the match groups contain these elements:
3637 0 The match of the full regular expression, including the characters
3638 before and after the proper match
3639 1 The character before the proper match, or empty at beginning of line
3640 2 The proper match, including the leading and trailing markers
3641 3 The leading marker like * or /, indicating the type of highlighting
3642 4 The text between the emphasis markers, not including the markers
3643 5 The character after the match, empty at the end of a line")
3644 (defvar org-verbatim-re nil
3645 "Regular expression for matching verbatim text.")
3646 (defvar org-emphasis-regexp-components) ; defined just below
3647 (defvar org-emphasis-alist) ; defined just below
3648 (defun org-set-emph-re (var val)
3649 "Set variable and compute the emphasis regular expression."
3650 (set var val)
3651 (when (and (boundp 'org-emphasis-alist)
3652 (boundp 'org-emphasis-regexp-components)
3653 org-emphasis-alist org-emphasis-regexp-components)
3654 (let* ((e org-emphasis-regexp-components)
3655 (pre (car e))
3656 (post (nth 1 e))
3657 (border (nth 2 e))
3658 (body (nth 3 e))
3659 (nl (nth 4 e))
3660 (body1 (concat body "*?"))
3661 (markers (mapconcat 'car org-emphasis-alist ""))
3662 (vmarkers (mapconcat
3663 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3664 org-emphasis-alist "")))
3665 ;; make sure special characters appear at the right position in the class
3666 (if (string-match "\\^" markers)
3667 (setq markers (concat (replace-match "" t t markers) "^")))
3668 (if (string-match "-" markers)
3669 (setq markers (concat (replace-match "" t t markers) "-")))
3670 (if (string-match "\\^" vmarkers)
3671 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3672 (if (string-match "-" vmarkers)
3673 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3674 (if (> nl 0)
3675 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3676 (int-to-string nl) "\\}")))
3677 ;; Make the regexp
3678 (setq org-emph-re
3679 (concat "\\([" pre "]\\|^\\)"
3680 "\\("
3681 "\\([" markers "]\\)"
3682 "\\("
3683 "[^" border "]\\|"
3684 "[^" border "]"
3685 body1
3686 "[^" border "]"
3687 "\\)"
3688 "\\3\\)"
3689 "\\([" post "]\\|$\\)"))
3690 (setq org-verbatim-re
3691 (concat "\\([" pre "]\\|^\\)"
3692 "\\("
3693 "\\([" vmarkers "]\\)"
3694 "\\("
3695 "[^" border "]\\|"
3696 "[^" border "]"
3697 body1
3698 "[^" border "]"
3699 "\\)"
3700 "\\3\\)"
3701 "\\([" post "]\\|$\\)")))))
3703 (defcustom org-emphasis-regexp-components
3704 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3705 "Components used to build the regular expression for emphasis.
3706 This is a list with five entries. Terminology: In an emphasis string
3707 like \" *strong word* \", we call the initial space PREMATCH, the final
3708 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3709 and \"trong wor\" is the body. The different components in this variable
3710 specify what is allowed/forbidden in each part:
3712 pre Chars allowed as prematch. Beginning of line will be allowed too.
3713 post Chars allowed as postmatch. End of line will be allowed too.
3714 border The chars *forbidden* as border characters.
3715 body-regexp A regexp like \".\" to match a body character. Don't use
3716 non-shy groups here, and don't allow newline here.
3717 newline The maximum number of newlines allowed in an emphasis exp.
3719 Use customize to modify this, or restart Emacs after changing it."
3720 :group 'org-appearance
3721 :set 'org-set-emph-re
3722 :type '(list
3723 (sexp :tag "Allowed chars in pre ")
3724 (sexp :tag "Allowed chars in post ")
3725 (sexp :tag "Forbidden chars in border ")
3726 (sexp :tag "Regexp for body ")
3727 (integer :tag "number of newlines allowed")
3728 (option (boolean :tag "Please ignore this button"))))
3730 (defcustom org-emphasis-alist
3731 `(("*" bold "<b>" "</b>")
3732 ("/" italic "<i>" "</i>")
3733 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3734 ("=" org-code "<code>" "</code>" verbatim)
3735 ("~" org-verbatim "<code>" "</code>" verbatim)
3736 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3737 "<del>" "</del>")
3739 "Special syntax for emphasized text.
3740 Text starting and ending with a special character will be emphasized, for
3741 example *bold*, _underlined_ and /italic/. This variable sets the marker
3742 characters, the face to be used by font-lock for highlighting in Org-mode
3743 Emacs buffers, and the HTML tags to be used for this.
3744 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3745 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3746 Use customize to modify this, or restart Emacs after changing it."
3747 :group 'org-appearance
3748 :set 'org-set-emph-re
3749 :type '(repeat
3750 (list
3751 (string :tag "Marker character")
3752 (choice
3753 (face :tag "Font-lock-face")
3754 (plist :tag "Face property list"))
3755 (string :tag "HTML start tag")
3756 (string :tag "HTML end tag")
3757 (option (const verbatim)))))
3759 (defvar org-protecting-blocks
3760 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3761 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3762 This is needed for font-lock setup.")
3764 ;;; Miscellaneous options
3766 (defgroup org-completion nil
3767 "Completion in Org-mode."
3768 :tag "Org Completion"
3769 :group 'org)
3771 (defcustom org-completion-use-ido nil
3772 "Non-nil means use ido completion wherever possible.
3773 Note that `ido-mode' must be active for this variable to be relevant.
3774 If you decide to turn this variable on, you might well want to turn off
3775 `org-outline-path-complete-in-steps'.
3776 See also `org-completion-use-iswitchb'."
3777 :group 'org-completion
3778 :type 'boolean)
3780 (defcustom org-completion-use-iswitchb nil
3781 "Non-nil means use iswitchb completion wherever possible.
3782 Note that `iswitchb-mode' must be active for this variable to be relevant.
3783 If you decide to turn this variable on, you might well want to turn off
3784 `org-outline-path-complete-in-steps'.
3785 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3786 :group 'org-completion
3787 :type 'boolean)
3789 (defcustom org-completion-fallback-command 'hippie-expand
3790 "The expansion command called by \\[pcomplete] in normal context.
3791 Normal means, no org-mode-specific context."
3792 :group 'org-completion
3793 :type 'function)
3795 ;;; Functions and variables from their packages
3796 ;; Declared here to avoid compiler warnings
3798 ;; XEmacs only
3799 (defvar outline-mode-menu-heading)
3800 (defvar outline-mode-menu-show)
3801 (defvar outline-mode-menu-hide)
3802 (defvar zmacs-regions) ; XEmacs regions
3804 ;; Emacs only
3805 (defvar mark-active)
3807 ;; Various packages
3808 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3809 (declare-function calendar-forward-day "cal-move" (arg))
3810 (declare-function calendar-goto-date "cal-move" (date))
3811 (declare-function calendar-goto-today "cal-move" ())
3812 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3813 (defvar calc-embedded-close-formula)
3814 (defvar calc-embedded-open-formula)
3815 (declare-function cdlatex-tab "ext:cdlatex" ())
3816 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3817 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3818 (defvar font-lock-unfontify-region-function)
3819 (declare-function iswitchb-read-buffer "iswitchb"
3820 (prompt &optional default require-match start matches-set))
3821 (defvar iswitchb-temp-buflist)
3822 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3823 (defvar org-agenda-tags-todo-honor-ignore-options)
3824 (declare-function org-agenda-skip "org-agenda" ())
3825 (declare-function
3826 org-agenda-format-item "org-agenda"
3827 (extra txt &optional category tags dotime noprefix remove-re habitp))
3828 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3829 (declare-function org-agenda-change-all-lines "org-agenda"
3830 (newhead hdmarker &optional fixface just-this))
3831 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3832 (declare-function org-agenda-maybe-redo "org-agenda" ())
3833 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3834 (beg end))
3835 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3836 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3837 "org-agenda" (&optional end))
3838 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3839 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3840 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3841 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3842 (declare-function org-indent-mode "org-indent" (&optional arg))
3843 (declare-function parse-time-string "parse-time" (string))
3844 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3845 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3846 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3847 (defvar remember-data-file)
3848 (defvar texmathp-why)
3849 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3850 (declare-function table--at-cell-p "table" (position &optional object at-column))
3852 (defvar w3m-current-url)
3853 (defvar w3m-current-title)
3855 (defvar org-latex-regexps)
3857 ;;; Autoload and prepare some org modules
3859 ;; Some table stuff that needs to be defined here, because it is used
3860 ;; by the functions setting up org-mode or checking for table context.
3862 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3863 "Detect an org-type or table-type table.")
3864 (defconst org-table-line-regexp "^[ \t]*|"
3865 "Detect an org-type table line.")
3866 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3867 "Detect an org-type table line.")
3868 (defconst org-table-hline-regexp "^[ \t]*|-"
3869 "Detect an org-type table hline.")
3870 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3871 "Detect a table-type table hline.")
3872 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3873 "Detect the first line outside a table when searching from within it.
3874 This works for both table types.")
3876 ;; Autoload the functions in org-table.el that are needed by functions here.
3878 (eval-and-compile
3879 (org-autoload "org-table"
3880 '(org-table-align org-table-begin org-table-blank-field
3881 org-table-convert org-table-convert-region org-table-copy-down
3882 org-table-copy-region org-table-create
3883 org-table-create-or-convert-from-region
3884 org-table-create-with-table.el org-table-current-dline
3885 org-table-cut-region org-table-delete-column org-table-edit-field
3886 org-table-edit-formulas org-table-end org-table-eval-formula
3887 org-table-export org-table-field-info
3888 org-table-get-stored-formulas org-table-goto-column
3889 org-table-hline-and-move org-table-import org-table-insert-column
3890 org-table-insert-hline org-table-insert-row org-table-iterate
3891 org-table-justify-field-maybe org-table-kill-row
3892 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3893 org-table-move-column org-table-move-column-left
3894 org-table-move-column-right org-table-move-row
3895 org-table-move-row-down org-table-move-row-up
3896 org-table-next-field org-table-next-row org-table-paste-rectangle
3897 org-table-previous-field org-table-recalculate
3898 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3899 org-table-toggle-coordinate-overlays
3900 org-table-toggle-formula-debugger org-table-wrap-region
3901 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3902 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3903 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3905 (defun org-at-table-p (&optional table-type)
3906 "Return t if the cursor is inside an org-type table.
3907 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3908 (if org-enable-table-editor
3909 (save-excursion
3910 (beginning-of-line 1)
3911 (looking-at (if table-type org-table-any-line-regexp
3912 org-table-line-regexp)))
3913 nil))
3914 (defsubst org-table-p () (org-at-table-p))
3916 (defun org-at-table.el-p ()
3917 "Return t if and only if we are at a table.el table."
3918 (and (org-at-table-p 'any)
3919 (save-excursion
3920 (goto-char (org-table-begin 'any))
3921 (looking-at org-table1-hline-regexp))))
3922 (defun org-table-recognize-table.el ()
3923 "If there is a table.el table nearby, recognize it and move into it."
3924 (if org-table-tab-recognizes-table.el
3925 (if (org-at-table.el-p)
3926 (progn
3927 (beginning-of-line 1)
3928 (if (looking-at org-table-dataline-regexp)
3930 (if (looking-at org-table1-hline-regexp)
3931 (progn
3932 (beginning-of-line 2)
3933 (if (looking-at org-table-any-border-regexp)
3934 (beginning-of-line -1)))))
3935 (if (re-search-forward "|" (org-table-end t) t)
3936 (progn
3937 (require 'table)
3938 (if (table--at-cell-p (point))
3940 (message "recognizing table.el table...")
3941 (table-recognize-table)
3942 (message "recognizing table.el table...done")))
3943 (error "This should not happen"))
3945 nil)
3946 nil))
3948 (defun org-at-table-hline-p ()
3949 "Return t if the cursor is inside a hline in a table."
3950 (if org-enable-table-editor
3951 (save-excursion
3952 (beginning-of-line 1)
3953 (looking-at org-table-hline-regexp))
3954 nil))
3956 (defvar org-table-clean-did-remove-column nil)
3958 (defun org-table-map-tables (function &optional quietly)
3959 "Apply FUNCTION to the start of all tables in the buffer."
3960 (save-excursion
3961 (save-restriction
3962 (widen)
3963 (goto-char (point-min))
3964 (while (re-search-forward org-table-any-line-regexp nil t)
3965 (unless quietly
3966 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3967 (beginning-of-line 1)
3968 (when (and (looking-at org-table-line-regexp)
3969 ;; Exclude tables in src/example/verbatim/clocktable blocks
3970 (not (org-in-block-p '("src" "example"))))
3971 (save-excursion (funcall function))
3972 (or (looking-at org-table-line-regexp)
3973 (forward-char 1)))
3974 (re-search-forward org-table-any-border-regexp nil 1))))
3975 (unless quietly (message "Mapping tables: done")))
3977 ;; Declare and autoload functions from org-exp.el & Co
3979 (declare-function org-default-export-plist "org-exp")
3980 (declare-function org-infile-export-plist "org-exp")
3981 (declare-function org-get-current-options "org-exp")
3982 (eval-and-compile
3983 (org-autoload "org-exp"
3984 '(org-export org-export-visible
3985 org-insert-export-options-template
3986 org-table-clean-before-export))
3987 (org-autoload "org-ascii"
3988 '(org-export-as-ascii org-export-ascii-preprocess
3989 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3990 org-export-region-as-ascii))
3991 (org-autoload "org-latex"
3992 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3993 org-replace-region-by-latex org-export-region-as-latex
3994 org-export-as-latex org-export-as-pdf
3995 org-export-as-pdf-and-open))
3996 (org-autoload "org-html"
3997 '(org-export-as-html-and-open
3998 org-export-as-html-batch org-export-as-html-to-buffer
3999 org-replace-region-by-html org-export-region-as-html
4000 org-export-as-html))
4001 (org-autoload "org-docbook"
4002 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4003 org-replace-region-by-docbook org-export-region-as-docbook
4004 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4005 org-export-as-docbook))
4006 (org-autoload "org-icalendar"
4007 '(org-export-icalendar-this-file
4008 org-export-icalendar-all-agenda-files
4009 org-export-icalendar-combine-agenda-files))
4010 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4011 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4013 ;; Declare and autoload functions from org-agenda.el
4015 (eval-and-compile
4016 (org-autoload "org-agenda"
4017 '(org-agenda org-agenda-list org-search-view
4018 org-todo-list org-tags-view org-agenda-list-stuck-projects
4019 org-diary org-agenda-to-appt
4020 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4022 ;; Autoload org-remember
4024 (eval-and-compile
4025 (org-autoload "org-remember"
4026 '(org-remember-insinuate org-remember-annotation
4027 org-remember-apply-template org-remember org-remember-handler)))
4029 (eval-and-compile
4030 (org-autoload "org-capture"
4031 '(org-capture org-capture-insert-template-here
4032 org-capture-import-remember-templates)))
4034 ;; Autoload org-clock.el
4036 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4037 (beg end))
4038 (declare-function org-clock-update-mode-line "org-clock" ())
4039 (declare-function org-resolve-clocks "org-clock"
4040 (&optional also-non-dangling-p prompt last-valid))
4041 (defvar org-clock-start-time)
4042 (defvar org-clock-marker (make-marker)
4043 "Marker recording the last clock-in.")
4044 (defvar org-clock-hd-marker (make-marker)
4045 "Marker recording the last clock-in, but the headline position.")
4046 (defvar org-clock-heading ""
4047 "The heading of the current clock entry.")
4048 (defun org-clock-is-active ()
4049 "Return non-nil if clock is currently running.
4050 The return value is actually the clock marker."
4051 (marker-buffer org-clock-marker))
4053 (eval-and-compile
4054 (org-autoload
4055 "org-clock"
4056 '(org-clock-in org-clock-out org-clock-cancel
4057 org-clock-goto org-clock-sum org-clock-display
4058 org-clock-remove-overlays org-clock-report
4059 org-clocktable-shift org-dblock-write:clocktable
4060 org-get-clocktable org-resolve-clocks)))
4062 (defun org-clock-update-time-maybe ()
4063 "If this is a CLOCK line, update it and return t.
4064 Otherwise, return nil."
4065 (interactive)
4066 (save-excursion
4067 (beginning-of-line 1)
4068 (skip-chars-forward " \t")
4069 (when (looking-at org-clock-string)
4070 (let ((re (concat "[ \t]*" org-clock-string
4071 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4072 "\\([ \t]*=>.*\\)?\\)?"))
4073 ts te h m s neg)
4074 (cond
4075 ((not (looking-at re))
4076 nil)
4077 ((not (match-end 2))
4078 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4079 (> org-clock-marker (point))
4080 (<= org-clock-marker (point-at-eol)))
4081 ;; The clock is running here
4082 (setq org-clock-start-time
4083 (apply 'encode-time
4084 (org-parse-time-string (match-string 1))))
4085 (org-clock-update-mode-line)))
4087 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4088 (end-of-line 1)
4089 (setq ts (match-string 1)
4090 te (match-string 3))
4091 (setq s (- (org-float-time
4092 (apply 'encode-time (org-parse-time-string te)))
4093 (org-float-time
4094 (apply 'encode-time (org-parse-time-string ts))))
4095 neg (< s 0)
4096 s (abs s)
4097 h (floor (/ s 3600))
4098 s (- s (* 3600 h))
4099 m (floor (/ s 60))
4100 s (- s (* 60 s)))
4101 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4102 t))))))
4104 (defun org-check-running-clock ()
4105 "Check if the current buffer contains the running clock.
4106 If yes, offer to stop it and to save the buffer with the changes."
4107 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4108 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4109 (buffer-name))))
4110 (org-clock-out)
4111 (when (y-or-n-p "Save changed buffer?")
4112 (save-buffer))))
4114 (defun org-clocktable-try-shift (dir n)
4115 "Check if this line starts a clock table, if yes, shift the time block."
4116 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4117 (org-clocktable-shift dir n)))
4119 ;; Autoload org-timer.el
4121 (eval-and-compile
4122 (org-autoload
4123 "org-timer"
4124 '(org-timer-start org-timer org-timer-item
4125 org-timer-change-times-in-region
4126 org-timer-set-timer
4127 org-timer-reset-timers
4128 org-timer-show-remaining-time)))
4130 ;; Autoload org-feed.el
4132 (eval-and-compile
4133 (org-autoload
4134 "org-feed"
4135 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4138 ;; Autoload org-indent.el
4140 ;; Define the variable already here, to make sure we have it.
4141 (defvar org-indent-mode nil
4142 "Non-nil if Org-Indent mode is enabled.
4143 Use the command `org-indent-mode' to change this variable.")
4145 (eval-and-compile
4146 (org-autoload
4147 "org-indent"
4148 '(org-indent-mode)))
4150 ;; Autoload org-mobile.el
4152 (eval-and-compile
4153 (org-autoload
4154 "org-mobile"
4155 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4157 ;; Autoload archiving code
4158 ;; The stuff that is needed for cycling and tags has to be defined here.
4160 (defgroup org-archive nil
4161 "Options concerning archiving in Org-mode."
4162 :tag "Org Archive"
4163 :group 'org-structure)
4165 (defcustom org-archive-location "%s_archive::"
4166 "The location where subtrees should be archived.
4168 The value of this variable is a string, consisting of two parts,
4169 separated by a double-colon. The first part is a filename and
4170 the second part is a headline.
4172 When the filename is omitted, archiving happens in the same file.
4173 %s in the filename will be replaced by the current file
4174 name (without the directory part). Archiving to a different file
4175 is useful to keep archived entries from contributing to the
4176 Org-mode Agenda.
4178 The archived entries will be filed as subtrees of the specified
4179 headline. When the headline is omitted, the subtrees are simply
4180 filed away at the end of the file, as top-level entries. Also in
4181 the heading you can use %s to represent the file name, this can be
4182 useful when using the same archive for a number of different files.
4184 Here are a few examples:
4185 \"%s_archive::\"
4186 If the current file is Projects.org, archive in file
4187 Projects.org_archive, as top-level trees. This is the default.
4189 \"::* Archived Tasks\"
4190 Archive in the current file, under the top-level headline
4191 \"* Archived Tasks\".
4193 \"~/org/archive.org::\"
4194 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4196 \"~/org/archive.org::* From %s\"
4197 Archive in file ~/org/archive.org (absolute path), under headlines
4198 \"From FILENAME\" where file name is the current file name.
4200 \"~/org/datetree.org::datetree/* Finished Tasks\"
4201 The \"datetree/\" string is special, signifying to archive
4202 items to the datetree. Items are placed in either the CLOSED
4203 date of the item, or the current date if there is no CLOSED date.
4204 The heading will be a subentry to the current date. There doesn't
4205 need to be a heading, but there always needs to be a slash after
4206 datetree. For example, to store archived items directly in the
4207 datetree, use \"~/org/datetree.org::datetree/\".
4209 \"basement::** Finished Tasks\"
4210 Archive in file ./basement (relative path), as level 3 trees
4211 below the level 2 heading \"** Finished Tasks\".
4213 You may set this option on a per-file basis by adding to the buffer a
4214 line like
4216 #+ARCHIVE: basement::** Finished Tasks
4218 You may also define it locally for a subtree by setting an ARCHIVE property
4219 in the entry. If such a property is found in an entry, or anywhere up
4220 the hierarchy, it will be used."
4221 :group 'org-archive
4222 :type 'string)
4224 (defcustom org-archive-tag "ARCHIVE"
4225 "The tag that marks a subtree as archived.
4226 An archived subtree does not open during visibility cycling, and does
4227 not contribute to the agenda listings.
4228 After changing this, font-lock must be restarted in the relevant buffers to
4229 get the proper fontification."
4230 :group 'org-archive
4231 :group 'org-keywords
4232 :type 'string)
4234 (defcustom org-agenda-skip-archived-trees t
4235 "Non-nil means the agenda will skip any items located in archived trees.
4236 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4237 variable is no longer recommended, you should leave it at the value t.
4238 Instead, use the key `v' to cycle the archives-mode in the agenda."
4239 :group 'org-archive
4240 :group 'org-agenda-skip
4241 :type 'boolean)
4243 (defcustom org-columns-skip-archived-trees t
4244 "Non-nil means ignore archived trees when creating column view."
4245 :group 'org-archive
4246 :group 'org-properties
4247 :type 'boolean)
4249 (defcustom org-cycle-open-archived-trees nil
4250 "Non-nil means `org-cycle' will open archived trees.
4251 An archived tree is a tree marked with the tag ARCHIVE.
4252 When nil, archived trees will stay folded. You can still open them with
4253 normal outline commands like `show-all', but not with the cycling commands."
4254 :group 'org-archive
4255 :group 'org-cycle
4256 :type 'boolean)
4258 (defcustom org-sparse-tree-open-archived-trees nil
4259 "Non-nil means sparse tree construction shows matches in archived trees.
4260 When nil, matches in these trees are highlighted, but the trees are kept in
4261 collapsed state."
4262 :group 'org-archive
4263 :group 'org-sparse-trees
4264 :type 'boolean)
4266 (defun org-cycle-hide-archived-subtrees (state)
4267 "Re-hide all archived subtrees after a visibility state change."
4268 (when (and (not org-cycle-open-archived-trees)
4269 (not (memq state '(overview folded))))
4270 (save-excursion
4271 (let* ((globalp (memq state '(contents all)))
4272 (beg (if globalp (point-min) (point)))
4273 (end (if globalp (point-max) (org-end-of-subtree t))))
4274 (org-hide-archived-subtrees beg end)
4275 (goto-char beg)
4276 (if (looking-at (concat ".*:" org-archive-tag ":"))
4277 (message "%s" (substitute-command-keys
4278 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4280 (defun org-force-cycle-archived ()
4281 "Cycle subtree even if it is archived."
4282 (interactive)
4283 (setq this-command 'org-cycle)
4284 (let ((org-cycle-open-archived-trees t))
4285 (call-interactively 'org-cycle)))
4287 (defun org-hide-archived-subtrees (beg end)
4288 "Re-hide all archived subtrees after a visibility state change."
4289 (save-excursion
4290 (let* ((re (concat ":" org-archive-tag ":")))
4291 (goto-char beg)
4292 (while (re-search-forward re end t)
4293 (when (org-at-heading-p)
4294 (org-flag-subtree t)
4295 (org-end-of-subtree t))))))
4297 (defun org-flag-subtree (flag)
4298 (save-excursion
4299 (org-back-to-heading t)
4300 (outline-end-of-heading)
4301 (outline-flag-region (point)
4302 (progn (org-end-of-subtree t) (point))
4303 flag)))
4305 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4307 (eval-and-compile
4308 (org-autoload "org-archive"
4309 '(org-add-archive-files org-archive-subtree
4310 org-archive-to-archive-sibling org-toggle-archive-tag
4311 org-archive-subtree-default
4312 org-archive-subtree-default-with-confirmation)))
4314 ;; Autoload Column View Code
4316 (declare-function org-columns-number-to-string "org-colview")
4317 (declare-function org-columns-get-format-and-top-level "org-colview")
4318 (declare-function org-columns-compute "org-colview")
4320 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4321 '(org-columns-number-to-string org-columns-get-format-and-top-level
4322 org-columns-compute org-agenda-columns org-columns-remove-overlays
4323 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4325 ;; Autoload ID code
4327 (declare-function org-id-store-link "org-id")
4328 (declare-function org-id-locations-load "org-id")
4329 (declare-function org-id-locations-save "org-id")
4330 (defvar org-id-track-globally)
4331 (org-autoload "org-id"
4332 '(org-id-get-create org-id-new org-id-copy org-id-get
4333 org-id-get-with-outline-path-completion
4334 org-id-get-with-outline-drilling org-id-store-link
4335 org-id-goto org-id-find org-id-store-link))
4337 ;; Autoload Plotting Code
4339 (org-autoload "org-plot"
4340 '(org-plot/gnuplot))
4342 ;;; Variables for pre-computed regular expressions, all buffer local
4344 (defvar org-drawer-regexp nil
4345 "Matches first line of a hidden block.")
4346 (make-variable-buffer-local 'org-drawer-regexp)
4347 (defvar org-todo-regexp nil
4348 "Matches any of the TODO state keywords.")
4349 (make-variable-buffer-local 'org-todo-regexp)
4350 (defvar org-not-done-regexp nil
4351 "Matches any of the TODO state keywords except the last one.")
4352 (make-variable-buffer-local 'org-not-done-regexp)
4353 (defvar org-not-done-heading-regexp nil
4354 "Matches a TODO headline that is not done.")
4355 (make-variable-buffer-local 'org-not-done-regexp)
4356 (defvar org-todo-line-regexp nil
4357 "Matches a headline and puts TODO state into group 2 if present.")
4358 (make-variable-buffer-local 'org-todo-line-regexp)
4359 (defvar org-complex-heading-regexp nil
4360 "Matches a headline and puts everything into groups:
4361 group 1: the stars
4362 group 2: The todo keyword, maybe
4363 group 3: Priority cookie
4364 group 4: True headline
4365 group 5: Tags")
4366 (make-variable-buffer-local 'org-complex-heading-regexp)
4367 (defvar org-complex-heading-regexp-format nil
4368 "Printf format to make regexp to match an exact headline.
4369 This regexp will match the headline of any node which has the
4370 exact headline text that is put into the format, but may have any
4371 TODO state, priority and tags.")
4372 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4373 (defvar org-todo-line-tags-regexp nil
4374 "Matches a headline and puts TODO state into group 2 if present.
4375 Also put tags into group 4 if tags are present.")
4376 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4377 (defvar org-ds-keyword-length 12
4378 "Maximum length of the Deadline and SCHEDULED keywords.")
4379 (make-variable-buffer-local 'org-ds-keyword-length)
4380 (defvar org-deadline-regexp nil
4381 "Matches the DEADLINE keyword.")
4382 (make-variable-buffer-local 'org-deadline-regexp)
4383 (defvar org-deadline-time-regexp nil
4384 "Matches the DEADLINE keyword together with a time stamp.")
4385 (make-variable-buffer-local 'org-deadline-time-regexp)
4386 (defvar org-deadline-line-regexp nil
4387 "Matches the DEADLINE keyword and the rest of the line.")
4388 (make-variable-buffer-local 'org-deadline-line-regexp)
4389 (defvar org-scheduled-regexp nil
4390 "Matches the SCHEDULED keyword.")
4391 (make-variable-buffer-local 'org-scheduled-regexp)
4392 (defvar org-scheduled-time-regexp nil
4393 "Matches the SCHEDULED keyword together with a time stamp.")
4394 (make-variable-buffer-local 'org-scheduled-time-regexp)
4395 (defvar org-closed-time-regexp nil
4396 "Matches the CLOSED keyword together with a time stamp.")
4397 (make-variable-buffer-local 'org-closed-time-regexp)
4399 (defvar org-keyword-time-regexp nil
4400 "Matches any of the 4 keywords, together with the time stamp.")
4401 (make-variable-buffer-local 'org-keyword-time-regexp)
4402 (defvar org-keyword-time-not-clock-regexp nil
4403 "Matches any of the 3 keywords, together with the time stamp.")
4404 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4405 (defvar org-maybe-keyword-time-regexp nil
4406 "Matches a timestamp, possibly preceded by a keyword.")
4407 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4408 (defvar org-planning-or-clock-line-re nil
4409 "Matches a line with planning or clock info.")
4410 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4411 (defvar org-all-time-keywords nil
4412 "List of time keywords.")
4413 (make-variable-buffer-local 'org-all-time-keywords)
4415 (defconst org-plain-time-of-day-regexp
4416 (concat
4417 "\\(\\<[012]?[0-9]"
4418 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4419 "\\(--?"
4420 "\\(\\<[012]?[0-9]"
4421 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4422 "\\)?")
4423 "Regular expression to match a plain time or time range.
4424 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4425 groups carry important information:
4426 0 the full match
4427 1 the first time, range or not
4428 8 the second time, if it is a range.")
4430 (defconst org-plain-time-extension-regexp
4431 (concat
4432 "\\(\\<[012]?[0-9]"
4433 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4434 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4435 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4436 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4437 groups carry important information:
4438 0 the full match
4439 7 hours of duration
4440 9 minutes of duration")
4442 (defconst org-stamp-time-of-day-regexp
4443 (concat
4444 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4445 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4446 "\\(--?"
4447 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4448 "Regular expression to match a timestamp time or time range.
4449 After a match, the following groups carry important information:
4450 0 the full match
4451 1 date plus weekday, for back referencing to make sure both times are on the same day
4452 2 the first time, range or not
4453 4 the second time, if it is a range.")
4455 (defconst org-startup-options
4456 '(("fold" org-startup-folded t)
4457 ("overview" org-startup-folded t)
4458 ("nofold" org-startup-folded nil)
4459 ("showall" org-startup-folded nil)
4460 ("showeverything" org-startup-folded showeverything)
4461 ("content" org-startup-folded content)
4462 ("indent" org-startup-indented t)
4463 ("noindent" org-startup-indented nil)
4464 ("hidestars" org-hide-leading-stars t)
4465 ("showstars" org-hide-leading-stars nil)
4466 ("odd" org-odd-levels-only t)
4467 ("oddeven" org-odd-levels-only nil)
4468 ("align" org-startup-align-all-tables t)
4469 ("noalign" org-startup-align-all-tables nil)
4470 ("inlineimages" org-startup-with-inline-images t)
4471 ("noinlineimages" org-startup-with-inline-images nil)
4472 ("customtime" org-display-custom-times t)
4473 ("logdone" org-log-done time)
4474 ("lognotedone" org-log-done note)
4475 ("nologdone" org-log-done nil)
4476 ("lognoteclock-out" org-log-note-clock-out t)
4477 ("nolognoteclock-out" org-log-note-clock-out nil)
4478 ("logrepeat" org-log-repeat state)
4479 ("lognoterepeat" org-log-repeat note)
4480 ("nologrepeat" org-log-repeat nil)
4481 ("logreschedule" org-log-reschedule time)
4482 ("lognotereschedule" org-log-reschedule note)
4483 ("nologreschedule" org-log-reschedule nil)
4484 ("logredeadline" org-log-redeadline time)
4485 ("lognoteredeadline" org-log-redeadline note)
4486 ("nologredeadline" org-log-redeadline nil)
4487 ("logrefile" org-log-refile time)
4488 ("lognoterefile" org-log-refile note)
4489 ("nologrefile" org-log-refile nil)
4490 ("fninline" org-footnote-define-inline t)
4491 ("nofninline" org-footnote-define-inline nil)
4492 ("fnlocal" org-footnote-section nil)
4493 ("fnauto" org-footnote-auto-label t)
4494 ("fnprompt" org-footnote-auto-label nil)
4495 ("fnconfirm" org-footnote-auto-label confirm)
4496 ("fnplain" org-footnote-auto-label plain)
4497 ("fnadjust" org-footnote-auto-adjust t)
4498 ("nofnadjust" org-footnote-auto-adjust nil)
4499 ("constcgs" constants-unit-system cgs)
4500 ("constSI" constants-unit-system SI)
4501 ("noptag" org-tag-persistent-alist nil)
4502 ("hideblocks" org-hide-block-startup t)
4503 ("nohideblocks" org-hide-block-startup nil)
4504 ("beamer" org-startup-with-beamer-mode t)
4505 ("entitiespretty" org-pretty-entities t)
4506 ("entitiesplain" org-pretty-entities nil))
4507 "Variable associated with STARTUP options for org-mode.
4508 Each element is a list of three items: the startup options (as written
4509 in the #+STARTUP line), the corresponding variable, and the value to set
4510 this variable to if the option is found. An optional forth element PUSH
4511 means to push this value onto the list in the variable.")
4513 (defun org-update-property-plist (key val props)
4514 "Update PROPS with KEY and VAL."
4515 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4516 (key (if appending (substring key 0 (- (length key) 1)) key))
4517 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4518 (previous (cdr (assoc key props))))
4519 (if appending
4520 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4521 (cons (cons key val) remainder))))
4523 (defconst org-block-regexp
4524 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4525 "Regular expression for hiding blocks.")
4526 (defconst org-heading-keyword-regexp-format
4527 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4528 "Printf format for a regexp matching an headline with some keyword.
4529 This regexp will match the headline of any node which has the
4530 exact keyword that is put into the format. The keyword isn't in
4531 any group by default, but the stars and the body are.")
4532 (defconst org-heading-keyword-maybe-regexp-format
4533 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4534 "Printf format for a regexp matching an headline, possibly with some keyword.
4535 This regexp can match any headline with the specified keyword, or
4536 without a keyword. The keyword isn't in any group by default,
4537 but the stars and the body are.")
4539 (defun org-set-regexps-and-options ()
4540 "Precompute regular expressions for current buffer."
4541 (when (derived-mode-p 'org-mode)
4542 (org-set-local 'org-todo-kwd-alist nil)
4543 (org-set-local 'org-todo-key-alist nil)
4544 (org-set-local 'org-todo-key-trigger nil)
4545 (org-set-local 'org-todo-keywords-1 nil)
4546 (org-set-local 'org-done-keywords nil)
4547 (org-set-local 'org-todo-heads nil)
4548 (org-set-local 'org-todo-sets nil)
4549 (org-set-local 'org-todo-log-states nil)
4550 (org-set-local 'org-file-properties nil)
4551 (org-set-local 'org-file-tags nil)
4552 (let ((re (org-make-options-regexp
4553 '("CATEGORY" "TODO" "COLUMNS"
4554 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4555 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4556 "OPTIONS")
4557 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4558 (splitre "[ \t]+")
4559 (scripts org-use-sub-superscripts)
4560 kwds kws0 kwsa key log value cat arch tags const links hw dws
4561 tail sep kws1 prio props ftags drawers beamer-p
4562 ext-setup-or-nil setup-contents (start 0))
4563 (save-excursion
4564 (save-restriction
4565 (widen)
4566 (goto-char (point-min))
4567 (while (or (and ext-setup-or-nil
4568 (string-match re ext-setup-or-nil start)
4569 (setq start (match-end 0)))
4570 (and (setq ext-setup-or-nil nil start 0)
4571 (re-search-forward re nil t)))
4572 (setq key (upcase (match-string 1 ext-setup-or-nil))
4573 value (org-match-string-no-properties 2 ext-setup-or-nil))
4574 (if (stringp value) (setq value (org-trim value)))
4575 (cond
4576 ((equal key "CATEGORY")
4577 (setq cat value))
4578 ((member key '("SEQ_TODO" "TODO"))
4579 (push (cons 'sequence (org-split-string value splitre)) kwds))
4580 ((equal key "TYP_TODO")
4581 (push (cons 'type (org-split-string value splitre)) kwds))
4582 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4583 ;; general TODO-like setup
4584 (push (cons (intern (downcase (match-string 1 key)))
4585 (org-split-string value splitre)) kwds))
4586 ((equal key "TAGS")
4587 (setq tags (append tags (if tags '("\\n") nil)
4588 (org-split-string value splitre))))
4589 ((equal key "COLUMNS")
4590 (org-set-local 'org-columns-default-format value))
4591 ((equal key "LINK")
4592 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4593 (push (cons (match-string 1 value)
4594 (org-trim (match-string 2 value)))
4595 links)))
4596 ((equal key "PRIORITIES")
4597 (setq prio (org-split-string value " +")))
4598 ((equal key "PROPERTY")
4599 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4600 (setq props (org-update-property-plist (match-string 1 value)
4601 (match-string 2 value)
4602 props))))
4603 ((equal key "FILETAGS")
4604 (when (string-match "\\S-" value)
4605 (setq ftags
4606 (append
4607 ftags
4608 (apply 'append
4609 (mapcar (lambda (x) (org-split-string x ":"))
4610 (org-split-string value)))))))
4611 ((equal key "DRAWERS")
4612 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4613 ((equal key "CONSTANTS")
4614 (setq const (append const (org-split-string value splitre))))
4615 ((equal key "STARTUP")
4616 (let ((opts (org-split-string value splitre))
4617 l var val)
4618 (while (setq l (pop opts))
4619 (when (setq l (assoc l org-startup-options))
4620 (setq var (nth 1 l) val (nth 2 l))
4621 (if (not (nth 3 l))
4622 (set (make-local-variable var) val)
4623 (if (not (listp (symbol-value var)))
4624 (set (make-local-variable var) nil))
4625 (set (make-local-variable var) (symbol-value var))
4626 (add-to-list var val))))))
4627 ((equal key "ARCHIVE")
4628 (setq arch value)
4629 (remove-text-properties 0 (length arch)
4630 '(face t fontified t) arch))
4631 ((equal key "LATEX_CLASS")
4632 (setq beamer-p (equal value "beamer")))
4633 ((equal key "OPTIONS")
4634 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4635 (setq scripts (read (match-string 2 value)))))
4636 ((equal key "SETUPFILE")
4637 (setq setup-contents (org-file-contents
4638 (expand-file-name
4639 (org-remove-double-quotes value))
4640 'noerror))
4641 (if (not ext-setup-or-nil)
4642 (setq ext-setup-or-nil setup-contents start 0)
4643 (setq ext-setup-or-nil
4644 (concat (substring ext-setup-or-nil 0 start)
4645 "\n" setup-contents "\n"
4646 (substring ext-setup-or-nil start)))))))
4647 ;; search for property blocks
4648 (goto-char (point-min))
4649 (while (re-search-forward org-block-regexp nil t)
4650 (when (equal "PROPERTY" (upcase (match-string 1)))
4651 (setq value (replace-regexp-in-string
4652 "[\n\r]" " " (match-string 4)))
4653 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4654 (setq props (org-update-property-plist (match-string 1 value)
4655 (match-string 2 value)
4656 props)))))))
4657 (org-set-local 'org-use-sub-superscripts scripts)
4658 (when cat
4659 (org-set-local 'org-category (intern cat))
4660 (push (cons "CATEGORY" cat) props))
4661 (when prio
4662 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4663 (setq prio (mapcar 'string-to-char prio))
4664 (org-set-local 'org-highest-priority (nth 0 prio))
4665 (org-set-local 'org-lowest-priority (nth 1 prio))
4666 (org-set-local 'org-default-priority (nth 2 prio)))
4667 (and props (org-set-local 'org-file-properties (nreverse props)))
4668 (and ftags (org-set-local 'org-file-tags
4669 (mapcar 'org-add-prop-inherited ftags)))
4670 (and drawers (org-set-local 'org-drawers drawers))
4671 (and arch (org-set-local 'org-archive-location arch))
4672 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4673 ;; Process the TODO keywords
4674 (unless kwds
4675 ;; Use the global values as if they had been given locally.
4676 (setq kwds (default-value 'org-todo-keywords))
4677 (if (stringp (car kwds))
4678 (setq kwds (list (cons org-todo-interpretation
4679 (default-value 'org-todo-keywords)))))
4680 (setq kwds (reverse kwds)))
4681 (setq kwds (nreverse kwds))
4682 (let (inter kws kw)
4683 (while (setq kws (pop kwds))
4684 (let ((kws (or
4685 (run-hook-with-args-until-success
4686 'org-todo-setup-filter-hook kws)
4687 kws)))
4688 (setq inter (pop kws) sep (member "|" kws)
4689 kws0 (delete "|" (copy-sequence kws))
4690 kwsa nil
4691 kws1 (mapcar
4692 (lambda (x)
4693 ;; 1 2
4694 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4695 (progn
4696 (setq kw (match-string 1 x)
4697 key (and (match-end 2) (match-string 2 x))
4698 log (org-extract-log-state-settings x))
4699 (push (cons kw (and key (string-to-char key))) kwsa)
4700 (and log (push log org-todo-log-states))
4702 (error "Invalid TODO keyword %s" x)))
4703 kws0)
4704 kwsa (if kwsa (append '((:startgroup))
4705 (nreverse kwsa)
4706 '((:endgroup))))
4707 hw (car kws1)
4708 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4709 tail (list inter hw (car dws) (org-last dws))))
4710 (add-to-list 'org-todo-heads hw 'append)
4711 (push kws1 org-todo-sets)
4712 (setq org-done-keywords (append org-done-keywords dws nil))
4713 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4714 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4715 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4716 (setq org-todo-sets (nreverse org-todo-sets)
4717 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4718 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4719 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4720 ;; Process the constants
4721 (when const
4722 (let (e cst)
4723 (while (setq e (pop const))
4724 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4725 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4726 (setq org-table-formula-constants-local cst)))
4728 ;; Process the tags.
4729 (when tags
4730 (let (e tgs)
4731 (while (setq e (pop tags))
4732 (cond
4733 ((equal e "{") (push '(:startgroup) tgs))
4734 ((equal e "}") (push '(:endgroup) tgs))
4735 ((equal e "\\n") (push '(:newline) tgs))
4736 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4737 (push (cons (match-string 1 e)
4738 (string-to-char (match-string 2 e)))
4739 tgs))
4740 (t (push (list e) tgs))))
4741 (org-set-local 'org-tag-alist nil)
4742 (while (setq e (pop tgs))
4743 (or (and (stringp (car e))
4744 (assoc (car e) org-tag-alist))
4745 (push e org-tag-alist)))))
4747 ;; Compute the regular expressions and other local variables.
4748 ;; Using `org-outline-regexp-bol' would complicate them much,
4749 ;; because of the fixed white space at the end of that string.
4750 (if (not org-done-keywords)
4751 (setq org-done-keywords (and org-todo-keywords-1
4752 (list (org-last org-todo-keywords-1)))))
4753 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4754 (length org-scheduled-string)
4755 (length org-clock-string)
4756 (length org-closed-string)))
4757 org-drawer-regexp
4758 (concat "^[ \t]*:\\("
4759 (mapconcat 'regexp-quote org-drawers "\\|")
4760 "\\):[ \t]*$")
4761 org-not-done-keywords
4762 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4763 org-todo-regexp
4764 (concat "\\("
4765 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4766 "\\)")
4767 org-not-done-regexp
4768 (concat "\\("
4769 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4770 "\\)")
4771 org-not-done-heading-regexp
4772 (format org-heading-keyword-regexp-format org-not-done-regexp)
4773 org-todo-line-regexp
4774 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4775 org-complex-heading-regexp
4776 (concat "^\\(\\*+\\)"
4777 "\\(?: +" org-todo-regexp "\\)?"
4778 "\\(?: +\\(\\[#.\\]\\)\\)?"
4779 "\\(?: +\\(.*?\\)\\)?"
4780 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4781 "[ \t]*$")
4782 org-complex-heading-regexp-format
4783 (concat "^\\(\\*+\\)"
4784 "\\(?: +" org-todo-regexp "\\)?"
4785 "\\(?: +\\(\\[#.\\]\\)\\)?"
4786 "\\(?: +"
4787 ;; Stats cookies can be stuck to body.
4788 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4789 "\\(%s\\)"
4790 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4791 "\\)"
4792 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4793 "[ \t]*$")
4794 org-todo-line-tags-regexp
4795 (concat "^\\(\\*+\\)"
4796 "\\(?: +" org-todo-regexp "\\)?"
4797 "\\(?: +\\(.*?\\)\\)?"
4798 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4799 "[ \t]*$")
4800 org-deadline-regexp (concat "\\<" org-deadline-string)
4801 org-deadline-time-regexp
4802 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4803 org-deadline-line-regexp
4804 (concat "\\<\\(" org-deadline-string "\\).*")
4805 org-scheduled-regexp
4806 (concat "\\<" org-scheduled-string)
4807 org-scheduled-time-regexp
4808 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4809 org-closed-time-regexp
4810 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4811 org-keyword-time-regexp
4812 (concat "\\<\\(" org-scheduled-string
4813 "\\|" org-deadline-string
4814 "\\|" org-closed-string
4815 "\\|" org-clock-string "\\)"
4816 " *[[<]\\([^]>]+\\)[]>]")
4817 org-keyword-time-not-clock-regexp
4818 (concat "\\<\\(" org-scheduled-string
4819 "\\|" org-deadline-string
4820 "\\|" org-closed-string
4821 "\\)"
4822 " *[[<]\\([^]>]+\\)[]>]")
4823 org-maybe-keyword-time-regexp
4824 (concat "\\(\\<\\(" org-scheduled-string
4825 "\\|" org-deadline-string
4826 "\\|" org-closed-string
4827 "\\|" org-clock-string "\\)\\)?"
4828 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4829 org-planning-or-clock-line-re
4830 (concat "^[ \t]*\\("
4831 org-scheduled-string "\\|"
4832 org-deadline-string "\\|"
4833 org-closed-string "\\|"
4834 org-clock-string "\\)")
4835 org-all-time-keywords
4836 (mapcar (lambda (w) (substring w 0 -1))
4837 (list org-scheduled-string org-deadline-string
4838 org-clock-string org-closed-string))
4840 (org-compute-latex-and-specials-regexp)
4841 (org-set-font-lock-defaults))))
4843 (defun org-file-contents (file &optional noerror)
4844 "Return the contents of FILE, as a string."
4845 (if (or (not file)
4846 (not (file-readable-p file)))
4847 (if noerror
4848 (progn
4849 (message "Cannot read file \"%s\"" file)
4850 (ding) (sit-for 2)
4852 (error "Cannot read file \"%s\"" file))
4853 (with-temp-buffer
4854 (insert-file-contents file)
4855 (buffer-string))))
4857 (defun org-extract-log-state-settings (x)
4858 "Extract the log state setting from a TODO keyword string.
4859 This will extract info from a string like \"WAIT(w@/!)\"."
4860 (let (kw key log1 log2)
4861 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4862 (setq kw (match-string 1 x)
4863 key (and (match-end 2) (match-string 2 x))
4864 log1 (and (match-end 3) (match-string 3 x))
4865 log2 (and (match-end 4) (match-string 4 x)))
4866 (and (or log1 log2)
4867 (list kw
4868 (and log1 (if (equal log1 "!") 'time 'note))
4869 (and log2 (if (equal log2 "!") 'time 'note)))))))
4871 (defun org-remove-keyword-keys (list)
4872 "Remove a pair of parenthesis at the end of each string in LIST."
4873 (mapcar (lambda (x)
4874 (if (string-match "(.*)$" x)
4875 (substring x 0 (match-beginning 0))
4877 list))
4879 (defun org-assign-fast-keys (alist)
4880 "Assign fast keys to a keyword-key alist.
4881 Respect keys that are already there."
4882 (let (new e (alt ?0))
4883 (while (setq e (pop alist))
4884 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4885 (cdr e)) ;; Key already assigned.
4886 (push e new)
4887 (let ((clist (string-to-list (downcase (car e))))
4888 (used (append new alist)))
4889 (when (= (car clist) ?@)
4890 (pop clist))
4891 (while (and clist (rassoc (car clist) used))
4892 (pop clist))
4893 (unless clist
4894 (while (rassoc alt used)
4895 (incf alt)))
4896 (push (cons (car e) (or (car clist) alt)) new))))
4897 (nreverse new)))
4899 ;;; Some variables used in various places
4901 (defvar org-window-configuration nil
4902 "Used in various places to store a window configuration.")
4903 (defvar org-selected-window nil
4904 "Used in various places to store a window configuration.")
4905 (defvar org-finish-function nil
4906 "Function to be called when `C-c C-c' is used.
4907 This is for getting out of special buffers like remember.")
4910 ;; FIXME: Occasionally check by commenting these, to make sure
4911 ;; no other functions uses these, forgetting to let-bind them.
4912 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4913 (defvar org-last-state)
4914 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4916 ;; Defined somewhere in this file, but used before definition.
4917 (defvar org-entities) ;; defined in org-entities.el
4918 (defvar org-struct-menu)
4919 (defvar org-org-menu)
4920 (defvar org-tbl-menu)
4922 ;;;; Define the Org-mode
4924 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4925 (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"))
4928 ;; We use a before-change function to check if a table might need
4929 ;; an update.
4930 (defvar org-table-may-need-update t
4931 "Indicates that a table might need an update.
4932 This variable is set by `org-before-change-function'.
4933 `org-table-align' sets it back to nil.")
4934 (defun org-before-change-function (beg end)
4935 "Every change indicates that a table might need an update."
4936 (setq org-table-may-need-update t))
4937 (defvar org-mode-map)
4938 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4939 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4940 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4941 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4942 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4943 (defvar org-table-buffer-is-an nil)
4945 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4946 ;; some places -- e.g. see the macro org-with-limited-levels.
4948 ;; In Org buffers, the value of `outline-regexp' is that of
4949 ;; `org-outline-regexp'. The only function still directly relying on
4950 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4951 ;; job when `orgstruct-mode' is active.
4952 (defvar org-outline-regexp "\\*+ "
4953 "Regexp to match Org headlines.")
4954 (defconst org-outline-regexp-bol "^\\*+ "
4955 "Regexp to match Org headlines.
4956 This is similar to `org-outline-regexp' but additionally makes
4957 sure that we are at the beginning of the line.")
4959 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4960 "Matches an headline, putting stars and text into groups.
4961 Stars are put in group 1 and the trimmed body in group 2.")
4963 (defvar bidi-paragraph-direction)
4964 (defvar buffer-face-mode-face)
4966 ;;;###autoload
4967 (define-derived-mode org-mode outline-mode "Org"
4968 "Outline-based notes management and organizer, alias
4969 \"Carsten's outline-mode for keeping track of everything.\"
4971 Org-mode develops organizational tasks around a NOTES file which
4972 contains information about projects as plain text. Org-mode is
4973 implemented on top of outline-mode, which is ideal to keep the content
4974 of large files well structured. It supports ToDo items, deadlines and
4975 time stamps, which magically appear in the diary listing of the Emacs
4976 calendar. Tables are easily created with a built-in table editor.
4977 Plain text URL-like links connect to websites, emails (VM), Usenet
4978 messages (Gnus), BBDB entries, and any files related to the project.
4979 For printing and sharing of notes, an Org-mode file (or a part of it)
4980 can be exported as a structured ASCII or HTML file.
4982 The following commands are available:
4984 \\{org-mode-map}"
4986 ;; Get rid of Outline menus, they are not needed
4987 ;; Need to do this here because define-derived-mode sets up
4988 ;; the keymap so late. Still, it is a waste to call this each time
4989 ;; we switch another buffer into org-mode.
4990 (if (featurep 'xemacs)
4991 (when (boundp 'outline-mode-menu-heading)
4992 ;; Assume this is Greg's port, it uses easymenu
4993 (easy-menu-remove outline-mode-menu-heading)
4994 (easy-menu-remove outline-mode-menu-show)
4995 (easy-menu-remove outline-mode-menu-hide))
4996 (define-key org-mode-map [menu-bar headings] 'undefined)
4997 (define-key org-mode-map [menu-bar hide] 'undefined)
4998 (define-key org-mode-map [menu-bar show] 'undefined))
5000 (org-load-modules-maybe)
5001 (easy-menu-add org-org-menu)
5002 (easy-menu-add org-tbl-menu)
5003 (org-install-agenda-files-menu)
5004 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5005 (add-to-invisibility-spec '(org-cwidth))
5006 (add-to-invisibility-spec '(org-hide-block . t))
5007 (when (featurep 'xemacs)
5008 (org-set-local 'line-move-ignore-invisible t))
5009 (org-set-local 'outline-regexp org-outline-regexp)
5010 (org-set-local 'outline-level 'org-outline-level)
5011 (setq bidi-paragraph-direction 'left-to-right)
5012 (when (and org-ellipsis
5013 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5014 (fboundp 'make-glyph-code))
5015 (unless org-display-table
5016 (setq org-display-table (make-display-table)))
5017 (set-display-table-slot
5018 org-display-table 4
5019 (vconcat (mapcar
5020 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5021 org-ellipsis)))
5022 (if (stringp org-ellipsis) org-ellipsis "..."))))
5023 (setq buffer-display-table org-display-table))
5024 (org-set-regexps-and-options)
5025 (when (and org-tag-faces (not org-tags-special-faces-re))
5026 ;; tag faces set outside customize.... force initialization.
5027 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5028 ;; Calc embedded
5029 (org-set-local 'calc-embedded-open-mode "# ")
5030 (modify-syntax-entry ?@ "w")
5031 (if org-startup-truncated (setq truncate-lines t))
5032 (org-set-local 'font-lock-unfontify-region-function
5033 'org-unfontify-region)
5034 ;; Activate before-change-function
5035 (org-set-local 'org-table-may-need-update t)
5036 (org-add-hook 'before-change-functions 'org-before-change-function nil
5037 'local)
5038 ;; Check for running clock before killing a buffer
5039 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5040 ;; Paragraphs and auto-filling
5041 (org-set-autofill-regexps)
5042 (org-set-local 'indent-line-function 'org-indent-line)
5043 (org-set-local 'indent-region-function 'org-indent-region)
5044 (org-update-radio-target-regexp)
5045 ;; Beginning/end of defun
5046 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5047 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5048 ;; Next error for sparse trees
5049 (org-set-local 'next-error-function 'org-occur-next-match)
5050 ;; Make sure dependence stuff works reliably, even for users who set it
5051 ;; too late :-(
5052 (if org-enforce-todo-dependencies
5053 (add-hook 'org-blocker-hook
5054 'org-block-todo-from-children-or-siblings-or-parent)
5055 (remove-hook 'org-blocker-hook
5056 'org-block-todo-from-children-or-siblings-or-parent))
5057 (if org-enforce-todo-checkbox-dependencies
5058 (add-hook 'org-blocker-hook
5059 'org-block-todo-from-checkboxes)
5060 (remove-hook 'org-blocker-hook
5061 'org-block-todo-from-checkboxes))
5063 ;; Comment characters
5064 (org-set-local 'comment-start "#")
5065 (org-set-local 'comment-padding " ")
5067 ;; Align options lines
5068 (org-set-local
5069 'align-mode-rules-list
5070 '((org-in-buffer-settings
5071 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5072 (modes . '(org-mode)))))
5074 ;; Imenu
5075 (org-set-local 'imenu-create-index-function
5076 'org-imenu-get-tree)
5078 ;; Make isearch reveal context
5079 (if (or (featurep 'xemacs)
5080 (not (boundp 'outline-isearch-open-invisible-function)))
5081 ;; Emacs 21 and XEmacs make use of the hook
5082 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5083 ;; Emacs 22 deals with this through a special variable
5084 (org-set-local 'outline-isearch-open-invisible-function
5085 (lambda (&rest ignore) (org-show-context 'isearch))))
5087 ;; Turn on org-beamer-mode?
5088 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5090 ;; Setup the pcomplete hooks
5091 (set (make-local-variable 'pcomplete-command-completion-function)
5092 'org-pcomplete-initial)
5093 (set (make-local-variable 'pcomplete-command-name-function)
5094 'org-command-at-point)
5095 (set (make-local-variable 'pcomplete-default-completion-function)
5096 'ignore)
5097 (set (make-local-variable 'pcomplete-parse-arguments-function)
5098 'org-parse-arguments)
5099 (set (make-local-variable 'pcomplete-termination-string) "")
5100 (when (>= emacs-major-version 23)
5101 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5103 ;; If empty file that did not turn on org-mode automatically, make it to.
5104 (if (and org-insert-mode-line-in-empty-file
5105 (org-called-interactively-p 'any)
5106 (= (point-min) (point-max)))
5107 (insert "# -*- mode: org -*-\n\n"))
5108 (unless org-inhibit-startup
5109 (when org-startup-align-all-tables
5110 (let ((bmp (buffer-modified-p)))
5111 (org-table-map-tables 'org-table-align 'quietly)
5112 (set-buffer-modified-p bmp)))
5113 (when org-startup-with-inline-images
5114 (org-display-inline-images))
5115 (when org-startup-indented
5116 (require 'org-indent)
5117 (org-indent-mode 1))
5118 (unless org-inhibit-startup-visibility-stuff
5119 (org-set-startup-visibility))))
5121 (when (fboundp 'abbrev-table-put)
5122 (abbrev-table-put org-mode-abbrev-table
5123 :parents (list text-mode-abbrev-table)))
5125 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5127 (defun org-current-time ()
5128 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5129 (if (> (car org-time-stamp-rounding-minutes) 1)
5130 (let ((r (car org-time-stamp-rounding-minutes))
5131 (time (decode-time)))
5132 (apply 'encode-time
5133 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5134 (nthcdr 2 time))))
5135 (current-time)))
5137 (defun org-today ()
5138 "Return today date, considering `org-extend-today-until'."
5139 (time-to-days
5140 (time-subtract (current-time)
5141 (list 0 (* 3600 org-extend-today-until) 0))))
5143 ;;;; Font-Lock stuff, including the activators
5145 (defvar org-mouse-map (make-sparse-keymap))
5146 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5147 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5148 (when org-mouse-1-follows-link
5149 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5150 (when org-tab-follows-link
5151 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5152 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5154 (require 'font-lock)
5156 (defconst org-non-link-chars "]\t\n\r<>")
5157 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5158 "shell" "elisp" "doi" "message"))
5159 (defvar org-link-types-re nil
5160 "Matches a link that has a url-like prefix like \"http:\"")
5161 (defvar org-link-re-with-space nil
5162 "Matches a link with spaces, optional angular brackets around it.")
5163 (defvar org-link-re-with-space2 nil
5164 "Matches a link with spaces, optional angular brackets around it.")
5165 (defvar org-link-re-with-space3 nil
5166 "Matches a link with spaces, only for internal part in bracket links.")
5167 (defvar org-angle-link-re nil
5168 "Matches link with angular brackets, spaces are allowed.")
5169 (defvar org-plain-link-re nil
5170 "Matches plain link, without spaces.")
5171 (defvar org-bracket-link-regexp nil
5172 "Matches a link in double brackets.")
5173 (defvar org-bracket-link-analytic-regexp nil
5174 "Regular expression used to analyze links.
5175 Here is what the match groups contain after a match:
5176 1: http:
5177 2: http
5178 3: path
5179 4: [desc]
5180 5: desc")
5181 (defvar org-bracket-link-analytic-regexp++ nil
5182 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5183 (defvar org-any-link-re nil
5184 "Regular expression matching any link.")
5186 (defcustom org-match-sexp-depth 3
5187 "Number of stacked braces for sub/superscript matching.
5188 This has to be set before loading org.el to be effective."
5189 :group 'org-export-translation ; ??????????????????????????/
5190 :type 'integer)
5192 (defun org-create-multibrace-regexp (left right n)
5193 "Create a regular expression which will match a balanced sexp.
5194 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5195 as single character strings.
5196 The regexp returned will match the entire expression including the
5197 delimiters. It will also define a single group which contains the
5198 match except for the outermost delimiters. The maximum depth of
5199 stacked delimiters is N. Escaping delimiters is not possible."
5200 (let* ((nothing (concat "[^" left right "]*?"))
5201 (or "\\|")
5202 (re nothing)
5203 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5204 (while (> n 1)
5205 (setq n (1- n)
5206 re (concat re or next)
5207 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5208 (concat left "\\(" re "\\)" right)))
5210 (defvar org-match-substring-regexp
5211 (concat
5212 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5213 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5214 "\\|"
5215 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5216 "\\|"
5217 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5218 "The regular expression matching a sub- or superscript.")
5220 (defvar org-match-substring-with-braces-regexp
5221 (concat
5222 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5223 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5224 "\\)")
5225 "The regular expression matching a sub- or superscript, forcing braces.")
5227 (defun org-make-link-regexps ()
5228 "Update the link regular expressions.
5229 This should be called after the variable `org-link-types' has changed."
5230 (setq org-link-types-re
5231 (concat
5232 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5233 org-link-re-with-space
5234 (concat
5235 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5236 "\\([^" org-non-link-chars " ]"
5237 "[^" org-non-link-chars "]*"
5238 "[^" org-non-link-chars " ]\\)>?")
5239 org-link-re-with-space2
5240 (concat
5241 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5242 "\\([^" org-non-link-chars " ]"
5243 "[^\t\n\r]*"
5244 "[^" org-non-link-chars " ]\\)>?")
5245 org-link-re-with-space3
5246 (concat
5247 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5248 "\\([^" org-non-link-chars " ]"
5249 "[^\t\n\r]*\\)")
5250 org-angle-link-re
5251 (concat
5252 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5253 "\\([^" org-non-link-chars " ]"
5254 "[^" org-non-link-chars "]*"
5255 "\\)>")
5256 org-plain-link-re
5257 (concat
5258 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5259 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5260 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5261 org-bracket-link-regexp
5262 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5263 org-bracket-link-analytic-regexp
5264 (concat
5265 "\\[\\["
5266 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5267 "\\([^]]+\\)"
5268 "\\]"
5269 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5270 "\\]")
5271 org-bracket-link-analytic-regexp++
5272 (concat
5273 "\\[\\["
5274 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5275 "\\([^]]+\\)"
5276 "\\]"
5277 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5278 "\\]")
5279 org-any-link-re
5280 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5281 org-angle-link-re "\\)\\|\\("
5282 org-plain-link-re "\\)")))
5284 (org-make-link-regexps)
5286 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5287 "Regular expression for fast time stamp matching.")
5288 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5289 "Regular expression for fast time stamp matching.")
5290 (defconst org-ts-regexp0
5291 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5292 "Regular expression matching time strings for analysis.
5293 This one does not require the space after the date, so it can be used
5294 on a string that terminates immediately after the date.")
5295 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5296 "Regular expression matching time strings for analysis.")
5297 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5298 "Regular expression matching time stamps, with groups.")
5299 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5300 "Regular expression matching time stamps (also [..]), with groups.")
5301 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5302 "Regular expression matching a time stamp range.")
5303 (defconst org-tr-regexp-both
5304 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5305 "Regular expression matching a time stamp range.")
5306 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5307 org-ts-regexp "\\)?")
5308 "Regular expression matching a time stamp or time stamp range.")
5309 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5310 org-ts-regexp-both "\\)?")
5311 "Regular expression matching a time stamp or time stamp range.
5312 The time stamps may be either active or inactive.")
5314 (defvar org-emph-face nil)
5316 (defun org-do-emphasis-faces (limit)
5317 "Run through the buffer and add overlays to emphasized strings."
5318 (let (rtn a)
5319 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5320 (if (not (= (char-after (match-beginning 3))
5321 (char-after (match-beginning 4))))
5322 (progn
5323 (setq rtn t)
5324 (setq a (assoc (match-string 3) org-emphasis-alist))
5325 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5326 'face
5327 (nth 1 a))
5328 (and (nth 4 a)
5329 (org-remove-flyspell-overlays-in
5330 (match-beginning 0) (match-end 0)))
5331 (add-text-properties (match-beginning 2) (match-end 2)
5332 '(font-lock-multiline t org-emphasis t))
5333 (when org-hide-emphasis-markers
5334 (add-text-properties (match-end 4) (match-beginning 5)
5335 '(invisible org-link))
5336 (add-text-properties (match-beginning 3) (match-end 3)
5337 '(invisible org-link)))))
5338 (backward-char 1))
5339 rtn))
5341 (defun org-emphasize (&optional char)
5342 "Insert or change an emphasis, i.e. a font like bold or italic.
5343 If there is an active region, change that region to a new emphasis.
5344 If there is no region, just insert the marker characters and position
5345 the cursor between them.
5346 CHAR should be either the marker character, or the first character of the
5347 HTML tag associated with that emphasis. If CHAR is a space, the means
5348 to remove the emphasis of the selected region.
5349 If char is not given (for example in an interactive call) it
5350 will be prompted for."
5351 (interactive)
5352 (let ((eal org-emphasis-alist) e det
5353 (erc org-emphasis-regexp-components)
5354 (prompt "")
5355 (string "") beg end move tag c s)
5356 (if (org-region-active-p)
5357 (setq beg (region-beginning) end (region-end)
5358 string (buffer-substring beg end))
5359 (setq move t))
5361 (while (setq e (pop eal))
5362 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5363 c (aref tag 0))
5364 (push (cons c (string-to-char (car e))) det)
5365 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5366 (substring tag 1)))))
5367 (setq det (nreverse det))
5368 (unless char
5369 (message "%s" (concat "Emphasis marker or tag:" prompt))
5370 (setq char (read-char-exclusive)))
5371 (setq char (or (cdr (assoc char det)) char))
5372 (if (equal char ?\ )
5373 (setq s "" move nil)
5374 (unless (assoc (char-to-string char) org-emphasis-alist)
5375 (error "No such emphasis marker: \"%c\"" char))
5376 (setq s (char-to-string char)))
5377 (while (and (> (length string) 1)
5378 (equal (substring string 0 1) (substring string -1))
5379 (assoc (substring string 0 1) org-emphasis-alist))
5380 (setq string (substring string 1 -1)))
5381 (setq string (concat s string s))
5382 (if beg (delete-region beg end))
5383 (unless (or (bolp)
5384 (string-match (concat "[" (nth 0 erc) "\n]")
5385 (char-to-string (char-before (point)))))
5386 (insert " "))
5387 (unless (or (eobp)
5388 (string-match (concat "[" (nth 1 erc) "\n]")
5389 (char-to-string (char-after (point)))))
5390 (insert " ") (backward-char 1))
5391 (insert string)
5392 (and move (backward-char 1))))
5394 (defconst org-nonsticky-props
5395 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5397 (defsubst org-rear-nonsticky-at (pos)
5398 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5400 (defun org-activate-plain-links (limit)
5401 "Run through the buffer and add overlays to links."
5402 (catch 'exit
5403 (let (f)
5404 (if (re-search-forward org-plain-link-re limit t)
5405 (progn
5406 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5407 (setq f (get-text-property (match-beginning 0) 'face))
5408 (if (or (eq f 'org-tag)
5409 (and (listp f) (memq 'org-tag f)))
5411 (add-text-properties (match-beginning 0) (match-end 0)
5412 (list 'mouse-face 'highlight
5413 'face 'org-link
5414 'keymap org-mouse-map))
5415 (org-rear-nonsticky-at (match-end 0)))
5416 t)))))
5418 (defun org-activate-code (limit)
5419 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5420 (progn
5421 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5422 (remove-text-properties (match-beginning 0) (match-end 0)
5423 '(display t invisible t intangible t))
5424 t)))
5426 (defcustom org-src-fontify-natively nil
5427 "When non-nil, fontify code in code blocks."
5428 :type 'boolean
5429 :version "24.1"
5430 :group 'org-appearance
5431 :group 'org-babel)
5433 (defcustom org-src-prevent-auto-filling nil
5434 "When non-nil, prevent auto-filling in src blocks."
5435 :type 'boolean
5436 :version "24.1"
5437 :group 'org-appearance
5438 :group 'org-babel)
5440 (defcustom org-allow-promoting-top-level-subtree nil
5441 "When non-nil, allow promoting a top level subtree.
5442 The leading star of the top level headline will be replaced
5443 by a #."
5444 :type 'boolean
5445 :version "24.1"
5446 :group 'org-appearance)
5448 (defun org-fontify-meta-lines-and-blocks (limit)
5449 (condition-case nil
5450 (org-fontify-meta-lines-and-blocks-1 limit)
5451 (error (message "org-mode fontification error"))))
5453 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5454 "Fontify #+ lines and blocks, in the correct ways."
5455 (let ((case-fold-search t))
5456 (if (re-search-forward
5457 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5458 limit t)
5459 (let ((beg (match-beginning 0))
5460 (block-start (match-end 0))
5461 (block-end nil)
5462 (lang (match-string 7))
5463 (beg1 (line-beginning-position 2))
5464 (dc1 (downcase (match-string 2)))
5465 (dc3 (downcase (match-string 3)))
5466 end end1 quoting block-type ovl)
5467 (cond
5468 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5469 ;; a single line of backend-specific content
5470 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5471 (remove-text-properties (match-beginning 0) (match-end 0)
5472 '(display t invisible t intangible t))
5473 (add-text-properties (match-beginning 1) (match-end 3)
5474 '(font-lock-fontified t face org-meta-line))
5475 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5476 '(font-lock-fontified t face org-block))
5477 ; for backend-specific code
5479 ((and (match-end 4) (equal dc3 "begin"))
5480 ;; Truly a block
5481 (setq block-type (downcase (match-string 5))
5482 quoting (member block-type org-protecting-blocks))
5483 (when (re-search-forward
5484 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5485 nil t) ;; on purpose, we look further than LIMIT
5486 (setq end (min (point-max) (match-end 0))
5487 end1 (min (point-max) (1- (match-beginning 0))))
5488 (setq block-end (match-beginning 0))
5489 (when quoting
5490 (remove-text-properties beg end
5491 '(display t invisible t intangible t)))
5492 (add-text-properties
5493 beg end
5494 '(font-lock-fontified t font-lock-multiline t))
5495 (add-text-properties beg beg1 '(face org-meta-line))
5496 (add-text-properties end1 (min (point-max) (1+ end))
5497 '(face org-meta-line)) ; for end_src
5498 (cond
5499 ((and lang (not (string= lang "")) org-src-fontify-natively)
5500 (org-src-font-lock-fontify-block lang block-start block-end)
5501 ;; remove old background overlays
5502 (mapc (lambda (ov)
5503 (if (eq (overlay-get ov 'face) 'org-block-background)
5504 (delete-overlay ov)))
5505 (overlays-at (/ (+ beg1 block-end) 2)))
5506 ;; add a background overlay
5507 (setq ovl (make-overlay beg1 block-end))
5508 (overlay-put ovl 'face 'org-block-background)
5509 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5510 (quoting
5511 (add-text-properties beg1 (min (point-max) (1+ end1))
5512 '(face org-block))) ; end of source block
5513 ((not org-fontify-quote-and-verse-blocks))
5514 ((string= block-type "quote")
5515 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5516 ((string= block-type "verse")
5517 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5518 (add-text-properties beg beg1 '(face org-block-begin-line))
5519 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5520 '(face org-block-end-line))
5522 ((member dc1 '("title:" "author:" "email:" "date:"))
5523 (add-text-properties
5524 beg (match-end 3)
5525 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5526 '(font-lock-fontified t invisible t)
5527 '(font-lock-fontified t face org-document-info-keyword)))
5528 (add-text-properties
5529 (match-beginning 6) (match-end 6)
5530 (if (string-equal dc1 "title:")
5531 '(font-lock-fontified t face org-document-title)
5532 '(font-lock-fontified t face org-document-info))))
5533 ((not (member (char-after beg) '(?\ ?\t)))
5534 ;; just any other in-buffer setting, but not indented
5535 (add-text-properties
5536 beg (match-end 0)
5537 '(font-lock-fontified t face org-meta-line))
5539 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5540 "orgtbl:" "tblfm:" "tblname:" "results:"
5541 "call:" "header:" "headers:" "name:"))
5542 (and (match-end 4) (equal dc3 "attr")))
5543 (add-text-properties
5544 beg (match-end 0)
5545 '(font-lock-fontified t face org-meta-line))
5547 ((member dc3 '(" " ""))
5548 (add-text-properties
5549 beg (match-end 0)
5550 '(font-lock-fontified t face font-lock-comment-face)))
5551 (t nil))))))
5553 (defun org-strip-protective-commas (beg end)
5554 "Strip protective commas between BEG and END in the current buffer."
5555 (interactive "r")
5556 (save-excursion
5557 (save-match-data
5558 (goto-char beg)
5559 (let ((front-line (save-excursion
5560 (re-search-forward
5561 "[^[:space:]]" end t)
5562 (goto-char (match-beginning 0))
5563 (current-column))))
5564 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5565 (goto-char (match-beginning 1))
5566 (when (= (current-column) front-line)
5567 (replace-match "" nil nil nil 1)))))))
5569 (defun org-activate-angle-links (limit)
5570 "Run through the buffer and add overlays to links."
5571 (if (re-search-forward org-angle-link-re limit t)
5572 (progn
5573 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5574 (add-text-properties (match-beginning 0) (match-end 0)
5575 (list 'mouse-face 'highlight
5576 'keymap org-mouse-map))
5577 (org-rear-nonsticky-at (match-end 0))
5578 t)))
5580 (defun org-activate-footnote-links (limit)
5581 "Run through the buffer and add overlays to footnotes."
5582 (let ((fn (org-footnote-next-reference-or-definition limit)))
5583 (when fn
5584 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5585 (org-remove-flyspell-overlays-in beg end)
5586 (add-text-properties beg end
5587 (list 'mouse-face 'highlight
5588 'keymap org-mouse-map
5589 'help-echo
5590 (if (= (point-at-bol) beg)
5591 "Footnote definition"
5592 "Footnote reference")
5593 'font-lock-fontified t
5594 'font-lock-multiline t
5595 'face 'org-footnote))))))
5597 (defun org-activate-bracket-links (limit)
5598 "Run through the buffer and add overlays to bracketed links."
5599 (if (re-search-forward org-bracket-link-regexp limit t)
5600 (let* ((help (concat "LINK: "
5601 (org-match-string-no-properties 1)))
5602 ;; FIXME: above we should remove the escapes.
5603 ;; but that requires another match, protecting match data,
5604 ;; a lot of overhead for font-lock.
5605 (ip (org-maybe-intangible
5606 (list 'invisible 'org-link
5607 'keymap org-mouse-map 'mouse-face 'highlight
5608 'font-lock-multiline t 'help-echo help)))
5609 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5610 'font-lock-multiline t 'help-echo help)))
5611 ;; We need to remove the invisible property here. Table narrowing
5612 ;; may have made some of this invisible.
5613 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5614 (remove-text-properties (match-beginning 0) (match-end 0)
5615 '(invisible nil))
5616 (if (match-end 3)
5617 (progn
5618 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5619 (org-rear-nonsticky-at (match-beginning 3))
5620 (add-text-properties (match-beginning 3) (match-end 3) vp)
5621 (org-rear-nonsticky-at (match-end 3))
5622 (add-text-properties (match-end 3) (match-end 0) ip)
5623 (org-rear-nonsticky-at (match-end 0)))
5624 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5625 (org-rear-nonsticky-at (match-beginning 1))
5626 (add-text-properties (match-beginning 1) (match-end 1) vp)
5627 (org-rear-nonsticky-at (match-end 1))
5628 (add-text-properties (match-end 1) (match-end 0) ip)
5629 (org-rear-nonsticky-at (match-end 0)))
5630 t)))
5632 (defun org-activate-dates (limit)
5633 "Run through the buffer and add overlays to dates."
5634 (if (re-search-forward org-tsr-regexp-both limit t)
5635 (progn
5636 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5637 (add-text-properties (match-beginning 0) (match-end 0)
5638 (list 'mouse-face 'highlight
5639 'keymap org-mouse-map))
5640 (org-rear-nonsticky-at (match-end 0))
5641 (when org-display-custom-times
5642 (if (match-end 3)
5643 (org-display-custom-time (match-beginning 3) (match-end 3)))
5644 (org-display-custom-time (match-beginning 1) (match-end 1)))
5645 t)))
5647 (defvar org-target-link-regexp nil
5648 "Regular expression matching radio targets in plain text.")
5649 (make-variable-buffer-local 'org-target-link-regexp)
5650 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5651 "Regular expression matching a link target.")
5652 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5653 "Regular expression matching a radio target.")
5654 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5655 "Regular expression matching any target.")
5657 (defun org-activate-target-links (limit)
5658 "Run through the buffer and add overlays to target matches."
5659 (when org-target-link-regexp
5660 (let ((case-fold-search t))
5661 (if (re-search-forward org-target-link-regexp limit t)
5662 (progn
5663 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5664 (add-text-properties (match-beginning 0) (match-end 0)
5665 (list 'mouse-face 'highlight
5666 'keymap org-mouse-map
5667 'help-echo "Radio target link"
5668 'org-linked-text t))
5669 (org-rear-nonsticky-at (match-end 0))
5670 t)))))
5672 (defun org-update-radio-target-regexp ()
5673 "Find all radio targets in this file and update the regular expression."
5674 (interactive)
5675 (when (memq 'radio org-activate-links)
5676 (setq org-target-link-regexp
5677 (org-make-target-link-regexp (org-all-targets 'radio)))
5678 (org-restart-font-lock)))
5680 (defun org-hide-wide-columns (limit)
5681 (let (s e)
5682 (setq s (text-property-any (point) (or limit (point-max))
5683 'org-cwidth t))
5684 (when s
5685 (setq e (next-single-property-change s 'org-cwidth))
5686 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5687 (goto-char e)
5688 t)))
5690 (defvar org-latex-and-specials-regexp nil
5691 "Regular expression for highlighting export special stuff.")
5692 (defvar org-match-substring-regexp)
5693 (defvar org-match-substring-with-braces-regexp)
5695 ;; This should be with the exporter code, but we also use if for font-locking
5696 (defconst org-export-html-special-string-regexps
5697 '(("\\\\-" . "&shy;")
5698 ("---\\([^-]\\)" . "&mdash;\\1")
5699 ("--\\([^-]\\)" . "&ndash;\\1")
5700 ("\\.\\.\\." . "&hellip;"))
5701 "Regular expressions for special string conversion.")
5704 (defun org-compute-latex-and-specials-regexp ()
5705 "Compute regular expression for stuff treated specially by exporters."
5706 (if (not org-highlight-latex-fragments-and-specials)
5707 (org-set-local 'org-latex-and-specials-regexp nil)
5708 (require 'org-exp)
5709 (let*
5710 ((matchers (plist-get org-format-latex-options :matchers))
5711 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5712 org-latex-regexps)))
5713 (org-export-allow-BIND nil)
5714 (options (org-combine-plists (org-default-export-plist)
5715 (org-infile-export-plist)))
5716 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5717 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5718 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5719 (org-export-html-expand (plist-get options :expand-quoted-html))
5720 (org-export-with-special-strings (plist-get options :special-strings))
5721 (re-sub
5722 (cond
5723 ((equal org-export-with-sub-superscripts '{})
5724 (list org-match-substring-with-braces-regexp))
5725 (org-export-with-sub-superscripts
5726 (list org-match-substring-regexp))
5727 (t nil)))
5728 (re-latex
5729 (if org-export-with-LaTeX-fragments
5730 (mapcar (lambda (x) (nth 1 x)) latexs)))
5731 (re-macros
5732 (if org-export-with-TeX-macros
5733 (list (concat "\\\\"
5734 (regexp-opt
5735 (append
5737 (delq nil
5738 (mapcar 'car-safe
5739 (append org-entities-user
5740 org-entities)))
5741 (if (boundp 'org-latex-entities)
5742 (mapcar (lambda (x)
5743 (or (car-safe x) x))
5744 org-latex-entities)
5745 nil))
5746 'words))) ; FIXME
5748 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5749 (re-special (if org-export-with-special-strings
5750 (mapcar (lambda (x) (car x))
5751 org-export-html-special-string-regexps)))
5752 (re-rest
5753 (delq nil
5754 (list
5755 (if org-export-html-expand "@<[^>\n]+>")
5756 ))))
5757 (org-set-local
5758 'org-latex-and-specials-regexp
5759 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5760 re-rest) "\\|")))))
5762 (defun org-do-latex-and-special-faces (limit)
5763 "Run through the buffer and add overlays to links."
5764 (when org-latex-and-specials-regexp
5765 (let (rtn d)
5766 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5767 limit t))
5768 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5769 'face))
5770 '(org-code org-verbatim underline)))
5771 (progn
5772 (setq rtn t
5773 d (cond ((member (char-after (1+ (match-beginning 0)))
5774 '(?_ ?^)) 1)
5775 (t 0)))
5776 (font-lock-prepend-text-property
5777 (+ d (match-beginning 0)) (match-end 0)
5778 'face 'org-latex-and-export-specials)
5779 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5780 '(font-lock-multiline t)))))
5781 rtn)))
5783 (defun org-restart-font-lock ()
5784 "Restart `font-lock-mode', to force refontification."
5785 (when (and (boundp 'font-lock-mode) font-lock-mode)
5786 (font-lock-mode -1)
5787 (font-lock-mode 1)))
5789 (defun org-all-targets (&optional radio)
5790 "Return a list of all targets in this file.
5791 With optional argument RADIO, only find radio targets."
5792 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5793 rtn)
5794 (save-excursion
5795 (goto-char (point-min))
5796 (while (re-search-forward re nil t)
5797 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5798 rtn)))
5800 (defun org-make-target-link-regexp (targets)
5801 "Make regular expression matching all strings in TARGETS.
5802 The regular expression finds the targets also if there is a line break
5803 between words."
5804 (and targets
5805 (concat
5806 "\\<\\("
5807 (mapconcat
5808 (lambda (x)
5809 (setq x (regexp-quote x))
5810 (while (string-match " +" x)
5811 (setq x (replace-match "\\s-+" t t x)))
5813 targets
5814 "\\|")
5815 "\\)\\>")))
5817 (defun org-activate-tags (limit)
5818 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5819 (progn
5820 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5821 (add-text-properties (match-beginning 1) (match-end 1)
5822 (list 'mouse-face 'highlight
5823 'keymap org-mouse-map))
5824 (org-rear-nonsticky-at (match-end 1))
5825 t)))
5827 (defun org-outline-level ()
5828 "Compute the outline level of the heading at point.
5829 This function assumes that the cursor is at the beginning of a line matched
5830 by `outline-regexp'. Otherwise it returns garbage.
5831 If this is called at a normal headline, the level is the number of stars.
5832 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5833 (save-excursion
5834 (looking-at org-outline-regexp)
5835 (1- (- (match-end 0) (match-beginning 0)))))
5837 (defvar org-font-lock-keywords nil)
5839 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5840 "Regular expression matching a property line.")
5842 (defvar org-font-lock-hook nil
5843 "Functions to be called for special font lock stuff.")
5845 (defvar org-font-lock-set-keywords-hook nil
5846 "Functions that can manipulate `org-font-lock-extra-keywords'.
5847 This is called after `org-font-lock-extra-keywords' is defined, but before
5848 it is installed to be used by font lock. This can be useful if something
5849 needs to be inserted at a specific position in the font-lock sequence.")
5851 (defun org-font-lock-hook (limit)
5852 (run-hook-with-args 'org-font-lock-hook limit))
5854 (defun org-set-font-lock-defaults ()
5855 (let* ((em org-fontify-emphasized-text)
5856 (lk org-activate-links)
5857 (org-font-lock-extra-keywords
5858 (list
5859 ;; Call the hook
5860 '(org-font-lock-hook)
5861 ;; Headlines
5862 `(,(if org-fontify-whole-heading-line
5863 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5864 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5865 (1 (org-get-level-face 1))
5866 (2 (org-get-level-face 2))
5867 (3 (org-get-level-face 3)))
5868 ;; Table lines
5869 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5870 (1 'org-table t))
5871 ;; Table internals
5872 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5873 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5874 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5875 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5876 ;; Drawers
5877 (list org-drawer-regexp '(0 'org-special-keyword t))
5878 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5879 ;; Properties
5880 (list org-property-re
5881 '(1 'org-special-keyword t)
5882 '(3 'org-property-value t))
5883 ;; Links
5884 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5885 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5886 (if (memq 'plain lk) '(org-activate-plain-links))
5887 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5888 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5889 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5890 (if (memq 'footnote lk) '(org-activate-footnote-links))
5891 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5892 '(org-hide-wide-columns (0 nil append))
5893 ;; TODO keyword
5894 (list (format org-heading-keyword-regexp-format
5895 org-todo-regexp)
5896 '(2 (org-get-todo-face 2) t))
5897 ;; DONE
5898 (if org-fontify-done-headline
5899 (list (format org-heading-keyword-regexp-format
5900 (concat
5901 "\\(?:"
5902 (mapconcat 'regexp-quote org-done-keywords "\\|")
5903 "\\)"))
5904 '(2 'org-headline-done t))
5905 nil)
5906 ;; Priorities
5907 '(org-font-lock-add-priority-faces)
5908 ;; Tags
5909 '(org-font-lock-add-tag-faces)
5910 ;; Special keywords
5911 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5912 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5913 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5914 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5915 ;; Emphasis
5916 (if em
5917 (if (featurep 'xemacs)
5918 '(org-do-emphasis-faces (0 nil append))
5919 '(org-do-emphasis-faces)))
5920 ;; Checkboxes
5921 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5922 1 'org-checkbox prepend)
5923 (if (cdr (assq 'checkbox org-list-automatic-rules))
5924 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5925 (0 (org-get-checkbox-statistics-face) t)))
5926 ;; Description list items
5927 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5928 1 'org-list-dt prepend)
5929 ;; ARCHIVEd headings
5930 (list (concat
5931 org-outline-regexp-bol
5932 "\\(.*:" org-archive-tag ":.*\\)")
5933 '(1 'org-archived prepend))
5934 ;; Specials
5935 '(org-do-latex-and-special-faces)
5936 '(org-fontify-entities)
5937 '(org-raise-scripts)
5938 ;; Code
5939 '(org-activate-code (1 'org-code t))
5940 ;; COMMENT
5941 (list (format org-heading-keyword-regexp-format
5942 (concat "\\("
5943 org-comment-string "\\|" org-quote-string
5944 "\\)"))
5945 '(2 'org-special-keyword t))
5946 '("^#.*" (0 'font-lock-comment-face t))
5947 ;; Blocks and meta lines
5948 '(org-fontify-meta-lines-and-blocks)
5950 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5951 (run-hooks 'org-font-lock-set-keywords-hook)
5952 ;; Now set the full font-lock-keywords
5953 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5954 (org-set-local 'font-lock-defaults
5955 '(org-font-lock-keywords t nil nil backward-paragraph))
5956 (kill-local-variable 'font-lock-keywords) nil))
5958 (defun org-toggle-pretty-entities ()
5959 "Toggle the composition display of entities as UTF8 characters."
5960 (interactive)
5961 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5962 (org-restart-font-lock)
5963 (if org-pretty-entities
5964 (message "Entities are displayed as UTF8 characters")
5965 (save-restriction
5966 (widen)
5967 (org-decompose-region (point-min) (point-max))
5968 (message "Entities are displayed plain"))))
5970 (defun org-fontify-entities (limit)
5971 "Find an entity to fontify."
5972 (let (ee)
5973 (when org-pretty-entities
5974 (catch 'match
5975 (while (re-search-forward
5976 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5977 limit t)
5978 (if (and (not (org-in-indented-comment-line))
5979 (setq ee (org-entity-get (match-string 1)))
5980 (= (length (nth 6 ee)) 1))
5981 (let*
5982 ((end (if (equal (match-string 2) "{}")
5983 (match-end 2)
5984 (match-end 1))))
5985 (add-text-properties
5986 (match-beginning 0) end
5987 (list 'font-lock-fontified t))
5988 (compose-region (match-beginning 0) end
5989 (nth 6 ee) nil)
5990 (backward-char 1)
5991 (throw 'match t))))
5992 nil))))
5994 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5995 "Fontify string S like in Org-mode."
5996 (with-temp-buffer
5997 (insert s)
5998 (let ((org-odd-levels-only odd-levels))
5999 (org-mode)
6000 (font-lock-fontify-buffer)
6001 (buffer-string))))
6003 (defvar org-m nil)
6004 (defvar org-l nil)
6005 (defvar org-f nil)
6006 (defun org-get-level-face (n)
6007 "Get the right face for match N in font-lock matching of headlines."
6008 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6009 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6010 (if org-cycle-level-faces
6011 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6012 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6013 (cond
6014 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6015 ((eq n 2) org-f)
6016 (t (if org-level-color-stars-only nil org-f))))
6019 (defun org-get-todo-face (kwd)
6020 "Get the right face for a TODO keyword KWD.
6021 If KWD is a number, get the corresponding match group."
6022 (if (numberp kwd) (setq kwd (match-string kwd)))
6023 (or (org-face-from-face-or-color
6024 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6025 (and (member kwd org-done-keywords) 'org-done)
6026 'org-todo))
6028 (defun org-face-from-face-or-color (context inherit face-or-color)
6029 "Create a face list that inherits INHERIT, but sets the foreground color.
6030 When FACE-OR-COLOR is not a string, just return it."
6031 (if (stringp face-or-color)
6032 (list :inherit inherit
6033 (cdr (assoc context org-faces-easy-properties))
6034 face-or-color)
6035 face-or-color))
6037 (defun org-font-lock-add-tag-faces (limit)
6038 "Add the special tag faces."
6039 (when (and org-tag-faces org-tags-special-faces-re)
6040 (while (re-search-forward org-tags-special-faces-re limit t)
6041 (add-text-properties (match-beginning 1) (match-end 1)
6042 (list 'face (org-get-tag-face 1)
6043 'font-lock-fontified t))
6044 (backward-char 1))))
6046 (defun org-font-lock-add-priority-faces (limit)
6047 "Add the special priority faces."
6048 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6049 (when (save-match-data (org-at-heading-p))
6050 (add-text-properties
6051 (match-beginning 0) (match-end 0)
6052 (list 'face (or (org-face-from-face-or-color
6053 'priority 'org-special-keyword
6054 (cdr (assoc (char-after (match-beginning 1))
6055 org-priority-faces)))
6056 'org-special-keyword)
6057 'font-lock-fontified t)))))
6059 (defun org-get-tag-face (kwd)
6060 "Get the right face for a TODO keyword KWD.
6061 If KWD is a number, get the corresponding match group."
6062 (if (numberp kwd) (setq kwd (match-string kwd)))
6063 (or (org-face-from-face-or-color
6064 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6065 'org-tag))
6067 (defun org-unfontify-region (beg end &optional maybe_loudly)
6068 "Remove fontification and activation overlays from links."
6069 (font-lock-default-unfontify-region beg end)
6070 (let* ((buffer-undo-list t)
6071 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6072 (inhibit-modification-hooks t)
6073 deactivate-mark buffer-file-name buffer-file-truename)
6074 (org-decompose-region beg end)
6075 (remove-text-properties beg end
6076 '(mouse-face t keymap t org-linked-text t
6077 invisible t intangible t
6078 org-no-flyspell t org-emphasis t))
6079 (org-remove-font-lock-display-properties beg end)))
6081 (defconst org-script-display '(((raise -0.3) (height 0.7))
6082 ((raise 0.3) (height 0.7))
6083 ((raise -0.5))
6084 ((raise 0.5)))
6085 "Display properties for showing superscripts and subscripts.")
6087 (defun org-remove-font-lock-display-properties (beg end)
6088 "Remove specific display properties that have been added by font lock.
6089 The will remove the raise properties that are used to show superscripts
6090 and subscripts."
6091 (let (next prop)
6092 (while (< beg end)
6093 (setq next (next-single-property-change beg 'display nil end)
6094 prop (get-text-property beg 'display))
6095 (if (member prop org-script-display)
6096 (put-text-property beg next 'display nil))
6097 (setq beg next))))
6099 (defun org-raise-scripts (limit)
6100 "Add raise properties to sub/superscripts."
6101 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6102 (if (re-search-forward
6103 (if (eq org-use-sub-superscripts t)
6104 org-match-substring-regexp
6105 org-match-substring-with-braces-regexp)
6106 limit t)
6107 (let* ((pos (point)) table-p comment-p
6108 (mpos (match-beginning 3))
6109 (emph-p (get-text-property mpos 'org-emphasis))
6110 (link-p (get-text-property mpos 'mouse-face))
6111 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6112 (goto-char (point-at-bol))
6113 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6114 comment-p (org-looking-at-p "[ \t]*#"))
6115 (goto-char pos)
6116 ;; FIXME: Should we go back one character here, for a_b^c
6117 ;; (goto-char (1- pos)) ;????????????????????
6118 (if (or comment-p emph-p link-p keyw-p)
6120 (put-text-property (match-beginning 3) (match-end 0)
6121 'display
6122 (if (equal (char-after (match-beginning 2)) ?^)
6123 (nth (if table-p 3 1) org-script-display)
6124 (nth (if table-p 2 0) org-script-display)))
6125 (add-text-properties (match-beginning 2) (match-end 2)
6126 (list 'invisible t
6127 'org-dwidth t 'org-dwidth-n 1))
6128 (if (and (eq (char-after (match-beginning 3)) ?{)
6129 (eq (char-before (match-end 3)) ?}))
6130 (progn
6131 (add-text-properties
6132 (match-beginning 3) (1+ (match-beginning 3))
6133 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6134 (add-text-properties
6135 (1- (match-end 3)) (match-end 3)
6136 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6137 t)))))
6139 ;;;; Visibility cycling, including org-goto and indirect buffer
6141 ;;; Cycling
6143 (defvar org-cycle-global-status nil)
6144 (make-variable-buffer-local 'org-cycle-global-status)
6145 (defvar org-cycle-subtree-status nil)
6146 (make-variable-buffer-local 'org-cycle-subtree-status)
6148 ;;;###autoload
6150 (defvar org-inlinetask-min-level)
6152 (defun org-cycle (&optional arg)
6153 "TAB-action and visibility cycling for Org-mode.
6155 This is the command invoked in Org-mode by the TAB key. Its main purpose
6156 is outline visibility cycling, but it also invokes other actions
6157 in special contexts.
6159 - When this function is called with a prefix argument, rotate the entire
6160 buffer through 3 states (global cycling)
6161 1. OVERVIEW: Show only top-level headlines.
6162 2. CONTENTS: Show all headlines of all levels, but no body text.
6163 3. SHOW ALL: Show everything.
6164 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6165 determined by the variable `org-startup-folded', and by any VISIBILITY
6166 properties in the buffer.
6167 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6168 including any drawers.
6170 - When inside a table, re-align the table and move to the next field.
6172 - When point is at the beginning of a headline, rotate the subtree started
6173 by this line through 3 different states (local cycling)
6174 1. FOLDED: Only the main headline is shown.
6175 2. CHILDREN: The main headline and the direct children are shown.
6176 From this state, you can move to one of the children
6177 and zoom in further.
6178 3. SUBTREE: Show the entire subtree, including body text.
6179 If there is no subtree, switch directly from CHILDREN to FOLDED.
6181 - When point is at the beginning of an empty headline and the variable
6182 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6183 of the headline by demoting and promoting it to likely levels. This
6184 speeds up creation document structure by pressing TAB once or several
6185 times right after creating a new headline.
6187 - When there is a numeric prefix, go up to a heading with level ARG, do
6188 a `show-subtree' and return to the previous cursor position. If ARG
6189 is negative, go up that many levels.
6191 - When point is not at the beginning of a headline, execute the global
6192 binding for TAB, which is re-indenting the line. See the option
6193 `org-cycle-emulate-tab' for details.
6195 - Special case: if point is at the beginning of the buffer and there is
6196 no headline in line 1, this function will act as if called with prefix arg
6197 (C-u TAB, same as S-TAB) also when called without prefix arg.
6198 But only if also the variable `org-cycle-global-at-bob' is t."
6199 (interactive "P")
6200 (org-load-modules-maybe)
6201 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6202 (and org-cycle-level-after-item/entry-creation
6203 (or (org-cycle-level)
6204 (org-cycle-item-indentation))))
6205 (let* ((limit-level
6206 (or org-cycle-max-level
6207 (and (boundp 'org-inlinetask-min-level)
6208 org-inlinetask-min-level
6209 (1- org-inlinetask-min-level))))
6210 (nstars (and limit-level
6211 (if org-odd-levels-only
6212 (and limit-level (1- (* limit-level 2)))
6213 limit-level)))
6214 (org-outline-regexp
6215 (if (not (derived-mode-p 'org-mode))
6216 outline-regexp
6217 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6218 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6219 (not (looking-at org-outline-regexp))))
6220 (org-cycle-hook
6221 (if bob-special
6222 (delq 'org-optimize-window-after-visibility-change
6223 (copy-sequence org-cycle-hook))
6224 org-cycle-hook))
6225 (pos (point)))
6227 (if (or bob-special (equal arg '(4)))
6228 ;; special case: use global cycling
6229 (setq arg t))
6231 (cond
6233 ((equal arg '(16))
6234 (setq last-command 'dummy)
6235 (org-set-startup-visibility)
6236 (message "Startup visibility, plus VISIBILITY properties"))
6238 ((equal arg '(64))
6239 (show-all)
6240 (message "Entire buffer visible, including drawers"))
6242 ;; Table: enter it or move to the next field.
6243 ((org-at-table-p 'any)
6244 (if (org-at-table.el-p)
6245 (message "Use C-c ' to edit table.el tables")
6246 (if arg (org-table-edit-field t)
6247 (org-table-justify-field-maybe)
6248 (call-interactively 'org-table-next-field))))
6250 ((run-hook-with-args-until-success
6251 'org-tab-after-check-for-table-hook))
6253 ;; Global cycling: delegate to `org-cycle-internal-global'.
6254 ((eq arg t) (org-cycle-internal-global))
6256 ;; Drawers: delegate to `org-flag-drawer'.
6257 ((and org-drawers org-drawer-regexp
6258 (save-excursion
6259 (beginning-of-line 1)
6260 (looking-at org-drawer-regexp)))
6261 (org-flag-drawer ; toggle block visibility
6262 (not (get-char-property (match-end 0) 'invisible))))
6264 ;; Show-subtree, ARG levels up from here.
6265 ((integerp arg)
6266 (save-excursion
6267 (org-back-to-heading)
6268 (outline-up-heading (if (< arg 0) (- arg)
6269 (- (funcall outline-level) arg)))
6270 (org-show-subtree)))
6272 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6273 ((and (featurep 'org-inlinetask)
6274 (org-inlinetask-at-task-p)
6275 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6276 (org-inlinetask-toggle-visibility))
6278 ((org-try-cdlatex-tab))
6280 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6281 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6282 (save-excursion (beginning-of-line 1)
6283 (looking-at org-outline-regexp)))
6284 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6285 (org-cycle-internal-local))
6287 ;; From there: TAB emulation and template completion.
6288 (buffer-read-only (org-back-to-heading))
6290 ((run-hook-with-args-until-success
6291 'org-tab-after-check-for-cycling-hook))
6293 ((org-try-structure-completion))
6295 ((run-hook-with-args-until-success
6296 'org-tab-before-tab-emulation-hook))
6298 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6299 (or (not (bolp))
6300 (not (looking-at org-outline-regexp))))
6301 (call-interactively (global-key-binding "\t")))
6303 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6304 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6305 (or (and (eq org-cycle-emulate-tab 'white)
6306 (= (match-end 0) (point-at-eol)))
6307 (and (eq org-cycle-emulate-tab 'whitestart)
6308 (>= (match-end 0) pos))))
6310 (eq org-cycle-emulate-tab t))
6311 (call-interactively (global-key-binding "\t")))
6313 (t (save-excursion
6314 (org-back-to-heading)
6315 (org-cycle)))))))
6317 (defun org-cycle-internal-global ()
6318 "Do the global cycling action."
6319 ;; Hack to avoid display of messages for .org attachments in Gnus
6320 (let ((ga (string-match "\\*fontification" (buffer-name))))
6321 (cond
6322 ((and (eq last-command this-command)
6323 (eq org-cycle-global-status 'overview))
6324 ;; We just created the overview - now do table of contents
6325 ;; This can be slow in very large buffers, so indicate action
6326 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6327 (unless ga (message "CONTENTS..."))
6328 (org-content)
6329 (unless ga (message "CONTENTS...done"))
6330 (setq org-cycle-global-status 'contents)
6331 (run-hook-with-args 'org-cycle-hook 'contents))
6333 ((and (eq last-command this-command)
6334 (eq org-cycle-global-status 'contents))
6335 ;; We just showed the table of contents - now show everything
6336 (run-hook-with-args 'org-pre-cycle-hook 'all)
6337 (show-all)
6338 (unless ga (message "SHOW ALL"))
6339 (setq org-cycle-global-status 'all)
6340 (run-hook-with-args 'org-cycle-hook 'all))
6343 ;; Default action: go to overview
6344 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6345 (org-overview)
6346 (unless ga (message "OVERVIEW"))
6347 (setq org-cycle-global-status 'overview)
6348 (run-hook-with-args 'org-cycle-hook 'overview)))))
6350 (defun org-cycle-internal-local ()
6351 "Do the local cycling action."
6352 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6353 ;; First, determine end of headline (EOH), end of subtree or item
6354 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6355 (save-excursion
6356 (if (org-at-item-p)
6357 (progn
6358 (beginning-of-line)
6359 (setq struct (org-list-struct))
6360 (setq eoh (point-at-eol))
6361 (setq eos (org-list-get-item-end-before-blank (point) struct))
6362 (setq has-children (org-list-has-child-p (point) struct)))
6363 (org-back-to-heading)
6364 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6365 (setq eos (save-excursion
6366 (org-end-of-subtree t)
6367 (unless (eobp)
6368 (skip-chars-forward " \t\n"))
6369 (if (eobp) (point) (1- (point)))))
6370 (setq has-children
6371 (or (save-excursion
6372 (let ((level (funcall outline-level)))
6373 (outline-next-heading)
6374 (and (org-at-heading-p t)
6375 (> (funcall outline-level) level))))
6376 (save-excursion
6377 (org-list-search-forward (org-item-beginning-re) eos t)))))
6378 ;; Determine end invisible part of buffer (EOL)
6379 (beginning-of-line 2)
6380 ;; XEmacs doesn't have `next-single-char-property-change'
6381 (if (featurep 'xemacs)
6382 (while (and (not (eobp)) ;; this is like `next-line'
6383 (get-char-property (1- (point)) 'invisible))
6384 (beginning-of-line 2))
6385 (while (and (not (eobp)) ;; this is like `next-line'
6386 (get-char-property (1- (point)) 'invisible))
6387 (goto-char (next-single-char-property-change (point) 'invisible))
6388 (and (eolp) (beginning-of-line 2))))
6389 (setq eol (point)))
6390 ;; Find out what to do next and set `this-command'
6391 (cond
6392 ((= eos eoh)
6393 ;; Nothing is hidden behind this heading
6394 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6395 (message "EMPTY ENTRY")
6396 (setq org-cycle-subtree-status nil)
6397 (save-excursion
6398 (goto-char eos)
6399 (outline-next-heading)
6400 (if (outline-invisible-p) (org-flag-heading nil))))
6401 ((and (or (>= eol eos)
6402 (not (string-match "\\S-" (buffer-substring eol eos))))
6403 (or has-children
6404 (not (setq children-skipped
6405 org-cycle-skip-children-state-if-no-children))))
6406 ;; Entire subtree is hidden in one line: children view
6407 (run-hook-with-args 'org-pre-cycle-hook 'children)
6408 (if (org-at-item-p)
6409 (org-list-set-item-visibility (point-at-bol) struct 'children)
6410 (org-show-entry)
6411 (org-with-limited-levels (show-children))
6412 ;; FIXME: This slows down the func way too much.
6413 ;; How keep drawers hidden in subtree anyway?
6414 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6415 ;; (org-cycle-hide-drawers 'subtree))
6417 ;; Fold every list in subtree to top-level items.
6418 (when (eq org-cycle-include-plain-lists 'integrate)
6419 (save-excursion
6420 (org-back-to-heading)
6421 (while (org-list-search-forward (org-item-beginning-re) eos t)
6422 (beginning-of-line 1)
6423 (let* ((struct (org-list-struct))
6424 (prevs (org-list-prevs-alist struct))
6425 (end (org-list-get-bottom-point struct)))
6426 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6427 (org-list-get-all-items (point) struct prevs))
6428 (goto-char end))))))
6429 (message "CHILDREN")
6430 (save-excursion
6431 (goto-char eos)
6432 (outline-next-heading)
6433 (if (outline-invisible-p) (org-flag-heading nil)))
6434 (setq org-cycle-subtree-status 'children)
6435 (run-hook-with-args 'org-cycle-hook 'children))
6436 ((or children-skipped
6437 (and (eq last-command this-command)
6438 (eq org-cycle-subtree-status 'children)))
6439 ;; We just showed the children, or no children are there,
6440 ;; now show everything.
6441 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6442 (outline-flag-region eoh eos nil)
6443 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6444 (setq org-cycle-subtree-status 'subtree)
6445 (run-hook-with-args 'org-cycle-hook 'subtree))
6447 ;; Default action: hide the subtree.
6448 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6449 (outline-flag-region eoh eos t)
6450 (message "FOLDED")
6451 (setq org-cycle-subtree-status 'folded)
6452 (run-hook-with-args 'org-cycle-hook 'folded)))))
6454 ;;;###autoload
6455 (defun org-global-cycle (&optional arg)
6456 "Cycle the global visibility. For details see `org-cycle'.
6457 With \\[universal-argument] prefix arg, switch to startup visibility.
6458 With a numeric prefix, show all headlines up to that level."
6459 (interactive "P")
6460 (let ((org-cycle-include-plain-lists
6461 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6462 (cond
6463 ((integerp arg)
6464 (show-all)
6465 (hide-sublevels arg)
6466 (setq org-cycle-global-status 'contents))
6467 ((equal arg '(4))
6468 (org-set-startup-visibility)
6469 (message "Startup visibility, plus VISIBILITY properties."))
6471 (org-cycle '(4))))))
6473 (defun org-set-startup-visibility ()
6474 "Set the visibility required by startup options and properties."
6475 (cond
6476 ((eq org-startup-folded t)
6477 (org-cycle '(4)))
6478 ((eq org-startup-folded 'content)
6479 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6480 (org-cycle '(4)) (org-cycle '(4)))))
6481 (unless (eq org-startup-folded 'showeverything)
6482 (if org-hide-block-startup (org-hide-block-all))
6483 (org-set-visibility-according-to-property 'no-cleanup)
6484 (org-cycle-hide-archived-subtrees 'all)
6485 (org-cycle-hide-drawers 'all)
6486 (org-cycle-show-empty-lines t)))
6488 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6489 "Switch subtree visibilities according to :VISIBILITY: property."
6490 (interactive)
6491 (let (org-show-entry-below state)
6492 (save-excursion
6493 (goto-char (point-min))
6494 (while (re-search-forward
6495 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6496 nil t)
6497 (setq state (match-string 1))
6498 (save-excursion
6499 (org-back-to-heading t)
6500 (hide-subtree)
6501 (org-reveal)
6502 (cond
6503 ((equal state '("fold" "folded"))
6504 (hide-subtree))
6505 ((equal state "children")
6506 (org-show-hidden-entry)
6507 (show-children))
6508 ((equal state "content")
6509 (save-excursion
6510 (save-restriction
6511 (org-narrow-to-subtree)
6512 (org-content))))
6513 ((member state '("all" "showall"))
6514 (show-subtree)))))
6515 (unless no-cleanup
6516 (org-cycle-hide-archived-subtrees 'all)
6517 (org-cycle-hide-drawers 'all)
6518 (org-cycle-show-empty-lines 'all)))))
6520 ;; This function uses outline-regexp instead of the more fundamental
6521 ;; org-outline-regexp so that org-cycle-global works outside of Org
6522 ;; buffers, where outline-regexp is needed.
6523 (defun org-overview ()
6524 "Switch to overview mode, showing only top-level headlines.
6525 Really, this shows all headlines with level equal or greater than the level
6526 of the first headline in the buffer. This is important, because if the
6527 first headline is not level one, then (hide-sublevels 1) gives confusing
6528 results."
6529 (interactive)
6530 (let ((level (save-excursion
6531 (goto-char (point-min))
6532 (if (re-search-forward (concat "^" outline-regexp) nil t)
6533 (progn
6534 (goto-char (match-beginning 0))
6535 (funcall outline-level))))))
6536 (and level (hide-sublevels level))))
6538 (defun org-content (&optional arg)
6539 "Show all headlines in the buffer, like a table of contents.
6540 With numerical argument N, show content up to level N."
6541 (interactive "P")
6542 (save-excursion
6543 ;; Visit all headings and show their offspring
6544 (and (integerp arg) (org-overview))
6545 (goto-char (point-max))
6546 (catch 'exit
6547 (while (and (progn (condition-case nil
6548 (outline-previous-visible-heading 1)
6549 (error (goto-char (point-min))))
6551 (looking-at org-outline-regexp))
6552 (if (integerp arg)
6553 (show-children (1- arg))
6554 (show-branches))
6555 (if (bobp) (throw 'exit nil))))))
6558 (defun org-optimize-window-after-visibility-change (state)
6559 "Adjust the window after a change in outline visibility.
6560 This function is the default value of the hook `org-cycle-hook'."
6561 (when (get-buffer-window (current-buffer))
6562 (cond
6563 ((eq state 'content) nil)
6564 ((eq state 'all) nil)
6565 ((eq state 'folded) nil)
6566 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6567 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6569 (defun org-remove-empty-overlays-at (pos)
6570 "Remove outline overlays that do not contain non-white stuff."
6571 (mapc
6572 (lambda (o)
6573 (and (eq 'outline (overlay-get o 'invisible))
6574 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6575 (overlay-end o))))
6576 (delete-overlay o)))
6577 (overlays-at pos)))
6579 (defun org-clean-visibility-after-subtree-move ()
6580 "Fix visibility issues after moving a subtree."
6581 ;; First, find a reasonable region to look at:
6582 ;; Start two siblings above, end three below
6583 (let* ((beg (save-excursion
6584 (and (org-get-last-sibling)
6585 (org-get-last-sibling))
6586 (point)))
6587 (end (save-excursion
6588 (and (org-get-next-sibling)
6589 (org-get-next-sibling)
6590 (org-get-next-sibling))
6591 (if (org-at-heading-p)
6592 (point-at-eol)
6593 (point))))
6594 (level (looking-at "\\*+"))
6595 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6596 (save-excursion
6597 (save-restriction
6598 (narrow-to-region beg end)
6599 (when re
6600 ;; Properly fold already folded siblings
6601 (goto-char (point-min))
6602 (while (re-search-forward re nil t)
6603 (if (and (not (outline-invisible-p))
6604 (save-excursion
6605 (goto-char (point-at-eol)) (outline-invisible-p)))
6606 (hide-entry))))
6607 (org-cycle-show-empty-lines 'overview)
6608 (org-cycle-hide-drawers 'overview)))))
6610 (defun org-cycle-show-empty-lines (state)
6611 "Show empty lines above all visible headlines.
6612 The region to be covered depends on STATE when called through
6613 `org-cycle-hook'. Lisp program can use t for STATE to get the
6614 entire buffer covered. Note that an empty line is only shown if there
6615 are at least `org-cycle-separator-lines' empty lines before the headline."
6616 (when (not (= org-cycle-separator-lines 0))
6617 (save-excursion
6618 (let* ((n (abs org-cycle-separator-lines))
6619 (re (cond
6620 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6621 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6622 (t (let ((ns (number-to-string (- n 2))))
6623 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6624 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6625 beg end b e)
6626 (cond
6627 ((memq state '(overview contents t))
6628 (setq beg (point-min) end (point-max)))
6629 ((memq state '(children folded))
6630 (setq beg (point) end (progn (org-end-of-subtree t t)
6631 (beginning-of-line 2)
6632 (point)))))
6633 (when beg
6634 (goto-char beg)
6635 (while (re-search-forward re end t)
6636 (unless (get-char-property (match-end 1) 'invisible)
6637 (setq e (match-end 1))
6638 (if (< org-cycle-separator-lines 0)
6639 (setq b (save-excursion
6640 (goto-char (match-beginning 0))
6641 (org-back-over-empty-lines)
6642 (if (save-excursion
6643 (goto-char (max (point-min) (1- (point))))
6644 (org-at-heading-p))
6645 (1- (point))
6646 (point))))
6647 (setq b (match-beginning 1)))
6648 (outline-flag-region b e nil)))))))
6649 ;; Never hide empty lines at the end of the file.
6650 (save-excursion
6651 (goto-char (point-max))
6652 (outline-previous-heading)
6653 (outline-end-of-heading)
6654 (if (and (looking-at "[ \t\n]+")
6655 (= (match-end 0) (point-max)))
6656 (outline-flag-region (point) (match-end 0) nil))))
6658 (defun org-show-empty-lines-in-parent ()
6659 "Move to the parent and re-show empty lines before visible headlines."
6660 (save-excursion
6661 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6662 (org-cycle-show-empty-lines context))))
6664 (defun org-files-list ()
6665 "Return `org-agenda-files' list, plus all open org-mode files.
6666 This is useful for operations that need to scan all of a user's
6667 open and agenda-wise Org files."
6668 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6669 (dolist (buf (buffer-list))
6670 (with-current-buffer buf
6671 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6672 (let ((file (expand-file-name (buffer-file-name))))
6673 (unless (member file files)
6674 (push file files))))))
6675 files))
6677 (defsubst org-entry-beginning-position ()
6678 "Return the beginning position of the current entry."
6679 (save-excursion (outline-back-to-heading t) (point)))
6681 (defsubst org-entry-end-position ()
6682 "Return the end position of the current entry."
6683 (save-excursion (outline-next-heading) (point)))
6685 (defun org-cycle-hide-drawers (state)
6686 "Re-hide all drawers after a visibility state change."
6687 (when (and (derived-mode-p 'org-mode)
6688 (not (memq state '(overview folded contents))))
6689 (save-excursion
6690 (let* ((globalp (memq state '(contents all)))
6691 (beg (if globalp (point-min) (point)))
6692 (end (if globalp (point-max)
6693 (if (eq state 'children)
6694 (save-excursion (outline-next-heading) (point))
6695 (org-end-of-subtree t)))))
6696 (goto-char beg)
6697 (while (re-search-forward org-drawer-regexp end t)
6698 (org-flag-drawer t))))))
6700 (defun org-flag-drawer (flag)
6701 "When FLAG is non-nil, hide the drawer we are within.
6702 Otherwise make it visible."
6703 (save-excursion
6704 (beginning-of-line 1)
6705 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6706 (let ((b (match-end 0)))
6707 (if (re-search-forward
6708 "^[ \t]*:END:"
6709 (save-excursion (outline-next-heading) (point)) t)
6710 (outline-flag-region b (point-at-eol) flag)
6711 (error ":END: line missing at position %s" b))))))
6713 (defun org-subtree-end-visible-p ()
6714 "Is the end of the current subtree visible?"
6715 (pos-visible-in-window-p
6716 (save-excursion (org-end-of-subtree t) (point))))
6718 (defun org-first-headline-recenter (&optional N)
6719 "Move cursor to the first headline and recenter the headline.
6720 Optional argument N means put the headline into the Nth line of the window."
6721 (goto-char (point-min))
6722 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6723 (beginning-of-line)
6724 (recenter (prefix-numeric-value N))))
6726 ;;; Saving and restoring visibility
6728 (defun org-outline-overlay-data (&optional use-markers)
6729 "Return a list of the locations of all outline overlays.
6730 These are overlays with the `invisible' property value `outline'.
6731 The return value is a list of cons cells, with start and stop
6732 positions for each overlay.
6733 If USE-MARKERS is set, return the positions as markers."
6734 (let (beg end)
6735 (save-excursion
6736 (save-restriction
6737 (widen)
6738 (delq nil
6739 (mapcar (lambda (o)
6740 (when (eq (overlay-get o 'invisible) 'outline)
6741 (setq beg (overlay-start o)
6742 end (overlay-end o))
6743 (and beg end (> end beg)
6744 (if use-markers
6745 (cons (move-marker (make-marker) beg)
6746 (move-marker (make-marker) end))
6747 (cons beg end)))))
6748 (overlays-in (point-min) (point-max))))))))
6750 (defun org-set-outline-overlay-data (data)
6751 "Create visibility overlays for all positions in DATA.
6752 DATA should have been made by `org-outline-overlay-data'."
6753 (let (o)
6754 (save-excursion
6755 (save-restriction
6756 (widen)
6757 (show-all)
6758 (mapc (lambda (c)
6759 (outline-flag-region (car c) (cdr c) t))
6760 data)))))
6762 ;;; Folding of blocks
6764 (defvar org-hide-block-overlays nil
6765 "Overlays hiding blocks.")
6766 (make-variable-buffer-local 'org-hide-block-overlays)
6768 (defun org-block-map (function &optional start end)
6769 "Call FUNCTION at the head of all source blocks in the current buffer.
6770 Optional arguments START and END can be used to limit the range."
6771 (let ((start (or start (point-min)))
6772 (end (or end (point-max))))
6773 (save-excursion
6774 (goto-char start)
6775 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6776 (save-excursion
6777 (save-match-data
6778 (goto-char (match-beginning 0))
6779 (funcall function)))))))
6781 (defun org-hide-block-toggle-all ()
6782 "Toggle the visibility of all blocks in the current buffer."
6783 (org-block-map #'org-hide-block-toggle))
6785 (defun org-hide-block-all ()
6786 "Fold all blocks in the current buffer."
6787 (interactive)
6788 (org-show-block-all)
6789 (org-block-map #'org-hide-block-toggle-maybe))
6791 (defun org-show-block-all ()
6792 "Unfold all blocks in the current buffer."
6793 (interactive)
6794 (mapc 'delete-overlay org-hide-block-overlays)
6795 (setq org-hide-block-overlays nil))
6797 (defun org-hide-block-toggle-maybe ()
6798 "Toggle visibility of block at point."
6799 (interactive)
6800 (let ((case-fold-search t))
6801 (if (save-excursion
6802 (beginning-of-line 1)
6803 (looking-at org-block-regexp))
6804 (progn (org-hide-block-toggle)
6805 t) ;; to signal that we took action
6806 nil))) ;; to signal that we did not
6808 (defun org-hide-block-toggle (&optional force)
6809 "Toggle the visibility of the current block."
6810 (interactive)
6811 (save-excursion
6812 (beginning-of-line)
6813 (if (re-search-forward org-block-regexp nil t)
6814 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6815 (end (match-end 0)) ;; end of entire body
6817 (if (memq t (mapcar (lambda (overlay)
6818 (eq (overlay-get overlay 'invisible)
6819 'org-hide-block))
6820 (overlays-at start)))
6821 (if (or (not force) (eq force 'off))
6822 (mapc (lambda (ov)
6823 (when (member ov org-hide-block-overlays)
6824 (setq org-hide-block-overlays
6825 (delq ov org-hide-block-overlays)))
6826 (when (eq (overlay-get ov 'invisible)
6827 'org-hide-block)
6828 (delete-overlay ov)))
6829 (overlays-at start)))
6830 (setq ov (make-overlay start end))
6831 (overlay-put ov 'invisible 'org-hide-block)
6832 ;; make the block accessible to isearch
6833 (overlay-put
6834 ov 'isearch-open-invisible
6835 (lambda (ov)
6836 (when (member ov org-hide-block-overlays)
6837 (setq org-hide-block-overlays
6838 (delq ov org-hide-block-overlays)))
6839 (when (eq (overlay-get ov 'invisible)
6840 'org-hide-block)
6841 (delete-overlay ov))))
6842 (push ov org-hide-block-overlays)))
6843 (error "Not looking at a source block"))))
6845 ;; org-tab-after-check-for-cycling-hook
6846 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6847 ;; Remove overlays when changing major mode
6848 (add-hook 'org-mode-hook
6849 (lambda () (org-add-hook 'change-major-mode-hook
6850 'org-show-block-all 'append 'local)))
6852 ;;; Org-goto
6854 (defvar org-goto-window-configuration nil)
6855 (defvar org-goto-marker nil)
6856 (defvar org-goto-map
6857 (let ((map (make-sparse-keymap)))
6858 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6859 (while (setq cmd (pop cmds))
6860 (substitute-key-definition cmd cmd map global-map)))
6861 (suppress-keymap map)
6862 (org-defkey map "\C-m" 'org-goto-ret)
6863 (org-defkey map [(return)] 'org-goto-ret)
6864 (org-defkey map [(left)] 'org-goto-left)
6865 (org-defkey map [(right)] 'org-goto-right)
6866 (org-defkey map [(control ?g)] 'org-goto-quit)
6867 (org-defkey map "\C-i" 'org-cycle)
6868 (org-defkey map [(tab)] 'org-cycle)
6869 (org-defkey map [(down)] 'outline-next-visible-heading)
6870 (org-defkey map [(up)] 'outline-previous-visible-heading)
6871 (if org-goto-auto-isearch
6872 (if (fboundp 'define-key-after)
6873 (define-key-after map [t] 'org-goto-local-auto-isearch)
6874 nil)
6875 (org-defkey map "q" 'org-goto-quit)
6876 (org-defkey map "n" 'outline-next-visible-heading)
6877 (org-defkey map "p" 'outline-previous-visible-heading)
6878 (org-defkey map "f" 'outline-forward-same-level)
6879 (org-defkey map "b" 'outline-backward-same-level)
6880 (org-defkey map "u" 'outline-up-heading))
6881 (org-defkey map "/" 'org-occur)
6882 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6883 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6884 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6885 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6886 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6887 map))
6889 (defconst org-goto-help
6890 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6891 RET=jump to location [Q]uit and return to previous location
6892 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6894 (defvar org-goto-start-pos) ; dynamically scoped parameter
6896 ;; FIXME: Docstring does not mention both interfaces
6897 (defun org-goto (&optional alternative-interface)
6898 "Look up a different location in the current file, keeping current visibility.
6900 When you want look-up or go to a different location in a
6901 document, the fastest way is often to fold the entire buffer and
6902 then dive into the tree. This method has the disadvantage, that
6903 the previous location will be folded, which may not be what you
6904 want.
6906 This command works around this by showing a copy of the current
6907 buffer in an indirect buffer, in overview mode. You can dive
6908 into the tree in that copy, use org-occur and incremental search
6909 to find a location. When pressing RET or `Q', the command
6910 returns to the original buffer in which the visibility is still
6911 unchanged. After RET it will also jump to the location selected
6912 in the indirect buffer and expose the headline hierarchy above.
6914 With a prefix argument, use the alternative interface: e.g. if
6915 `org-goto-interface' is 'outline use 'outline-path-completion."
6916 (interactive "P")
6917 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6918 (org-refile-use-outline-path t)
6919 (org-refile-target-verify-function nil)
6920 (interface
6921 (if (not alternative-interface)
6922 org-goto-interface
6923 (if (eq org-goto-interface 'outline)
6924 'outline-path-completion
6925 'outline)))
6926 (org-goto-start-pos (point))
6927 (selected-point
6928 (if (eq interface 'outline)
6929 (car (org-get-location (current-buffer) org-goto-help))
6930 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6931 (org-refile-check-position pa)
6932 (nth 3 pa)))))
6933 (if selected-point
6934 (progn
6935 (org-mark-ring-push org-goto-start-pos)
6936 (goto-char selected-point)
6937 (if (or (outline-invisible-p) (org-invisible-p2))
6938 (org-show-context 'org-goto)))
6939 (message "Quit"))))
6941 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6942 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6943 (defvar org-goto-local-auto-isearch-map) ; defined below
6945 (defun org-get-location (buf help)
6946 "Let the user select a location in the Org-mode buffer BUF.
6947 This function uses a recursive edit. It returns the selected position
6948 or nil."
6949 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6950 (isearch-hide-immediately nil)
6951 (isearch-search-fun-function
6952 (lambda () 'org-goto-local-search-headings))
6953 (org-goto-selected-point org-goto-exit-command)
6954 (pop-up-frames nil)
6955 (special-display-buffer-names nil)
6956 (special-display-regexps nil)
6957 (special-display-function nil))
6958 (save-excursion
6959 (save-window-excursion
6960 (delete-other-windows)
6961 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6962 (org-pop-to-buffer-same-window
6963 (condition-case nil
6964 (make-indirect-buffer (current-buffer) "*org-goto*")
6965 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6966 (with-output-to-temp-buffer "*Help*"
6967 (princ help))
6968 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6969 (setq buffer-read-only nil)
6970 (let ((org-startup-truncated t)
6971 (org-startup-folded nil)
6972 (org-startup-align-all-tables nil))
6973 (org-mode)
6974 (org-overview))
6975 (setq buffer-read-only t)
6976 (if (and (boundp 'org-goto-start-pos)
6977 (integer-or-marker-p org-goto-start-pos))
6978 (let ((org-show-hierarchy-above t)
6979 (org-show-siblings t)
6980 (org-show-following-heading t))
6981 (goto-char org-goto-start-pos)
6982 (and (outline-invisible-p) (org-show-context)))
6983 (goto-char (point-min)))
6984 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6985 (message "Select location and press RET")
6986 (use-local-map org-goto-map)
6987 (recursive-edit)
6989 (kill-buffer "*org-goto*")
6990 (cons org-goto-selected-point org-goto-exit-command)))
6992 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6993 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6994 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6995 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6997 (defun org-goto-local-search-headings (string bound noerror)
6998 "Search and make sure that any matches are in headlines."
6999 (catch 'return
7000 (while (if isearch-forward
7001 (search-forward string bound noerror)
7002 (search-backward string bound noerror))
7003 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7004 (and (member :headline context)
7005 (not (member :tags context))))
7006 (throw 'return (point))))))
7008 (defun org-goto-local-auto-isearch ()
7009 "Start isearch."
7010 (interactive)
7011 (goto-char (point-min))
7012 (let ((keys (this-command-keys)))
7013 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7014 (isearch-mode t)
7015 (isearch-process-search-char (string-to-char keys)))))
7017 (defun org-goto-ret (&optional arg)
7018 "Finish `org-goto' by going to the new location."
7019 (interactive "P")
7020 (setq org-goto-selected-point (point)
7021 org-goto-exit-command 'return)
7022 (throw 'exit nil))
7024 (defun org-goto-left ()
7025 "Finish `org-goto' by going to the new location."
7026 (interactive)
7027 (if (org-at-heading-p)
7028 (progn
7029 (beginning-of-line 1)
7030 (setq org-goto-selected-point (point)
7031 org-goto-exit-command 'left)
7032 (throw 'exit nil))
7033 (error "Not on a heading")))
7035 (defun org-goto-right ()
7036 "Finish `org-goto' by going to the new location."
7037 (interactive)
7038 (if (org-at-heading-p)
7039 (progn
7040 (setq org-goto-selected-point (point)
7041 org-goto-exit-command 'right)
7042 (throw 'exit nil))
7043 (error "Not on a heading")))
7045 (defun org-goto-quit ()
7046 "Finish `org-goto' without cursor motion."
7047 (interactive)
7048 (setq org-goto-selected-point nil)
7049 (setq org-goto-exit-command 'quit)
7050 (throw 'exit nil))
7052 ;;; Indirect buffer display of subtrees
7054 (defvar org-indirect-dedicated-frame nil
7055 "This is the frame being used for indirect tree display.")
7056 (defvar org-last-indirect-buffer nil)
7058 (defun org-tree-to-indirect-buffer (&optional arg)
7059 "Create indirect buffer and narrow it to current subtree.
7060 With numerical prefix ARG, go up to this level and then take that tree.
7061 If ARG is negative, go up that many levels.
7062 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7063 indirect buffer previously made with this command, to avoid proliferation of
7064 indirect buffers. However, when you call the command with a \
7065 \\[universal-argument] prefix, or
7066 when `org-indirect-buffer-display' is `new-frame', the last buffer
7067 is kept so that you can work with several indirect buffers at the same time.
7068 If `org-indirect-buffer-display' is `dedicated-frame', the \
7069 \\[universal-argument] prefix also
7070 requests that a new frame be made for the new buffer, so that the dedicated
7071 frame is not changed."
7072 (interactive "P")
7073 (let ((cbuf (current-buffer))
7074 (cwin (selected-window))
7075 (pos (point))
7076 beg end level heading ibuf)
7077 (save-excursion
7078 (org-back-to-heading t)
7079 (when (numberp arg)
7080 (setq level (org-outline-level))
7081 (if (< arg 0) (setq arg (+ level arg)))
7082 (while (> (setq level (org-outline-level)) arg)
7083 (outline-up-heading 1 t)))
7084 (setq beg (point)
7085 heading (org-get-heading))
7086 (org-end-of-subtree t t)
7087 (if (org-at-heading-p) (backward-char 1))
7088 (setq end (point)))
7089 (if (and (buffer-live-p org-last-indirect-buffer)
7090 (not (eq org-indirect-buffer-display 'new-frame))
7091 (not arg))
7092 (kill-buffer org-last-indirect-buffer))
7093 (setq ibuf (org-get-indirect-buffer cbuf)
7094 org-last-indirect-buffer ibuf)
7095 (cond
7096 ((or (eq org-indirect-buffer-display 'new-frame)
7097 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7098 (select-frame (make-frame))
7099 (delete-other-windows)
7100 (org-pop-to-buffer-same-window ibuf)
7101 (org-set-frame-title heading))
7102 ((eq org-indirect-buffer-display 'dedicated-frame)
7103 (raise-frame
7104 (select-frame (or (and org-indirect-dedicated-frame
7105 (frame-live-p org-indirect-dedicated-frame)
7106 org-indirect-dedicated-frame)
7107 (setq org-indirect-dedicated-frame (make-frame)))))
7108 (delete-other-windows)
7109 (org-pop-to-buffer-same-window ibuf)
7110 (org-set-frame-title (concat "Indirect: " heading)))
7111 ((eq org-indirect-buffer-display 'current-window)
7112 (org-pop-to-buffer-same-window ibuf))
7113 ((eq org-indirect-buffer-display 'other-window)
7114 (pop-to-buffer ibuf))
7115 (t (error "Invalid value")))
7116 (if (featurep 'xemacs)
7117 (save-excursion (org-mode) (turn-on-font-lock)))
7118 (narrow-to-region beg end)
7119 (show-all)
7120 (goto-char pos)
7121 (run-hook-with-args 'org-cycle-hook 'all)
7122 (and (window-live-p cwin) (select-window cwin))))
7124 (defun org-get-indirect-buffer (&optional buffer)
7125 (setq buffer (or buffer (current-buffer)))
7126 (let ((n 1) (base (buffer-name buffer)) bname)
7127 (while (buffer-live-p
7128 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7129 (setq n (1+ n)))
7130 (condition-case nil
7131 (make-indirect-buffer buffer bname 'clone)
7132 (error (make-indirect-buffer buffer bname)))))
7134 (defun org-set-frame-title (title)
7135 "Set the title of the current frame to the string TITLE."
7136 ;; FIXME: how to name a single frame in XEmacs???
7137 (unless (featurep 'xemacs)
7138 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7140 ;;;; Structure editing
7142 ;;; Inserting headlines
7144 (defun org-previous-line-empty-p ()
7145 (save-excursion
7146 (and (not (bobp))
7147 (or (beginning-of-line 0) t)
7148 (save-match-data
7149 (looking-at "[ \t]*$")))))
7151 (defun org-insert-heading (&optional force-heading invisible-ok)
7152 "Insert a new heading or item with same depth at point.
7153 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7154 If point is at the beginning of a headline, insert a sibling before the
7155 current headline. If point is not at the beginning, split the line,
7156 create the new headline with the text in the current line after point
7157 \(but see also the variable `org-M-RET-may-split-line').
7159 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7160 This is important for non-interactive uses of the command."
7161 (interactive "P")
7162 (if (or (= (buffer-size) 0)
7163 (and (not (save-excursion
7164 (and (ignore-errors (org-back-to-heading invisible-ok))
7165 (org-at-heading-p))))
7166 (or force-heading (not (org-in-item-p)))))
7167 (progn
7168 (insert "\n* ")
7169 (run-hooks 'org-insert-heading-hook))
7170 (when (or force-heading (not (org-insert-item)))
7171 (let* ((empty-line-p nil)
7172 (level nil)
7173 (on-heading (org-at-heading-p))
7174 (head (save-excursion
7175 (condition-case nil
7176 (progn
7177 (org-back-to-heading invisible-ok)
7178 (when (and (not on-heading)
7179 (featurep 'org-inlinetask)
7180 (integerp org-inlinetask-min-level)
7181 (>= (length (match-string 0))
7182 org-inlinetask-min-level))
7183 ;; Find a heading level before the inline task
7184 (while (and (setq level (org-up-heading-safe))
7185 (>= level org-inlinetask-min-level)))
7186 (if (org-at-heading-p)
7187 (org-back-to-heading invisible-ok)
7188 (error "This should not happen")))
7189 (setq empty-line-p (org-previous-line-empty-p))
7190 (match-string 0))
7191 (error "*"))))
7192 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7193 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7194 pos hide-previous previous-pos)
7195 (cond
7196 ((and (org-at-heading-p) (bolp)
7197 (or (bobp)
7198 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7199 ;; insert before the current line
7200 (open-line (if blank 2 1)))
7201 ((and (bolp)
7202 (not org-insert-heading-respect-content)
7203 (or (bobp)
7204 (save-excursion
7205 (backward-char 1) (not (outline-invisible-p)))))
7206 ;; insert right here
7207 nil)
7209 ;; somewhere in the line
7210 (save-excursion
7211 (setq previous-pos (point-at-bol))
7212 (end-of-line)
7213 (setq hide-previous (outline-invisible-p)))
7214 (and org-insert-heading-respect-content (org-show-subtree))
7215 (let ((split
7216 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7217 (save-excursion
7218 (let ((p (point)))
7219 (goto-char (point-at-bol))
7220 (and (looking-at org-complex-heading-regexp)
7221 (match-beginning 4)
7222 (> p (match-beginning 4)))))))
7223 tags pos)
7224 (cond
7225 (org-insert-heading-respect-content
7226 (org-end-of-subtree nil t)
7227 (when (featurep 'org-inlinetask)
7228 (while (and (not (eobp))
7229 (looking-at "\\(\\*+\\)[ \t]+")
7230 (>= (length (match-string 1))
7231 org-inlinetask-min-level))
7232 (org-end-of-subtree nil t)))
7233 (or (bolp) (newline))
7234 (or (org-previous-line-empty-p)
7235 (and blank (newline)))
7236 (open-line 1))
7237 ((org-at-heading-p)
7238 (when hide-previous
7239 (show-children)
7240 (org-show-entry))
7241 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7242 (setq tags (and (match-end 2) (match-string 2)))
7243 (and (match-end 1)
7244 (delete-region (match-beginning 1) (match-end 1)))
7245 (setq pos (point-at-bol))
7246 (or split (end-of-line 1))
7247 (delete-horizontal-space)
7248 (if (string-match "\\`\\*+\\'"
7249 (buffer-substring (point-at-bol) (point)))
7250 (insert " "))
7251 (newline (if blank 2 1))
7252 (when tags
7253 (save-excursion
7254 (goto-char pos)
7255 (end-of-line 1)
7256 (insert " " tags)
7257 (org-set-tags nil 'align))))
7259 (or split (end-of-line 1))
7260 (newline (if blank 2 1)))))))
7261 (insert head) (just-one-space)
7262 (setq pos (point))
7263 (end-of-line 1)
7264 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7265 (when (and org-insert-heading-respect-content hide-previous)
7266 (save-excursion
7267 (goto-char previous-pos)
7268 (hide-subtree)))
7269 (run-hooks 'org-insert-heading-hook)))))
7271 (defun org-get-heading (&optional no-tags no-todo)
7272 "Return the heading of the current entry, without the stars.
7273 When NO-TAGS is non-nil, don't include tags.
7274 When NO-TODO is non-nil, don't include TODO keywords."
7275 (save-excursion
7276 (org-back-to-heading t)
7277 (cond
7278 ((and no-tags no-todo)
7279 (looking-at org-complex-heading-regexp)
7280 (match-string 4))
7281 (no-tags
7282 (looking-at (concat org-outline-regexp
7283 "\\(.*?\\)"
7284 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7285 (match-string 1))
7286 (no-todo
7287 (looking-at org-todo-line-regexp)
7288 (match-string 3))
7289 (t (looking-at org-heading-regexp)
7290 (match-string 2)))))
7292 (defun org-heading-components ()
7293 "Return the components of the current heading.
7294 This is a list with the following elements:
7295 - the level as an integer
7296 - the reduced level, different if `org-odd-levels-only' is set.
7297 - the TODO keyword, or nil
7298 - the priority character, like ?A, or nil if no priority is given
7299 - the headline text itself, or the tags string if no headline text
7300 - the tags string, or nil."
7301 (save-excursion
7302 (org-back-to-heading t)
7303 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7304 (list (length (match-string 1))
7305 (org-reduced-level (length (match-string 1)))
7306 (org-match-string-no-properties 2)
7307 (and (match-end 3) (aref (match-string 3) 2))
7308 (org-match-string-no-properties 4)
7309 (org-match-string-no-properties 5)))))
7311 (defun org-get-entry ()
7312 "Get the entry text, after heading, entire subtree."
7313 (save-excursion
7314 (org-back-to-heading t)
7315 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7317 (defun org-insert-heading-after-current ()
7318 "Insert a new heading with same level as current, after current subtree."
7319 (interactive)
7320 (org-back-to-heading)
7321 (org-insert-heading)
7322 (org-move-subtree-down)
7323 (end-of-line 1))
7325 (defun org-insert-heading-respect-content ()
7326 (interactive)
7327 (let ((org-insert-heading-respect-content t))
7328 (org-insert-heading t)))
7330 (defun org-insert-todo-heading-respect-content (&optional force-state)
7331 (interactive "P")
7332 (let ((org-insert-heading-respect-content t))
7333 (org-insert-todo-heading force-state t)))
7335 (defun org-insert-todo-heading (arg &optional force-heading)
7336 "Insert a new heading with the same level and TODO state as current heading.
7337 If the heading has no TODO state, or if the state is DONE, use the first
7338 state (TODO by default). Also with prefix arg, force first state."
7339 (interactive "P")
7340 (when (or force-heading (not (org-insert-item 'checkbox)))
7341 (org-insert-heading force-heading)
7342 (save-excursion
7343 (org-back-to-heading)
7344 (outline-previous-heading)
7345 (looking-at org-todo-line-regexp))
7346 (let*
7347 ((new-mark-x
7348 (if (or arg
7349 (not (match-beginning 2))
7350 (member (match-string 2) org-done-keywords))
7351 (car org-todo-keywords-1)
7352 (match-string 2)))
7353 (new-mark
7355 (run-hook-with-args-until-success
7356 'org-todo-get-default-hook new-mark-x nil)
7357 new-mark-x)))
7358 (beginning-of-line 1)
7359 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7360 (if org-treat-insert-todo-heading-as-state-change
7361 (org-todo new-mark)
7362 (insert new-mark " "))))
7363 (when org-provide-todo-statistics
7364 (org-update-parent-todo-statistics))))
7366 (defun org-insert-subheading (arg)
7367 "Insert a new subheading and demote it.
7368 Works for outline headings and for plain lists alike."
7369 (interactive "P")
7370 (org-insert-heading arg)
7371 (cond
7372 ((org-at-heading-p) (org-do-demote))
7373 ((org-at-item-p) (org-indent-item))))
7375 (defun org-insert-todo-subheading (arg)
7376 "Insert a new subheading with TODO keyword or checkbox and demote it.
7377 Works for outline headings and for plain lists alike."
7378 (interactive "P")
7379 (org-insert-todo-heading arg)
7380 (cond
7381 ((org-at-heading-p) (org-do-demote))
7382 ((org-at-item-p) (org-indent-item))))
7384 ;;; Promotion and Demotion
7386 (defvar org-after-demote-entry-hook nil
7387 "Hook run after an entry has been demoted.
7388 The cursor will be at the beginning of the entry.
7389 When a subtree is being demoted, the hook will be called for each node.")
7391 (defvar org-after-promote-entry-hook nil
7392 "Hook run after an entry has been promoted.
7393 The cursor will be at the beginning of the entry.
7394 When a subtree is being promoted, the hook will be called for each node.")
7396 (defun org-promote-subtree ()
7397 "Promote the entire subtree.
7398 See also `org-promote'."
7399 (interactive)
7400 (save-excursion
7401 (org-with-limited-levels (org-map-tree 'org-promote)))
7402 (org-fix-position-after-promote))
7404 (defun org-demote-subtree ()
7405 "Demote the entire subtree. See `org-demote'.
7406 See also `org-promote'."
7407 (interactive)
7408 (save-excursion
7409 (org-with-limited-levels (org-map-tree 'org-demote)))
7410 (org-fix-position-after-promote))
7413 (defun org-do-promote ()
7414 "Promote the current heading higher up the tree.
7415 If the region is active in `transient-mark-mode', promote all headings
7416 in the region."
7417 (interactive)
7418 (save-excursion
7419 (if (org-region-active-p)
7420 (org-map-region 'org-promote (region-beginning) (region-end))
7421 (org-promote)))
7422 (org-fix-position-after-promote))
7424 (defun org-do-demote ()
7425 "Demote the current heading lower down the tree.
7426 If the region is active in `transient-mark-mode', demote all headings
7427 in the region."
7428 (interactive)
7429 (save-excursion
7430 (if (org-region-active-p)
7431 (org-map-region 'org-demote (region-beginning) (region-end))
7432 (org-demote)))
7433 (org-fix-position-after-promote))
7435 (defun org-fix-position-after-promote ()
7436 "Make sure that after pro/demotion cursor position is right."
7437 (let ((pos (point)))
7438 (when (save-excursion
7439 (beginning-of-line 1)
7440 (looking-at org-todo-line-regexp)
7441 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7442 (cond ((eobp) (insert " "))
7443 ((eolp) (insert " "))
7444 ((equal (char-after) ?\ ) (forward-char 1))))))
7446 (defun org-current-level ()
7447 "Return the level of the current entry, or nil if before the first headline.
7448 The level is the number of stars at the beginning of the headline."
7449 (save-excursion
7450 (org-with-limited-levels
7451 (if (ignore-errors (org-back-to-heading t))
7452 (funcall outline-level)))))
7454 (defun org-get-previous-line-level ()
7455 "Return the outline depth of the last headline before the current line.
7456 Returns 0 for the first headline in the buffer, and nil if before the
7457 first headline."
7458 (let ((current-level (org-current-level))
7459 (prev-level (when (> (line-number-at-pos) 1)
7460 (save-excursion
7461 (beginning-of-line 0)
7462 (org-current-level)))))
7463 (cond ((null current-level) nil) ; Before first headline
7464 ((null prev-level) 0) ; At first headline
7465 (prev-level))))
7467 (defun org-reduced-level (l)
7468 "Compute the effective level of a heading.
7469 This takes into account the setting of `org-odd-levels-only'."
7470 (cond
7471 ((zerop l) 0)
7472 (org-odd-levels-only (1+ (floor (/ l 2))))
7473 (t l)))
7475 (defun org-level-increment ()
7476 "Return the number of stars that will be added or removed at a
7477 time to headlines when structure editing, based on the value of
7478 `org-odd-levels-only'."
7479 (if org-odd-levels-only 2 1))
7481 (defun org-get-valid-level (level &optional change)
7482 "Rectify a level change under the influence of `org-odd-levels-only'
7483 LEVEL is a current level, CHANGE is by how much the level should be
7484 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7485 even level numbers will become the next higher odd number."
7486 (if org-odd-levels-only
7487 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7488 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7489 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7490 (max 1 (+ level (or change 0)))))
7492 (if (boundp 'define-obsolete-function-alias)
7493 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7494 (define-obsolete-function-alias 'org-get-legal-level
7495 'org-get-valid-level)
7496 (define-obsolete-function-alias 'org-get-legal-level
7497 'org-get-valid-level "23.1")))
7499 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7500 ;; ̀org-with-limited-levels'
7501 (defun org-promote ()
7502 "Promote the current heading higher up the tree.
7503 If the region is active in `transient-mark-mode', promote all headings
7504 in the region."
7505 (org-back-to-heading t)
7506 (let* ((level (save-match-data (funcall outline-level)))
7507 (after-change-functions (remove 'flyspell-after-change-function
7508 after-change-functions))
7509 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7510 (diff (abs (- level (length up-head) -1))))
7511 (cond ((and (= level 1) org-called-with-limited-levels
7512 org-allow-promoting-top-level-subtree)
7513 (replace-match "# " nil t))
7514 ((= level 1)
7515 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7516 (t (replace-match up-head nil t)))
7517 ;; Fixup tag positioning
7518 (unless (= level 1)
7519 (and org-auto-align-tags (org-set-tags nil t))
7520 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7521 (run-hooks 'org-after-promote-entry-hook)))
7523 (defun org-demote ()
7524 "Demote the current heading lower down the tree.
7525 If the region is active in `transient-mark-mode', demote all headings
7526 in the region."
7527 (org-back-to-heading t)
7528 (let* ((level (save-match-data (funcall outline-level)))
7529 (after-change-functions (remove 'flyspell-after-change-function
7530 after-change-functions))
7531 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7532 (diff (abs (- level (length down-head) -1))))
7533 (replace-match down-head nil t)
7534 ;; Fixup tag positioning
7535 (and org-auto-align-tags (org-set-tags nil t))
7536 (if org-adapt-indentation (org-fixup-indentation diff))
7537 (run-hooks 'org-after-demote-entry-hook)))
7539 (defun org-cycle-level ()
7540 "Cycle the level of an empty headline through possible states.
7541 This goes first to child, then to parent, level, then up the hierarchy.
7542 After top level, it switches back to sibling level."
7543 (interactive)
7544 (let ((org-adapt-indentation nil))
7545 (when (org-point-at-end-of-empty-headline)
7546 (setq this-command 'org-cycle-level) ; Only needed for caching
7547 (let ((cur-level (org-current-level))
7548 (prev-level (org-get-previous-line-level)))
7549 (cond
7550 ;; If first headline in file, promote to top-level.
7551 ((= prev-level 0)
7552 (loop repeat (/ (- cur-level 1) (org-level-increment))
7553 do (org-do-promote)))
7554 ;; If same level as prev, demote one.
7555 ((= prev-level cur-level)
7556 (org-do-demote))
7557 ;; If parent is top-level, promote to top level if not already.
7558 ((= prev-level 1)
7559 (loop repeat (/ (- cur-level 1) (org-level-increment))
7560 do (org-do-promote)))
7561 ;; If top-level, return to prev-level.
7562 ((= cur-level 1)
7563 (loop repeat (/ (- prev-level 1) (org-level-increment))
7564 do (org-do-demote)))
7565 ;; If less than prev-level, promote one.
7566 ((< cur-level prev-level)
7567 (org-do-promote))
7568 ;; If deeper than prev-level, promote until higher than
7569 ;; prev-level.
7570 ((> cur-level prev-level)
7571 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7572 do (org-do-promote))))
7573 t))))
7575 (defun org-map-tree (fun)
7576 "Call FUN for every heading underneath the current one."
7577 (org-back-to-heading)
7578 (let ((level (funcall outline-level)))
7579 (save-excursion
7580 (funcall fun)
7581 (while (and (progn
7582 (outline-next-heading)
7583 (> (funcall outline-level) level))
7584 (not (eobp)))
7585 (funcall fun)))))
7587 (defun org-map-region (fun beg end)
7588 "Call FUN for every heading between BEG and END."
7589 (let ((org-ignore-region t))
7590 (save-excursion
7591 (setq end (copy-marker end))
7592 (goto-char beg)
7593 (if (and (re-search-forward org-outline-regexp-bol nil t)
7594 (< (point) end))
7595 (funcall fun))
7596 (while (and (progn
7597 (outline-next-heading)
7598 (< (point) end))
7599 (not (eobp)))
7600 (funcall fun)))))
7602 (defvar org-property-end-re) ; silence byte-compiler
7603 (defun org-fixup-indentation (diff)
7604 "Change the indentation in the current entry by DIFF.
7605 However, if any line in the current entry has no indentation, or if it
7606 would end up with no indentation after the change, nothing at all is done."
7607 (save-excursion
7608 (let ((end (save-excursion (outline-next-heading)
7609 (point-marker)))
7610 (prohibit (if (> diff 0)
7611 "^\\S-"
7612 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7613 col)
7614 (unless (save-excursion (end-of-line 1)
7615 (re-search-forward prohibit end t))
7616 (while (and (< (point) end)
7617 (re-search-forward "^[ \t]+" end t))
7618 (goto-char (match-end 0))
7619 (setq col (current-column))
7620 (if (< diff 0) (replace-match ""))
7621 (org-indent-to-column (+ diff col))))
7622 (move-marker end nil))))
7624 (defun org-convert-to-odd-levels ()
7625 "Convert an org-mode file with all levels allowed to one with odd levels.
7626 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7627 level 5 etc."
7628 (interactive)
7629 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7630 (let ((outline-level 'org-outline-level)
7631 (org-odd-levels-only nil) n)
7632 (save-excursion
7633 (goto-char (point-min))
7634 (while (re-search-forward "^\\*\\*+ " nil t)
7635 (setq n (- (length (match-string 0)) 2))
7636 (while (>= (setq n (1- n)) 0)
7637 (org-demote))
7638 (end-of-line 1))))))
7640 (defun org-convert-to-oddeven-levels ()
7641 "Convert an org-mode file with only odd levels to one with odd/even levels.
7642 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7643 file contains a section with an even level, conversion would
7644 destroy the structure of the file. An error is signaled in this
7645 case."
7646 (interactive)
7647 (goto-char (point-min))
7648 ;; First check if there are no even levels
7649 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7650 (org-show-context t)
7651 (error "Not all levels are odd in this file. Conversion not possible"))
7652 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7653 (let ((outline-regexp org-outline-regexp)
7654 (outline-level 'org-outline-level)
7655 (org-odd-levels-only nil) n)
7656 (save-excursion
7657 (goto-char (point-min))
7658 (while (re-search-forward "^\\*\\*+ " nil t)
7659 (setq n (/ (1- (length (match-string 0))) 2))
7660 (while (>= (setq n (1- n)) 0)
7661 (org-promote))
7662 (end-of-line 1))))))
7664 (defun org-tr-level (n)
7665 "Make N odd if required."
7666 (if org-odd-levels-only (1+ (/ n 2)) n))
7668 ;;; Vertical tree motion, cutting and pasting of subtrees
7670 (defun org-move-subtree-up (&optional arg)
7671 "Move the current subtree up past ARG headlines of the same level."
7672 (interactive "p")
7673 (org-move-subtree-down (- (prefix-numeric-value arg))))
7675 (defun org-move-subtree-down (&optional arg)
7676 "Move the current subtree down past ARG headlines of the same level."
7677 (interactive "p")
7678 (setq arg (prefix-numeric-value arg))
7679 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7680 'org-get-last-sibling))
7681 (ins-point (make-marker))
7682 (cnt (abs arg))
7683 (col (current-column))
7684 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7685 ;; Select the tree
7686 (org-back-to-heading)
7687 (setq beg0 (point))
7688 (save-excursion
7689 (setq ne-beg (org-back-over-empty-lines))
7690 (setq beg (point)))
7691 (save-match-data
7692 (save-excursion (outline-end-of-heading)
7693 (setq folded (outline-invisible-p)))
7694 (outline-end-of-subtree))
7695 (outline-next-heading)
7696 (setq ne-end (org-back-over-empty-lines))
7697 (setq end (point))
7698 (goto-char beg0)
7699 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7700 ;; include less whitespace
7701 (save-excursion
7702 (goto-char beg)
7703 (forward-line (- ne-beg ne-end))
7704 (setq beg (point))))
7705 ;; Find insertion point, with error handling
7706 (while (> cnt 0)
7707 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7708 (progn (goto-char beg0)
7709 (error "Cannot move past superior level or buffer limit")))
7710 (setq cnt (1- cnt)))
7711 (if (> arg 0)
7712 ;; Moving forward - still need to move over subtree
7713 (progn (org-end-of-subtree t t)
7714 (save-excursion
7715 (org-back-over-empty-lines)
7716 (or (bolp) (newline)))))
7717 (setq ne-ins (org-back-over-empty-lines))
7718 (move-marker ins-point (point))
7719 (setq txt (buffer-substring beg end))
7720 (org-save-markers-in-region beg end)
7721 (delete-region beg end)
7722 (org-remove-empty-overlays-at beg)
7723 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7724 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7725 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7726 (let ((bbb (point)))
7727 (insert-before-markers txt)
7728 (org-reinstall-markers-in-region bbb)
7729 (move-marker ins-point bbb))
7730 (or (bolp) (insert "\n"))
7731 (setq ins-end (point))
7732 (goto-char ins-point)
7733 (org-skip-whitespace)
7734 (when (and (< arg 0)
7735 (org-first-sibling-p)
7736 (> ne-ins ne-beg))
7737 ;; Move whitespace back to beginning
7738 (save-excursion
7739 (goto-char ins-end)
7740 (let ((kill-whole-line t))
7741 (kill-line (- ne-ins ne-beg)) (point)))
7742 (insert (make-string (- ne-ins ne-beg) ?\n)))
7743 (move-marker ins-point nil)
7744 (if folded
7745 (hide-subtree)
7746 (org-show-entry)
7747 (show-children)
7748 (org-cycle-hide-drawers 'children))
7749 (org-clean-visibility-after-subtree-move)
7750 ;; move back to the initial column we were at
7751 (move-to-column col)))
7753 (defvar org-subtree-clip ""
7754 "Clipboard for cut and paste of subtrees.
7755 This is actually only a copy of the kill, because we use the normal kill
7756 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7758 (defvar org-subtree-clip-folded nil
7759 "Was the last copied subtree folded?
7760 This is used to fold the tree back after pasting.")
7762 (defun org-cut-subtree (&optional n)
7763 "Cut the current subtree into the clipboard.
7764 With prefix arg N, cut this many sequential subtrees.
7765 This is a short-hand for marking the subtree and then cutting it."
7766 (interactive "p")
7767 (org-copy-subtree n 'cut))
7769 (defun org-copy-subtree (&optional n cut force-store-markers)
7770 "Cut the current subtree into the clipboard.
7771 With prefix arg N, cut this many sequential subtrees.
7772 This is a short-hand for marking the subtree and then copying it.
7773 If CUT is non-nil, actually cut the subtree.
7774 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7775 of some markers in the region, even if CUT is non-nil. This is
7776 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7777 (interactive "p")
7778 (let (beg end folded (beg0 (point)))
7779 (if (org-called-interactively-p 'any)
7780 (org-back-to-heading nil) ; take what looks like a subtree
7781 (org-back-to-heading t)) ; take what is really there
7782 (org-back-over-empty-lines)
7783 (setq beg (point))
7784 (skip-chars-forward " \t\r\n")
7785 (save-match-data
7786 (save-excursion (outline-end-of-heading)
7787 (setq folded (outline-invisible-p)))
7788 (condition-case nil
7789 (org-forward-same-level (1- n) t)
7790 (error nil))
7791 (org-end-of-subtree t t))
7792 (org-back-over-empty-lines)
7793 (setq end (point))
7794 (goto-char beg0)
7795 (when (> end beg)
7796 (setq org-subtree-clip-folded folded)
7797 (when (or cut force-store-markers)
7798 (org-save-markers-in-region beg end))
7799 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7800 (setq org-subtree-clip (current-kill 0))
7801 (message "%s: Subtree(s) with %d characters"
7802 (if cut "Cut" "Copied")
7803 (length org-subtree-clip)))))
7805 (defun org-paste-subtree (&optional level tree for-yank)
7806 "Paste the clipboard as a subtree, with modification of headline level.
7807 The entire subtree is promoted or demoted in order to match a new headline
7808 level.
7810 If the cursor is at the beginning of a headline, the same level as
7811 that headline is used to paste the tree
7813 If not, the new level is derived from the *visible* headings
7814 before and after the insertion point, and taken to be the inferior headline
7815 level of the two. So if the previous visible heading is level 3 and the
7816 next is level 4 (or vice versa), level 4 will be used for insertion.
7817 This makes sure that the subtree remains an independent subtree and does
7818 not swallow low level entries.
7820 You can also force a different level, either by using a numeric prefix
7821 argument, or by inserting the heading marker by hand. For example, if the
7822 cursor is after \"*****\", then the tree will be shifted to level 5.
7824 If optional TREE is given, use this text instead of the kill ring.
7826 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7827 move back over whitespace before inserting, and move point to the end of
7828 the inserted text when done."
7829 (interactive "P")
7830 (setq tree (or tree (and kill-ring (current-kill 0))))
7831 (unless (org-kill-is-subtree-p tree)
7832 (error "%s"
7833 (substitute-command-keys
7834 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7835 (org-with-limited-levels
7836 (let* ((visp (not (outline-invisible-p)))
7837 (txt tree)
7838 (^re_ "\\(\\*+\\)[ \t]*")
7839 (old-level (if (string-match org-outline-regexp-bol txt)
7840 (- (match-end 0) (match-beginning 0) 1)
7841 -1))
7842 (force-level (cond (level (prefix-numeric-value level))
7843 ((and (looking-at "[ \t]*$")
7844 (string-match
7845 "^\\*+$" (buffer-substring
7846 (point-at-bol) (point))))
7847 (- (match-end 1) (match-beginning 1)))
7848 ((and (bolp)
7849 (looking-at org-outline-regexp))
7850 (- (match-end 0) (point) 1))
7851 (t nil)))
7852 (previous-level (save-excursion
7853 (condition-case nil
7854 (progn
7855 (outline-previous-visible-heading 1)
7856 (if (looking-at ^re_)
7857 (- (match-end 0) (match-beginning 0) 1)
7859 (error 1))))
7860 (next-level (save-excursion
7861 (condition-case nil
7862 (progn
7863 (or (looking-at org-outline-regexp)
7864 (outline-next-visible-heading 1))
7865 (if (looking-at ^re_)
7866 (- (match-end 0) (match-beginning 0) 1)
7868 (error 1))))
7869 (new-level (or force-level (max previous-level next-level)))
7870 (shift (if (or (= old-level -1)
7871 (= new-level -1)
7872 (= old-level new-level))
7874 (- new-level old-level)))
7875 (delta (if (> shift 0) -1 1))
7876 (func (if (> shift 0) 'org-demote 'org-promote))
7877 (org-odd-levels-only nil)
7878 beg end newend)
7879 ;; Remove the forced level indicator
7880 (if force-level
7881 (delete-region (point-at-bol) (point)))
7882 ;; Paste
7883 (beginning-of-line (if (bolp) 1 2))
7884 (unless for-yank (org-back-over-empty-lines))
7885 (setq beg (point))
7886 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7887 (insert-before-markers txt)
7888 (unless (string-match "\n\\'" txt) (insert "\n"))
7889 (setq newend (point))
7890 (org-reinstall-markers-in-region beg)
7891 (setq end (point))
7892 (goto-char beg)
7893 (skip-chars-forward " \t\n\r")
7894 (setq beg (point))
7895 (if (and (outline-invisible-p) visp)
7896 (save-excursion (outline-show-heading)))
7897 ;; Shift if necessary
7898 (unless (= shift 0)
7899 (save-restriction
7900 (narrow-to-region beg end)
7901 (while (not (= shift 0))
7902 (org-map-region func (point-min) (point-max))
7903 (setq shift (+ delta shift)))
7904 (goto-char (point-min))
7905 (setq newend (point-max))))
7906 (when (or (org-called-interactively-p 'interactive) for-yank)
7907 (message "Clipboard pasted as level %d subtree" new-level))
7908 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7909 kill-ring
7910 (eq org-subtree-clip (current-kill 0))
7911 org-subtree-clip-folded)
7912 ;; The tree was folded before it was killed/copied
7913 (hide-subtree))
7914 (and for-yank (goto-char newend)))))
7916 (defun org-kill-is-subtree-p (&optional txt)
7917 "Check if the current kill is an outline subtree, or a set of trees.
7918 Returns nil if kill does not start with a headline, or if the first
7919 headline level is not the largest headline level in the tree.
7920 So this will actually accept several entries of equal levels as well,
7921 which is OK for `org-paste-subtree'.
7922 If optional TXT is given, check this string instead of the current kill."
7923 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7924 (re (org-get-limited-outline-regexp))
7925 (^re (concat "^" re))
7926 (start-level (and kill
7927 (string-match
7928 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7929 kill)
7930 (- (match-end 2) (match-beginning 2) 1)))
7931 (start (1+ (or (match-beginning 2) -1))))
7932 (if (not start-level)
7933 (progn
7934 nil) ;; does not even start with a heading
7935 (catch 'exit
7936 (while (setq start (string-match ^re kill (1+ start)))
7937 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7938 (throw 'exit nil)))
7939 t))))
7941 (defvar org-markers-to-move nil
7942 "Markers that should be moved with a cut-and-paste operation.
7943 Those markers are stored together with their positions relative to
7944 the start of the region.")
7946 (defun org-save-markers-in-region (beg end)
7947 "Check markers in region.
7948 If these markers are between BEG and END, record their position relative
7949 to BEG, so that after moving the block of text, we can put the markers back
7950 into place.
7951 This function gets called just before an entry or tree gets cut from the
7952 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7953 called immediately, to move the markers with the entries."
7954 (setq org-markers-to-move nil)
7955 (when (featurep 'org-clock)
7956 (org-clock-save-markers-for-cut-and-paste beg end))
7957 (when (featurep 'org-agenda)
7958 (org-agenda-save-markers-for-cut-and-paste beg end)))
7960 (defun org-check-and-save-marker (marker beg end)
7961 "Check if MARKER is between BEG and END.
7962 If yes, remember the marker and the distance to BEG."
7963 (when (and (marker-buffer marker)
7964 (equal (marker-buffer marker) (current-buffer)))
7965 (if (and (>= marker beg) (< marker end))
7966 (push (cons marker (- marker beg)) org-markers-to-move))))
7968 (defun org-reinstall-markers-in-region (beg)
7969 "Move all remembered markers to their position relative to BEG."
7970 (mapc (lambda (x)
7971 (move-marker (car x) (+ beg (cdr x))))
7972 org-markers-to-move)
7973 (setq org-markers-to-move nil))
7975 (defun org-narrow-to-subtree ()
7976 "Narrow buffer to the current subtree."
7977 (interactive)
7978 (save-excursion
7979 (save-match-data
7980 (org-with-limited-levels
7981 (narrow-to-region
7982 (progn (org-back-to-heading t) (point))
7983 (progn (org-end-of-subtree t t)
7984 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7985 (point)))))))
7987 (defun org-narrow-to-block ()
7988 "Narrow buffer to the current block."
7989 (interactive)
7990 (let* ((case-fold-search t)
7991 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7992 "^[ \t]*#\\+end_.*")))
7993 (if blockp
7994 (narrow-to-region (car blockp) (cdr blockp))
7995 (error "Not in a block"))))
7997 (eval-when-compile
7998 (defvar org-property-drawer-re))
8000 (defvar org-property-start-re) ;; defined below
8001 (defun org-clone-subtree-with-time-shift (n &optional shift)
8002 "Clone the task (subtree) at point N times.
8003 The clones will be inserted as siblings.
8005 In interactive use, the user will be prompted for the number of
8006 clones to be produced, and for a time SHIFT, which may be a
8007 repeater as used in time stamps, for example `+3d'.
8009 When a valid repeater is given and the entry contains any time
8010 stamps, the clones will become a sequence in time, with time
8011 stamps in the subtree shifted for each clone produced. If SHIFT
8012 is nil or the empty string, time stamps will be left alone. The
8013 ID property of the original subtree is removed.
8015 If the original subtree did contain time stamps with a repeater,
8016 the following will happen:
8017 - the repeater will be removed in each clone
8018 - an additional clone will be produced, with the current, unshifted
8019 date(s) in the entry.
8020 - the original entry will be placed *after* all the clones, with
8021 repeater intact.
8022 - the start days in the repeater in the original entry will be shifted
8023 to past the last clone.
8024 In this way you can spell out a number of instances of a repeating task,
8025 and still retain the repeater to cover future instances of the task."
8026 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8027 (let (beg end template task idprop
8028 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8029 (drawer-re org-drawer-regexp))
8030 (if (not (and (integerp n) (> n 0)))
8031 (error "Invalid number of replications %s" n))
8032 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8033 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8034 shift)))
8035 (error "Invalid shift specification %s" shift))
8036 (when doshift
8037 (setq shift-n (string-to-number (match-string 1 shift))
8038 shift-what (cdr (assoc (match-string 2 shift)
8039 '(("d" . day) ("w" . week)
8040 ("m" . month) ("y" . year))))))
8041 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8042 (setq nmin 1 nmax n)
8043 (org-back-to-heading t)
8044 (setq beg (point))
8045 (setq idprop (org-entry-get nil "ID"))
8046 (org-end-of-subtree t t)
8047 (or (bolp) (insert "\n"))
8048 (setq end (point))
8049 (setq template (buffer-substring beg end))
8050 (when (and doshift
8051 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8052 (delete-region beg end)
8053 (setq end beg)
8054 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8055 (goto-char end)
8056 (loop for n from nmin to nmax do
8057 ;; prepare clone
8058 (with-temp-buffer
8059 (insert template)
8060 (org-mode)
8061 (goto-char (point-min))
8062 (org-show-subtree)
8063 (and idprop (if org-clone-delete-id
8064 (org-entry-delete nil "ID")
8065 (org-id-get-create t)))
8066 (unless (= n 0)
8067 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8068 (kill-whole-line))
8069 (goto-char (point-min))
8070 (while (re-search-forward drawer-re nil t)
8071 (mapc (lambda (d)
8072 (org-remove-empty-drawer-at d (point))) org-drawers)))
8073 (goto-char (point-min))
8074 (when doshift
8075 (while (re-search-forward org-ts-regexp-both nil t)
8076 (org-timestamp-change (* n shift-n) shift-what))
8077 (unless (= n n-no-remove)
8078 (goto-char (point-min))
8079 (while (re-search-forward org-ts-regexp nil t)
8080 (save-excursion
8081 (goto-char (match-beginning 0))
8082 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8083 (delete-region (match-beginning 1) (match-end 1)))))))
8084 (setq task (buffer-string)))
8085 (insert task))
8086 (goto-char beg)))
8088 ;;; Outline Sorting
8090 (defun org-sort (with-case)
8091 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8092 Optional argument WITH-CASE means sort case-sensitively."
8093 (interactive "P")
8094 (cond
8095 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8096 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8098 (org-call-with-arg 'org-sort-entries with-case))))
8100 (defun org-sort-remove-invisible (s)
8101 (remove-text-properties 0 (length s) org-rm-props s)
8102 (while (string-match org-bracket-link-regexp s)
8103 (setq s (replace-match (if (match-end 2)
8104 (match-string 3 s)
8105 (match-string 1 s)) t t s)))
8108 (defvar org-priority-regexp) ; defined later in the file
8110 (defvar org-after-sorting-entries-or-items-hook nil
8111 "Hook that is run after a bunch of entries or items have been sorted.
8112 When children are sorted, the cursor is in the parent line when this
8113 hook gets called. When a region or a plain list is sorted, the cursor
8114 will be in the first entry of the sorted region/list.")
8116 (defun org-sort-entries
8117 (&optional with-case sorting-type getkey-func compare-func property)
8118 "Sort entries on a certain level of an outline tree.
8119 If there is an active region, the entries in the region are sorted.
8120 Else, if the cursor is before the first entry, sort the top-level items.
8121 Else, the children of the entry at point are sorted.
8123 Sorting can be alphabetically, numerically, by date/time as given by
8124 a time stamp, by a property or by priority.
8126 The command prompts for the sorting type unless it has been given to the
8127 function through the SORTING-TYPE argument, which needs to be a character,
8128 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8129 precise meaning of each character:
8131 n Numerically, by converting the beginning of the entry/item to a number.
8132 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8133 t By date/time, either the first active time stamp in the entry, or, if
8134 none exist, by the first inactive one.
8135 s By the scheduled date/time.
8136 d By deadline date/time.
8137 c By creation time, which is assumed to be the first inactive time stamp
8138 at the beginning of a line.
8139 p By priority according to the cookie.
8140 r By the value of a property.
8142 Capital letters will reverse the sort order.
8144 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8145 called with point at the beginning of the record. It must return either
8146 a string or a number that should serve as the sorting key for that record.
8148 Comparing entries ignores case by default. However, with an optional argument
8149 WITH-CASE, the sorting considers case as well."
8150 (interactive "P")
8151 (let ((case-func (if with-case 'identity 'downcase))
8152 start beg end stars re re2
8153 txt what tmp)
8154 ;; Find beginning and end of region to sort
8155 (cond
8156 ((org-region-active-p)
8157 ;; we will sort the region
8158 (setq end (region-end)
8159 what "region")
8160 (goto-char (region-beginning))
8161 (if (not (org-at-heading-p)) (outline-next-heading))
8162 (setq start (point)))
8163 ((or (org-at-heading-p)
8164 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8165 ;; we will sort the children of the current headline
8166 (org-back-to-heading)
8167 (setq start (point)
8168 end (progn (org-end-of-subtree t t)
8169 (or (bolp) (insert "\n"))
8170 (org-back-over-empty-lines)
8171 (point))
8172 what "children")
8173 (goto-char start)
8174 (show-subtree)
8175 (outline-next-heading))
8177 ;; we will sort the top-level entries in this file
8178 (goto-char (point-min))
8179 (or (org-at-heading-p) (outline-next-heading))
8180 (setq start (point))
8181 (goto-char (point-max))
8182 (beginning-of-line 1)
8183 (when (looking-at ".*?\\S-")
8184 ;; File ends in a non-white line
8185 (end-of-line 1)
8186 (insert "\n"))
8187 (setq end (point-max))
8188 (setq what "top-level")
8189 (goto-char start)
8190 (show-all)))
8192 (setq beg (point))
8193 (if (>= beg end) (error "Nothing to sort"))
8195 (looking-at "\\(\\*+\\)")
8196 (setq stars (match-string 1)
8197 re (concat "^" (regexp-quote stars) " +")
8198 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8199 txt (buffer-substring beg end))
8200 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8201 (if (and (not (equal stars "*")) (string-match re2 txt))
8202 (error "Region to sort contains a level above the first entry"))
8204 (unless sorting-type
8205 (message
8206 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8207 [t]ime [s]cheduled [d]eadline [c]reated
8208 A/N/T/S/D/C/P/O/F means reversed:"
8209 what)
8210 (setq sorting-type (read-char-exclusive))
8212 (and (= (downcase sorting-type) ?f)
8213 (setq getkey-func
8214 (org-icompleting-read "Sort using function: "
8215 obarray 'fboundp t nil nil))
8216 (setq getkey-func (intern getkey-func)))
8218 (and (= (downcase sorting-type) ?r)
8219 (setq property
8220 (org-icompleting-read "Property: "
8221 (mapcar 'list (org-buffer-property-keys t))
8222 nil t))))
8224 (message "Sorting entries...")
8226 (save-restriction
8227 (narrow-to-region start end)
8228 (let ((dcst (downcase sorting-type))
8229 (case-fold-search nil)
8230 (now (current-time)))
8231 (sort-subr
8232 (/= dcst sorting-type)
8233 ;; This function moves to the beginning character of the "record" to
8234 ;; be sorted.
8235 (lambda nil
8236 (if (re-search-forward re nil t)
8237 (goto-char (match-beginning 0))
8238 (goto-char (point-max))))
8239 ;; This function moves to the last character of the "record" being
8240 ;; sorted.
8241 (lambda nil
8242 (save-match-data
8243 (condition-case nil
8244 (outline-forward-same-level 1)
8245 (error
8246 (goto-char (point-max))))))
8247 ;; This function returns the value that gets sorted against.
8248 (lambda nil
8249 (cond
8250 ((= dcst ?n)
8251 (if (looking-at org-complex-heading-regexp)
8252 (string-to-number (match-string 4))
8253 nil))
8254 ((= dcst ?a)
8255 (if (looking-at org-complex-heading-regexp)
8256 (funcall case-func (match-string 4))
8257 nil))
8258 ((= dcst ?t)
8259 (let ((end (save-excursion (outline-next-heading) (point))))
8260 (if (or (re-search-forward org-ts-regexp end t)
8261 (re-search-forward org-ts-regexp-both end t))
8262 (org-time-string-to-seconds (match-string 0))
8263 (org-float-time now))))
8264 ((= dcst ?c)
8265 (let ((end (save-excursion (outline-next-heading) (point))))
8266 (if (re-search-forward
8267 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8268 end t)
8269 (org-time-string-to-seconds (match-string 0))
8270 (org-float-time now))))
8271 ((= dcst ?s)
8272 (let ((end (save-excursion (outline-next-heading) (point))))
8273 (if (re-search-forward org-scheduled-time-regexp end t)
8274 (org-time-string-to-seconds (match-string 1))
8275 (org-float-time now))))
8276 ((= dcst ?d)
8277 (let ((end (save-excursion (outline-next-heading) (point))))
8278 (if (re-search-forward org-deadline-time-regexp end t)
8279 (org-time-string-to-seconds (match-string 1))
8280 (org-float-time now))))
8281 ((= dcst ?p)
8282 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8283 (string-to-char (match-string 2))
8284 org-default-priority))
8285 ((= dcst ?r)
8286 (or (org-entry-get nil property) ""))
8287 ((= dcst ?o)
8288 (if (looking-at org-complex-heading-regexp)
8289 (- 9999 (length (member (match-string 2)
8290 org-todo-keywords-1)))))
8291 ((= dcst ?f)
8292 (if getkey-func
8293 (progn
8294 (setq tmp (funcall getkey-func))
8295 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8296 tmp)
8297 (error "Invalid key function `%s'" getkey-func)))
8298 (t (error "Invalid sorting type `%c'" sorting-type))))
8300 (cond
8301 ((= dcst ?a) 'string<)
8302 ((= dcst ?f) compare-func)
8303 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8304 (t nil)))))
8305 (run-hooks 'org-after-sorting-entries-or-items-hook)
8306 (message "Sorting entries...done")))
8308 (defun org-do-sort (table what &optional with-case sorting-type)
8309 "Sort TABLE of WHAT according to SORTING-TYPE.
8310 The user will be prompted for the SORTING-TYPE if the call to this
8311 function does not specify it. WHAT is only for the prompt, to indicate
8312 what is being sorted. The sorting key will be extracted from
8313 the car of the elements of the table.
8314 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8315 (unless sorting-type
8316 (message
8317 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8318 what)
8319 (setq sorting-type (read-char-exclusive)))
8320 (let ((dcst (downcase sorting-type))
8321 extractfun comparefun)
8322 ;; Define the appropriate functions
8323 (cond
8324 ((= dcst ?n)
8325 (setq extractfun 'string-to-number
8326 comparefun (if (= dcst sorting-type) '< '>)))
8327 ((= dcst ?a)
8328 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8329 (lambda(x) (downcase (org-sort-remove-invisible x))))
8330 comparefun (if (= dcst sorting-type)
8331 'string<
8332 (lambda (a b) (and (not (string< a b))
8333 (not (string= a b)))))))
8334 ((= dcst ?t)
8335 (setq extractfun
8336 (lambda (x)
8337 (if (or (string-match org-ts-regexp x)
8338 (string-match org-ts-regexp-both x))
8339 (org-float-time
8340 (org-time-string-to-time (match-string 0 x)))
8342 comparefun (if (= dcst sorting-type) '< '>)))
8343 (t (error "Invalid sorting type `%c'" sorting-type)))
8345 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8346 table)
8347 (lambda (a b) (funcall comparefun (car a) (car b))))))
8350 ;;; The orgstruct minor mode
8352 ;; Define a minor mode which can be used in other modes in order to
8353 ;; integrate the org-mode structure editing commands.
8355 ;; This is really a hack, because the org-mode structure commands use
8356 ;; keys which normally belong to the major mode. Here is how it
8357 ;; works: The minor mode defines all the keys necessary to operate the
8358 ;; structure commands, but wraps the commands into a function which
8359 ;; tests if the cursor is currently at a headline or a plain list
8360 ;; item. If that is the case, the structure command is used,
8361 ;; temporarily setting many Org-mode variables like regular
8362 ;; expressions for filling etc. However, when any of those keys is
8363 ;; used at a different location, function uses `key-binding' to look
8364 ;; up if the key has an associated command in another currently active
8365 ;; keymap (minor modes, major mode, global), and executes that
8366 ;; command. There might be problems if any of the keys is otherwise
8367 ;; used as a prefix key.
8369 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8370 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8371 ;; addresses this by checking explicitly for both bindings.
8373 (defvar orgstruct-mode-map (make-sparse-keymap)
8374 "Keymap for the minor `orgstruct-mode'.")
8376 (defvar org-local-vars nil
8377 "List of local variables, for use by `orgstruct-mode'.")
8379 ;;;###autoload
8380 (define-minor-mode orgstruct-mode
8381 "Toggle the minor mode `orgstruct-mode'.
8382 This mode is for using Org-mode structure commands in other
8383 modes. The following keys behave as if Org-mode were active, if
8384 the cursor is on a headline, or on a plain list item (both as
8385 defined by Org-mode).
8387 M-up Move entry/item up
8388 M-down Move entry/item down
8389 M-left Promote
8390 M-right Demote
8391 M-S-up Move entry/item up
8392 M-S-down Move entry/item down
8393 M-S-left Promote subtree
8394 M-S-right Demote subtree
8395 M-q Fill paragraph and items like in Org-mode
8396 C-c ^ Sort entries
8397 C-c - Cycle list bullet
8398 TAB Cycle item visibility
8399 M-RET Insert new heading/item
8400 S-M-RET Insert new TODO heading / Checkbox item
8401 C-c C-c Set tags / toggle checkbox"
8402 nil " OrgStruct" nil
8403 (org-load-modules-maybe)
8404 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8406 ;;;###autoload
8407 (defun turn-on-orgstruct ()
8408 "Unconditionally turn on `orgstruct-mode'."
8409 (orgstruct-mode 1))
8411 (defvar org-fb-vars nil)
8412 (make-variable-buffer-local 'org-fb-vars)
8413 (defun orgstruct++-mode (&optional arg)
8414 "Toggle `orgstruct-mode', the enhanced version of it.
8415 In addition to setting orgstruct-mode, this also exports all
8416 indentation and autofilling variables from org-mode into the
8417 buffer. It will also recognize item context in multiline items."
8418 (interactive "P")
8419 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8420 (if (< arg 1)
8421 (progn (orgstruct-mode -1)
8422 (mapc (lambda(v)
8423 (org-set-local (car v)
8424 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8425 org-fb-vars))
8426 (orgstruct-mode 1)
8427 (setq org-fb-vars nil)
8428 (let (var val)
8429 (mapc
8430 (lambda (x)
8431 (when (string-match
8432 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8433 (symbol-name (car x)))
8434 (setq var (car x) val (nth 1 x))
8435 (push (list var `(quote ,(eval var))) org-fb-vars)
8436 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8437 org-local-vars)
8438 (org-set-local 'orgstruct-is-++ t))))
8440 (defvar orgstruct-is-++ nil
8441 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8442 (make-variable-buffer-local 'orgstruct-is-++)
8444 ;;;###autoload
8445 (defun turn-on-orgstruct++ ()
8446 "Unconditionally turn on `orgstruct++-mode'."
8447 (orgstruct++-mode 1))
8449 (defun orgstruct-error ()
8450 "Error when there is no default binding for a structure key."
8451 (interactive)
8452 (error "This key has no function outside structure elements"))
8454 (defun orgstruct-setup ()
8455 "Setup orgstruct keymaps."
8456 (let ((nfunc 0)
8457 (bindings
8458 (list
8459 '([(meta up)] org-metaup)
8460 '([(meta down)] org-metadown)
8461 '([(meta left)] org-metaleft)
8462 '([(meta right)] org-metaright)
8463 '([(meta shift up)] org-shiftmetaup)
8464 '([(meta shift down)] org-shiftmetadown)
8465 '([(meta shift left)] org-shiftmetaleft)
8466 '([(meta shift right)] org-shiftmetaright)
8467 '([?\e (up)] org-metaup)
8468 '([?\e (down)] org-metadown)
8469 '([?\e (left)] org-metaleft)
8470 '([?\e (right)] org-metaright)
8471 '([?\e (shift up)] org-shiftmetaup)
8472 '([?\e (shift down)] org-shiftmetadown)
8473 '([?\e (shift left)] org-shiftmetaleft)
8474 '([?\e (shift right)] org-shiftmetaright)
8475 '([(shift up)] org-shiftup)
8476 '([(shift down)] org-shiftdown)
8477 '([(shift left)] org-shiftleft)
8478 '([(shift right)] org-shiftright)
8479 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8480 '("\M-q" fill-paragraph)
8481 '("\C-c^" org-sort)
8482 '("\C-c-" org-cycle-list-bullet)))
8483 elt key fun cmd)
8484 (while (setq elt (pop bindings))
8485 (setq nfunc (1+ nfunc))
8486 (setq key (org-key (car elt))
8487 fun (nth 1 elt)
8488 cmd (orgstruct-make-binding fun nfunc key))
8489 (org-defkey orgstruct-mode-map key cmd))
8491 ;; Special treatment needed for TAB and RET
8492 (org-defkey orgstruct-mode-map [(tab)]
8493 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8494 (org-defkey orgstruct-mode-map "\C-i"
8495 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8497 (org-defkey orgstruct-mode-map "\M-\C-m"
8498 (orgstruct-make-binding 'org-insert-heading 105
8499 "\M-\C-m" [(meta return)]))
8500 (org-defkey orgstruct-mode-map [(meta return)]
8501 (orgstruct-make-binding 'org-insert-heading 106
8502 [(meta return)] "\M-\C-m"))
8504 (org-defkey orgstruct-mode-map [(shift meta return)]
8505 (orgstruct-make-binding 'org-insert-todo-heading 107
8506 [(meta return)] "\M-\C-m"))
8508 (org-defkey orgstruct-mode-map "\e\C-m"
8509 (orgstruct-make-binding 'org-insert-heading 108
8510 "\e\C-m" [?\e (return)]))
8511 (org-defkey orgstruct-mode-map [?\e (return)]
8512 (orgstruct-make-binding 'org-insert-heading 109
8513 [?\e (return)] "\e\C-m"))
8514 (org-defkey orgstruct-mode-map [?\e (shift return)]
8515 (orgstruct-make-binding 'org-insert-todo-heading 110
8516 [?\e (return)] "\e\C-m"))
8518 (unless org-local-vars
8519 (setq org-local-vars (org-get-local-variables)))
8523 (defun orgstruct-make-binding (fun n &rest keys)
8524 "Create a function for binding in the structure minor mode.
8525 FUN is the command to call inside a table. N is used to create a unique
8526 command name. KEYS are keys that should be checked in for a command
8527 to execute outside of tables."
8528 (eval
8529 (list 'defun
8530 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8531 '(arg)
8532 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8533 "Outside of structure, run the binding of `"
8534 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8535 "'.")
8536 '(interactive "p")
8537 (list 'if
8538 `(org-context-p 'headline 'item
8539 (and orgstruct-is-++
8540 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8541 'item-body))
8542 (list 'org-run-like-in-org-mode (list 'quote fun))
8543 (list 'let '(orgstruct-mode)
8544 (list 'call-interactively
8545 (append '(or)
8546 (mapcar (lambda (k)
8547 (list 'key-binding k))
8548 keys)
8549 '('orgstruct-error))))))))
8551 (defun org-context-p (&rest contexts)
8552 "Check if local context is any of CONTEXTS.
8553 Possible values in the list of contexts are `table', `headline', and `item'."
8554 (let ((pos (point)))
8555 (goto-char (point-at-bol))
8556 (prog1 (or (and (memq 'table contexts)
8557 (looking-at "[ \t]*|"))
8558 (and (memq 'headline contexts)
8559 (looking-at org-outline-regexp))
8560 (and (memq 'item contexts)
8561 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8562 (and (memq 'item-body contexts)
8563 (org-in-item-p)))
8564 (goto-char pos))))
8566 (defun org-get-local-variables ()
8567 "Return a list of all local variables in an org-mode buffer."
8568 (let (varlist)
8569 (with-current-buffer (get-buffer-create "*Org tmp*")
8570 (erase-buffer)
8571 (org-mode)
8572 (setq varlist (buffer-local-variables)))
8573 (kill-buffer "*Org tmp*")
8574 (delq nil
8575 (mapcar
8576 (lambda (x)
8577 (setq x
8578 (if (symbolp x)
8579 (list x)
8580 (list (car x) (list 'quote (cdr x)))))
8581 (if (string-match
8582 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8583 (symbol-name (car x)))
8584 x nil))
8585 varlist))))
8587 (defun org-clone-local-variables (from-buffer &optional regexp)
8588 "Clone local variables from FROM-BUFFER.
8589 Optional argument REGEXP selects variables to clone."
8590 (mapc
8591 (lambda (pair)
8592 (and (symbolp (car pair))
8593 (or (null regexp)
8594 (string-match regexp (symbol-name (car pair))))
8595 (set (make-local-variable (car pair))
8596 (cdr pair))))
8597 (buffer-local-variables from-buffer)))
8599 ;;;###autoload
8600 (defun org-run-like-in-org-mode (cmd)
8601 "Run a command, pretending that the current buffer is in Org-mode.
8602 This will temporarily bind local variables that are typically bound in
8603 Org-mode to the values they have in Org-mode, and then interactively
8604 call CMD."
8605 (org-load-modules-maybe)
8606 (unless org-local-vars
8607 (setq org-local-vars (org-get-local-variables)))
8608 (eval (list 'let org-local-vars
8609 (list 'call-interactively (list 'quote cmd)))))
8611 ;;;; Archiving
8613 (defun org-get-category (&optional pos force-refresh)
8614 "Get the category applying to position POS."
8615 (save-match-data
8616 (if force-refresh (org-refresh-category-properties))
8617 (let ((pos (or pos (point))))
8618 (or (get-text-property pos 'org-category)
8619 (progn (org-refresh-category-properties)
8620 (get-text-property pos 'org-category))))))
8622 (defun org-refresh-category-properties ()
8623 "Refresh category text properties in the buffer."
8624 (let ((inhibit-read-only t)
8625 (def-cat (cond
8626 ((null org-category)
8627 (if buffer-file-name
8628 (file-name-sans-extension
8629 (file-name-nondirectory buffer-file-name))
8630 "???"))
8631 ((symbolp org-category) (symbol-name org-category))
8632 (t org-category)))
8633 beg end cat pos optionp)
8634 (org-unmodified
8635 (save-excursion
8636 (save-restriction
8637 (widen)
8638 (goto-char (point-min))
8639 (put-text-property (point) (point-max) 'org-category def-cat)
8640 (while (re-search-forward
8641 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8642 (setq pos (match-end 0)
8643 optionp (equal (char-after (match-beginning 0)) ?#)
8644 cat (org-trim (match-string 2)))
8645 (if optionp
8646 (setq beg (point-at-bol) end (point-max))
8647 (org-back-to-heading t)
8648 (setq beg (point) end (org-end-of-subtree t t)))
8649 (put-text-property beg end 'org-category cat)
8650 (put-text-property beg end 'org-category-position beg)
8651 (goto-char pos)))))))
8654 ;;;; Link Stuff
8656 ;;; Link abbreviations
8658 (defun org-link-expand-abbrev (link)
8659 "Apply replacements as defined in `org-link-abbrev-alist'."
8660 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8661 (let* ((key (match-string 1 link))
8662 (as (or (assoc key org-link-abbrev-alist-local)
8663 (assoc key org-link-abbrev-alist)))
8664 (tag (and (match-end 2) (match-string 3 link)))
8665 rpl)
8666 (if (not as)
8667 link
8668 (setq rpl (cdr as))
8669 (cond
8670 ((symbolp rpl) (funcall rpl tag))
8671 ((string-match "%(\\([^)]+\\))" rpl)
8672 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8673 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8674 ((string-match "%h" rpl)
8675 (replace-match (url-hexify-string (or tag "")) t t rpl))
8676 (t (concat rpl tag)))))
8677 link))
8679 ;;; Storing and inserting links
8681 (defvar org-insert-link-history nil
8682 "Minibuffer history for links inserted with `org-insert-link'.")
8684 (defvar org-stored-links nil
8685 "Contains the links stored with `org-store-link'.")
8687 (defvar org-store-link-plist nil
8688 "Plist with info about the most recently link created with `org-store-link'.")
8690 (defvar org-link-protocols nil
8691 "Link protocols added to Org-mode using `org-add-link-type'.")
8693 (defvar org-store-link-functions nil
8694 "List of functions that are called to create and store a link.
8695 Each function will be called in turn until one returns a non-nil
8696 value. Each function should check if it is responsible for creating
8697 this link (for example by looking at the major mode).
8698 If not, it must exit and return nil.
8699 If yes, it should return a non-nil value after a calling
8700 `org-store-link-props' with a list of properties and values.
8701 Special properties are:
8703 :type The link prefix, like \"http\". This must be given.
8704 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8705 This is obligatory as well.
8706 :description Optional default description for the second pair
8707 of brackets in an Org-mode link. The user can still change
8708 this when inserting this link into an Org-mode buffer.
8710 In addition to these, any additional properties can be specified
8711 and then used in remember templates.")
8713 (defun org-add-link-type (type &optional follow export)
8714 "Add TYPE to the list of `org-link-types'.
8715 Re-compute all regular expressions depending on `org-link-types'
8717 FOLLOW and EXPORT are two functions.
8719 FOLLOW should take the link path as the single argument and do whatever
8720 is necessary to follow the link, for example find a file or display
8721 a mail message.
8723 EXPORT should format the link path for export to one of the export formats.
8724 It should be a function accepting three arguments:
8726 path the path of the link, the text after the prefix (like \"http:\")
8727 desc the description of the link, if any, or a description added by
8728 org-export-normalize-links if there is none
8729 format the export format, a symbol like `html' or `latex' or `ascii'..
8731 The function may use the FORMAT information to return different values
8732 depending on the format. The return value will be put literally into
8733 the exported file. If the return value is nil, this means Org should
8734 do what it normally does with links which do not have EXPORT defined.
8736 Org-mode has a built-in default for exporting links. If you are happy with
8737 this default, there is no need to define an export function for the link
8738 type. For a simple example of an export function, see `org-bbdb.el'."
8739 (add-to-list 'org-link-types type t)
8740 (org-make-link-regexps)
8741 (if (assoc type org-link-protocols)
8742 (setcdr (assoc type org-link-protocols) (list follow export))
8743 (push (list type follow export) org-link-protocols)))
8745 (defvar org-agenda-buffer-name)
8747 ;;;###autoload
8748 (defun org-store-link (arg)
8749 "\\<org-mode-map>Store an org-link to the current location.
8750 This link is added to `org-stored-links' and can later be inserted
8751 into an org-buffer with \\[org-insert-link].
8753 For some link types, a prefix arg is interpreted:
8754 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8755 For file links, arg negates `org-context-in-file-links'."
8756 (interactive "P")
8757 (org-load-modules-maybe)
8758 (setq org-store-link-plist nil) ; reset
8759 (org-with-limited-levels
8760 (let (link cpltxt desc description search txt custom-id agenda-link)
8761 (cond
8763 ((run-hook-with-args-until-success 'org-store-link-functions)
8764 (setq link (plist-get org-store-link-plist :link)
8765 desc (or (plist-get org-store-link-plist :description) link)))
8767 ((org-src-edit-buffer-p)
8768 (let (label gc)
8769 (while (or (not label)
8770 (save-excursion
8771 (save-restriction
8772 (widen)
8773 (goto-char (point-min))
8774 (re-search-forward
8775 (regexp-quote (format org-coderef-label-format label))
8776 nil t))))
8777 (when label (message "Label exists already") (sit-for 2))
8778 (setq label (read-string "Code line label: " label)))
8779 (end-of-line 1)
8780 (setq link (format org-coderef-label-format label))
8781 (setq gc (- 79 (length link)))
8782 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8783 (insert link)
8784 (setq link (concat "(" label ")") desc nil)))
8786 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8787 ;; We are in the agenda, link to referenced location
8788 (let ((m (or (get-text-property (point) 'org-hd-marker)
8789 (get-text-property (point) 'org-marker))))
8790 (when m
8791 (org-with-point-at m
8792 (setq agenda-link
8793 (if (org-called-interactively-p 'any)
8794 (call-interactively 'org-store-link)
8795 (org-store-link nil)))))))
8797 ((eq major-mode 'calendar-mode)
8798 (let ((cd (calendar-cursor-to-date)))
8799 (setq link
8800 (format-time-string
8801 (car org-time-stamp-formats)
8802 (apply 'encode-time
8803 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8804 nil nil nil))))
8805 (org-store-link-props :type "calendar" :date cd)))
8807 ((eq major-mode 'w3-mode)
8808 (setq cpltxt (if (and (buffer-name)
8809 (not (string-match "Untitled" (buffer-name))))
8810 (buffer-name)
8811 (url-view-url t))
8812 link (org-make-link (url-view-url t)))
8813 (org-store-link-props :type "w3" :url (url-view-url t)))
8815 ((eq major-mode 'w3m-mode)
8816 (setq cpltxt (or w3m-current-title w3m-current-url)
8817 link (org-make-link w3m-current-url))
8818 (org-store-link-props :type "w3m" :url (url-view-url t)))
8820 ((setq search (run-hook-with-args-until-success
8821 'org-create-file-search-functions))
8822 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8823 "::" search))
8824 (setq cpltxt (or description link)))
8826 ((eq major-mode 'image-mode)
8827 (setq cpltxt (concat "file:"
8828 (abbreviate-file-name buffer-file-name))
8829 link (org-make-link cpltxt))
8830 (org-store-link-props :type "image" :file buffer-file-name))
8832 ((eq major-mode 'dired-mode)
8833 ;; link to the file in the current line
8834 (let ((file (dired-get-filename nil t)))
8835 (setq file (if file
8836 (abbreviate-file-name
8837 (expand-file-name (dired-get-filename nil t)))
8838 ;; otherwise, no file so use current directory.
8839 default-directory))
8840 (setq cpltxt (concat "file:" file)
8841 link (org-make-link cpltxt))))
8843 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8844 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8845 (cond
8846 ((org-in-regexp "<<\\(.*?\\)>>")
8847 (setq cpltxt
8848 (concat "file:"
8849 (abbreviate-file-name
8850 (buffer-file-name (buffer-base-buffer)))
8851 "::" (match-string 1))
8852 link (org-make-link cpltxt)))
8853 ((and (featurep 'org-id)
8854 (or (eq org-link-to-org-use-id t)
8855 (and (eq org-link-to-org-use-id 'create-if-interactive)
8856 (org-called-interactively-p 'any))
8857 (and (eq org-link-to-org-use-id
8858 'create-if-interactive-and-no-custom-id)
8859 (org-called-interactively-p 'any)
8860 (not custom-id))
8861 (and org-link-to-org-use-id
8862 (org-entry-get nil "ID"))))
8863 ;; We can make a link using the ID.
8864 (setq link (condition-case nil
8865 (prog1 (org-id-store-link)
8866 (setq desc (plist-get org-store-link-plist
8867 :description)))
8868 (error
8869 ;; probably before first headline, link to file only
8870 (concat "file:"
8871 (abbreviate-file-name
8872 (buffer-file-name (buffer-base-buffer))))))))
8874 ;; Just link to current headline
8875 (setq cpltxt (concat "file:"
8876 (abbreviate-file-name
8877 (buffer-file-name (buffer-base-buffer)))))
8878 ;; Add a context search string
8879 (when (org-xor org-context-in-file-links arg)
8880 (setq txt (cond
8881 ((org-at-heading-p) nil)
8882 ((org-region-active-p)
8883 (buffer-substring (region-beginning) (region-end)))
8884 (t nil)))
8885 (when (or (null txt) (string-match "\\S-" txt))
8886 (setq cpltxt
8887 (concat cpltxt "::"
8888 (condition-case nil
8889 (org-make-org-heading-search-string txt)
8890 (error "")))
8891 desc (or (nth 4 (ignore-errors
8892 (org-heading-components))) "NONE"))))
8893 (if (string-match "::\\'" cpltxt)
8894 (setq cpltxt (substring cpltxt 0 -2)))
8895 (setq link (org-make-link cpltxt)))))
8897 ((buffer-file-name (buffer-base-buffer))
8898 ;; Just link to this file here.
8899 (setq cpltxt (concat "file:"
8900 (abbreviate-file-name
8901 (buffer-file-name (buffer-base-buffer)))))
8902 ;; Add a context string
8903 (when (org-xor org-context-in-file-links arg)
8904 (setq txt (if (org-region-active-p)
8905 (buffer-substring (region-beginning) (region-end))
8906 (buffer-substring (point-at-bol) (point-at-eol))))
8907 ;; Only use search option if there is some text.
8908 (when (string-match "\\S-" txt)
8909 (setq cpltxt
8910 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8911 desc "NONE")))
8912 (setq link (org-make-link cpltxt)))
8914 ((org-called-interactively-p 'interactive)
8915 (error "Cannot link to a buffer which is not visiting a file"))
8917 (t (setq link nil)))
8919 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8920 (setq link (or link cpltxt)
8921 desc (or desc cpltxt))
8922 (if (equal desc "NONE") (setq desc nil))
8924 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8925 (progn
8926 (setq org-stored-links
8927 (cons (list link desc) org-stored-links))
8928 (message "Stored: %s" (or desc link))
8929 (when custom-id
8930 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8931 "::#" custom-id))
8932 (setq org-stored-links
8933 (cons (list link desc) org-stored-links))))
8934 (or agenda-link (and link (org-make-link-string link desc)))))))
8936 (defun org-store-link-props (&rest plist)
8937 "Store link properties, extract names and addresses."
8938 (let (x adr)
8939 (when (setq x (plist-get plist :from))
8940 (setq adr (mail-extract-address-components x))
8941 (setq plist (plist-put plist :fromname (car adr)))
8942 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8943 (when (setq x (plist-get plist :to))
8944 (setq adr (mail-extract-address-components x))
8945 (setq plist (plist-put plist :toname (car adr)))
8946 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8947 (let ((from (plist-get plist :from))
8948 (to (plist-get plist :to)))
8949 (when (and from to org-from-is-user-regexp)
8950 (setq plist
8951 (plist-put plist :fromto
8952 (if (string-match org-from-is-user-regexp from)
8953 (concat "to %t")
8954 (concat "from %f"))))))
8955 (setq org-store-link-plist plist))
8957 (defun org-add-link-props (&rest plist)
8958 "Add these properties to the link property list."
8959 (let (key value)
8960 (while plist
8961 (setq key (pop plist) value (pop plist))
8962 (setq org-store-link-plist
8963 (plist-put org-store-link-plist key value)))))
8965 (defun org-email-link-description (&optional fmt)
8966 "Return the description part of an email link.
8967 This takes information from `org-store-link-plist' and formats it
8968 according to FMT (default from `org-email-link-description-format')."
8969 (setq fmt (or fmt org-email-link-description-format))
8970 (let* ((p org-store-link-plist)
8971 (to (plist-get p :toaddress))
8972 (from (plist-get p :fromaddress))
8973 (table
8974 (list
8975 (cons "%c" (plist-get p :fromto))
8976 (cons "%F" (plist-get p :from))
8977 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8978 (cons "%T" (plist-get p :to))
8979 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8980 (cons "%s" (plist-get p :subject))
8981 (cons "%d" (plist-get p :date))
8982 (cons "%m" (plist-get p :message-id)))))
8983 (when (string-match "%c" fmt)
8984 ;; Check if the user wrote this message
8985 (if (and org-from-is-user-regexp from to
8986 (save-match-data (string-match org-from-is-user-regexp from)))
8987 (setq fmt (replace-match "to %t" t t fmt))
8988 (setq fmt (replace-match "from %f" t t fmt))))
8989 (org-replace-escapes fmt table)))
8991 (defun org-make-org-heading-search-string (&optional string heading)
8992 "Make search string for STRING or current headline."
8993 (interactive)
8994 (let ((s (or string (org-get-heading)))
8995 (lines org-context-in-file-links))
8996 (unless (and string (not heading))
8997 ;; We are using a headline, clean up garbage in there.
8998 (if (string-match org-todo-regexp s)
8999 (setq s (replace-match "" t t s)))
9000 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9001 (setq s (replace-match "" t t s)))
9002 (setq s (org-trim s))
9003 (if (string-match (concat "^\\(" org-quote-string "\\|"
9004 org-comment-string "\\)") s)
9005 (setq s (replace-match "" t t s)))
9006 (while (string-match org-ts-regexp s)
9007 (setq s (replace-match "" t t s))))
9008 (or string (setq s (concat "*" s))) ; Add * for headlines
9009 (when (and string (integerp lines) (> lines 0))
9010 (let ((slines (org-split-string s "\n")))
9011 (when (< lines (length slines))
9012 (setq s (mapconcat
9013 'identity
9014 (reverse (nthcdr (- (length slines) lines)
9015 (reverse slines))) "\n")))))
9016 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9018 (defun org-make-link (&rest strings)
9019 "Concatenate STRINGS."
9020 (apply 'concat strings))
9022 (defun org-make-link-string (link &optional description)
9023 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9024 (unless (string-match "\\S-" link)
9025 (error "Empty link"))
9026 (when (and description
9027 (stringp description)
9028 (not (string-match "\\S-" description)))
9029 (setq description nil))
9030 (when (stringp description)
9031 ;; Remove brackets from the description, they are fatal.
9032 (while (string-match "\\[" description)
9033 (setq description (replace-match "{" t t description)))
9034 (while (string-match "\\]" description)
9035 (setq description (replace-match "}" t t description))))
9036 (when (equal link description)
9037 ;; No description needed, it is identical
9038 (setq description nil))
9039 (when (and (not description)
9040 (not (string-match (org-image-file-name-regexp) link))
9041 (not (equal link (org-link-escape link))))
9042 (setq description (org-extract-attributes link)))
9043 (setq link
9044 (cond ((string-match (org-image-file-name-regexp) link) link)
9045 ((string-match org-link-types-re link)
9046 (concat (match-string 1 link)
9047 (org-link-escape (substring link (match-end 1)))))
9048 (t (org-link-escape link))))
9049 (concat "[[" link "]"
9050 (if description (concat "[" description "]") "")
9051 "]"))
9053 (defconst org-link-escape-chars
9054 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9055 "List of characters that should be escaped in link.
9056 This is the list that is used for internal purposes.")
9058 (defvar org-url-encoding-use-url-hexify nil)
9060 (defconst org-link-escape-chars-browser
9061 '(?\ )
9062 "List of escapes for characters that are problematic in links.
9063 This is the list that is used before handing over to the browser.")
9065 (defun org-link-escape (text &optional table merge)
9066 "Return percent escaped representation of TEXT.
9067 TEXT is a string with the text to escape.
9068 Optional argument TABLE is a list with characters that should be
9069 escaped. When nil, `org-link-escape-chars' is used.
9070 If optional argument MERGE is set, merge TABLE into
9071 `org-link-escape-chars'."
9072 (if (and org-url-encoding-use-url-hexify (not table))
9073 (url-hexify-string text)
9074 (cond
9075 ((and table merge)
9076 (mapc (lambda (defchr)
9077 (unless (member defchr table)
9078 (setq table (cons defchr table)))) org-link-escape-chars))
9079 ((null table)
9080 (setq table org-link-escape-chars)))
9081 (mapconcat
9082 (lambda (char)
9083 (if (or (member char table)
9084 (< char 32) (= char 37) (> char 126))
9085 (mapconcat (lambda (sequence-element)
9086 (format "%%%.2X" sequence-element))
9087 (or (encode-coding-char char 'utf-8)
9088 (error "Unable to percent escape character: %s"
9089 (char-to-string char))) "")
9090 (char-to-string char))) text "")))
9092 (defun org-link-unescape (str)
9093 "Unhex hexified Unicode strings as returned from the JavaScript function
9094 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9095 (unless (and (null str) (string= "" str))
9096 (let ((pos 0) (case-fold-search t) unhexed)
9097 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9098 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9099 (setq str (replace-match unhexed t t str))
9100 (setq pos (+ pos (length unhexed))))))
9101 str)
9103 (defun org-link-unescape-compound (hex)
9104 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9105 Note: this function also decodes single byte encodings like
9106 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9107 (save-match-data
9108 (let* ((bytes (cdr (split-string hex "%")))
9109 (ret "")
9110 (eat 0)
9111 (sum 0))
9112 (while bytes
9113 (let* ((val (string-to-number (pop bytes) 16))
9114 (shift-xor
9115 (if (= 0 eat)
9116 (cond
9117 ((>= val 252) (cons 6 252))
9118 ((>= val 248) (cons 5 248))
9119 ((>= val 240) (cons 4 240))
9120 ((>= val 224) (cons 3 224))
9121 ((>= val 192) (cons 2 192))
9122 (t (cons 0 0)))
9123 (cons 6 128))))
9124 (if (>= val 192) (setq eat (car shift-xor)))
9125 (setq val (logxor val (cdr shift-xor)))
9126 (setq sum (+ (lsh sum (car shift-xor)) val))
9127 (if (> eat 0) (setq eat (- eat 1)))
9128 (cond
9129 ((= 0 eat) ;multi byte
9130 (setq ret (concat ret (org-char-to-string sum)))
9131 (setq sum 0))
9132 ((not bytes) ; single byte(s)
9133 (setq ret (org-link-unescape-single-byte-sequence hex))))
9134 )) ;; end (while bytes
9135 ret )))
9137 (defun org-link-unescape-single-byte-sequence (hex)
9138 "Unhexify hex-encoded single byte character sequences."
9139 (mapconcat (lambda (byte)
9140 (char-to-string (string-to-number byte 16)))
9141 (cdr (split-string hex "%")) ""))
9143 (defun org-xor (a b)
9144 "Exclusive or."
9145 (if a (not b) b))
9147 (defun org-fixup-message-id-for-http (s)
9148 "Replace special characters in a message id, so it can be used in an http query."
9149 (when (string-match "%" s)
9150 (setq s (mapconcat (lambda (c)
9151 (if (eq c ?%)
9152 "%25"
9153 (char-to-string c)))
9154 s "")))
9155 (while (string-match "<" s)
9156 (setq s (replace-match "%3C" t t s)))
9157 (while (string-match ">" s)
9158 (setq s (replace-match "%3E" t t s)))
9159 (while (string-match "@" s)
9160 (setq s (replace-match "%40" t t s)))
9163 (defun org-link-prettify (link)
9164 "Return a human-readable representation of LINK.
9165 The car of LINK must be a raw link the cdr of LINK must be either
9166 a link description or nil."
9167 (let ((desc (or (cadr link) "<no description>")))
9168 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9169 "[[" (car link) "]]")))
9171 ;;;###autoload
9172 (defun org-insert-link-global ()
9173 "Insert a link like Org-mode does.
9174 This command can be called in any mode to insert a link in Org-mode syntax."
9175 (interactive)
9176 (org-load-modules-maybe)
9177 (org-run-like-in-org-mode 'org-insert-link))
9179 (defun org-insert-link (&optional complete-file link-location default-description)
9180 "Insert a link. At the prompt, enter the link.
9182 Completion can be used to insert any of the link protocol prefixes like
9183 http or ftp in use.
9185 The history can be used to select a link previously stored with
9186 `org-store-link'. When the empty string is entered (i.e. if you just
9187 press RET at the prompt), the link defaults to the most recently
9188 stored link. As SPC triggers completion in the minibuffer, you need to
9189 use M-SPC or C-q SPC to force the insertion of a space character.
9191 You will also be prompted for a description, and if one is given, it will
9192 be displayed in the buffer instead of the link.
9194 If there is already a link at point, this command will allow you to edit link
9195 and description parts.
9197 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9198 be selected using completion. The path to the file will be relative to the
9199 current directory if the file is in the current directory or a subdirectory.
9200 Otherwise, the link will be the absolute path as completed in the minibuffer
9201 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9202 option `org-link-file-path-type'.
9204 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9205 the current directory or below.
9207 With three \\[universal-argument] prefixes, negate the meaning of
9208 `org-keep-stored-link-after-insertion'.
9210 If `org-make-link-description-function' is non-nil, this function will be
9211 called with the link target, and the result will be the default
9212 link description.
9214 If the LINK-LOCATION parameter is non-nil, this value will be
9215 used as the link location instead of reading one interactively.
9217 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9218 be used as the default description."
9219 (interactive "P")
9220 (let* ((wcf (current-window-configuration))
9221 (region (if (org-region-active-p)
9222 (buffer-substring (region-beginning) (region-end))))
9223 (remove (and region (list (region-beginning) (region-end))))
9224 (desc region)
9225 tmphist ; byte-compile incorrectly complains about this
9226 (link link-location)
9227 entry file all-prefixes)
9228 (cond
9229 (link-location) ; specified by arg, just use it.
9230 ((org-in-regexp org-bracket-link-regexp 1)
9231 ;; We do have a link at point, and we are going to edit it.
9232 (setq remove (list (match-beginning 0) (match-end 0)))
9233 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9234 (setq link (read-string "Link: "
9235 (org-link-unescape
9236 (org-match-string-no-properties 1)))))
9237 ((or (org-in-regexp org-angle-link-re)
9238 (org-in-regexp org-plain-link-re))
9239 ;; Convert to bracket link
9240 (setq remove (list (match-beginning 0) (match-end 0))
9241 link (read-string "Link: "
9242 (org-remove-angle-brackets (match-string 0)))))
9243 ((member complete-file '((4) (16)))
9244 ;; Completing read for file names.
9245 (setq link (org-file-complete-link complete-file)))
9247 ;; Read link, with completion for stored links.
9248 (with-output-to-temp-buffer "*Org Links*"
9249 (princ "Insert a link.
9250 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9251 (when org-stored-links
9252 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9253 (princ (mapconcat 'org-link-prettify
9254 (reverse org-stored-links) "\n"))))
9255 (let ((cw (selected-window)))
9256 (select-window (get-buffer-window "*Org Links*" 'visible))
9257 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9258 (unless (pos-visible-in-window-p (point-max))
9259 (org-fit-window-to-buffer))
9260 (and (window-live-p cw) (select-window cw)))
9261 ;; Fake a link history, containing the stored links.
9262 (setq tmphist (append (mapcar 'car org-stored-links)
9263 org-insert-link-history))
9264 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9265 (mapcar 'car org-link-abbrev-alist)
9266 org-link-types))
9267 (unwind-protect
9268 (progn
9269 (setq link
9270 (let ((org-completion-use-ido nil)
9271 (org-completion-use-iswitchb nil))
9272 (org-completing-read
9273 "Link: "
9274 (append
9275 (mapcar (lambda (x) (list (concat x ":")))
9276 all-prefixes)
9277 (mapcar 'car org-stored-links))
9278 nil nil nil
9279 'tmphist
9280 (car (car org-stored-links)))))
9281 (if (not (string-match "\\S-" link))
9282 (error "No link selected"))
9283 (if (or (member link all-prefixes)
9284 (and (equal ":" (substring link -1))
9285 (member (substring link 0 -1) all-prefixes)
9286 (setq link (substring link 0 -1))))
9287 (setq link (org-link-try-special-completion link))))
9288 (set-window-configuration wcf)
9289 (kill-buffer "*Org Links*"))
9290 (setq entry (assoc link org-stored-links))
9291 (or entry (push link org-insert-link-history))
9292 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9293 (not org-keep-stored-link-after-insertion))
9294 (setq org-stored-links (delq (assoc link org-stored-links)
9295 org-stored-links)))
9296 (setq desc (or desc (nth 1 entry)))))
9298 (if (string-match org-plain-link-re link)
9299 ;; URL-like link, normalize the use of angular brackets.
9300 (setq link (org-make-link (org-remove-angle-brackets link))))
9302 ;; Check if we are linking to the current file with a search option
9303 ;; If yes, simplify the link by using only the search option.
9304 (when (and buffer-file-name
9305 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9306 (let* ((path (match-string 1 link))
9307 (case-fold-search nil)
9308 (search (match-string 2 link)))
9309 (save-match-data
9310 (if (equal (file-truename buffer-file-name) (file-truename path))
9311 ;; We are linking to this same file, with a search option
9312 (setq link search)))))
9314 ;; Check if we can/should use a relative path. If yes, simplify the link
9315 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9316 (let* ((type (match-string 1 link))
9317 (path (match-string 2 link))
9318 (origpath path)
9319 (case-fold-search nil))
9320 (cond
9321 ((or (eq org-link-file-path-type 'absolute)
9322 (equal complete-file '(16)))
9323 (setq path (abbreviate-file-name (expand-file-name path))))
9324 ((eq org-link-file-path-type 'noabbrev)
9325 (setq path (expand-file-name path)))
9326 ((eq org-link-file-path-type 'relative)
9327 (setq path (file-relative-name path)))
9329 (save-match-data
9330 (if (string-match (concat "^" (regexp-quote
9331 (expand-file-name
9332 (file-name-as-directory
9333 default-directory))))
9334 (expand-file-name path))
9335 ;; We are linking a file with relative path name.
9336 (setq path (substring (expand-file-name path)
9337 (match-end 0)))
9338 (setq path (abbreviate-file-name (expand-file-name path)))))))
9339 (setq link (concat type path))
9340 (if (equal desc origpath)
9341 (setq desc path))))
9343 (if org-make-link-description-function
9344 (setq desc (funcall org-make-link-description-function link desc))
9345 (if default-description (setq desc default-description)))
9347 (setq desc (read-string "Description: " desc))
9348 (unless (string-match "\\S-" desc) (setq desc nil))
9349 (if remove (apply 'delete-region remove))
9350 (insert (org-make-link-string link desc))))
9352 (defun org-link-try-special-completion (type)
9353 "If there is completion support for link type TYPE, offer it."
9354 (let ((fun (intern (concat "org-" type "-complete-link"))))
9355 (if (functionp fun)
9356 (funcall fun)
9357 (read-string "Link (no completion support): " (concat type ":")))))
9359 (defun org-file-complete-link (&optional arg)
9360 "Create a file link using completion."
9361 (let (file link)
9362 (setq file (read-file-name "File: "))
9363 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9364 (pwd1 (file-name-as-directory (abbreviate-file-name
9365 (expand-file-name ".")))))
9366 (cond
9367 ((equal arg '(16))
9368 (setq link (org-make-link
9369 "file:"
9370 (abbreviate-file-name (expand-file-name file)))))
9371 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9372 (setq link (org-make-link "file:" (match-string 1 file))))
9373 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9374 (expand-file-name file))
9375 (setq link (org-make-link
9376 "file:" (match-string 1 (expand-file-name file)))))
9377 (t (setq link (org-make-link "file:" file)))))
9378 link))
9380 (defun org-completing-read (&rest args)
9381 "Completing-read with SPACE being a normal character."
9382 (let ((enable-recursive-minibuffers t)
9383 (minibuffer-local-completion-map
9384 (copy-keymap minibuffer-local-completion-map)))
9385 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9386 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9387 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9388 (apply 'org-icompleting-read args)))
9390 (defun org-completing-read-no-i (&rest args)
9391 (let (org-completion-use-ido org-completion-use-iswitchb)
9392 (apply 'org-completing-read args)))
9394 (defun org-iswitchb-completing-read (prompt choices &rest args)
9395 "Use iswitch as a completing-read replacement to choose from choices.
9396 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9397 from."
9398 (let* ((iswitchb-use-virtual-buffers nil)
9399 (iswitchb-make-buflist-hook
9400 (lambda ()
9401 (setq iswitchb-temp-buflist choices))))
9402 (iswitchb-read-buffer prompt)))
9404 (defun org-icompleting-read (&rest args)
9405 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9406 (org-without-partial-completion
9407 (if (and org-completion-use-ido
9408 (fboundp 'ido-completing-read)
9409 (boundp 'ido-mode) ido-mode
9410 (listp (second args)))
9411 (let ((ido-enter-matching-directory nil))
9412 (apply 'ido-completing-read (concat (car args))
9413 (if (consp (car (nth 1 args)))
9414 (mapcar 'car (nth 1 args))
9415 (nth 1 args))
9416 (cddr args)))
9417 (if (and org-completion-use-iswitchb
9418 (boundp 'iswitchb-mode) iswitchb-mode
9419 (listp (second args)))
9420 (apply 'org-iswitchb-completing-read (concat (car args))
9421 (if (consp (car (nth 1 args)))
9422 (mapcar 'car (nth 1 args))
9423 (nth 1 args))
9424 (cddr args))
9425 (apply 'completing-read args)))))
9427 (defun org-extract-attributes (s)
9428 "Extract the attributes cookie from a string and set as text property."
9429 (let (a attr (start 0) key value)
9430 (save-match-data
9431 (when (string-match "{{\\([^}]+\\)}}$" s)
9432 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9433 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9434 (setq key (match-string 1 a) value (match-string 2 a)
9435 start (match-end 0)
9436 attr (plist-put attr (intern key) value))))
9437 (org-add-props s nil 'org-attr attr))
9440 (defun org-extract-attributes-from-string (tag)
9441 (let (key value attr)
9442 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9443 (setq key (match-string 1 tag) value (match-string 2 tag)
9444 tag (replace-match "" t t tag)
9445 attr (plist-put attr (intern key) value)))
9446 (cons tag attr)))
9448 (defun org-attributes-to-string (plist)
9449 "Format a property list into an HTML attribute list."
9450 (let ((s "") key value)
9451 (while plist
9452 (setq key (pop plist) value (pop plist))
9453 (and value
9454 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9457 ;;; Opening/following a link
9459 (defvar org-link-search-failed nil)
9461 (defvar org-open-link-functions nil
9462 "Hook for functions finding a plain text link.
9463 These functions must take a single argument, the link content.
9464 They will be called for links that look like [[link text][description]]
9465 when LINK TEXT does not have a protocol like \"http:\" and does not look
9466 like a filename (e.g. \"./blue.png\").
9468 These functions will be called *before* Org attempts to resolve the
9469 link by doing text searches in the current buffer - so if you want a
9470 link \"[[target]]\" to still find \"<<target>>\", your function should
9471 handle this as a special case.
9473 When the function does handle the link, it must return a non-nil value.
9474 If it decides that it is not responsible for this link, it must return
9475 nil to indicate that that Org-mode can continue with other options
9476 like exact and fuzzy text search.")
9478 (defun org-next-link ()
9479 "Move forward to the next link.
9480 If the link is in hidden text, expose it."
9481 (interactive)
9482 (when (and org-link-search-failed (eq this-command last-command))
9483 (goto-char (point-min))
9484 (message "Link search wrapped back to beginning of buffer"))
9485 (setq org-link-search-failed nil)
9486 (let* ((pos (point))
9487 (ct (org-context))
9488 (a (assoc :link ct)))
9489 (if a (goto-char (nth 2 a)))
9490 (if (re-search-forward org-any-link-re nil t)
9491 (progn
9492 (goto-char (match-beginning 0))
9493 (if (outline-invisible-p) (org-show-context)))
9494 (goto-char pos)
9495 (setq org-link-search-failed t)
9496 (error "No further link found"))))
9498 (defun org-previous-link ()
9499 "Move backward to the previous link.
9500 If the link is in hidden text, expose it."
9501 (interactive)
9502 (when (and org-link-search-failed (eq this-command last-command))
9503 (goto-char (point-max))
9504 (message "Link search wrapped back to end of buffer"))
9505 (setq org-link-search-failed nil)
9506 (let* ((pos (point))
9507 (ct (org-context))
9508 (a (assoc :link ct)))
9509 (if a (goto-char (nth 1 a)))
9510 (if (re-search-backward org-any-link-re nil t)
9511 (progn
9512 (goto-char (match-beginning 0))
9513 (if (outline-invisible-p) (org-show-context)))
9514 (goto-char pos)
9515 (setq org-link-search-failed t)
9516 (error "No further link found"))))
9518 (defun org-translate-link (s)
9519 "Translate a link string if a translation function has been defined."
9520 (if (and org-link-translation-function
9521 (fboundp org-link-translation-function)
9522 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9523 (progn
9524 (setq s (funcall org-link-translation-function
9525 (match-string 1 s) (match-string 2 s)))
9526 (concat (car s) ":" (cdr s)))
9529 (defun org-translate-link-from-planner (type path)
9530 "Translate a link from Emacs Planner syntax so that Org can follow it.
9531 This is still an experimental function, your mileage may vary."
9532 (cond
9533 ((member type '("http" "https" "news" "ftp"))
9534 ;; standard Internet links are the same.
9535 nil)
9536 ((and (equal type "irc") (string-match "^//" path))
9537 ;; Planner has two / at the beginning of an irc link, we have 1.
9538 ;; We should have zero, actually....
9539 (setq path (substring path 1)))
9540 ((and (equal type "lisp") (string-match "^/" path))
9541 ;; Planner has a slash, we do not.
9542 (setq type "elisp" path (substring path 1)))
9543 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9544 ;; A typical message link. Planner has the id after the final slash,
9545 ;; we separate it with a hash mark
9546 (setq path (concat (match-string 1 path) "#"
9547 (org-remove-angle-brackets (match-string 2 path)))))
9549 (cons type path))
9551 (defun org-find-file-at-mouse (ev)
9552 "Open file link or URL at mouse."
9553 (interactive "e")
9554 (mouse-set-point ev)
9555 (org-open-at-point 'in-emacs))
9557 (defun org-open-at-mouse (ev)
9558 "Open file link or URL at mouse.
9559 See the docstring of `org-open-file' for details."
9560 (interactive "e")
9561 (mouse-set-point ev)
9562 (if (eq major-mode 'org-agenda-mode)
9563 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9564 (org-open-at-point))
9566 (defvar org-window-config-before-follow-link nil
9567 "The window configuration before following a link.
9568 This is saved in case the need arises to restore it.")
9570 (defvar org-open-link-marker (make-marker)
9571 "Marker pointing to the location where `org-open-at-point; was called.")
9573 ;;;###autoload
9574 (defun org-open-at-point-global ()
9575 "Follow a link like Org-mode does.
9576 This command can be called in any mode to follow a link that has
9577 Org-mode syntax."
9578 (interactive)
9579 (org-run-like-in-org-mode 'org-open-at-point))
9581 ;;;###autoload
9582 (defun org-open-link-from-string (s &optional arg reference-buffer)
9583 "Open a link in the string S, as if it was in Org-mode."
9584 (interactive "sLink: \nP")
9585 (let ((reference-buffer (or reference-buffer (current-buffer))))
9586 (with-temp-buffer
9587 (let ((org-inhibit-startup (not reference-buffer)))
9588 (org-mode)
9589 (insert s)
9590 (goto-char (point-min))
9591 (when reference-buffer
9592 (setq org-link-abbrev-alist-local
9593 (with-current-buffer reference-buffer
9594 org-link-abbrev-alist-local)))
9595 (org-open-at-point arg reference-buffer)))))
9597 (defvar org-open-at-point-functions nil
9598 "Hook that is run when following a link at point.
9600 Functions in this hook must return t if they identify and follow
9601 a link at point. If they don't find anything interesting at point,
9602 they must return nil.")
9604 (defun org-open-at-point (&optional arg reference-buffer)
9605 "Open link at or after point.
9606 If there is no link at point, this function will search forward up to
9607 the end of the current line.
9608 Normally, files will be opened by an appropriate application. If the
9609 optional prefix argument ARG is non-nil, Emacs will visit the file.
9610 With a double prefix argument, try to open outside of Emacs, in the
9611 application the system uses for this file type."
9612 (interactive "P")
9613 ;; if in a code block, then open the block's results
9614 (unless (call-interactively #'org-babel-open-src-block-result)
9615 (org-load-modules-maybe)
9616 (move-marker org-open-link-marker (point))
9617 (setq org-window-config-before-follow-link (current-window-configuration))
9618 (org-remove-occur-highlights nil nil t)
9619 (cond
9620 ((and (org-at-heading-p)
9621 (not (org-at-timestamp-p t))
9622 (not (org-in-regexp
9623 (concat org-plain-link-re "\\|"
9624 org-bracket-link-regexp "\\|"
9625 org-angle-link-re "\\|"
9626 "[ \t]:[^ \t\n]+:[ \t]*$")))
9627 (not (get-text-property (point) 'org-linked-text)))
9628 (or (org-offer-links-in-entry arg)
9629 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9630 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9631 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9632 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9633 (not (org-in-regexp org-bracket-link-regexp)))
9634 (org-footnote-action))
9636 (let (type path link line search (pos (point)))
9637 (catch 'match
9638 (save-excursion
9639 (skip-chars-forward "^]\n\r")
9640 (when (org-in-regexp org-bracket-link-regexp 1)
9641 (setq link (org-extract-attributes
9642 (org-link-unescape (org-match-string-no-properties 1))))
9643 (while (string-match " *\n *" link)
9644 (setq link (replace-match " " t t link)))
9645 (setq link (org-link-expand-abbrev link))
9646 (cond
9647 ((or (file-name-absolute-p link)
9648 (string-match "^\\.\\.?/" link))
9649 (setq type "file" path link))
9650 ((string-match org-link-re-with-space3 link)
9651 (setq type (match-string 1 link) path (match-string 2 link)))
9652 (t (setq type "thisfile" path link)))
9653 (throw 'match t)))
9655 (when (get-text-property (point) 'org-linked-text)
9656 (setq type "thisfile"
9657 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9658 (1+ (point)) (point))
9659 path (buffer-substring
9660 (or (previous-single-property-change pos 'org-linked-text)
9661 (point-min))
9662 (or (next-single-property-change pos 'org-linked-text)
9663 (point-max))))
9664 (throw 'match t))
9666 (save-excursion
9667 (when (or (org-in-regexp org-angle-link-re)
9668 (org-in-regexp org-plain-link-re))
9669 (setq type (match-string 1)
9670 path (org-link-unescape (match-string 2)))
9671 (throw 'match t)))
9672 (save-excursion
9673 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9674 (setq type "tags"
9675 path (match-string 1))
9676 (while (string-match ":" path)
9677 (setq path (replace-match "+" t t path)))
9678 (throw 'match t)))
9679 (when (org-in-regexp "<\\([^><\n]+\\)>")
9680 (setq type "tree-match"
9681 path (match-string 1))
9682 (throw 'match t)))
9683 (unless path
9684 (error "No link found"))
9686 ;; switch back to reference buffer
9687 ;; needed when if called in a temporary buffer through
9688 ;; org-open-link-from-string
9689 (with-current-buffer (or reference-buffer (current-buffer))
9691 ;; Remove any trailing spaces in path
9692 (if (string-match " +\\'" path)
9693 (setq path (replace-match "" t t path)))
9694 (if (and org-link-translation-function
9695 (fboundp org-link-translation-function))
9696 ;; Check if we need to translate the link
9697 (let ((tmp (funcall org-link-translation-function type path)))
9698 (setq type (car tmp) path (cdr tmp))))
9700 (cond
9702 ((assoc type org-link-protocols)
9703 (funcall (nth 1 (assoc type org-link-protocols)) path))
9705 ((equal type "mailto")
9706 (let ((cmd (car org-link-mailto-program))
9707 (args (cdr org-link-mailto-program)) args1
9708 (address path) (subject "") a)
9709 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9710 (setq address (match-string 1 path)
9711 subject (org-link-escape (match-string 2 path))))
9712 (while args
9713 (cond
9714 ((not (stringp (car args))) (push (pop args) args1))
9715 (t (setq a (pop args))
9716 (if (string-match "%a" a)
9717 (setq a (replace-match address t t a)))
9718 (if (string-match "%s" a)
9719 (setq a (replace-match subject t t a)))
9720 (push a args1))))
9721 (apply cmd (nreverse args1))))
9723 ((member type '("http" "https" "ftp" "news"))
9724 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9725 (org-link-escape
9726 path org-link-escape-chars-browser)
9727 path))))
9729 ((string= type "doi")
9730 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9731 (org-link-escape
9732 path org-link-escape-chars-browser)
9733 path))))
9735 ((member type '("message"))
9736 (browse-url (concat type ":" path)))
9738 ((string= type "tags")
9739 (org-tags-view arg path))
9741 ((string= type "tree-match")
9742 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9744 ((string= type "file")
9745 (if (string-match "::\\([0-9]+\\)\\'" path)
9746 (setq line (string-to-number (match-string 1 path))
9747 path (substring path 0 (match-beginning 0)))
9748 (if (string-match "::\\(.+\\)\\'" path)
9749 (setq search (match-string 1 path)
9750 path (substring path 0 (match-beginning 0)))))
9751 (if (string-match "[*?{]" (file-name-nondirectory path))
9752 (dired path)
9753 (org-open-file path arg line search)))
9755 ((string= type "shell")
9756 (let ((cmd path))
9757 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9758 (string-match org-confirm-shell-link-not-regexp cmd))
9759 (not org-confirm-shell-link-function)
9760 (funcall org-confirm-shell-link-function
9761 (format "Execute \"%s\" in shell? "
9762 (org-add-props cmd nil
9763 'face 'org-warning))))
9764 (progn
9765 (message "Executing %s" cmd)
9766 (shell-command cmd))
9767 (error "Abort"))))
9769 ((string= type "elisp")
9770 (let ((cmd path))
9771 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9772 (string-match org-confirm-elisp-link-not-regexp cmd))
9773 (not org-confirm-elisp-link-function)
9774 (funcall org-confirm-elisp-link-function
9775 (format "Execute \"%s\" as elisp? "
9776 (org-add-props cmd nil
9777 'face 'org-warning))))
9778 (message "%s => %s" cmd
9779 (if (equal (string-to-char cmd) ?\()
9780 (eval (read cmd))
9781 (call-interactively (read cmd))))
9782 (error "Abort"))))
9784 ((and (string= type "thisfile")
9785 (run-hook-with-args-until-success
9786 'org-open-link-functions path)))
9788 ((string= type "thisfile")
9789 (if arg
9790 (switch-to-buffer-other-window
9791 (org-get-buffer-for-internal-link (current-buffer)))
9792 (org-mark-ring-push))
9793 (let ((cmd `(org-link-search
9794 ,path
9795 ,(cond ((equal arg '(4)) ''occur)
9796 ((equal arg '(16)) ''org-occur)
9797 (t nil))
9798 ,pos)))
9799 (condition-case nil (let ((org-link-search-inhibit-query t))
9800 (eval cmd))
9801 (error (progn (widen) (eval cmd))))))
9804 (browse-url-at-point)))))))
9805 (move-marker org-open-link-marker nil)
9806 (run-hook-with-args 'org-follow-link-hook)))
9808 (defun org-offer-links-in-entry (&optional nth zero)
9809 "Offer links in the current entry and follow the selected link.
9810 If there is only one link, follow it immediately as well.
9811 If NTH is an integer, immediately pick the NTH link found.
9812 If ZERO is a string, check also this string for a link, and if
9813 there is one, offer it as link number zero."
9814 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9815 "\\(" org-angle-link-re "\\)\\|"
9816 "\\(" org-plain-link-re "\\)"))
9817 (cnt ?0)
9818 (in-emacs (if (integerp nth) nil nth))
9819 have-zero end links link c)
9820 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9821 (push (match-string 0 zero) links)
9822 (setq cnt (1- cnt) have-zero t))
9823 (save-excursion
9824 (org-back-to-heading t)
9825 (setq end (save-excursion (outline-next-heading) (point)))
9826 (while (re-search-forward re end t)
9827 (push (match-string 0) links))
9828 (setq links (org-uniquify (reverse links))))
9830 (cond
9831 ((null links)
9832 (message "No links"))
9833 ((equal (length links) 1)
9834 (setq link (list (car links))))
9835 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9836 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9837 (t ; we have to select a link
9838 (save-excursion
9839 (save-window-excursion
9840 (delete-other-windows)
9841 (with-output-to-temp-buffer "*Select Link*"
9842 (mapc (lambda (l)
9843 (if (not (string-match org-bracket-link-regexp l))
9844 (princ (format "[%c] %s\n" (incf cnt)
9845 (org-remove-angle-brackets l)))
9846 (if (match-end 3)
9847 (princ (format "[%c] %s (%s)\n" (incf cnt)
9848 (match-string 3 l) (match-string 1 l)))
9849 (princ (format "[%c] %s\n" (incf cnt)
9850 (match-string 1 l))))))
9851 links))
9852 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9853 (message "Select link to open, RET to open all:")
9854 (setq c (read-char-exclusive))
9855 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9856 (when (equal c ?q) (error "Abort"))
9857 (if (equal c ?\C-m)
9858 (setq link links)
9859 (setq nth (- c ?0))
9860 (if have-zero (setq nth (1+ nth)))
9861 (unless (and (integerp nth) (>= (length links) nth))
9862 (error "Invalid link selection"))
9863 (setq link (list (nth (1- nth) links))))))
9864 (if link
9865 (let ((buf (current-buffer)))
9866 (dolist (l link)
9867 (org-open-link-from-string l in-emacs buf))
9869 nil)))
9871 ;; Add special file links that specify the way of opening
9873 (org-add-link-type "file+sys" 'org-open-file-with-system)
9874 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9875 (defun org-open-file-with-system (path)
9876 "Open file at PATH using the system way of opening it."
9877 (org-open-file path 'system))
9878 (defun org-open-file-with-emacs (path)
9879 "Open file at PATH in Emacs."
9880 (org-open-file path 'emacs))
9881 (defun org-remove-file-link-modifiers ()
9882 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9883 (goto-char (point-min))
9884 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9885 (org-if-unprotected
9886 (replace-match "file:" t t))))
9887 (eval-after-load "org-exp"
9888 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9889 'org-remove-file-link-modifiers))
9891 ;;;; Time estimates
9893 (defun org-get-effort (&optional pom)
9894 "Get the effort estimate for the current entry."
9895 (org-entry-get pom org-effort-property))
9897 ;;; File search
9899 (defvar org-create-file-search-functions nil
9900 "List of functions to construct the right search string for a file link.
9901 These functions are called in turn with point at the location to
9902 which the link should point.
9904 A function in the hook should first test if it would like to
9905 handle this file type, for example by checking the `major-mode'
9906 or the file extension. If it decides not to handle this file, it
9907 should just return nil to give other functions a chance. If it
9908 does handle the file, it must return the search string to be used
9909 when following the link. The search string will be part of the
9910 file link, given after a double colon, and `org-open-at-point'
9911 will automatically search for it. If special measures must be
9912 taken to make the search successful, another function should be
9913 added to the companion hook `org-execute-file-search-functions',
9914 which see.
9916 A function in this hook may also use `setq' to set the variable
9917 `description' to provide a suggestion for the descriptive text to
9918 be used for this link when it gets inserted into an Org-mode
9919 buffer with \\[org-insert-link].")
9921 (defvar org-execute-file-search-functions nil
9922 "List of functions to execute a file search triggered by a link.
9924 Functions added to this hook must accept a single argument, the
9925 search string that was part of the file link, the part after the
9926 double colon. The function must first check if it would like to
9927 handle this search, for example by checking the `major-mode' or
9928 the file extension. If it decides not to handle this search, it
9929 should just return nil to give other functions a chance. If it
9930 does handle the search, it must return a non-nil value to keep
9931 other functions from trying.
9933 Each function can access the current prefix argument through the
9934 variable `current-prefix-argument'. Note that a single prefix is
9935 used to force opening a link in Emacs, so it may be good to only
9936 use a numeric or double prefix to guide the search function.
9938 In case this is needed, a function in this hook can also restore
9939 the window configuration before `org-open-at-point' was called using:
9941 (set-window-configuration org-window-config-before-follow-link)")
9943 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9944 (defun org-link-search (s &optional type avoid-pos stealth)
9945 "Search for a link search option.
9946 If S is surrounded by forward slashes, it is interpreted as a
9947 regular expression. In org-mode files, this will create an `org-occur'
9948 sparse tree. In ordinary files, `occur' will be used to list matches.
9949 If the current buffer is in `dired-mode', grep will be used to search
9950 in all files. If AVOID-POS is given, ignore matches near that position.
9952 When optional argument STEALTH is non-nil, do not modify
9953 visibility around point, thus ignoring
9954 `org-show-hierarchy-above', `org-show-following-heading' and
9955 `org-show-siblings' variables."
9956 (let ((case-fold-search t)
9957 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9958 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9959 (append '(("") (" ") ("\t") ("\n"))
9960 org-emphasis-alist)
9961 "\\|") "\\)"))
9962 (pos (point))
9963 (pre nil) (post nil)
9964 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9965 (cond
9966 ;; First check if there are any special search functions
9967 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9968 ;; Now try the builtin stuff
9969 ((and (equal (string-to-char s0) ?#)
9970 (> (length s0) 1)
9971 (save-excursion
9972 (goto-char (point-min))
9973 (and
9974 (re-search-forward
9975 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9976 (setq type 'dedicated
9977 pos (match-beginning 0))))
9978 ;; There is an exact target for this
9979 (goto-char pos)
9980 (org-back-to-heading t)))
9981 ((save-excursion
9982 (goto-char (point-min))
9983 (and
9984 (re-search-forward
9985 (concat "<<" (regexp-quote s0) ">>") nil t)
9986 (setq type 'dedicated
9987 pos (match-beginning 0))))
9988 ;; There is an exact target for this
9989 (goto-char pos))
9990 ((save-excursion
9991 (goto-char (point-min))
9992 (and
9993 (re-search-forward
9994 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9995 (setq type 'dedicated pos (match-beginning 0))))
9996 ;; Found an invisible target.
9997 (goto-char pos))
9998 ((save-excursion
9999 (goto-char (point-min))
10000 (and
10001 (re-search-forward
10002 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10003 (setq type 'dedicated pos (match-beginning 0))))
10004 ;; Found an element with a matching #+name affiliated keyword.
10005 (goto-char pos))
10006 ((and (string-match "^(\\(.*\\))$" s0)
10007 (save-excursion
10008 (goto-char (point-min))
10009 (and
10010 (re-search-forward
10011 (concat "[^[]" (regexp-quote
10012 (format org-coderef-label-format
10013 (match-string 1 s0))))
10014 nil t)
10015 (setq type 'dedicated
10016 pos (1+ (match-beginning 0))))))
10017 ;; There is a coderef target for this
10018 (goto-char pos))
10019 ((string-match "^/\\(.*\\)/$" s)
10020 ;; A regular expression
10021 (cond
10022 ((derived-mode-p 'org-mode)
10023 (org-occur (match-string 1 s)))
10024 ;;((eq major-mode 'dired-mode)
10025 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10026 (t (org-do-occur (match-string 1 s)))))
10027 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10028 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10029 (goto-char (point-min))
10030 (cond
10031 ((let (case-fold-search)
10032 (re-search-forward (format org-complex-heading-regexp-format
10033 (regexp-quote s))
10034 nil t))
10035 ;; OK, found a match
10036 (setq type 'dedicated)
10037 (goto-char (match-beginning 0)))
10038 ((and (not org-link-search-inhibit-query)
10039 (eq org-link-search-must-match-exact-headline 'query-to-create)
10040 (y-or-n-p "No match - create this as a new heading? "))
10041 (goto-char (point-max))
10042 (or (bolp) (newline))
10043 (insert "* " s "\n")
10044 (beginning-of-line 0))
10046 (goto-char pos)
10047 (error "No match"))))
10049 ;; A normal search string
10050 (when (equal (string-to-char s) ?*)
10051 ;; Anchor on headlines, post may include tags.
10052 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10053 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10054 s (substring s 1)))
10055 (remove-text-properties
10056 0 (length s)
10057 '(face nil mouse-face nil keymap nil fontified nil) s)
10058 ;; Make a series of regular expressions to find a match
10059 (setq words (org-split-string s "[ \n\r\t]+")
10061 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10062 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10063 "\\)" markers)
10064 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10065 re2a (concat "[ \t\r\n]" re2a_)
10066 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10067 re4 (concat "[^a-zA-Z_]" re4_)
10069 re1 (concat pre re2 post)
10070 re3 (concat pre (if pre re4_ re4) post)
10071 re5 (concat pre ".*" re4)
10072 re2 (concat pre re2)
10073 re2a (concat pre (if pre re2a_ re2a))
10074 re4 (concat pre (if pre re4_ re4))
10075 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10076 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10077 re5 "\\)"
10079 (cond
10080 ((eq type 'org-occur) (org-occur reall))
10081 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10082 (t (goto-char (point-min))
10083 (setq type 'fuzzy)
10084 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10085 (org-search-not-self 1 re1 nil t)
10086 (org-search-not-self 1 re2 nil t)
10087 (org-search-not-self 1 re2a nil t)
10088 (org-search-not-self 1 re3 nil t)
10089 (org-search-not-self 1 re4 nil t)
10090 (org-search-not-self 1 re5 nil t)
10092 (goto-char (match-beginning 1))
10093 (goto-char pos)
10094 (error "No match"))))))
10095 (and (derived-mode-p 'org-mode)
10096 (not stealth)
10097 (org-show-context 'link-search))
10098 type))
10100 (defun org-search-not-self (group &rest args)
10101 "Execute `re-search-forward', but only accept matches that do not
10102 enclose the position of `org-open-link-marker'."
10103 (let ((m org-open-link-marker))
10104 (catch 'exit
10105 (while (apply 're-search-forward args)
10106 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10107 (goto-char (match-end group))
10108 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10109 (> (match-beginning 0) (marker-position m))
10110 (< (match-end 0) (marker-position m)))
10111 (save-match-data
10112 (or (not (org-in-regexp
10113 org-bracket-link-analytic-regexp 1))
10114 (not (match-end 4)) ; no description
10115 (and (<= (match-beginning 4) (point))
10116 (>= (match-end 4) (point))))))
10117 (throw 'exit (point))))))))
10119 (defun org-get-buffer-for-internal-link (buffer)
10120 "Return a buffer to be used for displaying the link target of internal links."
10121 (cond
10122 ((not org-display-internal-link-with-indirect-buffer)
10123 buffer)
10124 ((string-match "(Clone)$" (buffer-name buffer))
10125 (message "Buffer is already a clone, not making another one")
10126 ;; we also do not modify visibility in this case
10127 buffer)
10128 (t ; make a new indirect buffer for displaying the link
10129 (let* ((bn (buffer-name buffer))
10130 (ibn (concat bn "(Clone)"))
10131 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10132 (with-current-buffer ib (org-overview))
10133 ib))))
10135 (defun org-do-occur (regexp &optional cleanup)
10136 "Call the Emacs command `occur'.
10137 If CLEANUP is non-nil, remove the printout of the regular expression
10138 in the *Occur* buffer. This is useful if the regex is long and not useful
10139 to read."
10140 (occur regexp)
10141 (when cleanup
10142 (let ((cwin (selected-window)) win beg end)
10143 (when (setq win (get-buffer-window "*Occur*"))
10144 (select-window win))
10145 (goto-char (point-min))
10146 (when (re-search-forward "match[a-z]+" nil t)
10147 (setq beg (match-end 0))
10148 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10149 (setq end (1- (match-beginning 0)))))
10150 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10151 (goto-char (point-min))
10152 (select-window cwin))))
10154 ;;; The mark ring for links jumps
10156 (defvar org-mark-ring nil
10157 "Mark ring for positions before jumps in Org-mode.")
10158 (defvar org-mark-ring-last-goto nil
10159 "Last position in the mark ring used to go back.")
10160 ;; Fill and close the ring
10161 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10162 (loop for i from 1 to org-mark-ring-length do
10163 (push (make-marker) org-mark-ring))
10164 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10165 org-mark-ring)
10167 (defun org-mark-ring-push (&optional pos buffer)
10168 "Put the current position or POS into the mark ring and rotate it."
10169 (interactive)
10170 (setq pos (or pos (point)))
10171 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10172 (move-marker (car org-mark-ring)
10173 (or pos (point))
10174 (or buffer (current-buffer)))
10175 (message "%s"
10176 (substitute-command-keys
10177 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10179 (defun org-mark-ring-goto (&optional n)
10180 "Jump to the previous position in the mark ring.
10181 With prefix arg N, jump back that many stored positions. When
10182 called several times in succession, walk through the entire ring.
10183 Org-mode commands jumping to a different position in the current file,
10184 or to another Org-mode file, automatically push the old position
10185 onto the ring."
10186 (interactive "p")
10187 (let (p m)
10188 (if (eq last-command this-command)
10189 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10190 (setq p org-mark-ring))
10191 (setq org-mark-ring-last-goto p)
10192 (setq m (car p))
10193 (org-pop-to-buffer-same-window (marker-buffer m))
10194 (goto-char m)
10195 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10197 (defun org-remove-angle-brackets (s)
10198 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10199 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10201 (defun org-add-angle-brackets (s)
10202 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10203 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10205 (defun org-remove-double-quotes (s)
10206 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10207 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10210 ;;; Following specific links
10212 (defun org-follow-timestamp-link ()
10213 (cond
10214 ((org-at-date-range-p t)
10215 (let ((org-agenda-start-on-weekday)
10216 (t1 (match-string 1))
10217 (t2 (match-string 2)))
10218 (setq t1 (time-to-days (org-time-string-to-time t1))
10219 t2 (time-to-days (org-time-string-to-time t2)))
10220 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10221 ((org-at-timestamp-p t)
10222 (org-agenda-list nil (time-to-days (org-time-string-to-time
10223 (substring (match-string 1) 0 10)))
10225 (t (error "This should not happen"))))
10228 ;;; Following file links
10229 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10230 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10231 (declare-function mailcap-mime-info
10232 "mailcap" (string &optional request no-decode))
10233 (defvar org-wait nil)
10234 (defun org-open-file (path &optional in-emacs line search)
10235 "Open the file at PATH.
10236 First, this expands any special file name abbreviations. Then the
10237 configuration variable `org-file-apps' is checked if it contains an
10238 entry for this file type, and if yes, the corresponding command is launched.
10240 If no application is found, Emacs simply visits the file.
10242 With optional prefix argument IN-EMACS, Emacs will visit the file.
10243 With a double \\[universal-argument] \\[universal-argument] \
10244 prefix arg, Org tries to avoid opening in Emacs
10245 and to use an external application to visit the file.
10247 Optional LINE specifies a line to go to, optional SEARCH a string
10248 to search for. If LINE or SEARCH is given, the file will be
10249 opened in Emacs, unless an entry from org-file-apps that makes
10250 use of groups in a regexp matches.
10252 If you want to change the way frames are used when following a
10253 link, please customize `org-link-frame-setup'.
10255 If the file does not exist, an error is thrown."
10256 (let* ((file (if (equal path "")
10257 buffer-file-name
10258 (substitute-in-file-name (expand-file-name path))))
10259 (file-apps (append org-file-apps (org-default-apps)))
10260 (apps (org-remove-if
10261 'org-file-apps-entry-match-against-dlink-p file-apps))
10262 (apps-dlink (org-remove-if-not
10263 'org-file-apps-entry-match-against-dlink-p file-apps))
10264 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10265 (dirp (if remp nil (file-directory-p file)))
10266 (file (if (and dirp org-open-directory-means-index-dot-org)
10267 (concat (file-name-as-directory file) "index.org")
10268 file))
10269 (a-m-a-p (assq 'auto-mode apps))
10270 (dfile (downcase file))
10271 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10272 (link (cond ((and (eq line nil)
10273 (eq search nil))
10274 file)
10275 (line
10276 (concat file "::" (number-to-string line)))
10277 (search
10278 (concat file "::" search))))
10279 (dlink (downcase link))
10280 (old-buffer (current-buffer))
10281 (old-pos (point))
10282 (old-mode major-mode)
10283 ext cmd link-match-data)
10284 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10285 (setq ext (match-string 1 dfile))
10286 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10287 (setq ext (match-string 1 dfile))))
10288 (cond
10289 ((member in-emacs '((16) system))
10290 (setq cmd (cdr (assoc 'system apps))))
10291 (in-emacs (setq cmd 'emacs))
10293 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10294 (and dirp (cdr (assoc 'directory apps)))
10295 ; first, try matching against apps-dlink
10296 ; if we get a match here, store the match data for later
10297 (let ((match (assoc-default dlink apps-dlink
10298 'string-match)))
10299 (if match
10300 (progn (setq link-match-data (match-data))
10301 match)
10302 (progn (setq in-emacs (or in-emacs line search))
10303 nil))) ; if we have no match in apps-dlink,
10304 ; always open the file in emacs if line or search
10305 ; is given (for backwards compatibility)
10306 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10307 'string-match)
10308 (cdr (assoc ext apps))
10309 (cdr (assoc t apps))))))
10310 (when (eq cmd 'system)
10311 (setq cmd (cdr (assoc 'system apps))))
10312 (when (eq cmd 'default)
10313 (setq cmd (cdr (assoc t apps))))
10314 (when (eq cmd 'mailcap)
10315 (require 'mailcap)
10316 (mailcap-parse-mailcaps)
10317 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10318 (command (mailcap-mime-info mime-type)))
10319 (if (stringp command)
10320 (setq cmd command)
10321 (setq cmd 'emacs))))
10322 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10323 (not (file-exists-p file))
10324 (not org-open-non-existing-files))
10325 (error "No such file: %s" file))
10326 (cond
10327 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10328 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10329 (while (string-match "['\"]%s['\"]" cmd)
10330 (setq cmd (replace-match "%s" t t cmd)))
10331 (while (string-match "%s" cmd)
10332 (setq cmd (replace-match
10333 (save-match-data
10334 (shell-quote-argument
10335 (convert-standard-filename file)))
10336 t t cmd)))
10338 ;; Replace "%1", "%2" etc. in command with group matches from regex
10339 (save-match-data
10340 (let ((match-index 1)
10341 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10342 (set-match-data link-match-data)
10343 (while (<= match-index number-of-groups)
10344 (let ((regex (concat "%" (number-to-string match-index)))
10345 (replace-with (match-string match-index dlink)))
10346 (while (string-match regex cmd)
10347 (setq cmd (replace-match replace-with t t cmd))))
10348 (setq match-index (+ match-index 1)))))
10350 (save-window-excursion
10351 (start-process-shell-command cmd nil cmd)
10352 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10354 ((or (stringp cmd)
10355 (eq cmd 'emacs))
10356 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10357 (widen)
10358 (if line (org-goto-line line)
10359 (if search (org-link-search search))))
10360 ((consp cmd)
10361 (let ((file (convert-standard-filename file)))
10362 (save-match-data
10363 (set-match-data link-match-data)
10364 (eval cmd))))
10365 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10366 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10367 (or (not (equal old-buffer (current-buffer)))
10368 (not (equal old-pos (point))))
10369 (org-mark-ring-push old-pos old-buffer))))
10371 (defun org-file-apps-entry-match-against-dlink-p (entry)
10372 "This function returns non-nil if `entry' uses a regular
10373 expression which should be matched against the whole link by
10374 org-open-file.
10376 It assumes that is the case when the entry uses a regular
10377 expression which has at least one grouping construct and the
10378 action is either a lisp form or a command string containing
10379 '%1', i.e. using at least one subexpression match as a
10380 parameter."
10381 (let ((selector (car entry))
10382 (action (cdr entry)))
10383 (if (stringp selector)
10384 (and (> (regexp-opt-depth selector) 0)
10385 (or (and (stringp action)
10386 (string-match "%[0-9]" action))
10387 (consp action)))
10388 nil)))
10390 (defun org-default-apps ()
10391 "Return the default applications for this operating system."
10392 (cond
10393 ((eq system-type 'darwin)
10394 org-file-apps-defaults-macosx)
10395 ((eq system-type 'windows-nt)
10396 org-file-apps-defaults-windowsnt)
10397 (t org-file-apps-defaults-gnu)))
10399 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10400 "Convert extensions to regular expressions in the cars of LIST.
10401 Also, weed out any non-string entries, because the return value is used
10402 only for regexp matching.
10403 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10404 point to the symbol `emacs', indicating that the file should
10405 be opened in Emacs."
10406 (append
10407 (delq nil
10408 (mapcar (lambda (x)
10409 (if (not (stringp (car x)))
10411 (if (string-match "\\W" (car x))
10413 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10414 list))
10415 (if add-auto-mode
10416 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10418 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10419 (defun org-file-remote-p (file)
10420 "Test whether FILE specifies a location on a remote system.
10421 Return non-nil if the location is indeed remote.
10423 For example, the filename \"/user@host:/foo\" specifies a location
10424 on the system \"/user@host:\"."
10425 (cond ((fboundp 'file-remote-p)
10426 (file-remote-p file))
10427 ((fboundp 'tramp-handle-file-remote-p)
10428 (tramp-handle-file-remote-p file))
10429 ((and (boundp 'ange-ftp-name-format)
10430 (string-match (car ange-ftp-name-format) file))
10432 (t nil)))
10435 ;;;; Refiling
10437 (defun org-get-org-file ()
10438 "Read a filename, with default directory `org-directory'."
10439 (let ((default (or org-default-notes-file remember-data-file)))
10440 (read-file-name (format "File name [%s]: " default)
10441 (file-name-as-directory org-directory)
10442 default)))
10444 (defun org-notes-order-reversed-p ()
10445 "Check if the current file should receive notes in reversed order."
10446 (cond
10447 ((not org-reverse-note-order) nil)
10448 ((eq t org-reverse-note-order) t)
10449 ((not (listp org-reverse-note-order)) nil)
10450 (t (catch 'exit
10451 (let ((all org-reverse-note-order)
10452 entry)
10453 (while (setq entry (pop all))
10454 (if (string-match (car entry) buffer-file-name)
10455 (throw 'exit (cdr entry))))
10456 nil)))))
10458 (defvar org-refile-target-table nil
10459 "The list of refile targets, created by `org-refile'.")
10461 (defvar org-agenda-new-buffers nil
10462 "Buffers created to visit agenda files.")
10464 (defvar org-refile-cache nil
10465 "Cache for refile targets.")
10467 (defvar org-refile-markers nil
10468 "All the markers used for caching refile locations.")
10470 (defun org-refile-marker (pos)
10471 "Get a new refile marker, but only if caching is in use."
10472 (if (not org-refile-use-cache)
10474 (let ((m (make-marker)))
10475 (move-marker m pos)
10476 (push m org-refile-markers)
10477 m)))
10479 (defun org-refile-cache-clear ()
10480 "Clear the refile cache and disable all the markers."
10481 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10482 (setq org-refile-markers nil)
10483 (setq org-refile-cache nil)
10484 (message "Refile cache has been cleared"))
10486 (defun org-refile-cache-check-set (set)
10487 "Check if all the markers in the cache still have live buffers."
10488 (let (marker)
10489 (catch 'exit
10490 (while (and set (setq marker (nth 3 (pop set))))
10491 ;; if org-refile-use-outline-path is 'file, marker may be nil
10492 (when (and marker (null (marker-buffer marker)))
10493 (message "not found") (sit-for 3)
10494 (throw 'exit nil)))
10495 t)))
10497 (defun org-refile-cache-put (set &rest identifiers)
10498 "Push the refile targets SET into the cache, under IDENTIFIERS."
10499 (let* ((key (sha1 (prin1-to-string identifiers)))
10500 (entry (assoc key org-refile-cache)))
10501 (if entry
10502 (setcdr entry set)
10503 (push (cons key set) org-refile-cache))))
10505 (defun org-refile-cache-get (&rest identifiers)
10506 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10507 (cond
10508 ((not org-refile-cache) nil)
10509 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10511 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10512 org-refile-cache))))
10513 (and set (org-refile-cache-check-set set) set)))))
10515 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10516 "Produce a table with refile targets."
10517 (let ((case-fold-search nil)
10518 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10519 (entries (or org-refile-targets '((nil . (:level . 1)))))
10520 targets tgs txt re files f desc descre fast-path-p level pos0)
10521 (message "Getting targets...")
10522 (with-current-buffer (or default-buffer (current-buffer))
10523 (while (setq entry (pop entries))
10524 (setq files (car entry) desc (cdr entry))
10525 (setq fast-path-p nil)
10526 (cond
10527 ((null files) (setq files (list (current-buffer))))
10528 ((eq files 'org-agenda-files)
10529 (setq files (org-agenda-files 'unrestricted)))
10530 ((and (symbolp files) (fboundp files))
10531 (setq files (funcall files)))
10532 ((and (symbolp files) (boundp files))
10533 (setq files (symbol-value files))))
10534 (if (stringp files) (setq files (list files)))
10535 (cond
10536 ((eq (car desc) :tag)
10537 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10538 ((eq (car desc) :todo)
10539 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10540 ((eq (car desc) :regexp)
10541 (setq descre (cdr desc)))
10542 ((eq (car desc) :level)
10543 (setq descre (concat "^\\*\\{" (number-to-string
10544 (if org-odd-levels-only
10545 (1- (* 2 (cdr desc)))
10546 (cdr desc)))
10547 "\\}[ \t]")))
10548 ((eq (car desc) :maxlevel)
10549 (setq fast-path-p t)
10550 (setq descre (concat "^\\*\\{1," (number-to-string
10551 (if org-odd-levels-only
10552 (1- (* 2 (cdr desc)))
10553 (cdr desc)))
10554 "\\}[ \t]")))
10555 (t (error "Bad refiling target description %s" desc)))
10556 (while (setq f (pop files))
10557 (with-current-buffer
10558 (if (bufferp f) f (org-get-agenda-file-buffer f))
10560 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10561 (progn
10562 (if (bufferp f) (setq f (buffer-file-name
10563 (buffer-base-buffer f))))
10564 (setq f (and f (expand-file-name f)))
10565 (if (eq org-refile-use-outline-path 'file)
10566 (push (list (file-name-nondirectory f) f nil nil) tgs))
10567 (save-excursion
10568 (save-restriction
10569 (widen)
10570 (goto-char (point-min))
10571 (while (re-search-forward descre nil t)
10572 (goto-char (setq pos0 (point-at-bol)))
10573 (catch 'next
10574 (when org-refile-target-verify-function
10575 (save-match-data
10576 (or (funcall org-refile-target-verify-function)
10577 (throw 'next t))))
10578 (when (and (looking-at org-complex-heading-regexp)
10579 (not (member (match-string 4) excluded-entries))
10580 (match-string 4))
10581 (setq level (org-reduced-level
10582 (- (match-end 1) (match-beginning 1)))
10583 txt (org-link-display-format (match-string 4))
10584 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10585 re (format org-complex-heading-regexp-format
10586 (regexp-quote (match-string 4))))
10587 (when org-refile-use-outline-path
10588 (setq txt (mapconcat
10589 'org-protect-slash
10590 (append
10591 (if (eq org-refile-use-outline-path
10592 'file)
10593 (list (file-name-nondirectory
10594 (buffer-file-name
10595 (buffer-base-buffer))))
10596 (if (eq org-refile-use-outline-path
10597 'full-file-path)
10598 (list (buffer-file-name
10599 (buffer-base-buffer)))))
10600 (org-get-outline-path fast-path-p
10601 level txt)
10602 (list txt))
10603 "/")))
10604 (push (list txt f re (org-refile-marker (point)))
10605 tgs)))
10606 (when (= (point) pos0)
10607 ;; verification function has not moved point
10608 (goto-char (point-at-eol))))))))
10609 (when org-refile-use-cache
10610 (org-refile-cache-put tgs (buffer-file-name) descre))
10611 (setq targets (append tgs targets))
10612 ))))
10613 (message "Getting targets...done")
10614 (nreverse targets)))
10616 (defun org-protect-slash (s)
10617 (while (string-match "/" s)
10618 (setq s (replace-match "\\" t t s)))
10621 (defvar org-olpa (make-vector 20 nil))
10623 (defun org-get-outline-path (&optional fastp level heading)
10624 "Return the outline path to the current entry, as a list.
10626 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10627 routine which makes outline path derivations for an entire file,
10628 avoiding backtracing. Refile target collection makes use of that."
10629 (if fastp
10630 (progn
10631 (if (> level 19)
10632 (error "Outline path failure, more than 19 levels"))
10633 (loop for i from level upto 19 do
10634 (aset org-olpa i nil))
10635 (prog1
10636 (delq nil (append org-olpa nil))
10637 (aset org-olpa level heading)))
10638 (let (rtn case-fold-search)
10639 (save-excursion
10640 (save-restriction
10641 (widen)
10642 (while (org-up-heading-safe)
10643 (when (looking-at org-complex-heading-regexp)
10644 (push (org-match-string-no-properties 4) rtn)))
10645 rtn)))))
10647 (defun org-format-outline-path (path &optional width prefix)
10648 "Format the outline path PATH for display.
10649 Width is the maximum number of characters that is available.
10650 Prefix is a prefix to be included in the returned string,
10651 such as the file name."
10652 (setq width (or width 79))
10653 (if prefix (setq width (- width (length prefix))))
10654 (if (not path)
10655 (or prefix "")
10656 (let* ((nsteps (length path))
10657 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10658 (maxwidth (if (<= total-width width)
10659 10000 ;; everything fits
10660 ;; we need to shorten the level headings
10661 (/ (- width nsteps) nsteps)))
10662 (org-odd-levels-only nil)
10663 (n 0)
10664 (total (1+ (length prefix))))
10665 (setq maxwidth (max maxwidth 10))
10666 (concat prefix
10667 (mapconcat
10668 (lambda (h)
10669 (setq n (1+ n))
10670 (if (and (= n nsteps) (< maxwidth 10000))
10671 (setq maxwidth (- total-width total)))
10672 (if (< (length h) maxwidth)
10673 (progn (setq total (+ total (length h) 1)) h)
10674 (setq h (substring h 0 (- maxwidth 2))
10675 total (+ total maxwidth 1))
10676 (if (string-match "[ \t]+\\'" h)
10677 (setq h (substring h 0 (match-beginning 0))))
10678 (setq h (concat h "..")))
10679 (org-add-props h nil 'face
10680 (nth (% (1- n) org-n-level-faces)
10681 org-level-faces))
10683 path "/")))))
10685 (defun org-display-outline-path (&optional file current)
10686 "Display the current outline path in the echo area."
10687 (interactive "P")
10688 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10689 (case-fold-search nil)
10690 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10691 (if current (setq path (append path
10692 (save-excursion
10693 (org-back-to-heading t)
10694 (if (looking-at org-complex-heading-regexp)
10695 (list (match-string 4)))))))
10696 (message "%s"
10697 (org-format-outline-path
10698 path
10699 (1- (frame-width))
10700 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10702 (defvar org-refile-history nil
10703 "History for refiling operations.")
10705 (defvar org-after-refile-insert-hook nil
10706 "Hook run after `org-refile' has inserted its stuff at the new location.
10707 Note that this is still *before* the stuff will be removed from
10708 the *old* location.")
10710 (defvar org-capture-last-stored-marker)
10711 (defun org-refile (&optional goto default-buffer rfloc)
10712 "Move the entry or entries at point to another heading.
10713 The list of target headings is compiled using the information in
10714 `org-refile-targets', which see.
10716 At the target location, the entry is filed as a subitem of the target
10717 heading. Depending on `org-reverse-note-order', the new subitem will
10718 either be the first or the last subitem.
10720 If there is an active region, all entries in that region will be moved.
10721 However, the region must fulfill the requirement that the first heading
10722 is the first one sets the top-level of the moved text - at most siblings
10723 below it are allowed.
10725 With prefix arg GOTO, the command will only visit the target location
10726 and not actually move anything.
10728 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10729 go to the location where the last refiling operation has put the subtree.
10730 With a prefix argument of `2', refile to the running clock.
10732 RFLOC can be a refile location obtained in a different way.
10734 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10736 If you are using target caching (see `org-refile-use-cache'),
10737 you have to clear the target cache in order to find new targets.
10738 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10739 prefix argument (`C-u C-u C-u C-c C-w')."
10741 (interactive "P")
10742 (if (member goto '(0 (64)))
10743 (org-refile-cache-clear)
10744 (let* ((cbuf (current-buffer))
10745 (regionp (org-region-active-p))
10746 (region-start (and regionp (region-beginning)))
10747 (region-end (and regionp (region-end)))
10748 (region-length (and regionp (- region-end region-start)))
10749 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10750 pos it nbuf file re level reversed)
10751 (setq last-command nil)
10752 (when regionp
10753 (goto-char region-start)
10754 (or (bolp) (goto-char (point-at-bol)))
10755 (setq region-start (point))
10756 (unless (or (org-kill-is-subtree-p
10757 (buffer-substring region-start region-end))
10758 (prog1 org-refile-active-region-within-subtree
10759 (org-toggle-heading)))
10760 (error "The region is not a (sequence of) subtree(s)")))
10761 (if (equal goto '(16))
10762 (org-refile-goto-last-stored)
10763 (when (or
10764 (and (equal goto 2)
10765 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10766 (prog1
10767 (setq it (list (or org-clock-heading "running clock")
10768 (buffer-file-name
10769 (marker-buffer org-clock-hd-marker))
10771 (marker-position org-clock-hd-marker)))
10772 (setq goto nil)))
10773 (setq it (or rfloc
10774 (let (heading-text)
10775 (save-excursion
10776 (unless goto
10777 (org-back-to-heading t)
10778 (setq heading-text
10779 (nth 4 (org-heading-components))))
10780 (org-refile-get-location
10781 (cond (goto "Goto")
10782 (regionp "Refile region to")
10783 (t (concat "Refile subtree \""
10784 heading-text "\" to")))
10785 default-buffer
10786 (and (not (equal '(4) goto))
10787 org-refile-allow-creating-parent-nodes)
10788 goto))))))
10789 (setq file (nth 1 it)
10790 re (nth 2 it)
10791 pos (nth 3 it))
10792 (if (and (not goto)
10794 (equal (buffer-file-name) file)
10795 (if regionp
10796 (and (>= pos region-start)
10797 (<= pos region-end))
10798 (and (>= pos (point))
10799 (< pos (save-excursion
10800 (org-end-of-subtree t t))))))
10801 (error "Cannot refile to position inside the tree or region"))
10803 (setq nbuf (or (find-buffer-visiting file)
10804 (find-file-noselect file)))
10805 (if goto
10806 (progn
10807 (org-pop-to-buffer-same-window nbuf)
10808 (goto-char pos)
10809 (org-show-context 'org-goto))
10810 (if regionp
10811 (progn
10812 (org-kill-new (buffer-substring region-start region-end))
10813 (org-save-markers-in-region region-start region-end))
10814 (org-copy-subtree 1 nil t))
10815 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10816 (find-file-noselect file)))
10817 (setq reversed (org-notes-order-reversed-p))
10818 (save-excursion
10819 (save-restriction
10820 (widen)
10821 (if pos
10822 (progn
10823 (goto-char pos)
10824 (looking-at org-outline-regexp)
10825 (setq level (org-get-valid-level (funcall outline-level) 1))
10826 (goto-char
10827 (if reversed
10828 (or (outline-next-heading) (point-max))
10829 (or (save-excursion (org-get-next-sibling))
10830 (org-end-of-subtree t t)
10831 (point-max)))))
10832 (setq level 1)
10833 (if (not reversed)
10834 (goto-char (point-max))
10835 (goto-char (point-min))
10836 (or (outline-next-heading) (goto-char (point-max)))))
10837 (if (not (bolp)) (newline))
10838 (org-paste-subtree level)
10839 (when org-log-refile
10840 (org-add-log-setup 'refile nil nil 'findpos
10841 org-log-refile)
10842 (unless (eq org-log-refile 'note)
10843 (save-excursion (org-add-log-note))))
10844 (and org-auto-align-tags
10845 (let ((org-loop-over-headlines-in-active-region nil))
10846 (org-set-tags nil t)))
10847 (bookmark-set "org-refile-last-stored")
10848 ;; If we are refiling for capture, make sure that the
10849 ;; last-capture pointers point here
10850 (when (org-bound-and-true-p org-refile-for-capture)
10851 (bookmark-set "org-capture-last-stored-marker")
10852 (move-marker org-capture-last-stored-marker (point)))
10853 (if (fboundp 'deactivate-mark) (deactivate-mark))
10854 (run-hooks 'org-after-refile-insert-hook))))
10855 (if regionp
10856 (delete-region (point) (+ (point) region-length))
10857 (org-cut-subtree))
10858 (when (featurep 'org-inlinetask)
10859 (org-inlinetask-remove-END-maybe))
10860 (setq org-markers-to-move nil)
10861 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10863 (defun org-refile-goto-last-stored ()
10864 "Go to the location where the last refile was stored."
10865 (interactive)
10866 (bookmark-jump "org-refile-last-stored")
10867 (message "This is the location of the last refile"))
10869 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10870 no-exclude)
10871 "Prompt the user for a refile location, using PROMPT.
10872 PROMPT should not be suffixed with a colon and a space, because
10873 this function appends the default value from
10874 `org-refile-history' automatically, if that is not empty.
10875 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10876 this is used for the GOTO interface."
10877 (let ((org-refile-targets org-refile-targets)
10878 (org-refile-use-outline-path org-refile-use-outline-path)
10879 excluded-entries)
10880 (when (and (derived-mode-p 'org-mode)
10881 (not org-refile-use-cache)
10882 (not no-exclude))
10883 (org-map-tree
10884 (lambda()
10885 (setq excluded-entries
10886 (append excluded-entries (list (org-get-heading t t)))))))
10887 (setq org-refile-target-table
10888 (org-refile-get-targets default-buffer excluded-entries)))
10889 (unless org-refile-target-table
10890 (error "No refile targets"))
10891 (let* ((prompt (concat prompt
10892 (and (car org-refile-history)
10893 (concat " (default " (car org-refile-history) ")"))
10894 ": "))
10895 (cbuf (current-buffer))
10896 (partial-completion-mode nil)
10897 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10898 (cfunc (if (and org-refile-use-outline-path
10899 org-outline-path-complete-in-steps)
10900 'org-olpath-completing-read
10901 'org-icompleting-read))
10902 (extra (if org-refile-use-outline-path "/" ""))
10903 (filename (and cfn (expand-file-name cfn)))
10904 (tbl (mapcar
10905 (lambda (x)
10906 (if (and (not (member org-refile-use-outline-path
10907 '(file full-file-path)))
10908 (not (equal filename (nth 1 x))))
10909 (cons (concat (car x) extra " ("
10910 (file-name-nondirectory (nth 1 x)) ")")
10911 (cdr x))
10912 (cons (concat (car x) extra) (cdr x))))
10913 org-refile-target-table))
10914 (completion-ignore-case t)
10915 pa answ parent-target child parent old-hist)
10916 (setq old-hist org-refile-history)
10917 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10918 nil 'org-refile-history (car org-refile-history)))
10919 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10920 (org-refile-check-position pa)
10921 (if pa
10922 (progn
10923 (when (or (not org-refile-history)
10924 (not (eq old-hist org-refile-history))
10925 (not (equal (car pa) (car org-refile-history))))
10926 (setq org-refile-history
10927 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10928 org-refile-history
10929 (cdr org-refile-history))))
10930 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10931 (pop org-refile-history)))
10933 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10934 (progn
10935 (setq parent (match-string 1 answ)
10936 child (match-string 2 answ))
10937 (setq parent-target (or (assoc parent tbl)
10938 (assoc (concat parent "/") tbl)))
10939 (when (and parent-target
10940 (or (eq new-nodes t)
10941 (and (eq new-nodes 'confirm)
10942 (y-or-n-p (format "Create new node \"%s\"? "
10943 child)))))
10944 (org-refile-new-child parent-target child)))
10945 (error "Invalid target location")))))
10947 (declare-function org-string-nw-p "org-macs.el" (s))
10948 (defun org-refile-check-position (refile-pointer)
10949 "Check if the refile pointer matches the readline to which it points."
10950 (let* ((file (nth 1 refile-pointer))
10951 (re (nth 2 refile-pointer))
10952 (pos (nth 3 refile-pointer))
10953 buffer)
10954 (when (org-string-nw-p re)
10955 (setq buffer (if (markerp pos)
10956 (marker-buffer pos)
10957 (or (find-buffer-visiting file)
10958 (find-file-noselect file))))
10959 (with-current-buffer buffer
10960 (save-excursion
10961 (save-restriction
10962 (widen)
10963 (goto-char pos)
10964 (beginning-of-line 1)
10965 (unless (org-looking-at-p re)
10966 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10968 (defun org-refile-new-child (parent-target child)
10969 "Use refile target PARENT-TARGET to add new CHILD below it."
10970 (unless parent-target
10971 (error "Cannot find parent for new node"))
10972 (let ((file (nth 1 parent-target))
10973 (pos (nth 3 parent-target))
10974 level)
10975 (with-current-buffer (or (find-buffer-visiting file)
10976 (find-file-noselect file))
10977 (save-excursion
10978 (save-restriction
10979 (widen)
10980 (if pos
10981 (goto-char pos)
10982 (goto-char (point-max))
10983 (if (not (bolp)) (newline)))
10984 (when (looking-at org-outline-regexp)
10985 (setq level (funcall outline-level))
10986 (org-end-of-subtree t t))
10987 (org-back-over-empty-lines)
10988 (insert "\n" (make-string
10989 (if pos (org-get-valid-level level 1) 1) ?*)
10990 " " child "\n")
10991 (beginning-of-line 0)
10992 (list (concat (car parent-target) "/" child) file "" (point)))))))
10994 (defun org-olpath-completing-read (prompt collection &rest args)
10995 "Read an outline path like a file name."
10996 (let ((thetable collection)
10997 (org-completion-use-ido nil) ; does not work with ido.
10998 (org-completion-use-iswitchb nil)) ; or iswitchb
10999 (apply
11000 'org-icompleting-read prompt
11001 (lambda (string predicate &optional flag)
11002 (let (rtn r f (l (length string)))
11003 (cond
11004 ((eq flag nil)
11005 ;; try completion
11006 (try-completion string thetable))
11007 ((eq flag t)
11008 ;; all-completions
11009 (setq rtn (all-completions string thetable predicate))
11010 (mapcar
11011 (lambda (x)
11012 (setq r (substring x l))
11013 (if (string-match " ([^)]*)$" x)
11014 (setq f (match-string 0 x))
11015 (setq f ""))
11016 (if (string-match "/" r)
11017 (concat string (substring r 0 (match-end 0)) f)
11019 rtn))
11020 ((eq flag 'lambda)
11021 ;; exact match?
11022 (assoc string thetable)))))
11023 args)))
11025 ;;;; Dynamic blocks
11027 (defun org-find-dblock (name)
11028 "Find the first dynamic block with name NAME in the buffer.
11029 If not found, stay at current position and return nil."
11030 (let (pos)
11031 (save-excursion
11032 (goto-char (point-min))
11033 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
11034 nil t)
11035 (match-beginning 0))))
11036 (if pos (goto-char pos))
11037 pos))
11039 (defconst org-dblock-start-re
11040 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11041 "Matches the start line of a dynamic block, with parameters.")
11043 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
11044 "Matches the end of a dynamic block.")
11046 (defun org-create-dblock (plist)
11047 "Create a dynamic block section, with parameters taken from PLIST.
11048 PLIST must contain a :name entry which is used as name of the block."
11049 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11050 (end-of-line 1)
11051 (newline))
11052 (let ((col (current-column))
11053 (name (plist-get plist :name)))
11054 (insert "#+BEGIN: " name)
11055 (while plist
11056 (if (eq (car plist) :name)
11057 (setq plist (cddr plist))
11058 (insert " " (prin1-to-string (pop plist)))))
11059 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11060 (beginning-of-line -2)))
11062 (defun org-prepare-dblock ()
11063 "Prepare dynamic block for refresh.
11064 This empties the block, puts the cursor at the insert position and returns
11065 the property list including an extra property :name with the block name."
11066 (unless (looking-at org-dblock-start-re)
11067 (error "Not at a dynamic block"))
11068 (let* ((begdel (1+ (match-end 0)))
11069 (name (org-no-properties (match-string 1)))
11070 (params (append (list :name name)
11071 (read (concat "(" (match-string 3) ")")))))
11072 (save-excursion
11073 (beginning-of-line 1)
11074 (skip-chars-forward " \t")
11075 (setq params (plist-put params :indentation-column (current-column))))
11076 (unless (re-search-forward org-dblock-end-re nil t)
11077 (error "Dynamic block not terminated"))
11078 (setq params
11079 (append params
11080 (list :content (buffer-substring
11081 begdel (match-beginning 0)))))
11082 (delete-region begdel (match-beginning 0))
11083 (goto-char begdel)
11084 (open-line 1)
11085 params))
11087 (defun org-map-dblocks (&optional command)
11088 "Apply COMMAND to all dynamic blocks in the current buffer.
11089 If COMMAND is not given, use `org-update-dblock'."
11090 (let ((cmd (or command 'org-update-dblock)))
11091 (save-excursion
11092 (goto-char (point-min))
11093 (while (re-search-forward org-dblock-start-re nil t)
11094 (goto-char (match-beginning 0))
11095 (save-excursion
11096 (condition-case nil
11097 (funcall cmd)
11098 (error (message "Error during update of dynamic block"))))
11099 (unless (re-search-forward org-dblock-end-re nil t)
11100 (error "Dynamic block not terminated"))))))
11102 (defun org-dblock-update (&optional arg)
11103 "User command for updating dynamic blocks.
11104 Update the dynamic block at point. With prefix ARG, update all dynamic
11105 blocks in the buffer."
11106 (interactive "P")
11107 (if arg
11108 (org-update-all-dblocks)
11109 (or (looking-at org-dblock-start-re)
11110 (org-beginning-of-dblock))
11111 (org-update-dblock)))
11113 (defun org-update-dblock ()
11114 "Update the dynamic block at point.
11115 This means to empty the block, parse for parameters and then call
11116 the correct writing function."
11117 (interactive)
11118 (save-window-excursion
11119 (let* ((pos (point))
11120 (line (org-current-line))
11121 (params (org-prepare-dblock))
11122 (name (plist-get params :name))
11123 (indent (plist-get params :indentation-column))
11124 (cmd (intern (concat "org-dblock-write:" name))))
11125 (message "Updating dynamic block `%s' at line %d..." name line)
11126 (funcall cmd params)
11127 (message "Updating dynamic block `%s' at line %d...done" name line)
11128 (goto-char pos)
11129 (when (and indent (> indent 0))
11130 (setq indent (make-string indent ?\ ))
11131 (save-excursion
11132 (org-beginning-of-dblock)
11133 (forward-line 1)
11134 (while (not (looking-at org-dblock-end-re))
11135 (insert indent)
11136 (beginning-of-line 2))
11137 (when (looking-at org-dblock-end-re)
11138 (and (looking-at "[ \t]+")
11139 (replace-match ""))
11140 (insert indent)))))))
11142 (defun org-beginning-of-dblock ()
11143 "Find the beginning of the dynamic block at point.
11144 Error if there is no such block at point."
11145 (let ((pos (point))
11146 beg)
11147 (end-of-line 1)
11148 (if (and (re-search-backward org-dblock-start-re nil t)
11149 (setq beg (match-beginning 0))
11150 (re-search-forward org-dblock-end-re nil t)
11151 (> (match-end 0) pos))
11152 (goto-char beg)
11153 (goto-char pos)
11154 (error "Not in a dynamic block"))))
11156 ;;;###autoload
11157 (defun org-update-all-dblocks ()
11158 "Update all dynamic blocks in the buffer.
11159 This function can be used in a hook."
11160 (interactive)
11161 (when (derived-mode-p 'org-mode)
11162 (org-map-dblocks 'org-update-dblock)))
11165 ;;;; Completion
11167 (defconst org-additional-option-like-keywords
11168 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11169 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11170 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11171 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11172 "BEGIN:" "END:"
11173 "ORGTBL" "TBLFM:" "TBLNAME:"
11174 "BEGIN_EXAMPLE" "END_EXAMPLE"
11175 "BEGIN_QUOTE" "END_QUOTE"
11176 "BEGIN_VERSE" "END_VERSE"
11177 "BEGIN_CENTER" "END_CENTER"
11178 "BEGIN_SRC" "END_SRC"
11179 "BEGIN_RESULT" "END_RESULT"
11180 "NAME:" "RESULTS:"
11181 "HEADER:" "HEADERS:"
11182 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11183 "CAPTION:" "LABEL:"
11184 "SETUPFILE:"
11185 "INCLUDE:"
11186 "BIND:"
11187 "MACRO:"))
11189 (defcustom org-structure-template-alist
11191 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11192 "<src lang=\"?\">\n\n</src>")
11193 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11194 "<example>\n?\n</example>")
11195 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11196 "<quote>\n?\n</quote>")
11197 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11198 "<verse>\n?\n</verse>")
11199 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11200 "<center>\n?\n</center>")
11201 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11202 "<literal style=\"latex\">\n?\n</literal>")
11203 ("L" "#+LaTeX: "
11204 "<literal style=\"latex\">?</literal>")
11205 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11206 "<literal style=\"html\">\n?\n</literal>")
11207 ("H" "#+HTML: "
11208 "<literal style=\"html\">?</literal>")
11209 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11210 ("A" "#+ASCII: ")
11211 ("i" "#+INDEX: ?"
11212 "#+INDEX: ?")
11213 ("I" "#+INCLUDE %file ?"
11214 "<include file=%file markup=\"?\">")
11216 "Structure completion elements.
11217 This is a list of abbreviation keys and values. The value gets inserted
11218 if you type `<' followed by the key and then press the completion key,
11219 usually `M-TAB'. %file will be replaced by a file name after prompting
11220 for the file using completion. The cursor will be placed at the position
11221 of the `?` in the template.
11222 There are two templates for each key, the first uses the original Org syntax,
11223 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11224 the default when the /org-mtags.el/ module has been loaded. See also the
11225 variable `org-mtags-prefer-muse-templates'."
11226 :group 'org-completion
11227 :type '(repeat
11228 (string :tag "Key")
11229 (string :tag "Template")
11230 (string :tag "Muse Template")))
11232 (defun org-try-structure-completion ()
11233 "Try to complete a structure template before point.
11234 This looks for strings like \"<e\" on an otherwise empty line and
11235 expands them."
11236 (let ((l (buffer-substring (point-at-bol) (point)))
11238 (when (and (looking-at "[ \t]*$")
11239 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11240 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11241 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11242 (match-beginning 1)) a)
11243 t)))
11245 (defun org-complete-expand-structure-template (start cell)
11246 "Expand a structure template."
11247 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11248 (rpl (nth (if musep 2 1) cell))
11249 (ind ""))
11250 (delete-region start (point))
11251 (when (string-match "\\`#\\+" rpl)
11252 (cond
11253 ((bolp))
11254 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11255 (setq ind (buffer-substring (point-at-bol) (point))))
11256 (t (newline))))
11257 (setq start (point))
11258 (if (string-match "%file" rpl)
11259 (setq rpl (replace-match
11260 (concat
11261 "\""
11262 (save-match-data
11263 (abbreviate-file-name (read-file-name "Include file: ")))
11264 "\"")
11265 t t rpl)))
11266 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11267 (concat "\n" ind)))
11268 (insert rpl)
11269 (if (re-search-backward "\\?" start t) (delete-char 1))))
11271 ;;;; TODO, DEADLINE, Comments
11273 (defun org-toggle-comment ()
11274 "Change the COMMENT state of an entry."
11275 (interactive)
11276 (save-excursion
11277 (org-back-to-heading)
11278 (let (case-fold-search)
11279 (cond
11280 ((looking-at (format org-heading-keyword-regexp-format
11281 org-comment-string))
11282 (goto-char (match-end 1))
11283 (looking-at (concat " +" org-comment-string))
11284 (replace-match "" t t)
11285 (when (eolp) (insert " ")))
11286 ((looking-at org-outline-regexp)
11287 (goto-char (match-end 0))
11288 (insert org-comment-string " "))))))
11290 (defvar org-last-todo-state-is-todo nil
11291 "This is non-nil when the last TODO state change led to a TODO state.
11292 If the last change removed the TODO tag or switched to DONE, then
11293 this is nil.")
11295 (defvar org-setting-tags nil) ; dynamically skipped
11297 (defvar org-todo-setup-filter-hook nil
11298 "Hook for functions that pre-filter todo specs.
11299 Each function takes a todo spec and returns either nil or the spec
11300 transformed into canonical form." )
11302 (defvar org-todo-get-default-hook nil
11303 "Hook for functions that get a default item for todo.
11304 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11305 nil or a string to be used for the todo mark." )
11307 (defvar org-agenda-headline-snapshot-before-repeat)
11309 (defun org-current-effective-time ()
11310 "Return current time adjusted for `org-extend-today-until' variable"
11311 (let* ((ct (org-current-time))
11312 (dct (decode-time ct))
11313 (ct1
11314 (if (and org-use-effective-time
11315 (< (nth 2 dct) org-extend-today-until))
11316 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11317 ct)))
11318 ct1))
11320 (defun org-todo-yesterday (&optional arg)
11321 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11322 (interactive "P")
11323 (if (eq major-mode 'org-agenda-mode)
11324 (apply 'org-agenda-todo-yesterday arg)
11325 (let* ((hour (third (decode-time
11326 (org-current-time))))
11327 (org-extend-today-until (1+ hour)))
11328 (org-todo arg))))
11330 (defun org-todo (&optional arg)
11331 "Change the TODO state of an item.
11332 The state of an item is given by a keyword at the start of the heading,
11333 like
11334 *** TODO Write paper
11335 *** DONE Call mom
11337 The different keywords are specified in the variable `org-todo-keywords'.
11338 By default the available states are \"TODO\" and \"DONE\".
11339 So for this example: when the item starts with TODO, it is changed to DONE.
11340 When it starts with DONE, the DONE is removed. And when neither TODO nor
11341 DONE are present, add TODO at the beginning of the heading.
11343 With \\[universal-argument] prefix arg, use completion to determine the new \
11344 state.
11345 With numeric prefix arg, switch to that state.
11346 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11347 keywords (nextset).
11348 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11349 With a numeric prefix arg of 0, inhibit note taking for the change.
11351 For calling through lisp, arg is also interpreted in the following way:
11352 'none -> empty state
11353 \"\"(empty string) -> switch to empty state
11354 'done -> switch to DONE
11355 'nextset -> switch to the next set of keywords
11356 'previousset -> switch to the previous set of keywords
11357 \"WAITING\" -> switch to the specified keyword, but only if it
11358 really is a member of `org-todo-keywords'."
11359 (interactive "P")
11360 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11361 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11362 'region-start-level 'region))
11363 org-loop-over-headlines-in-active-region)
11364 (org-map-entries
11365 `(org-todo ,arg)
11366 org-loop-over-headlines-in-active-region
11367 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11368 (if (equal arg '(16)) (setq arg 'nextset))
11369 (let ((org-blocker-hook org-blocker-hook)
11370 (case-fold-search nil))
11371 (when (equal arg '(64))
11372 (setq arg nil org-blocker-hook nil))
11373 (when (and org-blocker-hook
11374 (or org-inhibit-blocking
11375 (org-entry-get nil "NOBLOCKING")))
11376 (setq org-blocker-hook nil))
11377 (save-excursion
11378 (catch 'exit
11379 (org-back-to-heading t)
11380 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11381 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11382 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11383 (let* ((match-data (match-data))
11384 (startpos (point-at-bol))
11385 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11386 (org-log-done org-log-done)
11387 (org-log-repeat org-log-repeat)
11388 (org-todo-log-states org-todo-log-states)
11389 (org-inhibit-logging
11390 (if (equal arg 0)
11391 (progn (setq arg nil) 'note) org-inhibit-logging))
11392 (this (match-string 1))
11393 (hl-pos (match-beginning 0))
11394 (head (org-get-todo-sequence-head this))
11395 (ass (assoc head org-todo-kwd-alist))
11396 (interpret (nth 1 ass))
11397 (done-word (nth 3 ass))
11398 (final-done-word (nth 4 ass))
11399 (org-last-state (or this ""))
11400 (completion-ignore-case t)
11401 (member (member this org-todo-keywords-1))
11402 (tail (cdr member))
11403 (org-state (cond
11404 ((and org-todo-key-trigger
11405 (or (and (equal arg '(4))
11406 (eq org-use-fast-todo-selection 'prefix))
11407 (and (not arg) org-use-fast-todo-selection
11408 (not (eq org-use-fast-todo-selection
11409 'prefix)))))
11410 ;; Use fast selection
11411 (org-fast-todo-selection))
11412 ((and (equal arg '(4))
11413 (or (not org-use-fast-todo-selection)
11414 (not org-todo-key-trigger)))
11415 ;; Read a state with completion
11416 (org-icompleting-read
11417 "State: " (mapcar (lambda(x) (list x))
11418 org-todo-keywords-1)
11419 nil t))
11420 ((eq arg 'right)
11421 (if this
11422 (if tail (car tail) nil)
11423 (car org-todo-keywords-1)))
11424 ((eq arg 'left)
11425 (if (equal member org-todo-keywords-1)
11427 (if this
11428 (nth (- (length org-todo-keywords-1)
11429 (length tail) 2)
11430 org-todo-keywords-1)
11431 (org-last org-todo-keywords-1))))
11432 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11433 (setq arg nil))) ; hack to fall back to cycling
11434 (arg
11435 ;; user or caller requests a specific state
11436 (cond
11437 ((equal arg "") nil)
11438 ((eq arg 'none) nil)
11439 ((eq arg 'done) (or done-word (car org-done-keywords)))
11440 ((eq arg 'nextset)
11441 (or (car (cdr (member head org-todo-heads)))
11442 (car org-todo-heads)))
11443 ((eq arg 'previousset)
11444 (let ((org-todo-heads (reverse org-todo-heads)))
11445 (or (car (cdr (member head org-todo-heads)))
11446 (car org-todo-heads))))
11447 ((car (member arg org-todo-keywords-1)))
11448 ((stringp arg)
11449 (error "State `%s' not valid in this file" arg))
11450 ((nth (1- (prefix-numeric-value arg))
11451 org-todo-keywords-1))))
11452 ((null member) (or head (car org-todo-keywords-1)))
11453 ((equal this final-done-word) nil) ;; -> make empty
11454 ((null tail) nil) ;; -> first entry
11455 ((memq interpret '(type priority))
11456 (if (eq this-command last-command)
11457 (car tail)
11458 (if (> (length tail) 0)
11459 (or done-word (car org-done-keywords))
11460 nil)))
11462 (car tail))))
11463 (org-state (or
11464 (run-hook-with-args-until-success
11465 'org-todo-get-default-hook org-state org-last-state)
11466 org-state))
11467 (next (if org-state (concat " " org-state " ") " "))
11468 (change-plist (list :type 'todo-state-change :from this :to org-state
11469 :position startpos))
11470 dolog now-done-p)
11471 (when org-blocker-hook
11472 (setq org-last-todo-state-is-todo
11473 (not (member this org-done-keywords)))
11474 (unless (save-excursion
11475 (save-match-data
11476 (org-with-wide-buffer
11477 (run-hook-with-args-until-failure
11478 'org-blocker-hook change-plist))))
11479 (if (org-called-interactively-p 'interactive)
11480 (error "TODO state change from %s to %s blocked" this org-state)
11481 ;; fail silently
11482 (message "TODO state change from %s to %s blocked" this org-state)
11483 (throw 'exit nil))))
11484 (store-match-data match-data)
11485 (replace-match next t t)
11486 (unless (pos-visible-in-window-p hl-pos)
11487 (message "TODO state changed to %s" (org-trim next)))
11488 (unless head
11489 (setq head (org-get-todo-sequence-head org-state)
11490 ass (assoc head org-todo-kwd-alist)
11491 interpret (nth 1 ass)
11492 done-word (nth 3 ass)
11493 final-done-word (nth 4 ass)))
11494 (when (memq arg '(nextset previousset))
11495 (message "Keyword-Set %d/%d: %s"
11496 (- (length org-todo-sets) -1
11497 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11498 (length org-todo-sets)
11499 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11500 (setq org-last-todo-state-is-todo
11501 (not (member org-state org-done-keywords)))
11502 (setq now-done-p (and (member org-state org-done-keywords)
11503 (not (member this org-done-keywords))))
11504 (and logging (org-local-logging logging))
11505 (when (and (or org-todo-log-states org-log-done)
11506 (not (eq org-inhibit-logging t))
11507 (not (memq arg '(nextset previousset))))
11508 ;; we need to look at recording a time and note
11509 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11510 (nth 2 (assoc this org-todo-log-states))))
11511 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11512 (setq dolog 'time))
11513 (when (and org-state
11514 (member org-state org-not-done-keywords)
11515 (not (member this org-not-done-keywords)))
11516 ;; This is now a todo state and was not one before
11517 ;; If there was a CLOSED time stamp, get rid of it.
11518 (org-add-planning-info nil nil 'closed))
11519 (when (and now-done-p org-log-done)
11520 ;; It is now done, and it was not done before
11521 (org-add-planning-info 'closed (org-current-effective-time))
11522 (if (and (not dolog) (eq 'note org-log-done))
11523 (org-add-log-setup 'done org-state this 'findpos 'note)))
11524 (when (and org-state dolog)
11525 ;; This is a non-nil state, and we need to log it
11526 (org-add-log-setup 'state org-state this 'findpos dolog)))
11527 ;; Fixup tag positioning
11528 (org-todo-trigger-tag-changes org-state)
11529 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11530 (when org-provide-todo-statistics
11531 (org-update-parent-todo-statistics))
11532 (run-hooks 'org-after-todo-state-change-hook)
11533 (if (and arg (not (member org-state org-done-keywords)))
11534 (setq head (org-get-todo-sequence-head org-state)))
11535 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11536 ;; Do we need to trigger a repeat?
11537 (when now-done-p
11538 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11539 ;; This is for the agenda, take a snapshot of the headline.
11540 (save-match-data
11541 (setq org-agenda-headline-snapshot-before-repeat
11542 (org-get-heading))))
11543 (org-auto-repeat-maybe org-state))
11544 ;; Fixup cursor location if close to the keyword
11545 (if (and (outline-on-heading-p)
11546 (not (bolp))
11547 (save-excursion (beginning-of-line 1)
11548 (looking-at org-todo-line-regexp))
11549 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11550 (progn
11551 (goto-char (or (match-end 2) (match-end 1)))
11552 (and (looking-at " ") (just-one-space))))
11553 (when org-trigger-hook
11554 (save-excursion
11555 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11557 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11558 "Block turning an entry into a TODO, using the hierarchy.
11559 This checks whether the current task should be blocked from state
11560 changes. Such blocking occurs when:
11562 1. The task has children which are not all in a completed state.
11564 2. A task has a parent with the property :ORDERED:, and there
11565 are siblings prior to the current task with incomplete
11566 status.
11568 3. The parent of the task is blocked because it has siblings that should
11569 be done first, or is child of a block grandparent TODO entry."
11571 (if (not org-enforce-todo-dependencies)
11572 t ; if locally turned off don't block
11573 (catch 'dont-block
11574 ;; If this is not a todo state change, or if this entry is already DONE,
11575 ;; do not block
11576 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11577 (member (plist-get change-plist :from)
11578 (cons 'done org-done-keywords))
11579 (member (plist-get change-plist :to)
11580 (cons 'todo org-not-done-keywords))
11581 (not (plist-get change-plist :to)))
11582 (throw 'dont-block t))
11583 ;; If this task has children, and any are undone, it's blocked
11584 (save-excursion
11585 (org-back-to-heading t)
11586 (let ((this-level (funcall outline-level)))
11587 (outline-next-heading)
11588 (let ((child-level (funcall outline-level)))
11589 (while (and (not (eobp))
11590 (> child-level this-level))
11591 ;; this todo has children, check whether they are all
11592 ;; completed
11593 (if (and (not (org-entry-is-done-p))
11594 (org-entry-is-todo-p))
11595 (throw 'dont-block nil))
11596 (outline-next-heading)
11597 (setq child-level (funcall outline-level))))))
11598 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11599 ;; any previous siblings are undone, it's blocked
11600 (save-excursion
11601 (org-back-to-heading t)
11602 (let* ((pos (point))
11603 (parent-pos (and (org-up-heading-safe) (point))))
11604 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11605 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11606 (forward-line 1)
11607 (re-search-forward org-not-done-heading-regexp pos t))
11608 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11609 ;; Search further up the hierarchy, to see if an ancestor is blocked
11610 (while t
11611 (goto-char parent-pos)
11612 (if (not (looking-at org-not-done-heading-regexp))
11613 (throw 'dont-block t)) ; do not block, parent is not a TODO
11614 (setq pos (point))
11615 (setq parent-pos (and (org-up-heading-safe) (point)))
11616 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11617 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11618 (forward-line 1)
11619 (re-search-forward org-not-done-heading-regexp pos t))
11620 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11622 (defcustom org-track-ordered-property-with-tag nil
11623 "Should the ORDERED property also be shown as a tag?
11624 The ORDERED property decides if an entry should require subtasks to be
11625 completed in sequence. Since a property is not very visible, setting
11626 this option means that toggling the ORDERED property with the command
11627 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11628 not relevant for the behavior, but it makes things more visible.
11630 Note that toggling the tag with tags commands will not change the property
11631 and therefore not influence behavior!
11633 This can be t, meaning the tag ORDERED should be used, It can also be a
11634 string to select a different tag for this task."
11635 :group 'org-todo
11636 :type '(choice
11637 (const :tag "No tracking" nil)
11638 (const :tag "Track with ORDERED tag" t)
11639 (string :tag "Use other tag")))
11641 (defun org-toggle-ordered-property ()
11642 "Toggle the ORDERED property of the current entry.
11643 For better visibility, you can track the value of this property with a tag.
11644 See variable `org-track-ordered-property-with-tag'."
11645 (interactive)
11646 (let* ((t1 org-track-ordered-property-with-tag)
11647 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11648 (save-excursion
11649 (org-back-to-heading)
11650 (if (org-entry-get nil "ORDERED")
11651 (progn
11652 (org-delete-property "ORDERED")
11653 (and tag (org-toggle-tag tag 'off))
11654 (message "Subtasks can be completed in arbitrary order"))
11655 (org-entry-put nil "ORDERED" "t")
11656 (and tag (org-toggle-tag tag 'on))
11657 (message "Subtasks must be completed in sequence")))))
11659 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11660 (defun org-block-todo-from-checkboxes (change-plist)
11661 "Block turning an entry into a TODO, using checkboxes.
11662 This checks whether the current task should be blocked from state
11663 changes because there are unchecked boxes in this entry."
11664 (if (not org-enforce-todo-checkbox-dependencies)
11665 t ; if locally turned off don't block
11666 (catch 'dont-block
11667 ;; If this is not a todo state change, or if this entry is already DONE,
11668 ;; do not block
11669 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11670 (member (plist-get change-plist :from)
11671 (cons 'done org-done-keywords))
11672 (member (plist-get change-plist :to)
11673 (cons 'todo org-not-done-keywords))
11674 (not (plist-get change-plist :to)))
11675 (throw 'dont-block t))
11676 ;; If this task has checkboxes that are not checked, it's blocked
11677 (save-excursion
11678 (org-back-to-heading t)
11679 (let ((beg (point)) end)
11680 (outline-next-heading)
11681 (setq end (point))
11682 (goto-char beg)
11683 (if (org-list-search-forward
11684 (concat (org-item-beginning-re)
11685 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11686 "\\[[- ]\\]")
11687 end t)
11688 (progn
11689 (if (boundp 'org-blocked-by-checkboxes)
11690 (setq org-blocked-by-checkboxes t))
11691 (throw 'dont-block nil)))))
11692 t))) ; do not block
11694 (defun org-entry-blocked-p ()
11695 "Is the current entry blocked?"
11696 (if (org-entry-get nil "NOBLOCKING")
11697 nil ;; Never block this entry
11698 (not
11699 (run-hook-with-args-until-failure
11700 'org-blocker-hook
11701 (list :type 'todo-state-change
11702 :position (point)
11703 :from 'todo
11704 :to 'done)))))
11706 (defun org-update-statistics-cookies (all)
11707 "Update the statistics cookie, either from TODO or from checkboxes.
11708 This should be called with the cursor in a line with a statistics cookie."
11709 (interactive "P")
11710 (if all
11711 (progn
11712 (org-update-checkbox-count 'all)
11713 (org-map-entries 'org-update-parent-todo-statistics))
11714 (if (not (org-at-heading-p))
11715 (org-update-checkbox-count)
11716 (let ((pos (move-marker (make-marker) (point)))
11717 end l1 l2)
11718 (ignore-errors (org-back-to-heading t))
11719 (if (not (org-at-heading-p))
11720 (org-update-checkbox-count)
11721 (setq l1 (org-outline-level))
11722 (setq end (save-excursion
11723 (outline-next-heading)
11724 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11725 (point)))
11726 (if (and (save-excursion
11727 (re-search-forward
11728 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11729 (not (save-excursion (re-search-forward
11730 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11731 (org-update-checkbox-count)
11732 (if (and l2 (> l2 l1))
11733 (progn
11734 (goto-char end)
11735 (org-update-parent-todo-statistics))
11736 (goto-char pos)
11737 (beginning-of-line 1)
11738 (while (re-search-forward
11739 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11740 (point-at-eol) t)
11741 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11742 (goto-char pos)
11743 (move-marker pos nil)))))
11745 (defvar org-entry-property-inherited-from) ;; defined below
11746 (defun org-update-parent-todo-statistics ()
11747 "Update any statistics cookie in the parent of the current headline.
11748 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11749 the entire subtree and this will travel up the hierarchy and update
11750 statistics everywhere."
11751 (let* ((prop (save-excursion (org-up-heading-safe)
11752 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11753 (recursive (or (not org-hierarchical-todo-statistics)
11754 (and prop (string-match "\\<recursive\\>" prop))))
11755 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11757 (first t)
11758 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11759 level ltoggle l1 new ndel
11760 (cnt-all 0) (cnt-done 0) is-percent kwd
11761 checkbox-beg ov ovs ove cookie-present)
11762 (catch 'exit
11763 (save-excursion
11764 (beginning-of-line 1)
11765 (setq ltoggle (funcall outline-level))
11766 ;; Three situations are to consider:
11768 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11769 ;; to the top-level ancestor on the headline;
11771 ;; 2. If parent has "recursive" property, repeat up to the
11772 ;; headline setting that property, taking inheritance into
11773 ;; account;
11775 ;; 3. Else, move up to direct parent and proceed only once.
11776 (while (and (setq level (org-up-heading-safe))
11777 (or recursive first)
11778 (>= (point) lim))
11779 (setq first nil cookie-present nil)
11780 (unless (and level
11781 (not (string-match
11782 "\\<checkbox\\>"
11783 (downcase (or (org-entry-get nil "COOKIE_DATA")
11784 "")))))
11785 (throw 'exit nil))
11786 (while (re-search-forward box-re (point-at-eol) t)
11787 (setq cnt-all 0 cnt-done 0 cookie-present t)
11788 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11789 (save-match-data
11790 (unless (outline-next-heading) (throw 'exit nil))
11791 (while (and (looking-at org-complex-heading-regexp)
11792 (> (setq l1 (length (match-string 1))) level))
11793 (setq kwd (and (or recursive (= l1 ltoggle))
11794 (match-string 2)))
11795 (if (or (eq org-provide-todo-statistics 'all-headlines)
11796 (and (listp org-provide-todo-statistics)
11797 (or (member kwd org-provide-todo-statistics)
11798 (member kwd org-done-keywords))))
11799 (setq cnt-all (1+ cnt-all))
11800 (if (eq org-provide-todo-statistics t)
11801 (and kwd (setq cnt-all (1+ cnt-all)))))
11802 (and (member kwd org-done-keywords)
11803 (setq cnt-done (1+ cnt-done)))
11804 (outline-next-heading)))
11805 (setq new
11806 (if is-percent
11807 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11808 (format "[%d/%d]" cnt-done cnt-all))
11809 ndel (- (match-end 0) checkbox-beg))
11810 ;; handle overlays when updating cookie from column view
11811 (when (setq ov (car (overlays-at checkbox-beg)))
11812 (setq ovs (overlay-start ov) ove (overlay-end ov))
11813 (delete-overlay ov))
11814 (goto-char checkbox-beg)
11815 (insert new)
11816 (delete-region (point) (+ (point) ndel))
11817 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11818 (when ov (move-overlay ov ovs ove)))
11819 (when cookie-present
11820 (run-hook-with-args 'org-after-todo-statistics-hook
11821 cnt-done (- cnt-all cnt-done))))))
11822 (run-hooks 'org-todo-statistics-hook)))
11824 (defvar org-after-todo-statistics-hook nil
11825 "Hook that is called after a TODO statistics cookie has been updated.
11826 Each function is called with two arguments: the number of not-done entries
11827 and the number of done entries.
11829 For example, the following function, when added to this hook, will switch
11830 an entry to DONE when all children are done, and back to TODO when new
11831 entries are set to a TODO status. Note that this hook is only called
11832 when there is a statistics cookie in the headline!
11834 (defun org-summary-todo (n-done n-not-done)
11835 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11836 (let (org-log-done org-log-states) ; turn off logging
11837 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11840 (defvar org-todo-statistics-hook nil
11841 "Hook that is run whenever Org thinks TODO statistics should be updated.
11842 This hook runs even if there is no statistics cookie present, in which case
11843 `org-after-todo-statistics-hook' would not run.")
11845 (defun org-todo-trigger-tag-changes (state)
11846 "Apply the changes defined in `org-todo-state-tags-triggers'."
11847 (let ((l org-todo-state-tags-triggers)
11848 changes)
11849 (when (or (not state) (equal state ""))
11850 (setq changes (append changes (cdr (assoc "" l)))))
11851 (when (and (stringp state) (> (length state) 0))
11852 (setq changes (append changes (cdr (assoc state l)))))
11853 (when (member state org-not-done-keywords)
11854 (setq changes (append changes (cdr (assoc 'todo l)))))
11855 (when (member state org-done-keywords)
11856 (setq changes (append changes (cdr (assoc 'done l)))))
11857 (dolist (c changes)
11858 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11860 (defun org-local-logging (value)
11861 "Get logging settings from a property VALUE."
11862 (let* (words w a)
11863 ;; directly set the variables, they are already local.
11864 (setq org-log-done nil
11865 org-log-repeat nil
11866 org-todo-log-states nil)
11867 (setq words (org-split-string value))
11868 (while (setq w (pop words))
11869 (cond
11870 ((setq a (assoc w org-startup-options))
11871 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11872 (set (nth 1 a) (nth 2 a))))
11873 ((setq a (org-extract-log-state-settings w))
11874 (and (member (car a) org-todo-keywords-1)
11875 (push a org-todo-log-states)))))))
11877 (defun org-get-todo-sequence-head (kwd)
11878 "Return the head of the TODO sequence to which KWD belongs.
11879 If KWD is not set, check if there is a text property remembering the
11880 right sequence."
11881 (let (p)
11882 (cond
11883 ((not kwd)
11884 (or (get-text-property (point-at-bol) 'org-todo-head)
11885 (progn
11886 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11887 nil (point-at-eol)))
11888 (get-text-property p 'org-todo-head))))
11889 ((not (member kwd org-todo-keywords-1))
11890 (car org-todo-keywords-1))
11891 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11893 (defun org-fast-todo-selection ()
11894 "Fast TODO keyword selection with single keys.
11895 Returns the new TODO keyword, or nil if no state change should occur."
11896 (let* ((fulltable org-todo-key-alist)
11897 (done-keywords org-done-keywords) ;; needed for the faces.
11898 (maxlen (apply 'max (mapcar
11899 (lambda (x)
11900 (if (stringp (car x)) (string-width (car x)) 0))
11901 fulltable)))
11902 (expert nil)
11903 (fwidth (+ maxlen 3 1 3))
11904 (ncol (/ (- (window-width) 4) fwidth))
11905 tg cnt e c tbl
11906 groups ingroup)
11907 (save-excursion
11908 (save-window-excursion
11909 (if expert
11910 (set-buffer (get-buffer-create " *Org todo*"))
11911 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11912 (erase-buffer)
11913 (org-set-local 'org-done-keywords done-keywords)
11914 (setq tbl fulltable cnt 0)
11915 (while (setq e (pop tbl))
11916 (cond
11917 ((equal e '(:startgroup))
11918 (push '() groups) (setq ingroup t)
11919 (when (not (= cnt 0))
11920 (setq cnt 0)
11921 (insert "\n"))
11922 (insert "{ "))
11923 ((equal e '(:endgroup))
11924 (setq ingroup nil cnt 0)
11925 (insert "}\n"))
11926 ((equal e '(:newline))
11927 (when (not (= cnt 0))
11928 (setq cnt 0)
11929 (insert "\n")
11930 (setq e (car tbl))
11931 (while (equal (car tbl) '(:newline))
11932 (insert "\n")
11933 (setq tbl (cdr tbl)))))
11935 (setq tg (car e) c (cdr e))
11936 (if ingroup (push tg (car groups)))
11937 (setq tg (org-add-props tg nil 'face
11938 (org-get-todo-face tg)))
11939 (if (and (= cnt 0) (not ingroup)) (insert " "))
11940 (insert "[" c "] " tg (make-string
11941 (- fwidth 4 (length tg)) ?\ ))
11942 (when (= (setq cnt (1+ cnt)) ncol)
11943 (insert "\n")
11944 (if ingroup (insert " "))
11945 (setq cnt 0)))))
11946 (insert "\n")
11947 (goto-char (point-min))
11948 (if (not expert) (org-fit-window-to-buffer))
11949 (message "[a-z..]:Set [SPC]:clear")
11950 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11951 (cond
11952 ((or (= c ?\C-g)
11953 (and (= c ?q) (not (rassoc c fulltable))))
11954 (setq quit-flag t))
11955 ((= c ?\ ) nil)
11956 ((setq e (rassoc c fulltable) tg (car e))
11958 (t (setq quit-flag t)))))))
11960 (defun org-entry-is-todo-p ()
11961 (member (org-get-todo-state) org-not-done-keywords))
11963 (defun org-entry-is-done-p ()
11964 (member (org-get-todo-state) org-done-keywords))
11966 (defun org-get-todo-state ()
11967 (save-excursion
11968 (org-back-to-heading t)
11969 (and (looking-at org-todo-line-regexp)
11970 (match-end 2)
11971 (match-string 2))))
11973 (defun org-at-date-range-p (&optional inactive-ok)
11974 "Is the cursor inside a date range?"
11975 (interactive)
11976 (save-excursion
11977 (catch 'exit
11978 (let ((pos (point)))
11979 (skip-chars-backward "^[<\r\n")
11980 (skip-chars-backward "<[")
11981 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11982 (>= (match-end 0) pos)
11983 (throw 'exit t))
11984 (skip-chars-backward "^<[\r\n")
11985 (skip-chars-backward "<[")
11986 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11987 (>= (match-end 0) pos)
11988 (throw 'exit t)))
11989 nil)))
11991 (defun org-get-repeat (&optional tagline)
11992 "Check if there is a deadline/schedule with repeater in this entry."
11993 (save-match-data
11994 (save-excursion
11995 (org-back-to-heading t)
11996 (and (re-search-forward (if tagline
11997 (concat tagline "\\s-*" org-repeat-re)
11998 org-repeat-re)
11999 (org-entry-end-position) t)
12000 (match-string-no-properties 1)))))
12002 (defvar org-last-changed-timestamp)
12003 (defvar org-last-inserted-timestamp)
12004 (defvar org-log-post-message)
12005 (defvar org-log-note-purpose)
12006 (defvar org-log-note-how)
12007 (defvar org-log-note-extra)
12008 (defun org-auto-repeat-maybe (done-word)
12009 "Check if the current headline contains a repeated deadline/schedule.
12010 If yes, set TODO state back to what it was and change the base date
12011 of repeating deadline/scheduled time stamps to new date.
12012 This function is run automatically after each state change to a DONE state."
12013 ;; last-state is dynamically scoped into this function
12014 (let* ((repeat (org-get-repeat))
12015 (aa (assoc org-last-state org-todo-kwd-alist))
12016 (interpret (nth 1 aa))
12017 (head (nth 2 aa))
12018 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12019 (msg "Entry repeats: ")
12020 (org-log-done nil)
12021 (org-todo-log-states nil)
12022 re type n what ts time to-state)
12023 (when repeat
12024 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12025 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12026 org-todo-repeat-to-state))
12027 (unless (and to-state (member to-state org-todo-keywords-1))
12028 (setq to-state (if (eq interpret 'type) org-last-state head)))
12029 (org-todo to-state)
12030 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12031 (org-entry-put nil "LAST_REPEAT" (format-time-string
12032 (org-time-stamp-format t t))))
12033 (when org-log-repeat
12034 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12035 (memq 'org-add-log-note post-command-hook))
12036 ;; OK, we are already setup for some record
12037 (if (eq org-log-repeat 'note)
12038 ;; make sure we take a note, not only a time stamp
12039 (setq org-log-note-how 'note))
12040 ;; Set up for taking a record
12041 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12042 org-last-state
12043 'findpos org-log-repeat)))
12044 (org-back-to-heading t)
12045 (org-add-planning-info nil nil 'closed)
12046 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12047 org-deadline-time-regexp "\\)\\|\\("
12048 org-ts-regexp "\\)"))
12049 (while (re-search-forward
12050 re (save-excursion (outline-next-heading) (point)) t)
12051 (setq type (if (match-end 1) org-scheduled-string
12052 (if (match-end 3) org-deadline-string "Plain:"))
12053 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12054 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12055 (setq n (string-to-number (match-string 2 ts))
12056 what (match-string 3 ts))
12057 (if (equal what "w") (setq n (* n 7) what "d"))
12058 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12059 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12060 ;; Preparation, see if we need to modify the start date for the change
12061 (when (match-end 1)
12062 (setq time (save-match-data (org-time-string-to-time ts)))
12063 (cond
12064 ((equal (match-string 1 ts) ".")
12065 ;; Shift starting date to today
12066 (org-timestamp-change
12067 (- (org-today) (time-to-days time))
12068 'day))
12069 ((equal (match-string 1 ts) "+")
12070 (let ((nshiftmax 10) (nshift 0))
12071 (while (or (= nshift 0)
12072 (<= (time-to-days time)
12073 (time-to-days (current-time))))
12074 (when (= (incf nshift) nshiftmax)
12075 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12076 (error "Abort")))
12077 (org-timestamp-change n (cdr (assoc what whata)))
12078 (org-at-timestamp-p t)
12079 (setq ts (match-string 1))
12080 (setq time (save-match-data (org-time-string-to-time ts)))))
12081 (org-timestamp-change (- n) (cdr (assoc what whata)))
12082 ;; rematch, so that we have everything in place for the real shift
12083 (org-at-timestamp-p t)
12084 (setq ts (match-string 1))
12085 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12086 (org-timestamp-change n (cdr (assoc what whata)))
12087 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12088 (setq org-log-post-message msg)
12089 (message "%s" msg))))
12091 (defun org-show-todo-tree (arg)
12092 "Make a compact tree which shows all headlines marked with TODO.
12093 The tree will show the lines where the regexp matches, and all higher
12094 headlines above the match.
12095 With a \\[universal-argument] prefix, prompt for a regexp to match.
12096 With a numeric prefix N, construct a sparse tree for the Nth element
12097 of `org-todo-keywords-1'."
12098 (interactive "P")
12099 (let ((case-fold-search nil)
12100 (kwd-re
12101 (cond ((null arg) org-not-done-regexp)
12102 ((equal arg '(4))
12103 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12104 (mapcar 'list org-todo-keywords-1))))
12105 (concat "\\("
12106 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12107 "\\)\\>")))
12108 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12109 (regexp-quote (nth (1- (prefix-numeric-value arg))
12110 org-todo-keywords-1)))
12111 (t (error "Invalid prefix argument: %s" arg)))))
12112 (message "%d TODO entries found"
12113 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12115 (defun org-deadline (&optional remove time)
12116 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12117 With argument REMOVE, remove any deadline from the item.
12118 With argument TIME, set the deadline at the corresponding date. TIME
12119 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12120 (interactive "P")
12121 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12122 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12123 'region-start-level 'region))
12124 org-loop-over-headlines-in-active-region)
12125 (org-map-entries
12126 `(org-deadline ',remove ,time)
12127 org-loop-over-headlines-in-active-region
12128 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12129 (let* ((old-date (org-entry-get nil "DEADLINE"))
12130 (repeater (and old-date
12131 (string-match
12132 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12133 old-date)
12134 (match-string 1 old-date))))
12135 (if remove
12136 (progn
12137 (when (and old-date org-log-redeadline)
12138 (org-add-log-setup 'deldeadline nil old-date 'findpos
12139 org-log-redeadline))
12140 (org-remove-timestamp-with-keyword org-deadline-string)
12141 (message "Item no longer has a deadline."))
12142 (org-add-planning-info 'deadline time 'closed)
12143 (when (and old-date org-log-redeadline
12144 (not (equal old-date
12145 (substring org-last-inserted-timestamp 1 -1))))
12146 (org-add-log-setup 'redeadline nil old-date 'findpos
12147 org-log-redeadline))
12148 (when repeater
12149 (save-excursion
12150 (org-back-to-heading t)
12151 (when (re-search-forward (concat org-deadline-string " "
12152 org-last-inserted-timestamp)
12153 (save-excursion
12154 (outline-next-heading) (point)) t)
12155 (goto-char (1- (match-end 0)))
12156 (insert " " repeater)
12157 (setq org-last-inserted-timestamp
12158 (concat (substring org-last-inserted-timestamp 0 -1)
12159 " " repeater
12160 (substring org-last-inserted-timestamp -1))))))
12161 (message "Deadline on %s" org-last-inserted-timestamp)))))
12163 (defun org-schedule (&optional remove time)
12164 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12165 With argument REMOVE, remove any scheduling date from the item.
12166 With argument TIME, scheduled at the corresponding date. TIME can
12167 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12168 (interactive "P")
12169 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12170 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12171 'region-start-level 'region))
12172 org-loop-over-headlines-in-active-region)
12173 (org-map-entries
12174 `(org-schedule ',remove ,time)
12175 org-loop-over-headlines-in-active-region
12176 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12177 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12178 (repeater (and old-date
12179 (string-match
12180 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12181 old-date)
12182 (match-string 1 old-date))))
12183 (if remove
12184 (progn
12185 (when (and old-date org-log-reschedule)
12186 (org-add-log-setup 'delschedule nil old-date 'findpos
12187 org-log-reschedule))
12188 (org-remove-timestamp-with-keyword org-scheduled-string)
12189 (message "Item is no longer scheduled."))
12190 (org-add-planning-info 'scheduled time 'closed)
12191 (when (and old-date org-log-reschedule
12192 (not (equal old-date
12193 (substring org-last-inserted-timestamp 1 -1))))
12194 (org-add-log-setup 'reschedule nil old-date 'findpos
12195 org-log-reschedule))
12196 (when repeater
12197 (save-excursion
12198 (org-back-to-heading t)
12199 (when (re-search-forward (concat org-scheduled-string " "
12200 org-last-inserted-timestamp)
12201 (save-excursion
12202 (outline-next-heading) (point)) t)
12203 (goto-char (1- (match-end 0)))
12204 (insert " " repeater)
12205 (setq org-last-inserted-timestamp
12206 (concat (substring org-last-inserted-timestamp 0 -1)
12207 " " repeater
12208 (substring org-last-inserted-timestamp -1))))))
12209 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12211 (defun org-get-scheduled-time (pom &optional inherit)
12212 "Get the scheduled time as a time tuple, of a format suitable
12213 for calling org-schedule with, or if there is no scheduling,
12214 returns nil."
12215 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12216 (when time
12217 (apply 'encode-time (org-parse-time-string time)))))
12219 (defun org-get-deadline-time (pom &optional inherit)
12220 "Get the deadline as a time tuple, of a format suitable for
12221 calling org-deadline with, or if there is no scheduling, returns
12222 nil."
12223 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12224 (when time
12225 (apply 'encode-time (org-parse-time-string time)))))
12227 (defun org-remove-timestamp-with-keyword (keyword)
12228 "Remove all time stamps with KEYWORD in the current entry."
12229 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12230 beg)
12231 (save-excursion
12232 (org-back-to-heading t)
12233 (setq beg (point))
12234 (outline-next-heading)
12235 (while (re-search-backward re beg t)
12236 (replace-match "")
12237 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12238 (equal (char-before) ?\ ))
12239 (backward-delete-char 1)
12240 (if (string-match "^[ \t]*$" (buffer-substring
12241 (point-at-bol) (point-at-eol)))
12242 (delete-region (point-at-bol)
12243 (min (point-max) (1+ (point-at-eol))))))))))
12245 (defun org-add-planning-info (what &optional time &rest remove)
12246 "Insert new timestamp with keyword in the line directly after the headline.
12247 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12248 If non is given, the user is prompted for a date.
12249 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12250 be removed."
12251 (interactive)
12252 (let (org-time-was-given org-end-time-was-given ts
12253 end default-time default-input)
12255 (catch 'exit
12256 (when (and (memq what '(scheduled deadline))
12257 (or (not time)
12258 (and (stringp time)
12259 (string-match "^[-+]+[0-9]" time))))
12260 ;; Try to get a default date/time from existing timestamp
12261 (save-excursion
12262 (org-back-to-heading t)
12263 (setq end (save-excursion (outline-next-heading) (point)))
12264 (when (re-search-forward (if (eq what 'scheduled)
12265 org-scheduled-time-regexp
12266 org-deadline-time-regexp)
12267 end t)
12268 (setq ts (match-string 1)
12269 default-time
12270 (apply 'encode-time (org-parse-time-string ts))
12271 default-input (and ts (org-get-compact-tod ts))))))
12272 (when what
12273 (setq time
12274 (if (stringp time)
12275 ;; This is a string (relative or absolute), set proper date
12276 (apply 'encode-time
12277 (org-read-date-analyze
12278 time default-time (decode-time default-time)))
12279 ;; If necessary, get the time from the user
12280 (or time (org-read-date nil 'to-time nil nil
12281 default-time default-input)))))
12283 (when (and org-insert-labeled-timestamps-at-point
12284 (member what '(scheduled deadline)))
12285 (insert
12286 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12287 (org-insert-time-stamp time org-time-was-given
12288 nil nil nil (list org-end-time-was-given))
12289 (setq what nil))
12290 (save-excursion
12291 (save-restriction
12292 (let (col list elt ts buffer-invisibility-spec)
12293 (org-back-to-heading t)
12294 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12295 (goto-char (match-end 1))
12296 (setq col (current-column))
12297 (goto-char (match-end 0))
12298 (if (eobp) (insert "\n") (forward-char 1))
12299 (when (and (not what)
12300 (not (looking-at
12301 (concat "[ \t]*"
12302 org-keyword-time-not-clock-regexp))))
12303 ;; Nothing to add, nothing to remove...... :-)
12304 (throw 'exit nil))
12305 (if (and (not (looking-at org-outline-regexp))
12306 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12307 "[^\r\n]*"))
12308 (not (equal (match-string 1) org-clock-string)))
12309 (narrow-to-region (match-beginning 0) (match-end 0))
12310 (insert-before-markers "\n")
12311 (backward-char 1)
12312 (narrow-to-region (point) (point))
12313 (and org-adapt-indentation (org-indent-to-column col)))
12314 ;; Check if we have to remove something.
12315 (setq list (cons what remove))
12316 (while list
12317 (setq elt (pop list))
12318 (when (or (and (eq elt 'scheduled)
12319 (re-search-forward org-scheduled-time-regexp nil t))
12320 (and (eq elt 'deadline)
12321 (re-search-forward org-deadline-time-regexp nil t))
12322 (and (eq elt 'closed)
12323 (re-search-forward org-closed-time-regexp nil t)))
12324 (replace-match "")
12325 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12326 (and (looking-at "[ \t]+") (replace-match ""))
12327 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12328 (when what
12329 (insert
12330 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12331 (cond ((eq what 'scheduled) org-scheduled-string)
12332 ((eq what 'deadline) org-deadline-string)
12333 ((eq what 'closed) org-closed-string))
12334 " ")
12335 (setq ts (org-insert-time-stamp
12336 time
12337 (or org-time-was-given
12338 (and (eq what 'closed) org-log-done-with-time))
12339 (eq what 'closed)
12340 nil nil (list org-end-time-was-given)))
12341 (insert
12342 (if (not (or (bolp) (eq (char-before) ?\ )
12343 (memq (char-after) '(32 10))
12344 (eobp))) " " ""))
12345 (end-of-line 1))
12346 (goto-char (point-min))
12347 (widen)
12348 (if (and (looking-at "[ \t]*\n")
12349 (equal (char-before) ?\n))
12350 (delete-region (1- (point)) (point-at-eol)))
12351 ts))))))
12353 (defvar org-log-note-marker (make-marker))
12354 (defvar org-log-note-purpose nil)
12355 (defvar org-log-note-state nil)
12356 (defvar org-log-note-previous-state nil)
12357 (defvar org-log-note-how nil)
12358 (defvar org-log-note-extra nil)
12359 (defvar org-log-note-window-configuration nil)
12360 (defvar org-log-note-return-to (make-marker))
12361 (defvar org-log-note-effective-time nil
12362 "Remembered current time so that dynamically scoped
12363 `org-extend-today-until' affects tha timestamps in state change
12364 log")
12366 (defvar org-log-post-message nil
12367 "Message to be displayed after a log note has been stored.
12368 The auto-repeater uses this.")
12370 (defun org-add-note ()
12371 "Add a note to the current entry.
12372 This is done in the same way as adding a state change note."
12373 (interactive)
12374 (org-add-log-setup 'note nil nil 'findpos nil))
12376 (defvar org-property-end-re)
12377 (defun org-add-log-setup (&optional purpose state prev-state
12378 findpos how extra)
12379 "Set up the post command hook to take a note.
12380 If this is about to TODO state change, the new state is expected in STATE.
12381 When FINDPOS is non-nil, find the correct position for the note in
12382 the current entry. If not, assume that it can be inserted at point.
12383 HOW is an indicator what kind of note should be created.
12384 EXTRA is additional text that will be inserted into the notes buffer."
12385 (let* ((org-log-into-drawer (org-log-into-drawer))
12386 (drawer (cond ((stringp org-log-into-drawer)
12387 org-log-into-drawer)
12388 (org-log-into-drawer "LOGBOOK")
12389 (t nil))))
12390 (save-restriction
12391 (save-excursion
12392 (when findpos
12393 (org-back-to-heading t)
12394 (narrow-to-region (point) (save-excursion
12395 (outline-next-heading) (point)))
12396 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12397 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12398 "[^\r\n]*\\)?"))
12399 (goto-char (match-end 0))
12400 (cond
12401 (drawer
12402 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12403 nil t)
12404 (progn
12405 (goto-char (match-end 0))
12406 (or org-log-states-order-reversed
12407 (and (re-search-forward org-property-end-re nil t)
12408 (goto-char (1- (match-beginning 0))))))
12409 (insert "\n:" drawer ":\n:END:")
12410 (beginning-of-line 0)
12411 (org-indent-line)
12412 (beginning-of-line 2)
12413 (org-indent-line)
12414 (end-of-line 0)))
12415 ((and org-log-state-notes-insert-after-drawers
12416 (save-excursion
12417 (forward-line) (looking-at org-drawer-regexp)))
12418 (forward-line)
12419 (while (looking-at org-drawer-regexp)
12420 (goto-char (match-end 0))
12421 (re-search-forward org-property-end-re (point-max) t)
12422 (forward-line))
12423 (forward-line -1)))
12424 (unless org-log-states-order-reversed
12425 (and (= (char-after) ?\n) (forward-char 1))
12426 (org-skip-over-state-notes)
12427 (skip-chars-backward " \t\n\r")))
12428 (move-marker org-log-note-marker (point))
12429 (setq org-log-note-purpose purpose
12430 org-log-note-state state
12431 org-log-note-previous-state prev-state
12432 org-log-note-how how
12433 org-log-note-extra extra
12434 org-log-note-effective-time (org-current-effective-time))
12435 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12437 (defun org-skip-over-state-notes ()
12438 "Skip past the list of State notes in an entry."
12439 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12440 (when (ignore-errors (goto-char (org-in-item-p)))
12441 (let* ((struct (org-list-struct))
12442 (prevs (org-list-prevs-alist struct)))
12443 (while (looking-at "[ \t]*- State")
12444 (goto-char (or (org-list-get-next-item (point) struct prevs)
12445 (org-list-get-item-end (point) struct)))))))
12447 (defun org-add-log-note (&optional purpose)
12448 "Pop up a window for taking a note, and add this note later at point."
12449 (remove-hook 'post-command-hook 'org-add-log-note)
12450 (setq org-log-note-window-configuration (current-window-configuration))
12451 (delete-other-windows)
12452 (move-marker org-log-note-return-to (point))
12453 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12454 (goto-char org-log-note-marker)
12455 (org-switch-to-buffer-other-window "*Org Note*")
12456 (erase-buffer)
12457 (if (memq org-log-note-how '(time state))
12458 (let (current-prefix-arg) (org-store-log-note))
12459 (let ((org-inhibit-startup t)) (org-mode))
12460 (insert (format "# Insert note for %s.
12461 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12462 (cond
12463 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12464 ((eq org-log-note-purpose 'done) "closed todo item")
12465 ((eq org-log-note-purpose 'state)
12466 (format "state change from \"%s\" to \"%s\""
12467 (or org-log-note-previous-state "")
12468 (or org-log-note-state "")))
12469 ((eq org-log-note-purpose 'reschedule)
12470 "rescheduling")
12471 ((eq org-log-note-purpose 'delschedule)
12472 "no longer scheduled")
12473 ((eq org-log-note-purpose 'redeadline)
12474 "changing deadline")
12475 ((eq org-log-note-purpose 'deldeadline)
12476 "removing deadline")
12477 ((eq org-log-note-purpose 'refile)
12478 "refiling")
12479 ((eq org-log-note-purpose 'note)
12480 "this entry")
12481 (t (error "This should not happen")))))
12482 (if org-log-note-extra (insert org-log-note-extra))
12483 (org-set-local 'org-finish-function 'org-store-log-note)
12484 (run-hooks 'org-log-buffer-setup-hook)))
12486 (defvar org-note-abort nil) ; dynamically scoped
12487 (defun org-store-log-note ()
12488 "Finish taking a log note, and insert it to where it belongs."
12489 (let ((txt (buffer-string))
12490 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12491 lines ind bul)
12492 (kill-buffer (current-buffer))
12493 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12494 (setq txt (replace-match "" t t txt)))
12495 (if (string-match "\\s-+\\'" txt)
12496 (setq txt (replace-match "" t t txt)))
12497 (setq lines (org-split-string txt "\n"))
12498 (when (and note (string-match "\\S-" note))
12499 (setq note
12500 (org-replace-escapes
12501 note
12502 (list (cons "%u" (user-login-name))
12503 (cons "%U" user-full-name)
12504 (cons "%t" (format-time-string
12505 (org-time-stamp-format 'long 'inactive)
12506 org-log-note-effective-time))
12507 (cons "%T" (format-time-string
12508 (org-time-stamp-format 'long nil)
12509 org-log-note-effective-time))
12510 (cons "%d" (format-time-string
12511 (org-time-stamp-format nil 'inactive)
12512 org-log-note-effective-time))
12513 (cons "%D" (format-time-string
12514 (org-time-stamp-format nil nil)
12515 org-log-note-effective-time))
12516 (cons "%s" (if org-log-note-state
12517 (concat "\"" org-log-note-state "\"")
12518 ""))
12519 (cons "%S" (if org-log-note-previous-state
12520 (concat "\"" org-log-note-previous-state "\"")
12521 "\"\"")))))
12522 (if lines (setq note (concat note " \\\\")))
12523 (push note lines))
12524 (when (or current-prefix-arg org-note-abort)
12525 (when org-log-into-drawer
12526 (org-remove-empty-drawer-at
12527 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12528 org-log-note-marker))
12529 (setq lines nil))
12530 (when lines
12531 (with-current-buffer (marker-buffer org-log-note-marker)
12532 (save-excursion
12533 (goto-char org-log-note-marker)
12534 (move-marker org-log-note-marker nil)
12535 (end-of-line 1)
12536 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12537 (setq ind (save-excursion
12538 (if (ignore-errors (goto-char (org-in-item-p)))
12539 (let ((struct (org-list-struct)))
12540 (org-list-get-ind
12541 (org-list-get-top-point struct) struct))
12542 (skip-chars-backward " \r\t\n")
12543 (cond
12544 ((and (org-at-heading-p)
12545 org-adapt-indentation)
12546 (1+ (org-current-level)))
12547 ((org-at-heading-p) 0)
12548 (t (org-get-indentation))))))
12549 (setq bul (org-list-bullet-string "-"))
12550 (org-indent-line-to ind)
12551 (insert bul (pop lines))
12552 (let ((ind-body (+ (length bul) ind)))
12553 (while lines
12554 (insert "\n")
12555 (org-indent-line-to ind-body)
12556 (insert (pop lines))))
12557 (message "Note stored")
12558 (org-back-to-heading t)
12559 (org-cycle-hide-drawers 'children)))))
12560 (set-window-configuration org-log-note-window-configuration)
12561 (with-current-buffer (marker-buffer org-log-note-return-to)
12562 (goto-char org-log-note-return-to))
12563 (move-marker org-log-note-return-to nil)
12564 (and org-log-post-message (message "%s" org-log-post-message)))
12566 (defun org-remove-empty-drawer-at (drawer pos)
12567 "Remove an empty drawer DRAWER at position POS.
12568 POS may also be a marker."
12569 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12570 (save-excursion
12571 (save-restriction
12572 (widen)
12573 (goto-char pos)
12574 (if (org-in-regexp
12575 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12576 (replace-match ""))))))
12578 (defun org-sparse-tree (&optional arg)
12579 "Create a sparse tree, prompt for the details.
12580 This command can create sparse trees. You first need to select the type
12581 of match used to create the tree:
12583 t Show all TODO entries.
12584 T Show entries with a specific TODO keyword.
12585 m Show entries selected by a tags/property match.
12586 p Enter a property name and its value (both with completion on existing
12587 names/values) and show entries with that property.
12588 r Show entries matching a regular expression (`/' can be used as well)
12589 d Show deadlines due within `org-deadline-warning-days'.
12590 b Show deadlines and scheduled items before a date.
12591 a Show deadlines and scheduled items after a date."
12592 (interactive "P")
12593 (let (ans kwd value)
12594 (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")
12595 (setq ans (read-char-exclusive))
12596 (cond
12597 ((equal ans ?d)
12598 (call-interactively 'org-check-deadlines))
12599 ((equal ans ?b)
12600 (call-interactively 'org-check-before-date))
12601 ((equal ans ?a)
12602 (call-interactively 'org-check-after-date))
12603 ((equal ans ?D)
12604 (call-interactively 'org-check-dates-range))
12605 ((equal ans ?t)
12606 (org-show-todo-tree nil))
12607 ((equal ans ?T)
12608 (org-show-todo-tree '(4)))
12609 ((member ans '(?T ?m))
12610 (call-interactively 'org-match-sparse-tree))
12611 ((member ans '(?p ?P))
12612 (setq kwd (org-icompleting-read "Property: "
12613 (mapcar 'list (org-buffer-property-keys))))
12614 (setq value (org-icompleting-read "Value: "
12615 (mapcar 'list (org-property-values kwd))))
12616 (unless (string-match "\\`{.*}\\'" value)
12617 (setq value (concat "\"" value "\"")))
12618 (org-match-sparse-tree arg (concat kwd "=" value)))
12619 ((member ans '(?r ?R ?/))
12620 (call-interactively 'org-occur))
12621 (t (error "No such sparse tree command \"%c\"" ans)))))
12623 (defvar org-occur-highlights nil
12624 "List of overlays used for occur matches.")
12625 (make-variable-buffer-local 'org-occur-highlights)
12626 (defvar org-occur-parameters nil
12627 "Parameters of the active org-occur calls.
12628 This is a list, each call to org-occur pushes as cons cell,
12629 containing the regular expression and the callback, onto the list.
12630 The list can contain several entries if `org-occur' has been called
12631 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12632 will only contain one set of parameters. When the highlights are
12633 removed (for example with `C-c C-c', or with the next edit (depending
12634 on `org-remove-highlights-with-change'), this variable is emptied
12635 as well.")
12636 (make-variable-buffer-local 'org-occur-parameters)
12638 (defun org-occur (regexp &optional keep-previous callback)
12639 "Make a compact tree which shows all matches of REGEXP.
12640 The tree will show the lines where the regexp matches, and all higher
12641 headlines above the match. It will also show the heading after the match,
12642 to make sure editing the matching entry is easy.
12643 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12644 call to `org-occur' will be kept, to allow stacking of calls to this
12645 command.
12646 If CALLBACK is non-nil, it is a function which is called to confirm
12647 that the match should indeed be shown."
12648 (interactive "sRegexp: \nP")
12649 (when (equal regexp "")
12650 (error "Regexp cannot be empty"))
12651 (unless keep-previous
12652 (org-remove-occur-highlights nil nil t))
12653 (push (cons regexp callback) org-occur-parameters)
12654 (let ((cnt 0))
12655 (save-excursion
12656 (goto-char (point-min))
12657 (if (or (not keep-previous) ; do not want to keep
12658 (not org-occur-highlights)) ; no previous matches
12659 ;; hide everything
12660 (org-overview))
12661 (while (re-search-forward regexp nil t)
12662 (when (or (not callback)
12663 (save-match-data (funcall callback)))
12664 (setq cnt (1+ cnt))
12665 (when org-highlight-sparse-tree-matches
12666 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12667 (org-show-context 'occur-tree))))
12668 (when org-remove-highlights-with-change
12669 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12670 nil 'local))
12671 (unless org-sparse-tree-open-archived-trees
12672 (org-hide-archived-subtrees (point-min) (point-max)))
12673 (run-hooks 'org-occur-hook)
12674 (if (org-called-interactively-p 'interactive)
12675 (message "%d match(es) for regexp %s" cnt regexp))
12676 cnt))
12678 (defun org-occur-next-match (&optional n reset)
12679 "Function for `next-error-function' to find sparse tree matches.
12680 N is the number of matches to move, when negative move backwards.
12681 RESET is entirely ignored - this function always goes back to the
12682 starting point when no match is found."
12683 (let* ((limit (if (< n 0) (point-min) (point-max)))
12684 (search-func (if (< n 0)
12685 'previous-single-char-property-change
12686 'next-single-char-property-change))
12687 (n (abs n))
12688 (pos (point))
12690 (catch 'exit
12691 (while (setq p1 (funcall search-func (point) 'org-type))
12692 (when (equal p1 limit)
12693 (goto-char pos)
12694 (error "No more matches"))
12695 (when (equal (get-char-property p1 'org-type) 'org-occur)
12696 (setq n (1- n))
12697 (when (= n 0)
12698 (goto-char p1)
12699 (throw 'exit (point))))
12700 (goto-char p1))
12701 (goto-char p1)
12702 (error "No more matches"))))
12704 (defun org-show-context (&optional key)
12705 "Make sure point and context are visible.
12706 How much context is shown depends upon the variables
12707 `org-show-hierarchy-above', `org-show-following-heading',
12708 `org-show-entry-below' and `org-show-siblings'."
12709 (let ((heading-p (org-at-heading-p t))
12710 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12711 (following-p (org-get-alist-option org-show-following-heading key))
12712 (entry-p (org-get-alist-option org-show-entry-below key))
12713 (siblings-p (org-get-alist-option org-show-siblings key)))
12714 (catch 'exit
12715 ;; Show heading or entry text
12716 (if (and heading-p (not entry-p))
12717 (org-flag-heading nil) ; only show the heading
12718 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12719 (org-show-hidden-entry))) ; show entire entry
12720 (when following-p
12721 ;; Show next sibling, or heading below text
12722 (save-excursion
12723 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12724 (org-flag-heading nil))))
12725 (when siblings-p (org-show-siblings))
12726 (when hierarchy-p
12727 ;; show all higher headings, possibly with siblings
12728 (save-excursion
12729 (while (and (condition-case nil
12730 (progn (org-up-heading-all 1) t)
12731 (error nil))
12732 (not (bobp)))
12733 (org-flag-heading nil)
12734 (when siblings-p (org-show-siblings))))))))
12736 (defvar org-reveal-start-hook nil
12737 "Hook run before revealing a location.")
12739 (defun org-reveal (&optional siblings)
12740 "Show current entry, hierarchy above it, and the following headline.
12741 This can be used to show a consistent set of context around locations
12742 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12743 not t for the search context.
12745 With optional argument SIBLINGS, on each level of the hierarchy all
12746 siblings are shown. This repairs the tree structure to what it would
12747 look like when opened with hierarchical calls to `org-cycle'.
12748 With double optional argument \\[universal-argument] \\[universal-argument], \
12749 go to the parent and show the
12750 entire tree."
12751 (interactive "P")
12752 (run-hooks 'org-reveal-start-hook)
12753 (let ((org-show-hierarchy-above t)
12754 (org-show-following-heading t)
12755 (org-show-siblings (if siblings t org-show-siblings)))
12756 (org-show-context nil))
12757 (when (equal siblings '(16))
12758 (save-excursion
12759 (when (org-up-heading-safe)
12760 (org-show-subtree)
12761 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12763 (defun org-highlight-new-match (beg end)
12764 "Highlight from BEG to END and mark the highlight is an occur headline."
12765 (let ((ov (make-overlay beg end)))
12766 (overlay-put ov 'face 'secondary-selection)
12767 (overlay-put ov 'org-type 'org-occur)
12768 (push ov org-occur-highlights)))
12770 (defun org-remove-occur-highlights (&optional beg end noremove)
12771 "Remove the occur highlights from the buffer.
12772 BEG and END are ignored. If NOREMOVE is nil, remove this function
12773 from the `before-change-functions' in the current buffer."
12774 (interactive)
12775 (unless org-inhibit-highlight-removal
12776 (mapc 'delete-overlay org-occur-highlights)
12777 (setq org-occur-highlights nil)
12778 (setq org-occur-parameters nil)
12779 (unless noremove
12780 (remove-hook 'before-change-functions
12781 'org-remove-occur-highlights 'local))))
12783 ;;;; Priorities
12785 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12786 "Regular expression matching the priority indicator.")
12788 (defvar org-remove-priority-next-time nil)
12790 (defun org-priority-up ()
12791 "Increase the priority of the current item."
12792 (interactive)
12793 (org-priority 'up))
12795 (defun org-priority-down ()
12796 "Decrease the priority of the current item."
12797 (interactive)
12798 (org-priority 'down))
12800 (defun org-priority (&optional action)
12801 "Change the priority of an item by ARG.
12802 ACTION can be `set', `up', `down', or a character."
12803 (interactive)
12804 (unless org-enable-priority-commands
12805 (error "Priority commands are disabled"))
12806 (setq action (or action 'set))
12807 (let (current new news have remove)
12808 (save-excursion
12809 (org-back-to-heading t)
12810 (if (looking-at org-priority-regexp)
12811 (setq current (string-to-char (match-string 2))
12812 have t))
12813 (cond
12814 ((eq action 'remove)
12815 (setq remove t new ?\ ))
12816 ((or (eq action 'set)
12817 (if (featurep 'xemacs) (characterp action) (integerp action)))
12818 (if (not (eq action 'set))
12819 (setq new action)
12820 (message "Priority %c-%c, SPC to remove: "
12821 org-highest-priority org-lowest-priority)
12822 (save-match-data
12823 (setq new (read-char-exclusive))))
12824 (if (and (= (upcase org-highest-priority) org-highest-priority)
12825 (= (upcase org-lowest-priority) org-lowest-priority))
12826 (setq new (upcase new)))
12827 (cond ((equal new ?\ ) (setq remove t))
12828 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12829 (error "Priority must be between `%c' and `%c'"
12830 org-highest-priority org-lowest-priority))))
12831 ((eq action 'up)
12832 (setq new (if have
12833 (1- current) ; normal cycling
12834 ;; last priority was empty
12835 (if (eq last-command this-command)
12836 org-lowest-priority ; wrap around empty to lowest
12837 ;; default
12838 (if org-priority-start-cycle-with-default
12839 org-default-priority
12840 (1- org-default-priority))))))
12841 ((eq action 'down)
12842 (setq new (if have
12843 (1+ current) ; normal cycling
12844 ;; last priority was empty
12845 (if (eq last-command this-command)
12846 org-highest-priority ; wrap around empty to highest
12847 ;; default
12848 (if org-priority-start-cycle-with-default
12849 org-default-priority
12850 (1+ org-default-priority))))))
12851 (t (error "Invalid action")))
12852 (if (or (< (upcase new) org-highest-priority)
12853 (> (upcase new) org-lowest-priority))
12854 (if (and (memq action '(up down))
12855 (not have) (not (eq last-command this-command)))
12856 ;; `new' is from default priority
12857 (error
12858 "The default can not be set, see `org-default-priority' why")
12859 ;; normal cycling: `new' is beyond highest/lowest priority
12860 ;; and is wrapped around to the empty priority
12861 (setq remove t)))
12862 (setq news (format "%c" new))
12863 (if have
12864 (if remove
12865 (replace-match "" t t nil 1)
12866 (replace-match news t t nil 2))
12867 (if remove
12868 (error "No priority cookie found in line")
12869 (let ((case-fold-search nil))
12870 (looking-at org-todo-line-regexp))
12871 (if (match-end 2)
12872 (progn
12873 (goto-char (match-end 2))
12874 (insert " [#" news "]"))
12875 (goto-char (match-beginning 3))
12876 (insert "[#" news "] "))))
12877 (org-preserve-lc (org-set-tags nil 'align)))
12878 (if remove
12879 (message "Priority removed")
12880 (message "Priority of current item set to %s" news))))
12882 (defun org-get-priority (s)
12883 "Find priority cookie and return priority."
12884 (if (functionp org-get-priority-function)
12885 (funcall org-get-priority-function)
12886 (save-match-data
12887 (if (not (string-match org-priority-regexp s))
12888 (* 1000 (- org-lowest-priority org-default-priority))
12889 (* 1000 (- org-lowest-priority
12890 (string-to-char (match-string 2 s))))))))
12892 ;;;; Tags
12894 (defvar org-agenda-archives-mode)
12895 (defvar org-map-continue-from nil
12896 "Position from where mapping should continue.
12897 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12899 (defvar org-scanner-tags nil
12900 "The current tag list while the tags scanner is running.")
12901 (defvar org-trust-scanner-tags nil
12902 "Should `org-get-tags-at' use the tags for the scanner.
12903 This is for internal dynamical scoping only.
12904 When this is non-nil, the function `org-get-tags-at' will return the value
12905 of `org-scanner-tags' instead of building the list by itself. This
12906 can lead to large speed-ups when the tags scanner is used in a file with
12907 many entries, and when the list of tags is retrieved, for example to
12908 obtain a list of properties. Building the tags list for each entry in such
12909 a file becomes an N^2 operation - but with this variable set, it scales
12910 as N.")
12912 (defun org-scan-tags (action matcher todo-only &optional start-level)
12913 "Scan headline tags with inheritance and produce output ACTION.
12915 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12916 or `agenda' to produce an entry list for an agenda view. It can also be
12917 a Lisp form or a function that should be called at each matched headline, in
12918 this case the return value is a list of all return values from these calls.
12920 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12921 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12922 only lines with a not-done TODO keyword are included in the output.
12923 This should be the same variable that was scoped into
12924 and set by `org-make-tags-matcher' when it constructed MATCHER.
12926 START-LEVEL can be a string with asterisks, reducing the scope to
12927 headlines matching this string."
12928 (require 'org-agenda)
12929 (let* ((re (concat "^"
12930 (if start-level
12931 ;; Get the correct level to match
12932 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12933 org-outline-regexp)
12934 " *\\(\\<\\("
12935 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12936 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12937 (props (list 'face 'default
12938 'done-face 'org-agenda-done
12939 'undone-face 'default
12940 'mouse-face 'highlight
12941 'org-not-done-regexp org-not-done-regexp
12942 'org-todo-regexp org-todo-regexp
12943 'org-complex-heading-regexp org-complex-heading-regexp
12944 'help-echo
12945 (format "mouse-2 or RET jump to org file %s"
12946 (abbreviate-file-name
12947 (or (buffer-file-name (buffer-base-buffer))
12948 (buffer-name (buffer-base-buffer)))))))
12949 (case-fold-search nil)
12950 (org-map-continue-from nil)
12951 lspos tags tags-list
12952 (tags-alist (list (cons 0 org-file-tags)))
12953 (llast 0) rtn rtn1 level category i txt
12954 todo marker entry priority)
12955 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12956 (setq action (list 'lambda nil action)))
12957 (save-excursion
12958 (goto-char (point-min))
12959 (when (eq action 'sparse-tree)
12960 (org-overview)
12961 (org-remove-occur-highlights))
12962 (while (re-search-forward re nil t)
12963 (setq org-map-continue-from nil)
12964 (catch :skip
12965 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12966 tags (if (match-end 4) (org-match-string-no-properties 4)))
12967 (goto-char (setq lspos (match-beginning 0)))
12968 (setq level (org-reduced-level (funcall outline-level))
12969 category (org-get-category))
12970 (setq i llast llast level)
12971 ;; remove tag lists from same and sublevels
12972 (while (>= i level)
12973 (when (setq entry (assoc i tags-alist))
12974 (setq tags-alist (delete entry tags-alist)))
12975 (setq i (1- i)))
12976 ;; add the next tags
12977 (when tags
12978 (setq tags (org-split-string tags ":")
12979 tags-alist
12980 (cons (cons level tags) tags-alist)))
12981 ;; compile tags for current headline
12982 (setq tags-list
12983 (if org-use-tag-inheritance
12984 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12985 tags)
12986 org-scanner-tags tags-list)
12987 (when org-use-tag-inheritance
12988 (setcdr (car tags-alist)
12989 (mapcar (lambda (x)
12990 (setq x (copy-sequence x))
12991 (org-add-prop-inherited x))
12992 (cdar tags-alist))))
12993 (when (and tags org-use-tag-inheritance
12994 (or (not (eq t org-use-tag-inheritance))
12995 org-tags-exclude-from-inheritance))
12996 ;; selective inheritance, remove uninherited ones
12997 (setcdr (car tags-alist)
12998 (org-remove-uninherited-tags (cdar tags-alist))))
12999 (when (and
13001 ;; eval matcher only when the todo condition is OK
13002 (and (or (not todo-only) (member todo org-not-done-keywords))
13003 (let ((case-fold-search t) (org-trust-scanner-tags t))
13004 (eval matcher)))
13006 ;; Call the skipper, but return t if it does not skip,
13007 ;; so that the `and' form continues evaluating
13008 (progn
13009 (unless (eq action 'sparse-tree) (org-agenda-skip))
13012 ;; Check if timestamps are deselecting this entry
13013 (or (not todo-only)
13014 (and (member todo org-not-done-keywords)
13015 (or (not org-agenda-tags-todo-honor-ignore-options)
13016 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13018 ;; Extra check for the archive tag
13019 ;; FIXME: Does the skipper already do this????
13021 (not (member org-archive-tag tags-list))
13022 ;; we have an archive tag, should we use this anyway?
13023 (or (not org-agenda-skip-archived-trees)
13024 (and (eq action 'agenda) org-agenda-archives-mode))))
13026 ;; select this headline
13028 (cond
13029 ((eq action 'sparse-tree)
13030 (and org-highlight-sparse-tree-matches
13031 (org-get-heading) (match-end 0)
13032 (org-highlight-new-match
13033 (match-beginning 1) (match-end 1)))
13034 (org-show-context 'tags-tree))
13035 ((eq action 'agenda)
13036 (setq txt (org-agenda-format-item
13038 (concat
13039 (if (eq org-tags-match-list-sublevels 'indented)
13040 (make-string (1- level) ?.) "")
13041 (org-get-heading))
13042 category
13043 tags-list)
13044 priority (org-get-priority txt))
13045 (goto-char lspos)
13046 (setq marker (org-agenda-new-marker))
13047 (org-add-props txt props
13048 'org-marker marker 'org-hd-marker marker 'org-category category
13049 'todo-state todo
13050 'priority priority 'type "tagsmatch")
13051 (push txt rtn))
13052 ((functionp action)
13053 (setq org-map-continue-from nil)
13054 (save-excursion
13055 (setq rtn1 (funcall action))
13056 (push rtn1 rtn)))
13057 (t (error "Invalid action")))
13059 ;; if we are to skip sublevels, jump to end of subtree
13060 (unless org-tags-match-list-sublevels
13061 (org-end-of-subtree t)
13062 (backward-char 1))))
13063 ;; Get the correct position from where to continue
13064 (if org-map-continue-from
13065 (goto-char org-map-continue-from)
13066 (and (= (point) lspos) (end-of-line 1)))))
13067 (when (and (eq action 'sparse-tree)
13068 (not org-sparse-tree-open-archived-trees))
13069 (org-hide-archived-subtrees (point-min) (point-max)))
13070 (nreverse rtn)))
13072 (defun org-remove-uninherited-tags (tags)
13073 "Remove all tags that are not inherited from the list TAGS."
13074 (cond
13075 ((eq org-use-tag-inheritance t)
13076 (if org-tags-exclude-from-inheritance
13077 (org-delete-all org-tags-exclude-from-inheritance tags)
13078 tags))
13079 ((not org-use-tag-inheritance) nil)
13080 ((stringp org-use-tag-inheritance)
13081 (delq nil (mapcar
13082 (lambda (x)
13083 (if (and (string-match org-use-tag-inheritance x)
13084 (not (member x org-tags-exclude-from-inheritance)))
13085 x nil))
13086 tags)))
13087 ((listp org-use-tag-inheritance)
13088 (delq nil (mapcar
13089 (lambda (x)
13090 (if (member x org-use-tag-inheritance) x nil))
13091 tags)))))
13093 (defun org-match-sparse-tree (&optional todo-only match)
13094 "Create a sparse tree according to tags string MATCH.
13095 MATCH can contain positive and negative selection of tags, like
13096 \"+WORK+URGENT-WITHBOSS\".
13097 If optional argument TODO-ONLY is non-nil, only select lines that are
13098 also TODO lines."
13099 (interactive "P")
13100 (org-prepare-agenda-buffers (list (current-buffer)))
13101 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13103 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13105 (defvar org-cached-props nil)
13106 (defun org-cached-entry-get (pom property)
13107 (if (or (eq t org-use-property-inheritance)
13108 (and (stringp org-use-property-inheritance)
13109 (string-match org-use-property-inheritance property))
13110 (and (listp org-use-property-inheritance)
13111 (member property org-use-property-inheritance)))
13112 ;; Caching is not possible, check it directly
13113 (org-entry-get pom property 'inherit)
13114 ;; Get all properties, so that we can do complicated checks easily
13115 (cdr (assoc property (or org-cached-props
13116 (setq org-cached-props
13117 (org-entry-properties pom)))))))
13119 (defun org-global-tags-completion-table (&optional files)
13120 "Return the list of all tags in all agenda buffer/files.
13121 Optional FILES argument is a list of files to which can be used
13122 instead of the agenda files."
13123 (save-excursion
13124 (org-uniquify
13125 (delq nil
13126 (apply 'append
13127 (mapcar
13128 (lambda (file)
13129 (set-buffer (find-file-noselect file))
13130 (append (org-get-buffer-tags)
13131 (mapcar (lambda (x) (if (stringp (car-safe x))
13132 (list (car-safe x)) nil))
13133 org-tag-alist)))
13134 (if (and files (car files))
13135 files
13136 (org-agenda-files))))))))
13138 (defun org-make-tags-matcher (match)
13139 "Create the TAGS/TODO matcher form for the selection string MATCH.
13141 The variable `todo-only' is scoped dynamically into this function; it will be
13142 set to t if the matcher restricts matching to TODO entries,
13143 otherwise will not be touched.
13145 Returns a cons of the selection string MATCH and the constructed
13146 lisp form implementing the matcher. The matcher is to be
13147 evaluated at an Org entry, with point on the headline,
13148 and returns t if the entry matches the
13149 selection string MATCH. The returned lisp form references
13150 two variables with information about the entry, which must be
13151 bound around the form's evaluation: todo, the TODO keyword at the
13152 entry (or nil of none); and tags-list, the list of all tags at the
13153 entry including inherited ones. Additionally, the category
13154 of the entry (if any) must be specified as the text property
13155 'org-category on the headline.
13157 See also `org-scan-tags'.
13159 (declare (special todo-only))
13160 (unless (boundp 'todo-only)
13161 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13162 (unless match
13163 ;; Get a new match request, with completion
13164 (let ((org-last-tags-completion-table
13165 (org-global-tags-completion-table)))
13166 (setq match (org-completing-read-no-i
13167 "Match: " 'org-tags-completion-function nil nil nil
13168 'org-tags-history))))
13170 ;; Parse the string and create a lisp form
13171 (let ((match0 match)
13172 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13173 minus tag mm
13174 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13175 orterms term orlist re-p str-p level-p level-op time-p
13176 prop-p pn pv po gv rest)
13177 (if (string-match "/+" match)
13178 ;; match contains also a todo-matching request
13179 (progn
13180 (setq tagsmatch (substring match 0 (match-beginning 0))
13181 todomatch (substring match (match-end 0)))
13182 (if (string-match "^!" todomatch)
13183 (setq todo-only t todomatch (substring todomatch 1)))
13184 (if (string-match "^\\s-*$" todomatch)
13185 (setq todomatch nil)))
13186 ;; only matching tags
13187 (setq tagsmatch match todomatch nil))
13189 ;; Make the tags matcher
13190 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13191 (setq tagsmatcher t)
13192 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13193 (while (setq term (pop orterms))
13194 (while (and (equal (substring term -1) "\\") orterms)
13195 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13196 (while (string-match re term)
13197 (setq rest (substring term (match-end 0))
13198 minus (and (match-end 1)
13199 (equal (match-string 1 term) "-"))
13200 tag (save-match-data (replace-regexp-in-string
13201 "\\\\-" "-"
13202 (match-string 2 term)))
13203 re-p (equal (string-to-char tag) ?{)
13204 level-p (match-end 4)
13205 prop-p (match-end 5)
13206 mm (cond
13207 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13208 (level-p
13209 (setq level-op (org-op-to-function (match-string 3 term)))
13210 `(,level-op level ,(string-to-number
13211 (match-string 4 term))))
13212 (prop-p
13213 (setq pn (match-string 5 term)
13214 po (match-string 6 term)
13215 pv (match-string 7 term)
13216 re-p (equal (string-to-char pv) ?{)
13217 str-p (equal (string-to-char pv) ?\")
13218 time-p (save-match-data
13219 (string-match "^\"[[<].*[]>]\"$" pv))
13220 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13221 (if time-p (setq pv (org-matcher-time pv)))
13222 (setq po (org-op-to-function po (if time-p 'time str-p)))
13223 (cond
13224 ((equal pn "CATEGORY")
13225 (setq gv '(get-text-property (point) 'org-category)))
13226 ((equal pn "TODO")
13227 (setq gv 'todo))
13229 (setq gv `(org-cached-entry-get nil ,pn))))
13230 (if re-p
13231 (if (eq po 'org<>)
13232 `(not (string-match ,pv (or ,gv "")))
13233 `(string-match ,pv (or ,gv "")))
13234 (if str-p
13235 `(,po (or ,gv "") ,pv)
13236 `(,po (string-to-number (or ,gv ""))
13237 ,(string-to-number pv) ))))
13238 (t `(member ,tag tags-list)))
13239 mm (if minus (list 'not mm) mm)
13240 term rest)
13241 (push mm tagsmatcher))
13242 (push (if (> (length tagsmatcher) 1)
13243 (cons 'and tagsmatcher)
13244 (car tagsmatcher))
13245 orlist)
13246 (setq tagsmatcher nil))
13247 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13248 (setq tagsmatcher
13249 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13250 ;; Make the todo matcher
13251 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13252 (setq todomatcher t)
13253 (setq orterms (org-split-string todomatch "|") orlist nil)
13254 (while (setq term (pop orterms))
13255 (while (string-match re term)
13256 (setq minus (and (match-end 1)
13257 (equal (match-string 1 term) "-"))
13258 kwd (match-string 2 term)
13259 re-p (equal (string-to-char kwd) ?{)
13260 term (substring term (match-end 0))
13261 mm (if re-p
13262 `(string-match ,(substring kwd 1 -1) todo)
13263 (list 'equal 'todo kwd))
13264 mm (if minus (list 'not mm) mm))
13265 (push mm todomatcher))
13266 (push (if (> (length todomatcher) 1)
13267 (cons 'and todomatcher)
13268 (car todomatcher))
13269 orlist)
13270 (setq todomatcher nil))
13271 (setq todomatcher (if (> (length orlist) 1)
13272 (cons 'or orlist) (car orlist))))
13274 ;; Return the string and lisp forms of the matcher
13275 (setq matcher (if todomatcher
13276 (list 'and tagsmatcher todomatcher)
13277 tagsmatcher))
13278 (when todo-only
13279 (setq matcher (list 'and '(member todo org-not-done-keywords)
13280 matcher)))
13281 (cons match0 matcher)))
13283 (defun org-op-to-function (op &optional stringp)
13284 "Turn an operator into the appropriate function."
13285 (setq op
13286 (cond
13287 ((equal op "<" ) '(< string< org-time<))
13288 ((equal op ">" ) '(> org-string> org-time>))
13289 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13290 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13291 ((member op '("=" "==")) '(= string= org-time=))
13292 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13293 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13295 (defun org<> (a b) (not (= a b)))
13296 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13297 (defun org-string>= (a b) (not (string< a b)))
13298 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13299 (defun org-string<> (a b) (not (string= a b)))
13300 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13301 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13302 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13303 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13304 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13305 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13306 (defun org-2ft (s)
13307 "Convert S to a floating point time.
13308 If S is already a number, just return it. If it is a string, parse
13309 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13310 (cond
13311 ((numberp s) s)
13312 ((stringp s)
13313 (condition-case nil
13314 (float-time (apply 'encode-time (org-parse-time-string s)))
13315 (error 0.)))
13316 (t 0.)))
13318 (defun org-time-today ()
13319 "Time in seconds today at 0:00.
13320 Returns the float number of seconds since the beginning of the
13321 epoch to the beginning of today (00:00)."
13322 (float-time (apply 'encode-time
13323 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13325 (defun org-matcher-time (s)
13326 "Interpret a time comparison value."
13327 (save-match-data
13328 (cond
13329 ((string= s "<now>") (float-time))
13330 ((string= s "<today>") (org-time-today))
13331 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13332 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13333 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13334 (+ (org-time-today)
13335 (* (string-to-number (match-string 1 s))
13336 (cdr (assoc (match-string 2 s)
13337 '(("d" . 86400.0) ("w" . 604800.0)
13338 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13339 (t (org-2ft s)))))
13341 (defun org-match-any-p (re list)
13342 "Does re match any element of list?"
13343 (setq list (mapcar (lambda (x) (string-match re x)) list))
13344 (delq nil list))
13346 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13347 (defvar org-tags-overlay (make-overlay 1 1))
13348 (org-detach-overlay org-tags-overlay)
13350 (defun org-get-local-tags-at (&optional pos)
13351 "Get a list of tags defined in the current headline."
13352 (org-get-tags-at pos 'local))
13354 (defun org-get-local-tags ()
13355 "Get a list of tags defined in the current headline."
13356 (org-get-tags-at nil 'local))
13358 (defun org-get-tags-at (&optional pos local)
13359 "Get a list of all headline tags applicable at POS.
13360 POS defaults to point. If tags are inherited, the list contains
13361 the targets in the same sequence as the headlines appear, i.e.
13362 the tags of the current headline come last.
13363 When LOCAL is non-nil, only return tags from the current headline,
13364 ignore inherited ones."
13365 (interactive)
13366 (if (and org-trust-scanner-tags
13367 (or (not pos) (equal pos (point)))
13368 (not local))
13369 org-scanner-tags
13370 (let (tags ltags lastpos parent)
13371 (save-excursion
13372 (save-restriction
13373 (widen)
13374 (goto-char (or pos (point)))
13375 (save-match-data
13376 (catch 'done
13377 (condition-case nil
13378 (progn
13379 (org-back-to-heading t)
13380 (while (not (equal lastpos (point)))
13381 (setq lastpos (point))
13382 (when (looking-at
13383 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13384 (setq ltags (org-split-string
13385 (org-match-string-no-properties 1) ":"))
13386 (when parent
13387 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13388 (setq tags (append
13389 (if parent
13390 (org-remove-uninherited-tags ltags)
13391 ltags)
13392 tags)))
13393 (or org-use-tag-inheritance (throw 'done t))
13394 (if local (throw 'done t))
13395 (or (org-up-heading-safe) (error nil))
13396 (setq parent t)))
13397 (error nil)))))
13398 (if local
13399 tags
13400 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13402 (defun org-add-prop-inherited (s)
13403 (add-text-properties 0 (length s) '(inherited t) s)
13406 (defun org-toggle-tag (tag &optional onoff)
13407 "Toggle the tag TAG for the current line.
13408 If ONOFF is `on' or `off', don't toggle but set to this state."
13409 (let (res current)
13410 (save-excursion
13411 (org-back-to-heading t)
13412 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13413 (point-at-eol) t)
13414 (progn
13415 (setq current (match-string 1))
13416 (replace-match ""))
13417 (setq current ""))
13418 (setq current (nreverse (org-split-string current ":")))
13419 (cond
13420 ((eq onoff 'on)
13421 (setq res t)
13422 (or (member tag current) (push tag current)))
13423 ((eq onoff 'off)
13424 (or (not (member tag current)) (setq current (delete tag current))))
13425 (t (if (member tag current)
13426 (setq current (delete tag current))
13427 (setq res t)
13428 (push tag current))))
13429 (end-of-line 1)
13430 (if current
13431 (progn
13432 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13433 (org-set-tags nil t))
13434 (delete-horizontal-space))
13435 (run-hooks 'org-after-tags-change-hook))
13436 res))
13438 (defun org-align-tags-here (to-col)
13439 ;; Assumes that this is a headline
13440 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13441 (beginning-of-line 1)
13442 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13443 (< pos (match-beginning 2)))
13444 (progn
13445 (setq tags-l (- (match-end 2) (match-beginning 2)))
13446 (goto-char (match-beginning 1))
13447 (insert " ")
13448 (delete-region (point) (1+ (match-beginning 2)))
13449 (setq ncol (max (current-column)
13450 (1+ col)
13451 (if (> to-col 0)
13452 to-col
13453 (- (abs to-col) tags-l))))
13454 (setq p (point))
13455 (insert (make-string (- ncol (current-column)) ?\ ))
13456 (setq ncol (current-column))
13457 (when indent-tabs-mode (tabify p (point-at-eol)))
13458 (org-move-to-column (min ncol col) t))
13459 (goto-char pos))))
13461 (defun org-set-tags-command (&optional arg just-align)
13462 "Call the set-tags command for the current entry."
13463 (interactive "P")
13464 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13465 (org-set-tags arg just-align)
13466 (save-excursion
13467 (org-back-to-heading t)
13468 (org-set-tags arg just-align))))
13470 (defun org-set-tags-to (data)
13471 "Set the tags of the current entry to DATA, replacing the current tags.
13472 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13473 If DATA is nil or the empty string, any tags will be removed."
13474 (interactive "sTags: ")
13475 (setq data
13476 (cond
13477 ((eq data nil) "")
13478 ((equal data "") "")
13479 ((stringp data)
13480 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13481 ":"))
13482 ((listp data)
13483 (concat ":" (mapconcat 'identity data ":") ":"))
13484 (t nil)))
13485 (when data
13486 (save-excursion
13487 (org-back-to-heading t)
13488 (when (looking-at org-complex-heading-regexp)
13489 (if (match-end 5)
13490 (progn
13491 (goto-char (match-beginning 5))
13492 (insert data)
13493 (delete-region (point) (point-at-eol))
13494 (org-set-tags nil 'align))
13495 (goto-char (point-at-eol))
13496 (insert " " data)
13497 (org-set-tags nil 'align)))
13498 (beginning-of-line 1)
13499 (if (looking-at ".*?\\([ \t]+\\)$")
13500 (delete-region (match-beginning 1) (match-end 1))))))
13502 (defun org-align-all-tags ()
13503 "Align the tags i all headings."
13504 (interactive)
13505 (save-excursion
13506 (or (ignore-errors (org-back-to-heading t))
13507 (outline-next-heading))
13508 (if (org-at-heading-p)
13509 (org-set-tags t)
13510 (message "No headings"))))
13512 (defvar org-indent-indentation-per-level)
13513 (defun org-set-tags (&optional arg just-align)
13514 "Set the tags for the current headline.
13515 With prefix ARG, realign all tags in headings in the current buffer."
13516 (interactive "P")
13517 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13518 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13519 'region-start-level 'region))
13520 org-loop-over-headlines-in-active-region)
13521 (org-map-entries
13522 ;; We don't use ARG and JUST-ALIGN here these args are not
13523 ;; useful when looping over headlines
13524 `(org-set-tags)
13525 org-loop-over-headlines-in-active-region
13526 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13527 (let* ((re org-outline-regexp-bol)
13528 (current (unless arg (org-get-tags-string)))
13529 (col (current-column))
13530 (org-setting-tags t)
13531 table current-tags inherited-tags ; computed below when needed
13532 tags p0 c0 c1 rpl di tc level)
13533 (if arg
13534 (save-excursion
13535 (goto-char (point-min))
13536 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13537 (while (re-search-forward re nil t)
13538 (org-set-tags nil t)
13539 (end-of-line 1)))
13540 (message "All tags realigned to column %d" org-tags-column))
13541 (if just-align
13542 (setq tags current)
13543 ;; Get a new set of tags from the user
13544 (save-excursion
13545 (setq table (append org-tag-persistent-alist
13546 (or org-tag-alist (org-get-buffer-tags))
13547 (and
13548 org-complete-tags-always-offer-all-agenda-tags
13549 (org-global-tags-completion-table
13550 (org-agenda-files))))
13551 org-last-tags-completion-table table
13552 current-tags (org-split-string current ":")
13553 inherited-tags (nreverse
13554 (nthcdr (length current-tags)
13555 (nreverse (org-get-tags-at))))
13556 tags
13557 (if (or (eq t org-use-fast-tag-selection)
13558 (and org-use-fast-tag-selection
13559 (delq nil (mapcar 'cdr table))))
13560 (org-fast-tag-selection
13561 current-tags inherited-tags table
13562 (if org-fast-tag-selection-include-todo
13563 org-todo-key-alist))
13564 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13565 (org-trim
13566 (org-icompleting-read "Tags: "
13567 'org-tags-completion-function
13568 nil nil current 'org-tags-history))))))
13569 (while (string-match "[-+&]+" tags)
13570 ;; No boolean logic, just a list
13571 (setq tags (replace-match ":" t t tags))))
13573 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13575 (if org-tags-sort-function
13576 (setq tags (mapconcat 'identity
13577 (sort (org-split-string
13578 tags (org-re "[^[:alnum:]_@#%]+"))
13579 org-tags-sort-function) ":")))
13581 (if (string-match "\\`[\t ]*\\'" tags)
13582 (setq tags "")
13583 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13584 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13586 ;; Insert new tags at the correct column
13587 (beginning-of-line 1)
13588 (setq level (or (and (looking-at org-outline-regexp)
13589 (- (match-end 0) (point) 1))
13591 (cond
13592 ((and (equal current "") (equal tags "")))
13593 ((re-search-forward
13594 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13595 (point-at-eol) t)
13596 (if (equal tags "")
13597 (setq rpl "")
13598 (goto-char (match-beginning 0))
13599 (setq c0 (current-column)
13600 ;; compute offset for the case of org-indent-mode active
13601 di (if org-indent-mode
13602 (* (1- org-indent-indentation-per-level) (1- level))
13604 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13605 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13606 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13607 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13608 (replace-match rpl t t)
13609 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13610 tags)
13611 (t (error "Tags alignment failed")))
13612 (org-move-to-column col)
13613 (unless just-align
13614 (run-hooks 'org-after-tags-change-hook))))))
13616 (defun org-change-tag-in-region (beg end tag off)
13617 "Add or remove TAG for each entry in the region.
13618 This works in the agenda, and also in an org-mode buffer."
13619 (interactive
13620 (list (region-beginning) (region-end)
13621 (let ((org-last-tags-completion-table
13622 (if (derived-mode-p 'org-mode)
13623 (org-get-buffer-tags)
13624 (org-global-tags-completion-table))))
13625 (org-icompleting-read
13626 "Tag: " 'org-tags-completion-function nil nil nil
13627 'org-tags-history))
13628 (progn
13629 (message "[s]et or [r]emove? ")
13630 (equal (read-char-exclusive) ?r))))
13631 (if (fboundp 'deactivate-mark) (deactivate-mark))
13632 (let ((agendap (equal major-mode 'org-agenda-mode))
13633 l1 l2 m buf pos newhead (cnt 0))
13634 (goto-char end)
13635 (setq l2 (1- (org-current-line)))
13636 (goto-char beg)
13637 (setq l1 (org-current-line))
13638 (loop for l from l1 to l2 do
13639 (org-goto-line l)
13640 (setq m (get-text-property (point) 'org-hd-marker))
13641 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13642 (and agendap m))
13643 (setq buf (if agendap (marker-buffer m) (current-buffer))
13644 pos (if agendap m (point)))
13645 (with-current-buffer buf
13646 (save-excursion
13647 (save-restriction
13648 (goto-char pos)
13649 (setq cnt (1+ cnt))
13650 (org-toggle-tag tag (if off 'off 'on))
13651 (setq newhead (org-get-heading)))))
13652 (and agendap (org-agenda-change-all-lines newhead m))))
13653 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13655 (defun org-tags-completion-function (string predicate &optional flag)
13656 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13657 (confirm (lambda (x) (stringp (car x)))))
13658 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13659 (setq s1 (match-string 1 string)
13660 s2 (match-string 2 string))
13661 (setq s1 "" s2 string))
13662 (cond
13663 ((eq flag nil)
13664 ;; try completion
13665 (setq rtn (try-completion s2 ctable confirm))
13666 (if (stringp rtn)
13667 (setq rtn
13668 (concat s1 s2 (substring rtn (length s2))
13669 (if (and org-add-colon-after-tag-completion
13670 (assoc rtn ctable))
13671 ":" ""))))
13672 rtn)
13673 ((eq flag t)
13674 ;; all-completions
13675 (all-completions s2 ctable confirm)
13677 ((eq flag 'lambda)
13678 ;; exact match?
13679 (assoc s2 ctable)))
13682 (defun org-fast-tag-insert (kwd tags face &optional end)
13683 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13684 (insert (format "%-12s" (concat kwd ":"))
13685 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13686 (or end "")))
13688 (defun org-fast-tag-show-exit (flag)
13689 (save-excursion
13690 (org-goto-line 3)
13691 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13692 (replace-match ""))
13693 (when flag
13694 (end-of-line 1)
13695 (org-move-to-column (- (window-width) 19) t)
13696 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13698 (defun org-set-current-tags-overlay (current prefix)
13699 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13700 (if (featurep 'xemacs)
13701 (org-overlay-display org-tags-overlay (concat prefix s)
13702 'secondary-selection)
13703 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13704 (org-overlay-display org-tags-overlay (concat prefix s)))))
13706 (defvar org-last-tag-selection-key nil)
13707 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13708 "Fast tag selection with single keys.
13709 CURRENT is the current list of tags in the headline, INHERITED is the
13710 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13711 possibly with grouping information. TODO-TABLE is a similar table with
13712 TODO keywords, should these have keys assigned to them.
13713 If the keys are nil, a-z are automatically assigned.
13714 Returns the new tags string, or nil to not change the current settings."
13715 (let* ((fulltable (append table todo-table))
13716 (maxlen (apply 'max (mapcar
13717 (lambda (x)
13718 (if (stringp (car x)) (string-width (car x)) 0))
13719 fulltable)))
13720 (buf (current-buffer))
13721 (expert (eq org-fast-tag-selection-single-key 'expert))
13722 (buffer-tags nil)
13723 (fwidth (+ maxlen 3 1 3))
13724 (ncol (/ (- (window-width) 4) fwidth))
13725 (i-face 'org-done)
13726 (c-face 'org-todo)
13727 tg cnt e c char c1 c2 ntable tbl rtn
13728 ov-start ov-end ov-prefix
13729 (exit-after-next org-fast-tag-selection-single-key)
13730 (done-keywords org-done-keywords)
13731 groups ingroup)
13732 (save-excursion
13733 (beginning-of-line 1)
13734 (if (looking-at
13735 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13736 (setq ov-start (match-beginning 1)
13737 ov-end (match-end 1)
13738 ov-prefix "")
13739 (setq ov-start (1- (point-at-eol))
13740 ov-end (1+ ov-start))
13741 (skip-chars-forward "^\n\r")
13742 (setq ov-prefix
13743 (concat
13744 (buffer-substring (1- (point)) (point))
13745 (if (> (current-column) org-tags-column)
13747 (make-string (- org-tags-column (current-column)) ?\ ))))))
13748 (move-overlay org-tags-overlay ov-start ov-end)
13749 (save-window-excursion
13750 (if expert
13751 (set-buffer (get-buffer-create " *Org tags*"))
13752 (delete-other-windows)
13753 (split-window-vertically)
13754 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13755 (erase-buffer)
13756 (org-set-local 'org-done-keywords done-keywords)
13757 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13758 (org-fast-tag-insert "Current" current c-face "\n\n")
13759 (org-fast-tag-show-exit exit-after-next)
13760 (org-set-current-tags-overlay current ov-prefix)
13761 (setq tbl fulltable char ?a cnt 0)
13762 (while (setq e (pop tbl))
13763 (cond
13764 ((equal (car e) :startgroup)
13765 (push '() groups) (setq ingroup t)
13766 (when (not (= cnt 0))
13767 (setq cnt 0)
13768 (insert "\n"))
13769 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13770 ((equal (car e) :endgroup)
13771 (setq ingroup nil cnt 0)
13772 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13773 ((equal e '(:newline))
13774 (when (not (= cnt 0))
13775 (setq cnt 0)
13776 (insert "\n")
13777 (setq e (car tbl))
13778 (while (equal (car tbl) '(:newline))
13779 (insert "\n")
13780 (setq tbl (cdr tbl)))))
13782 (setq tg (copy-sequence (car e)) c2 nil)
13783 (if (cdr e)
13784 (setq c (cdr e))
13785 ;; automatically assign a character.
13786 (setq c1 (string-to-char
13787 (downcase (substring
13788 tg (if (= (string-to-char tg) ?@) 1 0)))))
13789 (if (or (rassoc c1 ntable) (rassoc c1 table))
13790 (while (or (rassoc char ntable) (rassoc char table))
13791 (setq char (1+ char)))
13792 (setq c2 c1))
13793 (setq c (or c2 char)))
13794 (if ingroup (push tg (car groups)))
13795 (setq tg (org-add-props tg nil 'face
13796 (cond
13797 ((not (assoc tg table))
13798 (org-get-todo-face tg))
13799 ((member tg current) c-face)
13800 ((member tg inherited) i-face)
13801 (t nil))))
13802 (if (and (= cnt 0) (not ingroup)) (insert " "))
13803 (insert "[" c "] " tg (make-string
13804 (- fwidth 4 (length tg)) ?\ ))
13805 (push (cons tg c) ntable)
13806 (when (= (setq cnt (1+ cnt)) ncol)
13807 (insert "\n")
13808 (if ingroup (insert " "))
13809 (setq cnt 0)))))
13810 (setq ntable (nreverse ntable))
13811 (insert "\n")
13812 (goto-char (point-min))
13813 (if (not expert) (org-fit-window-to-buffer))
13814 (setq rtn
13815 (catch 'exit
13816 (while t
13817 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13818 (if (not groups) "no " "")
13819 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13820 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13821 (setq org-last-tag-selection-key c)
13822 (cond
13823 ((= c ?\r) (throw 'exit t))
13824 ((= c ?!)
13825 (setq groups (not groups))
13826 (goto-char (point-min))
13827 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13828 ((= c ?\C-c)
13829 (if (not expert)
13830 (org-fast-tag-show-exit
13831 (setq exit-after-next (not exit-after-next)))
13832 (setq expert nil)
13833 (delete-other-windows)
13834 (set-window-buffer (split-window-vertically) " *Org tags*")
13835 (org-switch-to-buffer-other-window " *Org tags*")
13836 (org-fit-window-to-buffer)))
13837 ((or (= c ?\C-g)
13838 (and (= c ?q) (not (rassoc c ntable))))
13839 (org-detach-overlay org-tags-overlay)
13840 (setq quit-flag t))
13841 ((= c ?\ )
13842 (setq current nil)
13843 (if exit-after-next (setq exit-after-next 'now)))
13844 ((= c ?\t)
13845 (condition-case nil
13846 (setq tg (org-icompleting-read
13847 "Tag: "
13848 (or buffer-tags
13849 (with-current-buffer buf
13850 (org-get-buffer-tags)))))
13851 (quit (setq tg "")))
13852 (when (string-match "\\S-" tg)
13853 (add-to-list 'buffer-tags (list tg))
13854 (if (member tg current)
13855 (setq current (delete tg current))
13856 (push tg current)))
13857 (if exit-after-next (setq exit-after-next 'now)))
13858 ((setq e (rassoc c todo-table) tg (car e))
13859 (with-current-buffer buf
13860 (save-excursion (org-todo tg)))
13861 (if exit-after-next (setq exit-after-next 'now)))
13862 ((setq e (rassoc c ntable) tg (car e))
13863 (if (member tg current)
13864 (setq current (delete tg current))
13865 (loop for g in groups do
13866 (if (member tg g)
13867 (mapc (lambda (x)
13868 (setq current (delete x current)))
13869 g)))
13870 (push tg current))
13871 (if exit-after-next (setq exit-after-next 'now))))
13873 ;; Create a sorted list
13874 (setq current
13875 (sort current
13876 (lambda (a b)
13877 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13878 (if (eq exit-after-next 'now) (throw 'exit t))
13879 (goto-char (point-min))
13880 (beginning-of-line 2)
13881 (delete-region (point) (point-at-eol))
13882 (org-fast-tag-insert "Current" current c-face)
13883 (org-set-current-tags-overlay current ov-prefix)
13884 (while (re-search-forward
13885 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13886 (setq tg (match-string 1))
13887 (add-text-properties
13888 (match-beginning 1) (match-end 1)
13889 (list 'face
13890 (cond
13891 ((member tg current) c-face)
13892 ((member tg inherited) i-face)
13893 (t (get-text-property (match-beginning 1) 'face))))))
13894 (goto-char (point-min)))))
13895 (org-detach-overlay org-tags-overlay)
13896 (if rtn
13897 (mapconcat 'identity current ":")
13898 nil))))
13900 (defun org-get-tags-string ()
13901 "Get the TAGS string in the current headline."
13902 (unless (org-at-heading-p t)
13903 (error "Not on a heading"))
13904 (save-excursion
13905 (beginning-of-line 1)
13906 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13907 (org-match-string-no-properties 1)
13908 "")))
13910 (defun org-get-tags ()
13911 "Get the list of tags specified in the current headline."
13912 (org-split-string (org-get-tags-string) ":"))
13914 (defun org-get-buffer-tags ()
13915 "Get a table of all tags used in the buffer, for completion."
13916 (let (tags)
13917 (save-excursion
13918 (goto-char (point-min))
13919 (while (re-search-forward
13920 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13921 (when (equal (char-after (point-at-bol 0)) ?*)
13922 (mapc (lambda (x) (add-to-list 'tags x))
13923 (org-split-string (org-match-string-no-properties 1) ":")))))
13924 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13925 (mapcar 'list tags)))
13927 ;;;; The mapping API
13929 ;;;###autoload
13930 (defun org-map-entries (func &optional match scope &rest skip)
13931 "Call FUNC at each headline selected by MATCH in SCOPE.
13933 FUNC is a function or a lisp form. The function will be called without
13934 arguments, with the cursor positioned at the beginning of the headline.
13935 The return values of all calls to the function will be collected and
13936 returned as a list.
13938 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13939 does not need to preserve point. After evaluation, the cursor will be
13940 moved to the end of the line (presumably of the headline of the
13941 processed entry) and search continues from there. Under some
13942 circumstances, this may not produce the wanted results. For example,
13943 if you have removed (e.g. archived) the current (sub)tree it could
13944 mean that the next entry will be skipped entirely. In such cases, you
13945 can specify the position from where search should continue by making
13946 FUNC set the variable `org-map-continue-from' to the desired buffer
13947 position.
13949 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13950 Only headlines that are matched by this query will be considered during
13951 the iteration. When MATCH is nil or t, all headlines will be
13952 visited by the iteration.
13954 SCOPE determines the scope of this command. It can be any of:
13956 nil The current buffer, respecting the restriction if any
13957 tree The subtree started with the entry at point
13958 region The entries within the active region, if any
13959 region-start-level
13960 The entries within the active region, but only those at
13961 the same level than the first one.
13962 file The current buffer, without restriction
13963 file-with-archives
13964 The current buffer, and any archives associated with it
13965 agenda All agenda files
13966 agenda-with-archives
13967 All agenda files with any archive files associated with them
13968 \(file1 file2 ...)
13969 If this is a list, all files in the list will be scanned
13971 The remaining args are treated as settings for the skipping facilities of
13972 the scanner. The following items can be given here:
13974 archive skip trees with the archive tag.
13975 comment skip trees with the COMMENT keyword
13976 function or Emacs Lisp form:
13977 will be used as value for `org-agenda-skip-function', so whenever
13978 the function returns t, FUNC will not be called for that
13979 entry and search will continue from the point where the
13980 function leaves it.
13982 If your function needs to retrieve the tags including inherited tags
13983 at the *current* entry, you can use the value of the variable
13984 `org-scanner-tags' which will be much faster than getting the value
13985 with `org-get-tags-at'. If your function gets properties with
13986 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13987 to t around the call to `org-entry-properties' to get the same speedup.
13988 Note that if your function moves around to retrieve tags and properties at
13989 a *different* entry, you cannot use these techniques."
13990 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13991 (not (org-region-active-p)))
13992 (let* ((org-agenda-archives-mode nil) ; just to make sure
13993 (org-agenda-skip-archived-trees (memq 'archive skip))
13994 (org-agenda-skip-comment-trees (memq 'comment skip))
13995 (org-agenda-skip-function
13996 (car (org-delete-all '(comment archive) skip)))
13997 (org-tags-match-list-sublevels t)
13998 (start-level (eq scope 'region-start-level))
13999 matcher file res
14000 org-todo-keywords-for-agenda
14001 org-done-keywords-for-agenda
14002 org-todo-keyword-alist-for-agenda
14003 org-drawers-for-agenda
14004 org-tag-alist-for-agenda
14005 todo-only)
14007 (cond
14008 ((eq match t) (setq matcher t))
14009 ((eq match nil) (setq matcher t))
14010 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14012 (save-excursion
14013 (save-restriction
14014 (cond ((eq scope 'tree)
14015 (org-back-to-heading t)
14016 (org-narrow-to-subtree)
14017 (setq scope nil))
14018 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14019 (org-region-active-p))
14020 ;; If needed, set start-level to a string like "2"
14021 (when start-level
14022 (save-excursion
14023 (goto-char (region-beginning))
14024 (unless (org-at-heading-p) (outline-next-heading))
14025 (setq start-level (org-current-level))))
14026 (narrow-to-region (region-beginning)
14027 (save-excursion
14028 (goto-char (region-end))
14029 (unless (and (bolp) (org-at-heading-p))
14030 (outline-next-heading))
14031 (point)))
14032 (setq scope nil)))
14034 (if (not scope)
14035 (progn
14036 (org-prepare-agenda-buffers
14037 (list (buffer-file-name (current-buffer))))
14038 (setq res (org-scan-tags func matcher todo-only start-level)))
14039 ;; Get the right scope
14040 (cond
14041 ((and scope (listp scope) (symbolp (car scope)))
14042 (setq scope (eval scope)))
14043 ((eq scope 'agenda)
14044 (setq scope (org-agenda-files t)))
14045 ((eq scope 'agenda-with-archives)
14046 (setq scope (org-agenda-files t))
14047 (setq scope (org-add-archive-files scope)))
14048 ((eq scope 'file)
14049 (setq scope (list (buffer-file-name))))
14050 ((eq scope 'file-with-archives)
14051 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14052 (org-prepare-agenda-buffers scope)
14053 (while (setq file (pop scope))
14054 (with-current-buffer (org-find-base-buffer-visiting file)
14055 (save-excursion
14056 (save-restriction
14057 (widen)
14058 (goto-char (point-min))
14059 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14060 res)))
14062 ;;;; Properties
14064 ;;; Setting and retrieving properties
14066 (defconst org-special-properties
14067 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14068 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
14069 "The special properties valid in Org-mode.
14071 These are properties that are not defined in the property drawer,
14072 but in some other way.")
14074 (defconst org-default-properties
14075 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14076 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14077 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14078 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14079 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14080 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14081 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14082 "Some properties that are used by Org-mode for various purposes.
14083 Being in this list makes sure that they are offered for completion.")
14085 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14086 "Regular expression matching the first line of a property drawer.")
14088 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14089 "Regular expression matching the last line of a property drawer.")
14091 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14092 "Regular expression matching the first line of a property drawer.")
14094 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14095 "Regular expression matching the first line of a property drawer.")
14097 (defconst org-property-drawer-re
14098 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14099 org-property-end-re "\\)\n?")
14100 "Matches an entire property drawer.")
14102 (defconst org-clock-drawer-re
14103 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14104 org-property-end-re "\\)\n?")
14105 "Matches an entire clock drawer.")
14107 (defsubst org-re-property (property)
14108 "Return a regexp matching PROPERTY.
14109 Match group 1 will be set to the value "
14110 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14112 (defun org-property-action ()
14113 "Do an action on properties."
14114 (interactive)
14115 (let (c)
14116 (org-at-property-p)
14117 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14118 (setq c (read-char-exclusive))
14119 (cond
14120 ((equal c ?s)
14121 (call-interactively 'org-set-property))
14122 ((equal c ?d)
14123 (call-interactively 'org-delete-property))
14124 ((equal c ?D)
14125 (call-interactively 'org-delete-property-globally))
14126 ((equal c ?c)
14127 (call-interactively 'org-compute-property-at-point))
14128 (t (error "No such property action %c" c)))))
14130 (defun org-set-effort (&optional value)
14131 "Set the effort property of the current entry.
14132 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14133 allowed value."
14134 (interactive "P")
14135 (if (equal value 0) (setq value 10))
14136 (let* ((completion-ignore-case t)
14137 (prop org-effort-property)
14138 (cur (org-entry-get nil prop))
14139 (allowed (org-property-get-allowed-values nil prop 'table))
14140 (existing (mapcar 'list (org-property-values prop)))
14142 (val (cond
14143 ((stringp value) value)
14144 ((and allowed (integerp value))
14145 (or (car (nth (1- value) allowed))
14146 (car (org-last allowed))))
14147 (allowed
14148 (message "Select 1-9,0, [RET%s]: %s"
14149 (if cur (concat "=" cur) "")
14150 (mapconcat 'car allowed " "))
14151 (setq rpl (read-char-exclusive))
14152 (if (equal rpl ?\r)
14154 (setq rpl (- rpl ?0))
14155 (if (equal rpl 0) (setq rpl 10))
14156 (if (and (> rpl 0) (<= rpl (length allowed)))
14157 (car (nth (1- rpl) allowed))
14158 (org-completing-read "Effort: " allowed nil))))
14160 (let (org-completion-use-ido org-completion-use-iswitchb)
14161 (org-completing-read
14162 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14163 (concat "[" cur "]") "")
14164 ": ")
14165 existing nil nil "" nil cur))))))
14166 (unless (equal (org-entry-get nil prop) val)
14167 (org-entry-put nil prop val))
14168 (message "%s is now %s" prop val)))
14170 (defun org-at-property-p ()
14171 "Is cursor inside a property drawer?"
14172 (save-excursion
14173 (beginning-of-line 1)
14174 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14175 (save-match-data ;; Used by calling procedures
14176 (let ((p (point))
14177 (range (unless (org-before-first-heading-p)
14178 (org-get-property-block))))
14179 (and range (<= (car range) p) (< p (cdr range))))))))
14181 (defun org-get-property-block (&optional beg end force)
14182 "Return the (beg . end) range of the body of the property drawer.
14183 BEG and END can be beginning and end of subtree, if not given
14184 they will be found.
14185 If the drawer does not exist and FORCE is non-nil, create the drawer."
14186 (catch 'exit
14187 (save-excursion
14188 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14189 (end (or end (progn (outline-next-heading) (point)))))
14190 (goto-char beg)
14191 (if (re-search-forward org-property-start-re end t)
14192 (setq beg (1+ (match-end 0)))
14193 (if force
14194 (save-excursion
14195 (org-insert-property-drawer)
14196 (setq end (progn (outline-next-heading) (point))))
14197 (throw 'exit nil))
14198 (goto-char beg)
14199 (if (re-search-forward org-property-start-re end t)
14200 (setq beg (1+ (match-end 0)))))
14201 (if (re-search-forward org-property-end-re end t)
14202 (setq end (match-beginning 0))
14203 (or force (throw 'exit nil))
14204 (goto-char beg)
14205 (setq end beg)
14206 (org-indent-line)
14207 (insert ":END:\n"))
14208 (cons beg end)))))
14210 (defun org-entry-properties (&optional pom which specific)
14211 "Get all properties of the entry at point-or-marker POM.
14212 This includes the TODO keyword, the tags, time strings for deadline,
14213 scheduled, and clocking, and any additional properties defined in the
14214 entry. The return value is an alist, keys may occur multiple times
14215 if the property key was used several times.
14216 POM may also be nil, in which case the current entry is used.
14217 If WHICH is nil or `all', get all properties. If WHICH is
14218 `special' or `standard', only get that subclass. If WHICH
14219 is a string only get exactly this property. SPECIFIC can be a string, the
14220 specific property we are interested in. Specifying it can speed
14221 things up because then unnecessary parsing is avoided."
14222 (setq which (or which 'all))
14223 (org-with-point-at pom
14224 (let ((clockstr (substring org-clock-string 0 -1))
14225 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14226 (case-fold-search nil)
14227 beg end range props sum-props key key1 value string clocksum)
14228 (save-excursion
14229 (when (condition-case nil
14230 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14231 (error nil))
14232 (setq beg (point))
14233 (setq sum-props (get-text-property (point) 'org-summaries))
14234 (setq clocksum (get-text-property (point) :org-clock-minutes))
14235 (outline-next-heading)
14236 (setq end (point))
14237 (when (memq which '(all special))
14238 ;; Get the special properties, like TODO and tags
14239 (goto-char beg)
14240 (when (and (or (not specific) (string= specific "TODO"))
14241 (looking-at org-todo-line-regexp) (match-end 2))
14242 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14243 (when (and (or (not specific) (string= specific "PRIORITY"))
14244 (looking-at org-priority-regexp))
14245 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14246 (when (or (not specific) (string= specific "FILE"))
14247 (push (cons "FILE" buffer-file-name) props))
14248 (when (and (or (not specific) (string= specific "TAGS"))
14249 (setq value (org-get-tags-string))
14250 (string-match "\\S-" value))
14251 (push (cons "TAGS" value) props))
14252 (when (and (or (not specific) (string= specific "ALLTAGS"))
14253 (setq value (org-get-tags-at)))
14254 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14255 ":"))
14256 props))
14257 (when (or (not specific) (string= specific "BLOCKED"))
14258 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14259 (when (or (not specific)
14260 (member specific
14261 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14262 "TIMESTAMP" "TIMESTAMP_IA")))
14263 (catch 'match
14264 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14265 (setq key (if (match-end 1)
14266 (substring (org-match-string-no-properties 1)
14267 0 -1))
14268 string (if (equal key clockstr)
14269 (org-no-properties
14270 (org-trim
14271 (buffer-substring
14272 (match-beginning 3) (goto-char
14273 (point-at-eol)))))
14274 (substring (org-match-string-no-properties 3)
14275 1 -1)))
14276 ;; Get the correct property name from the key. This is
14277 ;; necessary if the user has configured time keywords.
14278 (setq key1 (concat key ":"))
14279 (cond
14280 ((not key)
14281 (setq key
14282 (if (= (char-after (match-beginning 3)) ?\[)
14283 "TIMESTAMP_IA" "TIMESTAMP")))
14284 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14285 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14286 ((equal key1 org-closed-string) (setq key "CLOSED"))
14287 ((equal key1 org-clock-string) (setq key "CLOCK")))
14288 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14289 (progn
14290 (push (cons key string) props)
14291 ;; no need to search further if match is found
14292 (throw 'match t))
14293 (when (or (equal key "CLOCK") (not (assoc key props)))
14294 (push (cons key string) props))))))
14297 (when (memq which '(all standard))
14298 ;; Get the standard properties, like :PROP: ...
14299 (setq range (org-get-property-block beg end))
14300 (when range
14301 (goto-char (car range))
14302 (while (re-search-forward
14303 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14304 (cdr range) t)
14305 (setq key (org-match-string-no-properties 1)
14306 value (org-trim (or (org-match-string-no-properties 2) "")))
14307 (unless (member key excluded)
14308 (push (cons key (or value "")) props)))))
14309 (if clocksum
14310 (push (cons "CLOCKSUM"
14311 (org-columns-number-to-string (/ (float clocksum) 60.)
14312 'add_times))
14313 props))
14314 (unless (assoc "CATEGORY" props)
14315 (push (cons "CATEGORY" (org-get-category)) props))
14316 (append sum-props (nreverse props)))))))
14318 (defun org-entry-get (pom property &optional inherit literal-nil)
14319 "Get value of PROPERTY for entry at point-or-marker POM.
14320 If INHERIT is non-nil and the entry does not have the property,
14321 then also check higher levels of the hierarchy.
14322 If INHERIT is the symbol `selective', use inheritance only if the setting
14323 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14324 If the property is present but empty, the return value is the empty string.
14325 If the property is not present at all, nil is returned.
14327 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14328 do not interpret it as the list atom nil. This is used for inheritance
14329 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14330 (org-with-point-at pom
14331 (if (and inherit (if (eq inherit 'selective)
14332 (org-property-inherit-p property)
14334 (org-entry-get-with-inheritance property literal-nil)
14335 (if (member property org-special-properties)
14336 ;; We need a special property. Use `org-entry-properties' to
14337 ;; retrieve it, but specify the wanted property
14338 (cdr (assoc property (org-entry-properties nil 'special property)))
14339 (let ((range (unless (org-before-first-heading-p)
14340 (org-get-property-block)))
14341 (props (list (or (assoc property org-file-properties)
14342 (assoc property org-global-properties)
14343 (assoc property org-global-properties-fixed))))
14344 val)
14345 (org-flet ((ap (key)
14346 (when (re-search-forward
14347 (org-re-property key) (cdr range) t)
14348 (setq props
14349 (org-update-property-plist
14351 (if (match-end 1)
14352 (org-match-string-no-properties 1) "")
14353 props)))))
14354 (when (and range (goto-char (car range)))
14355 (ap property)
14356 (goto-char (car range))
14357 (while (ap (concat property "+")))
14358 (setq val (cdr (assoc property props)))
14359 (when val (if literal-nil val (org-not-nil val))))))))))
14361 (defun org-property-or-variable-value (var &optional inherit)
14362 "Check if there is a property fixing the value of VAR.
14363 If yes, return this value. If not, return the current value of the variable."
14364 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14365 (if (and prop (stringp prop) (string-match "\\S-" prop))
14366 (read prop)
14367 (symbol-value var))))
14369 (defun org-entry-delete (pom property)
14370 "Delete the property PROPERTY from entry at point-or-marker POM."
14371 (org-with-point-at pom
14372 (if (member property org-special-properties)
14373 nil ; cannot delete these properties.
14374 (let ((range (org-get-property-block)))
14375 (if (and range
14376 (goto-char (car range))
14377 (re-search-forward
14378 (org-re-property property)
14379 (cdr range) t))
14380 (progn
14381 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14383 nil)))))
14385 ;; Multi-values properties are properties that contain multiple values
14386 ;; These values are assumed to be single words, separated by whitespace.
14387 (defun org-entry-add-to-multivalued-property (pom property value)
14388 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14389 (let* ((old (org-entry-get pom property))
14390 (values (and old (org-split-string old "[ \t]"))))
14391 (setq value (org-entry-protect-space value))
14392 (unless (member value values)
14393 (setq values (cons value values))
14394 (org-entry-put pom property
14395 (mapconcat 'identity values " ")))))
14397 (defun org-entry-remove-from-multivalued-property (pom property value)
14398 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14399 (let* ((old (org-entry-get pom property))
14400 (values (and old (org-split-string old "[ \t]"))))
14401 (setq value (org-entry-protect-space value))
14402 (when (member value values)
14403 (setq values (delete value values))
14404 (org-entry-put pom property
14405 (mapconcat 'identity values " ")))))
14407 (defun org-entry-member-in-multivalued-property (pom property value)
14408 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14409 (let* ((old (org-entry-get pom property))
14410 (values (and old (org-split-string old "[ \t]"))))
14411 (setq value (org-entry-protect-space value))
14412 (member value values)))
14414 (defun org-entry-get-multivalued-property (pom property)
14415 "Return a list of values in a multivalued property."
14416 (let* ((value (org-entry-get pom property))
14417 (values (and value (org-split-string value "[ \t]"))))
14418 (mapcar 'org-entry-restore-space values)))
14420 (defun org-entry-put-multivalued-property (pom property &rest values)
14421 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14422 VALUES should be a list of strings. Spaces will be protected."
14423 (org-entry-put pom property
14424 (mapconcat 'org-entry-protect-space values " "))
14425 (let* ((value (org-entry-get pom property))
14426 (values (and value (org-split-string value "[ \t]"))))
14427 (mapcar 'org-entry-restore-space values)))
14429 (defun org-entry-protect-space (s)
14430 "Protect spaces and newline in string S."
14431 (while (string-match " " s)
14432 (setq s (replace-match "%20" t t s)))
14433 (while (string-match "\n" s)
14434 (setq s (replace-match "%0A" t t s)))
14437 (defun org-entry-restore-space (s)
14438 "Restore spaces and newline in string S."
14439 (while (string-match "%20" s)
14440 (setq s (replace-match " " t t s)))
14441 (while (string-match "%0A" s)
14442 (setq s (replace-match "\n" t t s)))
14445 (defvar org-entry-property-inherited-from (make-marker)
14446 "Marker pointing to the entry from where a property was inherited.
14447 Each call to `org-entry-get-with-inheritance' will set this marker to the
14448 location of the entry where the inheritance search matched. If there was
14449 no match, the marker will point nowhere.
14450 Note that also `org-entry-get' calls this function, if the INHERIT flag
14451 is set.")
14453 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14454 "Get entry property, and search higher levels if not present.
14455 The search will stop at the first ancestor which has the property defined.
14456 If the value found is \"nil\", return nil to show that the property
14457 should be considered as undefined (this is the meaning of nil here).
14458 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14459 (move-marker org-entry-property-inherited-from nil)
14460 (let (tmp)
14461 (unless (org-before-first-heading-p)
14462 (save-excursion
14463 (save-restriction
14464 (widen)
14465 (catch 'ex
14466 (while t
14467 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14468 (org-back-to-heading t)
14469 (move-marker org-entry-property-inherited-from (point))
14470 (throw 'ex tmp))
14471 (or (org-up-heading-safe) (throw 'ex nil)))))))
14472 (setq tmp (or tmp
14473 (cdr (assoc property org-file-properties))
14474 (cdr (assoc property org-global-properties))
14475 (cdr (assoc property org-global-properties-fixed))))
14476 (if literal-nil tmp (org-not-nil tmp))))
14478 (defvar org-property-changed-functions nil
14479 "Hook called when the value of a property has changed.
14480 Each hook function should accept two arguments, the name of the property
14481 and the new value.")
14483 (defun org-entry-put (pom property value)
14484 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14485 (org-with-point-at pom
14486 (org-back-to-heading t)
14487 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14488 range)
14489 (cond
14490 ((equal property "TODO")
14491 (when (and (stringp value) (string-match "\\S-" value)
14492 (not (member value org-todo-keywords-1)))
14493 (error "\"%s\" is not a valid TODO state" value))
14494 (if (or (not value)
14495 (not (string-match "\\S-" value)))
14496 (setq value 'none))
14497 (org-todo value)
14498 (org-set-tags nil 'align))
14499 ((equal property "PRIORITY")
14500 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14501 (string-to-char value) ?\ ))
14502 (org-set-tags nil 'align))
14503 ((equal property "SCHEDULED")
14504 (if (re-search-forward org-scheduled-time-regexp end t)
14505 (cond
14506 ((eq value 'earlier) (org-timestamp-change -1 'day))
14507 ((eq value 'later) (org-timestamp-change 1 'day))
14508 (t (call-interactively 'org-schedule)))
14509 (call-interactively 'org-schedule)))
14510 ((equal property "DEADLINE")
14511 (if (re-search-forward org-deadline-time-regexp end t)
14512 (cond
14513 ((eq value 'earlier) (org-timestamp-change -1 'day))
14514 ((eq value 'later) (org-timestamp-change 1 'day))
14515 (t (call-interactively 'org-deadline)))
14516 (call-interactively 'org-deadline)))
14517 ((member property org-special-properties)
14518 (error "The %s property can not yet be set with `org-entry-put'"
14519 property))
14520 (t ; a non-special property
14521 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14522 (setq range (org-get-property-block beg end 'force))
14523 (goto-char (car range))
14524 (if (re-search-forward
14525 (org-re-property property) (cdr range) t)
14526 (progn
14527 (delete-region (match-beginning 0) (match-end 0))
14528 (goto-char (match-beginning 0)))
14529 (goto-char (cdr range))
14530 (insert "\n")
14531 (backward-char 1)
14532 (org-indent-line))
14533 (insert ":" property ":")
14534 (and value (insert " " value))
14535 (org-indent-line)))))
14536 (run-hook-with-args 'org-property-changed-functions property value)))
14538 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14539 "Get all property keys in the current buffer.
14540 With INCLUDE-SPECIALS, also list the special properties that reflect things
14541 like tags and TODO state.
14542 With INCLUDE-DEFAULTS, also include properties that has special meaning
14543 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14544 and others.
14545 With INCLUDE-COLUMNS, also include property names given in COLUMN
14546 formats in the current buffer."
14547 (let (rtn range cfmt s p)
14548 (save-excursion
14549 (save-restriction
14550 (widen)
14551 (goto-char (point-min))
14552 (while (re-search-forward org-property-start-re nil t)
14553 (setq range (org-get-property-block))
14554 (goto-char (car range))
14555 (while (re-search-forward
14556 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14557 (cdr range) t)
14558 (add-to-list 'rtn (org-match-string-no-properties 1)))
14559 (outline-next-heading))))
14561 (when include-specials
14562 (setq rtn (append org-special-properties rtn)))
14564 (when include-defaults
14565 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14566 (add-to-list 'rtn org-effort-property))
14568 (when include-columns
14569 (save-excursion
14570 (save-restriction
14571 (widen)
14572 (goto-char (point-min))
14573 (while (re-search-forward
14574 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14575 nil t)
14576 (setq cfmt (match-string 2) s 0)
14577 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14578 cfmt s)
14579 (setq s (match-end 0)
14580 p (match-string 1 cfmt))
14581 (unless (or (equal p "ITEM")
14582 (member p org-special-properties))
14583 (add-to-list 'rtn (match-string 1 cfmt))))))))
14585 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14587 (defun org-property-values (key)
14588 "Return a list of all values of property KEY in the current buffer."
14589 (save-excursion
14590 (save-restriction
14591 (widen)
14592 (goto-char (point-min))
14593 (let ((re (org-re-property key))
14594 values)
14595 (while (re-search-forward re nil t)
14596 (add-to-list 'values (org-trim (match-string 1))))
14597 (delete "" values)))))
14599 (defun org-insert-property-drawer ()
14600 "Insert a property drawer into the current entry."
14601 (org-back-to-heading t)
14602 (looking-at org-outline-regexp)
14603 (let ((indent (if org-adapt-indentation
14604 (- (match-end 0) (match-beginning 0))
14606 (beg (point))
14607 (re (concat "^[ \t]*" org-keyword-time-regexp))
14608 end hiddenp)
14609 (outline-next-heading)
14610 (setq end (point))
14611 (goto-char beg)
14612 (while (re-search-forward re end t))
14613 (setq hiddenp (outline-invisible-p))
14614 (end-of-line 1)
14615 (and (equal (char-after) ?\n) (forward-char 1))
14616 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14617 (if (member (match-string 1) '("CLOCK:" ":END:"))
14618 ;; just skip this line
14619 (beginning-of-line 2)
14620 ;; Drawer start, find the end
14621 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14622 (beginning-of-line 1)))
14623 (org-skip-over-state-notes)
14624 (skip-chars-backward " \t\n\r")
14625 (if (eq (char-before) ?*) (forward-char 1))
14626 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14627 (beginning-of-line 0)
14628 (org-indent-to-column indent)
14629 (beginning-of-line 2)
14630 (org-indent-to-column indent)
14631 (beginning-of-line 0)
14632 (if hiddenp
14633 (save-excursion
14634 (org-back-to-heading t)
14635 (hide-entry))
14636 (org-flag-drawer t))))
14638 (defun org-insert-drawer (&optional arg drawer)
14639 "Insert a drawer at point.
14641 Optional argument DRAWER, when non-nil, is a string representing
14642 drawer's name. Otherwise, the user is prompted for a name.
14644 If a region is active, insert the drawer around that region
14645 instead.
14647 Point is left between drawer's boundaries."
14648 (interactive "P")
14649 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14650 "LOGBOOK"))
14651 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14652 ;; internally by Org. They are meant to be inserted
14653 ;; automatically.
14654 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14655 ;; Remove system drawers from list. Note: For some reason,
14656 ;; `org-completing-read' ignores the predicate while
14657 ;; `completing-read' handles it fine.
14658 (drawer (if arg "PROPERTIES"
14659 (or drawer
14660 (completing-read
14661 "Drawer: " org-drawers
14662 (lambda (d) (not (member d system-drawers))))))))
14663 (cond
14664 ;; With C-u, fall back on `org-insert-property-drawer'
14665 (arg (org-insert-property-drawer))
14666 ;; With an active region, insert a drawer at point.
14667 ((not (org-region-active-p))
14668 (progn
14669 (unless (bolp) (insert "\n"))
14670 (insert (format ":%s:\n\n:END:\n" drawer))
14671 (forward-line -2)))
14672 ;; Otherwise, insert the drawer at point
14674 (let ((rbeg (region-beginning))
14675 (rend (copy-marker (region-end))))
14676 (unwind-protect
14677 (progn
14678 (goto-char rbeg)
14679 (beginning-of-line)
14680 (when (save-excursion
14681 (re-search-forward org-outline-regexp-bol rend t))
14682 (error "Drawers cannot contain headlines"))
14683 ;; Position point at the beginning of the first
14684 ;; non-blank line in region. Insert drawer's opening
14685 ;; there, then indent it.
14686 (org-skip-whitespace)
14687 (beginning-of-line)
14688 (insert ":" drawer ":\n")
14689 (forward-line -1)
14690 (indent-for-tab-command)
14691 ;; Move point to the beginning of the first blank line
14692 ;; after the last non-blank line in region. Insert
14693 ;; drawer's closing, then indent it.
14694 (goto-char rend)
14695 (skip-chars-backward " \r\t\n")
14696 (insert "\n:END:")
14697 (indent-for-tab-command)
14698 (unless (eolp) (insert "\n")))
14699 ;; Clear marker, whatever the outcome of insertion is.
14700 (set-marker rend nil)))))))
14702 (defvar org-property-set-functions-alist nil
14703 "Property set function alist.
14704 Each entry should have the following format:
14706 (PROPERTY . READ-FUNCTION)
14708 The read function will be called with the same argument as
14709 `org-completing-read'.")
14711 (defun org-set-property-function (property)
14712 "Get the function that should be used to set PROPERTY.
14713 This is computed according to `org-property-set-functions-alist'."
14714 (or (cdr (assoc property org-property-set-functions-alist))
14715 'org-completing-read))
14717 (defun org-read-property-value (property)
14718 "Read PROPERTY value from user."
14719 (let* ((completion-ignore-case t)
14720 (allowed (org-property-get-allowed-values nil property 'table))
14721 (cur (org-entry-get nil property))
14722 (prompt (concat property " value"
14723 (if (and cur (string-match "\\S-" cur))
14724 (concat " [" cur "]") "") ": "))
14725 (set-function (org-set-property-function property))
14726 (val (if allowed
14727 (funcall set-function prompt allowed nil
14728 (not (get-text-property 0 'org-unrestricted
14729 (caar allowed))))
14730 (let (org-completion-use-ido org-completion-use-iswitchb)
14731 (funcall set-function prompt
14732 (mapcar 'list (org-property-values property))
14733 nil nil "" nil cur)))))
14734 (if (equal val "")
14736 val)))
14738 (defvar org-last-set-property nil)
14739 (defun org-read-property-name ()
14740 "Read a property name."
14741 (let* ((completion-ignore-case t)
14742 (keys (org-buffer-property-keys nil t t))
14743 (default-prop (or (save-excursion
14744 (save-match-data
14745 (beginning-of-line)
14746 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14747 (null (string= (match-string 1) "END"))
14748 (match-string 1))))
14749 org-last-set-property))
14750 (property (org-icompleting-read
14751 (concat "Property"
14752 (if default-prop (concat " [" default-prop "]") "")
14753 ": ")
14754 (mapcar 'list keys)
14755 nil nil nil nil
14756 default-prop
14758 (if (member property keys)
14759 property
14760 (or (cdr (assoc (downcase property)
14761 (mapcar (lambda (x) (cons (downcase x) x))
14762 keys)))
14763 property))))
14765 (defun org-set-property (property value)
14766 "In the current entry, set PROPERTY to VALUE.
14767 When called interactively, this will prompt for a property name, offering
14768 completion on existing and default properties. And then it will prompt
14769 for a value, offering completion either on allowed values (via an inherited
14770 xxx_ALL property) or on existing values in other instances of this property
14771 in the current file."
14772 (interactive (list nil nil))
14773 (let* ((property (or property (org-read-property-name)))
14774 (value (or value (org-read-property-value property)))
14775 (fn (cdr (assoc property org-properties-postprocess-alist))))
14776 (setq org-last-set-property property)
14777 ;; Possibly postprocess the inserted value:
14778 (when fn (setq value (funcall fn value)))
14779 (unless (equal (org-entry-get nil property) value)
14780 (org-entry-put nil property value))))
14782 (defun org-delete-property (property)
14783 "In the current entry, delete PROPERTY."
14784 (interactive
14785 (let* ((completion-ignore-case t)
14786 (prop (org-icompleting-read "Property: "
14787 (org-entry-properties nil 'standard))))
14788 (list prop)))
14789 (message "Property %s %s" property
14790 (if (org-entry-delete nil property)
14791 "deleted"
14792 "was not present in the entry")))
14794 (defun org-delete-property-globally (property)
14795 "Remove PROPERTY globally, from all entries."
14796 (interactive
14797 (let* ((completion-ignore-case t)
14798 (prop (org-icompleting-read
14799 "Globally remove property: "
14800 (mapcar 'list (org-buffer-property-keys)))))
14801 (list prop)))
14802 (save-excursion
14803 (save-restriction
14804 (widen)
14805 (goto-char (point-min))
14806 (let ((cnt 0))
14807 (while (re-search-forward
14808 (org-re-property property)
14809 nil t)
14810 (setq cnt (1+ cnt))
14811 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14812 (message "Property \"%s\" removed from %d entries" property cnt)))))
14814 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14816 (defun org-compute-property-at-point ()
14817 "Compute the property at point.
14818 This looks for an enclosing column format, extracts the operator and
14819 then applies it to the property in the column format's scope."
14820 (interactive)
14821 (unless (org-at-property-p)
14822 (error "Not at a property"))
14823 (let ((prop (org-match-string-no-properties 2)))
14824 (org-columns-get-format-and-top-level)
14825 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14826 (error "No operator defined for property %s" prop))
14827 (org-columns-compute prop)))
14829 (defvar org-property-allowed-value-functions nil
14830 "Hook for functions supplying allowed values for a specific property.
14831 The functions must take a single argument, the name of the property, and
14832 return a flat list of allowed values. If \":ETC\" is one of
14833 the values, this means that these values are intended as defaults for
14834 completion, but that other values should be allowed too.
14835 The functions must return nil if they are not responsible for this
14836 property.")
14838 (defun org-property-get-allowed-values (pom property &optional table)
14839 "Get allowed values for the property PROPERTY.
14840 When TABLE is non-nil, return an alist that can directly be used for
14841 completion."
14842 (let (vals)
14843 (cond
14844 ((equal property "TODO")
14845 (setq vals (org-with-point-at pom
14846 (append org-todo-keywords-1 '("")))))
14847 ((equal property "PRIORITY")
14848 (let ((n org-lowest-priority))
14849 (while (>= n org-highest-priority)
14850 (push (char-to-string n) vals)
14851 (setq n (1- n)))))
14852 ((member property org-special-properties))
14853 ((setq vals (run-hook-with-args-until-success
14854 'org-property-allowed-value-functions property)))
14856 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14857 (when (and vals (string-match "\\S-" vals))
14858 (setq vals (car (read-from-string (concat "(" vals ")"))))
14859 (setq vals (mapcar (lambda (x)
14860 (cond ((stringp x) x)
14861 ((numberp x) (number-to-string x))
14862 ((symbolp x) (symbol-name x))
14863 (t "???")))
14864 vals)))))
14865 (when (member ":ETC" vals)
14866 (setq vals (remove ":ETC" vals))
14867 (org-add-props (car vals) '(org-unrestricted t)))
14868 (if table (mapcar 'list vals) vals)))
14870 (defun org-property-previous-allowed-value (&optional previous)
14871 "Switch to the next allowed value for this property."
14872 (interactive)
14873 (org-property-next-allowed-value t))
14875 (defun org-property-next-allowed-value (&optional previous)
14876 "Switch to the next allowed value for this property."
14877 (interactive)
14878 (unless (org-at-property-p)
14879 (error "Not at a property"))
14880 (let* ((key (match-string 2))
14881 (value (match-string 3))
14882 (allowed (or (org-property-get-allowed-values (point) key)
14883 (and (member value '("[ ]" "[-]" "[X]"))
14884 '("[ ]" "[X]"))))
14885 nval)
14886 (unless allowed
14887 (error "Allowed values for this property have not been defined"))
14888 (if previous (setq allowed (reverse allowed)))
14889 (if (member value allowed)
14890 (setq nval (car (cdr (member value allowed)))))
14891 (setq nval (or nval (car allowed)))
14892 (if (equal nval value)
14893 (error "Only one allowed value for this property"))
14894 (org-at-property-p)
14895 (replace-match (concat " :" key ": " nval) t t)
14896 (org-indent-line)
14897 (beginning-of-line 1)
14898 (skip-chars-forward " \t")
14899 (run-hook-with-args 'org-property-changed-functions key nval)))
14901 (defun org-find-olp (path &optional this-buffer)
14902 "Return a marker pointing to the entry at outline path OLP.
14903 If anything goes wrong, throw an error.
14904 You can wrap this call to catch the error like this:
14906 (condition-case msg
14907 (org-mobile-locate-entry (match-string 4))
14908 (error (nth 1 msg)))
14910 The return value will then be either a string with the error message,
14911 or a marker if everything is OK.
14913 If THIS-BUFFER is set, the outline path does not contain a file,
14914 only headings."
14915 (let* ((file (if this-buffer buffer-file-name (pop path)))
14916 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14917 (level 1)
14918 (lmin 1)
14919 (lmax 1)
14920 limit re end found pos heading cnt flevel)
14921 (unless buffer (error "File not found :%s" file))
14922 (with-current-buffer buffer
14923 (save-excursion
14924 (save-restriction
14925 (widen)
14926 (setq limit (point-max))
14927 (goto-char (point-min))
14928 (while (setq heading (pop path))
14929 (setq re (format org-complex-heading-regexp-format
14930 (regexp-quote heading)))
14931 (setq cnt 0 pos (point))
14932 (while (re-search-forward re end t)
14933 (setq level (- (match-end 1) (match-beginning 1)))
14934 (if (and (>= level lmin) (<= level lmax))
14935 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14936 (when (= cnt 0) (error "Heading not found on level %d: %s"
14937 lmax heading))
14938 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14939 lmax heading))
14940 (goto-char found)
14941 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14942 (setq end (save-excursion (org-end-of-subtree t t))))
14943 (when (org-at-heading-p)
14944 (move-marker (make-marker) (point))))))))
14946 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14947 "Find node HEADING in BUFFER.
14948 Return a marker to the heading if it was found, or nil if not.
14949 If POS-ONLY is set, return just the position instead of a marker.
14951 The heading text must match exact, but it may have a TODO keyword,
14952 a priority cookie and tags in the standard locations."
14953 (with-current-buffer (or buffer (current-buffer))
14954 (save-excursion
14955 (save-restriction
14956 (widen)
14957 (goto-char (point-min))
14958 (let (case-fold-search)
14959 (if (re-search-forward
14960 (format org-complex-heading-regexp-format
14961 (regexp-quote heading)) nil t)
14962 (if pos-only
14963 (match-beginning 0)
14964 (move-marker (make-marker) (match-beginning 0)))))))))
14966 (defun org-find-exact-heading-in-directory (heading &optional dir)
14967 "Find Org node headline HEADING in all .org files in directory DIR.
14968 When the target headline is found, return a marker to this location."
14969 (let ((files (directory-files (or dir default-directory)
14970 nil "\\`[^.#].*\\.org\\'"))
14971 file visiting m buffer)
14972 (catch 'found
14973 (while (setq file (pop files))
14974 (message "trying %s" file)
14975 (setq visiting (org-find-base-buffer-visiting file))
14976 (setq buffer (or visiting (find-file-noselect file)))
14977 (setq m (org-find-exact-headline-in-buffer
14978 heading buffer))
14979 (when (and (not m) (not visiting)) (kill-buffer buffer))
14980 (and m (throw 'found m))))))
14982 (defun org-find-entry-with-id (ident)
14983 "Locate the entry that contains the ID property with exact value IDENT.
14984 IDENT can be a string, a symbol or a number, this function will search for
14985 the string representation of it.
14986 Return the position where this entry starts, or nil if there is no such entry."
14987 (interactive "sID: ")
14988 (let ((id (cond
14989 ((stringp ident) ident)
14990 ((symbol-name ident) (symbol-name ident))
14991 ((numberp ident) (number-to-string ident))
14992 (t (error "IDENT %s must be a string, symbol or number" ident))))
14993 (case-fold-search nil))
14994 (save-excursion
14995 (save-restriction
14996 (widen)
14997 (goto-char (point-min))
14998 (when (re-search-forward
14999 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15000 nil t)
15001 (org-back-to-heading t)
15002 (point))))))
15004 ;;;; Timestamps
15006 (defvar org-last-changed-timestamp nil)
15007 (defvar org-last-inserted-timestamp nil
15008 "The last time stamp inserted with `org-insert-time-stamp'.")
15009 (defvar org-time-was-given) ; dynamically scoped parameter
15010 (defvar org-end-time-was-given) ; dynamically scoped parameter
15011 (defvar org-ts-what) ; dynamically scoped parameter
15013 (defun org-time-stamp (arg &optional inactive)
15014 "Prompt for a date/time and insert a time stamp.
15015 If the user specifies a time like HH:MM or if this command is
15016 called with at least one prefix argument, the time stamp contains
15017 the date and the time. Otherwise, only the date is be included.
15019 All parts of a date not specified by the user is filled in from
15020 the current date/time. So if you just press return without
15021 typing anything, the time stamp will represent the current
15022 date/time.
15024 If there is already a timestamp at the cursor, it will be
15025 modified.
15027 With two universal prefix arguments, insert an active timestamp
15028 with the current time without prompting the user."
15029 (interactive "P")
15030 (let* ((ts nil)
15031 (default-time
15032 ;; Default time is either today, or, when entering a range,
15033 ;; the range start.
15034 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15035 (save-excursion
15036 (re-search-backward
15037 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15038 (- (point) 20) t)))
15039 (apply 'encode-time (org-parse-time-string (match-string 1)))
15040 (current-time)))
15041 (default-input (and ts (org-get-compact-tod ts)))
15042 (repeater (save-excursion
15043 (save-match-data
15044 (beginning-of-line)
15045 (when (re-search-forward
15046 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15047 (save-excursion (progn (end-of-line) (point))) t)
15048 (match-string 0)))))
15049 org-time-was-given org-end-time-was-given time)
15050 (cond
15051 ((and (org-at-timestamp-p t)
15052 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15053 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15054 (insert "--")
15055 (setq time (let ((this-command this-command))
15056 (org-read-date arg 'totime nil nil
15057 default-time default-input inactive)))
15058 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15059 ((org-at-timestamp-p t)
15060 (setq time (let ((this-command this-command))
15061 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15062 (when (org-at-timestamp-p t) ; just to get the match data
15063 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15064 (replace-match "")
15065 (setq org-last-changed-timestamp
15066 (org-insert-time-stamp
15067 time (or org-time-was-given arg)
15068 inactive nil nil (list org-end-time-was-given)))
15069 (when repeater (goto-char (1- (point))) (insert " " repeater)
15070 (setq org-last-changed-timestamp
15071 (concat (substring org-last-inserted-timestamp 0 -1)
15072 " " repeater ">"))))
15073 (message "Timestamp updated"))
15074 ((equal arg '(16))
15075 (org-insert-time-stamp (current-time) t))
15077 (setq time (let ((this-command this-command))
15078 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15079 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15080 nil nil (list org-end-time-was-given))))))
15082 ;; FIXME: can we use this for something else, like computing time differences?
15083 (defun org-get-compact-tod (s)
15084 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15085 (let* ((t1 (match-string 1 s))
15086 (h1 (string-to-number (match-string 2 s)))
15087 (m1 (string-to-number (match-string 3 s)))
15088 (t2 (and (match-end 4) (match-string 5 s)))
15089 (h2 (and t2 (string-to-number (match-string 6 s))))
15090 (m2 (and t2 (string-to-number (match-string 7 s))))
15091 dh dm)
15092 (if (not t2)
15094 (setq dh (- h2 h1) dm (- m2 m1))
15095 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15096 (concat t1 "+" (number-to-string dh)
15097 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15099 (defun org-time-stamp-inactive (&optional arg)
15100 "Insert an inactive time stamp.
15101 An inactive time stamp is enclosed in square brackets instead of angle
15102 brackets. It is inactive in the sense that it does not trigger agenda entries,
15103 does not link to the calendar and cannot be changed with the S-cursor keys.
15104 So these are more for recording a certain time/date."
15105 (interactive "P")
15106 (org-time-stamp arg 'inactive))
15108 (defvar org-date-ovl (make-overlay 1 1))
15109 (overlay-put org-date-ovl 'face 'org-date-selected)
15110 (org-detach-overlay org-date-ovl)
15112 (defvar org-ans1) ; dynamically scoped parameter
15113 (defvar org-ans2) ; dynamically scoped parameter
15115 (defvar org-plain-time-of-day-regexp) ; defined below
15117 (defvar org-overriding-default-time nil) ; dynamically scoped
15118 (defvar org-read-date-overlay nil)
15119 (defvar org-dcst nil) ; dynamically scoped
15120 (defvar org-read-date-history nil)
15121 (defvar org-read-date-final-answer nil)
15122 (defvar org-read-date-analyze-futurep nil)
15123 (defvar org-read-date-analyze-forced-year nil)
15124 (defvar org-read-date-inactive)
15126 (defun org-read-date (&optional org-with-time to-time from-string prompt
15127 default-time default-input inactive)
15128 "Read a date, possibly a time, and make things smooth for the user.
15129 The prompt will suggest to enter an ISO date, but you can also enter anything
15130 which will at least partially be understood by `parse-time-string'.
15131 Unrecognized parts of the date will default to the current day, month, year,
15132 hour and minute. If this command is called to replace a timestamp at point,
15133 or to enter the second timestamp of a range, the default time is taken
15134 from the existing stamp. Furthermore, the command prefers the future,
15135 so if you are giving a date where the year is not given, and the day-month
15136 combination is already past in the current year, it will assume you
15137 mean next year. For details, see the manual. A few examples:
15139 3-2-5 --> 2003-02-05
15140 feb 15 --> currentyear-02-15
15141 2/15 --> currentyear-02-15
15142 sep 12 9 --> 2009-09-12
15143 12:45 --> today 12:45
15144 22 sept 0:34 --> currentyear-09-22 0:34
15145 12 --> currentyear-currentmonth-12
15146 Fri --> nearest Friday (today or later)
15147 etc.
15149 Furthermore you can specify a relative date by giving, as the *first* thing
15150 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15151 change in days weeks, months, years.
15152 With a single plus or minus, the date is relative to today. With a double
15153 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15154 +4d --> four days from today
15155 +4 --> same as above
15156 +2w --> two weeks from today
15157 ++5 --> five days from default date
15159 The function understands only English month and weekday abbreviations.
15161 While prompting, a calendar is popped up - you can also select the
15162 date with the mouse (button 1). The calendar shows a period of three
15163 months. To scroll it to other months, use the keys `>' and `<'.
15164 If you don't like the calendar, turn it off with
15165 \(setq org-read-date-popup-calendar nil)
15167 With optional argument TO-TIME, the date will immediately be converted
15168 to an internal time.
15169 With an optional argument WITH-TIME, the prompt will suggest to also
15170 insert a time. Note that when WITH-TIME is not set, you can still
15171 enter a time, and this function will inform the calling routine about
15172 this change. The calling routine may then choose to change the format
15173 used to insert the time stamp into the buffer to include the time.
15174 With optional argument FROM-STRING, read from this string instead from
15175 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15176 the time/date that is used for everything that is not specified by the
15177 user."
15178 (require 'parse-time)
15179 (let* ((org-time-stamp-rounding-minutes
15180 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15181 (org-dcst org-display-custom-times)
15182 (ct (org-current-time))
15183 (org-def (or org-overriding-default-time default-time ct))
15184 (org-defdecode (decode-time org-def))
15185 (dummy (progn
15186 (when (< (nth 2 org-defdecode) org-extend-today-until)
15187 (setcar (nthcdr 2 org-defdecode) -1)
15188 (setcar (nthcdr 1 org-defdecode) 59)
15189 (setq org-def (apply 'encode-time org-defdecode)
15190 org-defdecode (decode-time org-def)))))
15191 (calendar-frame-setup nil)
15192 (calendar-setup nil)
15193 (calendar-move-hook nil)
15194 (calendar-view-diary-initially-flag nil)
15195 (calendar-view-holidays-initially-flag nil)
15196 (timestr (format-time-string
15197 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15198 (prompt (concat (if prompt (concat prompt " ") "")
15199 (format "Date+time [%s]: " timestr)))
15200 ans (org-ans0 "") org-ans1 org-ans2 final)
15202 (cond
15203 (from-string (setq ans from-string))
15204 (org-read-date-popup-calendar
15205 (save-excursion
15206 (save-window-excursion
15207 (calendar)
15208 (org-eval-in-calendar '(setq cursor-type nil) t)
15209 (unwind-protect
15210 (progn
15211 (calendar-forward-day (- (time-to-days org-def)
15212 (calendar-absolute-from-gregorian
15213 (calendar-current-date))))
15214 (org-eval-in-calendar nil t)
15215 (let* ((old-map (current-local-map))
15216 (map (copy-keymap calendar-mode-map))
15217 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15218 (org-defkey map (kbd "RET") 'org-calendar-select)
15219 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15220 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15221 (org-defkey minibuffer-local-map [(meta shift left)]
15222 (lambda () (interactive)
15223 (org-eval-in-calendar '(calendar-backward-month 1))))
15224 (org-defkey minibuffer-local-map [(meta shift right)]
15225 (lambda () (interactive)
15226 (org-eval-in-calendar '(calendar-forward-month 1))))
15227 (org-defkey minibuffer-local-map [(meta shift up)]
15228 (lambda () (interactive)
15229 (org-eval-in-calendar '(calendar-backward-year 1))))
15230 (org-defkey minibuffer-local-map [(meta shift down)]
15231 (lambda () (interactive)
15232 (org-eval-in-calendar '(calendar-forward-year 1))))
15233 (org-defkey minibuffer-local-map [?\e (shift left)]
15234 (lambda () (interactive)
15235 (org-eval-in-calendar '(calendar-backward-month 1))))
15236 (org-defkey minibuffer-local-map [?\e (shift right)]
15237 (lambda () (interactive)
15238 (org-eval-in-calendar '(calendar-forward-month 1))))
15239 (org-defkey minibuffer-local-map [?\e (shift up)]
15240 (lambda () (interactive)
15241 (org-eval-in-calendar '(calendar-backward-year 1))))
15242 (org-defkey minibuffer-local-map [?\e (shift down)]
15243 (lambda () (interactive)
15244 (org-eval-in-calendar '(calendar-forward-year 1))))
15245 (org-defkey minibuffer-local-map [(shift up)]
15246 (lambda () (interactive)
15247 (org-eval-in-calendar '(calendar-backward-week 1))))
15248 (org-defkey minibuffer-local-map [(shift down)]
15249 (lambda () (interactive)
15250 (org-eval-in-calendar '(calendar-forward-week 1))))
15251 (org-defkey minibuffer-local-map [(shift left)]
15252 (lambda () (interactive)
15253 (org-eval-in-calendar '(calendar-backward-day 1))))
15254 (org-defkey minibuffer-local-map [(shift right)]
15255 (lambda () (interactive)
15256 (org-eval-in-calendar '(calendar-forward-day 1))))
15257 (org-defkey minibuffer-local-map ">"
15258 (lambda () (interactive)
15259 (org-eval-in-calendar '(scroll-calendar-left 1))))
15260 (org-defkey minibuffer-local-map "<"
15261 (lambda () (interactive)
15262 (org-eval-in-calendar '(scroll-calendar-right 1))))
15263 (org-defkey minibuffer-local-map "\C-v"
15264 (lambda () (interactive)
15265 (org-eval-in-calendar
15266 '(calendar-scroll-left-three-months 1))))
15267 (org-defkey minibuffer-local-map "\M-v"
15268 (lambda () (interactive)
15269 (org-eval-in-calendar
15270 '(calendar-scroll-right-three-months 1))))
15271 (run-hooks 'org-read-date-minibuffer-setup-hook)
15272 (unwind-protect
15273 (progn
15274 (use-local-map map)
15275 (setq org-read-date-inactive inactive)
15276 (add-hook 'post-command-hook 'org-read-date-display)
15277 (setq org-ans0 (read-string prompt default-input
15278 'org-read-date-history nil))
15279 ;; org-ans0: from prompt
15280 ;; org-ans1: from mouse click
15281 ;; org-ans2: from calendar motion
15282 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15283 (remove-hook 'post-command-hook 'org-read-date-display)
15284 (use-local-map old-map)
15285 (when org-read-date-overlay
15286 (delete-overlay org-read-date-overlay)
15287 (setq org-read-date-overlay nil)))))
15288 (bury-buffer "*Calendar*")))))
15290 (t ; Naked prompt only
15291 (unwind-protect
15292 (setq ans (read-string prompt default-input
15293 'org-read-date-history timestr))
15294 (when org-read-date-overlay
15295 (delete-overlay org-read-date-overlay)
15296 (setq org-read-date-overlay nil)))))
15298 (setq final (org-read-date-analyze ans org-def org-defdecode))
15300 (when org-read-date-analyze-forced-year
15301 (message "Year was forced into %s"
15302 (if org-read-date-force-compatible-dates
15303 "compatible range (1970-2037)"
15304 "range representable on this machine"))
15305 (ding))
15307 ;; One round trip to get rid of 34th of August and stuff like that....
15308 (setq final (decode-time (apply 'encode-time final)))
15310 (setq org-read-date-final-answer ans)
15312 (if to-time
15313 (apply 'encode-time final)
15314 (if (and (boundp 'org-time-was-given) org-time-was-given)
15315 (format "%04d-%02d-%02d %02d:%02d"
15316 (nth 5 final) (nth 4 final) (nth 3 final)
15317 (nth 2 final) (nth 1 final))
15318 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15320 (defvar org-def)
15321 (defvar org-defdecode)
15322 (defvar org-with-time)
15323 (defun org-read-date-display ()
15324 "Display the current date prompt interpretation in the minibuffer."
15325 (when org-read-date-display-live
15326 (when org-read-date-overlay
15327 (delete-overlay org-read-date-overlay))
15328 (when (minibufferp (current-buffer))
15329 (save-excursion
15330 (end-of-line 1)
15331 (while (not (equal (buffer-substring
15332 (max (point-min) (- (point) 4)) (point))
15333 " "))
15334 (insert " ")))
15335 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15336 " " (or org-ans1 org-ans2)))
15337 (org-end-time-was-given nil)
15338 (f (org-read-date-analyze ans org-def org-defdecode))
15339 (fmts (if org-dcst
15340 org-time-stamp-custom-formats
15341 org-time-stamp-formats))
15342 (fmt (if (or org-with-time
15343 (and (boundp 'org-time-was-given) org-time-was-given))
15344 (cdr fmts)
15345 (car fmts)))
15346 (txt (format-time-string fmt (apply 'encode-time f)))
15347 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15348 (txt (concat "=> " txt)))
15349 (when (and org-end-time-was-given
15350 (string-match org-plain-time-of-day-regexp txt))
15351 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15352 org-end-time-was-given
15353 (substring txt (match-end 0)))))
15354 (when org-read-date-analyze-futurep
15355 (setq txt (concat txt " (=>F)")))
15356 (setq org-read-date-overlay
15357 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15358 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15360 (defun org-read-date-analyze (ans org-def org-defdecode)
15361 "Analyze the combined answer of the date prompt."
15362 ;; FIXME: cleanup and comment
15363 (let ((nowdecode (decode-time (current-time)))
15364 delta deltan deltaw deltadef year month day
15365 hour minute second wday pm h2 m2 tl wday1
15366 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15367 (setq org-read-date-analyze-futurep nil
15368 org-read-date-analyze-forced-year nil)
15369 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15370 (setq ans "+0"))
15372 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15373 (setq ans (replace-match "" t t ans)
15374 deltan (car delta)
15375 deltaw (nth 1 delta)
15376 deltadef (nth 2 delta)))
15378 ;; Check if there is an iso week date in there
15379 ;; If yes, store the info and postpone interpreting it until the rest
15380 ;; of the parsing is done
15381 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15382 (setq iso-year (if (match-end 1)
15383 (org-small-year-to-year
15384 (string-to-number (match-string 1 ans))))
15385 iso-weekday (if (match-end 3)
15386 (string-to-number (match-string 3 ans)))
15387 iso-week (string-to-number (match-string 2 ans)))
15388 (setq ans (replace-match "" t t ans)))
15390 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15391 (when (string-match
15392 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15393 (setq year (if (match-end 2)
15394 (string-to-number (match-string 2 ans))
15395 (progn (setq kill-year t)
15396 (string-to-number (format-time-string "%Y"))))
15397 month (string-to-number (match-string 3 ans))
15398 day (string-to-number (match-string 4 ans)))
15399 (if (< year 100) (setq year (+ 2000 year)))
15400 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15401 t nil ans)))
15403 ;; Help matching dotted european dates
15404 (when (string-match
15405 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15406 (setq year (if (match-end 3)
15407 (string-to-number (match-string 3 ans))
15408 (progn (setq kill-year t)
15409 (string-to-number (format-time-string "%Y"))))
15410 day (string-to-number (match-string 1 ans))
15411 month (string-to-number (match-string 2 ans))
15412 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15413 t nil ans)))
15415 ;; Help matching american dates, like 5/30 or 5/30/7
15416 (when (string-match
15417 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15418 (setq year (if (match-end 4)
15419 (string-to-number (match-string 4 ans))
15420 (progn (setq kill-year t)
15421 (string-to-number (format-time-string "%Y"))))
15422 month (string-to-number (match-string 1 ans))
15423 day (string-to-number (match-string 2 ans)))
15424 (if (< year 100) (setq year (+ 2000 year)))
15425 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15426 t nil ans)))
15427 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15428 ;; If there is a time with am/pm, and *no* time without it, we convert
15429 ;; so that matching will be successful.
15430 (loop for i from 1 to 2 do ; twice, for end time as well
15431 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15432 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15433 (setq hour (string-to-number (match-string 1 ans))
15434 minute (if (match-end 3)
15435 (string-to-number (match-string 3 ans))
15437 pm (equal ?p
15438 (string-to-char (downcase (match-string 4 ans)))))
15439 (if (and (= hour 12) (not pm))
15440 (setq hour 0)
15441 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15442 (setq ans (replace-match (format "%02d:%02d" hour minute)
15443 t t ans))))
15445 ;; Check if a time range is given as a duration
15446 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15447 (setq hour (string-to-number (match-string 1 ans))
15448 h2 (+ hour (string-to-number (match-string 3 ans)))
15449 minute (string-to-number (match-string 2 ans))
15450 m2 (+ minute (if (match-end 5) (string-to-number
15451 (match-string 5 ans))0)))
15452 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15453 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15454 t t ans)))
15456 ;; Check if there is a time range
15457 (when (boundp 'org-end-time-was-given)
15458 (setq org-time-was-given nil)
15459 (when (and (string-match org-plain-time-of-day-regexp ans)
15460 (match-end 8))
15461 (setq org-end-time-was-given (match-string 8 ans))
15462 (setq ans (concat (substring ans 0 (match-beginning 7))
15463 (substring ans (match-end 7))))))
15465 (setq tl (parse-time-string ans)
15466 day (or (nth 3 tl) (nth 3 org-defdecode))
15467 month (or (nth 4 tl)
15468 (if (and org-read-date-prefer-future
15469 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15470 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15471 (nth 4 org-defdecode)))
15472 year (or (and (not kill-year) (nth 5 tl))
15473 (if (and org-read-date-prefer-future
15474 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15475 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15476 (nth 5 org-defdecode)))
15477 hour (or (nth 2 tl) (nth 2 org-defdecode))
15478 minute (or (nth 1 tl) (nth 1 org-defdecode))
15479 second (or (nth 0 tl) 0)
15480 wday (nth 6 tl))
15482 (when (and (eq org-read-date-prefer-future 'time)
15483 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15484 (equal day (nth 3 nowdecode))
15485 (equal month (nth 4 nowdecode))
15486 (equal year (nth 5 nowdecode))
15487 (nth 2 tl)
15488 (or (< (nth 2 tl) (nth 2 nowdecode))
15489 (and (= (nth 2 tl) (nth 2 nowdecode))
15490 (nth 1 tl)
15491 (< (nth 1 tl) (nth 1 nowdecode)))))
15492 (setq day (1+ day)
15493 futurep t))
15495 ;; Special date definitions below
15496 (cond
15497 (iso-week
15498 ;; There was an iso week
15499 (require 'cal-iso)
15500 (setq futurep nil)
15501 (setq year (or iso-year year)
15502 day (or iso-weekday wday 1)
15503 wday nil ; to make sure that the trigger below does not match
15504 iso-date (calendar-gregorian-from-absolute
15505 (calendar-absolute-from-iso
15506 (list iso-week day year))))
15507 ; FIXME: Should we also push ISO weeks into the future?
15508 ; (when (and org-read-date-prefer-future
15509 ; (not iso-year)
15510 ; (< (calendar-absolute-from-gregorian iso-date)
15511 ; (time-to-days (current-time))))
15512 ; (setq year (1+ year)
15513 ; iso-date (calendar-gregorian-from-absolute
15514 ; (calendar-absolute-from-iso
15515 ; (list iso-week day year)))))
15516 (setq month (car iso-date)
15517 year (nth 2 iso-date)
15518 day (nth 1 iso-date)))
15519 (deltan
15520 (setq futurep nil)
15521 (unless deltadef
15522 (let ((now (decode-time (current-time))))
15523 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15524 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15525 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15526 ((equal deltaw "m") (setq month (+ month deltan)))
15527 ((equal deltaw "y") (setq year (+ year deltan)))))
15528 ((and wday (not (nth 3 tl)))
15529 (setq futurep nil)
15530 ;; Weekday was given, but no day, so pick that day in the week
15531 ;; on or after the derived date.
15532 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15533 (unless (equal wday wday1)
15534 (setq day (+ day (% (- wday wday1 -7) 7))))))
15535 (if (and (boundp 'org-time-was-given)
15536 (nth 2 tl))
15537 (setq org-time-was-given t))
15538 (if (< year 100) (setq year (+ 2000 year)))
15539 ;; Check of the date is representable
15540 (if org-read-date-force-compatible-dates
15541 (progn
15542 (if (< year 1970)
15543 (setq year 1970 org-read-date-analyze-forced-year t))
15544 (if (> year 2037)
15545 (setq year 2037 org-read-date-analyze-forced-year t)))
15546 (condition-case nil
15547 (ignore (encode-time second minute hour day month year))
15548 (error
15549 (setq year (nth 5 org-defdecode))
15550 (setq org-read-date-analyze-forced-year t))))
15551 (setq org-read-date-analyze-futurep futurep)
15552 (list second minute hour day month year)))
15554 (defvar parse-time-weekdays)
15555 (defun org-read-date-get-relative (s today default)
15556 "Check string S for special relative date string.
15557 TODAY and DEFAULT are internal times, for today and for a default.
15558 Return shift list (N what def-flag)
15559 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15560 N is the number of WHATs to shift.
15561 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15562 the DEFAULT date rather than TODAY."
15563 (require 'parse-time)
15564 (when (and
15565 (string-match
15566 (concat
15567 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15568 "\\([0-9]+\\)?"
15569 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15570 "\\([ \t]\\|$\\)") s)
15571 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15572 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15573 (string-to-char (substring (match-string 1 s) -1))
15574 ?+))
15575 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15576 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15577 (what (if (match-end 3) (match-string 3 s) "d"))
15578 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15579 (date (if rel default today))
15580 (wday (nth 6 (decode-time date)))
15581 delta)
15582 (if wday1
15583 (progn
15584 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15585 (if (= dir ?-) (setq delta (- delta 7)))
15586 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15587 (list delta "d" rel))
15588 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15590 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15591 "Turn a user-specified date into the internal representation.
15592 The internal representation needed by the calendar is (month day year).
15593 This is a wrapper to handle the brain-dead convention in calendar that
15594 user function argument order change dependent on argument order."
15595 (if (boundp 'calendar-date-style)
15596 (cond
15597 ((eq calendar-date-style 'american)
15598 (list arg1 arg2 arg3))
15599 ((eq calendar-date-style 'european)
15600 (list arg2 arg1 arg3))
15601 ((eq calendar-date-style 'iso)
15602 (list arg2 arg3 arg1)))
15603 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15604 (if (org-bound-and-true-p european-calendar-style)
15605 (list arg2 arg1 arg3)
15606 (list arg1 arg2 arg3)))))
15608 (defun org-eval-in-calendar (form &optional keepdate)
15609 "Eval FORM in the calendar window and return to current window.
15610 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15611 otherwise stick to the current value of `org-ans2'."
15612 (let ((sf (selected-frame))
15613 (sw (selected-window)))
15614 (select-window (get-buffer-window "*Calendar*" t))
15615 (eval form)
15616 (when (and (not keepdate) (calendar-cursor-to-date))
15617 (let* ((date (calendar-cursor-to-date))
15618 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15619 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15620 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15621 (select-window sw)
15622 (org-select-frame-set-input-focus sf)))
15624 (defun org-calendar-select ()
15625 "Return to `org-read-date' with the date currently selected.
15626 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15627 (interactive)
15628 (when (calendar-cursor-to-date)
15629 (let* ((date (calendar-cursor-to-date))
15630 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15631 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15632 (if (active-minibuffer-window) (exit-minibuffer))))
15634 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15635 "Insert a date stamp for the date given by the internal TIME.
15636 WITH-HM means use the stamp format that includes the time of the day.
15637 INACTIVE means use square brackets instead of angular ones, so that the
15638 stamp will not contribute to the agenda.
15639 PRE and POST are optional strings to be inserted before and after the
15640 stamp.
15641 The command returns the inserted time stamp."
15642 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15643 stamp)
15644 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15645 (insert-before-markers (or pre ""))
15646 (when (listp extra)
15647 (setq extra (car extra))
15648 (if (and (stringp extra)
15649 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15650 (setq extra (format "-%02d:%02d"
15651 (string-to-number (match-string 1 extra))
15652 (string-to-number (match-string 2 extra))))
15653 (setq extra nil)))
15654 (when extra
15655 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15656 (insert-before-markers (setq stamp (format-time-string fmt time)))
15657 (insert-before-markers (or post ""))
15658 (setq org-last-inserted-timestamp stamp)))
15660 (defun org-toggle-time-stamp-overlays ()
15661 "Toggle the use of custom time stamp formats."
15662 (interactive)
15663 (setq org-display-custom-times (not org-display-custom-times))
15664 (unless org-display-custom-times
15665 (let ((p (point-min)) (bmp (buffer-modified-p)))
15666 (while (setq p (next-single-property-change p 'display))
15667 (if (and (get-text-property p 'display)
15668 (eq (get-text-property p 'face) 'org-date))
15669 (remove-text-properties
15670 p (setq p (next-single-property-change p 'display))
15671 '(display t))))
15672 (set-buffer-modified-p bmp)))
15673 (if (featurep 'xemacs)
15674 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15675 (org-restart-font-lock)
15676 (setq org-table-may-need-update t)
15677 (if org-display-custom-times
15678 (message "Time stamps are overlaid with custom format")
15679 (message "Time stamp overlays removed")))
15681 (defun org-display-custom-time (beg end)
15682 "Overlay modified time stamp format over timestamp between BEG and END."
15683 (let* ((ts (buffer-substring beg end))
15684 t1 w1 with-hm tf time str w2 (off 0))
15685 (save-match-data
15686 (setq t1 (org-parse-time-string ts t))
15687 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15688 (setq off (- (match-end 0) (match-beginning 0)))))
15689 (setq end (- end off))
15690 (setq w1 (- end beg)
15691 with-hm (and (nth 1 t1) (nth 2 t1))
15692 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15693 time (org-fix-decoded-time t1)
15694 str (org-add-props
15695 (format-time-string
15696 (substring tf 1 -1) (apply 'encode-time time))
15697 nil 'mouse-face 'highlight)
15698 w2 (length str))
15699 (if (not (= w2 w1))
15700 (add-text-properties (1+ beg) (+ 2 beg)
15701 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15702 (if (featurep 'xemacs)
15703 (progn
15704 (put-text-property beg end 'invisible t)
15705 (put-text-property beg end 'end-glyph (make-glyph str)))
15706 (put-text-property beg end 'display str))))
15708 (defun org-translate-time (string)
15709 "Translate all timestamps in STRING to custom format.
15710 But do this only if the variable `org-display-custom-times' is set."
15711 (when org-display-custom-times
15712 (save-match-data
15713 (let* ((start 0)
15714 (re org-ts-regexp-both)
15715 t1 with-hm inactive tf time str beg end)
15716 (while (setq start (string-match re string start))
15717 (setq beg (match-beginning 0)
15718 end (match-end 0)
15719 t1 (save-match-data
15720 (org-parse-time-string (substring string beg end) t))
15721 with-hm (and (nth 1 t1) (nth 2 t1))
15722 inactive (equal (substring string beg (1+ beg)) "[")
15723 tf (funcall (if with-hm 'cdr 'car)
15724 org-time-stamp-custom-formats)
15725 time (org-fix-decoded-time t1)
15726 str (format-time-string
15727 (concat
15728 (if inactive "[" "<") (substring tf 1 -1)
15729 (if inactive "]" ">"))
15730 (apply 'encode-time time))
15731 string (replace-match str t t string)
15732 start (+ start (length str)))))))
15733 string)
15735 (defun org-fix-decoded-time (time)
15736 "Set 0 instead of nil for the first 6 elements of time.
15737 Don't touch the rest."
15738 (let ((n 0))
15739 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15741 (defun org-days-to-time (timestamp-string)
15742 "Difference between TIMESTAMP-STRING and now in days."
15743 (- (time-to-days (org-time-string-to-time timestamp-string))
15744 (time-to-days (current-time))))
15746 (defun org-deadline-close (timestamp-string &optional ndays)
15747 "Is the time in TIMESTAMP-STRING close to the current date?"
15748 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15749 (and (< (org-days-to-time timestamp-string) ndays)
15750 (not (org-entry-is-done-p))))
15752 (defun org-get-wdays (ts)
15753 "Get the deadline lead time appropriate for timestring TS."
15754 (cond
15755 ((<= org-deadline-warning-days 0)
15756 ;; 0 or negative, enforce this value no matter what
15757 (- org-deadline-warning-days))
15758 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15759 ;; lead time is specified.
15760 (floor (* (string-to-number (match-string 1 ts))
15761 (cdr (assoc (match-string 2 ts)
15762 '(("d" . 1) ("w" . 7)
15763 ("m" . 30.4) ("y" . 365.25)))))))
15764 ;; go for the default.
15765 (t org-deadline-warning-days)))
15767 (defun org-calendar-select-mouse (ev)
15768 "Return to `org-read-date' with the date currently selected.
15769 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15770 (interactive "e")
15771 (mouse-set-point ev)
15772 (when (calendar-cursor-to-date)
15773 (let* ((date (calendar-cursor-to-date))
15774 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15775 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15776 (if (active-minibuffer-window) (exit-minibuffer))))
15778 (defun org-check-deadlines (ndays)
15779 "Check if there are any deadlines due or past due.
15780 A deadline is considered due if it happens within `org-deadline-warning-days'
15781 days from today's date. If the deadline appears in an entry marked DONE,
15782 it is not shown. The prefix arg NDAYS can be used to test that many
15783 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15784 (interactive "P")
15785 (let* ((org-warn-days
15786 (cond
15787 ((equal ndays '(4)) 100000)
15788 (ndays (prefix-numeric-value ndays))
15789 (t (abs org-deadline-warning-days))))
15790 (case-fold-search nil)
15791 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15792 (callback
15793 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15795 (message "%d deadlines past-due or due within %d days"
15796 (org-occur regexp nil callback)
15797 org-warn-days)))
15799 (defun org-check-before-date (date)
15800 "Check if there are deadlines or scheduled entries before DATE."
15801 (interactive (list (org-read-date)))
15802 (let ((case-fold-search nil)
15803 (regexp (concat "\\<\\(" org-deadline-string
15804 "\\|" org-scheduled-string
15805 "\\) *<\\([^>]+\\)>"))
15806 (callback
15807 (lambda () (time-less-p
15808 (org-time-string-to-time (match-string 2))
15809 (org-time-string-to-time date)))))
15810 (message "%d entries before %s"
15811 (org-occur regexp nil callback) date)))
15813 (defun org-check-after-date (date)
15814 "Check if there are deadlines or scheduled entries after DATE."
15815 (interactive (list (org-read-date)))
15816 (let ((case-fold-search nil)
15817 (regexp (concat "\\<\\(" org-deadline-string
15818 "\\|" org-scheduled-string
15819 "\\) *<\\([^>]+\\)>"))
15820 (callback
15821 (lambda () (not
15822 (time-less-p
15823 (org-time-string-to-time (match-string 2))
15824 (org-time-string-to-time date))))))
15825 (message "%d entries after %s"
15826 (org-occur regexp nil callback) date)))
15828 (defun org-check-dates-range (start-date end-date)
15829 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15830 (interactive (list (org-read-date nil nil nil "Range starts")
15831 (org-read-date nil nil nil "Range end")))
15832 (let ((case-fold-search nil)
15833 (regexp (concat "\\<\\(" org-deadline-string
15834 "\\|" org-scheduled-string
15835 "\\) *<\\([^>]+\\)>"))
15836 (callback
15837 (lambda ()
15838 (let ((match (match-string 2)))
15839 (and
15840 (not (time-less-p
15841 (org-time-string-to-time match)
15842 (org-time-string-to-time start-date)))
15843 (time-less-p
15844 (org-time-string-to-time match)
15845 (org-time-string-to-time end-date)))))))
15846 (message "%d entries between %s and %s"
15847 (org-occur regexp nil callback) start-date end-date)))
15849 (defun org-evaluate-time-range (&optional to-buffer)
15850 "Evaluate a time range by computing the difference between start and end.
15851 Normally the result is just printed in the echo area, but with prefix arg
15852 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15853 If the time range is actually in a table, the result is inserted into the
15854 next column.
15855 For time difference computation, a year is assumed to be exactly 365
15856 days in order to avoid rounding problems."
15857 (interactive "P")
15859 (org-clock-update-time-maybe)
15860 (save-excursion
15861 (unless (org-at-date-range-p t)
15862 (goto-char (point-at-bol))
15863 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15864 (if (not (org-at-date-range-p t))
15865 (error "Not at a time-stamp range, and none found in current line")))
15866 (let* ((ts1 (match-string 1))
15867 (ts2 (match-string 2))
15868 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15869 (match-end (match-end 0))
15870 (time1 (org-time-string-to-time ts1))
15871 (time2 (org-time-string-to-time ts2))
15872 (t1 (org-float-time time1))
15873 (t2 (org-float-time time2))
15874 (diff (abs (- t2 t1)))
15875 (negative (< (- t2 t1) 0))
15876 ;; (ys (floor (* 365 24 60 60)))
15877 (ds (* 24 60 60))
15878 (hs (* 60 60))
15879 (fy "%dy %dd %02d:%02d")
15880 (fy1 "%dy %dd")
15881 (fd "%dd %02d:%02d")
15882 (fd1 "%dd")
15883 (fh "%02d:%02d")
15884 y d h m align)
15885 (if havetime
15886 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15888 d (floor (/ diff ds)) diff (mod diff ds)
15889 h (floor (/ diff hs)) diff (mod diff hs)
15890 m (floor (/ diff 60)))
15891 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15893 d (floor (+ (/ diff ds) 0.5))
15894 h 0 m 0))
15895 (if (not to-buffer)
15896 (message "%s" (org-make-tdiff-string y d h m))
15897 (if (org-at-table-p)
15898 (progn
15899 (goto-char match-end)
15900 (setq align t)
15901 (and (looking-at " *|") (goto-char (match-end 0))))
15902 (goto-char match-end))
15903 (if (looking-at
15904 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15905 (replace-match ""))
15906 (if negative (insert " -"))
15907 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15908 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15909 (insert " " (format fh h m))))
15910 (if align (org-table-align))
15911 (message "Time difference inserted")))))
15913 (defun org-make-tdiff-string (y d h m)
15914 (let ((fmt "")
15915 (l nil))
15916 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15917 l (push y l)))
15918 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15919 l (push d l)))
15920 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15921 l (push h l)))
15922 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15923 l (push m l)))
15924 (apply 'format fmt (nreverse l))))
15926 (defun org-time-string-to-time (s &optional buffer pos)
15927 (condition-case errdata
15928 (apply 'encode-time (org-parse-time-string s))
15929 (error (error "Bad timestamp `%s'%s\nError was: %s"
15930 s (if (not (and buffer pos))
15932 (format " at %d in buffer `%s'" pos buffer))
15933 (cdr errdata)))))
15935 (defun org-time-string-to-seconds (s)
15936 (org-float-time (org-time-string-to-time s)))
15938 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15939 "Convert a time stamp to an absolute day number.
15940 If there is a specifier for a cyclic time stamp, get the closest date to
15941 DAYNR.
15942 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15943 The variable date is bound by the calendar when this is called."
15944 (cond
15945 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15946 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15947 daynr
15948 (+ daynr 1000)))
15949 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
15950 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15951 (time-to-days (current-time))) (match-string 0 s)
15952 prefer show-all))
15953 (t (time-to-days
15954 (condition-case errdata
15955 (apply 'encode-time (org-parse-time-string s))
15956 (error (error "Bad timestamp `%s'%s\nError was: %s"
15957 s (if (not (and buffer pos))
15959 (format " at %d in buffer `%s'" pos buffer))
15960 (cdr errdata))))))))
15962 (defun org-days-to-iso-week (days)
15963 "Return the iso week number."
15964 (require 'cal-iso)
15965 (car (calendar-iso-from-absolute days)))
15967 (defun org-small-year-to-year (year)
15968 "Convert 2-digit years into 4-digit years.
15969 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15970 The year 2000 cannot be abbreviated. Any year larger than 99
15971 is returned unchanged."
15972 (if (< year 38)
15973 (setq year (+ 2000 year))
15974 (if (< year 100)
15975 (setq year (+ 1900 year))))
15976 year)
15978 (defun org-time-from-absolute (d)
15979 "Return the time corresponding to date D.
15980 D may be an absolute day number, or a calendar-type list (month day year)."
15981 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15982 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15984 (defun org-calendar-holiday ()
15985 "List of holidays, for Diary display in Org-mode."
15986 (require 'holidays)
15987 (let ((hl (funcall
15988 (if (fboundp 'calendar-check-holidays)
15989 'calendar-check-holidays 'check-calendar-holidays) date)))
15990 (if hl (mapconcat 'identity hl "; "))))
15992 (defun org-diary-sexp-entry (sexp entry date)
15993 "Process a SEXP diary ENTRY for DATE."
15994 (require 'diary-lib)
15995 (let ((result (if calendar-debug-sexp
15996 (let ((stack-trace-on-error t))
15997 (eval (car (read-from-string sexp))))
15998 (condition-case nil
15999 (eval (car (read-from-string sexp)))
16000 (error
16001 (beep)
16002 (message "Bad sexp at line %d in %s: %s"
16003 (org-current-line)
16004 (buffer-file-name) sexp)
16005 (sleep-for 2))))))
16006 (cond ((stringp result) (split-string result "; "))
16007 ((and (consp result)
16008 (not (consp (cdr result)))
16009 (stringp (cdr result))) (cdr result))
16010 ((and (consp result)
16011 (stringp (car result))) result)
16012 (result entry)
16013 (t nil))))
16015 (defun org-diary-to-ical-string (frombuf)
16016 "Get iCalendar entries from diary entries in buffer FROMBUF.
16017 This uses the icalendar.el library."
16018 (let* ((tmpdir (if (featurep 'xemacs)
16019 (temp-directory)
16020 temporary-file-directory))
16021 (tmpfile (make-temp-name
16022 (expand-file-name "orgics" tmpdir)))
16023 buf rtn b e)
16024 (with-current-buffer frombuf
16025 (icalendar-export-region (point-min) (point-max) tmpfile)
16026 (setq buf (find-buffer-visiting tmpfile))
16027 (set-buffer buf)
16028 (goto-char (point-min))
16029 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16030 (setq b (match-beginning 0)))
16031 (goto-char (point-max))
16032 (if (re-search-backward "^END:VEVENT" nil t)
16033 (setq e (match-end 0)))
16034 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16035 (kill-buffer buf)
16036 (delete-file tmpfile)
16037 rtn))
16039 (defun org-closest-date (start current change prefer show-all)
16040 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16041 When PREFER is `past', return a date that is either CURRENT or past.
16042 When PREFER is `future', return a date that is either CURRENT or future.
16043 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16044 ;; Make the proper lists from the dates
16045 (catch 'exit
16046 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16047 dn dw sday cday n1 n2 n0
16048 d m y y1 y2 date1 date2 nmonths nm ny m2)
16050 (setq start (org-date-to-gregorian start)
16051 current (org-date-to-gregorian
16052 (if show-all
16053 current
16054 (time-to-days (current-time))))
16055 sday (calendar-absolute-from-gregorian start)
16056 cday (calendar-absolute-from-gregorian current))
16058 (if (<= cday sday) (throw 'exit sday))
16060 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16061 (setq dn (string-to-number (match-string 1 change))
16062 dw (cdr (assoc (match-string 2 change) a1)))
16063 (error "Invalid change specifier: %s" change))
16064 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16065 (cond
16066 ((eq dw 'day)
16067 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16068 n2 (+ n1 dn)))
16069 ((eq dw 'year)
16070 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16071 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16072 (setq date1 (list m d y1)
16073 n1 (calendar-absolute-from-gregorian date1)
16074 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16075 n2 (calendar-absolute-from-gregorian date2)))
16076 ((eq dw 'month)
16077 ;; approx number of month between the two dates
16078 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16079 ;; How often does dn fit in there?
16080 (setq d (nth 1 start) m (car start) y (nth 2 start)
16081 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16082 m (+ m nm)
16083 ny (floor (/ m 12))
16084 y (+ y ny)
16085 m (- m (* ny 12)))
16086 (while (> m 12) (setq m (- m 12) y (1+ y)))
16087 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16088 (setq m2 (+ m dn) y2 y)
16089 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16090 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16091 (while (<= n2 cday)
16092 (setq n1 n2 m m2 y y2)
16093 (setq m2 (+ m dn) y2 y)
16094 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16095 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16096 ;; Make sure n1 is the earlier date
16097 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16098 (if show-all
16099 (cond
16100 ((eq prefer 'past) (if (= cday n2) n2 n1))
16101 ((eq prefer 'future) (if (= cday n1) n1 n2))
16102 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16103 (cond
16104 ((eq prefer 'past) (if (= cday n2) n2 n1))
16105 ((eq prefer 'future) (if (= cday n1) n1 n2))
16106 (t (if (= cday n1) n1 n2)))))))
16108 (defun org-date-to-gregorian (date)
16109 "Turn any specification of DATE into a Gregorian date for the calendar."
16110 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16111 ((and (listp date) (= (length date) 3)) date)
16112 ((stringp date)
16113 (setq date (org-parse-time-string date))
16114 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16115 ((listp date)
16116 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16118 (defun org-parse-time-string (s &optional nodefault)
16119 "Parse the standard Org-mode time string.
16120 This should be a lot faster than the normal `parse-time-string'.
16121 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16122 hour and minute fields will be nil if not given."
16123 (if (string-match org-ts-regexp0 s)
16124 (list 0
16125 (if (or (match-beginning 8) (not nodefault))
16126 (string-to-number (or (match-string 8 s) "0")))
16127 (if (or (match-beginning 7) (not nodefault))
16128 (string-to-number (or (match-string 7 s) "0")))
16129 (string-to-number (match-string 4 s))
16130 (string-to-number (match-string 3 s))
16131 (string-to-number (match-string 2 s))
16132 nil nil nil)
16133 (error "Not a standard Org-mode time string: %s" s)))
16135 (defun org-timestamp-up (&optional arg)
16136 "Increase the date item at the cursor by one.
16137 If the cursor is on the year, change the year. If it is on the month,
16138 the day or the time, change that.
16139 With prefix ARG, change by that many units."
16140 (interactive "p")
16141 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16143 (defun org-timestamp-down (&optional arg)
16144 "Decrease the date item at the cursor by one.
16145 If the cursor is on the year, change the year. If it is on the month,
16146 the day or the time, change that.
16147 With prefix ARG, change by that many units."
16148 (interactive "p")
16149 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16151 (defun org-timestamp-up-day (&optional arg)
16152 "Increase the date in the time stamp by one day.
16153 With prefix ARG, change that many days."
16154 (interactive "p")
16155 (if (and (not (org-at-timestamp-p t))
16156 (org-at-heading-p))
16157 (org-todo 'up)
16158 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16160 (defun org-timestamp-down-day (&optional arg)
16161 "Decrease the date in the time stamp by one day.
16162 With prefix ARG, change that many days."
16163 (interactive "p")
16164 (if (and (not (org-at-timestamp-p t))
16165 (org-at-heading-p))
16166 (org-todo 'down)
16167 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16169 (defun org-at-timestamp-p (&optional inactive-ok)
16170 "Determine if the cursor is in or at a timestamp."
16171 (interactive)
16172 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16173 (pos (point))
16174 (ans (or (looking-at tsr)
16175 (save-excursion
16176 (skip-chars-backward "^[<\n\r\t")
16177 (if (> (point) (point-min)) (backward-char 1))
16178 (and (looking-at tsr)
16179 (> (- (match-end 0) pos) -1))))))
16180 (and ans
16181 (boundp 'org-ts-what)
16182 (setq org-ts-what
16183 (cond
16184 ((= pos (match-beginning 0)) 'bracket)
16185 ;; Point is considered to be "on the bracket" whether
16186 ;; it's really on it or right after it.
16187 ((= pos (1- (match-end 0))) 'bracket)
16188 ((= pos (match-end 0)) 'after)
16189 ((org-pos-in-match-range pos 2) 'year)
16190 ((org-pos-in-match-range pos 3) 'month)
16191 ((org-pos-in-match-range pos 7) 'hour)
16192 ((org-pos-in-match-range pos 8) 'minute)
16193 ((or (org-pos-in-match-range pos 4)
16194 (org-pos-in-match-range pos 5)) 'day)
16195 ((and (> pos (or (match-end 8) (match-end 5)))
16196 (< pos (match-end 0)))
16197 (- pos (or (match-end 8) (match-end 5))))
16198 (t 'day))))
16199 ans))
16201 (defun org-toggle-timestamp-type ()
16202 "Toggle the type (<active> or [inactive]) of a time stamp."
16203 (interactive)
16204 (when (org-at-timestamp-p t)
16205 (let ((beg (match-beginning 0)) (end (match-end 0))
16206 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16207 (save-excursion
16208 (goto-char beg)
16209 (while (re-search-forward "[][<>]" end t)
16210 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16211 t t)))
16212 (message "Timestamp is now %sactive"
16213 (if (equal (char-after beg) ?<) "" "in")))))
16215 (defun org-timestamp-change (n &optional what updown)
16216 "Change the date in the time stamp at point.
16217 The date will be changed by N times WHAT. WHAT can be `day', `month',
16218 `year', `minute', `second'. If WHAT is not given, the cursor position
16219 in the timestamp determines what will be changed."
16220 (let ((origin (point)) origin-cat
16221 with-hm inactive
16222 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16223 org-ts-what
16224 extra rem
16225 ts time time0)
16226 (if (not (org-at-timestamp-p t))
16227 (error "Not at a timestamp"))
16228 (if (and (not what) (eq org-ts-what 'bracket))
16229 (org-toggle-timestamp-type)
16230 ;; Point isn't on brackets. Remember the part of the time-stamp
16231 ;; the point was in. Indeed, size of time-stamps may change,
16232 ;; but point must be kept in the same category nonetheless.
16233 (setq origin-cat org-ts-what)
16234 (if (and (not what) (not (eq org-ts-what 'day))
16235 org-display-custom-times
16236 (get-text-property (point) 'display)
16237 (not (get-text-property (1- (point)) 'display)))
16238 (setq org-ts-what 'day))
16239 (setq org-ts-what (or what org-ts-what)
16240 inactive (= (char-after (match-beginning 0)) ?\[)
16241 ts (match-string 0))
16242 (replace-match "")
16243 (if (string-match
16244 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16246 (setq extra (match-string 1 ts)))
16247 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16248 (setq with-hm t))
16249 (setq time0 (org-parse-time-string ts))
16250 (when (and updown
16251 (eq org-ts-what 'minute)
16252 (not current-prefix-arg))
16253 ;; This looks like s-up and s-down. Change by one rounding step.
16254 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16255 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16256 (setcar (cdr time0) (+ (nth 1 time0)
16257 (if (> n 0) (- rem) (- dm rem))))))
16258 (setq time
16259 (encode-time (or (car time0) 0)
16260 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16261 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16262 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16263 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16264 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16265 (nthcdr 6 time0)))
16266 (when (and (member org-ts-what '(hour minute))
16267 extra
16268 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16269 (setq extra (org-modify-ts-extra
16270 extra
16271 (if (eq org-ts-what 'hour) 2 5)
16272 n dm)))
16273 (when (integerp org-ts-what)
16274 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16275 (if (eq what 'calendar)
16276 (let ((cal-date (org-get-date-from-calendar)))
16277 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16278 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16279 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16280 (setcar time0 (or (car time0) 0))
16281 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16282 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16283 (setq time (apply 'encode-time time0))))
16284 ;; Insert the new time-stamp, and ensure point stays in the same
16285 ;; category as before (i.e. not after the last position in that
16286 ;; category).
16287 (let ((pos (point)))
16288 ;; Stay before inserted string. `save-excursion' is of no use.
16289 (setq org-last-changed-timestamp
16290 (org-insert-time-stamp time with-hm inactive nil nil extra))
16291 (goto-char pos))
16292 (save-match-data
16293 (looking-at org-ts-regexp3)
16294 (goto-char (cond
16295 ;; `day' category ends before `hour' if any, or at
16296 ;; the end of the day name.
16297 ((eq origin-cat 'day)
16298 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16299 ((eq origin-cat 'hour) (min (match-end 7) origin))
16300 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16301 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16302 ;; `year' and `month' have both fixed size: point
16303 ;; couldn't have moved into another part.
16304 (t origin))))
16305 ;; Update clock if on a CLOCK line.
16306 (org-clock-update-time-maybe)
16307 ;; Try to recenter the calendar window, if any.
16308 (if (and org-calendar-follow-timestamp-change
16309 (get-buffer-window "*Calendar*" t)
16310 (memq org-ts-what '(day month year)))
16311 (org-recenter-calendar (time-to-days time))))))
16313 (defun org-modify-ts-extra (s pos n dm)
16314 "Change the different parts of the lead-time and repeat fields in timestamp."
16315 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16316 ng h m new rem)
16317 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16318 (cond
16319 ((or (org-pos-in-match-range pos 2)
16320 (org-pos-in-match-range pos 3))
16321 (setq m (string-to-number (match-string 3 s))
16322 h (string-to-number (match-string 2 s)))
16323 (if (org-pos-in-match-range pos 2)
16324 (setq h (+ h n))
16325 (setq n (* dm (org-no-warnings (signum n))))
16326 (when (not (= 0 (setq rem (% m dm))))
16327 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16328 (setq m (+ m n)))
16329 (if (< m 0) (setq m (+ m 60) h (1- h)))
16330 (if (> m 59) (setq m (- m 60) h (1+ h)))
16331 (setq h (min 24 (max 0 h)))
16332 (setq ng 1 new (format "-%02d:%02d" h m)))
16333 ((org-pos-in-match-range pos 6)
16334 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16335 ((org-pos-in-match-range pos 5)
16336 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16338 ((org-pos-in-match-range pos 9)
16339 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16340 ((org-pos-in-match-range pos 8)
16341 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16343 (when ng
16344 (setq s (concat
16345 (substring s 0 (match-beginning ng))
16347 (substring s (match-end ng))))))
16350 (defun org-recenter-calendar (date)
16351 "If the calendar is visible, recenter it to DATE."
16352 (let ((cwin (get-buffer-window "*Calendar*" t)))
16353 (when cwin
16354 (let ((calendar-move-hook nil))
16355 (with-selected-window cwin
16356 (calendar-goto-date (if (listp date) date
16357 (calendar-gregorian-from-absolute date))))))))
16359 (defun org-goto-calendar (&optional arg)
16360 "Go to the Emacs calendar at the current date.
16361 If there is a time stamp in the current line, go to that date.
16362 A prefix ARG can be used to force the current date."
16363 (interactive "P")
16364 (let ((tsr org-ts-regexp) diff
16365 (calendar-move-hook nil)
16366 (calendar-view-holidays-initially-flag nil)
16367 (calendar-view-diary-initially-flag nil))
16368 (if (or (org-at-timestamp-p)
16369 (save-excursion
16370 (beginning-of-line 1)
16371 (looking-at (concat ".*" tsr))))
16372 (let ((d1 (time-to-days (current-time)))
16373 (d2 (time-to-days
16374 (org-time-string-to-time (match-string 1)))))
16375 (setq diff (- d2 d1))))
16376 (calendar)
16377 (calendar-goto-today)
16378 (if (and diff (not arg)) (calendar-forward-day diff))))
16380 (defun org-get-date-from-calendar ()
16381 "Return a list (month day year) of date at point in calendar."
16382 (with-current-buffer "*Calendar*"
16383 (save-match-data
16384 (calendar-cursor-to-date))))
16386 (defun org-date-from-calendar ()
16387 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16388 If there is already a time stamp at the cursor position, update it."
16389 (interactive)
16390 (if (org-at-timestamp-p t)
16391 (org-timestamp-change 0 'calendar)
16392 (let ((cal-date (org-get-date-from-calendar)))
16393 (org-insert-time-stamp
16394 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16396 (defun org-minutes-to-hh:mm-string (m)
16397 "Compute H:MM from a number of minutes."
16398 (let ((h (/ m 60)))
16399 (setq m (- m (* 60 h)))
16400 (format org-time-clocksum-format h m)))
16402 (defun org-hh:mm-string-to-minutes (s)
16403 "Convert a string H:MM to a number of minutes.
16404 If the string is just a number, interpret it as minutes.
16405 In fact, the first hh:mm or number in the string will be taken,
16406 there can be extra stuff in the string.
16407 If no number is found, the return value is 0."
16408 (cond
16409 ((integerp s) s)
16410 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16411 (+ (* (string-to-number (match-string 1 s)) 60)
16412 (string-to-number (match-string 2 s))))
16413 ((string-match "\\([0-9]+\\)" s)
16414 (string-to-number (match-string 1 s)))
16415 (t 0)))
16417 (defcustom org-effort-durations
16418 `(("h" . 60)
16419 ("d" . ,(* 60 8))
16420 ("w" . ,(* 60 8 5))
16421 ("m" . ,(* 60 8 5 4))
16422 ("y" . ,(* 60 8 5 40)))
16423 "Conversion factor to minutes for an effort modifier.
16425 Each entry has the form (MODIFIER . MINUTES).
16427 In an effort string, a number followed by MODIFIER is multiplied
16428 by the specified number of MINUTES to obtain an effort in
16429 minutes.
16431 For example, if the value of this variable is ((\"hours\" . 60)), then an
16432 effort string \"2hours\" is equivalent to 120 minutes."
16433 :group 'org-agenda
16434 :version "24.1"
16435 :type '(alist :key-type (string :tag "Modifier")
16436 :value-type (number :tag "Minutes")))
16438 (defun org-duration-string-to-minutes (s &optional output-to-string)
16439 "Convert a duration string S to minutes.
16441 A bare number is interpreted as minutes, modifiers can be set by
16442 customizing `org-effort-durations' (which see).
16444 Entries containing a colon are interpreted as H:MM by
16445 `org-hh:mm-string-to-minutes'."
16446 (let ((result 0)
16447 (re (concat "\\([0-9.]+\\) *\\("
16448 (regexp-opt (mapcar 'car org-effort-durations))
16449 "\\)")))
16450 (while (string-match re s)
16451 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16452 (string-to-number (match-string 1 s))))
16453 (setq s (replace-match "" nil t s)))
16454 (setq result (floor result))
16455 (incf result (org-hh:mm-string-to-minutes s))
16456 (if output-to-string (number-to-string result) result)))
16458 ;;;; Files
16460 (defun org-save-all-org-buffers ()
16461 "Save all Org-mode buffers without user confirmation."
16462 (interactive)
16463 (message "Saving all Org-mode buffers...")
16464 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16465 (when (featurep 'org-id) (org-id-locations-save))
16466 (message "Saving all Org-mode buffers... done"))
16468 (defun org-revert-all-org-buffers ()
16469 "Revert all Org-mode buffers.
16470 Prompt for confirmation when there are unsaved changes.
16471 Be sure you know what you are doing before letting this function
16472 overwrite your changes.
16474 This function is useful in a setup where one tracks org files
16475 with a version control system, to revert on one machine after pulling
16476 changes from another. I believe the procedure must be like this:
16478 1. M-x org-save-all-org-buffers
16479 2. Pull changes from the other machine, resolve conflicts
16480 3. M-x org-revert-all-org-buffers"
16481 (interactive)
16482 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16483 (error "Abort"))
16484 (save-excursion
16485 (save-window-excursion
16486 (mapc
16487 (lambda (b)
16488 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16489 (with-current-buffer b buffer-file-name))
16490 (org-pop-to-buffer-same-window b)
16491 (revert-buffer t 'no-confirm)))
16492 (buffer-list))
16493 (when (and (featurep 'org-id) org-id-track-globally)
16494 (org-id-locations-load)))))
16496 ;;;; Agenda files
16498 ;;;###autoload
16499 (defun org-switchb (&optional arg)
16500 "Switch between Org buffers.
16501 With one prefix argument, restrict available buffers to files.
16502 With two prefix arguments, restrict available buffers to agenda files.
16504 Defaults to `iswitchb' for buffer name completion.
16505 Set `org-completion-use-ido' to make it use ido instead."
16506 (interactive "P")
16507 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16508 ((equal arg '(16)) (org-buffer-list 'agenda))
16509 (t (org-buffer-list))))
16510 (org-completion-use-iswitchb org-completion-use-iswitchb)
16511 (org-completion-use-ido org-completion-use-ido))
16512 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16513 (setq org-completion-use-iswitchb t))
16514 (org-pop-to-buffer-same-window
16515 (org-icompleting-read "Org buffer: "
16516 (mapcar 'list (mapcar 'buffer-name blist))
16517 nil t))))
16519 ;;; Define some older names previously used for this functionality
16520 ;;;###autoload
16521 (defalias 'org-ido-switchb 'org-switchb)
16522 ;;;###autoload
16523 (defalias 'org-iswitchb 'org-switchb)
16525 (defun org-buffer-list (&optional predicate exclude-tmp)
16526 "Return a list of Org buffers.
16527 PREDICATE can be `export', `files' or `agenda'.
16529 export restrict the list to Export buffers.
16530 files restrict the list to buffers visiting Org files.
16531 agenda restrict the list to buffers visiting agenda files.
16533 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16534 (let* ((bfn nil)
16535 (agenda-files (and (eq predicate 'agenda)
16536 (mapcar 'file-truename (org-agenda-files t))))
16537 (filter
16538 (cond
16539 ((eq predicate 'files)
16540 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16541 ((eq predicate 'export)
16542 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16543 ((eq predicate 'agenda)
16544 (lambda (b)
16545 (with-current-buffer b
16546 (and (derived-mode-p 'org-mode)
16547 (setq bfn (buffer-file-name b))
16548 (member (file-truename bfn) agenda-files)))))
16549 (t (lambda (b) (with-current-buffer b
16550 (or (derived-mode-p 'org-mode)
16551 (string-match "\*Org .*Export"
16552 (buffer-name b)))))))))
16553 (delq nil
16554 (mapcar
16555 (lambda(b)
16556 (if (and (funcall filter b)
16557 (or (not exclude-tmp)
16558 (not (string-match "tmp" (buffer-name b)))))
16560 nil))
16561 (buffer-list)))))
16563 (defun org-agenda-files (&optional unrestricted archives)
16564 "Get the list of agenda files.
16565 Optional UNRESTRICTED means return the full list even if a restriction
16566 is currently in place.
16567 When ARCHIVES is t, include all archive files that are really being
16568 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16569 `org-agenda-archives-mode' is t."
16570 (let ((files
16571 (cond
16572 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16573 ((stringp org-agenda-files) (org-read-agenda-file-list))
16574 ((listp org-agenda-files) org-agenda-files)
16575 (t (error "Invalid value of `org-agenda-files'")))))
16576 (setq files (apply 'append
16577 (mapcar (lambda (f)
16578 (if (file-directory-p f)
16579 (directory-files
16580 f t org-agenda-file-regexp)
16581 (list f)))
16582 files)))
16583 (when org-agenda-skip-unavailable-files
16584 (setq files (delq nil
16585 (mapcar (function
16586 (lambda (file)
16587 (and (file-readable-p file) file)))
16588 files))))
16589 (when (or (eq archives t)
16590 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16591 (setq files (org-add-archive-files files)))
16592 files))
16594 (defun org-agenda-file-p (&optional file)
16595 "Return non-nil, if FILE is an agenda file.
16596 If FILE is omitted, use the file associated with the current
16597 buffer."
16598 (member (or file (buffer-file-name))
16599 (org-agenda-files t)))
16601 (defun org-edit-agenda-file-list ()
16602 "Edit the list of agenda files.
16603 Depending on setup, this either uses customize to edit the variable
16604 `org-agenda-files', or it visits the file that is holding the list. In the
16605 latter case, the buffer is set up in a way that saving it automatically kills
16606 the buffer and restores the previous window configuration."
16607 (interactive)
16608 (if (stringp org-agenda-files)
16609 (let ((cw (current-window-configuration)))
16610 (find-file org-agenda-files)
16611 (org-set-local 'org-window-configuration cw)
16612 (org-add-hook 'after-save-hook
16613 (lambda ()
16614 (set-window-configuration
16615 (prog1 org-window-configuration
16616 (kill-buffer (current-buffer))))
16617 (org-install-agenda-files-menu)
16618 (message "New agenda file list installed"))
16619 nil 'local)
16620 (message "%s" (substitute-command-keys
16621 "Edit list and finish with \\[save-buffer]")))
16622 (customize-variable 'org-agenda-files)))
16624 (defun org-store-new-agenda-file-list (list)
16625 "Set new value for the agenda file list and save it correctly."
16626 (if (stringp org-agenda-files)
16627 (let ((fe (org-read-agenda-file-list t)) b u)
16628 (while (setq b (find-buffer-visiting org-agenda-files))
16629 (kill-buffer b))
16630 (with-temp-file org-agenda-files
16631 (insert
16632 (mapconcat
16633 (lambda (f) ;; Keep un-expanded entries.
16634 (if (setq u (assoc f fe))
16635 (cdr u)
16637 list "\n")
16638 "\n")))
16639 (let ((org-mode-hook nil) (org-inhibit-startup t)
16640 (org-insert-mode-line-in-empty-file nil))
16641 (setq org-agenda-files list)
16642 (customize-save-variable 'org-agenda-files org-agenda-files))))
16644 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16645 "Read the list of agenda files from a file.
16646 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16647 filenames, used by `org-store-new-agenda-file-list' to write back
16648 un-expanded file names."
16649 (when (file-directory-p org-agenda-files)
16650 (error "`org-agenda-files' cannot be a single directory"))
16651 (when (stringp org-agenda-files)
16652 (with-temp-buffer
16653 (insert-file-contents org-agenda-files)
16654 (mapcar
16655 (lambda (f)
16656 (let ((e (expand-file-name (substitute-in-file-name f)
16657 org-directory)))
16658 (if pair-with-expansion
16659 (cons e f)
16660 e)))
16661 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16663 ;;;###autoload
16664 (defun org-cycle-agenda-files ()
16665 "Cycle through the files in `org-agenda-files'.
16666 If the current buffer visits an agenda file, find the next one in the list.
16667 If the current buffer does not, find the first agenda file."
16668 (interactive)
16669 (let* ((fs (org-agenda-files t))
16670 (files (append fs (list (car fs))))
16671 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16672 file)
16673 (unless files (error "No agenda files"))
16674 (catch 'exit
16675 (while (setq file (pop files))
16676 (if (equal (file-truename file) tcf)
16677 (when (car files)
16678 (find-file (car files))
16679 (throw 'exit t))))
16680 (find-file (car fs)))
16681 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16683 (defun org-agenda-file-to-front (&optional to-end)
16684 "Move/add the current file to the top of the agenda file list.
16685 If the file is not present in the list, it is added to the front. If it is
16686 present, it is moved there. With optional argument TO-END, add/move to the
16687 end of the list."
16688 (interactive "P")
16689 (let ((org-agenda-skip-unavailable-files nil)
16690 (file-alist (mapcar (lambda (x)
16691 (cons (file-truename x) x))
16692 (org-agenda-files t)))
16693 (ctf (file-truename buffer-file-name))
16694 x had)
16695 (setq x (assoc ctf file-alist) had x)
16697 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16698 (if to-end
16699 (setq file-alist (append (delq x file-alist) (list x)))
16700 (setq file-alist (cons x (delq x file-alist))))
16701 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16702 (org-install-agenda-files-menu)
16703 (message "File %s to %s of agenda file list"
16704 (if had "moved" "added") (if to-end "end" "front"))))
16706 (defun org-remove-file (&optional file)
16707 "Remove current file from the list of files in variable `org-agenda-files'.
16708 These are the files which are being checked for agenda entries.
16709 Optional argument FILE means use this file instead of the current."
16710 (interactive)
16711 (let* ((org-agenda-skip-unavailable-files nil)
16712 (file (or file buffer-file-name))
16713 (true-file (file-truename file))
16714 (afile (abbreviate-file-name file))
16715 (files (delq nil (mapcar
16716 (lambda (x)
16717 (if (equal true-file
16718 (file-truename x))
16719 nil x))
16720 (org-agenda-files t)))))
16721 (if (not (= (length files) (length (org-agenda-files t))))
16722 (progn
16723 (org-store-new-agenda-file-list files)
16724 (org-install-agenda-files-menu)
16725 (message "Removed file: %s" afile))
16726 (message "File was not in list: %s (not removed)" afile))))
16728 (defun org-file-menu-entry (file)
16729 (vector file (list 'find-file file) t))
16731 (defun org-check-agenda-file (file)
16732 "Make sure FILE exists. If not, ask user what to do."
16733 (when (not (file-exists-p file))
16734 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16735 (abbreviate-file-name file))
16736 (let ((r (downcase (read-char-exclusive))))
16737 (cond
16738 ((equal r ?r)
16739 (org-remove-file file)
16740 (throw 'nextfile t))
16741 (t (error "Abort"))))))
16743 (defun org-get-agenda-file-buffer (file)
16744 "Get a buffer visiting FILE. If the buffer needs to be created, add
16745 it to the list of buffers which might be released later."
16746 (let ((buf (org-find-base-buffer-visiting file)))
16747 (if buf
16748 buf ; just return it
16749 ;; Make a new buffer and remember it
16750 (setq buf (find-file-noselect file))
16751 (if buf (push buf org-agenda-new-buffers))
16752 buf)))
16754 (defun org-release-buffers (blist)
16755 "Release all buffers in list, asking the user for confirmation when needed.
16756 When a buffer is unmodified, it is just killed. When modified, it is saved
16757 \(if the user agrees) and then killed."
16758 (let (buf file)
16759 (while (setq buf (pop blist))
16760 (setq file (buffer-file-name buf))
16761 (when (and (buffer-modified-p buf)
16762 file
16763 (y-or-n-p (format "Save file %s? " file)))
16764 (with-current-buffer buf (save-buffer)))
16765 (kill-buffer buf))))
16767 (defun org-prepare-agenda-buffers (files)
16768 "Create buffers for all agenda files, protect archived trees and comments."
16769 (interactive)
16770 (let ((pa '(:org-archived t))
16771 (pc '(:org-comment t))
16772 (pall '(:org-archived t :org-comment t))
16773 (inhibit-read-only t)
16774 (rea (concat ":" org-archive-tag ":"))
16775 bmp file re)
16776 (save-excursion
16777 (save-restriction
16778 (while (setq file (pop files))
16779 (catch 'nextfile
16780 (if (bufferp file)
16781 (set-buffer file)
16782 (org-check-agenda-file file)
16783 (set-buffer (org-get-agenda-file-buffer file)))
16784 (widen)
16785 (setq bmp (buffer-modified-p))
16786 (org-refresh-category-properties)
16787 (setq org-todo-keywords-for-agenda
16788 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16789 (setq org-done-keywords-for-agenda
16790 (append org-done-keywords-for-agenda org-done-keywords))
16791 (setq org-todo-keyword-alist-for-agenda
16792 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16793 (setq org-drawers-for-agenda
16794 (append org-drawers-for-agenda org-drawers))
16795 (setq org-tag-alist-for-agenda
16796 (append org-tag-alist-for-agenda org-tag-alist))
16798 (save-excursion
16799 (remove-text-properties (point-min) (point-max) pall)
16800 (when org-agenda-skip-archived-trees
16801 (goto-char (point-min))
16802 (while (re-search-forward rea nil t)
16803 (if (org-at-heading-p t)
16804 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16805 (goto-char (point-min))
16806 (setq re (format org-heading-keyword-regexp-format
16807 org-comment-string))
16808 (while (re-search-forward re nil t)
16809 (add-text-properties
16810 (match-beginning 0) (org-end-of-subtree t) pc)))
16811 (set-buffer-modified-p bmp)))))
16812 (setq org-todo-keywords-for-agenda
16813 (org-uniquify org-todo-keywords-for-agenda))
16814 (setq org-todo-keyword-alist-for-agenda
16815 (org-uniquify org-todo-keyword-alist-for-agenda)
16816 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16818 ;;;; Embedded LaTeX
16820 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16821 "Keymap for the minor `org-cdlatex-mode'.")
16823 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16824 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16825 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16826 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16827 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16829 (defvar org-cdlatex-texmathp-advice-is-done nil
16830 "Flag remembering if we have applied the advice to texmathp already.")
16832 (define-minor-mode org-cdlatex-mode
16833 "Toggle the minor `org-cdlatex-mode'.
16834 This mode supports entering LaTeX environment and math in LaTeX fragments
16835 in Org-mode.
16836 \\{org-cdlatex-mode-map}"
16837 nil " OCDL" nil
16838 (when org-cdlatex-mode
16839 (require 'cdlatex)
16840 (run-hooks 'cdlatex-mode-hook)
16841 (cdlatex-compute-tables))
16842 (unless org-cdlatex-texmathp-advice-is-done
16843 (setq org-cdlatex-texmathp-advice-is-done t)
16844 (defadvice texmathp (around org-math-always-on activate)
16845 "Always return t in org-mode buffers.
16846 This is because we want to insert math symbols without dollars even outside
16847 the LaTeX math segments. If Orgmode thinks that point is actually inside
16848 an embedded LaTeX fragment, let texmathp do its job.
16849 \\[org-cdlatex-mode-map]"
16850 (interactive)
16851 (let (p)
16852 (cond
16853 ((not (derived-mode-p 'org-mode)) ad-do-it)
16854 ((eq this-command 'cdlatex-math-symbol)
16855 (setq ad-return-value t
16856 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16858 (let ((p (org-inside-LaTeX-fragment-p)))
16859 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16860 (setq ad-return-value t
16861 texmathp-why '("Org-mode embedded math" . 0))
16862 (if p ad-do-it)))))))))
16864 (defun turn-on-org-cdlatex ()
16865 "Unconditionally turn on `org-cdlatex-mode'."
16866 (org-cdlatex-mode 1))
16868 (defun org-inside-LaTeX-fragment-p ()
16869 "Test if point is inside a LaTeX fragment.
16870 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16871 sequence appearing also before point.
16872 Even though the matchers for math are configurable, this function assumes
16873 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16874 delimiters are skipped when they have been removed by customization.
16875 The return value is nil, or a cons cell with the delimiter and the
16876 position of this delimiter.
16878 This function does a reasonably good job, but can locally be fooled by
16879 for example currency specifications. For example it will assume being in
16880 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16881 fragments that are properly closed, but during editing, we have to live
16882 with the uncertainty caused by missing closing delimiters. This function
16883 looks only before point, not after."
16884 (catch 'exit
16885 (let ((pos (point))
16886 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16887 (lim (progn
16888 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16889 (point)))
16890 dd-on str (start 0) m re)
16891 (goto-char pos)
16892 (when dodollar
16893 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16894 re (nth 1 (assoc "$" org-latex-regexps)))
16895 (while (string-match re str start)
16896 (cond
16897 ((= (match-end 0) (length str))
16898 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16899 ((= (match-end 0) (- (length str) 5))
16900 (throw 'exit nil))
16901 (t (setq start (match-end 0))))))
16902 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16903 (goto-char pos)
16904 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16905 (and (match-beginning 2) (throw 'exit nil))
16906 ;; count $$
16907 (while (re-search-backward "\\$\\$" lim t)
16908 (setq dd-on (not dd-on)))
16909 (goto-char pos)
16910 (if dd-on (cons "$$" m))))))
16912 (defun org-inside-latex-macro-p ()
16913 "Is point inside a LaTeX macro or its arguments?"
16914 (save-match-data
16915 (org-in-regexp
16916 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16918 (defun org-try-cdlatex-tab ()
16919 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16920 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16921 - inside a LaTeX fragment, or
16922 - after the first word in a line, where an abbreviation expansion could
16923 insert a LaTeX environment."
16924 (when org-cdlatex-mode
16925 (cond
16926 ;; Before any word on the line: No expansion possible.
16927 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16928 ;; Just after first word on the line: Expand it. Make sure it
16929 ;; cannot happen on headlines, though.
16930 ((save-excursion
16931 (skip-chars-backward "a-zA-Z0-9*")
16932 (skip-chars-backward " \t")
16933 (and (bolp) (not (org-at-heading-p))))
16934 (cdlatex-tab) t)
16935 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16937 (defun org-cdlatex-underscore-caret (&optional arg)
16938 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16939 Revert to the normal definition outside of these fragments."
16940 (interactive "P")
16941 (if (org-inside-LaTeX-fragment-p)
16942 (call-interactively 'cdlatex-sub-superscript)
16943 (let (org-cdlatex-mode)
16944 (call-interactively (key-binding (vector last-input-event))))))
16946 (defun org-cdlatex-math-modify (&optional arg)
16947 "Execute `cdlatex-math-modify' in LaTeX fragments.
16948 Revert to the normal definition outside of these fragments."
16949 (interactive "P")
16950 (if (org-inside-LaTeX-fragment-p)
16951 (call-interactively 'cdlatex-math-modify)
16952 (let (org-cdlatex-mode)
16953 (call-interactively (key-binding (vector last-input-event))))))
16955 (defvar org-latex-fragment-image-overlays nil
16956 "List of overlays carrying the images of latex fragments.")
16957 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16959 (defun org-remove-latex-fragment-image-overlays ()
16960 "Remove all overlays with LaTeX fragment images in current buffer."
16961 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16962 (setq org-latex-fragment-image-overlays nil))
16964 (defun org-preview-latex-fragment (&optional subtree)
16965 "Preview the LaTeX fragment at point, or all locally or globally.
16966 If the cursor is in a LaTeX fragment, create the image and overlay
16967 it over the source code. If there is no fragment at point, display
16968 all fragments in the current text, from one headline to the next. With
16969 prefix SUBTREE, display all fragments in the current subtree. With a
16970 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16971 the cursor is before the first headline,
16972 display all fragments in the buffer.
16973 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16974 (interactive "P")
16975 (unless buffer-file-name
16976 (error "Can't preview LaTeX fragment in a non-file buffer"))
16977 (org-remove-latex-fragment-image-overlays)
16978 (save-excursion
16979 (save-restriction
16980 (let (beg end at msg)
16981 (cond
16982 ((or (equal subtree '(16))
16983 (not (save-excursion
16984 (re-search-backward org-outline-regexp-bol nil t))))
16985 (setq beg (point-min) end (point-max)
16986 msg "Creating images for buffer...%s"))
16987 ((equal subtree '(4))
16988 (org-back-to-heading)
16989 (setq beg (point) end (org-end-of-subtree t)
16990 msg "Creating images for subtree...%s"))
16992 (if (setq at (org-inside-LaTeX-fragment-p))
16993 (goto-char (max (point-min) (- (cdr at) 2)))
16994 (org-back-to-heading))
16995 (setq beg (point) end (progn (outline-next-heading) (point))
16996 msg (if at "Creating image...%s"
16997 "Creating images for entry...%s"))))
16998 (message msg "")
16999 (narrow-to-region beg end)
17000 (goto-char beg)
17001 (org-format-latex
17002 (concat "ltxpng/" (file-name-sans-extension
17003 (file-name-nondirectory
17004 buffer-file-name)))
17005 default-directory 'overlays msg at 'forbuffer
17006 org-latex-create-formula-image-program)
17007 (message msg "done. Use `C-c C-c' to remove images.")))))
17009 (defvar org-latex-regexps
17010 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17011 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17012 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17013 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17014 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17015 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17016 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17017 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17018 "Regular expressions for matching embedded LaTeX.")
17020 (defvar org-export-have-math nil) ;; dynamic scoping
17021 (defun org-format-latex (prefix &optional dir overlays msg at
17022 forbuffer processing-type)
17023 "Replace LaTeX fragments with links to an image, and produce images.
17024 Some of the options can be changed using the variable
17025 `org-format-latex-options'."
17026 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17027 (let* ((prefixnodir (file-name-nondirectory prefix))
17028 (absprefix (expand-file-name prefix dir))
17029 (todir (file-name-directory absprefix))
17030 (opt org-format-latex-options)
17031 (matchers (plist-get opt :matchers))
17032 (re-list org-latex-regexps)
17033 (org-format-latex-header-extra
17034 (plist-get (org-infile-export-plist) :latex-header-extra))
17035 (cnt 0) txt hash link beg end re e checkdir
17036 executables-checked string
17037 m n block-type block linkfile movefile ov)
17038 ;; Check the different regular expressions
17039 (while (setq e (pop re-list))
17040 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17041 block (if block-type "\n\n" ""))
17042 (when (member m matchers)
17043 (goto-char (point-min))
17044 (while (re-search-forward re nil t)
17045 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17046 (not (get-text-property (match-beginning n)
17047 'org-protected))
17048 (or (not overlays)
17049 (not (eq (get-char-property (match-beginning n)
17050 'org-overlay-type)
17051 'org-latex-overlay))))
17052 (setq org-export-have-math t)
17053 (cond
17054 ((eq processing-type 'verbatim)
17055 ;; Leave the text verbatim, just protect it
17056 (add-text-properties (match-beginning n) (match-end n)
17057 '(org-protected t)))
17058 ((eq processing-type 'mathjax)
17059 ;; Prepare for MathJax processing
17060 (setq string (match-string n))
17061 (if (member m '("$" "$1"))
17062 (save-excursion
17063 (delete-region (match-beginning n) (match-end n))
17064 (goto-char (match-beginning n))
17065 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17066 "\\)")
17067 '(org-protected t))))
17068 (add-text-properties (match-beginning n) (match-end n)
17069 '(org-protected t))))
17070 ((or (eq processing-type 'dvipng)
17071 (eq processing-type 'imagemagick))
17072 ;; Process to an image
17073 (setq txt (match-string n)
17074 beg (match-beginning n) end (match-end n)
17075 cnt (1+ cnt))
17076 (let (print-length print-level) ; make sure full list is printed
17077 (setq hash (sha1 (prin1-to-string
17078 (list org-format-latex-header
17079 org-format-latex-header-extra
17080 org-export-latex-default-packages-alist
17081 org-export-latex-packages-alist
17082 org-format-latex-options
17083 forbuffer txt)))
17084 linkfile (format "%s_%s.png" prefix hash)
17085 movefile (format "%s_%s.png" absprefix hash)))
17086 (setq link (concat block "[[file:" linkfile "]]" block))
17087 (if msg (message msg cnt))
17088 (goto-char beg)
17089 (unless checkdir ; make sure the directory exists
17090 (setq checkdir t)
17091 (or (file-directory-p todir) (make-directory todir t)))
17092 (cond
17093 ((eq processing-type 'dvipng)
17094 (unless executables-checked
17095 (org-check-external-command
17096 "latex" "needed to convert LaTeX fragments to images")
17097 (org-check-external-command
17098 "dvipng" "needed to convert LaTeX fragments to images")
17099 (setq executables-checked t))
17100 (unless (file-exists-p movefile)
17101 (org-create-formula-image-with-dvipng
17102 txt movefile opt forbuffer)))
17103 ((eq processing-type 'imagemagick)
17104 (unless executables-checked
17105 (org-check-external-command
17106 "convert" "you need to install imagemagick")
17107 (setq executables-checked t))
17108 (unless (file-exists-p movefile)
17109 (org-create-formula-image-with-imagemagick
17110 txt movefile opt forbuffer))))
17111 (if overlays
17112 (progn
17113 (mapc (lambda (o)
17114 (if (eq (overlay-get o 'org-overlay-type)
17115 'org-latex-overlay)
17116 (delete-overlay o)))
17117 (overlays-in beg end))
17118 (setq ov (make-overlay beg end))
17119 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17120 (if (featurep 'xemacs)
17121 (progn
17122 (overlay-put ov 'invisible t)
17123 (overlay-put
17124 ov 'end-glyph
17125 (make-glyph (vector 'png :file movefile))))
17126 (overlay-put
17127 ov 'display
17128 (list 'image :type 'png :file movefile :ascent 'center)))
17129 (push ov org-latex-fragment-image-overlays)
17130 (goto-char end))
17131 (delete-region beg end)
17132 (insert (org-add-props link
17133 (list 'org-latex-src
17134 (replace-regexp-in-string
17135 "\"" "" txt)
17136 'org-latex-src-embed-type
17137 (if block-type 'paragraph 'character))))))
17138 ((eq processing-type 'mathml)
17139 ;; Process to MathML
17140 (unless executables-checked
17141 (unless (save-match-data (org-format-latex-mathml-available-p))
17142 (error "LaTeX to MathML converter not configured"))
17143 (setq executables-checked t))
17144 (setq txt (match-string n)
17145 beg (match-beginning n) end (match-end n)
17146 cnt (1+ cnt))
17147 (if msg (message msg cnt))
17148 (goto-char beg)
17149 (delete-region beg end)
17150 (insert (org-format-latex-as-mathml
17151 txt block-type prefix dir)))
17153 (error "Unknown conversion type %s for latex fragments"
17154 processing-type)))))))))
17156 (defun org-create-math-formula (latex-frag &optional mathml-file)
17157 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17158 Use `org-latex-to-mathml-convert-command'. If the conversion is
17159 sucessful, return the portion between \"<math...> </math>\"
17160 elements otherwise return nil. When MATHML-FILE is specified,
17161 write the results in to that file. When invoked as an
17162 interactive command, prompt for LATEX-FRAG, with initial value
17163 set to the current active region and echo the results for user
17164 inspection."
17165 (interactive (list (let ((frag (when (region-active-p)
17166 (buffer-substring-no-properties
17167 (region-beginning) (region-end)))))
17168 (read-string "LaTeX Fragment: " frag nil frag))))
17169 (unless latex-frag (error "Invalid latex-frag"))
17170 (let* ((tmp-in-file (file-relative-name
17171 (make-temp-name (expand-file-name "ltxmathml-in"))))
17172 (ignore (write-region latex-frag nil tmp-in-file))
17173 (tmp-out-file (file-relative-name
17174 (make-temp-name (expand-file-name "ltxmathml-out"))))
17175 (cmd (format-spec
17176 org-latex-to-mathml-convert-command
17177 `((?j . ,(shell-quote-argument
17178 (expand-file-name org-latex-to-mathml-jar-file)))
17179 (?I . ,(shell-quote-argument tmp-in-file))
17180 (?o . ,(shell-quote-argument tmp-out-file)))))
17181 mathml shell-command-output)
17182 (when (org-called-interactively-p 'any)
17183 (unless (org-format-latex-mathml-available-p)
17184 (error "LaTeX to MathML converter not configured")))
17185 (message "Running %s" cmd)
17186 (setq shell-command-output (shell-command-to-string cmd))
17187 (setq mathml
17188 (when (file-readable-p tmp-out-file)
17189 (with-current-buffer (find-file-noselect tmp-out-file t)
17190 (goto-char (point-min))
17191 (when (re-search-forward
17192 (concat
17193 (regexp-quote
17194 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17195 "\\(.\\|\n\\)*"
17196 (regexp-quote "</math>")) nil t)
17197 (prog1 (match-string 0) (kill-buffer))))))
17198 (cond
17199 (mathml
17200 (setq mathml
17201 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17202 (when mathml-file
17203 (write-region mathml nil mathml-file))
17204 (when (org-called-interactively-p 'any)
17205 (message mathml)))
17206 ((message "LaTeX to MathML conversion failed")
17207 (message shell-command-output)))
17208 (delete-file tmp-in-file)
17209 (when (file-exists-p tmp-out-file)
17210 (delete-file tmp-out-file))
17211 mathml))
17213 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17214 prefix &optional dir)
17215 "Use `org-create-math-formula' but check local cache first."
17216 (let* ((absprefix (expand-file-name prefix dir))
17217 (print-length nil) (print-level nil)
17218 (formula-id (concat
17219 "formula-"
17220 (sha1
17221 (prin1-to-string
17222 (list latex-frag
17223 org-latex-to-mathml-convert-command)))))
17224 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17225 (formula-cache-dir (file-name-directory formula-cache)))
17227 (unless (file-directory-p formula-cache-dir)
17228 (make-directory formula-cache-dir t))
17230 (unless (file-exists-p formula-cache)
17231 (org-create-math-formula latex-frag formula-cache))
17233 (if (file-exists-p formula-cache)
17234 ;; Successful conversion. Return the link to MathML file.
17235 (org-add-props
17236 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17237 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17238 'org-latex-src-embed-type (if latex-frag-type
17239 'paragraph 'character)))
17240 ;; Failed conversion. Return the LaTeX fragment verbatim
17241 (add-text-properties
17242 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17243 latex-frag)))
17245 ;; This function borrows from Ganesh Swami's latex2png.el
17246 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17247 "This calls dvipng."
17248 (require 'org-latex)
17249 (let* ((tmpdir (if (featurep 'xemacs)
17250 (temp-directory)
17251 temporary-file-directory))
17252 (texfilebase (make-temp-name
17253 (expand-file-name "orgtex" tmpdir)))
17254 (texfile (concat texfilebase ".tex"))
17255 (dvifile (concat texfilebase ".dvi"))
17256 (pngfile (concat texfilebase ".png"))
17257 (fnh (if (featurep 'xemacs)
17258 (font-height (face-font 'default))
17259 (face-attribute 'default :height nil)))
17260 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17261 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17262 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17263 "Black"))
17264 (bg (or (plist-get options (if buffer :background :html-background))
17265 "Transparent")))
17266 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17267 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17268 (with-temp-file texfile
17269 (insert (org-splice-latex-header
17270 org-format-latex-header
17271 org-export-latex-default-packages-alist
17272 org-export-latex-packages-alist t
17273 org-format-latex-header-extra))
17274 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17275 (require 'org-latex)
17276 (org-export-latex-fix-inputenc))
17277 (let ((dir default-directory))
17278 (condition-case nil
17279 (progn
17280 (cd tmpdir)
17281 (call-process "latex" nil nil nil texfile))
17282 (error nil))
17283 (cd dir))
17284 (if (not (file-exists-p dvifile))
17285 (progn (message "Failed to create dvi file from %s" texfile) nil)
17286 (condition-case nil
17287 (if (featurep 'xemacs)
17288 (call-process "dvipng" nil nil nil
17289 "-fg" fg "-bg" bg
17290 "-T" "tight"
17291 "-o" pngfile
17292 dvifile)
17293 (call-process "dvipng" nil nil nil
17294 "-fg" fg "-bg" bg
17295 "-D" dpi
17296 ;;"-x" scale "-y" scale
17297 "-T" "tight"
17298 "-o" pngfile
17299 dvifile))
17300 (error nil))
17301 (if (not (file-exists-p pngfile))
17302 (if org-format-latex-signal-error
17303 (error "Failed to create png file from %s" texfile)
17304 (message "Failed to create png file from %s" texfile)
17305 nil)
17306 ;; Use the requested file name and clean up
17307 (copy-file pngfile tofile 'replace)
17308 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17309 (if (file-exists-p (concat texfilebase e))
17310 (delete-file (concat texfilebase e))))
17311 pngfile))))
17313 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17314 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17315 "This calls convert, which is included into imagemagick."
17316 (require 'org-latex)
17317 (let* ((tmpdir (if (featurep 'xemacs)
17318 (temp-directory)
17319 temporary-file-directory))
17320 (texfilebase (make-temp-name
17321 (expand-file-name "orgtex" tmpdir)))
17322 (texfile (concat texfilebase ".tex"))
17323 (pdffile (concat texfilebase ".pdf"))
17324 (pngfile (concat texfilebase ".png"))
17325 (fnh (if (featurep 'xemacs)
17326 (font-height (face-font 'default))
17327 (face-attribute 'default :height nil)))
17328 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17329 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17330 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17331 "black"))
17332 (bg (or (plist-get options (if buffer :background :html-background))
17333 "white")))
17334 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17335 (setq fg (org-latex-color-format fg)))
17336 (if (eq bg 'default) (setq bg (org-latex-color :background))
17337 (setq bg (org-latex-color-format
17338 (if (string= bg "Transparent")(setq bg "white")))))
17339 (with-temp-file texfile
17340 (insert (org-splice-latex-header
17341 org-format-latex-header
17342 org-export-latex-default-packages-alist
17343 org-export-latex-packages-alist t
17344 org-format-latex-header-extra))
17345 (insert "\n\\begin{document}\n"
17346 "\\definecolor{fg}{rgb}{" fg "}\n"
17347 "\\definecolor{bg}{rgb}{" bg "}\n"
17348 "\n\\pagecolor{bg}\n"
17349 "\n{\\color{fg}\n"
17350 string
17351 "\n}\n"
17352 "\n\\end{document}\n" )
17353 (require 'org-latex)
17354 (org-export-latex-fix-inputenc))
17355 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17356 (condition-case nil
17357 (progn
17358 (cd tmpdir)
17359 (setq cmds org-latex-to-pdf-process)
17360 (while cmds
17361 (setq latex-frags-cmds (pop cmds))
17362 (if (listp latex-frags-cmds)
17363 (setq cmds nil)
17364 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17365 (while latex-frags-cmds
17366 (setq cmd (pop latex-frags-cmds))
17367 (while (string-match "%b" cmd)
17368 (setq cmd (replace-match
17369 (save-match-data
17370 (shell-quote-argument texfile))
17371 t t cmd)))
17372 (while (string-match "%f" cmd)
17373 (setq cmd (replace-match
17374 (save-match-data
17375 (shell-quote-argument (file-name-nondirectory texfile)))
17376 t t cmd)))
17377 (while (string-match "%o" cmd)
17378 (setq cmd (replace-match
17379 (save-match-data
17380 (shell-quote-argument (file-name-directory texfile)))
17381 t t cmd)))
17382 (setq cmd (split-string cmd))
17383 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17384 (error nil))
17385 (cd dir))
17386 (if (not (file-exists-p pdffile))
17387 (progn (message "Failed to create pdf file from %s" texfile) nil)
17388 (condition-case nil
17389 (if (featurep 'xemacs)
17390 (call-process "convert" nil nil nil
17391 "-density" "96"
17392 "-trim"
17393 "-antialias"
17394 pdffile
17395 "-quality" "100"
17396 ;; "-sharpen" "0x1.0"
17397 pngfile)
17398 (call-process "convert" nil nil nil
17399 "-density" dpi
17400 "-trim"
17401 "-antialias"
17402 pdffile
17403 "-quality" "100"
17404 ; "-sharpen" "0x1.0"
17405 pngfile))
17406 (error nil))
17407 (if (not (file-exists-p pngfile))
17408 (if org-format-latex-signal-error
17409 (error "Failed to create png file from %s" texfile)
17410 (message "Failed to create png file from %s" texfile)
17411 nil)
17412 ;; Use the requested file name and clean up
17413 (copy-file pngfile tofile 'replace)
17414 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17415 (if (file-exists-p (concat texfilebase e))
17416 (delete-file (concat texfilebase e))))
17417 pngfile))))
17419 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17420 "Fill a LaTeX header template TPL.
17421 In the template, the following place holders will be recognized:
17423 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17424 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17425 [PACKAGES] \\usepackage statements for PKG
17426 [NO-PACKAGES] do not include PKG
17427 [EXTRA] the string EXTRA
17428 [NO-EXTRA] do not include EXTRA
17430 For backward compatibility, if both the positive and the negative place
17431 holder is missing, the positive one (without the \"NO-\") will be
17432 assumed to be present at the end of the template.
17433 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17434 EXTRA is a string.
17435 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17436 (let (rpl (end ""))
17437 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17438 (setq rpl (if (or (match-end 1) (not def-pkg))
17439 "" (org-latex-packages-to-string def-pkg snippets-p t))
17440 tpl (replace-match rpl t t tpl))
17441 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17443 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17444 (setq rpl (if (or (match-end 1) (not pkg))
17445 "" (org-latex-packages-to-string pkg snippets-p t))
17446 tpl (replace-match rpl t t tpl))
17447 (if pkg (setq end
17448 (concat end "\n"
17449 (org-latex-packages-to-string pkg snippets-p)))))
17451 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17452 (setq rpl (if (or (match-end 1) (not extra))
17453 "" (concat extra "\n"))
17454 tpl (replace-match rpl t t tpl))
17455 (if (and extra (string-match "\\S-" extra))
17456 (setq end (concat end "\n" extra))))
17458 (if (string-match "\\S-" end)
17459 (concat tpl "\n" end)
17460 tpl)))
17462 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17463 "Turn an alist of packages into a string with the \\usepackage macros."
17464 (setq pkg (mapconcat (lambda(p)
17465 (cond
17466 ((stringp p) p)
17467 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17468 (format "%% Package %s omitted" (cadr p)))
17469 ((equal "" (car p))
17470 (format "\\usepackage{%s}" (cadr p)))
17472 (format "\\usepackage[%s]{%s}"
17473 (car p) (cadr p)))))
17475 "\n"))
17476 (if newline (concat pkg "\n") pkg))
17478 (defun org-dvipng-color (attr)
17479 "Return a RGB color specification for dvipng."
17480 (apply 'format "rgb %s %s %s"
17481 (mapcar 'org-normalize-color
17482 (if (featurep 'xemacs)
17483 (color-rgb-components
17484 (face-property 'default
17485 (cond ((eq attr :foreground) 'foreground)
17486 ((eq attr :background) 'background))))
17487 (color-values (face-attribute 'default attr nil))))))
17489 (defun org-latex-color (attr)
17490 "Return a RGB color for the LaTeX color package."
17491 (apply 'format "%s,%s,%s"
17492 (mapcar 'org-normalize-color
17493 (if (featurep 'xemacs)
17494 (color-rgb-components
17495 (face-property 'default
17496 (cond ((eq attr :foreground) 'foreground)
17497 ((eq attr :background) 'background))))
17498 (color-values (face-attribute 'default attr nil))))))
17500 (defun org-latex-color-format (color-name)
17501 "Convert COLOR-NAME to a RGB color value."
17502 (apply 'format "%s,%s,%s"
17503 (mapcar 'org-normalize-color
17504 (color-values color-name))))
17506 (defun org-normalize-color (value)
17507 "Return string to be used as color value for an RGB component."
17508 (format "%g" (/ value 65535.0)))
17510 ;; Image display
17513 (defvar org-inline-image-overlays nil)
17514 (make-variable-buffer-local 'org-inline-image-overlays)
17516 (defun org-toggle-inline-images (&optional include-linked)
17517 "Toggle the display of inline images.
17518 INCLUDE-LINKED is passed to `org-display-inline-images'."
17519 (interactive "P")
17520 (if org-inline-image-overlays
17521 (progn
17522 (org-remove-inline-images)
17523 (message "Inline image display turned off"))
17524 (org-display-inline-images include-linked)
17525 (if org-inline-image-overlays
17526 (message "%d images displayed inline"
17527 (length org-inline-image-overlays))
17528 (message "No images to display inline"))))
17530 (defun org-display-inline-images (&optional include-linked refresh beg end)
17531 "Display inline images.
17532 Normally only links without a description part are inlined, because this
17533 is how it will work for export. When INCLUDE-LINKED is set, also links
17534 with a description part will be inlined. This can be nice for a quick
17535 look at those images, but it does not reflect what exported files will look
17536 like.
17537 When REFRESH is set, refresh existing images between BEG and END.
17538 This will create new image displays only if necessary.
17539 BEG and END default to the buffer boundaries."
17540 (interactive "P")
17541 (unless refresh
17542 (org-remove-inline-images)
17543 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17544 (save-excursion
17545 (save-restriction
17546 (widen)
17547 (setq beg (or beg (point-min)) end (or end (point-max)))
17548 (goto-char beg)
17549 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17550 (substring (org-image-file-name-regexp) 0 -2)
17551 "\\)\\]" (if include-linked "" "\\]")))
17552 old file ov img)
17553 (while (re-search-forward re end t)
17554 (setq old (get-char-property-and-overlay (match-beginning 1)
17555 'org-image-overlay))
17556 (setq file (expand-file-name
17557 (concat (or (match-string 3) "") (match-string 4))))
17558 (when (file-exists-p file)
17559 (if (and (car-safe old) refresh)
17560 (image-refresh (overlay-get (cdr old) 'display))
17561 (setq img (save-match-data (create-image file)))
17562 (when img
17563 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17564 (overlay-put ov 'display img)
17565 (overlay-put ov 'face 'default)
17566 (overlay-put ov 'org-image-overlay t)
17567 (overlay-put ov 'modification-hooks
17568 (list 'org-display-inline-modification-hook))
17569 (push ov org-inline-image-overlays)))))))))
17571 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17572 "Remove inline-display overlay if a corresponding region is modified."
17573 (let ((inhibit-modification-hooks t))
17574 (when (and ov after)
17575 (delete ov org-inline-image-overlays)
17576 (delete-overlay ov))))
17578 (defun org-remove-inline-images ()
17579 "Remove inline display of images."
17580 (interactive)
17581 (mapc 'delete-overlay org-inline-image-overlays)
17582 (setq org-inline-image-overlays nil))
17584 ;;;; Key bindings
17586 ;; Outline functions from `outline-mode-prefix-map'
17587 ;; that can be remapped in Org:
17588 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17589 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17590 (define-key org-mode-map [remap outline-forward-same-level]
17591 'org-forward-same-level)
17592 (define-key org-mode-map [remap outline-backward-same-level]
17593 'org-backward-same-level)
17594 (define-key org-mode-map [remap show-branches]
17595 'org-kill-note-or-show-branches)
17596 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17597 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17598 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17600 ;; Outline functions from `outline-mode-prefix-map' that can not
17601 ;; be remapped in Org:
17603 ;; - the column "key binding" shows whether the Outline function is still
17604 ;; available in Org mode on the same key that it has been bound to in
17605 ;; Outline mode:
17606 ;; - "overridden": key used for a different functionality in Org mode
17607 ;; - else: key still bound to the same Outline function in Org mode
17609 ;; | Outline function | key binding | Org replacement |
17610 ;; |------------------------------------+-------------+-----------------------|
17611 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17612 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17613 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17614 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17615 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17616 ;; | `show-entry' | overridden | no replacement |
17617 ;; | `show-children' | `C-c C-i' | visibility cycling |
17618 ;; | `show-branches' | `C-c C-k' | still same function |
17619 ;; | `show-subtree' | overridden | visibility cycling |
17620 ;; | `show-all' | overridden | no replacement |
17621 ;; | `hide-subtree' | overridden | visibility cycling |
17622 ;; | `hide-body' | overridden | no replacement |
17623 ;; | `hide-entry' | overridden | visibility cycling |
17624 ;; | `hide-leaves' | overridden | no replacement |
17625 ;; | `hide-sublevels' | overridden | no replacement |
17626 ;; | `hide-other' | overridden | no replacement |
17628 ;; Make `C-c C-x' a prefix key
17629 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17631 ;; TAB key with modifiers
17632 (org-defkey org-mode-map "\C-i" 'org-cycle)
17633 (org-defkey org-mode-map [(tab)] 'org-cycle)
17634 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17635 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17636 ;; The following line is necessary under Suse GNU/Linux
17637 (unless (featurep 'xemacs)
17638 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17639 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17640 (define-key org-mode-map [backtab] 'org-shifttab)
17642 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17643 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17644 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17646 ;; Cursor keys with modifiers
17647 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17648 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17649 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17650 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17652 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17653 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17654 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17655 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17657 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17658 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17659 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17660 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17662 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17663 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17664 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17665 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17667 ;; Babel keys
17668 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17669 (mapc (lambda (pair)
17670 (define-key org-babel-map (car pair) (cdr pair)))
17671 org-babel-key-bindings)
17673 ;;; Extra keys for tty access.
17674 ;; We only set them when really needed because otherwise the
17675 ;; menus don't show the simple keys
17677 (when (or org-use-extra-keys
17678 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17679 (not window-system))
17680 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17681 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17682 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17683 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17684 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17685 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17686 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17687 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17688 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17689 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17690 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17691 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17692 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17693 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17694 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17695 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17696 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17697 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17698 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17699 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17700 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17701 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17702 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17703 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17704 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17705 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17706 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17707 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17709 ;; All the other keys
17711 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17712 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17713 (if (boundp 'narrow-map)
17714 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17715 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17716 (if (boundp 'narrow-map)
17717 (org-defkey narrow-map "b" 'org-narrow-to-block)
17718 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17719 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17720 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17721 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17722 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17723 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17724 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17725 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17726 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17727 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17728 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17729 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17730 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17731 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17732 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17733 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17734 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17735 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17736 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17737 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17738 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17739 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17740 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17741 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17742 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17743 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17744 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17745 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17746 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17747 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17748 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17749 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17750 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17751 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17752 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17753 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17754 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17755 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17756 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17757 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17758 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17759 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17760 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17761 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17762 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17763 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17764 (org-defkey org-mode-map "\C-c^" 'org-sort)
17765 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17766 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17767 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17768 (org-defkey org-mode-map "\C-m" 'org-return)
17769 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17770 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17771 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17772 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17773 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17774 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17775 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17776 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17777 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17778 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17779 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17780 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17781 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17782 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17783 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17784 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17785 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17786 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17787 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17788 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17789 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17790 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17791 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17793 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17794 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17795 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17796 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17798 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17799 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17800 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
17801 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17802 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17803 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
17804 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17805 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17806 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17807 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17808 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17809 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17810 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17811 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17812 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17813 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17814 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17815 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17816 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17818 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17819 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17820 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17821 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17822 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17824 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17826 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17828 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17829 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17831 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17834 (when (featurep 'xemacs)
17835 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17838 (defconst org-speed-commands-default
17840 ("Outline Navigation")
17841 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17842 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17843 ("f" . (org-speed-move-safe 'org-forward-same-level))
17844 ("b" . (org-speed-move-safe 'org-backward-same-level))
17845 ("u" . (org-speed-move-safe 'outline-up-heading))
17846 ("j" . org-goto)
17847 ("g" . (org-refile t))
17848 ("Outline Visibility")
17849 ("c" . org-cycle)
17850 ("C" . org-shifttab)
17851 (" " . org-display-outline-path)
17852 (":" . org-columns)
17853 ("Outline Structure Editing")
17854 ("U" . org-shiftmetaup)
17855 ("D" . org-shiftmetadown)
17856 ("r" . org-metaright)
17857 ("l" . org-metaleft)
17858 ("R" . org-shiftmetaright)
17859 ("L" . org-shiftmetaleft)
17860 ("i" . (progn (forward-char 1) (call-interactively
17861 'org-insert-heading-respect-content)))
17862 ("^" . org-sort)
17863 ("w" . org-refile)
17864 ("a" . org-archive-subtree-default-with-confirmation)
17865 ("." . org-mark-subtree)
17866 ("#" . org-toggle-comment)
17867 ("Clock Commands")
17868 ("I" . org-clock-in)
17869 ("O" . org-clock-out)
17870 ("Meta Data Editing")
17871 ("t" . org-todo)
17872 ("0" . (org-priority ?\ ))
17873 ("1" . (org-priority ?A))
17874 ("2" . (org-priority ?B))
17875 ("3" . (org-priority ?C))
17876 (";" . org-set-tags-command)
17877 ("e" . org-set-effort)
17878 ("Agenda Views etc")
17879 ("v" . org-agenda)
17880 ("/" . org-sparse-tree)
17881 ("Misc")
17882 ("o" . org-open-at-point)
17883 ("?" . org-speed-command-help)
17884 ("<" . (org-agenda-set-restriction-lock 'subtree))
17885 (">" . (org-agenda-remove-restriction-lock))
17887 "The default speed commands.")
17889 (defun org-print-speed-command (e)
17890 (if (> (length (car e)) 1)
17891 (progn
17892 (princ "\n")
17893 (princ (car e))
17894 (princ "\n")
17895 (princ (make-string (length (car e)) ?-))
17896 (princ "\n"))
17897 (princ (car e))
17898 (princ " ")
17899 (if (symbolp (cdr e))
17900 (princ (symbol-name (cdr e)))
17901 (prin1 (cdr e)))
17902 (princ "\n")))
17904 (defun org-speed-command-help ()
17905 "Show the available speed commands."
17906 (interactive)
17907 (if (not org-use-speed-commands)
17908 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17909 (with-output-to-temp-buffer "*Help*"
17910 (princ "User-defined Speed commands\n===========================\n")
17911 (mapc 'org-print-speed-command org-speed-commands-user)
17912 (princ "\n")
17913 (princ "Built-in Speed commands\n=======================\n")
17914 (mapc 'org-print-speed-command org-speed-commands-default))
17915 (with-current-buffer "*Help*"
17916 (setq truncate-lines t))))
17918 (defun org-speed-move-safe (cmd)
17919 "Execute CMD, but make sure that the cursor always ends up in a headline.
17920 If not, return to the original position and throw an error."
17921 (interactive)
17922 (let ((pos (point)))
17923 (call-interactively cmd)
17924 (unless (and (bolp) (org-at-heading-p))
17925 (goto-char pos)
17926 (error "Boundary reached while executing %s" cmd))))
17928 (defvar org-self-insert-command-undo-counter 0)
17930 (defvar org-table-auto-blank-field) ; defined in org-table.el
17931 (defvar org-speed-command nil)
17933 (defun org-speed-command-default-hook (keys)
17934 "Hook for activating single-letter speed commands.
17935 `org-speed-commands-default' specifies a minimal command set.
17936 Use `org-speed-commands-user' for further customization."
17937 (when (or (and (bolp) (looking-at org-outline-regexp))
17938 (and (functionp org-use-speed-commands)
17939 (funcall org-use-speed-commands)))
17940 (cdr (assoc keys (append org-speed-commands-user
17941 org-speed-commands-default)))))
17943 (defun org-babel-speed-command-hook (keys)
17944 "Hook for activating single-letter code block commands."
17945 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17946 (cdr (assoc keys org-babel-key-bindings))))
17948 (defcustom org-speed-command-hook
17949 '(org-speed-command-default-hook org-babel-speed-command-hook)
17950 "Hook for activating speed commands at strategic locations.
17951 Hook functions are called in sequence until a valid handler is
17952 found.
17954 Each hook takes a single argument, a user-pressed command key
17955 which is also a `self-insert-command' from the global map.
17957 Within the hook, examine the cursor position and the command key
17958 and return nil or a valid handler as appropriate. Handler could
17959 be one of an interactive command, a function, or a form.
17961 Set `org-use-speed-commands' to non-nil value to enable this
17962 hook. The default setting is `org-speed-command-default-hook'."
17963 :group 'org-structure
17964 :version "24.1"
17965 :type 'hook)
17967 (defun org-self-insert-command (N)
17968 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17969 If the cursor is in a table looking at whitespace, the whitespace is
17970 overwritten, and the table is not marked as requiring realignment."
17971 (interactive "p")
17972 (org-check-before-invisible-edit 'insert)
17973 (cond
17974 ((and org-use-speed-commands
17975 (setq org-speed-command
17976 (run-hook-with-args-until-success
17977 'org-speed-command-hook (this-command-keys))))
17978 (cond
17979 ((commandp org-speed-command)
17980 (setq this-command org-speed-command)
17981 (call-interactively org-speed-command))
17982 ((functionp org-speed-command)
17983 (funcall org-speed-command))
17984 ((and org-speed-command (listp org-speed-command))
17985 (eval org-speed-command))
17986 (t (let (org-use-speed-commands)
17987 (call-interactively 'org-self-insert-command)))))
17988 ((and
17989 (org-table-p)
17990 (progn
17991 ;; check if we blank the field, and if that triggers align
17992 (and (featurep 'org-table) org-table-auto-blank-field
17993 (member last-command
17994 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17995 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17996 ;; got extra space, this field does not determine column width
17997 (let (org-table-may-need-update) (org-table-blank-field))
17998 ;; no extra space, this field may determine column width
17999 (org-table-blank-field)))
18001 (eq N 1)
18002 (looking-at "[^|\n]* |"))
18003 (let (org-table-may-need-update)
18004 (goto-char (1- (match-end 0)))
18005 (backward-delete-char 1)
18006 (goto-char (match-beginning 0))
18007 (self-insert-command N)))
18009 (setq org-table-may-need-update t)
18010 (self-insert-command N)
18011 (org-fix-tags-on-the-fly)
18012 (if org-self-insert-cluster-for-undo
18013 (if (not (eq last-command 'org-self-insert-command))
18014 (setq org-self-insert-command-undo-counter 1)
18015 (if (>= org-self-insert-command-undo-counter 20)
18016 (setq org-self-insert-command-undo-counter 1)
18017 (and (> org-self-insert-command-undo-counter 0)
18018 buffer-undo-list (listp buffer-undo-list)
18019 (not (cadr buffer-undo-list)) ; remove nil entry
18020 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18021 (setq org-self-insert-command-undo-counter
18022 (1+ org-self-insert-command-undo-counter))))))))
18024 (defun org-check-before-invisible-edit (kind)
18025 "Check is editing if kind KIND would be dangerous with invisible text around.
18026 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18027 ;; First, try to get out of here as quickly as possible, to reduce overhead
18028 (if (and org-catch-invisible-edits
18029 (or (not (boundp 'visible-mode)) (not visible-mode))
18030 (or (get-char-property (point) 'invisible)
18031 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18032 ;; OK, we need to take a closer look
18033 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18034 (invisible-before-point (if (bobp) nil (get-char-property
18035 (1- (point)) 'invisible)))
18036 (border-and-ok-direction
18038 ;; Check if we are acting predictably before invisible text
18039 (and invisible-at-point (not invisible-before-point)
18040 (memq kind '(insert delete-backward)))
18041 ;; Check if we are acting predictably after invisible text
18042 ;; This works not well, and I have turned it off. It seems
18043 ;; better to always show and stop after invisible text.
18044 ;; (and (not invisible-at-point) invisible-before-point
18045 ;; (memq kind '(insert delete)))
18048 (when (or (memq invisible-at-point '(outline org-hide-block))
18049 (memq invisible-before-point '(outline org-hide-block)))
18050 (if (eq org-catch-invisible-edits 'error)
18051 (error "Editing in invisible areas is prohibited - make visible first"))
18052 ;; Make the area visible
18053 (save-excursion
18054 (if invisible-before-point
18055 (goto-char (previous-single-char-property-change
18056 (point) 'invisible)))
18057 (org-cycle))
18058 (cond
18059 ((eq org-catch-invisible-edits 'show)
18060 ;; That's it, we do the edit after showing
18061 (message
18062 "Unfolding invisible region around point before editing")
18063 (sit-for 1))
18064 ((and (eq org-catch-invisible-edits 'smart)
18065 border-and-ok-direction)
18066 (message "Unfolding invisible region around point before editing"))
18068 ;; Don't do the edit, make the user repeat it in full visibility
18069 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
18071 (defun org-fix-tags-on-the-fly ()
18072 (when (and (equal (char-after (point-at-bol)) ?*)
18073 (org-at-heading-p))
18074 (org-align-tags-here org-tags-column)))
18076 (defun org-delete-backward-char (N)
18077 "Like `delete-backward-char', insert whitespace at field end in tables.
18078 When deleting backwards, in tables this function will insert whitespace in
18079 front of the next \"|\" separator, to keep the table aligned. The table will
18080 still be marked for re-alignment if the field did fill the entire column,
18081 because, in this case the deletion might narrow the column."
18082 (interactive "p")
18083 (org-check-before-invisible-edit 'delete-backward)
18084 (if (and (org-table-p)
18085 (eq N 1)
18086 (string-match "|" (buffer-substring (point-at-bol) (point)))
18087 (looking-at ".*?|"))
18088 (let ((pos (point))
18089 (noalign (looking-at "[^|\n\r]* |"))
18090 (c org-table-may-need-update))
18091 (backward-delete-char N)
18092 (if (not overwrite-mode)
18093 (progn
18094 (skip-chars-forward "^|")
18095 (insert " ")
18096 (goto-char (1- pos))))
18097 ;; noalign: if there were two spaces at the end, this field
18098 ;; does not determine the width of the column.
18099 (if noalign (setq org-table-may-need-update c)))
18100 (backward-delete-char N)
18101 (org-fix-tags-on-the-fly)))
18103 (defun org-delete-char (N)
18104 "Like `delete-char', but insert whitespace at field end in tables.
18105 When deleting characters, in tables this function will insert whitespace in
18106 front of the next \"|\" separator, to keep the table aligned. The table will
18107 still be marked for re-alignment if the field did fill the entire column,
18108 because, in this case the deletion might narrow the column."
18109 (interactive "p")
18110 (org-check-before-invisible-edit 'delete)
18111 (if (and (org-table-p)
18112 (not (bolp))
18113 (not (= (char-after) ?|))
18114 (eq N 1))
18115 (if (looking-at ".*?|")
18116 (let ((pos (point))
18117 (noalign (looking-at "[^|\n\r]* |"))
18118 (c org-table-may-need-update))
18119 (replace-match (concat
18120 (substring (match-string 0) 1 -1)
18121 " |"))
18122 (goto-char pos)
18123 ;; noalign: if there were two spaces at the end, this field
18124 ;; does not determine the width of the column.
18125 (if noalign (setq org-table-may-need-update c)))
18126 (delete-char N))
18127 (delete-char N)
18128 (org-fix-tags-on-the-fly)))
18130 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18131 (put 'org-self-insert-command 'delete-selection t)
18132 (put 'orgtbl-self-insert-command 'delete-selection t)
18133 (put 'org-delete-char 'delete-selection 'supersede)
18134 (put 'org-delete-backward-char 'delete-selection 'supersede)
18135 (put 'org-yank 'delete-selection 'yank)
18137 ;; Make `flyspell-mode' delay after some commands
18138 (put 'org-self-insert-command 'flyspell-delayed t)
18139 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18140 (put 'org-delete-char 'flyspell-delayed t)
18141 (put 'org-delete-backward-char 'flyspell-delayed t)
18143 ;; Make pabbrev-mode expand after org-mode commands
18144 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18145 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18147 ;; How to do this: Measure non-white length of current string
18148 ;; If equal to column width, we should realign.
18150 (defun org-remap (map &rest commands)
18151 "In MAP, remap the functions given in COMMANDS.
18152 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18153 (let (new old)
18154 (while commands
18155 (setq old (pop commands) new (pop commands))
18156 (if (fboundp 'command-remapping)
18157 (org-defkey map (vector 'remap old) new)
18158 (substitute-key-definition old new map global-map)))))
18160 (when (eq org-enable-table-editor 'optimized)
18161 ;; If the user wants maximum table support, we need to hijack
18162 ;; some standard editing functions
18163 (org-remap org-mode-map
18164 'self-insert-command 'org-self-insert-command
18165 'delete-char 'org-delete-char
18166 'delete-backward-char 'org-delete-backward-char)
18167 (org-defkey org-mode-map "|" 'org-force-self-insert))
18169 (defvar org-ctrl-c-ctrl-c-hook nil
18170 "Hook for functions attaching themselves to `C-c C-c'.
18172 This can be used to add additional functionality to the C-c C-c
18173 key which executes context-dependent commands. This hook is run
18174 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18175 run after the last test.
18177 Each function will be called with no arguments. The function
18178 must check if the context is appropriate for it to act. If yes,
18179 it should do its thing and then return a non-nil value. If the
18180 context is wrong, just do nothing and return nil.")
18182 (defvar org-ctrl-c-ctrl-c-final-hook nil
18183 "Hook for functions attaching themselves to `C-c C-c'.
18185 This can be used to add additional functionality to the C-c C-c
18186 key which executes context-dependent commands. This hook is run
18187 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18188 before the first test.
18190 Each function will be called with no arguments. The function
18191 must check if the context is appropriate for it to act. If yes,
18192 it should do its thing and then return a non-nil value. If the
18193 context is wrong, just do nothing and return nil.")
18195 (defvar org-tab-first-hook nil
18196 "Hook for functions to attach themselves to TAB.
18197 See `org-ctrl-c-ctrl-c-hook' for more information.
18198 This hook runs as the first action when TAB is pressed, even before
18199 `org-cycle' messes around with the `outline-regexp' to cater for
18200 inline tasks and plain list item folding.
18201 If any function in this hook returns t, any other actions that
18202 would have been caused by TAB (such as table field motion or visibility
18203 cycling) will not occur.")
18205 (defvar org-tab-after-check-for-table-hook nil
18206 "Hook for functions to attach themselves to TAB.
18207 See `org-ctrl-c-ctrl-c-hook' for more information.
18208 This hook runs after it has been established that the cursor is not in a
18209 table, but before checking if the cursor is in a headline or if global cycling
18210 should be done.
18211 If any function in this hook returns t, not other actions like visibility
18212 cycling will be done.")
18214 (defvar org-tab-after-check-for-cycling-hook nil
18215 "Hook for functions to attach themselves to TAB.
18216 See `org-ctrl-c-ctrl-c-hook' for more information.
18217 This hook runs after it has been established that not table field motion and
18218 not visibility should be done because of current context. This is probably
18219 the place where a package like yasnippets can hook in.")
18221 (defvar org-tab-before-tab-emulation-hook nil
18222 "Hook for functions to attach themselves to TAB.
18223 See `org-ctrl-c-ctrl-c-hook' for more information.
18224 This hook runs after every other options for TAB have been exhausted, but
18225 before indentation and \t insertion takes place.")
18227 (defvar org-metaleft-hook nil
18228 "Hook for functions attaching themselves to `M-left'.
18229 See `org-ctrl-c-ctrl-c-hook' for more information.")
18230 (defvar org-metaright-hook nil
18231 "Hook for functions attaching themselves to `M-right'.
18232 See `org-ctrl-c-ctrl-c-hook' for more information.")
18233 (defvar org-metaup-hook nil
18234 "Hook for functions attaching themselves to `M-up'.
18235 See `org-ctrl-c-ctrl-c-hook' for more information.")
18236 (defvar org-metadown-hook nil
18237 "Hook for functions attaching themselves to `M-down'.
18238 See `org-ctrl-c-ctrl-c-hook' for more information.")
18239 (defvar org-shiftmetaleft-hook nil
18240 "Hook for functions attaching themselves to `M-S-left'.
18241 See `org-ctrl-c-ctrl-c-hook' for more information.")
18242 (defvar org-shiftmetaright-hook nil
18243 "Hook for functions attaching themselves to `M-S-right'.
18244 See `org-ctrl-c-ctrl-c-hook' for more information.")
18245 (defvar org-shiftmetaup-hook nil
18246 "Hook for functions attaching themselves to `M-S-up'.
18247 See `org-ctrl-c-ctrl-c-hook' for more information.")
18248 (defvar org-shiftmetadown-hook nil
18249 "Hook for functions attaching themselves to `M-S-down'.
18250 See `org-ctrl-c-ctrl-c-hook' for more information.")
18251 (defvar org-metareturn-hook nil
18252 "Hook for functions attaching themselves to `M-RET'.
18253 See `org-ctrl-c-ctrl-c-hook' for more information.")
18254 (defvar org-shiftup-hook nil
18255 "Hook for functions attaching themselves to `S-up'.
18256 See `org-ctrl-c-ctrl-c-hook' for more information.")
18257 (defvar org-shiftup-final-hook nil
18258 "Hook for functions attaching themselves to `S-up'.
18259 This one runs after all other options except shift-select have been excluded.
18260 See `org-ctrl-c-ctrl-c-hook' for more information.")
18261 (defvar org-shiftdown-hook nil
18262 "Hook for functions attaching themselves to `S-down'.
18263 See `org-ctrl-c-ctrl-c-hook' for more information.")
18264 (defvar org-shiftdown-final-hook nil
18265 "Hook for functions attaching themselves to `S-down'.
18266 This one runs after all other options except shift-select have been excluded.
18267 See `org-ctrl-c-ctrl-c-hook' for more information.")
18268 (defvar org-shiftleft-hook nil
18269 "Hook for functions attaching themselves to `S-left'.
18270 See `org-ctrl-c-ctrl-c-hook' for more information.")
18271 (defvar org-shiftleft-final-hook nil
18272 "Hook for functions attaching themselves to `S-left'.
18273 This one runs after all other options except shift-select have been excluded.
18274 See `org-ctrl-c-ctrl-c-hook' for more information.")
18275 (defvar org-shiftright-hook nil
18276 "Hook for functions attaching themselves to `S-right'.
18277 See `org-ctrl-c-ctrl-c-hook' for more information.")
18278 (defvar org-shiftright-final-hook nil
18279 "Hook for functions attaching themselves to `S-right'.
18280 This one runs after all other options except shift-select have been excluded.
18281 See `org-ctrl-c-ctrl-c-hook' for more information.")
18283 (defun org-modifier-cursor-error ()
18284 "Throw an error, a modified cursor command was applied in wrong context."
18285 (error "This command is active in special context like tables, headlines or items"))
18287 (defun org-shiftselect-error ()
18288 "Throw an error because Shift-Cursor command was applied in wrong context."
18289 (if (and (boundp 'shift-select-mode) shift-select-mode)
18290 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18291 (error "This command works only in special context like headlines or timestamps")))
18293 (defun org-call-for-shift-select (cmd)
18294 (let ((this-command-keys-shift-translated t))
18295 (call-interactively cmd)))
18297 (defun org-shifttab (&optional arg)
18298 "Global visibility cycling or move to previous table field.
18299 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18300 on context.
18301 See the individual commands for more information."
18302 (interactive "P")
18303 (cond
18304 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18305 ((integerp arg)
18306 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18307 (message "Content view to level: %d" arg)
18308 (org-content (prefix-numeric-value arg2))
18309 (setq org-cycle-global-status 'overview)))
18310 (t (call-interactively 'org-global-cycle))))
18312 (defun org-shiftmetaleft ()
18313 "Promote subtree or delete table column.
18314 Calls `org-promote-subtree', `org-outdent-item-tree', or
18315 `org-table-delete-column', depending on context. See the
18316 individual commands for more information."
18317 (interactive)
18318 (cond
18319 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18320 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18321 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18322 ((if (not (org-region-active-p)) (org-at-item-p)
18323 (save-excursion (goto-char (region-beginning))
18324 (org-at-item-p)))
18325 (call-interactively 'org-outdent-item-tree))
18326 (t (org-modifier-cursor-error))))
18328 (defun org-shiftmetaright ()
18329 "Demote subtree or insert table column.
18330 Calls `org-demote-subtree', `org-indent-item-tree', or
18331 `org-table-insert-column', depending on context. See the
18332 individual commands for more information."
18333 (interactive)
18334 (cond
18335 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18336 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18337 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18338 ((if (not (org-region-active-p)) (org-at-item-p)
18339 (save-excursion (goto-char (region-beginning))
18340 (org-at-item-p)))
18341 (call-interactively 'org-indent-item-tree))
18342 (t (org-modifier-cursor-error))))
18344 (defun org-shiftmetaup (&optional arg)
18345 "Move subtree up or kill table row.
18346 Calls `org-move-subtree-up' or `org-table-kill-row' or
18347 `org-move-item-up' depending on context. See the individual commands
18348 for more information."
18349 (interactive "P")
18350 (cond
18351 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18352 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18353 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18354 ((org-at-item-p) (call-interactively 'org-move-item-up))
18355 (t (org-modifier-cursor-error))))
18357 (defun org-shiftmetadown (&optional arg)
18358 "Move subtree down or insert table row.
18359 Calls `org-move-subtree-down' or `org-table-insert-row' or
18360 `org-move-item-down', depending on context. See the individual
18361 commands for more information."
18362 (interactive "P")
18363 (cond
18364 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18365 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18366 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18367 ((org-at-item-p) (call-interactively 'org-move-item-down))
18368 (t (org-modifier-cursor-error))))
18370 (defsubst org-hidden-tree-error ()
18371 (error
18372 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18374 (defun org-metaleft (&optional arg)
18375 "Promote heading or move table column to left.
18376 Calls `org-do-promote' or `org-table-move-column', depending on context.
18377 With no specific context, calls the Emacs default `backward-word'.
18378 See the individual commands for more information."
18379 (interactive "P")
18380 (cond
18381 ((run-hook-with-args-until-success 'org-metaleft-hook))
18382 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18383 ((org-with-limited-levels
18384 (or (org-at-heading-p)
18385 (and (org-region-active-p)
18386 (save-excursion
18387 (goto-char (region-beginning))
18388 (org-at-heading-p)))))
18389 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18390 (call-interactively 'org-do-promote))
18391 ;; At an inline task.
18392 ((org-at-heading-p)
18393 (call-interactively 'org-inlinetask-promote))
18394 ((or (org-at-item-p)
18395 (and (org-region-active-p)
18396 (save-excursion
18397 (goto-char (region-beginning))
18398 (org-at-item-p))))
18399 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18400 (call-interactively 'org-outdent-item))
18401 (t (call-interactively 'backward-word))))
18403 (defun org-metaright (&optional arg)
18404 "Demote a subtree, a list item or move table column to right.
18405 In front of a drawer or a block keyword, indent it correctly.
18406 With no specific context, calls the Emacs default `forward-word'.
18407 See the individual commands for more information."
18408 (interactive "P")
18409 (cond
18410 ((run-hook-with-args-until-success 'org-metaright-hook))
18411 ((org-at-table-p) (call-interactively 'org-table-move-column))
18412 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18413 ((org-at-block-p) (call-interactively 'org-indent-block))
18414 ((org-with-limited-levels
18415 (or (org-at-heading-p)
18416 (and (org-region-active-p)
18417 (save-excursion
18418 (goto-char (region-beginning))
18419 (org-at-heading-p)))))
18420 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18421 (call-interactively 'org-do-demote))
18422 ;; At an inline task.
18423 ((org-at-heading-p)
18424 (call-interactively 'org-inlinetask-demote))
18425 ((or (org-at-item-p)
18426 (and (org-region-active-p)
18427 (save-excursion
18428 (goto-char (region-beginning))
18429 (org-at-item-p))))
18430 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18431 (call-interactively 'org-indent-item))
18432 (t (call-interactively 'forward-word))))
18434 (defun org-check-for-hidden (what)
18435 "Check if there are hidden headlines/items in the current visual line.
18436 WHAT can be either `headlines' or `items'. If the current line is
18437 an outline or item heading and it has a folded subtree below it,
18438 this function returns t, nil otherwise."
18439 (let ((re (cond
18440 ((eq what 'headlines) org-outline-regexp-bol)
18441 ((eq what 'items) (org-item-beginning-re))
18442 (t (error "This should not happen"))))
18443 beg end)
18444 (save-excursion
18445 (catch 'exit
18446 (unless (org-region-active-p)
18447 (setq beg (point-at-bol))
18448 (beginning-of-line 2)
18449 (while (and (not (eobp)) ;; this is like `next-line'
18450 (get-char-property (1- (point)) 'invisible))
18451 (beginning-of-line 2))
18452 (setq end (point))
18453 (goto-char beg)
18454 (goto-char (point-at-eol))
18455 (setq end (max end (point)))
18456 (while (re-search-forward re end t)
18457 (if (get-char-property (match-beginning 0) 'invisible)
18458 (throw 'exit t))))
18459 nil))))
18461 (defun org-metaup (&optional arg)
18462 "Move subtree up or move table row up.
18463 Calls `org-move-subtree-up' or `org-table-move-row' or
18464 `org-move-item-up', depending on context. See the individual commands
18465 for more information."
18466 (interactive "P")
18467 (cond
18468 ((run-hook-with-args-until-success 'org-metaup-hook))
18469 ((org-region-active-p)
18470 (let* ((a (min (region-beginning) (region-end)))
18471 (b (1- (max (region-beginning) (region-end))))
18472 (c (save-excursion (goto-char a)
18473 (move-beginning-of-line 0)))
18474 (d (save-excursion (goto-char a)
18475 (move-end-of-line 0) (point))))
18476 (transpose-regions a b c d)
18477 (goto-char c)))
18478 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18479 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18480 ((org-at-item-p) (call-interactively 'org-move-item-up))
18481 (t (transpose-lines 1) (beginning-of-line -1))))
18483 (defun org-metadown (&optional arg)
18484 "Move subtree down or move table row down.
18485 Calls `org-move-subtree-down' or `org-table-move-row' or
18486 `org-move-item-down', depending on context. See the individual
18487 commands for more information."
18488 (interactive "P")
18489 (cond
18490 ((run-hook-with-args-until-success 'org-metadown-hook))
18491 ((org-region-active-p)
18492 (let* ((a (min (region-beginning) (region-end)))
18493 (b (max (region-beginning) (region-end)))
18494 (c (save-excursion (goto-char b)
18495 (move-beginning-of-line 1)))
18496 (d (save-excursion (goto-char b)
18497 (move-end-of-line 1) (1+ (point)))))
18498 (transpose-regions a b c d)
18499 (goto-char d)))
18500 ((org-at-table-p) (call-interactively 'org-table-move-row))
18501 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18502 ((org-at-item-p) (call-interactively 'org-move-item-down))
18503 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18505 (defun org-shiftup (&optional arg)
18506 "Increase item in timestamp or increase priority of current headline.
18507 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18508 depending on context. See the individual commands for more information."
18509 (interactive "P")
18510 (cond
18511 ((run-hook-with-args-until-success 'org-shiftup-hook))
18512 ((and org-support-shift-select (org-region-active-p))
18513 (org-call-for-shift-select 'previous-line))
18514 ((org-at-timestamp-p t)
18515 (call-interactively (if org-edit-timestamp-down-means-later
18516 'org-timestamp-down 'org-timestamp-up)))
18517 ((and (not (eq org-support-shift-select 'always))
18518 org-enable-priority-commands
18519 (org-at-heading-p))
18520 (call-interactively 'org-priority-up))
18521 ((and (not org-support-shift-select) (org-at-item-p))
18522 (call-interactively 'org-previous-item))
18523 ((org-clocktable-try-shift 'up arg))
18524 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18525 (org-support-shift-select
18526 (org-call-for-shift-select 'previous-line))
18527 (t (org-shiftselect-error))))
18529 (defun org-shiftdown (&optional arg)
18530 "Decrease item in timestamp or decrease priority of current headline.
18531 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18532 depending on context. See the individual commands for more information."
18533 (interactive "P")
18534 (cond
18535 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18536 ((and org-support-shift-select (org-region-active-p))
18537 (org-call-for-shift-select 'next-line))
18538 ((org-at-timestamp-p t)
18539 (call-interactively (if org-edit-timestamp-down-means-later
18540 'org-timestamp-up 'org-timestamp-down)))
18541 ((and (not (eq org-support-shift-select 'always))
18542 org-enable-priority-commands
18543 (org-at-heading-p))
18544 (call-interactively 'org-priority-down))
18545 ((and (not org-support-shift-select) (org-at-item-p))
18546 (call-interactively 'org-next-item))
18547 ((org-clocktable-try-shift 'down arg))
18548 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18549 (org-support-shift-select
18550 (org-call-for-shift-select 'next-line))
18551 (t (org-shiftselect-error))))
18553 (defun org-shiftright (&optional arg)
18554 "Cycle the thing at point or in the current line, depending on context.
18555 Depending on context, this does one of the following:
18557 - switch a timestamp at point one day into the future
18558 - on a headline, switch to the next TODO keyword.
18559 - on an item, switch entire list to the next bullet type
18560 - on a property line, switch to the next allowed value
18561 - on a clocktable definition line, move time block into the future"
18562 (interactive "P")
18563 (cond
18564 ((run-hook-with-args-until-success 'org-shiftright-hook))
18565 ((and org-support-shift-select (org-region-active-p))
18566 (org-call-for-shift-select 'forward-char))
18567 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18568 ((and (not (eq org-support-shift-select 'always))
18569 (org-at-heading-p))
18570 (let ((org-inhibit-logging
18571 (not org-treat-S-cursor-todo-selection-as-state-change))
18572 (org-inhibit-blocking
18573 (not org-treat-S-cursor-todo-selection-as-state-change)))
18574 (org-call-with-arg 'org-todo 'right)))
18575 ((or (and org-support-shift-select
18576 (not (eq org-support-shift-select 'always))
18577 (org-at-item-bullet-p))
18578 (and (not org-support-shift-select) (org-at-item-p)))
18579 (org-call-with-arg 'org-cycle-list-bullet nil))
18580 ((and (not (eq org-support-shift-select 'always))
18581 (org-at-property-p))
18582 (call-interactively 'org-property-next-allowed-value))
18583 ((org-clocktable-try-shift 'right arg))
18584 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18585 (org-support-shift-select
18586 (org-call-for-shift-select 'forward-char))
18587 (t (org-shiftselect-error))))
18589 (defun org-shiftleft (&optional arg)
18590 "Cycle the thing at point or in the current line, depending on context.
18591 Depending on context, this does one of the following:
18593 - switch a timestamp at point one day into the past
18594 - on a headline, switch to the previous TODO keyword.
18595 - on an item, switch entire list to the previous bullet type
18596 - on a property line, switch to the previous allowed value
18597 - on a clocktable definition line, move time block into the past"
18598 (interactive "P")
18599 (cond
18600 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18601 ((and org-support-shift-select (org-region-active-p))
18602 (org-call-for-shift-select 'backward-char))
18603 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18604 ((and (not (eq org-support-shift-select 'always))
18605 (org-at-heading-p))
18606 (let ((org-inhibit-logging
18607 (not org-treat-S-cursor-todo-selection-as-state-change))
18608 (org-inhibit-blocking
18609 (not org-treat-S-cursor-todo-selection-as-state-change)))
18610 (org-call-with-arg 'org-todo 'left)))
18611 ((or (and org-support-shift-select
18612 (not (eq org-support-shift-select 'always))
18613 (org-at-item-bullet-p))
18614 (and (not org-support-shift-select) (org-at-item-p)))
18615 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18616 ((and (not (eq org-support-shift-select 'always))
18617 (org-at-property-p))
18618 (call-interactively 'org-property-previous-allowed-value))
18619 ((org-clocktable-try-shift 'left arg))
18620 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18621 (org-support-shift-select
18622 (org-call-for-shift-select 'backward-char))
18623 (t (org-shiftselect-error))))
18625 (defun org-shiftcontrolright ()
18626 "Switch to next TODO set."
18627 (interactive)
18628 (cond
18629 ((and org-support-shift-select (org-region-active-p))
18630 (org-call-for-shift-select 'forward-word))
18631 ((and (not (eq org-support-shift-select 'always))
18632 (org-at-heading-p))
18633 (org-call-with-arg 'org-todo 'nextset))
18634 (org-support-shift-select
18635 (org-call-for-shift-select 'forward-word))
18636 (t (org-shiftselect-error))))
18638 (defun org-shiftcontrolleft ()
18639 "Switch to previous TODO set."
18640 (interactive)
18641 (cond
18642 ((and org-support-shift-select (org-region-active-p))
18643 (org-call-for-shift-select 'backward-word))
18644 ((and (not (eq org-support-shift-select 'always))
18645 (org-at-heading-p))
18646 (org-call-with-arg 'org-todo 'previousset))
18647 (org-support-shift-select
18648 (org-call-for-shift-select 'backward-word))
18649 (t (org-shiftselect-error))))
18651 (defun org-shiftcontrolup ()
18652 "Change timestamps synchronously up in CLOCK log lines."
18653 (interactive)
18654 (cond ((and (not org-support-shift-select)
18655 (org-at-clock-log-p)
18656 (org-at-timestamp-p t))
18657 (org-clock-timestamps-up))
18658 (t (org-shiftselect-error))))
18660 (defun org-shiftcontroldown ()
18661 "Change timestamps synchronously down in CLOCK log lines."
18662 (interactive)
18663 (cond ((and (not org-support-shift-select)
18664 (org-at-clock-log-p)
18665 (org-at-timestamp-p t))
18666 (org-clock-timestamps-down))
18667 (t (org-shiftselect-error))))
18669 (defun org-ctrl-c-ret ()
18670 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18671 (interactive)
18672 (cond
18673 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18674 (t (call-interactively 'org-insert-heading))))
18676 (defun org-find-visible ()
18677 (let ((s (point)))
18678 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18679 (get-char-property s 'invisible)))
18681 (defun org-find-invisible ()
18682 (let ((s (point)))
18683 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18684 (not (get-char-property s 'invisible))))
18687 (defun org-copy-visible (beg end)
18688 "Copy the visible parts of the region."
18689 (interactive "r")
18690 (let (snippets s)
18691 (save-excursion
18692 (save-restriction
18693 (narrow-to-region beg end)
18694 (setq s (goto-char (point-min)))
18695 (while (not (= (point) (point-max)))
18696 (goto-char (org-find-invisible))
18697 (push (buffer-substring s (point)) snippets)
18698 (setq s (goto-char (org-find-visible))))))
18699 (kill-new (apply 'concat (nreverse snippets)))))
18701 (defun org-copy-special ()
18702 "Copy region in table or copy current subtree.
18703 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18704 See the individual commands for more information."
18705 (interactive)
18706 (call-interactively
18707 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18709 (defun org-cut-special ()
18710 "Cut region in table or cut current subtree.
18711 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18712 See the individual commands for more information."
18713 (interactive)
18714 (call-interactively
18715 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18717 (defun org-paste-special (arg)
18718 "Paste rectangular region into table, or past subtree relative to level.
18719 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18720 See the individual commands for more information."
18721 (interactive "P")
18722 (if (org-at-table-p)
18723 (org-table-paste-rectangle)
18724 (org-paste-subtree arg)))
18726 (defun org-edit-special (&optional arg)
18727 "Call a special editor for the stuff at point.
18728 When at a table, call the formula editor with `org-table-edit-formulas'.
18729 When at the first line of an src example, call `org-edit-src-code'.
18730 When in an #+include line, visit the include file. Otherwise call
18731 `ffap' to visit the file at point."
18732 (interactive)
18733 ;; possibly prep session before editing source
18734 (when arg
18735 (let* ((info (org-babel-get-src-block-info))
18736 (lang (nth 0 info))
18737 (params (nth 2 info))
18738 (session (cdr (assoc :session params))))
18739 (when (and info session) ;; we are in a source-code block with a session
18740 (funcall
18741 (intern (concat "org-babel-prep-session:" lang)) session params))))
18742 (cond ;; proceed with `org-edit-special'
18743 ((save-excursion
18744 (beginning-of-line 1)
18745 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18746 (find-file (org-trim (match-string 1))))
18747 ((org-edit-src-code))
18748 ((org-edit-fixed-width-region))
18749 ((org-at-table.el-p)
18750 (org-edit-src-code))
18751 ((or (org-at-table-p)
18752 (save-excursion
18753 (beginning-of-line 1)
18754 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18755 (call-interactively 'org-table-edit-formulas))
18756 (t (call-interactively 'ffap))))
18758 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18759 (defun org-ctrl-c-ctrl-c (&optional arg)
18760 "Set tags in headline, or update according to changed information at point.
18762 This command does many different things, depending on context:
18764 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18765 this is what we do.
18767 - If the cursor is on a statistics cookie, update it.
18769 - If the cursor is in a headline, prompt for tags and insert them
18770 into the current line, aligned to `org-tags-column'. When called
18771 with prefix arg, realign all tags in the current buffer.
18773 - If the cursor is in one of the special #+KEYWORD lines, this
18774 triggers scanning the buffer for these lines and updating the
18775 information.
18777 - If the cursor is inside a table, realign the table. This command
18778 works even if the automatic table editor has been turned off.
18780 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18781 the entire table.
18783 - If the cursor is at a footnote reference or definition, jump to
18784 the corresponding definition or references, respectively.
18786 - If the cursor is a the beginning of a dynamic block, update it.
18788 - If the current buffer is a capture buffer, close note and file it.
18790 - If the cursor is on a <<<target>>>, update radio targets and
18791 corresponding links in this buffer.
18793 - If the cursor is on a numbered item in a plain list, renumber the
18794 ordered list.
18796 - If the cursor is on a checkbox, toggle it.
18798 - If the cursor is on a code block, evaluate it. The variable
18799 `org-confirm-babel-evaluate' can be used to control prompting
18800 before code block evaluation, by default every code block
18801 evaluation requires confirmation. Code block evaluation can be
18802 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18803 (interactive "P")
18804 (let ((org-enable-table-editor t))
18805 (cond
18806 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18807 org-occur-highlights
18808 org-latex-fragment-image-overlays)
18809 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18810 (org-remove-occur-highlights)
18811 (org-remove-latex-fragment-image-overlays)
18812 (message "Temporary highlights/overlays removed from current buffer"))
18813 ((and (local-variable-p 'org-finish-function (current-buffer))
18814 (fboundp org-finish-function))
18815 (funcall org-finish-function))
18816 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18817 ((org-in-regexp org-ts-regexp-both)
18818 (org-timestamp-change 0 'day))
18819 ((or (looking-at org-property-start-re)
18820 (org-at-property-p))
18821 (call-interactively 'org-property-action))
18822 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18823 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18824 (or (org-at-heading-p) (org-at-item-p)))
18825 (call-interactively 'org-update-statistics-cookies))
18826 ((org-at-heading-p) (call-interactively 'org-set-tags))
18827 ((org-at-table.el-p)
18828 (message "Use C-c ' to edit table.el tables"))
18829 ((org-at-table-p)
18830 (org-table-maybe-eval-formula)
18831 (if arg
18832 (call-interactively 'org-table-recalculate)
18833 (org-table-maybe-recalculate-line))
18834 (call-interactively 'org-table-align)
18835 (orgtbl-send-table 'maybe))
18836 ((or (org-footnote-at-reference-p)
18837 (org-footnote-at-definition-p))
18838 (call-interactively 'org-footnote-action))
18839 ((org-at-item-checkbox-p)
18840 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18841 ;; list only if at top item.
18842 (let* ((cbox (match-string 1))
18843 (struct (org-list-struct))
18844 (old-struct (copy-tree struct))
18845 (parents (org-list-parents-alist struct))
18846 (orderedp (org-entry-get nil "ORDERED"))
18847 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18848 block-item)
18849 ;; Use a light version of `org-toggle-checkbox' to avoid
18850 ;; computing list structure twice.
18851 (let ((new-box (cond
18852 ((equal arg '(16)) "[-]")
18853 ((equal arg '(4)) nil)
18854 ((equal "[X]" cbox) "[ ]")
18855 (t "[X]"))))
18856 (if (and firstp arg)
18857 ;; If at first item of sub-list, remove check-box from
18858 ;; every item at the same level.
18859 (mapc
18860 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18861 (org-list-get-all-items
18862 (point-at-bol) struct (org-list-prevs-alist struct)))
18863 (org-list-set-checkbox (point-at-bol) struct new-box)))
18864 ;; Replicate `org-list-write-struct', while grabbing a return
18865 ;; value from `org-list-struct-fix-box'.
18866 (org-list-struct-fix-ind struct parents 2)
18867 (org-list-struct-fix-item-end struct)
18868 (let ((prevs (org-list-prevs-alist struct)))
18869 (org-list-struct-fix-bul struct prevs)
18870 (org-list-struct-fix-ind struct parents)
18871 (setq block-item
18872 (org-list-struct-fix-box struct parents prevs orderedp)))
18873 (org-list-struct-apply-struct struct old-struct)
18874 (org-update-checkbox-count-maybe)
18875 (when block-item
18876 (message
18877 "Checkboxes were removed due to unchecked box at line %d"
18878 (org-current-line block-item)))
18879 (when firstp (org-list-send-list 'maybe))))
18880 ((org-at-item-p)
18881 ;; Cursor at an item: repair list. Do checkbox related actions
18882 ;; only if function was called with an argument. Send list only
18883 ;; if at top item.
18884 (let* ((struct (org-list-struct))
18885 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18886 old-struct)
18887 (when arg
18888 (setq old-struct (copy-tree struct))
18889 (if firstp
18890 ;; If at first item of sub-list, add check-box to every
18891 ;; item at the same level.
18892 (mapc
18893 (lambda (pos)
18894 (unless (org-list-get-checkbox pos struct)
18895 (org-list-set-checkbox pos struct "[ ]")))
18896 (org-list-get-all-items
18897 (point-at-bol) struct (org-list-prevs-alist struct)))
18898 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18899 (org-list-write-struct
18900 struct (org-list-parents-alist struct) old-struct)
18901 (when arg (org-update-checkbox-count-maybe))
18902 (when firstp (org-list-send-list 'maybe))))
18903 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18904 ;; Dynamic block
18905 (beginning-of-line 1)
18906 (save-excursion (org-update-dblock)))
18907 ((save-excursion
18908 (let ((case-fold-search t))
18909 (beginning-of-line 1)
18910 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
18911 (cond
18912 ((or (equal (match-string 1) "TBLFM")
18913 (equal (match-string 1) "tblfm"))
18914 ;; Recalculate the table before this line
18915 (save-excursion
18916 (beginning-of-line 1)
18917 (skip-chars-backward " \r\n\t")
18918 (if (org-at-table-p)
18919 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18921 (let ((org-inhibit-startup-visibility-stuff t)
18922 (org-startup-align-all-tables nil))
18923 (when (boundp 'org-table-coordinate-overlays)
18924 (mapc 'delete-overlay org-table-coordinate-overlays)
18925 (setq org-table-coordinate-overlays nil))
18926 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18927 (message "Local setup has been refreshed"))))
18928 ((org-clock-update-time-maybe))
18930 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18931 (error "C-c C-c can do nothing useful at this location"))))))
18933 (defun org-mode-restart ()
18934 "Restart Org-mode, to scan again for special lines.
18935 Also updates the keyword regular expressions."
18936 (interactive)
18937 (org-mode)
18938 (message "Org-mode restarted"))
18940 (defun org-kill-note-or-show-branches ()
18941 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18942 (interactive)
18943 (if (not org-finish-function)
18944 (progn
18945 (hide-subtree)
18946 (call-interactively 'show-branches))
18947 (let ((org-note-abort t))
18948 (funcall org-finish-function))))
18950 (defun org-return (&optional indent)
18951 "Goto next table row or insert a newline.
18952 Calls `org-table-next-row' or `newline', depending on context.
18953 See the individual commands for more information."
18954 (interactive)
18955 (let (org-ts-what)
18956 (cond
18957 ((or (bobp) (org-in-src-block-p))
18958 (if indent (newline-and-indent) (newline)))
18959 ((org-at-table-p)
18960 (org-table-justify-field-maybe)
18961 (call-interactively 'org-table-next-row))
18962 ;; when `newline-and-indent' is called within a list, make sure
18963 ;; text moved stays inside the item.
18964 ((and (org-in-item-p) indent)
18965 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18966 (progn
18967 (save-match-data (newline))
18968 (org-indent-line-to (length (match-string 0))))
18969 (let ((ind (org-get-indentation)))
18970 (newline)
18971 (if (org-looking-back org-list-end-re)
18972 (org-indent-line)
18973 (org-indent-line-to ind)))))
18974 ((and org-return-follows-link
18975 (org-at-timestamp-p t)
18976 (not (eq org-ts-what 'after)))
18977 (org-follow-timestamp-link))
18978 ((and org-return-follows-link
18979 (let ((tprop (get-text-property (point) 'face)))
18980 (or (eq tprop 'org-link)
18981 (and (listp tprop) (memq 'org-link tprop)))))
18982 (call-interactively 'org-open-at-point))
18983 ((and (org-at-heading-p)
18984 (looking-at
18985 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18986 (org-show-entry)
18987 (end-of-line 1)
18988 (newline))
18989 (t (if indent (newline-and-indent) (newline))))))
18991 (defun org-return-indent ()
18992 "Goto next table row or insert a newline and indent.
18993 Calls `org-table-next-row' or `newline-and-indent', depending on
18994 context. See the individual commands for more information."
18995 (interactive)
18996 (org-return t))
18998 (defun org-ctrl-c-star ()
18999 "Compute table, or change heading status of lines.
19000 Calls `org-table-recalculate' or `org-toggle-heading',
19001 depending on context."
19002 (interactive)
19003 (cond
19004 ((org-at-table-p)
19005 (call-interactively 'org-table-recalculate))
19007 ;; Convert all lines in region to list items
19008 (call-interactively 'org-toggle-heading))))
19010 (defun org-ctrl-c-minus ()
19011 "Insert separator line in table or modify bullet status of line.
19012 Also turns a plain line or a region of lines into list items.
19013 Calls `org-table-insert-hline', `org-toggle-item', or
19014 `org-cycle-list-bullet', depending on context."
19015 (interactive)
19016 (cond
19017 ((org-at-table-p)
19018 (call-interactively 'org-table-insert-hline))
19019 ((org-region-active-p)
19020 (call-interactively 'org-toggle-item))
19021 ((org-in-item-p)
19022 (call-interactively 'org-cycle-list-bullet))
19024 (call-interactively 'org-toggle-item))))
19026 (defun org-toggle-item (arg)
19027 "Convert headings or normal lines to items, items to normal lines.
19028 If there is no active region, only the current line is considered.
19030 If the first non blank line in the region is an headline, convert
19031 all headlines to items, shifting text accordingly.
19033 If it is an item, convert all items to normal lines.
19035 If it is normal text, change region into an item. With a prefix
19036 argument ARG, change each line in region into an item."
19037 (interactive "P")
19038 (let ((shift-text
19039 (function
19040 ;; Shift text in current section to IND, from point to END.
19041 ;; The function leaves point to END line.
19042 (lambda (ind end)
19043 (let ((min-i 1000) (end (copy-marker end)))
19044 ;; First determine the minimum indentation (MIN-I) of
19045 ;; the text.
19046 (save-excursion
19047 (catch 'exit
19048 (while (< (point) end)
19049 (let ((i (org-get-indentation)))
19050 (cond
19051 ;; Skip blank lines and inline tasks.
19052 ((looking-at "^[ \t]*$"))
19053 ((looking-at org-outline-regexp-bol))
19054 ;; We can't find less than 0 indentation.
19055 ((zerop i) (throw 'exit (setq min-i 0)))
19056 ((< i min-i) (setq min-i i))))
19057 (forward-line))))
19058 ;; Then indent each line so that a line indented to
19059 ;; MIN-I becomes indented to IND. Ignore blank lines
19060 ;; and inline tasks in the process.
19061 (let ((delta (- ind min-i)))
19062 (while (< (point) end)
19063 (unless (or (looking-at "^[ \t]*$")
19064 (looking-at org-outline-regexp-bol))
19065 (org-indent-line-to (+ (org-get-indentation) delta)))
19066 (forward-line)))))))
19067 (skip-blanks
19068 (function
19069 ;; Return beginning of first non-blank line, starting from
19070 ;; line at POS.
19071 (lambda (pos)
19072 (save-excursion
19073 (goto-char pos)
19074 (skip-chars-forward " \r\t\n")
19075 (point-at-bol)))))
19076 beg end)
19077 ;; Determine boundaries of changes.
19078 (if (org-region-active-p)
19079 (setq beg (funcall skip-blanks (region-beginning))
19080 end (copy-marker (region-end)))
19081 (setq beg (funcall skip-blanks (point-at-bol))
19082 end (copy-marker (point-at-eol))))
19083 ;; Depending on the starting line, choose an action on the text
19084 ;; between BEG and END.
19085 (org-with-limited-levels
19086 (save-excursion
19087 (goto-char beg)
19088 (cond
19089 ;; Case 1. Start at an item: de-itemize. Note that it only
19090 ;; happens when a region is active: `org-ctrl-c-minus'
19091 ;; would call `org-cycle-list-bullet' otherwise.
19092 ((org-at-item-p)
19093 (while (< (point) end)
19094 (when (org-at-item-p)
19095 (skip-chars-forward " \t")
19096 (delete-region (point) (match-end 0)))
19097 (forward-line)))
19098 ;; Case 2. Start at an heading: convert to items.
19099 ((org-at-heading-p)
19100 (let* ((bul (org-list-bullet-string "-"))
19101 (bul-len (length bul))
19102 ;; Indentation of the first heading. It should be
19103 ;; relative to the indentation of its parent, if any.
19104 (start-ind (save-excursion
19105 (cond
19106 ((not org-adapt-indentation) 0)
19107 ((not (outline-previous-heading)) 0)
19108 (t (length (match-string 0))))))
19109 ;; Level of first heading. Further headings will be
19110 ;; compared to it to determine hierarchy in the list.
19111 (ref-level (org-reduced-level (org-outline-level))))
19112 (while (< (point) end)
19113 (let* ((level (org-reduced-level (org-outline-level)))
19114 (delta (max 0 (- level ref-level))))
19115 ;; If current headline is less indented than the first
19116 ;; one, set it as reference, in order to preserve
19117 ;; subtrees.
19118 (when (< level ref-level) (setq ref-level level))
19119 (replace-match bul t t)
19120 (org-indent-line-to (+ start-ind (* delta bul-len)))
19121 ;; Ensure all text down to END (or SECTION-END) belongs
19122 ;; to the newly created item.
19123 (let ((section-end (save-excursion
19124 (or (outline-next-heading) (point)))))
19125 (forward-line)
19126 (funcall shift-text
19127 (+ start-ind (* (1+ delta) bul-len))
19128 (min end section-end)))))))
19129 ;; Case 3. Normal line with ARG: turn each non-item line into
19130 ;; an item.
19131 (arg
19132 (while (< (point) end)
19133 (unless (or (org-at-heading-p) (org-at-item-p))
19134 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19135 (replace-match
19136 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19137 (forward-line)))
19138 ;; Case 4. Normal line without ARG: make the first line of
19139 ;; region an item, and shift indentation of others
19140 ;; lines to set them as item's body.
19141 (t (let* ((bul (org-list-bullet-string "-"))
19142 (bul-len (length bul))
19143 (ref-ind (org-get-indentation)))
19144 (skip-chars-forward " \t")
19145 (insert bul)
19146 (forward-line)
19147 (while (< (point) end)
19148 ;; Ensure that lines less indented than first one
19149 ;; still get included in item body.
19150 (funcall shift-text
19151 (+ ref-ind bul-len)
19152 (min end (save-excursion (or (outline-next-heading)
19153 (point)))))
19154 (forward-line)))))))))
19156 (defun org-toggle-heading (&optional nstars)
19157 "Convert headings to normal text, or items or text to headings.
19158 If there is no active region, only the current line is considered.
19160 With a \\[universal-argument] prefix, convert the whole list at
19161 point into heading.
19163 In a region:
19165 - If the first non blank line is an headline, remove the stars
19166 from all headlines in the region.
19168 - If it is a normal line turn each and every normal line (i.e. not an
19169 heading or an item) in the region into a heading.
19171 - If it is a plain list item, turn all plain list items into headings.
19173 When converting a line into a heading, the number of stars is chosen
19174 such that the lines become children of the current entry. However,
19175 when a prefix argument is given, its value determines the number of
19176 stars to add."
19177 (interactive "P")
19178 (let ((skip-blanks
19179 (function
19180 ;; Return beginning of first non-blank line, starting from
19181 ;; line at POS.
19182 (lambda (pos)
19183 (save-excursion
19184 (goto-char pos)
19185 (while (org-at-comment-p) (forward-line))
19186 (skip-chars-forward " \r\t\n")
19187 (point-at-bol)))))
19188 beg end toggled)
19189 ;; Determine boundaries of changes. If a universal prefix has
19190 ;; been given, put the list in a region. If region ends at a bol,
19191 ;; do not consider the last line to be in the region.
19193 (when (and current-prefix-arg (org-at-item-p))
19194 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19195 (org-mark-list))
19197 (if (org-region-active-p)
19198 (setq beg (funcall skip-blanks (region-beginning))
19199 end (copy-marker (save-excursion
19200 (goto-char (region-end))
19201 (if (bolp) (point) (point-at-eol)))))
19202 (setq beg (funcall skip-blanks (point-at-bol))
19203 end (copy-marker (point-at-eol))))
19204 ;; Ensure inline tasks don't count as headings.
19205 (org-with-limited-levels
19206 (save-excursion
19207 (goto-char beg)
19208 (cond
19209 ;; Case 1. Started at an heading: de-star headings.
19210 ((org-at-heading-p)
19211 (while (< (point) end)
19212 (when (org-at-heading-p t)
19213 (looking-at org-outline-regexp) (replace-match "")
19214 (setq toggled t))
19215 (forward-line)))
19216 ;; Case 2. Started at an item: change items into headlines.
19217 ;; One star will be added by `org-list-to-subtree'.
19218 ((org-at-item-p)
19219 (let* ((stars (make-string
19220 (if nstars
19221 ;; subtract the star that will be added again by
19222 ;; `org-list-to-subtree'
19223 (1- (prefix-numeric-value current-prefix-arg))
19224 (or (org-current-level) 0))
19225 ?*))
19226 (add-stars
19227 (cond (nstars "") ; stars from prefix only
19228 ((equal stars "") "") ; before first heading
19229 (org-odd-levels-only "*") ; inside heading, odd
19230 (t "")))) ; inside heading, oddeven
19231 (while (< (point) end)
19232 (when (org-at-item-p)
19233 ;; Pay attention to cases when region ends before list.
19234 (let* ((struct (org-list-struct))
19235 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19236 (save-restriction
19237 (narrow-to-region (point) list-end)
19238 (insert
19239 (org-list-to-subtree
19240 (org-list-parse-list t)
19241 '(:istart (concat stars add-stars (funcall get-stars depth))
19242 :icount (concat stars add-stars (funcall get-stars depth)))))))
19243 (setq toggled t))
19244 (forward-line))))
19245 ;; Case 3. Started at normal text: make every line an heading,
19246 ;; skipping headlines and items.
19247 (t (let* ((stars (make-string
19248 (if nstars
19249 (prefix-numeric-value current-prefix-arg)
19250 (or (org-current-level) 0))
19251 ?*))
19252 (add-stars
19253 (cond (nstars "") ; stars from prefix only
19254 ((equal stars "") "*") ; before first heading
19255 (org-odd-levels-only "**") ; inside heading, odd
19256 (t "*"))) ; inside heading, oddeven
19257 (rpl (concat stars add-stars " ")))
19258 (while (< (point) end)
19259 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19260 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19261 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19262 (forward-line)))))))
19263 (unless toggled (message "Cannot toggle heading from here"))))
19265 (defun org-meta-return (&optional arg)
19266 "Insert a new heading or wrap a region in a table.
19267 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19268 See the individual commands for more information."
19269 (interactive "P")
19270 (cond
19271 ((run-hook-with-args-until-success 'org-metareturn-hook))
19272 ((or (org-at-drawer-p) (org-at-property-p))
19273 (newline-and-indent))
19274 ((org-at-table-p)
19275 (call-interactively 'org-table-wrap-region))
19276 (t (call-interactively 'org-insert-heading))))
19278 ;;; Menu entries
19280 ;; Define the Org-mode menus
19281 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19282 '("Tbl"
19283 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19284 ["Next Field" org-cycle (org-at-table-p)]
19285 ["Previous Field" org-shifttab (org-at-table-p)]
19286 ["Next Row" org-return (org-at-table-p)]
19287 "--"
19288 ["Blank Field" org-table-blank-field (org-at-table-p)]
19289 ["Edit Field" org-table-edit-field (org-at-table-p)]
19290 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19291 "--"
19292 ("Column"
19293 ["Move Column Left" org-metaleft (org-at-table-p)]
19294 ["Move Column Right" org-metaright (org-at-table-p)]
19295 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19296 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19297 ("Row"
19298 ["Move Row Up" org-metaup (org-at-table-p)]
19299 ["Move Row Down" org-metadown (org-at-table-p)]
19300 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19301 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19302 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19303 "--"
19304 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19305 ("Rectangle"
19306 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19307 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19308 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19309 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19310 "--"
19311 ("Calculate"
19312 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19313 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19314 ["Edit Formulas" org-edit-special (org-at-table-p)]
19315 "--"
19316 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19317 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19318 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19319 "--"
19320 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19321 "--"
19322 ["Sum Column/Rectangle" org-table-sum
19323 (or (org-at-table-p) (org-region-active-p))]
19324 ["Which Column?" org-table-current-column (org-at-table-p)])
19325 ["Debug Formulas"
19326 org-table-toggle-formula-debugger
19327 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19328 ["Show Col/Row Numbers"
19329 org-table-toggle-coordinate-overlays
19330 :style toggle
19331 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19332 "--"
19333 ["Create" org-table-create (and (not (org-at-table-p))
19334 org-enable-table-editor)]
19335 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19336 ["Import from File" org-table-import (not (org-at-table-p))]
19337 ["Export to File" org-table-export (org-at-table-p)]
19338 "--"
19339 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19341 (easy-menu-define org-org-menu org-mode-map "Org menu"
19342 '("Org"
19343 ("Show/Hide"
19344 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19345 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19346 ["Sparse Tree..." org-sparse-tree t]
19347 ["Reveal Context" org-reveal t]
19348 ["Show All" show-all t]
19349 "--"
19350 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19351 "--"
19352 ["New Heading" org-insert-heading t]
19353 ("Navigate Headings"
19354 ["Up" outline-up-heading t]
19355 ["Next" outline-next-visible-heading t]
19356 ["Previous" outline-previous-visible-heading t]
19357 ["Next Same Level" outline-forward-same-level t]
19358 ["Previous Same Level" outline-backward-same-level t]
19359 "--"
19360 ["Jump" org-goto t])
19361 ("Edit Structure"
19362 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19363 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19364 "--"
19365 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19366 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19367 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19368 "--"
19369 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19370 "--"
19371 ["Copy visible text" org-copy-visible t]
19372 "--"
19373 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19374 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19375 ["Demote Heading" org-metaright (not (org-at-table-p))]
19376 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19377 "--"
19378 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19379 "--"
19380 ["Convert to odd levels" org-convert-to-odd-levels t]
19381 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19382 ("Editing"
19383 ["Emphasis..." org-emphasize t]
19384 ["Edit Source Example" org-edit-special t]
19385 "--"
19386 ["Footnote new/jump" org-footnote-action t]
19387 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19388 ("Archive"
19389 ["Archive (default method)" org-archive-subtree-default t]
19390 "--"
19391 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19392 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19393 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19395 "--"
19396 ("Hyperlinks"
19397 ["Store Link (Global)" org-store-link t]
19398 ["Find existing link to here" org-occur-link-in-agenda-files t]
19399 ["Insert Link" org-insert-link t]
19400 ["Follow Link" org-open-at-point t]
19401 "--"
19402 ["Next link" org-next-link t]
19403 ["Previous link" org-previous-link t]
19404 "--"
19405 ["Descriptive Links"
19406 org-toggle-link-display
19407 :style radio
19408 :selected org-descriptive-links
19410 ["Literal Links"
19411 org-toggle-link-display
19412 :style radio
19413 :selected (not org-descriptive-links)])
19414 "--"
19415 ("TODO Lists"
19416 ["TODO/DONE/-" org-todo t]
19417 ("Select keyword"
19418 ["Next keyword" org-shiftright (org-at-heading-p)]
19419 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19420 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19421 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19422 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19423 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19424 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19425 "--"
19426 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19427 :selected org-enforce-todo-dependencies :style toggle :active t]
19428 "Settings for tree at point"
19429 ["Do Children sequentially" org-toggle-ordered-property :style radio
19430 :selected (org-entry-get nil "ORDERED")
19431 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19432 ["Do Children parallel" org-toggle-ordered-property :style radio
19433 :selected (not (org-entry-get nil "ORDERED"))
19434 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19435 "--"
19436 ["Set Priority" org-priority t]
19437 ["Priority Up" org-shiftup t]
19438 ["Priority Down" org-shiftdown t]
19439 "--"
19440 ["Get news from all feeds" org-feed-update-all t]
19441 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19442 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19443 ("TAGS and Properties"
19444 ["Set Tags" org-set-tags-command t]
19445 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19446 "--"
19447 ["Set property" org-set-property t]
19448 ["Column view of properties" org-columns t]
19449 ["Insert Column View DBlock" org-insert-columns-dblock t])
19450 ("Dates and Scheduling"
19451 ["Timestamp" org-time-stamp t]
19452 ["Timestamp (inactive)" org-time-stamp-inactive t]
19453 ("Change Date"
19454 ["1 Day Later" org-shiftright t]
19455 ["1 Day Earlier" org-shiftleft t]
19456 ["1 ... Later" org-shiftup t]
19457 ["1 ... Earlier" org-shiftdown t])
19458 ["Compute Time Range" org-evaluate-time-range t]
19459 ["Schedule Item" org-schedule t]
19460 ["Deadline" org-deadline t]
19461 "--"
19462 ["Custom time format" org-toggle-time-stamp-overlays
19463 :style radio :selected org-display-custom-times]
19464 "--"
19465 ["Goto Calendar" org-goto-calendar t]
19466 ["Date from Calendar" org-date-from-calendar t]
19467 "--"
19468 ["Start/Restart Timer" org-timer-start t]
19469 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19470 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19471 ["Insert Timer String" org-timer t]
19472 ["Insert Timer Item" org-timer-item t])
19473 ("Logging work"
19474 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19475 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19476 ["Clock out" org-clock-out t]
19477 ["Clock cancel" org-clock-cancel t]
19478 "--"
19479 ["Mark as default task" org-clock-mark-default-task t]
19480 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19481 ["Goto running clock" org-clock-goto t]
19482 "--"
19483 ["Display times" org-clock-display t]
19484 ["Create clock table" org-clock-report t]
19485 "--"
19486 ["Record DONE time"
19487 (progn (setq org-log-done (not org-log-done))
19488 (message "Switching to %s will %s record a timestamp"
19489 (car org-done-keywords)
19490 (if org-log-done "automatically" "not")))
19491 :style toggle :selected org-log-done])
19492 "--"
19493 ["Agenda Command..." org-agenda t]
19494 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19495 ("File List for Agenda")
19496 ("Special views current file"
19497 ["TODO Tree" org-show-todo-tree t]
19498 ["Check Deadlines" org-check-deadlines t]
19499 ["Timeline" org-timeline t]
19500 ["Tags/Property tree" org-match-sparse-tree t])
19501 "--"
19502 ["Export/Publish..." org-export t]
19503 ("LaTeX"
19504 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19505 :selected org-cdlatex-mode]
19506 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19507 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19508 ["Modify math symbol" org-cdlatex-math-modify
19509 (org-inside-LaTeX-fragment-p)]
19510 ["Insert citation" org-reftex-citation t]
19511 "--"
19512 ["Template for BEAMER" (progn (require 'org-beamer)
19513 (org-insert-beamer-options-template)) t])
19514 "--"
19515 ("MobileOrg"
19516 ["Push Files and Views" org-mobile-push t]
19517 ["Get Captured and Flagged" org-mobile-pull t]
19518 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19519 "--"
19520 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19521 "--"
19522 ("Documentation"
19523 ["Show Version" org-version t]
19524 ["Info Documentation" org-info t])
19525 ("Customize"
19526 ["Browse Org Group" org-customize t]
19527 "--"
19528 ["Expand This Menu" org-create-customize-menu
19529 (fboundp 'customize-menu-create)])
19530 ["Send bug report" org-submit-bug-report t]
19531 "--"
19532 ("Refresh/Reload"
19533 ["Refresh setup current buffer" org-mode-restart t]
19534 ["Reload Org (after update)" org-reload t]
19535 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19538 (defun org-info (&optional node)
19539 "Read documentation for Org-mode in the info system.
19540 With optional NODE, go directly to that node."
19541 (interactive)
19542 (info (format "(org)%s" (or node ""))))
19544 ;;;###autoload
19545 (defun org-submit-bug-report ()
19546 "Submit a bug report on Org-mode via mail.
19548 Don't hesitate to report any problems or inaccurate documentation.
19550 If you don't have setup sending mail from (X)Emacs, please copy the
19551 output buffer into your mail program, as it gives us important
19552 information about your Org-mode version and configuration."
19553 (interactive)
19554 (require 'reporter)
19555 (org-load-modules-maybe)
19556 (org-require-autoloaded-modules)
19557 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19558 (reporter-submit-bug-report
19559 "emacs-orgmode@gnu.org"
19560 (org-version nil 'full)
19561 (let (list)
19562 (save-window-excursion
19563 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19564 (delete-other-windows)
19565 (erase-buffer)
19566 (insert "You are about to submit a bug report to the Org-mode mailing list.
19568 We would like to add your full Org-mode and Outline configuration to the
19569 bug report. This greatly simplifies the work of the maintainer and
19570 other experts on the mailing list.
19572 HOWEVER, some variables you have customized may contain private
19573 information. The names of customers, colleagues, or friends, might
19574 appear in the form of file names, tags, todo states, or search strings.
19575 If you answer yes to the prompt, you might want to check and remove
19576 such private information before sending the email.")
19577 (add-text-properties (point-min) (point-max) '(face org-warning))
19578 (when (yes-or-no-p "Include your Org-mode configuration ")
19579 (mapatoms
19580 (lambda (v)
19581 (and (boundp v)
19582 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19583 (or (and (symbol-value v)
19584 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19585 (and
19586 (get v 'custom-type) (get v 'standard-value)
19587 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19588 (push v list)))))
19589 (kill-buffer (get-buffer "*Warn about privacy*"))
19590 list))
19591 nil nil
19592 "Remember to cover the basics, that is, what you expected to happen and
19593 what in fact did happen. You don't know how to make a good report? See
19595 http://orgmode.org/manual/Feedback.html#Feedback
19597 Your bug report will be posted to the Org-mode mailing list.
19598 ------------------------------------------------------------------------")
19599 (save-excursion
19600 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19601 (replace-match "\\1Bug: \\3 [\\2]")))))
19604 (defun org-install-agenda-files-menu ()
19605 (let ((bl (buffer-list)))
19606 (save-excursion
19607 (while bl
19608 (set-buffer (pop bl))
19609 (if (derived-mode-p 'org-mode) (setq bl nil)))
19610 (when (derived-mode-p 'org-mode)
19611 (easy-menu-change
19612 '("Org") "File List for Agenda"
19613 (append
19614 (list
19615 ["Edit File List" (org-edit-agenda-file-list) t]
19616 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19617 ["Remove Current File from List" org-remove-file t]
19618 ["Cycle through agenda files" org-cycle-agenda-files t]
19619 ["Occur in all agenda files" org-occur-in-agenda-files t]
19620 "--")
19621 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19623 ;;;; Documentation
19625 ;;;###autoload
19626 (defun org-require-autoloaded-modules ()
19627 (interactive)
19628 (mapc 'require
19629 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19630 org-docbook org-exp org-html org-icalendar
19631 org-id org-latex
19632 org-publish org-remember org-table
19633 org-timer org-xoxo)))
19635 ;;;###autoload
19636 (defun org-reload (&optional uncompiled)
19637 "Reload all org lisp files.
19638 With prefix arg UNCOMPILED, load the uncompiled versions."
19639 (interactive "P")
19640 (require 'find-func)
19641 (let* ((file-re "^org\\(-.*\\)?\\.el")
19642 (dir-org (file-name-directory (org-find-library-dir "org")))
19643 (dir-org-contrib (ignore-errors
19644 (file-name-directory
19645 (org-find-library-dir "org-contribdir"))))
19646 (babel-files
19647 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19648 (append (list nil "comint" "eval" "exp" "keys"
19649 "lob" "ref" "table" "tangle")
19650 (delq nil
19651 (mapcar
19652 (lambda (lang)
19653 (when (cdr lang) (symbol-name (car lang))))
19654 org-babel-load-languages)))))
19655 (files
19656 (append babel-files
19657 (and dir-org-contrib
19658 (directory-files dir-org-contrib t file-re))
19659 (directory-files dir-org t file-re)))
19660 (remove-re (concat (if (featurep 'xemacs)
19661 "org-colview" "org-colview-xemacs")
19662 "\\'")))
19663 (setq files (mapcar 'file-name-sans-extension files))
19664 (setq files (mapcar
19665 (lambda (x) (if (string-match remove-re x) nil x))
19666 files))
19667 (setq files (delq nil files))
19668 (mapc
19669 (lambda (f)
19670 (when (featurep (intern (file-name-nondirectory f)))
19671 (if (and (not uncompiled)
19672 (file-exists-p (concat f ".elc")))
19673 (load (concat f ".elc") nil nil 'nosuffix)
19674 (load (concat f ".el") nil nil 'nosuffix))))
19675 files)
19676 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19677 (org-version nil 'full 'message))
19679 ;;;###autoload
19680 (defun org-customize ()
19681 "Call the customize function with org as argument."
19682 (interactive)
19683 (org-load-modules-maybe)
19684 (org-require-autoloaded-modules)
19685 (customize-browse 'org))
19687 (defun org-create-customize-menu ()
19688 "Create a full customization menu for Org-mode, insert it into the menu."
19689 (interactive)
19690 (org-load-modules-maybe)
19691 (org-require-autoloaded-modules)
19692 (if (fboundp 'customize-menu-create)
19693 (progn
19694 (easy-menu-change
19695 '("Org") "Customize"
19696 `(["Browse Org group" org-customize t]
19697 "--"
19698 ,(customize-menu-create 'org)
19699 ["Set" Custom-set t]
19700 ["Save" Custom-save t]
19701 ["Reset to Current" Custom-reset-current t]
19702 ["Reset to Saved" Custom-reset-saved t]
19703 ["Reset to Standard Settings" Custom-reset-standard t]))
19704 (message "\"Org\"-menu now contains full customization menu"))
19705 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19707 ;;;; Miscellaneous stuff
19709 ;;; Generally useful functions
19711 (defun org-get-at-bol (property)
19712 "Get text property PROPERTY at beginning of line."
19713 (get-text-property (point-at-bol) property))
19715 (defun org-find-text-property-in-string (prop s)
19716 "Return the first non-nil value of property PROP in string S."
19717 (or (get-text-property 0 prop s)
19718 (get-text-property (or (next-single-property-change 0 prop s) 0)
19719 prop s)))
19721 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19722 "Display the given MESSAGE as a warning."
19723 (if (fboundp 'display-warning)
19724 (display-warning 'org message
19725 (if (featurep 'xemacs) 'warning :warning))
19726 (let ((buf (get-buffer-create "*Org warnings*")))
19727 (with-current-buffer buf
19728 (goto-char (point-max))
19729 (insert "Warning (Org): " message)
19730 (unless (bolp)
19731 (newline)))
19732 (display-buffer buf)
19733 (sit-for 0))))
19735 (defun org-eval (form)
19736 "Eval FORM and return result."
19737 (condition-case error
19738 (eval form)
19739 (error (format "%%![Error: %s]" error))))
19741 (defun org-in-clocktable-p ()
19742 "Check if the cursor is in a clocktable."
19743 (let ((pos (point)) start)
19744 (save-excursion
19745 (end-of-line 1)
19746 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19747 (setq start (match-beginning 0))
19748 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19749 (>= (match-end 0) pos)
19750 start))))
19752 (defun org-in-commented-line ()
19753 "Is point in a line starting with `#'?"
19754 (equal (char-after (point-at-bol)) ?#))
19756 (defun org-in-indented-comment-line ()
19757 "Is point in a line starting with `#' after some white space?"
19758 (save-excursion
19759 (save-match-data
19760 (goto-char (point-at-bol))
19761 (looking-at "[ \t]*#"))))
19763 (defun org-in-verbatim-emphasis ()
19764 (save-match-data
19765 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19767 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19768 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19769 (if (and marker (marker-buffer marker)
19770 (buffer-live-p (marker-buffer marker)))
19771 (progn
19772 (org-pop-to-buffer-same-window (marker-buffer marker))
19773 (if (or (> marker (point-max)) (< marker (point-min)))
19774 (widen))
19775 (goto-char marker)
19776 (org-show-context 'org-goto))
19777 (if bookmark
19778 (bookmark-jump bookmark)
19779 (error "Cannot find location"))))
19781 (defun org-quote-csv-field (s)
19782 "Quote field for inclusion in CSV material."
19783 (if (string-match "[\",]" s)
19784 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19787 (defun org-force-self-insert (N)
19788 "Needed to enforce self-insert under remapping."
19789 (interactive "p")
19790 (self-insert-command N))
19792 (defun org-string-width (s)
19793 "Compute width of string, ignoring invisible characters.
19794 This ignores character with invisibility property `org-link', and also
19795 characters with property `org-cwidth', because these will become invisible
19796 upon the next fontification round."
19797 (let (b l)
19798 (when (or (eq t buffer-invisibility-spec)
19799 (assq 'org-link buffer-invisibility-spec))
19800 (while (setq b (text-property-any 0 (length s)
19801 'invisible 'org-link s))
19802 (setq s (concat (substring s 0 b)
19803 (substring s (or (next-single-property-change
19804 b 'invisible s) (length s)))))))
19805 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19806 (setq s (concat (substring s 0 b)
19807 (substring s (or (next-single-property-change
19808 b 'org-cwidth s) (length s))))))
19809 (setq l (string-width s) b -1)
19810 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19811 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19814 (defun org-shorten-string (s maxlength)
19815 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19816 If the string is shorter or has length MAXLENGTH, just return the
19817 original string. If it is longer, the functions finds a space in the
19818 string, breaks this string off at that locations and adds three dots
19819 as ellipsis. Including the ellipsis, the string will not be longer
19820 than MAXLENGTH. If finding a good breaking point in the string does
19821 not work, the string is just chopped off in the middle of a word
19822 if necessary."
19823 (if (<= (length s) maxlength)
19825 (let* ((n (max (- maxlength 4) 1))
19826 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19827 (if (string-match re s)
19828 (concat (match-string 1 s) "...")
19829 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19831 (defun org-get-indentation (&optional line)
19832 "Get the indentation of the current line, interpreting tabs.
19833 When LINE is given, assume it represents a line and compute its indentation."
19834 (if line
19835 (if (string-match "^ *" (org-remove-tabs line))
19836 (match-end 0))
19837 (save-excursion
19838 (beginning-of-line 1)
19839 (skip-chars-forward " \t")
19840 (current-column))))
19842 (defun org-get-string-indentation (s)
19843 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19844 (let ((n -1) (i 0) (w tab-width) c)
19845 (catch 'exit
19846 (while (< (setq n (1+ n)) (length s))
19847 (setq c (aref s n))
19848 (cond ((= c ?\ ) (setq i (1+ i)))
19849 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19850 (t (throw 'exit t)))))
19853 (defun org-remove-tabs (s &optional width)
19854 "Replace tabulators in S with spaces.
19855 Assumes that s is a single line, starting in column 0."
19856 (setq width (or width tab-width))
19857 (while (string-match "\t" s)
19858 (setq s (replace-match
19859 (make-string
19860 (- (* width (/ (+ (match-beginning 0) width) width))
19861 (match-beginning 0)) ?\ )
19862 t t s)))
19865 (defun org-fix-indentation (line ind)
19866 "Fix indentation in LINE.
19867 IND is a cons cell with target and minimum indentation.
19868 If the current indentation in LINE is smaller than the minimum,
19869 leave it alone. If it is larger than ind, set it to the target."
19870 (let* ((l (org-remove-tabs line))
19871 (i (org-get-indentation l))
19872 (i1 (car ind)) (i2 (cdr ind)))
19873 (if (>= i i2) (setq l (substring line i2)))
19874 (if (> i1 0)
19875 (concat (make-string i1 ?\ ) l)
19876 l)))
19878 (defun org-remove-indentation (code &optional n)
19879 "Remove the maximum common indentation from the lines in CODE.
19880 N may optionally be the number of spaces to remove."
19881 (with-temp-buffer
19882 (insert code)
19883 (org-do-remove-indentation n)
19884 (buffer-string)))
19886 (defun org-do-remove-indentation (&optional n)
19887 "Remove the maximum common indentation from the buffer."
19888 (untabify (point-min) (point-max))
19889 (let ((min 10000) re)
19890 (if n
19891 (setq min n)
19892 (goto-char (point-min))
19893 (while (re-search-forward "^ *[^ \n]" nil t)
19894 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19895 (unless (or (= min 0) (= min 10000))
19896 (setq re (format "^ \\{%d\\}" min))
19897 (goto-char (point-min))
19898 (while (re-search-forward re nil t)
19899 (replace-match "")
19900 (end-of-line 1))
19901 min)))
19903 (defun org-fill-template (template alist)
19904 "Find each %key of ALIST in TEMPLATE and replace it."
19905 (let ((case-fold-search nil)
19906 entry key value)
19907 (setq alist (sort (copy-sequence alist)
19908 (lambda (a b) (< (length (car a)) (length (car b))))))
19909 (while (setq entry (pop alist))
19910 (setq template
19911 (replace-regexp-in-string
19912 (concat "%" (regexp-quote (car entry)))
19913 (cdr entry) template t t)))
19914 template))
19916 (defun org-base-buffer (buffer)
19917 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19918 (if (not buffer)
19919 buffer
19920 (or (buffer-base-buffer buffer)
19921 buffer)))
19923 (defun org-trim (s)
19924 "Remove whitespace at beginning and end of string."
19925 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19926 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19929 (defun org-wrap (string &optional width lines)
19930 "Wrap string to either a number of lines, or a width in characters.
19931 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19932 that costs. If there is a word longer than WIDTH, the text is actually
19933 wrapped to the length of that word.
19934 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19935 many lines, whatever width that takes.
19936 The return value is a list of lines, without newlines at the end."
19937 (let* ((words (org-split-string string "[ \t\n]+"))
19938 (maxword (apply 'max (mapcar 'org-string-width words)))
19939 w ll)
19940 (cond (width
19941 (org-do-wrap words (max maxword width)))
19942 (lines
19943 (setq w maxword)
19944 (setq ll (org-do-wrap words maxword))
19945 (if (<= (length ll) lines)
19947 (setq ll words)
19948 (while (> (length ll) lines)
19949 (setq w (1+ w))
19950 (setq ll (org-do-wrap words w)))
19951 ll))
19952 (t (error "Cannot wrap this")))))
19954 (defun org-do-wrap (words width)
19955 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19956 (let (lines line)
19957 (while words
19958 (setq line (pop words))
19959 (while (and words (< (+ (length line) (length (car words))) width))
19960 (setq line (concat line " " (pop words))))
19961 (setq lines (push line lines)))
19962 (nreverse lines)))
19964 (defun org-split-string (string &optional separators)
19965 "Splits STRING into substrings at SEPARATORS.
19966 No empty strings are returned if there are matches at the beginning
19967 and end of string."
19968 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19969 (start 0)
19970 notfirst
19971 (list nil))
19972 (while (and (string-match rexp string
19973 (if (and notfirst
19974 (= start (match-beginning 0))
19975 (< start (length string)))
19976 (1+ start) start))
19977 (< (match-beginning 0) (length string)))
19978 (setq notfirst t)
19979 (or (eq (match-beginning 0) 0)
19980 (and (eq (match-beginning 0) (match-end 0))
19981 (eq (match-beginning 0) start))
19982 (setq list
19983 (cons (substring string start (match-beginning 0))
19984 list)))
19985 (setq start (match-end 0)))
19986 (or (eq start (length string))
19987 (setq list
19988 (cons (substring string start)
19989 list)))
19990 (nreverse list)))
19992 (defun org-quote-vert (s)
19993 "Replace \"|\" with \"\\vert\"."
19994 (while (string-match "|" s)
19995 (setq s (replace-match "\\vert" t t s)))
19998 (defun org-uuidgen-p (s)
19999 "Is S an ID created by UUIDGEN?"
20000 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20002 (defun org-in-src-block-p nil
20003 "Whether point is in a code source block."
20004 (let (ov)
20005 (when (setq ov (overlays-at (point)))
20006 (memq 'org-block-background
20007 (overlay-properties
20008 (car ov))))))
20010 (defun org-context ()
20011 "Return a list of contexts of the current cursor position.
20012 If several contexts apply, all are returned.
20013 Each context entry is a list with a symbol naming the context, and
20014 two positions indicating start and end of the context. Possible
20015 contexts are:
20017 :headline anywhere in a headline
20018 :headline-stars on the leading stars in a headline
20019 :todo-keyword on a TODO keyword (including DONE) in a headline
20020 :tags on the TAGS in a headline
20021 :priority on the priority cookie in a headline
20022 :item on the first line of a plain list item
20023 :item-bullet on the bullet/number of a plain list item
20024 :checkbox on the checkbox in a plain list item
20025 :table in an org-mode table
20026 :table-special on a special filed in a table
20027 :table-table in a table.el table
20028 :clocktable in a clocktable
20029 :src-block in a source block
20030 :link on a hyperlink
20031 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20032 :target on a <<target>>
20033 :radio-target on a <<<radio-target>>>
20034 :latex-fragment on a LaTeX fragment
20035 :latex-preview on a LaTeX fragment with overlaid preview image
20037 This function expects the position to be visible because it uses font-lock
20038 faces as a help to recognize the following contexts: :table-special, :link,
20039 and :keyword."
20040 (let* ((f (get-text-property (point) 'face))
20041 (faces (if (listp f) f (list f)))
20042 (case-fold-search t)
20043 (p (point)) clist o)
20044 ;; First the large context
20045 (cond
20046 ((org-at-heading-p t)
20047 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20048 (when (progn
20049 (beginning-of-line 1)
20050 (looking-at org-todo-line-tags-regexp))
20051 (push (org-point-in-group p 1 :headline-stars) clist)
20052 (push (org-point-in-group p 2 :todo-keyword) clist)
20053 (push (org-point-in-group p 4 :tags) clist))
20054 (goto-char p)
20055 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20056 (if (looking-at "\\[#[A-Z0-9]\\]")
20057 (push (org-point-in-group p 0 :priority) clist)))
20059 ((org-at-item-p)
20060 (push (org-point-in-group p 2 :item-bullet) clist)
20061 (push (list :item (point-at-bol)
20062 (save-excursion (org-end-of-item) (point)))
20063 clist)
20064 (and (org-at-item-checkbox-p)
20065 (push (org-point-in-group p 0 :checkbox) clist)))
20067 ((org-at-table-p)
20068 (push (list :table (org-table-begin) (org-table-end)) clist)
20069 (if (memq 'org-formula faces)
20070 (push (list :table-special
20071 (previous-single-property-change p 'face)
20072 (next-single-property-change p 'face)) clist)))
20073 ((org-at-table-p 'any)
20074 (push (list :table-table) clist)))
20075 (goto-char p)
20077 ;; New the "medium" contexts: clocktables, source blocks
20078 (cond ((org-in-clocktable-p)
20079 (push (list :clocktable
20080 (and (or (looking-at "#\\+BEGIN: clocktable")
20081 (search-backward "#+BEGIN: clocktable" nil t))
20082 (match-beginning 0))
20083 (and (re-search-forward "#\\+END:?" nil t)
20084 (match-end 0))) clist))
20085 ((org-in-src-block-p)
20086 (push (list :src-block
20087 (and (or (looking-at "#\\+BEGIN_SRC")
20088 (search-backward "#+BEGIN_SRC" nil t))
20089 (match-beginning 0))
20090 (and (search-forward "#+END_SRC" nil t)
20091 (match-beginning 0))) clist)))
20092 (goto-char p)
20094 ;; Now the small context
20095 (cond
20096 ((org-at-timestamp-p)
20097 (push (org-point-in-group p 0 :timestamp) clist))
20098 ((memq 'org-link faces)
20099 (push (list :link
20100 (previous-single-property-change p 'face)
20101 (next-single-property-change p 'face)) clist))
20102 ((memq 'org-special-keyword faces)
20103 (push (list :keyword
20104 (previous-single-property-change p 'face)
20105 (next-single-property-change p 'face)) clist))
20106 ((org-at-target-p)
20107 (push (org-point-in-group p 0 :target) clist)
20108 (goto-char (1- (match-beginning 0)))
20109 (if (looking-at org-radio-target-regexp)
20110 (push (org-point-in-group p 0 :radio-target) clist))
20111 (goto-char p))
20112 ((setq o (car (delq nil
20113 (mapcar
20114 (lambda (x)
20115 (if (memq x org-latex-fragment-image-overlays) x))
20116 (overlays-at (point))))))
20117 (push (list :latex-fragment
20118 (overlay-start o) (overlay-end o)) clist)
20119 (push (list :latex-preview
20120 (overlay-start o) (overlay-end o)) clist))
20121 ((org-inside-LaTeX-fragment-p)
20122 ;; FIXME: positions wrong.
20123 (push (list :latex-fragment (point) (point)) clist)))
20125 (setq clist (nreverse (delq nil clist)))
20126 clist))
20128 ;; FIXME: Compare with at-regexp-p Do we need both?
20129 (defun org-in-regexp (re &optional nlines visually)
20130 "Check if point is inside a match of regexp.
20131 Normally only the current line is checked, but you can include NLINES extra
20132 lines both before and after point into the search.
20133 If VISUALLY is set, require that the cursor is not after the match but
20134 really on, so that the block visually is on the match."
20135 (catch 'exit
20136 (let ((pos (point))
20137 (eol (point-at-eol (+ 1 (or nlines 0))))
20138 (inc (if visually 1 0)))
20139 (save-excursion
20140 (beginning-of-line (- 1 (or nlines 0)))
20141 (while (re-search-forward re eol t)
20142 (if (and (<= (match-beginning 0) pos)
20143 (>= (+ inc (match-end 0)) pos))
20144 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20146 (defun org-at-regexp-p (regexp)
20147 "Is point inside a match of REGEXP in the current line?"
20148 (catch 'exit
20149 (save-excursion
20150 (let ((pos (point)) (end (point-at-eol)))
20151 (beginning-of-line 1)
20152 (while (re-search-forward regexp end t)
20153 (if (and (<= (match-beginning 0) pos)
20154 (>= (match-end 0) pos))
20155 (throw 'exit t)))
20156 nil))))
20158 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20159 "Non-nil when point is between matches of START-RE and END-RE.
20161 Also return a non-nil value when point is on one of the matches.
20163 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20164 buffer positions. Default values are the positions of headlines
20165 surrounding the point.
20167 The functions returns a cons cell whose car (resp. cdr) is the
20168 position before START-RE (resp. after END-RE)."
20169 (save-match-data
20170 (let ((pos (point))
20171 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20172 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20173 beg end)
20174 (save-excursion
20175 ;; Point is on a block when on START-RE or if START-RE can be
20176 ;; found before it...
20177 (and (or (org-at-regexp-p start-re)
20178 (re-search-backward start-re limit-up t))
20179 (setq beg (match-beginning 0))
20180 ;; ... and END-RE after it...
20181 (goto-char (match-end 0))
20182 (re-search-forward end-re limit-down t)
20183 (> (setq end (match-end 0)) pos)
20184 ;; ... without another START-RE in-between.
20185 (goto-char (match-beginning 0))
20186 (not (re-search-backward start-re (1+ beg) t))
20187 ;; Return value.
20188 (cons beg end))))))
20190 (defun org-in-block-p (names)
20191 "Non-nil when point belongs to a block whose name belongs to NAMES.
20193 NAMES is a list of strings containing names of blocks.
20195 Return first block name matched, or nil. Beware that in case of
20196 nested blocks, the returned name may not belong to the closest
20197 block from point."
20198 (save-match-data
20199 (catch 'exit
20200 (let ((case-fold-search t)
20201 (lim-up (save-excursion (outline-previous-heading)))
20202 (lim-down (save-excursion (outline-next-heading))))
20203 (mapc (lambda (name)
20204 (let ((n (regexp-quote name)))
20205 (when (org-between-regexps-p
20206 (concat "^[ \t]*#\\+begin_" n)
20207 (concat "^[ \t]*#\\+end_" n)
20208 lim-up lim-down)
20209 (throw 'exit n))))
20210 names))
20211 nil)))
20213 (defun org-occur-in-agenda-files (regexp &optional nlines)
20214 "Call `multi-occur' with buffers for all agenda files."
20215 (interactive "sOrg-files matching: \np")
20216 (let* ((files (org-agenda-files))
20217 (tnames (mapcar 'file-truename files))
20218 (extra org-agenda-text-search-extra-files)
20220 (when (eq (car extra) 'agenda-archives)
20221 (setq extra (cdr extra))
20222 (setq files (org-add-archive-files files)))
20223 (while (setq f (pop extra))
20224 (unless (member (file-truename f) tnames)
20225 (add-to-list 'files f 'append)
20226 (add-to-list 'tnames (file-truename f) 'append)))
20227 (multi-occur
20228 (mapcar (lambda (x)
20229 (with-current-buffer
20230 (or (get-file-buffer x) (find-file-noselect x))
20231 (widen)
20232 (current-buffer)))
20233 files)
20234 regexp)))
20236 (if (boundp 'occur-mode-find-occurrence-hook)
20237 ;; Emacs 23
20238 (add-hook 'occur-mode-find-occurrence-hook
20239 (lambda ()
20240 (when (derived-mode-p 'org-mode)
20241 (org-reveal))))
20242 ;; Emacs 22
20243 (defadvice occur-mode-goto-occurrence
20244 (after org-occur-reveal activate)
20245 (and (derived-mode-p 'org-mode) (org-reveal)))
20246 (defadvice occur-mode-goto-occurrence-other-window
20247 (after org-occur-reveal activate)
20248 (and (derived-mode-p 'org-mode) (org-reveal)))
20249 (defadvice occur-mode-display-occurrence
20250 (after org-occur-reveal activate)
20251 (when (derived-mode-p 'org-mode)
20252 (let ((pos (occur-mode-find-occurrence)))
20253 (with-current-buffer (marker-buffer pos)
20254 (save-excursion
20255 (goto-char pos)
20256 (org-reveal)))))))
20258 (defun org-occur-link-in-agenda-files ()
20259 "Create a link and search for it in the agendas.
20260 The link is not stored in `org-stored-links', it is just created
20261 for the search purpose."
20262 (interactive)
20263 (let ((link (condition-case nil
20264 (org-store-link nil)
20265 (error "Unable to create a link to here"))))
20266 (org-occur-in-agenda-files (regexp-quote link))))
20268 (defun org-uniquify (list)
20269 "Remove duplicate elements from LIST."
20270 (let (res)
20271 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20272 res))
20274 (defun org-delete-all (elts list)
20275 "Remove all elements in ELTS from LIST."
20276 (while elts
20277 (setq list (delete (pop elts) list)))
20278 list)
20280 (defun org-count (cl-item cl-seq)
20281 "Count the number of occurrences of ITEM in SEQ.
20282 Taken from `count' in cl-seq.el with all keyword arguments removed."
20283 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20284 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20285 (while (< cl-start cl-end)
20286 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20287 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20288 (setq cl-start (1+ cl-start)))
20289 cl-count))
20291 (defun org-remove-if (predicate seq)
20292 "Remove everything from SEQ that fulfills PREDICATE."
20293 (let (res e)
20294 (while seq
20295 (setq e (pop seq))
20296 (if (not (funcall predicate e)) (push e res)))
20297 (nreverse res)))
20299 (defun org-remove-if-not (predicate seq)
20300 "Remove everything from SEQ that does not fulfill PREDICATE."
20301 (let (res e)
20302 (while seq
20303 (setq e (pop seq))
20304 (if (funcall predicate e) (push e res)))
20305 (nreverse res)))
20307 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20308 "Reduce two-argument FUNCTION across SEQ.
20309 Taken from `reduce' in cl-seq.el with all keyword arguments but
20310 \":initial-value\" removed."
20311 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20312 (cadr (memq :initial-value cl-keys)))
20313 (cl-seq (pop cl-seq))
20314 (t (funcall cl-func)))))
20315 (while cl-seq
20316 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20317 cl-accum))
20319 (defun org-back-over-empty-lines ()
20320 "Move backwards over whitespace, to the beginning of the first empty line.
20321 Returns the number of empty lines passed."
20322 (let ((pos (point)))
20323 (if (cdr (assoc 'heading org-blank-before-new-entry))
20324 (skip-chars-backward " \t\n\r")
20325 (unless (eobp)
20326 (forward-line -1)))
20327 (beginning-of-line 2)
20328 (goto-char (min (point) pos))
20329 (count-lines (point) pos)))
20331 (defun org-skip-whitespace ()
20332 (skip-chars-forward " \t\n\r"))
20334 (defun org-point-in-group (point group &optional context)
20335 "Check if POINT is in match-group GROUP.
20336 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20337 match. If the match group does not exist or point is not inside it,
20338 return nil."
20339 (and (match-beginning group)
20340 (>= point (match-beginning group))
20341 (<= point (match-end group))
20342 (if context
20343 (list context (match-beginning group) (match-end group))
20344 t)))
20346 (defun org-switch-to-buffer-other-window (&rest args)
20347 "Switch to buffer in a second window on the current frame.
20348 In particular, do not allow pop-up frames.
20349 Returns the newly created buffer."
20350 (let (pop-up-frames special-display-buffer-names special-display-regexps
20351 special-display-function)
20352 (apply 'switch-to-buffer-other-window args)))
20354 (defun org-combine-plists (&rest plists)
20355 "Create a single property list from all plists in PLISTS.
20356 The process starts by copying the first list, and then setting properties
20357 from the other lists. Settings in the last list are the most significant
20358 ones and overrule settings in the other lists."
20359 (let ((rtn (copy-sequence (pop plists)))
20360 p v ls)
20361 (while plists
20362 (setq ls (pop plists))
20363 (while ls
20364 (setq p (pop ls) v (pop ls))
20365 (setq rtn (plist-put rtn p v))))
20366 rtn))
20368 (defun org-replace-escapes (string table)
20369 "Replace %-escapes in STRING with values in TABLE.
20370 TABLE is an association list with keys like \"%a\" and string values.
20371 The sequences in STRING may contain normal field width and padding information,
20372 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20373 so values can contain further %-escapes if they are define later in TABLE."
20374 (let ((tbl (copy-alist table))
20375 (case-fold-search nil)
20376 (pchg 0)
20377 e re rpl)
20378 (while (setq e (pop tbl))
20379 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20380 (when (and (cdr e) (string-match re (cdr e)))
20381 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20382 (safe "SREF"))
20383 (add-text-properties 0 3 (list 'sref sref) safe)
20384 (setcdr e (replace-match safe t t (cdr e)))))
20385 (while (string-match re string)
20386 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20387 (cdr e)))
20388 (setq string (replace-match rpl t t string))))
20389 (while (setq pchg (next-property-change pchg string))
20390 (let ((sref (get-text-property pchg 'sref string)))
20391 (when (and sref (string-match "SREF" string pchg))
20392 (setq string (replace-match sref t t string)))))
20393 string))
20395 (defun org-sublist (list start end)
20396 "Return a section of LIST, from START to END.
20397 Counting starts at 1."
20398 (let (rtn (c start))
20399 (setq list (nthcdr (1- start) list))
20400 (while (and list (<= c end))
20401 (push (pop list) rtn)
20402 (setq c (1+ c)))
20403 (nreverse rtn)))
20405 (defun org-find-base-buffer-visiting (file)
20406 "Like `find-buffer-visiting' but always return the base buffer and
20407 not an indirect buffer."
20408 (let ((buf (or (get-file-buffer file)
20409 (find-buffer-visiting file))))
20410 (if buf
20411 (or (buffer-base-buffer buf) buf)
20412 nil)))
20414 (defun org-image-file-name-regexp (&optional extensions)
20415 "Return regexp matching the file names of images.
20416 If EXTENSIONS is given, only match these."
20417 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20418 (image-file-name-regexp)
20419 (let ((image-file-name-extensions
20420 (or extensions
20421 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20422 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20423 (concat "\\."
20424 (regexp-opt (nconc (mapcar 'upcase
20425 image-file-name-extensions)
20426 image-file-name-extensions)
20428 "\\'"))))
20430 (defun org-file-image-p (file &optional extensions)
20431 "Return non-nil if FILE is an image."
20432 (save-match-data
20433 (string-match (org-image-file-name-regexp extensions) file)))
20435 (defun org-get-cursor-date ()
20436 "Return the date at cursor in as a time.
20437 This works in the calendar and in the agenda, anywhere else it just
20438 returns the current time."
20439 (let (date day defd)
20440 (cond
20441 ((eq major-mode 'calendar-mode)
20442 (setq date (calendar-cursor-to-date)
20443 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20444 ((eq major-mode 'org-agenda-mode)
20445 (setq day (get-text-property (point) 'day))
20446 (if day
20447 (setq date (calendar-gregorian-from-absolute day)
20448 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20449 (nth 2 date))))))
20450 (or defd (current-time))))
20452 (defvar org-agenda-action-marker (make-marker)
20453 "Marker pointing to the entry for the next agenda action.")
20455 (defun org-mark-entry-for-agenda-action ()
20456 "Mark the current entry as target of an agenda action.
20457 Agenda actions are actions executed from the agenda with the key `k',
20458 which make use of the date at the cursor."
20459 (interactive)
20460 (move-marker org-agenda-action-marker
20461 (save-excursion (org-back-to-heading t) (point))
20462 (current-buffer))
20463 (message
20464 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20466 (defun org-mark-subtree ()
20467 "Mark the current subtree.
20468 This puts point at the start of the current subtree, and mark at the end.
20470 If point is in an inline task, mark that task instead."
20471 (interactive)
20472 (let ((inline-task-p
20473 (and (featurep 'org-inlinetask)
20474 (org-inlinetask-in-task-p)))
20475 (beg))
20476 ;; Get beginning of subtree
20477 (cond
20478 (inline-task-p (org-inlinetask-goto-beginning))
20479 ((org-at-heading-p) (beginning-of-line))
20480 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20481 (setq beg (point))
20482 ;; Get end of it
20483 (if inline-task-p
20484 (org-inlinetask-goto-end)
20485 (org-end-of-subtree))
20486 ;; Mark zone
20487 (push-mark (point) nil t)
20488 (goto-char beg)))
20490 ;;; Paragraph filling stuff.
20491 ;; We want this to be just right, so use the full arsenal.
20493 (defun org-indent-line ()
20494 "Indent line depending on context."
20495 (interactive)
20496 (let* ((pos (point))
20497 (itemp (org-at-item-p))
20498 (case-fold-search t)
20499 (org-drawer-regexp (or org-drawer-regexp "\000"))
20500 (inline-task-p (and (featurep 'org-inlinetask)
20501 (org-inlinetask-in-task-p)))
20502 (inline-re (and inline-task-p
20503 (org-inlinetask-outline-regexp)))
20504 column)
20505 (beginning-of-line 1)
20506 (cond
20507 ;; Comments
20508 ((looking-at "# ") (setq column 0))
20509 ;; Headings
20510 ((looking-at org-outline-regexp) (setq column 0))
20511 ;; Included files
20512 ((looking-at "#\\+include:") (setq column 0))
20513 ;; Footnote definition
20514 ((looking-at org-footnote-definition-re) (setq column 0))
20515 ;; Literal examples
20516 ((looking-at "[ \t]*:\\( \\|$\\)")
20517 (setq column (org-get-indentation))) ; do nothing
20518 ;; Lists
20519 ((ignore-errors (goto-char (org-in-item-p)))
20520 (setq column (if itemp
20521 (org-get-indentation)
20522 (org-list-item-body-column (point))))
20523 (goto-char pos))
20524 ;; Drawers
20525 ((and (looking-at "[ \t]*:END:")
20526 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20527 (save-excursion
20528 (goto-char (1- (match-beginning 1)))
20529 (setq column (current-column))))
20530 ;; Special blocks
20531 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20532 (save-excursion
20533 (re-search-backward
20534 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20535 (setq column (org-get-indentation (match-string 0))))
20536 ((and (not (looking-at "[ \t]*#\\+begin_"))
20537 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20538 (save-excursion
20539 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20540 (setq column
20541 (cond ((equal (downcase (match-string 1)) "src")
20542 ;; src blocks: let `org-edit-src-exit' handle them
20543 (org-get-indentation))
20544 ((equal (downcase (match-string 1)) "example")
20545 (max (org-get-indentation)
20546 (org-get-indentation (match-string 0))))
20548 (org-get-indentation (match-string 0))))))
20549 ;; This line has nothing special, look at the previous relevant
20550 ;; line to compute indentation
20552 (beginning-of-line 0)
20553 (while (and (not (bobp))
20554 (not (looking-at org-drawer-regexp))
20555 ;; When point started in an inline task, do not move
20556 ;; above task starting line.
20557 (not (and inline-task-p (looking-at inline-re)))
20558 ;; Skip drawers, blocks, empty lines, verbatim,
20559 ;; comments, tables, footnotes definitions, lists,
20560 ;; inline tasks.
20561 (or (and (looking-at "[ \t]*:END:")
20562 (re-search-backward org-drawer-regexp nil t))
20563 (and (looking-at "[ \t]*#\\+end_")
20564 (re-search-backward "[ \t]*#\\+begin_"nil t))
20565 (looking-at "[ \t]*[\n:#|]")
20566 (looking-at org-footnote-definition-re)
20567 (and (ignore-errors (goto-char (org-in-item-p)))
20568 (goto-char
20569 (org-list-get-top-point (org-list-struct))))
20570 (and (not inline-task-p)
20571 (featurep 'org-inlinetask)
20572 (org-inlinetask-in-task-p)
20573 (or (org-inlinetask-goto-beginning) t))))
20574 (beginning-of-line 0))
20575 (cond
20576 ;; There was an heading above.
20577 ((looking-at "\\*+[ \t]+")
20578 (if (not org-adapt-indentation)
20579 (setq column 0)
20580 (goto-char (match-end 0))
20581 (setq column (current-column))))
20582 ;; A drawer had started and is unfinished
20583 ((looking-at org-drawer-regexp)
20584 (goto-char (1- (match-beginning 1)))
20585 (setq column (current-column)))
20586 ;; Else, nothing noticeable found: get indentation and go on.
20587 (t (setq column (org-get-indentation))))))
20588 ;; Now apply indentation and move cursor accordingly
20589 (goto-char pos)
20590 (if (<= (current-column) (current-indentation))
20591 (org-indent-line-to column)
20592 (save-excursion (org-indent-line-to column)))
20593 ;; Special polishing for properties, see `org-property-format'
20594 (setq column (current-column))
20595 (beginning-of-line 1)
20596 (if (looking-at
20597 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20598 (replace-match (concat (match-string 1)
20599 (format org-property-format
20600 (match-string 2) (match-string 3)))
20601 t t))
20602 (org-move-to-column column)
20603 (when (and orgstruct-is-++ (eq pos (point)))
20604 (org-let org-fb-vars
20605 '(indent-according-to-mode)))))
20607 (defun org-indent-drawer ()
20608 "Indent the drawer at point."
20609 (interactive)
20610 (let ((p (point))
20611 (e (and (save-excursion (re-search-forward ":END:" nil t))
20612 (match-end 0)))
20613 (folded
20614 (save-excursion
20615 (end-of-line)
20616 (when (overlays-at (point))
20617 (member 'invisible (overlay-properties
20618 (car (overlays-at (point)))))))))
20619 (when folded (org-cycle))
20620 (indent-for-tab-command)
20621 (while (and (move-beginning-of-line 2) (< (point) e))
20622 (indent-for-tab-command))
20623 (goto-char p)
20624 (when folded (org-cycle)))
20625 (message "Drawer at point indented"))
20627 (defun org-indent-block ()
20628 "Indent the block at point."
20629 (interactive)
20630 (let ((p (point))
20631 (case-fold-search t)
20632 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20633 (match-end 0)))
20634 (folded
20635 (save-excursion
20636 (end-of-line)
20637 (when (overlays-at (point))
20638 (member 'invisible (overlay-properties
20639 (car (overlays-at (point)))))))))
20640 (when folded (org-cycle))
20641 (indent-for-tab-command)
20642 (while (and (move-beginning-of-line 2) (< (point) e))
20643 (indent-for-tab-command))
20644 (goto-char p)
20645 (when folded (org-cycle)))
20646 (message "Block at point indented"))
20648 (defun org-indent-region (start end)
20649 "Indent region."
20650 (interactive "r")
20651 (save-excursion
20652 (let ((line-end (org-current-line end)))
20653 (goto-char start)
20654 (while (< (org-current-line) line-end)
20655 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20656 (t (call-interactively 'org-indent-line)))
20657 (move-beginning-of-line 2)))))
20659 ;; For reference, this is the default value of adaptive-fill-regexp
20660 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20661 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20662 "Variable to store copy of `adaptive-fill-regexp'.
20663 Since `adaptive-fill-regexp' is set to never match, we need to
20664 store a backup of its value before entering `org-mode' so that
20665 the functionality can be provided as a fall-back.")
20667 (defun org-set-autofill-regexps ()
20668 (interactive)
20669 ;; In the paragraph separator we include headlines, because filling
20670 ;; text in a line directly attached to a headline would otherwise
20671 ;; fill the headline as well.
20672 (org-set-local 'comment-start-skip "^#+[ \t]*")
20673 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20674 ;; The paragraph starter includes hand-formatted lists.
20675 (org-set-local
20676 'paragraph-start
20677 (concat
20678 "\f" "\\|"
20679 "[ ]*$" "\\|"
20680 org-outline-regexp "\\|"
20681 "[ \t]*#" "\\|"
20682 (org-item-re) "\\|"
20683 "[ \t]*[:|]" "\\|"
20684 "\\$\\$" "\\|"
20685 "\\\\\\(begin\\|end\\|[][]\\)"))
20686 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20687 ;; But only if the user has not turned off tables or fixed-width regions
20688 (org-set-local
20689 'auto-fill-inhibit-regexp
20690 (concat org-outline-regexp
20691 "\\|#\\+"
20692 "\\|[ \t]*" org-keyword-time-regexp
20693 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20694 (concat
20695 "\\|[ \t]*["
20696 (if org-enable-table-editor "|" "")
20697 (if org-enable-fixed-width-editor ":" "")
20698 "]"))))
20699 ;; We use our own fill-paragraph function, to make sure that tables
20700 ;; and fixed-width regions are not wrapped. That function will pass
20701 ;; through to `fill-paragraph' when appropriate.
20702 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20703 ;; Prevent auto-fill from inserting unwanted new items.
20704 (if (boundp 'fill-nobreak-predicate)
20705 (org-set-local
20706 'fill-nobreak-predicate
20707 (org-uniquify
20708 (append fill-nobreak-predicate
20709 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20710 ;; Adaptive filling: To get full control, first make sure that
20711 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20712 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20713 (org-set-local 'org-adaptive-fill-regexp-backup
20714 adaptive-fill-regexp))
20715 (org-set-local 'adaptive-fill-regexp "\000")
20716 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20717 (org-set-local 'adaptive-fill-function
20718 'org-adaptive-fill-function)
20719 (org-set-local
20720 'align-mode-rules-list
20721 '((org-in-buffer-settings
20722 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20723 (modes . '(org-mode))))))
20725 (defun org-fill-item-nobreak-p ()
20726 "Non-nil when a line break at point would insert a new item."
20727 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20729 (defun org-fill-line-break-nobreak-p ()
20730 "Non-nil when a line break at point would create an Org line break."
20731 (save-excursion
20732 (skip-chars-backward "[ \t]")
20733 (skip-chars-backward "\\\\")
20734 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20736 (defun org-fill-paragraph (&optional justify)
20737 "Re-align a table, pass through to fill-paragraph if no table."
20738 (let ((table-p (org-at-table-p))
20739 (table.el-p (org-at-table.el-p))
20740 (itemp (org-in-item-p))
20741 (srcp (org-in-src-block-p)))
20742 (cond ((and (equal (char-after (point-at-bol)) ?*)
20743 (save-excursion (goto-char (point-at-bol))
20744 (looking-at org-outline-regexp)))
20745 t) ; skip headlines
20746 (table.el-p t) ; skip table.el tables
20747 (table-p (org-table-align) t) ; align Org tables
20748 (srcp ; indent entire src block to prevent
20749 (save-excursion ; fill-paragraph-as-region to mess up
20750 (org-babel-do-in-edit-buffer
20751 (indent-region (point-min) (point-max)))))
20752 (itemp ; align text in items
20753 (let* ((struct (save-excursion (goto-char itemp)
20754 (org-list-struct)))
20755 (parents (org-list-parents-alist struct))
20756 (children (org-list-get-children itemp struct parents))
20757 beg end prev next prefix)
20758 ;; Determine in which part of item point is: before
20759 ;; first child, after last child, between two
20760 ;; sub-lists, or simply in item if there's no child.
20761 (cond
20762 ((not children)
20763 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20764 beg itemp
20765 end (org-list-get-item-end itemp struct)))
20766 ((< (point) (setq next (car children)))
20767 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20768 beg itemp
20769 end next))
20770 ((> (point) (setq prev (car (last children))))
20771 (setq beg (org-list-get-item-end prev struct)
20772 end (org-list-get-item-end itemp struct)
20773 prefix (save-excursion
20774 (goto-char beg)
20775 (skip-chars-forward " \t")
20776 (make-string (current-column) ?\ ))))
20777 (t (catch 'exit
20778 (while (setq next (pop children))
20779 (if (> (point) next)
20780 (setq prev next)
20781 (setq beg (org-list-get-item-end prev struct)
20782 end next
20783 prefix (save-excursion
20784 (goto-char beg)
20785 (skip-chars-forward " \t")
20786 (make-string (current-column) ?\ )))
20787 (throw 'exit nil))))))
20788 ;; Use `fill-paragraph' with buffer narrowed to item
20789 ;; without any child, and with our computed PREFIX.
20790 (org-flet ((fill-context-prefix (from to &optional flr) prefix))
20791 (save-restriction
20792 (narrow-to-region beg end)
20793 (save-excursion (fill-paragraph justify)))) t))
20794 ;; Special case where point is not in a list but is on
20795 ;; a paragraph adjacent to a list: make sure this paragraph
20796 ;; doesn't get merged with the end of the list by narrowing
20797 ;; buffer first.
20798 ((and (derived-mode-p 'org-mode)
20799 (save-excursion (forward-paragraph -1)
20800 (setq itemp (org-in-item-p))))
20801 (let ((struct (save-excursion (goto-char itemp)
20802 (org-list-struct))))
20803 (save-restriction
20804 (narrow-to-region (org-list-get-bottom-point struct)
20805 (save-excursion (forward-paragraph 1)
20806 (point)))
20807 (fill-paragraph justify) t)))
20808 ;; Don't fill schedule/deadline line before a paragraph
20809 ;; This only makes sense in real org-mode buffers
20810 ((and (eq major-mode 'org-mode)
20811 (save-excursion (forward-paragraph -1)
20812 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20813 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$")))))
20814 (save-restriction
20815 (narrow-to-region (1+ (match-end 0))
20816 (save-excursion (forward-paragraph 1) (point)))
20817 (fill-paragraph justify) t))
20818 ;; Else fall back on fill-paragraph-function as possibly
20819 ;; defined in `org-fb-vars'
20820 (orgstruct-is-++
20821 (org-let org-fb-vars
20822 '(fill-paragraph justify)))
20823 (t nil))))
20825 (defun org-adaptive-fill-function ()
20826 "Return a fill prefix for org-mode files."
20827 (let (itemp)
20828 (save-excursion
20829 (cond
20830 ;; Comment line
20831 ((looking-at "#[ \t]+")
20832 (match-string-no-properties 0))
20833 ;; Plain list item
20834 ((org-at-item-p)
20835 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20836 ;; Point is in a list after `backward-paragraph': original
20837 ;; point wasn't in the list, or filling would have been taken
20838 ;; care of by `org-auto-fill-function', but the list and the
20839 ;; real paragraph are not separated by a blank line. Thus, move
20840 ;; point after the list to go back to real paragraph and
20841 ;; determine fill-prefix.
20842 ((setq itemp (org-in-item-p))
20843 (goto-char itemp)
20844 (let* ((struct (org-list-struct))
20845 (bottom (org-list-get-bottom-point struct)))
20846 (goto-char bottom)
20847 (make-string (org-get-indentation) ?\ )))
20848 ;; Other text
20849 ((looking-at org-adaptive-fill-regexp-backup)
20850 (match-string-no-properties 0))))))
20852 (defun org-auto-fill-function ()
20853 "Auto-fill function."
20854 (unless (and org-src-prevent-auto-filling (org-in-src-block-p))
20855 (let (itemp prefix)
20856 ;; When in a list, compute an appropriate fill-prefix and make
20857 ;; sure it will be used by `do-auto-fill'.
20858 (cond ((setq itemp (org-in-item-p))
20859 (progn
20860 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20861 (org-flet ((fill-context-prefix (from to &optional flr) prefix))
20862 (do-auto-fill))))
20863 (orgstruct-is-++
20864 (org-let org-fb-vars
20865 '(do-auto-fill)))
20866 (t (do-auto-fill))))))
20868 ;;; Other stuff.
20870 (defun org-toggle-fixed-width-section (arg)
20871 "Toggle the fixed-width export.
20872 If there is no active region, the QUOTE keyword at the current headline is
20873 inserted or removed. When present, it causes the text between this headline
20874 and the next to be exported as fixed-width text, and unmodified.
20875 If there is an active region, this command adds or removes a colon as the
20876 first character of this line. If the first character of a line is a colon,
20877 this line is also exported in fixed-width font."
20878 (interactive "P")
20879 (let* ((cc 0)
20880 (regionp (org-region-active-p))
20881 (beg (if regionp (region-beginning) (point)))
20882 (end (if regionp (region-end)))
20883 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20884 (case-fold-search nil)
20885 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20886 off)
20887 (if regionp
20888 (save-excursion
20889 (goto-char beg)
20890 (setq cc (current-column))
20891 (beginning-of-line 1)
20892 (setq off (looking-at re))
20893 (while (> nlines 0)
20894 (setq nlines (1- nlines))
20895 (beginning-of-line 1)
20896 (cond
20897 (arg
20898 (org-move-to-column cc t)
20899 (insert ": \n")
20900 (forward-line -1))
20901 ((and off (looking-at re))
20902 (replace-match "" t t nil 1))
20903 ((not off) (org-move-to-column cc t) (insert ": ")))
20904 (forward-line 1)))
20905 (save-excursion
20906 (org-back-to-heading)
20907 (cond
20908 ((looking-at (format org-heading-keyword-regexp-format
20909 org-quote-string))
20910 (goto-char (match-end 1))
20911 (looking-at (concat " +" org-quote-string))
20912 (replace-match "" t t)
20913 (when (eolp) (insert " ")))
20914 ((looking-at org-outline-regexp)
20915 (goto-char (match-end 0))
20916 (insert org-quote-string " ")))))))
20918 (defun org-reftex-citation ()
20919 "Use reftex-citation to insert a citation into the buffer.
20920 This looks for a line like
20922 #+BIBLIOGRAPHY: foo plain option:-d
20924 and derives from it that foo.bib is the bibliography file relevant
20925 for this document. It then installs the necessary environment for RefTeX
20926 to work in this buffer and calls `reftex-citation' to insert a citation
20927 into the buffer.
20929 Export of such citations to both LaTeX and HTML is handled by the contributed
20930 package org-exp-bibtex by Taru Karttunen."
20931 (interactive)
20932 (let ((reftex-docstruct-symbol 'rds)
20933 (reftex-cite-format "\\cite{%l}")
20934 rds bib)
20935 (save-excursion
20936 (save-restriction
20937 (widen)
20938 (let ((case-fold-search t)
20939 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20940 (if (not (save-excursion
20941 (or (re-search-forward re nil t)
20942 (re-search-backward re nil t))))
20943 (error "No bibliography defined in file")
20944 (setq bib (concat (match-string 1) ".bib")
20945 rds (list (list 'bib bib)))))))
20946 (call-interactively 'reftex-citation)))
20948 ;;;; Functions extending outline functionality
20950 (defun org-beginning-of-line (&optional arg)
20951 "Go to the beginning of the current line. If that is invisible, continue
20952 to a visible line beginning. This makes the function of C-a more intuitive.
20953 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20954 first attempt, and only move to after the tags when the cursor is already
20955 beyond the end of the headline."
20956 (interactive "P")
20957 (let ((pos (point))
20958 (special (if (consp org-special-ctrl-a/e)
20959 (car org-special-ctrl-a/e)
20960 org-special-ctrl-a/e))
20961 refpos)
20962 (if (org-bound-and-true-p line-move-visual)
20963 (beginning-of-visual-line 1)
20964 (beginning-of-line 1))
20965 (if (and arg (fboundp 'move-beginning-of-line))
20966 (call-interactively 'move-beginning-of-line)
20967 (if (bobp)
20969 (backward-char 1)
20970 (if (org-truely-invisible-p)
20971 (while (and (not (bobp)) (org-truely-invisible-p))
20972 (backward-char 1)
20973 (beginning-of-line 1))
20974 (forward-char 1))))
20975 (when special
20976 (cond
20977 ((and (looking-at org-complex-heading-regexp)
20978 (= (char-after (match-end 1)) ?\ ))
20979 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20980 (point-at-eol)))
20981 (goto-char
20982 (if (eq special t)
20983 (cond ((> pos refpos) refpos)
20984 ((= pos (point)) refpos)
20985 (t (point)))
20986 (cond ((> pos (point)) (point))
20987 ((not (eq last-command this-command)) (point))
20988 (t refpos)))))
20989 ((org-at-item-p)
20990 ;; Being at an item and not looking at an the item means point
20991 ;; was previously moved to beginning of a visual line, which
20992 ;; doesn't contain the item. Therefore, do nothing special,
20993 ;; just stay here.
20994 (when (looking-at org-list-full-item-re)
20995 ;; Set special position at first white space character after
20996 ;; bullet, and check-box, if any.
20997 (let ((after-bullet
20998 (let ((box (match-end 3)))
20999 (if (not box) (match-end 1)
21000 (let ((after (char-after box)))
21001 (if (and after (= after ? )) (1+ box) box))))))
21002 ;; Special case: Move point to special position when
21003 ;; currently after it or at beginning of line.
21004 (if (eq special t)
21005 (when (or (> pos after-bullet) (= (point) pos))
21006 (goto-char after-bullet))
21007 ;; Reversed case: Move point to special position when
21008 ;; point was already at beginning of line and command is
21009 ;; repeated.
21010 (when (and (= (point) pos) (eq last-command this-command))
21011 (goto-char after-bullet))))))))
21012 (org-no-warnings
21013 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21015 (defun org-end-of-line (&optional arg)
21016 "Go to the end of the line.
21017 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21018 first attempt, and only move to after the tags when the cursor is already
21019 beyond the end of the headline."
21020 (interactive "P")
21021 (let ((special (if (consp org-special-ctrl-a/e)
21022 (cdr org-special-ctrl-a/e)
21023 org-special-ctrl-a/e)))
21024 (cond
21025 ((or (not special) arg
21026 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21027 (call-interactively
21028 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21029 ((fboundp 'move-end-of-line) 'move-end-of-line)
21030 (t 'end-of-line))))
21031 ((org-at-heading-p)
21032 (let ((pos (point)))
21033 (beginning-of-line 1)
21034 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21035 (if (eq special t)
21036 (if (or (< pos (match-beginning 1))
21037 (= pos (match-end 0)))
21038 (goto-char (match-beginning 1))
21039 (goto-char (match-end 0)))
21040 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21041 (goto-char (match-end 0))
21042 (goto-char (match-beginning 1))))
21043 (call-interactively (if (fboundp 'move-end-of-line)
21044 'move-end-of-line
21045 'end-of-line)))))
21046 ((org-at-drawer-p)
21047 (move-end-of-line 1)
21048 (when (overlays-at (1- (point))) (backward-char 1)))
21049 ;; At an item: Move before any hidden text.
21050 (t (call-interactively
21051 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21052 ((fboundp 'move-end-of-line) 'move-end-of-line)
21053 (t 'end-of-line)))))
21054 (org-no-warnings
21055 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21057 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21058 (define-key org-mode-map "\C-e" 'org-end-of-line)
21060 (defun org-backward-sentence (&optional arg)
21061 "Go to beginning of sentence, or beginning of table field.
21062 This will call `backward-sentence' or `org-table-beginning-of-field',
21063 depending on context."
21064 (interactive "P")
21065 (cond
21066 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21067 (t (call-interactively 'backward-sentence))))
21069 (defun org-forward-sentence (&optional arg)
21070 "Go to end of sentence, or end of table field.
21071 This will call `forward-sentence' or `org-table-end-of-field',
21072 depending on context."
21073 (interactive "P")
21074 (cond
21075 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21076 (t (call-interactively 'forward-sentence))))
21078 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21079 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21081 (defun org-kill-line (&optional arg)
21082 "Kill line, to tags or end of line."
21083 (interactive "P")
21084 (cond
21085 ((or (not org-special-ctrl-k)
21086 (bolp)
21087 (not (org-at-heading-p)))
21088 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21089 org-ctrl-k-protect-subtree)
21090 (if (or (eq org-ctrl-k-protect-subtree 'error)
21091 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21092 (error "C-k aborted - would kill hidden subtree")))
21093 (call-interactively
21094 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21095 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21096 (kill-region (point) (match-beginning 1))
21097 (org-set-tags nil t))
21098 (t (kill-region (point) (point-at-eol)))))
21100 (define-key org-mode-map "\C-k" 'org-kill-line)
21102 (defun org-yank (&optional arg)
21103 "Yank. If the kill is a subtree, treat it specially.
21104 This command will look at the current kill and check if is a single
21105 subtree, or a series of subtrees[1]. If it passes the test, and if the
21106 cursor is at the beginning of a line or after the stars of a currently
21107 empty headline, then the yank is handled specially. How exactly depends
21108 on the value of the following variables, both set by default.
21110 org-yank-folded-subtrees
21111 When set, the subtree(s) will be folded after insertion, but only
21112 if doing so would now swallow text after the yanked text.
21114 org-yank-adjusted-subtrees
21115 When set, the subtree will be promoted or demoted in order to
21116 fit into the local outline tree structure, which means that the level
21117 will be adjusted so that it becomes the smaller one of the two
21118 *visible* surrounding headings.
21120 Any prefix to this command will cause `yank' to be called directly with
21121 no special treatment. In particular, a simple \\[universal-argument] prefix \
21122 will just
21123 plainly yank the text as it is.
21125 \[1] The test checks if the first non-white line is a heading
21126 and if there are no other headings with fewer stars."
21127 (interactive "P")
21128 (org-yank-generic 'yank arg))
21130 (defun org-yank-generic (command arg)
21131 "Perform some yank-like command.
21133 This function implements the behavior described in the `org-yank'
21134 documentation. However, it has been generalized to work for any
21135 interactive command with similar behavior."
21137 ;; pretend to be command COMMAND
21138 (setq this-command command)
21140 (if arg
21141 (call-interactively command)
21143 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21144 (and (org-kill-is-subtree-p)
21145 (or (bolp)
21146 (and (looking-at "[ \t]*$")
21147 (string-match
21148 "\\`\\*+\\'"
21149 (buffer-substring (point-at-bol) (point)))))))
21150 swallowp)
21151 (cond
21152 ((and subtreep org-yank-folded-subtrees)
21153 (let ((beg (point))
21154 end)
21155 (if (and subtreep org-yank-adjusted-subtrees)
21156 (org-paste-subtree nil nil 'for-yank)
21157 (call-interactively command))
21159 (setq end (point))
21160 (goto-char beg)
21161 (when (and (bolp) subtreep
21162 (not (setq swallowp
21163 (org-yank-folding-would-swallow-text beg end))))
21164 (org-with-limited-levels
21165 (or (looking-at org-outline-regexp)
21166 (re-search-forward org-outline-regexp-bol end t))
21167 (while (and (< (point) end) (looking-at org-outline-regexp))
21168 (hide-subtree)
21169 (org-cycle-show-empty-lines 'folded)
21170 (condition-case nil
21171 (outline-forward-same-level 1)
21172 (error (goto-char end))))))
21173 (when swallowp
21174 (message
21175 "Inserted text not folded because that would swallow text"))
21177 (goto-char end)
21178 (skip-chars-forward " \t\n\r")
21179 (beginning-of-line 1)
21180 (push-mark beg 'nomsg)))
21181 ((and subtreep org-yank-adjusted-subtrees)
21182 (let ((beg (point-at-bol)))
21183 (org-paste-subtree nil nil 'for-yank)
21184 (push-mark beg 'nomsg)))
21186 (call-interactively command))))))
21188 (defun org-yank-folding-would-swallow-text (beg end)
21189 "Would hide-subtree at BEG swallow any text after END?"
21190 (let (level)
21191 (org-with-limited-levels
21192 (save-excursion
21193 (goto-char beg)
21194 (when (or (looking-at org-outline-regexp)
21195 (re-search-forward org-outline-regexp-bol end t))
21196 (setq level (org-outline-level)))
21197 (goto-char end)
21198 (skip-chars-forward " \t\r\n\v\f")
21199 (if (or (eobp)
21200 (and (bolp) (looking-at org-outline-regexp)
21201 (<= (org-outline-level) level)))
21202 nil ; Nothing would be swallowed
21203 t))))) ; something would swallow
21205 (define-key org-mode-map "\C-y" 'org-yank)
21207 (defun org-truely-invisible-p ()
21208 "Check if point is at a character currently not visible.
21209 This version does not only check the character property, but also
21210 `visible-mode'."
21211 ;; Early versions of noutline don't have `outline-invisible-p'.
21212 (if (org-bound-and-true-p visible-mode)
21214 (outline-invisible-p)))
21216 (defun org-invisible-p2 ()
21217 "Check if point is at a character currently not visible."
21218 (save-excursion
21219 (if (and (eolp) (not (bobp))) (backward-char 1))
21220 ;; Early versions of noutline don't have `outline-invisible-p'.
21221 (outline-invisible-p)))
21223 (defun org-back-to-heading (&optional invisible-ok)
21224 "Call `outline-back-to-heading', but provide a better error message."
21225 (condition-case nil
21226 (outline-back-to-heading invisible-ok)
21227 (error (error "Before first headline at position %d in buffer %s"
21228 (point) (current-buffer)))))
21230 (defun org-beginning-of-defun ()
21231 "Go to the beginning of the subtree, i.e. back to the heading."
21232 (org-back-to-heading))
21233 (defun org-end-of-defun ()
21234 "Go to the end of the subtree."
21235 (org-end-of-subtree nil t))
21237 (defun org-before-first-heading-p ()
21238 "Before first heading?"
21239 (save-excursion
21240 (end-of-line)
21241 (null (re-search-backward org-outline-regexp-bol nil t))))
21243 (defun org-at-heading-p (&optional ignored)
21244 (outline-on-heading-p t))
21245 ;; Compatibility alias with Org versions < 7.8.03
21246 (defalias 'org-on-heading-p 'org-at-heading-p)
21248 (defun org-at-comment-p nil
21249 "Is cursor in a line starting with a # character?"
21250 (save-excursion
21251 (beginning-of-line)
21252 (looking-at "^#")))
21254 (defun org-at-drawer-p nil
21255 "Is cursor at a drawer keyword?"
21256 (save-excursion
21257 (move-beginning-of-line 1)
21258 (looking-at org-drawer-regexp)))
21260 (defun org-at-block-p nil
21261 "Is cursor at a block keyword?"
21262 (save-excursion
21263 (move-beginning-of-line 1)
21264 (looking-at org-block-regexp)))
21266 (defun org-point-at-end-of-empty-headline ()
21267 "If point is at the end of an empty headline, return t, else nil.
21268 If the heading only contains a TODO keyword, it is still still considered
21269 empty."
21270 (and (looking-at "[ \t]*$")
21271 (when org-todo-line-regexp
21272 (save-excursion
21273 (beginning-of-line 1)
21274 (let ((case-fold-search nil))
21275 (looking-at org-todo-line-regexp)
21276 (string= (match-string 3) ""))))))
21278 (defun org-at-heading-or-item-p ()
21279 (or (org-at-heading-p) (org-at-item-p)))
21281 (defun org-at-target-p ()
21282 (or (org-in-regexp org-radio-target-regexp)
21283 (org-in-regexp org-target-regexp)))
21284 ;; Compatibility alias with Org versions < 7.8.03
21285 (defalias 'org-on-target-p 'org-at-target-p)
21287 (defun org-up-heading-all (arg)
21288 "Move to the heading line of which the present line is a subheading.
21289 This function considers both visible and invisible heading lines.
21290 With argument, move up ARG levels."
21291 (if (fboundp 'outline-up-heading-all)
21292 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21293 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21295 (defun org-up-heading-safe ()
21296 "Move to the heading line of which the present line is a subheading.
21297 This version will not throw an error. It will return the level of the
21298 headline found, or nil if no higher level is found.
21300 Also, this function will be a lot faster than `outline-up-heading',
21301 because it relies on stars being the outline starters. This can really
21302 make a significant difference in outlines with very many siblings."
21303 (let (start-level re)
21304 (org-back-to-heading t)
21305 (setq start-level (funcall outline-level))
21306 (if (equal start-level 1)
21308 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21309 (if (re-search-backward re nil t)
21310 (funcall outline-level)))))
21312 (defun org-first-sibling-p ()
21313 "Is this heading the first child of its parents?"
21314 (interactive)
21315 (let ((re org-outline-regexp-bol)
21316 level l)
21317 (unless (org-at-heading-p t)
21318 (error "Not at a heading"))
21319 (setq level (funcall outline-level))
21320 (save-excursion
21321 (if (not (re-search-backward re nil t))
21323 (setq l (funcall outline-level))
21324 (< l level)))))
21326 (defun org-goto-sibling (&optional previous)
21327 "Goto the next sibling, even if it is invisible.
21328 When PREVIOUS is set, go to the previous sibling instead. Returns t
21329 when a sibling was found. When none is found, return nil and don't
21330 move point."
21331 (let ((fun (if previous 're-search-backward 're-search-forward))
21332 (pos (point))
21333 (re org-outline-regexp-bol)
21334 level l)
21335 (when (condition-case nil (org-back-to-heading t) (error nil))
21336 (setq level (funcall outline-level))
21337 (catch 'exit
21338 (or previous (forward-char 1))
21339 (while (funcall fun re nil t)
21340 (setq l (funcall outline-level))
21341 (when (< l level) (goto-char pos) (throw 'exit nil))
21342 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21343 (goto-char pos)
21344 nil))))
21346 (defun org-show-siblings ()
21347 "Show all siblings of the current headline."
21348 (save-excursion
21349 (while (org-goto-sibling) (org-flag-heading nil)))
21350 (save-excursion
21351 (while (org-goto-sibling 'previous)
21352 (org-flag-heading nil))))
21354 (defun org-goto-first-child ()
21355 "Goto the first child, even if it is invisible.
21356 Return t when a child was found. Otherwise don't move point and
21357 return nil."
21358 (let (level (pos (point)) (re org-outline-regexp-bol))
21359 (when (condition-case nil (org-back-to-heading t) (error nil))
21360 (setq level (outline-level))
21361 (forward-char 1)
21362 (if (and (re-search-forward re nil t) (> (outline-level) level))
21363 (progn (goto-char (match-beginning 0)) t)
21364 (goto-char pos) nil))))
21366 (defun org-show-hidden-entry ()
21367 "Show an entry where even the heading is hidden."
21368 (save-excursion
21369 (org-show-entry)))
21371 (defun org-flag-heading (flag &optional entry)
21372 "Flag the current heading. FLAG non-nil means make invisible.
21373 When ENTRY is non-nil, show the entire entry."
21374 (save-excursion
21375 (org-back-to-heading t)
21376 ;; Check if we should show the entire entry
21377 (if entry
21378 (progn
21379 (org-show-entry)
21380 (save-excursion
21381 (and (outline-next-heading)
21382 (org-flag-heading nil))))
21383 (outline-flag-region (max (point-min) (1- (point)))
21384 (save-excursion (outline-end-of-heading) (point))
21385 flag))))
21387 (defun org-get-next-sibling ()
21388 "Move to next heading of the same level, and return point.
21389 If there is no such heading, return nil.
21390 This is like outline-next-sibling, but invisible headings are ok."
21391 (let ((level (funcall outline-level)))
21392 (outline-next-heading)
21393 (while (and (not (eobp)) (> (funcall outline-level) level))
21394 (outline-next-heading))
21395 (if (or (eobp) (< (funcall outline-level) level))
21397 (point))))
21399 (defun org-get-last-sibling ()
21400 "Move to previous heading of the same level, and return point.
21401 If there is no such heading, return nil."
21402 (let ((opoint (point))
21403 (level (funcall outline-level)))
21404 (outline-previous-heading)
21405 (when (and (/= (point) opoint) (outline-on-heading-p t))
21406 (while (and (> (funcall outline-level) level)
21407 (not (bobp)))
21408 (outline-previous-heading))
21409 (if (< (funcall outline-level) level)
21411 (point)))))
21413 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21414 ;; This contains an exact copy of the original function, but it uses
21415 ;; `org-back-to-heading', to make it work also in invisible
21416 ;; trees. And is uses an invisible-OK argument.
21417 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21418 ;; Furthermore, when used inside Org, finding the end of a large subtree
21419 ;; with many children and grandchildren etc, this can be much faster
21420 ;; than the outline version.
21421 (org-back-to-heading invisible-OK)
21422 (let ((first t)
21423 (level (funcall outline-level)))
21424 (if (and (derived-mode-p 'org-mode) (< level 1000))
21425 ;; A true heading (not a plain list item), in Org-mode
21426 ;; This means we can easily find the end by looking
21427 ;; only for the right number of stars. Using a regexp to do
21428 ;; this is so much faster than using a Lisp loop.
21429 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21430 (forward-char 1)
21431 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21432 ;; something else, do it the slow way
21433 (while (and (not (eobp))
21434 (or first (> (funcall outline-level) level)))
21435 (setq first nil)
21436 (outline-next-heading)))
21437 (unless to-heading
21438 (if (memq (preceding-char) '(?\n ?\^M))
21439 (progn
21440 ;; Go to end of line before heading
21441 (forward-char -1)
21442 (if (memq (preceding-char) '(?\n ?\^M))
21443 ;; leave blank line before heading
21444 (forward-char -1))))))
21445 (point))
21447 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21448 "Use Org version in org-mode, for dramatic speed-up."
21449 (if (derived-mode-p 'org-mode)
21450 (progn
21451 (org-end-of-subtree nil t)
21452 (unless (eobp) (backward-char 1)))
21453 ad-do-it))
21455 (defun org-end-of-meta-data-and-drawers ()
21456 "Jump to the first text after meta data and drawers in the current entry.
21457 This will move over empty lines, lines with planning time stamps,
21458 clocking lines, and drawers."
21459 (org-back-to-heading t)
21460 (let ((end (save-excursion (outline-next-heading) (point)))
21461 (re (concat "\\(" org-drawer-regexp "\\)"
21462 "\\|" "[ \t]*" org-keyword-time-regexp)))
21463 (forward-line 1)
21464 (while (re-search-forward re end t)
21465 (if (not (match-end 1))
21466 ;; empty or planning line
21467 (forward-line 1)
21468 ;; a drawer, find the end
21469 (re-search-forward "^[ \t]*:END:" end 'move)
21470 (forward-line 1)))
21471 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21472 (point)))
21474 (defun org-forward-same-level (arg &optional invisible-ok)
21475 "Move forward to the arg'th subheading at same level as this one.
21476 Stop at the first and last subheadings of a superior heading.
21477 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21478 it wil also look at invisible ones."
21479 (interactive "p")
21480 (org-back-to-heading invisible-ok)
21481 (org-at-heading-p)
21482 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21483 (re (format "^\\*\\{1,%d\\} " level))
21485 (forward-char 1)
21486 (while (> arg 0)
21487 (while (and (re-search-forward re nil 'move)
21488 (setq l (- (match-end 0) (match-beginning 0) 1))
21489 (= l level)
21490 (not invisible-ok)
21491 (progn (backward-char 1) (outline-invisible-p)))
21492 (if (< l level) (setq arg 1)))
21493 (setq arg (1- arg)))
21494 (beginning-of-line 1)))
21496 (defun org-backward-same-level (arg &optional invisible-ok)
21497 "Move backward to the arg'th subheading at same level as this one.
21498 Stop at the first and last subheadings of a superior heading."
21499 (interactive "p")
21500 (org-back-to-heading)
21501 (org-at-heading-p)
21502 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21503 (re (format "^\\*\\{1,%d\\} " level))
21505 (while (> arg 0)
21506 (while (and (re-search-backward re nil 'move)
21507 (setq l (- (match-end 0) (match-beginning 0) 1))
21508 (= l level)
21509 (not invisible-ok)
21510 (outline-invisible-p))
21511 (if (< l level) (setq arg 1)))
21512 (setq arg (1- arg)))))
21514 (defun org-show-subtree ()
21515 "Show everything after this heading at deeper levels."
21516 (interactive)
21517 (outline-flag-region
21518 (point)
21519 (save-excursion
21520 (org-end-of-subtree t t))
21521 nil))
21523 (defun org-show-entry ()
21524 "Show the body directly following this heading.
21525 Show the heading too, if it is currently invisible."
21526 (interactive)
21527 (save-excursion
21528 (condition-case nil
21529 (progn
21530 (org-back-to-heading t)
21531 (outline-flag-region
21532 (max (point-min) (1- (point)))
21533 (save-excursion
21534 (if (re-search-forward
21535 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21536 (match-beginning 1)
21537 (point-max)))
21538 nil)
21539 (org-cycle-hide-drawers 'children))
21540 (error nil))))
21542 (defun org-make-options-regexp (kwds &optional extra)
21543 "Make a regular expression for keyword lines."
21544 (concat
21546 "#?[ \t]*\\+\\("
21547 (mapconcat 'regexp-quote kwds "\\|")
21548 (if extra (concat "\\|" extra))
21549 "\\):[ \t]*"
21550 "\\(.*\\)"))
21552 ;; Make isearch reveal the necessary context
21553 (defun org-isearch-end ()
21554 "Reveal context after isearch exits."
21555 (when isearch-success ; only if search was successful
21556 (if (featurep 'xemacs)
21557 ;; Under XEmacs, the hook is run in the correct place,
21558 ;; we directly show the context.
21559 (org-show-context 'isearch)
21560 ;; In Emacs the hook runs *before* restoring the overlays.
21561 ;; So we have to use a one-time post-command-hook to do this.
21562 ;; (Emacs 22 has a special variable, see function `org-mode')
21563 (unless (and (boundp 'isearch-mode-end-hook-quit)
21564 isearch-mode-end-hook-quit)
21565 ;; Only when the isearch was not quitted.
21566 (org-add-hook 'post-command-hook 'org-isearch-post-command
21567 'append 'local)))))
21569 (defun org-isearch-post-command ()
21570 "Remove self from hook, and show context."
21571 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21572 (org-show-context 'isearch))
21575 ;;;; Integration with and fixes for other packages
21577 ;;; Imenu support
21579 (defvar org-imenu-markers nil
21580 "All markers currently used by Imenu.")
21581 (make-variable-buffer-local 'org-imenu-markers)
21583 (defun org-imenu-new-marker (&optional pos)
21584 "Return a new marker for use by Imenu, and remember the marker."
21585 (let ((m (make-marker)))
21586 (move-marker m (or pos (point)))
21587 (push m org-imenu-markers)
21590 (defun org-imenu-get-tree ()
21591 "Produce the index for Imenu."
21592 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21593 (setq org-imenu-markers nil)
21594 (let* ((n org-imenu-depth)
21595 (re (concat "^" (org-get-limited-outline-regexp)))
21596 (subs (make-vector (1+ n) nil))
21597 (last-level 0)
21598 m level head)
21599 (save-excursion
21600 (save-restriction
21601 (widen)
21602 (goto-char (point-max))
21603 (while (re-search-backward re nil t)
21604 (setq level (org-reduced-level (funcall outline-level)))
21605 (when (and (<= level n)
21606 (looking-at org-complex-heading-regexp))
21607 (setq head (org-link-display-format
21608 (org-match-string-no-properties 4))
21609 m (org-imenu-new-marker))
21610 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21611 (if (>= level last-level)
21612 (push (cons head m) (aref subs level))
21613 (push (cons head (aref subs (1+ level))) (aref subs level))
21614 (loop for i from (1+ level) to n do (aset subs i nil)))
21615 (setq last-level level)))))
21616 (aref subs 1)))
21618 (eval-after-load "imenu"
21619 '(progn
21620 (add-hook 'imenu-after-jump-hook
21621 (lambda ()
21622 (if (derived-mode-p 'org-mode)
21623 (org-show-context 'org-goto))))))
21625 (defun org-link-display-format (link)
21626 "Replace a link with either the description, or the link target
21627 if no description is present"
21628 (save-match-data
21629 (if (string-match org-bracket-link-analytic-regexp link)
21630 (replace-match (if (match-end 5)
21631 (match-string 5 link)
21632 (concat (match-string 1 link)
21633 (match-string 3 link)))
21634 nil t link)
21635 link)))
21637 (defun org-toggle-link-display ()
21638 "Toggle the literal or descriptive display of links."
21639 (interactive)
21640 (if org-descriptive-links
21641 (progn (org-remove-from-invisibility-spec '(org-link))
21642 (org-restart-font-lock)
21643 (setq org-descriptive-links nil))
21644 (progn (add-to-invisibility-spec '(org-link))
21645 (org-restart-font-lock)
21646 (setq org-descriptive-links t))))
21648 ;; Speedbar support
21650 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21651 "Overlay marking the agenda restriction line in speedbar.")
21652 (overlay-put org-speedbar-restriction-lock-overlay
21653 'face 'org-agenda-restriction-lock)
21654 (overlay-put org-speedbar-restriction-lock-overlay
21655 'help-echo "Agendas are currently limited to this item.")
21656 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21658 (defun org-speedbar-set-agenda-restriction ()
21659 "Restrict future agenda commands to the location at point in speedbar.
21660 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21661 (interactive)
21662 (require 'org-agenda)
21663 (let (p m tp np dir txt)
21664 (cond
21665 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21666 'org-imenu t))
21667 (setq m (get-text-property p 'org-imenu-marker))
21668 (with-current-buffer (marker-buffer m)
21669 (goto-char m)
21670 (org-agenda-set-restriction-lock 'subtree)))
21671 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21672 'speedbar-function 'speedbar-find-file))
21673 (setq tp (previous-single-property-change
21674 (1+ p) 'speedbar-function)
21675 np (next-single-property-change
21676 tp 'speedbar-function)
21677 dir (speedbar-line-directory)
21678 txt (buffer-substring-no-properties (or tp (point-min))
21679 (or np (point-max))))
21680 (with-current-buffer (find-file-noselect
21681 (let ((default-directory dir))
21682 (expand-file-name txt)))
21683 (unless (derived-mode-p 'org-mode)
21684 (error "Cannot restrict to non-Org-mode file"))
21685 (org-agenda-set-restriction-lock 'file)))
21686 (t (error "Don't know how to restrict Org-mode's agenda")))
21687 (move-overlay org-speedbar-restriction-lock-overlay
21688 (point-at-bol) (point-at-eol))
21689 (setq current-prefix-arg nil)
21690 (org-agenda-maybe-redo)))
21692 (eval-after-load "speedbar"
21693 '(progn
21694 (speedbar-add-supported-extension ".org")
21695 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21696 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21697 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21698 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21699 (add-hook 'speedbar-visiting-tag-hook
21700 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
21702 ;;; Fixes and Hacks for problems with other packages
21704 ;; Make flyspell not check words in links, to not mess up our keymap
21705 (defun org-mode-flyspell-verify ()
21706 "Don't let flyspell put overlays at active buttons, or on
21707 {todo,all-time,additional-option-like}-keywords."
21708 (let ((pos (max (1- (point)) (point-min)))
21709 (word (thing-at-point 'word)))
21710 (and (not (get-text-property pos 'keymap))
21711 (not (get-text-property pos 'org-no-flyspell))
21712 (not (member word org-todo-keywords-1))
21713 (not (member word org-all-time-keywords))
21714 (not (member word org-additional-option-like-keywords)))))
21716 (defun org-remove-flyspell-overlays-in (beg end)
21717 "Remove flyspell overlays in region."
21718 (and (org-bound-and-true-p flyspell-mode)
21719 (fboundp 'flyspell-delete-region-overlays)
21720 (flyspell-delete-region-overlays beg end))
21721 (add-text-properties beg end '(org-no-flyspell t)))
21723 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21724 (eval-after-load "bookmark"
21725 '(if (boundp 'bookmark-after-jump-hook)
21726 ;; We can use the hook
21727 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21728 ;; Hook not available, use advice
21729 (defadvice bookmark-jump (after org-make-visible activate)
21730 "Make the position visible."
21731 (org-bookmark-jump-unhide))))
21733 ;; Make sure saveplace shows the location if it was hidden
21734 (eval-after-load "saveplace"
21735 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21736 "Make the position visible."
21737 (org-bookmark-jump-unhide)))
21739 ;; Make sure ecb shows the location if it was hidden
21740 (eval-after-load "ecb"
21741 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21742 "Make hierarchy visible when jumping into location from ECB tree buffer."
21743 (if (derived-mode-p 'org-mode)
21744 (org-show-context))))
21746 (defun org-bookmark-jump-unhide ()
21747 "Unhide the current position, to show the bookmark location."
21748 (and (derived-mode-p 'org-mode)
21749 (or (outline-invisible-p)
21750 (save-excursion (goto-char (max (point-min) (1- (point))))
21751 (outline-invisible-p)))
21752 (org-show-context 'bookmark-jump)))
21754 ;; Make session.el ignore our circular variable
21755 (eval-after-load "session"
21756 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21758 ;;;; Experimental code
21760 (defun org-closed-in-range ()
21761 "Sparse tree of items closed in a certain time range.
21762 Still experimental, may disappear in the future."
21763 (interactive)
21764 ;; Get the time interval from the user.
21765 (let* ((time1 (org-float-time
21766 (org-read-date nil 'to-time nil "Starting date: ")))
21767 (time2 (org-float-time
21768 (org-read-date nil 'to-time nil "End date:")))
21769 ;; callback function
21770 (callback (lambda ()
21771 (let ((time
21772 (org-float-time
21773 (apply 'encode-time
21774 (org-parse-time-string
21775 (match-string 1))))))
21776 ;; check if time in interval
21777 (and (>= time time1) (<= time time2))))))
21778 ;; make tree, check each match with the callback
21779 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21781 ;;;; Finish up
21783 (provide 'org)
21785 (run-hooks 'org-load-hook)
21787 ;;; org.el ends here