Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob9f816e5a00029b65fea36236b88d62d168c0f890
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (let ((load-suffixes (list ".el")))
82 (load "org-loaddefs" 'noerror nil nil 'mustsuffix))
84 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
85 ;; some places -- e.g. see the macro org-with-limited-levels.
87 ;; In Org buffers, the value of `outline-regexp' is that of
88 ;; `org-outline-regexp'. The only function still directly relying on
89 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
90 ;; job when `orgstruct-mode' is active.
91 (defvar org-outline-regexp "\\*+ "
92 "Regexp to match Org headlines.")
94 (defvar org-outline-regexp-bol "^\\*+ "
95 "Regexp to match Org headlines.
96 This is similar to `org-outline-regexp' but additionally makes
97 sure that we are at the beginning of the line.")
99 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
100 "Matches an headline, putting stars and text into groups.
101 Stars are put in group 1 and the trimmed body in group 2.")
103 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
104 (when (fboundp 'defvaralias)
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-at-clock-log-p "org-clock" ())
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
121 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function orgtbl-mode "org-table" (&optional arg))
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-beamer-mode "org-beamer" ())
127 (declare-function org-table-edit-field "org-table" (arg))
128 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
129 (declare-function org-id-get-create "org-id" (&optional force))
130 (declare-function org-id-find-id-file "org-id" (id))
131 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
132 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
133 (declare-function org-table-align "org-table" ())
134 (declare-function org-table-paste-rectangle "org-table" ())
135 (declare-function org-table-maybe-eval-formula "org-table" ())
136 (declare-function org-table-maybe-recalculate-line "org-table" ())
138 (autoload 'org-element-at-point "org-element")
139 (autoload 'org-element-type "org-element")
141 (declare-function org-element-at-point "org-element" (&optional keep-trail))
142 (declare-function org-element-type "org-element" (element))
143 (declare-function org-element-context "org-element" ())
144 (declare-function org-element-contents "org-element" (element))
145 (declare-function org-element-property "org-element" (property element))
146 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
147 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
150 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
152 ;; load languages based on value of `org-babel-load-languages'
153 (defvar org-babel-load-languages)
155 ;;;###autoload
156 (defun org-babel-do-load-languages (sym value)
157 "Load the languages defined in `org-babel-load-languages'."
158 (set-default sym value)
159 (mapc (lambda (pair)
160 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
161 (if active
162 (progn
163 (require (intern (concat "ob-" lang))))
164 (progn
165 (funcall 'fmakunbound
166 (intern (concat "org-babel-execute:" lang)))
167 (funcall 'fmakunbound
168 (intern (concat "org-babel-expand-body:" lang)))))))
169 org-babel-load-languages))
171 (defcustom org-babel-load-languages '((emacs-lisp . t))
172 "Languages which can be evaluated in Org-mode buffers.
173 This list can be used to load support for any of the languages
174 below, note that each language will depend on a different set of
175 system executables and/or Emacs modes. When a language is
176 \"loaded\", then code blocks in that language can be evaluated
177 with `org-babel-execute-src-block' bound by default to C-c
178 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
179 be set to remove code block evaluation from the C-c C-c
180 keybinding. By default only Emacs Lisp (which has no
181 requirements) is loaded."
182 :group 'org-babel
183 :set 'org-babel-do-load-languages
184 :version "24.1"
185 :type '(alist :tag "Babel Languages"
186 :key-type
187 (choice
188 (const :tag "Awk" awk)
189 (const :tag "C" C)
190 (const :tag "R" R)
191 (const :tag "Asymptote" asymptote)
192 (const :tag "Calc" calc)
193 (const :tag "Clojure" clojure)
194 (const :tag "CSS" css)
195 (const :tag "Ditaa" ditaa)
196 (const :tag "Dot" dot)
197 (const :tag "Emacs Lisp" emacs-lisp)
198 (const :tag "Fortran" fortran)
199 (const :tag "Gnuplot" gnuplot)
200 (const :tag "Haskell" haskell)
201 (const :tag "IO" io)
202 (const :tag "Java" java)
203 (const :tag "Javascript" js)
204 (const :tag "LaTeX" latex)
205 (const :tag "Ledger" ledger)
206 (const :tag "Lilypond" lilypond)
207 (const :tag "Lisp" lisp)
208 (const :tag "Makefile" makefile)
209 (const :tag "Maxima" maxima)
210 (const :tag "Matlab" matlab)
211 (const :tag "Mscgen" mscgen)
212 (const :tag "Ocaml" ocaml)
213 (const :tag "Octave" octave)
214 (const :tag "Org" org)
215 (const :tag "Perl" perl)
216 (const :tag "Pico Lisp" picolisp)
217 (const :tag "PlantUML" plantuml)
218 (const :tag "Python" python)
219 (const :tag "Ruby" ruby)
220 (const :tag "Sass" sass)
221 (const :tag "Scala" scala)
222 (const :tag "Scheme" scheme)
223 (const :tag "Screen" screen)
224 (const :tag "Shell Script" sh)
225 (const :tag "Shen" shen)
226 (const :tag "Sql" sql)
227 (const :tag "Sqlite" sqlite))
228 :value-type (boolean :tag "Activate" :value t)))
230 ;;;; Customization variables
231 (defcustom org-clone-delete-id nil
232 "Remove ID property of clones of a subtree.
233 When non-nil, clones of a subtree don't inherit the ID property.
234 Otherwise they inherit the ID property with a new unique
235 identifier."
236 :type 'boolean
237 :version "24.1"
238 :group 'org-id)
240 ;;; Version
241 (require 'org-compat)
242 (org-check-version)
244 ;;;###autoload
245 (defun org-version (&optional here full message)
246 "Show the org-mode version in the echo area.
247 With prefix argument HERE, insert it at point.
248 When FULL is non-nil, use a verbose version string.
249 When MESSAGE is non-nil, display a message with the version."
250 (interactive "P")
251 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
252 (save-load-suffixes load-suffixes)
253 (load-suffixes (list ".el"))
254 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
255 (org-trash (or
256 (and (fboundp 'org-release) (fboundp 'org-git-version))
257 (load (concat org-dir "org-version")
258 'noerror 'nomessage nil 'mustsuffix)))
259 (load-suffixes save-load-suffixes)
260 (org-version (org-release))
261 (git-version (org-git-version))
262 (version (format "Org-mode version %s (%s @ %s)"
263 org-version
264 git-version
265 (if org-install-dir
266 (if (string= org-dir org-install-dir)
267 org-install-dir
268 (concat "mixed installation! " org-install-dir " and " org-dir))
269 "org-loaddefs.el can not be found!")))
270 (_version (if full version org-version)))
271 (if (org-called-interactively-p 'interactive)
272 (if here
273 (insert version)
274 (message version))
275 (if message (message _version))
276 _version)))
278 (defconst org-version (org-version))
280 ;;; Compatibility constants
282 ;;; The custom variables
284 (defgroup org nil
285 "Outline-based notes management and organizer."
286 :tag "Org"
287 :group 'outlines
288 :group 'calendar)
290 (defcustom org-mode-hook nil
291 "Mode hook for Org-mode, run after the mode was turned on."
292 :group 'org
293 :type 'hook)
295 (defcustom org-load-hook nil
296 "Hook that is run after org.el has been loaded."
297 :group 'org
298 :type 'hook)
300 (defcustom org-log-buffer-setup-hook nil
301 "Hook that is run after an Org log buffer is created."
302 :group 'org
303 :version "24.1"
304 :type 'hook)
306 (defvar org-modules) ; defined below
307 (defvar org-modules-loaded nil
308 "Have the modules been loaded already?")
310 (defun org-load-modules-maybe (&optional force)
311 "Load all extensions listed in `org-modules'."
312 (when (or force (not org-modules-loaded))
313 (mapc (lambda (ext)
314 (condition-case nil (require ext)
315 (error (message "Problems while trying to load feature `%s'" ext))))
316 org-modules)
317 (setq org-modules-loaded t)))
319 (defun org-set-modules (var value)
320 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
321 (set var value)
322 (when (featurep 'org)
323 (org-load-modules-maybe 'force)))
325 (when (org-bound-and-true-p org-modules)
326 (let ((a (member 'org-infojs org-modules)))
327 (and a (setcar a 'org-jsinfo))))
329 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
330 "Modules that should always be loaded together with org.el.
331 If a description starts with <C>, the file is not part of Emacs
332 and loading it will require that you have downloaded and properly installed
333 the org-mode distribution.
335 You can also use this system to load external packages (i.e. neither Org
336 core modules, nor modules from the CONTRIB directory). Just add symbols
337 to the end of the list. If the package is called org-xyz.el, then you need
338 to add the symbol `xyz', and the package must have a call to
340 (provide 'org-xyz)"
341 :group 'org
342 :set 'org-set-modules
343 :type
344 '(set :greedy t
345 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
346 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
347 (const :tag " crypt: Encryption of subtrees" org-crypt)
348 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
349 (const :tag " docview: Links to doc-view buffers" org-docview)
350 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
351 (const :tag " id: Global IDs for identifying entries" org-id)
352 (const :tag " info: Links to Info nodes" org-info)
353 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
354 (const :tag " habit: Track your consistency with habits" org-habit)
355 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
356 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
357 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
358 (const :tag " mew Links to Mew folders/messages" org-mew)
359 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
360 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
361 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
362 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
363 (const :tag " vm: Links to VM folders/messages" org-vm)
364 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
365 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
366 (const :tag " mouse: Additional mouse support" org-mouse)
367 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
369 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
370 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
371 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
372 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
373 (const :tag "C collector: Collect properties into tables" org-collector)
374 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
375 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
376 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
377 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
378 (const :tag "C eval: Include command output as text" org-eval)
379 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
380 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
381 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
382 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
383 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
385 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
387 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
388 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
389 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
390 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
391 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
392 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
393 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
394 (const :tag "C mtags: Support for muse-like tags" org-mtags)
395 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
396 (const :tag "C registry: A registry for Org-mode links" org-registry)
397 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
398 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
399 (const :tag "C secretary: Team management with org-mode" org-secretary)
400 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
401 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
402 (const :tag "C track: Keep up with Org-mode development" org-track)
403 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
404 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
405 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
407 (defcustom org-support-shift-select nil
408 "Non-nil means make shift-cursor commands select text when possible.
410 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
411 start selecting a region, or enlarge regions started in this way.
412 In Org-mode, in special contexts, these same keys are used for
413 other purposes, important enough to compete with shift selection.
414 Org tries to balance these needs by supporting `shift-select-mode'
415 outside these special contexts, under control of this variable.
417 The default of this variable is nil, to avoid confusing behavior. Shifted
418 cursor keys will then execute Org commands in the following contexts:
419 - on a headline, changing TODO state (left/right) and priority (up/down)
420 - on a time stamp, changing the time
421 - in a plain list item, changing the bullet type
422 - in a property definition line, switching between allowed values
423 - in the BEGIN line of a clock table (changing the time block).
424 Outside these contexts, the commands will throw an error.
426 When this variable is t and the cursor is not in a special
427 context, Org-mode will support shift-selection for making and
428 enlarging regions. To make this more effective, the bullet
429 cycling will no longer happen anywhere in an item line, but only
430 if the cursor is exactly on the bullet.
432 If you set this variable to the symbol `always', then the keys
433 will not be special in headlines, property lines, and item lines,
434 to make shift selection work there as well. If this is what you
435 want, you can use the following alternative commands: `C-c C-t'
436 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
437 can be used to switch TODO sets, `C-c -' to cycle item bullet
438 types, and properties can be edited by hand or in column view.
440 However, when the cursor is on a timestamp, shift-cursor commands
441 will still edit the time stamp - this is just too good to give up.
443 XEmacs user should have this variable set to nil, because
444 `shift-select-mode' is in Emacs 23 or later only."
445 :group 'org
446 :type '(choice
447 (const :tag "Never" nil)
448 (const :tag "When outside special context" t)
449 (const :tag "Everywhere except timestamps" always)))
451 (defcustom org-loop-over-headlines-in-active-region nil
452 "Shall some commands act upon headlines in the active region?
454 When set to `t', some commands will be performed in all headlines
455 within the active region.
457 When set to `start-level', some commands will be performed in all
458 headlines within the active region, provided that these headlines
459 are of the same level than the first one.
461 When set to a string, those commands will be performed on the
462 matching headlines within the active region. Such string must be
463 a tags/property/todo match as it is used in the agenda tags view.
465 The list of commands is: `org-schedule', `org-deadline',
466 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
467 `org-archive-to-archive-sibling'. The archiving commands skip
468 already archived entries."
469 :type '(choice (const :tag "Don't loop" nil)
470 (const :tag "All headlines in active region" t)
471 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
472 (string :tag "Tags/Property/Todo matcher"))
473 :version "24.1"
474 :group 'org-todo
475 :group 'org-archive)
477 (defgroup org-startup nil
478 "Options concerning startup of Org-mode."
479 :tag "Org Startup"
480 :group 'org)
482 (defcustom org-startup-folded t
483 "Non-nil means entering Org-mode will switch to OVERVIEW.
484 This can also be configured on a per-file basis by adding one of
485 the following lines anywhere in the buffer:
487 #+STARTUP: fold (or `overview', this is equivalent)
488 #+STARTUP: nofold (or `showall', this is equivalent)
489 #+STARTUP: content
490 #+STARTUP: showeverything"
491 :group 'org-startup
492 :type '(choice
493 (const :tag "nofold: show all" nil)
494 (const :tag "fold: overview" t)
495 (const :tag "content: all headlines" content)
496 (const :tag "show everything, even drawers" showeverything)))
498 (defcustom org-startup-truncated t
499 "Non-nil means entering Org-mode will set `truncate-lines'.
500 This is useful since some lines containing links can be very long and
501 uninteresting. Also tables look terrible when wrapped."
502 :group 'org-startup
503 :type 'boolean)
505 (defcustom org-startup-indented nil
506 "Non-nil means turn on `org-indent-mode' on startup.
507 This can also be configured on a per-file basis by adding one of
508 the following lines anywhere in the buffer:
510 #+STARTUP: indent
511 #+STARTUP: noindent"
512 :group 'org-structure
513 :type '(choice
514 (const :tag "Not" nil)
515 (const :tag "Globally (slow on startup in large files)" t)))
517 (defcustom org-use-sub-superscripts t
518 "Non-nil means interpret \"_\" and \"^\" for export.
519 When this option is turned on, you can use TeX-like syntax for sub- and
520 superscripts. Several characters after \"_\" or \"^\" will be
521 considered as a single item - so grouping with {} is normally not
522 needed. For example, the following things will be parsed as single
523 sub- or superscripts.
525 10^24 or 10^tau several digits will be considered 1 item.
526 10^-12 or 10^-tau a leading sign with digits or a word
527 x^2-y^3 will be read as x^2 - y^3, because items are
528 terminated by almost any nonword/nondigit char.
529 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
531 Still, ambiguity is possible - so when in doubt use {} to enclose the
532 sub/superscript. If you set this variable to the symbol `{}',
533 the braces are *required* in order to trigger interpretations as
534 sub/superscript. This can be helpful in documents that need \"_\"
535 frequently in plain text.
537 Not all export backends support this, but HTML does.
539 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
540 :group 'org-startup
541 :group 'org-export-translation
542 :version "24.1"
543 :type '(choice
544 (const :tag "Always interpret" t)
545 (const :tag "Only with braces" {})
546 (const :tag "Never interpret" nil)))
548 (if (fboundp 'defvaralias)
549 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
552 (defcustom org-startup-with-beamer-mode nil
553 "Non-nil means turn on `org-beamer-mode' on startup.
554 This can also be configured on a per-file basis by adding one of
555 the following lines anywhere in the buffer:
557 #+STARTUP: beamer"
558 :group 'org-startup
559 :version "24.1"
560 :type 'boolean)
562 (defcustom org-startup-align-all-tables nil
563 "Non-nil means align all tables when visiting a file.
564 This is useful when the column width in tables is forced with <N> cookies
565 in table fields. Such tables will look correct only after the first re-align.
566 This can also be configured on a per-file basis by adding one of
567 the following lines anywhere in the buffer:
568 #+STARTUP: align
569 #+STARTUP: noalign"
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-startup-with-inline-images nil
574 "Non-nil means show inline images when loading a new Org file.
575 This can also be configured on a per-file basis by adding one of
576 the following lines anywhere in the buffer:
577 #+STARTUP: inlineimages
578 #+STARTUP: noinlineimages"
579 :group 'org-startup
580 :version "24.1"
581 :type 'boolean)
583 (defcustom org-insert-mode-line-in-empty-file nil
584 "Non-nil means insert the first line setting Org-mode in empty files.
585 When the function `org-mode' is called interactively in an empty file, this
586 normally means that the file name does not automatically trigger Org-mode.
587 To ensure that the file will always be in Org-mode in the future, a
588 line enforcing Org-mode will be inserted into the buffer, if this option
589 has been set."
590 :group 'org-startup
591 :type 'boolean)
593 (defcustom org-replace-disputed-keys nil
594 "Non-nil means use alternative key bindings for some keys.
595 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
596 These keys are also used by other packages like shift-selection-mode'
597 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
598 If you want to use Org-mode together with one of these other modes,
599 or more generally if you would like to move some Org-mode commands to
600 other keys, set this variable and configure the keys with the variable
601 `org-disputed-keys'.
603 This option is only relevant at load-time of Org-mode, and must be set
604 *before* org.el is loaded. Changing it requires a restart of Emacs to
605 become effective."
606 :group 'org-startup
607 :type 'boolean)
609 (defcustom org-use-extra-keys nil
610 "Non-nil means use extra key sequence definitions for certain commands.
611 This happens automatically if you run XEmacs or if `window-system'
612 is nil. This variable lets you do the same manually. You must
613 set it before loading org.
615 Example: on Carbon Emacs 22 running graphically, with an external
616 keyboard on a Powerbook, the default way of setting M-left might
617 not work for either Alt or ESC. Setting this variable will make
618 it work for ESC."
619 :group 'org-startup
620 :type 'boolean)
622 (if (fboundp 'defvaralias)
623 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
625 (defcustom org-disputed-keys
626 '(([(shift up)] . [(meta p)])
627 ([(shift down)] . [(meta n)])
628 ([(shift left)] . [(meta -)])
629 ([(shift right)] . [(meta +)])
630 ([(control shift right)] . [(meta shift +)])
631 ([(control shift left)] . [(meta shift -)]))
632 "Keys for which Org-mode and other modes compete.
633 This is an alist, cars are the default keys, second element specifies
634 the alternative to use when `org-replace-disputed-keys' is t.
636 Keys can be specified in any syntax supported by `define-key'.
637 The value of this option takes effect only at Org-mode's startup,
638 therefore you'll have to restart Emacs to apply it after changing."
639 :group 'org-startup
640 :type 'alist)
642 (defun org-key (key)
643 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
644 Or return the original if not disputed.
645 Also apply the translations defined in `org-xemacs-key-equivalents'."
646 (when org-replace-disputed-keys
647 (let* ((nkey (key-description key))
648 (x (org-find-if (lambda (x)
649 (equal (key-description (car x)) nkey))
650 org-disputed-keys)))
651 (setq key (if x (cdr x) key))))
652 (when (featurep 'xemacs)
653 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
654 key)
656 (defun org-find-if (predicate seq)
657 (catch 'exit
658 (while seq
659 (if (funcall predicate (car seq))
660 (throw 'exit (car seq))
661 (pop seq)))))
663 (defun org-defkey (keymap key def)
664 "Define a key, possibly translated, as returned by `org-key'."
665 (define-key keymap (org-key key) def))
667 (defcustom org-ellipsis nil
668 "The ellipsis to use in the Org-mode outline.
669 When nil, just use the standard three dots. When a string, use that instead,
670 When a face, use the standard 3 dots, but with the specified face.
671 The change affects only Org-mode (which will then use its own display table).
672 Changing this requires executing `M-x org-mode' in a buffer to become
673 effective."
674 :group 'org-startup
675 :type '(choice (const :tag "Default" nil)
676 (face :tag "Face" :value org-warning)
677 (string :tag "String" :value "...#")))
679 (defvar org-display-table nil
680 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
682 (defgroup org-keywords nil
683 "Keywords in Org-mode."
684 :tag "Org Keywords"
685 :group 'org)
687 (defcustom org-deadline-string "DEADLINE:"
688 "String to mark deadline entries.
689 A deadline is this string, followed by a time stamp. Should be a word,
690 terminated by a colon. You can insert a schedule keyword and
691 a timestamp with \\[org-deadline].
692 Changes become only effective after restarting Emacs."
693 :group 'org-keywords
694 :type 'string)
696 (defcustom org-scheduled-string "SCHEDULED:"
697 "String to mark scheduled TODO entries.
698 A schedule is this string, followed by a time stamp. Should be a word,
699 terminated by a colon. You can insert a schedule keyword and
700 a timestamp with \\[org-schedule].
701 Changes become only effective after restarting Emacs."
702 :group 'org-keywords
703 :type 'string)
705 (defcustom org-closed-string "CLOSED:"
706 "String used as the prefix for timestamps logging closing a TODO entry."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-clock-string "CLOCK:"
711 "String used as prefix for timestamps clocking work hours on an item."
712 :group 'org-keywords
713 :type 'string)
715 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
716 org-scheduled-string "\\|"
717 org-deadline-string "\\|"
718 org-closed-string "\\|"
719 org-clock-string "\\)")
720 "Matches a line with planning or clock info.")
722 (defcustom org-comment-string "COMMENT"
723 "Entries starting with this keyword will never be exported.
724 An entry can be toggled between COMMENT and normal with
725 \\[org-toggle-comment].
726 Changes become only effective after restarting Emacs."
727 :group 'org-keywords
728 :type 'string)
730 (defcustom org-quote-string "QUOTE"
731 "Entries starting with this keyword will be exported in fixed-width font.
732 Quoting applies only to the text in the entry following the headline, and does
733 not extend beyond the next headline, even if that is lower level.
734 An entry can be toggled between QUOTE and normal with
735 \\[org-toggle-fixed-width-section]."
736 :group 'org-keywords
737 :type 'string)
739 (defconst org-repeat-re
740 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
741 "Regular expression for specifying repeated events.
742 After a match, group 1 contains the repeat expression.")
744 (defgroup org-structure nil
745 "Options concerning the general structure of Org-mode files."
746 :tag "Org Structure"
747 :group 'org)
749 (defgroup org-reveal-location nil
750 "Options about how to make context of a location visible."
751 :tag "Org Reveal Location"
752 :group 'org-structure)
754 (defconst org-context-choice
755 '(choice
756 (const :tag "Always" t)
757 (const :tag "Never" nil)
758 (repeat :greedy t :tag "Individual contexts"
759 (cons
760 (choice :tag "Context"
761 (const agenda)
762 (const org-goto)
763 (const occur-tree)
764 (const tags-tree)
765 (const link-search)
766 (const mark-goto)
767 (const bookmark-jump)
768 (const isearch)
769 (const default))
770 (boolean))))
771 "Contexts for the reveal options.")
773 (defcustom org-show-hierarchy-above '((default . t))
774 "Non-nil means show full hierarchy when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the hierarchy of headings
777 above the exposed location is shown.
778 Turning this off for example for sparse trees makes them very compact.
779 Instead of t, this can also be an alist specifying this option for different
780 contexts. Valid contexts are
781 agenda when exposing an entry from the agenda
782 org-goto when using the command `org-goto' on key C-c C-j
783 occur-tree when using the command `org-occur' on key C-c /
784 tags-tree when constructing a sparse tree based on tags matches
785 link-search when exposing search matches associated with a link
786 mark-goto when exposing the jump goal of a mark
787 bookmark-jump when exposing a bookmark location
788 isearch when exiting from an incremental search
789 default default for all contexts not set explicitly"
790 :group 'org-reveal-location
791 :type org-context-choice)
793 (defcustom org-show-following-heading '((default . nil))
794 "Non-nil means show following heading when revealing a location.
795 Org-mode often shows locations in an org-mode file which might have
796 been invisible before. When this is set, the heading following the
797 match is shown.
798 Turning this off for example for sparse trees makes them very compact,
799 but makes it harder to edit the location of the match. In such a case,
800 use the command \\[org-reveal] to show more context.
801 Instead of t, this can also be an alist specifying this option for different
802 contexts. See `org-show-hierarchy-above' for valid contexts."
803 :group 'org-reveal-location
804 :type org-context-choice)
806 (defcustom org-show-siblings '((default . nil) (isearch t))
807 "Non-nil means show all sibling heading when revealing a location.
808 Org-mode often shows locations in an org-mode file which might have
809 been invisible before. When this is set, the sibling of the current entry
810 heading are all made visible. If `org-show-hierarchy-above' is t,
811 the same happens on each level of the hierarchy above the current entry.
813 By default this is on for the isearch context, off for all other contexts.
814 Turning this off for example for sparse trees makes them very compact,
815 but makes it harder to edit the location of the match. In such a case,
816 use the command \\[org-reveal] to show more context.
817 Instead of t, this can also be an alist specifying this option for different
818 contexts. See `org-show-hierarchy-above' for valid contexts."
819 :group 'org-reveal-location
820 :type org-context-choice)
822 (defcustom org-show-entry-below '((default . nil))
823 "Non-nil means show the entry below a headline when revealing a location.
824 Org-mode often shows locations in an org-mode file which might have
825 been invisible before. When this is set, the text below the headline that is
826 exposed is also shown.
828 By default this is off for all contexts.
829 Instead of t, this can also be an alist specifying this option for different
830 contexts. See `org-show-hierarchy-above' for valid contexts."
831 :group 'org-reveal-location
832 :type org-context-choice)
834 (defcustom org-indirect-buffer-display 'other-window
835 "How should indirect tree buffers be displayed?
836 This applies to indirect buffers created with the commands
837 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
838 Valid values are:
839 current-window Display in the current window
840 other-window Just display in another window.
841 dedicated-frame Create one new frame, and re-use it each time.
842 new-frame Make a new frame each time. Note that in this case
843 previously-made indirect buffers are kept, and you need to
844 kill these buffers yourself."
845 :group 'org-structure
846 :group 'org-agenda-windows
847 :type '(choice
848 (const :tag "In current window" current-window)
849 (const :tag "In current frame, other window" other-window)
850 (const :tag "Each time a new frame" new-frame)
851 (const :tag "One dedicated frame" dedicated-frame)))
853 (defcustom org-use-speed-commands nil
854 "Non-nil means activate single letter commands at beginning of a headline.
855 This may also be a function to test for appropriate locations where speed
856 commands should be active."
857 :group 'org-structure
858 :type '(choice
859 (const :tag "Never" nil)
860 (const :tag "At beginning of headline stars" t)
861 (function)))
863 (defcustom org-speed-commands-user nil
864 "Alist of additional speed commands.
865 This list will be checked before `org-speed-commands-default'
866 when the variable `org-use-speed-commands' is non-nil
867 and when the cursor is at the beginning of a headline.
868 The car if each entry is a string with a single letter, which must
869 be assigned to `self-insert-command' in the global map.
870 The cdr is either a command to be called interactively, a function
871 to be called, or a form to be evaluated.
872 An entry that is just a list with a single string will be interpreted
873 as a descriptive headline that will be added when listing the speed
874 commands in the Help buffer using the `?' speed command."
875 :group 'org-structure
876 :type '(repeat :value ("k" . ignore)
877 (choice :value ("k" . ignore)
878 (list :tag "Descriptive Headline" (string :tag "Headline"))
879 (cons :tag "Letter and Command"
880 (string :tag "Command letter")
881 (choice
882 (function)
883 (sexp))))))
885 (defgroup org-cycle nil
886 "Options concerning visibility cycling in Org-mode."
887 :tag "Org Cycle"
888 :group 'org-structure)
890 (defcustom org-cycle-skip-children-state-if-no-children t
891 "Non-nil means skip CHILDREN state in entries that don't have any."
892 :group 'org-cycle
893 :type 'boolean)
895 (defcustom org-cycle-max-level nil
896 "Maximum level which should still be subject to visibility cycling.
897 Levels higher than this will, for cycling, be treated as text, not a headline.
898 When `org-odd-levels-only' is set, a value of N in this variable actually
899 means 2N-1 stars as the limiting headline.
900 When nil, cycle all levels.
901 Note that the limiting level of cycling is also influenced by
902 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
903 `org-inlinetask-min-level' is, cycling will be limited to levels one less
904 than its value."
905 :group 'org-cycle
906 :type '(choice
907 (const :tag "No limit" nil)
908 (integer :tag "Maximum level")))
910 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
911 "Names of drawers. Drawers are not opened by cycling on the headline above.
912 Drawers only open with a TAB on the drawer line itself. A drawer looks like
913 this:
914 :DRAWERNAME:
915 .....
916 :END:
917 The drawer \"PROPERTIES\" is special for capturing properties through
918 the property API.
920 Drawers can be defined on the per-file basis with a line like:
922 #+DRAWERS: HIDDEN STATE PROPERTIES"
923 :group 'org-structure
924 :group 'org-cycle
925 :type '(repeat (string :tag "Drawer Name")))
927 (defcustom org-hide-block-startup nil
928 "Non-nil means entering Org-mode will fold all blocks.
929 This can also be set in on a per-file basis with
931 #+STARTUP: hideblocks
932 #+STARTUP: showblocks"
933 :group 'org-startup
934 :group 'org-cycle
935 :type 'boolean)
937 (defcustom org-cycle-global-at-bob nil
938 "Cycle globally if cursor is at beginning of buffer and not at a headline.
939 This makes it possible to do global cycling without having to use S-TAB or
940 \\[universal-argument] TAB. For this special case to work, the first line
941 of the buffer must not be a headline -- it may be empty or some other text.
942 When used in this way, `org-cycle-hook' is disabled temporarily to make
943 sure the cursor stays at the beginning of the buffer. When this option is
944 nil, don't do anything special at the beginning of the buffer."
945 :group 'org-cycle
946 :type 'boolean)
948 (defcustom org-cycle-level-after-item/entry-creation t
949 "Non-nil means cycle entry level or item indentation in new empty entries.
951 When the cursor is at the end of an empty headline, i.e with only stars
952 and maybe a TODO keyword, TAB will then switch the entry to become a child,
953 and then all possible ancestor states, before returning to the original state.
954 This makes data entry extremely fast: M-RET to create a new headline,
955 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
957 When the cursor is at the end of an empty plain list item, one TAB will
958 make it a subitem, two or more tabs will back up to make this an item
959 higher up in the item hierarchy."
960 :group 'org-cycle
961 :type 'boolean)
963 (defcustom org-cycle-emulate-tab t
964 "Where should `org-cycle' emulate TAB.
965 nil Never
966 white Only in completely white lines
967 whitestart Only at the beginning of lines, before the first non-white char
968 t Everywhere except in headlines
969 exc-hl-bol Everywhere except at the start of a headline
970 If TAB is used in a place where it does not emulate TAB, the current subtree
971 visibility is cycled."
972 :group 'org-cycle
973 :type '(choice (const :tag "Never" nil)
974 (const :tag "Only in completely white lines" white)
975 (const :tag "Before first char in a line" whitestart)
976 (const :tag "Everywhere except in headlines" t)
977 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
980 (defcustom org-cycle-separator-lines 2
981 "Number of empty lines needed to keep an empty line between collapsed trees.
982 If you leave an empty line between the end of a subtree and the following
983 headline, this empty line is hidden when the subtree is folded.
984 Org-mode will leave (exactly) one empty line visible if the number of
985 empty lines is equal or larger to the number given in this variable.
986 So the default 2 means at least 2 empty lines after the end of a subtree
987 are needed to produce free space between a collapsed subtree and the
988 following headline.
990 If the number is negative, and the number of empty lines is at least -N,
991 all empty lines are shown.
993 Special case: when 0, never leave empty lines in collapsed view."
994 :group 'org-cycle
995 :type 'integer)
996 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
998 (defcustom org-pre-cycle-hook nil
999 "Hook that is run before visibility cycling is happening.
1000 The function(s) in this hook must accept a single argument which indicates
1001 the new state that will be set right after running this hook. The
1002 argument is a symbol. Before a global state change, it can have the values
1003 `overview', `content', or `all'. Before a local state change, it can have
1004 the values `folded', `children', or `subtree'."
1005 :group 'org-cycle
1006 :type 'hook)
1008 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1009 org-cycle-hide-drawers
1010 org-cycle-hide-inline-tasks
1011 org-cycle-show-empty-lines
1012 org-optimize-window-after-visibility-change)
1013 "Hook that is run after `org-cycle' has changed the buffer visibility.
1014 The function(s) in this hook must accept a single argument which indicates
1015 the new state that was set by the most recent `org-cycle' command. The
1016 argument is a symbol. After a global state change, it can have the values
1017 `overview', `contents', or `all'. After a local state change, it can have
1018 the values `folded', `children', or `subtree'."
1019 :group 'org-cycle
1020 :type 'hook)
1022 (defgroup org-edit-structure nil
1023 "Options concerning structure editing in Org-mode."
1024 :tag "Org Edit Structure"
1025 :group 'org-structure)
1027 (defcustom org-odd-levels-only nil
1028 "Non-nil means skip even levels and only use odd levels for the outline.
1029 This has the effect that two stars are being added/taken away in
1030 promotion/demotion commands. It also influences how levels are
1031 handled by the exporters.
1032 Changing it requires restart of `font-lock-mode' to become effective
1033 for fontification also in regions already fontified.
1034 You may also set this on a per-file basis by adding one of the following
1035 lines to the buffer:
1037 #+STARTUP: odd
1038 #+STARTUP: oddeven"
1039 :group 'org-edit-structure
1040 :group 'org-appearance
1041 :type 'boolean)
1043 (defcustom org-adapt-indentation t
1044 "Non-nil means adapt indentation to outline node level.
1046 When this variable is set, Org assumes that you write outlines by
1047 indenting text in each node to align with the headline (after the stars).
1048 The following issues are influenced by this variable:
1050 - When this is set and the *entire* text in an entry is indented, the
1051 indentation is increased by one space in a demotion command, and
1052 decreased by one in a promotion command. If any line in the entry
1053 body starts with text at column 0, indentation is not changed at all.
1055 - Property drawers and planning information is inserted indented when
1056 this variable s set. When nil, they will not be indented.
1058 - TAB indents a line relative to context. The lines below a headline
1059 will be indented when this variable is set.
1061 Note that this is all about true indentation, by adding and removing
1062 space characters. See also `org-indent.el' which does level-dependent
1063 indentation in a virtual way, i.e. at display time in Emacs."
1064 :group 'org-edit-structure
1065 :type 'boolean)
1067 (defcustom org-special-ctrl-a/e nil
1068 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1070 When t, `C-a' will bring back the cursor to the beginning of the
1071 headline text, i.e. after the stars and after a possible TODO
1072 keyword. In an item, this will be the position after bullet and
1073 check-box, if any. When the cursor is already at that position,
1074 another `C-a' will bring it to the beginning of the line.
1076 `C-e' will jump to the end of the headline, ignoring the presence
1077 of tags in the headline. A second `C-e' will then jump to the
1078 true end of the line, after any tags. This also means that, when
1079 this variable is non-nil, `C-e' also will never jump beyond the
1080 end of the heading of a folded section, i.e. not after the
1081 ellipses.
1083 When set to the symbol `reversed', the first `C-a' or `C-e' works
1084 normally, going to the true line boundary first. Only a directly
1085 following, identical keypress will bring the cursor to the
1086 special positions.
1088 This may also be a cons cell where the behavior for `C-a' and
1089 `C-e' is set separately."
1090 :group 'org-edit-structure
1091 :type '(choice
1092 (const :tag "off" nil)
1093 (const :tag "on: after stars/bullet and before tags first" t)
1094 (const :tag "reversed: true line boundary first" reversed)
1095 (cons :tag "Set C-a and C-e separately"
1096 (choice :tag "Special C-a"
1097 (const :tag "off" nil)
1098 (const :tag "on: after stars/bullet first" t)
1099 (const :tag "reversed: before stars/bullet first" reversed))
1100 (choice :tag "Special C-e"
1101 (const :tag "off" nil)
1102 (const :tag "on: before tags first" t)
1103 (const :tag "reversed: after tags first" reversed)))))
1104 (if (fboundp 'defvaralias)
1105 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1107 (defcustom org-special-ctrl-k nil
1108 "Non-nil means `C-k' will behave specially in headlines.
1109 When nil, `C-k' will call the default `kill-line' command.
1110 When t, the following will happen while the cursor is in the headline:
1112 - When the cursor is at the beginning of a headline, kill the entire
1113 line and possible the folded subtree below the line.
1114 - When in the middle of the headline text, kill the headline up to the tags.
1115 - When after the headline text, kill the tags."
1116 :group 'org-edit-structure
1117 :type 'boolean)
1119 (defcustom org-ctrl-k-protect-subtree nil
1120 "Non-nil means, do not delete a hidden subtree with C-k.
1121 When set to the symbol `error', simply throw an error when C-k is
1122 used to kill (part-of) a headline that has hidden text behind it.
1123 Any other non-nil value will result in a query to the user, if it is
1124 OK to kill that hidden subtree. When nil, kill without remorse."
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not protect hidden subtrees" nil)
1129 (const :tag "Protect hidden subtrees with a security query" t)
1130 (const :tag "Never kill a hidden subtree with C-k" error)))
1132 (defcustom org-catch-invisible-edits nil
1133 "Check if in invisible region before inserting or deleting a character.
1134 Valid values are:
1136 nil Do not check, so just do invisible edits.
1137 error Throw an error and do nothing.
1138 show Make point visible, and do the requested edit.
1139 show-and-error Make point visible, then throw an error and abort the edit.
1140 smart Make point visible, and do insertion/deletion if it is
1141 adjacent to visible text and the change feels predictable.
1142 Never delete a previously invisible character or add in the
1143 middle or right after an invisible region. Basically, this
1144 allows insertion and backward-delete right before ellipses.
1145 FIXME: maybe in this case we should not even show?"
1146 :group 'org-edit-structure
1147 :version "24.1"
1148 :type '(choice
1149 (const :tag "Do not check" nil)
1150 (const :tag "Throw error when trying to edit" error)
1151 (const :tag "Unhide, but do not do the edit" show-and-error)
1152 (const :tag "Show invisible part and do the edit" show)
1153 (const :tag "Be smart and do the right thing" smart)))
1155 (defcustom org-yank-folded-subtrees t
1156 "Non-nil means when yanking subtrees, fold them.
1157 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1158 it starts with a heading and all other headings in it are either children
1159 or siblings, then fold all the subtrees. However, do this only if no
1160 text after the yank would be swallowed into a folded tree by this action."
1161 :group 'org-edit-structure
1162 :type 'boolean)
1164 (defcustom org-yank-adjusted-subtrees nil
1165 "Non-nil means when yanking subtrees, adjust the level.
1166 With this setting, `org-paste-subtree' is used to insert the subtree, see
1167 this function for details."
1168 :group 'org-edit-structure
1169 :type 'boolean)
1171 (defcustom org-M-RET-may-split-line '((default . t))
1172 "Non-nil means M-RET will split the line at the cursor position.
1173 When nil, it will go to the end of the line before making a
1174 new line.
1175 You may also set this option in a different way for different
1176 contexts. Valid contexts are:
1178 headline when creating a new headline
1179 item when creating a new item
1180 table in a table field
1181 default the value to be used for all contexts not explicitly
1182 customized"
1183 :group 'org-structure
1184 :group 'org-table
1185 :type '(choice
1186 (const :tag "Always" t)
1187 (const :tag "Never" nil)
1188 (repeat :greedy t :tag "Individual contexts"
1189 (cons
1190 (choice :tag "Context"
1191 (const headline)
1192 (const item)
1193 (const table)
1194 (const default))
1195 (boolean)))))
1198 (defcustom org-insert-heading-respect-content nil
1199 "Non-nil means insert new headings after the current subtree.
1200 When nil, the new heading is created directly after the current line.
1201 The commands \\[org-insert-heading-respect-content] and
1202 \\[org-insert-todo-heading-respect-content] turn this variable on
1203 for the duration of the command."
1204 :group 'org-structure
1205 :type 'boolean)
1207 (defcustom org-blank-before-new-entry '((heading . auto)
1208 (plain-list-item . auto))
1209 "Should `org-insert-heading' leave a blank line before new heading/item?
1210 The value is an alist, with `heading' and `plain-list-item' as CAR,
1211 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1212 which case Org will look at the surrounding headings/items and try to
1213 make an intelligent decision whether to insert a blank line or not.
1215 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1216 set, the setting here is ignored and no empty line is inserted, to avoid
1217 breaking the list structure."
1218 :group 'org-edit-structure
1219 :type '(list
1220 (cons (const heading)
1221 (choice (const :tag "Never" nil)
1222 (const :tag "Always" t)
1223 (const :tag "Auto" auto)))
1224 (cons (const plain-list-item)
1225 (choice (const :tag "Never" nil)
1226 (const :tag "Always" t)
1227 (const :tag "Auto" auto)))))
1229 (defcustom org-insert-heading-hook nil
1230 "Hook being run after inserting a new heading."
1231 :group 'org-edit-structure
1232 :type 'hook)
1234 (defcustom org-enable-fixed-width-editor t
1235 "Non-nil means lines starting with \":\" are treated as fixed-width.
1236 This currently only means they are never auto-wrapped.
1237 When nil, such lines will be treated like ordinary lines.
1238 See also the QUOTE keyword."
1239 :group 'org-edit-structure
1240 :type 'boolean)
1242 (defcustom org-goto-auto-isearch t
1243 "Non-nil means typing characters in `org-goto' starts incremental search."
1244 :group 'org-edit-structure
1245 :type 'boolean)
1247 (defgroup org-sparse-trees nil
1248 "Options concerning sparse trees in Org-mode."
1249 :tag "Org Sparse Trees"
1250 :group 'org-structure)
1252 (defcustom org-highlight-sparse-tree-matches t
1253 "Non-nil means highlight all matches that define a sparse tree.
1254 The highlights will automatically disappear the next time the buffer is
1255 changed by an edit command."
1256 :group 'org-sparse-trees
1257 :type 'boolean)
1259 (defcustom org-remove-highlights-with-change t
1260 "Non-nil means any change to the buffer will remove temporary highlights.
1261 Such highlights are created by `org-occur' and `org-clock-display'.
1262 When nil, `C-c C-c needs to be used to get rid of the highlights.
1263 The highlights created by `org-preview-latex-fragment' always need
1264 `C-c C-c' to be removed."
1265 :group 'org-sparse-trees
1266 :group 'org-time
1267 :type 'boolean)
1270 (defcustom org-occur-hook '(org-first-headline-recenter)
1271 "Hook that is run after `org-occur' has constructed a sparse tree.
1272 This can be used to recenter the window to show as much of the structure
1273 as possible."
1274 :group 'org-sparse-trees
1275 :type 'hook)
1277 (defgroup org-imenu-and-speedbar nil
1278 "Options concerning imenu and speedbar in Org-mode."
1279 :tag "Org Imenu and Speedbar"
1280 :group 'org-structure)
1282 (defcustom org-imenu-depth 2
1283 "The maximum level for Imenu access to Org-mode headlines.
1284 This also applied for speedbar access."
1285 :group 'org-imenu-and-speedbar
1286 :type 'integer)
1288 (defgroup org-table nil
1289 "Options concerning tables in Org-mode."
1290 :tag "Org Table"
1291 :group 'org)
1293 (defcustom org-enable-table-editor 'optimized
1294 "Non-nil means lines starting with \"|\" are handled by the table editor.
1295 When nil, such lines will be treated like ordinary lines.
1297 When equal to the symbol `optimized', the table editor will be optimized to
1298 do the following:
1299 - Automatic overwrite mode in front of whitespace in table fields.
1300 This makes the structure of the table stay in tact as long as the edited
1301 field does not exceed the column width.
1302 - Minimize the number of realigns. Normally, the table is aligned each time
1303 TAB or RET are pressed to move to another field. With optimization this
1304 happens only if changes to a field might have changed the column width.
1305 Optimization requires replacing the functions `self-insert-command',
1306 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1307 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1308 very good at guessing when a re-align will be necessary, but you can always
1309 force one with \\[org-ctrl-c-ctrl-c].
1311 If you would like to use the optimized version in Org-mode, but the
1312 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1314 This variable can be used to turn on and off the table editor during a session,
1315 but in order to toggle optimization, a restart is required.
1317 See also the variable `org-table-auto-blank-field'."
1318 :group 'org-table
1319 :type '(choice
1320 (const :tag "off" nil)
1321 (const :tag "on" t)
1322 (const :tag "on, optimized" optimized)))
1324 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1325 (version<= emacs-version "24.1"))
1326 "Non-nil means cluster self-insert commands for undo when possible.
1327 If this is set, then, like in the Emacs command loop, 20 consecutive
1328 characters will be undone together.
1329 This is configurable, because there is some impact on typing performance."
1330 :group 'org-table
1331 :type 'boolean)
1333 (defcustom org-table-tab-recognizes-table.el t
1334 "Non-nil means TAB will automatically notice a table.el table.
1335 When it sees such a table, it moves point into it and - if necessary -
1336 calls `table-recognize-table'."
1337 :group 'org-table-editing
1338 :type 'boolean)
1340 (defgroup org-link nil
1341 "Options concerning links in Org-mode."
1342 :tag "Org Link"
1343 :group 'org)
1345 (defvar org-link-abbrev-alist-local nil
1346 "Buffer-local version of `org-link-abbrev-alist', which see.
1347 The value of this is taken from the #+LINK lines.")
1348 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1350 (defcustom org-link-abbrev-alist nil
1351 "Alist of link abbreviations.
1352 The car of each element is a string, to be replaced at the start of a link.
1353 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1354 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1356 [[linkkey:tag][description]]
1358 The 'linkkey' must be a word word, starting with a letter, followed
1359 by letters, numbers, '-' or '_'.
1361 If REPLACE is a string, the tag will simply be appended to create the link.
1362 If the string contains \"%s\", the tag will be inserted there. If the string
1363 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1364 at that point (see the function `url-hexify-string'). If the string contains
1365 the specifier \"%(my-function)\", then the custom function `my-function' will
1366 be invoked: this function takes the tag as its only argument and must return
1367 a string.
1369 REPLACE may also be a function that will be called with the tag as the
1370 only argument to create the link, which should be returned as a string.
1372 See the manual for examples."
1373 :group 'org-link
1374 :type '(repeat
1375 (cons
1376 (string :tag "Protocol")
1377 (choice
1378 (string :tag "Format")
1379 (function)))))
1381 (defcustom org-descriptive-links t
1382 "Non-nil means Org will display descriptive links.
1383 E.g. [[http://orgmode.org][Org website]] will be displayed as
1384 \"Org Website\", hiding the link itself and just displaying its
1385 description. When set to `nil', Org will display the full links
1386 literally.
1388 You can interactively set the value of this variable by calling
1389 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1390 :group 'org-link
1391 :type 'boolean)
1393 (defcustom org-link-file-path-type 'adaptive
1394 "How the path name in file links should be stored.
1395 Valid values are:
1397 relative Relative to the current directory, i.e. the directory of the file
1398 into which the link is being inserted.
1399 absolute Absolute path, if possible with ~ for home directory.
1400 noabbrev Absolute path, no abbreviation of home directory.
1401 adaptive Use relative path for files in the current directory and sub-
1402 directories of it. For other files, use an absolute path."
1403 :group 'org-link
1404 :type '(choice
1405 (const relative)
1406 (const absolute)
1407 (const noabbrev)
1408 (const adaptive)))
1410 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1411 "Types of links that should be activated in Org-mode files.
1412 This is a list of symbols, each leading to the activation of a certain link
1413 type. In principle, it does not hurt to turn on most link types - there may
1414 be a small gain when turning off unused link types. The types are:
1416 bracket The recommended [[link][description]] or [[link]] links with hiding.
1417 angle Links in angular brackets that may contain whitespace like
1418 <bbdb:Carsten Dominik>.
1419 plain Plain links in normal text, no whitespace, like http://google.com.
1420 radio Text that is matched by a radio target, see manual for details.
1421 tag Tag settings in a headline (link to tag search).
1422 date Time stamps (link to calendar).
1423 footnote Footnote labels.
1425 Changing this variable requires a restart of Emacs to become effective."
1426 :group 'org-link
1427 :type '(set :greedy t
1428 (const :tag "Double bracket links" bracket)
1429 (const :tag "Angular bracket links" angle)
1430 (const :tag "Plain text links" plain)
1431 (const :tag "Radio target matches" radio)
1432 (const :tag "Tags" tag)
1433 (const :tag "Timestamps" date)
1434 (const :tag "Footnotes" footnote)))
1436 (defcustom org-make-link-description-function nil
1437 "Function to use for generating link descriptions from links.
1438 When nil, the link location will be used. This function must take
1439 two parameters: the first one is the link, the second one is the
1440 description generated by `org-insert-link'. The function should
1441 return the description to use."
1442 :group 'org-link
1443 :type 'function)
1445 (defgroup org-link-store nil
1446 "Options concerning storing links in Org-mode."
1447 :tag "Org Store Link"
1448 :group 'org-link)
1450 (defcustom org-url-hexify-p t
1451 "When non-nil, hexify URL when creating a link."
1452 :type 'boolean
1453 :version "24.3"
1454 :group 'org-link-store)
1456 (defcustom org-email-link-description-format "Email %c: %.30s"
1457 "Format of the description part of a link to an email or usenet message.
1458 The following %-escapes will be replaced by corresponding information:
1460 %F full \"From\" field
1461 %f name, taken from \"From\" field, address if no name
1462 %T full \"To\" field
1463 %t first name in \"To\" field, address if no name
1464 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1465 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1466 %s subject
1467 %d date
1468 %m message-id.
1470 You may use normal field width specification between the % and the letter.
1471 This is for example useful to limit the length of the subject.
1473 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1474 :group 'org-link-store
1475 :type 'string)
1477 (defcustom org-from-is-user-regexp
1478 (let (r1 r2)
1479 (when (and user-mail-address (not (string= user-mail-address "")))
1480 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1481 (when (and user-full-name (not (string= user-full-name "")))
1482 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1483 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1484 "Regexp matched against the \"From:\" header of an email or usenet message.
1485 It should match if the message is from the user him/herself."
1486 :group 'org-link-store
1487 :type 'regexp)
1489 (defcustom org-context-in-file-links t
1490 "Non-nil means file links from `org-store-link' contain context.
1491 A search string will be added to the file name with :: as separator and
1492 used to find the context when the link is activated by the command
1493 `org-open-at-point'. When this option is t, the entire active region
1494 will be placed in the search string of the file link. If set to a
1495 positive integer, only the first n lines of context will be stored.
1497 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1498 negates this setting for the duration of the command."
1499 :group 'org-link-store
1500 :type '(choice boolean integer))
1502 (defcustom org-keep-stored-link-after-insertion nil
1503 "Non-nil means keep link in list for entire session.
1505 The command `org-store-link' adds a link pointing to the current
1506 location to an internal list. These links accumulate during a session.
1507 The command `org-insert-link' can be used to insert links into any
1508 Org-mode file (offering completion for all stored links). When this
1509 option is nil, every link which has been inserted once using \\[org-insert-link]
1510 will be removed from the list, to make completing the unused links
1511 more efficient."
1512 :group 'org-link-store
1513 :type 'boolean)
1515 (defgroup org-link-follow nil
1516 "Options concerning following links in Org-mode."
1517 :tag "Org Follow Link"
1518 :group 'org-link)
1520 (defcustom org-link-translation-function nil
1521 "Function to translate links with different syntax to Org syntax.
1522 This can be used to translate links created for example by the Planner
1523 or emacs-wiki packages to Org syntax.
1524 The function must accept two parameters, a TYPE containing the link
1525 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1526 which is everything after the link protocol. It should return a cons
1527 with possibly modified values of type and path.
1528 Org contains a function for this, so if you set this variable to
1529 `org-translate-link-from-planner', you should be able follow many
1530 links created by planner."
1531 :group 'org-link-follow
1532 :type 'function)
1534 (defcustom org-follow-link-hook nil
1535 "Hook that is run after a link has been followed."
1536 :group 'org-link-follow
1537 :type 'hook)
1539 (defcustom org-tab-follows-link nil
1540 "Non-nil means on links TAB will follow the link.
1541 Needs to be set before org.el is loaded.
1542 This really should not be used, it does not make sense, and the
1543 implementation is bad."
1544 :group 'org-link-follow
1545 :type 'boolean)
1547 (defcustom org-return-follows-link nil
1548 "Non-nil means on links RET will follow the link."
1549 :group 'org-link-follow
1550 :type 'boolean)
1552 (defcustom org-mouse-1-follows-link
1553 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1554 "Non-nil means mouse-1 on a link will follow the link.
1555 A longer mouse click will still set point. Does not work on XEmacs.
1556 Needs to be set before org.el is loaded."
1557 :group 'org-link-follow
1558 :type 'boolean)
1560 (defcustom org-mark-ring-length 4
1561 "Number of different positions to be recorded in the ring.
1562 Changing this requires a restart of Emacs to work correctly."
1563 :group 'org-link-follow
1564 :type 'integer)
1566 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1567 "Non-nil means internal links in Org files must exactly match a headline.
1568 When nil, the link search tries to match a phrase with all words
1569 in the search text."
1570 :group 'org-link-follow
1571 :version "24.1"
1572 :type '(choice
1573 (const :tag "Use fuzzy text search" nil)
1574 (const :tag "Match only exact headline" t)
1575 (const :tag "Match exact headline or query to create it"
1576 query-to-create)))
1578 (defcustom org-link-frame-setup
1579 '((vm . vm-visit-folder-other-frame)
1580 (vm-imap . vm-visit-imap-folder-other-frame)
1581 (gnus . org-gnus-no-new-news)
1582 (file . find-file-other-window)
1583 (wl . wl-other-frame))
1584 "Setup the frame configuration for following links.
1585 When following a link with Emacs, it may often be useful to display
1586 this link in another window or frame. This variable can be used to
1587 set this up for the different types of links.
1588 For VM, use any of
1589 `vm-visit-folder'
1590 `vm-visit-folder-other-window'
1591 `vm-visit-folder-other-frame'
1592 For Gnus, use any of
1593 `gnus'
1594 `gnus-other-frame'
1595 `org-gnus-no-new-news'
1596 For FILE, use any of
1597 `find-file'
1598 `find-file-other-window'
1599 `find-file-other-frame'
1600 For Wanderlust use any of
1601 `wl'
1602 `wl-other-frame'
1603 For the calendar, use the variable `calendar-setup'.
1604 For BBDB, it is currently only possible to display the matches in
1605 another window."
1606 :group 'org-link-follow
1607 :type '(list
1608 (cons (const vm)
1609 (choice
1610 (const vm-visit-folder)
1611 (const vm-visit-folder-other-window)
1612 (const vm-visit-folder-other-frame)))
1613 (cons (const gnus)
1614 (choice
1615 (const gnus)
1616 (const gnus-other-frame)
1617 (const org-gnus-no-new-news)))
1618 (cons (const file)
1619 (choice
1620 (const find-file)
1621 (const find-file-other-window)
1622 (const find-file-other-frame)))
1623 (cons (const wl)
1624 (choice
1625 (const wl)
1626 (const wl-other-frame)))))
1628 (defcustom org-display-internal-link-with-indirect-buffer nil
1629 "Non-nil means use indirect buffer to display infile links.
1630 Activating internal links (from one location in a file to another location
1631 in the same file) normally just jumps to the location. When the link is
1632 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1633 is displayed in
1634 another window. When this option is set, the other window actually displays
1635 an indirect buffer clone of the current buffer, to avoid any visibility
1636 changes to the current buffer."
1637 :group 'org-link-follow
1638 :type 'boolean)
1640 (defcustom org-open-non-existing-files nil
1641 "Non-nil means `org-open-file' will open non-existing files.
1642 When nil, an error will be generated.
1643 This variable applies only to external applications because they
1644 might choke on non-existing files. If the link is to a file that
1645 will be opened in Emacs, the variable is ignored."
1646 :group 'org-link-follow
1647 :type 'boolean)
1649 (defcustom org-open-directory-means-index-dot-org nil
1650 "Non-nil means a link to a directory really means to index.org.
1651 When nil, following a directory link will run dired or open a finder/explorer
1652 window on that directory."
1653 :group 'org-link-follow
1654 :type 'boolean)
1656 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1657 "Function and arguments to call for following mailto links.
1658 This is a list with the first element being a Lisp function, and the
1659 remaining elements being arguments to the function. In string arguments,
1660 %a will be replaced by the address, and %s will be replaced by the subject
1661 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1662 :group 'org-link-follow
1663 :type '(choice
1664 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1665 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1666 (const :tag "message-mail" (message-mail "%a" "%s"))
1667 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1669 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1670 "Non-nil means ask for confirmation before executing shell links.
1671 Shell links can be dangerous: just think about a link
1673 [[shell:rm -rf ~/*][Google Search]]
1675 This link would show up in your Org-mode document as \"Google Search\",
1676 but really it would remove your entire home directory.
1677 Therefore we advise against setting this variable to nil.
1678 Just change it to `y-or-n-p' if you want to confirm with a
1679 single keystroke rather than having to type \"yes\"."
1680 :group 'org-link-follow
1681 :type '(choice
1682 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1683 (const :tag "with y-or-n (faster)" y-or-n-p)
1684 (const :tag "no confirmation (dangerous)" nil)))
1685 (put 'org-confirm-shell-link-function
1686 'safe-local-variable
1687 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1689 (defcustom org-confirm-shell-link-not-regexp ""
1690 "A regexp to skip confirmation for shell links."
1691 :group 'org-link-follow
1692 :version "24.1"
1693 :type 'regexp)
1695 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1696 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1697 Elisp links can be dangerous: just think about a link
1699 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1701 This link would show up in your Org-mode document as \"Google Search\",
1702 but really it would remove your entire home directory.
1703 Therefore we advise against setting this variable to nil.
1704 Just change it to `y-or-n-p' if you want to confirm with a
1705 single keystroke rather than having to type \"yes\"."
1706 :group 'org-link-follow
1707 :type '(choice
1708 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1709 (const :tag "with y-or-n (faster)" y-or-n-p)
1710 (const :tag "no confirmation (dangerous)" nil)))
1711 (put 'org-confirm-shell-link-function
1712 'safe-local-variable
1713 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1715 (defcustom org-confirm-elisp-link-not-regexp ""
1716 "A regexp to skip confirmation for Elisp links."
1717 :group 'org-link-follow
1718 :version "24.1"
1719 :type 'regexp)
1721 (defconst org-file-apps-defaults-gnu
1722 '((remote . emacs)
1723 (system . mailcap)
1724 (t . mailcap))
1725 "Default file applications on a UNIX or GNU/Linux system.
1726 See `org-file-apps'.")
1728 (defconst org-file-apps-defaults-macosx
1729 '((remote . emacs)
1730 (t . "open %s")
1731 (system . "open %s")
1732 ("ps.gz" . "gv %s")
1733 ("eps.gz" . "gv %s")
1734 ("dvi" . "xdvi %s")
1735 ("fig" . "xfig %s"))
1736 "Default file applications on a MacOS X system.
1737 The system \"open\" is known as a default, but we use X11 applications
1738 for some files for which the OS does not have a good default.
1739 See `org-file-apps'.")
1741 (defconst org-file-apps-defaults-windowsnt
1742 (list
1743 '(remote . emacs)
1744 (cons t
1745 (list (if (featurep 'xemacs)
1746 'mswindows-shell-execute
1747 'w32-shell-execute)
1748 "open" 'file))
1749 (cons 'system
1750 (list (if (featurep 'xemacs)
1751 'mswindows-shell-execute
1752 'w32-shell-execute)
1753 "open" 'file)))
1754 "Default file applications on a Windows NT system.
1755 The system \"open\" is used for most files.
1756 See `org-file-apps'.")
1758 (defcustom org-file-apps
1760 (auto-mode . emacs)
1761 ("\\.mm\\'" . default)
1762 ("\\.x?html?\\'" . default)
1763 ("\\.pdf\\'" . default)
1765 "External applications for opening `file:path' items in a document.
1766 Org-mode uses system defaults for different file types, but
1767 you can use this variable to set the application for a given file
1768 extension. The entries in this list are cons cells where the car identifies
1769 files and the cdr the corresponding command. Possible values for the
1770 file identifier are
1771 \"string\" A string as a file identifier can be interpreted in different
1772 ways, depending on its contents:
1774 - Alphanumeric characters only:
1775 Match links with this file extension.
1776 Example: (\"pdf\" . \"evince %s\")
1777 to open PDFs with evince.
1779 - Regular expression: Match links where the
1780 filename matches the regexp. If you want to
1781 use groups here, use shy groups.
1783 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1784 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1785 to open *.html and *.xhtml with firefox.
1787 - Regular expression which contains (non-shy) groups:
1788 Match links where the whole link, including \"::\", and
1789 anything after that, matches the regexp.
1790 In a custom command string, %1, %2, etc. are replaced with
1791 the parts of the link that were matched by the groups.
1792 For backwards compatibility, if a command string is given
1793 that does not use any of the group matches, this case is
1794 handled identically to the second one (i.e. match against
1795 file name only).
1796 In a custom lisp form, you can access the group matches with
1797 (match-string n link).
1799 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1800 to open [[file:document.pdf::5]] with evince at page 5.
1802 `directory' Matches a directory
1803 `remote' Matches a remote file, accessible through tramp or efs.
1804 Remote files most likely should be visited through Emacs
1805 because external applications cannot handle such paths.
1806 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1807 so all files Emacs knows how to handle. Using this with
1808 command `emacs' will open most files in Emacs. Beware that this
1809 will also open html files inside Emacs, unless you add
1810 (\"html\" . default) to the list as well.
1811 t Default for files not matched by any of the other options.
1812 `system' The system command to open files, like `open' on Windows
1813 and Mac OS X, and mailcap under GNU/Linux. This is the command
1814 that will be selected if you call `C-c C-o' with a double
1815 \\[universal-argument] \\[universal-argument] prefix.
1817 Possible values for the command are:
1818 `emacs' The file will be visited by the current Emacs process.
1819 `default' Use the default application for this file type, which is the
1820 association for t in the list, most likely in the system-specific
1821 part.
1822 This can be used to overrule an unwanted setting in the
1823 system-specific variable.
1824 `system' Use the system command for opening files, like \"open\".
1825 This command is specified by the entry whose car is `system'.
1826 Most likely, the system-specific version of this variable
1827 does define this command, but you can overrule/replace it
1828 here.
1829 string A command to be executed by a shell; %s will be replaced
1830 by the path to the file.
1831 sexp A Lisp form which will be evaluated. The file path will
1832 be available in the Lisp variable `file'.
1833 For more examples, see the system specific constants
1834 `org-file-apps-defaults-macosx'
1835 `org-file-apps-defaults-windowsnt'
1836 `org-file-apps-defaults-gnu'."
1837 :group 'org-link-follow
1838 :type '(repeat
1839 (cons (choice :value ""
1840 (string :tag "Extension")
1841 (const :tag "System command to open files" system)
1842 (const :tag "Default for unrecognized files" t)
1843 (const :tag "Remote file" remote)
1844 (const :tag "Links to a directory" directory)
1845 (const :tag "Any files that have Emacs modes"
1846 auto-mode))
1847 (choice :value ""
1848 (const :tag "Visit with Emacs" emacs)
1849 (const :tag "Use default" default)
1850 (const :tag "Use the system command" system)
1851 (string :tag "Command")
1852 (sexp :tag "Lisp form")))))
1854 (defcustom org-doi-server-url "http://dx.doi.org/"
1855 "The URL of the DOI server."
1856 :type 'string
1857 :version "24.3"
1858 :group 'org-link-follow)
1860 (defgroup org-refile nil
1861 "Options concerning refiling entries in Org-mode."
1862 :tag "Org Refile"
1863 :group 'org)
1865 (defcustom org-directory "~/org"
1866 "Directory with org files.
1867 This is just a default location to look for Org files. There is no need
1868 at all to put your files into this directory. It is only used in the
1869 following situations:
1871 1. When a capture template specifies a target file that is not an
1872 absolute path. The path will then be interpreted relative to
1873 `org-directory'
1874 2. When a capture note is filed away in an interactive way (when exiting the
1875 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1876 with `org-directory' as the default path."
1877 :group 'org-refile
1878 :group 'org-remember
1879 :group 'org-capture
1880 :type 'directory)
1882 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1883 "Default target for storing notes.
1884 Used as a fall back file for org-remember.el and org-capture.el, for
1885 templates that do not specify a target file."
1886 :group 'org-refile
1887 :group 'org-remember
1888 :group 'org-capture
1889 :type '(choice
1890 (const :tag "Default from remember-data-file" nil)
1891 file))
1893 (defcustom org-goto-interface 'outline
1894 "The default interface to be used for `org-goto'.
1895 Allowed values are:
1896 outline The interface shows an outline of the relevant file
1897 and the correct heading is found by moving through
1898 the outline or by searching with incremental search.
1899 outline-path-completion Headlines in the current buffer are offered via
1900 completion. This is the interface also used by
1901 the refile command."
1902 :group 'org-refile
1903 :type '(choice
1904 (const :tag "Outline" outline)
1905 (const :tag "Outline-path-completion" outline-path-completion)))
1907 (defcustom org-goto-max-level 5
1908 "Maximum target level when running `org-goto' with refile interface."
1909 :group 'org-refile
1910 :type 'integer)
1912 (defcustom org-reverse-note-order nil
1913 "Non-nil means store new notes at the beginning of a file or entry.
1914 When nil, new notes will be filed to the end of a file or entry.
1915 This can also be a list with cons cells of regular expressions that
1916 are matched against file names, and values."
1917 :group 'org-remember
1918 :group 'org-capture
1919 :group 'org-refile
1920 :type '(choice
1921 (const :tag "Reverse always" t)
1922 (const :tag "Reverse never" nil)
1923 (repeat :tag "By file name regexp"
1924 (cons regexp boolean))))
1926 (defcustom org-log-refile nil
1927 "Information to record when a task is refiled.
1929 Possible values are:
1931 nil Don't add anything
1932 time Add a time stamp to the task
1933 note Prompt for a note and add it with template `org-log-note-headings'
1935 This option can also be set with on a per-file-basis with
1937 #+STARTUP: nologrefile
1938 #+STARTUP: logrefile
1939 #+STARTUP: lognoterefile
1941 You can have local logging settings for a subtree by setting the LOGGING
1942 property to one or more of these keywords.
1944 When bulk-refiling from the agenda, the value `note' is forbidden and
1945 will temporarily be changed to `time'."
1946 :group 'org-refile
1947 :group 'org-progress
1948 :version "24.1"
1949 :type '(choice
1950 (const :tag "No logging" nil)
1951 (const :tag "Record timestamp" time)
1952 (const :tag "Record timestamp with note." note)))
1954 (defcustom org-refile-targets nil
1955 "Targets for refiling entries with \\[org-refile].
1956 This is a list of cons cells. Each cell contains:
1957 - a specification of the files to be considered, either a list of files,
1958 or a symbol whose function or variable value will be used to retrieve
1959 a file name or a list of file names. If you use `org-agenda-files' for
1960 that, all agenda files will be scanned for targets. Nil means consider
1961 headings in the current buffer.
1962 - A specification of how to find candidate refile targets. This may be
1963 any of:
1964 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1965 This tag has to be present in all target headlines, inheritance will
1966 not be considered.
1967 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1968 todo keyword.
1969 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1970 headlines that are refiling targets.
1971 - a cons cell (:level . N). Any headline of level N is considered a target.
1972 Note that, when `org-odd-levels-only' is set, level corresponds to
1973 order in hierarchy, not to the number of stars.
1974 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1975 Note that, when `org-odd-levels-only' is set, level corresponds to
1976 order in hierarchy, not to the number of stars.
1978 Each element of this list generates a set of possible targets.
1979 The union of these sets is presented (with completion) to
1980 the user by `org-refile'.
1982 You can set the variable `org-refile-target-verify-function' to a function
1983 to verify each headline found by the simple criteria above.
1985 When this variable is nil, all top-level headlines in the current buffer
1986 are used, equivalent to the value `((nil . (:level . 1))'."
1987 :group 'org-refile
1988 :type '(repeat
1989 (cons
1990 (choice :value org-agenda-files
1991 (const :tag "All agenda files" org-agenda-files)
1992 (const :tag "Current buffer" nil)
1993 (function) (variable) (file))
1994 (choice :tag "Identify target headline by"
1995 (cons :tag "Specific tag" (const :value :tag) (string))
1996 (cons :tag "TODO keyword" (const :value :todo) (string))
1997 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1998 (cons :tag "Level number" (const :value :level) (integer))
1999 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2001 (defcustom org-refile-target-verify-function nil
2002 "Function to verify if the headline at point should be a refile target.
2003 The function will be called without arguments, with point at the
2004 beginning of the headline. It should return t and leave point
2005 where it is if the headline is a valid target for refiling.
2007 If the target should not be selected, the function must return nil.
2008 In addition to this, it may move point to a place from where the search
2009 should be continued. For example, the function may decide that the entire
2010 subtree of the current entry should be excluded and move point to the end
2011 of the subtree."
2012 :group 'org-refile
2013 :type 'function)
2015 (defcustom org-refile-use-cache nil
2016 "Non-nil means cache refile targets to speed up the process.
2017 The cache for a particular file will be updated automatically when
2018 the buffer has been killed, or when any of the marker used for flagging
2019 refile targets no longer points at a live buffer.
2020 If you have added new entries to a buffer that might themselves be targets,
2021 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2022 find that easier, `C-u C-u C-u C-c C-w'."
2023 :group 'org-refile
2024 :version "24.1"
2025 :type 'boolean)
2027 (defcustom org-refile-use-outline-path nil
2028 "Non-nil means provide refile targets as paths.
2029 So a level 3 headline will be available as level1/level2/level3.
2031 When the value is `file', also include the file name (without directory)
2032 into the path. In this case, you can also stop the completion after
2033 the file name, to get entries inserted as top level in the file.
2035 When `full-file-path', include the full file path."
2036 :group 'org-refile
2037 :type '(choice
2038 (const :tag "Not" nil)
2039 (const :tag "Yes" t)
2040 (const :tag "Start with file name" file)
2041 (const :tag "Start with full file path" full-file-path)))
2043 (defcustom org-outline-path-complete-in-steps t
2044 "Non-nil means complete the outline path in hierarchical steps.
2045 When Org-mode uses the refile interface to select an outline path
2046 \(see variable `org-refile-use-outline-path'), the completion of
2047 the path can be done is a single go, or if can be done in steps down
2048 the headline hierarchy. Going in steps is probably the best if you
2049 do not use a special completion package like `ido' or `icicles'.
2050 However, when using these packages, going in one step can be very
2051 fast, while still showing the whole path to the entry."
2052 :group 'org-refile
2053 :type 'boolean)
2055 (defcustom org-refile-allow-creating-parent-nodes nil
2056 "Non-nil means allow to create new nodes as refile targets.
2057 New nodes are then created by adding \"/new node name\" to the completion
2058 of an existing node. When the value of this variable is `confirm',
2059 new node creation must be confirmed by the user (recommended)
2060 When nil, the completion must match an existing entry.
2062 Note that, if the new heading is not seen by the criteria
2063 listed in `org-refile-targets', multiple instances of the same
2064 heading would be created by trying again to file under the new
2065 heading."
2066 :group 'org-refile
2067 :type '(choice
2068 (const :tag "Never" nil)
2069 (const :tag "Always" t)
2070 (const :tag "Prompt for confirmation" confirm)))
2072 (defcustom org-refile-active-region-within-subtree nil
2073 "Non-nil means also refile active region within a subtree.
2075 By default `org-refile' doesn't allow refiling regions if they
2076 don't contain a set of subtrees, but it might be convenient to
2077 do so sometimes: in that case, the first line of the region is
2078 converted to a headline before refiling."
2079 :group 'org-refile
2080 :version "24.1"
2081 :type 'boolean)
2083 (defgroup org-todo nil
2084 "Options concerning TODO items in Org-mode."
2085 :tag "Org TODO"
2086 :group 'org)
2088 (defgroup org-progress nil
2089 "Options concerning Progress logging in Org-mode."
2090 :tag "Org Progress"
2091 :group 'org-time)
2093 (defvar org-todo-interpretation-widgets
2094 '((:tag "Sequence (cycling hits every state)" sequence)
2095 (:tag "Type (cycling directly to DONE)" type))
2096 "The available interpretation symbols for customizing `org-todo-keywords'.
2097 Interested libraries should add to this list.")
2099 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2100 "List of TODO entry keyword sequences and their interpretation.
2101 \\<org-mode-map>This is a list of sequences.
2103 Each sequence starts with a symbol, either `sequence' or `type',
2104 indicating if the keywords should be interpreted as a sequence of
2105 action steps, or as different types of TODO items. The first
2106 keywords are states requiring action - these states will select a headline
2107 for inclusion into the global TODO list Org-mode produces. If one of
2108 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2109 signify that no further action is necessary. If \"|\" is not found,
2110 the last keyword is treated as the only DONE state of the sequence.
2112 The command \\[org-todo] cycles an entry through these states, and one
2113 additional state where no keyword is present. For details about this
2114 cycling, see the manual.
2116 TODO keywords and interpretation can also be set on a per-file basis with
2117 the special #+SEQ_TODO and #+TYP_TODO lines.
2119 Each keyword can optionally specify a character for fast state selection
2120 \(in combination with the variable `org-use-fast-todo-selection')
2121 and specifiers for state change logging, using the same syntax that
2122 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2123 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2124 indicates to record a time stamp each time this state is selected.
2126 Each keyword may also specify if a timestamp or a note should be
2127 recorded when entering or leaving the state, by adding additional
2128 characters in the parenthesis after the keyword. This looks like this:
2129 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2130 record only the time of the state change. With X and Y being either
2131 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2132 Y when leaving the state if and only if the *target* state does not
2133 define X. You may omit any of the fast-selection key or X or /Y,
2134 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2136 For backward compatibility, this variable may also be just a list
2137 of keywords. In this case the interpretation (sequence or type) will be
2138 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2139 :group 'org-todo
2140 :group 'org-keywords
2141 :type '(choice
2142 (repeat :tag "Old syntax, just keywords"
2143 (string :tag "Keyword"))
2144 (repeat :tag "New syntax"
2145 (cons
2146 (choice
2147 :tag "Interpretation"
2148 ;;Quick and dirty way to see
2149 ;;`org-todo-interpretations'. This takes the
2150 ;;place of item arguments
2151 :convert-widget
2152 (lambda (widget)
2153 (widget-put widget
2154 :args (mapcar
2155 #'(lambda (x)
2156 (widget-convert
2157 (cons 'const x)))
2158 org-todo-interpretation-widgets))
2159 widget))
2160 (repeat
2161 (string :tag "Keyword"))))))
2163 (defvar org-todo-keywords-1 nil
2164 "All TODO and DONE keywords active in a buffer.")
2165 (make-variable-buffer-local 'org-todo-keywords-1)
2166 (defvar org-todo-keywords-for-agenda nil)
2167 (defvar org-done-keywords-for-agenda nil)
2168 (defvar org-drawers-for-agenda nil)
2169 (defvar org-todo-keyword-alist-for-agenda nil)
2170 (defvar org-tag-alist-for-agenda nil)
2171 (defvar org-agenda-contributing-files nil)
2172 (defvar org-not-done-keywords nil)
2173 (make-variable-buffer-local 'org-not-done-keywords)
2174 (defvar org-done-keywords nil)
2175 (make-variable-buffer-local 'org-done-keywords)
2176 (defvar org-todo-heads nil)
2177 (make-variable-buffer-local 'org-todo-heads)
2178 (defvar org-todo-sets nil)
2179 (make-variable-buffer-local 'org-todo-sets)
2180 (defvar org-todo-log-states nil)
2181 (make-variable-buffer-local 'org-todo-log-states)
2182 (defvar org-todo-kwd-alist nil)
2183 (make-variable-buffer-local 'org-todo-kwd-alist)
2184 (defvar org-todo-key-alist nil)
2185 (make-variable-buffer-local 'org-todo-key-alist)
2186 (defvar org-todo-key-trigger nil)
2187 (make-variable-buffer-local 'org-todo-key-trigger)
2189 (defcustom org-todo-interpretation 'sequence
2190 "Controls how TODO keywords are interpreted.
2191 This variable is in principle obsolete and is only used for
2192 backward compatibility, if the interpretation of todo keywords is
2193 not given already in `org-todo-keywords'. See that variable for
2194 more information."
2195 :group 'org-todo
2196 :group 'org-keywords
2197 :type '(choice (const sequence)
2198 (const type)))
2200 (defcustom org-use-fast-todo-selection t
2201 "Non-nil means use the fast todo selection scheme with C-c C-t.
2202 This variable describes if and under what circumstances the cycling
2203 mechanism for TODO keywords will be replaced by a single-key, direct
2204 selection scheme.
2206 When nil, fast selection is never used.
2208 When the symbol `prefix', it will be used when `org-todo' is called
2209 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2210 `C-u t' in an agenda buffer.
2212 When t, fast selection is used by default. In this case, the prefix
2213 argument forces cycling instead.
2215 In all cases, the special interface is only used if access keys have
2216 actually been assigned by the user, i.e. if keywords in the configuration
2217 are followed by a letter in parenthesis, like TODO(t)."
2218 :group 'org-todo
2219 :type '(choice
2220 (const :tag "Never" nil)
2221 (const :tag "By default" t)
2222 (const :tag "Only with C-u C-c C-t" prefix)))
2224 (defcustom org-provide-todo-statistics t
2225 "Non-nil means update todo statistics after insert and toggle.
2226 ALL-HEADLINES means update todo statistics by including headlines
2227 with no TODO keyword as well, counting them as not done.
2228 A list of TODO keywords means the same, but skip keywords that are
2229 not in this list.
2231 When this is set, todo statistics is updated in the parent of the
2232 current entry each time a todo state is changed."
2233 :group 'org-todo
2234 :type '(choice
2235 (const :tag "Yes, only for TODO entries" t)
2236 (const :tag "Yes, including all entries" 'all-headlines)
2237 (repeat :tag "Yes, for TODOs in this list"
2238 (string :tag "TODO keyword"))
2239 (other :tag "No TODO statistics" nil)))
2241 (defcustom org-hierarchical-todo-statistics t
2242 "Non-nil means TODO statistics covers just direct children.
2243 When nil, all entries in the subtree are considered.
2244 This has only an effect if `org-provide-todo-statistics' is set.
2245 To set this to nil for only a single subtree, use a COOKIE_DATA
2246 property and include the word \"recursive\" into the value."
2247 :group 'org-todo
2248 :type 'boolean)
2250 (defcustom org-after-todo-state-change-hook nil
2251 "Hook which is run after the state of a TODO item was changed.
2252 The new state (a string with a TODO keyword, or nil) is available in the
2253 Lisp variable `org-state'."
2254 :group 'org-todo
2255 :type 'hook)
2257 (defvar org-blocker-hook nil
2258 "Hook for functions that are allowed to block a state change.
2260 Functions in this hook should not modify the buffer.
2261 Each function gets as its single argument a property list,
2262 see `org-trigger-hook' for more information about this list.
2264 If any of the functions in this hook returns nil, the state change
2265 is blocked.")
2267 (defvar org-trigger-hook nil
2268 "Hook for functions that are triggered by a state change.
2270 Each function gets as its single argument a property list with at
2271 least the following elements:
2273 (:type type-of-change :position pos-at-entry-start
2274 :from old-state :to new-state)
2276 Depending on the type, more properties may be present.
2278 This mechanism is currently implemented for:
2280 TODO state changes
2281 ------------------
2282 :type todo-state-change
2283 :from previous state (keyword as a string), or nil, or a symbol
2284 'todo' or 'done', to indicate the general type of state.
2285 :to new state, like in :from")
2287 (defcustom org-enforce-todo-dependencies nil
2288 "Non-nil means undone TODO entries will block switching the parent to DONE.
2289 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2290 be blocked if any prior sibling is not yet done.
2291 Finally, if the parent is blocked because of ordered siblings of its own,
2292 the child will also be blocked."
2293 :set (lambda (var val)
2294 (set var val)
2295 (if val
2296 (add-hook 'org-blocker-hook
2297 'org-block-todo-from-children-or-siblings-or-parent)
2298 (remove-hook 'org-blocker-hook
2299 'org-block-todo-from-children-or-siblings-or-parent)))
2300 :group 'org-todo
2301 :type 'boolean)
2303 (defcustom org-enforce-todo-checkbox-dependencies nil
2304 "Non-nil means unchecked boxes will block switching the parent to DONE.
2305 When this is nil, checkboxes have no influence on switching TODO states.
2306 When non-nil, you first need to check off all check boxes before the TODO
2307 entry can be switched to DONE.
2308 This variable needs to be set before org.el is loaded, and you need to
2309 restart Emacs after a change to make the change effective. The only way
2310 to change is while Emacs is running is through the customize interface."
2311 :set (lambda (var val)
2312 (set var val)
2313 (if val
2314 (add-hook 'org-blocker-hook
2315 'org-block-todo-from-checkboxes)
2316 (remove-hook 'org-blocker-hook
2317 'org-block-todo-from-checkboxes)))
2318 :group 'org-todo
2319 :type 'boolean)
2321 (defcustom org-treat-insert-todo-heading-as-state-change nil
2322 "Non-nil means inserting a TODO heading is treated as state change.
2323 So when the command \\[org-insert-todo-heading] is used, state change
2324 logging will apply if appropriate. When nil, the new TODO item will
2325 be inserted directly, and no logging will take place."
2326 :group 'org-todo
2327 :type 'boolean)
2329 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2330 "Non-nil means switching TODO states with S-cursor counts as state change.
2331 This is the default behavior. However, setting this to nil allows a
2332 convenient way to select a TODO state and bypass any logging associated
2333 with that."
2334 :group 'org-todo
2335 :type 'boolean)
2337 (defcustom org-todo-state-tags-triggers nil
2338 "Tag changes that should be triggered by TODO state changes.
2339 This is a list. Each entry is
2341 (state-change (tag . flag) .......)
2343 State-change can be a string with a state, and empty string to indicate the
2344 state that has no TODO keyword, or it can be one of the symbols `todo'
2345 or `done', meaning any not-done or done state, respectively."
2346 :group 'org-todo
2347 :group 'org-tags
2348 :type '(repeat
2349 (cons (choice :tag "When changing to"
2350 (const :tag "Not-done state" todo)
2351 (const :tag "Done state" done)
2352 (string :tag "State"))
2353 (repeat
2354 (cons :tag "Tag action"
2355 (string :tag "Tag")
2356 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2358 (defcustom org-log-done nil
2359 "Information to record when a task moves to the DONE state.
2361 Possible values are:
2363 nil Don't add anything, just change the keyword
2364 time Add a time stamp to the task
2365 note Prompt for a note and add it with template `org-log-note-headings'
2367 This option can also be set with on a per-file-basis with
2369 #+STARTUP: nologdone
2370 #+STARTUP: logdone
2371 #+STARTUP: lognotedone
2373 You can have local logging settings for a subtree by setting the LOGGING
2374 property to one or more of these keywords."
2375 :group 'org-todo
2376 :group 'org-progress
2377 :type '(choice
2378 (const :tag "No logging" nil)
2379 (const :tag "Record CLOSED timestamp" time)
2380 (const :tag "Record CLOSED timestamp with note." note)))
2382 ;; Normalize old uses of org-log-done.
2383 (cond
2384 ((eq org-log-done t) (setq org-log-done 'time))
2385 ((and (listp org-log-done) (memq 'done org-log-done))
2386 (setq org-log-done 'note)))
2388 (defcustom org-log-reschedule nil
2389 "Information to record when the scheduling date of a tasks is modified.
2391 Possible values are:
2393 nil Don't add anything, just change the date
2394 time Add a time stamp to the task
2395 note Prompt for a note and add it with template `org-log-note-headings'
2397 This option can also be set with on a per-file-basis with
2399 #+STARTUP: nologreschedule
2400 #+STARTUP: logreschedule
2401 #+STARTUP: lognotereschedule"
2402 :group 'org-todo
2403 :group 'org-progress
2404 :type '(choice
2405 (const :tag "No logging" nil)
2406 (const :tag "Record timestamp" time)
2407 (const :tag "Record timestamp with note." note)))
2409 (defcustom org-log-redeadline nil
2410 "Information to record when the deadline date of a tasks is modified.
2412 Possible values are:
2414 nil Don't add anything, just change the date
2415 time Add a time stamp to the task
2416 note Prompt for a note and add it with template `org-log-note-headings'
2418 This option can also be set with on a per-file-basis with
2420 #+STARTUP: nologredeadline
2421 #+STARTUP: logredeadline
2422 #+STARTUP: lognoteredeadline
2424 You can have local logging settings for a subtree by setting the LOGGING
2425 property to one or more of these keywords."
2426 :group 'org-todo
2427 :group 'org-progress
2428 :type '(choice
2429 (const :tag "No logging" nil)
2430 (const :tag "Record timestamp" time)
2431 (const :tag "Record timestamp with note." note)))
2433 (defcustom org-log-note-clock-out nil
2434 "Non-nil means record a note when clocking out of an item.
2435 This can also be configured on a per-file basis by adding one of
2436 the following lines anywhere in the buffer:
2438 #+STARTUP: lognoteclock-out
2439 #+STARTUP: nolognoteclock-out"
2440 :group 'org-todo
2441 :group 'org-progress
2442 :type 'boolean)
2444 (defcustom org-log-done-with-time t
2445 "Non-nil means the CLOSED time stamp will contain date and time.
2446 When nil, only the date will be recorded."
2447 :group 'org-progress
2448 :type 'boolean)
2450 (defcustom org-log-note-headings
2451 '((done . "CLOSING NOTE %t")
2452 (state . "State %-12s from %-12S %t")
2453 (note . "Note taken on %t")
2454 (reschedule . "Rescheduled from %S on %t")
2455 (delschedule . "Not scheduled, was %S on %t")
2456 (redeadline . "New deadline from %S on %t")
2457 (deldeadline . "Removed deadline, was %S on %t")
2458 (refile . "Refiled on %t")
2459 (clock-out . ""))
2460 "Headings for notes added to entries.
2461 The value is an alist, with the car being a symbol indicating the note
2462 context, and the cdr is the heading to be used. The heading may also be the
2463 empty string.
2464 %t in the heading will be replaced by a time stamp.
2465 %T will be an active time stamp instead the default inactive one
2466 %d will be replaced by a short-format time stamp.
2467 %D will be replaced by an active short-format time stamp.
2468 %s will be replaced by the new TODO state, in double quotes.
2469 %S will be replaced by the old TODO state, in double quotes.
2470 %u will be replaced by the user name.
2471 %U will be replaced by the full user name.
2473 In fact, it is not a good idea to change the `state' entry, because
2474 agenda log mode depends on the format of these entries."
2475 :group 'org-todo
2476 :group 'org-progress
2477 :type '(list :greedy t
2478 (cons (const :tag "Heading when closing an item" done) string)
2479 (cons (const :tag
2480 "Heading when changing todo state (todo sequence only)"
2481 state) string)
2482 (cons (const :tag "Heading when just taking a note" note) string)
2483 (cons (const :tag "Heading when clocking out" clock-out) string)
2484 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2485 (cons (const :tag "Heading when rescheduling" reschedule) string)
2486 (cons (const :tag "Heading when changing deadline" redeadline) string)
2487 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2488 (cons (const :tag "Heading when refiling" refile) string)))
2490 (unless (assq 'note org-log-note-headings)
2491 (push '(note . "%t") org-log-note-headings))
2493 (defcustom org-log-into-drawer nil
2494 "Non-nil means insert state change notes and time stamps into a drawer.
2495 When nil, state changes notes will be inserted after the headline and
2496 any scheduling and clock lines, but not inside a drawer.
2498 The value of this variable should be the name of the drawer to use.
2499 LOGBOOK is proposed as the default drawer for this purpose, you can
2500 also set this to a string to define the drawer of your choice.
2502 A value of t is also allowed, representing \"LOGBOOK\".
2504 A value of t or nil can also be set with on a per-file-basis with
2506 #+STARTUP: logdrawer
2507 #+STARTUP: nologdrawer
2509 If this variable is set, `org-log-state-notes-insert-after-drawers'
2510 will be ignored.
2512 You can set the property LOG_INTO_DRAWER to overrule this setting for
2513 a subtree."
2514 :group 'org-todo
2515 :group 'org-progress
2516 :type '(choice
2517 (const :tag "Not into a drawer" nil)
2518 (const :tag "LOGBOOK" t)
2519 (string :tag "Other")))
2521 (if (fboundp 'defvaralias)
2522 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2524 (defun org-log-into-drawer ()
2525 "Return the value of `org-log-into-drawer', but let properties overrule.
2526 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2527 used instead of the default value."
2528 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2529 (cond
2530 ((not p) org-log-into-drawer)
2531 ((equal p "nil") nil)
2532 ((equal p "t") "LOGBOOK")
2533 (t p))))
2535 (defcustom org-log-state-notes-insert-after-drawers nil
2536 "Non-nil means insert state change notes after any drawers in entry.
2537 Only the drawers that *immediately* follow the headline and the
2538 deadline/scheduled line are skipped.
2539 When nil, insert notes right after the heading and perhaps the line
2540 with deadline/scheduling if present.
2542 This variable will have no effect if `org-log-into-drawer' is
2543 set."
2544 :group 'org-todo
2545 :group 'org-progress
2546 :type 'boolean)
2548 (defcustom org-log-states-order-reversed t
2549 "Non-nil means the latest state note will be directly after heading.
2550 When nil, the state change notes will be ordered according to time.
2552 This option can also be set with on a per-file-basis with
2554 #+STARTUP: logstatesreversed
2555 #+STARTUP: nologstatesreversed"
2556 :group 'org-todo
2557 :group 'org-progress
2558 :type 'boolean)
2560 (defcustom org-todo-repeat-to-state nil
2561 "The TODO state to which a repeater should return the repeating task.
2562 By default this is the first task in a TODO sequence, or the previous state
2563 in a TODO_TYP set. But you can specify another task here.
2564 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2565 :group 'org-todo
2566 :version "24.1"
2567 :type '(choice (const :tag "Head of sequence" nil)
2568 (string :tag "Specific state")))
2570 (defcustom org-log-repeat 'time
2571 "Non-nil means record moving through the DONE state when triggering repeat.
2572 An auto-repeating task is immediately switched back to TODO when
2573 marked DONE. If you are not logging state changes (by adding \"@\"
2574 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2575 record a closing note, there will be no record of the task moving
2576 through DONE. This variable forces taking a note anyway.
2578 nil Don't force a record
2579 time Record a time stamp
2580 note Prompt for a note and add it with template `org-log-note-headings'
2582 This option can also be set with on a per-file-basis with
2584 #+STARTUP: nologrepeat
2585 #+STARTUP: logrepeat
2586 #+STARTUP: lognoterepeat
2588 You can have local logging settings for a subtree by setting the LOGGING
2589 property to one or more of these keywords."
2590 :group 'org-todo
2591 :group 'org-progress
2592 :type '(choice
2593 (const :tag "Don't force a record" nil)
2594 (const :tag "Force recording the DONE state" time)
2595 (const :tag "Force recording a note with the DONE state" note)))
2598 (defgroup org-priorities nil
2599 "Priorities in Org-mode."
2600 :tag "Org Priorities"
2601 :group 'org-todo)
2603 (defcustom org-enable-priority-commands t
2604 "Non-nil means priority commands are active.
2605 When nil, these commands will be disabled, so that you never accidentally
2606 set a priority."
2607 :group 'org-priorities
2608 :type 'boolean)
2610 (defcustom org-highest-priority ?A
2611 "The highest priority of TODO items. A character like ?A, ?B etc.
2612 Must have a smaller ASCII number than `org-lowest-priority'."
2613 :group 'org-priorities
2614 :type 'character)
2616 (defcustom org-lowest-priority ?C
2617 "The lowest priority of TODO items. A character like ?A, ?B etc.
2618 Must have a larger ASCII number than `org-highest-priority'."
2619 :group 'org-priorities
2620 :type 'character)
2622 (defcustom org-default-priority ?B
2623 "The default priority of TODO items.
2624 This is the priority an item gets if no explicit priority is given.
2625 When starting to cycle on an empty priority the first step in the cycle
2626 depends on `org-priority-start-cycle-with-default'. The resulting first
2627 step priority must not exceed the range from `org-highest-priority' to
2628 `org-lowest-priority' which means that `org-default-priority' has to be
2629 in this range exclusive or inclusive the range boundaries. Else the
2630 first step refuses to set the default and the second will fall back
2631 to (depending on the command used) the highest or lowest priority."
2632 :group 'org-priorities
2633 :type 'character)
2635 (defcustom org-priority-start-cycle-with-default t
2636 "Non-nil means start with default priority when starting to cycle.
2637 When this is nil, the first step in the cycle will be (depending on the
2638 command used) one higher or lower than the default priority.
2639 See also `org-default-priority'."
2640 :group 'org-priorities
2641 :type 'boolean)
2643 (defcustom org-get-priority-function nil
2644 "Function to extract the priority from a string.
2645 The string is normally the headline. If this is nil Org computes the
2646 priority from the priority cookie like [#A] in the headline. It returns
2647 an integer, increasing by 1000 for each priority level.
2648 The user can set a different function here, which should take a string
2649 as an argument and return the numeric priority."
2650 :group 'org-priorities
2651 :version "24.1"
2652 :type 'function)
2654 (defgroup org-time nil
2655 "Options concerning time stamps and deadlines in Org-mode."
2656 :tag "Org Time"
2657 :group 'org)
2659 (defcustom org-insert-labeled-timestamps-at-point nil
2660 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2661 When nil, these labeled time stamps are forces into the second line of an
2662 entry, just after the headline. When scheduling from the global TODO list,
2663 the time stamp will always be forced into the second line."
2664 :group 'org-time
2665 :type 'boolean)
2667 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2668 "Formats for `format-time-string' which are used for time stamps.
2669 It is not recommended to change this constant.")
2671 (defcustom org-time-stamp-rounding-minutes '(0 5)
2672 "Number of minutes to round time stamps to.
2673 These are two values, the first applies when first creating a time stamp.
2674 The second applies when changing it with the commands `S-up' and `S-down'.
2675 When changing the time stamp, this means that it will change in steps
2676 of N minutes, as given by the second value.
2678 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2679 numbers should be factors of 60, so for example 5, 10, 15.
2681 When this is larger than 1, you can still force an exact time stamp by using
2682 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2683 and by using a prefix arg to `S-up/down' to specify the exact number
2684 of minutes to shift."
2685 :group 'org-time
2686 :get #'(lambda (var) ; Make sure both elements are there
2687 (if (integerp (default-value var))
2688 (list (default-value var) 5)
2689 (default-value var)))
2690 :type '(list
2691 (integer :tag "when inserting times")
2692 (integer :tag "when modifying times")))
2694 ;; Normalize old customizations of this variable.
2695 (when (integerp org-time-stamp-rounding-minutes)
2696 (setq org-time-stamp-rounding-minutes
2697 (list org-time-stamp-rounding-minutes
2698 org-time-stamp-rounding-minutes)))
2700 (defcustom org-display-custom-times nil
2701 "Non-nil means overlay custom formats over all time stamps.
2702 The formats are defined through the variable `org-time-stamp-custom-formats'.
2703 To turn this on on a per-file basis, insert anywhere in the file:
2704 #+STARTUP: customtime"
2705 :group 'org-time
2706 :set 'set-default
2707 :type 'sexp)
2708 (make-variable-buffer-local 'org-display-custom-times)
2710 (defcustom org-time-stamp-custom-formats
2711 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2712 "Custom formats for time stamps. See `format-time-string' for the syntax.
2713 These are overlaid over the default ISO format if the variable
2714 `org-display-custom-times' is set. Time like %H:%M should be at the
2715 end of the second format. The custom formats are also honored by export
2716 commands, if custom time display is turned on at the time of export."
2717 :group 'org-time
2718 :type 'sexp)
2720 (defun org-time-stamp-format (&optional long inactive)
2721 "Get the right format for a time string."
2722 (let ((f (if long (cdr org-time-stamp-formats)
2723 (car org-time-stamp-formats))))
2724 (if inactive
2725 (concat "[" (substring f 1 -1) "]")
2726 f)))
2728 (defcustom org-time-clocksum-format
2729 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2730 "The format string used when creating CLOCKSUM lines.
2731 This is also used when Org mode generates a time duration.
2733 The value can be a single format string containing two
2734 %-sequences, which will be filled with the number of hours and
2735 minutes in that order.
2737 Alternatively, the value can be a plist associating any of the
2738 keys :years, :months, :weeks, :days, :hours or :minutes with
2739 format strings. The time duration is formatted using only the
2740 time components that are needed and concatenating the results.
2741 If a time unit in absent, it falls back to the next smallest
2742 unit.
2744 The keys :require-years, :require-months, :require-days,
2745 :require-weeks, :require-hours, :require-minutes are also
2746 meaningful. A non-nil value for these keys indicates that the
2747 corresponding time component should always be included, even if
2748 its value is 0.
2751 For example,
2753 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2754 :require-minutes t)
2756 means durations longer than a day will be expressed in days,
2757 hours and minutes, and durations less than a day will always be
2758 expressed in hours and minutes (even for durations less than an
2759 hour).
2761 The value
2763 \(:days \"%dd\" :minutes \"%dm\")
2765 means durations longer than a day will be expressed in days and
2766 minutes, and durations less than a day will be expressed entirely
2767 in minutes (even for durations longer than an hour)."
2768 :group 'org-time
2769 :type '(choice (string :tag "Format string")
2770 (set :tag "Plist"
2771 (group :inline t (const :tag "Years" :years)
2772 (string :tag "Format string"))
2773 (group :inline t
2774 (const :tag "Always show years" :require-years)
2775 (const t))
2776 (group :inline t (const :tag "Months" :months)
2777 (string :tag "Format string"))
2778 (group :inline t
2779 (const :tag "Always show months" :require-months)
2780 (const t))
2781 (group :inline t (const :tag "Weeks" :weeks)
2782 (string :tag "Format string"))
2783 (group :inline t
2784 (const :tag "Always show weeks" :require-weeks)
2785 (const t))
2786 (group :inline t (const :tag "Days" :days)
2787 (string :tag "Format string"))
2788 (group :inline t
2789 (const :tag "Always show days" :require-days)
2790 (const t))
2791 (group :inline t (const :tag "Hours" :hours)
2792 (string :tag "Format string"))
2793 (group :inline t
2794 (const :tag "Always show hours" :require-hours)
2795 (const t))
2796 (group :inline t (const :tag "Minutes" :minutes)
2797 (string :tag "Format string"))
2798 (group :inline t
2799 (const :tag "Always show minutes" :require-minutes)
2800 (const t)))))
2802 (defcustom org-time-clocksum-use-fractional nil
2803 "If non-nil, \\[org-clock-display] uses fractional times.
2804 org-mode generates a time duration."
2805 :group 'org-time
2806 :type 'boolean)
2808 (defcustom org-time-clocksum-fractional-format "%.2f"
2809 "The format string used when creating CLOCKSUM lines,
2810 or when Org mode generates a time duration, if
2811 `org-time-clocksum-use-fractional' is enabled.
2813 The value can be a single format string containing one
2814 %-sequence, which will be filled with the number of hours as
2815 a float.
2817 Alternatively, the value can be a plist associating any of the
2818 keys :years, :months, :weeks, :days, :hours or :minutes with
2819 a format string. The time duration is formatted using the
2820 largest time unit which gives a non-zero integer part. If all
2821 specified formats have zero integer part, the smallest time unit
2822 is used."
2823 :group 'org-time
2824 :type '(choice (string :tag "Format string")
2825 (set (group :inline t (const :tag "Years" :years)
2826 (string :tag "Format string"))
2827 (group :inline t (const :tag "Months" :months)
2828 (string :tag "Format string"))
2829 (group :inline t (const :tag "Weeks" :weeks)
2830 (string :tag "Format string"))
2831 (group :inline t (const :tag "Days" :days)
2832 (string :tag "Format string"))
2833 (group :inline t (const :tag "Hours" :hours)
2834 (string :tag "Format string"))
2835 (group :inline t (const :tag "Minutes" :minutes)
2836 (string :tag "Format string")))))
2838 (defcustom org-deadline-warning-days 14
2839 "No. of days before expiration during which a deadline becomes active.
2840 This variable governs the display in sparse trees and in the agenda.
2841 When 0 or negative, it means use this number (the absolute value of it)
2842 even if a deadline has a different individual lead time specified.
2844 Custom commands can set this variable in the options section."
2845 :group 'org-time
2846 :group 'org-agenda-daily/weekly
2847 :type 'integer)
2849 (defcustom org-read-date-prefer-future t
2850 "Non-nil means assume future for incomplete date input from user.
2851 This affects the following situations:
2852 1. The user gives a month but not a year.
2853 For example, if it is April and you enter \"feb 2\", this will be read
2854 as Feb 2, *next* year. \"May 5\", however, will be this year.
2855 2. The user gives a day, but no month.
2856 For example, if today is the 15th, and you enter \"3\", Org-mode will
2857 read this as the third of *next* month. However, if you enter \"17\",
2858 it will be considered as *this* month.
2860 If you set this variable to the symbol `time', then also the following
2861 will work:
2863 3. If the user gives a time.
2864 If the time is before now, it will be interpreted as tomorrow.
2866 Currently none of this works for ISO week specifications.
2868 When this option is nil, the current day, month and year will always be
2869 used as defaults.
2871 See also `org-agenda-jump-prefer-future'."
2872 :group 'org-time
2873 :type '(choice
2874 (const :tag "Never" nil)
2875 (const :tag "Check month and day" t)
2876 (const :tag "Check month, day, and time" time)))
2878 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2879 "Should the agenda jump command prefer the future for incomplete dates?
2880 The default is to do the same as configured in `org-read-date-prefer-future'.
2881 But you can also set a deviating value here.
2882 This may t or nil, or the symbol `org-read-date-prefer-future'."
2883 :group 'org-agenda
2884 :group 'org-time
2885 :version "24.1"
2886 :type '(choice
2887 (const :tag "Use org-read-date-prefer-future"
2888 org-read-date-prefer-future)
2889 (const :tag "Never" nil)
2890 (const :tag "Always" t)))
2892 (defcustom org-read-date-force-compatible-dates t
2893 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2895 Depending on the system Emacs is running on, certain dates cannot
2896 be represented with the type used internally to represent time.
2897 Dates between 1970-1-1 and 2038-1-1 can always be represented
2898 correctly. Some systems allow for earlier dates, some for later,
2899 some for both. One way to find out it to insert any date into an
2900 Org buffer, putting the cursor on the year and hitting S-up and
2901 S-down to test the range.
2903 When this variable is set to t, the date/time prompt will not let
2904 you specify dates outside the 1970-2037 range, so it is certain that
2905 these dates will work in whatever version of Emacs you are
2906 running, and also that you can move a file from one Emacs implementation
2907 to another. WHenever Org is forcing the year for you, it will display
2908 a message and beep.
2910 When this variable is nil, Org will check if the date is
2911 representable in the specific Emacs implementation you are using.
2912 If not, it will force a year, usually the current year, and beep
2913 to remind you. Currently this setting is not recommended because
2914 the likelihood that you will open your Org files in an Emacs that
2915 has limited date range is not negligible.
2917 A workaround for this problem is to use diary sexp dates for time
2918 stamps outside of this range."
2919 :group 'org-time
2920 :version "24.1"
2921 :type 'boolean)
2923 (defcustom org-read-date-display-live t
2924 "Non-nil means display current interpretation of date prompt live.
2925 This display will be in an overlay, in the minibuffer."
2926 :group 'org-time
2927 :type 'boolean)
2929 (defcustom org-read-date-popup-calendar t
2930 "Non-nil means pop up a calendar when prompting for a date.
2931 In the calendar, the date can be selected with mouse-1. However, the
2932 minibuffer will also be active, and you can simply enter the date as well.
2933 When nil, only the minibuffer will be available."
2934 :group 'org-time
2935 :type 'boolean)
2936 (if (fboundp 'defvaralias)
2937 (defvaralias 'org-popup-calendar-for-date-prompt
2938 'org-read-date-popup-calendar))
2940 (defcustom org-read-date-minibuffer-setup-hook nil
2941 "Hook to be used to set up keys for the date/time interface.
2942 Add key definitions to `minibuffer-local-map', which will be a temporary
2943 copy."
2944 :group 'org-time
2945 :type 'hook)
2947 (defcustom org-extend-today-until 0
2948 "The hour when your day really ends. Must be an integer.
2949 This has influence for the following applications:
2950 - When switching the agenda to \"today\". It it is still earlier than
2951 the time given here, the day recognized as TODAY is actually yesterday.
2952 - When a date is read from the user and it is still before the time given
2953 here, the current date and time will be assumed to be yesterday, 23:59.
2954 Also, timestamps inserted in capture templates follow this rule.
2956 IMPORTANT: This is a feature whose implementation is and likely will
2957 remain incomplete. Really, it is only here because past midnight seems to
2958 be the favorite working time of John Wiegley :-)"
2959 :group 'org-time
2960 :type 'integer)
2962 (defcustom org-use-effective-time nil
2963 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2964 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2965 \"effective time\" of any timestamps between midnight and 8am will be
2966 23:59 of the previous day."
2967 :group 'org-time
2968 :version "24.1"
2969 :type 'boolean)
2971 (defcustom org-use-last-clock-out-time-as-effective-time nil
2972 "When non-nil, use the last clock out time for `org-todo'.
2973 Note that this option has precedence over the combined use of
2974 `org-use-effective-time' and `org-extend-today-until'."
2975 :group 'org-time
2976 ;; :version "24.3"
2977 :type 'boolean)
2979 (defcustom org-edit-timestamp-down-means-later nil
2980 "Non-nil means S-down will increase the time in a time stamp.
2981 When nil, S-up will increase."
2982 :group 'org-time
2983 :type 'boolean)
2985 (defcustom org-calendar-follow-timestamp-change t
2986 "Non-nil means make the calendar window follow timestamp changes.
2987 When a timestamp is modified and the calendar window is visible, it will be
2988 moved to the new date."
2989 :group 'org-time
2990 :type 'boolean)
2992 (defgroup org-tags nil
2993 "Options concerning tags in Org-mode."
2994 :tag "Org Tags"
2995 :group 'org)
2997 (defcustom org-tag-alist nil
2998 "List of tags allowed in Org-mode files.
2999 When this list is nil, Org-mode will base TAG input on what is already in the
3000 buffer.
3001 The value of this variable is an alist, the car of each entry must be a
3002 keyword as a string, the cdr may be a character that is used to select
3003 that tag through the fast-tag-selection interface.
3004 See the manual for details."
3005 :group 'org-tags
3006 :type '(repeat
3007 (choice
3008 (cons (string :tag "Tag name")
3009 (character :tag "Access char"))
3010 (list :tag "Start radio group"
3011 (const :startgroup)
3012 (option (string :tag "Group description")))
3013 (list :tag "End radio group"
3014 (const :endgroup)
3015 (option (string :tag "Group description")))
3016 (const :tag "New line" (:newline)))))
3018 (defcustom org-tag-persistent-alist nil
3019 "List of tags that will always appear in all Org-mode files.
3020 This is in addition to any in buffer settings or customizations
3021 of `org-tag-alist'.
3022 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3023 The value of this variable is an alist, the car of each entry must be a
3024 keyword as a string, the cdr may be a character that is used to select
3025 that tag through the fast-tag-selection interface.
3026 See the manual for details.
3027 To disable these tags on a per-file basis, insert anywhere in the file:
3028 #+STARTUP: noptag"
3029 :group 'org-tags
3030 :type '(repeat
3031 (choice
3032 (cons (string :tag "Tag name")
3033 (character :tag "Access char"))
3034 (const :tag "Start radio group" (:startgroup))
3035 (const :tag "End radio group" (:endgroup))
3036 (const :tag "New line" (:newline)))))
3038 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3039 "If non-nil, always offer completion for all tags of all agenda files.
3040 Instead of customizing this variable directly, you might want to
3041 set it locally for capture buffers, because there no list of
3042 tags in that file can be created dynamically (there are none).
3044 (add-hook 'org-capture-mode-hook
3045 (lambda ()
3046 (set (make-local-variable
3047 'org-complete-tags-always-offer-all-agenda-tags)
3048 t)))"
3049 :group 'org-tags
3050 :version "24.1"
3051 :type 'boolean)
3053 (defvar org-file-tags nil
3054 "List of tags that can be inherited by all entries in the file.
3055 The tags will be inherited if the variable `org-use-tag-inheritance'
3056 says they should be.
3057 This variable is populated from #+FILETAGS lines.")
3059 (defcustom org-use-fast-tag-selection 'auto
3060 "Non-nil means use fast tag selection scheme.
3061 This is a special interface to select and deselect tags with single keys.
3062 When nil, fast selection is never used.
3063 When the symbol `auto', fast selection is used if and only if selection
3064 characters for tags have been configured, either through the variable
3065 `org-tag-alist' or through a #+TAGS line in the buffer.
3066 When t, fast selection is always used and selection keys are assigned
3067 automatically if necessary."
3068 :group 'org-tags
3069 :type '(choice
3070 (const :tag "Always" t)
3071 (const :tag "Never" nil)
3072 (const :tag "When selection characters are configured" 'auto)))
3074 (defcustom org-fast-tag-selection-single-key nil
3075 "Non-nil means fast tag selection exits after first change.
3076 When nil, you have to press RET to exit it.
3077 During fast tag selection, you can toggle this flag with `C-c'.
3078 This variable can also have the value `expert'. In this case, the window
3079 displaying the tags menu is not even shown, until you press C-c again."
3080 :group 'org-tags
3081 :type '(choice
3082 (const :tag "No" nil)
3083 (const :tag "Yes" t)
3084 (const :tag "Expert" expert)))
3086 (defvar org-fast-tag-selection-include-todo nil
3087 "Non-nil means fast tags selection interface will also offer TODO states.
3088 This is an undocumented feature, you should not rely on it.")
3090 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3091 "The column to which tags should be indented in a headline.
3092 If this number is positive, it specifies the column. If it is negative,
3093 it means that the tags should be flushright to that column. For example,
3094 -80 works well for a normal 80 character screen.
3095 When 0, place tags directly after headline text, with only one space in
3096 between."
3097 :group 'org-tags
3098 :type 'integer)
3100 (defcustom org-auto-align-tags t
3101 "Non-nil keeps tags aligned when modifying headlines.
3102 Some operations (i.e. demoting) change the length of a headline and
3103 therefore shift the tags around. With this option turned on, after
3104 each such operation the tags are again aligned to `org-tags-column'."
3105 :group 'org-tags
3106 :type 'boolean)
3108 (defcustom org-use-tag-inheritance t
3109 "Non-nil means tags in levels apply also for sublevels.
3110 When nil, only the tags directly given in a specific line apply there.
3111 This may also be a list of tags that should be inherited, or a regexp that
3112 matches tags that should be inherited. Additional control is possible
3113 with the variable `org-tags-exclude-from-inheritance' which gives an
3114 explicit list of tags to be excluded from inheritance., even if the value of
3115 `org-use-tag-inheritance' would select it for inheritance.
3117 If this option is t, a match early-on in a tree can lead to a large
3118 number of matches in the subtree when constructing the agenda or creating
3119 a sparse tree. If you only want to see the first match in a tree during
3120 a search, check out the variable `org-tags-match-list-sublevels'."
3121 :group 'org-tags
3122 :type '(choice
3123 (const :tag "Not" nil)
3124 (const :tag "Always" t)
3125 (repeat :tag "Specific tags" (string :tag "Tag"))
3126 (regexp :tag "Tags matched by regexp")))
3128 (defcustom org-tags-exclude-from-inheritance nil
3129 "List of tags that should never be inherited.
3130 This is a way to exclude a few tags from inheritance. For way to do
3131 the opposite, to actively allow inheritance for selected tags,
3132 see the variable `org-use-tag-inheritance'."
3133 :group 'org-tags
3134 :type '(repeat (string :tag "Tag")))
3136 (defun org-tag-inherit-p (tag)
3137 "Check if TAG is one that should be inherited."
3138 (cond
3139 ((member tag org-tags-exclude-from-inheritance) nil)
3140 ((eq org-use-tag-inheritance t) t)
3141 ((not org-use-tag-inheritance) nil)
3142 ((stringp org-use-tag-inheritance)
3143 (string-match org-use-tag-inheritance tag))
3144 ((listp org-use-tag-inheritance)
3145 (member tag org-use-tag-inheritance))
3146 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3148 (defcustom org-tags-match-list-sublevels t
3149 "Non-nil means list also sublevels of headlines matching a search.
3150 This variable applies to tags/property searches, and also to stuck
3151 projects because this search is based on a tags match as well.
3153 When set to the symbol `indented', sublevels are indented with
3154 leading dots.
3156 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3157 the sublevels of a headline matching a tag search often also match
3158 the same search. Listing all of them can create very long lists.
3159 Setting this variable to nil causes subtrees of a match to be skipped.
3161 This variable is semi-obsolete and probably should always be true. It
3162 is better to limit inheritance to certain tags using the variables
3163 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3164 :group 'org-tags
3165 :type '(choice
3166 (const :tag "No, don't list them" nil)
3167 (const :tag "Yes, do list them" t)
3168 (const :tag "List them, indented with leading dots" indented)))
3170 (defcustom org-tags-sort-function nil
3171 "When set, tags are sorted using this function as a comparator."
3172 :group 'org-tags
3173 :type '(choice
3174 (const :tag "No sorting" nil)
3175 (const :tag "Alphabetical" string<)
3176 (const :tag "Reverse alphabetical" string>)
3177 (function :tag "Custom function" nil)))
3179 (defvar org-tags-history nil
3180 "History of minibuffer reads for tags.")
3181 (defvar org-last-tags-completion-table nil
3182 "The last used completion table for tags.")
3183 (defvar org-after-tags-change-hook nil
3184 "Hook that is run after the tags in a line have changed.")
3186 (defgroup org-properties nil
3187 "Options concerning properties in Org-mode."
3188 :tag "Org Properties"
3189 :group 'org)
3191 (defcustom org-property-format "%-10s %s"
3192 "How property key/value pairs should be formatted by `indent-line'.
3193 When `indent-line' hits a property definition, it will format the line
3194 according to this format, mainly to make sure that the values are
3195 lined-up with respect to each other."
3196 :group 'org-properties
3197 :type 'string)
3199 (defcustom org-properties-postprocess-alist nil
3200 "Alist of properties and functions to adjust inserted values.
3201 Elements of this alist must be of the form
3203 ([string] [function])
3205 where [string] must be a property name and [function] must be a
3206 lambda expression: this lambda expression must take one argument,
3207 the value to adjust, and return the new value as a string.
3209 For example, this element will allow the property \"Remaining\"
3210 to be updated wrt the relation between the \"Effort\" property
3211 and the clock summary:
3213 ((\"Remaining\" (lambda(value)
3214 (let ((clocksum (org-clock-sum-current-item))
3215 (effort (org-duration-string-to-minutes
3216 (org-entry-get (point) \"Effort\"))))
3217 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3218 :group 'org-properties
3219 :version "24.1"
3220 :type '(alist :key-type (string :tag "Property")
3221 :value-type (function :tag "Function")))
3223 (defcustom org-use-property-inheritance nil
3224 "Non-nil means properties apply also for sublevels.
3226 This setting is chiefly used during property searches. Turning it on can
3227 cause significant overhead when doing a search, which is why it is not
3228 on by default.
3230 When nil, only the properties directly given in the current entry count.
3231 When t, every property is inherited. The value may also be a list of
3232 properties that should have inheritance, or a regular expression matching
3233 properties that should be inherited.
3235 However, note that some special properties use inheritance under special
3236 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3237 and the properties ending in \"_ALL\" when they are used as descriptor
3238 for valid values of a property.
3240 Note for programmers:
3241 When querying an entry with `org-entry-get', you can control if inheritance
3242 should be used. By default, `org-entry-get' looks only at the local
3243 properties. You can request inheritance by setting the inherit argument
3244 to t (to force inheritance) or to `selective' (to respect the setting
3245 in this variable)."
3246 :group 'org-properties
3247 :type '(choice
3248 (const :tag "Not" nil)
3249 (const :tag "Always" t)
3250 (repeat :tag "Specific properties" (string :tag "Property"))
3251 (regexp :tag "Properties matched by regexp")))
3253 (defun org-property-inherit-p (property)
3254 "Check if PROPERTY is one that should be inherited."
3255 (cond
3256 ((eq org-use-property-inheritance t) t)
3257 ((not org-use-property-inheritance) nil)
3258 ((stringp org-use-property-inheritance)
3259 (string-match org-use-property-inheritance property))
3260 ((listp org-use-property-inheritance)
3261 (member property org-use-property-inheritance))
3262 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3264 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3265 "The default column format, if no other format has been defined.
3266 This variable can be set on the per-file basis by inserting a line
3268 #+COLUMNS: %25ITEM ....."
3269 :group 'org-properties
3270 :type 'string)
3272 (defcustom org-columns-ellipses ".."
3273 "The ellipses to be used when a field in column view is truncated.
3274 When this is the empty string, as many characters as possible are shown,
3275 but then there will be no visual indication that the field has been truncated.
3276 When this is a string of length N, the last N characters of a truncated
3277 field are replaced by this string. If the column is narrower than the
3278 ellipses string, only part of the ellipses string will be shown."
3279 :group 'org-properties
3280 :type 'string)
3282 (defcustom org-columns-modify-value-for-display-function nil
3283 "Function that modifies values for display in column view.
3284 For example, it can be used to cut out a certain part from a time stamp.
3285 The function must take 2 arguments:
3287 column-title The title of the column (*not* the property name)
3288 value The value that should be modified.
3290 The function should return the value that should be displayed,
3291 or nil if the normal value should be used."
3292 :group 'org-properties
3293 :type 'function)
3295 (defcustom org-effort-property "Effort"
3296 "The property that is being used to keep track of effort estimates.
3297 Effort estimates given in this property need to have the format H:MM."
3298 :group 'org-properties
3299 :group 'org-progress
3300 :type '(string :tag "Property"))
3302 (defconst org-global-properties-fixed
3303 '(("VISIBILITY_ALL" . "folded children content all")
3304 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3305 "List of property/value pairs that can be inherited by any entry.
3307 These are fixed values, for the preset properties. The user variable
3308 that can be used to add to this list is `org-global-properties'.
3310 The entries in this list are cons cells where the car is a property
3311 name and cdr is a string with the value. If the value represents
3312 multiple items like an \"_ALL\" property, separate the items by
3313 spaces.")
3315 (defcustom org-global-properties nil
3316 "List of property/value pairs that can be inherited by any entry.
3318 This list will be combined with the constant `org-global-properties-fixed'.
3320 The entries in this list are cons cells where the car is a property
3321 name and cdr is a string with the value.
3323 You can set buffer-local values for the same purpose in the variable
3324 `org-file-properties' this by adding lines like
3326 #+PROPERTY: NAME VALUE"
3327 :group 'org-properties
3328 :type '(repeat
3329 (cons (string :tag "Property")
3330 (string :tag "Value"))))
3332 (defvar org-file-properties nil
3333 "List of property/value pairs that can be inherited by any entry.
3334 Valid for the current buffer.
3335 This variable is populated from #+PROPERTY lines.")
3336 (make-variable-buffer-local 'org-file-properties)
3338 (defgroup org-agenda nil
3339 "Options concerning agenda views in Org-mode."
3340 :tag "Org Agenda"
3341 :group 'org)
3343 (defvar org-category nil
3344 "Variable used by org files to set a category for agenda display.
3345 Such files should use a file variable to set it, for example
3347 # -*- mode: org; org-category: \"ELisp\"
3349 or contain a special line
3351 #+CATEGORY: ELisp
3353 If the file does not specify a category, then file's base name
3354 is used instead.")
3355 (make-variable-buffer-local 'org-category)
3356 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3358 (defcustom org-agenda-files nil
3359 "The files to be used for agenda display.
3360 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3361 \\[org-remove-file]. You can also use customize to edit the list.
3363 If an entry is a directory, all files in that directory that are matched by
3364 `org-agenda-file-regexp' will be part of the file list.
3366 If the value of the variable is not a list but a single file name, then
3367 the list of agenda files is actually stored and maintained in that file, one
3368 agenda file per line. In this file paths can be given relative to
3369 `org-directory'. Tilde expansion and environment variable substitution
3370 are also made."
3371 :group 'org-agenda
3372 :type '(choice
3373 (repeat :tag "List of files and directories" file)
3374 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3376 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3377 "Regular expression to match files for `org-agenda-files'.
3378 If any element in the list in that variable contains a directory instead
3379 of a normal file, all files in that directory that are matched by this
3380 regular expression will be included."
3381 :group 'org-agenda
3382 :type 'regexp)
3384 (defcustom org-agenda-text-search-extra-files nil
3385 "List of extra files to be searched by text search commands.
3386 These files will be search in addition to the agenda files by the
3387 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3388 Note that these files will only be searched for text search commands,
3389 not for the other agenda views like todo lists, tag searches or the weekly
3390 agenda. This variable is intended to list notes and possibly archive files
3391 that should also be searched by these two commands.
3392 In fact, if the first element in the list is the symbol `agenda-archives',
3393 than all archive files of all agenda files will be added to the search
3394 scope."
3395 :group 'org-agenda
3396 :type '(set :greedy t
3397 (const :tag "Agenda Archives" agenda-archives)
3398 (repeat :inline t (file))))
3400 (if (fboundp 'defvaralias)
3401 (defvaralias 'org-agenda-multi-occur-extra-files
3402 'org-agenda-text-search-extra-files))
3404 (defcustom org-agenda-skip-unavailable-files nil
3405 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3406 A nil value means to remove them, after a query, from the list."
3407 :group 'org-agenda
3408 :type 'boolean)
3410 (defcustom org-calendar-to-agenda-key [?c]
3411 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3412 The command `org-calendar-goto-agenda' will be bound to this key. The
3413 default is the character `c' because then `c' can be used to switch back and
3414 forth between agenda and calendar."
3415 :group 'org-agenda
3416 :type 'sexp)
3418 (defcustom org-calendar-insert-diary-entry-key [?i]
3419 "The key to be installed in `calendar-mode-map' for adding diary entries.
3420 This option is irrelevant until `org-agenda-diary-file' has been configured
3421 to point to an Org-mode file. When that is the case, the command
3422 `org-agenda-diary-entry' will be bound to the key given here, by default
3423 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3424 if you want to continue doing this, you need to change this to a different
3425 key."
3426 :group 'org-agenda
3427 :type 'sexp)
3429 (defcustom org-agenda-diary-file 'diary-file
3430 "File to which to add new entries with the `i' key in agenda and calendar.
3431 When this is the symbol `diary-file', the functionality in the Emacs
3432 calendar will be used to add entries to the `diary-file'. But when this
3433 points to a file, `org-agenda-diary-entry' will be used instead."
3434 :group 'org-agenda
3435 :type '(choice
3436 (const :tag "The standard Emacs diary file" diary-file)
3437 (file :tag "Special Org file diary entries")))
3439 (eval-after-load "calendar"
3440 '(progn
3441 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3442 'org-calendar-goto-agenda)
3443 (add-hook 'calendar-mode-hook
3444 (lambda ()
3445 (unless (eq org-agenda-diary-file 'diary-file)
3446 (define-key calendar-mode-map
3447 org-calendar-insert-diary-entry-key
3448 'org-agenda-diary-entry))))))
3450 (defgroup org-latex nil
3451 "Options for embedding LaTeX code into Org-mode."
3452 :tag "Org LaTeX"
3453 :group 'org)
3455 (defcustom org-format-latex-options
3456 '(:foreground default :background default :scale 1.0
3457 :html-foreground "Black" :html-background "Transparent"
3458 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3459 "Options for creating images from LaTeX fragments.
3460 This is a property list with the following properties:
3461 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3462 `default' means use the foreground of the default face.
3463 `auto' means use the foreground from the text face.
3464 :background the background color, or \"Transparent\".
3465 `default' means use the background of the default face.
3466 `auto' means use the background from the text face.
3467 :scale a scaling factor for the size of the images, to get more pixels
3468 :html-foreground, :html-background, :html-scale
3469 the same numbers for HTML export.
3470 :matchers a list indicating which matchers should be used to
3471 find LaTeX fragments. Valid members of this list are:
3472 \"begin\" find environments
3473 \"$1\" find single characters surrounded by $.$
3474 \"$\" find math expressions surrounded by $...$
3475 \"$$\" find math expressions surrounded by $$....$$
3476 \"\\(\" find math expressions surrounded by \\(...\\)
3477 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3478 :group 'org-latex
3479 :type 'plist)
3481 (defcustom org-format-latex-signal-error t
3482 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3483 When nil, just push out a message."
3484 :group 'org-latex
3485 :version "24.1"
3486 :type 'boolean)
3488 (defcustom org-latex-to-mathml-jar-file nil
3489 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3490 Use this to specify additional executable file say a jar file.
3492 When using MathToWeb as the converter, specify the full-path to
3493 your mathtoweb.jar file."
3494 :group 'org-latex
3495 :version "24.1"
3496 :type '(choice
3497 (const :tag "None" nil)
3498 (file :tag "JAR file" :must-match t)))
3500 (defcustom org-latex-to-mathml-convert-command nil
3501 "Command to convert LaTeX fragments to MathML.
3502 Replace format-specifiers in the command as noted below and use
3503 `shell-command' to convert LaTeX to MathML.
3504 %j: Executable file in fully expanded form as specified by
3505 `org-latex-to-mathml-jar-file'.
3506 %I: Input LaTeX file in fully expanded form
3507 %o: Output MathML file
3508 This command is used by `org-create-math-formula'.
3510 When using MathToWeb as the converter, set this to
3511 \"java -jar %j -unicode -force -df %o %I\"."
3512 :group 'org-latex
3513 :version "24.1"
3514 :type '(choice
3515 (const :tag "None" nil)
3516 (string :tag "\nShell command")))
3518 (defcustom org-latex-create-formula-image-program 'dvipng
3519 "Program to convert LaTeX fragments with.
3521 dvipng Process the LaTeX fragments to dvi file, then convert
3522 dvi files to png files using dvipng.
3523 This will also include processing of non-math environments.
3524 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3525 to convert pdf files to png files"
3526 :group 'org-latex
3527 :version "24.1"
3528 :type '(choice
3529 (const :tag "dvipng" dvipng)
3530 (const :tag "imagemagick" imagemagick)))
3532 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3533 "Path to store latex preview images.
3534 A relative path here creates many directories relative to the
3535 processed org files paths. An absolute path puts all preview
3536 images at the same place."
3537 :group 'org-latex
3538 :version "24.3"
3539 :type 'string)
3541 (defun org-format-latex-mathml-available-p ()
3542 "Return t if `org-latex-to-mathml-convert-command' is usable."
3543 (save-match-data
3544 (when (and (boundp 'org-latex-to-mathml-convert-command)
3545 org-latex-to-mathml-convert-command)
3546 (let ((executable (car (split-string
3547 org-latex-to-mathml-convert-command))))
3548 (when (executable-find executable)
3549 (if (string-match
3550 "%j" org-latex-to-mathml-convert-command)
3551 (file-readable-p org-latex-to-mathml-jar-file)
3552 t))))))
3554 (defcustom org-format-latex-header "\\documentclass{article}
3555 \\usepackage[usenames]{color}
3556 \\usepackage{amsmath}
3557 \\usepackage[mathscr]{eucal}
3558 \\pagestyle{empty} % do not remove
3559 \[PACKAGES]
3560 \[DEFAULT-PACKAGES]
3561 % The settings below are copied from fullpage.sty
3562 \\setlength{\\textwidth}{\\paperwidth}
3563 \\addtolength{\\textwidth}{-3cm}
3564 \\setlength{\\oddsidemargin}{1.5cm}
3565 \\addtolength{\\oddsidemargin}{-2.54cm}
3566 \\setlength{\\evensidemargin}{\\oddsidemargin}
3567 \\setlength{\\textheight}{\\paperheight}
3568 \\addtolength{\\textheight}{-\\headheight}
3569 \\addtolength{\\textheight}{-\\headsep}
3570 \\addtolength{\\textheight}{-\\footskip}
3571 \\addtolength{\\textheight}{-3cm}
3572 \\setlength{\\topmargin}{1.5cm}
3573 \\addtolength{\\topmargin}{-2.54cm}"
3574 "The document header used for processing LaTeX fragments.
3575 It is imperative that this header make sure that no page number
3576 appears on the page. The package defined in the variables
3577 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3578 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3579 will be appended."
3580 :group 'org-latex
3581 :type 'string)
3583 (defvar org-format-latex-header-extra nil)
3585 (defun org-set-packages-alist (var val)
3586 "Set the packages alist and make sure it has 3 elements per entry."
3587 (set var (mapcar (lambda (x)
3588 (if (and (consp x) (= (length x) 2))
3589 (list (car x) (nth 1 x) t)
3591 val)))
3593 (defun org-get-packages-alist (var)
3595 "Get the packages alist and make sure it has 3 elements per entry."
3596 (mapcar (lambda (x)
3597 (if (and (consp x) (= (length x) 2))
3598 (list (car x) (nth 1 x) t)
3600 (default-value var)))
3602 ;; The following variables are defined here because is it also used
3603 ;; when formatting latex fragments. Originally it was part of the
3604 ;; LaTeX exporter, which is why the name includes "export".
3605 (defcustom org-export-latex-default-packages-alist
3606 '(("AUTO" "inputenc" t)
3607 ("T1" "fontenc" t)
3608 ("" "fixltx2e" nil)
3609 ("" "graphicx" t)
3610 ("" "longtable" nil)
3611 ("" "float" nil)
3612 ("" "wrapfig" nil)
3613 ("" "soul" t)
3614 ("" "textcomp" t)
3615 ("" "marvosym" t)
3616 ("" "wasysym" t)
3617 ("" "latexsym" t)
3618 ("" "amssymb" t)
3619 ("" "hyperref" nil)
3620 "\\tolerance=1000"
3622 "Alist of default packages to be inserted in the header.
3623 Change this only if one of the packages here causes an incompatibility
3624 with another package you are using.
3625 The packages in this list are needed by one part or another of Org-mode
3626 to function properly.
3628 - inputenc, fontenc: for basic font and character selection
3629 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3630 for interpreting the entities in `org-entities'. You can skip some of these
3631 packages if you don't use any of the symbols in it.
3632 - graphicx: for including images
3633 - float, wrapfig: for figure placement
3634 - longtable: for long tables
3635 - hyperref: for cross references
3637 Therefore you should not modify this variable unless you know what you
3638 are doing. The one reason to change it anyway is that you might be loading
3639 some other package that conflicts with one of the default packages.
3640 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3641 If SNIPPET-FLAG is t, the package also needs to be included when
3642 compiling LaTeX snippets into images for inclusion into HTML."
3643 :group 'org-export-latex
3644 :set 'org-set-packages-alist
3645 :get 'org-get-packages-alist
3646 :version "24.1"
3647 :type '(repeat
3648 (choice
3649 (list :tag "options/package pair"
3650 (string :tag "options")
3651 (string :tag "package")
3652 (boolean :tag "Snippet"))
3653 (string :tag "A line of LaTeX"))))
3655 (defcustom org-export-latex-packages-alist nil
3656 "Alist of packages to be inserted in every LaTeX header.
3657 These will be inserted after `org-export-latex-default-packages-alist'.
3658 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3659 SNIPPET-FLAG, when t, indicates that this package is also needed when
3660 turning LaTeX snippets into images for inclusion into HTML.
3661 Make sure that you only list packages here which:
3662 - you want in every file
3663 - do not conflict with the default packages in
3664 `org-export-latex-default-packages-alist'
3665 - do not conflict with the setup in `org-format-latex-header'."
3666 :group 'org-export-latex
3667 :set 'org-set-packages-alist
3668 :get 'org-get-packages-alist
3669 :type '(repeat
3670 (choice
3671 (list :tag "options/package pair"
3672 (string :tag "options")
3673 (string :tag "package")
3674 (boolean :tag "Snippet"))
3675 (string :tag "A line of LaTeX"))))
3678 (defgroup org-appearance nil
3679 "Settings for Org-mode appearance."
3680 :tag "Org Appearance"
3681 :group 'org)
3683 (defcustom org-level-color-stars-only nil
3684 "Non-nil means fontify only the stars in each headline.
3685 When nil, the entire headline is fontified.
3686 Changing it requires restart of `font-lock-mode' to become effective
3687 also in regions already fontified."
3688 :group 'org-appearance
3689 :type 'boolean)
3691 (defcustom org-hide-leading-stars nil
3692 "Non-nil means hide the first N-1 stars in a headline.
3693 This works by using the face `org-hide' for these stars. This
3694 face is white for a light background, and black for a dark
3695 background. You may have to customize the face `org-hide' to
3696 make this work.
3697 Changing it requires restart of `font-lock-mode' to become effective
3698 also in regions already fontified.
3699 You may also set this on a per-file basis by adding one of the following
3700 lines to the buffer:
3702 #+STARTUP: hidestars
3703 #+STARTUP: showstars"
3704 :group 'org-appearance
3705 :type 'boolean)
3707 (defcustom org-hidden-keywords nil
3708 "List of symbols corresponding to keywords to be hidden the org buffer.
3709 For example, a value '(title) for this list will make the document's title
3710 appear in the buffer without the initial #+TITLE: keyword."
3711 :group 'org-appearance
3712 :version "24.1"
3713 :type '(set (const :tag "#+AUTHOR" author)
3714 (const :tag "#+DATE" date)
3715 (const :tag "#+EMAIL" email)
3716 (const :tag "#+TITLE" title)))
3718 (defcustom org-custom-properties nil
3719 "List of properties (as strings) with a special meaning.
3720 The default use of these custom properties is to let the user
3721 hide them with `org-toggle-custom-properties-visibility'."
3722 :group 'org-properties
3723 :group 'org-appearance
3724 :version "24.3"
3725 :type '(repeat (string :tag "Property Name")))
3727 (defcustom org-fontify-done-headline nil
3728 "Non-nil means change the face of a headline if it is marked DONE.
3729 Normally, only the TODO/DONE keyword indicates the state of a headline.
3730 When this is non-nil, the headline after the keyword is set to the
3731 `org-headline-done' as an additional indication."
3732 :group 'org-appearance
3733 :type 'boolean)
3735 (defcustom org-fontify-emphasized-text t
3736 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3737 Changing this variable requires a restart of Emacs to take effect."
3738 :group 'org-appearance
3739 :type 'boolean)
3741 (defcustom org-fontify-whole-heading-line nil
3742 "Non-nil means fontify the whole line for headings.
3743 This is useful when setting a background color for the
3744 org-level-* faces."
3745 :group 'org-appearance
3746 :type 'boolean)
3748 (defcustom org-highlight-latex-fragments-and-specials nil
3749 "Non-nil means fontify what is treated specially by the exporters."
3750 :group 'org-appearance
3751 :type 'boolean)
3753 (defcustom org-hide-emphasis-markers nil
3754 "Non-nil mean font-lock should hide the emphasis marker characters."
3755 :group 'org-appearance
3756 :type 'boolean)
3758 (defcustom org-pretty-entities nil
3759 "Non-nil means show entities as UTF8 characters.
3760 When nil, the \\name form remains in the buffer."
3761 :group 'org-appearance
3762 :version "24.1"
3763 :type 'boolean)
3765 (defcustom org-pretty-entities-include-sub-superscripts t
3766 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3767 :group 'org-appearance
3768 :version "24.1"
3769 :type 'boolean)
3771 (defvar org-emph-re nil
3772 "Regular expression for matching emphasis.
3773 After a match, the match groups contain these elements:
3774 0 The match of the full regular expression, including the characters
3775 before and after the proper match
3776 1 The character before the proper match, or empty at beginning of line
3777 2 The proper match, including the leading and trailing markers
3778 3 The leading marker like * or /, indicating the type of highlighting
3779 4 The text between the emphasis markers, not including the markers
3780 5 The character after the match, empty at the end of a line")
3781 (defvar org-verbatim-re nil
3782 "Regular expression for matching verbatim text.")
3783 (defvar org-emphasis-regexp-components) ; defined just below
3784 (defvar org-emphasis-alist) ; defined just below
3785 (defun org-set-emph-re (var val)
3786 "Set variable and compute the emphasis regular expression."
3787 (set var val)
3788 (when (and (boundp 'org-emphasis-alist)
3789 (boundp 'org-emphasis-regexp-components)
3790 org-emphasis-alist org-emphasis-regexp-components)
3791 (let* ((e org-emphasis-regexp-components)
3792 (pre (car e))
3793 (post (nth 1 e))
3794 (border (nth 2 e))
3795 (body (nth 3 e))
3796 (nl (nth 4 e))
3797 (body1 (concat body "*?"))
3798 (markers (mapconcat 'car org-emphasis-alist ""))
3799 (vmarkers (mapconcat
3800 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3801 org-emphasis-alist "")))
3802 ;; make sure special characters appear at the right position in the class
3803 (if (string-match "\\^" markers)
3804 (setq markers (concat (replace-match "" t t markers) "^")))
3805 (if (string-match "-" markers)
3806 (setq markers (concat (replace-match "" t t markers) "-")))
3807 (if (string-match "\\^" vmarkers)
3808 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3809 (if (string-match "-" vmarkers)
3810 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3811 (if (> nl 0)
3812 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3813 (int-to-string nl) "\\}")))
3814 ;; Make the regexp
3815 (setq org-emph-re
3816 (concat "\\([" pre "]\\|^\\)"
3817 "\\("
3818 "\\([" markers "]\\)"
3819 "\\("
3820 "[^" border "]\\|"
3821 "[^" border "]"
3822 body1
3823 "[^" border "]"
3824 "\\)"
3825 "\\3\\)"
3826 "\\([" post "]\\|$\\)"))
3827 (setq org-verbatim-re
3828 (concat "\\([" pre "]\\|^\\)"
3829 "\\("
3830 "\\([" vmarkers "]\\)"
3831 "\\("
3832 "[^" border "]\\|"
3833 "[^" border "]"
3834 body1
3835 "[^" border "]"
3836 "\\)"
3837 "\\3\\)"
3838 "\\([" post "]\\|$\\)")))))
3840 (defcustom org-emphasis-regexp-components
3841 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3842 "Components used to build the regular expression for emphasis.
3843 This is a list with five entries. Terminology: In an emphasis string
3844 like \" *strong word* \", we call the initial space PREMATCH, the final
3845 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3846 and \"trong wor\" is the body. The different components in this variable
3847 specify what is allowed/forbidden in each part:
3849 pre Chars allowed as prematch. Beginning of line will be allowed too.
3850 post Chars allowed as postmatch. End of line will be allowed too.
3851 border The chars *forbidden* as border characters.
3852 body-regexp A regexp like \".\" to match a body character. Don't use
3853 non-shy groups here, and don't allow newline here.
3854 newline The maximum number of newlines allowed in an emphasis exp.
3856 Use customize to modify this, or restart Emacs after changing it."
3857 :group 'org-appearance
3858 :set 'org-set-emph-re
3859 :type '(list
3860 (sexp :tag "Allowed chars in pre ")
3861 (sexp :tag "Allowed chars in post ")
3862 (sexp :tag "Forbidden chars in border ")
3863 (sexp :tag "Regexp for body ")
3864 (integer :tag "number of newlines allowed")
3865 (option (boolean :tag "Please ignore this button"))))
3867 (defcustom org-emphasis-alist
3868 `(("*" bold "<b>" "</b>")
3869 ("/" italic "<i>" "</i>")
3870 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3871 ("=" org-code "<code>" "</code>" verbatim)
3872 ("~" org-verbatim "<code>" "</code>" verbatim)
3873 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3874 "<del>" "</del>")
3876 "Special syntax for emphasized text.
3877 Text starting and ending with a special character will be emphasized, for
3878 example *bold*, _underlined_ and /italic/. This variable sets the marker
3879 characters, the face to be used by font-lock for highlighting in Org-mode
3880 Emacs buffers, and the HTML tags to be used for this.
3881 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3882 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3883 Use customize to modify this, or restart Emacs after changing it."
3884 :group 'org-appearance
3885 :set 'org-set-emph-re
3886 :type '(repeat
3887 (list
3888 (string :tag "Marker character")
3889 (choice
3890 (face :tag "Font-lock-face")
3891 (plist :tag "Face property list"))
3892 (string :tag "HTML start tag")
3893 (string :tag "HTML end tag")
3894 (option (const verbatim)))))
3896 (defvar org-syntax-table
3897 (let ((st (make-syntax-table)))
3898 (mapc (lambda(c) (modify-syntax-entry
3899 (string-to-char (car c)) "w p" st))
3900 org-emphasis-alist)
3901 st))
3903 (defvar org-protecting-blocks
3904 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3905 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3906 This is needed for font-lock setup.")
3908 ;;; Miscellaneous options
3910 (defgroup org-completion nil
3911 "Completion in Org-mode."
3912 :tag "Org Completion"
3913 :group 'org)
3915 (defcustom org-completion-use-ido nil
3916 "Non-nil means use ido completion wherever possible.
3917 Note that `ido-mode' must be active for this variable to be relevant.
3918 If you decide to turn this variable on, you might well want to turn off
3919 `org-outline-path-complete-in-steps'.
3920 See also `org-completion-use-iswitchb'."
3921 :group 'org-completion
3922 :type 'boolean)
3924 (defcustom org-completion-use-iswitchb nil
3925 "Non-nil means use iswitchb completion wherever possible.
3926 Note that `iswitchb-mode' must be active for this variable to be relevant.
3927 If you decide to turn this variable on, you might well want to turn off
3928 `org-outline-path-complete-in-steps'.
3929 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3930 :group 'org-completion
3931 :type 'boolean)
3933 (defcustom org-completion-fallback-command 'hippie-expand
3934 "The expansion command called by \\[pcomplete] in normal context.
3935 Normal means, no org-mode-specific context."
3936 :group 'org-completion
3937 :type 'function)
3939 ;;; Functions and variables from their packages
3940 ;; Declared here to avoid compiler warnings
3942 ;; XEmacs only
3943 (defvar outline-mode-menu-heading)
3944 (defvar outline-mode-menu-show)
3945 (defvar outline-mode-menu-hide)
3946 (defvar zmacs-regions) ; XEmacs regions
3948 ;; Emacs only
3949 (defvar mark-active)
3951 ;; Various packages
3952 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3953 (declare-function calendar-forward-day "cal-move" (arg))
3954 (declare-function calendar-goto-date "cal-move" (date))
3955 (declare-function calendar-goto-today "cal-move" ())
3956 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3957 (defvar calc-embedded-close-formula)
3958 (defvar calc-embedded-open-formula)
3959 (declare-function cdlatex-tab "ext:cdlatex" ())
3960 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3961 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3962 (defvar font-lock-unfontify-region-function)
3963 (declare-function iswitchb-read-buffer "iswitchb"
3964 (prompt &optional default require-match start matches-set))
3965 (defvar iswitchb-temp-buflist)
3966 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3967 (defvar org-agenda-tags-todo-honor-ignore-options)
3968 (declare-function org-agenda-skip "org-agenda" ())
3969 (declare-function
3970 org-agenda-format-item "org-agenda"
3971 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3972 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3973 (declare-function org-agenda-change-all-lines "org-agenda"
3974 (newhead hdmarker &optional fixface just-this))
3975 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3976 (declare-function org-agenda-maybe-redo "org-agenda" ())
3977 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3978 (beg end))
3979 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3980 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3981 "org-agenda" (&optional end))
3982 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3983 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3984 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3985 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3986 (declare-function org-indent-mode "org-indent" (&optional arg))
3987 (declare-function parse-time-string "parse-time" (string))
3988 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3989 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3990 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3991 (defvar remember-data-file)
3992 (defvar texmathp-why)
3993 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3994 (declare-function table--at-cell-p "table" (position &optional object at-column))
3996 (defvar org-latex-regexps)
3998 ;;; Autoload and prepare some org modules
4000 ;; Some table stuff that needs to be defined here, because it is used
4001 ;; by the functions setting up org-mode or checking for table context.
4003 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4004 "Detect an org-type or table-type table.")
4005 (defconst org-table-line-regexp "^[ \t]*|"
4006 "Detect an org-type table line.")
4007 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4008 "Detect an org-type table line.")
4009 (defconst org-table-hline-regexp "^[ \t]*|-"
4010 "Detect an org-type table hline.")
4011 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4012 "Detect a table-type table hline.")
4013 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4014 "Detect the first line outside a table when searching from within it.
4015 This works for both table types.")
4017 ;; Autoload the functions in org-table.el that are needed by functions here.
4019 (eval-and-compile
4020 (org-autoload "org-table"
4021 '(org-table-begin org-table-blank-field org-table-end)))
4023 ;;;###autoload
4024 (defun turn-on-orgtbl ()
4025 "Unconditionally turn on `orgtbl-mode'."
4026 (require 'org-table)
4027 (orgtbl-mode 1))
4029 (defun org-at-table-p (&optional table-type)
4030 "Return t if the cursor is inside an org-type table.
4031 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4032 (if org-enable-table-editor
4033 (save-excursion
4034 (beginning-of-line 1)
4035 (looking-at (if table-type org-table-any-line-regexp
4036 org-table-line-regexp)))
4037 nil))
4038 (defsubst org-table-p () (org-at-table-p))
4040 (defun org-at-table.el-p ()
4041 "Return t if and only if we are at a table.el table."
4042 (and (org-at-table-p 'any)
4043 (save-excursion
4044 (goto-char (org-table-begin 'any))
4045 (looking-at org-table1-hline-regexp))))
4046 (defun org-table-recognize-table.el ()
4047 "If there is a table.el table nearby, recognize it and move into it."
4048 (if org-table-tab-recognizes-table.el
4049 (if (org-at-table.el-p)
4050 (progn
4051 (beginning-of-line 1)
4052 (if (looking-at org-table-dataline-regexp)
4054 (if (looking-at org-table1-hline-regexp)
4055 (progn
4056 (beginning-of-line 2)
4057 (if (looking-at org-table-any-border-regexp)
4058 (beginning-of-line -1)))))
4059 (if (re-search-forward "|" (org-table-end t) t)
4060 (progn
4061 (require 'table)
4062 (if (table--at-cell-p (point))
4064 (message "recognizing table.el table...")
4065 (table-recognize-table)
4066 (message "recognizing table.el table...done")))
4067 (error "This should not happen"))
4069 nil)
4070 nil))
4072 (defun org-at-table-hline-p ()
4073 "Return t if the cursor is inside a hline in a table."
4074 (if org-enable-table-editor
4075 (save-excursion
4076 (beginning-of-line 1)
4077 (looking-at org-table-hline-regexp))
4078 nil))
4080 (defvar org-table-clean-did-remove-column nil)
4082 (defun org-table-map-tables (function &optional quietly)
4083 "Apply FUNCTION to the start of all tables in the buffer."
4084 (save-excursion
4085 (save-restriction
4086 (widen)
4087 (goto-char (point-min))
4088 (while (re-search-forward org-table-any-line-regexp nil t)
4089 (unless quietly
4090 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4091 (beginning-of-line 1)
4092 (when (and (looking-at org-table-line-regexp)
4093 ;; Exclude tables in src/example/verbatim/clocktable blocks
4094 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4095 (save-excursion (funcall function))
4096 (or (looking-at org-table-line-regexp)
4097 (forward-char 1)))
4098 (re-search-forward org-table-any-border-regexp nil 1))))
4099 (unless quietly (message "Mapping tables: done")))
4101 ;; Declare and autoload functions from org-exp.el & Co
4103 (declare-function org-default-export-plist "org-exp")
4104 (declare-function org-infile-export-plist "org-exp")
4105 (declare-function org-get-current-options "org-exp")
4107 ;; Declare and autoload functions from org-agenda.el
4109 (eval-and-compile
4110 (org-autoload "org-agenda"
4111 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4113 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4114 (declare-function org-clock-update-mode-line "org-clock" ())
4115 (declare-function org-resolve-clocks "org-clock"
4116 (&optional also-non-dangling-p prompt last-valid))
4117 (defvar org-clock-start-time)
4118 (defvar org-clock-marker (make-marker)
4119 "Marker recording the last clock-in.")
4120 (defvar org-clock-hd-marker (make-marker)
4121 "Marker recording the last clock-in, but the headline position.")
4122 (defvar org-clock-heading ""
4123 "The heading of the current clock entry.")
4124 (defun org-clock-is-active ()
4125 "Return non-nil if clock is currently running.
4126 The return value is actually the clock marker."
4127 (marker-buffer org-clock-marker))
4129 (eval-and-compile
4130 (org-autoload "org-clock" '(org-clock-remove-overlays
4131 org-clock-update-time-maybe
4132 org-clocktable-shift)))
4134 (defun org-check-running-clock ()
4135 "Check if the current buffer contains the running clock.
4136 If yes, offer to stop it and to save the buffer with the changes."
4137 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4138 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4139 (buffer-name))))
4140 (org-clock-out)
4141 (when (y-or-n-p "Save changed buffer?")
4142 (save-buffer))))
4144 (defun org-clocktable-try-shift (dir n)
4145 "Check if this line starts a clock table, if yes, shift the time block."
4146 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4147 (org-clocktable-shift dir n)))
4149 ;;;###autoload
4150 (defun org-clock-persistence-insinuate ()
4151 "Set up hooks for clock persistence."
4152 (require 'org-clock)
4153 (add-hook 'org-mode-hook 'org-clock-load)
4154 (add-hook 'kill-emacs-hook 'org-clock-save))
4156 ;; Define the variable already here, to make sure we have it.
4157 (defvar org-indent-mode nil
4158 "Non-nil if Org-Indent mode is enabled.
4159 Use the command `org-indent-mode' to change this variable.")
4161 ;; Autoload archiving code
4162 ;; The stuff that is needed for cycling and tags has to be defined here.
4164 (defgroup org-archive nil
4165 "Options concerning archiving in Org-mode."
4166 :tag "Org Archive"
4167 :group 'org-structure)
4169 (defcustom org-archive-location "%s_archive::"
4170 "The location where subtrees should be archived.
4172 The value of this variable is a string, consisting of two parts,
4173 separated by a double-colon. The first part is a filename and
4174 the second part is a headline.
4176 When the filename is omitted, archiving happens in the same file.
4177 %s in the filename will be replaced by the current file
4178 name (without the directory part). Archiving to a different file
4179 is useful to keep archived entries from contributing to the
4180 Org-mode Agenda.
4182 The archived entries will be filed as subtrees of the specified
4183 headline. When the headline is omitted, the subtrees are simply
4184 filed away at the end of the file, as top-level entries. Also in
4185 the heading you can use %s to represent the file name, this can be
4186 useful when using the same archive for a number of different files.
4188 Here are a few examples:
4189 \"%s_archive::\"
4190 If the current file is Projects.org, archive in file
4191 Projects.org_archive, as top-level trees. This is the default.
4193 \"::* Archived Tasks\"
4194 Archive in the current file, under the top-level headline
4195 \"* Archived Tasks\".
4197 \"~/org/archive.org::\"
4198 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4200 \"~/org/archive.org::* From %s\"
4201 Archive in file ~/org/archive.org (absolute path), under headlines
4202 \"From FILENAME\" where file name is the current file name.
4204 \"~/org/datetree.org::datetree/* Finished Tasks\"
4205 The \"datetree/\" string is special, signifying to archive
4206 items to the datetree. Items are placed in either the CLOSED
4207 date of the item, or the current date if there is no CLOSED date.
4208 The heading will be a subentry to the current date. There doesn't
4209 need to be a heading, but there always needs to be a slash after
4210 datetree. For example, to store archived items directly in the
4211 datetree, use \"~/org/datetree.org::datetree/\".
4213 \"basement::** Finished Tasks\"
4214 Archive in file ./basement (relative path), as level 3 trees
4215 below the level 2 heading \"** Finished Tasks\".
4217 You may set this option on a per-file basis by adding to the buffer a
4218 line like
4220 #+ARCHIVE: basement::** Finished Tasks
4222 You may also define it locally for a subtree by setting an ARCHIVE property
4223 in the entry. If such a property is found in an entry, or anywhere up
4224 the hierarchy, it will be used."
4225 :group 'org-archive
4226 :type 'string)
4228 (defcustom org-archive-tag "ARCHIVE"
4229 "The tag that marks a subtree as archived.
4230 An archived subtree does not open during visibility cycling, and does
4231 not contribute to the agenda listings.
4232 After changing this, font-lock must be restarted in the relevant buffers to
4233 get the proper fontification."
4234 :group 'org-archive
4235 :group 'org-keywords
4236 :type 'string)
4238 (defcustom org-agenda-skip-archived-trees t
4239 "Non-nil means the agenda will skip any items located in archived trees.
4240 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4241 variable is no longer recommended, you should leave it at the value t.
4242 Instead, use the key `v' to cycle the archives-mode in the agenda."
4243 :group 'org-archive
4244 :group 'org-agenda-skip
4245 :type 'boolean)
4247 (defcustom org-columns-skip-archived-trees t
4248 "Non-nil means ignore archived trees when creating column view."
4249 :group 'org-archive
4250 :group 'org-properties
4251 :type 'boolean)
4253 (defcustom org-cycle-open-archived-trees nil
4254 "Non-nil means `org-cycle' will open archived trees.
4255 An archived tree is a tree marked with the tag ARCHIVE.
4256 When nil, archived trees will stay folded. You can still open them with
4257 normal outline commands like `show-all', but not with the cycling commands."
4258 :group 'org-archive
4259 :group 'org-cycle
4260 :type 'boolean)
4262 (defcustom org-sparse-tree-open-archived-trees nil
4263 "Non-nil means sparse tree construction shows matches in archived trees.
4264 When nil, matches in these trees are highlighted, but the trees are kept in
4265 collapsed state."
4266 :group 'org-archive
4267 :group 'org-sparse-trees
4268 :type 'boolean)
4270 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4271 "The default date type when building a sparse tree.
4272 When this is nil, a date is a scheduled or a deadline timestamp.
4273 Otherwise, these types are allowed:
4275 all: all timestamps
4276 active: only active timestamps (<...>)
4277 inactive: only inactive timestamps (<...)
4278 scheduled: only scheduled timestamps
4279 deadline: only deadline timestamps"
4280 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4281 (const :tag "All timestamps" all)
4282 (const :tag "Only active timestamps" active)
4283 (const :tag "Only inactive timestamps" inactive)
4284 (const :tag "Only scheduled timestamps" scheduled)
4285 (const :tag "Only deadline timestamps" deadline))
4286 :version "24.3"
4287 :group 'org-sparse-trees)
4289 (defun org-cycle-hide-archived-subtrees (state)
4290 "Re-hide all archived subtrees after a visibility state change."
4291 (when (and (not org-cycle-open-archived-trees)
4292 (not (memq state '(overview folded))))
4293 (save-excursion
4294 (let* ((globalp (memq state '(contents all)))
4295 (beg (if globalp (point-min) (point)))
4296 (end (if globalp (point-max) (org-end-of-subtree t))))
4297 (org-hide-archived-subtrees beg end)
4298 (goto-char beg)
4299 (if (looking-at (concat ".*:" org-archive-tag ":"))
4300 (message "%s" (substitute-command-keys
4301 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4303 (defun org-force-cycle-archived ()
4304 "Cycle subtree even if it is archived."
4305 (interactive)
4306 (setq this-command 'org-cycle)
4307 (let ((org-cycle-open-archived-trees t))
4308 (call-interactively 'org-cycle)))
4310 (defun org-hide-archived-subtrees (beg end)
4311 "Re-hide all archived subtrees after a visibility state change."
4312 (save-excursion
4313 (let* ((re (concat ":" org-archive-tag ":")))
4314 (goto-char beg)
4315 (while (re-search-forward re end t)
4316 (when (org-at-heading-p)
4317 (org-flag-subtree t)
4318 (org-end-of-subtree t))))))
4320 (declare-function outline-end-of-heading "outline" ())
4321 (declare-function outline-flag-region "outline" (from to flag))
4322 (defun org-flag-subtree (flag)
4323 (save-excursion
4324 (org-back-to-heading t)
4325 (outline-end-of-heading)
4326 (outline-flag-region (point)
4327 (progn (org-end-of-subtree t) (point))
4328 flag)))
4330 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4332 (eval-and-compile
4333 (org-autoload "org-archive"
4334 '(org-add-archive-files)))
4336 ;; Autoload Column View Code
4338 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4339 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4340 (declare-function org-columns-compute "org-colview" (property))
4342 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4343 '(org-columns-number-to-string
4344 org-columns-get-format-and-top-level
4345 org-columns-compute
4346 org-columns-remove-overlays))
4348 ;; Autoload ID code
4350 (declare-function org-id-store-link "org-id")
4351 (declare-function org-id-locations-load "org-id")
4352 (declare-function org-id-locations-save "org-id")
4353 (defvar org-id-track-globally)
4354 (org-autoload "org-id"
4355 '(org-id-new
4356 org-id-copy
4357 org-id-get-with-outline-path-completion
4358 org-id-get-with-outline-drilling))
4360 ;;; Variables for pre-computed regular expressions, all buffer local
4362 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4363 "Matches first line of a hidden block.")
4364 (make-variable-buffer-local 'org-drawer-regexp)
4365 (defvar org-todo-regexp nil
4366 "Matches any of the TODO state keywords.")
4367 (make-variable-buffer-local 'org-todo-regexp)
4368 (defvar org-not-done-regexp nil
4369 "Matches any of the TODO state keywords except the last one.")
4370 (make-variable-buffer-local 'org-not-done-regexp)
4371 (defvar org-not-done-heading-regexp nil
4372 "Matches a TODO headline that is not done.")
4373 (make-variable-buffer-local 'org-not-done-regexp)
4374 (defvar org-todo-line-regexp nil
4375 "Matches a headline and puts TODO state into group 2 if present.")
4376 (make-variable-buffer-local 'org-todo-line-regexp)
4377 (defvar org-complex-heading-regexp nil
4378 "Matches a headline and puts everything into groups:
4379 group 1: the stars
4380 group 2: The todo keyword, maybe
4381 group 3: Priority cookie
4382 group 4: True headline
4383 group 5: Tags")
4384 (make-variable-buffer-local 'org-complex-heading-regexp)
4385 (defvar org-complex-heading-regexp-format nil
4386 "Printf format to make regexp to match an exact headline.
4387 This regexp will match the headline of any node which has the
4388 exact headline text that is put into the format, but may have any
4389 TODO state, priority and tags.")
4390 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4391 (defvar org-todo-line-tags-regexp nil
4392 "Matches a headline and puts TODO state into group 2 if present.
4393 Also put tags into group 4 if tags are present.")
4394 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4395 (defvar org-ds-keyword-length 12
4396 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4397 (make-variable-buffer-local 'org-ds-keyword-length)
4398 (defvar org-deadline-regexp nil
4399 "Matches the DEADLINE keyword.")
4400 (make-variable-buffer-local 'org-deadline-regexp)
4401 (defvar org-deadline-time-regexp nil
4402 "Matches the DEADLINE keyword together with a time stamp.")
4403 (make-variable-buffer-local 'org-deadline-time-regexp)
4404 (defvar org-deadline-line-regexp nil
4405 "Matches the DEADLINE keyword and the rest of the line.")
4406 (make-variable-buffer-local 'org-deadline-line-regexp)
4407 (defvar org-scheduled-regexp nil
4408 "Matches the SCHEDULED keyword.")
4409 (make-variable-buffer-local 'org-scheduled-regexp)
4410 (defvar org-scheduled-time-regexp nil
4411 "Matches the SCHEDULED keyword together with a time stamp.")
4412 (make-variable-buffer-local 'org-scheduled-time-regexp)
4413 (defvar org-closed-time-regexp nil
4414 "Matches the CLOSED keyword together with a time stamp.")
4415 (make-variable-buffer-local 'org-closed-time-regexp)
4417 (defvar org-keyword-time-regexp nil
4418 "Matches any of the 4 keywords, together with the time stamp.")
4419 (make-variable-buffer-local 'org-keyword-time-regexp)
4420 (defvar org-keyword-time-not-clock-regexp nil
4421 "Matches any of the 3 keywords, together with the time stamp.")
4422 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4423 (defvar org-maybe-keyword-time-regexp nil
4424 "Matches a timestamp, possibly preceded by a keyword.")
4425 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4426 (defvar org-all-time-keywords nil
4427 "List of time keywords.")
4428 (make-variable-buffer-local 'org-all-time-keywords)
4430 (defconst org-plain-time-of-day-regexp
4431 (concat
4432 "\\(\\<[012]?[0-9]"
4433 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4434 "\\(--?"
4435 "\\(\\<[012]?[0-9]"
4436 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4437 "\\)?")
4438 "Regular expression to match a plain time or time range.
4439 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4440 groups carry important information:
4441 0 the full match
4442 1 the first time, range or not
4443 8 the second time, if it is a range.")
4445 (defconst org-plain-time-extension-regexp
4446 (concat
4447 "\\(\\<[012]?[0-9]"
4448 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4449 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4450 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4451 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4452 groups carry important information:
4453 0 the full match
4454 7 hours of duration
4455 9 minutes of duration")
4457 (defconst org-stamp-time-of-day-regexp
4458 (concat
4459 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4460 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4461 "\\(--?"
4462 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4463 "Regular expression to match a timestamp time or time range.
4464 After a match, the following groups carry important information:
4465 0 the full match
4466 1 date plus weekday, for back referencing to make sure both times are on the same day
4467 2 the first time, range or not
4468 4 the second time, if it is a range.")
4470 (defconst org-startup-options
4471 '(("fold" org-startup-folded t)
4472 ("overview" org-startup-folded t)
4473 ("nofold" org-startup-folded nil)
4474 ("showall" org-startup-folded nil)
4475 ("showeverything" org-startup-folded showeverything)
4476 ("content" org-startup-folded content)
4477 ("indent" org-startup-indented t)
4478 ("noindent" org-startup-indented nil)
4479 ("hidestars" org-hide-leading-stars t)
4480 ("showstars" org-hide-leading-stars nil)
4481 ("odd" org-odd-levels-only t)
4482 ("oddeven" org-odd-levels-only nil)
4483 ("align" org-startup-align-all-tables t)
4484 ("noalign" org-startup-align-all-tables nil)
4485 ("inlineimages" org-startup-with-inline-images t)
4486 ("noinlineimages" org-startup-with-inline-images nil)
4487 ("customtime" org-display-custom-times t)
4488 ("logdone" org-log-done time)
4489 ("lognotedone" org-log-done note)
4490 ("nologdone" org-log-done nil)
4491 ("lognoteclock-out" org-log-note-clock-out t)
4492 ("nolognoteclock-out" org-log-note-clock-out nil)
4493 ("logrepeat" org-log-repeat state)
4494 ("lognoterepeat" org-log-repeat note)
4495 ("logdrawer" org-log-into-drawer t)
4496 ("nologdrawer" org-log-into-drawer nil)
4497 ("logstatesreversed" org-log-states-order-reversed t)
4498 ("nologstatesreversed" org-log-states-order-reversed nil)
4499 ("nologrepeat" org-log-repeat nil)
4500 ("logreschedule" org-log-reschedule time)
4501 ("lognotereschedule" org-log-reschedule note)
4502 ("nologreschedule" org-log-reschedule nil)
4503 ("logredeadline" org-log-redeadline time)
4504 ("lognoteredeadline" org-log-redeadline note)
4505 ("nologredeadline" org-log-redeadline nil)
4506 ("logrefile" org-log-refile time)
4507 ("lognoterefile" org-log-refile note)
4508 ("nologrefile" org-log-refile nil)
4509 ("fninline" org-footnote-define-inline t)
4510 ("nofninline" org-footnote-define-inline nil)
4511 ("fnlocal" org-footnote-section nil)
4512 ("fnauto" org-footnote-auto-label t)
4513 ("fnprompt" org-footnote-auto-label nil)
4514 ("fnconfirm" org-footnote-auto-label confirm)
4515 ("fnplain" org-footnote-auto-label plain)
4516 ("fnadjust" org-footnote-auto-adjust t)
4517 ("nofnadjust" org-footnote-auto-adjust nil)
4518 ("constcgs" constants-unit-system cgs)
4519 ("constSI" constants-unit-system SI)
4520 ("noptag" org-tag-persistent-alist nil)
4521 ("hideblocks" org-hide-block-startup t)
4522 ("nohideblocks" org-hide-block-startup nil)
4523 ("beamer" org-startup-with-beamer-mode t)
4524 ("entitiespretty" org-pretty-entities t)
4525 ("entitiesplain" org-pretty-entities nil))
4526 "Variable associated with STARTUP options for org-mode.
4527 Each element is a list of three items: the startup options (as written
4528 in the #+STARTUP line), the corresponding variable, and the value to set
4529 this variable to if the option is found. An optional forth element PUSH
4530 means to push this value onto the list in the variable.")
4532 (defun org-update-property-plist (key val props)
4533 "Update PROPS with KEY and VAL."
4534 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4535 (key (if appending (substring key 0 (- (length key) 1)) key))
4536 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4537 (previous (cdr (assoc key props))))
4538 (if appending
4539 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4540 (cons (cons key val) remainder))))
4542 (defconst org-block-regexp
4543 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4544 "Regular expression for hiding blocks.")
4545 (defconst org-heading-keyword-regexp-format
4546 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4547 "Printf format for a regexp matching an headline with some keyword.
4548 This regexp will match the headline of any node which has the
4549 exact keyword that is put into the format. The keyword isn't in
4550 any group by default, but the stars and the body are.")
4551 (defconst org-heading-keyword-maybe-regexp-format
4552 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4553 "Printf format for a regexp matching an headline, possibly with some keyword.
4554 This regexp can match any headline with the specified keyword, or
4555 without a keyword. The keyword isn't in any group by default,
4556 but the stars and the body are.")
4558 (defun org-set-regexps-and-options ()
4559 "Precompute regular expressions for current buffer."
4560 (when (derived-mode-p 'org-mode)
4561 (org-set-local 'org-todo-kwd-alist nil)
4562 (org-set-local 'org-todo-key-alist nil)
4563 (org-set-local 'org-todo-key-trigger nil)
4564 (org-set-local 'org-todo-keywords-1 nil)
4565 (org-set-local 'org-done-keywords nil)
4566 (org-set-local 'org-todo-heads nil)
4567 (org-set-local 'org-todo-sets nil)
4568 (org-set-local 'org-todo-log-states nil)
4569 (org-set-local 'org-file-properties nil)
4570 (org-set-local 'org-file-tags nil)
4571 (let ((re (org-make-options-regexp
4572 '("CATEGORY" "TODO" "COLUMNS"
4573 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4574 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4575 "OPTIONS")
4576 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4577 (splitre "[ \t]+")
4578 (scripts org-use-sub-superscripts)
4579 kwds kws0 kwsa key log value cat arch tags const links hw dws
4580 tail sep kws1 prio props ftags drawers beamer-p
4581 ext-setup-or-nil setup-contents (start 0))
4582 (save-excursion
4583 (save-restriction
4584 (widen)
4585 (goto-char (point-min))
4586 (while (or (and ext-setup-or-nil
4587 (string-match re ext-setup-or-nil start)
4588 (setq start (match-end 0)))
4589 (and (setq ext-setup-or-nil nil start 0)
4590 (re-search-forward re nil t)))
4591 (setq key (upcase (match-string 1 ext-setup-or-nil))
4592 value (org-match-string-no-properties 2 ext-setup-or-nil))
4593 (if (stringp value) (setq value (org-trim value)))
4594 (cond
4595 ((equal key "CATEGORY")
4596 (setq cat value))
4597 ((member key '("SEQ_TODO" "TODO"))
4598 (push (cons 'sequence (org-split-string value splitre)) kwds))
4599 ((equal key "TYP_TODO")
4600 (push (cons 'type (org-split-string value splitre)) kwds))
4601 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4602 ;; general TODO-like setup
4603 (push (cons (intern (downcase (match-string 1 key)))
4604 (org-split-string value splitre)) kwds))
4605 ((equal key "TAGS")
4606 (setq tags (append tags (if tags '("\\n") nil)
4607 (org-split-string value splitre))))
4608 ((equal key "COLUMNS")
4609 (org-set-local 'org-columns-default-format value))
4610 ((equal key "LINK")
4611 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4612 (push (cons (match-string 1 value)
4613 (org-trim (match-string 2 value)))
4614 links)))
4615 ((equal key "PRIORITIES")
4616 (setq prio (org-split-string value " +")))
4617 ((equal key "PROPERTY")
4618 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4619 (setq props (org-update-property-plist (match-string 1 value)
4620 (match-string 2 value)
4621 props))))
4622 ((equal key "FILETAGS")
4623 (when (string-match "\\S-" value)
4624 (setq ftags
4625 (append
4626 ftags
4627 (apply 'append
4628 (mapcar (lambda (x) (org-split-string x ":"))
4629 (org-split-string value)))))))
4630 ((equal key "DRAWERS")
4631 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4632 ((equal key "CONSTANTS")
4633 (setq const (append const (org-split-string value splitre))))
4634 ((equal key "STARTUP")
4635 (let ((opts (org-split-string value splitre))
4636 l var val)
4637 (while (setq l (pop opts))
4638 (when (setq l (assoc l org-startup-options))
4639 (setq var (nth 1 l) val (nth 2 l))
4640 (if (not (nth 3 l))
4641 (set (make-local-variable var) val)
4642 (if (not (listp (symbol-value var)))
4643 (set (make-local-variable var) nil))
4644 (set (make-local-variable var) (symbol-value var))
4645 (add-to-list var val))))))
4646 ((equal key "ARCHIVE")
4647 (setq arch value)
4648 (remove-text-properties 0 (length arch)
4649 '(face t fontified t) arch))
4650 ((equal key "LATEX_CLASS")
4651 (setq beamer-p (equal value "beamer")))
4652 ((equal key "OPTIONS")
4653 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4654 (setq scripts (read (match-string 2 value)))))
4655 ((equal key "SETUPFILE")
4656 (setq setup-contents (org-file-contents
4657 (expand-file-name
4658 (org-remove-double-quotes value))
4659 'noerror))
4660 (if (not ext-setup-or-nil)
4661 (setq ext-setup-or-nil setup-contents start 0)
4662 (setq ext-setup-or-nil
4663 (concat (substring ext-setup-or-nil 0 start)
4664 "\n" setup-contents "\n"
4665 (substring ext-setup-or-nil start)))))))
4666 ;; search for property blocks
4667 (goto-char (point-min))
4668 (while (re-search-forward org-block-regexp nil t)
4669 (when (equal "PROPERTY" (upcase (match-string 1)))
4670 (setq value (replace-regexp-in-string
4671 "[\n\r]" " " (match-string 4)))
4672 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4673 (setq props (org-update-property-plist (match-string 1 value)
4674 (match-string 2 value)
4675 props)))))))
4676 (org-set-local 'org-use-sub-superscripts scripts)
4677 (when cat
4678 (org-set-local 'org-category (intern cat))
4679 (push (cons "CATEGORY" cat) props))
4680 (when prio
4681 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4682 (setq prio (mapcar 'string-to-char prio))
4683 (org-set-local 'org-highest-priority (nth 0 prio))
4684 (org-set-local 'org-lowest-priority (nth 1 prio))
4685 (org-set-local 'org-default-priority (nth 2 prio)))
4686 (and props (org-set-local 'org-file-properties (nreverse props)))
4687 (and ftags (org-set-local 'org-file-tags
4688 (mapcar 'org-add-prop-inherited ftags)))
4689 (and drawers (org-set-local 'org-drawers drawers))
4690 (and arch (org-set-local 'org-archive-location arch))
4691 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4692 ;; Process the TODO keywords
4693 (unless kwds
4694 ;; Use the global values as if they had been given locally.
4695 (setq kwds (default-value 'org-todo-keywords))
4696 (if (stringp (car kwds))
4697 (setq kwds (list (cons org-todo-interpretation
4698 (default-value 'org-todo-keywords)))))
4699 (setq kwds (reverse kwds)))
4700 (setq kwds (nreverse kwds))
4701 (let (inter kws kw)
4702 (while (setq kws (pop kwds))
4703 (let ((kws (or
4704 (run-hook-with-args-until-success
4705 'org-todo-setup-filter-hook kws)
4706 kws)))
4707 (setq inter (pop kws) sep (member "|" kws)
4708 kws0 (delete "|" (copy-sequence kws))
4709 kwsa nil
4710 kws1 (mapcar
4711 (lambda (x)
4712 ;; 1 2
4713 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4714 (progn
4715 (setq kw (match-string 1 x)
4716 key (and (match-end 2) (match-string 2 x))
4717 log (org-extract-log-state-settings x))
4718 (push (cons kw (and key (string-to-char key))) kwsa)
4719 (and log (push log org-todo-log-states))
4721 (error "Invalid TODO keyword %s" x)))
4722 kws0)
4723 kwsa (if kwsa (append '((:startgroup))
4724 (nreverse kwsa)
4725 '((:endgroup))))
4726 hw (car kws1)
4727 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4728 tail (list inter hw (car dws) (org-last dws))))
4729 (add-to-list 'org-todo-heads hw 'append)
4730 (push kws1 org-todo-sets)
4731 (setq org-done-keywords (append org-done-keywords dws nil))
4732 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4733 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4734 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4735 (setq org-todo-sets (nreverse org-todo-sets)
4736 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4737 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4738 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4739 ;; Process the constants
4740 (when const
4741 (let (e cst)
4742 (while (setq e (pop const))
4743 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4744 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4745 (setq org-table-formula-constants-local cst)))
4747 ;; Process the tags.
4748 (when tags
4749 (let (e tgs)
4750 (while (setq e (pop tags))
4751 (cond
4752 ((equal e "{") (push '(:startgroup) tgs))
4753 ((equal e "}") (push '(:endgroup) tgs))
4754 ((equal e "\\n") (push '(:newline) tgs))
4755 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4756 (push (cons (match-string 1 e)
4757 (string-to-char (match-string 2 e)))
4758 tgs))
4759 (t (push (list e) tgs))))
4760 (org-set-local 'org-tag-alist nil)
4761 (while (setq e (pop tgs))
4762 (or (and (stringp (car e))
4763 (assoc (car e) org-tag-alist))
4764 (push e org-tag-alist)))))
4766 ;; Compute the regular expressions and other local variables.
4767 ;; Using `org-outline-regexp-bol' would complicate them much,
4768 ;; because of the fixed white space at the end of that string.
4769 (if (not org-done-keywords)
4770 (setq org-done-keywords (and org-todo-keywords-1
4771 (list (org-last org-todo-keywords-1)))))
4772 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4773 (length org-scheduled-string)
4774 (length org-clock-string)
4775 (length org-closed-string)))
4776 org-drawer-regexp
4777 (concat "^[ \t]*:\\("
4778 (mapconcat 'regexp-quote org-drawers "\\|")
4779 "\\):[ \t]*$")
4780 org-not-done-keywords
4781 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4782 org-todo-regexp
4783 (concat "\\("
4784 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4785 "\\)")
4786 org-not-done-regexp
4787 (concat "\\("
4788 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4789 "\\)")
4790 org-not-done-heading-regexp
4791 (format org-heading-keyword-regexp-format org-not-done-regexp)
4792 org-todo-line-regexp
4793 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4794 org-complex-heading-regexp
4795 (concat "^\\(\\*+\\)"
4796 "\\(?: +" org-todo-regexp "\\)?"
4797 "\\(?: +\\(\\[#.\\]\\)\\)?"
4798 "\\(?: +\\(.*?\\)\\)??"
4799 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4800 "[ \t]*$")
4801 org-complex-heading-regexp-format
4802 (concat "^\\(\\*+\\)"
4803 "\\(?: +" org-todo-regexp "\\)?"
4804 "\\(?: +\\(\\[#.\\]\\)\\)?"
4805 "\\(?: +"
4806 ;; Stats cookies can be stuck to body.
4807 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4808 "\\(%s\\)"
4809 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4810 "\\)"
4811 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4812 "[ \t]*$")
4813 org-todo-line-tags-regexp
4814 (concat "^\\(\\*+\\)"
4815 "\\(?: +" org-todo-regexp "\\)?"
4816 "\\(?: +\\(.*?\\)\\)??"
4817 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4818 "[ \t]*$")
4819 org-deadline-regexp (concat "\\<" org-deadline-string)
4820 org-deadline-time-regexp
4821 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4822 org-deadline-line-regexp
4823 (concat "\\<\\(" org-deadline-string "\\).*")
4824 org-scheduled-regexp
4825 (concat "\\<" org-scheduled-string)
4826 org-scheduled-time-regexp
4827 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4828 org-closed-time-regexp
4829 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4830 org-keyword-time-regexp
4831 (concat "\\<\\(" org-scheduled-string
4832 "\\|" org-deadline-string
4833 "\\|" org-closed-string
4834 "\\|" org-clock-string "\\)"
4835 " *[[<]\\([^]>]+\\)[]>]")
4836 org-keyword-time-not-clock-regexp
4837 (concat "\\<\\(" org-scheduled-string
4838 "\\|" org-deadline-string
4839 "\\|" org-closed-string
4840 "\\)"
4841 " *[[<]\\([^]>]+\\)[]>]")
4842 org-maybe-keyword-time-regexp
4843 (concat "\\(\\<\\(" org-scheduled-string
4844 "\\|" org-deadline-string
4845 "\\|" org-closed-string
4846 "\\|" org-clock-string "\\)\\)?"
4847 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4848 org-all-time-keywords
4849 (mapcar (lambda (w) (substring w 0 -1))
4850 (list org-scheduled-string org-deadline-string
4851 org-clock-string org-closed-string))
4853 (org-compute-latex-and-specials-regexp)
4854 (org-set-font-lock-defaults))))
4856 (defun org-file-contents (file &optional noerror)
4857 "Return the contents of FILE, as a string."
4858 (if (or (not file)
4859 (not (file-readable-p file)))
4860 (if noerror
4861 (progn
4862 (message "Cannot read file \"%s\"" file)
4863 (ding) (sit-for 2)
4865 (error "Cannot read file \"%s\"" file))
4866 (with-temp-buffer
4867 (insert-file-contents file)
4868 (buffer-string))))
4870 (defun org-extract-log-state-settings (x)
4871 "Extract the log state setting from a TODO keyword string.
4872 This will extract info from a string like \"WAIT(w@/!)\"."
4873 (let (kw key log1 log2)
4874 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4875 (setq kw (match-string 1 x)
4876 key (and (match-end 2) (match-string 2 x))
4877 log1 (and (match-end 3) (match-string 3 x))
4878 log2 (and (match-end 4) (match-string 4 x)))
4879 (and (or log1 log2)
4880 (list kw
4881 (and log1 (if (equal log1 "!") 'time 'note))
4882 (and log2 (if (equal log2 "!") 'time 'note)))))))
4884 (defun org-remove-keyword-keys (list)
4885 "Remove a pair of parenthesis at the end of each string in LIST."
4886 (mapcar (lambda (x)
4887 (if (string-match "(.*)$" x)
4888 (substring x 0 (match-beginning 0))
4890 list))
4892 (defun org-assign-fast-keys (alist)
4893 "Assign fast keys to a keyword-key alist.
4894 Respect keys that are already there."
4895 (let (new e (alt ?0))
4896 (while (setq e (pop alist))
4897 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4898 (cdr e)) ;; Key already assigned.
4899 (push e new)
4900 (let ((clist (string-to-list (downcase (car e))))
4901 (used (append new alist)))
4902 (when (= (car clist) ?@)
4903 (pop clist))
4904 (while (and clist (rassoc (car clist) used))
4905 (pop clist))
4906 (unless clist
4907 (while (rassoc alt used)
4908 (incf alt)))
4909 (push (cons (car e) (or (car clist) alt)) new))))
4910 (nreverse new)))
4912 ;;; Some variables used in various places
4914 (defvar org-window-configuration nil
4915 "Used in various places to store a window configuration.")
4916 (defvar org-selected-window nil
4917 "Used in various places to store a window configuration.")
4918 (defvar org-finish-function nil
4919 "Function to be called when `C-c C-c' is used.
4920 This is for getting out of special buffers like capture.")
4923 ;; FIXME: Occasionally check by commenting these, to make sure
4924 ;; no other functions uses these, forgetting to let-bind them.
4925 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4926 (defvar org-last-state)
4927 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4929 ;; Defined somewhere in this file, but used before definition.
4930 (defvar org-entities) ;; defined in org-entities.el
4931 (defvar org-struct-menu)
4932 (defvar org-org-menu)
4933 (defvar org-tbl-menu)
4935 ;;;; Define the Org-mode
4937 ;; We use a before-change function to check if a table might need
4938 ;; an update.
4939 (defvar org-table-may-need-update t
4940 "Indicates that a table might need an update.
4941 This variable is set by `org-before-change-function'.
4942 `org-table-align' sets it back to nil.")
4943 (defun org-before-change-function (beg end)
4944 "Every change indicates that a table might need an update."
4945 (setq org-table-may-need-update t))
4946 (defvar org-mode-map)
4947 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4948 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4949 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4950 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4951 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4952 (defvar org-table-buffer-is-an nil)
4954 (defvar bidi-paragraph-direction)
4955 (defvar buffer-face-mode-face)
4957 (require 'outline)
4958 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4959 (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"))
4960 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4962 ;; Other stuff we need.
4963 (require 'time-date)
4964 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4965 (require 'easymenu)
4966 (require 'overlay)
4968 (require 'org-macs)
4969 (require 'org-entities)
4970 ;; (require 'org-compat) moved higher up in the file before it is first used
4971 (require 'org-faces)
4972 (require 'org-list)
4973 (require 'org-pcomplete)
4974 (require 'org-src)
4975 (require 'org-footnote)
4977 ;; babel
4978 (require 'ob)
4980 ;;;###autoload
4981 (define-derived-mode org-mode outline-mode "Org"
4982 "Outline-based notes management and organizer, alias
4983 \"Carsten's outline-mode for keeping track of everything.\"
4985 Org-mode develops organizational tasks around a NOTES file which
4986 contains information about projects as plain text. Org-mode is
4987 implemented on top of outline-mode, which is ideal to keep the content
4988 of large files well structured. It supports ToDo items, deadlines and
4989 time stamps, which magically appear in the diary listing of the Emacs
4990 calendar. Tables are easily created with a built-in table editor.
4991 Plain text URL-like links connect to websites, emails (VM), Usenet
4992 messages (Gnus), BBDB entries, and any files related to the project.
4993 For printing and sharing of notes, an Org-mode file (or a part of it)
4994 can be exported as a structured ASCII or HTML file.
4996 The following commands are available:
4998 \\{org-mode-map}"
5000 ;; Get rid of Outline menus, they are not needed
5001 ;; Need to do this here because define-derived-mode sets up
5002 ;; the keymap so late. Still, it is a waste to call this each time
5003 ;; we switch another buffer into org-mode.
5004 (if (featurep 'xemacs)
5005 (when (boundp 'outline-mode-menu-heading)
5006 ;; Assume this is Greg's port, it uses easymenu
5007 (easy-menu-remove outline-mode-menu-heading)
5008 (easy-menu-remove outline-mode-menu-show)
5009 (easy-menu-remove outline-mode-menu-hide))
5010 (define-key org-mode-map [menu-bar headings] 'undefined)
5011 (define-key org-mode-map [menu-bar hide] 'undefined)
5012 (define-key org-mode-map [menu-bar show] 'undefined))
5014 (org-load-modules-maybe)
5015 (easy-menu-add org-org-menu)
5016 (easy-menu-add org-tbl-menu)
5017 (org-install-agenda-files-menu)
5018 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5019 (add-to-invisibility-spec '(org-cwidth))
5020 (add-to-invisibility-spec '(org-hide-block . t))
5021 (when (featurep 'xemacs)
5022 (org-set-local 'line-move-ignore-invisible t))
5023 (org-set-local 'outline-regexp org-outline-regexp)
5024 (org-set-local 'outline-level 'org-outline-level)
5025 (setq bidi-paragraph-direction 'left-to-right)
5026 (when (and org-ellipsis
5027 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5028 (fboundp 'make-glyph-code))
5029 (unless org-display-table
5030 (setq org-display-table (make-display-table)))
5031 (set-display-table-slot
5032 org-display-table 4
5033 (vconcat (mapcar
5034 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5035 org-ellipsis)))
5036 (if (stringp org-ellipsis) org-ellipsis "..."))))
5037 (setq buffer-display-table org-display-table))
5038 (org-set-regexps-and-options)
5039 (when (and org-tag-faces (not org-tags-special-faces-re))
5040 ;; tag faces set outside customize.... force initialization.
5041 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5042 ;; Calc embedded
5043 (org-set-local 'calc-embedded-open-mode "# ")
5044 (modify-syntax-entry ?@ "w")
5045 (modify-syntax-entry ?\" "\"")
5046 (if org-startup-truncated (setq truncate-lines t))
5047 (org-set-local 'font-lock-unfontify-region-function
5048 'org-unfontify-region)
5049 ;; Activate before-change-function
5050 (org-set-local 'org-table-may-need-update t)
5051 (org-add-hook 'before-change-functions 'org-before-change-function nil
5052 'local)
5053 ;; Check for running clock before killing a buffer
5054 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5055 ;; Initialize macros templates.
5056 (org-macro-initialize-templates)
5057 ;; Initialize radio targets.
5058 (org-update-radio-target-regexp)
5059 ;; Indentation.
5060 (org-set-local 'indent-line-function 'org-indent-line)
5061 (org-set-local 'indent-region-function 'org-indent-region)
5062 ;; Filling and auto-filling.
5063 (org-setup-filling)
5064 ;; Comments.
5065 (org-setup-comments-handling)
5066 ;; Beginning/end of defun
5067 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5068 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5069 ;; Next error for sparse trees
5070 (org-set-local 'next-error-function 'org-occur-next-match)
5071 ;; Make sure dependence stuff works reliably, even for users who set it
5072 ;; too late :-(
5073 (if org-enforce-todo-dependencies
5074 (add-hook 'org-blocker-hook
5075 'org-block-todo-from-children-or-siblings-or-parent)
5076 (remove-hook 'org-blocker-hook
5077 'org-block-todo-from-children-or-siblings-or-parent))
5078 (if org-enforce-todo-checkbox-dependencies
5079 (add-hook 'org-blocker-hook
5080 'org-block-todo-from-checkboxes)
5081 (remove-hook 'org-blocker-hook
5082 'org-block-todo-from-checkboxes))
5084 ;; Align options lines
5085 (org-set-local
5086 'align-mode-rules-list
5087 '((org-in-buffer-settings
5088 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5089 (modes . '(org-mode)))))
5091 ;; Imenu
5092 (org-set-local 'imenu-create-index-function
5093 'org-imenu-get-tree)
5095 ;; Make isearch reveal context
5096 (if (or (featurep 'xemacs)
5097 (not (boundp 'outline-isearch-open-invisible-function)))
5098 ;; Emacs 21 and XEmacs make use of the hook
5099 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5100 ;; Emacs 22 deals with this through a special variable
5101 (org-set-local 'outline-isearch-open-invisible-function
5102 (lambda (&rest ignore) (org-show-context 'isearch))))
5104 ;; Turn on org-beamer-mode?
5105 (and org-startup-with-beamer-mode (org-beamer-mode))
5107 ;; Setup the pcomplete hooks
5108 (set (make-local-variable 'pcomplete-command-completion-function)
5109 'org-pcomplete-initial)
5110 (set (make-local-variable 'pcomplete-command-name-function)
5111 'org-command-at-point)
5112 (set (make-local-variable 'pcomplete-default-completion-function)
5113 'ignore)
5114 (set (make-local-variable 'pcomplete-parse-arguments-function)
5115 'org-parse-arguments)
5116 (set (make-local-variable 'pcomplete-termination-string) "")
5117 (when (>= emacs-major-version 23)
5118 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5120 ;; If empty file that did not turn on org-mode automatically, make it to.
5121 (if (and org-insert-mode-line-in-empty-file
5122 (org-called-interactively-p 'any)
5123 (= (point-min) (point-max)))
5124 (insert "# -*- mode: org -*-\n\n"))
5125 (unless org-inhibit-startup
5126 (when org-startup-align-all-tables
5127 (let ((bmp (buffer-modified-p)))
5128 (org-table-map-tables 'org-table-align 'quietly)
5129 (set-buffer-modified-p bmp)))
5130 (when org-startup-with-inline-images
5131 (org-display-inline-images))
5132 (when org-startup-indented
5133 (require 'org-indent)
5134 (org-indent-mode 1))
5135 (unless org-inhibit-startup-visibility-stuff
5136 (org-set-startup-visibility)))
5137 ;; Try to set org-hide correctly
5138 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5140 (when (fboundp 'abbrev-table-put)
5141 (abbrev-table-put org-mode-abbrev-table
5142 :parents (list text-mode-abbrev-table)))
5144 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5147 (defun org-find-invisible-foreground ()
5148 (let ((candidates (remove
5149 "unspecified-bg"
5150 (nconc
5151 (list (face-background 'default)
5152 (face-background 'org-default))
5153 (mapcar
5154 (lambda (alist)
5155 (when (boundp alist)
5156 (cdr (assoc 'background-color (symbol-value alist)))))
5157 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5158 (list (face-foreground 'org-hide))))))
5159 (car (remove nil candidates))))
5161 (defun org-current-time (&optional rounding-minutes)
5162 "Current time, possibly rounded to ROUNDING-MINUTES.
5163 When ROUNDING-MINUTES is not an integer, fall back on the car of
5164 `org-time-stamp-rounding-minutes'."
5165 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5166 (car org-time-stamp-rounding-minutes)))
5167 (time (decode-time)))
5168 (if (> r 1)
5169 (apply 'encode-time
5170 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5171 (nthcdr 2 time)))
5172 (current-time))))
5174 (defun org-today ()
5175 "Return today date, considering `org-extend-today-until'."
5176 (time-to-days
5177 (time-subtract (current-time)
5178 (list 0 (* 3600 org-extend-today-until) 0))))
5180 ;;;; Font-Lock stuff, including the activators
5182 (defvar org-mouse-map (make-sparse-keymap))
5183 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5184 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5185 (when org-mouse-1-follows-link
5186 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5187 (when org-tab-follows-link
5188 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5189 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5191 (require 'font-lock)
5193 (defconst org-non-link-chars "]\t\n\r<>")
5194 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5195 "shell" "elisp" "doi" "message"))
5196 (defvar org-link-types-re nil
5197 "Matches a link that has a url-like prefix like \"http:\"")
5198 (defvar org-link-re-with-space nil
5199 "Matches a link with spaces, optional angular brackets around it.")
5200 (defvar org-link-re-with-space2 nil
5201 "Matches a link with spaces, optional angular brackets around it.")
5202 (defvar org-link-re-with-space3 nil
5203 "Matches a link with spaces, only for internal part in bracket links.")
5204 (defvar org-angle-link-re nil
5205 "Matches link with angular brackets, spaces are allowed.")
5206 (defvar org-plain-link-re nil
5207 "Matches plain link, without spaces.")
5208 (defvar org-bracket-link-regexp nil
5209 "Matches a link in double brackets.")
5210 (defvar org-bracket-link-analytic-regexp nil
5211 "Regular expression used to analyze links.
5212 Here is what the match groups contain after a match:
5213 1: http:
5214 2: http
5215 3: path
5216 4: [desc]
5217 5: desc")
5218 (defvar org-bracket-link-analytic-regexp++ nil
5219 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5220 (defvar org-any-link-re nil
5221 "Regular expression matching any link.")
5223 (defcustom org-match-sexp-depth 3
5224 "Number of stacked braces for sub/superscript matching.
5225 This has to be set before loading org.el to be effective."
5226 :group 'org-export-translation ; ??????????????????????????/
5227 :type 'integer)
5229 (defun org-create-multibrace-regexp (left right n)
5230 "Create a regular expression which will match a balanced sexp.
5231 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5232 as single character strings.
5233 The regexp returned will match the entire expression including the
5234 delimiters. It will also define a single group which contains the
5235 match except for the outermost delimiters. The maximum depth of
5236 stacked delimiters is N. Escaping delimiters is not possible."
5237 (let* ((nothing (concat "[^" left right "]*?"))
5238 (or "\\|")
5239 (re nothing)
5240 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5241 (while (> n 1)
5242 (setq n (1- n)
5243 re (concat re or next)
5244 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5245 (concat left "\\(" re "\\)" right)))
5247 (defvar org-match-substring-regexp
5248 (concat
5249 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5250 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5251 "\\|"
5252 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5253 "\\|"
5254 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5255 "The regular expression matching a sub- or superscript.")
5257 (defvar org-match-substring-with-braces-regexp
5258 (concat
5259 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5260 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5261 "\\)")
5262 "The regular expression matching a sub- or superscript, forcing braces.")
5264 (defun org-make-link-regexps ()
5265 "Update the link regular expressions.
5266 This should be called after the variable `org-link-types' has changed."
5267 (setq org-link-types-re
5268 (concat
5269 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5270 org-link-re-with-space
5271 (concat
5272 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5273 "\\([^" org-non-link-chars " ]"
5274 "[^" org-non-link-chars "]*"
5275 "[^" org-non-link-chars " ]\\)>?")
5276 org-link-re-with-space2
5277 (concat
5278 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5279 "\\([^" org-non-link-chars " ]"
5280 "[^\t\n\r]*"
5281 "[^" org-non-link-chars " ]\\)>?")
5282 org-link-re-with-space3
5283 (concat
5284 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5285 "\\([^" org-non-link-chars " ]"
5286 "[^\t\n\r]*\\)")
5287 org-angle-link-re
5288 (concat
5289 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5290 "\\([^" org-non-link-chars " ]"
5291 "[^" org-non-link-chars "]*"
5292 "\\)>")
5293 org-plain-link-re
5294 (concat
5295 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5296 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5297 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5298 org-bracket-link-regexp
5299 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5300 org-bracket-link-analytic-regexp
5301 (concat
5302 "\\[\\["
5303 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5304 "\\([^]]+\\)"
5305 "\\]"
5306 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5307 "\\]")
5308 org-bracket-link-analytic-regexp++
5309 (concat
5310 "\\[\\["
5311 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5312 "\\([^]]+\\)"
5313 "\\]"
5314 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5315 "\\]")
5316 org-any-link-re
5317 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5318 org-angle-link-re "\\)\\|\\("
5319 org-plain-link-re "\\)")))
5321 (org-make-link-regexps)
5323 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5324 "Regular expression for fast time stamp matching.")
5325 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5326 "Regular expression for fast time stamp matching.")
5327 (defconst org-ts-regexp0
5328 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5329 "Regular expression matching time strings for analysis.
5330 This one does not require the space after the date, so it can be used
5331 on a string that terminates immediately after the date.")
5332 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5333 "Regular expression matching time strings for analysis.")
5334 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5335 "Regular expression matching time stamps, with groups.")
5336 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5337 "Regular expression matching time stamps (also [..]), with groups.")
5338 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5339 "Regular expression matching a time stamp range.")
5340 (defconst org-tr-regexp-both
5341 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5342 "Regular expression matching a time stamp range.")
5343 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5344 org-ts-regexp "\\)?")
5345 "Regular expression matching a time stamp or time stamp range.")
5346 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5347 org-ts-regexp-both "\\)?")
5348 "Regular expression matching a time stamp or time stamp range.
5349 The time stamps may be either active or inactive.")
5351 (defvar org-emph-face nil)
5353 (defun org-do-emphasis-faces (limit)
5354 "Run through the buffer and add overlays to emphasized strings."
5355 (let (rtn a)
5356 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5357 (if (not (= (char-after (match-beginning 3))
5358 (char-after (match-beginning 4))))
5359 (progn
5360 (setq rtn t)
5361 (setq a (assoc (match-string 3) org-emphasis-alist))
5362 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5363 'face
5364 (nth 1 a))
5365 (and (nth 4 a)
5366 (org-remove-flyspell-overlays-in
5367 (match-beginning 0) (match-end 0)))
5368 (add-text-properties (match-beginning 2) (match-end 2)
5369 '(font-lock-multiline t org-emphasis t))
5370 (when org-hide-emphasis-markers
5371 (add-text-properties (match-end 4) (match-beginning 5)
5372 '(invisible org-link))
5373 (add-text-properties (match-beginning 3) (match-end 3)
5374 '(invisible org-link)))))
5375 (backward-char 1))
5376 rtn))
5378 (defun org-emphasize (&optional char)
5379 "Insert or change an emphasis, i.e. a font like bold or italic.
5380 If there is an active region, change that region to a new emphasis.
5381 If there is no region, just insert the marker characters and position
5382 the cursor between them.
5383 CHAR should be either the marker character, or the first character of the
5384 HTML tag associated with that emphasis. If CHAR is a space, the means
5385 to remove the emphasis of the selected region.
5386 If char is not given (for example in an interactive call) it
5387 will be prompted for."
5388 (interactive)
5389 (let ((eal org-emphasis-alist) e det
5390 (erc org-emphasis-regexp-components)
5391 (prompt "")
5392 (string "") beg end move tag c s)
5393 (if (org-region-active-p)
5394 (setq beg (region-beginning) end (region-end)
5395 string (buffer-substring beg end))
5396 (setq move t))
5398 (while (setq e (pop eal))
5399 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5400 c (aref tag 0))
5401 (push (cons c (string-to-char (car e))) det)
5402 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5403 (substring tag 1)))))
5404 (setq det (nreverse det))
5405 (unless char
5406 (message "%s" (concat "Emphasis marker or tag:" prompt))
5407 (setq char (read-char-exclusive)))
5408 (setq char (or (cdr (assoc char det)) char))
5409 (if (equal char ?\ )
5410 (setq s "" move nil)
5411 (unless (assoc (char-to-string char) org-emphasis-alist)
5412 (error "No such emphasis marker: \"%c\"" char))
5413 (setq s (char-to-string char)))
5414 (while (and (> (length string) 1)
5415 (equal (substring string 0 1) (substring string -1))
5416 (assoc (substring string 0 1) org-emphasis-alist))
5417 (setq string (substring string 1 -1)))
5418 (setq string (concat s string s))
5419 (if beg (delete-region beg end))
5420 (unless (or (bolp)
5421 (string-match (concat "[" (nth 0 erc) "\n]")
5422 (char-to-string (char-before (point)))))
5423 (insert " "))
5424 (unless (or (eobp)
5425 (string-match (concat "[" (nth 1 erc) "\n]")
5426 (char-to-string (char-after (point)))))
5427 (insert " ") (backward-char 1))
5428 (insert string)
5429 (and move (backward-char 1))))
5431 (defconst org-nonsticky-props
5432 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5434 (defsubst org-rear-nonsticky-at (pos)
5435 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5437 (defun org-activate-plain-links (limit)
5438 "Run through the buffer and add overlays to links."
5439 (catch 'exit
5440 (let (f hl)
5441 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5442 (not (org-in-src-block-p)))
5443 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5444 (setq f (get-text-property (match-beginning 0) 'face))
5445 (setq hl (org-match-string-no-properties 0))
5446 (if (or (eq f 'org-tag)
5447 (and (listp f) (memq 'org-tag f)))
5449 (add-text-properties (match-beginning 0) (match-end 0)
5450 (list 'mouse-face 'highlight
5451 'face 'org-link
5452 'htmlize-link `(:uri ,hl)
5453 'keymap org-mouse-map))
5454 (org-rear-nonsticky-at (match-end 0)))
5455 t))))
5457 (defun org-activate-code (limit)
5458 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5459 (progn
5460 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5461 (remove-text-properties (match-beginning 0) (match-end 0)
5462 '(display t invisible t intangible t))
5463 t)))
5465 (defcustom org-src-fontify-natively nil
5466 "When non-nil, fontify code in code blocks."
5467 :type 'boolean
5468 :version "24.1"
5469 :group 'org-appearance
5470 :group 'org-babel)
5472 (defcustom org-allow-promoting-top-level-subtree nil
5473 "When non-nil, allow promoting a top level subtree.
5474 The leading star of the top level headline will be replaced
5475 by a #."
5476 :type 'boolean
5477 :version "24.1"
5478 :group 'org-appearance)
5480 (defun org-fontify-meta-lines-and-blocks (limit)
5481 (condition-case nil
5482 (org-fontify-meta-lines-and-blocks-1 limit)
5483 (error (message "org-mode fontification error"))))
5485 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5486 "Fontify #+ lines and blocks, in the correct ways."
5487 (let ((case-fold-search t))
5488 (if (re-search-forward
5489 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5490 limit t)
5491 (let ((beg (match-beginning 0))
5492 (block-start (match-end 0))
5493 (block-end nil)
5494 (lang (match-string 7))
5495 (beg1 (line-beginning-position 2))
5496 (dc1 (downcase (match-string 2)))
5497 (dc3 (downcase (match-string 3)))
5498 end end1 quoting block-type ovl)
5499 (cond
5500 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5501 ;; a single line of backend-specific content
5502 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5503 (remove-text-properties (match-beginning 0) (match-end 0)
5504 '(display t invisible t intangible t))
5505 (add-text-properties (match-beginning 1) (match-end 3)
5506 '(font-lock-fontified t face org-meta-line))
5507 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5508 '(font-lock-fontified t face org-block))
5509 ; for backend-specific code
5511 ((and (match-end 4) (equal dc3 "+begin"))
5512 ;; Truly a block
5513 (setq block-type (downcase (match-string 5))
5514 quoting (member block-type org-protecting-blocks))
5515 (when (re-search-forward
5516 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5517 nil t) ;; on purpose, we look further than LIMIT
5518 (setq end (min (point-max) (match-end 0))
5519 end1 (min (point-max) (1- (match-beginning 0))))
5520 (setq block-end (match-beginning 0))
5521 (when quoting
5522 (remove-text-properties beg end
5523 '(display t invisible t intangible t)))
5524 (add-text-properties
5525 beg end
5526 '(font-lock-fontified t font-lock-multiline t))
5527 (add-text-properties beg beg1 '(face org-meta-line))
5528 (add-text-properties end1 (min (point-max) (1+ end))
5529 '(face org-meta-line)) ; for end_src
5530 (cond
5531 ((and lang (not (string= lang "")) org-src-fontify-natively)
5532 (org-src-font-lock-fontify-block lang block-start block-end)
5533 ;; remove old background overlays
5534 (mapc (lambda (ov)
5535 (if (eq (overlay-get ov 'face) 'org-block-background)
5536 (delete-overlay ov)))
5537 (overlays-at (/ (+ beg1 block-end) 2)))
5538 ;; add a background overlay
5539 (setq ovl (make-overlay beg1 block-end))
5540 (overlay-put ovl 'face 'org-block-background)
5541 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5542 (quoting
5543 (add-text-properties beg1 (min (point-max) (1+ end1))
5544 '(face org-block))) ; end of source block
5545 ((not org-fontify-quote-and-verse-blocks))
5546 ((string= block-type "quote")
5547 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5548 ((string= block-type "verse")
5549 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5550 (add-text-properties beg beg1 '(face org-block-begin-line))
5551 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5552 '(face org-block-end-line))
5554 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5555 (add-text-properties
5556 beg (match-end 3)
5557 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5558 '(font-lock-fontified t invisible t)
5559 '(font-lock-fontified t face org-document-info-keyword)))
5560 (add-text-properties
5561 (match-beginning 6) (match-end 6)
5562 (if (string-equal dc1 "+title:")
5563 '(font-lock-fontified t face org-document-title)
5564 '(font-lock-fontified t face org-document-info))))
5565 ((or (equal dc1 "+results")
5566 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5567 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5568 "+call:" "+header:" "+headers:" "+name:"))
5569 (and (match-end 4) (equal dc3 "+attr")))
5570 (add-text-properties
5571 beg (match-end 0)
5572 '(font-lock-fontified t face org-meta-line))
5574 ((member dc3 '(" " ""))
5575 (add-text-properties
5576 beg (match-end 0)
5577 '(font-lock-fontified t face font-lock-comment-face)))
5578 ((not (member (char-after beg) '(?\ ?\t)))
5579 ;; just any other in-buffer setting, but not indented
5580 (add-text-properties
5581 beg (match-end 0)
5582 '(font-lock-fontified t face org-meta-line))
5584 (t nil))))))
5586 (defun org-activate-angle-links (limit)
5587 "Run through the buffer and add overlays to links."
5588 (if (and (re-search-forward org-angle-link-re limit t)
5589 (not (org-in-src-block-p)))
5590 (progn
5591 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5592 (add-text-properties (match-beginning 0) (match-end 0)
5593 (list 'mouse-face 'highlight
5594 'keymap org-mouse-map))
5595 (org-rear-nonsticky-at (match-end 0))
5596 t)))
5598 (defun org-activate-footnote-links (limit)
5599 "Run through the buffer and add overlays to footnotes."
5600 (let ((fn (org-footnote-next-reference-or-definition limit)))
5601 (when fn
5602 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5603 (org-remove-flyspell-overlays-in beg end)
5604 (add-text-properties beg end
5605 (list 'mouse-face 'highlight
5606 'keymap org-mouse-map
5607 'help-echo
5608 (if (= (point-at-bol) beg)
5609 "Footnote definition"
5610 "Footnote reference")
5611 'font-lock-fontified t
5612 'font-lock-multiline t
5613 'face 'org-footnote))))))
5615 (defun org-activate-bracket-links (limit)
5616 "Run through the buffer and add overlays to bracketed links."
5617 (if (and (re-search-forward org-bracket-link-regexp limit t)
5618 (not (org-in-src-block-p)))
5619 (let* ((hl (org-match-string-no-properties 1))
5620 (help (concat "LINK: " hl))
5621 ;; FIXME: Above we should remove the escapes. But that
5622 ;; requires another match, protecting match data, a lot
5623 ;; of overhead for font-lock.
5624 (ip (org-maybe-intangible
5625 (list 'invisible 'org-link
5626 'keymap org-mouse-map 'mouse-face 'highlight
5627 'font-lock-multiline t 'help-echo help
5628 'htmlize-link `(:uri ,hl))))
5629 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5630 'font-lock-multiline t 'help-echo help
5631 'htmlize-link `(:uri ,hl))))
5632 ;; We need to remove the invisible property here. Table narrowing
5633 ;; may have made some of this invisible.
5634 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5635 (remove-text-properties (match-beginning 0) (match-end 0)
5636 '(invisible nil))
5637 (if (match-end 3)
5638 (progn
5639 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5640 (org-rear-nonsticky-at (match-beginning 3))
5641 (add-text-properties (match-beginning 3) (match-end 3) vp)
5642 (org-rear-nonsticky-at (match-end 3))
5643 (add-text-properties (match-end 3) (match-end 0) ip)
5644 (org-rear-nonsticky-at (match-end 0)))
5645 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5646 (org-rear-nonsticky-at (match-beginning 1))
5647 (add-text-properties (match-beginning 1) (match-end 1) vp)
5648 (org-rear-nonsticky-at (match-end 1))
5649 (add-text-properties (match-end 1) (match-end 0) ip)
5650 (org-rear-nonsticky-at (match-end 0)))
5651 t)))
5653 (defun org-activate-dates (limit)
5654 "Run through the buffer and add overlays to dates."
5655 (if (re-search-forward org-tsr-regexp-both limit t)
5656 (progn
5657 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5658 (add-text-properties (match-beginning 0) (match-end 0)
5659 (list 'mouse-face 'highlight
5660 'keymap org-mouse-map))
5661 (org-rear-nonsticky-at (match-end 0))
5662 (when org-display-custom-times
5663 (if (match-end 3)
5664 (org-display-custom-time (match-beginning 3) (match-end 3)))
5665 (org-display-custom-time (match-beginning 1) (match-end 1)))
5666 t)))
5668 (defvar org-target-link-regexp nil
5669 "Regular expression matching radio targets in plain text.")
5670 (make-variable-buffer-local 'org-target-link-regexp)
5671 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5672 "Regular expression matching a link target.")
5673 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5674 "Regular expression matching a radio target.")
5675 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5676 "Regular expression matching any target.")
5678 (defun org-activate-target-links (limit)
5679 "Run through the buffer and add overlays to target matches."
5680 (when org-target-link-regexp
5681 (let ((case-fold-search t))
5682 (if (re-search-forward org-target-link-regexp limit t)
5683 (progn
5684 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5685 (add-text-properties (match-beginning 0) (match-end 0)
5686 (list 'mouse-face 'highlight
5687 'keymap org-mouse-map
5688 'help-echo "Radio target link"
5689 'org-linked-text t))
5690 (org-rear-nonsticky-at (match-end 0))
5691 t)))))
5693 (defun org-update-radio-target-regexp ()
5694 "Find all radio targets in this file and update the regular expression."
5695 (interactive)
5696 (when (memq 'radio org-activate-links)
5697 (setq org-target-link-regexp
5698 (org-make-target-link-regexp (org-all-targets 'radio)))
5699 (org-restart-font-lock)))
5701 (defun org-hide-wide-columns (limit)
5702 (let (s e)
5703 (setq s (text-property-any (point) (or limit (point-max))
5704 'org-cwidth t))
5705 (when s
5706 (setq e (next-single-property-change s 'org-cwidth))
5707 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5708 (goto-char e)
5709 t)))
5711 (defvar org-latex-and-specials-regexp nil
5712 "Regular expression for highlighting export special stuff.")
5713 (defvar org-match-substring-regexp)
5714 (defvar org-match-substring-with-braces-regexp)
5716 ;; This should be with the exporter code, but we also use if for font-locking
5717 (defconst org-export-html-special-string-regexps
5718 '(("\\\\-" . "&shy;")
5719 ("---\\([^-]\\)" . "&mdash;\\1")
5720 ("--\\([^-]\\)" . "&ndash;\\1")
5721 ("\\.\\.\\." . "&hellip;"))
5722 "Regular expressions for special string conversion.")
5725 (defun org-compute-latex-and-specials-regexp ()
5726 "Compute regular expression for stuff treated specially by exporters."
5727 (if (not org-highlight-latex-fragments-and-specials)
5728 (org-set-local 'org-latex-and-specials-regexp nil)
5729 (require 'org-exp)
5730 (let*
5731 ((matchers (plist-get org-format-latex-options :matchers))
5732 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5733 org-latex-regexps)))
5734 (org-export-allow-BIND nil)
5735 (options (org-combine-plists (org-default-export-plist)
5736 (org-infile-export-plist)))
5737 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5738 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5739 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5740 (org-export-html-expand (plist-get options :expand-quoted-html))
5741 (org-export-with-special-strings (plist-get options :special-strings))
5742 (re-sub
5743 (cond
5744 ((equal org-export-with-sub-superscripts '{})
5745 (list org-match-substring-with-braces-regexp))
5746 (org-export-with-sub-superscripts
5747 (list org-match-substring-regexp))))
5748 (re-latex
5749 (if org-export-with-LaTeX-fragments
5750 (mapcar (lambda (x) (nth 1 x)) latexs)))
5751 (re-macros
5752 (if org-export-with-TeX-macros
5753 (list (concat "\\\\"
5754 (regexp-opt
5755 (append
5757 (delq nil
5758 (mapcar 'car-safe
5759 (append org-entities-user
5760 org-entities)))
5761 (if (boundp 'org-latex-entities)
5762 (mapcar (lambda (x)
5763 (or (car-safe x) x))
5764 org-latex-entities)
5765 nil))
5766 'words))) ; FIXME
5768 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5769 (re-special (if org-export-with-special-strings
5770 (mapcar (lambda (x) (car x))
5771 org-export-html-special-string-regexps)))
5772 (re-rest
5773 (delq nil
5774 (list
5775 (if org-export-html-expand "@<[^>\n]+>")
5776 ))))
5777 (org-set-local
5778 'org-latex-and-specials-regexp
5779 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5780 re-rest) "\\|")))))
5782 (defun org-do-latex-and-special-faces (limit)
5783 "Run through the buffer and add overlays to links."
5784 (when org-latex-and-specials-regexp
5785 (let (rtn d)
5786 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5787 limit t))
5788 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5789 'face))
5790 '(org-code org-verbatim underline)))
5791 (progn
5792 (setq rtn t
5793 d (cond ((member (char-after (1+ (match-beginning 0)))
5794 '(?_ ?^)) 1)
5795 (t 0)))
5796 (font-lock-prepend-text-property
5797 (+ d (match-beginning 0)) (match-end 0)
5798 'face 'org-latex-and-export-specials)
5799 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5800 '(font-lock-multiline t)))))
5801 rtn)))
5803 (defun org-restart-font-lock ()
5804 "Restart `font-lock-mode', to force refontification."
5805 (when (and (boundp 'font-lock-mode) font-lock-mode)
5806 (font-lock-mode -1)
5807 (font-lock-mode 1)))
5809 (defun org-all-targets (&optional radio)
5810 "Return a list of all targets in this file.
5811 When optional argument RADIO is non-nil, only find radio
5812 targets."
5813 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5814 (save-excursion
5815 (goto-char (point-min))
5816 (while (re-search-forward re nil t)
5817 ;; Make sure point is really within the object.
5818 (backward-char)
5819 (let ((obj (org-element-context)))
5820 (when (memq (org-element-type obj) '(radio-target target))
5821 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5822 rtn)))
5824 (defun org-make-target-link-regexp (targets)
5825 "Make regular expression matching all strings in TARGETS.
5826 The regular expression finds the targets also if there is a line break
5827 between words."
5828 (and targets
5829 (concat
5830 "\\<\\("
5831 (mapconcat
5832 (lambda (x)
5833 (setq x (regexp-quote x))
5834 (while (string-match " +" x)
5835 (setq x (replace-match "\\s-+" t t x)))
5837 targets
5838 "\\|")
5839 "\\)\\>")))
5841 (defun org-activate-tags (limit)
5842 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5843 (progn
5844 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5845 (add-text-properties (match-beginning 1) (match-end 1)
5846 (list 'mouse-face 'highlight
5847 'keymap org-mouse-map))
5848 (org-rear-nonsticky-at (match-end 1))
5849 t)))
5851 (defun org-outline-level ()
5852 "Compute the outline level of the heading at point.
5853 If this is called at a normal headline, the level is the number of stars.
5854 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5855 (save-excursion
5856 (if (not (condition-case nil
5857 (org-back-to-heading t)
5858 (error nil)))
5860 (looking-at org-outline-regexp)
5861 (1- (- (match-end 0) (match-beginning 0))))))
5863 (defvar org-font-lock-keywords nil)
5865 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5866 "Regular expression matching a property line.")
5868 (defvar org-font-lock-hook nil
5869 "Functions to be called for special font lock stuff.")
5871 (defvar org-font-lock-set-keywords-hook nil
5872 "Functions that can manipulate `org-font-lock-extra-keywords'.
5873 This is called after `org-font-lock-extra-keywords' is defined, but before
5874 it is installed to be used by font lock. This can be useful if something
5875 needs to be inserted at a specific position in the font-lock sequence.")
5877 (defun org-font-lock-hook (limit)
5878 "Run `org-font-lock-hook' within LIMIT."
5879 (run-hook-with-args 'org-font-lock-hook limit))
5881 (defun org-set-font-lock-defaults ()
5882 "Set font lock defaults for the current buffer."
5883 (let* ((em org-fontify-emphasized-text)
5884 (lk org-activate-links)
5885 (org-font-lock-extra-keywords
5886 (list
5887 ;; Call the hook
5888 '(org-font-lock-hook)
5889 ;; Headlines
5890 `(,(if org-fontify-whole-heading-line
5891 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5892 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5893 (1 (org-get-level-face 1))
5894 (2 (org-get-level-face 2))
5895 (3 (org-get-level-face 3)))
5896 ;; Table lines
5897 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5898 (1 'org-table t))
5899 ;; Table internals
5900 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5901 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5902 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5903 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5904 ;; Drawers
5905 (list org-drawer-regexp '(0 'org-special-keyword t))
5906 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5907 ;; Properties
5908 (list org-property-re
5909 '(1 'org-special-keyword t)
5910 '(3 'org-property-value t))
5911 ;; Links
5912 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5913 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5914 (if (memq 'plain lk) '(org-activate-plain-links))
5915 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5916 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5917 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5918 (if (memq 'footnote lk) '(org-activate-footnote-links))
5919 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5920 '(org-hide-wide-columns (0 nil append))
5921 ;; TODO keyword
5922 (list (format org-heading-keyword-regexp-format
5923 org-todo-regexp)
5924 '(2 (org-get-todo-face 2) t))
5925 ;; DONE
5926 (if org-fontify-done-headline
5927 (list (format org-heading-keyword-regexp-format
5928 (concat
5929 "\\(?:"
5930 (mapconcat 'regexp-quote org-done-keywords "\\|")
5931 "\\)"))
5932 '(2 'org-headline-done t))
5933 nil)
5934 ;; Priorities
5935 '(org-font-lock-add-priority-faces)
5936 ;; Tags
5937 '(org-font-lock-add-tag-faces)
5938 ;; Special keywords
5939 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5940 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5941 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5942 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5943 ;; Emphasis
5944 (if em
5945 (if (featurep 'xemacs)
5946 '(org-do-emphasis-faces (0 nil append))
5947 '(org-do-emphasis-faces)))
5948 ;; Checkboxes
5949 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5950 1 'org-checkbox prepend)
5951 (if (cdr (assq 'checkbox org-list-automatic-rules))
5952 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5953 (0 (org-get-checkbox-statistics-face) t)))
5954 ;; Description list items
5955 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5956 1 'org-list-dt prepend)
5957 ;; ARCHIVEd headings
5958 (list (concat
5959 org-outline-regexp-bol
5960 "\\(.*:" org-archive-tag ":.*\\)")
5961 '(1 'org-archived prepend))
5962 ;; Specials
5963 '(org-do-latex-and-special-faces)
5964 '(org-fontify-entities)
5965 '(org-raise-scripts)
5966 ;; Code
5967 '(org-activate-code (1 'org-code t))
5968 ;; COMMENT
5969 (list (format org-heading-keyword-regexp-format
5970 (concat "\\("
5971 org-comment-string "\\|" org-quote-string
5972 "\\)"))
5973 '(2 'org-special-keyword t))
5974 ;; Blocks and meta lines
5975 '(org-fontify-meta-lines-and-blocks)
5977 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5978 (run-hooks 'org-font-lock-set-keywords-hook)
5979 ;; Now set the full font-lock-keywords
5980 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5981 (org-set-local 'font-lock-defaults
5982 '(org-font-lock-keywords t nil nil backward-paragraph))
5983 (kill-local-variable 'font-lock-keywords) nil))
5985 (defun org-toggle-pretty-entities ()
5986 "Toggle the composition display of entities as UTF8 characters."
5987 (interactive)
5988 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5989 (org-restart-font-lock)
5990 (if org-pretty-entities
5991 (message "Entities are displayed as UTF8 characters")
5992 (save-restriction
5993 (widen)
5994 (org-decompose-region (point-min) (point-max))
5995 (message "Entities are displayed plain"))))
5997 (defvar org-custom-properties-overlays nil
5998 "List of overlays used for custom properties.")
5999 (make-variable-buffer-local 'org-custom-properties-overlays)
6001 (defun org-toggle-custom-properties-visibility ()
6002 "Display or hide properties in `org-custom-properties'."
6003 (interactive)
6004 (if org-custom-properties-overlays
6005 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6006 (setq org-custom-properties-overlays nil))
6007 (unless (not org-custom-properties)
6008 (save-excursion
6009 (save-restriction
6010 (widen)
6011 (goto-char (point-min))
6012 (while (re-search-forward org-property-re nil t)
6013 (mapc (lambda(p)
6014 (when (equal p (substring (match-string 1) 1 -1))
6015 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6016 (overlay-put o 'invisible t)
6017 (overlay-put o 'org-custom-property t)
6018 (push o org-custom-properties-overlays))))
6019 org-custom-properties)))))))
6021 (defun org-fontify-entities (limit)
6022 "Find an entity to fontify."
6023 (let (ee)
6024 (when org-pretty-entities
6025 (catch 'match
6026 (while (re-search-forward
6027 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6028 limit t)
6029 (if (and (not (org-in-indented-comment-line))
6030 (setq ee (org-entity-get (match-string 1)))
6031 (= (length (nth 6 ee)) 1))
6032 (let*
6033 ((end (if (equal (match-string 2) "{}")
6034 (match-end 2)
6035 (match-end 1))))
6036 (add-text-properties
6037 (match-beginning 0) end
6038 (list 'font-lock-fontified t))
6039 (compose-region (match-beginning 0) end
6040 (nth 6 ee) nil)
6041 (backward-char 1)
6042 (throw 'match t))))
6043 nil))))
6045 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6046 "Fontify string S like in Org-mode."
6047 (with-temp-buffer
6048 (insert s)
6049 (let ((org-odd-levels-only odd-levels))
6050 (org-mode)
6051 (font-lock-fontify-buffer)
6052 (buffer-string))))
6054 (defvar org-m nil)
6055 (defvar org-l nil)
6056 (defvar org-f nil)
6057 (defun org-get-level-face (n)
6058 "Get the right face for match N in font-lock matching of headlines."
6059 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6060 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6061 (if org-cycle-level-faces
6062 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6063 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6064 (cond
6065 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6066 ((eq n 2) org-f)
6067 (t (if org-level-color-stars-only nil org-f))))
6070 (defun org-get-todo-face (kwd)
6071 "Get the right face for a TODO keyword KWD.
6072 If KWD is a number, get the corresponding match group."
6073 (if (numberp kwd) (setq kwd (match-string kwd)))
6074 (or (org-face-from-face-or-color
6075 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6076 (and (member kwd org-done-keywords) 'org-done)
6077 'org-todo))
6079 (defun org-face-from-face-or-color (context inherit face-or-color)
6080 "Create a face list that inherits INHERIT, but sets the foreground color.
6081 When FACE-OR-COLOR is not a string, just return it."
6082 (if (stringp face-or-color)
6083 (list :inherit inherit
6084 (cdr (assoc context org-faces-easy-properties))
6085 face-or-color)
6086 face-or-color))
6088 (defun org-font-lock-add-tag-faces (limit)
6089 "Add the special tag faces."
6090 (when (and org-tag-faces org-tags-special-faces-re)
6091 (while (re-search-forward org-tags-special-faces-re limit t)
6092 (add-text-properties (match-beginning 1) (match-end 1)
6093 (list 'face (org-get-tag-face 1)
6094 'font-lock-fontified t))
6095 (backward-char 1))))
6097 (defun org-font-lock-add-priority-faces (limit)
6098 "Add the special priority faces."
6099 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6100 (when (save-match-data (org-at-heading-p))
6101 (add-text-properties
6102 (match-beginning 0) (match-end 0)
6103 (list 'face (or (org-face-from-face-or-color
6104 'priority 'org-special-keyword
6105 (cdr (assoc (char-after (match-beginning 1))
6106 org-priority-faces)))
6107 'org-special-keyword)
6108 'font-lock-fontified t)))))
6110 (defun org-get-tag-face (kwd)
6111 "Get the right face for a TODO keyword KWD.
6112 If KWD is a number, get the corresponding match group."
6113 (if (numberp kwd) (setq kwd (match-string kwd)))
6114 (or (org-face-from-face-or-color
6115 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6116 'org-tag))
6118 (defun org-unfontify-region (beg end &optional maybe_loudly)
6119 "Remove fontification and activation overlays from links."
6120 (font-lock-default-unfontify-region beg end)
6121 (let* ((buffer-undo-list t)
6122 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6123 (inhibit-modification-hooks t)
6124 deactivate-mark buffer-file-name buffer-file-truename)
6125 (org-decompose-region beg end)
6126 (remove-text-properties beg end
6127 '(mouse-face t keymap t org-linked-text t
6128 invisible t intangible t
6129 org-no-flyspell t org-emphasis t))
6130 (org-remove-font-lock-display-properties beg end)))
6132 (defconst org-script-display '(((raise -0.3) (height 0.7))
6133 ((raise 0.3) (height 0.7))
6134 ((raise -0.5))
6135 ((raise 0.5)))
6136 "Display properties for showing superscripts and subscripts.")
6138 (defun org-remove-font-lock-display-properties (beg end)
6139 "Remove specific display properties that have been added by font lock.
6140 The will remove the raise properties that are used to show superscripts
6141 and subscripts."
6142 (let (next prop)
6143 (while (< beg end)
6144 (setq next (next-single-property-change beg 'display nil end)
6145 prop (get-text-property beg 'display))
6146 (if (member prop org-script-display)
6147 (put-text-property beg next 'display nil))
6148 (setq beg next))))
6150 (defun org-raise-scripts (limit)
6151 "Add raise properties to sub/superscripts."
6152 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6153 (if (re-search-forward
6154 (if (eq org-use-sub-superscripts t)
6155 org-match-substring-regexp
6156 org-match-substring-with-braces-regexp)
6157 limit t)
6158 (let* ((pos (point)) table-p comment-p
6159 (mpos (match-beginning 3))
6160 (emph-p (get-text-property mpos 'org-emphasis))
6161 (link-p (get-text-property mpos 'mouse-face))
6162 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6163 (goto-char (point-at-bol))
6164 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6165 comment-p (org-looking-at-p "[ \t]*#"))
6166 (goto-char pos)
6167 ;; FIXME: Should we go back one character here, for a_b^c
6168 ;; (goto-char (1- pos)) ;????????????????????
6169 (if (or comment-p emph-p link-p keyw-p)
6171 (put-text-property (match-beginning 3) (match-end 0)
6172 'display
6173 (if (equal (char-after (match-beginning 2)) ?^)
6174 (nth (if table-p 3 1) org-script-display)
6175 (nth (if table-p 2 0) org-script-display)))
6176 (add-text-properties (match-beginning 2) (match-end 2)
6177 (list 'invisible t
6178 'org-dwidth t 'org-dwidth-n 1))
6179 (if (and (eq (char-after (match-beginning 3)) ?{)
6180 (eq (char-before (match-end 3)) ?}))
6181 (progn
6182 (add-text-properties
6183 (match-beginning 3) (1+ (match-beginning 3))
6184 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6185 (add-text-properties
6186 (1- (match-end 3)) (match-end 3)
6187 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6188 t)))))
6190 ;;;; Visibility cycling, including org-goto and indirect buffer
6192 ;;; Cycling
6194 (defvar org-cycle-global-status nil)
6195 (make-variable-buffer-local 'org-cycle-global-status)
6196 (defvar org-cycle-subtree-status nil)
6197 (make-variable-buffer-local 'org-cycle-subtree-status)
6199 (defvar org-inlinetask-min-level)
6201 ;;;###autoload
6202 (defun org-cycle (&optional arg)
6203 "TAB-action and visibility cycling for Org-mode.
6205 This is the command invoked in Org-mode by the TAB key. Its main purpose
6206 is outline visibility cycling, but it also invokes other actions
6207 in special contexts.
6209 - When this function is called with a prefix argument, rotate the entire
6210 buffer through 3 states (global cycling)
6211 1. OVERVIEW: Show only top-level headlines.
6212 2. CONTENTS: Show all headlines of all levels, but no body text.
6213 3. SHOW ALL: Show everything.
6214 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6215 determined by the variable `org-startup-folded', and by any VISIBILITY
6216 properties in the buffer.
6217 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6218 including any drawers.
6220 - When inside a table, re-align the table and move to the next field.
6222 - When point is at the beginning of a headline, rotate the subtree started
6223 by this line through 3 different states (local cycling)
6224 1. FOLDED: Only the main headline is shown.
6225 2. CHILDREN: The main headline and the direct children are shown.
6226 From this state, you can move to one of the children
6227 and zoom in further.
6228 3. SUBTREE: Show the entire subtree, including body text.
6229 If there is no subtree, switch directly from CHILDREN to FOLDED.
6231 - When point is at the beginning of an empty headline and the variable
6232 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6233 of the headline by demoting and promoting it to likely levels. This
6234 speeds up creation document structure by pressing TAB once or several
6235 times right after creating a new headline.
6237 - When there is a numeric prefix, go up to a heading with level ARG, do
6238 a `show-subtree' and return to the previous cursor position. If ARG
6239 is negative, go up that many levels.
6241 - When point is not at the beginning of a headline, execute the global
6242 binding for TAB, which is re-indenting the line. See the option
6243 `org-cycle-emulate-tab' for details.
6245 - Special case: if point is at the beginning of the buffer and there is
6246 no headline in line 1, this function will act as if called with prefix arg
6247 (C-u TAB, same as S-TAB) also when called without prefix arg.
6248 But only if also the variable `org-cycle-global-at-bob' is t."
6249 (interactive "P")
6250 (org-load-modules-maybe)
6251 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6252 (and org-cycle-level-after-item/entry-creation
6253 (or (org-cycle-level)
6254 (org-cycle-item-indentation))))
6255 (let* (message-log-max ; Don't populate the *Messages* buffer
6256 (limit-level
6257 (or org-cycle-max-level
6258 (and (boundp 'org-inlinetask-min-level)
6259 org-inlinetask-min-level
6260 (1- org-inlinetask-min-level))))
6261 (nstars (and limit-level
6262 (if org-odd-levels-only
6263 (and limit-level (1- (* limit-level 2)))
6264 limit-level)))
6265 (org-outline-regexp
6266 (if (not (derived-mode-p 'org-mode))
6267 outline-regexp
6268 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6269 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6270 (not (looking-at org-outline-regexp))))
6271 (org-cycle-hook
6272 (if bob-special
6273 (delq 'org-optimize-window-after-visibility-change
6274 (copy-sequence org-cycle-hook))
6275 org-cycle-hook))
6276 (pos (point)))
6278 (if (or bob-special (equal arg '(4)))
6279 ;; special case: use global cycling
6280 (setq arg t))
6282 (cond
6284 ((equal arg '(16))
6285 (setq last-command 'dummy)
6286 (org-set-startup-visibility)
6287 (message "Startup visibility, plus VISIBILITY properties"))
6289 ((equal arg '(64))
6290 (show-all)
6291 (message "Entire buffer visible, including drawers"))
6293 ;; Table: enter it or move to the next field.
6294 ((org-at-table-p 'any)
6295 (if (org-at-table.el-p)
6296 (message "Use C-c ' to edit table.el tables")
6297 (if arg (org-table-edit-field t)
6298 (org-table-justify-field-maybe)
6299 (call-interactively 'org-table-next-field))))
6301 ((run-hook-with-args-until-success
6302 'org-tab-after-check-for-table-hook))
6304 ;; Global cycling: delegate to `org-cycle-internal-global'.
6305 ((eq arg t) (org-cycle-internal-global))
6307 ;; Drawers: delegate to `org-flag-drawer'.
6308 ((and org-drawers org-drawer-regexp
6309 (save-excursion
6310 (beginning-of-line 1)
6311 (looking-at org-drawer-regexp)))
6312 (org-flag-drawer ; toggle block visibility
6313 (not (get-char-property (match-end 0) 'invisible))))
6315 ;; Show-subtree, ARG levels up from here.
6316 ((integerp arg)
6317 (save-excursion
6318 (org-back-to-heading)
6319 (outline-up-heading (if (< arg 0) (- arg)
6320 (- (funcall outline-level) arg)))
6321 (org-show-subtree)))
6323 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6324 ((and (featurep 'org-inlinetask)
6325 (org-inlinetask-at-task-p)
6326 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6327 (org-inlinetask-toggle-visibility))
6329 ((org-try-cdlatex-tab))
6331 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6332 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6333 (save-excursion (beginning-of-line 1)
6334 (looking-at org-outline-regexp)))
6335 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6336 (org-cycle-internal-local))
6338 ;; From there: TAB emulation and template completion.
6339 (buffer-read-only (org-back-to-heading))
6341 ((run-hook-with-args-until-success
6342 'org-tab-after-check-for-cycling-hook))
6344 ((org-try-structure-completion))
6346 ((run-hook-with-args-until-success
6347 'org-tab-before-tab-emulation-hook))
6349 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6350 (or (not (bolp))
6351 (not (looking-at org-outline-regexp))))
6352 (call-interactively (global-key-binding "\t")))
6354 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6355 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6356 (or (and (eq org-cycle-emulate-tab 'white)
6357 (= (match-end 0) (point-at-eol)))
6358 (and (eq org-cycle-emulate-tab 'whitestart)
6359 (>= (match-end 0) pos))))
6361 (eq org-cycle-emulate-tab t))
6362 (call-interactively (global-key-binding "\t")))
6364 (t (save-excursion
6365 (org-back-to-heading)
6366 (org-cycle)))))))
6368 (defun org-cycle-internal-global ()
6369 "Do the global cycling action."
6370 ;; Hack to avoid display of messages for .org attachments in Gnus
6371 (let (message-log-max ; Don't populate the *Messages* buffer
6372 (ga (string-match "\\*fontification" (buffer-name))))
6373 (cond
6374 ((and (eq last-command this-command)
6375 (eq org-cycle-global-status 'overview))
6376 ;; We just created the overview - now do table of contents
6377 ;; This can be slow in very large buffers, so indicate action
6378 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6379 (unless ga (message "CONTENTS..."))
6380 (org-content)
6381 (unless ga (message "CONTENTS...done"))
6382 (setq org-cycle-global-status 'contents)
6383 (run-hook-with-args 'org-cycle-hook 'contents))
6385 ((and (eq last-command this-command)
6386 (eq org-cycle-global-status 'contents))
6387 ;; We just showed the table of contents - now show everything
6388 (run-hook-with-args 'org-pre-cycle-hook 'all)
6389 (show-all)
6390 (unless ga (message "SHOW ALL"))
6391 (setq org-cycle-global-status 'all)
6392 (run-hook-with-args 'org-cycle-hook 'all))
6395 ;; Default action: go to overview
6396 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6397 (org-overview)
6398 (unless ga (message "OVERVIEW"))
6399 (setq org-cycle-global-status 'overview)
6400 (run-hook-with-args 'org-cycle-hook 'overview)))))
6402 (defun org-cycle-internal-local ()
6403 "Do the local cycling action."
6404 (let (message-log-max ; Don't populate the *Messages* buffer
6405 (goal-column 0) eoh eol eos has-children children-skipped struct)
6406 ;; First, determine end of headline (EOH), end of subtree or item
6407 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6408 (save-excursion
6409 (if (org-at-item-p)
6410 (progn
6411 (beginning-of-line)
6412 (setq struct (org-list-struct))
6413 (setq eoh (point-at-eol))
6414 (setq eos (org-list-get-item-end-before-blank (point) struct))
6415 (setq has-children (org-list-has-child-p (point) struct)))
6416 (org-back-to-heading)
6417 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6418 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6419 (setq has-children
6420 (or (save-excursion
6421 (let ((level (funcall outline-level)))
6422 (outline-next-heading)
6423 (and (org-at-heading-p t)
6424 (> (funcall outline-level) level))))
6425 (save-excursion
6426 (org-list-search-forward (org-item-beginning-re) eos t)))))
6427 ;; Determine end invisible part of buffer (EOL)
6428 (beginning-of-line 2)
6429 ;; XEmacs doesn't have `next-single-char-property-change'
6430 (if (featurep 'xemacs)
6431 (while (and (not (eobp)) ;; this is like `next-line'
6432 (get-char-property (1- (point)) 'invisible))
6433 (beginning-of-line 2))
6434 (while (and (not (eobp)) ;; this is like `next-line'
6435 (get-char-property (1- (point)) 'invisible))
6436 (goto-char (next-single-char-property-change (point) 'invisible))
6437 (and (eolp) (beginning-of-line 2))))
6438 (setq eol (point)))
6439 ;; Find out what to do next and set `this-command'
6440 (cond
6441 ((= eos eoh)
6442 ;; Nothing is hidden behind this heading
6443 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6444 (message "EMPTY ENTRY")
6445 (setq org-cycle-subtree-status nil)
6446 (save-excursion
6447 (goto-char eos)
6448 (outline-next-heading)
6449 (if (outline-invisible-p) (org-flag-heading nil))))
6450 ((and (or (>= eol eos)
6451 (not (string-match "\\S-" (buffer-substring eol eos))))
6452 (or has-children
6453 (not (setq children-skipped
6454 org-cycle-skip-children-state-if-no-children))))
6455 ;; Entire subtree is hidden in one line: children view
6456 (run-hook-with-args 'org-pre-cycle-hook 'children)
6457 (if (org-at-item-p)
6458 (org-list-set-item-visibility (point-at-bol) struct 'children)
6459 (org-show-entry)
6460 (org-with-limited-levels (show-children))
6461 ;; FIXME: This slows down the func way too much.
6462 ;; How keep drawers hidden in subtree anyway?
6463 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6464 ;; (org-cycle-hide-drawers 'subtree))
6466 ;; Fold every list in subtree to top-level items.
6467 (when (eq org-cycle-include-plain-lists 'integrate)
6468 (save-excursion
6469 (org-back-to-heading)
6470 (while (org-list-search-forward (org-item-beginning-re) eos t)
6471 (beginning-of-line 1)
6472 (let* ((struct (org-list-struct))
6473 (prevs (org-list-prevs-alist struct))
6474 (end (org-list-get-bottom-point struct)))
6475 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6476 (org-list-get-all-items (point) struct prevs))
6477 (goto-char end))))))
6478 (message "CHILDREN")
6479 (save-excursion
6480 (goto-char eos)
6481 (outline-next-heading)
6482 (if (outline-invisible-p) (org-flag-heading nil)))
6483 (setq org-cycle-subtree-status 'children)
6484 (run-hook-with-args 'org-cycle-hook 'children))
6485 ((or children-skipped
6486 (and (eq last-command this-command)
6487 (eq org-cycle-subtree-status 'children)))
6488 ;; We just showed the children, or no children are there,
6489 ;; now show everything.
6490 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6491 (outline-flag-region eoh eos nil)
6492 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6493 (setq org-cycle-subtree-status 'subtree)
6494 (run-hook-with-args 'org-cycle-hook 'subtree))
6496 ;; Default action: hide the subtree.
6497 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6498 (outline-flag-region eoh eos t)
6499 (message "FOLDED")
6500 (setq org-cycle-subtree-status 'folded)
6501 (run-hook-with-args 'org-cycle-hook 'folded)))))
6503 ;;;###autoload
6504 (defun org-global-cycle (&optional arg)
6505 "Cycle the global visibility. For details see `org-cycle'.
6506 With \\[universal-argument] prefix arg, switch to startup visibility.
6507 With a numeric prefix, show all headlines up to that level."
6508 (interactive "P")
6509 (let ((org-cycle-include-plain-lists
6510 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6511 (cond
6512 ((integerp arg)
6513 (show-all)
6514 (hide-sublevels arg)
6515 (setq org-cycle-global-status 'contents))
6516 ((equal arg '(4))
6517 (org-set-startup-visibility)
6518 (message "Startup visibility, plus VISIBILITY properties."))
6520 (org-cycle '(4))))))
6522 (defun org-set-startup-visibility ()
6523 "Set the visibility required by startup options and properties."
6524 (cond
6525 ((eq org-startup-folded t)
6526 (org-cycle '(4)))
6527 ((eq org-startup-folded 'content)
6528 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6529 (org-cycle '(4)) (org-cycle '(4)))))
6530 (unless (eq org-startup-folded 'showeverything)
6531 (if org-hide-block-startup (org-hide-block-all))
6532 (org-set-visibility-according-to-property 'no-cleanup)
6533 (org-cycle-hide-archived-subtrees 'all)
6534 (org-cycle-hide-drawers 'all)
6535 (org-cycle-show-empty-lines t)))
6537 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6538 "Switch subtree visibilities according to :VISIBILITY: property."
6539 (interactive)
6540 (let (org-show-entry-below state)
6541 (save-excursion
6542 (goto-char (point-min))
6543 (while (re-search-forward
6544 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6545 nil t)
6546 (setq state (match-string 1))
6547 (save-excursion
6548 (org-back-to-heading t)
6549 (hide-subtree)
6550 (org-reveal)
6551 (cond
6552 ((equal state '("fold" "folded"))
6553 (hide-subtree))
6554 ((equal state "children")
6555 (org-show-hidden-entry)
6556 (show-children))
6557 ((equal state "content")
6558 (save-excursion
6559 (save-restriction
6560 (org-narrow-to-subtree)
6561 (org-content))))
6562 ((member state '("all" "showall"))
6563 (show-subtree)))))
6564 (unless no-cleanup
6565 (org-cycle-hide-archived-subtrees 'all)
6566 (org-cycle-hide-drawers 'all)
6567 (org-cycle-show-empty-lines 'all)))))
6569 ;; This function uses outline-regexp instead of the more fundamental
6570 ;; org-outline-regexp so that org-cycle-global works outside of Org
6571 ;; buffers, where outline-regexp is needed.
6572 (defun org-overview ()
6573 "Switch to overview mode, showing only top-level headlines.
6574 Really, this shows all headlines with level equal or greater than the level
6575 of the first headline in the buffer. This is important, because if the
6576 first headline is not level one, then (hide-sublevels 1) gives confusing
6577 results."
6578 (interactive)
6579 (let ((level (save-excursion
6580 (goto-char (point-min))
6581 (if (re-search-forward (concat "^" outline-regexp) nil t)
6582 (progn
6583 (goto-char (match-beginning 0))
6584 (funcall outline-level))))))
6585 (and level (hide-sublevels level))))
6587 (defun org-content (&optional arg)
6588 "Show all headlines in the buffer, like a table of contents.
6589 With numerical argument N, show content up to level N."
6590 (interactive "P")
6591 (save-excursion
6592 ;; Visit all headings and show their offspring
6593 (and (integerp arg) (org-overview))
6594 (goto-char (point-max))
6595 (catch 'exit
6596 (while (and (progn (condition-case nil
6597 (outline-previous-visible-heading 1)
6598 (error (goto-char (point-min))))
6600 (looking-at org-outline-regexp))
6601 (if (integerp arg)
6602 (show-children (1- arg))
6603 (show-branches))
6604 (if (bobp) (throw 'exit nil))))))
6607 (defun org-optimize-window-after-visibility-change (state)
6608 "Adjust the window after a change in outline visibility.
6609 This function is the default value of the hook `org-cycle-hook'."
6610 (when (get-buffer-window (current-buffer))
6611 (cond
6612 ((eq state 'content) nil)
6613 ((eq state 'all) nil)
6614 ((eq state 'folded) nil)
6615 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6616 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6618 (defun org-remove-empty-overlays-at (pos)
6619 "Remove outline overlays that do not contain non-white stuff."
6620 (mapc
6621 (lambda (o)
6622 (and (eq 'outline (overlay-get o 'invisible))
6623 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6624 (overlay-end o))))
6625 (delete-overlay o)))
6626 (overlays-at pos)))
6628 (defun org-clean-visibility-after-subtree-move ()
6629 "Fix visibility issues after moving a subtree."
6630 ;; First, find a reasonable region to look at:
6631 ;; Start two siblings above, end three below
6632 (let* ((beg (save-excursion
6633 (and (org-get-last-sibling)
6634 (org-get-last-sibling))
6635 (point)))
6636 (end (save-excursion
6637 (and (org-get-next-sibling)
6638 (org-get-next-sibling)
6639 (org-get-next-sibling))
6640 (if (org-at-heading-p)
6641 (point-at-eol)
6642 (point))))
6643 (level (looking-at "\\*+"))
6644 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6645 (save-excursion
6646 (save-restriction
6647 (narrow-to-region beg end)
6648 (when re
6649 ;; Properly fold already folded siblings
6650 (goto-char (point-min))
6651 (while (re-search-forward re nil t)
6652 (if (and (not (outline-invisible-p))
6653 (save-excursion
6654 (goto-char (point-at-eol)) (outline-invisible-p)))
6655 (hide-entry))))
6656 (org-cycle-show-empty-lines 'overview)
6657 (org-cycle-hide-drawers 'overview)))))
6659 (defun org-cycle-show-empty-lines (state)
6660 "Show empty lines above all visible headlines.
6661 The region to be covered depends on STATE when called through
6662 `org-cycle-hook'. Lisp program can use t for STATE to get the
6663 entire buffer covered. Note that an empty line is only shown if there
6664 are at least `org-cycle-separator-lines' empty lines before the headline."
6665 (when (not (= org-cycle-separator-lines 0))
6666 (save-excursion
6667 (let* ((n (abs org-cycle-separator-lines))
6668 (re (cond
6669 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6670 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6671 (t (let ((ns (number-to-string (- n 2))))
6672 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6673 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6674 beg end b e)
6675 (cond
6676 ((memq state '(overview contents t))
6677 (setq beg (point-min) end (point-max)))
6678 ((memq state '(children folded))
6679 (setq beg (point) end (progn (org-end-of-subtree t t)
6680 (beginning-of-line 2)
6681 (point)))))
6682 (when beg
6683 (goto-char beg)
6684 (while (re-search-forward re end t)
6685 (unless (get-char-property (match-end 1) 'invisible)
6686 (setq e (match-end 1))
6687 (if (< org-cycle-separator-lines 0)
6688 (setq b (save-excursion
6689 (goto-char (match-beginning 0))
6690 (org-back-over-empty-lines)
6691 (if (save-excursion
6692 (goto-char (max (point-min) (1- (point))))
6693 (org-at-heading-p))
6694 (1- (point))
6695 (point))))
6696 (setq b (match-beginning 1)))
6697 (outline-flag-region b e nil)))))))
6698 ;; Never hide empty lines at the end of the file.
6699 (save-excursion
6700 (goto-char (point-max))
6701 (outline-previous-heading)
6702 (outline-end-of-heading)
6703 (if (and (looking-at "[ \t\n]+")
6704 (= (match-end 0) (point-max)))
6705 (outline-flag-region (point) (match-end 0) nil))))
6707 (defun org-show-empty-lines-in-parent ()
6708 "Move to the parent and re-show empty lines before visible headlines."
6709 (save-excursion
6710 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6711 (org-cycle-show-empty-lines context))))
6713 (defun org-files-list ()
6714 "Return `org-agenda-files' list, plus all open org-mode files.
6715 This is useful for operations that need to scan all of a user's
6716 open and agenda-wise Org files."
6717 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6718 (dolist (buf (buffer-list))
6719 (with-current-buffer buf
6720 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6721 (let ((file (expand-file-name (buffer-file-name))))
6722 (unless (member file files)
6723 (push file files))))))
6724 files))
6726 (defsubst org-entry-beginning-position ()
6727 "Return the beginning position of the current entry."
6728 (save-excursion (outline-back-to-heading t) (point)))
6730 (defsubst org-entry-end-position ()
6731 "Return the end position of the current entry."
6732 (save-excursion (outline-next-heading) (point)))
6734 (defun org-cycle-hide-drawers (state)
6735 "Re-hide all drawers after a visibility state change."
6736 (when (and (derived-mode-p 'org-mode)
6737 (not (memq state '(overview folded contents))))
6738 (save-excursion
6739 (let* ((globalp (memq state '(contents all)))
6740 (beg (if globalp (point-min) (point)))
6741 (end (if globalp (point-max)
6742 (if (eq state 'children)
6743 (save-excursion (outline-next-heading) (point))
6744 (org-end-of-subtree t)))))
6745 (goto-char beg)
6746 (while (re-search-forward org-drawer-regexp end t)
6747 (org-flag-drawer t))))))
6749 (defun org-cycle-hide-inline-tasks (state)
6750 "Re-hide inline task when switching to 'contents visibility state."
6751 (when (and (eq state 'contents)
6752 (boundp 'org-inlinetask-min-level)
6753 org-inlinetask-min-level)
6754 (hide-sublevels (1- org-inlinetask-min-level))))
6756 (defun org-flag-drawer (flag)
6757 "When FLAG is non-nil, hide the drawer we are within.
6758 Otherwise make it visible."
6759 (save-excursion
6760 (beginning-of-line 1)
6761 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6762 (let ((b (match-end 0)))
6763 (if (re-search-forward
6764 "^[ \t]*:END:"
6765 (save-excursion (outline-next-heading) (point)) t)
6766 (outline-flag-region b (point-at-eol) flag)
6767 (error ":END: line missing at position %s" b))))))
6769 (defun org-subtree-end-visible-p ()
6770 "Is the end of the current subtree visible?"
6771 (pos-visible-in-window-p
6772 (save-excursion (org-end-of-subtree t) (point))))
6774 (defun org-first-headline-recenter (&optional N)
6775 "Move cursor to the first headline and recenter the headline.
6776 Optional argument N means put the headline into the Nth line of the window."
6777 (goto-char (point-min))
6778 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6779 (beginning-of-line)
6780 (recenter (prefix-numeric-value N))))
6782 ;;; Saving and restoring visibility
6784 (defun org-outline-overlay-data (&optional use-markers)
6785 "Return a list of the locations of all outline overlays.
6786 These are overlays with the `invisible' property value `outline'.
6787 The return value is a list of cons cells, with start and stop
6788 positions for each overlay.
6789 If USE-MARKERS is set, return the positions as markers."
6790 (let (beg end)
6791 (save-excursion
6792 (save-restriction
6793 (widen)
6794 (delq nil
6795 (mapcar (lambda (o)
6796 (when (eq (overlay-get o 'invisible) 'outline)
6797 (setq beg (overlay-start o)
6798 end (overlay-end o))
6799 (and beg end (> end beg)
6800 (if use-markers
6801 (cons (move-marker (make-marker) beg)
6802 (move-marker (make-marker) end))
6803 (cons beg end)))))
6804 (overlays-in (point-min) (point-max))))))))
6806 (defun org-set-outline-overlay-data (data)
6807 "Create visibility overlays for all positions in DATA.
6808 DATA should have been made by `org-outline-overlay-data'."
6809 (let (o)
6810 (save-excursion
6811 (save-restriction
6812 (widen)
6813 (show-all)
6814 (mapc (lambda (c)
6815 (outline-flag-region (car c) (cdr c) t))
6816 data)))))
6818 ;;; Folding of blocks
6820 (defvar org-hide-block-overlays nil
6821 "Overlays hiding blocks.")
6822 (make-variable-buffer-local 'org-hide-block-overlays)
6824 (defun org-block-map (function &optional start end)
6825 "Call FUNCTION at the head of all source blocks in the current buffer.
6826 Optional arguments START and END can be used to limit the range."
6827 (let ((start (or start (point-min)))
6828 (end (or end (point-max))))
6829 (save-excursion
6830 (goto-char start)
6831 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6832 (save-excursion
6833 (save-match-data
6834 (goto-char (match-beginning 0))
6835 (funcall function)))))))
6837 (defun org-hide-block-toggle-all ()
6838 "Toggle the visibility of all blocks in the current buffer."
6839 (org-block-map #'org-hide-block-toggle))
6841 (defun org-hide-block-all ()
6842 "Fold all blocks in the current buffer."
6843 (interactive)
6844 (org-show-block-all)
6845 (org-block-map #'org-hide-block-toggle-maybe))
6847 (defun org-show-block-all ()
6848 "Unfold all blocks in the current buffer."
6849 (interactive)
6850 (mapc 'delete-overlay org-hide-block-overlays)
6851 (setq org-hide-block-overlays nil))
6853 (defun org-hide-block-toggle-maybe ()
6854 "Toggle visibility of block at point."
6855 (interactive)
6856 (let ((case-fold-search t))
6857 (if (save-excursion
6858 (beginning-of-line 1)
6859 (looking-at org-block-regexp))
6860 (progn (org-hide-block-toggle)
6861 t) ;; to signal that we took action
6862 nil))) ;; to signal that we did not
6864 (defun org-hide-block-toggle (&optional force)
6865 "Toggle the visibility of the current block."
6866 (interactive)
6867 (save-excursion
6868 (beginning-of-line)
6869 (if (re-search-forward org-block-regexp nil t)
6870 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6871 (end (match-end 0)) ;; end of entire body
6873 (if (memq t (mapcar (lambda (overlay)
6874 (eq (overlay-get overlay 'invisible)
6875 'org-hide-block))
6876 (overlays-at start)))
6877 (if (or (not force) (eq force 'off))
6878 (mapc (lambda (ov)
6879 (when (member ov org-hide-block-overlays)
6880 (setq org-hide-block-overlays
6881 (delq ov org-hide-block-overlays)))
6882 (when (eq (overlay-get ov 'invisible)
6883 'org-hide-block)
6884 (delete-overlay ov)))
6885 (overlays-at start)))
6886 (setq ov (make-overlay start end))
6887 (overlay-put ov 'invisible 'org-hide-block)
6888 ;; make the block accessible to isearch
6889 (overlay-put
6890 ov 'isearch-open-invisible
6891 (lambda (ov)
6892 (when (member ov org-hide-block-overlays)
6893 (setq org-hide-block-overlays
6894 (delq ov org-hide-block-overlays)))
6895 (when (eq (overlay-get ov 'invisible)
6896 'org-hide-block)
6897 (delete-overlay ov))))
6898 (push ov org-hide-block-overlays)))
6899 (error "Not looking at a source block"))))
6901 ;; org-tab-after-check-for-cycling-hook
6902 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6903 ;; Remove overlays when changing major mode
6904 (add-hook 'org-mode-hook
6905 (lambda () (org-add-hook 'change-major-mode-hook
6906 'org-show-block-all 'append 'local)))
6908 ;;; Org-goto
6910 (defvar org-goto-window-configuration nil)
6911 (defvar org-goto-marker nil)
6912 (defvar org-goto-map
6913 (let ((map (make-sparse-keymap)))
6914 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6915 (while (setq cmd (pop cmds))
6916 (substitute-key-definition cmd cmd map global-map)))
6917 (suppress-keymap map)
6918 (org-defkey map "\C-m" 'org-goto-ret)
6919 (org-defkey map [(return)] 'org-goto-ret)
6920 (org-defkey map [(left)] 'org-goto-left)
6921 (org-defkey map [(right)] 'org-goto-right)
6922 (org-defkey map [(control ?g)] 'org-goto-quit)
6923 (org-defkey map "\C-i" 'org-cycle)
6924 (org-defkey map [(tab)] 'org-cycle)
6925 (org-defkey map [(down)] 'outline-next-visible-heading)
6926 (org-defkey map [(up)] 'outline-previous-visible-heading)
6927 (if org-goto-auto-isearch
6928 (if (fboundp 'define-key-after)
6929 (define-key-after map [t] 'org-goto-local-auto-isearch)
6930 nil)
6931 (org-defkey map "q" 'org-goto-quit)
6932 (org-defkey map "n" 'outline-next-visible-heading)
6933 (org-defkey map "p" 'outline-previous-visible-heading)
6934 (org-defkey map "f" 'outline-forward-same-level)
6935 (org-defkey map "b" 'outline-backward-same-level)
6936 (org-defkey map "u" 'outline-up-heading))
6937 (org-defkey map "/" 'org-occur)
6938 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6939 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6940 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6941 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6942 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6943 map))
6945 (defconst org-goto-help
6946 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6947 RET=jump to location [Q]uit and return to previous location
6948 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6950 (defvar org-goto-start-pos) ; dynamically scoped parameter
6952 ;; FIXME: Docstring does not mention both interfaces
6953 (defun org-goto (&optional alternative-interface)
6954 "Look up a different location in the current file, keeping current visibility.
6956 When you want look-up or go to a different location in a
6957 document, the fastest way is often to fold the entire buffer and
6958 then dive into the tree. This method has the disadvantage, that
6959 the previous location will be folded, which may not be what you
6960 want.
6962 This command works around this by showing a copy of the current
6963 buffer in an indirect buffer, in overview mode. You can dive
6964 into the tree in that copy, use org-occur and incremental search
6965 to find a location. When pressing RET or `Q', the command
6966 returns to the original buffer in which the visibility is still
6967 unchanged. After RET it will also jump to the location selected
6968 in the indirect buffer and expose the headline hierarchy above.
6970 With a prefix argument, use the alternative interface: e.g. if
6971 `org-goto-interface' is 'outline use 'outline-path-completion."
6972 (interactive "P")
6973 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6974 (org-refile-use-outline-path t)
6975 (org-refile-target-verify-function nil)
6976 (interface
6977 (if (not alternative-interface)
6978 org-goto-interface
6979 (if (eq org-goto-interface 'outline)
6980 'outline-path-completion
6981 'outline)))
6982 (org-goto-start-pos (point))
6983 (selected-point
6984 (if (eq interface 'outline)
6985 (car (org-get-location (current-buffer) org-goto-help))
6986 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6987 (org-refile-check-position pa)
6988 (nth 3 pa)))))
6989 (if selected-point
6990 (progn
6991 (org-mark-ring-push org-goto-start-pos)
6992 (goto-char selected-point)
6993 (if (or (outline-invisible-p) (org-invisible-p2))
6994 (org-show-context 'org-goto)))
6995 (message "Quit"))))
6997 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6998 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6999 (defvar org-goto-local-auto-isearch-map) ; defined below
7001 (defun org-get-location (buf help)
7002 "Let the user select a location in the Org-mode buffer BUF.
7003 This function uses a recursive edit. It returns the selected position
7004 or nil."
7005 (org-no-popups
7006 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7007 (isearch-hide-immediately nil)
7008 (isearch-search-fun-function
7009 (lambda () 'org-goto-local-search-headings))
7010 (org-goto-selected-point org-goto-exit-command))
7011 (save-excursion
7012 (save-window-excursion
7013 (delete-other-windows)
7014 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7015 (org-pop-to-buffer-same-window
7016 (condition-case nil
7017 (make-indirect-buffer (current-buffer) "*org-goto*")
7018 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7019 (with-output-to-temp-buffer "*Help*"
7020 (princ help))
7021 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7022 (setq buffer-read-only nil)
7023 (let ((org-startup-truncated t)
7024 (org-startup-folded nil)
7025 (org-startup-align-all-tables nil))
7026 (org-mode)
7027 (org-overview))
7028 (setq buffer-read-only t)
7029 (if (and (boundp 'org-goto-start-pos)
7030 (integer-or-marker-p org-goto-start-pos))
7031 (let ((org-show-hierarchy-above t)
7032 (org-show-siblings t)
7033 (org-show-following-heading t))
7034 (goto-char org-goto-start-pos)
7035 (and (outline-invisible-p) (org-show-context)))
7036 (goto-char (point-min)))
7037 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7038 (message "Select location and press RET")
7039 (use-local-map org-goto-map)
7040 (recursive-edit)
7042 (kill-buffer "*org-goto*")
7043 (cons org-goto-selected-point org-goto-exit-command))))
7045 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7046 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7047 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7048 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7050 (defun org-goto-local-search-headings (string bound noerror)
7051 "Search and make sure that any matches are in headlines."
7052 (catch 'return
7053 (while (if isearch-forward
7054 (search-forward string bound noerror)
7055 (search-backward string bound noerror))
7056 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7057 (and (member :headline context)
7058 (not (member :tags context))))
7059 (throw 'return (point))))))
7061 (defun org-goto-local-auto-isearch ()
7062 "Start isearch."
7063 (interactive)
7064 (goto-char (point-min))
7065 (let ((keys (this-command-keys)))
7066 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7067 (isearch-mode t)
7068 (isearch-process-search-char (string-to-char keys)))))
7070 (defun org-goto-ret (&optional arg)
7071 "Finish `org-goto' by going to the new location."
7072 (interactive "P")
7073 (setq org-goto-selected-point (point)
7074 org-goto-exit-command 'return)
7075 (throw 'exit nil))
7077 (defun org-goto-left ()
7078 "Finish `org-goto' by going to the new location."
7079 (interactive)
7080 (if (org-at-heading-p)
7081 (progn
7082 (beginning-of-line 1)
7083 (setq org-goto-selected-point (point)
7084 org-goto-exit-command 'left)
7085 (throw 'exit nil))
7086 (error "Not on a heading")))
7088 (defun org-goto-right ()
7089 "Finish `org-goto' by going to the new location."
7090 (interactive)
7091 (if (org-at-heading-p)
7092 (progn
7093 (setq org-goto-selected-point (point)
7094 org-goto-exit-command 'right)
7095 (throw 'exit nil))
7096 (error "Not on a heading")))
7098 (defun org-goto-quit ()
7099 "Finish `org-goto' without cursor motion."
7100 (interactive)
7101 (setq org-goto-selected-point nil)
7102 (setq org-goto-exit-command 'quit)
7103 (throw 'exit nil))
7105 ;;; Indirect buffer display of subtrees
7107 (defvar org-indirect-dedicated-frame nil
7108 "This is the frame being used for indirect tree display.")
7109 (defvar org-last-indirect-buffer nil)
7111 (defun org-tree-to-indirect-buffer (&optional arg)
7112 "Create indirect buffer and narrow it to current subtree.
7113 With a numerical prefix ARG, go up to this level and then take that tree.
7114 If ARG is negative, go up that many levels.
7116 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7117 indirect buffer previously made with this command, to avoid proliferation of
7118 indirect buffers. However, when you call the command with a \
7119 \\[universal-argument] prefix, or
7120 when `org-indirect-buffer-display' is `new-frame', the last buffer
7121 is kept so that you can work with several indirect buffers at the same time.
7122 If `org-indirect-buffer-display' is `dedicated-frame', the \
7123 \\[universal-argument] prefix also
7124 requests that a new frame be made for the new buffer, so that the dedicated
7125 frame is not changed."
7126 (interactive "P")
7127 (let ((cbuf (current-buffer))
7128 (cwin (selected-window))
7129 (pos (point))
7130 beg end level heading ibuf)
7131 (save-excursion
7132 (org-back-to-heading t)
7133 (when (numberp arg)
7134 (setq level (org-outline-level))
7135 (if (< arg 0) (setq arg (+ level arg)))
7136 (while (> (setq level (org-outline-level)) arg)
7137 (org-up-heading-safe)))
7138 (setq beg (point)
7139 heading (org-get-heading))
7140 (org-end-of-subtree t t)
7141 (if (org-at-heading-p) (backward-char 1))
7142 (setq end (point)))
7143 (if (and (buffer-live-p org-last-indirect-buffer)
7144 (not (eq org-indirect-buffer-display 'new-frame))
7145 (not arg))
7146 (kill-buffer org-last-indirect-buffer))
7147 (setq ibuf (org-get-indirect-buffer cbuf)
7148 org-last-indirect-buffer ibuf)
7149 (cond
7150 ((or (eq org-indirect-buffer-display 'new-frame)
7151 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7152 (select-frame (make-frame))
7153 (delete-other-windows)
7154 (org-pop-to-buffer-same-window ibuf)
7155 (org-set-frame-title heading))
7156 ((eq org-indirect-buffer-display 'dedicated-frame)
7157 (raise-frame
7158 (select-frame (or (and org-indirect-dedicated-frame
7159 (frame-live-p org-indirect-dedicated-frame)
7160 org-indirect-dedicated-frame)
7161 (setq org-indirect-dedicated-frame (make-frame)))))
7162 (delete-other-windows)
7163 (org-pop-to-buffer-same-window ibuf)
7164 (org-set-frame-title (concat "Indirect: " heading)))
7165 ((eq org-indirect-buffer-display 'current-window)
7166 (org-pop-to-buffer-same-window ibuf))
7167 ((eq org-indirect-buffer-display 'other-window)
7168 (pop-to-buffer ibuf))
7169 (t (error "Invalid value")))
7170 (if (featurep 'xemacs)
7171 (save-excursion (org-mode) (turn-on-font-lock)))
7172 (narrow-to-region beg end)
7173 (show-all)
7174 (goto-char pos)
7175 (run-hook-with-args 'org-cycle-hook 'all)
7176 (and (window-live-p cwin) (select-window cwin))))
7178 (defun org-get-indirect-buffer (&optional buffer)
7179 (setq buffer (or buffer (current-buffer)))
7180 (let ((n 1) (base (buffer-name buffer)) bname)
7181 (while (buffer-live-p
7182 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7183 (setq n (1+ n)))
7184 (condition-case nil
7185 (make-indirect-buffer buffer bname 'clone)
7186 (error (make-indirect-buffer buffer bname)))))
7188 (defun org-set-frame-title (title)
7189 "Set the title of the current frame to the string TITLE."
7190 ;; FIXME: how to name a single frame in XEmacs???
7191 (unless (featurep 'xemacs)
7192 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7194 ;;;; Structure editing
7196 ;;; Inserting headlines
7198 (defun org-previous-line-empty-p ()
7199 (save-excursion
7200 (and (not (bobp))
7201 (or (beginning-of-line 0) t)
7202 (save-match-data
7203 (looking-at "[ \t]*$")))))
7205 (defun org-insert-heading (&optional force-heading invisible-ok)
7206 "Insert a new heading or item with same depth at point.
7207 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7208 If point is at the beginning of a headline, insert a sibling before the
7209 current headline. If point is not at the beginning, split the line,
7210 create the new headline with the text in the current line after point
7211 \(but see also the variable `org-M-RET-may-split-line').
7213 With a double prefix arg, force the heading to be inserted at the
7214 end of the parent subtree.
7216 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7217 This is important for non-interactive uses of the command."
7218 (interactive "P")
7219 (if (or (= (buffer-size) 0)
7220 (and (not (save-excursion
7221 (and (ignore-errors (org-back-to-heading invisible-ok))
7222 (org-at-heading-p))))
7223 (or force-heading (not (org-in-item-p)))))
7224 (progn
7225 (insert "\n* ")
7226 (run-hooks 'org-insert-heading-hook))
7227 (when (or force-heading (not (org-insert-item)))
7228 (let* ((empty-line-p nil)
7229 (level nil)
7230 (on-heading (org-at-heading-p))
7231 (head (save-excursion
7232 (condition-case nil
7233 (progn
7234 (org-back-to-heading invisible-ok)
7235 (when (and (not on-heading)
7236 (featurep 'org-inlinetask)
7237 (integerp org-inlinetask-min-level)
7238 (>= (length (match-string 0))
7239 org-inlinetask-min-level))
7240 ;; Find a heading level before the inline task
7241 (while (and (setq level (org-up-heading-safe))
7242 (>= level org-inlinetask-min-level)))
7243 (if (org-at-heading-p)
7244 (org-back-to-heading invisible-ok)
7245 (error "This should not happen")))
7246 (setq empty-line-p (org-previous-line-empty-p))
7247 (match-string 0))
7248 (error "*"))))
7249 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7250 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7251 pos hide-previous previous-pos)
7252 (cond
7253 ((and (org-at-heading-p) (bolp)
7254 (or (bobp)
7255 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7256 ;; insert before the current line
7257 (open-line (if blank 2 1)))
7258 ((and (bolp)
7259 (not org-insert-heading-respect-content)
7260 (or (bobp)
7261 (save-excursion
7262 (backward-char 1) (not (outline-invisible-p)))))
7263 ;; insert right here
7264 nil)
7266 ;; somewhere in the line
7267 (save-excursion
7268 (setq previous-pos (point-at-bol))
7269 (end-of-line)
7270 (setq hide-previous (outline-invisible-p)))
7271 (and org-insert-heading-respect-content (org-show-subtree))
7272 (let ((split
7273 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7274 (save-excursion
7275 (let ((p (point)))
7276 (goto-char (point-at-bol))
7277 (and (looking-at org-complex-heading-regexp)
7278 (match-beginning 4)
7279 (> p (match-beginning 4)))))))
7280 tags pos)
7281 (cond
7282 (org-insert-heading-respect-content
7283 (if (not (equal force-heading '(16)))
7284 (org-end-of-subtree nil t)
7285 (org-up-heading-safe)
7286 (org-end-of-subtree nil t))
7287 (when (featurep 'org-inlinetask)
7288 (while (and (not (eobp))
7289 (looking-at "\\(\\*+\\)[ \t]+")
7290 (>= (length (match-string 1))
7291 org-inlinetask-min-level))
7292 (org-end-of-subtree nil t)))
7293 (or (bolp) (newline))
7294 (or (org-previous-line-empty-p)
7295 (and blank (newline)))
7296 (open-line 1))
7297 ((org-at-heading-p)
7298 (when hide-previous
7299 (show-children)
7300 (org-show-entry))
7301 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7302 (setq tags (and (match-end 2) (match-string 2)))
7303 (and (match-end 1)
7304 (delete-region (match-beginning 1) (match-end 1)))
7305 (setq pos (point-at-bol))
7306 (or split (end-of-line 1))
7307 (delete-horizontal-space)
7308 (if (string-match "\\`\\*+\\'"
7309 (buffer-substring (point-at-bol) (point)))
7310 (insert " "))
7311 (newline (if blank 2 1))
7312 (when tags
7313 (save-excursion
7314 (goto-char pos)
7315 (end-of-line 1)
7316 (insert " " tags)
7317 (org-set-tags nil 'align))))
7319 (or split (end-of-line 1))
7320 (newline (if blank 2 1)))))))
7321 (insert head) (just-one-space)
7322 (setq pos (point))
7323 (end-of-line 1)
7324 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7325 (when (and org-insert-heading-respect-content hide-previous)
7326 (save-excursion
7327 (goto-char previous-pos)
7328 (hide-subtree)))
7329 (run-hooks 'org-insert-heading-hook)))))
7331 (defun org-get-heading (&optional no-tags no-todo)
7332 "Return the heading of the current entry, without the stars.
7333 When NO-TAGS is non-nil, don't include tags.
7334 When NO-TODO is non-nil, don't include TODO keywords."
7335 (save-excursion
7336 (org-back-to-heading t)
7337 (cond
7338 ((and no-tags no-todo)
7339 (looking-at org-complex-heading-regexp)
7340 (match-string 4))
7341 (no-tags
7342 (looking-at (concat org-outline-regexp
7343 "\\(.*?\\)"
7344 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7345 (match-string 1))
7346 (no-todo
7347 (looking-at org-todo-line-regexp)
7348 (match-string 3))
7349 (t (looking-at org-heading-regexp)
7350 (match-string 2)))))
7352 (defun org-heading-components ()
7353 "Return the components of the current heading.
7354 This is a list with the following elements:
7355 - the level as an integer
7356 - the reduced level, different if `org-odd-levels-only' is set.
7357 - the TODO keyword, or nil
7358 - the priority character, like ?A, or nil if no priority is given
7359 - the headline text itself, or the tags string if no headline text
7360 - the tags string, or nil."
7361 (save-excursion
7362 (org-back-to-heading t)
7363 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7364 (list (length (match-string 1))
7365 (org-reduced-level (length (match-string 1)))
7366 (org-match-string-no-properties 2)
7367 (and (match-end 3) (aref (match-string 3) 2))
7368 (org-match-string-no-properties 4)
7369 (org-match-string-no-properties 5)))))
7371 (defun org-get-entry ()
7372 "Get the entry text, after heading, entire subtree."
7373 (save-excursion
7374 (org-back-to-heading t)
7375 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7377 (defun org-insert-heading-after-current ()
7378 "Insert a new heading with same level as current, after current subtree."
7379 (interactive)
7380 (org-back-to-heading)
7381 (org-insert-heading)
7382 (org-move-subtree-down)
7383 (end-of-line 1))
7385 (defun org-insert-heading-respect-content ()
7386 (interactive)
7387 (let ((org-insert-heading-respect-content t))
7388 (org-insert-heading t)))
7390 (defun org-insert-todo-heading-respect-content (&optional force-state)
7391 (interactive "P")
7392 (let ((org-insert-heading-respect-content t))
7393 (org-insert-todo-heading force-state t)))
7395 (defun org-insert-todo-heading (arg &optional force-heading)
7396 "Insert a new heading with the same level and TODO state as current heading.
7397 If the heading has no TODO state, or if the state is DONE, use the first
7398 state (TODO by default). Also one prefix arg, force first state. With two
7399 prefix args, force inserting at the end of the parent subtree."
7400 (interactive "P")
7401 (when (or force-heading (not (org-insert-item 'checkbox)))
7402 (org-insert-heading (or (and (equal arg '(16)) '(16))
7403 force-heading))
7404 (save-excursion
7405 (org-back-to-heading)
7406 (outline-previous-heading)
7407 (looking-at org-todo-line-regexp))
7408 (let*
7409 ((new-mark-x
7410 (if (or arg
7411 (not (match-beginning 2))
7412 (member (match-string 2) org-done-keywords))
7413 (car org-todo-keywords-1)
7414 (match-string 2)))
7415 (new-mark
7417 (run-hook-with-args-until-success
7418 'org-todo-get-default-hook new-mark-x nil)
7419 new-mark-x)))
7420 (beginning-of-line 1)
7421 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7422 (if org-treat-insert-todo-heading-as-state-change
7423 (org-todo new-mark)
7424 (insert new-mark " "))))
7425 (when org-provide-todo-statistics
7426 (org-update-parent-todo-statistics))))
7428 (defun org-insert-subheading (arg)
7429 "Insert a new subheading and demote it.
7430 Works for outline headings and for plain lists alike."
7431 (interactive "P")
7432 (org-insert-heading arg)
7433 (cond
7434 ((org-at-heading-p) (org-do-demote))
7435 ((org-at-item-p) (org-indent-item))))
7437 (defun org-insert-todo-subheading (arg)
7438 "Insert a new subheading with TODO keyword or checkbox and demote it.
7439 Works for outline headings and for plain lists alike."
7440 (interactive "P")
7441 (org-insert-todo-heading arg)
7442 (cond
7443 ((org-at-heading-p) (org-do-demote))
7444 ((org-at-item-p) (org-indent-item))))
7446 ;;; Promotion and Demotion
7448 (defvar org-after-demote-entry-hook nil
7449 "Hook run after an entry has been demoted.
7450 The cursor will be at the beginning of the entry.
7451 When a subtree is being demoted, the hook will be called for each node.")
7453 (defvar org-after-promote-entry-hook nil
7454 "Hook run after an entry has been promoted.
7455 The cursor will be at the beginning of the entry.
7456 When a subtree is being promoted, the hook will be called for each node.")
7458 (defun org-promote-subtree ()
7459 "Promote the entire subtree.
7460 See also `org-promote'."
7461 (interactive)
7462 (save-excursion
7463 (org-with-limited-levels (org-map-tree 'org-promote)))
7464 (org-fix-position-after-promote))
7466 (defun org-demote-subtree ()
7467 "Demote the entire subtree. See `org-demote'.
7468 See also `org-promote'."
7469 (interactive)
7470 (save-excursion
7471 (org-with-limited-levels (org-map-tree 'org-demote)))
7472 (org-fix-position-after-promote))
7475 (defun org-do-promote ()
7476 "Promote the current heading higher up the tree.
7477 If the region is active in `transient-mark-mode', promote all headings
7478 in the region."
7479 (interactive)
7480 (save-excursion
7481 (if (org-region-active-p)
7482 (org-map-region 'org-promote (region-beginning) (region-end))
7483 (org-promote)))
7484 (org-fix-position-after-promote))
7486 (defun org-do-demote ()
7487 "Demote the current heading lower down the tree.
7488 If the region is active in `transient-mark-mode', demote all headings
7489 in the region."
7490 (interactive)
7491 (save-excursion
7492 (if (org-region-active-p)
7493 (org-map-region 'org-demote (region-beginning) (region-end))
7494 (org-demote)))
7495 (org-fix-position-after-promote))
7497 (defun org-fix-position-after-promote ()
7498 "Make sure that after pro/demotion cursor position is right."
7499 (let ((pos (point)))
7500 (when (save-excursion
7501 (beginning-of-line 1)
7502 (looking-at org-todo-line-regexp)
7503 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7504 (cond ((eobp) (insert " "))
7505 ((eolp) (insert " "))
7506 ((equal (char-after) ?\ ) (forward-char 1))))))
7508 (defun org-current-level ()
7509 "Return the level of the current entry, or nil if before the first headline.
7510 The level is the number of stars at the beginning of the headline."
7511 (save-excursion
7512 (org-with-limited-levels
7513 (if (ignore-errors (org-back-to-heading t))
7514 (funcall outline-level)))))
7516 (defun org-get-previous-line-level ()
7517 "Return the outline depth of the last headline before the current line.
7518 Returns 0 for the first headline in the buffer, and nil if before the
7519 first headline."
7520 (let ((current-level (org-current-level))
7521 (prev-level (when (> (line-number-at-pos) 1)
7522 (save-excursion
7523 (beginning-of-line 0)
7524 (org-current-level)))))
7525 (cond ((null current-level) nil) ; Before first headline
7526 ((null prev-level) 0) ; At first headline
7527 (prev-level))))
7529 (defun org-reduced-level (l)
7530 "Compute the effective level of a heading.
7531 This takes into account the setting of `org-odd-levels-only'."
7532 (cond
7533 ((zerop l) 0)
7534 (org-odd-levels-only (1+ (floor (/ l 2))))
7535 (t l)))
7537 (defun org-level-increment ()
7538 "Return the number of stars that will be added or removed at a
7539 time to headlines when structure editing, based on the value of
7540 `org-odd-levels-only'."
7541 (if org-odd-levels-only 2 1))
7543 (defun org-get-valid-level (level &optional change)
7544 "Rectify a level change under the influence of `org-odd-levels-only'
7545 LEVEL is a current level, CHANGE is by how much the level should be
7546 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7547 even level numbers will become the next higher odd number."
7548 (if org-odd-levels-only
7549 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7550 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7551 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7552 (max 1 (+ level (or change 0)))))
7554 (if (boundp 'define-obsolete-function-alias)
7555 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7556 (define-obsolete-function-alias 'org-get-legal-level
7557 'org-get-valid-level)
7558 (define-obsolete-function-alias 'org-get-legal-level
7559 'org-get-valid-level "23.1")))
7561 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7562 ;; ̀org-with-limited-levels'
7563 (defun org-promote ()
7564 "Promote the current heading higher up the tree.
7565 If the region is active in `transient-mark-mode', promote all headings
7566 in the region."
7567 (org-back-to-heading t)
7568 (let* ((level (save-match-data (funcall outline-level)))
7569 (after-change-functions (remove 'flyspell-after-change-function
7570 after-change-functions))
7571 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7572 (diff (abs (- level (length up-head) -1))))
7573 (cond ((and (= level 1) org-called-with-limited-levels
7574 org-allow-promoting-top-level-subtree)
7575 (replace-match "# " nil t))
7576 ((= level 1)
7577 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7578 (t (replace-match up-head nil t)))
7579 ;; Fixup tag positioning
7580 (unless (= level 1)
7581 (and org-auto-align-tags (org-set-tags nil t))
7582 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7583 (run-hooks 'org-after-promote-entry-hook)))
7585 (defun org-demote ()
7586 "Demote the current heading lower down the tree.
7587 If the region is active in `transient-mark-mode', demote all headings
7588 in the region."
7589 (org-back-to-heading t)
7590 (let* ((level (save-match-data (funcall outline-level)))
7591 (after-change-functions (remove 'flyspell-after-change-function
7592 after-change-functions))
7593 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7594 (diff (abs (- level (length down-head) -1))))
7595 (replace-match down-head nil t)
7596 ;; Fixup tag positioning
7597 (and org-auto-align-tags (org-set-tags nil t))
7598 (if org-adapt-indentation (org-fixup-indentation diff))
7599 (run-hooks 'org-after-demote-entry-hook)))
7601 (defun org-cycle-level ()
7602 "Cycle the level of an empty headline through possible states.
7603 This goes first to child, then to parent, level, then up the hierarchy.
7604 After top level, it switches back to sibling level."
7605 (interactive)
7606 (let ((org-adapt-indentation nil))
7607 (when (org-point-at-end-of-empty-headline)
7608 (setq this-command 'org-cycle-level) ; Only needed for caching
7609 (let ((cur-level (org-current-level))
7610 (prev-level (org-get-previous-line-level)))
7611 (cond
7612 ;; If first headline in file, promote to top-level.
7613 ((= prev-level 0)
7614 (loop repeat (/ (- cur-level 1) (org-level-increment))
7615 do (org-do-promote)))
7616 ;; If same level as prev, demote one.
7617 ((= prev-level cur-level)
7618 (org-do-demote))
7619 ;; If parent is top-level, promote to top level if not already.
7620 ((= prev-level 1)
7621 (loop repeat (/ (- cur-level 1) (org-level-increment))
7622 do (org-do-promote)))
7623 ;; If top-level, return to prev-level.
7624 ((= cur-level 1)
7625 (loop repeat (/ (- prev-level 1) (org-level-increment))
7626 do (org-do-demote)))
7627 ;; If less than prev-level, promote one.
7628 ((< cur-level prev-level)
7629 (org-do-promote))
7630 ;; If deeper than prev-level, promote until higher than
7631 ;; prev-level.
7632 ((> cur-level prev-level)
7633 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7634 do (org-do-promote))))
7635 t))))
7637 (defun org-map-tree (fun)
7638 "Call FUN for every heading underneath the current one."
7639 (org-back-to-heading)
7640 (let ((level (funcall outline-level)))
7641 (save-excursion
7642 (funcall fun)
7643 (while (and (progn
7644 (outline-next-heading)
7645 (> (funcall outline-level) level))
7646 (not (eobp)))
7647 (funcall fun)))))
7649 (defun org-map-region (fun beg end)
7650 "Call FUN for every heading between BEG and END."
7651 (let ((org-ignore-region t))
7652 (save-excursion
7653 (setq end (copy-marker end))
7654 (goto-char beg)
7655 (if (and (re-search-forward org-outline-regexp-bol nil t)
7656 (< (point) end))
7657 (funcall fun))
7658 (while (and (progn
7659 (outline-next-heading)
7660 (< (point) end))
7661 (not (eobp)))
7662 (funcall fun)))))
7664 (defvar org-property-end-re) ; silence byte-compiler
7665 (defun org-fixup-indentation (diff)
7666 "Change the indentation in the current entry by DIFF.
7667 However, if any line in the current entry has no indentation, or if it
7668 would end up with no indentation after the change, nothing at all is done."
7669 (save-excursion
7670 (let ((end (save-excursion (outline-next-heading)
7671 (point-marker)))
7672 (prohibit (if (> diff 0)
7673 "^\\S-"
7674 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7675 col)
7676 (unless (save-excursion (end-of-line 1)
7677 (re-search-forward prohibit end t))
7678 (while (and (< (point) end)
7679 (re-search-forward "^[ \t]+" end t))
7680 (goto-char (match-end 0))
7681 (setq col (current-column))
7682 (if (< diff 0) (replace-match ""))
7683 (org-indent-to-column (+ diff col))))
7684 (move-marker end nil))))
7686 (defun org-convert-to-odd-levels ()
7687 "Convert an org-mode file with all levels allowed to one with odd levels.
7688 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7689 level 5 etc."
7690 (interactive)
7691 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7692 (let ((outline-level 'org-outline-level)
7693 (org-odd-levels-only nil) n)
7694 (save-excursion
7695 (goto-char (point-min))
7696 (while (re-search-forward "^\\*\\*+ " nil t)
7697 (setq n (- (length (match-string 0)) 2))
7698 (while (>= (setq n (1- n)) 0)
7699 (org-demote))
7700 (end-of-line 1))))))
7702 (defun org-convert-to-oddeven-levels ()
7703 "Convert an org-mode file with only odd levels to one with odd/even levels.
7704 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7705 file contains a section with an even level, conversion would
7706 destroy the structure of the file. An error is signaled in this
7707 case."
7708 (interactive)
7709 (goto-char (point-min))
7710 ;; First check if there are no even levels
7711 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7712 (org-show-context t)
7713 (error "Not all levels are odd in this file. Conversion not possible"))
7714 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7715 (let ((outline-regexp org-outline-regexp)
7716 (outline-level 'org-outline-level)
7717 (org-odd-levels-only nil) n)
7718 (save-excursion
7719 (goto-char (point-min))
7720 (while (re-search-forward "^\\*\\*+ " nil t)
7721 (setq n (/ (1- (length (match-string 0))) 2))
7722 (while (>= (setq n (1- n)) 0)
7723 (org-promote))
7724 (end-of-line 1))))))
7726 (defun org-tr-level (n)
7727 "Make N odd if required."
7728 (if org-odd-levels-only (1+ (/ n 2)) n))
7730 ;;; Vertical tree motion, cutting and pasting of subtrees
7732 (defun org-move-subtree-up (&optional arg)
7733 "Move the current subtree up past ARG headlines of the same level."
7734 (interactive "p")
7735 (org-move-subtree-down (- (prefix-numeric-value arg))))
7737 (defun org-move-subtree-down (&optional arg)
7738 "Move the current subtree down past ARG headlines of the same level."
7739 (interactive "p")
7740 (setq arg (prefix-numeric-value arg))
7741 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7742 'org-get-last-sibling))
7743 (ins-point (make-marker))
7744 (cnt (abs arg))
7745 (col (current-column))
7746 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7747 ;; Select the tree
7748 (org-back-to-heading)
7749 (setq beg0 (point))
7750 (save-excursion
7751 (setq ne-beg (org-back-over-empty-lines))
7752 (setq beg (point)))
7753 (save-match-data
7754 (save-excursion (outline-end-of-heading)
7755 (setq folded (outline-invisible-p)))
7756 (outline-end-of-subtree))
7757 (outline-next-heading)
7758 (setq ne-end (org-back-over-empty-lines))
7759 (setq end (point))
7760 (goto-char beg0)
7761 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7762 ;; include less whitespace
7763 (save-excursion
7764 (goto-char beg)
7765 (forward-line (- ne-beg ne-end))
7766 (setq beg (point))))
7767 ;; Find insertion point, with error handling
7768 (while (> cnt 0)
7769 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7770 (progn (goto-char beg0)
7771 (error "Cannot move past superior level or buffer limit")))
7772 (setq cnt (1- cnt)))
7773 (if (> arg 0)
7774 ;; Moving forward - still need to move over subtree
7775 (progn (org-end-of-subtree t t)
7776 (save-excursion
7777 (org-back-over-empty-lines)
7778 (or (bolp) (newline)))))
7779 (setq ne-ins (org-back-over-empty-lines))
7780 (move-marker ins-point (point))
7781 (setq txt (buffer-substring beg end))
7782 (org-save-markers-in-region beg end)
7783 (delete-region beg end)
7784 (org-remove-empty-overlays-at beg)
7785 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7786 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7787 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7788 (let ((bbb (point)))
7789 (insert-before-markers txt)
7790 (org-reinstall-markers-in-region bbb)
7791 (move-marker ins-point bbb))
7792 (or (bolp) (insert "\n"))
7793 (setq ins-end (point))
7794 (goto-char ins-point)
7795 (org-skip-whitespace)
7796 (when (and (< arg 0)
7797 (org-first-sibling-p)
7798 (> ne-ins ne-beg))
7799 ;; Move whitespace back to beginning
7800 (save-excursion
7801 (goto-char ins-end)
7802 (let ((kill-whole-line t))
7803 (kill-line (- ne-ins ne-beg)) (point)))
7804 (insert (make-string (- ne-ins ne-beg) ?\n)))
7805 (move-marker ins-point nil)
7806 (if folded
7807 (hide-subtree)
7808 (org-show-entry)
7809 (show-children)
7810 (org-cycle-hide-drawers 'children))
7811 (org-clean-visibility-after-subtree-move)
7812 ;; move back to the initial column we were at
7813 (move-to-column col)))
7815 (defvar org-subtree-clip ""
7816 "Clipboard for cut and paste of subtrees.
7817 This is actually only a copy of the kill, because we use the normal kill
7818 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7820 (defvar org-subtree-clip-folded nil
7821 "Was the last copied subtree folded?
7822 This is used to fold the tree back after pasting.")
7824 (defun org-cut-subtree (&optional n)
7825 "Cut the current subtree into the clipboard.
7826 With prefix arg N, cut this many sequential subtrees.
7827 This is a short-hand for marking the subtree and then cutting it."
7828 (interactive "p")
7829 (org-copy-subtree n 'cut))
7831 (defun org-copy-subtree (&optional n cut force-store-markers)
7832 "Cut the current subtree into the clipboard.
7833 With prefix arg N, cut this many sequential subtrees.
7834 This is a short-hand for marking the subtree and then copying it.
7835 If CUT is non-nil, actually cut the subtree.
7836 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7837 of some markers in the region, even if CUT is non-nil. This is
7838 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7839 (interactive "p")
7840 (let (beg end folded (beg0 (point)))
7841 (if (org-called-interactively-p 'any)
7842 (org-back-to-heading nil) ; take what looks like a subtree
7843 (org-back-to-heading t)) ; take what is really there
7844 (setq beg (point))
7845 (skip-chars-forward " \t\r\n")
7846 (save-match-data
7847 (save-excursion (outline-end-of-heading)
7848 (setq folded (outline-invisible-p)))
7849 (condition-case nil
7850 (org-forward-heading-same-level (1- n) t)
7851 (error nil))
7852 (org-end-of-subtree t t))
7853 (setq end (point))
7854 (goto-char beg0)
7855 (when (> end beg)
7856 (setq org-subtree-clip-folded folded)
7857 (when (or cut force-store-markers)
7858 (org-save-markers-in-region beg end))
7859 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7860 (setq org-subtree-clip (current-kill 0))
7861 (message "%s: Subtree(s) with %d characters"
7862 (if cut "Cut" "Copied")
7863 (length org-subtree-clip)))))
7865 (defun org-paste-subtree (&optional level tree for-yank)
7866 "Paste the clipboard as a subtree, with modification of headline level.
7867 The entire subtree is promoted or demoted in order to match a new headline
7868 level.
7870 If the cursor is at the beginning of a headline, the same level as
7871 that headline is used to paste the tree
7873 If not, the new level is derived from the *visible* headings
7874 before and after the insertion point, and taken to be the inferior headline
7875 level of the two. So if the previous visible heading is level 3 and the
7876 next is level 4 (or vice versa), level 4 will be used for insertion.
7877 This makes sure that the subtree remains an independent subtree and does
7878 not swallow low level entries.
7880 You can also force a different level, either by using a numeric prefix
7881 argument, or by inserting the heading marker by hand. For example, if the
7882 cursor is after \"*****\", then the tree will be shifted to level 5.
7884 If optional TREE is given, use this text instead of the kill ring.
7886 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7887 move back over whitespace before inserting, and move point to the end of
7888 the inserted text when done."
7889 (interactive "P")
7890 (setq tree (or tree (and kill-ring (current-kill 0))))
7891 (unless (org-kill-is-subtree-p tree)
7892 (error "%s"
7893 (substitute-command-keys
7894 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7895 (org-with-limited-levels
7896 (let* ((visp (not (outline-invisible-p)))
7897 (txt tree)
7898 (^re_ "\\(\\*+\\)[ \t]*")
7899 (old-level (if (string-match org-outline-regexp-bol txt)
7900 (- (match-end 0) (match-beginning 0) 1)
7901 -1))
7902 (force-level (cond (level (prefix-numeric-value level))
7903 ((and (looking-at "[ \t]*$")
7904 (string-match
7905 "^\\*+$" (buffer-substring
7906 (point-at-bol) (point))))
7907 (- (match-end 1) (match-beginning 1)))
7908 ((and (bolp)
7909 (looking-at org-outline-regexp))
7910 (- (match-end 0) (point) 1))))
7911 (previous-level (save-excursion
7912 (condition-case nil
7913 (progn
7914 (outline-previous-visible-heading 1)
7915 (if (looking-at ^re_)
7916 (- (match-end 0) (match-beginning 0) 1)
7918 (error 1))))
7919 (next-level (save-excursion
7920 (condition-case nil
7921 (progn
7922 (or (looking-at org-outline-regexp)
7923 (outline-next-visible-heading 1))
7924 (if (looking-at ^re_)
7925 (- (match-end 0) (match-beginning 0) 1)
7927 (error 1))))
7928 (new-level (or force-level (max previous-level next-level)))
7929 (shift (if (or (= old-level -1)
7930 (= new-level -1)
7931 (= old-level new-level))
7933 (- new-level old-level)))
7934 (delta (if (> shift 0) -1 1))
7935 (func (if (> shift 0) 'org-demote 'org-promote))
7936 (org-odd-levels-only nil)
7937 beg end newend)
7938 ;; Remove the forced level indicator
7939 (if force-level
7940 (delete-region (point-at-bol) (point)))
7941 ;; Paste
7942 (beginning-of-line (if (bolp) 1 2))
7943 (setq beg (point))
7944 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7945 (insert-before-markers txt)
7946 (unless (string-match "\n\\'" txt) (insert "\n"))
7947 (setq newend (point))
7948 (org-reinstall-markers-in-region beg)
7949 (setq end (point))
7950 (goto-char beg)
7951 (skip-chars-forward " \t\n\r")
7952 (setq beg (point))
7953 (if (and (outline-invisible-p) visp)
7954 (save-excursion (outline-show-heading)))
7955 ;; Shift if necessary
7956 (unless (= shift 0)
7957 (save-restriction
7958 (narrow-to-region beg end)
7959 (while (not (= shift 0))
7960 (org-map-region func (point-min) (point-max))
7961 (setq shift (+ delta shift)))
7962 (goto-char (point-min))
7963 (setq newend (point-max))))
7964 (when (or (org-called-interactively-p 'interactive) for-yank)
7965 (message "Clipboard pasted as level %d subtree" new-level))
7966 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7967 kill-ring
7968 (eq org-subtree-clip (current-kill 0))
7969 org-subtree-clip-folded)
7970 ;; The tree was folded before it was killed/copied
7971 (hide-subtree))
7972 (and for-yank (goto-char newend)))))
7974 (defun org-kill-is-subtree-p (&optional txt)
7975 "Check if the current kill is an outline subtree, or a set of trees.
7976 Returns nil if kill does not start with a headline, or if the first
7977 headline level is not the largest headline level in the tree.
7978 So this will actually accept several entries of equal levels as well,
7979 which is OK for `org-paste-subtree'.
7980 If optional TXT is given, check this string instead of the current kill."
7981 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7982 (re (org-get-limited-outline-regexp))
7983 (^re (concat "^" re))
7984 (start-level (and kill
7985 (string-match
7986 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7987 kill)
7988 (- (match-end 2) (match-beginning 2) 1)))
7989 (start (1+ (or (match-beginning 2) -1))))
7990 (if (not start-level)
7991 (progn
7992 nil) ;; does not even start with a heading
7993 (catch 'exit
7994 (while (setq start (string-match ^re kill (1+ start)))
7995 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7996 (throw 'exit nil)))
7997 t))))
7999 (defvar org-markers-to-move nil
8000 "Markers that should be moved with a cut-and-paste operation.
8001 Those markers are stored together with their positions relative to
8002 the start of the region.")
8004 (defun org-save-markers-in-region (beg end)
8005 "Check markers in region.
8006 If these markers are between BEG and END, record their position relative
8007 to BEG, so that after moving the block of text, we can put the markers back
8008 into place.
8009 This function gets called just before an entry or tree gets cut from the
8010 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8011 called immediately, to move the markers with the entries."
8012 (setq org-markers-to-move nil)
8013 (when (featurep 'org-clock)
8014 (org-clock-save-markers-for-cut-and-paste beg end))
8015 (when (featurep 'org-agenda)
8016 (org-agenda-save-markers-for-cut-and-paste beg end)))
8018 (defun org-check-and-save-marker (marker beg end)
8019 "Check if MARKER is between BEG and END.
8020 If yes, remember the marker and the distance to BEG."
8021 (when (and (marker-buffer marker)
8022 (equal (marker-buffer marker) (current-buffer)))
8023 (if (and (>= marker beg) (< marker end))
8024 (push (cons marker (- marker beg)) org-markers-to-move))))
8026 (defun org-reinstall-markers-in-region (beg)
8027 "Move all remembered markers to their position relative to BEG."
8028 (mapc (lambda (x)
8029 (move-marker (car x) (+ beg (cdr x))))
8030 org-markers-to-move)
8031 (setq org-markers-to-move nil))
8033 (defun org-narrow-to-subtree ()
8034 "Narrow buffer to the current subtree."
8035 (interactive)
8036 (save-excursion
8037 (save-match-data
8038 (org-with-limited-levels
8039 (narrow-to-region
8040 (progn (org-back-to-heading t) (point))
8041 (progn (org-end-of-subtree t t)
8042 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8043 (point)))))))
8045 (defun org-narrow-to-block ()
8046 "Narrow buffer to the current block."
8047 (interactive)
8048 (let* ((case-fold-search t)
8049 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8050 "^[ \t]*#\\+end_.*")))
8051 (if blockp
8052 (narrow-to-region (car blockp) (cdr blockp))
8053 (error "Not in a block"))))
8055 (eval-when-compile
8056 (defvar org-property-drawer-re))
8058 (defvar org-property-start-re) ;; defined below
8059 (defun org-clone-subtree-with-time-shift (n &optional shift)
8060 "Clone the task (subtree) at point N times.
8061 The clones will be inserted as siblings.
8063 In interactive use, the user will be prompted for the number of
8064 clones to be produced, and for a time SHIFT, which may be a
8065 repeater as used in time stamps, for example `+3d'.
8067 When a valid repeater is given and the entry contains any time
8068 stamps, the clones will become a sequence in time, with time
8069 stamps in the subtree shifted for each clone produced. If SHIFT
8070 is nil or the empty string, time stamps will be left alone. The
8071 ID property of the original subtree is removed.
8073 If the original subtree did contain time stamps with a repeater,
8074 the following will happen:
8075 - the repeater will be removed in each clone
8076 - an additional clone will be produced, with the current, unshifted
8077 date(s) in the entry.
8078 - the original entry will be placed *after* all the clones, with
8079 repeater intact.
8080 - the start days in the repeater in the original entry will be shifted
8081 to past the last clone.
8082 In this way you can spell out a number of instances of a repeating task,
8083 and still retain the repeater to cover future instances of the task."
8084 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8085 (let (beg end template task idprop
8086 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8087 (drawer-re org-drawer-regexp))
8088 (if (not (and (integerp n) (> n 0)))
8089 (error "Invalid number of replications %s" n))
8090 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8091 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8092 shift)))
8093 (error "Invalid shift specification %s" shift))
8094 (when doshift
8095 (setq shift-n (string-to-number (match-string 1 shift))
8096 shift-what (cdr (assoc (match-string 2 shift)
8097 '(("d" . day) ("w" . week)
8098 ("m" . month) ("y" . year))))))
8099 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8100 (setq nmin 1 nmax n)
8101 (org-back-to-heading t)
8102 (setq beg (point))
8103 (setq idprop (org-entry-get nil "ID"))
8104 (org-end-of-subtree t t)
8105 (or (bolp) (insert "\n"))
8106 (setq end (point))
8107 (setq template (buffer-substring beg end))
8108 (when (and doshift
8109 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8110 (delete-region beg end)
8111 (setq end beg)
8112 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8113 (goto-char end)
8114 (loop for n from nmin to nmax do
8115 ;; prepare clone
8116 (with-temp-buffer
8117 (insert template)
8118 (org-mode)
8119 (goto-char (point-min))
8120 (org-show-subtree)
8121 (and idprop (if org-clone-delete-id
8122 (org-entry-delete nil "ID")
8123 (org-id-get-create t)))
8124 (unless (= n 0)
8125 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8126 (kill-whole-line))
8127 (goto-char (point-min))
8128 (while (re-search-forward drawer-re nil t)
8129 (mapc (lambda (d)
8130 (org-remove-empty-drawer-at d (point))) org-drawers)))
8131 (goto-char (point-min))
8132 (when doshift
8133 (while (re-search-forward org-ts-regexp-both nil t)
8134 (org-timestamp-change (* n shift-n) shift-what))
8135 (unless (= n n-no-remove)
8136 (goto-char (point-min))
8137 (while (re-search-forward org-ts-regexp nil t)
8138 (save-excursion
8139 (goto-char (match-beginning 0))
8140 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8141 (delete-region (match-beginning 1) (match-end 1)))))))
8142 (setq task (buffer-string)))
8143 (insert task))
8144 (goto-char beg)))
8146 ;;; Outline Sorting
8148 (defun org-sort (with-case)
8149 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8150 Optional argument WITH-CASE means sort case-sensitively."
8151 (interactive "P")
8152 (cond
8153 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8154 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8156 (org-call-with-arg 'org-sort-entries with-case))))
8158 (defun org-sort-remove-invisible (s)
8159 (remove-text-properties 0 (length s) org-rm-props s)
8160 (while (string-match org-bracket-link-regexp s)
8161 (setq s (replace-match (if (match-end 2)
8162 (match-string 3 s)
8163 (match-string 1 s)) t t s)))
8166 (defvar org-priority-regexp) ; defined later in the file
8168 (defvar org-after-sorting-entries-or-items-hook nil
8169 "Hook that is run after a bunch of entries or items have been sorted.
8170 When children are sorted, the cursor is in the parent line when this
8171 hook gets called. When a region or a plain list is sorted, the cursor
8172 will be in the first entry of the sorted region/list.")
8174 (defun org-sort-entries
8175 (&optional with-case sorting-type getkey-func compare-func property)
8176 "Sort entries on a certain level of an outline tree.
8177 If there is an active region, the entries in the region are sorted.
8178 Else, if the cursor is before the first entry, sort the top-level items.
8179 Else, the children of the entry at point are sorted.
8181 Sorting can be alphabetically, numerically, by date/time as given by
8182 a time stamp, by a property or by priority.
8184 The command prompts for the sorting type unless it has been given to the
8185 function through the SORTING-TYPE argument, which needs to be a character,
8186 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8187 precise meaning of each character:
8189 n Numerically, by converting the beginning of the entry/item to a number.
8190 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8191 o By order of TODO keywords.
8192 t By date/time, either the first active time stamp in the entry, or, if
8193 none exist, by the first inactive one.
8194 s By the scheduled date/time.
8195 d By deadline date/time.
8196 c By creation time, which is assumed to be the first inactive time stamp
8197 at the beginning of a line.
8198 p By priority according to the cookie.
8199 r By the value of a property.
8201 Capital letters will reverse the sort order.
8203 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8204 called with point at the beginning of the record. It must return either
8205 a string or a number that should serve as the sorting key for that record.
8207 Comparing entries ignores case by default. However, with an optional argument
8208 WITH-CASE, the sorting considers case as well."
8209 (interactive "P")
8210 (let ((case-func (if with-case 'identity 'downcase))
8211 (cmstr
8212 ;; The clock marker is lost when using `sort-subr', let's
8213 ;; store the clocking string.
8214 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8215 (save-excursion
8216 (goto-char org-clock-marker)
8217 (looking-back "^.*") (match-string-no-properties 0))))
8218 start beg end stars re re2
8219 txt what tmp)
8220 ;; Find beginning and end of region to sort
8221 (cond
8222 ((org-region-active-p)
8223 ;; we will sort the region
8224 (setq end (region-end)
8225 what "region")
8226 (goto-char (region-beginning))
8227 (if (not (org-at-heading-p)) (outline-next-heading))
8228 (setq start (point)))
8229 ((or (org-at-heading-p)
8230 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8231 ;; we will sort the children of the current headline
8232 (org-back-to-heading)
8233 (setq start (point)
8234 end (progn (org-end-of-subtree t t)
8235 (or (bolp) (insert "\n"))
8236 (org-back-over-empty-lines)
8237 (point))
8238 what "children")
8239 (goto-char start)
8240 (show-subtree)
8241 (outline-next-heading))
8243 ;; we will sort the top-level entries in this file
8244 (goto-char (point-min))
8245 (or (org-at-heading-p) (outline-next-heading))
8246 (setq start (point))
8247 (goto-char (point-max))
8248 (beginning-of-line 1)
8249 (when (looking-at ".*?\\S-")
8250 ;; File ends in a non-white line
8251 (end-of-line 1)
8252 (insert "\n"))
8253 (setq end (point-max))
8254 (setq what "top-level")
8255 (goto-char start)
8256 (show-all)))
8258 (setq beg (point))
8259 (if (>= beg end) (error "Nothing to sort"))
8261 (looking-at "\\(\\*+\\)")
8262 (setq stars (match-string 1)
8263 re (concat "^" (regexp-quote stars) " +")
8264 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8265 txt (buffer-substring beg end))
8266 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8267 (if (and (not (equal stars "*")) (string-match re2 txt))
8268 (error "Region to sort contains a level above the first entry"))
8270 (unless sorting-type
8271 (message
8272 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8273 [t]ime [s]cheduled [d]eadline [c]reated
8274 A/N/P/R/O/F/T/S/D/C means reversed:"
8275 what)
8276 (setq sorting-type (read-char-exclusive))
8278 (unless getkey-func
8279 (and (= (downcase sorting-type) ?f)
8280 (setq getkey-func
8281 (org-icompleting-read "Sort using function: "
8282 obarray 'fboundp t nil nil))
8283 (setq getkey-func (intern getkey-func))))
8285 (and (= (downcase sorting-type) ?r)
8286 (not property)
8287 (setq property
8288 (org-icompleting-read "Property: "
8289 (mapcar 'list (org-buffer-property-keys t))
8290 nil t))))
8292 (message "Sorting entries...")
8294 (save-restriction
8295 (narrow-to-region start end)
8296 (let ((dcst (downcase sorting-type))
8297 (case-fold-search nil)
8298 (now (current-time)))
8299 (sort-subr
8300 (/= dcst sorting-type)
8301 ;; This function moves to the beginning character of the "record" to
8302 ;; be sorted.
8303 (lambda nil
8304 (if (re-search-forward re nil t)
8305 (goto-char (match-beginning 0))
8306 (goto-char (point-max))))
8307 ;; This function moves to the last character of the "record" being
8308 ;; sorted.
8309 (lambda nil
8310 (save-match-data
8311 (condition-case nil
8312 (outline-forward-same-level 1)
8313 (error
8314 (goto-char (point-max))))))
8315 ;; This function returns the value that gets sorted against.
8316 (lambda nil
8317 (cond
8318 ((= dcst ?n)
8319 (if (looking-at org-complex-heading-regexp)
8320 (string-to-number (match-string 4))
8321 nil))
8322 ((= dcst ?a)
8323 (if (looking-at org-complex-heading-regexp)
8324 (funcall case-func (match-string 4))
8325 nil))
8326 ((= dcst ?t)
8327 (let ((end (save-excursion (outline-next-heading) (point))))
8328 (if (or (re-search-forward org-ts-regexp end t)
8329 (re-search-forward org-ts-regexp-both end t))
8330 (org-time-string-to-seconds (match-string 0))
8331 (org-float-time now))))
8332 ((= dcst ?c)
8333 (let ((end (save-excursion (outline-next-heading) (point))))
8334 (if (re-search-forward
8335 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8336 end t)
8337 (org-time-string-to-seconds (match-string 0))
8338 (org-float-time now))))
8339 ((= dcst ?s)
8340 (let ((end (save-excursion (outline-next-heading) (point))))
8341 (if (re-search-forward org-scheduled-time-regexp end t)
8342 (org-time-string-to-seconds (match-string 1))
8343 (org-float-time now))))
8344 ((= dcst ?d)
8345 (let ((end (save-excursion (outline-next-heading) (point))))
8346 (if (re-search-forward org-deadline-time-regexp end t)
8347 (org-time-string-to-seconds (match-string 1))
8348 (org-float-time now))))
8349 ((= dcst ?p)
8350 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8351 (string-to-char (match-string 2))
8352 org-default-priority))
8353 ((= dcst ?r)
8354 (or (org-entry-get nil property) ""))
8355 ((= dcst ?o)
8356 (if (looking-at org-complex-heading-regexp)
8357 (- 9999 (length (member (match-string 2)
8358 org-todo-keywords-1)))))
8359 ((= dcst ?f)
8360 (if getkey-func
8361 (progn
8362 (setq tmp (funcall getkey-func))
8363 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8364 tmp)
8365 (error "Invalid key function `%s'" getkey-func)))
8366 (t (error "Invalid sorting type `%c'" sorting-type))))
8368 (cond
8369 ((= dcst ?a) 'string<)
8370 ((= dcst ?f) compare-func)
8371 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8372 (run-hooks 'org-after-sorting-entries-or-items-hook)
8373 ;; Reset the clock marker if needed
8374 (when cmstr
8375 (save-excursion
8376 (goto-char start)
8377 (search-forward cmstr nil t)
8378 (move-marker org-clock-marker (point))))
8379 (message "Sorting entries...done")))
8381 (defun org-do-sort (table what &optional with-case sorting-type)
8382 "Sort TABLE of WHAT according to SORTING-TYPE.
8383 The user will be prompted for the SORTING-TYPE if the call to this
8384 function does not specify it. WHAT is only for the prompt, to indicate
8385 what is being sorted. The sorting key will be extracted from
8386 the car of the elements of the table.
8387 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8388 (unless sorting-type
8389 (message
8390 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8391 what)
8392 (setq sorting-type (read-char-exclusive)))
8393 (let ((dcst (downcase sorting-type))
8394 extractfun comparefun)
8395 ;; Define the appropriate functions
8396 (cond
8397 ((= dcst ?n)
8398 (setq extractfun 'string-to-number
8399 comparefun (if (= dcst sorting-type) '< '>)))
8400 ((= dcst ?a)
8401 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8402 (lambda(x) (downcase (org-sort-remove-invisible x))))
8403 comparefun (if (= dcst sorting-type)
8404 'string<
8405 (lambda (a b) (and (not (string< a b))
8406 (not (string= a b)))))))
8407 ((= dcst ?t)
8408 (setq extractfun
8409 (lambda (x)
8410 (if (or (string-match org-ts-regexp x)
8411 (string-match org-ts-regexp-both x))
8412 (org-float-time
8413 (org-time-string-to-time (match-string 0 x)))
8415 comparefun (if (= dcst sorting-type) '< '>)))
8416 (t (error "Invalid sorting type `%c'" sorting-type)))
8418 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8419 table)
8420 (lambda (a b) (funcall comparefun (car a) (car b))))))
8423 ;;; The orgstruct minor mode
8425 ;; Define a minor mode which can be used in other modes in order to
8426 ;; integrate the org-mode structure editing commands.
8428 ;; This is really a hack, because the org-mode structure commands use
8429 ;; keys which normally belong to the major mode. Here is how it
8430 ;; works: The minor mode defines all the keys necessary to operate the
8431 ;; structure commands, but wraps the commands into a function which
8432 ;; tests if the cursor is currently at a headline or a plain list
8433 ;; item. If that is the case, the structure command is used,
8434 ;; temporarily setting many Org-mode variables like regular
8435 ;; expressions for filling etc. However, when any of those keys is
8436 ;; used at a different location, function uses `key-binding' to look
8437 ;; up if the key has an associated command in another currently active
8438 ;; keymap (minor modes, major mode, global), and executes that
8439 ;; command. There might be problems if any of the keys is otherwise
8440 ;; used as a prefix key.
8442 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8443 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8444 ;; addresses this by checking explicitly for both bindings.
8446 (defvar orgstruct-mode-map (make-sparse-keymap)
8447 "Keymap for the minor `orgstruct-mode'.")
8449 (defvar org-local-vars nil
8450 "List of local variables, for use by `orgstruct-mode'.")
8452 ;;;###autoload
8453 (define-minor-mode orgstruct-mode
8454 "Toggle the minor mode `orgstruct-mode'.
8455 This mode is for using Org-mode structure commands in other
8456 modes. The following keys behave as if Org-mode were active, if
8457 the cursor is on a headline, or on a plain list item (both as
8458 defined by Org-mode).
8460 M-up Move entry/item up
8461 M-down Move entry/item down
8462 M-left Promote
8463 M-right Demote
8464 M-S-up Move entry/item up
8465 M-S-down Move entry/item down
8466 M-S-left Promote subtree
8467 M-S-right Demote subtree
8468 M-q Fill paragraph and items like in Org-mode
8469 C-c ^ Sort entries
8470 C-c - Cycle list bullet
8471 TAB Cycle item visibility
8472 M-RET Insert new heading/item
8473 S-M-RET Insert new TODO heading / Checkbox item
8474 C-c C-c Set tags / toggle checkbox"
8475 nil " OrgStruct" nil
8476 (org-load-modules-maybe)
8477 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8479 ;;;###autoload
8480 (defun turn-on-orgstruct ()
8481 "Unconditionally turn on `orgstruct-mode'."
8482 (orgstruct-mode 1))
8484 (defvar org-fb-vars nil)
8485 (make-variable-buffer-local 'org-fb-vars)
8486 (defun orgstruct++-mode (&optional arg)
8487 "Toggle `orgstruct-mode', the enhanced version of it.
8488 In addition to setting orgstruct-mode, this also exports all
8489 indentation and autofilling variables from org-mode into the
8490 buffer. It will also recognize item context in multiline items."
8491 (interactive "P")
8492 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8493 (if (< arg 1)
8494 (progn (orgstruct-mode -1)
8495 (mapc (lambda(v)
8496 (org-set-local (car v)
8497 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8498 org-fb-vars))
8499 (orgstruct-mode 1)
8500 (setq org-fb-vars nil)
8501 (let (var val)
8502 (mapc
8503 (lambda (x)
8504 (when (string-match
8505 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8506 (symbol-name (car x)))
8507 (setq var (car x) val (nth 1 x))
8508 (push (list var `(quote ,(eval var))) org-fb-vars)
8509 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8510 org-local-vars)
8511 (org-set-local 'orgstruct-is-++ t))))
8513 (defvar orgstruct-is-++ nil
8514 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8515 (make-variable-buffer-local 'orgstruct-is-++)
8517 ;;;###autoload
8518 (defun turn-on-orgstruct++ ()
8519 "Unconditionally turn on `orgstruct++-mode'."
8520 (orgstruct++-mode 1))
8522 (defun orgstruct-error ()
8523 "Error when there is no default binding for a structure key."
8524 (interactive)
8525 (error "This key has no function outside structure elements"))
8527 (defun orgstruct-setup ()
8528 "Setup orgstruct keymaps."
8529 (let ((nfunc 0)
8530 (bindings
8531 (list
8532 '([(meta up)] org-metaup)
8533 '([(meta down)] org-metadown)
8534 '([(meta left)] org-metaleft)
8535 '([(meta right)] org-metaright)
8536 '([(meta shift up)] org-shiftmetaup)
8537 '([(meta shift down)] org-shiftmetadown)
8538 '([(meta shift left)] org-shiftmetaleft)
8539 '([(meta shift right)] org-shiftmetaright)
8540 '([?\e (up)] org-metaup)
8541 '([?\e (down)] org-metadown)
8542 '([?\e (left)] org-metaleft)
8543 '([?\e (right)] org-metaright)
8544 '([?\e (shift up)] org-shiftmetaup)
8545 '([?\e (shift down)] org-shiftmetadown)
8546 '([?\e (shift left)] org-shiftmetaleft)
8547 '([?\e (shift right)] org-shiftmetaright)
8548 '([(shift up)] org-shiftup)
8549 '([(shift down)] org-shiftdown)
8550 '([(shift left)] org-shiftleft)
8551 '([(shift right)] org-shiftright)
8552 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8553 '("\M-q" fill-paragraph)
8554 '("\C-c^" org-sort)
8555 '("\C-c-" org-cycle-list-bullet)))
8556 elt key fun cmd)
8557 (while (setq elt (pop bindings))
8558 (setq nfunc (1+ nfunc))
8559 (setq key (org-key (car elt))
8560 fun (nth 1 elt)
8561 cmd (orgstruct-make-binding fun nfunc key))
8562 (org-defkey orgstruct-mode-map key cmd))
8564 ;; Prevent an error for users who forgot to make autoloads
8565 (require 'org-element)
8567 ;; Special treatment needed for TAB and RET
8568 (org-defkey orgstruct-mode-map [(tab)]
8569 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8570 (org-defkey orgstruct-mode-map "\C-i"
8571 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8573 (org-defkey orgstruct-mode-map "\M-\C-m"
8574 (orgstruct-make-binding 'org-insert-heading 105
8575 "\M-\C-m" [(meta return)]))
8576 (org-defkey orgstruct-mode-map [(meta return)]
8577 (orgstruct-make-binding 'org-insert-heading 106
8578 [(meta return)] "\M-\C-m"))
8580 (org-defkey orgstruct-mode-map [(shift meta return)]
8581 (orgstruct-make-binding 'org-insert-todo-heading 107
8582 [(meta return)] "\M-\C-m"))
8584 (org-defkey orgstruct-mode-map "\e\C-m"
8585 (orgstruct-make-binding 'org-insert-heading 108
8586 "\e\C-m" [?\e (return)]))
8587 (org-defkey orgstruct-mode-map [?\e (return)]
8588 (orgstruct-make-binding 'org-insert-heading 109
8589 [?\e (return)] "\e\C-m"))
8590 (org-defkey orgstruct-mode-map [?\e (shift return)]
8591 (orgstruct-make-binding 'org-insert-todo-heading 110
8592 [?\e (return)] "\e\C-m"))
8594 (unless org-local-vars
8595 (setq org-local-vars (org-get-local-variables)))
8599 (defun orgstruct-make-binding (fun n &rest keys)
8600 "Create a function for binding in the structure minor mode.
8601 FUN is the command to call inside a table. N is used to create a unique
8602 command name. KEYS are keys that should be checked in for a command
8603 to execute outside of tables."
8604 (eval
8605 (list 'defun
8606 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8607 '(arg)
8608 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8609 "Outside of structure, run the binding of `"
8610 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8611 "'.")
8612 '(interactive "p")
8613 (list 'if
8614 `(org-context-p 'headline 'item
8615 (and orgstruct-is-++
8616 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8617 'item-body))
8618 (list 'org-run-like-in-org-mode (list 'quote fun))
8619 (list 'let '(orgstruct-mode)
8620 (list 'call-interactively
8621 (append '(or)
8622 (mapcar (lambda (k)
8623 (list 'key-binding k))
8624 keys)
8625 '('orgstruct-error))))))))
8627 (defun org-contextualize-keys (alist contexts)
8628 "Return valid elements in ALIST depending on CONTEXTS.
8630 `org-agenda-custom-commands' or `org-capture-templates' are the
8631 values used for ALIST, and `org-agenda-custom-commands-contexts'
8632 or `org-capture-templates-contexts' are the associated contexts
8633 definitions."
8634 (let ((contexts
8635 ;; normalize contexts
8636 (mapcar
8637 (lambda(c) (cond ((listp (cadr c))
8638 (list (car c) (car c) (cadr c)))
8639 ((string= "" (cadr c))
8640 (list (car c) (car c) (caddr c)))
8641 (t c))) contexts))
8642 (a alist) c r s)
8643 ;; loop over all commands or templates
8644 (while (setq c (pop a))
8645 (let (vrules repl)
8646 (cond
8647 ((not (assoc (car c) contexts))
8648 (push c r))
8649 ((and (assoc (car c) contexts)
8650 (setq vrules (org-contextualize-validate-key
8651 (car c) contexts)))
8652 (mapc (lambda (vr)
8653 (when (not (equal (car vr) (cadr vr)))
8654 (setq repl vr))) vrules)
8655 (if (not repl) (push c r)
8656 (push (cadr repl) s)
8657 (push
8658 (cons (car c)
8659 (cdr (or (assoc (cadr repl) alist)
8660 (error "Undefined key `%s' as contextual replacement for `%s'"
8661 (cadr repl) (car c)))))
8662 r))))))
8663 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8664 (delq
8666 (delete-dups
8667 (mapcar (lambda (x)
8668 (let ((tpl (car x)))
8669 (when (not (delq
8671 (mapcar (lambda(y)
8672 (equal y tpl)) s))) x)))
8673 (reverse r))))))
8675 (defun org-contextualize-validate-key (key contexts)
8676 "Check CONTEXTS for agenda or capture KEY."
8677 (let (r rr res)
8678 (while (setq r (pop contexts))
8679 (mapc
8680 (lambda (rr)
8681 (when
8682 (and (equal key (car r))
8683 (if (functionp rr) (funcall rr)
8684 (or (and (eq (car rr) 'in-file)
8685 (buffer-file-name)
8686 (string-match (cdr rr) (buffer-file-name)))
8687 (and (eq (car rr) 'in-mode)
8688 (string-match (cdr rr) (symbol-name major-mode)))
8689 (when (and (eq (car rr) 'not-in-file)
8690 (buffer-file-name))
8691 (not (string-match (cdr rr) (buffer-file-name))))
8692 (when (eq (car rr) 'not-in-mode)
8693 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8694 (push r res)))
8695 (car (last r))))
8696 (delete-dups (delq nil res))))
8698 (defun org-context-p (&rest contexts)
8699 "Check if local context is any of CONTEXTS.
8700 Possible values in the list of contexts are `table', `headline', and `item'."
8701 (let ((pos (point)))
8702 (goto-char (point-at-bol))
8703 (prog1 (or (and (memq 'table contexts)
8704 (looking-at "[ \t]*|"))
8705 (and (memq 'headline contexts)
8706 (looking-at org-outline-regexp))
8707 (and (memq 'item contexts)
8708 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8709 (and (memq 'item-body contexts)
8710 (org-in-item-p)))
8711 (goto-char pos))))
8713 (defun org-get-local-variables ()
8714 "Return a list of all local variables in an Org mode buffer."
8715 (let (varlist)
8716 (with-current-buffer (get-buffer-create "*Org tmp*")
8717 (erase-buffer)
8718 (org-mode)
8719 (setq varlist (buffer-local-variables)))
8720 (kill-buffer "*Org tmp*")
8721 (delq nil
8722 (mapcar
8723 (lambda (x)
8724 (setq x
8725 (if (symbolp x)
8726 (list x)
8727 (list (car x) (list 'quote (cdr x)))))
8728 (if (string-match
8729 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8730 (symbol-name (car x)))
8731 x nil))
8732 varlist))))
8734 (defun org-clone-local-variables (from-buffer &optional regexp)
8735 "Clone local variables from FROM-BUFFER.
8736 Optional argument REGEXP selects variables to clone."
8737 (mapc
8738 (lambda (pair)
8739 (and (symbolp (car pair))
8740 (or (null regexp)
8741 (string-match regexp (symbol-name (car pair))))
8742 (set (make-local-variable (car pair))
8743 (cdr pair))))
8744 (buffer-local-variables from-buffer)))
8746 ;;;###autoload
8747 (defun org-run-like-in-org-mode (cmd)
8748 "Run a command, pretending that the current buffer is in Org-mode.
8749 This will temporarily bind local variables that are typically bound in
8750 Org-mode to the values they have in Org-mode, and then interactively
8751 call CMD."
8752 (org-load-modules-maybe)
8753 (unless org-local-vars
8754 (setq org-local-vars (org-get-local-variables)))
8755 (eval (list 'let org-local-vars
8756 (list 'call-interactively (list 'quote cmd)))))
8758 ;;;; Archiving
8760 (defun org-get-category (&optional pos force-refresh)
8761 "Get the category applying to position POS."
8762 (save-match-data
8763 (if force-refresh (org-refresh-category-properties))
8764 (let ((pos (or pos (point))))
8765 (or (get-text-property pos 'org-category)
8766 (progn (org-refresh-category-properties)
8767 (get-text-property pos 'org-category))))))
8769 (defun org-refresh-category-properties ()
8770 "Refresh category text properties in the buffer."
8771 (let ((case-fold-search t)
8772 (inhibit-read-only t)
8773 (def-cat (cond
8774 ((null org-category)
8775 (if buffer-file-name
8776 (file-name-sans-extension
8777 (file-name-nondirectory buffer-file-name))
8778 "???"))
8779 ((symbolp org-category) (symbol-name org-category))
8780 (t org-category)))
8781 beg end cat pos optionp)
8782 (org-unmodified
8783 (save-excursion
8784 (save-restriction
8785 (widen)
8786 (goto-char (point-min))
8787 (put-text-property (point) (point-max) 'org-category def-cat)
8788 (while (re-search-forward
8789 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8790 (setq pos (match-end 0)
8791 optionp (equal (char-after (match-beginning 0)) ?#)
8792 cat (org-trim (match-string 2)))
8793 (if optionp
8794 (setq beg (point-at-bol) end (point-max))
8795 (org-back-to-heading t)
8796 (setq beg (point) end (org-end-of-subtree t t)))
8797 (put-text-property beg end 'org-category cat)
8798 (put-text-property beg end 'org-category-position beg)
8799 (goto-char pos)))))))
8802 ;;;; Link Stuff
8804 ;;; Link abbreviations
8806 (defun org-link-expand-abbrev (link)
8807 "Apply replacements as defined in `org-link-abbrev-alist'."
8808 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8809 (let* ((key (match-string 1 link))
8810 (as (or (assoc key org-link-abbrev-alist-local)
8811 (assoc key org-link-abbrev-alist)))
8812 (tag (and (match-end 2) (match-string 3 link)))
8813 rpl)
8814 (if (not as)
8815 link
8816 (setq rpl (cdr as))
8817 (cond
8818 ((symbolp rpl) (funcall rpl tag))
8819 ((string-match "%(\\([^)]+\\))" rpl)
8820 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8821 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8822 ((string-match "%h" rpl)
8823 (replace-match (url-hexify-string (or tag "")) t t rpl))
8824 (t (concat rpl tag)))))
8825 link))
8827 ;;; Storing and inserting links
8829 (defvar org-insert-link-history nil
8830 "Minibuffer history for links inserted with `org-insert-link'.")
8832 (defvar org-stored-links nil
8833 "Contains the links stored with `org-store-link'.")
8835 (defvar org-store-link-plist nil
8836 "Plist with info about the most recently link created with `org-store-link'.")
8838 (defvar org-link-protocols nil
8839 "Link protocols added to Org-mode using `org-add-link-type'.")
8841 (defvar org-store-link-functions nil
8842 "List of functions that are called to create and store a link.
8843 Each function will be called in turn until one returns a non-nil
8844 value. Each function should check if it is responsible for creating
8845 this link (for example by looking at the major mode).
8846 If not, it must exit and return nil.
8847 If yes, it should return a non-nil value after a calling
8848 `org-store-link-props' with a list of properties and values.
8849 Special properties are:
8851 :type The link prefix, like \"http\". This must be given.
8852 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8853 This is obligatory as well.
8854 :description Optional default description for the second pair
8855 of brackets in an Org-mode link. The user can still change
8856 this when inserting this link into an Org-mode buffer.
8858 In addition to these, any additional properties can be specified
8859 and then used in capture templates.")
8861 (defun org-add-link-type (type &optional follow export)
8862 "Add TYPE to the list of `org-link-types'.
8863 Re-compute all regular expressions depending on `org-link-types'
8865 FOLLOW and EXPORT are two functions.
8867 FOLLOW should take the link path as the single argument and do whatever
8868 is necessary to follow the link, for example find a file or display
8869 a mail message.
8871 EXPORT should format the link path for export to one of the export formats.
8872 It should be a function accepting three arguments:
8874 path the path of the link, the text after the prefix (like \"http:\")
8875 desc the description of the link, if any, or a description added by
8876 org-export-normalize-links if there is none
8877 format the export format, a symbol like `html' or `latex' or `ascii'..
8879 The function may use the FORMAT information to return different values
8880 depending on the format. The return value will be put literally into
8881 the exported file. If the return value is nil, this means Org should
8882 do what it normally does with links which do not have EXPORT defined.
8884 Org-mode has a built-in default for exporting links. If you are happy with
8885 this default, there is no need to define an export function for the link
8886 type. For a simple example of an export function, see `org-bbdb.el'."
8887 (add-to-list 'org-link-types type t)
8888 (org-make-link-regexps)
8889 (if (assoc type org-link-protocols)
8890 (setcdr (assoc type org-link-protocols) (list follow export))
8891 (push (list type follow export) org-link-protocols)))
8893 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8894 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8896 ;;;###autoload
8897 (defun org-store-link (arg)
8898 "\\<org-mode-map>Store an org-link to the current location.
8899 This link is added to `org-stored-links' and can later be inserted
8900 into an org-buffer with \\[org-insert-link].
8902 For some link types, a prefix arg is interpreted.
8903 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8904 For file links, arg negates `org-context-in-file-links'.
8906 A double prefix arg force skipping storing functions that are not
8907 part of Org's core."
8908 (interactive "P")
8909 (org-load-modules-maybe)
8910 (setq org-store-link-plist nil) ; reset
8911 (org-with-limited-levels
8912 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8913 (cond
8914 ((and (not (equal arg '(16)))
8915 (setq sfuns
8916 (delq
8917 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8918 org-store-link-functions))
8919 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8920 (or (and (cdr sfuns)
8921 (funcall (intern
8922 (completing-read "Which function for creating the link? "
8923 sfunsn t (car sfunsn)))))
8924 (funcall (caar sfuns)))
8925 (setq link (plist-get org-store-link-plist :link)
8926 desc (or (plist-get org-store-link-plist :description) link))))
8927 ((org-src-edit-buffer-p)
8928 (let (label gc)
8929 (while (or (not label)
8930 (save-excursion
8931 (save-restriction
8932 (widen)
8933 (goto-char (point-min))
8934 (re-search-forward
8935 (regexp-quote (format org-coderef-label-format label))
8936 nil t))))
8937 (when label (message "Label exists already") (sit-for 2))
8938 (setq label (read-string "Code line label: " label)))
8939 (end-of-line 1)
8940 (setq link (format org-coderef-label-format label))
8941 (setq gc (- 79 (length link)))
8942 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8943 (insert link)
8944 (setq link (concat "(" label ")") desc nil)))
8946 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8947 ;; We are in the agenda, link to referenced location
8948 (let ((m (or (get-text-property (point) 'org-hd-marker)
8949 (get-text-property (point) 'org-marker))))
8950 (when m
8951 (org-with-point-at m
8952 (setq agenda-link
8953 (if (org-called-interactively-p 'any)
8954 (call-interactively 'org-store-link)
8955 (org-store-link nil)))))))
8957 ((eq major-mode 'calendar-mode)
8958 (let ((cd (calendar-cursor-to-date)))
8959 (setq link
8960 (format-time-string
8961 (car org-time-stamp-formats)
8962 (apply 'encode-time
8963 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8964 nil nil nil))))
8965 (org-store-link-props :type "calendar" :date cd)))
8967 ((eq major-mode 'help-mode)
8968 (setq link (concat "help:" (save-excursion
8969 (goto-char (point-min))
8970 (looking-at "^[^ ]+")
8971 (match-string 0))))
8972 (org-store-link-props :type "help"))
8974 ((eq major-mode 'w3-mode)
8975 (setq cpltxt (if (and (buffer-name)
8976 (not (string-match "Untitled" (buffer-name))))
8977 (buffer-name)
8978 (url-view-url t))
8979 link (url-view-url t))
8980 (org-store-link-props :type "w3" :url (url-view-url t)))
8982 ((setq search (run-hook-with-args-until-success
8983 'org-create-file-search-functions))
8984 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8985 "::" search))
8986 (setq cpltxt (or description link)))
8988 ((eq major-mode 'image-mode)
8989 (setq cpltxt (concat "file:"
8990 (abbreviate-file-name buffer-file-name))
8991 link cpltxt)
8992 (org-store-link-props :type "image" :file buffer-file-name))
8994 ((eq major-mode 'dired-mode)
8995 ;; link to the file in the current line
8996 (let ((file (dired-get-filename nil t)))
8997 (setq file (if file
8998 (abbreviate-file-name
8999 (expand-file-name (dired-get-filename nil t)))
9000 ;; otherwise, no file so use current directory.
9001 default-directory))
9002 (setq cpltxt (concat "file:" file)
9003 link cpltxt)))
9005 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9006 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9007 (cond
9008 ((org-in-regexp "<<\\(.*?\\)>>")
9009 (setq cpltxt
9010 (concat "file:"
9011 (abbreviate-file-name
9012 (buffer-file-name (buffer-base-buffer)))
9013 "::" (match-string 1))
9014 link cpltxt))
9015 ((and (featurep 'org-id)
9016 (or (eq org-link-to-org-use-id t)
9017 (and (org-called-interactively-p 'any)
9018 (or (eq org-link-to-org-use-id 'create-if-interactive)
9019 (and (eq org-link-to-org-use-id
9020 'create-if-interactive-and-no-custom-id)
9021 (not custom-id))))
9022 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
9023 ;; We can make a link using the ID.
9024 (setq link (condition-case nil
9025 (prog1 (org-id-store-link)
9026 (setq desc (plist-get org-store-link-plist :description)))
9027 (error
9028 ;; probably before first headline, link to file only
9029 (concat "file:"
9030 (abbreviate-file-name
9031 (buffer-file-name (buffer-base-buffer))))))))
9033 ;; Just link to current headline
9034 (setq cpltxt (concat "file:"
9035 (abbreviate-file-name
9036 (buffer-file-name (buffer-base-buffer)))))
9037 ;; Add a context search string
9038 (when (org-xor org-context-in-file-links arg)
9039 (let* ((ee (org-element-at-point))
9040 (et (org-element-type ee))
9041 (ev (plist-get (cadr ee) :value)))
9042 (setq txt (cond
9043 ((org-at-heading-p) nil)
9044 ((eq et 'keyword) ev)
9045 ((org-region-active-p)
9046 (buffer-substring (region-beginning) (region-end)))))
9047 (when (or (null txt) (string-match "\\S-" txt))
9048 (setq cpltxt
9049 (concat cpltxt "::"
9050 (condition-case nil
9051 (org-make-org-heading-search-string txt)
9052 (error "")))
9053 desc (or (and (eq et 'keyword) ev)
9054 (nth 4 (ignore-errors (org-heading-components)))
9055 "NONE")))))
9056 (if (string-match "::\\'" cpltxt)
9057 (setq cpltxt (substring cpltxt 0 -2)))
9058 (setq link cpltxt))))
9060 ((buffer-file-name (buffer-base-buffer))
9061 ;; Just link to this file here.
9062 (setq cpltxt (concat "file:"
9063 (abbreviate-file-name
9064 (buffer-file-name (buffer-base-buffer)))))
9065 ;; Add a context string
9066 (when (org-xor org-context-in-file-links arg)
9067 (setq txt (if (org-region-active-p)
9068 (buffer-substring (region-beginning) (region-end))
9069 (buffer-substring (point-at-bol) (point-at-eol))))
9070 ;; Only use search option if there is some text.
9071 (when (string-match "\\S-" txt)
9072 (setq cpltxt
9073 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9074 desc "NONE")))
9075 (setq link cpltxt))
9077 ((org-called-interactively-p 'interactive)
9078 (user-error "No method for storing a link from this buffer"))
9080 (t (setq link nil)))
9082 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9083 (setq link (or link cpltxt)
9084 desc (or desc cpltxt))
9085 (cond ((equal desc "NONE") (setq desc nil))
9086 ((string-match org-bracket-link-regexp desc)
9087 (setq desc (replace-regexp-in-string
9088 org-bracket-link-regexp
9089 (concat "\\3" (if (equal (length (match-string 0 desc))
9090 (length desc)) "*" "")) desc))))
9092 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9093 (progn
9094 (setq org-stored-links
9095 (cons (list link desc) org-stored-links))
9096 (message "Stored: %s" (or desc link))
9097 (when custom-id
9098 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9099 "::#" custom-id))
9100 (setq org-stored-links
9101 (cons (list link desc) org-stored-links))))
9102 (or agenda-link (and link (org-make-link-string link desc)))))))
9104 (defun org-store-link-props (&rest plist)
9105 "Store link properties, extract names and addresses."
9106 (let (x adr)
9107 (when (setq x (plist-get plist :from))
9108 (setq adr (mail-extract-address-components x))
9109 (setq plist (plist-put plist :fromname (car adr)))
9110 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9111 (when (setq x (plist-get plist :to))
9112 (setq adr (mail-extract-address-components x))
9113 (setq plist (plist-put plist :toname (car adr)))
9114 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9115 (let ((from (plist-get plist :from))
9116 (to (plist-get plist :to)))
9117 (when (and from to org-from-is-user-regexp)
9118 (setq plist
9119 (plist-put plist :fromto
9120 (if (string-match org-from-is-user-regexp from)
9121 (concat "to %t")
9122 (concat "from %f"))))))
9123 (setq org-store-link-plist plist))
9125 (defun org-add-link-props (&rest plist)
9126 "Add these properties to the link property list."
9127 (let (key value)
9128 (while plist
9129 (setq key (pop plist) value (pop plist))
9130 (setq org-store-link-plist
9131 (plist-put org-store-link-plist key value)))))
9133 (defun org-email-link-description (&optional fmt)
9134 "Return the description part of an email link.
9135 This takes information from `org-store-link-plist' and formats it
9136 according to FMT (default from `org-email-link-description-format')."
9137 (setq fmt (or fmt org-email-link-description-format))
9138 (let* ((p org-store-link-plist)
9139 (to (plist-get p :toaddress))
9140 (from (plist-get p :fromaddress))
9141 (table
9142 (list
9143 (cons "%c" (plist-get p :fromto))
9144 (cons "%F" (plist-get p :from))
9145 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9146 (cons "%T" (plist-get p :to))
9147 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9148 (cons "%s" (plist-get p :subject))
9149 (cons "%d" (plist-get p :date))
9150 (cons "%m" (plist-get p :message-id)))))
9151 (when (string-match "%c" fmt)
9152 ;; Check if the user wrote this message
9153 (if (and org-from-is-user-regexp from to
9154 (save-match-data (string-match org-from-is-user-regexp from)))
9155 (setq fmt (replace-match "to %t" t t fmt))
9156 (setq fmt (replace-match "from %f" t t fmt))))
9157 (org-replace-escapes fmt table)))
9159 (defun org-make-org-heading-search-string (&optional string)
9160 "Make search string for the current headline or STRING."
9161 (let ((s (or string
9162 (and (derived-mode-p 'org-mode)
9163 (save-excursion
9164 (org-back-to-heading t)
9165 (plist-get (cadr (org-element-at-point))
9166 :raw-value)))))
9167 (lines org-context-in-file-links))
9168 (or string (setq s (concat "*" s))) ; Add * for headlines
9169 (when (and string (integerp lines) (> lines 0))
9170 (let ((slines (org-split-string s "\n")))
9171 (when (< lines (length slines))
9172 (setq s (mapconcat
9173 'identity
9174 (reverse (nthcdr (- (length slines) lines)
9175 (reverse slines))) "\n")))))
9176 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9178 (defun org-make-link-string (link &optional description)
9179 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9180 (unless (string-match "\\S-" link)
9181 (error "Empty link"))
9182 (when (and description
9183 (stringp description)
9184 (not (string-match "\\S-" description)))
9185 (setq description nil))
9186 (when (stringp description)
9187 ;; Remove brackets from the description, they are fatal.
9188 (while (string-match "\\[" description)
9189 (setq description (replace-match "{" t t description)))
9190 (while (string-match "\\]" description)
9191 (setq description (replace-match "}" t t description))))
9192 (when (equal link description)
9193 ;; No description needed, it is identical
9194 (setq description nil))
9195 (when (and (not description)
9196 (not (string-match (org-image-file-name-regexp) link))
9197 (not (equal link (org-link-escape link))))
9198 (setq description (org-extract-attributes link)))
9199 (setq link
9200 (cond ((string-match (org-image-file-name-regexp) link) link)
9201 ((string-match org-link-types-re link)
9202 (concat (match-string 1 link)
9203 (org-link-escape (substring link (match-end 1)))))
9204 (t (org-link-escape link))))
9205 (concat "[[" link "]"
9206 (if description (concat "[" description "]") "")
9207 "]"))
9209 (defconst org-link-escape-chars
9210 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9211 "List of characters that should be escaped in link.
9212 This is the list that is used for internal purposes.")
9214 (defconst org-link-escape-chars-browser
9215 '(?\ )
9216 "List of escapes for characters that are problematic in links.
9217 This is the list that is used before handing over to the browser.")
9219 (defun org-link-escape (text &optional table merge)
9220 "Return percent escaped representation of TEXT.
9221 TEXT is a string with the text to escape.
9222 Optional argument TABLE is a list with characters that should be
9223 escaped. When nil, `org-link-escape-chars' is used.
9224 If optional argument MERGE is set, merge TABLE into
9225 `org-link-escape-chars'."
9226 (cond
9227 ((and table merge)
9228 (mapc (lambda (defchr)
9229 (unless (member defchr table)
9230 (setq table (cons defchr table)))) org-link-escape-chars))
9231 ((null table)
9232 (setq table org-link-escape-chars)))
9233 (mapconcat
9234 (lambda (char)
9235 (if (or (member char table)
9236 (and (or (< char 32) (= char 37) (> char 126))
9237 org-url-hexify-p))
9238 (mapconcat (lambda (sequence-element)
9239 (format "%%%.2X" sequence-element))
9240 (or (encode-coding-char char 'utf-8)
9241 (error "Unable to percent escape character: %s"
9242 (char-to-string char))) "")
9243 (char-to-string char))) text ""))
9245 (defun org-link-unescape (str)
9246 "Unhex hexified Unicode strings as returned from the JavaScript function
9247 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9248 (unless (and (null str) (string= "" str))
9249 (let ((pos 0) (case-fold-search t) unhexed)
9250 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9251 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9252 (setq str (replace-match unhexed t t str))
9253 (setq pos (+ pos (length unhexed))))))
9254 str)
9256 (defun org-link-unescape-compound (hex)
9257 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9258 Note: this function also decodes single byte encodings like
9259 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9260 (save-match-data
9261 (let* ((bytes (cdr (split-string hex "%")))
9262 (ret "")
9263 (eat 0)
9264 (sum 0))
9265 (while bytes
9266 (let* ((val (string-to-number (pop bytes) 16))
9267 (shift-xor
9268 (if (= 0 eat)
9269 (cond
9270 ((>= val 252) (cons 6 252))
9271 ((>= val 248) (cons 5 248))
9272 ((>= val 240) (cons 4 240))
9273 ((>= val 224) (cons 3 224))
9274 ((>= val 192) (cons 2 192))
9275 (t (cons 0 0)))
9276 (cons 6 128))))
9277 (if (>= val 192) (setq eat (car shift-xor)))
9278 (setq val (logxor val (cdr shift-xor)))
9279 (setq sum (+ (lsh sum (car shift-xor)) val))
9280 (if (> eat 0) (setq eat (- eat 1)))
9281 (cond
9282 ((= 0 eat) ;multi byte
9283 (setq ret (concat ret (org-char-to-string sum)))
9284 (setq sum 0))
9285 ((not bytes) ; single byte(s)
9286 (setq ret (org-link-unescape-single-byte-sequence hex))))
9287 )) ;; end (while bytes
9288 ret )))
9290 (defun org-link-unescape-single-byte-sequence (hex)
9291 "Unhexify hex-encoded single byte character sequences."
9292 (mapconcat (lambda (byte)
9293 (char-to-string (string-to-number byte 16)))
9294 (cdr (split-string hex "%")) ""))
9296 (defun org-xor (a b)
9297 "Exclusive or."
9298 (if a (not b) b))
9300 (defun org-fixup-message-id-for-http (s)
9301 "Replace special characters in a message id, so it can be used in an http query."
9302 (when (string-match "%" s)
9303 (setq s (mapconcat (lambda (c)
9304 (if (eq c ?%)
9305 "%25"
9306 (char-to-string c)))
9307 s "")))
9308 (while (string-match "<" s)
9309 (setq s (replace-match "%3C" t t s)))
9310 (while (string-match ">" s)
9311 (setq s (replace-match "%3E" t t s)))
9312 (while (string-match "@" s)
9313 (setq s (replace-match "%40" t t s)))
9316 (defun org-link-prettify (link)
9317 "Return a human-readable representation of LINK.
9318 The car of LINK must be a raw link the cdr of LINK must be either
9319 a link description or nil."
9320 (let ((desc (or (cadr link) "<no description>")))
9321 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9322 "<" (car link) ">")))
9324 ;;;###autoload
9325 (defun org-insert-link-global ()
9326 "Insert a link like Org-mode does.
9327 This command can be called in any mode to insert a link in Org-mode syntax."
9328 (interactive)
9329 (org-load-modules-maybe)
9330 (org-run-like-in-org-mode 'org-insert-link))
9332 (defun org-insert-all-links (&optional keep)
9333 "Insert all links in `org-stored-links'."
9334 (interactive "P")
9335 (let ((links (copy-sequence org-stored-links)) l)
9336 (while (setq l (if keep (pop links) (pop org-stored-links)))
9337 (insert "- ")
9338 (org-insert-link nil (car l) (cadr l))
9339 (insert "\n"))))
9341 (defun org-link-fontify-links-to-this-file ()
9342 "Fontify links to the current file in `org-stored-links'."
9343 (let ((f (buffer-file-name)) a b)
9344 (setq a (mapcar (lambda(l)
9345 (let ((ll (car l)))
9346 (when (and (string-match "^file:\\(.+\\)::" ll)
9347 (equal f (expand-file-name (match-string 1 ll))))
9348 ll)))
9349 org-stored-links))
9350 (when (featurep 'org-id)
9351 (setq b (mapcar (lambda(l)
9352 (let ((ll (car l)))
9353 (when (and (string-match "^id:\\(.+\\)$" ll)
9354 (equal f (expand-file-name
9355 (or (org-id-find-id-file
9356 (match-string 1 ll)) ""))))
9357 ll)))
9358 org-stored-links)))
9359 (mapcar (lambda(l)
9360 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9361 (delq nil (append a b)))))
9363 (defvar org-link-links-in-this-file nil)
9364 (defun org-insert-link (&optional complete-file link-location default-description)
9365 "Insert a link. At the prompt, enter the link.
9367 Completion can be used to insert any of the link protocol prefixes like
9368 http or ftp in use.
9370 The history can be used to select a link previously stored with
9371 `org-store-link'. When the empty string is entered (i.e. if you just
9372 press RET at the prompt), the link defaults to the most recently
9373 stored link. As SPC triggers completion in the minibuffer, you need to
9374 use M-SPC or C-q SPC to force the insertion of a space character.
9376 You will also be prompted for a description, and if one is given, it will
9377 be displayed in the buffer instead of the link.
9379 If there is already a link at point, this command will allow you to edit link
9380 and description parts.
9382 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9383 be selected using completion. The path to the file will be relative to the
9384 current directory if the file is in the current directory or a subdirectory.
9385 Otherwise, the link will be the absolute path as completed in the minibuffer
9386 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9387 option `org-link-file-path-type'.
9389 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9390 the current directory or below.
9392 With three \\[universal-argument] prefixes, negate the meaning of
9393 `org-keep-stored-link-after-insertion'.
9395 If `org-make-link-description-function' is non-nil, this function will be
9396 called with the link target, and the result will be the default
9397 link description.
9399 If the LINK-LOCATION parameter is non-nil, this value will be
9400 used as the link location instead of reading one interactively.
9402 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9403 be used as the default description."
9404 (interactive "P")
9405 (let* ((wcf (current-window-configuration))
9406 (origbuf (current-buffer))
9407 (region (if (org-region-active-p)
9408 (buffer-substring (region-beginning) (region-end))))
9409 (remove (and region (list (region-beginning) (region-end))))
9410 (desc region)
9411 tmphist ; byte-compile incorrectly complains about this
9412 (link link-location)
9413 (abbrevs org-link-abbrev-alist-local)
9414 entry file all-prefixes auto-desc)
9415 (cond
9416 (link-location) ; specified by arg, just use it.
9417 ((org-in-regexp org-bracket-link-regexp 1)
9418 ;; We do have a link at point, and we are going to edit it.
9419 (setq remove (list (match-beginning 0) (match-end 0)))
9420 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9421 (setq link (read-string "Link: "
9422 (org-link-unescape
9423 (org-match-string-no-properties 1)))))
9424 ((or (org-in-regexp org-angle-link-re)
9425 (org-in-regexp org-plain-link-re))
9426 ;; Convert to bracket link
9427 (setq remove (list (match-beginning 0) (match-end 0))
9428 link (read-string "Link: "
9429 (org-remove-angle-brackets (match-string 0)))))
9430 ((member complete-file '((4) (16)))
9431 ;; Completing read for file names.
9432 (setq link (org-file-complete-link complete-file)))
9434 ;; Read link, with completion for stored links.
9435 (org-link-fontify-links-to-this-file)
9436 (org-switch-to-buffer-other-window "*Org Links*")
9437 (with-current-buffer "*Org Links*"
9438 (erase-buffer)
9439 (insert "Insert a link.
9440 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9441 (when org-stored-links
9442 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9443 (insert (mapconcat 'org-link-prettify
9444 (reverse org-stored-links) "\n")))
9445 (goto-char (point-min)))
9446 (let ((cw (selected-window)))
9447 (select-window (get-buffer-window "*Org Links*" 'visible))
9448 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9449 (unless (pos-visible-in-window-p (point-max))
9450 (org-fit-window-to-buffer))
9451 (and (window-live-p cw) (select-window cw)))
9452 ;; Fake a link history, containing the stored links.
9453 (setq tmphist (append (mapcar 'car org-stored-links)
9454 org-insert-link-history))
9455 (setq all-prefixes (append (mapcar 'car abbrevs)
9456 (mapcar 'car org-link-abbrev-alist)
9457 org-link-types))
9458 (unwind-protect
9459 (progn
9460 (setq link
9461 (org-completing-read
9462 "Link: "
9463 (append
9464 (mapcar (lambda (x) (concat x ":"))
9465 all-prefixes)
9466 (mapcar 'car org-stored-links))
9467 nil nil nil
9468 'tmphist
9469 (caar org-stored-links)))
9470 (if (not (string-match "\\S-" link))
9471 (error "No link selected"))
9472 (mapc (lambda(l)
9473 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9474 org-stored-links)
9475 (if (or (member link all-prefixes)
9476 (and (equal ":" (substring link -1))
9477 (member (substring link 0 -1) all-prefixes)
9478 (setq link (substring link 0 -1))))
9479 (setq link (with-current-buffer origbuf
9480 (org-link-try-special-completion link)))))
9481 (set-window-configuration wcf)
9482 (kill-buffer "*Org Links*"))
9483 (setq entry (assoc link org-stored-links))
9484 (or entry (push link org-insert-link-history))
9485 (setq desc (or desc (nth 1 entry)))))
9487 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9488 (not org-keep-stored-link-after-insertion))
9489 (setq org-stored-links (delq (assoc link org-stored-links)
9490 org-stored-links)))
9492 (if (string-match org-plain-link-re link)
9493 ;; URL-like link, normalize the use of angular brackets.
9494 (setq link (org-remove-angle-brackets link)))
9496 ;; Check if we are linking to the current file with a search
9497 ;; option If yes, simplify the link by using only the search
9498 ;; option.
9499 (when (and buffer-file-name
9500 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9501 (let* ((path (match-string 1 link))
9502 (case-fold-search nil)
9503 (search (match-string 2 link)))
9504 (save-match-data
9505 (if (equal (file-truename buffer-file-name) (file-truename path))
9506 ;; We are linking to this same file, with a search option
9507 (setq link search)))))
9509 ;; Check if we can/should use a relative path. If yes, simplify the link
9510 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9511 (let* ((type (match-string 1 link))
9512 (path (match-string 2 link))
9513 (origpath path)
9514 (case-fold-search nil))
9515 (cond
9516 ((or (eq org-link-file-path-type 'absolute)
9517 (equal complete-file '(16)))
9518 (setq path (abbreviate-file-name (expand-file-name path))))
9519 ((eq org-link-file-path-type 'noabbrev)
9520 (setq path (expand-file-name path)))
9521 ((eq org-link-file-path-type 'relative)
9522 (setq path (file-relative-name path)))
9524 (save-match-data
9525 (if (string-match (concat "^" (regexp-quote
9526 (expand-file-name
9527 (file-name-as-directory
9528 default-directory))))
9529 (expand-file-name path))
9530 ;; We are linking a file with relative path name.
9531 (setq path (substring (expand-file-name path)
9532 (match-end 0)))
9533 (setq path (abbreviate-file-name (expand-file-name path)))))))
9534 (setq link (concat type path))
9535 (if (equal desc origpath)
9536 (setq desc path))))
9538 (if org-make-link-description-function
9539 (setq desc
9540 (or (condition-case nil
9541 (funcall org-make-link-description-function link desc)
9542 (error (progn (message "Can't get link description from `%s'"
9543 (symbol-name org-make-link-description-function))
9544 (sit-for 2) nil)))
9545 (read-string "Description: " default-description)))
9546 (if default-description (setq desc default-description)
9547 (setq desc (or (and auto-desc desc)
9548 (read-string "Description: " desc)))))
9550 (unless (string-match "\\S-" desc) (setq desc nil))
9551 (if remove (apply 'delete-region remove))
9552 (insert (org-make-link-string link desc))))
9554 (defun org-link-try-special-completion (type)
9555 "If there is completion support for link type TYPE, offer it."
9556 (let ((fun (intern (concat "org-" type "-complete-link"))))
9557 (if (functionp fun)
9558 (funcall fun)
9559 (read-string "Link (no completion support): " (concat type ":")))))
9561 (defun org-file-complete-link (&optional arg)
9562 "Create a file link using completion."
9563 (let (file link)
9564 (setq file (org-iread-file-name "File: "))
9565 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9566 (pwd1 (file-name-as-directory (abbreviate-file-name
9567 (expand-file-name ".")))))
9568 (cond
9569 ((equal arg '(16))
9570 (setq link (concat
9571 "file:"
9572 (abbreviate-file-name (expand-file-name file)))))
9573 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9574 (setq link (concat "file:" (match-string 1 file))))
9575 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9576 (expand-file-name file))
9577 (setq link (concat
9578 "file:" (match-string 1 (expand-file-name file)))))
9579 (t (setq link (concat "file:" file)))))
9580 link))
9582 (defun org-iread-file-name (&rest args)
9583 "Read-file-name using `ido-mode' speedup if available.
9584 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9585 See `read-file-name' for a description of parameters."
9586 (org-without-partial-completion
9587 (if (and org-completion-use-ido
9588 (fboundp 'ido-read-file-name)
9589 (boundp 'ido-mode) ido-mode
9590 (listp (second args)))
9591 (let ((ido-enter-matching-directory nil))
9592 (apply 'ido-read-file-name args))
9593 (apply 'read-file-name args))))
9595 (defun org-completing-read (&rest args)
9596 "Completing-read with SPACE being a normal character."
9597 (let ((enable-recursive-minibuffers t)
9598 (minibuffer-local-completion-map
9599 (copy-keymap minibuffer-local-completion-map)))
9600 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9601 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9602 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9603 (apply 'org-icompleting-read args)))
9605 (defun org-completing-read-no-i (&rest args)
9606 (let (org-completion-use-ido org-completion-use-iswitchb)
9607 (apply 'org-completing-read args)))
9609 (defun org-iswitchb-completing-read (prompt choices &rest args)
9610 "Use iswitch as a completing-read replacement to choose from choices.
9611 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9612 from."
9613 (let* ((iswitchb-use-virtual-buffers nil)
9614 (iswitchb-make-buflist-hook
9615 (lambda ()
9616 (setq iswitchb-temp-buflist choices))))
9617 (iswitchb-read-buffer prompt)))
9619 (defun org-icompleting-read (&rest args)
9620 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9621 (org-without-partial-completion
9622 (if (and org-completion-use-ido
9623 (fboundp 'ido-completing-read)
9624 (boundp 'ido-mode) ido-mode
9625 (listp (second args)))
9626 (let ((ido-enter-matching-directory nil))
9627 (apply 'ido-completing-read (concat (car args))
9628 (if (consp (car (nth 1 args)))
9629 (mapcar 'car (nth 1 args))
9630 (nth 1 args))
9631 (cddr args)))
9632 (if (and org-completion-use-iswitchb
9633 (boundp 'iswitchb-mode) iswitchb-mode
9634 (listp (second args)))
9635 (apply 'org-iswitchb-completing-read (concat (car args))
9636 (if (consp (car (nth 1 args)))
9637 (mapcar 'car (nth 1 args))
9638 (nth 1 args))
9639 (cddr args))
9640 (apply 'completing-read args)))))
9642 (defun org-extract-attributes (s)
9643 "Extract the attributes cookie from a string and set as text property."
9644 (let (a attr (start 0) key value)
9645 (save-match-data
9646 (when (string-match "{{\\([^}]+\\)}}$" s)
9647 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9648 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9649 (setq key (match-string 1 a) value (match-string 2 a)
9650 start (match-end 0)
9651 attr (plist-put attr (intern key) value))))
9652 (org-add-props s nil 'org-attr attr))
9655 (defun org-extract-attributes-from-string (tag)
9656 (let (key value attr)
9657 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9658 (setq key (match-string 1 tag) value (match-string 2 tag)
9659 tag (replace-match "" t t tag)
9660 attr (plist-put attr (intern key) value)))
9661 (cons tag attr)))
9663 (defun org-attributes-to-string (plist)
9664 "Format a property list into an HTML attribute list."
9665 (let ((s "") key value)
9666 (while plist
9667 (setq key (pop plist) value (pop plist))
9668 (and value
9669 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9672 ;;; Opening/following a link
9674 (defvar org-link-search-failed nil)
9676 (defvar org-open-link-functions nil
9677 "Hook for functions finding a plain text link.
9678 These functions must take a single argument, the link content.
9679 They will be called for links that look like [[link text][description]]
9680 when LINK TEXT does not have a protocol like \"http:\" and does not look
9681 like a filename (e.g. \"./blue.png\").
9683 These functions will be called *before* Org attempts to resolve the
9684 link by doing text searches in the current buffer - so if you want a
9685 link \"[[target]]\" to still find \"<<target>>\", your function should
9686 handle this as a special case.
9688 When the function does handle the link, it must return a non-nil value.
9689 If it decides that it is not responsible for this link, it must return
9690 nil to indicate that that Org-mode can continue with other options
9691 like exact and fuzzy text search.")
9693 (defun org-next-link ()
9694 "Move forward to the next link.
9695 If the link is in hidden text, expose it."
9696 (interactive)
9697 (when (and org-link-search-failed (eq this-command last-command))
9698 (goto-char (point-min))
9699 (message "Link search wrapped back to beginning of buffer"))
9700 (setq org-link-search-failed nil)
9701 (let* ((pos (point))
9702 (ct (org-context))
9703 (a (assoc :link ct)))
9704 (if a (goto-char (nth 2 a)))
9705 (if (re-search-forward org-any-link-re nil t)
9706 (progn
9707 (goto-char (match-beginning 0))
9708 (if (outline-invisible-p) (org-show-context)))
9709 (goto-char pos)
9710 (setq org-link-search-failed t)
9711 (error "No further link found"))))
9713 (defun org-previous-link ()
9714 "Move backward to the previous link.
9715 If the link is in hidden text, expose it."
9716 (interactive)
9717 (when (and org-link-search-failed (eq this-command last-command))
9718 (goto-char (point-max))
9719 (message "Link search wrapped back to end of buffer"))
9720 (setq org-link-search-failed nil)
9721 (let* ((pos (point))
9722 (ct (org-context))
9723 (a (assoc :link ct)))
9724 (if a (goto-char (nth 1 a)))
9725 (if (re-search-backward org-any-link-re nil t)
9726 (progn
9727 (goto-char (match-beginning 0))
9728 (if (outline-invisible-p) (org-show-context)))
9729 (goto-char pos)
9730 (setq org-link-search-failed t)
9731 (error "No further link found"))))
9733 (defun org-translate-link (s)
9734 "Translate a link string if a translation function has been defined."
9735 (if (and org-link-translation-function
9736 (fboundp org-link-translation-function)
9737 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9738 (progn
9739 (setq s (funcall org-link-translation-function
9740 (match-string 1 s) (match-string 2 s)))
9741 (concat (car s) ":" (cdr s)))
9744 (defun org-translate-link-from-planner (type path)
9745 "Translate a link from Emacs Planner syntax so that Org can follow it.
9746 This is still an experimental function, your mileage may vary."
9747 (cond
9748 ((member type '("http" "https" "news" "ftp"))
9749 ;; standard Internet links are the same.
9750 nil)
9751 ((and (equal type "irc") (string-match "^//" path))
9752 ;; Planner has two / at the beginning of an irc link, we have 1.
9753 ;; We should have zero, actually....
9754 (setq path (substring path 1)))
9755 ((and (equal type "lisp") (string-match "^/" path))
9756 ;; Planner has a slash, we do not.
9757 (setq type "elisp" path (substring path 1)))
9758 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9759 ;; A typical message link. Planner has the id after the final slash,
9760 ;; we separate it with a hash mark
9761 (setq path (concat (match-string 1 path) "#"
9762 (org-remove-angle-brackets (match-string 2 path)))))
9764 (cons type path))
9766 (defun org-find-file-at-mouse (ev)
9767 "Open file link or URL at mouse."
9768 (interactive "e")
9769 (mouse-set-point ev)
9770 (org-open-at-point 'in-emacs))
9772 (defun org-open-at-mouse (ev)
9773 "Open file link or URL at mouse.
9774 See the docstring of `org-open-file' for details."
9775 (interactive "e")
9776 (mouse-set-point ev)
9777 (if (eq major-mode 'org-agenda-mode)
9778 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9779 (org-open-at-point))
9781 (defvar org-window-config-before-follow-link nil
9782 "The window configuration before following a link.
9783 This is saved in case the need arises to restore it.")
9785 (defvar org-open-link-marker (make-marker)
9786 "Marker pointing to the location where `org-open-at-point; was called.")
9788 ;;;###autoload
9789 (defun org-open-at-point-global ()
9790 "Follow a link like Org-mode does.
9791 This command can be called in any mode to follow a link that has
9792 Org-mode syntax."
9793 (interactive)
9794 (org-run-like-in-org-mode 'org-open-at-point))
9796 ;;;###autoload
9797 (defun org-open-link-from-string (s &optional arg reference-buffer)
9798 "Open a link in the string S, as if it was in Org-mode."
9799 (interactive "sLink: \nP")
9800 (let ((reference-buffer (or reference-buffer (current-buffer))))
9801 (with-temp-buffer
9802 (let ((org-inhibit-startup (not reference-buffer)))
9803 (org-mode)
9804 (insert s)
9805 (goto-char (point-min))
9806 (when reference-buffer
9807 (setq org-link-abbrev-alist-local
9808 (with-current-buffer reference-buffer
9809 org-link-abbrev-alist-local)))
9810 (org-open-at-point arg reference-buffer)))))
9812 (defvar org-open-at-point-functions nil
9813 "Hook that is run when following a link at point.
9815 Functions in this hook must return t if they identify and follow
9816 a link at point. If they don't find anything interesting at point,
9817 they must return nil.")
9819 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9820 (defun org-open-at-point (&optional arg reference-buffer)
9821 "Open link at or after point.
9822 If there is no link at point, this function will search forward up to
9823 the end of the current line.
9824 Normally, files will be opened by an appropriate application. If the
9825 optional prefix argument ARG is non-nil, Emacs will visit the file.
9826 With a double prefix argument, try to open outside of Emacs, in the
9827 application the system uses for this file type."
9828 (interactive "P")
9829 ;; if in a code block, then open the block's results
9830 (unless (call-interactively #'org-babel-open-src-block-result)
9831 (org-load-modules-maybe)
9832 (move-marker org-open-link-marker (point))
9833 (setq org-window-config-before-follow-link (current-window-configuration))
9834 (org-remove-occur-highlights nil nil t)
9835 (cond
9836 ((and (org-at-heading-p)
9837 (not (org-at-timestamp-p t))
9838 (not (org-in-regexp
9839 (concat org-plain-link-re "\\|"
9840 org-bracket-link-regexp "\\|"
9841 org-angle-link-re "\\|"
9842 "[ \t]:[^ \t\n]+:[ \t]*$")))
9843 (not (get-text-property (point) 'org-linked-text)))
9844 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9845 (lk (car lkall))
9846 (lkend (cdr lkall)))
9847 (when lk
9848 (prog1 (search-forward lk nil lkend)
9849 (goto-char (match-beginning 0))
9850 (org-open-at-point))))
9851 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9852 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9853 ((and (org-at-timestamp-p t)
9854 (not (org-in-regexp org-bracket-link-regexp)))
9855 (org-follow-timestamp-link))
9856 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9857 (not (org-in-regexp org-any-link-re)))
9858 (org-footnote-action))
9860 (let (type path link line search (pos (point)))
9861 (catch 'match
9862 (save-excursion
9863 (skip-chars-forward "^]\n\r")
9864 (when (org-in-regexp org-bracket-link-regexp 1)
9865 (setq link (org-extract-attributes
9866 (org-link-unescape (org-match-string-no-properties 1))))
9867 (while (string-match " *\n *" link)
9868 (setq link (replace-match " " t t link)))
9869 (setq link (org-link-expand-abbrev link))
9870 (cond
9871 ((or (file-name-absolute-p link)
9872 (string-match "^\\.\\.?/" link))
9873 (setq type "file" path link))
9874 ((string-match org-link-re-with-space3 link)
9875 (setq type (match-string 1 link) path (match-string 2 link)))
9876 ((string-match "^help:+\\(.+\\)" link)
9877 (setq type "help" path (match-string 1 link)))
9878 (t (setq type "thisfile" path link)))
9879 (throw 'match t)))
9881 (when (get-text-property (point) 'org-linked-text)
9882 (setq type "thisfile"
9883 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9884 (1+ (point)) (point))
9885 path (buffer-substring
9886 (or (previous-single-property-change pos 'org-linked-text)
9887 (point-min))
9888 (or (next-single-property-change pos 'org-linked-text)
9889 (point-max))))
9890 (throw 'match t))
9892 (save-excursion
9893 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9894 (when (or (org-in-regexp org-angle-link-re)
9895 (and plinkpos (goto-char (car plinkpos))
9896 (save-match-data (not (looking-back "\\[\\[")))))
9897 (setq type (match-string 1)
9898 path (org-link-unescape (match-string 2)))
9899 (throw 'match t))))
9900 (save-excursion
9901 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9902 (setq type "tags"
9903 path (match-string 1))
9904 (while (string-match ":" path)
9905 (setq path (replace-match "+" t t path)))
9906 (throw 'match t)))
9907 (when (org-in-regexp "<\\([^><\n]+\\)>")
9908 (setq type "tree-match"
9909 path (match-string 1))
9910 (throw 'match t)))
9911 (unless path
9912 (user-error "No link found"))
9914 ;; switch back to reference buffer
9915 ;; needed when if called in a temporary buffer through
9916 ;; org-open-link-from-string
9917 (with-current-buffer (or reference-buffer (current-buffer))
9919 ;; Remove any trailing spaces in path
9920 (if (string-match " +\\'" path)
9921 (setq path (replace-match "" t t path)))
9922 (if (and org-link-translation-function
9923 (fboundp org-link-translation-function))
9924 ;; Check if we need to translate the link
9925 (let ((tmp (funcall org-link-translation-function type path)))
9926 (setq type (car tmp) path (cdr tmp))))
9928 (cond
9930 ((assoc type org-link-protocols)
9931 (funcall (nth 1 (assoc type org-link-protocols)) path))
9933 ((equal type "help")
9934 (let ((f-or-v (intern path)))
9935 (cond ((fboundp f-or-v)
9936 (describe-function f-or-v))
9937 ((boundp f-or-v)
9938 (describe-variable f-or-v))
9939 (t (error "Not a known function or variable")))))
9941 ((equal type "mailto")
9942 (let ((cmd (car org-link-mailto-program))
9943 (args (cdr org-link-mailto-program)) args1
9944 (address path) (subject "") a)
9945 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9946 (setq address (match-string 1 path)
9947 subject (org-link-escape (match-string 2 path))))
9948 (while args
9949 (cond
9950 ((not (stringp (car args))) (push (pop args) args1))
9951 (t (setq a (pop args))
9952 (if (string-match "%a" a)
9953 (setq a (replace-match address t t a)))
9954 (if (string-match "%s" a)
9955 (setq a (replace-match subject t t a)))
9956 (push a args1))))
9957 (apply cmd (nreverse args1))))
9959 ((member type '("http" "https" "ftp" "news"))
9960 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9961 (org-link-escape
9962 path org-link-escape-chars-browser)
9963 path))))
9965 ((string= type "doi")
9966 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9967 (org-link-escape
9968 path org-link-escape-chars-browser)
9969 path))))
9971 ((member type '("message"))
9972 (browse-url (concat type ":" path)))
9974 ((string= type "tags")
9975 (org-tags-view arg path))
9977 ((string= type "tree-match")
9978 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9980 ((string= type "file")
9981 (if (string-match "::\\([0-9]+\\)\\'" path)
9982 (setq line (string-to-number (match-string 1 path))
9983 path (substring path 0 (match-beginning 0)))
9984 (if (string-match "::\\(.+\\)\\'" path)
9985 (setq search (match-string 1 path)
9986 path (substring path 0 (match-beginning 0)))))
9987 (if (string-match "[*?{]" (file-name-nondirectory path))
9988 (dired path)
9989 (org-open-file path arg line search)))
9991 ((string= type "shell")
9992 (let ((buf (generate-new-buffer "*Org Shell Output"))
9993 (cmd path))
9994 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9995 (string-match org-confirm-shell-link-not-regexp cmd))
9996 (not org-confirm-shell-link-function)
9997 (funcall org-confirm-shell-link-function
9998 (format "Execute \"%s\" in shell? "
9999 (org-add-props cmd nil
10000 'face 'org-warning))))
10001 (progn
10002 (message "Executing %s" cmd)
10003 (shell-command cmd buf)
10004 (if (featurep 'midnight)
10005 (setq clean-buffer-list-kill-buffer-names
10006 (cons buf clean-buffer-list-kill-buffer-names))))
10007 (error "Abort"))))
10009 ((string= type "elisp")
10010 (let ((cmd path))
10011 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10012 (string-match org-confirm-elisp-link-not-regexp cmd))
10013 (not org-confirm-elisp-link-function)
10014 (funcall org-confirm-elisp-link-function
10015 (format "Execute \"%s\" as elisp? "
10016 (org-add-props cmd nil
10017 'face 'org-warning))))
10018 (message "%s => %s" cmd
10019 (if (equal (string-to-char cmd) ?\()
10020 (eval (read cmd))
10021 (call-interactively (read cmd))))
10022 (error "Abort"))))
10024 ((and (string= type "thisfile")
10025 (run-hook-with-args-until-success
10026 'org-open-link-functions path)))
10028 ((string= type "thisfile")
10029 (if arg
10030 (switch-to-buffer-other-window
10031 (org-get-buffer-for-internal-link (current-buffer)))
10032 (org-mark-ring-push))
10033 (let ((cmd `(org-link-search
10034 ,path
10035 ,(cond ((equal arg '(4)) ''occur)
10036 ((equal arg '(16)) ''org-occur))
10037 ,pos)))
10038 (condition-case nil (let ((org-link-search-inhibit-query t))
10039 (eval cmd))
10040 (error (progn (widen) (eval cmd))))))
10042 (t (browse-url-at-point)))))))
10043 (move-marker org-open-link-marker nil)
10044 (run-hook-with-args 'org-follow-link-hook)))
10046 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10047 "Offer links in the current entry and return the selected link.
10048 If there is only one link, return it.
10049 If NTH is an integer, return the NTH link found.
10050 If ZERO is a string, check also this string for a link, and if
10051 there is one, return it."
10052 (with-current-buffer buffer
10053 (save-excursion
10054 (save-restriction
10055 (widen)
10056 (goto-char marker)
10057 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10058 "\\(" org-angle-link-re "\\)\\|"
10059 "\\(" org-plain-link-re "\\)"))
10060 (cnt ?0)
10061 (in-emacs (if (integerp nth) nil nth))
10062 have-zero end links link c)
10063 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10064 (push (match-string 0 zero) links)
10065 (setq cnt (1- cnt) have-zero t))
10066 (save-excursion
10067 (org-back-to-heading t)
10068 (setq end (save-excursion (outline-next-heading) (point)))
10069 (while (re-search-forward re end t)
10070 (push (match-string 0) links))
10071 (setq links (org-uniquify (reverse links))))
10072 (cond
10073 ((null links)
10074 (message "No links"))
10075 ((equal (length links) 1)
10076 (setq link (car links)))
10077 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10078 (setq link (nth (if have-zero nth (1- nth)) links)))
10079 (t ; we have to select a link
10080 (save-excursion
10081 (save-window-excursion
10082 (delete-other-windows)
10083 (with-output-to-temp-buffer "*Select Link*"
10084 (mapc (lambda (l)
10085 (if (not (string-match org-bracket-link-regexp l))
10086 (princ (format "[%c] %s\n" (incf cnt)
10087 (org-remove-angle-brackets l)))
10088 (if (match-end 3)
10089 (princ (format "[%c] %s (%s)\n" (incf cnt)
10090 (match-string 3 l) (match-string 1 l)))
10091 (princ (format "[%c] %s\n" (incf cnt)
10092 (match-string 1 l))))))
10093 links))
10094 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10095 (message "Select link to open, RET to open all:")
10096 (setq c (read-char-exclusive))
10097 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10098 (when (equal c ?q) (error "Abort"))
10099 (if (equal c ?\C-m)
10100 (setq link links)
10101 (setq nth (- c ?0))
10102 (if have-zero (setq nth (1+ nth)))
10103 (unless (and (integerp nth) (>= (length links) nth))
10104 (error "Invalid link selection"))
10105 (setq link (nth (1- nth) links)))))
10106 (cons link end))))))
10108 ;; Add special file links that specify the way of opening
10110 (org-add-link-type "file+sys" 'org-open-file-with-system)
10111 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10112 (defun org-open-file-with-system (path)
10113 "Open file at PATH using the system way of opening it."
10114 (org-open-file path 'system))
10115 (defun org-open-file-with-emacs (path)
10116 "Open file at PATH in Emacs."
10117 (org-open-file path 'emacs))
10118 (defun org-remove-file-link-modifiers ()
10119 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10120 (goto-char (point-min))
10121 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10122 (org-if-unprotected
10123 (replace-match "file:" t t))))
10124 (eval-after-load "org-exp"
10125 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10126 'org-remove-file-link-modifiers))
10128 ;;;; Time estimates
10130 (defun org-get-effort (&optional pom)
10131 "Get the effort estimate for the current entry."
10132 (org-entry-get pom org-effort-property))
10134 ;;; File search
10136 (defvar org-create-file-search-functions nil
10137 "List of functions to construct the right search string for a file link.
10138 These functions are called in turn with point at the location to
10139 which the link should point.
10141 A function in the hook should first test if it would like to
10142 handle this file type, for example by checking the `major-mode'
10143 or the file extension. If it decides not to handle this file, it
10144 should just return nil to give other functions a chance. If it
10145 does handle the file, it must return the search string to be used
10146 when following the link. The search string will be part of the
10147 file link, given after a double colon, and `org-open-at-point'
10148 will automatically search for it. If special measures must be
10149 taken to make the search successful, another function should be
10150 added to the companion hook `org-execute-file-search-functions',
10151 which see.
10153 A function in this hook may also use `setq' to set the variable
10154 `description' to provide a suggestion for the descriptive text to
10155 be used for this link when it gets inserted into an Org-mode
10156 buffer with \\[org-insert-link].")
10158 (defvar org-execute-file-search-functions nil
10159 "List of functions to execute a file search triggered by a link.
10161 Functions added to this hook must accept a single argument, the
10162 search string that was part of the file link, the part after the
10163 double colon. The function must first check if it would like to
10164 handle this search, for example by checking the `major-mode' or
10165 the file extension. If it decides not to handle this search, it
10166 should just return nil to give other functions a chance. If it
10167 does handle the search, it must return a non-nil value to keep
10168 other functions from trying.
10170 Each function can access the current prefix argument through the
10171 variable `current-prefix-argument'. Note that a single prefix is
10172 used to force opening a link in Emacs, so it may be good to only
10173 use a numeric or double prefix to guide the search function.
10175 In case this is needed, a function in this hook can also restore
10176 the window configuration before `org-open-at-point' was called using:
10178 (set-window-configuration org-window-config-before-follow-link)")
10180 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10181 (defun org-link-search (s &optional type avoid-pos stealth)
10182 "Search for a link search option.
10183 If S is surrounded by forward slashes, it is interpreted as a
10184 regular expression. In org-mode files, this will create an `org-occur'
10185 sparse tree. In ordinary files, `occur' will be used to list matches.
10186 If the current buffer is in `dired-mode', grep will be used to search
10187 in all files. If AVOID-POS is given, ignore matches near that position.
10189 When optional argument STEALTH is non-nil, do not modify
10190 visibility around point, thus ignoring
10191 `org-show-hierarchy-above', `org-show-following-heading' and
10192 `org-show-siblings' variables."
10193 (let ((case-fold-search t)
10194 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10195 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10196 (append '(("") (" ") ("\t") ("\n"))
10197 org-emphasis-alist)
10198 "\\|") "\\)"))
10199 (pos (point))
10200 (pre nil) (post nil)
10201 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10202 (cond
10203 ;; First check if there are any special search functions
10204 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10205 ;; Now try the builtin stuff
10206 ((and (equal (string-to-char s0) ?#)
10207 (> (length s0) 1)
10208 (save-excursion
10209 (goto-char (point-min))
10210 (and
10211 (re-search-forward
10212 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10213 (setq type 'dedicated
10214 pos (match-beginning 0))))
10215 ;; There is an exact target for this
10216 (goto-char pos)
10217 (org-back-to-heading t)))
10218 ((save-excursion
10219 (goto-char (point-min))
10220 (and
10221 (re-search-forward
10222 (concat "<<" (regexp-quote s0) ">>") nil t)
10223 (setq type 'dedicated
10224 pos (match-beginning 0))))
10225 ;; There is an exact target for this
10226 (goto-char pos))
10227 ((save-excursion
10228 (goto-char (point-min))
10229 (and
10230 (re-search-forward
10231 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10232 (setq type 'dedicated pos (match-beginning 0))))
10233 ;; Found an invisible target.
10234 (goto-char pos))
10235 ((save-excursion
10236 (goto-char (point-min))
10237 (and
10238 (re-search-forward
10239 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10240 (setq type 'dedicated pos (match-beginning 0))))
10241 ;; Found an element with a matching #+name affiliated keyword.
10242 (goto-char pos))
10243 ((and (string-match "^(\\(.*\\))$" s0)
10244 (save-excursion
10245 (goto-char (point-min))
10246 (and
10247 (re-search-forward
10248 (concat "[^[]" (regexp-quote
10249 (format org-coderef-label-format
10250 (match-string 1 s0))))
10251 nil t)
10252 (setq type 'dedicated
10253 pos (1+ (match-beginning 0))))))
10254 ;; There is a coderef target for this
10255 (goto-char pos))
10256 ((string-match "^/\\(.*\\)/$" s)
10257 ;; A regular expression
10258 (cond
10259 ((derived-mode-p 'org-mode)
10260 (org-occur (match-string 1 s)))
10261 ;;((eq major-mode 'dired-mode)
10262 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10263 (t (org-do-occur (match-string 1 s)))))
10264 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10265 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10266 (goto-char (point-min))
10267 (cond
10268 ((let (case-fold-search)
10269 (re-search-forward (format org-complex-heading-regexp-format
10270 (regexp-quote s))
10271 nil t))
10272 ;; OK, found a match
10273 (setq type 'dedicated)
10274 (goto-char (match-beginning 0)))
10275 ((and (not org-link-search-inhibit-query)
10276 (eq org-link-search-must-match-exact-headline 'query-to-create)
10277 (y-or-n-p "No match - create this as a new heading? "))
10278 (goto-char (point-max))
10279 (or (bolp) (newline))
10280 (insert "* " s "\n")
10281 (beginning-of-line 0))
10283 (goto-char pos)
10284 (error "No match"))))
10286 ;; A normal search string
10287 (when (equal (string-to-char s) ?*)
10288 ;; Anchor on headlines, post may include tags.
10289 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10290 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10291 s (substring s 1)))
10292 (remove-text-properties
10293 0 (length s)
10294 '(face nil mouse-face nil keymap nil fontified nil) s)
10295 ;; Make a series of regular expressions to find a match
10296 (setq words (org-split-string s "[ \n\r\t]+")
10298 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10299 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10300 "\\)" markers)
10301 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10302 re2a (concat "[ \t\r\n]" re2a_)
10303 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10304 re4 (concat "[^a-zA-Z_]" re4_)
10306 re1 (concat pre re2 post)
10307 re3 (concat pre (if pre re4_ re4) post)
10308 re5 (concat pre ".*" re4)
10309 re2 (concat pre re2)
10310 re2a (concat pre (if pre re2a_ re2a))
10311 re4 (concat pre (if pre re4_ re4))
10312 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10313 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10314 re5 "\\)"
10316 (cond
10317 ((eq type 'org-occur) (org-occur reall))
10318 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10319 (t (goto-char (point-min))
10320 (setq type 'fuzzy)
10321 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10322 (org-search-not-self 1 re1 nil t)
10323 (org-search-not-self 1 re2 nil t)
10324 (org-search-not-self 1 re2a nil t)
10325 (org-search-not-self 1 re3 nil t)
10326 (org-search-not-self 1 re4 nil t)
10327 (org-search-not-self 1 re5 nil t)
10329 (goto-char (match-beginning 1))
10330 (goto-char pos)
10331 (error "No match"))))))
10332 (and (derived-mode-p 'org-mode)
10333 (not stealth)
10334 (org-show-context 'link-search))
10335 type))
10337 (defun org-search-not-self (group &rest args)
10338 "Execute `re-search-forward', but only accept matches that do not
10339 enclose the position of `org-open-link-marker'."
10340 (let ((m org-open-link-marker))
10341 (catch 'exit
10342 (while (apply 're-search-forward args)
10343 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10344 (goto-char (match-end group))
10345 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10346 (> (match-beginning 0) (marker-position m))
10347 (< (match-end 0) (marker-position m)))
10348 (save-match-data
10349 (or (not (org-in-regexp
10350 org-bracket-link-analytic-regexp 1))
10351 (not (match-end 4)) ; no description
10352 (and (<= (match-beginning 4) (point))
10353 (>= (match-end 4) (point))))))
10354 (throw 'exit (point))))))))
10356 (defun org-get-buffer-for-internal-link (buffer)
10357 "Return a buffer to be used for displaying the link target of internal links."
10358 (cond
10359 ((not org-display-internal-link-with-indirect-buffer)
10360 buffer)
10361 ((string-match "(Clone)$" (buffer-name buffer))
10362 (message "Buffer is already a clone, not making another one")
10363 ;; we also do not modify visibility in this case
10364 buffer)
10365 (t ; make a new indirect buffer for displaying the link
10366 (let* ((bn (buffer-name buffer))
10367 (ibn (concat bn "(Clone)"))
10368 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10369 (with-current-buffer ib (org-overview))
10370 ib))))
10372 (defun org-do-occur (regexp &optional cleanup)
10373 "Call the Emacs command `occur'.
10374 If CLEANUP is non-nil, remove the printout of the regular expression
10375 in the *Occur* buffer. This is useful if the regex is long and not useful
10376 to read."
10377 (occur regexp)
10378 (when cleanup
10379 (let ((cwin (selected-window)) win beg end)
10380 (when (setq win (get-buffer-window "*Occur*"))
10381 (select-window win))
10382 (goto-char (point-min))
10383 (when (re-search-forward "match[a-z]+" nil t)
10384 (setq beg (match-end 0))
10385 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10386 (setq end (1- (match-beginning 0)))))
10387 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10388 (goto-char (point-min))
10389 (select-window cwin))))
10391 ;;; The mark ring for links jumps
10393 (defvar org-mark-ring nil
10394 "Mark ring for positions before jumps in Org-mode.")
10395 (defvar org-mark-ring-last-goto nil
10396 "Last position in the mark ring used to go back.")
10397 ;; Fill and close the ring
10398 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10399 (loop for i from 1 to org-mark-ring-length do
10400 (push (make-marker) org-mark-ring))
10401 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10402 org-mark-ring)
10404 (defun org-mark-ring-push (&optional pos buffer)
10405 "Put the current position or POS into the mark ring and rotate it."
10406 (interactive)
10407 (setq pos (or pos (point)))
10408 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10409 (move-marker (car org-mark-ring)
10410 (or pos (point))
10411 (or buffer (current-buffer)))
10412 (message "%s"
10413 (substitute-command-keys
10414 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10416 (defun org-mark-ring-goto (&optional n)
10417 "Jump to the previous position in the mark ring.
10418 With prefix arg N, jump back that many stored positions. When
10419 called several times in succession, walk through the entire ring.
10420 Org-mode commands jumping to a different position in the current file,
10421 or to another Org-mode file, automatically push the old position
10422 onto the ring."
10423 (interactive "p")
10424 (let (p m)
10425 (if (eq last-command this-command)
10426 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10427 (setq p org-mark-ring))
10428 (setq org-mark-ring-last-goto p)
10429 (setq m (car p))
10430 (org-pop-to-buffer-same-window (marker-buffer m))
10431 (goto-char m)
10432 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10434 (defun org-remove-angle-brackets (s)
10435 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10436 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10438 (defun org-add-angle-brackets (s)
10439 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10440 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10442 (defun org-remove-double-quotes (s)
10443 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10444 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10447 ;;; Following specific links
10449 (defun org-follow-timestamp-link ()
10450 "Open an agenda view for the time-stamp date/range at point."
10451 (cond
10452 ((org-at-date-range-p t)
10453 (let ((org-agenda-start-on-weekday)
10454 (t1 (match-string 1))
10455 (t2 (match-string 2)) tt1 tt2)
10456 (setq tt1 (time-to-days (org-time-string-to-time t1))
10457 tt2 (time-to-days (org-time-string-to-time t2)))
10458 (let ((org-agenda-buffer-tmp-name
10459 (format "*Org Agenda(a:%s)"
10460 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10461 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10462 ((org-at-timestamp-p t)
10463 (let ((org-agenda-buffer-tmp-name
10464 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10465 (org-agenda-list nil (time-to-days (org-time-string-to-time
10466 (substring (match-string 1) 0 10)))
10467 1)))
10468 (t (error "This should not happen"))))
10471 ;;; Following file links
10472 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10473 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10474 (declare-function mailcap-mime-info
10475 "mailcap" (string &optional request no-decode))
10476 (defvar org-wait nil)
10477 (defun org-open-file (path &optional in-emacs line search)
10478 "Open the file at PATH.
10479 First, this expands any special file name abbreviations. Then the
10480 configuration variable `org-file-apps' is checked if it contains an
10481 entry for this file type, and if yes, the corresponding command is launched.
10483 If no application is found, Emacs simply visits the file.
10485 With optional prefix argument IN-EMACS, Emacs will visit the file.
10486 With a double \\[universal-argument] \\[universal-argument] \
10487 prefix arg, Org tries to avoid opening in Emacs
10488 and to use an external application to visit the file.
10490 Optional LINE specifies a line to go to, optional SEARCH a string
10491 to search for. If LINE or SEARCH is given, the file will be
10492 opened in Emacs, unless an entry from org-file-apps that makes
10493 use of groups in a regexp matches.
10495 If you want to change the way frames are used when following a
10496 link, please customize `org-link-frame-setup'.
10498 If the file does not exist, an error is thrown."
10499 (let* ((file (if (equal path "")
10500 buffer-file-name
10501 (substitute-in-file-name (expand-file-name path))))
10502 (file-apps (append org-file-apps (org-default-apps)))
10503 (apps (org-remove-if
10504 'org-file-apps-entry-match-against-dlink-p file-apps))
10505 (apps-dlink (org-remove-if-not
10506 'org-file-apps-entry-match-against-dlink-p file-apps))
10507 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10508 (dirp (if remp nil (file-directory-p file)))
10509 (file (if (and dirp org-open-directory-means-index-dot-org)
10510 (concat (file-name-as-directory file) "index.org")
10511 file))
10512 (a-m-a-p (assq 'auto-mode apps))
10513 (dfile (downcase file))
10514 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10515 (link (cond ((and (eq line nil)
10516 (eq search nil))
10517 file)
10518 (line
10519 (concat file "::" (number-to-string line)))
10520 (search
10521 (concat file "::" search))))
10522 (dlink (downcase link))
10523 (old-buffer (current-buffer))
10524 (old-pos (point))
10525 (old-mode major-mode)
10526 ext cmd link-match-data)
10527 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10528 (setq ext (match-string 1 dfile))
10529 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10530 (setq ext (match-string 1 dfile))))
10531 (cond
10532 ((member in-emacs '((16) system))
10533 (setq cmd (cdr (assoc 'system apps))))
10534 (in-emacs (setq cmd 'emacs))
10536 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10537 (and dirp (cdr (assoc 'directory apps)))
10538 ; first, try matching against apps-dlink
10539 ; if we get a match here, store the match data for later
10540 (let ((match (assoc-default dlink apps-dlink
10541 'string-match)))
10542 (if match
10543 (progn (setq link-match-data (match-data))
10544 match)
10545 (progn (setq in-emacs (or in-emacs line search))
10546 nil))) ; if we have no match in apps-dlink,
10547 ; always open the file in emacs if line or search
10548 ; is given (for backwards compatibility)
10549 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10550 'string-match)
10551 (cdr (assoc ext apps))
10552 (cdr (assoc t apps))))))
10553 (when (eq cmd 'system)
10554 (setq cmd (cdr (assoc 'system apps))))
10555 (when (eq cmd 'default)
10556 (setq cmd (cdr (assoc t apps))))
10557 (when (eq cmd 'mailcap)
10558 (require 'mailcap)
10559 (mailcap-parse-mailcaps)
10560 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10561 (command (mailcap-mime-info mime-type)))
10562 (if (stringp command)
10563 (setq cmd command)
10564 (setq cmd 'emacs))))
10565 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10566 (not (file-exists-p file))
10567 (not org-open-non-existing-files))
10568 (error "No such file: %s" file))
10569 (cond
10570 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10571 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10572 (while (string-match "['\"]%s['\"]" cmd)
10573 (setq cmd (replace-match "%s" t t cmd)))
10574 (while (string-match "%s" cmd)
10575 (setq cmd (replace-match
10576 (save-match-data
10577 (shell-quote-argument
10578 (convert-standard-filename file)))
10579 t t cmd)))
10581 ;; Replace "%1", "%2" etc. in command with group matches from regex
10582 (save-match-data
10583 (let ((match-index 1)
10584 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10585 (set-match-data link-match-data)
10586 (while (<= match-index number-of-groups)
10587 (let ((regex (concat "%" (number-to-string match-index)))
10588 (replace-with (match-string match-index dlink)))
10589 (while (string-match regex cmd)
10590 (setq cmd (replace-match replace-with t t cmd))))
10591 (setq match-index (+ match-index 1)))))
10593 (save-window-excursion
10594 (message "Running %s...done" cmd)
10595 (start-process-shell-command cmd nil cmd)
10596 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10597 ((or (stringp cmd)
10598 (eq cmd 'emacs))
10599 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10600 (widen)
10601 (if line (org-goto-line line)
10602 (if search (org-link-search search))))
10603 ((consp cmd)
10604 (let ((file (convert-standard-filename file)))
10605 (save-match-data
10606 (set-match-data link-match-data)
10607 (eval cmd))))
10608 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10609 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10610 (or (not (equal old-buffer (current-buffer)))
10611 (not (equal old-pos (point))))
10612 (org-mark-ring-push old-pos old-buffer))))
10614 (defun org-file-apps-entry-match-against-dlink-p (entry)
10615 "This function returns non-nil if `entry' uses a regular
10616 expression which should be matched against the whole link by
10617 org-open-file.
10619 It assumes that is the case when the entry uses a regular
10620 expression which has at least one grouping construct and the
10621 action is either a lisp form or a command string containing
10622 '%1', i.e. using at least one subexpression match as a
10623 parameter."
10624 (let ((selector (car entry))
10625 (action (cdr entry)))
10626 (if (stringp selector)
10627 (and (> (regexp-opt-depth selector) 0)
10628 (or (and (stringp action)
10629 (string-match "%[0-9]" action))
10630 (consp action)))
10631 nil)))
10633 (defun org-default-apps ()
10634 "Return the default applications for this operating system."
10635 (cond
10636 ((eq system-type 'darwin)
10637 org-file-apps-defaults-macosx)
10638 ((eq system-type 'windows-nt)
10639 org-file-apps-defaults-windowsnt)
10640 (t org-file-apps-defaults-gnu)))
10642 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10643 "Convert extensions to regular expressions in the cars of LIST.
10644 Also, weed out any non-string entries, because the return value is used
10645 only for regexp matching.
10646 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10647 point to the symbol `emacs', indicating that the file should
10648 be opened in Emacs."
10649 (append
10650 (delq nil
10651 (mapcar (lambda (x)
10652 (if (not (stringp (car x)))
10654 (if (string-match "\\W" (car x))
10656 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10657 list))
10658 (if add-auto-mode
10659 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10661 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10662 (defun org-file-remote-p (file)
10663 "Test whether FILE specifies a location on a remote system.
10664 Return non-nil if the location is indeed remote.
10666 For example, the filename \"/user@host:/foo\" specifies a location
10667 on the system \"/user@host:\"."
10668 (cond ((fboundp 'file-remote-p)
10669 (file-remote-p file))
10670 ((fboundp 'tramp-handle-file-remote-p)
10671 (tramp-handle-file-remote-p file))
10672 ((and (boundp 'ange-ftp-name-format)
10673 (string-match (car ange-ftp-name-format) file))
10674 t)))
10677 ;;;; Refiling
10679 (defun org-get-org-file ()
10680 "Read a filename, with default directory `org-directory'."
10681 (let ((default (or org-default-notes-file remember-data-file)))
10682 (read-file-name (format "File name [%s]: " default)
10683 (file-name-as-directory org-directory)
10684 default)))
10686 (defun org-notes-order-reversed-p ()
10687 "Check if the current file should receive notes in reversed order."
10688 (cond
10689 ((not org-reverse-note-order) nil)
10690 ((eq t org-reverse-note-order) t)
10691 ((not (listp org-reverse-note-order)) nil)
10692 (t (catch 'exit
10693 (let ((all org-reverse-note-order)
10694 entry)
10695 (while (setq entry (pop all))
10696 (if (string-match (car entry) buffer-file-name)
10697 (throw 'exit (cdr entry))))
10698 nil)))))
10700 (defvar org-refile-target-table nil
10701 "The list of refile targets, created by `org-refile'.")
10703 (defvar org-agenda-new-buffers nil
10704 "Buffers created to visit agenda files.")
10706 (defvar org-refile-cache nil
10707 "Cache for refile targets.")
10709 (defvar org-refile-markers nil
10710 "All the markers used for caching refile locations.")
10712 (defun org-refile-marker (pos)
10713 "Get a new refile marker, but only if caching is in use."
10714 (if (not org-refile-use-cache)
10716 (let ((m (make-marker)))
10717 (move-marker m pos)
10718 (push m org-refile-markers)
10719 m)))
10721 (defun org-refile-cache-clear ()
10722 "Clear the refile cache and disable all the markers."
10723 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10724 (setq org-refile-markers nil)
10725 (setq org-refile-cache nil)
10726 (message "Refile cache has been cleared"))
10728 (defun org-refile-cache-check-set (set)
10729 "Check if all the markers in the cache still have live buffers."
10730 (let (marker)
10731 (catch 'exit
10732 (while (and set (setq marker (nth 3 (pop set))))
10733 ;; if org-refile-use-outline-path is 'file, marker may be nil
10734 (when (and marker (null (marker-buffer marker)))
10735 (message "not found") (sit-for 3)
10736 (throw 'exit nil)))
10737 t)))
10739 (defun org-refile-cache-put (set &rest identifiers)
10740 "Push the refile targets SET into the cache, under IDENTIFIERS."
10741 (let* ((key (sha1 (prin1-to-string identifiers)))
10742 (entry (assoc key org-refile-cache)))
10743 (if entry
10744 (setcdr entry set)
10745 (push (cons key set) org-refile-cache))))
10747 (defun org-refile-cache-get (&rest identifiers)
10748 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10749 (cond
10750 ((not org-refile-cache) nil)
10751 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10753 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10754 org-refile-cache))))
10755 (and set (org-refile-cache-check-set set) set)))))
10757 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10758 "Produce a table with refile targets."
10759 (let ((case-fold-search nil)
10760 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10761 (entries (or org-refile-targets '((nil . (:level . 1)))))
10762 targets tgs txt re files f desc descre fast-path-p level pos0)
10763 (message "Getting targets...")
10764 (with-current-buffer (or default-buffer (current-buffer))
10765 (while (setq entry (pop entries))
10766 (setq files (car entry) desc (cdr entry))
10767 (setq fast-path-p nil)
10768 (cond
10769 ((null files) (setq files (list (current-buffer))))
10770 ((eq files 'org-agenda-files)
10771 (setq files (org-agenda-files 'unrestricted)))
10772 ((and (symbolp files) (fboundp files))
10773 (setq files (funcall files)))
10774 ((and (symbolp files) (boundp files))
10775 (setq files (symbol-value files))))
10776 (if (stringp files) (setq files (list files)))
10777 (cond
10778 ((eq (car desc) :tag)
10779 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10780 ((eq (car desc) :todo)
10781 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10782 ((eq (car desc) :regexp)
10783 (setq descre (cdr desc)))
10784 ((eq (car desc) :level)
10785 (setq descre (concat "^\\*\\{" (number-to-string
10786 (if org-odd-levels-only
10787 (1- (* 2 (cdr desc)))
10788 (cdr desc)))
10789 "\\}[ \t]")))
10790 ((eq (car desc) :maxlevel)
10791 (setq fast-path-p t)
10792 (setq descre (concat "^\\*\\{1," (number-to-string
10793 (if org-odd-levels-only
10794 (1- (* 2 (cdr desc)))
10795 (cdr desc)))
10796 "\\}[ \t]")))
10797 (t (error "Bad refiling target description %s" desc)))
10798 (while (setq f (pop files))
10799 (with-current-buffer
10800 (if (bufferp f) f (org-get-agenda-file-buffer f))
10802 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10803 (progn
10804 (if (bufferp f) (setq f (buffer-file-name
10805 (buffer-base-buffer f))))
10806 (setq f (and f (expand-file-name f)))
10807 (if (eq org-refile-use-outline-path 'file)
10808 (push (list (file-name-nondirectory f) f nil nil) tgs))
10809 (save-excursion
10810 (save-restriction
10811 (widen)
10812 (goto-char (point-min))
10813 (while (re-search-forward descre nil t)
10814 (goto-char (setq pos0 (point-at-bol)))
10815 (catch 'next
10816 (when org-refile-target-verify-function
10817 (save-match-data
10818 (or (funcall org-refile-target-verify-function)
10819 (throw 'next t))))
10820 (when (and (looking-at org-complex-heading-regexp)
10821 (not (member (match-string 4) excluded-entries))
10822 (match-string 4))
10823 (setq level (org-reduced-level
10824 (- (match-end 1) (match-beginning 1)))
10825 txt (org-link-display-format (match-string 4))
10826 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10827 re (format org-complex-heading-regexp-format
10828 (regexp-quote (match-string 4))))
10829 (when org-refile-use-outline-path
10830 (setq txt (mapconcat
10831 'org-protect-slash
10832 (append
10833 (if (eq org-refile-use-outline-path
10834 'file)
10835 (list (file-name-nondirectory
10836 (buffer-file-name
10837 (buffer-base-buffer))))
10838 (if (eq org-refile-use-outline-path
10839 'full-file-path)
10840 (list (buffer-file-name
10841 (buffer-base-buffer)))))
10842 (org-get-outline-path fast-path-p
10843 level txt)
10844 (list txt))
10845 "/")))
10846 (push (list txt f re (org-refile-marker (point)))
10847 tgs)))
10848 (when (= (point) pos0)
10849 ;; verification function has not moved point
10850 (goto-char (point-at-eol))))))))
10851 (when org-refile-use-cache
10852 (org-refile-cache-put tgs (buffer-file-name) descre))
10853 (setq targets (append tgs targets))
10854 ))))
10855 (message "Getting targets...done")
10856 (nreverse targets)))
10858 (defun org-protect-slash (s)
10859 (while (string-match "/" s)
10860 (setq s (replace-match "\\" t t s)))
10863 (defvar org-olpa (make-vector 20 nil))
10865 (defun org-get-outline-path (&optional fastp level heading)
10866 "Return the outline path to the current entry, as a list.
10868 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10869 routine which makes outline path derivations for an entire file,
10870 avoiding backtracing. Refile target collection makes use of that."
10871 (if fastp
10872 (progn
10873 (if (> level 19)
10874 (error "Outline path failure, more than 19 levels"))
10875 (loop for i from level upto 19 do
10876 (aset org-olpa i nil))
10877 (prog1
10878 (delq nil (append org-olpa nil))
10879 (aset org-olpa level heading)))
10880 (let (rtn case-fold-search)
10881 (save-excursion
10882 (save-restriction
10883 (widen)
10884 (while (org-up-heading-safe)
10885 (when (looking-at org-complex-heading-regexp)
10886 (push (org-match-string-no-properties 4) rtn)))
10887 rtn)))))
10889 (defun org-format-outline-path (path &optional width prefix separator)
10890 "Format the outline path PATH for display.
10891 WIDTH is the maximum number of characters that is available.
10892 PREFIX is a prefix to be included in the returned string,
10893 such as the file name.
10894 SEPARATOR is inserted between the different parts of the path,
10895 the default is \"/\"."
10896 (setq width (or width 79))
10897 (if prefix (setq width (- width (length prefix))))
10898 (if (not path)
10899 (or prefix "")
10900 (let* ((nsteps (length path))
10901 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10902 (maxwidth (if (<= total-width width)
10903 10000 ;; everything fits
10904 ;; we need to shorten the level headings
10905 (/ (- width nsteps) nsteps)))
10906 (org-odd-levels-only nil)
10907 (n 0)
10908 (total (1+ (length prefix))))
10909 (setq maxwidth (max maxwidth 10))
10910 (concat prefix
10911 (if prefix (or separator "/"))
10912 (mapconcat
10913 (lambda (h)
10914 (setq n (1+ n))
10915 (if (and (= n nsteps) (< maxwidth 10000))
10916 (setq maxwidth (- total-width total)))
10917 (if (< (length h) maxwidth)
10918 (progn (setq total (+ total (length h) 1)) h)
10919 (setq h (substring h 0 (- maxwidth 2))
10920 total (+ total maxwidth 1))
10921 (if (string-match "[ \t]+\\'" h)
10922 (setq h (substring h 0 (match-beginning 0))))
10923 (setq h (concat h "..")))
10924 (org-add-props h nil 'face
10925 (nth (% (1- n) org-n-level-faces)
10926 org-level-faces))
10928 path (or separator "/"))))))
10930 (defun org-display-outline-path (&optional file current separator just-return-string)
10931 "Display the current outline path in the echo area.
10933 If FILE is non-nil, prepend the output with the file name.
10934 If CURRENT is non-nil, append the current heading to the output.
10935 SEPARATOR is passed through to `org-format-outline-path'. It separates
10936 the different parts of the path and defaults to \"/\".
10937 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10938 (interactive "P")
10939 (let* (case-fold-search
10940 message-log-max ; Don't populate the *Messages* buffer
10941 (bfn (buffer-file-name (buffer-base-buffer)))
10942 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10943 res)
10944 (if current (setq path (append path
10945 (save-excursion
10946 (org-back-to-heading t)
10947 (if (looking-at org-complex-heading-regexp)
10948 (list (match-string 4)))))))
10949 (setq res
10950 (org-format-outline-path
10951 path
10952 (1- (frame-width))
10953 (and file bfn (concat (file-name-nondirectory bfn) separator))
10954 separator))
10955 (if just-return-string
10956 (org-no-properties res)
10957 (message "%s" res))))
10959 (defvar org-refile-history nil
10960 "History for refiling operations.")
10962 (defvar org-after-refile-insert-hook nil
10963 "Hook run after `org-refile' has inserted its stuff at the new location.
10964 Note that this is still *before* the stuff will be removed from
10965 the *old* location.")
10967 (defvar org-capture-last-stored-marker)
10968 (defvar org-refile-keep nil
10969 "Non-nil means `org-refile' will copy instead of refile.")
10971 (defun org-copy ()
10972 "Like `org-refile', but copy."
10973 (interactive)
10974 (let ((org-refile-keep t))
10975 (funcall 'org-refile nil nil nil "Copy")))
10977 (defun org-refile (&optional goto default-buffer rfloc msg)
10978 "Move the entry or entries at point to another heading.
10979 The list of target headings is compiled using the information in
10980 `org-refile-targets', which see.
10982 At the target location, the entry is filed as a subitem of the target
10983 heading. Depending on `org-reverse-note-order', the new subitem will
10984 either be the first or the last subitem.
10986 If there is an active region, all entries in that region will be moved.
10987 However, the region must fulfill the requirement that the first heading
10988 is the first one sets the top-level of the moved text - at most siblings
10989 below it are allowed.
10991 With prefix arg GOTO, the command will only visit the target location
10992 and not actually move anything.
10994 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10995 go to the location where the last refiling operation has put the subtree.
10996 With a prefix argument of `2', refile to the running clock.
10998 RFLOC can be a refile location obtained in a different way.
11000 MSG is a string to replace \"Refile\" in the default prompt with
11001 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11003 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11005 If you are using target caching (see `org-refile-use-cache'),
11006 you have to clear the target cache in order to find new targets.
11007 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11008 prefix argument (`C-u C-u C-u C-c C-w')."
11010 (interactive "P")
11011 (if (member goto '(0 (64)))
11012 (org-refile-cache-clear)
11013 (let* ((actionmsg (or msg "Refile"))
11014 (cbuf (current-buffer))
11015 (regionp (org-region-active-p))
11016 (region-start (and regionp (region-beginning)))
11017 (region-end (and regionp (region-end)))
11018 (region-length (and regionp (- region-end region-start)))
11019 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11020 pos it nbuf file re level reversed)
11021 (setq last-command nil)
11022 (when regionp
11023 (goto-char region-start)
11024 (or (bolp) (goto-char (point-at-bol)))
11025 (setq region-start (point))
11026 (unless (or (org-kill-is-subtree-p
11027 (buffer-substring region-start region-end))
11028 (prog1 org-refile-active-region-within-subtree
11029 (org-toggle-heading)))
11030 (error "The region is not a (sequence of) subtree(s)")))
11031 (if (equal goto '(16))
11032 (org-refile-goto-last-stored)
11033 (when (or
11034 (and (equal goto 2)
11035 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11036 (prog1
11037 (setq it (list (or org-clock-heading "running clock")
11038 (buffer-file-name
11039 (marker-buffer org-clock-hd-marker))
11041 (marker-position org-clock-hd-marker)))
11042 (setq goto nil)))
11043 (setq it (or rfloc
11044 (let (heading-text)
11045 (save-excursion
11046 (unless goto
11047 (org-back-to-heading t)
11048 (setq heading-text
11049 (nth 4 (org-heading-components))))
11051 (org-refile-get-location
11052 (cond (goto "Goto")
11053 (regionp (concat actionmsg " region to"))
11054 (t (concat actionmsg " subtree \""
11055 heading-text "\" to")))
11056 default-buffer
11057 (and (not (equal '(4) goto))
11058 org-refile-allow-creating-parent-nodes)
11059 goto))))))
11060 (setq file (nth 1 it)
11061 re (nth 2 it)
11062 pos (nth 3 it))
11063 (if (and (not goto)
11065 (equal (buffer-file-name) file)
11066 (if regionp
11067 (and (>= pos region-start)
11068 (<= pos region-end))
11069 (and (>= pos (point))
11070 (< pos (save-excursion
11071 (org-end-of-subtree t t))))))
11072 (error "Cannot refile to position inside the tree or region"))
11074 (setq nbuf (or (find-buffer-visiting file)
11075 (find-file-noselect file)))
11076 (if goto
11077 (progn
11078 (org-pop-to-buffer-same-window nbuf)
11079 (goto-char pos)
11080 (org-show-context 'org-goto))
11081 (if regionp
11082 (progn
11083 (org-kill-new (buffer-substring region-start region-end))
11084 (org-save-markers-in-region region-start region-end))
11085 (org-copy-subtree 1 nil t))
11086 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11087 (find-file-noselect file)))
11088 (setq reversed (org-notes-order-reversed-p))
11089 (save-excursion
11090 (save-restriction
11091 (widen)
11092 (if pos
11093 (progn
11094 (goto-char pos)
11095 (looking-at org-outline-regexp)
11096 (setq level (org-get-valid-level (funcall outline-level) 1))
11097 (goto-char
11098 (if reversed
11099 (or (outline-next-heading) (point-max))
11100 (or (save-excursion (org-get-next-sibling))
11101 (org-end-of-subtree t t)
11102 (point-max)))))
11103 (setq level 1)
11104 (if (not reversed)
11105 (goto-char (point-max))
11106 (goto-char (point-min))
11107 (or (outline-next-heading) (goto-char (point-max)))))
11108 (if (not (bolp)) (newline))
11109 (org-paste-subtree level)
11110 (when org-log-refile
11111 (org-add-log-setup 'refile nil nil 'findpos
11112 org-log-refile)
11113 (unless (eq org-log-refile 'note)
11114 (save-excursion (org-add-log-note))))
11115 (and org-auto-align-tags
11116 (let ((org-loop-over-headlines-in-active-region nil))
11117 (org-set-tags nil t)))
11118 (with-demoted-errors
11119 (bookmark-set "org-refile-last-stored"))
11120 ;; If we are refiling for capture, make sure that the
11121 ;; last-capture pointers point here
11122 (when (org-bound-and-true-p org-refile-for-capture)
11123 (with-demoted-errors
11124 (bookmark-set "org-capture-last-stored-marker"))
11125 (move-marker org-capture-last-stored-marker (point)))
11126 (if (fboundp 'deactivate-mark) (deactivate-mark))
11127 (run-hooks 'org-after-refile-insert-hook))))
11128 (unless org-refile-keep
11129 (if regionp
11130 (delete-region (point) (+ (point) region-length))
11131 (org-cut-subtree)))
11132 (when (featurep 'org-inlinetask)
11133 (org-inlinetask-remove-END-maybe))
11134 (setq org-markers-to-move nil)
11135 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11137 (defun org-refile-goto-last-stored ()
11138 "Go to the location where the last refile was stored."
11139 (interactive)
11140 (bookmark-jump "org-refile-last-stored")
11141 (message "This is the location of the last refile"))
11143 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11144 no-exclude)
11145 "Prompt the user for a refile location, using PROMPT.
11146 PROMPT should not be suffixed with a colon and a space, because
11147 this function appends the default value from
11148 `org-refile-history' automatically, if that is not empty.
11149 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11150 this is used for the GOTO interface."
11151 (let ((org-refile-targets org-refile-targets)
11152 (org-refile-use-outline-path org-refile-use-outline-path)
11153 excluded-entries)
11154 (when (and (derived-mode-p 'org-mode)
11155 (not org-refile-use-cache)
11156 (not no-exclude))
11157 (org-map-tree
11158 (lambda()
11159 (setq excluded-entries
11160 (append excluded-entries (list (org-get-heading t t)))))))
11161 (setq org-refile-target-table
11162 (org-refile-get-targets default-buffer excluded-entries)))
11163 (unless org-refile-target-table
11164 (error "No refile targets"))
11165 (let* ((cbuf (current-buffer))
11166 (partial-completion-mode nil)
11167 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11168 (cfunc (if (and org-refile-use-outline-path
11169 org-outline-path-complete-in-steps)
11170 'org-olpath-completing-read
11171 'org-icompleting-read))
11172 (extra (if org-refile-use-outline-path "/" ""))
11173 (cbnex (concat (buffer-name) extra))
11174 (filename (and cfn (expand-file-name cfn)))
11175 (tbl (mapcar
11176 (lambda (x)
11177 (if (and (not (member org-refile-use-outline-path
11178 '(file full-file-path)))
11179 (not (equal filename (nth 1 x))))
11180 (cons (concat (car x) extra " ("
11181 (file-name-nondirectory (nth 1 x)) ")")
11182 (cdr x))
11183 (cons (concat (car x) extra) (cdr x))))
11184 org-refile-target-table))
11185 (completion-ignore-case t)
11186 cdef
11187 (prompt (concat prompt
11188 (or (and (car org-refile-history)
11189 (concat " (default " (car org-refile-history) ")"))
11190 (and (assoc cbnex tbl) (setq cdef cbnex)
11191 (concat " (default " cbnex ")"))) ": "))
11192 pa answ parent-target child parent old-hist)
11193 (setq old-hist org-refile-history)
11194 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11195 nil 'org-refile-history (or cdef (car org-refile-history))))
11196 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11197 (org-refile-check-position pa)
11198 (if pa
11199 (progn
11200 (when (or (not org-refile-history)
11201 (not (eq old-hist org-refile-history))
11202 (not (equal (car pa) (car org-refile-history))))
11203 (setq org-refile-history
11204 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11205 org-refile-history
11206 (cdr org-refile-history))))
11207 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11208 (pop org-refile-history)))
11210 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11211 (progn
11212 (setq parent (match-string 1 answ)
11213 child (match-string 2 answ))
11214 (setq parent-target (or (assoc parent tbl)
11215 (assoc (concat parent "/") tbl)))
11216 (when (and parent-target
11217 (or (eq new-nodes t)
11218 (and (eq new-nodes 'confirm)
11219 (y-or-n-p (format "Create new node \"%s\"? "
11220 child)))))
11221 (org-refile-new-child parent-target child)))
11222 (error "Invalid target location")))))
11224 (declare-function org-string-nw-p "org-macs" (s))
11225 (defun org-refile-check-position (refile-pointer)
11226 "Check if the refile pointer matches the headline to which it points."
11227 (let* ((file (nth 1 refile-pointer))
11228 (re (nth 2 refile-pointer))
11229 (pos (nth 3 refile-pointer))
11230 buffer)
11231 (if (and (not (markerp pos)) (not file))
11232 (error "Please save the buffer to a file before refiling")
11233 (when (org-string-nw-p re)
11234 (setq buffer (if (markerp pos)
11235 (marker-buffer pos)
11236 (or (find-buffer-visiting file)
11237 (find-file-noselect file))))
11238 (with-current-buffer buffer
11239 (save-excursion
11240 (save-restriction
11241 (widen)
11242 (goto-char pos)
11243 (beginning-of-line 1)
11244 (unless (org-looking-at-p re)
11245 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11247 (defun org-refile-new-child (parent-target child)
11248 "Use refile target PARENT-TARGET to add new CHILD below it."
11249 (unless parent-target
11250 (error "Cannot find parent for new node"))
11251 (let ((file (nth 1 parent-target))
11252 (pos (nth 3 parent-target))
11253 level)
11254 (with-current-buffer (or (find-buffer-visiting file)
11255 (find-file-noselect file))
11256 (save-excursion
11257 (save-restriction
11258 (widen)
11259 (if pos
11260 (goto-char pos)
11261 (goto-char (point-max))
11262 (if (not (bolp)) (newline)))
11263 (when (looking-at org-outline-regexp)
11264 (setq level (funcall outline-level))
11265 (org-end-of-subtree t t))
11266 (org-back-over-empty-lines)
11267 (insert "\n" (make-string
11268 (if pos (org-get-valid-level level 1) 1) ?*)
11269 " " child "\n")
11270 (beginning-of-line 0)
11271 (list (concat (car parent-target) "/" child) file "" (point)))))))
11273 (defun org-olpath-completing-read (prompt collection &rest args)
11274 "Read an outline path like a file name."
11275 (let ((thetable collection)
11276 (org-completion-use-ido nil) ; does not work with ido.
11277 (org-completion-use-iswitchb nil)) ; or iswitchb
11278 (apply
11279 'org-icompleting-read prompt
11280 (lambda (string predicate &optional flag)
11281 (let (rtn r f (l (length string)))
11282 (cond
11283 ((eq flag nil)
11284 ;; try completion
11285 (try-completion string thetable))
11286 ((eq flag t)
11287 ;; all-completions
11288 (setq rtn (all-completions string thetable predicate))
11289 (mapcar
11290 (lambda (x)
11291 (setq r (substring x l))
11292 (if (string-match " ([^)]*)$" x)
11293 (setq f (match-string 0 x))
11294 (setq f ""))
11295 (if (string-match "/" r)
11296 (concat string (substring r 0 (match-end 0)) f)
11298 rtn))
11299 ((eq flag 'lambda)
11300 ;; exact match?
11301 (assoc string thetable)))))
11302 args)))
11304 ;;;; Dynamic blocks
11306 (defun org-find-dblock (name)
11307 "Find the first dynamic block with name NAME in the buffer.
11308 If not found, stay at current position and return nil."
11309 (let ((case-fold-search t) pos)
11310 (save-excursion
11311 (goto-char (point-min))
11312 (setq pos (and (re-search-forward
11313 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11314 (match-beginning 0))))
11315 (if pos (goto-char pos))
11316 pos))
11318 (defconst org-dblock-start-re
11319 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11320 "Matches the start line of a dynamic block, with parameters.")
11322 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11323 "Matches the end of a dynamic block.")
11325 (defun org-create-dblock (plist)
11326 "Create a dynamic block section, with parameters taken from PLIST.
11327 PLIST must contain a :name entry which is used as name of the block."
11328 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11329 (end-of-line 1)
11330 (newline))
11331 (let ((col (current-column))
11332 (name (plist-get plist :name)))
11333 (insert "#+BEGIN: " name)
11334 (while plist
11335 (if (eq (car plist) :name)
11336 (setq plist (cddr plist))
11337 (insert " " (prin1-to-string (pop plist)))))
11338 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11339 (beginning-of-line -2)))
11341 (defun org-prepare-dblock ()
11342 "Prepare dynamic block for refresh.
11343 This empties the block, puts the cursor at the insert position and returns
11344 the property list including an extra property :name with the block name."
11345 (unless (looking-at org-dblock-start-re)
11346 (error "Not at a dynamic block"))
11347 (let* ((begdel (1+ (match-end 0)))
11348 (name (org-no-properties (match-string 1)))
11349 (params (append (list :name name)
11350 (read (concat "(" (match-string 3) ")")))))
11351 (save-excursion
11352 (beginning-of-line 1)
11353 (skip-chars-forward " \t")
11354 (setq params (plist-put params :indentation-column (current-column))))
11355 (unless (re-search-forward org-dblock-end-re nil t)
11356 (error "Dynamic block not terminated"))
11357 (setq params
11358 (append params
11359 (list :content (buffer-substring
11360 begdel (match-beginning 0)))))
11361 (delete-region begdel (match-beginning 0))
11362 (goto-char begdel)
11363 (open-line 1)
11364 params))
11366 (defun org-map-dblocks (&optional command)
11367 "Apply COMMAND to all dynamic blocks in the current buffer.
11368 If COMMAND is not given, use `org-update-dblock'."
11369 (let ((cmd (or command 'org-update-dblock)))
11370 (save-excursion
11371 (goto-char (point-min))
11372 (while (re-search-forward org-dblock-start-re nil t)
11373 (goto-char (match-beginning 0))
11374 (save-excursion
11375 (condition-case nil
11376 (funcall cmd)
11377 (error (message "Error during update of dynamic block"))))
11378 (unless (re-search-forward org-dblock-end-re nil t)
11379 (error "Dynamic block not terminated"))))))
11381 (defun org-dblock-update (&optional arg)
11382 "User command for updating dynamic blocks.
11383 Update the dynamic block at point. With prefix ARG, update all dynamic
11384 blocks in the buffer."
11385 (interactive "P")
11386 (if arg
11387 (org-update-all-dblocks)
11388 (or (looking-at org-dblock-start-re)
11389 (org-beginning-of-dblock))
11390 (org-update-dblock)))
11392 (defun org-update-dblock ()
11393 "Update the dynamic block at point.
11394 This means to empty the block, parse for parameters and then call
11395 the correct writing function."
11396 (interactive)
11397 (save-window-excursion
11398 (let* ((pos (point))
11399 (line (org-current-line))
11400 (params (org-prepare-dblock))
11401 (name (plist-get params :name))
11402 (indent (plist-get params :indentation-column))
11403 (cmd (intern (concat "org-dblock-write:" name))))
11404 (message "Updating dynamic block `%s' at line %d..." name line)
11405 (funcall cmd params)
11406 (message "Updating dynamic block `%s' at line %d...done" name line)
11407 (goto-char pos)
11408 (when (and indent (> indent 0))
11409 (setq indent (make-string indent ?\ ))
11410 (save-excursion
11411 (org-beginning-of-dblock)
11412 (forward-line 1)
11413 (while (not (looking-at org-dblock-end-re))
11414 (insert indent)
11415 (beginning-of-line 2))
11416 (when (looking-at org-dblock-end-re)
11417 (and (looking-at "[ \t]+")
11418 (replace-match ""))
11419 (insert indent)))))))
11421 (defun org-beginning-of-dblock ()
11422 "Find the beginning of the dynamic block at point.
11423 Error if there is no such block at point."
11424 (let ((pos (point))
11425 beg)
11426 (end-of-line 1)
11427 (if (and (re-search-backward org-dblock-start-re nil t)
11428 (setq beg (match-beginning 0))
11429 (re-search-forward org-dblock-end-re nil t)
11430 (> (match-end 0) pos))
11431 (goto-char beg)
11432 (goto-char pos)
11433 (error "Not in a dynamic block"))))
11435 (defun org-update-all-dblocks ()
11436 "Update all dynamic blocks in the buffer.
11437 This function can be used in a hook."
11438 (interactive)
11439 (when (derived-mode-p 'org-mode)
11440 (org-map-dblocks 'org-update-dblock)))
11443 ;;;; Completion
11445 (defconst org-additional-option-like-keywords
11446 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11447 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11448 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11449 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11450 "BEGIN:" "END:"
11451 "ORGTBL" "TBLFM:" "TBLNAME:"
11452 "BEGIN_EXAMPLE" "END_EXAMPLE"
11453 "BEGIN_VERBATIM" "END_VERBATIM"
11454 "BEGIN_QUOTE" "END_QUOTE"
11455 "BEGIN_VERSE" "END_VERSE"
11456 "BEGIN_CENTER" "END_CENTER"
11457 "BEGIN_SRC" "END_SRC"
11458 "BEGIN_RESULT" "END_RESULT"
11459 "BEGIN_lstlisting" "END_lstlisting"
11460 "NAME:" "RESULTS:"
11461 "HEADER:" "HEADERS:"
11462 "COLUMNS:" "PROPERTY:"
11463 "CAPTION:" "LABEL:"
11464 "SETUPFILE:"
11465 "INCLUDE:" "INDEX:"
11466 "BIND:"
11467 "MACRO:"))
11469 (defconst org-options-keywords
11470 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11471 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11472 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11473 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11474 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11475 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11476 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11478 (defconst org-additional-option-like-keywords-for-flyspell
11479 (delete-dups
11480 (split-string
11481 (mapconcat (lambda(k)
11482 (replace-regexp-in-string
11483 "_\\|:" " "
11484 (concat k " " (downcase k) " " (upcase k))))
11485 (append org-options-keywords org-additional-option-like-keywords)
11486 " ")
11487 " +" t)))
11489 (defcustom org-structure-template-alist
11490 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11491 "<src lang=\"?\">\n\n</src>")
11492 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11493 "<example>\n?\n</example>")
11494 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11495 "<quote>\n?\n</quote>")
11496 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11497 "<verse>\n?\n</verse>")
11498 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11499 "<verbatim>\n?\n</verbatim>")
11500 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11501 "<center>\n?\n</center>")
11502 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11503 "<literal style=\"latex\">\n?\n</literal>")
11504 ("L" "#+LaTeX: "
11505 "<literal style=\"latex\">?</literal>")
11506 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11507 "<literal style=\"html\">\n?\n</literal>")
11508 ("H" "#+HTML: "
11509 "<literal style=\"html\">?</literal>")
11510 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11511 ("A" "#+ASCII: ")
11512 ("i" "#+INDEX: ?"
11513 "#+INDEX: ?")
11514 ("I" "#+INCLUDE: %file ?"
11515 "<include file=%file markup=\"?\">"))
11516 "Structure completion elements.
11517 This is a list of abbreviation keys and values. The value gets inserted
11518 if you type `<' followed by the key and then press the completion key,
11519 usually `M-TAB'. %file will be replaced by a file name after prompting
11520 for the file using completion. The cursor will be placed at the position
11521 of the `?` in the template.
11522 There are two templates for each key, the first uses the original Org syntax,
11523 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11524 the default when the /org-mtags.el/ module has been loaded. See also the
11525 variable `org-mtags-prefer-muse-templates'."
11526 :group 'org-completion
11527 :type '(repeat
11528 (string :tag "Key")
11529 (string :tag "Template")
11530 (string :tag "Muse Template")))
11532 (defun org-try-structure-completion ()
11533 "Try to complete a structure template before point.
11534 This looks for strings like \"<e\" on an otherwise empty line and
11535 expands them."
11536 (let ((l (buffer-substring (point-at-bol) (point)))
11538 (when (and (looking-at "[ \t]*$")
11539 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11540 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11541 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11542 (match-beginning 1)) a)
11543 t)))
11545 (defun org-complete-expand-structure-template (start cell)
11546 "Expand a structure template."
11547 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11548 (rpl (nth (if musep 2 1) cell))
11549 (ind ""))
11550 (delete-region start (point))
11551 (when (string-match "\\`#\\+" rpl)
11552 (cond
11553 ((bolp))
11554 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11555 (setq ind (buffer-substring (point-at-bol) (point))))
11556 (t (newline))))
11557 (setq start (point))
11558 (if (string-match "%file" rpl)
11559 (setq rpl (replace-match
11560 (concat
11561 "\""
11562 (save-match-data
11563 (abbreviate-file-name (read-file-name "Include file: ")))
11564 "\"")
11565 t t rpl)))
11566 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11567 (concat "\n" ind)))
11568 (insert rpl)
11569 (if (re-search-backward "\\?" start t) (delete-char 1))))
11571 ;;;; TODO, DEADLINE, Comments
11573 (defun org-toggle-comment ()
11574 "Change the COMMENT state of an entry."
11575 (interactive)
11576 (save-excursion
11577 (org-back-to-heading)
11578 (let (case-fold-search)
11579 (cond
11580 ((looking-at (format org-heading-keyword-regexp-format
11581 org-comment-string))
11582 (goto-char (match-end 1))
11583 (looking-at (concat " +" org-comment-string))
11584 (replace-match "" t t)
11585 (when (eolp) (insert " ")))
11586 ((looking-at org-outline-regexp)
11587 (goto-char (match-end 0))
11588 (insert org-comment-string " "))))))
11590 (defvar org-last-todo-state-is-todo nil
11591 "This is non-nil when the last TODO state change led to a TODO state.
11592 If the last change removed the TODO tag or switched to DONE, then
11593 this is nil.")
11595 (defvar org-setting-tags nil) ; dynamically skipped
11597 (defvar org-todo-setup-filter-hook nil
11598 "Hook for functions that pre-filter todo specs.
11599 Each function takes a todo spec and returns either nil or the spec
11600 transformed into canonical form." )
11602 (defvar org-todo-get-default-hook nil
11603 "Hook for functions that get a default item for todo.
11604 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11605 nil or a string to be used for the todo mark." )
11607 (defvar org-agenda-headline-snapshot-before-repeat)
11609 (defun org-current-effective-time ()
11610 "Return current time adjusted for `org-extend-today-until' variable."
11611 (let* ((ct (org-current-time))
11612 (dct (decode-time ct))
11613 (ct1
11614 (cond
11615 (org-use-last-clock-out-time-as-effective-time
11616 (or (org-clock-get-last-clock-out-time) ct))
11617 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11618 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11619 (t ct))))
11620 ct1))
11622 (defun org-todo-yesterday (&optional arg)
11623 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11624 (interactive "P")
11625 (if (eq major-mode 'org-agenda-mode)
11626 (apply 'org-agenda-todo-yesterday arg)
11627 (let* ((hour (third (decode-time
11628 (org-current-time))))
11629 (org-extend-today-until (1+ hour)))
11630 (org-todo arg))))
11632 (defvar org-block-entry-blocking ""
11633 "First entry preventing the TODO state change.")
11635 (defun org-todo (&optional arg)
11636 "Change the TODO state of an item.
11637 The state of an item is given by a keyword at the start of the heading,
11638 like
11639 *** TODO Write paper
11640 *** DONE Call mom
11642 The different keywords are specified in the variable `org-todo-keywords'.
11643 By default the available states are \"TODO\" and \"DONE\".
11644 So for this example: when the item starts with TODO, it is changed to DONE.
11645 When it starts with DONE, the DONE is removed. And when neither TODO nor
11646 DONE are present, add TODO at the beginning of the heading.
11648 With \\[universal-argument] prefix arg, use completion to determine the new \
11649 state.
11650 With numeric prefix arg, switch to that state.
11651 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11652 keywords (nextset).
11653 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11654 With a numeric prefix arg of 0, inhibit note taking for the change.
11656 For calling through lisp, arg is also interpreted in the following way:
11657 'none -> empty state
11658 \"\"(empty string) -> switch to empty state
11659 'done -> switch to DONE
11660 'nextset -> switch to the next set of keywords
11661 'previousset -> switch to the previous set of keywords
11662 \"WAITING\" -> switch to the specified keyword, but only if it
11663 really is a member of `org-todo-keywords'."
11664 (interactive "P")
11665 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11666 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11667 'region-start-level 'region))
11668 org-loop-over-headlines-in-active-region)
11669 (org-map-entries
11670 `(org-todo ,arg)
11671 org-loop-over-headlines-in-active-region
11672 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11673 (if (equal arg '(16)) (setq arg 'nextset))
11674 (let ((org-blocker-hook org-blocker-hook)
11675 commentp
11676 case-fold-search)
11677 (when (equal arg '(64))
11678 (setq arg nil org-blocker-hook nil))
11679 (when (and org-blocker-hook
11680 (or org-inhibit-blocking
11681 (org-entry-get nil "NOBLOCKING")))
11682 (setq org-blocker-hook nil))
11683 (save-excursion
11684 (catch 'exit
11685 (org-back-to-heading t)
11686 (when (looking-at (concat "^\\*+ " org-comment-string))
11687 (org-toggle-comment)
11688 (setq commentp t))
11689 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11690 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11691 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11692 (let* ((match-data (match-data))
11693 (startpos (point-at-bol))
11694 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11695 (org-log-done org-log-done)
11696 (org-log-repeat org-log-repeat)
11697 (org-todo-log-states org-todo-log-states)
11698 (org-inhibit-logging
11699 (if (equal arg 0)
11700 (progn (setq arg nil) 'note) org-inhibit-logging))
11701 (this (match-string 1))
11702 (hl-pos (match-beginning 0))
11703 (head (org-get-todo-sequence-head this))
11704 (ass (assoc head org-todo-kwd-alist))
11705 (interpret (nth 1 ass))
11706 (done-word (nth 3 ass))
11707 (final-done-word (nth 4 ass))
11708 (org-last-state (or this ""))
11709 (completion-ignore-case t)
11710 (member (member this org-todo-keywords-1))
11711 (tail (cdr member))
11712 (org-state (cond
11713 ((and org-todo-key-trigger
11714 (or (and (equal arg '(4))
11715 (eq org-use-fast-todo-selection 'prefix))
11716 (and (not arg) org-use-fast-todo-selection
11717 (not (eq org-use-fast-todo-selection
11718 'prefix)))))
11719 ;; Use fast selection
11720 (org-fast-todo-selection))
11721 ((and (equal arg '(4))
11722 (or (not org-use-fast-todo-selection)
11723 (not org-todo-key-trigger)))
11724 ;; Read a state with completion
11725 (org-icompleting-read
11726 "State: " (mapcar (lambda(x) (list x))
11727 org-todo-keywords-1)
11728 nil t))
11729 ((eq arg 'right)
11730 (if this
11731 (if tail (car tail) nil)
11732 (car org-todo-keywords-1)))
11733 ((eq arg 'left)
11734 (if (equal member org-todo-keywords-1)
11736 (if this
11737 (nth (- (length org-todo-keywords-1)
11738 (length tail) 2)
11739 org-todo-keywords-1)
11740 (org-last org-todo-keywords-1))))
11741 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11742 (setq arg nil))) ; hack to fall back to cycling
11743 (arg
11744 ;; user or caller requests a specific state
11745 (cond
11746 ((equal arg "") nil)
11747 ((eq arg 'none) nil)
11748 ((eq arg 'done) (or done-word (car org-done-keywords)))
11749 ((eq arg 'nextset)
11750 (or (car (cdr (member head org-todo-heads)))
11751 (car org-todo-heads)))
11752 ((eq arg 'previousset)
11753 (let ((org-todo-heads (reverse org-todo-heads)))
11754 (or (car (cdr (member head org-todo-heads)))
11755 (car org-todo-heads))))
11756 ((car (member arg org-todo-keywords-1)))
11757 ((stringp arg)
11758 (error "State `%s' not valid in this file" arg))
11759 ((nth (1- (prefix-numeric-value arg))
11760 org-todo-keywords-1))))
11761 ((null member) (or head (car org-todo-keywords-1)))
11762 ((equal this final-done-word) nil) ;; -> make empty
11763 ((null tail) nil) ;; -> first entry
11764 ((memq interpret '(type priority))
11765 (if (eq this-command last-command)
11766 (car tail)
11767 (if (> (length tail) 0)
11768 (or done-word (car org-done-keywords))
11769 nil)))
11771 (car tail))))
11772 (org-state (or
11773 (run-hook-with-args-until-success
11774 'org-todo-get-default-hook org-state org-last-state)
11775 org-state))
11776 (next (if org-state (concat " " org-state " ") " "))
11777 (change-plist (list :type 'todo-state-change :from this :to org-state
11778 :position startpos))
11779 dolog now-done-p)
11780 (when org-blocker-hook
11781 (setq org-last-todo-state-is-todo
11782 (not (member this org-done-keywords)))
11783 (unless (save-excursion
11784 (save-match-data
11785 (org-with-wide-buffer
11786 (run-hook-with-args-until-failure
11787 'org-blocker-hook change-plist))))
11788 (if (org-called-interactively-p 'interactive)
11789 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11790 this org-state org-block-entry-blocking)
11791 ;; fail silently
11792 (message "TODO state change from %s to %s blocked (by \"%s\")"
11793 this org-state org-block-entry-blocking)
11794 (throw 'exit nil))))
11795 (store-match-data match-data)
11796 (replace-match next t t)
11797 (unless (pos-visible-in-window-p hl-pos)
11798 (message "TODO state changed to %s" (org-trim next)))
11799 (unless head
11800 (setq head (org-get-todo-sequence-head org-state)
11801 ass (assoc head org-todo-kwd-alist)
11802 interpret (nth 1 ass)
11803 done-word (nth 3 ass)
11804 final-done-word (nth 4 ass)))
11805 (when (memq arg '(nextset previousset))
11806 (message "Keyword-Set %d/%d: %s"
11807 (- (length org-todo-sets) -1
11808 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11809 (length org-todo-sets)
11810 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11811 (setq org-last-todo-state-is-todo
11812 (not (member org-state org-done-keywords)))
11813 (setq now-done-p (and (member org-state org-done-keywords)
11814 (not (member this org-done-keywords))))
11815 (and logging (org-local-logging logging))
11816 (when (and (or org-todo-log-states org-log-done)
11817 (not (eq org-inhibit-logging t))
11818 (not (memq arg '(nextset previousset))))
11819 ;; we need to look at recording a time and note
11820 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11821 (nth 2 (assoc this org-todo-log-states))))
11822 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11823 (setq dolog 'time))
11824 (when (and org-state
11825 (member org-state org-not-done-keywords)
11826 (not (member this org-not-done-keywords)))
11827 ;; This is now a todo state and was not one before
11828 ;; If there was a CLOSED time stamp, get rid of it.
11829 (org-add-planning-info nil nil 'closed))
11830 (when (and now-done-p org-log-done)
11831 ;; It is now done, and it was not done before
11832 (org-add-planning-info 'closed (org-current-effective-time))
11833 (if (and (not dolog) (eq 'note org-log-done))
11834 (org-add-log-setup 'done org-state this 'findpos 'note)))
11835 (when (and org-state dolog)
11836 ;; This is a non-nil state, and we need to log it
11837 (org-add-log-setup 'state org-state this 'findpos dolog)))
11838 ;; Fixup tag positioning
11839 (org-todo-trigger-tag-changes org-state)
11840 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11841 (when org-provide-todo-statistics
11842 (org-update-parent-todo-statistics))
11843 (run-hooks 'org-after-todo-state-change-hook)
11844 (if (and arg (not (member org-state org-done-keywords)))
11845 (setq head (org-get-todo-sequence-head org-state)))
11846 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11847 ;; Do we need to trigger a repeat?
11848 (when now-done-p
11849 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11850 ;; This is for the agenda, take a snapshot of the headline.
11851 (save-match-data
11852 (setq org-agenda-headline-snapshot-before-repeat
11853 (org-get-heading))))
11854 (org-auto-repeat-maybe org-state))
11855 ;; Fixup cursor location if close to the keyword
11856 (if (and (outline-on-heading-p)
11857 (not (bolp))
11858 (save-excursion (beginning-of-line 1)
11859 (looking-at org-todo-line-regexp))
11860 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11861 (progn
11862 (goto-char (or (match-end 2) (match-end 1)))
11863 (and (looking-at " ") (just-one-space))))
11864 (when org-trigger-hook
11865 (save-excursion
11866 (run-hook-with-args 'org-trigger-hook change-plist)))
11867 (when commentp (org-toggle-comment))))))))
11869 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11870 "Block turning an entry into a TODO, using the hierarchy.
11871 This checks whether the current task should be blocked from state
11872 changes. Such blocking occurs when:
11874 1. The task has children which are not all in a completed state.
11876 2. A task has a parent with the property :ORDERED:, and there
11877 are siblings prior to the current task with incomplete
11878 status.
11880 3. The parent of the task is blocked because it has siblings that should
11881 be done first, or is child of a block grandparent TODO entry."
11883 (if (not org-enforce-todo-dependencies)
11884 t ; if locally turned off don't block
11885 (catch 'dont-block
11886 ;; If this is not a todo state change, or if this entry is already DONE,
11887 ;; do not block
11888 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11889 (member (plist-get change-plist :from)
11890 (cons 'done org-done-keywords))
11891 (member (plist-get change-plist :to)
11892 (cons 'todo org-not-done-keywords))
11893 (not (plist-get change-plist :to)))
11894 (throw 'dont-block t))
11895 ;; If this task has children, and any are undone, it's blocked
11896 (save-excursion
11897 (org-back-to-heading t)
11898 (let ((this-level (funcall outline-level)))
11899 (outline-next-heading)
11900 (let ((child-level (funcall outline-level)))
11901 (while (and (not (eobp))
11902 (> child-level this-level))
11903 ;; this todo has children, check whether they are all
11904 ;; completed
11905 (if (and (not (org-entry-is-done-p))
11906 (org-entry-is-todo-p))
11907 (progn (setq org-block-entry-blocking (org-get-heading))
11908 (throw 'dont-block nil)))
11909 (outline-next-heading)
11910 (setq child-level (funcall outline-level))))))
11911 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11912 ;; any previous siblings are undone, it's blocked
11913 (save-excursion
11914 (org-back-to-heading t)
11915 (let* ((pos (point))
11916 (parent-pos (and (org-up-heading-safe) (point))))
11917 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11918 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11919 (forward-line 1)
11920 (re-search-forward org-not-done-heading-regexp pos t))
11921 (setq org-block-entry-blocking (match-string 0))
11922 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11923 ;; Search further up the hierarchy, to see if an ancestor is blocked
11924 (while t
11925 (goto-char parent-pos)
11926 (if (not (looking-at org-not-done-heading-regexp))
11927 (throw 'dont-block t)) ; do not block, parent is not a TODO
11928 (setq pos (point))
11929 (setq parent-pos (and (org-up-heading-safe) (point)))
11930 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11931 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11932 (forward-line 1)
11933 (re-search-forward org-not-done-heading-regexp pos t)
11934 (setq org-block-entry-blocking (org-get-heading)))
11935 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11937 (defcustom org-track-ordered-property-with-tag nil
11938 "Should the ORDERED property also be shown as a tag?
11939 The ORDERED property decides if an entry should require subtasks to be
11940 completed in sequence. Since a property is not very visible, setting
11941 this option means that toggling the ORDERED property with the command
11942 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11943 not relevant for the behavior, but it makes things more visible.
11945 Note that toggling the tag with tags commands will not change the property
11946 and therefore not influence behavior!
11948 This can be t, meaning the tag ORDERED should be used, It can also be a
11949 string to select a different tag for this task."
11950 :group 'org-todo
11951 :type '(choice
11952 (const :tag "No tracking" nil)
11953 (const :tag "Track with ORDERED tag" t)
11954 (string :tag "Use other tag")))
11956 (defun org-toggle-ordered-property ()
11957 "Toggle the ORDERED property of the current entry.
11958 For better visibility, you can track the value of this property with a tag.
11959 See variable `org-track-ordered-property-with-tag'."
11960 (interactive)
11961 (let* ((t1 org-track-ordered-property-with-tag)
11962 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11963 (save-excursion
11964 (org-back-to-heading)
11965 (if (org-entry-get nil "ORDERED")
11966 (progn
11967 (org-delete-property "ORDERED")
11968 (and tag (org-toggle-tag tag 'off))
11969 (message "Subtasks can be completed in arbitrary order"))
11970 (org-entry-put nil "ORDERED" "t")
11971 (and tag (org-toggle-tag tag 'on))
11972 (message "Subtasks must be completed in sequence")))))
11974 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11975 (defun org-block-todo-from-checkboxes (change-plist)
11976 "Block turning an entry into a TODO, using checkboxes.
11977 This checks whether the current task should be blocked from state
11978 changes because there are unchecked boxes in this entry."
11979 (if (not org-enforce-todo-checkbox-dependencies)
11980 t ; if locally turned off don't block
11981 (catch 'dont-block
11982 ;; If this is not a todo state change, or if this entry is already DONE,
11983 ;; do not block
11984 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11985 (member (plist-get change-plist :from)
11986 (cons 'done org-done-keywords))
11987 (member (plist-get change-plist :to)
11988 (cons 'todo org-not-done-keywords))
11989 (not (plist-get change-plist :to)))
11990 (throw 'dont-block t))
11991 ;; If this task has checkboxes that are not checked, it's blocked
11992 (save-excursion
11993 (org-back-to-heading t)
11994 (let ((beg (point)) end)
11995 (outline-next-heading)
11996 (setq end (point))
11997 (goto-char beg)
11998 (if (org-list-search-forward
11999 (concat (org-item-beginning-re)
12000 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12001 "\\[[- ]\\]")
12002 end t)
12003 (progn
12004 (if (boundp 'org-blocked-by-checkboxes)
12005 (setq org-blocked-by-checkboxes t))
12006 (throw 'dont-block nil)))))
12007 t))) ; do not block
12009 (defun org-entry-blocked-p ()
12010 "Is the current entry blocked?"
12011 (org-with-buffer-modified-unmodified
12012 (if (org-entry-get nil "NOBLOCKING")
12013 nil ;; Never block this entry
12014 (not
12015 (run-hook-with-args-until-failure
12016 'org-blocker-hook
12017 (list :type 'todo-state-change
12018 :position (point)
12019 :from 'todo
12020 :to 'done))))))
12022 (defun org-update-statistics-cookies (all)
12023 "Update the statistics cookie, either from TODO or from checkboxes.
12024 This should be called with the cursor in a line with a statistics cookie."
12025 (interactive "P")
12026 (if all
12027 (progn
12028 (org-update-checkbox-count 'all)
12029 (org-map-entries 'org-update-parent-todo-statistics))
12030 (if (not (org-at-heading-p))
12031 (org-update-checkbox-count)
12032 (let ((pos (point-marker))
12033 end l1 l2)
12034 (ignore-errors (org-back-to-heading t))
12035 (if (not (org-at-heading-p))
12036 (org-update-checkbox-count)
12037 (setq l1 (org-outline-level))
12038 (setq end (save-excursion
12039 (outline-next-heading)
12040 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12041 (point)))
12042 (if (and (save-excursion
12043 (re-search-forward
12044 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12045 (not (save-excursion (re-search-forward
12046 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12047 (org-update-checkbox-count)
12048 (if (and l2 (> l2 l1))
12049 (progn
12050 (goto-char end)
12051 (org-update-parent-todo-statistics))
12052 (goto-char pos)
12053 (beginning-of-line 1)
12054 (while (re-search-forward
12055 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12056 (point-at-eol) t)
12057 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12058 (goto-char pos)
12059 (move-marker pos nil)))))
12061 (defvar org-entry-property-inherited-from) ;; defined below
12062 (defun org-update-parent-todo-statistics ()
12063 "Update any statistics cookie in the parent of the current headline.
12064 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12065 the entire subtree and this will travel up the hierarchy and update
12066 statistics everywhere."
12067 (let* ((prop (save-excursion (org-up-heading-safe)
12068 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12069 (recursive (or (not org-hierarchical-todo-statistics)
12070 (and prop (string-match "\\<recursive\\>" prop))))
12071 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12073 (first t)
12074 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12075 level ltoggle l1 new ndel
12076 (cnt-all 0) (cnt-done 0) is-percent kwd
12077 checkbox-beg ov ovs ove cookie-present)
12078 (catch 'exit
12079 (save-excursion
12080 (beginning-of-line 1)
12081 (setq ltoggle (funcall outline-level))
12082 ;; Three situations are to consider:
12084 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12085 ;; to the top-level ancestor on the headline;
12087 ;; 2. If parent has "recursive" property, repeat up to the
12088 ;; headline setting that property, taking inheritance into
12089 ;; account;
12091 ;; 3. Else, move up to direct parent and proceed only once.
12092 (while (and (setq level (org-up-heading-safe))
12093 (or recursive first)
12094 (>= (point) lim))
12095 (setq first nil cookie-present nil)
12096 (unless (and level
12097 (not (string-match
12098 "\\<checkbox\\>"
12099 (downcase (or (org-entry-get nil "COOKIE_DATA")
12100 "")))))
12101 (throw 'exit nil))
12102 (while (re-search-forward box-re (point-at-eol) t)
12103 (setq cnt-all 0 cnt-done 0 cookie-present t)
12104 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12105 (save-match-data
12106 (unless (outline-next-heading) (throw 'exit nil))
12107 (while (and (looking-at org-complex-heading-regexp)
12108 (> (setq l1 (length (match-string 1))) level))
12109 (setq kwd (and (or recursive (= l1 ltoggle))
12110 (match-string 2)))
12111 (if (or (eq org-provide-todo-statistics 'all-headlines)
12112 (and (listp org-provide-todo-statistics)
12113 (or (member kwd org-provide-todo-statistics)
12114 (member kwd org-done-keywords))))
12115 (setq cnt-all (1+ cnt-all))
12116 (if (eq org-provide-todo-statistics t)
12117 (and kwd (setq cnt-all (1+ cnt-all)))))
12118 (and (member kwd org-done-keywords)
12119 (setq cnt-done (1+ cnt-done)))
12120 (outline-next-heading)))
12121 (setq new
12122 (if is-percent
12123 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12124 (format "[%d/%d]" cnt-done cnt-all))
12125 ndel (- (match-end 0) checkbox-beg))
12126 ;; handle overlays when updating cookie from column view
12127 (when (setq ov (car (overlays-at checkbox-beg)))
12128 (setq ovs (overlay-start ov) ove (overlay-end ov))
12129 (delete-overlay ov))
12130 (goto-char checkbox-beg)
12131 (insert new)
12132 (delete-region (point) (+ (point) ndel))
12133 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12134 (when ov (move-overlay ov ovs ove)))
12135 (when cookie-present
12136 (run-hook-with-args 'org-after-todo-statistics-hook
12137 cnt-done (- cnt-all cnt-done))))))
12138 (run-hooks 'org-todo-statistics-hook)))
12140 (defvar org-after-todo-statistics-hook nil
12141 "Hook that is called after a TODO statistics cookie has been updated.
12142 Each function is called with two arguments: the number of not-done entries
12143 and the number of done entries.
12145 For example, the following function, when added to this hook, will switch
12146 an entry to DONE when all children are done, and back to TODO when new
12147 entries are set to a TODO status. Note that this hook is only called
12148 when there is a statistics cookie in the headline!
12150 (defun org-summary-todo (n-done n-not-done)
12151 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12152 (let (org-log-done org-log-states) ; turn off logging
12153 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12156 (defvar org-todo-statistics-hook nil
12157 "Hook that is run whenever Org thinks TODO statistics should be updated.
12158 This hook runs even if there is no statistics cookie present, in which case
12159 `org-after-todo-statistics-hook' would not run.")
12161 (defun org-todo-trigger-tag-changes (state)
12162 "Apply the changes defined in `org-todo-state-tags-triggers'."
12163 (let ((l org-todo-state-tags-triggers)
12164 changes)
12165 (when (or (not state) (equal state ""))
12166 (setq changes (append changes (cdr (assoc "" l)))))
12167 (when (and (stringp state) (> (length state) 0))
12168 (setq changes (append changes (cdr (assoc state l)))))
12169 (when (member state org-not-done-keywords)
12170 (setq changes (append changes (cdr (assoc 'todo l)))))
12171 (when (member state org-done-keywords)
12172 (setq changes (append changes (cdr (assoc 'done l)))))
12173 (dolist (c changes)
12174 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12176 (defun org-local-logging (value)
12177 "Get logging settings from a property VALUE."
12178 (let* (words w a)
12179 ;; directly set the variables, they are already local.
12180 (setq org-log-done nil
12181 org-log-repeat nil
12182 org-todo-log-states nil)
12183 (setq words (org-split-string value))
12184 (while (setq w (pop words))
12185 (cond
12186 ((setq a (assoc w org-startup-options))
12187 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12188 (set (nth 1 a) (nth 2 a))))
12189 ((setq a (org-extract-log-state-settings w))
12190 (and (member (car a) org-todo-keywords-1)
12191 (push a org-todo-log-states)))))))
12193 (defun org-get-todo-sequence-head (kwd)
12194 "Return the head of the TODO sequence to which KWD belongs.
12195 If KWD is not set, check if there is a text property remembering the
12196 right sequence."
12197 (let (p)
12198 (cond
12199 ((not kwd)
12200 (or (get-text-property (point-at-bol) 'org-todo-head)
12201 (progn
12202 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12203 nil (point-at-eol)))
12204 (get-text-property p 'org-todo-head))))
12205 ((not (member kwd org-todo-keywords-1))
12206 (car org-todo-keywords-1))
12207 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12209 (defun org-fast-todo-selection ()
12210 "Fast TODO keyword selection with single keys.
12211 Returns the new TODO keyword, or nil if no state change should occur."
12212 (let* ((fulltable org-todo-key-alist)
12213 (done-keywords org-done-keywords) ;; needed for the faces.
12214 (maxlen (apply 'max (mapcar
12215 (lambda (x)
12216 (if (stringp (car x)) (string-width (car x)) 0))
12217 fulltable)))
12218 (expert nil)
12219 (fwidth (+ maxlen 3 1 3))
12220 (ncol (/ (- (window-width) 4) fwidth))
12221 tg cnt e c tbl
12222 groups ingroup)
12223 (save-excursion
12224 (save-window-excursion
12225 (if expert
12226 (set-buffer (get-buffer-create " *Org todo*"))
12227 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12228 (erase-buffer)
12229 (org-set-local 'org-done-keywords done-keywords)
12230 (setq tbl fulltable cnt 0)
12231 (while (setq e (pop tbl))
12232 (cond
12233 ((equal e '(:startgroup))
12234 (push '() groups) (setq ingroup t)
12235 (when (not (= cnt 0))
12236 (setq cnt 0)
12237 (insert "\n"))
12238 (insert "{ "))
12239 ((equal e '(:endgroup))
12240 (setq ingroup nil cnt 0)
12241 (insert "}\n"))
12242 ((equal e '(:newline))
12243 (when (not (= cnt 0))
12244 (setq cnt 0)
12245 (insert "\n")
12246 (setq e (car tbl))
12247 (while (equal (car tbl) '(:newline))
12248 (insert "\n")
12249 (setq tbl (cdr tbl)))))
12251 (setq tg (car e) c (cdr e))
12252 (if ingroup (push tg (car groups)))
12253 (setq tg (org-add-props tg nil 'face
12254 (org-get-todo-face tg)))
12255 (if (and (= cnt 0) (not ingroup)) (insert " "))
12256 (insert "[" c "] " tg (make-string
12257 (- fwidth 4 (length tg)) ?\ ))
12258 (when (= (setq cnt (1+ cnt)) ncol)
12259 (insert "\n")
12260 (if ingroup (insert " "))
12261 (setq cnt 0)))))
12262 (insert "\n")
12263 (goto-char (point-min))
12264 (if (not expert) (org-fit-window-to-buffer))
12265 (message "[a-z..]:Set [SPC]:clear")
12266 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12267 (cond
12268 ((or (= c ?\C-g)
12269 (and (= c ?q) (not (rassoc c fulltable))))
12270 (setq quit-flag t))
12271 ((= c ?\ ) nil)
12272 ((setq e (rassoc c fulltable) tg (car e))
12274 (t (setq quit-flag t)))))))
12276 (defun org-entry-is-todo-p ()
12277 (member (org-get-todo-state) org-not-done-keywords))
12279 (defun org-entry-is-done-p ()
12280 (member (org-get-todo-state) org-done-keywords))
12282 (defun org-get-todo-state ()
12283 (save-excursion
12284 (org-back-to-heading t)
12285 (and (looking-at org-todo-line-regexp)
12286 (match-end 2)
12287 (match-string 2))))
12289 (defun org-at-date-range-p (&optional inactive-ok)
12290 "Is the cursor inside a date range?"
12291 (interactive)
12292 (save-excursion
12293 (catch 'exit
12294 (let ((pos (point)))
12295 (skip-chars-backward "^[<\r\n")
12296 (skip-chars-backward "<[")
12297 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12298 (>= (match-end 0) pos)
12299 (throw 'exit t))
12300 (skip-chars-backward "^<[\r\n")
12301 (skip-chars-backward "<[")
12302 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12303 (>= (match-end 0) pos)
12304 (throw 'exit t)))
12305 nil)))
12307 (defun org-get-repeat (&optional tagline)
12308 "Check if there is a deadline/schedule with repeater in this entry."
12309 (save-match-data
12310 (save-excursion
12311 (org-back-to-heading t)
12312 (and (re-search-forward (if tagline
12313 (concat tagline "\\s-*" org-repeat-re)
12314 org-repeat-re)
12315 (org-entry-end-position) t)
12316 (match-string-no-properties 1)))))
12318 (defvar org-last-changed-timestamp)
12319 (defvar org-last-inserted-timestamp)
12320 (defvar org-log-post-message)
12321 (defvar org-log-note-purpose)
12322 (defvar org-log-note-how)
12323 (defvar org-log-note-extra)
12324 (defun org-auto-repeat-maybe (done-word)
12325 "Check if the current headline contains a repeated deadline/schedule.
12326 If yes, set TODO state back to what it was and change the base date
12327 of repeating deadline/scheduled time stamps to new date.
12328 This function is run automatically after each state change to a DONE state."
12329 ;; last-state is dynamically scoped into this function
12330 (let* ((repeat (org-get-repeat))
12331 (aa (assoc org-last-state org-todo-kwd-alist))
12332 (interpret (nth 1 aa))
12333 (head (nth 2 aa))
12334 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12335 (msg "Entry repeats: ")
12336 (org-log-done nil)
12337 (org-todo-log-states nil)
12338 re type n what ts time to-state)
12339 (when repeat
12340 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12341 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12342 org-todo-repeat-to-state))
12343 (unless (and to-state (member to-state org-todo-keywords-1))
12344 (setq to-state (if (eq interpret 'type) org-last-state head)))
12345 (org-todo to-state)
12346 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12347 (org-entry-put nil "LAST_REPEAT" (format-time-string
12348 (org-time-stamp-format t t))))
12349 (when org-log-repeat
12350 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12351 (memq 'org-add-log-note post-command-hook))
12352 ;; OK, we are already setup for some record
12353 (if (eq org-log-repeat 'note)
12354 ;; make sure we take a note, not only a time stamp
12355 (setq org-log-note-how 'note))
12356 ;; Set up for taking a record
12357 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12358 org-last-state
12359 'findpos org-log-repeat)))
12360 (org-back-to-heading t)
12361 (org-add-planning-info nil nil 'closed)
12362 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12363 org-deadline-time-regexp "\\)\\|\\("
12364 org-ts-regexp "\\)"))
12365 (while (re-search-forward
12366 re (save-excursion (outline-next-heading) (point)) t)
12367 (setq type (if (match-end 1) org-scheduled-string
12368 (if (match-end 3) org-deadline-string "Plain:"))
12369 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12370 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12371 (setq n (string-to-number (match-string 2 ts))
12372 what (match-string 3 ts))
12373 (if (equal what "w") (setq n (* n 7) what "d"))
12374 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12375 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12376 ;; Preparation, see if we need to modify the start date for the change
12377 (when (match-end 1)
12378 (setq time (save-match-data (org-time-string-to-time ts)))
12379 (cond
12380 ((equal (match-string 1 ts) ".")
12381 ;; Shift starting date to today
12382 (org-timestamp-change
12383 (- (org-today) (time-to-days time))
12384 'day))
12385 ((equal (match-string 1 ts) "+")
12386 (let ((nshiftmax 10) (nshift 0))
12387 (while (or (= nshift 0)
12388 (<= (time-to-days time)
12389 (time-to-days (current-time))))
12390 (when (= (incf nshift) nshiftmax)
12391 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12392 (error "Abort")))
12393 (org-timestamp-change n (cdr (assoc what whata)))
12394 (org-at-timestamp-p t)
12395 (setq ts (match-string 1))
12396 (setq time (save-match-data (org-time-string-to-time ts)))))
12397 (org-timestamp-change (- n) (cdr (assoc what whata)))
12398 ;; rematch, so that we have everything in place for the real shift
12399 (org-at-timestamp-p t)
12400 (setq ts (match-string 1))
12401 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12402 (org-timestamp-change n (cdr (assoc what whata)))
12403 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12404 (setq org-log-post-message msg)
12405 (message "%s" msg))))
12407 (defun org-show-todo-tree (arg)
12408 "Make a compact tree which shows all headlines marked with TODO.
12409 The tree will show the lines where the regexp matches, and all higher
12410 headlines above the match.
12411 With a \\[universal-argument] prefix, prompt for a regexp to match.
12412 With a numeric prefix N, construct a sparse tree for the Nth element
12413 of `org-todo-keywords-1'."
12414 (interactive "P")
12415 (let ((case-fold-search nil)
12416 (kwd-re
12417 (cond ((null arg) org-not-done-regexp)
12418 ((equal arg '(4))
12419 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12420 (mapcar 'list org-todo-keywords-1))))
12421 (concat "\\("
12422 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12423 "\\)\\>")))
12424 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12425 (regexp-quote (nth (1- (prefix-numeric-value arg))
12426 org-todo-keywords-1)))
12427 (t (error "Invalid prefix argument: %s" arg)))))
12428 (message "%d TODO entries found"
12429 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12431 (defun org-deadline (&optional remove time)
12432 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12433 With argument REMOVE, remove any deadline from the item.
12434 With argument TIME, set the deadline at the corresponding date. TIME
12435 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12436 (interactive "P")
12437 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12438 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12439 'region-start-level 'region))
12440 org-loop-over-headlines-in-active-region)
12441 (org-map-entries
12442 `(org-deadline ',remove ,time)
12443 org-loop-over-headlines-in-active-region
12444 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12445 (let* ((old-date (org-entry-get nil "DEADLINE"))
12446 (repeater (and old-date
12447 (string-match
12448 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12449 old-date)
12450 (match-string 1 old-date))))
12451 (if remove
12452 (progn
12453 (when (and old-date org-log-redeadline)
12454 (org-add-log-setup 'deldeadline nil old-date 'findpos
12455 org-log-redeadline))
12456 (org-remove-timestamp-with-keyword org-deadline-string)
12457 (message "Item no longer has a deadline."))
12458 (org-add-planning-info 'deadline time 'closed)
12459 (when (and old-date org-log-redeadline
12460 (not (equal old-date
12461 (substring org-last-inserted-timestamp 1 -1))))
12462 (org-add-log-setup 'redeadline nil old-date 'findpos
12463 org-log-redeadline))
12464 (when repeater
12465 (save-excursion
12466 (org-back-to-heading t)
12467 (when (re-search-forward (concat org-deadline-string " "
12468 org-last-inserted-timestamp)
12469 (save-excursion
12470 (outline-next-heading) (point)) t)
12471 (goto-char (1- (match-end 0)))
12472 (insert " " repeater)
12473 (setq org-last-inserted-timestamp
12474 (concat (substring org-last-inserted-timestamp 0 -1)
12475 " " repeater
12476 (substring org-last-inserted-timestamp -1))))))
12477 (message "Deadline on %s" org-last-inserted-timestamp)))))
12479 (defun org-schedule (&optional remove time)
12480 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12481 With argument REMOVE, remove any scheduling date from the item.
12482 With argument TIME, scheduled at the corresponding date. TIME can
12483 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12484 (interactive "P")
12485 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12486 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12487 'region-start-level 'region))
12488 org-loop-over-headlines-in-active-region)
12489 (org-map-entries
12490 `(org-schedule ',remove ,time)
12491 org-loop-over-headlines-in-active-region
12492 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12493 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12494 (repeater (and old-date
12495 (string-match
12496 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12497 old-date)
12498 (match-string 1 old-date))))
12499 (if remove
12500 (progn
12501 (when (and old-date org-log-reschedule)
12502 (org-add-log-setup 'delschedule nil old-date 'findpos
12503 org-log-reschedule))
12504 (org-remove-timestamp-with-keyword org-scheduled-string)
12505 (message "Item is no longer scheduled."))
12506 (org-add-planning-info 'scheduled time 'closed)
12507 (when (and old-date org-log-reschedule
12508 (not (equal old-date
12509 (substring org-last-inserted-timestamp 1 -1))))
12510 (org-add-log-setup 'reschedule nil old-date 'findpos
12511 org-log-reschedule))
12512 (when repeater
12513 (save-excursion
12514 (org-back-to-heading t)
12515 (when (re-search-forward (concat org-scheduled-string " "
12516 org-last-inserted-timestamp)
12517 (save-excursion
12518 (outline-next-heading) (point)) t)
12519 (goto-char (1- (match-end 0)))
12520 (insert " " repeater)
12521 (setq org-last-inserted-timestamp
12522 (concat (substring org-last-inserted-timestamp 0 -1)
12523 " " repeater
12524 (substring org-last-inserted-timestamp -1))))))
12525 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12527 (defun org-get-scheduled-time (pom &optional inherit)
12528 "Get the scheduled time as a time tuple, of a format suitable
12529 for calling org-schedule with, or if there is no scheduling,
12530 returns nil."
12531 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12532 (when time
12533 (apply 'encode-time (org-parse-time-string time)))))
12535 (defun org-get-deadline-time (pom &optional inherit)
12536 "Get the deadline as a time tuple, of a format suitable for
12537 calling org-deadline with, or if there is no scheduling, returns
12538 nil."
12539 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12540 (when time
12541 (apply 'encode-time (org-parse-time-string time)))))
12543 (defun org-remove-timestamp-with-keyword (keyword)
12544 "Remove all time stamps with KEYWORD in the current entry."
12545 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12546 beg)
12547 (save-excursion
12548 (org-back-to-heading t)
12549 (setq beg (point))
12550 (outline-next-heading)
12551 (while (re-search-backward re beg t)
12552 (replace-match "")
12553 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12554 (equal (char-before) ?\ ))
12555 (backward-delete-char 1)
12556 (if (string-match "^[ \t]*$" (buffer-substring
12557 (point-at-bol) (point-at-eol)))
12558 (delete-region (point-at-bol)
12559 (min (point-max) (1+ (point-at-eol))))))))))
12561 (defun org-add-planning-info (what &optional time &rest remove)
12562 "Insert new timestamp with keyword in the line directly after the headline.
12563 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12564 If non is given, the user is prompted for a date.
12565 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12566 be removed."
12567 (interactive)
12568 (let (org-time-was-given org-end-time-was-given ts
12569 end default-time default-input)
12571 (catch 'exit
12572 (when (and (memq what '(scheduled deadline))
12573 (or (not time)
12574 (and (stringp time)
12575 (string-match "^[-+]+[0-9]" time))))
12576 ;; Try to get a default date/time from existing timestamp
12577 (save-excursion
12578 (org-back-to-heading t)
12579 (setq end (save-excursion (outline-next-heading) (point)))
12580 (when (re-search-forward (if (eq what 'scheduled)
12581 org-scheduled-time-regexp
12582 org-deadline-time-regexp)
12583 end t)
12584 (setq ts (match-string 1)
12585 default-time
12586 (apply 'encode-time (org-parse-time-string ts))
12587 default-input (and ts (org-get-compact-tod ts))))))
12588 (when what
12589 (setq time
12590 (if (stringp time)
12591 ;; This is a string (relative or absolute), set proper date
12592 (apply 'encode-time
12593 (org-read-date-analyze
12594 time default-time (decode-time default-time)))
12595 ;; If necessary, get the time from the user
12596 (or time (org-read-date nil 'to-time nil nil
12597 default-time default-input)))))
12599 (when (and org-insert-labeled-timestamps-at-point
12600 (member what '(scheduled deadline)))
12601 (insert
12602 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12603 (org-insert-time-stamp time org-time-was-given
12604 nil nil nil (list org-end-time-was-given))
12605 (setq what nil))
12606 (save-excursion
12607 (save-restriction
12608 (let (col list elt ts buffer-invisibility-spec)
12609 (org-back-to-heading t)
12610 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12611 (goto-char (match-end 1))
12612 (setq col (current-column))
12613 (goto-char (match-end 0))
12614 (if (eobp) (insert "\n") (forward-char 1))
12615 (when (and (not what)
12616 (not (looking-at
12617 (concat "[ \t]*"
12618 org-keyword-time-not-clock-regexp))))
12619 ;; Nothing to add, nothing to remove...... :-)
12620 (throw 'exit nil))
12621 (if (and (not (looking-at org-outline-regexp))
12622 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12623 "[^\r\n]*"))
12624 (not (equal (match-string 1) org-clock-string)))
12625 (narrow-to-region (match-beginning 0) (match-end 0))
12626 (insert-before-markers "\n")
12627 (backward-char 1)
12628 (narrow-to-region (point) (point))
12629 (and org-adapt-indentation (org-indent-to-column col)))
12630 ;; Check if we have to remove something.
12631 (setq list (cons what remove))
12632 (while list
12633 (setq elt (pop list))
12634 (when (or (and (eq elt 'scheduled)
12635 (re-search-forward org-scheduled-time-regexp nil t))
12636 (and (eq elt 'deadline)
12637 (re-search-forward org-deadline-time-regexp nil t))
12638 (and (eq elt 'closed)
12639 (re-search-forward org-closed-time-regexp nil t)))
12640 (replace-match "")
12641 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12642 (and (looking-at "[ \t]+") (replace-match ""))
12643 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12644 (when what
12645 (insert
12646 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12647 (cond ((eq what 'scheduled) org-scheduled-string)
12648 ((eq what 'deadline) org-deadline-string)
12649 ((eq what 'closed) org-closed-string))
12650 " ")
12651 (setq ts (org-insert-time-stamp
12652 time
12653 (or org-time-was-given
12654 (and (eq what 'closed) org-log-done-with-time))
12655 (eq what 'closed)
12656 nil nil (list org-end-time-was-given)))
12657 (insert
12658 (if (not (or (bolp) (eq (char-before) ?\ )
12659 (memq (char-after) '(32 10))
12660 (eobp))) " " ""))
12661 (end-of-line 1))
12662 (goto-char (point-min))
12663 (widen)
12664 (if (and (looking-at "[ \t]*\n")
12665 (equal (char-before) ?\n))
12666 (delete-region (1- (point)) (point-at-eol)))
12667 ts))))))
12669 (defvar org-log-note-marker (make-marker))
12670 (defvar org-log-note-purpose nil)
12671 (defvar org-log-note-state nil)
12672 (defvar org-log-note-previous-state nil)
12673 (defvar org-log-note-how nil)
12674 (defvar org-log-note-extra nil)
12675 (defvar org-log-note-window-configuration nil)
12676 (defvar org-log-note-return-to (make-marker))
12677 (defvar org-log-note-effective-time nil
12678 "Remembered current time so that dynamically scoped
12679 `org-extend-today-until' affects tha timestamps in state change
12680 log")
12682 (defvar org-log-post-message nil
12683 "Message to be displayed after a log note has been stored.
12684 The auto-repeater uses this.")
12686 (defun org-add-note ()
12687 "Add a note to the current entry.
12688 This is done in the same way as adding a state change note."
12689 (interactive)
12690 (org-add-log-setup 'note nil nil 'findpos nil))
12692 (defvar org-property-end-re)
12693 (defun org-add-log-setup (&optional purpose state prev-state
12694 findpos how extra)
12695 "Set up the post command hook to take a note.
12696 If this is about to TODO state change, the new state is expected in STATE.
12697 When FINDPOS is non-nil, find the correct position for the note in
12698 the current entry. If not, assume that it can be inserted at point.
12699 HOW is an indicator what kind of note should be created.
12700 EXTRA is additional text that will be inserted into the notes buffer."
12701 (let* ((org-log-into-drawer (org-log-into-drawer))
12702 (drawer (cond ((stringp org-log-into-drawer)
12703 org-log-into-drawer)
12704 (org-log-into-drawer "LOGBOOK"))))
12705 (save-restriction
12706 (save-excursion
12707 (when findpos
12708 (org-back-to-heading t)
12709 (narrow-to-region (point) (save-excursion
12710 (outline-next-heading) (point)))
12711 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12712 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12713 "[^\r\n]*\\)?"))
12714 (goto-char (match-end 0))
12715 (cond
12716 (drawer
12717 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12718 nil t)
12719 (progn
12720 (goto-char (match-end 0))
12721 (or org-log-states-order-reversed
12722 (and (re-search-forward org-property-end-re nil t)
12723 (goto-char (1- (match-beginning 0))))))
12724 (insert "\n:" drawer ":\n:END:")
12725 (beginning-of-line 0)
12726 (org-indent-line)
12727 (beginning-of-line 2)
12728 (org-indent-line)
12729 (end-of-line 0)))
12730 ((and org-log-state-notes-insert-after-drawers
12731 (save-excursion
12732 (forward-line) (looking-at org-drawer-regexp)))
12733 (forward-line)
12734 (while (looking-at org-drawer-regexp)
12735 (goto-char (match-end 0))
12736 (re-search-forward org-property-end-re (point-max) t)
12737 (forward-line))
12738 (forward-line -1)))
12739 (unless org-log-states-order-reversed
12740 (and (= (char-after) ?\n) (forward-char 1))
12741 (org-skip-over-state-notes)
12742 (skip-chars-backward " \t\n\r")))
12743 (move-marker org-log-note-marker (point))
12744 (setq org-log-note-purpose purpose
12745 org-log-note-state state
12746 org-log-note-previous-state prev-state
12747 org-log-note-how how
12748 org-log-note-extra extra
12749 org-log-note-effective-time (org-current-effective-time))
12750 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12752 (defun org-skip-over-state-notes ()
12753 "Skip past the list of State notes in an entry."
12754 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12755 (when (ignore-errors (goto-char (org-in-item-p)))
12756 (let* ((struct (org-list-struct))
12757 (prevs (org-list-prevs-alist struct)))
12758 (while (looking-at "[ \t]*- State")
12759 (goto-char (or (org-list-get-next-item (point) struct prevs)
12760 (org-list-get-item-end (point) struct)))))))
12762 (defun org-add-log-note (&optional purpose)
12763 "Pop up a window for taking a note, and add this note later at point."
12764 (remove-hook 'post-command-hook 'org-add-log-note)
12765 (setq org-log-note-window-configuration (current-window-configuration))
12766 (delete-other-windows)
12767 (move-marker org-log-note-return-to (point))
12768 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12769 (goto-char org-log-note-marker)
12770 (org-switch-to-buffer-other-window "*Org Note*")
12771 (erase-buffer)
12772 (if (memq org-log-note-how '(time state))
12773 (let (current-prefix-arg) (org-store-log-note))
12774 (let ((org-inhibit-startup t)) (org-mode))
12775 (insert (format "# Insert note for %s.
12776 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12777 (cond
12778 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12779 ((eq org-log-note-purpose 'done) "closed todo item")
12780 ((eq org-log-note-purpose 'state)
12781 (format "state change from \"%s\" to \"%s\""
12782 (or org-log-note-previous-state "")
12783 (or org-log-note-state "")))
12784 ((eq org-log-note-purpose 'reschedule)
12785 "rescheduling")
12786 ((eq org-log-note-purpose 'delschedule)
12787 "no longer scheduled")
12788 ((eq org-log-note-purpose 'redeadline)
12789 "changing deadline")
12790 ((eq org-log-note-purpose 'deldeadline)
12791 "removing deadline")
12792 ((eq org-log-note-purpose 'refile)
12793 "refiling")
12794 ((eq org-log-note-purpose 'note)
12795 "this entry")
12796 (t (error "This should not happen")))))
12797 (if org-log-note-extra (insert org-log-note-extra))
12798 (org-set-local 'org-finish-function 'org-store-log-note)
12799 (run-hooks 'org-log-buffer-setup-hook)))
12801 (defvar org-note-abort nil) ; dynamically scoped
12802 (defun org-store-log-note ()
12803 "Finish taking a log note, and insert it to where it belongs."
12804 (let ((txt (buffer-string)))
12805 (kill-buffer (current-buffer))
12806 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12807 lines ind bul)
12808 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12809 (setq txt (replace-match "" t t txt)))
12810 (if (string-match "\\s-+\\'" txt)
12811 (setq txt (replace-match "" t t txt)))
12812 (setq lines (org-split-string txt "\n"))
12813 (when (and note (string-match "\\S-" note))
12814 (setq note
12815 (org-replace-escapes
12816 note
12817 (list (cons "%u" (user-login-name))
12818 (cons "%U" user-full-name)
12819 (cons "%t" (format-time-string
12820 (org-time-stamp-format 'long 'inactive)
12821 org-log-note-effective-time))
12822 (cons "%T" (format-time-string
12823 (org-time-stamp-format 'long nil)
12824 org-log-note-effective-time))
12825 (cons "%d" (format-time-string
12826 (org-time-stamp-format nil 'inactive)
12827 org-log-note-effective-time))
12828 (cons "%D" (format-time-string
12829 (org-time-stamp-format nil nil)
12830 org-log-note-effective-time))
12831 (cons "%s" (if org-log-note-state
12832 (concat "\"" org-log-note-state "\"")
12833 ""))
12834 (cons "%S" (if org-log-note-previous-state
12835 (concat "\"" org-log-note-previous-state "\"")
12836 "\"\"")))))
12837 (if lines (setq note (concat note " \\\\")))
12838 (push note lines))
12839 (when (or current-prefix-arg org-note-abort)
12840 (when org-log-into-drawer
12841 (org-remove-empty-drawer-at
12842 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12843 org-log-note-marker))
12844 (setq lines nil))
12845 (when lines
12846 (with-current-buffer (marker-buffer org-log-note-marker)
12847 (save-excursion
12848 (goto-char org-log-note-marker)
12849 (move-marker org-log-note-marker nil)
12850 (end-of-line 1)
12851 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12852 (setq ind (save-excursion
12853 (if (ignore-errors (goto-char (org-in-item-p)))
12854 (let ((struct (org-list-struct)))
12855 (org-list-get-ind
12856 (org-list-get-top-point struct) struct))
12857 (skip-chars-backward " \r\t\n")
12858 (cond
12859 ((and (org-at-heading-p)
12860 org-adapt-indentation)
12861 (1+ (org-current-level)))
12862 ((org-at-heading-p) 0)
12863 (t (org-get-indentation))))))
12864 (setq bul (org-list-bullet-string "-"))
12865 (org-indent-line-to ind)
12866 (insert bul (pop lines))
12867 (let ((ind-body (+ (length bul) ind)))
12868 (while lines
12869 (insert "\n")
12870 (org-indent-line-to ind-body)
12871 (insert (pop lines))))
12872 (message "Note stored")
12873 (org-back-to-heading t)
12874 (org-cycle-hide-drawers 'children))))))
12875 (set-window-configuration org-log-note-window-configuration)
12876 (with-current-buffer (marker-buffer org-log-note-return-to)
12877 (goto-char org-log-note-return-to))
12878 (move-marker org-log-note-return-to nil)
12879 (and org-log-post-message (message "%s" org-log-post-message)))
12881 (defun org-remove-empty-drawer-at (drawer pos)
12882 "Remove an empty drawer DRAWER at position POS.
12883 POS may also be a marker."
12884 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12885 (save-excursion
12886 (save-restriction
12887 (widen)
12888 (goto-char pos)
12889 (if (org-in-regexp
12890 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12891 (replace-match ""))))))
12893 (defvar org-ts-type nil)
12894 (defun org-sparse-tree (&optional arg type)
12895 "Create a sparse tree, prompt for the details.
12896 This command can create sparse trees. You first need to select the type
12897 of match used to create the tree:
12899 t Show all TODO entries.
12900 T Show entries with a specific TODO keyword.
12901 m Show entries selected by a tags/property match.
12902 p Enter a property name and its value (both with completion on existing
12903 names/values) and show entries with that property.
12904 r Show entries matching a regular expression (`/' can be used as well).
12905 b Show deadlines and scheduled items before a date.
12906 a Show deadlines and scheduled items after a date.
12907 d Show deadlines due within `org-deadline-warning-days'.
12908 D Show deadlines and scheduled items between a date range."
12909 (interactive "P")
12910 (let (ans kwd value ts-type)
12911 (setq type (or type org-sparse-tree-default-date-type))
12912 (setq org-ts-type type)
12913 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
12914 (cond ((eq type 'all) "all timestamps")
12915 ((eq type 'scheduled) "only scheduled")
12916 ((eq type 'deadline) "only deadline")
12917 ((eq type 'active) "only active timestamps")
12918 ((eq type 'inactive) "only inactive timestamps")
12919 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12920 (t "scheduled/deadline")))
12921 (setq ans (read-char-exclusive))
12922 (cond
12923 ((equal ans ?c)
12924 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12925 ((equal ans ?d)
12926 (call-interactively 'org-check-deadlines))
12927 ((equal ans ?b)
12928 (call-interactively 'org-check-before-date))
12929 ((equal ans ?a)
12930 (call-interactively 'org-check-after-date))
12931 ((equal ans ?D)
12932 (call-interactively 'org-check-dates-range))
12933 ((equal ans ?t)
12934 (call-interactively 'org-show-todo-tree))
12935 ((equal ans ?T)
12936 (org-show-todo-tree '(4)))
12937 ((member ans '(?T ?m))
12938 (call-interactively 'org-match-sparse-tree))
12939 ((member ans '(?p ?P))
12940 (setq kwd (org-icompleting-read "Property: "
12941 (mapcar 'list (org-buffer-property-keys))))
12942 (setq value (org-icompleting-read "Value: "
12943 (mapcar 'list (org-property-values kwd))))
12944 (unless (string-match "\\`{.*}\\'" value)
12945 (setq value (concat "\"" value "\"")))
12946 (org-match-sparse-tree arg (concat kwd "=" value)))
12947 ((member ans '(?r ?R ?/))
12948 (call-interactively 'org-occur))
12949 (t (error "No such sparse tree command \"%c\"" ans)))))
12951 (defvar org-occur-highlights nil
12952 "List of overlays used for occur matches.")
12953 (make-variable-buffer-local 'org-occur-highlights)
12954 (defvar org-occur-parameters nil
12955 "Parameters of the active org-occur calls.
12956 This is a list, each call to org-occur pushes as cons cell,
12957 containing the regular expression and the callback, onto the list.
12958 The list can contain several entries if `org-occur' has been called
12959 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12960 will only contain one set of parameters. When the highlights are
12961 removed (for example with `C-c C-c', or with the next edit (depending
12962 on `org-remove-highlights-with-change'), this variable is emptied
12963 as well.")
12964 (make-variable-buffer-local 'org-occur-parameters)
12966 (defun org-occur (regexp &optional keep-previous callback)
12967 "Make a compact tree which shows all matches of REGEXP.
12968 The tree will show the lines where the regexp matches, and all higher
12969 headlines above the match. It will also show the heading after the match,
12970 to make sure editing the matching entry is easy.
12971 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12972 call to `org-occur' will be kept, to allow stacking of calls to this
12973 command.
12974 If CALLBACK is non-nil, it is a function which is called to confirm
12975 that the match should indeed be shown."
12976 (interactive "sRegexp: \nP")
12977 (when (equal regexp "")
12978 (error "Regexp cannot be empty"))
12979 (unless keep-previous
12980 (org-remove-occur-highlights nil nil t))
12981 (push (cons regexp callback) org-occur-parameters)
12982 (let ((cnt 0))
12983 (save-excursion
12984 (goto-char (point-min))
12985 (if (or (not keep-previous) ; do not want to keep
12986 (not org-occur-highlights)) ; no previous matches
12987 ;; hide everything
12988 (org-overview))
12989 (while (re-search-forward regexp nil t)
12990 (when (or (not callback)
12991 (save-match-data (funcall callback)))
12992 (setq cnt (1+ cnt))
12993 (when org-highlight-sparse-tree-matches
12994 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12995 (org-show-context 'occur-tree))))
12996 (when org-remove-highlights-with-change
12997 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12998 nil 'local))
12999 (unless org-sparse-tree-open-archived-trees
13000 (org-hide-archived-subtrees (point-min) (point-max)))
13001 (run-hooks 'org-occur-hook)
13002 (if (org-called-interactively-p 'interactive)
13003 (message "%d match(es) for regexp %s" cnt regexp))
13004 cnt))
13006 (defun org-occur-next-match (&optional n reset)
13007 "Function for `next-error-function' to find sparse tree matches.
13008 N is the number of matches to move, when negative move backwards.
13009 RESET is entirely ignored - this function always goes back to the
13010 starting point when no match is found."
13011 (let* ((limit (if (< n 0) (point-min) (point-max)))
13012 (search-func (if (< n 0)
13013 'previous-single-char-property-change
13014 'next-single-char-property-change))
13015 (n (abs n))
13016 (pos (point))
13018 (catch 'exit
13019 (while (setq p1 (funcall search-func (point) 'org-type))
13020 (when (equal p1 limit)
13021 (goto-char pos)
13022 (error "No more matches"))
13023 (when (equal (get-char-property p1 'org-type) 'org-occur)
13024 (setq n (1- n))
13025 (when (= n 0)
13026 (goto-char p1)
13027 (throw 'exit (point))))
13028 (goto-char p1))
13029 (goto-char p1)
13030 (error "No more matches"))))
13032 (defun org-show-context (&optional key)
13033 "Make sure point and context are visible.
13034 How much context is shown depends upon the variables
13035 `org-show-hierarchy-above', `org-show-following-heading',
13036 `org-show-entry-below' and `org-show-siblings'."
13037 (let ((heading-p (org-at-heading-p t))
13038 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13039 (following-p (org-get-alist-option org-show-following-heading key))
13040 (entry-p (org-get-alist-option org-show-entry-below key))
13041 (siblings-p (org-get-alist-option org-show-siblings key)))
13042 (catch 'exit
13043 ;; Show heading or entry text
13044 (if (and heading-p (not entry-p))
13045 (org-flag-heading nil) ; only show the heading
13046 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13047 (org-show-hidden-entry))) ; show entire entry
13048 (when following-p
13049 ;; Show next sibling, or heading below text
13050 (save-excursion
13051 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13052 (org-flag-heading nil))))
13053 (when siblings-p (org-show-siblings))
13054 (when hierarchy-p
13055 ;; show all higher headings, possibly with siblings
13056 (save-excursion
13057 (while (and (condition-case nil
13058 (progn (org-up-heading-all 1) t)
13059 (error nil))
13060 (not (bobp)))
13061 (org-flag-heading nil)
13062 (when siblings-p (org-show-siblings))))))))
13064 (defvar org-reveal-start-hook nil
13065 "Hook run before revealing a location.")
13067 (defun org-reveal (&optional siblings)
13068 "Show current entry, hierarchy above it, and the following headline.
13069 This can be used to show a consistent set of context around locations
13070 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13071 not t for the search context.
13073 With optional argument SIBLINGS, on each level of the hierarchy all
13074 siblings are shown. This repairs the tree structure to what it would
13075 look like when opened with hierarchical calls to `org-cycle'.
13076 With double optional argument \\[universal-argument] \\[universal-argument], \
13077 go to the parent and show the
13078 entire tree."
13079 (interactive "P")
13080 (run-hooks 'org-reveal-start-hook)
13081 (let ((org-show-hierarchy-above t)
13082 (org-show-following-heading t)
13083 (org-show-siblings (if siblings t org-show-siblings)))
13084 (org-show-context nil))
13085 (when (equal siblings '(16))
13086 (save-excursion
13087 (when (org-up-heading-safe)
13088 (org-show-subtree)
13089 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13091 (defun org-highlight-new-match (beg end)
13092 "Highlight from BEG to END and mark the highlight is an occur headline."
13093 (let ((ov (make-overlay beg end)))
13094 (overlay-put ov 'face 'secondary-selection)
13095 (overlay-put ov 'org-type 'org-occur)
13096 (push ov org-occur-highlights)))
13098 (defun org-remove-occur-highlights (&optional beg end noremove)
13099 "Remove the occur highlights from the buffer.
13100 BEG and END are ignored. If NOREMOVE is nil, remove this function
13101 from the `before-change-functions' in the current buffer."
13102 (interactive)
13103 (unless org-inhibit-highlight-removal
13104 (mapc 'delete-overlay org-occur-highlights)
13105 (setq org-occur-highlights nil)
13106 (setq org-occur-parameters nil)
13107 (unless noremove
13108 (remove-hook 'before-change-functions
13109 'org-remove-occur-highlights 'local))))
13111 ;;;; Priorities
13113 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13114 "Regular expression matching the priority indicator.")
13116 (defvar org-remove-priority-next-time nil)
13118 (defun org-priority-up ()
13119 "Increase the priority of the current item."
13120 (interactive)
13121 (org-priority 'up))
13123 (defun org-priority-down ()
13124 "Decrease the priority of the current item."
13125 (interactive)
13126 (org-priority 'down))
13128 (defun org-priority (&optional action show)
13129 "Change the priority of an item.
13130 ACTION can be `set', `up', `down', or a character."
13131 (interactive "P")
13132 (if (equal action '(4))
13133 (org-show-priority)
13134 (unless org-enable-priority-commands
13135 (error "Priority commands are disabled"))
13136 (setq action (or action 'set))
13137 (let (current new news have remove)
13138 (save-excursion
13139 (org-back-to-heading t)
13140 (if (looking-at org-priority-regexp)
13141 (setq current (string-to-char (match-string 2))
13142 have t))
13143 (cond
13144 ((eq action 'remove)
13145 (setq remove t new ?\ ))
13146 ((or (eq action 'set)
13147 (if (featurep 'xemacs) (characterp action) (integerp action)))
13148 (if (not (eq action 'set))
13149 (setq new action)
13150 (message "Priority %c-%c, SPC to remove: "
13151 org-highest-priority org-lowest-priority)
13152 (save-match-data
13153 (setq new (read-char-exclusive))))
13154 (if (and (= (upcase org-highest-priority) org-highest-priority)
13155 (= (upcase org-lowest-priority) org-lowest-priority))
13156 (setq new (upcase new)))
13157 (cond ((equal new ?\ ) (setq remove t))
13158 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13159 (error "Priority must be between `%c' and `%c'"
13160 org-highest-priority org-lowest-priority))))
13161 ((eq action 'up)
13162 (setq new (if have
13163 (1- current) ; normal cycling
13164 ;; last priority was empty
13165 (if (eq last-command this-command)
13166 org-lowest-priority ; wrap around empty to lowest
13167 ;; default
13168 (if org-priority-start-cycle-with-default
13169 org-default-priority
13170 (1- org-default-priority))))))
13171 ((eq action 'down)
13172 (setq new (if have
13173 (1+ current) ; normal cycling
13174 ;; last priority was empty
13175 (if (eq last-command this-command)
13176 org-highest-priority ; wrap around empty to highest
13177 ;; default
13178 (if org-priority-start-cycle-with-default
13179 org-default-priority
13180 (1+ org-default-priority))))))
13181 (t (error "Invalid action")))
13182 (if (or (< (upcase new) org-highest-priority)
13183 (> (upcase new) org-lowest-priority))
13184 (if (and (memq action '(up down))
13185 (not have) (not (eq last-command this-command)))
13186 ;; `new' is from default priority
13187 (error
13188 "The default can not be set, see `org-default-priority' why")
13189 ;; normal cycling: `new' is beyond highest/lowest priority
13190 ;; and is wrapped around to the empty priority
13191 (setq remove t)))
13192 (setq news (format "%c" new))
13193 (if have
13194 (if remove
13195 (replace-match "" t t nil 1)
13196 (replace-match news t t nil 2))
13197 (if remove
13198 (error "No priority cookie found in line")
13199 (let ((case-fold-search nil))
13200 (looking-at org-todo-line-regexp))
13201 (if (match-end 2)
13202 (progn
13203 (goto-char (match-end 2))
13204 (insert " [#" news "]"))
13205 (goto-char (match-beginning 3))
13206 (insert "[#" news "] "))))
13207 (org-preserve-lc (org-set-tags nil 'align)))
13208 (if remove
13209 (message "Priority removed")
13210 (message "Priority of current item set to %s" news)))))
13212 (defun org-show-priority ()
13213 "Show the priority of the current item.
13214 This priority is composed of the main priority given with the [#A] cookies,
13215 and by additional input from the age of a schedules or deadline entry."
13216 (interactive)
13217 (let ((pri (if (eq major-mode 'org-agenda-mode)
13218 (org-get-at-bol 'priority)
13219 (save-excursion
13220 (save-match-data
13221 (beginning-of-line)
13222 (and (looking-at org-heading-regexp)
13223 (org-get-priority (match-string 0))))))))
13224 (message "Priority is %d" (if pri pri -1000))))
13226 (defun org-get-priority (s)
13227 "Find priority cookie and return priority."
13228 (if (functionp org-get-priority-function)
13229 (funcall org-get-priority-function)
13230 (save-match-data
13231 (if (not (string-match org-priority-regexp s))
13232 (* 1000 (- org-lowest-priority org-default-priority))
13233 (* 1000 (- org-lowest-priority
13234 (string-to-char (match-string 2 s))))))))
13236 ;;;; Tags
13238 (defvar org-agenda-archives-mode)
13239 (defvar org-map-continue-from nil
13240 "Position from where mapping should continue.
13241 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13243 (defvar org-scanner-tags nil
13244 "The current tag list while the tags scanner is running.")
13245 (defvar org-trust-scanner-tags nil
13246 "Should `org-get-tags-at' use the tags for the scanner.
13247 This is for internal dynamical scoping only.
13248 When this is non-nil, the function `org-get-tags-at' will return the value
13249 of `org-scanner-tags' instead of building the list by itself. This
13250 can lead to large speed-ups when the tags scanner is used in a file with
13251 many entries, and when the list of tags is retrieved, for example to
13252 obtain a list of properties. Building the tags list for each entry in such
13253 a file becomes an N^2 operation - but with this variable set, it scales
13254 as N.")
13256 (defun org-scan-tags (action matcher todo-only &optional start-level)
13257 "Scan headline tags with inheritance and produce output ACTION.
13259 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13260 or `agenda' to produce an entry list for an agenda view. It can also be
13261 a Lisp form or a function that should be called at each matched headline, in
13262 this case the return value is a list of all return values from these calls.
13264 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13265 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13266 only lines with a not-done TODO keyword are included in the output.
13267 This should be the same variable that was scoped into
13268 and set by `org-make-tags-matcher' when it constructed MATCHER.
13270 START-LEVEL can be a string with asterisks, reducing the scope to
13271 headlines matching this string."
13272 (require 'org-agenda)
13273 (let* ((re (concat "^"
13274 (if start-level
13275 ;; Get the correct level to match
13276 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13277 org-outline-regexp)
13278 " *\\(\\<\\("
13279 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13280 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13281 (props (list 'face 'default
13282 'done-face 'org-agenda-done
13283 'undone-face 'default
13284 'mouse-face 'highlight
13285 'org-not-done-regexp org-not-done-regexp
13286 'org-todo-regexp org-todo-regexp
13287 'org-complex-heading-regexp org-complex-heading-regexp
13288 'help-echo
13289 (format "mouse-2 or RET jump to org file %s"
13290 (abbreviate-file-name
13291 (or (buffer-file-name (buffer-base-buffer))
13292 (buffer-name (buffer-base-buffer)))))))
13293 (case-fold-search nil)
13294 (org-map-continue-from nil)
13295 lspos tags tags-list
13296 (tags-alist (list (cons 0 org-file-tags)))
13297 (llast 0) rtn rtn1 level category i txt
13298 todo marker entry priority)
13299 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13300 (setq action (list 'lambda nil action)))
13301 (save-excursion
13302 (goto-char (point-min))
13303 (when (eq action 'sparse-tree)
13304 (org-overview)
13305 (org-remove-occur-highlights))
13306 (while (re-search-forward re nil t)
13307 (setq org-map-continue-from nil)
13308 (catch :skip
13309 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13310 tags (if (match-end 4) (org-match-string-no-properties 4)))
13311 (goto-char (setq lspos (match-beginning 0)))
13312 (setq level (org-reduced-level (org-outline-level))
13313 category (org-get-category))
13314 (setq i llast llast level)
13315 ;; remove tag lists from same and sublevels
13316 (while (>= i level)
13317 (when (setq entry (assoc i tags-alist))
13318 (setq tags-alist (delete entry tags-alist)))
13319 (setq i (1- i)))
13320 ;; add the next tags
13321 (when tags
13322 (setq tags (org-split-string tags ":")
13323 tags-alist
13324 (cons (cons level tags) tags-alist)))
13325 ;; compile tags for current headline
13326 (setq tags-list
13327 (if org-use-tag-inheritance
13328 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13329 tags)
13330 org-scanner-tags tags-list)
13331 (when org-use-tag-inheritance
13332 (setcdr (car tags-alist)
13333 (mapcar (lambda (x)
13334 (setq x (copy-sequence x))
13335 (org-add-prop-inherited x))
13336 (cdar tags-alist))))
13337 (when (and tags org-use-tag-inheritance
13338 (or (not (eq t org-use-tag-inheritance))
13339 org-tags-exclude-from-inheritance))
13340 ;; selective inheritance, remove uninherited ones
13341 (setcdr (car tags-alist)
13342 (org-remove-uninherited-tags (cdar tags-alist))))
13343 (when (and
13345 ;; eval matcher only when the todo condition is OK
13346 (and (or (not todo-only) (member todo org-not-done-keywords))
13347 (let ((case-fold-search t) (org-trust-scanner-tags t))
13348 (eval matcher)))
13350 ;; Call the skipper, but return t if it does not skip,
13351 ;; so that the `and' form continues evaluating
13352 (progn
13353 (unless (eq action 'sparse-tree) (org-agenda-skip))
13356 ;; Check if timestamps are deselecting this entry
13357 (or (not todo-only)
13358 (and (member todo org-not-done-keywords)
13359 (or (not org-agenda-tags-todo-honor-ignore-options)
13360 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13362 ;; Extra check for the archive tag
13363 ;; FIXME: Does the skipper already do this????
13365 (not (member org-archive-tag tags-list))
13366 ;; we have an archive tag, should we use this anyway?
13367 (or (not org-agenda-skip-archived-trees)
13368 (and (eq action 'agenda) org-agenda-archives-mode))))
13370 ;; select this headline
13371 (cond
13372 ((eq action 'sparse-tree)
13373 (and org-highlight-sparse-tree-matches
13374 (org-get-heading) (match-end 0)
13375 (org-highlight-new-match
13376 (match-beginning 1) (match-end 1)))
13377 (org-show-context 'tags-tree))
13378 ((eq action 'agenda)
13379 (setq txt (org-agenda-format-item
13381 (concat
13382 (if (eq org-tags-match-list-sublevels 'indented)
13383 (make-string (1- level) ?.) "")
13384 (org-get-heading))
13385 level category
13386 tags-list)
13387 priority (org-get-priority txt))
13388 (goto-char lspos)
13389 (setq marker (org-agenda-new-marker))
13390 (org-add-props txt props
13391 'org-marker marker 'org-hd-marker marker 'org-category category
13392 'todo-state todo
13393 'priority priority 'type "tagsmatch")
13394 (push txt rtn))
13395 ((functionp action)
13396 (setq org-map-continue-from nil)
13397 (save-excursion
13398 (setq rtn1 (funcall action))
13399 (push rtn1 rtn)))
13400 (t (error "Invalid action")))
13402 ;; if we are to skip sublevels, jump to end of subtree
13403 (unless org-tags-match-list-sublevels
13404 (org-end-of-subtree t)
13405 (backward-char 1))))
13406 ;; Get the correct position from where to continue
13407 (if org-map-continue-from
13408 (goto-char org-map-continue-from)
13409 (and (= (point) lspos) (end-of-line 1)))))
13410 (when (and (eq action 'sparse-tree)
13411 (not org-sparse-tree-open-archived-trees))
13412 (org-hide-archived-subtrees (point-min) (point-max)))
13413 (nreverse rtn)))
13415 (defun org-remove-uninherited-tags (tags)
13416 "Remove all tags that are not inherited from the list TAGS."
13417 (cond
13418 ((eq org-use-tag-inheritance t)
13419 (if org-tags-exclude-from-inheritance
13420 (org-delete-all org-tags-exclude-from-inheritance tags)
13421 tags))
13422 ((not org-use-tag-inheritance) nil)
13423 ((stringp org-use-tag-inheritance)
13424 (delq nil (mapcar
13425 (lambda (x)
13426 (if (and (string-match org-use-tag-inheritance x)
13427 (not (member x org-tags-exclude-from-inheritance)))
13428 x nil))
13429 tags)))
13430 ((listp org-use-tag-inheritance)
13431 (delq nil (mapcar
13432 (lambda (x)
13433 (if (member x org-use-tag-inheritance) x nil))
13434 tags)))))
13436 (defun org-match-sparse-tree (&optional todo-only match)
13437 "Create a sparse tree according to tags string MATCH.
13438 MATCH can contain positive and negative selection of tags, like
13439 \"+WORK+URGENT-WITHBOSS\".
13440 If optional argument TODO-ONLY is non-nil, only select lines that are
13441 also TODO lines."
13442 (interactive "P")
13443 (org-agenda-prepare-buffers (list (current-buffer)))
13444 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13446 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13448 (defvar org-cached-props nil)
13449 (defun org-cached-entry-get (pom property)
13450 (if (or (eq t org-use-property-inheritance)
13451 (and (stringp org-use-property-inheritance)
13452 (string-match org-use-property-inheritance property))
13453 (and (listp org-use-property-inheritance)
13454 (member property org-use-property-inheritance)))
13455 ;; Caching is not possible, check it directly
13456 (org-entry-get pom property 'inherit)
13457 ;; Get all properties, so that we can do complicated checks easily
13458 (cdr (assoc property (or org-cached-props
13459 (setq org-cached-props
13460 (org-entry-properties pom)))))))
13462 (defun org-global-tags-completion-table (&optional files)
13463 "Return the list of all tags in all agenda buffer/files.
13464 Optional FILES argument is a list of files which can be used
13465 instead of the agenda files."
13466 (save-excursion
13467 (org-uniquify
13468 (delq nil
13469 (apply 'append
13470 (mapcar
13471 (lambda (file)
13472 (set-buffer (find-file-noselect file))
13473 (append (org-get-buffer-tags)
13474 (mapcar (lambda (x) (if (stringp (car-safe x))
13475 (list (car-safe x)) nil))
13476 org-tag-alist)))
13477 (if (and files (car files))
13478 files
13479 (org-agenda-files))))))))
13481 (defun org-make-tags-matcher (match)
13482 "Create the TAGS/TODO matcher form for the selection string MATCH.
13484 The variable `todo-only' is scoped dynamically into this function.
13485 It will be set to t if the matcher restricts matching to TODO entries,
13486 otherwise will not be touched.
13488 Returns a cons of the selection string MATCH and the constructed
13489 lisp form implementing the matcher. The matcher is to be evaluated
13490 at an Org entry, with point on the headline, and returns t if the
13491 entry matches the selection string MATCH. The returned lisp form
13492 references two variables with information about the entry, which
13493 must be bound around the form's evaluation: todo, the TODO keyword
13494 at the entry (or nil of none); and tags-list, the list of all tags
13495 at the entry including inherited ones. Additionally, the category
13496 of the entry (if any) must be specified as the text property
13497 'org-category on the headline.
13499 See also `org-scan-tags'.
13501 (declare (special todo-only))
13502 (unless (boundp 'todo-only)
13503 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13504 (unless match
13505 ;; Get a new match request, with completion
13506 (let ((org-last-tags-completion-table
13507 (org-global-tags-completion-table)))
13508 (setq match (org-completing-read-no-i
13509 "Match: " 'org-tags-completion-function nil nil nil
13510 'org-tags-history))))
13512 ;; Parse the string and create a lisp form
13513 (let ((match0 match)
13514 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13515 minus tag mm
13516 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13517 orterms term orlist re-p str-p level-p level-op time-p
13518 prop-p pn pv po gv rest)
13519 (if (string-match "/+" match)
13520 ;; match contains also a todo-matching request
13521 (progn
13522 (setq tagsmatch (substring match 0 (match-beginning 0))
13523 todomatch (substring match (match-end 0)))
13524 (if (string-match "^!" todomatch)
13525 (setq todo-only t todomatch (substring todomatch 1)))
13526 (if (string-match "^\\s-*$" todomatch)
13527 (setq todomatch nil)))
13528 ;; only matching tags
13529 (setq tagsmatch match todomatch nil))
13531 ;; Make the tags matcher
13532 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13533 (setq tagsmatcher t)
13534 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13535 (while (setq term (pop orterms))
13536 (while (and (equal (substring term -1) "\\") orterms)
13537 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13538 (while (string-match re term)
13539 (setq rest (substring term (match-end 0))
13540 minus (and (match-end 1)
13541 (equal (match-string 1 term) "-"))
13542 tag (save-match-data (replace-regexp-in-string
13543 "\\\\-" "-"
13544 (match-string 2 term)))
13545 re-p (equal (string-to-char tag) ?{)
13546 level-p (match-end 4)
13547 prop-p (match-end 5)
13548 mm (cond
13549 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13550 (level-p
13551 (setq level-op (org-op-to-function (match-string 3 term)))
13552 `(,level-op level ,(string-to-number
13553 (match-string 4 term))))
13554 (prop-p
13555 (setq pn (match-string 5 term)
13556 po (match-string 6 term)
13557 pv (match-string 7 term)
13558 re-p (equal (string-to-char pv) ?{)
13559 str-p (equal (string-to-char pv) ?\")
13560 time-p (save-match-data
13561 (string-match "^\"[[<].*[]>]\"$" pv))
13562 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13563 (if time-p (setq pv (org-matcher-time pv)))
13564 (setq po (org-op-to-function po (if time-p 'time str-p)))
13565 (cond
13566 ((equal pn "CATEGORY")
13567 (setq gv '(get-text-property (point) 'org-category)))
13568 ((equal pn "TODO")
13569 (setq gv 'todo))
13571 (setq gv `(org-cached-entry-get nil ,pn))))
13572 (if re-p
13573 (if (eq po 'org<>)
13574 `(not (string-match ,pv (or ,gv "")))
13575 `(string-match ,pv (or ,gv "")))
13576 (if str-p
13577 `(,po (or ,gv "") ,pv)
13578 `(,po (string-to-number (or ,gv ""))
13579 ,(string-to-number pv) ))))
13580 (t `(member ,tag tags-list)))
13581 mm (if minus (list 'not mm) mm)
13582 term rest)
13583 (push mm tagsmatcher))
13584 (push (if (> (length tagsmatcher) 1)
13585 (cons 'and tagsmatcher)
13586 (car tagsmatcher))
13587 orlist)
13588 (setq tagsmatcher nil))
13589 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13590 (setq tagsmatcher
13591 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13592 ;; Make the todo matcher
13593 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13594 (setq todomatcher t)
13595 (setq orterms (org-split-string todomatch "|") orlist nil)
13596 (while (setq term (pop orterms))
13597 (while (string-match re term)
13598 (setq minus (and (match-end 1)
13599 (equal (match-string 1 term) "-"))
13600 kwd (match-string 2 term)
13601 re-p (equal (string-to-char kwd) ?{)
13602 term (substring term (match-end 0))
13603 mm (if re-p
13604 `(string-match ,(substring kwd 1 -1) todo)
13605 (list 'equal 'todo kwd))
13606 mm (if minus (list 'not mm) mm))
13607 (push mm todomatcher))
13608 (push (if (> (length todomatcher) 1)
13609 (cons 'and todomatcher)
13610 (car todomatcher))
13611 orlist)
13612 (setq todomatcher nil))
13613 (setq todomatcher (if (> (length orlist) 1)
13614 (cons 'or orlist) (car orlist))))
13616 ;; Return the string and lisp forms of the matcher
13617 (setq matcher (if todomatcher
13618 (list 'and tagsmatcher todomatcher)
13619 tagsmatcher))
13620 (when todo-only
13621 (setq matcher (list 'and '(member todo org-not-done-keywords)
13622 matcher)))
13623 (cons match0 matcher)))
13625 (defun org-op-to-function (op &optional stringp)
13626 "Turn an operator into the appropriate function."
13627 (setq op
13628 (cond
13629 ((equal op "<" ) '(< string< org-time<))
13630 ((equal op ">" ) '(> org-string> org-time>))
13631 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13632 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13633 ((member op '("=" "==")) '(= string= org-time=))
13634 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13635 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13637 (defun org<> (a b) (not (= a b)))
13638 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13639 (defun org-string>= (a b) (not (string< a b)))
13640 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13641 (defun org-string<> (a b) (not (string= a b)))
13642 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13643 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13644 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13645 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13646 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13647 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13648 (defun org-2ft (s)
13649 "Convert S to a floating point time.
13650 If S is already a number, just return it. If it is a string, parse
13651 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13652 (cond
13653 ((numberp s) s)
13654 ((stringp s)
13655 (condition-case nil
13656 (float-time (apply 'encode-time (org-parse-time-string s)))
13657 (error 0.)))
13658 (t 0.)))
13660 (defun org-time-today ()
13661 "Time in seconds today at 0:00.
13662 Returns the float number of seconds since the beginning of the
13663 epoch to the beginning of today (00:00)."
13664 (float-time (apply 'encode-time
13665 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13667 (defun org-matcher-time (s)
13668 "Interpret a time comparison value."
13669 (save-match-data
13670 (cond
13671 ((string= s "<now>") (float-time))
13672 ((string= s "<today>") (org-time-today))
13673 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13674 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13675 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13676 (+ (org-time-today)
13677 (* (string-to-number (match-string 1 s))
13678 (cdr (assoc (match-string 2 s)
13679 '(("d" . 86400.0) ("w" . 604800.0)
13680 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13681 (t (org-2ft s)))))
13683 (defun org-match-any-p (re list)
13684 "Does re match any element of list?"
13685 (setq list (mapcar (lambda (x) (string-match re x)) list))
13686 (delq nil list))
13688 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13689 (defvar org-tags-overlay (make-overlay 1 1))
13690 (org-detach-overlay org-tags-overlay)
13692 (defun org-get-local-tags-at (&optional pos)
13693 "Get a list of tags defined in the current headline."
13694 (org-get-tags-at pos 'local))
13696 (defun org-get-local-tags ()
13697 "Get a list of tags defined in the current headline."
13698 (org-get-tags-at nil 'local))
13700 (defun org-get-tags-at (&optional pos local)
13701 "Get a list of all headline tags applicable at POS.
13702 POS defaults to point. If tags are inherited, the list contains
13703 the targets in the same sequence as the headlines appear, i.e.
13704 the tags of the current headline come last.
13705 When LOCAL is non-nil, only return tags from the current headline,
13706 ignore inherited ones."
13707 (interactive)
13708 (if (and org-trust-scanner-tags
13709 (or (not pos) (equal pos (point)))
13710 (not local))
13711 org-scanner-tags
13712 (let (tags ltags lastpos parent)
13713 (save-excursion
13714 (save-restriction
13715 (widen)
13716 (goto-char (or pos (point)))
13717 (save-match-data
13718 (catch 'done
13719 (condition-case nil
13720 (progn
13721 (org-back-to-heading t)
13722 (while (not (equal lastpos (point)))
13723 (setq lastpos (point))
13724 (when (looking-at
13725 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13726 (setq ltags (org-split-string
13727 (org-match-string-no-properties 1) ":"))
13728 (when parent
13729 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13730 (setq tags (append
13731 (if parent
13732 (org-remove-uninherited-tags ltags)
13733 ltags)
13734 tags)))
13735 (or org-use-tag-inheritance (throw 'done t))
13736 (if local (throw 'done t))
13737 (or (org-up-heading-safe) (error nil))
13738 (setq parent t)))
13739 (error nil)))))
13740 (if local
13741 tags
13742 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13744 (defun org-add-prop-inherited (s)
13745 (add-text-properties 0 (length s) '(inherited t) s)
13748 (defun org-toggle-tag (tag &optional onoff)
13749 "Toggle the tag TAG for the current line.
13750 If ONOFF is `on' or `off', don't toggle but set to this state."
13751 (let (res current)
13752 (save-excursion
13753 (org-back-to-heading t)
13754 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13755 (point-at-eol) t)
13756 (progn
13757 (setq current (match-string 1))
13758 (replace-match ""))
13759 (setq current ""))
13760 (setq current (nreverse (org-split-string current ":")))
13761 (cond
13762 ((eq onoff 'on)
13763 (setq res t)
13764 (or (member tag current) (push tag current)))
13765 ((eq onoff 'off)
13766 (or (not (member tag current)) (setq current (delete tag current))))
13767 (t (if (member tag current)
13768 (setq current (delete tag current))
13769 (setq res t)
13770 (push tag current))))
13771 (end-of-line 1)
13772 (if current
13773 (progn
13774 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13775 (org-set-tags nil t))
13776 (delete-horizontal-space))
13777 (run-hooks 'org-after-tags-change-hook))
13778 res))
13780 (defun org-align-tags-here (to-col)
13781 ;; Assumes that this is a headline
13782 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13783 (beginning-of-line 1)
13784 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13785 (< pos (match-beginning 2)))
13786 (progn
13787 (setq tags-l (- (match-end 2) (match-beginning 2)))
13788 (goto-char (match-beginning 1))
13789 (insert " ")
13790 (delete-region (point) (1+ (match-beginning 2)))
13791 (setq ncol (max (current-column)
13792 (1+ col)
13793 (if (> to-col 0)
13794 to-col
13795 (- (abs to-col) tags-l))))
13796 (setq p (point))
13797 (insert (make-string (- ncol (current-column)) ?\ ))
13798 (setq ncol (current-column))
13799 (when indent-tabs-mode (tabify p (point-at-eol)))
13800 (org-move-to-column (min ncol col) t))
13801 (goto-char pos))))
13803 (defun org-set-tags-command (&optional arg just-align)
13804 "Call the set-tags command for the current entry."
13805 (interactive "P")
13806 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13807 (org-set-tags arg just-align)
13808 (save-excursion
13809 (org-back-to-heading t)
13810 (org-set-tags arg just-align))))
13812 (defun org-set-tags-to (data)
13813 "Set the tags of the current entry to DATA, replacing the current tags.
13814 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13815 If DATA is nil or the empty string, any tags will be removed."
13816 (interactive "sTags: ")
13817 (setq data
13818 (cond
13819 ((eq data nil) "")
13820 ((equal data "") "")
13821 ((stringp data)
13822 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13823 ":"))
13824 ((listp data)
13825 (concat ":" (mapconcat 'identity data ":") ":"))))
13826 (when data
13827 (save-excursion
13828 (org-back-to-heading t)
13829 (when (looking-at org-complex-heading-regexp)
13830 (if (match-end 5)
13831 (progn
13832 (goto-char (match-beginning 5))
13833 (insert data)
13834 (delete-region (point) (point-at-eol))
13835 (org-set-tags nil 'align))
13836 (goto-char (point-at-eol))
13837 (insert " " data)
13838 (org-set-tags nil 'align)))
13839 (beginning-of-line 1)
13840 (if (looking-at ".*?\\([ \t]+\\)$")
13841 (delete-region (match-beginning 1) (match-end 1))))))
13843 (defun org-align-all-tags ()
13844 "Align the tags i all headings."
13845 (interactive)
13846 (save-excursion
13847 (or (ignore-errors (org-back-to-heading t))
13848 (outline-next-heading))
13849 (if (org-at-heading-p)
13850 (org-set-tags t)
13851 (message "No headings"))))
13853 (defvar org-indent-indentation-per-level)
13854 (defun org-set-tags (&optional arg just-align)
13855 "Set the tags for the current headline.
13856 With prefix ARG, realign all tags in headings in the current buffer."
13857 (interactive "P")
13858 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13859 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13860 'region-start-level 'region))
13861 org-loop-over-headlines-in-active-region)
13862 (org-map-entries
13863 ;; We don't use ARG and JUST-ALIGN here these args are not
13864 ;; useful when looping over headlines
13865 `(org-set-tags)
13866 org-loop-over-headlines-in-active-region
13867 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13868 (let* ((re org-outline-regexp-bol)
13869 (current (unless arg (org-get-tags-string)))
13870 (col (current-column))
13871 (org-setting-tags t)
13872 table current-tags inherited-tags ; computed below when needed
13873 tags p0 c0 c1 rpl di tc level)
13874 (if arg
13875 (save-excursion
13876 (goto-char (point-min))
13877 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13878 (while (re-search-forward re nil t)
13879 (org-set-tags nil t)
13880 (end-of-line 1)))
13881 (message "All tags realigned to column %d" org-tags-column))
13882 (if just-align
13883 (setq tags current)
13884 ;; Get a new set of tags from the user
13885 (save-excursion
13886 (setq table (append org-tag-persistent-alist
13887 (or org-tag-alist (org-get-buffer-tags))
13888 (and
13889 org-complete-tags-always-offer-all-agenda-tags
13890 (org-global-tags-completion-table
13891 (org-agenda-files))))
13892 org-last-tags-completion-table table
13893 current-tags (org-split-string current ":")
13894 inherited-tags (nreverse
13895 (nthcdr (length current-tags)
13896 (nreverse (org-get-tags-at))))
13897 tags
13898 (if (or (eq t org-use-fast-tag-selection)
13899 (and org-use-fast-tag-selection
13900 (delq nil (mapcar 'cdr table))))
13901 (org-fast-tag-selection
13902 current-tags inherited-tags table
13903 (if org-fast-tag-selection-include-todo
13904 org-todo-key-alist))
13905 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13906 (org-trim
13907 (org-icompleting-read "Tags: "
13908 'org-tags-completion-function
13909 nil nil current 'org-tags-history))))))
13910 (while (string-match "[-+&]+" tags)
13911 ;; No boolean logic, just a list
13912 (setq tags (replace-match ":" t t tags))))
13914 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13916 (if org-tags-sort-function
13917 (setq tags (mapconcat 'identity
13918 (sort (org-split-string
13919 tags (org-re "[^[:alnum:]_@#%]+"))
13920 org-tags-sort-function) ":")))
13922 (if (string-match "\\`[\t ]*\\'" tags)
13923 (setq tags "")
13924 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13925 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13927 ;; Insert new tags at the correct column
13928 (beginning-of-line 1)
13929 (setq level (or (and (looking-at org-outline-regexp)
13930 (- (match-end 0) (point) 1))
13932 (cond
13933 ((and (equal current "") (equal tags "")))
13934 ((re-search-forward
13935 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13936 (point-at-eol) t)
13937 (if (equal tags "")
13938 (setq rpl "")
13939 (goto-char (match-beginning 0))
13940 (setq c0 (current-column)
13941 ;; compute offset for the case of org-indent-mode active
13942 di (if org-indent-mode
13943 (* (1- org-indent-indentation-per-level) (1- level))
13945 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13946 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13947 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13948 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13949 (replace-match rpl t t)
13950 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13951 tags)
13952 (t (error "Tags alignment failed")))
13953 (org-move-to-column col)
13954 (unless just-align
13955 (run-hooks 'org-after-tags-change-hook))))))
13957 (defun org-change-tag-in-region (beg end tag off)
13958 "Add or remove TAG for each entry in the region.
13959 This works in the agenda, and also in an org-mode buffer."
13960 (interactive
13961 (list (region-beginning) (region-end)
13962 (let ((org-last-tags-completion-table
13963 (if (derived-mode-p 'org-mode)
13964 (org-get-buffer-tags)
13965 (org-global-tags-completion-table))))
13966 (org-icompleting-read
13967 "Tag: " 'org-tags-completion-function nil nil nil
13968 'org-tags-history))
13969 (progn
13970 (message "[s]et or [r]emove? ")
13971 (equal (read-char-exclusive) ?r))))
13972 (if (fboundp 'deactivate-mark) (deactivate-mark))
13973 (let ((agendap (equal major-mode 'org-agenda-mode))
13974 l1 l2 m buf pos newhead (cnt 0))
13975 (goto-char end)
13976 (setq l2 (1- (org-current-line)))
13977 (goto-char beg)
13978 (setq l1 (org-current-line))
13979 (loop for l from l1 to l2 do
13980 (org-goto-line l)
13981 (setq m (get-text-property (point) 'org-hd-marker))
13982 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13983 (and agendap m))
13984 (setq buf (if agendap (marker-buffer m) (current-buffer))
13985 pos (if agendap m (point)))
13986 (with-current-buffer buf
13987 (save-excursion
13988 (save-restriction
13989 (goto-char pos)
13990 (setq cnt (1+ cnt))
13991 (org-toggle-tag tag (if off 'off 'on))
13992 (setq newhead (org-get-heading)))))
13993 (and agendap (org-agenda-change-all-lines newhead m))))
13994 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13996 (defun org-tags-completion-function (string predicate &optional flag)
13997 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13998 (confirm (lambda (x) (stringp (car x)))))
13999 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14000 (setq s1 (match-string 1 string)
14001 s2 (match-string 2 string))
14002 (setq s1 "" s2 string))
14003 (cond
14004 ((eq flag nil)
14005 ;; try completion
14006 (setq rtn (try-completion s2 ctable confirm))
14007 (if (stringp rtn)
14008 (setq rtn
14009 (concat s1 s2 (substring rtn (length s2))
14010 (if (and org-add-colon-after-tag-completion
14011 (assoc rtn ctable))
14012 ":" ""))))
14013 rtn)
14014 ((eq flag t)
14015 ;; all-completions
14016 (all-completions s2 ctable confirm)
14018 ((eq flag 'lambda)
14019 ;; exact match?
14020 (assoc s2 ctable)))
14023 (defun org-fast-tag-insert (kwd tags face &optional end)
14024 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14025 (insert (format "%-12s" (concat kwd ":"))
14026 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14027 (or end "")))
14029 (defun org-fast-tag-show-exit (flag)
14030 (save-excursion
14031 (org-goto-line 3)
14032 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14033 (replace-match ""))
14034 (when flag
14035 (end-of-line 1)
14036 (org-move-to-column (- (window-width) 19) t)
14037 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14039 (defun org-set-current-tags-overlay (current prefix)
14040 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14041 (if (featurep 'xemacs)
14042 (org-overlay-display org-tags-overlay (concat prefix s)
14043 'secondary-selection)
14044 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14045 (org-overlay-display org-tags-overlay (concat prefix s)))))
14047 (defvar org-last-tag-selection-key nil)
14048 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14049 "Fast tag selection with single keys.
14050 CURRENT is the current list of tags in the headline, INHERITED is the
14051 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14052 possibly with grouping information. TODO-TABLE is a similar table with
14053 TODO keywords, should these have keys assigned to them.
14054 If the keys are nil, a-z are automatically assigned.
14055 Returns the new tags string, or nil to not change the current settings."
14056 (let* ((fulltable (append table todo-table))
14057 (maxlen (apply 'max (mapcar
14058 (lambda (x)
14059 (if (stringp (car x)) (string-width (car x)) 0))
14060 fulltable)))
14061 (buf (current-buffer))
14062 (expert (eq org-fast-tag-selection-single-key 'expert))
14063 (buffer-tags nil)
14064 (fwidth (+ maxlen 3 1 3))
14065 (ncol (/ (- (window-width) 4) fwidth))
14066 (i-face 'org-done)
14067 (c-face 'org-todo)
14068 tg cnt e c char c1 c2 ntable tbl rtn
14069 ov-start ov-end ov-prefix
14070 (exit-after-next org-fast-tag-selection-single-key)
14071 (done-keywords org-done-keywords)
14072 groups ingroup)
14073 (save-excursion
14074 (beginning-of-line 1)
14075 (if (looking-at
14076 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14077 (setq ov-start (match-beginning 1)
14078 ov-end (match-end 1)
14079 ov-prefix "")
14080 (setq ov-start (1- (point-at-eol))
14081 ov-end (1+ ov-start))
14082 (skip-chars-forward "^\n\r")
14083 (setq ov-prefix
14084 (concat
14085 (buffer-substring (1- (point)) (point))
14086 (if (> (current-column) org-tags-column)
14088 (make-string (- org-tags-column (current-column)) ?\ ))))))
14089 (move-overlay org-tags-overlay ov-start ov-end)
14090 (save-window-excursion
14091 (if expert
14092 (set-buffer (get-buffer-create " *Org tags*"))
14093 (delete-other-windows)
14094 (split-window-vertically)
14095 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14096 (erase-buffer)
14097 (org-set-local 'org-done-keywords done-keywords)
14098 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14099 (org-fast-tag-insert "Current" current c-face "\n\n")
14100 (org-fast-tag-show-exit exit-after-next)
14101 (org-set-current-tags-overlay current ov-prefix)
14102 (setq tbl fulltable char ?a cnt 0)
14103 (while (setq e (pop tbl))
14104 (cond
14105 ((equal (car e) :startgroup)
14106 (push '() groups) (setq ingroup t)
14107 (when (not (= cnt 0))
14108 (setq cnt 0)
14109 (insert "\n"))
14110 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14111 ((equal (car e) :endgroup)
14112 (setq ingroup nil cnt 0)
14113 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14114 ((equal e '(:newline))
14115 (when (not (= cnt 0))
14116 (setq cnt 0)
14117 (insert "\n")
14118 (setq e (car tbl))
14119 (while (equal (car tbl) '(:newline))
14120 (insert "\n")
14121 (setq tbl (cdr tbl)))))
14123 (setq tg (copy-sequence (car e)) c2 nil)
14124 (if (cdr e)
14125 (setq c (cdr e))
14126 ;; automatically assign a character.
14127 (setq c1 (string-to-char
14128 (downcase (substring
14129 tg (if (= (string-to-char tg) ?@) 1 0)))))
14130 (if (or (rassoc c1 ntable) (rassoc c1 table))
14131 (while (or (rassoc char ntable) (rassoc char table))
14132 (setq char (1+ char)))
14133 (setq c2 c1))
14134 (setq c (or c2 char)))
14135 (if ingroup (push tg (car groups)))
14136 (setq tg (org-add-props tg nil 'face
14137 (cond
14138 ((not (assoc tg table))
14139 (org-get-todo-face tg))
14140 ((member tg current) c-face)
14141 ((member tg inherited) i-face))))
14142 (if (and (= cnt 0) (not ingroup)) (insert " "))
14143 (insert "[" c "] " tg (make-string
14144 (- fwidth 4 (length tg)) ?\ ))
14145 (push (cons tg c) ntable)
14146 (when (= (setq cnt (1+ cnt)) ncol)
14147 (insert "\n")
14148 (if ingroup (insert " "))
14149 (setq cnt 0)))))
14150 (setq ntable (nreverse ntable))
14151 (insert "\n")
14152 (goto-char (point-min))
14153 (if (not expert) (org-fit-window-to-buffer))
14154 (setq rtn
14155 (catch 'exit
14156 (while t
14157 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14158 (if (not groups) "no " "")
14159 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14160 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14161 (setq org-last-tag-selection-key c)
14162 (cond
14163 ((= c ?\r) (throw 'exit t))
14164 ((= c ?!)
14165 (setq groups (not groups))
14166 (goto-char (point-min))
14167 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14168 ((= c ?\C-c)
14169 (if (not expert)
14170 (org-fast-tag-show-exit
14171 (setq exit-after-next (not exit-after-next)))
14172 (setq expert nil)
14173 (delete-other-windows)
14174 (set-window-buffer (split-window-vertically) " *Org tags*")
14175 (org-switch-to-buffer-other-window " *Org tags*")
14176 (org-fit-window-to-buffer)))
14177 ((or (= c ?\C-g)
14178 (and (= c ?q) (not (rassoc c ntable))))
14179 (org-detach-overlay org-tags-overlay)
14180 (setq quit-flag t))
14181 ((= c ?\ )
14182 (setq current nil)
14183 (if exit-after-next (setq exit-after-next 'now)))
14184 ((= c ?\t)
14185 (condition-case nil
14186 (setq tg (org-icompleting-read
14187 "Tag: "
14188 (or buffer-tags
14189 (with-current-buffer buf
14190 (org-get-buffer-tags)))))
14191 (quit (setq tg "")))
14192 (when (string-match "\\S-" tg)
14193 (add-to-list 'buffer-tags (list tg))
14194 (if (member tg current)
14195 (setq current (delete tg current))
14196 (push tg current)))
14197 (if exit-after-next (setq exit-after-next 'now)))
14198 ((setq e (rassoc c todo-table) tg (car e))
14199 (with-current-buffer buf
14200 (save-excursion (org-todo tg)))
14201 (if exit-after-next (setq exit-after-next 'now)))
14202 ((setq e (rassoc c ntable) tg (car e))
14203 (if (member tg current)
14204 (setq current (delete tg current))
14205 (loop for g in groups do
14206 (if (member tg g)
14207 (mapc (lambda (x)
14208 (setq current (delete x current)))
14209 g)))
14210 (push tg current))
14211 (if exit-after-next (setq exit-after-next 'now))))
14213 ;; Create a sorted list
14214 (setq current
14215 (sort current
14216 (lambda (a b)
14217 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14218 (if (eq exit-after-next 'now) (throw 'exit t))
14219 (goto-char (point-min))
14220 (beginning-of-line 2)
14221 (delete-region (point) (point-at-eol))
14222 (org-fast-tag-insert "Current" current c-face)
14223 (org-set-current-tags-overlay current ov-prefix)
14224 (while (re-search-forward
14225 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14226 (setq tg (match-string 1))
14227 (add-text-properties
14228 (match-beginning 1) (match-end 1)
14229 (list 'face
14230 (cond
14231 ((member tg current) c-face)
14232 ((member tg inherited) i-face)
14233 (t (get-text-property (match-beginning 1) 'face))))))
14234 (goto-char (point-min)))))
14235 (org-detach-overlay org-tags-overlay)
14236 (if rtn
14237 (mapconcat 'identity current ":")
14238 nil))))
14240 (defun org-get-tags-string ()
14241 "Get the TAGS string in the current headline."
14242 (unless (org-at-heading-p t)
14243 (error "Not on a heading"))
14244 (save-excursion
14245 (beginning-of-line 1)
14246 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14247 (org-match-string-no-properties 1)
14248 "")))
14250 (defun org-get-tags ()
14251 "Get the list of tags specified in the current headline."
14252 (org-split-string (org-get-tags-string) ":"))
14254 (defun org-get-buffer-tags ()
14255 "Get a table of all tags used in the buffer, for completion."
14256 (let (tags)
14257 (save-excursion
14258 (goto-char (point-min))
14259 (while (re-search-forward
14260 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14261 (when (equal (char-after (point-at-bol 0)) ?*)
14262 (mapc (lambda (x) (add-to-list 'tags x))
14263 (org-split-string (org-match-string-no-properties 1) ":")))))
14264 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14265 (mapcar 'list tags)))
14267 ;;;; The mapping API
14269 (defun org-map-entries (func &optional match scope &rest skip)
14270 "Call FUNC at each headline selected by MATCH in SCOPE.
14272 FUNC is a function or a lisp form. The function will be called without
14273 arguments, with the cursor positioned at the beginning of the headline.
14274 The return values of all calls to the function will be collected and
14275 returned as a list.
14277 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14278 does not need to preserve point. After evaluation, the cursor will be
14279 moved to the end of the line (presumably of the headline of the
14280 processed entry) and search continues from there. Under some
14281 circumstances, this may not produce the wanted results. For example,
14282 if you have removed (e.g. archived) the current (sub)tree it could
14283 mean that the next entry will be skipped entirely. In such cases, you
14284 can specify the position from where search should continue by making
14285 FUNC set the variable `org-map-continue-from' to the desired buffer
14286 position.
14288 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14289 Only headlines that are matched by this query will be considered during
14290 the iteration. When MATCH is nil or t, all headlines will be
14291 visited by the iteration.
14293 SCOPE determines the scope of this command. It can be any of:
14295 nil The current buffer, respecting the restriction if any
14296 tree The subtree started with the entry at point
14297 region The entries within the active region, if any
14298 region-start-level
14299 The entries within the active region, but only those at
14300 the same level than the first one.
14301 file The current buffer, without restriction
14302 file-with-archives
14303 The current buffer, and any archives associated with it
14304 agenda All agenda files
14305 agenda-with-archives
14306 All agenda files with any archive files associated with them
14307 \(file1 file2 ...)
14308 If this is a list, all files in the list will be scanned
14310 The remaining args are treated as settings for the skipping facilities of
14311 the scanner. The following items can be given here:
14313 archive skip trees with the archive tag.
14314 comment skip trees with the COMMENT keyword
14315 function or Emacs Lisp form:
14316 will be used as value for `org-agenda-skip-function', so whenever
14317 the function returns t, FUNC will not be called for that
14318 entry and search will continue from the point where the
14319 function leaves it.
14321 If your function needs to retrieve the tags including inherited tags
14322 at the *current* entry, you can use the value of the variable
14323 `org-scanner-tags' which will be much faster than getting the value
14324 with `org-get-tags-at'. If your function gets properties with
14325 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14326 to t around the call to `org-entry-properties' to get the same speedup.
14327 Note that if your function moves around to retrieve tags and properties at
14328 a *different* entry, you cannot use these techniques."
14329 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14330 (not (org-region-active-p)))
14331 (let* ((org-agenda-archives-mode nil) ; just to make sure
14332 (org-agenda-skip-archived-trees (memq 'archive skip))
14333 (org-agenda-skip-comment-trees (memq 'comment skip))
14334 (org-agenda-skip-function
14335 (car (org-delete-all '(comment archive) skip)))
14336 (org-tags-match-list-sublevels t)
14337 (start-level (eq scope 'region-start-level))
14338 matcher file res
14339 org-todo-keywords-for-agenda
14340 org-done-keywords-for-agenda
14341 org-todo-keyword-alist-for-agenda
14342 org-drawers-for-agenda
14343 org-tag-alist-for-agenda
14344 todo-only)
14346 (cond
14347 ((eq match t) (setq matcher t))
14348 ((eq match nil) (setq matcher t))
14349 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14351 (save-excursion
14352 (save-restriction
14353 (cond ((eq scope 'tree)
14354 (org-back-to-heading t)
14355 (org-narrow-to-subtree)
14356 (setq scope nil))
14357 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14358 (org-region-active-p))
14359 ;; If needed, set start-level to a string like "2"
14360 (when start-level
14361 (save-excursion
14362 (goto-char (region-beginning))
14363 (unless (org-at-heading-p) (outline-next-heading))
14364 (setq start-level (org-current-level))))
14365 (narrow-to-region (region-beginning)
14366 (save-excursion
14367 (goto-char (region-end))
14368 (unless (and (bolp) (org-at-heading-p))
14369 (outline-next-heading))
14370 (point)))
14371 (setq scope nil)))
14373 (if (not scope)
14374 (progn
14375 (org-agenda-prepare-buffers
14376 (list (buffer-file-name (current-buffer))))
14377 (setq res (org-scan-tags func matcher todo-only start-level)))
14378 ;; Get the right scope
14379 (cond
14380 ((and scope (listp scope) (symbolp (car scope)))
14381 (setq scope (eval scope)))
14382 ((eq scope 'agenda)
14383 (setq scope (org-agenda-files t)))
14384 ((eq scope 'agenda-with-archives)
14385 (setq scope (org-agenda-files t))
14386 (setq scope (org-add-archive-files scope)))
14387 ((eq scope 'file)
14388 (setq scope (list (buffer-file-name))))
14389 ((eq scope 'file-with-archives)
14390 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14391 (org-agenda-prepare-buffers scope)
14392 (while (setq file (pop scope))
14393 (with-current-buffer (org-find-base-buffer-visiting file)
14394 (save-excursion
14395 (save-restriction
14396 (widen)
14397 (goto-char (point-min))
14398 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14399 res)))
14401 ;;;; Properties
14403 ;;; Setting and retrieving properties
14405 (defconst org-special-properties
14406 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14407 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14408 "The special properties valid in Org-mode.
14410 These are properties that are not defined in the property drawer,
14411 but in some other way.")
14413 (defconst org-default-properties
14414 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14415 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14416 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14417 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14418 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14419 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14420 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14421 "Some properties that are used by Org-mode for various purposes.
14422 Being in this list makes sure that they are offered for completion.")
14424 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14425 "Regular expression matching the first line of a property drawer.")
14427 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14428 "Regular expression matching the last line of a property drawer.")
14430 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14431 "Regular expression matching the first line of a property drawer.")
14433 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14434 "Regular expression matching the first line of a property drawer.")
14436 (defconst org-property-drawer-re
14437 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14438 org-property-end-re "\\)\n?")
14439 "Matches an entire property drawer.")
14441 (defconst org-clock-drawer-re
14442 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14443 org-property-end-re "\\)\n?")
14444 "Matches an entire clock drawer.")
14446 (defsubst org-re-property (property)
14447 "Return a regexp matching a PROPERTY line.
14448 Match group 1 will be set to the value."
14449 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14451 (defsubst org-re-property-keyword (property)
14452 "Return a regexp matching a PROPERTY line, possibly with no
14453 value for the property."
14454 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14456 (defun org-property-action ()
14457 "Do an action on properties."
14458 (interactive)
14459 (let (c)
14460 (org-at-property-p)
14461 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14462 (setq c (read-char-exclusive))
14463 (cond
14464 ((equal c ?s)
14465 (call-interactively 'org-set-property))
14466 ((equal c ?d)
14467 (call-interactively 'org-delete-property))
14468 ((equal c ?D)
14469 (call-interactively 'org-delete-property-globally))
14470 ((equal c ?c)
14471 (call-interactively 'org-compute-property-at-point))
14472 (t (error "No such property action %c" c)))))
14474 (defun org-inc-effort ()
14475 "Increment the value of the effort property in the current entry."
14476 (interactive)
14477 (org-set-effort nil t))
14479 (defun org-set-effort (&optional value increment)
14480 "Set the effort property of the current entry.
14481 With numerical prefix arg, use the nth allowed value, 0 stands for the
14482 10th allowed value.
14484 When INCREMENT is non-nil, set the property to the next allowed value."
14485 (interactive "P")
14486 (if (equal value 0) (setq value 10))
14487 (let* ((completion-ignore-case t)
14488 (prop org-effort-property)
14489 (cur (org-entry-get nil prop))
14490 (allowed (org-property-get-allowed-values nil prop 'table))
14491 (existing (mapcar 'list (org-property-values prop)))
14493 (val (cond
14494 ((stringp value) value)
14495 ((and allowed (integerp value))
14496 (or (car (nth (1- value) allowed))
14497 (car (org-last allowed))))
14498 ((and allowed increment)
14499 (or (caadr (member (list cur) allowed))
14500 (error "Allowed effort values are not set")))
14501 (allowed
14502 (message "Select 1-9,0, [RET%s]: %s"
14503 (if cur (concat "=" cur) "")
14504 (mapconcat 'car allowed " "))
14505 (setq rpl (read-char-exclusive))
14506 (if (equal rpl ?\r)
14508 (setq rpl (- rpl ?0))
14509 (if (equal rpl 0) (setq rpl 10))
14510 (if (and (> rpl 0) (<= rpl (length allowed)))
14511 (car (nth (1- rpl) allowed))
14512 (org-completing-read "Effort: " allowed nil))))
14514 (let (org-completion-use-ido org-completion-use-iswitchb)
14515 (org-completing-read
14516 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14517 (concat "[" cur "]") "")
14518 ": ")
14519 existing nil nil "" nil cur))))))
14520 (unless (equal (org-entry-get nil prop) val)
14521 (org-entry-put nil prop val))
14522 (message "%s is now %s" prop val)))
14524 (defun org-at-property-p ()
14525 "Is cursor inside a property drawer?"
14526 (save-excursion
14527 (beginning-of-line 1)
14528 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14529 (save-match-data ;; Used by calling procedures
14530 (let ((p (point))
14531 (range (unless (org-before-first-heading-p)
14532 (org-get-property-block))))
14533 (and range (<= (car range) p) (< p (cdr range))))))))
14535 (defun org-get-property-block (&optional beg end force)
14536 "Return the (beg . end) range of the body of the property drawer.
14537 BEG and END are the beginning and end of the current subtree, or of
14538 the part before the first headline. If they are not given, they will
14539 be found. If the drawer does not exist and FORCE is non-nil, create
14540 the drawer."
14541 (catch 'exit
14542 (save-excursion
14543 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14544 (progn (org-back-to-heading t) (point))))
14545 (end (or end (and (not (outline-next-heading)) (point-max))
14546 (point))))
14547 (goto-char beg)
14548 (if (re-search-forward org-property-start-re end t)
14549 (setq beg (1+ (match-end 0)))
14550 (if force
14551 (save-excursion
14552 (org-insert-property-drawer)
14553 (setq end (progn (outline-next-heading) (point))))
14554 (throw 'exit nil))
14555 (goto-char beg)
14556 (if (re-search-forward org-property-start-re end t)
14557 (setq beg (1+ (match-end 0)))))
14558 (if (re-search-forward org-property-end-re end t)
14559 (setq end (match-beginning 0))
14560 (or force (throw 'exit nil))
14561 (goto-char beg)
14562 (setq end beg)
14563 (org-indent-line)
14564 (insert ":END:\n"))
14565 (cons beg end)))))
14567 (defun org-entry-properties (&optional pom which specific)
14568 "Get all properties of the entry at point-or-marker POM.
14569 This includes the TODO keyword, the tags, time strings for deadline,
14570 scheduled, and clocking, and any additional properties defined in the
14571 entry. The return value is an alist, keys may occur multiple times
14572 if the property key was used several times.
14573 POM may also be nil, in which case the current entry is used.
14574 If WHICH is nil or `all', get all properties. If WHICH is
14575 `special' or `standard', only get that subclass. If WHICH
14576 is a string only get exactly this property. SPECIFIC can be a string, the
14577 specific property we are interested in. Specifying it can speed
14578 things up because then unnecessary parsing is avoided."
14579 (setq which (or which 'all))
14580 (org-with-point-at pom
14581 (let ((clockstr (substring org-clock-string 0 -1))
14582 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14583 (case-fold-search nil)
14584 beg end range props sum-props key key1 value string clocksum clocksumt)
14585 (save-excursion
14586 (when (condition-case nil
14587 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14588 (error nil))
14589 (setq beg (point))
14590 (setq sum-props (get-text-property (point) 'org-summaries))
14591 (setq clocksum (get-text-property (point) :org-clock-minutes)
14592 clocksumt (get-text-property (point) :org-clock-minutes-today))
14593 (outline-next-heading)
14594 (setq end (point))
14595 (when (memq which '(all special))
14596 ;; Get the special properties, like TODO and tags
14597 (goto-char beg)
14598 (when (and (or (not specific) (string= specific "TODO"))
14599 (looking-at org-todo-line-regexp) (match-end 2))
14600 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14601 (when (and (or (not specific) (string= specific "PRIORITY"))
14602 (looking-at org-priority-regexp))
14603 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14604 (when (or (not specific) (string= specific "FILE"))
14605 (push (cons "FILE" buffer-file-name) props))
14606 (when (and (or (not specific) (string= specific "TAGS"))
14607 (setq value (org-get-tags-string))
14608 (string-match "\\S-" value))
14609 (push (cons "TAGS" value) props))
14610 (when (and (or (not specific) (string= specific "ALLTAGS"))
14611 (setq value (org-get-tags-at)))
14612 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14613 ":"))
14614 props))
14615 (when (or (not specific) (string= specific "BLOCKED"))
14616 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14617 (when (or (not specific)
14618 (member specific
14619 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14620 "TIMESTAMP" "TIMESTAMP_IA")))
14621 (catch 'match
14622 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14623 (setq key (if (match-end 1)
14624 (substring (org-match-string-no-properties 1)
14625 0 -1))
14626 string (if (equal key clockstr)
14627 (org-trim
14628 (buffer-substring-no-properties
14629 (match-beginning 3) (goto-char
14630 (point-at-eol))))
14631 (substring (org-match-string-no-properties 3)
14632 1 -1)))
14633 ;; Get the correct property name from the key. This is
14634 ;; necessary if the user has configured time keywords.
14635 (setq key1 (concat key ":"))
14636 (cond
14637 ((not key)
14638 (setq key
14639 (if (= (char-after (match-beginning 3)) ?\[)
14640 "TIMESTAMP_IA" "TIMESTAMP")))
14641 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14642 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14643 ((equal key1 org-closed-string) (setq key "CLOSED"))
14644 ((equal key1 org-clock-string) (setq key "CLOCK")))
14645 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14646 (progn
14647 (push (cons key string) props)
14648 ;; no need to search further if match is found
14649 (throw 'match t))
14650 (when (or (equal key "CLOCK") (not (assoc key props)))
14651 (push (cons key string) props)))))))
14653 (when (memq which '(all standard))
14654 ;; Get the standard properties, like :PROP: ...
14655 (setq range (org-get-property-block beg end))
14656 (when range
14657 (goto-char (car range))
14658 (while (re-search-forward
14659 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14660 (cdr range) t)
14661 (setq key (org-match-string-no-properties 1)
14662 value (org-trim (or (org-match-string-no-properties 2) "")))
14663 (unless (member key excluded)
14664 (push (cons key (or value "")) props)))))
14665 (if clocksum
14666 (push (cons "CLOCKSUM"
14667 (org-columns-number-to-string (/ (float clocksum) 60.)
14668 'add_times))
14669 props))
14670 (if clocksumt
14671 (push (cons "CLOCKSUM_T"
14672 (org-columns-number-to-string (/ (float clocksumt) 60.)
14673 'add_times))
14674 props))
14675 (unless (assoc "CATEGORY" props)
14676 (push (cons "CATEGORY" (org-get-category)) props))
14677 (append sum-props (nreverse props)))))))
14679 (defun org-entry-get (pom property &optional inherit literal-nil)
14680 "Get value of PROPERTY for entry or content at point-or-marker POM.
14681 If INHERIT is non-nil and the entry does not have the property,
14682 then also check higher levels of the hierarchy.
14683 If INHERIT is the symbol `selective', use inheritance only if the setting
14684 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14685 If the property is present but empty, the return value is the empty string.
14686 If the property is not present at all, nil is returned.
14688 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14689 do not interpret it as the list atom nil. This is used for inheritance
14690 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14691 (org-with-point-at pom
14692 (if (and inherit (if (eq inherit 'selective)
14693 (org-property-inherit-p property)
14695 (org-entry-get-with-inheritance property literal-nil)
14696 (if (member property org-special-properties)
14697 ;; We need a special property. Use `org-entry-properties' to
14698 ;; retrieve it, but specify the wanted property
14699 (cdr (assoc property (org-entry-properties nil 'special property)))
14700 (let* ((range (org-get-property-block))
14701 (props (list (or (assoc property org-file-properties)
14702 (assoc property org-global-properties)
14703 (assoc property org-global-properties-fixed))))
14704 (ap (lambda (key)
14705 (when (re-search-forward
14706 (org-re-property key) (cdr range) t)
14707 (setq props
14708 (org-update-property-plist
14710 (if (match-end 1)
14711 (org-match-string-no-properties 1) "")
14712 props)))))
14713 val)
14714 (when (and range (goto-char (car range)))
14715 (funcall ap property)
14716 (goto-char (car range))
14717 (while (funcall ap (concat property "+")))
14718 (setq val (cdr (assoc property props)))
14719 (when val (if literal-nil val (org-not-nil val)))))))))
14721 (defun org-property-or-variable-value (var &optional inherit)
14722 "Check if there is a property fixing the value of VAR.
14723 If yes, return this value. If not, return the current value of the variable."
14724 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14725 (if (and prop (stringp prop) (string-match "\\S-" prop))
14726 (read prop)
14727 (symbol-value var))))
14729 (defun org-entry-delete (pom property)
14730 "Delete the property PROPERTY from entry at point-or-marker POM."
14731 (org-with-point-at pom
14732 (if (member property org-special-properties)
14733 nil ; cannot delete these properties.
14734 (let ((range (org-get-property-block)))
14735 (if (and range
14736 (goto-char (car range))
14737 (re-search-forward
14738 (org-re-property property)
14739 (cdr range) t))
14740 (progn
14741 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14743 nil)))))
14745 ;; Multi-values properties are properties that contain multiple values
14746 ;; These values are assumed to be single words, separated by whitespace.
14747 (defun org-entry-add-to-multivalued-property (pom property value)
14748 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14749 (let* ((old (org-entry-get pom property))
14750 (values (and old (org-split-string old "[ \t]"))))
14751 (setq value (org-entry-protect-space value))
14752 (unless (member value values)
14753 (setq values (cons value values))
14754 (org-entry-put pom property
14755 (mapconcat 'identity values " ")))))
14757 (defun org-entry-remove-from-multivalued-property (pom property value)
14758 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14759 (let* ((old (org-entry-get pom property))
14760 (values (and old (org-split-string old "[ \t]"))))
14761 (setq value (org-entry-protect-space value))
14762 (when (member value values)
14763 (setq values (delete value values))
14764 (org-entry-put pom property
14765 (mapconcat 'identity values " ")))))
14767 (defun org-entry-member-in-multivalued-property (pom property value)
14768 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14769 (let* ((old (org-entry-get pom property))
14770 (values (and old (org-split-string old "[ \t]"))))
14771 (setq value (org-entry-protect-space value))
14772 (member value values)))
14774 (defun org-entry-get-multivalued-property (pom property)
14775 "Return a list of values in a multivalued property."
14776 (let* ((value (org-entry-get pom property))
14777 (values (and value (org-split-string value "[ \t]"))))
14778 (mapcar 'org-entry-restore-space values)))
14780 (defun org-entry-put-multivalued-property (pom property &rest values)
14781 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14782 VALUES should be a list of strings. Spaces will be protected."
14783 (org-entry-put pom property
14784 (mapconcat 'org-entry-protect-space values " "))
14785 (let* ((value (org-entry-get pom property))
14786 (values (and value (org-split-string value "[ \t]"))))
14787 (mapcar 'org-entry-restore-space values)))
14789 (defun org-entry-protect-space (s)
14790 "Protect spaces and newline in string S."
14791 (while (string-match " " s)
14792 (setq s (replace-match "%20" t t s)))
14793 (while (string-match "\n" s)
14794 (setq s (replace-match "%0A" t t s)))
14797 (defun org-entry-restore-space (s)
14798 "Restore spaces and newline in string S."
14799 (while (string-match "%20" s)
14800 (setq s (replace-match " " t t s)))
14801 (while (string-match "%0A" s)
14802 (setq s (replace-match "\n" t t s)))
14805 (defvar org-entry-property-inherited-from (make-marker)
14806 "Marker pointing to the entry from where a property was inherited.
14807 Each call to `org-entry-get-with-inheritance' will set this marker to the
14808 location of the entry where the inheritance search matched. If there was
14809 no match, the marker will point nowhere.
14810 Note that also `org-entry-get' calls this function, if the INHERIT flag
14811 is set.")
14813 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14814 "Get PROPERTY of entry or content at point, search higher levels if needed.
14815 The search will stop at the first ancestor which has the property defined.
14816 If the value found is \"nil\", return nil to show that the property
14817 should be considered as undefined (this is the meaning of nil here).
14818 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14819 (move-marker org-entry-property-inherited-from nil)
14820 (let (tmp)
14821 (save-excursion
14822 (save-restriction
14823 (widen)
14824 (catch 'ex
14825 (while t
14826 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14827 (or (ignore-errors (org-back-to-heading t))
14828 (goto-char (point-min)))
14829 (move-marker org-entry-property-inherited-from (point))
14830 (throw 'ex tmp))
14831 (or (ignore-errors (org-up-heading-safe))
14832 (throw 'ex nil))))))
14833 (setq tmp (or tmp
14834 (cdr (assoc property org-file-properties))
14835 (cdr (assoc property org-global-properties))
14836 (cdr (assoc property org-global-properties-fixed))))
14837 (if literal-nil tmp (org-not-nil tmp))))
14839 (defvar org-property-changed-functions nil
14840 "Hook called when the value of a property has changed.
14841 Each hook function should accept two arguments, the name of the property
14842 and the new value.")
14844 (defun org-entry-put (pom property value)
14845 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14846 (org-with-point-at pom
14847 (org-back-to-heading t)
14848 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14849 range)
14850 (cond
14851 ((equal property "TODO")
14852 (when (and (stringp value) (string-match "\\S-" value)
14853 (not (member value org-todo-keywords-1)))
14854 (error "\"%s\" is not a valid TODO state" value))
14855 (if (or (not value)
14856 (not (string-match "\\S-" value)))
14857 (setq value 'none))
14858 (org-todo value)
14859 (org-set-tags nil 'align))
14860 ((equal property "PRIORITY")
14861 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14862 (string-to-char value) ?\ ))
14863 (org-set-tags nil 'align))
14864 ((equal property "CLOCKSUM")
14865 (if (not (re-search-forward
14866 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14867 (error "Cannot find a clock log")
14868 (goto-char (- (match-end 1) 2))
14869 (cond
14870 ((eq value 'earlier) (org-timestamp-down))
14871 ((eq value 'later) (org-timestamp-up)))
14872 (org-clock-sum-current-item)))
14873 ((equal property "SCHEDULED")
14874 (if (re-search-forward org-scheduled-time-regexp end t)
14875 (cond
14876 ((eq value 'earlier) (org-timestamp-change -1 'day))
14877 ((eq value 'later) (org-timestamp-change 1 'day))
14878 (t (call-interactively 'org-schedule)))
14879 (call-interactively 'org-schedule)))
14880 ((equal property "DEADLINE")
14881 (if (re-search-forward org-deadline-time-regexp end t)
14882 (cond
14883 ((eq value 'earlier) (org-timestamp-change -1 'day))
14884 ((eq value 'later) (org-timestamp-change 1 'day))
14885 (t (call-interactively 'org-deadline)))
14886 (call-interactively 'org-deadline)))
14887 ((member property org-special-properties)
14888 (error "The %s property can not yet be set with `org-entry-put'"
14889 property))
14890 (t ; a non-special property
14891 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14892 (setq range (org-get-property-block beg end 'force))
14893 (goto-char (car range))
14894 (if (re-search-forward
14895 (org-re-property-keyword property) (cdr range) t)
14896 (progn
14897 (delete-region (match-beginning 0) (match-end 0))
14898 (goto-char (match-beginning 0)))
14899 (goto-char (cdr range))
14900 (insert "\n")
14901 (backward-char 1)
14902 (org-indent-line))
14903 (insert ":" property ":")
14904 (and value (insert " " value))
14905 (org-indent-line)))))
14906 (run-hook-with-args 'org-property-changed-functions property value)))
14908 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14909 "Get all property keys in the current buffer.
14910 With INCLUDE-SPECIALS, also list the special properties that reflect things
14911 like tags and TODO state.
14912 With INCLUDE-DEFAULTS, also include properties that has special meaning
14913 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14914 and others.
14915 With INCLUDE-COLUMNS, also include property names given in COLUMN
14916 formats in the current buffer."
14917 (let (rtn range cfmt s p)
14918 (save-excursion
14919 (save-restriction
14920 (widen)
14921 (goto-char (point-min))
14922 (while (re-search-forward org-property-start-re nil t)
14923 (setq range (org-get-property-block))
14924 (goto-char (car range))
14925 (while (re-search-forward
14926 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14927 (cdr range) t)
14928 (add-to-list 'rtn (org-match-string-no-properties 1)))
14929 (outline-next-heading))))
14931 (when include-specials
14932 (setq rtn (append org-special-properties rtn)))
14934 (when include-defaults
14935 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14936 (add-to-list 'rtn org-effort-property))
14938 (when include-columns
14939 (save-excursion
14940 (save-restriction
14941 (widen)
14942 (goto-char (point-min))
14943 (while (re-search-forward
14944 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14945 nil t)
14946 (setq cfmt (match-string 2) s 0)
14947 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14948 cfmt s)
14949 (setq s (match-end 0)
14950 p (match-string 1 cfmt))
14951 (unless (or (equal p "ITEM")
14952 (member p org-special-properties))
14953 (add-to-list 'rtn (match-string 1 cfmt))))))))
14955 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14957 (defun org-property-values (key)
14958 "Return a list of all values of property KEY in the current buffer."
14959 (save-excursion
14960 (save-restriction
14961 (widen)
14962 (goto-char (point-min))
14963 (let ((re (org-re-property key))
14964 values)
14965 (while (re-search-forward re nil t)
14966 (add-to-list 'values (org-trim (match-string 1))))
14967 (delete "" values)))))
14969 (defun org-insert-property-drawer ()
14970 "Insert a property drawer into the current entry."
14971 (org-back-to-heading t)
14972 (looking-at org-outline-regexp)
14973 (let ((indent (if org-adapt-indentation
14974 (- (match-end 0) (match-beginning 0))
14976 (beg (point))
14977 (re (concat "^[ \t]*" org-keyword-time-regexp))
14978 end hiddenp)
14979 (outline-next-heading)
14980 (setq end (point))
14981 (goto-char beg)
14982 (while (re-search-forward re end t))
14983 (setq hiddenp (outline-invisible-p))
14984 (end-of-line 1)
14985 (and (equal (char-after) ?\n) (forward-char 1))
14986 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14987 (if (member (match-string 1) '("CLOCK:" ":END:"))
14988 ;; just skip this line
14989 (beginning-of-line 2)
14990 ;; Drawer start, find the end
14991 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14992 (beginning-of-line 1)))
14993 (org-skip-over-state-notes)
14994 (skip-chars-backward " \t\n\r")
14995 (if (eq (char-before) ?*) (forward-char 1))
14996 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14997 (beginning-of-line 0)
14998 (org-indent-to-column indent)
14999 (beginning-of-line 2)
15000 (org-indent-to-column indent)
15001 (beginning-of-line 0)
15002 (if hiddenp
15003 (save-excursion
15004 (org-back-to-heading t)
15005 (hide-entry))
15006 (org-flag-drawer t))))
15008 (defun org-insert-drawer (&optional arg drawer)
15009 "Insert a drawer at point.
15011 Optional argument DRAWER, when non-nil, is a string representing
15012 drawer's name. Otherwise, the user is prompted for a name.
15014 If a region is active, insert the drawer around that region
15015 instead.
15017 Point is left between drawer's boundaries."
15018 (interactive "P")
15019 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15020 "LOGBOOK"))
15021 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15022 ;; internally by Org. They are meant to be inserted
15023 ;; automatically.
15024 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15025 ;; Remove system drawers from list. Note: For some reason,
15026 ;; `org-completing-read' ignores the predicate while
15027 ;; `completing-read' handles it fine.
15028 (drawer (if arg "PROPERTIES"
15029 (or drawer
15030 (completing-read
15031 "Drawer: " org-drawers
15032 (lambda (d) (not (member d system-drawers))))))))
15033 (cond
15034 ;; With C-u, fall back on `org-insert-property-drawer'
15035 (arg (org-insert-property-drawer))
15036 ;; With an active region, insert a drawer at point.
15037 ((not (org-region-active-p))
15038 (progn
15039 (unless (bolp) (insert "\n"))
15040 (insert (format ":%s:\n\n:END:\n" drawer))
15041 (forward-line -2)))
15042 ;; Otherwise, insert the drawer at point
15044 (let ((rbeg (region-beginning))
15045 (rend (copy-marker (region-end))))
15046 (unwind-protect
15047 (progn
15048 (goto-char rbeg)
15049 (beginning-of-line)
15050 (when (save-excursion
15051 (re-search-forward org-outline-regexp-bol rend t))
15052 (error "Drawers cannot contain headlines"))
15053 ;; Position point at the beginning of the first
15054 ;; non-blank line in region. Insert drawer's opening
15055 ;; there, then indent it.
15056 (org-skip-whitespace)
15057 (beginning-of-line)
15058 (insert ":" drawer ":\n")
15059 (forward-line -1)
15060 (indent-for-tab-command)
15061 ;; Move point to the beginning of the first blank line
15062 ;; after the last non-blank line in region. Insert
15063 ;; drawer's closing, then indent it.
15064 (goto-char rend)
15065 (skip-chars-backward " \r\t\n")
15066 (insert "\n:END:")
15067 (deactivate-mark t)
15068 (indent-for-tab-command)
15069 (unless (eolp) (insert "\n")))
15070 ;; Clear marker, whatever the outcome of insertion is.
15071 (set-marker rend nil)))))))
15073 (defvar org-property-set-functions-alist nil
15074 "Property set function alist.
15075 Each entry should have the following format:
15077 (PROPERTY . READ-FUNCTION)
15079 The read function will be called with the same argument as
15080 `org-completing-read'.")
15082 (defun org-set-property-function (property)
15083 "Get the function that should be used to set PROPERTY.
15084 This is computed according to `org-property-set-functions-alist'."
15085 (or (cdr (assoc property org-property-set-functions-alist))
15086 'org-completing-read))
15088 (defun org-read-property-value (property)
15089 "Read PROPERTY value from user."
15090 (let* ((completion-ignore-case t)
15091 (allowed (org-property-get-allowed-values nil property 'table))
15092 (cur (org-entry-get nil property))
15093 (prompt (concat property " value"
15094 (if (and cur (string-match "\\S-" cur))
15095 (concat " [" cur "]") "") ": "))
15096 (set-function (org-set-property-function property))
15097 (val (if allowed
15098 (funcall set-function prompt allowed nil
15099 (not (get-text-property 0 'org-unrestricted
15100 (caar allowed))))
15101 (let (org-completion-use-ido org-completion-use-iswitchb)
15102 (funcall set-function prompt
15103 (mapcar 'list (org-property-values property))
15104 nil nil "" nil cur)))))
15105 (if (equal val "")
15107 val)))
15109 (defvar org-last-set-property nil)
15110 (defvar org-last-set-property-value nil)
15111 (defun org-read-property-name ()
15112 "Read a property name."
15113 (let* ((completion-ignore-case t)
15114 (keys (org-buffer-property-keys nil t t))
15115 (default-prop (or (save-excursion
15116 (save-match-data
15117 (beginning-of-line)
15118 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15119 (null (string= (match-string 1) "END"))
15120 (match-string 1))))
15121 org-last-set-property))
15122 (property (org-icompleting-read
15123 (concat "Property"
15124 (if default-prop (concat " [" default-prop "]") "")
15125 ": ")
15126 (mapcar 'list keys)
15127 nil nil nil nil
15128 default-prop)))
15129 (if (member property keys)
15130 property
15131 (or (cdr (assoc (downcase property)
15132 (mapcar (lambda (x) (cons (downcase x) x))
15133 keys)))
15134 property))))
15136 (defun org-set-property-and-value (use-last)
15137 "Allow to set [PROPERTY]: [value] direction from prompt.
15138 When use-default, don't even ask, just use the last
15139 \"[PROPERTY]: [value]\" string from the history."
15140 (interactive "P")
15141 (let* ((completion-ignore-case t)
15142 (pv (or (and use-last org-last-set-property-value)
15143 (org-completing-read
15144 "Enter a \"[Property]: [value]\" pair: "
15145 nil nil nil nil nil
15146 org-last-set-property-value)))
15147 prop val)
15148 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15149 (setq prop (match-string 1 pv)
15150 val (match-string 2 pv))
15151 (org-set-property prop val))))
15153 (defun org-set-property (property value)
15154 "In the current entry, set PROPERTY to VALUE.
15155 When called interactively, this will prompt for a property name, offering
15156 completion on existing and default properties. And then it will prompt
15157 for a value, offering completion either on allowed values (via an inherited
15158 xxx_ALL property) or on existing values in other instances of this property
15159 in the current file."
15160 (interactive (list nil nil))
15161 (let* ((property (or property (org-read-property-name)))
15162 (value (or value (org-read-property-value property)))
15163 (fn (cdr (assoc property org-properties-postprocess-alist))))
15164 (setq org-last-set-property property)
15165 (setq org-last-set-property-value (concat property ": " value))
15166 ;; Possibly postprocess the inserted value:
15167 (when fn (setq value (funcall fn value)))
15168 (unless (equal (org-entry-get nil property) value)
15169 (org-entry-put nil property value))))
15171 (defun org-delete-property (property)
15172 "In the current entry, delete PROPERTY."
15173 (interactive
15174 (let* ((completion-ignore-case t)
15175 (prop (org-icompleting-read "Property: "
15176 (org-entry-properties nil 'standard))))
15177 (list prop)))
15178 (message "Property %s %s" property
15179 (if (org-entry-delete nil property)
15180 "deleted"
15181 "was not present in the entry")))
15183 (defun org-delete-property-globally (property)
15184 "Remove PROPERTY globally, from all entries."
15185 (interactive
15186 (let* ((completion-ignore-case t)
15187 (prop (org-icompleting-read
15188 "Globally remove property: "
15189 (mapcar 'list (org-buffer-property-keys)))))
15190 (list prop)))
15191 (save-excursion
15192 (save-restriction
15193 (widen)
15194 (goto-char (point-min))
15195 (let ((cnt 0))
15196 (while (re-search-forward
15197 (org-re-property property)
15198 nil t)
15199 (setq cnt (1+ cnt))
15200 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15201 (message "Property \"%s\" removed from %d entries" property cnt)))))
15203 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15205 (defun org-compute-property-at-point ()
15206 "Compute the property at point.
15207 This looks for an enclosing column format, extracts the operator and
15208 then applies it to the property in the column format's scope."
15209 (interactive)
15210 (unless (org-at-property-p)
15211 (error "Not at a property"))
15212 (let ((prop (org-match-string-no-properties 2)))
15213 (org-columns-get-format-and-top-level)
15214 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15215 (error "No operator defined for property %s" prop))
15216 (org-columns-compute prop)))
15218 (defvar org-property-allowed-value-functions nil
15219 "Hook for functions supplying allowed values for a specific property.
15220 The functions must take a single argument, the name of the property, and
15221 return a flat list of allowed values. If \":ETC\" is one of
15222 the values, this means that these values are intended as defaults for
15223 completion, but that other values should be allowed too.
15224 The functions must return nil if they are not responsible for this
15225 property.")
15227 (defun org-property-get-allowed-values (pom property &optional table)
15228 "Get allowed values for the property PROPERTY.
15229 When TABLE is non-nil, return an alist that can directly be used for
15230 completion."
15231 (let (vals)
15232 (cond
15233 ((equal property "TODO")
15234 (setq vals (org-with-point-at pom
15235 (append org-todo-keywords-1 '("")))))
15236 ((equal property "PRIORITY")
15237 (let ((n org-lowest-priority))
15238 (while (>= n org-highest-priority)
15239 (push (char-to-string n) vals)
15240 (setq n (1- n)))))
15241 ((member property org-special-properties))
15242 ((setq vals (run-hook-with-args-until-success
15243 'org-property-allowed-value-functions property)))
15245 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15246 (when (and vals (string-match "\\S-" vals))
15247 (setq vals (car (read-from-string (concat "(" vals ")"))))
15248 (setq vals (mapcar (lambda (x)
15249 (cond ((stringp x) x)
15250 ((numberp x) (number-to-string x))
15251 ((symbolp x) (symbol-name x))
15252 (t "???")))
15253 vals)))))
15254 (when (member ":ETC" vals)
15255 (setq vals (remove ":ETC" vals))
15256 (org-add-props (car vals) '(org-unrestricted t)))
15257 (if table (mapcar 'list vals) vals)))
15259 (defun org-property-previous-allowed-value (&optional previous)
15260 "Switch to the next allowed value for this property."
15261 (interactive)
15262 (org-property-next-allowed-value t))
15264 (defun org-property-next-allowed-value (&optional previous)
15265 "Switch to the next allowed value for this property."
15266 (interactive)
15267 (unless (org-at-property-p)
15268 (error "Not at a property"))
15269 (let* ((key (match-string 2))
15270 (value (match-string 3))
15271 (allowed (or (org-property-get-allowed-values (point) key)
15272 (and (member value '("[ ]" "[-]" "[X]"))
15273 '("[ ]" "[X]"))))
15274 nval)
15275 (unless allowed
15276 (error "Allowed values for this property have not been defined"))
15277 (if previous (setq allowed (reverse allowed)))
15278 (if (member value allowed)
15279 (setq nval (car (cdr (member value allowed)))))
15280 (setq nval (or nval (car allowed)))
15281 (if (equal nval value)
15282 (error "Only one allowed value for this property"))
15283 (org-at-property-p)
15284 (replace-match (concat " :" key ": " nval) t t)
15285 (org-indent-line)
15286 (beginning-of-line 1)
15287 (skip-chars-forward " \t")
15288 (run-hook-with-args 'org-property-changed-functions key nval)))
15290 (defun org-find-olp (path &optional this-buffer)
15291 "Return a marker pointing to the entry at outline path OLP.
15292 If anything goes wrong, throw an error.
15293 You can wrap this call to catch the error like this:
15295 (condition-case msg
15296 (org-mobile-locate-entry (match-string 4))
15297 (error (nth 1 msg)))
15299 The return value will then be either a string with the error message,
15300 or a marker if everything is OK.
15302 If THIS-BUFFER is set, the outline path does not contain a file,
15303 only headings."
15304 (let* ((file (if this-buffer buffer-file-name (pop path)))
15305 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15306 (level 1)
15307 (lmin 1)
15308 (lmax 1)
15309 limit re end found pos heading cnt flevel)
15310 (unless buffer (error "File not found :%s" file))
15311 (with-current-buffer buffer
15312 (save-excursion
15313 (save-restriction
15314 (widen)
15315 (setq limit (point-max))
15316 (goto-char (point-min))
15317 (while (setq heading (pop path))
15318 (setq re (format org-complex-heading-regexp-format
15319 (regexp-quote heading)))
15320 (setq cnt 0 pos (point))
15321 (while (re-search-forward re end t)
15322 (setq level (- (match-end 1) (match-beginning 1)))
15323 (if (and (>= level lmin) (<= level lmax))
15324 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15325 (when (= cnt 0) (error "Heading not found on level %d: %s"
15326 lmax heading))
15327 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15328 lmax heading))
15329 (goto-char found)
15330 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15331 (setq end (save-excursion (org-end-of-subtree t t))))
15332 (when (org-at-heading-p)
15333 (point-marker)))))))
15335 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15336 "Find node HEADING in BUFFER.
15337 Return a marker to the heading if it was found, or nil if not.
15338 If POS-ONLY is set, return just the position instead of a marker.
15340 The heading text must match exact, but it may have a TODO keyword,
15341 a priority cookie and tags in the standard locations."
15342 (with-current-buffer (or buffer (current-buffer))
15343 (save-excursion
15344 (save-restriction
15345 (widen)
15346 (goto-char (point-min))
15347 (let (case-fold-search)
15348 (if (re-search-forward
15349 (format org-complex-heading-regexp-format
15350 (regexp-quote heading)) nil t)
15351 (if pos-only
15352 (match-beginning 0)
15353 (move-marker (make-marker) (match-beginning 0)))))))))
15355 (defun org-find-exact-heading-in-directory (heading &optional dir)
15356 "Find Org node headline HEADING in all .org files in directory DIR.
15357 When the target headline is found, return a marker to this location."
15358 (let ((files (directory-files (or dir default-directory)
15359 nil "\\`[^.#].*\\.org\\'"))
15360 file visiting m buffer)
15361 (catch 'found
15362 (while (setq file (pop files))
15363 (message "trying %s" file)
15364 (setq visiting (org-find-base-buffer-visiting file))
15365 (setq buffer (or visiting (find-file-noselect file)))
15366 (setq m (org-find-exact-headline-in-buffer
15367 heading buffer))
15368 (when (and (not m) (not visiting)) (kill-buffer buffer))
15369 (and m (throw 'found m))))))
15371 (defun org-find-entry-with-id (ident)
15372 "Locate the entry that contains the ID property with exact value IDENT.
15373 IDENT can be a string, a symbol or a number, this function will search for
15374 the string representation of it.
15375 Return the position where this entry starts, or nil if there is no such entry."
15376 (interactive "sID: ")
15377 (let ((id (cond
15378 ((stringp ident) ident)
15379 ((symbol-name ident) (symbol-name ident))
15380 ((numberp ident) (number-to-string ident))
15381 (t (error "IDENT %s must be a string, symbol or number" ident))))
15382 (case-fold-search nil))
15383 (save-excursion
15384 (save-restriction
15385 (widen)
15386 (goto-char (point-min))
15387 (when (re-search-forward
15388 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15389 nil t)
15390 (org-back-to-heading t)
15391 (point))))))
15393 ;;;; Timestamps
15395 (defvar org-last-changed-timestamp nil)
15396 (defvar org-last-inserted-timestamp nil
15397 "The last time stamp inserted with `org-insert-time-stamp'.")
15398 (defvar org-time-was-given) ; dynamically scoped parameter
15399 (defvar org-end-time-was-given) ; dynamically scoped parameter
15400 (defvar org-ts-what) ; dynamically scoped parameter
15402 (defun org-time-stamp (arg &optional inactive)
15403 "Prompt for a date/time and insert a time stamp.
15404 If the user specifies a time like HH:MM or if this command is
15405 called with at least one prefix argument, the time stamp contains
15406 the date and the time. Otherwise, only the date is be included.
15408 All parts of a date not specified by the user is filled in from
15409 the current date/time. So if you just press return without
15410 typing anything, the time stamp will represent the current
15411 date/time.
15413 If there is already a timestamp at the cursor, it will be
15414 modified.
15416 With two universal prefix arguments, insert an active timestamp
15417 with the current time without prompting the user."
15418 (interactive "P")
15419 (let* ((ts nil)
15420 (default-time
15421 ;; Default time is either today, or, when entering a range,
15422 ;; the range start.
15423 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15424 (save-excursion
15425 (re-search-backward
15426 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15427 (- (point) 20) t)))
15428 (apply 'encode-time (org-parse-time-string (match-string 1)))
15429 (current-time)))
15430 (default-input (and ts (org-get-compact-tod ts)))
15431 (repeater (save-excursion
15432 (save-match-data
15433 (beginning-of-line)
15434 (when (re-search-forward
15435 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15436 (save-excursion (progn (end-of-line) (point))) t)
15437 (match-string 0)))))
15438 org-time-was-given org-end-time-was-given time)
15439 (cond
15440 ((and (org-at-timestamp-p t)
15441 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15442 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15443 (insert "--")
15444 (setq time (let ((this-command this-command))
15445 (org-read-date arg 'totime nil nil
15446 default-time default-input inactive)))
15447 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15448 ((org-at-timestamp-p t)
15449 (setq time (let ((this-command this-command))
15450 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15451 (when (org-at-timestamp-p t) ; just to get the match data
15452 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15453 (replace-match "")
15454 (setq org-last-changed-timestamp
15455 (org-insert-time-stamp
15456 time (or org-time-was-given arg)
15457 inactive nil nil (list org-end-time-was-given)))
15458 (when repeater (goto-char (1- (point))) (insert " " repeater)
15459 (setq org-last-changed-timestamp
15460 (concat (substring org-last-inserted-timestamp 0 -1)
15461 " " repeater ">"))))
15462 (message "Timestamp updated"))
15463 ((equal arg '(16))
15464 (org-insert-time-stamp (current-time) t))
15466 (setq time (let ((this-command this-command))
15467 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15468 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15469 nil nil (list org-end-time-was-given))))))
15471 ;; FIXME: can we use this for something else, like computing time differences?
15472 (defun org-get-compact-tod (s)
15473 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15474 (let* ((t1 (match-string 1 s))
15475 (h1 (string-to-number (match-string 2 s)))
15476 (m1 (string-to-number (match-string 3 s)))
15477 (t2 (and (match-end 4) (match-string 5 s)))
15478 (h2 (and t2 (string-to-number (match-string 6 s))))
15479 (m2 (and t2 (string-to-number (match-string 7 s))))
15480 dh dm)
15481 (if (not t2)
15483 (setq dh (- h2 h1) dm (- m2 m1))
15484 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15485 (concat t1 "+" (number-to-string dh)
15486 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15488 (defun org-time-stamp-inactive (&optional arg)
15489 "Insert an inactive time stamp.
15490 An inactive time stamp is enclosed in square brackets instead of angle
15491 brackets. It is inactive in the sense that it does not trigger agenda entries,
15492 does not link to the calendar and cannot be changed with the S-cursor keys.
15493 So these are more for recording a certain time/date."
15494 (interactive "P")
15495 (org-time-stamp arg 'inactive))
15497 (defvar org-date-ovl (make-overlay 1 1))
15498 (overlay-put org-date-ovl 'face 'org-date-selected)
15499 (org-detach-overlay org-date-ovl)
15501 (defvar org-ans1) ; dynamically scoped parameter
15502 (defvar org-ans2) ; dynamically scoped parameter
15504 (defvar org-plain-time-of-day-regexp) ; defined below
15506 (defvar org-overriding-default-time nil) ; dynamically scoped
15507 (defvar org-read-date-overlay nil)
15508 (defvar org-dcst nil) ; dynamically scoped
15509 (defvar org-read-date-history nil)
15510 (defvar org-read-date-final-answer nil)
15511 (defvar org-read-date-analyze-futurep nil)
15512 (defvar org-read-date-analyze-forced-year nil)
15513 (defvar org-read-date-inactive)
15515 (defun org-read-date (&optional org-with-time to-time from-string prompt
15516 default-time default-input inactive)
15517 "Read a date, possibly a time, and make things smooth for the user.
15518 The prompt will suggest to enter an ISO date, but you can also enter anything
15519 which will at least partially be understood by `parse-time-string'.
15520 Unrecognized parts of the date will default to the current day, month, year,
15521 hour and minute. If this command is called to replace a timestamp at point,
15522 or to enter the second timestamp of a range, the default time is taken
15523 from the existing stamp. Furthermore, the command prefers the future,
15524 so if you are giving a date where the year is not given, and the day-month
15525 combination is already past in the current year, it will assume you
15526 mean next year. For details, see the manual. A few examples:
15528 3-2-5 --> 2003-02-05
15529 feb 15 --> currentyear-02-15
15530 2/15 --> currentyear-02-15
15531 sep 12 9 --> 2009-09-12
15532 12:45 --> today 12:45
15533 22 sept 0:34 --> currentyear-09-22 0:34
15534 12 --> currentyear-currentmonth-12
15535 Fri --> nearest Friday (today or later)
15536 etc.
15538 Furthermore you can specify a relative date by giving, as the *first* thing
15539 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15540 change in days weeks, months, years.
15541 With a single plus or minus, the date is relative to today. With a double
15542 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15543 +4d --> four days from today
15544 +4 --> same as above
15545 +2w --> two weeks from today
15546 ++5 --> five days from default date
15548 The function understands only English month and weekday abbreviations.
15550 While prompting, a calendar is popped up - you can also select the
15551 date with the mouse (button 1). The calendar shows a period of three
15552 months. To scroll it to other months, use the keys `>' and `<'.
15553 If you don't like the calendar, turn it off with
15554 \(setq org-read-date-popup-calendar nil)
15556 With optional argument TO-TIME, the date will immediately be converted
15557 to an internal time.
15558 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15559 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15560 still enter a time, and this function will inform the calling routine
15561 about this change. The calling routine may then choose to change the
15562 format used to insert the time stamp into the buffer to include the time.
15563 With optional argument FROM-STRING, read from this string instead from
15564 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15565 the time/date that is used for everything that is not specified by the
15566 user."
15567 (require 'parse-time)
15568 (let* ((org-time-stamp-rounding-minutes
15569 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15570 (org-dcst org-display-custom-times)
15571 (ct (org-current-time))
15572 (org-def (or org-overriding-default-time default-time ct))
15573 (org-defdecode (decode-time org-def))
15574 (dummy (progn
15575 (when (< (nth 2 org-defdecode) org-extend-today-until)
15576 (setcar (nthcdr 2 org-defdecode) -1)
15577 (setcar (nthcdr 1 org-defdecode) 59)
15578 (setq org-def (apply 'encode-time org-defdecode)
15579 org-defdecode (decode-time org-def)))))
15580 (calendar-frame-setup nil)
15581 (calendar-setup nil)
15582 (calendar-move-hook nil)
15583 (calendar-view-diary-initially-flag nil)
15584 (calendar-view-holidays-initially-flag nil)
15585 (timestr (format-time-string
15586 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15587 (prompt (concat (if prompt (concat prompt " ") "")
15588 (format "Date+time [%s]: " timestr)))
15589 ans (org-ans0 "") org-ans1 org-ans2 final)
15591 (cond
15592 (from-string (setq ans from-string))
15593 (org-read-date-popup-calendar
15594 (save-excursion
15595 (save-window-excursion
15596 (calendar)
15597 (org-eval-in-calendar '(setq cursor-type nil) t)
15598 (unwind-protect
15599 (progn
15600 (calendar-forward-day (- (time-to-days org-def)
15601 (calendar-absolute-from-gregorian
15602 (calendar-current-date))))
15603 (org-eval-in-calendar nil t)
15604 (let* ((old-map (current-local-map))
15605 (map (copy-keymap calendar-mode-map))
15606 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15607 (org-defkey map (kbd "RET") 'org-calendar-select)
15608 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15609 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15610 (org-defkey minibuffer-local-map [(meta shift left)]
15611 (lambda () (interactive)
15612 (org-eval-in-calendar '(calendar-backward-month 1))))
15613 (org-defkey minibuffer-local-map [(meta shift right)]
15614 (lambda () (interactive)
15615 (org-eval-in-calendar '(calendar-forward-month 1))))
15616 (org-defkey minibuffer-local-map [(meta shift up)]
15617 (lambda () (interactive)
15618 (org-eval-in-calendar '(calendar-backward-year 1))))
15619 (org-defkey minibuffer-local-map [(meta shift down)]
15620 (lambda () (interactive)
15621 (org-eval-in-calendar '(calendar-forward-year 1))))
15622 (org-defkey minibuffer-local-map [?\e (shift left)]
15623 (lambda () (interactive)
15624 (org-eval-in-calendar '(calendar-backward-month 1))))
15625 (org-defkey minibuffer-local-map [?\e (shift right)]
15626 (lambda () (interactive)
15627 (org-eval-in-calendar '(calendar-forward-month 1))))
15628 (org-defkey minibuffer-local-map [?\e (shift up)]
15629 (lambda () (interactive)
15630 (org-eval-in-calendar '(calendar-backward-year 1))))
15631 (org-defkey minibuffer-local-map [?\e (shift down)]
15632 (lambda () (interactive)
15633 (org-eval-in-calendar '(calendar-forward-year 1))))
15634 (org-defkey minibuffer-local-map [(shift up)]
15635 (lambda () (interactive)
15636 (org-eval-in-calendar '(calendar-backward-week 1))))
15637 (org-defkey minibuffer-local-map [(shift down)]
15638 (lambda () (interactive)
15639 (org-eval-in-calendar '(calendar-forward-week 1))))
15640 (org-defkey minibuffer-local-map [(shift left)]
15641 (lambda () (interactive)
15642 (org-eval-in-calendar '(calendar-backward-day 1))))
15643 (org-defkey minibuffer-local-map [(shift right)]
15644 (lambda () (interactive)
15645 (org-eval-in-calendar '(calendar-forward-day 1))))
15646 (org-defkey minibuffer-local-map ">"
15647 (lambda () (interactive)
15648 (org-eval-in-calendar '(scroll-calendar-left 1))))
15649 (org-defkey minibuffer-local-map "<"
15650 (lambda () (interactive)
15651 (org-eval-in-calendar '(scroll-calendar-right 1))))
15652 (org-defkey minibuffer-local-map "\C-v"
15653 (lambda () (interactive)
15654 (org-eval-in-calendar
15655 '(calendar-scroll-left-three-months 1))))
15656 (org-defkey minibuffer-local-map "\M-v"
15657 (lambda () (interactive)
15658 (org-eval-in-calendar
15659 '(calendar-scroll-right-three-months 1))))
15660 (run-hooks 'org-read-date-minibuffer-setup-hook)
15661 (unwind-protect
15662 (progn
15663 (use-local-map map)
15664 (setq org-read-date-inactive inactive)
15665 (add-hook 'post-command-hook 'org-read-date-display)
15666 (setq org-ans0 (read-string prompt default-input
15667 'org-read-date-history nil))
15668 ;; org-ans0: from prompt
15669 ;; org-ans1: from mouse click
15670 ;; org-ans2: from calendar motion
15671 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15672 (remove-hook 'post-command-hook 'org-read-date-display)
15673 (use-local-map old-map)
15674 (when org-read-date-overlay
15675 (delete-overlay org-read-date-overlay)
15676 (setq org-read-date-overlay nil)))))
15677 (bury-buffer "*Calendar*")))))
15679 (t ; Naked prompt only
15680 (unwind-protect
15681 (setq ans (read-string prompt default-input
15682 'org-read-date-history timestr))
15683 (when org-read-date-overlay
15684 (delete-overlay org-read-date-overlay)
15685 (setq org-read-date-overlay nil)))))
15687 (setq final (org-read-date-analyze ans org-def org-defdecode))
15689 (when org-read-date-analyze-forced-year
15690 (message "Year was forced into %s"
15691 (if org-read-date-force-compatible-dates
15692 "compatible range (1970-2037)"
15693 "range representable on this machine"))
15694 (ding))
15696 ;; One round trip to get rid of 34th of August and stuff like that....
15697 (setq final (decode-time (apply 'encode-time final)))
15699 (setq org-read-date-final-answer ans)
15701 (if to-time
15702 (apply 'encode-time final)
15703 (if (and (boundp 'org-time-was-given) org-time-was-given)
15704 (format "%04d-%02d-%02d %02d:%02d"
15705 (nth 5 final) (nth 4 final) (nth 3 final)
15706 (nth 2 final) (nth 1 final))
15707 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15709 (defvar org-def)
15710 (defvar org-defdecode)
15711 (defvar org-with-time)
15712 (defun org-read-date-display ()
15713 "Display the current date prompt interpretation in the minibuffer."
15714 (when org-read-date-display-live
15715 (when org-read-date-overlay
15716 (delete-overlay org-read-date-overlay))
15717 (when (minibufferp (current-buffer))
15718 (save-excursion
15719 (end-of-line 1)
15720 (while (not (equal (buffer-substring
15721 (max (point-min) (- (point) 4)) (point))
15722 " "))
15723 (insert " ")))
15724 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15725 " " (or org-ans1 org-ans2)))
15726 (org-end-time-was-given nil)
15727 (f (org-read-date-analyze ans org-def org-defdecode))
15728 (fmts (if org-dcst
15729 org-time-stamp-custom-formats
15730 org-time-stamp-formats))
15731 (fmt (if (or org-with-time
15732 (and (boundp 'org-time-was-given) org-time-was-given))
15733 (cdr fmts)
15734 (car fmts)))
15735 (txt (format-time-string fmt (apply 'encode-time f)))
15736 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15737 (txt (concat "=> " txt)))
15738 (when (and org-end-time-was-given
15739 (string-match org-plain-time-of-day-regexp txt))
15740 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15741 org-end-time-was-given
15742 (substring txt (match-end 0)))))
15743 (when org-read-date-analyze-futurep
15744 (setq txt (concat txt " (=>F)")))
15745 (setq org-read-date-overlay
15746 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15747 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15749 (defun org-read-date-analyze (ans org-def org-defdecode)
15750 "Analyze the combined answer of the date prompt."
15751 ;; FIXME: cleanup and comment
15752 (let ((nowdecode (decode-time (current-time)))
15753 delta deltan deltaw deltadef year month day
15754 hour minute second wday pm h2 m2 tl wday1
15755 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15756 (setq org-read-date-analyze-futurep nil
15757 org-read-date-analyze-forced-year nil)
15758 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15759 (setq ans "+0"))
15761 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15762 (setq ans (replace-match "" t t ans)
15763 deltan (car delta)
15764 deltaw (nth 1 delta)
15765 deltadef (nth 2 delta)))
15767 ;; Check if there is an iso week date in there. If yes, store the
15768 ;; info and postpone interpreting it until the rest of the parsing
15769 ;; is done.
15770 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15771 (setq iso-year (if (match-end 1)
15772 (org-small-year-to-year
15773 (string-to-number (match-string 1 ans))))
15774 iso-weekday (if (match-end 3)
15775 (string-to-number (match-string 3 ans)))
15776 iso-week (string-to-number (match-string 2 ans)))
15777 (setq ans (replace-match "" t t ans)))
15779 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15780 (when (string-match
15781 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15782 (setq year (if (match-end 2)
15783 (string-to-number (match-string 2 ans))
15784 (progn (setq kill-year t)
15785 (string-to-number (format-time-string "%Y"))))
15786 month (string-to-number (match-string 3 ans))
15787 day (string-to-number (match-string 4 ans)))
15788 (if (< year 100) (setq year (+ 2000 year)))
15789 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15790 t nil ans)))
15792 ;; Help matching dotted european dates
15793 (when (string-match
15794 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15795 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15796 (setq kill-year t)
15797 (string-to-number (format-time-string "%Y")))
15798 day (string-to-number (match-string 1 ans))
15799 month (string-to-number (match-string 2 ans))
15800 ans (replace-match (format "%04d-%02d-%02d" year month day)
15801 t nil ans)))
15803 ;; Help matching american dates, like 5/30 or 5/30/7
15804 (when (string-match
15805 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15806 (setq year (if (match-end 4)
15807 (string-to-number (match-string 4 ans))
15808 (progn (setq kill-year t)
15809 (string-to-number (format-time-string "%Y"))))
15810 month (string-to-number (match-string 1 ans))
15811 day (string-to-number (match-string 2 ans)))
15812 (if (< year 100) (setq year (+ 2000 year)))
15813 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15814 t nil ans)))
15815 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15816 ;; If there is a time with am/pm, and *no* time without it, we convert
15817 ;; so that matching will be successful.
15818 (loop for i from 1 to 2 do ; twice, for end time as well
15819 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15820 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15821 (setq hour (string-to-number (match-string 1 ans))
15822 minute (if (match-end 3)
15823 (string-to-number (match-string 3 ans))
15825 pm (equal ?p
15826 (string-to-char (downcase (match-string 4 ans)))))
15827 (if (and (= hour 12) (not pm))
15828 (setq hour 0)
15829 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15830 (setq ans (replace-match (format "%02d:%02d" hour minute)
15831 t t ans))))
15833 ;; Check if a time range is given as a duration
15834 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15835 (setq hour (string-to-number (match-string 1 ans))
15836 h2 (+ hour (string-to-number (match-string 3 ans)))
15837 minute (string-to-number (match-string 2 ans))
15838 m2 (+ minute (if (match-end 5) (string-to-number
15839 (match-string 5 ans))0)))
15840 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15841 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15842 t t ans)))
15844 ;; Check if there is a time range
15845 (when (boundp 'org-end-time-was-given)
15846 (setq org-time-was-given nil)
15847 (when (and (string-match org-plain-time-of-day-regexp ans)
15848 (match-end 8))
15849 (setq org-end-time-was-given (match-string 8 ans))
15850 (setq ans (concat (substring ans 0 (match-beginning 7))
15851 (substring ans (match-end 7))))))
15853 (setq tl (parse-time-string ans)
15854 day (or (nth 3 tl) (nth 3 org-defdecode))
15855 month (or (nth 4 tl)
15856 (if (and org-read-date-prefer-future
15857 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15858 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15859 (nth 4 org-defdecode)))
15860 year (or (and (not kill-year) (nth 5 tl))
15861 (if (and org-read-date-prefer-future
15862 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15863 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15864 (nth 5 org-defdecode)))
15865 hour (or (nth 2 tl) (nth 2 org-defdecode))
15866 minute (or (nth 1 tl) (nth 1 org-defdecode))
15867 second (or (nth 0 tl) 0)
15868 wday (nth 6 tl))
15870 (when (and (eq org-read-date-prefer-future 'time)
15871 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15872 (equal day (nth 3 nowdecode))
15873 (equal month (nth 4 nowdecode))
15874 (equal year (nth 5 nowdecode))
15875 (nth 2 tl)
15876 (or (< (nth 2 tl) (nth 2 nowdecode))
15877 (and (= (nth 2 tl) (nth 2 nowdecode))
15878 (nth 1 tl)
15879 (< (nth 1 tl) (nth 1 nowdecode)))))
15880 (setq day (1+ day)
15881 futurep t))
15883 ;; Special date definitions below
15884 (cond
15885 (iso-week
15886 ;; There was an iso week
15887 (require 'cal-iso)
15888 (setq futurep nil)
15889 (setq year (or iso-year year)
15890 day (or iso-weekday wday 1)
15891 wday nil ; to make sure that the trigger below does not match
15892 iso-date (calendar-gregorian-from-absolute
15893 (calendar-absolute-from-iso
15894 (list iso-week day year))))
15895 ; FIXME: Should we also push ISO weeks into the future?
15896 ; (when (and org-read-date-prefer-future
15897 ; (not iso-year)
15898 ; (< (calendar-absolute-from-gregorian iso-date)
15899 ; (time-to-days (current-time))))
15900 ; (setq year (1+ year)
15901 ; iso-date (calendar-gregorian-from-absolute
15902 ; (calendar-absolute-from-iso
15903 ; (list iso-week day year)))))
15904 (setq month (car iso-date)
15905 year (nth 2 iso-date)
15906 day (nth 1 iso-date)))
15907 (deltan
15908 (setq futurep nil)
15909 (unless deltadef
15910 (let ((now (decode-time (current-time))))
15911 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15912 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15913 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15914 ((equal deltaw "m") (setq month (+ month deltan)))
15915 ((equal deltaw "y") (setq year (+ year deltan)))))
15916 ((and wday (not (nth 3 tl)))
15917 ;; Weekday was given, but no day, so pick that day in the week
15918 ;; on or after the derived date.
15919 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15920 (unless (equal wday wday1)
15921 (setq day (+ day (% (- wday wday1 -7) 7))))))
15922 (if (and (boundp 'org-time-was-given)
15923 (nth 2 tl))
15924 (setq org-time-was-given t))
15925 (if (< year 100) (setq year (+ 2000 year)))
15926 ;; Check of the date is representable
15927 (if org-read-date-force-compatible-dates
15928 (progn
15929 (if (< year 1970)
15930 (setq year 1970 org-read-date-analyze-forced-year t))
15931 (if (> year 2037)
15932 (setq year 2037 org-read-date-analyze-forced-year t)))
15933 (condition-case nil
15934 (ignore (encode-time second minute hour day month year))
15935 (error
15936 (setq year (nth 5 org-defdecode))
15937 (setq org-read-date-analyze-forced-year t))))
15938 (setq org-read-date-analyze-futurep futurep)
15939 (list second minute hour day month year)))
15941 (defvar parse-time-weekdays)
15942 (defun org-read-date-get-relative (s today default)
15943 "Check string S for special relative date string.
15944 TODAY and DEFAULT are internal times, for today and for a default.
15945 Return shift list (N what def-flag)
15946 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15947 N is the number of WHATs to shift.
15948 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15949 the DEFAULT date rather than TODAY."
15950 (require 'parse-time)
15951 (when (and
15952 (string-match
15953 (concat
15954 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15955 "\\([0-9]+\\)?"
15956 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15957 "\\([ \t]\\|$\\)") s)
15958 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15959 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15960 (string-to-char (substring (match-string 1 s) -1))
15961 ?+))
15962 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15963 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15964 (what (if (match-end 3) (match-string 3 s) "d"))
15965 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15966 (date (if rel default today))
15967 (wday (nth 6 (decode-time date)))
15968 delta)
15969 (if wday1
15970 (progn
15971 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15972 (if (= dir ?-) (setq delta (- delta 7)))
15973 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15974 (list delta "d" rel))
15975 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15977 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15978 "Turn a user-specified date into the internal representation.
15979 The internal representation needed by the calendar is (month day year).
15980 This is a wrapper to handle the brain-dead convention in calendar that
15981 user function argument order change dependent on argument order."
15982 (if (boundp 'calendar-date-style)
15983 (cond
15984 ((eq calendar-date-style 'american)
15985 (list arg1 arg2 arg3))
15986 ((eq calendar-date-style 'european)
15987 (list arg2 arg1 arg3))
15988 ((eq calendar-date-style 'iso)
15989 (list arg2 arg3 arg1)))
15990 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15991 (if (org-bound-and-true-p european-calendar-style)
15992 (list arg2 arg1 arg3)
15993 (list arg1 arg2 arg3)))))
15995 (defun org-eval-in-calendar (form &optional keepdate)
15996 "Eval FORM in the calendar window and return to current window.
15997 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15998 otherwise stick to the current value of `org-ans2'."
15999 (let ((sf (selected-frame))
16000 (sw (selected-window)))
16001 (select-window (get-buffer-window "*Calendar*" t))
16002 (eval form)
16003 (when (and (not keepdate) (calendar-cursor-to-date))
16004 (let* ((date (calendar-cursor-to-date))
16005 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16006 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16007 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16008 (select-window sw)
16009 (org-select-frame-set-input-focus sf)))
16011 (defun org-calendar-select ()
16012 "Return to `org-read-date' with the date currently selected.
16013 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16014 (interactive)
16015 (when (calendar-cursor-to-date)
16016 (let* ((date (calendar-cursor-to-date))
16017 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16018 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16019 (if (active-minibuffer-window) (exit-minibuffer))))
16021 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16022 "Insert a date stamp for the date given by the internal TIME.
16023 WITH-HM means use the stamp format that includes the time of the day.
16024 INACTIVE means use square brackets instead of angular ones, so that the
16025 stamp will not contribute to the agenda.
16026 PRE and POST are optional strings to be inserted before and after the
16027 stamp.
16028 The command returns the inserted time stamp."
16029 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16030 stamp)
16031 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16032 (insert-before-markers (or pre ""))
16033 (when (listp extra)
16034 (setq extra (car extra))
16035 (if (and (stringp extra)
16036 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16037 (setq extra (format "-%02d:%02d"
16038 (string-to-number (match-string 1 extra))
16039 (string-to-number (match-string 2 extra))))
16040 (setq extra nil)))
16041 (when extra
16042 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16043 (insert-before-markers (setq stamp (format-time-string fmt time)))
16044 (insert-before-markers (or post ""))
16045 (setq org-last-inserted-timestamp stamp)))
16047 (defun org-toggle-time-stamp-overlays ()
16048 "Toggle the use of custom time stamp formats."
16049 (interactive)
16050 (setq org-display-custom-times (not org-display-custom-times))
16051 (unless org-display-custom-times
16052 (let ((p (point-min)) (bmp (buffer-modified-p)))
16053 (while (setq p (next-single-property-change p 'display))
16054 (if (and (get-text-property p 'display)
16055 (eq (get-text-property p 'face) 'org-date))
16056 (remove-text-properties
16057 p (setq p (next-single-property-change p 'display))
16058 '(display t))))
16059 (set-buffer-modified-p bmp)))
16060 (if (featurep 'xemacs)
16061 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16062 (org-restart-font-lock)
16063 (setq org-table-may-need-update t)
16064 (if org-display-custom-times
16065 (message "Time stamps are overlaid with custom format")
16066 (message "Time stamp overlays removed")))
16068 (defun org-display-custom-time (beg end)
16069 "Overlay modified time stamp format over timestamp between BEG and END."
16070 (let* ((ts (buffer-substring beg end))
16071 t1 w1 with-hm tf time str w2 (off 0))
16072 (save-match-data
16073 (setq t1 (org-parse-time-string ts t))
16074 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16075 (setq off (- (match-end 0) (match-beginning 0)))))
16076 (setq end (- end off))
16077 (setq w1 (- end beg)
16078 with-hm (and (nth 1 t1) (nth 2 t1))
16079 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16080 time (org-fix-decoded-time t1)
16081 str (org-add-props
16082 (format-time-string
16083 (substring tf 1 -1) (apply 'encode-time time))
16084 nil 'mouse-face 'highlight)
16085 w2 (length str))
16086 (if (not (= w2 w1))
16087 (add-text-properties (1+ beg) (+ 2 beg)
16088 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16089 (if (featurep 'xemacs)
16090 (progn
16091 (put-text-property beg end 'invisible t)
16092 (put-text-property beg end 'end-glyph (make-glyph str)))
16093 (put-text-property beg end 'display str))))
16095 (defun org-translate-time (string)
16096 "Translate all timestamps in STRING to custom format.
16097 But do this only if the variable `org-display-custom-times' is set."
16098 (when org-display-custom-times
16099 (save-match-data
16100 (let* ((start 0)
16101 (re org-ts-regexp-both)
16102 t1 with-hm inactive tf time str beg end)
16103 (while (setq start (string-match re string start))
16104 (setq beg (match-beginning 0)
16105 end (match-end 0)
16106 t1 (save-match-data
16107 (org-parse-time-string (substring string beg end) t))
16108 with-hm (and (nth 1 t1) (nth 2 t1))
16109 inactive (equal (substring string beg (1+ beg)) "[")
16110 tf (funcall (if with-hm 'cdr 'car)
16111 org-time-stamp-custom-formats)
16112 time (org-fix-decoded-time t1)
16113 str (format-time-string
16114 (concat
16115 (if inactive "[" "<") (substring tf 1 -1)
16116 (if inactive "]" ">"))
16117 (apply 'encode-time time))
16118 string (replace-match str t t string)
16119 start (+ start (length str)))))))
16120 string)
16122 (defun org-fix-decoded-time (time)
16123 "Set 0 instead of nil for the first 6 elements of time.
16124 Don't touch the rest."
16125 (let ((n 0))
16126 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16128 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16130 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16131 "Difference between TIMESTAMP-STRING and now in days.
16132 If SECONDS is non-nil, return the difference in seconds."
16133 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16134 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16135 (funcall fdiff (current-time)))))
16137 (defun org-deadline-close (timestamp-string &optional ndays)
16138 "Is the time in TIMESTAMP-STRING close to the current date?"
16139 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16140 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16141 (not (org-entry-is-done-p))))
16143 (defun org-get-wdays (ts)
16144 "Get the deadline lead time appropriate for timestring TS."
16145 (cond
16146 ((<= org-deadline-warning-days 0)
16147 ;; 0 or negative, enforce this value no matter what
16148 (- org-deadline-warning-days))
16149 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16150 ;; lead time is specified.
16151 (floor (* (string-to-number (match-string 1 ts))
16152 (cdr (assoc (match-string 2 ts)
16153 '(("d" . 1) ("w" . 7)
16154 ("m" . 30.4) ("y" . 365.25)))))))
16155 ;; go for the default.
16156 (t org-deadline-warning-days)))
16158 (defun org-calendar-select-mouse (ev)
16159 "Return to `org-read-date' with the date currently selected.
16160 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16161 (interactive "e")
16162 (mouse-set-point ev)
16163 (when (calendar-cursor-to-date)
16164 (let* ((date (calendar-cursor-to-date))
16165 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16166 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16167 (if (active-minibuffer-window) (exit-minibuffer))))
16169 (defun org-check-deadlines (ndays)
16170 "Check if there are any deadlines due or past due.
16171 A deadline is considered due if it happens within `org-deadline-warning-days'
16172 days from today's date. If the deadline appears in an entry marked DONE,
16173 it is not shown. The prefix arg NDAYS can be used to test that many
16174 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16175 (interactive "P")
16176 (let* ((org-warn-days
16177 (cond
16178 ((equal ndays '(4)) 100000)
16179 (ndays (prefix-numeric-value ndays))
16180 (t (abs org-deadline-warning-days))))
16181 (case-fold-search nil)
16182 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16183 (callback
16184 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16186 (message "%d deadlines past-due or due within %d days"
16187 (org-occur regexp nil callback)
16188 org-warn-days)))
16190 (defsubst org-re-timestamp (type)
16191 "Return a regexp for timestamp TYPE.
16192 Allowed values for TYPE are:
16194 all: all timestamps
16195 active: only active timestamps (<...>)
16196 inactive: only inactive timestamps ([...])
16197 scheduled: only scheduled timestamps
16198 deadline: only deadline timestamps
16200 When TYPE is nil, fall back on returning a regexp that matches
16201 both scheduled and deadline timestamps."
16202 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16203 ((eq type 'active) org-ts-regexp)
16204 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16205 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16206 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16207 ((eq type 'scheduled-or-deadline)
16208 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16210 (defun org-check-before-date (date)
16211 "Check if there are deadlines or scheduled entries before DATE."
16212 (interactive (list (org-read-date)))
16213 (let ((case-fold-search nil)
16214 (regexp (org-re-timestamp org-ts-type))
16215 (callback
16216 (lambda () (time-less-p
16217 (org-time-string-to-time (match-string 1))
16218 (org-time-string-to-time date)))))
16219 (message "%d entries before %s"
16220 (org-occur regexp nil callback) date)))
16222 (defun org-check-after-date (date)
16223 "Check if there are deadlines or scheduled entries after DATE."
16224 (interactive (list (org-read-date)))
16225 (let ((case-fold-search nil)
16226 (regexp (org-re-timestamp org-ts-type))
16227 (callback
16228 (lambda () (not
16229 (time-less-p
16230 (org-time-string-to-time (match-string 1))
16231 (org-time-string-to-time date))))))
16232 (message "%d entries after %s"
16233 (org-occur regexp nil callback) date)))
16235 (defun org-check-dates-range (start-date end-date)
16236 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16237 (interactive (list (org-read-date nil nil nil "Range starts")
16238 (org-read-date nil nil nil "Range end")))
16239 (let ((case-fold-search nil)
16240 (regexp (org-re-timestamp org-ts-type))
16241 (callback
16242 (lambda ()
16243 (let ((match (match-string 1)))
16244 (and
16245 (not (time-less-p
16246 (org-time-string-to-time match)
16247 (org-time-string-to-time start-date)))
16248 (time-less-p
16249 (org-time-string-to-time match)
16250 (org-time-string-to-time end-date)))))))
16251 (message "%d entries between %s and %s"
16252 (org-occur regexp nil callback) start-date end-date)))
16254 (defun org-evaluate-time-range (&optional to-buffer)
16255 "Evaluate a time range by computing the difference between start and end.
16256 Normally the result is just printed in the echo area, but with prefix arg
16257 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16258 If the time range is actually in a table, the result is inserted into the
16259 next column.
16260 For time difference computation, a year is assumed to be exactly 365
16261 days in order to avoid rounding problems."
16262 (interactive "P")
16264 (org-clock-update-time-maybe)
16265 (save-excursion
16266 (unless (org-at-date-range-p t)
16267 (goto-char (point-at-bol))
16268 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16269 (if (not (org-at-date-range-p t))
16270 (error "Not at a time-stamp range, and none found in current line")))
16271 (let* ((ts1 (match-string 1))
16272 (ts2 (match-string 2))
16273 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16274 (match-end (match-end 0))
16275 (time1 (org-time-string-to-time ts1))
16276 (time2 (org-time-string-to-time ts2))
16277 (t1 (org-float-time time1))
16278 (t2 (org-float-time time2))
16279 (diff (abs (- t2 t1)))
16280 (negative (< (- t2 t1) 0))
16281 ;; (ys (floor (* 365 24 60 60)))
16282 (ds (* 24 60 60))
16283 (hs (* 60 60))
16284 (fy "%dy %dd %02d:%02d")
16285 (fy1 "%dy %dd")
16286 (fd "%dd %02d:%02d")
16287 (fd1 "%dd")
16288 (fh "%02d:%02d")
16289 y d h m align)
16290 (if havetime
16291 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16293 d (floor (/ diff ds)) diff (mod diff ds)
16294 h (floor (/ diff hs)) diff (mod diff hs)
16295 m (floor (/ diff 60)))
16296 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16298 d (floor (+ (/ diff ds) 0.5))
16299 h 0 m 0))
16300 (if (not to-buffer)
16301 (message "%s" (org-make-tdiff-string y d h m))
16302 (if (org-at-table-p)
16303 (progn
16304 (goto-char match-end)
16305 (setq align t)
16306 (and (looking-at " *|") (goto-char (match-end 0))))
16307 (goto-char match-end))
16308 (if (looking-at
16309 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16310 (replace-match ""))
16311 (if negative (insert " -"))
16312 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16313 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16314 (insert " " (format fh h m))))
16315 (if align (org-table-align))
16316 (message "Time difference inserted")))))
16318 (defun org-make-tdiff-string (y d h m)
16319 (let ((fmt "")
16320 (l nil))
16321 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16322 l (push y l)))
16323 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16324 l (push d l)))
16325 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16326 l (push h l)))
16327 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16328 l (push m l)))
16329 (apply 'format fmt (nreverse l))))
16331 (defun org-time-string-to-time (s &optional buffer pos)
16332 "Convert a timestamp string into internal time."
16333 (condition-case errdata
16334 (apply 'encode-time (org-parse-time-string s))
16335 (error (error "Bad timestamp `%s'%s\nError was: %s"
16336 s (if (not (and buffer pos))
16338 (format " at %d in buffer `%s'" pos buffer))
16339 (cdr errdata)))))
16341 (defun org-time-string-to-seconds (s)
16342 "Convert a timestamp string to a number of seconds."
16343 (org-float-time (org-time-string-to-time s)))
16345 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16346 "Convert a time stamp to an absolute day number.
16347 If there is a specifier for a cyclic time stamp, get the closest date to
16348 DAYNR.
16349 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16350 The variable date is bound by the calendar when this is called."
16351 (cond
16352 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16353 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16354 daynr
16355 (+ daynr 1000)))
16356 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16357 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16358 (time-to-days (current-time))) (match-string 0 s)
16359 prefer show-all))
16360 (t (time-to-days
16361 (condition-case errdata
16362 (apply 'encode-time (org-parse-time-string s))
16363 (error (error "Bad timestamp `%s'%s\nError was: %s"
16364 s (if (not (and buffer pos))
16366 (format " at %d in buffer `%s'" pos buffer))
16367 (cdr errdata))))))))
16369 (defun org-days-to-iso-week (days)
16370 "Return the iso week number."
16371 (require 'cal-iso)
16372 (car (calendar-iso-from-absolute days)))
16374 (defun org-small-year-to-year (year)
16375 "Convert 2-digit years into 4-digit years.
16376 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16377 The year 2000 cannot be abbreviated. Any year larger than 99
16378 is returned unchanged."
16379 (if (< year 38)
16380 (setq year (+ 2000 year))
16381 (if (< year 100)
16382 (setq year (+ 1900 year))))
16383 year)
16385 (defun org-time-from-absolute (d)
16386 "Return the time corresponding to date D.
16387 D may be an absolute day number, or a calendar-type list (month day year)."
16388 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16389 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16391 (defun org-calendar-holiday ()
16392 "List of holidays, for Diary display in Org-mode."
16393 (require 'holidays)
16394 (let ((hl (funcall
16395 (if (fboundp 'calendar-check-holidays)
16396 'calendar-check-holidays 'check-calendar-holidays) date)))
16397 (if hl (mapconcat 'identity hl "; "))))
16399 (defun org-diary-sexp-entry (sexp entry date)
16400 "Process a SEXP diary ENTRY for DATE."
16401 (require 'diary-lib)
16402 (let ((result (if calendar-debug-sexp
16403 (let ((stack-trace-on-error t))
16404 (eval (car (read-from-string sexp))))
16405 (condition-case nil
16406 (eval (car (read-from-string sexp)))
16407 (error
16408 (beep)
16409 (message "Bad sexp at line %d in %s: %s"
16410 (org-current-line)
16411 (buffer-file-name) sexp)
16412 (sleep-for 2))))))
16413 (cond ((stringp result) (split-string result "; "))
16414 ((and (consp result)
16415 (not (consp (cdr result)))
16416 (stringp (cdr result))) (cdr result))
16417 ((and (consp result)
16418 (stringp (car result))) result)
16419 (result entry))))
16421 (defun org-diary-to-ical-string (frombuf)
16422 "Get iCalendar entries from diary entries in buffer FROMBUF.
16423 This uses the icalendar.el library."
16424 (let* ((tmpdir (if (featurep 'xemacs)
16425 (temp-directory)
16426 temporary-file-directory))
16427 (tmpfile (make-temp-name
16428 (expand-file-name "orgics" tmpdir)))
16429 buf rtn b e)
16430 (with-current-buffer frombuf
16431 (icalendar-export-region (point-min) (point-max) tmpfile)
16432 (setq buf (find-buffer-visiting tmpfile))
16433 (set-buffer buf)
16434 (goto-char (point-min))
16435 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16436 (setq b (match-beginning 0)))
16437 (goto-char (point-max))
16438 (if (re-search-backward "^END:VEVENT" nil t)
16439 (setq e (match-end 0)))
16440 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16441 (kill-buffer buf)
16442 (delete-file tmpfile)
16443 rtn))
16445 (defun org-closest-date (start current change prefer show-all)
16446 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16447 When PREFER is `past', return a date that is either CURRENT or past.
16448 When PREFER is `future', return a date that is either CURRENT or future.
16449 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16450 ;; Make the proper lists from the dates
16451 (catch 'exit
16452 (let ((a1 '(("h" . hour)
16453 ("d" . day)
16454 ("w" . week)
16455 ("m" . month)
16456 ("y" . year)))
16457 (shour (nth 2 (org-parse-time-string start)))
16458 dn dw sday cday n1 n2 n0
16459 d m y y1 y2 date1 date2 nmonths nm ny m2)
16461 (setq start (org-date-to-gregorian start)
16462 current (org-date-to-gregorian
16463 (if show-all
16464 current
16465 (time-to-days (current-time))))
16466 sday (calendar-absolute-from-gregorian start)
16467 cday (calendar-absolute-from-gregorian current))
16469 (if (<= cday sday) (throw 'exit sday))
16471 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16472 (setq dn (string-to-number (match-string 1 change))
16473 dw (cdr (assoc (match-string 2 change) a1)))
16474 (error "Invalid change specifier: %s" change))
16475 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16476 (cond
16477 ((eq dw 'hour)
16478 (let ((missing-hours
16479 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16480 dn)))
16481 (setq n1 (if (zerop missing-hours) cday
16482 (- cday (1+ (floor (/ missing-hours 24)))))
16483 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16484 ((eq dw 'day)
16485 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16486 n2 (+ n1 dn)))
16487 ((eq dw 'year)
16488 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16489 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16490 (setq date1 (list m d y1)
16491 n1 (calendar-absolute-from-gregorian date1)
16492 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16493 n2 (calendar-absolute-from-gregorian date2)))
16494 ((eq dw 'month)
16495 ;; approx number of month between the two dates
16496 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16497 ;; How often does dn fit in there?
16498 (setq d (nth 1 start) m (car start) y (nth 2 start)
16499 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16500 m (+ m nm)
16501 ny (floor (/ m 12))
16502 y (+ y ny)
16503 m (- m (* ny 12)))
16504 (while (> m 12) (setq m (- m 12) y (1+ y)))
16505 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16506 (setq m2 (+ m dn) y2 y)
16507 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16508 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16509 (while (<= n2 cday)
16510 (setq n1 n2 m m2 y y2)
16511 (setq m2 (+ m dn) y2 y)
16512 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16513 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16514 ;; Make sure n1 is the earlier date
16515 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16516 (if show-all
16517 (cond
16518 ((eq prefer 'past) (if (= cday n2) n2 n1))
16519 ((eq prefer 'future) (if (= cday n1) n1 n2))
16520 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16521 (cond
16522 ((eq prefer 'past) (if (= cday n2) n2 n1))
16523 ((eq prefer 'future) (if (= cday n1) n1 n2))
16524 (t (if (= cday n1) n1 n2)))))))
16526 (defun org-date-to-gregorian (date)
16527 "Turn any specification of DATE into a Gregorian date for the calendar."
16528 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16529 ((and (listp date) (= (length date) 3)) date)
16530 ((stringp date)
16531 (setq date (org-parse-time-string date))
16532 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16533 ((listp date)
16534 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16536 (defun org-parse-time-string (s &optional nodefault)
16537 "Parse the standard Org-mode time string.
16538 This should be a lot faster than the normal `parse-time-string'.
16539 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16540 hour and minute fields will be nil if not given."
16541 (if (string-match org-ts-regexp0 s)
16542 (list 0
16543 (if (or (match-beginning 8) (not nodefault))
16544 (string-to-number (or (match-string 8 s) "0")))
16545 (if (or (match-beginning 7) (not nodefault))
16546 (string-to-number (or (match-string 7 s) "0")))
16547 (string-to-number (match-string 4 s))
16548 (string-to-number (match-string 3 s))
16549 (string-to-number (match-string 2 s))
16550 nil nil nil)
16551 (error "Not a standard Org-mode time string: %s" s)))
16553 (defun org-timestamp-up (&optional arg)
16554 "Increase the date item at the cursor by one.
16555 If the cursor is on the year, change the year. If it is on the month,
16556 the day or the time, change that.
16557 With prefix ARG, change by that many units."
16558 (interactive "p")
16559 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16561 (defun org-timestamp-down (&optional arg)
16562 "Decrease the date item at the cursor by one.
16563 If the cursor is on the year, change the year. If it is on the month,
16564 the day or the time, change that.
16565 With prefix ARG, change by that many units."
16566 (interactive "p")
16567 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16569 (defun org-timestamp-up-day (&optional arg)
16570 "Increase the date in the time stamp by one day.
16571 With prefix ARG, change that many days."
16572 (interactive "p")
16573 (if (and (not (org-at-timestamp-p t))
16574 (org-at-heading-p))
16575 (org-todo 'up)
16576 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16578 (defun org-timestamp-down-day (&optional arg)
16579 "Decrease the date in the time stamp by one day.
16580 With prefix ARG, change that many days."
16581 (interactive "p")
16582 (if (and (not (org-at-timestamp-p t))
16583 (org-at-heading-p))
16584 (org-todo 'down)
16585 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16587 (defun org-at-timestamp-p (&optional inactive-ok)
16588 "Determine if the cursor is in or at a timestamp."
16589 (interactive)
16590 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16591 (pos (point))
16592 (ans (or (looking-at tsr)
16593 (save-excursion
16594 (skip-chars-backward "^[<\n\r\t")
16595 (if (> (point) (point-min)) (backward-char 1))
16596 (and (looking-at tsr)
16597 (> (- (match-end 0) pos) -1))))))
16598 (and ans
16599 (boundp 'org-ts-what)
16600 (setq org-ts-what
16601 (cond
16602 ((= pos (match-beginning 0)) 'bracket)
16603 ;; Point is considered to be "on the bracket" whether
16604 ;; it's really on it or right after it.
16605 ((= pos (1- (match-end 0))) 'bracket)
16606 ((= pos (match-end 0)) 'after)
16607 ((org-pos-in-match-range pos 2) 'year)
16608 ((org-pos-in-match-range pos 3) 'month)
16609 ((org-pos-in-match-range pos 7) 'hour)
16610 ((org-pos-in-match-range pos 8) 'minute)
16611 ((or (org-pos-in-match-range pos 4)
16612 (org-pos-in-match-range pos 5)) 'day)
16613 ((and (> pos (or (match-end 8) (match-end 5)))
16614 (< pos (match-end 0)))
16615 (- pos (or (match-end 8) (match-end 5))))
16616 (t 'day))))
16617 ans))
16619 (defun org-toggle-timestamp-type ()
16620 "Toggle the type (<active> or [inactive]) of a time stamp."
16621 (interactive)
16622 (when (org-at-timestamp-p t)
16623 (let ((beg (match-beginning 0)) (end (match-end 0))
16624 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16625 (save-excursion
16626 (goto-char beg)
16627 (while (re-search-forward "[][<>]" end t)
16628 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16629 t t)))
16630 (message "Timestamp is now %sactive"
16631 (if (equal (char-after beg) ?<) "" "in")))))
16633 (defvar org-clock-history) ; defined in org-clock.el
16634 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16635 (defun org-timestamp-change (n &optional what updown)
16636 "Change the date in the time stamp at point.
16637 The date will be changed by N times WHAT. WHAT can be `day', `month',
16638 `year', `minute', `second'. If WHAT is not given, the cursor position
16639 in the timestamp determines what will be changed."
16640 (let ((origin (point)) origin-cat
16641 with-hm inactive
16642 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16643 org-ts-what
16644 extra rem
16645 ts time time0 fixnext clrgx)
16646 (if (not (org-at-timestamp-p t))
16647 (error "Not at a timestamp"))
16648 (if (and (not what) (eq org-ts-what 'bracket))
16649 (org-toggle-timestamp-type)
16650 ;; Point isn't on brackets. Remember the part of the time-stamp
16651 ;; the point was in. Indeed, size of time-stamps may change,
16652 ;; but point must be kept in the same category nonetheless.
16653 (setq origin-cat org-ts-what)
16654 (if (and (not what) (not (eq org-ts-what 'day))
16655 org-display-custom-times
16656 (get-text-property (point) 'display)
16657 (not (get-text-property (1- (point)) 'display)))
16658 (setq org-ts-what 'day))
16659 (setq org-ts-what (or what org-ts-what)
16660 inactive (= (char-after (match-beginning 0)) ?\[)
16661 ts (match-string 0))
16662 (replace-match "")
16663 (if (string-match
16664 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16666 (setq extra (match-string 1 ts)))
16667 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16668 (setq with-hm t))
16669 (setq time0 (org-parse-time-string ts))
16670 (when (and updown
16671 (eq org-ts-what 'minute)
16672 (not current-prefix-arg))
16673 ;; This looks like s-up and s-down. Change by one rounding step.
16674 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16675 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16676 (setcar (cdr time0) (+ (nth 1 time0)
16677 (if (> n 0) (- rem) (- dm rem))))))
16678 (setq time
16679 (encode-time (or (car time0) 0)
16680 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16681 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16682 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16683 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16684 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16685 (nthcdr 6 time0)))
16686 (when (and (member org-ts-what '(hour minute))
16687 extra
16688 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16689 (setq extra (org-modify-ts-extra
16690 extra
16691 (if (eq org-ts-what 'hour) 2 5)
16692 n dm)))
16693 (when (integerp org-ts-what)
16694 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16695 (if (eq what 'calendar)
16696 (let ((cal-date (org-get-date-from-calendar)))
16697 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16698 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16699 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16700 (setcar time0 (or (car time0) 0))
16701 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16702 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16703 (setq time (apply 'encode-time time0))))
16704 ;; Insert the new time-stamp, and ensure point stays in the same
16705 ;; category as before (i.e. not after the last position in that
16706 ;; category).
16707 (let ((pos (point)))
16708 ;; Stay before inserted string. `save-excursion' is of no use.
16709 (setq org-last-changed-timestamp
16710 (org-insert-time-stamp time with-hm inactive nil nil extra))
16711 (goto-char pos))
16712 (save-match-data
16713 (looking-at org-ts-regexp3)
16714 (goto-char (cond
16715 ;; `day' category ends before `hour' if any, or at
16716 ;; the end of the day name.
16717 ((eq origin-cat 'day)
16718 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16719 ((eq origin-cat 'hour) (min (match-end 7) origin))
16720 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16721 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16722 ;; `year' and `month' have both fixed size: point
16723 ;; couldn't have moved into another part.
16724 (t origin))))
16725 ;; Update clock if on a CLOCK line.
16726 (org-clock-update-time-maybe)
16727 ;; Maybe adjust the closest clock in `org-clock-history'
16728 (when org-clock-adjust-closest
16729 (if (not (and (org-at-clock-log-p)
16730 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16731 org-clock-history))))))
16732 (message "No clock to adjust")
16733 (cond ((save-excursion ; fix previous clock?
16734 (re-search-backward org-ts-regexp0 nil t)
16735 (org-looking-back (concat org-clock-string " \\[")))
16736 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16737 ((save-excursion ; fix next clock?
16738 (re-search-backward org-ts-regexp0 nil t)
16739 (looking-at (concat org-ts-regexp0 "\\] =>")))
16740 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16741 (save-window-excursion
16742 ;; Find closest clock to point, adjust the previous/next one in history
16743 (let* ((p (save-excursion (org-back-to-heading t)))
16744 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16745 (clfixnth
16746 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16747 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16748 (if (not clfixpos)
16749 (message "No clock to adjust")
16750 (save-excursion
16751 (org-goto-marker-or-bmk clfixpos)
16752 (org-show-subtree)
16753 (when (re-search-forward clrgx nil t)
16754 (goto-char (match-beginning 1))
16755 (let (org-clock-adjust-closest)
16756 (org-timestamp-change n org-ts-what updown))
16757 (message "Clock adjusted in %s for heading: %s"
16758 (file-name-nondirectory (buffer-file-name))
16759 (org-get-heading t t)))))))))
16760 ;; Try to recenter the calendar window, if any.
16761 (if (and org-calendar-follow-timestamp-change
16762 (get-buffer-window "*Calendar*" t)
16763 (memq org-ts-what '(day month year)))
16764 (org-recenter-calendar (time-to-days time))))))
16766 (defun org-modify-ts-extra (s pos n dm)
16767 "Change the different parts of the lead-time and repeat fields in timestamp."
16768 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16769 ng h m new rem)
16770 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16771 (cond
16772 ((or (org-pos-in-match-range pos 2)
16773 (org-pos-in-match-range pos 3))
16774 (setq m (string-to-number (match-string 3 s))
16775 h (string-to-number (match-string 2 s)))
16776 (if (org-pos-in-match-range pos 2)
16777 (setq h (+ h n))
16778 (setq n (* dm (org-no-warnings (signum n))))
16779 (when (not (= 0 (setq rem (% m dm))))
16780 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16781 (setq m (+ m n)))
16782 (if (< m 0) (setq m (+ m 60) h (1- h)))
16783 (if (> m 59) (setq m (- m 60) h (1+ h)))
16784 (setq h (min 24 (max 0 h)))
16785 (setq ng 1 new (format "-%02d:%02d" h m)))
16786 ((org-pos-in-match-range pos 6)
16787 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16788 ((org-pos-in-match-range pos 5)
16789 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16791 ((org-pos-in-match-range pos 9)
16792 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16793 ((org-pos-in-match-range pos 8)
16794 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16796 (when ng
16797 (setq s (concat
16798 (substring s 0 (match-beginning ng))
16800 (substring s (match-end ng))))))
16803 (defun org-recenter-calendar (date)
16804 "If the calendar is visible, recenter it to DATE."
16805 (let ((cwin (get-buffer-window "*Calendar*" t)))
16806 (when cwin
16807 (let ((calendar-move-hook nil))
16808 (with-selected-window cwin
16809 (calendar-goto-date (if (listp date) date
16810 (calendar-gregorian-from-absolute date))))))))
16812 (defun org-goto-calendar (&optional arg)
16813 "Go to the Emacs calendar at the current date.
16814 If there is a time stamp in the current line, go to that date.
16815 A prefix ARG can be used to force the current date."
16816 (interactive "P")
16817 (let ((tsr org-ts-regexp) diff
16818 (calendar-move-hook nil)
16819 (calendar-view-holidays-initially-flag nil)
16820 (calendar-view-diary-initially-flag nil))
16821 (if (or (org-at-timestamp-p)
16822 (save-excursion
16823 (beginning-of-line 1)
16824 (looking-at (concat ".*" tsr))))
16825 (let ((d1 (time-to-days (current-time)))
16826 (d2 (time-to-days
16827 (org-time-string-to-time (match-string 1)))))
16828 (setq diff (- d2 d1))))
16829 (calendar)
16830 (calendar-goto-today)
16831 (if (and diff (not arg)) (calendar-forward-day diff))))
16833 (defun org-get-date-from-calendar ()
16834 "Return a list (month day year) of date at point in calendar."
16835 (with-current-buffer "*Calendar*"
16836 (save-match-data
16837 (calendar-cursor-to-date))))
16839 (defun org-date-from-calendar ()
16840 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16841 If there is already a time stamp at the cursor position, update it."
16842 (interactive)
16843 (if (org-at-timestamp-p t)
16844 (org-timestamp-change 0 'calendar)
16845 (let ((cal-date (org-get-date-from-calendar)))
16846 (org-insert-time-stamp
16847 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16849 (defun org-minutes-to-clocksum-string (m)
16850 "Format number of minutes as a clocksum string.
16851 The format is determined by `org-time-clocksum-format',
16852 `org-time-clocksum-use-fractional' and
16853 `org-time-clocksum-fractional-format'."
16854 (let ((clocksum "") fmt n)
16855 ;; fractional format
16856 (if org-time-clocksum-use-fractional
16857 (cond
16858 ;; single format string
16859 ((stringp org-time-clocksum-fractional-format)
16860 (format org-time-clocksum-fractional-format (/ m 60.0)))
16861 ;; choice of fractional formats for different time units
16862 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
16863 (> (/ (truncate m) (* 365 24 60)) 0))
16864 (format fmt (/ m (* 365 24 60.0))))
16865 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
16866 (> (/ (truncate m) (* 30 24 60)) 0))
16867 (format fmt (/ m (* 30 24 60.0))))
16868 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16869 (> (/ (truncate m) (* 7 24 60)) 0))
16870 (format fmt (/ m (* 7 24 60.0))))
16871 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
16872 (> (/ (truncate m) (* 24 60)) 0))
16873 (format fmt (/ m (* 24 60.0))))
16874 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16875 (> (/ (truncate m) 60) 0))
16876 (format fmt (/ m 60.0)))
16877 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
16878 (format fmt m))
16879 ;; fall back to smallest time unit with a format
16880 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16881 (format fmt (/ m 60.0)))
16882 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
16883 (format fmt (/ m (* 24 60.0))))
16884 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16885 (format fmt (/ m (* 7 24 60.0))))
16886 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
16887 (format fmt (/ m (* 30 24 60.0))))
16888 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
16889 (format fmt (/ m (* 365 24 60.0)))))
16890 ;; standard (non-fractional) format, with single format string
16891 (if (stringp org-time-clocksum-format)
16892 (format org-time-clocksum-format (setq n (/ m 60)) (- m (* 60 n)))
16893 ;; separate formats components
16894 (and (setq fmt (plist-get org-time-clocksum-format :years))
16895 (or (> (setq n (/ (truncate m) (* 365 24 60))) 0)
16896 (plist-get org-time-clocksum-format :require-years))
16897 (setq clocksum (concat clocksum (format fmt n))
16898 m (- m (* n 365 24 60))))
16899 (and (setq fmt (plist-get org-time-clocksum-format :months))
16900 (or (> (setq n (/ (truncate m) (* 30 24 60))) 0)
16901 (plist-get org-time-clocksum-format :require-months))
16902 (setq clocksum (concat clocksum (format fmt n))
16903 m (- m (* n 30 24 60))))
16904 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
16905 (or (> (setq n (/ (truncate m) (* 7 24 60))) 0)
16906 (plist-get org-time-clocksum-format :require-weeks))
16907 (setq clocksum (concat clocksum (format fmt n))
16908 m (- m (* n 7 24 60))))
16909 (and (setq fmt (plist-get org-time-clocksum-format :days))
16910 (or (> (setq n (/ (truncate m) (* 24 60))) 0)
16911 (plist-get org-time-clocksum-format :require-days))
16912 (setq clocksum (concat clocksum (format fmt n))
16913 m (- m (* n 24 60))))
16914 (and (setq fmt (plist-get org-time-clocksum-format :hours))
16915 (or (> (setq n (/ (truncate m) 60)) 0)
16916 (plist-get org-time-clocksum-format :require-hours))
16917 (setq clocksum (concat clocksum (format fmt n))
16918 m (- m (* n 60))))
16919 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
16920 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
16921 (setq clocksum (concat clocksum (format fmt m))))
16922 ;; return formatted time duration
16923 clocksum))))
16925 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
16926 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
16927 "Org mode version 8.0")
16929 (defun org-hours-to-clocksum-string (n)
16930 (org-minutes-to-clocksum-string (* n 60)))
16932 (defun org-hh:mm-string-to-minutes (s)
16933 "Convert a string H:MM to a number of minutes.
16934 If the string is just a number, interpret it as minutes.
16935 In fact, the first hh:mm or number in the string will be taken,
16936 there can be extra stuff in the string.
16937 If no number is found, the return value is 0."
16938 (cond
16939 ((integerp s) s)
16940 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16941 (+ (* (string-to-number (match-string 1 s)) 60)
16942 (string-to-number (match-string 2 s))))
16943 ((string-match "\\([0-9]+\\)" s)
16944 (string-to-number (match-string 1 s)))
16945 (t 0)))
16947 (defcustom org-effort-durations
16948 `(("h" . 60)
16949 ("d" . ,(* 60 8))
16950 ("w" . ,(* 60 8 5))
16951 ("m" . ,(* 60 8 5 4))
16952 ("y" . ,(* 60 8 5 40)))
16953 "Conversion factor to minutes for an effort modifier.
16955 Each entry has the form (MODIFIER . MINUTES).
16957 In an effort string, a number followed by MODIFIER is multiplied
16958 by the specified number of MINUTES to obtain an effort in
16959 minutes.
16961 For example, if the value of this variable is ((\"hours\" . 60)), then an
16962 effort string \"2hours\" is equivalent to 120 minutes."
16963 :group 'org-agenda
16964 :version "24.1"
16965 :type '(alist :key-type (string :tag "Modifier")
16966 :value-type (number :tag "Minutes")))
16968 (defcustom org-image-actual-width t
16969 "Should we use the actual width of images when inlining them?
16971 When set to `t', always use the image width.
16973 When set to a number, use imagemagick (when available) to set
16974 the image's width to this value.
16976 When set to a number in a list, try to get the width from the
16977 #+ATTR.* keyword if it matches a width specification like
16978 width=\"[0-9]+\", and fall back on that number if none is found.
16980 When set to nil, try to get the width from an #+ATTR.* keyword
16981 and fall back on the original width if none is found.
16983 This requires Emacs >= 24.1, build with imagemagick support."
16984 :group 'org-appearance
16985 :version "24.3"
16986 :type '(choice
16987 (const :tag "Use the image width" t)
16988 (integer :tag "Use a number of pixels")
16989 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16990 (const :tag "Use #+ATTR* or don't resize" nil)))
16992 (defun org-duration-string-to-minutes (s &optional output-to-string)
16993 "Convert a duration string S to minutes.
16995 A bare number is interpreted as minutes, modifiers can be set by
16996 customizing `org-effort-durations' (which see).
16998 Entries containing a colon are interpreted as H:MM by
16999 `org-hh:mm-string-to-minutes'."
17000 (let ((result 0)
17001 (re (concat "\\([0-9.]+\\) *\\("
17002 (regexp-opt (mapcar 'car org-effort-durations))
17003 "\\)")))
17004 (while (string-match re s)
17005 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17006 (string-to-number (match-string 1 s))))
17007 (setq s (replace-match "" nil t s)))
17008 (setq result (floor result))
17009 (incf result (org-hh:mm-string-to-minutes s))
17010 (if output-to-string (number-to-string result) result)))
17012 ;;;; Files
17014 (defun org-save-all-org-buffers ()
17015 "Save all Org-mode buffers without user confirmation."
17016 (interactive)
17017 (message "Saving all Org-mode buffers...")
17018 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17019 (when (featurep 'org-id) (org-id-locations-save))
17020 (message "Saving all Org-mode buffers... done"))
17022 (defun org-revert-all-org-buffers ()
17023 "Revert all Org-mode buffers.
17024 Prompt for confirmation when there are unsaved changes.
17025 Be sure you know what you are doing before letting this function
17026 overwrite your changes.
17028 This function is useful in a setup where one tracks org files
17029 with a version control system, to revert on one machine after pulling
17030 changes from another. I believe the procedure must be like this:
17032 1. M-x org-save-all-org-buffers
17033 2. Pull changes from the other machine, resolve conflicts
17034 3. M-x org-revert-all-org-buffers"
17035 (interactive)
17036 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17037 (error "Abort"))
17038 (save-excursion
17039 (save-window-excursion
17040 (mapc
17041 (lambda (b)
17042 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17043 (with-current-buffer b buffer-file-name))
17044 (org-pop-to-buffer-same-window b)
17045 (revert-buffer t 'no-confirm)))
17046 (buffer-list))
17047 (when (and (featurep 'org-id) org-id-track-globally)
17048 (org-id-locations-load)))))
17050 ;;;; Agenda files
17052 ;;;###autoload
17053 (defun org-switchb (&optional arg)
17054 "Switch between Org buffers.
17055 With one prefix argument, restrict available buffers to files.
17056 With two prefix arguments, restrict available buffers to agenda files.
17058 Defaults to `iswitchb' for buffer name completion.
17059 Set `org-completion-use-ido' to make it use ido instead."
17060 (interactive "P")
17061 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17062 ((equal arg '(16)) (org-buffer-list 'agenda))
17063 (t (org-buffer-list))))
17064 (org-completion-use-iswitchb org-completion-use-iswitchb)
17065 (org-completion-use-ido org-completion-use-ido))
17066 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17067 (setq org-completion-use-iswitchb t))
17068 (org-pop-to-buffer-same-window
17069 (org-icompleting-read "Org buffer: "
17070 (mapcar 'list (mapcar 'buffer-name blist))
17071 nil t))))
17073 ;;; Define some older names previously used for this functionality
17074 ;;;###autoload
17075 (defalias 'org-ido-switchb 'org-switchb)
17076 ;;;###autoload
17077 (defalias 'org-iswitchb 'org-switchb)
17079 (defun org-buffer-list (&optional predicate exclude-tmp)
17080 "Return a list of Org buffers.
17081 PREDICATE can be `export', `files' or `agenda'.
17083 export restrict the list to Export buffers.
17084 files restrict the list to buffers visiting Org files.
17085 agenda restrict the list to buffers visiting agenda files.
17087 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17088 (let* ((bfn nil)
17089 (agenda-files (and (eq predicate 'agenda)
17090 (mapcar 'file-truename (org-agenda-files t))))
17091 (filter
17092 (cond
17093 ((eq predicate 'files)
17094 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17095 ((eq predicate 'export)
17096 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17097 ((eq predicate 'agenda)
17098 (lambda (b)
17099 (with-current-buffer b
17100 (and (derived-mode-p 'org-mode)
17101 (setq bfn (buffer-file-name b))
17102 (member (file-truename bfn) agenda-files)))))
17103 (t (lambda (b) (with-current-buffer b
17104 (or (derived-mode-p 'org-mode)
17105 (string-match "\*Org .*Export"
17106 (buffer-name b)))))))))
17107 (delq nil
17108 (mapcar
17109 (lambda(b)
17110 (if (and (funcall filter b)
17111 (or (not exclude-tmp)
17112 (not (string-match "tmp" (buffer-name b)))))
17114 nil))
17115 (buffer-list)))))
17117 (defun org-agenda-files (&optional unrestricted archives)
17118 "Get the list of agenda files.
17119 Optional UNRESTRICTED means return the full list even if a restriction
17120 is currently in place.
17121 When ARCHIVES is t, include all archive files that are really being
17122 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17123 `org-agenda-archives-mode' is t."
17124 (let ((files
17125 (cond
17126 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17127 ((stringp org-agenda-files) (org-read-agenda-file-list))
17128 ((listp org-agenda-files) org-agenda-files)
17129 (t (error "Invalid value of `org-agenda-files'")))))
17130 (setq files (apply 'append
17131 (mapcar (lambda (f)
17132 (if (file-directory-p f)
17133 (directory-files
17134 f t org-agenda-file-regexp)
17135 (list f)))
17136 files)))
17137 (when org-agenda-skip-unavailable-files
17138 (setq files (delq nil
17139 (mapcar (function
17140 (lambda (file)
17141 (and (file-readable-p file) file)))
17142 files))))
17143 (when (or (eq archives t)
17144 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17145 (setq files (org-add-archive-files files)))
17146 files))
17148 (defun org-agenda-file-p (&optional file)
17149 "Return non-nil, if FILE is an agenda file.
17150 If FILE is omitted, use the file associated with the current
17151 buffer."
17152 (member (or file (buffer-file-name))
17153 (org-agenda-files t)))
17155 (defun org-edit-agenda-file-list ()
17156 "Edit the list of agenda files.
17157 Depending on setup, this either uses customize to edit the variable
17158 `org-agenda-files', or it visits the file that is holding the list. In the
17159 latter case, the buffer is set up in a way that saving it automatically kills
17160 the buffer and restores the previous window configuration."
17161 (interactive)
17162 (if (stringp org-agenda-files)
17163 (let ((cw (current-window-configuration)))
17164 (find-file org-agenda-files)
17165 (org-set-local 'org-window-configuration cw)
17166 (org-add-hook 'after-save-hook
17167 (lambda ()
17168 (set-window-configuration
17169 (prog1 org-window-configuration
17170 (kill-buffer (current-buffer))))
17171 (org-install-agenda-files-menu)
17172 (message "New agenda file list installed"))
17173 nil 'local)
17174 (message "%s" (substitute-command-keys
17175 "Edit list and finish with \\[save-buffer]")))
17176 (customize-variable 'org-agenda-files)))
17178 (defun org-store-new-agenda-file-list (list)
17179 "Set new value for the agenda file list and save it correctly."
17180 (if (stringp org-agenda-files)
17181 (let ((fe (org-read-agenda-file-list t)) b u)
17182 (while (setq b (find-buffer-visiting org-agenda-files))
17183 (kill-buffer b))
17184 (with-temp-file org-agenda-files
17185 (insert
17186 (mapconcat
17187 (lambda (f) ;; Keep un-expanded entries.
17188 (if (setq u (assoc f fe))
17189 (cdr u)
17191 list "\n")
17192 "\n")))
17193 (let ((org-mode-hook nil) (org-inhibit-startup t)
17194 (org-insert-mode-line-in-empty-file nil))
17195 (setq org-agenda-files list)
17196 (customize-save-variable 'org-agenda-files org-agenda-files))))
17198 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17199 "Read the list of agenda files from a file.
17200 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17201 filenames, used by `org-store-new-agenda-file-list' to write back
17202 un-expanded file names."
17203 (when (file-directory-p org-agenda-files)
17204 (error "`org-agenda-files' cannot be a single directory"))
17205 (when (stringp org-agenda-files)
17206 (with-temp-buffer
17207 (insert-file-contents org-agenda-files)
17208 (mapcar
17209 (lambda (f)
17210 (let ((e (expand-file-name (substitute-in-file-name f)
17211 org-directory)))
17212 (if pair-with-expansion
17213 (cons e f)
17214 e)))
17215 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17217 ;;;###autoload
17218 (defun org-cycle-agenda-files ()
17219 "Cycle through the files in `org-agenda-files'.
17220 If the current buffer visits an agenda file, find the next one in the list.
17221 If the current buffer does not, find the first agenda file."
17222 (interactive)
17223 (let* ((fs (org-agenda-files t))
17224 (files (append fs (list (car fs))))
17225 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17226 file)
17227 (unless files (error "No agenda files"))
17228 (catch 'exit
17229 (while (setq file (pop files))
17230 (if (equal (file-truename file) tcf)
17231 (when (car files)
17232 (find-file (car files))
17233 (throw 'exit t))))
17234 (find-file (car fs)))
17235 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17237 (defun org-agenda-file-to-front (&optional to-end)
17238 "Move/add the current file to the top of the agenda file list.
17239 If the file is not present in the list, it is added to the front. If it is
17240 present, it is moved there. With optional argument TO-END, add/move to the
17241 end of the list."
17242 (interactive "P")
17243 (let ((org-agenda-skip-unavailable-files nil)
17244 (file-alist (mapcar (lambda (x)
17245 (cons (file-truename x) x))
17246 (org-agenda-files t)))
17247 (ctf (file-truename
17248 (or buffer-file-name
17249 (error "Please save the current buffer to a file"))))
17250 x had)
17251 (setq x (assoc ctf file-alist) had x)
17253 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17254 (if to-end
17255 (setq file-alist (append (delq x file-alist) (list x)))
17256 (setq file-alist (cons x (delq x file-alist))))
17257 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17258 (org-install-agenda-files-menu)
17259 (message "File %s to %s of agenda file list"
17260 (if had "moved" "added") (if to-end "end" "front"))))
17262 (defun org-remove-file (&optional file)
17263 "Remove current file from the list of files in variable `org-agenda-files'.
17264 These are the files which are being checked for agenda entries.
17265 Optional argument FILE means use this file instead of the current."
17266 (interactive)
17267 (let* ((org-agenda-skip-unavailable-files nil)
17268 (file (or file buffer-file-name
17269 (error "Current buffer does not visit a file")))
17270 (true-file (file-truename file))
17271 (afile (abbreviate-file-name file))
17272 (files (delq nil (mapcar
17273 (lambda (x)
17274 (if (equal true-file
17275 (file-truename x))
17276 nil x))
17277 (org-agenda-files t)))))
17278 (if (not (= (length files) (length (org-agenda-files t))))
17279 (progn
17280 (org-store-new-agenda-file-list files)
17281 (org-install-agenda-files-menu)
17282 (message "Removed file: %s" afile))
17283 (message "File was not in list: %s (not removed)" afile))))
17285 (defun org-file-menu-entry (file)
17286 (vector file (list 'find-file file) t))
17288 (defun org-check-agenda-file (file)
17289 "Make sure FILE exists. If not, ask user what to do."
17290 (when (not (file-exists-p file))
17291 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17292 (abbreviate-file-name file))
17293 (let ((r (downcase (read-char-exclusive))))
17294 (cond
17295 ((equal r ?r)
17296 (org-remove-file file)
17297 (throw 'nextfile t))
17298 (t (error "Abort"))))))
17300 (defun org-get-agenda-file-buffer (file)
17301 "Get a buffer visiting FILE. If the buffer needs to be created, add
17302 it to the list of buffers which might be released later."
17303 (let ((buf (org-find-base-buffer-visiting file)))
17304 (if buf
17305 buf ; just return it
17306 ;; Make a new buffer and remember it
17307 (setq buf (find-file-noselect file))
17308 (if buf (push buf org-agenda-new-buffers))
17309 buf)))
17311 (defun org-release-buffers (blist)
17312 "Release all buffers in list, asking the user for confirmation when needed.
17313 When a buffer is unmodified, it is just killed. When modified, it is saved
17314 \(if the user agrees) and then killed."
17315 (let (buf file)
17316 (while (setq buf (pop blist))
17317 (setq file (buffer-file-name buf))
17318 (when (and (buffer-modified-p buf)
17319 file
17320 (y-or-n-p (format "Save file %s? " file)))
17321 (with-current-buffer buf (save-buffer)))
17322 (kill-buffer buf))))
17324 (defun org-agenda-prepare-buffers (files)
17325 "Create buffers for all agenda files, protect archived trees and comments."
17326 (interactive)
17327 (let ((pa '(:org-archived t))
17328 (pc '(:org-comment t))
17329 (pall '(:org-archived t :org-comment t))
17330 (inhibit-read-only t)
17331 (rea (concat ":" org-archive-tag ":"))
17332 bmp file re)
17333 (save-excursion
17334 (save-restriction
17335 (while (setq file (pop files))
17336 (catch 'nextfile
17337 (if (bufferp file)
17338 (set-buffer file)
17339 (org-check-agenda-file file)
17340 (set-buffer (org-get-agenda-file-buffer file)))
17341 (widen)
17342 (setq bmp (buffer-modified-p))
17343 (org-refresh-category-properties)
17344 (setq org-todo-keywords-for-agenda
17345 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17346 (setq org-done-keywords-for-agenda
17347 (append org-done-keywords-for-agenda org-done-keywords))
17348 (setq org-todo-keyword-alist-for-agenda
17349 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17350 (setq org-drawers-for-agenda
17351 (append org-drawers-for-agenda org-drawers))
17352 (setq org-tag-alist-for-agenda
17353 (append org-tag-alist-for-agenda org-tag-alist))
17355 (save-excursion
17356 (remove-text-properties (point-min) (point-max) pall)
17357 (when org-agenda-skip-archived-trees
17358 (goto-char (point-min))
17359 (while (re-search-forward rea nil t)
17360 (if (org-at-heading-p t)
17361 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17362 (goto-char (point-min))
17363 (setq re (format org-heading-keyword-regexp-format
17364 org-comment-string))
17365 (while (re-search-forward re nil t)
17366 (add-text-properties
17367 (match-beginning 0) (org-end-of-subtree t) pc)))
17368 (set-buffer-modified-p bmp)))))
17369 (setq org-todo-keywords-for-agenda
17370 (org-uniquify org-todo-keywords-for-agenda))
17371 (setq org-todo-keyword-alist-for-agenda
17372 (org-uniquify org-todo-keyword-alist-for-agenda)
17373 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17375 ;;;; Embedded LaTeX
17377 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17378 "Keymap for the minor `org-cdlatex-mode'.")
17380 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17381 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17382 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17383 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17384 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17386 (defvar org-cdlatex-texmathp-advice-is-done nil
17387 "Flag remembering if we have applied the advice to texmathp already.")
17389 (define-minor-mode org-cdlatex-mode
17390 "Toggle the minor `org-cdlatex-mode'.
17391 This mode supports entering LaTeX environment and math in LaTeX fragments
17392 in Org-mode.
17393 \\{org-cdlatex-mode-map}"
17394 nil " OCDL" nil
17395 (when org-cdlatex-mode
17396 (require 'cdlatex)
17397 (run-hooks 'cdlatex-mode-hook)
17398 (cdlatex-compute-tables))
17399 (unless org-cdlatex-texmathp-advice-is-done
17400 (setq org-cdlatex-texmathp-advice-is-done t)
17401 (defadvice texmathp (around org-math-always-on activate)
17402 "Always return t in org-mode buffers.
17403 This is because we want to insert math symbols without dollars even outside
17404 the LaTeX math segments. If Orgmode thinks that point is actually inside
17405 an embedded LaTeX fragment, let texmathp do its job.
17406 \\[org-cdlatex-mode-map]"
17407 (interactive)
17408 (let (p)
17409 (cond
17410 ((not (derived-mode-p 'org-mode)) ad-do-it)
17411 ((eq this-command 'cdlatex-math-symbol)
17412 (setq ad-return-value t
17413 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17415 (let ((p (org-inside-LaTeX-fragment-p)))
17416 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17417 (setq ad-return-value t
17418 texmathp-why '("Org-mode embedded math" . 0))
17419 (if p ad-do-it)))))))))
17421 (defun turn-on-org-cdlatex ()
17422 "Unconditionally turn on `org-cdlatex-mode'."
17423 (org-cdlatex-mode 1))
17425 (defun org-inside-LaTeX-fragment-p ()
17426 "Test if point is inside a LaTeX fragment.
17427 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17428 sequence appearing also before point.
17429 Even though the matchers for math are configurable, this function assumes
17430 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17431 delimiters are skipped when they have been removed by customization.
17432 The return value is nil, or a cons cell with the delimiter and the
17433 position of this delimiter.
17435 This function does a reasonably good job, but can locally be fooled by
17436 for example currency specifications. For example it will assume being in
17437 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17438 fragments that are properly closed, but during editing, we have to live
17439 with the uncertainty caused by missing closing delimiters. This function
17440 looks only before point, not after."
17441 (catch 'exit
17442 (let ((pos (point))
17443 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17444 (lim (progn
17445 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17446 (point)))
17447 dd-on str (start 0) m re)
17448 (goto-char pos)
17449 (when dodollar
17450 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17451 re (nth 1 (assoc "$" org-latex-regexps)))
17452 (while (string-match re str start)
17453 (cond
17454 ((= (match-end 0) (length str))
17455 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17456 ((= (match-end 0) (- (length str) 5))
17457 (throw 'exit nil))
17458 (t (setq start (match-end 0))))))
17459 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17460 (goto-char pos)
17461 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17462 (and (match-beginning 2) (throw 'exit nil))
17463 ;; count $$
17464 (while (re-search-backward "\\$\\$" lim t)
17465 (setq dd-on (not dd-on)))
17466 (goto-char pos)
17467 (if dd-on (cons "$$" m))))))
17469 (defun org-inside-latex-macro-p ()
17470 "Is point inside a LaTeX macro or its arguments?"
17471 (save-match-data
17472 (org-in-regexp
17473 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17475 (defun org-try-cdlatex-tab ()
17476 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17477 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17478 - inside a LaTeX fragment, or
17479 - after the first word in a line, where an abbreviation expansion could
17480 insert a LaTeX environment."
17481 (when org-cdlatex-mode
17482 (cond
17483 ;; Before any word on the line: No expansion possible.
17484 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17485 ;; Just after first word on the line: Expand it. Make sure it
17486 ;; cannot happen on headlines, though.
17487 ((save-excursion
17488 (skip-chars-backward "a-zA-Z0-9*")
17489 (skip-chars-backward " \t")
17490 (and (bolp) (not (org-at-heading-p))))
17491 (cdlatex-tab) t)
17492 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17494 (defun org-cdlatex-underscore-caret (&optional arg)
17495 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17496 Revert to the normal definition outside of these fragments."
17497 (interactive "P")
17498 (if (org-inside-LaTeX-fragment-p)
17499 (call-interactively 'cdlatex-sub-superscript)
17500 (let (org-cdlatex-mode)
17501 (call-interactively (key-binding (vector last-input-event))))))
17503 (defun org-cdlatex-math-modify (&optional arg)
17504 "Execute `cdlatex-math-modify' in LaTeX fragments.
17505 Revert to the normal definition outside of these fragments."
17506 (interactive "P")
17507 (if (org-inside-LaTeX-fragment-p)
17508 (call-interactively 'cdlatex-math-modify)
17509 (let (org-cdlatex-mode)
17510 (call-interactively (key-binding (vector last-input-event))))))
17512 (defvar org-latex-fragment-image-overlays nil
17513 "List of overlays carrying the images of latex fragments.")
17514 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17516 (defun org-remove-latex-fragment-image-overlays ()
17517 "Remove all overlays with LaTeX fragment images in current buffer."
17518 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17519 (setq org-latex-fragment-image-overlays nil))
17521 (defun org-preview-latex-fragment (&optional subtree)
17522 "Preview the LaTeX fragment at point, or all locally or globally.
17523 If the cursor is in a LaTeX fragment, create the image and overlay
17524 it over the source code. If there is no fragment at point, display
17525 all fragments in the current text, from one headline to the next. With
17526 prefix SUBTREE, display all fragments in the current subtree. With a
17527 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17528 the cursor is before the first headline,
17529 display all fragments in the buffer.
17530 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17531 (interactive "P")
17532 (unless buffer-file-name
17533 (error "Can't preview LaTeX fragment in a non-file buffer"))
17534 (org-remove-latex-fragment-image-overlays)
17535 (save-excursion
17536 (save-restriction
17537 (let (beg end at msg)
17538 (cond
17539 ((or (equal subtree '(16))
17540 (not (save-excursion
17541 (re-search-backward org-outline-regexp-bol nil t))))
17542 (setq beg (point-min) end (point-max)
17543 msg "Creating images for buffer...%s"))
17544 ((equal subtree '(4))
17545 (org-back-to-heading)
17546 (setq beg (point) end (org-end-of-subtree t)
17547 msg "Creating images for subtree...%s"))
17549 (if (setq at (org-inside-LaTeX-fragment-p))
17550 (goto-char (max (point-min) (- (cdr at) 2)))
17551 (org-back-to-heading))
17552 (setq beg (point) end (progn (outline-next-heading) (point))
17553 msg (if at "Creating image...%s"
17554 "Creating images for entry...%s"))))
17555 (message msg "")
17556 (narrow-to-region beg end)
17557 (goto-char beg)
17558 (org-format-latex
17559 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17560 (file-name-nondirectory
17561 buffer-file-name)))
17562 default-directory 'overlays msg at 'forbuffer
17563 org-latex-create-formula-image-program)
17564 (message msg "done. Use `C-c C-c' to remove images.")))))
17566 (defvar org-latex-regexps
17567 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17568 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17569 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17570 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17571 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17572 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17573 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17574 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17575 "Regular expressions for matching embedded LaTeX.")
17577 (defvar org-export-have-math nil) ;; dynamic scoping
17578 (defun org-format-latex (prefix &optional dir overlays msg at
17579 forbuffer processing-type)
17580 "Replace LaTeX fragments with links to an image, and produce images.
17581 Some of the options can be changed using the variable
17582 `org-format-latex-options'."
17583 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17584 (let* ((prefixnodir (file-name-nondirectory prefix))
17585 (absprefix (expand-file-name prefix dir))
17586 (todir (file-name-directory absprefix))
17587 (opt org-format-latex-options)
17588 (optnew org-format-latex-options)
17589 (matchers (plist-get opt :matchers))
17590 (re-list org-latex-regexps)
17591 (org-format-latex-header-extra
17592 (plist-get (org-infile-export-plist) :latex-header-extra))
17593 (cnt 0) txt hash link beg end re e checkdir
17594 string
17595 m n block-type block linkfile movefile ov)
17596 ;; Check the different regular expressions
17597 (while (setq e (pop re-list))
17598 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17599 block (if block-type "\n\n" ""))
17600 (when (member m matchers)
17601 (goto-char (point-min))
17602 (while (re-search-forward re nil t)
17603 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17604 (not (get-text-property (match-beginning n)
17605 'org-protected))
17606 (or (not overlays)
17607 (not (eq (get-char-property (match-beginning n)
17608 'org-overlay-type)
17609 'org-latex-overlay))))
17610 (setq org-export-have-math t)
17611 (cond
17612 ((eq processing-type 'verbatim)
17613 ;; Leave the text verbatim, just protect it
17614 (add-text-properties (match-beginning n) (match-end n)
17615 '(org-protected t)))
17616 ((eq processing-type 'mathjax)
17617 ;; Prepare for MathJax processing
17618 (setq string (match-string n))
17619 (if (member m '("$" "$1"))
17620 (save-excursion
17621 (delete-region (match-beginning n) (match-end n))
17622 (goto-char (match-beginning n))
17623 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17624 "\\)")
17625 '(org-protected t))))
17626 (add-text-properties (match-beginning n) (match-end n)
17627 '(org-protected t))))
17628 ((or (eq processing-type 'dvipng)
17629 (eq processing-type 'imagemagick))
17630 ;; Process to an image
17631 (setq txt (match-string n)
17632 beg (match-beginning n) end (match-end n)
17633 cnt (1+ cnt))
17634 (let ((face (face-at-point))
17635 (fg (plist-get opt :foreground))
17636 (bg (plist-get opt :background))
17637 print-length print-level) ; make sure full list is printed
17638 (when forbuffer
17639 ; Get the colors from the face at point
17640 (goto-char beg)
17641 (when (eq fg 'auto)
17642 (setq fg (face-attribute face :foreground nil 'default)))
17643 (when (eq bg 'auto)
17644 (setq bg (face-attribute face :background nil 'default)))
17645 (setq optnew (copy-sequence opt))
17646 (plist-put optnew :foreground fg)
17647 (plist-put optnew :background bg))
17648 (setq hash (sha1 (prin1-to-string
17649 (list org-format-latex-header
17650 org-format-latex-header-extra
17651 org-export-latex-default-packages-alist
17652 org-export-latex-packages-alist
17653 org-format-latex-options
17654 forbuffer txt fg bg)))
17655 linkfile (format "%s_%s.png" prefix hash)
17656 movefile (format "%s_%s.png" absprefix hash)))
17657 (setq link (concat block "[[file:" linkfile "]]" block))
17658 (if msg (message msg cnt))
17659 (goto-char beg)
17660 (unless checkdir ; make sure the directory exists
17661 (setq checkdir t)
17662 (or (file-directory-p todir) (make-directory todir t)))
17663 (unless (file-exists-p movefile)
17664 (org-create-formula-image
17665 txt movefile optnew forbuffer processing-type))
17666 (if overlays
17667 (progn
17668 (mapc (lambda (o)
17669 (if (eq (overlay-get o 'org-overlay-type)
17670 'org-latex-overlay)
17671 (delete-overlay o)))
17672 (overlays-in beg end))
17673 (setq ov (make-overlay beg end))
17674 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17675 (if (featurep 'xemacs)
17676 (progn
17677 (overlay-put ov 'invisible t)
17678 (overlay-put
17679 ov 'end-glyph
17680 (make-glyph (vector 'png :file movefile))))
17681 (overlay-put
17682 ov 'display
17683 (list 'image :type 'png :file movefile :ascent 'center)))
17684 (push ov org-latex-fragment-image-overlays)
17685 (goto-char end))
17686 (delete-region beg end)
17687 (insert (org-add-props link
17688 (list 'org-latex-src
17689 (replace-regexp-in-string
17690 "\"" "" txt)
17691 'org-latex-src-embed-type
17692 (if block-type 'paragraph 'character))))))
17693 ((eq processing-type 'mathml)
17694 ;; Process to MathML
17695 (unless (save-match-data (org-format-latex-mathml-available-p))
17696 (error "LaTeX to MathML converter not configured"))
17697 (setq txt (match-string n)
17698 beg (match-beginning n) end (match-end n)
17699 cnt (1+ cnt))
17700 (if msg (message msg cnt))
17701 (goto-char beg)
17702 (delete-region beg end)
17703 (insert (org-format-latex-as-mathml
17704 txt block-type prefix dir)))
17706 (error "Unknown conversion type %s for latex fragments"
17707 processing-type)))))))))
17709 (defun org-create-math-formula (latex-frag &optional mathml-file)
17710 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17711 Use `org-latex-to-mathml-convert-command'. If the conversion is
17712 sucessful, return the portion between \"<math...> </math>\"
17713 elements otherwise return nil. When MATHML-FILE is specified,
17714 write the results in to that file. When invoked as an
17715 interactive command, prompt for LATEX-FRAG, with initial value
17716 set to the current active region and echo the results for user
17717 inspection."
17718 (interactive (list (let ((frag (when (org-region-active-p)
17719 (buffer-substring-no-properties
17720 (region-beginning) (region-end)))))
17721 (read-string "LaTeX Fragment: " frag nil frag))))
17722 (unless latex-frag (error "Invalid latex-frag"))
17723 (let* ((tmp-in-file (file-relative-name
17724 (make-temp-name (expand-file-name "ltxmathml-in"))))
17725 (ignore (write-region latex-frag nil tmp-in-file))
17726 (tmp-out-file (file-relative-name
17727 (make-temp-name (expand-file-name "ltxmathml-out"))))
17728 (cmd (format-spec
17729 org-latex-to-mathml-convert-command
17730 `((?j . ,(shell-quote-argument
17731 (expand-file-name org-latex-to-mathml-jar-file)))
17732 (?I . ,(shell-quote-argument tmp-in-file))
17733 (?o . ,(shell-quote-argument tmp-out-file)))))
17734 mathml shell-command-output)
17735 (when (org-called-interactively-p 'any)
17736 (unless (org-format-latex-mathml-available-p)
17737 (error "LaTeX to MathML converter not configured")))
17738 (message "Running %s" cmd)
17739 (setq shell-command-output (shell-command-to-string cmd))
17740 (setq mathml
17741 (when (file-readable-p tmp-out-file)
17742 (with-current-buffer (find-file-noselect tmp-out-file t)
17743 (goto-char (point-min))
17744 (when (re-search-forward
17745 (concat
17746 (regexp-quote
17747 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17748 "\\(.\\|\n\\)*"
17749 (regexp-quote "</math>")) nil t)
17750 (prog1 (match-string 0) (kill-buffer))))))
17751 (cond
17752 (mathml
17753 (setq mathml
17754 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17755 (when mathml-file
17756 (write-region mathml nil mathml-file))
17757 (when (org-called-interactively-p 'any)
17758 (message mathml)))
17759 ((message "LaTeX to MathML conversion failed")
17760 (message shell-command-output)))
17761 (delete-file tmp-in-file)
17762 (when (file-exists-p tmp-out-file)
17763 (delete-file tmp-out-file))
17764 mathml))
17766 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17767 prefix &optional dir)
17768 "Use `org-create-math-formula' but check local cache first."
17769 (let* ((absprefix (expand-file-name prefix dir))
17770 (print-length nil) (print-level nil)
17771 (formula-id (concat
17772 "formula-"
17773 (sha1
17774 (prin1-to-string
17775 (list latex-frag
17776 org-latex-to-mathml-convert-command)))))
17777 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17778 (formula-cache-dir (file-name-directory formula-cache)))
17780 (unless (file-directory-p formula-cache-dir)
17781 (make-directory formula-cache-dir t))
17783 (unless (file-exists-p formula-cache)
17784 (org-create-math-formula latex-frag formula-cache))
17786 (if (file-exists-p formula-cache)
17787 ;; Successful conversion. Return the link to MathML file.
17788 (org-add-props
17789 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17790 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17791 'org-latex-src-embed-type (if latex-frag-type
17792 'paragraph 'character)))
17793 ;; Failed conversion. Return the LaTeX fragment verbatim
17794 (add-text-properties
17795 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17796 latex-frag)))
17798 (defun org-create-formula-image (string tofile options buffer &optional type)
17799 "Create an image from LaTeX source using dvipng or convert.
17800 This function calls either `org-create-formula-image-with-dvipng'
17801 or `org-create-formula-image-with-imagemagick' depending on the
17802 value of `org-latex-create-formula-image-program' or on the value
17803 of the optional TYPE variable.
17805 Note: ultimately these two function should be combined as they
17806 share a good deal of logic."
17807 (org-check-external-command
17808 "latex" "needed to convert LaTeX fragments to images")
17809 (funcall
17810 (case (or type org-latex-create-formula-image-program)
17811 ('dvipng
17812 (org-check-external-command
17813 "dvipng" "needed to convert LaTeX fragments to images")
17814 #'org-create-formula-image-with-dvipng)
17815 ('imagemagick
17816 (org-check-external-command
17817 "convert" "you need to install imagemagick")
17818 #'org-create-formula-image-with-imagemagick)
17819 (t (error
17820 "invalid value of `org-latex-create-formula-image-program'")))
17821 string tofile options buffer))
17823 ;; This function borrows from Ganesh Swami's latex2png.el
17824 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17825 "This calls dvipng."
17826 (require 'org-latex)
17827 (let* ((tmpdir (if (featurep 'xemacs)
17828 (temp-directory)
17829 temporary-file-directory))
17830 (texfilebase (make-temp-name
17831 (expand-file-name "orgtex" tmpdir)))
17832 (texfile (concat texfilebase ".tex"))
17833 (dvifile (concat texfilebase ".dvi"))
17834 (pngfile (concat texfilebase ".png"))
17835 (fnh (if (featurep 'xemacs)
17836 (font-height (face-font 'default))
17837 (face-attribute 'default :height nil)))
17838 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17839 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17840 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17841 "Black"))
17842 (bg (or (plist-get options (if buffer :background :html-background))
17843 "Transparent")))
17844 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17845 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17846 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17847 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17848 (with-temp-file texfile
17849 (insert (org-splice-latex-header
17850 org-format-latex-header
17851 org-export-latex-default-packages-alist
17852 org-export-latex-packages-alist t
17853 org-format-latex-header-extra))
17854 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17855 (require 'org-latex)
17856 (org-export-latex-fix-inputenc))
17857 (let ((dir default-directory))
17858 (condition-case nil
17859 (progn
17860 (cd tmpdir)
17861 (call-process "latex" nil nil nil texfile))
17862 (error nil))
17863 (cd dir))
17864 (if (not (file-exists-p dvifile))
17865 (progn (message "Failed to create dvi file from %s" texfile) nil)
17866 (condition-case nil
17867 (if (featurep 'xemacs)
17868 (call-process "dvipng" nil nil nil
17869 "-fg" fg "-bg" bg
17870 "-T" "tight"
17871 "-o" pngfile
17872 dvifile)
17873 (call-process "dvipng" nil nil nil
17874 "-fg" fg "-bg" bg
17875 "-D" dpi
17876 ;;"-x" scale "-y" scale
17877 "-T" "tight"
17878 "-o" pngfile
17879 dvifile))
17880 (error nil))
17881 (if (not (file-exists-p pngfile))
17882 (if org-format-latex-signal-error
17883 (error "Failed to create png file from %s" texfile)
17884 (message "Failed to create png file from %s" texfile)
17885 nil)
17886 ;; Use the requested file name and clean up
17887 (copy-file pngfile tofile 'replace)
17888 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17889 (if (file-exists-p (concat texfilebase e))
17890 (delete-file (concat texfilebase e))))
17891 pngfile))))
17893 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17894 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17895 "This calls convert, which is included into imagemagick."
17896 (require 'org-latex)
17897 (let* ((tmpdir (if (featurep 'xemacs)
17898 (temp-directory)
17899 temporary-file-directory))
17900 (texfilebase (make-temp-name
17901 (expand-file-name "orgtex" tmpdir)))
17902 (texfile (concat texfilebase ".tex"))
17903 (pdffile (concat texfilebase ".pdf"))
17904 (pngfile (concat texfilebase ".png"))
17905 (fnh (if (featurep 'xemacs)
17906 (font-height (face-font 'default))
17907 (face-attribute 'default :height nil)))
17908 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17909 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17910 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17911 "black"))
17912 (bg (or (plist-get options (if buffer :background :html-background))
17913 "white")))
17914 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17915 (setq fg (org-latex-color-format fg)))
17916 (if (eq bg 'default) (setq bg (org-latex-color :background))
17917 (setq bg (org-latex-color-format
17918 (if (string= bg "Transparent") "white" bg))))
17919 (with-temp-file texfile
17920 (insert (org-splice-latex-header
17921 org-format-latex-header
17922 org-export-latex-default-packages-alist
17923 org-export-latex-packages-alist t
17924 org-format-latex-header-extra))
17925 (insert "\n\\begin{document}\n"
17926 "\\definecolor{fg}{rgb}{" fg "}\n"
17927 "\\definecolor{bg}{rgb}{" bg "}\n"
17928 "\n\\pagecolor{bg}\n"
17929 "\n{\\color{fg}\n"
17930 string
17931 "\n}\n"
17932 "\n\\end{document}\n" )
17933 (require 'org-latex)
17934 (org-export-latex-fix-inputenc))
17935 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17936 (condition-case nil
17937 (progn
17938 (cd tmpdir)
17939 (setq cmds org-latex-to-pdf-process)
17940 (while cmds
17941 (setq latex-frags-cmds (pop cmds))
17942 (if (listp latex-frags-cmds)
17943 (setq cmds nil)
17944 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17945 (while latex-frags-cmds
17946 (setq cmd (pop latex-frags-cmds))
17947 (while (string-match "%b" cmd)
17948 (setq cmd (replace-match
17949 (save-match-data
17950 (shell-quote-argument texfile))
17951 t t cmd)))
17952 (while (string-match "%f" cmd)
17953 (setq cmd (replace-match
17954 (save-match-data
17955 (shell-quote-argument (file-name-nondirectory texfile)))
17956 t t cmd)))
17957 (while (string-match "%o" cmd)
17958 (setq cmd (replace-match
17959 (save-match-data
17960 (shell-quote-argument (file-name-directory texfile)))
17961 t t cmd)))
17962 (setq cmd (split-string cmd))
17963 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17964 (error nil))
17965 (cd dir))
17966 (if (not (file-exists-p pdffile))
17967 (progn (message "Failed to create pdf file from %s" texfile) nil)
17968 (condition-case nil
17969 (if (featurep 'xemacs)
17970 (call-process "convert" nil nil nil
17971 "-density" "96"
17972 "-trim"
17973 "-antialias"
17974 pdffile
17975 "-quality" "100"
17976 ;; "-sharpen" "0x1.0"
17977 pngfile)
17978 (call-process "convert" nil nil nil
17979 "-density" dpi
17980 "-trim"
17981 "-antialias"
17982 pdffile
17983 "-quality" "100"
17984 ; "-sharpen" "0x1.0"
17985 pngfile))
17986 (error nil))
17987 (if (not (file-exists-p pngfile))
17988 (if org-format-latex-signal-error
17989 (error "Failed to create png file from %s" texfile)
17990 (message "Failed to create png file from %s" texfile)
17991 nil)
17992 ;; Use the requested file name and clean up
17993 (copy-file pngfile tofile 'replace)
17994 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17995 (if (file-exists-p (concat texfilebase e))
17996 (delete-file (concat texfilebase e))))
17997 pngfile))))
17999 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18000 "Fill a LaTeX header template TPL.
18001 In the template, the following place holders will be recognized:
18003 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18004 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18005 [PACKAGES] \\usepackage statements for PKG
18006 [NO-PACKAGES] do not include PKG
18007 [EXTRA] the string EXTRA
18008 [NO-EXTRA] do not include EXTRA
18010 For backward compatibility, if both the positive and the negative place
18011 holder is missing, the positive one (without the \"NO-\") will be
18012 assumed to be present at the end of the template.
18013 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18014 EXTRA is a string.
18015 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18016 (let (rpl (end ""))
18017 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18018 (setq rpl (if (or (match-end 1) (not def-pkg))
18019 "" (org-latex-packages-to-string def-pkg snippets-p t))
18020 tpl (replace-match rpl t t tpl))
18021 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18023 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18024 (setq rpl (if (or (match-end 1) (not pkg))
18025 "" (org-latex-packages-to-string pkg snippets-p t))
18026 tpl (replace-match rpl t t tpl))
18027 (if pkg (setq end
18028 (concat end "\n"
18029 (org-latex-packages-to-string pkg snippets-p)))))
18031 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18032 (setq rpl (if (or (match-end 1) (not extra))
18033 "" (concat extra "\n"))
18034 tpl (replace-match rpl t t tpl))
18035 (if (and extra (string-match "\\S-" extra))
18036 (setq end (concat end "\n" extra))))
18038 (if (string-match "\\S-" end)
18039 (concat tpl "\n" end)
18040 tpl)))
18042 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18043 "Turn an alist of packages into a string with the \\usepackage macros."
18044 (setq pkg (mapconcat (lambda(p)
18045 (cond
18046 ((stringp p) p)
18047 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18048 (format "%% Package %s omitted" (cadr p)))
18049 ((equal "" (car p))
18050 (format "\\usepackage{%s}" (cadr p)))
18052 (format "\\usepackage[%s]{%s}"
18053 (car p) (cadr p)))))
18055 "\n"))
18056 (if newline (concat pkg "\n") pkg))
18058 (defun org-dvipng-color (attr)
18059 "Return a RGB color specification for dvipng."
18060 (apply 'format "rgb %s %s %s"
18061 (mapcar 'org-normalize-color
18062 (if (featurep 'xemacs)
18063 (color-rgb-components
18064 (face-property 'default
18065 (cond ((eq attr :foreground) 'foreground)
18066 ((eq attr :background) 'background))))
18067 (color-values (face-attribute 'default attr nil))))))
18069 (defun org-dvipng-color-format (color-name)
18070 "Convert COLOR-NAME to a RGB color value for dvipng."
18071 (apply 'format "rgb %s %s %s"
18072 (mapcar 'org-normalize-color
18073 (color-values color-name))))
18075 (defun org-latex-color (attr)
18076 "Return a RGB color for the LaTeX color package."
18077 (apply 'format "%s,%s,%s"
18078 (mapcar 'org-normalize-color
18079 (if (featurep 'xemacs)
18080 (color-rgb-components
18081 (face-property 'default
18082 (cond ((eq attr :foreground) 'foreground)
18083 ((eq attr :background) 'background))))
18084 (color-values (face-attribute 'default attr nil))))))
18086 (defun org-latex-color-format (color-name)
18087 "Convert COLOR-NAME to a RGB color value."
18088 (apply 'format "%s,%s,%s"
18089 (mapcar 'org-normalize-color
18090 (color-values color-name))))
18092 (defun org-normalize-color (value)
18093 "Return string to be used as color value for an RGB component."
18094 (format "%g" (/ value 65535.0)))
18096 ;; Image display
18099 (defvar org-inline-image-overlays nil)
18100 (make-variable-buffer-local 'org-inline-image-overlays)
18102 (defun org-toggle-inline-images (&optional include-linked)
18103 "Toggle the display of inline images.
18104 INCLUDE-LINKED is passed to `org-display-inline-images'."
18105 (interactive "P")
18106 (if org-inline-image-overlays
18107 (progn
18108 (org-remove-inline-images)
18109 (message "Inline image display turned off"))
18110 (org-display-inline-images include-linked)
18111 (if (and (org-called-interactively-p)
18112 org-inline-image-overlays)
18113 (message "%d images displayed inline"
18114 (length org-inline-image-overlays))
18115 (message "No images to display inline"))))
18117 (defun org-redisplay-inline-images ()
18118 "Refresh the display of inline images."
18119 (interactive)
18120 (if (not org-inline-image-overlays)
18121 (org-toggle-inline-images)
18122 (org-toggle-inline-images)
18123 (org-toggle-inline-images)))
18125 (defun org-display-inline-images (&optional include-linked refresh beg end)
18126 "Display inline images.
18127 Normally only links without a description part are inlined, because this
18128 is how it will work for export. When INCLUDE-LINKED is set, also links
18129 with a description part will be inlined. This can be nice for a quick
18130 look at those images, but it does not reflect what exported files will look
18131 like.
18132 When REFRESH is set, refresh existing images between BEG and END.
18133 This will create new image displays only if necessary.
18134 BEG and END default to the buffer boundaries."
18135 (interactive "P")
18136 (unless refresh
18137 (org-remove-inline-images)
18138 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18139 (save-excursion
18140 (save-restriction
18141 (widen)
18142 (setq beg (or beg (point-min)) end (or end (point-max)))
18143 (goto-char beg)
18144 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18145 (substring (org-image-file-name-regexp) 0 -2)
18146 "\\)\\]" (if include-linked "" "\\]")))
18147 old file ov img type attrwidth width)
18148 (while (re-search-forward re end t)
18149 (setq old (get-char-property-and-overlay (match-beginning 1)
18150 'org-image-overlay)
18151 file (expand-file-name
18152 (concat (or (match-string 3) "") (match-string 4))))
18153 (when (image-type-available-p 'imagemagick)
18154 (setq attrwidth (if (or (listp org-image-actual-width)
18155 (null org-image-actual-width))
18156 (save-excursion
18157 (save-match-data
18158 (when (re-search-backward
18159 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18160 (save-excursion
18161 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18162 (string-to-number (match-string 1))))))
18163 width (cond ((eq org-image-actual-width t) nil)
18164 ((null org-image-actual-width) attrwidth)
18165 ((numberp org-image-actual-width)
18166 org-image-actual-width)
18167 ((listp org-image-actual-width)
18168 (or attrwidth (car org-image-actual-width))))
18169 type (if width 'imagemagick)))
18170 (when (file-exists-p file)
18171 (if (and (car-safe old) refresh)
18172 (image-refresh (overlay-get (cdr old) 'display))
18173 (setq img (save-match-data (create-image file type nil :width width)))
18174 (when img
18175 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18176 (overlay-put ov 'display img)
18177 (overlay-put ov 'face 'default)
18178 (overlay-put ov 'org-image-overlay t)
18179 (overlay-put ov 'modification-hooks
18180 (list 'org-display-inline-remove-overlay))
18181 (push ov org-inline-image-overlays)))))))))
18183 (define-obsolete-function-alias
18184 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18186 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18187 "Remove inline-display overlay if a corresponding region is modified."
18188 (let ((inhibit-modification-hooks t))
18189 (when (and ov after)
18190 (delete ov org-inline-image-overlays)
18191 (delete-overlay ov))))
18193 (defun org-remove-inline-images ()
18194 "Remove inline display of images."
18195 (interactive)
18196 (mapc 'delete-overlay org-inline-image-overlays)
18197 (setq org-inline-image-overlays nil))
18199 ;;;; Key bindings
18201 ;; Outline functions from `outline-mode-prefix-map'
18202 ;; that can be remapped in Org:
18203 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18204 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18205 (define-key org-mode-map [remap outline-forward-same-level]
18206 'org-forward-heading-same-level)
18207 (define-key org-mode-map [remap outline-backward-same-level]
18208 'org-backward-heading-same-level)
18209 (define-key org-mode-map [remap show-branches]
18210 'org-kill-note-or-show-branches)
18211 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18212 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18213 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18215 ;; Outline functions from `outline-mode-prefix-map' that can not
18216 ;; be remapped in Org:
18218 ;; - the column "key binding" shows whether the Outline function is still
18219 ;; available in Org mode on the same key that it has been bound to in
18220 ;; Outline mode:
18221 ;; - "overridden": key used for a different functionality in Org mode
18222 ;; - else: key still bound to the same Outline function in Org mode
18224 ;; | Outline function | key binding | Org replacement |
18225 ;; |------------------------------------+-------------+-----------------------|
18226 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18227 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18228 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18229 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18230 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18231 ;; | `show-entry' | overridden | no replacement |
18232 ;; | `show-children' | `C-c C-i' | visibility cycling |
18233 ;; | `show-branches' | `C-c C-k' | still same function |
18234 ;; | `show-subtree' | overridden | visibility cycling |
18235 ;; | `show-all' | overridden | no replacement |
18236 ;; | `hide-subtree' | overridden | visibility cycling |
18237 ;; | `hide-body' | overridden | no replacement |
18238 ;; | `hide-entry' | overridden | visibility cycling |
18239 ;; | `hide-leaves' | overridden | no replacement |
18240 ;; | `hide-sublevels' | overridden | no replacement |
18241 ;; | `hide-other' | overridden | no replacement |
18243 ;; Make `C-c C-x' a prefix key
18244 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18246 ;; TAB key with modifiers
18247 (org-defkey org-mode-map "\C-i" 'org-cycle)
18248 (org-defkey org-mode-map [(tab)] 'org-cycle)
18249 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18250 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18251 ;; The following line is necessary under Suse GNU/Linux
18252 (unless (featurep 'xemacs)
18253 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18254 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18255 (define-key org-mode-map [backtab] 'org-shifttab)
18257 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18258 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18259 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18261 ;; Cursor keys with modifiers
18262 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18263 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18264 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18265 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18267 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18268 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18269 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18270 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18272 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18273 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18274 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18275 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18277 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18278 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18279 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18280 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18282 ;; Babel keys
18283 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18284 (mapc (lambda (pair)
18285 (define-key org-babel-map (car pair) (cdr pair)))
18286 org-babel-key-bindings)
18288 ;;; Extra keys for tty access.
18289 ;; We only set them when really needed because otherwise the
18290 ;; menus don't show the simple keys
18292 (when (or org-use-extra-keys
18293 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18294 (not window-system))
18295 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18296 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18297 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18298 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18299 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18300 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18301 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18302 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18303 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18304 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18305 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18306 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18307 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18308 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18309 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18310 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18311 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18312 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18313 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18314 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18315 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18316 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18317 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18318 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18319 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18320 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18321 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18322 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18324 ;; All the other keys
18326 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18327 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18328 (if (boundp 'narrow-map)
18329 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18330 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18331 (if (boundp 'narrow-map)
18332 (org-defkey narrow-map "b" 'org-narrow-to-block)
18333 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18334 (if (boundp 'narrow-map)
18335 (org-defkey narrow-map "e" 'org-narrow-to-element)
18336 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18337 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18338 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18339 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18340 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18341 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18342 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18343 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18344 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18345 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18346 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18347 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18348 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18349 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18350 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18351 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18352 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18353 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18354 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18355 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18356 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18357 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18358 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18359 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18360 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18361 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18362 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18363 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18364 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18365 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18366 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18367 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18368 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18369 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18370 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18371 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18372 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18373 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18374 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18375 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18376 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18377 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18378 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18379 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18380 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18381 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18382 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18383 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18384 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18385 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18386 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18387 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18388 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18389 (org-defkey org-mode-map "\C-c^" 'org-sort)
18390 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18391 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18392 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18393 (org-defkey org-mode-map "\C-m" 'org-return)
18394 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18395 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18396 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18397 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18398 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18399 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18400 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18401 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18402 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18403 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18404 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18405 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18406 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18407 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18408 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18409 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18410 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18411 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18412 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18413 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18414 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18415 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18416 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18418 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18419 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18420 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18422 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18423 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18424 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18425 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18426 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18427 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18428 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18429 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18430 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18431 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18432 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18433 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18434 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18435 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18436 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18437 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18438 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18439 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18440 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18441 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18442 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18443 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18444 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18446 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18447 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18448 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18449 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18450 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18452 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18454 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18456 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18457 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18459 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18462 (when (featurep 'xemacs)
18463 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18466 (defconst org-speed-commands-default
18468 ("Outline Navigation")
18469 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18470 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18471 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18472 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18473 ("u" . (org-speed-move-safe 'outline-up-heading))
18474 ("j" . org-goto)
18475 ("g" . (org-refile t))
18476 ("Outline Visibility")
18477 ("c" . org-cycle)
18478 ("C" . org-shifttab)
18479 (" " . org-display-outline-path)
18480 (":" . org-columns)
18481 ("Outline Structure Editing")
18482 ("U" . org-shiftmetaup)
18483 ("D" . org-shiftmetadown)
18484 ("r" . org-metaright)
18485 ("l" . org-metaleft)
18486 ("R" . org-shiftmetaright)
18487 ("L" . org-shiftmetaleft)
18488 ("i" . (progn (forward-char 1) (call-interactively
18489 'org-insert-heading-respect-content)))
18490 ("^" . org-sort)
18491 ("w" . org-refile)
18492 ("a" . org-archive-subtree-default-with-confirmation)
18493 ("." . org-mark-subtree)
18494 ("#" . org-toggle-comment)
18495 ("Clock Commands")
18496 ("I" . org-clock-in)
18497 ("O" . org-clock-out)
18498 ("Meta Data Editing")
18499 ("t" . org-todo)
18500 ("," . (org-priority))
18501 ("0" . (org-priority ?\ ))
18502 ("1" . (org-priority ?A))
18503 ("2" . (org-priority ?B))
18504 ("3" . (org-priority ?C))
18505 (";" . org-set-tags-command)
18506 ("e" . org-set-effort)
18507 ("E" . org-inc-effort)
18508 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18509 (org-entry-put (point) "APPT_WARNTIME" m)))
18510 ("Agenda Views etc")
18511 ("v" . org-agenda)
18512 ("/" . org-sparse-tree)
18513 ("Misc")
18514 ("o" . org-open-at-point)
18515 ("?" . org-speed-command-help)
18516 ("<" . (org-agenda-set-restriction-lock 'subtree))
18517 (">" . (org-agenda-remove-restriction-lock))
18519 "The default speed commands.")
18521 (defun org-print-speed-command (e)
18522 (if (> (length (car e)) 1)
18523 (progn
18524 (princ "\n")
18525 (princ (car e))
18526 (princ "\n")
18527 (princ (make-string (length (car e)) ?-))
18528 (princ "\n"))
18529 (princ (car e))
18530 (princ " ")
18531 (if (symbolp (cdr e))
18532 (princ (symbol-name (cdr e)))
18533 (prin1 (cdr e)))
18534 (princ "\n")))
18536 (defun org-speed-command-help ()
18537 "Show the available speed commands."
18538 (interactive)
18539 (if (not org-use-speed-commands)
18540 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18541 (with-output-to-temp-buffer "*Help*"
18542 (princ "User-defined Speed commands\n===========================\n")
18543 (mapc 'org-print-speed-command org-speed-commands-user)
18544 (princ "\n")
18545 (princ "Built-in Speed commands\n=======================\n")
18546 (mapc 'org-print-speed-command org-speed-commands-default))
18547 (with-current-buffer "*Help*"
18548 (setq truncate-lines t))))
18550 (defun org-speed-move-safe (cmd)
18551 "Execute CMD, but make sure that the cursor always ends up in a headline.
18552 If not, return to the original position and throw an error."
18553 (interactive)
18554 (let ((pos (point)))
18555 (call-interactively cmd)
18556 (unless (and (bolp) (org-at-heading-p))
18557 (goto-char pos)
18558 (error "Boundary reached while executing %s" cmd))))
18560 (defvar org-self-insert-command-undo-counter 0)
18562 (defvar org-table-auto-blank-field) ; defined in org-table.el
18563 (defvar org-speed-command nil)
18565 (define-obsolete-function-alias
18566 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18568 (defun org-speed-command-activate (keys)
18569 "Hook for activating single-letter speed commands.
18570 `org-speed-commands-default' specifies a minimal command set.
18571 Use `org-speed-commands-user' for further customization."
18572 (when (or (and (bolp) (looking-at org-outline-regexp))
18573 (and (functionp org-use-speed-commands)
18574 (funcall org-use-speed-commands)))
18575 (cdr (assoc keys (append org-speed-commands-user
18576 org-speed-commands-default)))))
18578 (define-obsolete-function-alias
18579 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18581 (defun org-babel-speed-command-activate (keys)
18582 "Hook for activating single-letter code block commands."
18583 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18584 (cdr (assoc keys org-babel-key-bindings))))
18586 (defcustom org-speed-command-hook
18587 '(org-speed-command-default-hook org-babel-speed-command-hook)
18588 "Hook for activating speed commands at strategic locations.
18589 Hook functions are called in sequence until a valid handler is
18590 found.
18592 Each hook takes a single argument, a user-pressed command key
18593 which is also a `self-insert-command' from the global map.
18595 Within the hook, examine the cursor position and the command key
18596 and return nil or a valid handler as appropriate. Handler could
18597 be one of an interactive command, a function, or a form.
18599 Set `org-use-speed-commands' to non-nil value to enable this
18600 hook. The default setting is `org-speed-command-activate'."
18601 :group 'org-structure
18602 :version "24.1"
18603 :type 'hook)
18605 (defun org-self-insert-command (N)
18606 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18607 If the cursor is in a table looking at whitespace, the whitespace is
18608 overwritten, and the table is not marked as requiring realignment."
18609 (interactive "p")
18610 (org-check-before-invisible-edit 'insert)
18611 (cond
18612 ((and org-use-speed-commands
18613 (setq org-speed-command
18614 (run-hook-with-args-until-success
18615 'org-speed-command-hook (this-command-keys))))
18616 (cond
18617 ((commandp org-speed-command)
18618 (setq this-command org-speed-command)
18619 (call-interactively org-speed-command))
18620 ((functionp org-speed-command)
18621 (funcall org-speed-command))
18622 ((and org-speed-command (listp org-speed-command))
18623 (eval org-speed-command))
18624 (t (let (org-use-speed-commands)
18625 (call-interactively 'org-self-insert-command)))))
18626 ((and
18627 (org-table-p)
18628 (progn
18629 ;; check if we blank the field, and if that triggers align
18630 (and (featurep 'org-table) org-table-auto-blank-field
18631 (member last-command
18632 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18633 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18634 ;; got extra space, this field does not determine column width
18635 (let (org-table-may-need-update) (org-table-blank-field))
18636 ;; no extra space, this field may determine column width
18637 (org-table-blank-field)))
18639 (eq N 1)
18640 (looking-at "[^|\n]* |"))
18641 (let (org-table-may-need-update)
18642 (goto-char (1- (match-end 0)))
18643 (backward-delete-char 1)
18644 (goto-char (match-beginning 0))
18645 (self-insert-command N)))
18647 (setq org-table-may-need-update t)
18648 (self-insert-command N)
18649 (org-fix-tags-on-the-fly)
18650 (if org-self-insert-cluster-for-undo
18651 (if (not (eq last-command 'org-self-insert-command))
18652 (setq org-self-insert-command-undo-counter 1)
18653 (if (>= org-self-insert-command-undo-counter 20)
18654 (setq org-self-insert-command-undo-counter 1)
18655 (and (> org-self-insert-command-undo-counter 0)
18656 buffer-undo-list (listp buffer-undo-list)
18657 (not (cadr buffer-undo-list)) ; remove nil entry
18658 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18659 (setq org-self-insert-command-undo-counter
18660 (1+ org-self-insert-command-undo-counter))))))))
18662 (defun org-check-before-invisible-edit (kind)
18663 "Check is editing if kind KIND would be dangerous with invisible text around.
18664 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18665 ;; First, try to get out of here as quickly as possible, to reduce overhead
18666 (if (and org-catch-invisible-edits
18667 (or (not (boundp 'visible-mode)) (not visible-mode))
18668 (or (get-char-property (point) 'invisible)
18669 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18670 ;; OK, we need to take a closer look
18671 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18672 (invisible-before-point (if (bobp) nil (get-char-property
18673 (1- (point)) 'invisible)))
18674 (border-and-ok-direction
18676 ;; Check if we are acting predictably before invisible text
18677 (and invisible-at-point (not invisible-before-point)
18678 (memq kind '(insert delete-backward)))
18679 ;; Check if we are acting predictably after invisible text
18680 ;; This works not well, and I have turned it off. It seems
18681 ;; better to always show and stop after invisible text.
18682 ;; (and (not invisible-at-point) invisible-before-point
18683 ;; (memq kind '(insert delete)))
18685 (when (or (memq invisible-at-point '(outline org-hide-block t))
18686 (memq invisible-before-point '(outline org-hide-block t)))
18687 (if (eq org-catch-invisible-edits 'error)
18688 (error "Editing in invisible areas is prohibited - make visible first"))
18689 (if (and org-custom-properties-overlays
18690 (y-or-n-p "Display invisible properties in this buffer? "))
18691 (org-toggle-custom-properties-visibility)
18692 ;; Make the area visible
18693 (save-excursion
18694 (if invisible-before-point
18695 (goto-char (previous-single-char-property-change
18696 (point) 'invisible)))
18697 (org-cycle))
18698 (cond
18699 ((eq org-catch-invisible-edits 'show)
18700 ;; That's it, we do the edit after showing
18701 (message
18702 "Unfolding invisible region around point before editing")
18703 (sit-for 1))
18704 ((and (eq org-catch-invisible-edits 'smart)
18705 border-and-ok-direction)
18706 (message "Unfolding invisible region around point before editing"))
18708 ;; Don't do the edit, make the user repeat it in full visibility
18709 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18711 (defun org-fix-tags-on-the-fly ()
18712 (when (and (equal (char-after (point-at-bol)) ?*)
18713 (org-at-heading-p))
18714 (org-align-tags-here org-tags-column)))
18716 (defun org-delete-backward-char (N)
18717 "Like `delete-backward-char', insert whitespace at field end in tables.
18718 When deleting backwards, in tables this function will insert whitespace in
18719 front of the next \"|\" separator, to keep the table aligned. The table will
18720 still be marked for re-alignment if the field did fill the entire column,
18721 because, in this case the deletion might narrow the column."
18722 (interactive "p")
18723 (save-match-data
18724 (org-check-before-invisible-edit 'delete-backward)
18725 (if (and (org-table-p)
18726 (eq N 1)
18727 (string-match "|" (buffer-substring (point-at-bol) (point)))
18728 (looking-at ".*?|"))
18729 (let ((pos (point))
18730 (noalign (looking-at "[^|\n\r]* |"))
18731 (c org-table-may-need-update))
18732 (backward-delete-char N)
18733 (if (not overwrite-mode)
18734 (progn
18735 (skip-chars-forward "^|")
18736 (insert " ")
18737 (goto-char (1- pos))))
18738 ;; noalign: if there were two spaces at the end, this field
18739 ;; does not determine the width of the column.
18740 (if noalign (setq org-table-may-need-update c)))
18741 (backward-delete-char N)
18742 (org-fix-tags-on-the-fly))))
18744 (defun org-delete-char (N)
18745 "Like `delete-char', but insert whitespace at field end in tables.
18746 When deleting characters, in tables this function will insert whitespace in
18747 front of the next \"|\" separator, to keep the table aligned. The table will
18748 still be marked for re-alignment if the field did fill the entire column,
18749 because, in this case the deletion might narrow the column."
18750 (interactive "p")
18751 (save-match-data
18752 (org-check-before-invisible-edit 'delete)
18753 (if (and (org-table-p)
18754 (not (bolp))
18755 (not (= (char-after) ?|))
18756 (eq N 1))
18757 (if (looking-at ".*?|")
18758 (let ((pos (point))
18759 (noalign (looking-at "[^|\n\r]* |"))
18760 (c org-table-may-need-update))
18761 (replace-match (concat
18762 (substring (match-string 0) 1 -1)
18763 " |"))
18764 (goto-char pos)
18765 ;; noalign: if there were two spaces at the end, this field
18766 ;; does not determine the width of the column.
18767 (if noalign (setq org-table-may-need-update c)))
18768 (delete-char N))
18769 (delete-char N)
18770 (org-fix-tags-on-the-fly))))
18772 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18773 (put 'org-self-insert-command 'delete-selection t)
18774 (put 'orgtbl-self-insert-command 'delete-selection t)
18775 (put 'org-delete-char 'delete-selection 'supersede)
18776 (put 'org-delete-backward-char 'delete-selection 'supersede)
18777 (put 'org-yank 'delete-selection 'yank)
18779 ;; Make `flyspell-mode' delay after some commands
18780 (put 'org-self-insert-command 'flyspell-delayed t)
18781 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18782 (put 'org-delete-char 'flyspell-delayed t)
18783 (put 'org-delete-backward-char 'flyspell-delayed t)
18785 ;; Make pabbrev-mode expand after org-mode commands
18786 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18787 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18789 ;; How to do this: Measure non-white length of current string
18790 ;; If equal to column width, we should realign.
18792 (defun org-remap (map &rest commands)
18793 "In MAP, remap the functions given in COMMANDS.
18794 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18795 (let (new old)
18796 (while commands
18797 (setq old (pop commands) new (pop commands))
18798 (if (fboundp 'command-remapping)
18799 (org-defkey map (vector 'remap old) new)
18800 (substitute-key-definition old new map global-map)))))
18802 (when (eq org-enable-table-editor 'optimized)
18803 ;; If the user wants maximum table support, we need to hijack
18804 ;; some standard editing functions
18805 (org-remap org-mode-map
18806 'self-insert-command 'org-self-insert-command
18807 'delete-char 'org-delete-char
18808 'delete-backward-char 'org-delete-backward-char)
18809 (org-defkey org-mode-map "|" 'org-force-self-insert))
18811 (defvar org-ctrl-c-ctrl-c-hook nil
18812 "Hook for functions attaching themselves to `C-c C-c'.
18814 This can be used to add additional functionality to the C-c C-c
18815 key which executes context-dependent commands. This hook is run
18816 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18817 run after the last test.
18819 Each function will be called with no arguments. The function
18820 must check if the context is appropriate for it to act. If yes,
18821 it should do its thing and then return a non-nil value. If the
18822 context is wrong, just do nothing and return nil.")
18824 (defvar org-ctrl-c-ctrl-c-final-hook nil
18825 "Hook for functions attaching themselves to `C-c C-c'.
18827 This can be used to add additional functionality to the C-c C-c
18828 key which executes context-dependent commands. This hook is run
18829 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18830 before the first test.
18832 Each function will be called with no arguments. The function
18833 must check if the context is appropriate for it to act. If yes,
18834 it should do its thing and then return a non-nil value. If the
18835 context is wrong, just do nothing and return nil.")
18837 (defvar org-tab-first-hook nil
18838 "Hook for functions to attach themselves to TAB.
18839 See `org-ctrl-c-ctrl-c-hook' for more information.
18840 This hook runs as the first action when TAB is pressed, even before
18841 `org-cycle' messes around with the `outline-regexp' to cater for
18842 inline tasks and plain list item folding.
18843 If any function in this hook returns t, any other actions that
18844 would have been caused by TAB (such as table field motion or visibility
18845 cycling) will not occur.")
18847 (defvar org-tab-after-check-for-table-hook nil
18848 "Hook for functions to attach themselves to TAB.
18849 See `org-ctrl-c-ctrl-c-hook' for more information.
18850 This hook runs after it has been established that the cursor is not in a
18851 table, but before checking if the cursor is in a headline or if global cycling
18852 should be done.
18853 If any function in this hook returns t, not other actions like visibility
18854 cycling will be done.")
18856 (defvar org-tab-after-check-for-cycling-hook nil
18857 "Hook for functions to attach themselves to TAB.
18858 See `org-ctrl-c-ctrl-c-hook' for more information.
18859 This hook runs after it has been established that not table field motion and
18860 not visibility should be done because of current context. This is probably
18861 the place where a package like yasnippets can hook in.")
18863 (defvar org-tab-before-tab-emulation-hook nil
18864 "Hook for functions to attach themselves to TAB.
18865 See `org-ctrl-c-ctrl-c-hook' for more information.
18866 This hook runs after every other options for TAB have been exhausted, but
18867 before indentation and \t insertion takes place.")
18869 (defvar org-metaleft-hook nil
18870 "Hook for functions attaching themselves to `M-left'.
18871 See `org-ctrl-c-ctrl-c-hook' for more information.")
18872 (defvar org-metaright-hook nil
18873 "Hook for functions attaching themselves to `M-right'.
18874 See `org-ctrl-c-ctrl-c-hook' for more information.")
18875 (defvar org-metaup-hook nil
18876 "Hook for functions attaching themselves to `M-up'.
18877 See `org-ctrl-c-ctrl-c-hook' for more information.")
18878 (defvar org-metadown-hook nil
18879 "Hook for functions attaching themselves to `M-down'.
18880 See `org-ctrl-c-ctrl-c-hook' for more information.")
18881 (defvar org-shiftmetaleft-hook nil
18882 "Hook for functions attaching themselves to `M-S-left'.
18883 See `org-ctrl-c-ctrl-c-hook' for more information.")
18884 (defvar org-shiftmetaright-hook nil
18885 "Hook for functions attaching themselves to `M-S-right'.
18886 See `org-ctrl-c-ctrl-c-hook' for more information.")
18887 (defvar org-shiftmetaup-hook nil
18888 "Hook for functions attaching themselves to `M-S-up'.
18889 See `org-ctrl-c-ctrl-c-hook' for more information.")
18890 (defvar org-shiftmetadown-hook nil
18891 "Hook for functions attaching themselves to `M-S-down'.
18892 See `org-ctrl-c-ctrl-c-hook' for more information.")
18893 (defvar org-metareturn-hook nil
18894 "Hook for functions attaching themselves to `M-RET'.
18895 See `org-ctrl-c-ctrl-c-hook' for more information.")
18896 (defvar org-shiftup-hook nil
18897 "Hook for functions attaching themselves to `S-up'.
18898 See `org-ctrl-c-ctrl-c-hook' for more information.")
18899 (defvar org-shiftup-final-hook nil
18900 "Hook for functions attaching themselves to `S-up'.
18901 This one runs after all other options except shift-select have been excluded.
18902 See `org-ctrl-c-ctrl-c-hook' for more information.")
18903 (defvar org-shiftdown-hook nil
18904 "Hook for functions attaching themselves to `S-down'.
18905 See `org-ctrl-c-ctrl-c-hook' for more information.")
18906 (defvar org-shiftdown-final-hook nil
18907 "Hook for functions attaching themselves to `S-down'.
18908 This one runs after all other options except shift-select have been excluded.
18909 See `org-ctrl-c-ctrl-c-hook' for more information.")
18910 (defvar org-shiftleft-hook nil
18911 "Hook for functions attaching themselves to `S-left'.
18912 See `org-ctrl-c-ctrl-c-hook' for more information.")
18913 (defvar org-shiftleft-final-hook nil
18914 "Hook for functions attaching themselves to `S-left'.
18915 This one runs after all other options except shift-select have been excluded.
18916 See `org-ctrl-c-ctrl-c-hook' for more information.")
18917 (defvar org-shiftright-hook nil
18918 "Hook for functions attaching themselves to `S-right'.
18919 See `org-ctrl-c-ctrl-c-hook' for more information.")
18920 (defvar org-shiftright-final-hook nil
18921 "Hook for functions attaching themselves to `S-right'.
18922 This one runs after all other options except shift-select have been excluded.
18923 See `org-ctrl-c-ctrl-c-hook' for more information.")
18925 (defun org-modifier-cursor-error ()
18926 "Throw an error, a modified cursor command was applied in wrong context."
18927 (error "This command is active in special context like tables, headlines or items"))
18929 (defun org-shiftselect-error ()
18930 "Throw an error because Shift-Cursor command was applied in wrong context."
18931 (if (and (boundp 'shift-select-mode) shift-select-mode)
18932 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18933 (error "This command works only in special context like headlines or timestamps")))
18935 (defun org-call-for-shift-select (cmd)
18936 (let ((this-command-keys-shift-translated t))
18937 (call-interactively cmd)))
18939 (defun org-shifttab (&optional arg)
18940 "Global visibility cycling or move to previous table field.
18941 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18942 on context.
18943 See the individual commands for more information."
18944 (interactive "P")
18945 (cond
18946 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18947 ((integerp arg)
18948 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18949 (message "Content view to level: %d" arg)
18950 (org-content (prefix-numeric-value arg2))
18951 (setq org-cycle-global-status 'overview)))
18952 (t (call-interactively 'org-global-cycle))))
18954 (defun org-shiftmetaleft ()
18955 "Promote subtree or delete table column.
18956 Calls `org-promote-subtree', `org-outdent-item-tree', or
18957 `org-table-delete-column', depending on context. See the
18958 individual commands for more information."
18959 (interactive)
18960 (cond
18961 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18962 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18963 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18964 ((if (not (org-region-active-p)) (org-at-item-p)
18965 (save-excursion (goto-char (region-beginning))
18966 (org-at-item-p)))
18967 (call-interactively 'org-outdent-item-tree))
18968 (t (org-modifier-cursor-error))))
18970 (defun org-shiftmetaright ()
18971 "Demote subtree or insert table column.
18972 Calls `org-demote-subtree', `org-indent-item-tree', or
18973 `org-table-insert-column', depending on context. See the
18974 individual commands for more information."
18975 (interactive)
18976 (cond
18977 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18978 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18979 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18980 ((if (not (org-region-active-p)) (org-at-item-p)
18981 (save-excursion (goto-char (region-beginning))
18982 (org-at-item-p)))
18983 (call-interactively 'org-indent-item-tree))
18984 (t (org-modifier-cursor-error))))
18986 (defun org-shiftmetaup (&optional arg)
18987 "Move subtree up or kill table row.
18988 Calls `org-move-subtree-up' or `org-table-kill-row' or
18989 `org-move-item-up' or `org-timestamp-up', depending on context.
18990 See the individual commands for more information."
18991 (interactive "P")
18992 (cond
18993 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18994 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18995 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18996 ((org-at-item-p) (call-interactively 'org-move-item-up))
18997 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18998 (call-interactively 'org-timestamp-up)))
18999 (t (org-modifier-cursor-error))))
19001 (defun org-shiftmetadown (&optional arg)
19002 "Move subtree down or insert table row.
19003 Calls `org-move-subtree-down' or `org-table-insert-row' or
19004 `org-move-item-down' or `org-timestamp-up', depending on context.
19005 See the individual commands for more information."
19006 (interactive "P")
19007 (cond
19008 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19009 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19010 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19011 ((org-at-item-p) (call-interactively 'org-move-item-down))
19012 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19013 (call-interactively 'org-timestamp-down)))
19014 (t (org-modifier-cursor-error))))
19016 (defsubst org-hidden-tree-error ()
19017 (error
19018 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19020 (defun org-metaleft (&optional arg)
19021 "Promote heading or move table column to left.
19022 Calls `org-do-promote' or `org-table-move-column', depending on context.
19023 With no specific context, calls the Emacs default `backward-word'.
19024 See the individual commands for more information."
19025 (interactive "P")
19026 (cond
19027 ((run-hook-with-args-until-success 'org-metaleft-hook))
19028 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19029 ((org-with-limited-levels
19030 (or (org-at-heading-p)
19031 (and (org-region-active-p)
19032 (save-excursion
19033 (goto-char (region-beginning))
19034 (org-at-heading-p)))))
19035 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19036 (call-interactively 'org-do-promote))
19037 ;; At an inline task.
19038 ((org-at-heading-p)
19039 (call-interactively 'org-inlinetask-promote))
19040 ((or (org-at-item-p)
19041 (and (org-region-active-p)
19042 (save-excursion
19043 (goto-char (region-beginning))
19044 (org-at-item-p))))
19045 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19046 (call-interactively 'org-outdent-item))
19047 (t (call-interactively 'backward-word))))
19049 (defun org-metaright (&optional arg)
19050 "Demote a subtree, a list item or move table column to right.
19051 In front of a drawer or a block keyword, indent it correctly.
19052 With no specific context, calls the Emacs default `forward-word'.
19053 See the individual commands for more information."
19054 (interactive "P")
19055 (cond
19056 ((run-hook-with-args-until-success 'org-metaright-hook))
19057 ((org-at-table-p) (call-interactively 'org-table-move-column))
19058 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19059 ((org-at-block-p) (call-interactively 'org-indent-block))
19060 ((org-with-limited-levels
19061 (or (org-at-heading-p)
19062 (and (org-region-active-p)
19063 (save-excursion
19064 (goto-char (region-beginning))
19065 (org-at-heading-p)))))
19066 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19067 (call-interactively 'org-do-demote))
19068 ;; At an inline task.
19069 ((org-at-heading-p)
19070 (call-interactively 'org-inlinetask-demote))
19071 ((or (org-at-item-p)
19072 (and (org-region-active-p)
19073 (save-excursion
19074 (goto-char (region-beginning))
19075 (org-at-item-p))))
19076 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19077 (call-interactively 'org-indent-item))
19078 (t (call-interactively 'forward-word))))
19080 (defun org-check-for-hidden (what)
19081 "Check if there are hidden headlines/items in the current visual line.
19082 WHAT can be either `headlines' or `items'. If the current line is
19083 an outline or item heading and it has a folded subtree below it,
19084 this function returns t, nil otherwise."
19085 (let ((re (cond
19086 ((eq what 'headlines) org-outline-regexp-bol)
19087 ((eq what 'items) (org-item-beginning-re))
19088 (t (error "This should not happen"))))
19089 beg end)
19090 (save-excursion
19091 (catch 'exit
19092 (unless (org-region-active-p)
19093 (setq beg (point-at-bol))
19094 (beginning-of-line 2)
19095 (while (and (not (eobp)) ;; this is like `next-line'
19096 (get-char-property (1- (point)) 'invisible))
19097 (beginning-of-line 2))
19098 (setq end (point))
19099 (goto-char beg)
19100 (goto-char (point-at-eol))
19101 (setq end (max end (point)))
19102 (while (re-search-forward re end t)
19103 (if (get-char-property (match-beginning 0) 'invisible)
19104 (throw 'exit t))))
19105 nil))))
19107 (defun org-metaup (&optional arg)
19108 "Move subtree up or move table row up.
19109 Calls `org-move-subtree-up' or `org-table-move-row' or
19110 `org-move-item-up', depending on context. See the individual commands
19111 for more information."
19112 (interactive "P")
19113 (cond
19114 ((run-hook-with-args-until-success 'org-metaup-hook))
19115 ((org-region-active-p)
19116 (let* ((a (min (region-beginning) (region-end)))
19117 (b (1- (max (region-beginning) (region-end))))
19118 (c (save-excursion (goto-char a)
19119 (move-beginning-of-line 0)))
19120 (d (save-excursion (goto-char a)
19121 (move-end-of-line 0) (point))))
19122 (transpose-regions a b c d)
19123 (goto-char c)))
19124 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19125 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19126 ((org-at-item-p) (call-interactively 'org-move-item-up))
19127 (t (org-drag-element-backward))))
19129 (defun org-metadown (&optional arg)
19130 "Move subtree down or move table row down.
19131 Calls `org-move-subtree-down' or `org-table-move-row' or
19132 `org-move-item-down', depending on context. See the individual
19133 commands for more information."
19134 (interactive "P")
19135 (cond
19136 ((run-hook-with-args-until-success 'org-metadown-hook))
19137 ((org-region-active-p)
19138 (let* ((a (min (region-beginning) (region-end)))
19139 (b (max (region-beginning) (region-end)))
19140 (c (save-excursion (goto-char b)
19141 (move-beginning-of-line 1)))
19142 (d (save-excursion (goto-char b)
19143 (move-end-of-line 1) (1+ (point)))))
19144 (transpose-regions a b c d)
19145 (goto-char d)))
19146 ((org-at-table-p) (call-interactively 'org-table-move-row))
19147 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19148 ((org-at-item-p) (call-interactively 'org-move-item-down))
19149 (t (org-drag-element-forward))))
19151 (defun org-shiftup (&optional arg)
19152 "Increase item in timestamp or increase priority of current headline.
19153 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19154 depending on context. See the individual commands for more information."
19155 (interactive "P")
19156 (cond
19157 ((run-hook-with-args-until-success 'org-shiftup-hook))
19158 ((and org-support-shift-select (org-region-active-p))
19159 (org-call-for-shift-select 'previous-line))
19160 ((org-at-timestamp-p t)
19161 (call-interactively (if org-edit-timestamp-down-means-later
19162 'org-timestamp-down 'org-timestamp-up)))
19163 ((and (not (eq org-support-shift-select 'always))
19164 org-enable-priority-commands
19165 (org-at-heading-p))
19166 (call-interactively 'org-priority-up))
19167 ((and (not org-support-shift-select) (org-at-item-p))
19168 (call-interactively 'org-previous-item))
19169 ((org-clocktable-try-shift 'up arg))
19170 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19171 (org-support-shift-select
19172 (org-call-for-shift-select 'previous-line))
19173 (t (org-shiftselect-error))))
19175 (defun org-shiftdown (&optional arg)
19176 "Decrease item in timestamp or decrease priority of current headline.
19177 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19178 depending on context. See the individual commands for more information."
19179 (interactive "P")
19180 (cond
19181 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19182 ((and org-support-shift-select (org-region-active-p))
19183 (org-call-for-shift-select 'next-line))
19184 ((org-at-timestamp-p t)
19185 (call-interactively (if org-edit-timestamp-down-means-later
19186 'org-timestamp-up 'org-timestamp-down)))
19187 ((and (not (eq org-support-shift-select 'always))
19188 org-enable-priority-commands
19189 (org-at-heading-p))
19190 (call-interactively 'org-priority-down))
19191 ((and (not org-support-shift-select) (org-at-item-p))
19192 (call-interactively 'org-next-item))
19193 ((org-clocktable-try-shift 'down arg))
19194 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19195 (org-support-shift-select
19196 (org-call-for-shift-select 'next-line))
19197 (t (org-shiftselect-error))))
19199 (defun org-shiftright (&optional arg)
19200 "Cycle the thing at point or in the current line, depending on context.
19201 Depending on context, this does one of the following:
19203 - switch a timestamp at point one day into the future
19204 - on a headline, switch to the next TODO keyword.
19205 - on an item, switch entire list to the next bullet type
19206 - on a property line, switch to the next allowed value
19207 - on a clocktable definition line, move time block into the future"
19208 (interactive "P")
19209 (cond
19210 ((run-hook-with-args-until-success 'org-shiftright-hook))
19211 ((and org-support-shift-select (org-region-active-p))
19212 (org-call-for-shift-select 'forward-char))
19213 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19214 ((and (not (eq org-support-shift-select 'always))
19215 (org-at-heading-p))
19216 (let ((org-inhibit-logging
19217 (not org-treat-S-cursor-todo-selection-as-state-change))
19218 (org-inhibit-blocking
19219 (not org-treat-S-cursor-todo-selection-as-state-change)))
19220 (org-call-with-arg 'org-todo 'right)))
19221 ((or (and org-support-shift-select
19222 (not (eq org-support-shift-select 'always))
19223 (org-at-item-bullet-p))
19224 (and (not org-support-shift-select) (org-at-item-p)))
19225 (org-call-with-arg 'org-cycle-list-bullet nil))
19226 ((and (not (eq org-support-shift-select 'always))
19227 (org-at-property-p))
19228 (call-interactively 'org-property-next-allowed-value))
19229 ((org-clocktable-try-shift 'right arg))
19230 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19231 (org-support-shift-select
19232 (org-call-for-shift-select 'forward-char))
19233 (t (org-shiftselect-error))))
19235 (defun org-shiftleft (&optional arg)
19236 "Cycle the thing at point or in the current line, depending on context.
19237 Depending on context, this does one of the following:
19239 - switch a timestamp at point one day into the past
19240 - on a headline, switch to the previous TODO keyword.
19241 - on an item, switch entire list to the previous bullet type
19242 - on a property line, switch to the previous allowed value
19243 - on a clocktable definition line, move time block into the past"
19244 (interactive "P")
19245 (cond
19246 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19247 ((and org-support-shift-select (org-region-active-p))
19248 (org-call-for-shift-select 'backward-char))
19249 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19250 ((and (not (eq org-support-shift-select 'always))
19251 (org-at-heading-p))
19252 (let ((org-inhibit-logging
19253 (not org-treat-S-cursor-todo-selection-as-state-change))
19254 (org-inhibit-blocking
19255 (not org-treat-S-cursor-todo-selection-as-state-change)))
19256 (org-call-with-arg 'org-todo 'left)))
19257 ((or (and org-support-shift-select
19258 (not (eq org-support-shift-select 'always))
19259 (org-at-item-bullet-p))
19260 (and (not org-support-shift-select) (org-at-item-p)))
19261 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19262 ((and (not (eq org-support-shift-select 'always))
19263 (org-at-property-p))
19264 (call-interactively 'org-property-previous-allowed-value))
19265 ((org-clocktable-try-shift 'left arg))
19266 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19267 (org-support-shift-select
19268 (org-call-for-shift-select 'backward-char))
19269 (t (org-shiftselect-error))))
19271 (defun org-shiftcontrolright ()
19272 "Switch to next TODO set."
19273 (interactive)
19274 (cond
19275 ((and org-support-shift-select (org-region-active-p))
19276 (org-call-for-shift-select 'forward-word))
19277 ((and (not (eq org-support-shift-select 'always))
19278 (org-at-heading-p))
19279 (org-call-with-arg 'org-todo 'nextset))
19280 (org-support-shift-select
19281 (org-call-for-shift-select 'forward-word))
19282 (t (org-shiftselect-error))))
19284 (defun org-shiftcontrolleft ()
19285 "Switch to previous TODO set."
19286 (interactive)
19287 (cond
19288 ((and org-support-shift-select (org-region-active-p))
19289 (org-call-for-shift-select 'backward-word))
19290 ((and (not (eq org-support-shift-select 'always))
19291 (org-at-heading-p))
19292 (org-call-with-arg 'org-todo 'previousset))
19293 (org-support-shift-select
19294 (org-call-for-shift-select 'backward-word))
19295 (t (org-shiftselect-error))))
19297 (defun org-shiftcontrolup (&optional n)
19298 "Change timestamps synchronously up in CLOCK log lines.
19299 Optional argument N tells to change by that many units."
19300 (interactive "P")
19301 (cond ((and (not org-support-shift-select)
19302 (org-at-clock-log-p)
19303 (org-at-timestamp-p t))
19304 (org-clock-timestamps-up n))
19305 (t (org-shiftselect-error))))
19307 (defun org-shiftcontroldown (&optional n)
19308 "Change timestamps synchronously down in CLOCK log lines.
19309 Optional argument N tells to change by that many units."
19310 (interactive "P")
19311 (cond ((and (not org-support-shift-select)
19312 (org-at-clock-log-p)
19313 (org-at-timestamp-p t))
19314 (org-clock-timestamps-down n))
19315 (t (org-shiftselect-error))))
19317 (defun org-ctrl-c-ret ()
19318 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19319 (interactive)
19320 (cond
19321 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19322 (t (call-interactively 'org-insert-heading))))
19324 (defun org-find-visible ()
19325 (let ((s (point)))
19326 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19327 (get-char-property s 'invisible)))
19329 (defun org-find-invisible ()
19330 (let ((s (point)))
19331 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19332 (not (get-char-property s 'invisible))))
19335 (defun org-copy-visible (beg end)
19336 "Copy the visible parts of the region."
19337 (interactive "r")
19338 (let (snippets s)
19339 (save-excursion
19340 (save-restriction
19341 (narrow-to-region beg end)
19342 (setq s (goto-char (point-min)))
19343 (while (not (= (point) (point-max)))
19344 (goto-char (org-find-invisible))
19345 (push (buffer-substring s (point)) snippets)
19346 (setq s (goto-char (org-find-visible))))))
19347 (kill-new (apply 'concat (nreverse snippets)))))
19349 (defun org-copy-special ()
19350 "Copy region in table or copy current subtree.
19351 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19352 See the individual commands for more information."
19353 (interactive)
19354 (call-interactively
19355 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19357 (defun org-cut-special ()
19358 "Cut region in table or cut current subtree.
19359 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19360 See the individual commands for more information."
19361 (interactive)
19362 (call-interactively
19363 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19365 (defun org-paste-special (arg)
19366 "Paste rectangular region into table, or past subtree relative to level.
19367 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19368 See the individual commands for more information."
19369 (interactive "P")
19370 (if (org-at-table-p)
19371 (org-table-paste-rectangle)
19372 (org-paste-subtree arg)))
19374 (defsubst org-in-fixed-width-region-p ()
19375 "Is point in a fixed-width region?"
19376 (save-match-data
19377 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19379 (defun org-edit-special (&optional arg)
19380 "Call a special editor for the stuff at point.
19381 When at a table, call the formula editor with `org-table-edit-formulas'.
19382 When in a source code block, call `org-edit-src-code'.
19383 When in a fixed-width region, call `org-edit-fixed-width-region'.
19384 When in an #+include line, visit the included file.
19385 On a link, call `ffap' to visit the link at point.
19386 Otherwise, return a user error."
19387 (interactive)
19388 ;; possibly prep session before editing source
19389 (when (and (org-in-src-block-p) arg)
19390 (let* ((info (org-babel-get-src-block-info))
19391 (lang (nth 0 info))
19392 (params (nth 2 info))
19393 (session (cdr (assoc :session params))))
19394 (when (and info session) ;; we are in a source-code block with a session
19395 (funcall
19396 (intern (concat "org-babel-prep-session:" lang)) session params))))
19397 (cond ;; proceed with `org-edit-special'
19398 ((save-excursion
19399 (beginning-of-line 1)
19400 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19401 (find-file (org-trim (match-string 1))))
19402 ((or (org-at-table-p)
19403 (save-excursion
19404 (beginning-of-line 1)
19405 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19406 (call-interactively 'org-table-edit-formulas))
19407 ((or (org-in-block-p '("src" "example" "latex" "html"))
19408 (org-at-table.el-p))
19409 (org-edit-src-code))
19410 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19411 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19412 (t (user-error "No special environment to edit here"))))
19414 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19415 (defun org-ctrl-c-ctrl-c (&optional arg)
19416 "Set tags in headline, or update according to changed information at point.
19418 This command does many different things, depending on context:
19420 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19421 this is what we do.
19423 - If the cursor is on a statistics cookie, update it.
19425 - If the cursor is in a headline, prompt for tags and insert them
19426 into the current line, aligned to `org-tags-column'. When called
19427 with prefix arg, realign all tags in the current buffer.
19429 - If the cursor is in one of the special #+KEYWORD lines, this
19430 triggers scanning the buffer for these lines and updating the
19431 information.
19433 - If the cursor is inside a table, realign the table. This command
19434 works even if the automatic table editor has been turned off.
19436 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19437 the entire table.
19439 - If the cursor is at a footnote reference or definition, jump to
19440 the corresponding definition or references, respectively.
19442 - If the cursor is a the beginning of a dynamic block, update it.
19444 - If the current buffer is a capture buffer, close note and file it.
19446 - If the cursor is on a <<<target>>>, update radio targets and
19447 corresponding links in this buffer.
19449 - If the cursor is on a numbered item in a plain list, renumber the
19450 ordered list.
19452 - If the cursor is on a checkbox, toggle it.
19454 - If the cursor is on a code block, evaluate it. The variable
19455 `org-confirm-babel-evaluate' can be used to control prompting
19456 before code block evaluation, by default every code block
19457 evaluation requires confirmation. Code block evaluation can be
19458 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19459 (interactive "P")
19460 (let ((org-enable-table-editor t))
19461 (cond
19462 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19463 org-occur-highlights
19464 org-latex-fragment-image-overlays)
19465 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19466 (org-remove-occur-highlights)
19467 (org-remove-latex-fragment-image-overlays)
19468 (message "Temporary highlights/overlays removed from current buffer"))
19469 ((and (local-variable-p 'org-finish-function (current-buffer))
19470 (fboundp org-finish-function))
19471 (funcall org-finish-function))
19472 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19473 ((org-in-regexp org-ts-regexp-both)
19474 (org-timestamp-change 0 'day))
19475 ((or (looking-at org-property-start-re)
19476 (org-at-property-p))
19477 (call-interactively 'org-property-action))
19478 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19479 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19480 (or (org-at-heading-p) (org-at-item-p)))
19481 (call-interactively 'org-update-statistics-cookies))
19482 ((org-at-heading-p) (call-interactively 'org-set-tags))
19483 ((org-at-table.el-p)
19484 (message "Use C-c ' to edit table.el tables"))
19485 ((org-at-table-p)
19486 (org-table-maybe-eval-formula)
19487 (if arg
19488 (call-interactively 'org-table-recalculate)
19489 (org-table-maybe-recalculate-line))
19490 (call-interactively 'org-table-align)
19491 (orgtbl-send-table 'maybe))
19492 ((or (org-footnote-at-reference-p)
19493 (org-footnote-at-definition-p))
19494 (call-interactively 'org-footnote-action))
19495 ((org-at-item-checkbox-p)
19496 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19497 ;; list only if at top item.
19498 (let* ((cbox (match-string 1))
19499 (struct (org-list-struct))
19500 (old-struct (copy-tree struct))
19501 (parents (org-list-parents-alist struct))
19502 (orderedp (org-entry-get nil "ORDERED"))
19503 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19504 block-item)
19505 ;; Use a light version of `org-toggle-checkbox' to avoid
19506 ;; computing list structure twice.
19507 (let ((new-box (cond
19508 ((equal arg '(16)) "[-]")
19509 ((equal arg '(4)) nil)
19510 ((equal "[X]" cbox) "[ ]")
19511 (t "[X]"))))
19512 (if (and firstp arg)
19513 ;; If at first item of sub-list, remove check-box from
19514 ;; every item at the same level.
19515 (mapc
19516 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19517 (org-list-get-all-items
19518 (point-at-bol) struct (org-list-prevs-alist struct)))
19519 (org-list-set-checkbox (point-at-bol) struct new-box)))
19520 ;; Replicate `org-list-write-struct', while grabbing a return
19521 ;; value from `org-list-struct-fix-box'.
19522 (org-list-struct-fix-ind struct parents 2)
19523 (org-list-struct-fix-item-end struct)
19524 (let ((prevs (org-list-prevs-alist struct)))
19525 (org-list-struct-fix-bul struct prevs)
19526 (org-list-struct-fix-ind struct parents)
19527 (setq block-item
19528 (org-list-struct-fix-box struct parents prevs orderedp)))
19529 (org-list-struct-apply-struct struct old-struct)
19530 (org-update-checkbox-count-maybe)
19531 (when block-item
19532 (message
19533 "Checkboxes were removed due to unchecked box at line %d"
19534 (org-current-line block-item)))
19535 (when firstp (org-list-send-list 'maybe))))
19536 ((org-at-item-p)
19537 ;; Cursor at an item: repair list. Do checkbox related actions
19538 ;; only if function was called with an argument. Send list only
19539 ;; if at top item.
19540 (let* ((struct (org-list-struct))
19541 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19542 old-struct)
19543 (when arg
19544 (setq old-struct (copy-tree struct))
19545 (if firstp
19546 ;; If at first item of sub-list, add check-box to every
19547 ;; item at the same level.
19548 (mapc
19549 (lambda (pos)
19550 (unless (org-list-get-checkbox pos struct)
19551 (org-list-set-checkbox pos struct "[ ]")))
19552 (org-list-get-all-items
19553 (point-at-bol) struct (org-list-prevs-alist struct)))
19554 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19555 (org-list-write-struct
19556 struct (org-list-parents-alist struct) old-struct)
19557 (when arg (org-update-checkbox-count-maybe))
19558 (when firstp (org-list-send-list 'maybe))))
19559 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19560 ;; Dynamic block
19561 (beginning-of-line 1)
19562 (save-excursion (org-update-dblock)))
19563 ((save-excursion
19564 (let ((case-fold-search t))
19565 (beginning-of-line 1)
19566 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19567 (cond
19568 ((or (equal (match-string 1) "TBLFM")
19569 (equal (match-string 1) "tblfm"))
19570 ;; Recalculate the table before this line
19571 (save-excursion
19572 (beginning-of-line 1)
19573 (skip-chars-backward " \r\n\t")
19574 (if (org-at-table-p)
19575 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19577 (let ((org-inhibit-startup-visibility-stuff t)
19578 (org-startup-align-all-tables nil))
19579 (when (boundp 'org-table-coordinate-overlays)
19580 (mapc 'delete-overlay org-table-coordinate-overlays)
19581 (setq org-table-coordinate-overlays nil))
19582 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19583 (message "Local setup has been refreshed"))))
19584 ((org-clock-update-time-maybe))
19586 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19587 (error "C-c C-c can do nothing useful at this location"))))))
19589 (defun org-mode-restart ()
19590 "Restart Org-mode, to scan again for special lines.
19591 Also updates the keyword regular expressions."
19592 (interactive)
19593 (org-mode)
19594 (message "Org-mode restarted"))
19596 (defun org-kill-note-or-show-branches ()
19597 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19598 (interactive)
19599 (if (not org-finish-function)
19600 (progn
19601 (hide-subtree)
19602 (call-interactively 'show-branches))
19603 (let ((org-note-abort t))
19604 (funcall org-finish-function))))
19606 (defun org-return (&optional indent)
19607 "Goto next table row or insert a newline.
19608 Calls `org-table-next-row' or `newline', depending on context.
19609 See the individual commands for more information."
19610 (interactive)
19611 (let (org-ts-what)
19612 (cond
19613 ((or (bobp) (org-in-src-block-p))
19614 (if indent (newline-and-indent) (newline)))
19615 ((org-at-table-p)
19616 (org-table-justify-field-maybe)
19617 (call-interactively 'org-table-next-row))
19618 ;; when `newline-and-indent' is called within a list, make sure
19619 ;; text moved stays inside the item.
19620 ((and (org-in-item-p) indent)
19621 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19622 (progn
19623 (save-match-data (newline))
19624 (org-indent-line-to (length (match-string 0))))
19625 (let ((ind (org-get-indentation)))
19626 (newline)
19627 (if (org-looking-back org-list-end-re)
19628 (org-indent-line)
19629 (org-indent-line-to ind)))))
19630 ((and org-return-follows-link
19631 (org-at-timestamp-p t)
19632 (not (eq org-ts-what 'after)))
19633 (org-follow-timestamp-link))
19634 ((and org-return-follows-link
19635 (let ((tprop (get-text-property (point) 'face)))
19636 (or (eq tprop 'org-link)
19637 (and (listp tprop) (memq 'org-link tprop)))))
19638 (call-interactively 'org-open-at-point))
19639 ((and (org-at-heading-p)
19640 (looking-at
19641 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19642 (org-show-entry)
19643 (end-of-line 1)
19644 (newline))
19645 (t (if indent (newline-and-indent) (newline))))))
19647 (defun org-return-indent ()
19648 "Goto next table row or insert a newline and indent.
19649 Calls `org-table-next-row' or `newline-and-indent', depending on
19650 context. See the individual commands for more information."
19651 (interactive)
19652 (org-return t))
19654 (defun org-ctrl-c-star ()
19655 "Compute table, or change heading status of lines.
19656 Calls `org-table-recalculate' or `org-toggle-heading',
19657 depending on context."
19658 (interactive)
19659 (cond
19660 ((org-at-table-p)
19661 (call-interactively 'org-table-recalculate))
19663 ;; Convert all lines in region to list items
19664 (call-interactively 'org-toggle-heading))))
19666 (defun org-ctrl-c-minus ()
19667 "Insert separator line in table or modify bullet status of line.
19668 Also turns a plain line or a region of lines into list items.
19669 Calls `org-table-insert-hline', `org-toggle-item', or
19670 `org-cycle-list-bullet', depending on context."
19671 (interactive)
19672 (cond
19673 ((org-at-table-p)
19674 (call-interactively 'org-table-insert-hline))
19675 ((org-region-active-p)
19676 (call-interactively 'org-toggle-item))
19677 ((org-in-item-p)
19678 (call-interactively 'org-cycle-list-bullet))
19680 (call-interactively 'org-toggle-item))))
19682 (defun org-toggle-item (arg)
19683 "Convert headings or normal lines to items, items to normal lines.
19684 If there is no active region, only the current line is considered.
19686 If the first non blank line in the region is an headline, convert
19687 all headlines to items, shifting text accordingly.
19689 If it is an item, convert all items to normal lines.
19691 If it is normal text, change region into an item. With a prefix
19692 argument ARG, change each line in region into an item."
19693 (interactive "P")
19694 (let ((shift-text
19695 (function
19696 ;; Shift text in current section to IND, from point to END.
19697 ;; The function leaves point to END line.
19698 (lambda (ind end)
19699 (let ((min-i 1000) (end (copy-marker end)))
19700 ;; First determine the minimum indentation (MIN-I) of
19701 ;; the text.
19702 (save-excursion
19703 (catch 'exit
19704 (while (< (point) end)
19705 (let ((i (org-get-indentation)))
19706 (cond
19707 ;; Skip blank lines and inline tasks.
19708 ((looking-at "^[ \t]*$"))
19709 ((looking-at org-outline-regexp-bol))
19710 ;; We can't find less than 0 indentation.
19711 ((zerop i) (throw 'exit (setq min-i 0)))
19712 ((< i min-i) (setq min-i i))))
19713 (forward-line))))
19714 ;; Then indent each line so that a line indented to
19715 ;; MIN-I becomes indented to IND. Ignore blank lines
19716 ;; and inline tasks in the process.
19717 (let ((delta (- ind min-i)))
19718 (while (< (point) end)
19719 (unless (or (looking-at "^[ \t]*$")
19720 (looking-at org-outline-regexp-bol))
19721 (org-indent-line-to (+ (org-get-indentation) delta)))
19722 (forward-line)))))))
19723 (skip-blanks
19724 (function
19725 ;; Return beginning of first non-blank line, starting from
19726 ;; line at POS.
19727 (lambda (pos)
19728 (save-excursion
19729 (goto-char pos)
19730 (skip-chars-forward " \r\t\n")
19731 (point-at-bol)))))
19732 beg end)
19733 ;; Determine boundaries of changes.
19734 (if (org-region-active-p)
19735 (setq beg (funcall skip-blanks (region-beginning))
19736 end (copy-marker (region-end)))
19737 (setq beg (funcall skip-blanks (point-at-bol))
19738 end (copy-marker (point-at-eol))))
19739 ;; Depending on the starting line, choose an action on the text
19740 ;; between BEG and END.
19741 (org-with-limited-levels
19742 (save-excursion
19743 (goto-char beg)
19744 (cond
19745 ;; Case 1. Start at an item: de-itemize. Note that it only
19746 ;; happens when a region is active: `org-ctrl-c-minus'
19747 ;; would call `org-cycle-list-bullet' otherwise.
19748 ((org-at-item-p)
19749 (while (< (point) end)
19750 (when (org-at-item-p)
19751 (skip-chars-forward " \t")
19752 (delete-region (point) (match-end 0)))
19753 (forward-line)))
19754 ;; Case 2. Start at an heading: convert to items.
19755 ((org-at-heading-p)
19756 (let* ((bul (org-list-bullet-string "-"))
19757 (bul-len (length bul))
19758 ;; Indentation of the first heading. It should be
19759 ;; relative to the indentation of its parent, if any.
19760 (start-ind (save-excursion
19761 (cond
19762 ((not org-adapt-indentation) 0)
19763 ((not (outline-previous-heading)) 0)
19764 (t (length (match-string 0))))))
19765 ;; Level of first heading. Further headings will be
19766 ;; compared to it to determine hierarchy in the list.
19767 (ref-level (org-reduced-level (org-outline-level))))
19768 (while (< (point) end)
19769 (let* ((level (org-reduced-level (org-outline-level)))
19770 (delta (max 0 (- level ref-level))))
19771 ;; If current headline is less indented than the first
19772 ;; one, set it as reference, in order to preserve
19773 ;; subtrees.
19774 (when (< level ref-level) (setq ref-level level))
19775 (replace-match bul t t)
19776 (org-indent-line-to (+ start-ind (* delta bul-len)))
19777 ;; Ensure all text down to END (or SECTION-END) belongs
19778 ;; to the newly created item.
19779 (let ((section-end (save-excursion
19780 (or (outline-next-heading) (point)))))
19781 (forward-line)
19782 (funcall shift-text
19783 (+ start-ind (* (1+ delta) bul-len))
19784 (min end section-end)))))))
19785 ;; Case 3. Normal line with ARG: turn each non-item line into
19786 ;; an item.
19787 (arg
19788 (while (< (point) end)
19789 (unless (or (org-at-heading-p) (org-at-item-p))
19790 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19791 (replace-match
19792 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19793 (forward-line)))
19794 ;; Case 4. Normal line without ARG: make the first line of
19795 ;; region an item, and shift indentation of others
19796 ;; lines to set them as item's body.
19797 (t (let* ((bul (org-list-bullet-string "-"))
19798 (bul-len (length bul))
19799 (ref-ind (org-get-indentation)))
19800 (skip-chars-forward " \t")
19801 (insert bul)
19802 (forward-line)
19803 (while (< (point) end)
19804 ;; Ensure that lines less indented than first one
19805 ;; still get included in item body.
19806 (funcall shift-text
19807 (+ ref-ind bul-len)
19808 (min end (save-excursion (or (outline-next-heading)
19809 (point)))))
19810 (forward-line)))))))))
19812 (defun org-toggle-heading (&optional nstars)
19813 "Convert headings to normal text, or items or text to headings.
19814 If there is no active region, only the current line is considered.
19816 With a \\[universal-argument] prefix, convert the whole list at
19817 point into heading.
19819 In a region:
19821 - If the first non blank line is an headline, remove the stars
19822 from all headlines in the region.
19824 - If it is a normal line turn each and every normal line (i.e. not an
19825 heading or an item) in the region into a heading.
19827 - If it is a plain list item, turn all plain list items into headings.
19829 When converting a line into a heading, the number of stars is chosen
19830 such that the lines become children of the current entry. However,
19831 when a prefix argument is given, its value determines the number of
19832 stars to add."
19833 (interactive "P")
19834 (let ((skip-blanks
19835 (function
19836 ;; Return beginning of first non-blank line, starting from
19837 ;; line at POS.
19838 (lambda (pos)
19839 (save-excursion
19840 (goto-char pos)
19841 (while (org-at-comment-p) (forward-line))
19842 (skip-chars-forward " \r\t\n")
19843 (point-at-bol)))))
19844 beg end toggled)
19845 ;; Determine boundaries of changes. If a universal prefix has
19846 ;; been given, put the list in a region. If region ends at a bol,
19847 ;; do not consider the last line to be in the region.
19849 (when (and current-prefix-arg (org-at-item-p))
19850 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19851 (org-mark-element))
19853 (if (org-region-active-p)
19854 (setq beg (funcall skip-blanks (region-beginning))
19855 end (copy-marker (save-excursion
19856 (goto-char (region-end))
19857 (if (bolp) (point) (point-at-eol)))))
19858 (setq beg (funcall skip-blanks (point-at-bol))
19859 end (copy-marker (point-at-eol))))
19860 ;; Ensure inline tasks don't count as headings.
19861 (org-with-limited-levels
19862 (save-excursion
19863 (goto-char beg)
19864 (cond
19865 ;; Case 1. Started at an heading: de-star headings.
19866 ((org-at-heading-p)
19867 (while (< (point) end)
19868 (when (org-at-heading-p t)
19869 (looking-at org-outline-regexp) (replace-match "")
19870 (setq toggled t))
19871 (forward-line)))
19872 ;; Case 2. Started at an item: change items into headlines.
19873 ;; One star will be added by `org-list-to-subtree'.
19874 ((org-at-item-p)
19875 (let* ((stars (make-string
19876 (if nstars
19877 ;; subtract the star that will be added again by
19878 ;; `org-list-to-subtree'
19879 (1- (prefix-numeric-value current-prefix-arg))
19880 (or (org-current-level) 0))
19881 ?*))
19882 (add-stars
19883 (cond (nstars "") ; stars from prefix only
19884 ((equal stars "") "") ; before first heading
19885 (org-odd-levels-only "*") ; inside heading, odd
19886 (t "")))) ; inside heading, oddeven
19887 (while (< (point) end)
19888 (when (org-at-item-p)
19889 ;; Pay attention to cases when region ends before list.
19890 (let* ((struct (org-list-struct))
19891 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19892 (save-restriction
19893 (narrow-to-region (point) list-end)
19894 (insert
19895 (org-list-to-subtree
19896 (org-list-parse-list t)
19897 '(:istart (concat stars add-stars (funcall get-stars depth))
19898 :icount (concat stars add-stars (funcall get-stars depth)))))))
19899 (setq toggled t))
19900 (forward-line))))
19901 ;; Case 3. Started at normal text: make every line an heading,
19902 ;; skipping headlines and items.
19903 (t (let* ((stars (make-string
19904 (if nstars
19905 (prefix-numeric-value current-prefix-arg)
19906 (or (org-current-level) 0))
19907 ?*))
19908 (add-stars
19909 (cond (nstars "") ; stars from prefix only
19910 ((equal stars "") "*") ; before first heading
19911 (org-odd-levels-only "**") ; inside heading, odd
19912 (t "*"))) ; inside heading, oddeven
19913 (rpl (concat stars add-stars " ")))
19914 (while (< (point) end)
19915 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19916 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19917 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19918 (forward-line)))))))
19919 (unless toggled (message "Cannot toggle heading from here"))))
19921 (defun org-meta-return (&optional arg)
19922 "Insert a new heading or wrap a region in a table.
19923 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19924 See the individual commands for more information."
19925 (interactive "P")
19926 (cond
19927 ((run-hook-with-args-until-success 'org-metareturn-hook))
19928 ((or (org-at-drawer-p) (org-at-property-p))
19929 (newline-and-indent))
19930 ((org-at-table-p)
19931 (call-interactively 'org-table-wrap-region))
19932 (t (call-interactively 'org-insert-heading))))
19934 ;;; Menu entries
19936 (defsubst org-in-subtree-not-table-p ()
19937 "Are we in a subtree and not in a table?"
19938 (and (not (org-before-first-heading-p))
19939 (not (org-at-table-p))))
19941 ;; Define the Org-mode menus
19942 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19943 '("Tbl"
19944 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19945 ["Next Field" org-cycle (org-at-table-p)]
19946 ["Previous Field" org-shifttab (org-at-table-p)]
19947 ["Next Row" org-return (org-at-table-p)]
19948 "--"
19949 ["Blank Field" org-table-blank-field (org-at-table-p)]
19950 ["Edit Field" org-table-edit-field (org-at-table-p)]
19951 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19952 "--"
19953 ("Column"
19954 ["Move Column Left" org-metaleft (org-at-table-p)]
19955 ["Move Column Right" org-metaright (org-at-table-p)]
19956 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19957 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19958 ("Row"
19959 ["Move Row Up" org-metaup (org-at-table-p)]
19960 ["Move Row Down" org-metadown (org-at-table-p)]
19961 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19962 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19963 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19964 "--"
19965 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19966 ("Rectangle"
19967 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19968 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19969 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19970 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19971 "--"
19972 ("Calculate"
19973 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19974 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19975 ["Edit Formulas" org-edit-special (org-at-table-p)]
19976 "--"
19977 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19978 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19979 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19980 "--"
19981 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19982 "--"
19983 ["Sum Column/Rectangle" org-table-sum
19984 (or (org-at-table-p) (org-region-active-p))]
19985 ["Which Column?" org-table-current-column (org-at-table-p)])
19986 ["Debug Formulas"
19987 org-table-toggle-formula-debugger
19988 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19989 ["Show Col/Row Numbers"
19990 org-table-toggle-coordinate-overlays
19991 :style toggle
19992 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19993 "--"
19994 ["Create" org-table-create (and (not (org-at-table-p))
19995 org-enable-table-editor)]
19996 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19997 ["Import from File" org-table-import (not (org-at-table-p))]
19998 ["Export to File" org-table-export (org-at-table-p)]
19999 "--"
20000 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20002 (easy-menu-define org-org-menu org-mode-map "Org menu"
20003 '("Org"
20004 ("Show/Hide"
20005 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20006 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20007 ["Sparse Tree..." org-sparse-tree t]
20008 ["Reveal Context" org-reveal t]
20009 ["Show All" show-all t]
20010 "--"
20011 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20012 "--"
20013 ["New Heading" org-insert-heading t]
20014 ("Navigate Headings"
20015 ["Up" outline-up-heading t]
20016 ["Next" outline-next-visible-heading t]
20017 ["Previous" outline-previous-visible-heading t]
20018 ["Next Same Level" outline-forward-same-level t]
20019 ["Previous Same Level" outline-backward-same-level t]
20020 "--"
20021 ["Jump" org-goto t])
20022 ("Edit Structure"
20023 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20024 "--"
20025 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20026 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20027 "--"
20028 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20029 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20030 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20031 "--"
20032 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20033 "--"
20034 ["Copy visible text" org-copy-visible t]
20035 "--"
20036 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20037 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20038 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20039 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20040 "--"
20041 ["Sort Region/Children" org-sort t]
20042 "--"
20043 ["Convert to odd levels" org-convert-to-odd-levels t]
20044 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20045 ("Editing"
20046 ["Emphasis..." org-emphasize t]
20047 ["Edit Source Example" org-edit-special t]
20048 "--"
20049 ["Footnote new/jump" org-footnote-action t]
20050 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20051 ("Archive"
20052 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20053 "--"
20054 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20055 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20056 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20058 "--"
20059 ("Hyperlinks"
20060 ["Store Link (Global)" org-store-link t]
20061 ["Find existing link to here" org-occur-link-in-agenda-files t]
20062 ["Insert Link" org-insert-link t]
20063 ["Follow Link" org-open-at-point t]
20064 "--"
20065 ["Next link" org-next-link t]
20066 ["Previous link" org-previous-link t]
20067 "--"
20068 ["Descriptive Links"
20069 org-toggle-link-display
20070 :style radio
20071 :selected org-descriptive-links
20073 ["Literal Links"
20074 org-toggle-link-display
20075 :style radio
20076 :selected (not org-descriptive-links)])
20077 "--"
20078 ("TODO Lists"
20079 ["TODO/DONE/-" org-todo t]
20080 ("Select keyword"
20081 ["Next keyword" org-shiftright (org-at-heading-p)]
20082 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20083 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20084 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20085 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20086 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20087 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20088 "--"
20089 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20090 :selected org-enforce-todo-dependencies :style toggle :active t]
20091 "Settings for tree at point"
20092 ["Do Children sequentially" org-toggle-ordered-property :style radio
20093 :selected (org-entry-get nil "ORDERED")
20094 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20095 ["Do Children parallel" org-toggle-ordered-property :style radio
20096 :selected (not (org-entry-get nil "ORDERED"))
20097 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20098 "--"
20099 ["Set Priority" org-priority t]
20100 ["Priority Up" org-shiftup t]
20101 ["Priority Down" org-shiftdown t]
20102 "--"
20103 ["Get news from all feeds" org-feed-update-all t]
20104 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20105 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20106 ("TAGS and Properties"
20107 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20108 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20109 "--"
20110 ["Set property" org-set-property (not (org-before-first-heading-p))]
20111 ["Column view of properties" org-columns t]
20112 ["Insert Column View DBlock" org-insert-columns-dblock t])
20113 ("Dates and Scheduling"
20114 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20115 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20116 ("Change Date"
20117 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20118 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20119 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20120 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20121 ["Compute Time Range" org-evaluate-time-range t]
20122 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20123 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20124 "--"
20125 ["Custom time format" org-toggle-time-stamp-overlays
20126 :style radio :selected org-display-custom-times]
20127 "--"
20128 ["Goto Calendar" org-goto-calendar t]
20129 ["Date from Calendar" org-date-from-calendar t]
20130 "--"
20131 ["Start/Restart Timer" org-timer-start t]
20132 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20133 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20134 ["Insert Timer String" org-timer t]
20135 ["Insert Timer Item" org-timer-item t])
20136 ("Logging work"
20137 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20138 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20139 ["Clock out" org-clock-out t]
20140 ["Clock cancel" org-clock-cancel t]
20141 "--"
20142 ["Mark as default task" org-clock-mark-default-task t]
20143 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20144 ["Goto running clock" org-clock-goto t]
20145 "--"
20146 ["Display times" org-clock-display t]
20147 ["Create clock table" org-clock-report t]
20148 "--"
20149 ["Record DONE time"
20150 (progn (setq org-log-done (not org-log-done))
20151 (message "Switching to %s will %s record a timestamp"
20152 (car org-done-keywords)
20153 (if org-log-done "automatically" "not")))
20154 :style toggle :selected org-log-done])
20155 "--"
20156 ["Agenda Command..." org-agenda t]
20157 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20158 ("File List for Agenda")
20159 ("Special views current file"
20160 ["TODO Tree" org-show-todo-tree t]
20161 ["Check Deadlines" org-check-deadlines t]
20162 ["Timeline" org-timeline t]
20163 ["Tags/Property tree" org-match-sparse-tree t])
20164 "--"
20165 ["Export/Publish..." org-export t]
20166 ("LaTeX"
20167 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20168 :selected org-cdlatex-mode]
20169 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20170 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20171 ["Modify math symbol" org-cdlatex-math-modify
20172 (org-inside-LaTeX-fragment-p)]
20173 ["Insert citation" org-reftex-citation t]
20174 "--"
20175 ["Template for BEAMER" (progn (require 'org-beamer)
20176 (org-insert-beamer-options-template)) t])
20177 "--"
20178 ("MobileOrg"
20179 ["Push Files and Views" org-mobile-push t]
20180 ["Get Captured and Flagged" org-mobile-pull t]
20181 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20182 "--"
20183 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20184 "--"
20185 ("Documentation"
20186 ["Show Version" org-version t]
20187 ["Info Documentation" org-info t])
20188 ("Customize"
20189 ["Browse Org Group" org-customize t]
20190 "--"
20191 ["Expand This Menu" org-create-customize-menu
20192 (fboundp 'customize-menu-create)])
20193 ["Send bug report" org-submit-bug-report t]
20194 "--"
20195 ("Refresh/Reload"
20196 ["Refresh setup current buffer" org-mode-restart t]
20197 ["Reload Org (after update)" org-reload t]
20198 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20201 (defun org-info (&optional node)
20202 "Read documentation for Org-mode in the info system.
20203 With optional NODE, go directly to that node."
20204 (interactive)
20205 (info (format "(org)%s" (or node ""))))
20207 ;;;###autoload
20208 (defun org-submit-bug-report ()
20209 "Submit a bug report on Org-mode via mail.
20211 Don't hesitate to report any problems or inaccurate documentation.
20213 If you don't have setup sending mail from (X)Emacs, please copy the
20214 output buffer into your mail program, as it gives us important
20215 information about your Org-mode version and configuration."
20216 (interactive)
20217 (require 'reporter)
20218 (org-load-modules-maybe)
20219 (org-require-autoloaded-modules)
20220 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20221 (reporter-submit-bug-report
20222 "emacs-orgmode@gnu.org"
20223 (org-version nil 'full)
20224 (let (list)
20225 (save-window-excursion
20226 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20227 (delete-other-windows)
20228 (erase-buffer)
20229 (insert "You are about to submit a bug report to the Org-mode mailing list.
20231 We would like to add your full Org-mode and Outline configuration to the
20232 bug report. This greatly simplifies the work of the maintainer and
20233 other experts on the mailing list.
20235 HOWEVER, some variables you have customized may contain private
20236 information. The names of customers, colleagues, or friends, might
20237 appear in the form of file names, tags, todo states, or search strings.
20238 If you answer yes to the prompt, you might want to check and remove
20239 such private information before sending the email.")
20240 (add-text-properties (point-min) (point-max) '(face org-warning))
20241 (when (yes-or-no-p "Include your Org-mode configuration ")
20242 (mapatoms
20243 (lambda (v)
20244 (and (boundp v)
20245 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20246 (or (and (symbol-value v)
20247 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20248 (and
20249 (get v 'custom-type) (get v 'standard-value)
20250 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20251 (push v list)))))
20252 (kill-buffer (get-buffer "*Warn about privacy*"))
20253 list))
20254 nil nil
20255 "Remember to cover the basics, that is, what you expected to happen and
20256 what in fact did happen. You don't know how to make a good report? See
20258 http://orgmode.org/manual/Feedback.html#Feedback
20260 Your bug report will be posted to the Org-mode mailing list.
20261 ------------------------------------------------------------------------")
20262 (save-excursion
20263 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20264 (replace-match "\\1Bug: \\3 [\\2]")))))
20267 (defun org-install-agenda-files-menu ()
20268 (let ((bl (buffer-list)))
20269 (save-excursion
20270 (while bl
20271 (set-buffer (pop bl))
20272 (if (derived-mode-p 'org-mode) (setq bl nil)))
20273 (when (derived-mode-p 'org-mode)
20274 (easy-menu-change
20275 '("Org") "File List for Agenda"
20276 (append
20277 (list
20278 ["Edit File List" (org-edit-agenda-file-list) t]
20279 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20280 ["Remove Current File from List" org-remove-file t]
20281 ["Cycle through agenda files" org-cycle-agenda-files t]
20282 ["Occur in all agenda files" org-occur-in-agenda-files t]
20283 "--")
20284 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20286 ;;;; Documentation
20288 (defun org-require-autoloaded-modules ()
20289 (interactive)
20290 (mapc 'require
20291 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20292 org-docbook org-exp org-html org-icalendar
20293 org-id org-latex
20294 org-publish org-remember org-table
20295 org-timer org-xoxo)))
20297 ;;;###autoload
20298 (defun org-reload (&optional uncompiled)
20299 "Reload all org lisp files.
20300 With prefix arg UNCOMPILED, load the uncompiled versions."
20301 (interactive "P")
20302 (require 'loadhist)
20303 (let* ((org-dir (org-find-library-dir "org"))
20304 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20305 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20306 (remove-re (mapconcat 'identity
20307 (mapcar (lambda (f) (concat "^" f "$"))
20308 (list (if (featurep 'xemacs)
20309 "org-colview"
20310 "org-colview-xemacs")
20311 "org" "org-loaddefs" "org-version"))
20312 "\\|"))
20313 (feats (delete-dups
20314 (mapcar 'file-name-sans-extension
20315 (mapcar 'file-name-nondirectory
20316 (delq nil
20317 (mapcar 'feature-file
20318 features))))))
20319 (lfeat (append
20320 (sort
20321 (setq feats
20322 (delq nil (mapcar
20323 (lambda (f)
20324 (if (and (string-match feature-re f)
20325 (not (string-match remove-re f)))
20326 f nil))
20327 feats)))
20328 'string-lessp)
20329 (list "org-version" "org")))
20330 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20331 load-uncore load-misses)
20332 (setq load-misses
20333 (delq 't
20334 (mapcar (lambda (f)
20335 (or (load (concat org-dir f) 'noerror nil nil 'mustsuffix)
20336 (and (string= org-dir contrib-dir)
20337 (load (concat contrib-dir f) 'noerror nil nil 'mustsuffix))
20338 (and (load (concat (org-find-library-dir f) f) 'noerror nil nil 'mustsuffix)
20339 (add-to-list 'load-uncore f 'append)
20342 lfeat)))
20343 (if load-uncore
20344 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20345 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20346 (if load-misses
20347 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20348 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20349 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20351 ;;;###autoload
20352 (defun org-customize ()
20353 "Call the customize function with org as argument."
20354 (interactive)
20355 (org-load-modules-maybe)
20356 (org-require-autoloaded-modules)
20357 (customize-browse 'org))
20359 (defun org-create-customize-menu ()
20360 "Create a full customization menu for Org-mode, insert it into the menu."
20361 (interactive)
20362 (org-load-modules-maybe)
20363 (org-require-autoloaded-modules)
20364 (if (fboundp 'customize-menu-create)
20365 (progn
20366 (easy-menu-change
20367 '("Org") "Customize"
20368 `(["Browse Org group" org-customize t]
20369 "--"
20370 ,(customize-menu-create 'org)
20371 ["Set" Custom-set t]
20372 ["Save" Custom-save t]
20373 ["Reset to Current" Custom-reset-current t]
20374 ["Reset to Saved" Custom-reset-saved t]
20375 ["Reset to Standard Settings" Custom-reset-standard t]))
20376 (message "\"Org\"-menu now contains full customization menu"))
20377 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20379 ;;;; Miscellaneous stuff
20381 ;;; Generally useful functions
20383 (defun org-get-at-bol (property)
20384 "Get text property PROPERTY at beginning of line."
20385 (get-text-property (point-at-bol) property))
20387 (defun org-find-text-property-in-string (prop s)
20388 "Return the first non-nil value of property PROP in string S."
20389 (or (get-text-property 0 prop s)
20390 (get-text-property (or (next-single-property-change 0 prop s) 0)
20391 prop s)))
20393 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20394 "Display the given MESSAGE as a warning."
20395 (if (fboundp 'display-warning)
20396 (display-warning 'org message
20397 (if (featurep 'xemacs) 'warning :warning))
20398 (let ((buf (get-buffer-create "*Org warnings*")))
20399 (with-current-buffer buf
20400 (goto-char (point-max))
20401 (insert "Warning (Org): " message)
20402 (unless (bolp)
20403 (newline)))
20404 (display-buffer buf)
20405 (sit-for 0))))
20407 (defun org-eval (form)
20408 "Eval FORM and return result."
20409 (condition-case error
20410 (eval form)
20411 (error (format "%%![Error: %s]" error))))
20413 (defun org-in-clocktable-p ()
20414 "Check if the cursor is in a clocktable."
20415 (let ((pos (point)) start)
20416 (save-excursion
20417 (end-of-line 1)
20418 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20419 (setq start (match-beginning 0))
20420 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20421 (>= (match-end 0) pos)
20422 start))))
20424 (defun org-in-commented-line ()
20425 "Is point in a line starting with `#'?"
20426 (equal (char-after (point-at-bol)) ?#))
20428 (defun org-in-indented-comment-line ()
20429 "Is point in a line starting with `#' after some white space?"
20430 (save-excursion
20431 (save-match-data
20432 (goto-char (point-at-bol))
20433 (looking-at "[ \t]*#"))))
20435 (defun org-in-verbatim-emphasis ()
20436 (save-match-data
20437 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20439 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20440 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20441 (if (and marker (marker-buffer marker)
20442 (buffer-live-p (marker-buffer marker)))
20443 (progn
20444 (org-pop-to-buffer-same-window (marker-buffer marker))
20445 (if (or (> marker (point-max)) (< marker (point-min)))
20446 (widen))
20447 (goto-char marker)
20448 (org-show-context 'org-goto))
20449 (if bookmark
20450 (bookmark-jump bookmark)
20451 (error "Cannot find location"))))
20453 (defun org-quote-csv-field (s)
20454 "Quote field for inclusion in CSV material."
20455 (if (string-match "[\",]" s)
20456 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20459 (defun org-force-self-insert (N)
20460 "Needed to enforce self-insert under remapping."
20461 (interactive "p")
20462 (self-insert-command N))
20464 (defun org-string-width (s)
20465 "Compute width of string, ignoring invisible characters.
20466 This ignores character with invisibility property `org-link', and also
20467 characters with property `org-cwidth', because these will become invisible
20468 upon the next fontification round."
20469 (let (b l)
20470 (when (or (eq t buffer-invisibility-spec)
20471 (assq 'org-link buffer-invisibility-spec))
20472 (while (setq b (text-property-any 0 (length s)
20473 'invisible 'org-link s))
20474 (setq s (concat (substring s 0 b)
20475 (substring s (or (next-single-property-change
20476 b 'invisible s) (length s)))))))
20477 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20478 (setq s (concat (substring s 0 b)
20479 (substring s (or (next-single-property-change
20480 b 'org-cwidth s) (length s))))))
20481 (setq l (string-width s) b -1)
20482 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20483 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20486 (defun org-shorten-string (s maxlength)
20487 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20488 If the string is shorter or has length MAXLENGTH, just return the
20489 original string. If it is longer, the functions finds a space in the
20490 string, breaks this string off at that locations and adds three dots
20491 as ellipsis. Including the ellipsis, the string will not be longer
20492 than MAXLENGTH. If finding a good breaking point in the string does
20493 not work, the string is just chopped off in the middle of a word
20494 if necessary."
20495 (if (<= (length s) maxlength)
20497 (let* ((n (max (- maxlength 4) 1))
20498 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20499 (if (string-match re s)
20500 (concat (match-string 1 s) "...")
20501 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20503 (defun org-get-indentation (&optional line)
20504 "Get the indentation of the current line, interpreting tabs.
20505 When LINE is given, assume it represents a line and compute its indentation."
20506 (if line
20507 (if (string-match "^ *" (org-remove-tabs line))
20508 (match-end 0))
20509 (save-excursion
20510 (beginning-of-line 1)
20511 (skip-chars-forward " \t")
20512 (current-column))))
20514 (defun org-get-string-indentation (s)
20515 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20516 (let ((n -1) (i 0) (w tab-width) c)
20517 (catch 'exit
20518 (while (< (setq n (1+ n)) (length s))
20519 (setq c (aref s n))
20520 (cond ((= c ?\ ) (setq i (1+ i)))
20521 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20522 (t (throw 'exit t)))))
20525 (defun org-remove-tabs (s &optional width)
20526 "Replace tabulators in S with spaces.
20527 Assumes that s is a single line, starting in column 0."
20528 (setq width (or width tab-width))
20529 (while (string-match "\t" s)
20530 (setq s (replace-match
20531 (make-string
20532 (- (* width (/ (+ (match-beginning 0) width) width))
20533 (match-beginning 0)) ?\ )
20534 t t s)))
20537 (defun org-fix-indentation (line ind)
20538 "Fix indentation in LINE.
20539 IND is a cons cell with target and minimum indentation.
20540 If the current indentation in LINE is smaller than the minimum,
20541 leave it alone. If it is larger than ind, set it to the target."
20542 (let* ((l (org-remove-tabs line))
20543 (i (org-get-indentation l))
20544 (i1 (car ind)) (i2 (cdr ind)))
20545 (if (>= i i2) (setq l (substring line i2)))
20546 (if (> i1 0)
20547 (concat (make-string i1 ?\ ) l)
20548 l)))
20550 (defun org-remove-indentation (code &optional n)
20551 "Remove the maximum common indentation from the lines in CODE.
20552 N may optionally be the number of spaces to remove."
20553 (with-temp-buffer
20554 (insert code)
20555 (org-do-remove-indentation n)
20556 (buffer-string)))
20558 (defun org-do-remove-indentation (&optional n)
20559 "Remove the maximum common indentation from the buffer."
20560 (untabify (point-min) (point-max))
20561 (let ((min 10000) re)
20562 (if n
20563 (setq min n)
20564 (goto-char (point-min))
20565 (while (re-search-forward "^ *[^ \n]" nil t)
20566 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20567 (unless (or (= min 0) (= min 10000))
20568 (setq re (format "^ \\{%d\\}" min))
20569 (goto-char (point-min))
20570 (while (re-search-forward re nil t)
20571 (replace-match "")
20572 (end-of-line 1))
20573 min)))
20575 (defun org-fill-template (template alist)
20576 "Find each %key of ALIST in TEMPLATE and replace it."
20577 (let ((case-fold-search nil)
20578 entry key value)
20579 (setq alist (sort (copy-sequence alist)
20580 (lambda (a b) (< (length (car a)) (length (car b))))))
20581 (while (setq entry (pop alist))
20582 (setq template
20583 (replace-regexp-in-string
20584 (concat "%" (regexp-quote (car entry)))
20585 (or (cdr entry) "") template t t)))
20586 template))
20588 (defun org-base-buffer (buffer)
20589 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20590 (if (not buffer)
20591 buffer
20592 (or (buffer-base-buffer buffer)
20593 buffer)))
20595 (defun org-trim (s)
20596 "Remove whitespace at beginning and end of string."
20597 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20598 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20601 (defun org-wrap (string &optional width lines)
20602 "Wrap string to either a number of lines, or a width in characters.
20603 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20604 that costs. If there is a word longer than WIDTH, the text is actually
20605 wrapped to the length of that word.
20606 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20607 many lines, whatever width that takes.
20608 The return value is a list of lines, without newlines at the end."
20609 (let* ((words (org-split-string string "[ \t\n]+"))
20610 (maxword (apply 'max (mapcar 'org-string-width words)))
20611 w ll)
20612 (cond (width
20613 (org-do-wrap words (max maxword width)))
20614 (lines
20615 (setq w maxword)
20616 (setq ll (org-do-wrap words maxword))
20617 (if (<= (length ll) lines)
20619 (setq ll words)
20620 (while (> (length ll) lines)
20621 (setq w (1+ w))
20622 (setq ll (org-do-wrap words w)))
20623 ll))
20624 (t (error "Cannot wrap this")))))
20626 (defun org-do-wrap (words width)
20627 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20628 (let (lines line)
20629 (while words
20630 (setq line (pop words))
20631 (while (and words (< (+ (length line) (length (car words))) width))
20632 (setq line (concat line " " (pop words))))
20633 (setq lines (push line lines)))
20634 (nreverse lines)))
20636 (defun org-split-string (string &optional separators)
20637 "Splits STRING into substrings at SEPARATORS.
20638 No empty strings are returned if there are matches at the beginning
20639 and end of string."
20640 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20641 (start 0)
20642 notfirst
20643 (list nil))
20644 (while (and (string-match rexp string
20645 (if (and notfirst
20646 (= start (match-beginning 0))
20647 (< start (length string)))
20648 (1+ start) start))
20649 (< (match-beginning 0) (length string)))
20650 (setq notfirst t)
20651 (or (eq (match-beginning 0) 0)
20652 (and (eq (match-beginning 0) (match-end 0))
20653 (eq (match-beginning 0) start))
20654 (setq list
20655 (cons (substring string start (match-beginning 0))
20656 list)))
20657 (setq start (match-end 0)))
20658 (or (eq start (length string))
20659 (setq list
20660 (cons (substring string start)
20661 list)))
20662 (nreverse list)))
20664 (defun org-quote-vert (s)
20665 "Replace \"|\" with \"\\vert\"."
20666 (while (string-match "|" s)
20667 (setq s (replace-match "\\vert" t t s)))
20670 (defun org-uuidgen-p (s)
20671 "Is S an ID created by UUIDGEN?"
20672 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20674 (defun org-in-src-block-p (&optional inside)
20675 "Whether point is in a code source block.
20676 When INSIDE is non-nil, don't consider we are within a src block
20677 when point is at #+BEGIN_SRC or #+END_SRC."
20678 (let ((case-fold-search t) ov)
20679 (or (and (setq ov (overlays-at (point)))
20680 (memq 'org-block-background
20681 (overlay-properties (car ov))))
20682 (and (not inside)
20683 (save-match-data
20684 (save-excursion
20685 (beginning-of-line)
20686 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20688 (defun org-context ()
20689 "Return a list of contexts of the current cursor position.
20690 If several contexts apply, all are returned.
20691 Each context entry is a list with a symbol naming the context, and
20692 two positions indicating start and end of the context. Possible
20693 contexts are:
20695 :headline anywhere in a headline
20696 :headline-stars on the leading stars in a headline
20697 :todo-keyword on a TODO keyword (including DONE) in a headline
20698 :tags on the TAGS in a headline
20699 :priority on the priority cookie in a headline
20700 :item on the first line of a plain list item
20701 :item-bullet on the bullet/number of a plain list item
20702 :checkbox on the checkbox in a plain list item
20703 :table in an org-mode table
20704 :table-special on a special filed in a table
20705 :table-table in a table.el table
20706 :clocktable in a clocktable
20707 :src-block in a source block
20708 :link on a hyperlink
20709 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20710 :target on a <<target>>
20711 :radio-target on a <<<radio-target>>>
20712 :latex-fragment on a LaTeX fragment
20713 :latex-preview on a LaTeX fragment with overlaid preview image
20715 This function expects the position to be visible because it uses font-lock
20716 faces as a help to recognize the following contexts: :table-special, :link,
20717 and :keyword."
20718 (let* ((f (get-text-property (point) 'face))
20719 (faces (if (listp f) f (list f)))
20720 (case-fold-search t)
20721 (p (point)) clist o)
20722 ;; First the large context
20723 (cond
20724 ((org-at-heading-p t)
20725 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20726 (when (progn
20727 (beginning-of-line 1)
20728 (looking-at org-todo-line-tags-regexp))
20729 (push (org-point-in-group p 1 :headline-stars) clist)
20730 (push (org-point-in-group p 2 :todo-keyword) clist)
20731 (push (org-point-in-group p 4 :tags) clist))
20732 (goto-char p)
20733 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20734 (if (looking-at "\\[#[A-Z0-9]\\]")
20735 (push (org-point-in-group p 0 :priority) clist)))
20737 ((org-at-item-p)
20738 (push (org-point-in-group p 2 :item-bullet) clist)
20739 (push (list :item (point-at-bol)
20740 (save-excursion (org-end-of-item) (point)))
20741 clist)
20742 (and (org-at-item-checkbox-p)
20743 (push (org-point-in-group p 0 :checkbox) clist)))
20745 ((org-at-table-p)
20746 (push (list :table (org-table-begin) (org-table-end)) clist)
20747 (if (memq 'org-formula faces)
20748 (push (list :table-special
20749 (previous-single-property-change p 'face)
20750 (next-single-property-change p 'face)) clist)))
20751 ((org-at-table-p 'any)
20752 (push (list :table-table) clist)))
20753 (goto-char p)
20755 (let ((case-fold-search t))
20756 ;; New the "medium" contexts: clocktables, source blocks
20757 (cond ((org-in-clocktable-p)
20758 (push (list :clocktable
20759 (and (or (looking-at "#\\+BEGIN: clocktable")
20760 (search-backward "#+BEGIN: clocktable" nil t))
20761 (match-beginning 0))
20762 (and (re-search-forward "#\\+END:?" nil t)
20763 (match-end 0))) clist))
20764 ((org-in-src-block-p)
20765 (push (list :src-block
20766 (and (or (looking-at "#\\+BEGIN_SRC")
20767 (search-backward "#+BEGIN_SRC" nil t))
20768 (match-beginning 0))
20769 (and (search-forward "#+END_SRC" nil t)
20770 (match-beginning 0))) clist))))
20771 (goto-char p)
20773 ;; Now the small context
20774 (cond
20775 ((org-at-timestamp-p)
20776 (push (org-point-in-group p 0 :timestamp) clist))
20777 ((memq 'org-link faces)
20778 (push (list :link
20779 (previous-single-property-change p 'face)
20780 (next-single-property-change p 'face)) clist))
20781 ((memq 'org-special-keyword faces)
20782 (push (list :keyword
20783 (previous-single-property-change p 'face)
20784 (next-single-property-change p 'face)) clist))
20785 ((org-at-target-p)
20786 (push (org-point-in-group p 0 :target) clist)
20787 (goto-char (1- (match-beginning 0)))
20788 (if (looking-at org-radio-target-regexp)
20789 (push (org-point-in-group p 0 :radio-target) clist))
20790 (goto-char p))
20791 ((setq o (car (delq nil
20792 (mapcar
20793 (lambda (x)
20794 (if (memq x org-latex-fragment-image-overlays) x))
20795 (overlays-at (point))))))
20796 (push (list :latex-fragment
20797 (overlay-start o) (overlay-end o)) clist)
20798 (push (list :latex-preview
20799 (overlay-start o) (overlay-end o)) clist))
20800 ((org-inside-LaTeX-fragment-p)
20801 ;; FIXME: positions wrong.
20802 (push (list :latex-fragment (point) (point)) clist)))
20804 (setq clist (nreverse (delq nil clist)))
20805 clist))
20807 ;; FIXME: Compare with at-regexp-p Do we need both?
20808 (defun org-in-regexp (re &optional nlines visually)
20809 "Check if point is inside a match of regexp.
20810 Normally only the current line is checked, but you can include NLINES extra
20811 lines both before and after point into the search.
20812 If VISUALLY is set, require that the cursor is not after the match but
20813 really on, so that the block visually is on the match."
20814 (catch 'exit
20815 (let ((pos (point))
20816 (eol (point-at-eol (+ 1 (or nlines 0))))
20817 (inc (if visually 1 0)))
20818 (save-excursion
20819 (beginning-of-line (- 1 (or nlines 0)))
20820 (while (re-search-forward re eol t)
20821 (if (and (<= (match-beginning 0) pos)
20822 (>= (+ inc (match-end 0)) pos))
20823 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20825 (defun org-at-regexp-p (regexp)
20826 "Is point inside a match of REGEXP in the current line?"
20827 (catch 'exit
20828 (save-excursion
20829 (let ((pos (point)) (end (point-at-eol)))
20830 (beginning-of-line 1)
20831 (while (re-search-forward regexp end t)
20832 (if (and (<= (match-beginning 0) pos)
20833 (>= (match-end 0) pos))
20834 (throw 'exit t)))
20835 nil))))
20837 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20838 "Non-nil when point is between matches of START-RE and END-RE.
20840 Also return a non-nil value when point is on one of the matches.
20842 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20843 buffer positions. Default values are the positions of headlines
20844 surrounding the point.
20846 The functions returns a cons cell whose car (resp. cdr) is the
20847 position before START-RE (resp. after END-RE)."
20848 (save-match-data
20849 (let ((pos (point))
20850 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20851 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20852 beg end)
20853 (save-excursion
20854 ;; Point is on a block when on START-RE or if START-RE can be
20855 ;; found before it...
20856 (and (or (org-at-regexp-p start-re)
20857 (re-search-backward start-re limit-up t))
20858 (setq beg (match-beginning 0))
20859 ;; ... and END-RE after it...
20860 (goto-char (match-end 0))
20861 (re-search-forward end-re limit-down t)
20862 (> (setq end (match-end 0)) pos)
20863 ;; ... without another START-RE in-between.
20864 (goto-char (match-beginning 0))
20865 (not (re-search-backward start-re (1+ beg) t))
20866 ;; Return value.
20867 (cons beg end))))))
20869 (defun org-in-block-p (names)
20870 "Non-nil when point belongs to a block whose name belongs to NAMES.
20872 NAMES is a list of strings containing names of blocks.
20874 Return first block name matched, or nil. Beware that in case of
20875 nested blocks, the returned name may not belong to the closest
20876 block from point."
20877 (save-match-data
20878 (catch 'exit
20879 (let ((case-fold-search t)
20880 (lim-up (save-excursion (outline-previous-heading)))
20881 (lim-down (save-excursion (outline-next-heading))))
20882 (mapc (lambda (name)
20883 (let ((n (regexp-quote name)))
20884 (when (org-between-regexps-p
20885 (concat "^[ \t]*#\\+begin_" n)
20886 (concat "^[ \t]*#\\+end_" n)
20887 lim-up lim-down)
20888 (throw 'exit n))))
20889 names))
20890 nil)))
20892 (defun org-occur-in-agenda-files (regexp &optional nlines)
20893 "Call `multi-occur' with buffers for all agenda files."
20894 (interactive "sOrg-files matching: \np")
20895 (let* ((files (org-agenda-files))
20896 (tnames (mapcar 'file-truename files))
20897 (extra org-agenda-text-search-extra-files)
20899 (when (eq (car extra) 'agenda-archives)
20900 (setq extra (cdr extra))
20901 (setq files (org-add-archive-files files)))
20902 (while (setq f (pop extra))
20903 (unless (member (file-truename f) tnames)
20904 (add-to-list 'files f 'append)
20905 (add-to-list 'tnames (file-truename f) 'append)))
20906 (multi-occur
20907 (mapcar (lambda (x)
20908 (with-current-buffer
20909 (or (get-file-buffer x) (find-file-noselect x))
20910 (widen)
20911 (current-buffer)))
20912 files)
20913 regexp)))
20915 (if (boundp 'occur-mode-find-occurrence-hook)
20916 ;; Emacs 23
20917 (add-hook 'occur-mode-find-occurrence-hook
20918 (lambda ()
20919 (when (derived-mode-p 'org-mode)
20920 (org-reveal))))
20921 ;; Emacs 22
20922 (defadvice occur-mode-goto-occurrence
20923 (after org-occur-reveal activate)
20924 (and (derived-mode-p 'org-mode) (org-reveal)))
20925 (defadvice occur-mode-goto-occurrence-other-window
20926 (after org-occur-reveal activate)
20927 (and (derived-mode-p 'org-mode) (org-reveal)))
20928 (defadvice occur-mode-display-occurrence
20929 (after org-occur-reveal activate)
20930 (when (derived-mode-p 'org-mode)
20931 (let ((pos (occur-mode-find-occurrence)))
20932 (with-current-buffer (marker-buffer pos)
20933 (save-excursion
20934 (goto-char pos)
20935 (org-reveal)))))))
20937 (defun org-occur-link-in-agenda-files ()
20938 "Create a link and search for it in the agendas.
20939 The link is not stored in `org-stored-links', it is just created
20940 for the search purpose."
20941 (interactive)
20942 (let ((link (condition-case nil
20943 (org-store-link nil)
20944 (error "Unable to create a link to here"))))
20945 (org-occur-in-agenda-files (regexp-quote link))))
20947 (defun org-uniquify (list)
20948 "Remove duplicate elements from LIST."
20949 (let (res)
20950 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20951 res))
20953 (defun org-delete-all (elts list)
20954 "Remove all elements in ELTS from LIST."
20955 (while elts
20956 (setq list (delete (pop elts) list)))
20957 list)
20959 (defun org-count (cl-item cl-seq)
20960 "Count the number of occurrences of ITEM in SEQ.
20961 Taken from `count' in cl-seq.el with all keyword arguments removed."
20962 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20963 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20964 (while (< cl-start cl-end)
20965 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20966 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20967 (setq cl-start (1+ cl-start)))
20968 cl-count))
20970 (defun org-remove-if (predicate seq)
20971 "Remove everything from SEQ that fulfills PREDICATE."
20972 (let (res e)
20973 (while seq
20974 (setq e (pop seq))
20975 (if (not (funcall predicate e)) (push e res)))
20976 (nreverse res)))
20978 (defun org-remove-if-not (predicate seq)
20979 "Remove everything from SEQ that does not fulfill PREDICATE."
20980 (let (res e)
20981 (while seq
20982 (setq e (pop seq))
20983 (if (funcall predicate e) (push e res)))
20984 (nreverse res)))
20986 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20987 "Reduce two-argument FUNCTION across SEQ.
20988 Taken from `reduce' in cl-seq.el with all keyword arguments but
20989 \":initial-value\" removed."
20990 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20991 (cadr (memq :initial-value cl-keys)))
20992 (cl-seq (pop cl-seq))
20993 (t (funcall cl-func)))))
20994 (while cl-seq
20995 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20996 cl-accum))
20998 (defun org-back-over-empty-lines ()
20999 "Move backwards over whitespace, to the beginning of the first empty line.
21000 Returns the number of empty lines passed."
21001 (let ((pos (point)))
21002 (if (cdr (assoc 'heading org-blank-before-new-entry))
21003 (skip-chars-backward " \t\n\r")
21004 (unless (eobp)
21005 (forward-line -1)))
21006 (beginning-of-line 2)
21007 (goto-char (min (point) pos))
21008 (count-lines (point) pos)))
21010 (defun org-skip-whitespace ()
21011 (skip-chars-forward " \t\n\r"))
21013 (defun org-point-in-group (point group &optional context)
21014 "Check if POINT is in match-group GROUP.
21015 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21016 match. If the match group does not exist or point is not inside it,
21017 return nil."
21018 (and (match-beginning group)
21019 (>= point (match-beginning group))
21020 (<= point (match-end group))
21021 (if context
21022 (list context (match-beginning group) (match-end group))
21023 t)))
21025 (defun org-switch-to-buffer-other-window (&rest args)
21026 "Switch to buffer in a second window on the current frame.
21027 In particular, do not allow pop-up frames.
21028 Returns the newly created buffer."
21029 (org-no-popups
21030 (apply 'switch-to-buffer-other-window args)))
21032 (defun org-combine-plists (&rest plists)
21033 "Create a single property list from all plists in PLISTS.
21034 The process starts by copying the first list, and then setting properties
21035 from the other lists. Settings in the last list are the most significant
21036 ones and overrule settings in the other lists."
21037 (let ((rtn (copy-sequence (pop plists)))
21038 p v ls)
21039 (while plists
21040 (setq ls (pop plists))
21041 (while ls
21042 (setq p (pop ls) v (pop ls))
21043 (setq rtn (plist-put rtn p v))))
21044 rtn))
21046 (defun org-replace-escapes (string table)
21047 "Replace %-escapes in STRING with values in TABLE.
21048 TABLE is an association list with keys like \"%a\" and string values.
21049 The sequences in STRING may contain normal field width and padding information,
21050 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21051 so values can contain further %-escapes if they are define later in TABLE."
21052 (let ((tbl (copy-alist table))
21053 (case-fold-search nil)
21054 (pchg 0)
21055 e re rpl)
21056 (while (setq e (pop tbl))
21057 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21058 (when (and (cdr e) (string-match re (cdr e)))
21059 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21060 (safe "SREF"))
21061 (add-text-properties 0 3 (list 'sref sref) safe)
21062 (setcdr e (replace-match safe t t (cdr e)))))
21063 (while (string-match re string)
21064 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21065 (cdr e)))
21066 (setq string (replace-match rpl t t string))))
21067 (while (setq pchg (next-property-change pchg string))
21068 (let ((sref (get-text-property pchg 'sref string)))
21069 (when (and sref (string-match "SREF" string pchg))
21070 (setq string (replace-match sref t t string)))))
21071 string))
21073 (defun org-sublist (list start end)
21074 "Return a section of LIST, from START to END.
21075 Counting starts at 1."
21076 (let (rtn (c start))
21077 (setq list (nthcdr (1- start) list))
21078 (while (and list (<= c end))
21079 (push (pop list) rtn)
21080 (setq c (1+ c)))
21081 (nreverse rtn)))
21083 (defun org-find-base-buffer-visiting (file)
21084 "Like `find-buffer-visiting' but always return the base buffer and
21085 not an indirect buffer."
21086 (let ((buf (or (get-file-buffer file)
21087 (find-buffer-visiting file))))
21088 (if buf
21089 (or (buffer-base-buffer buf) buf)
21090 nil)))
21092 (defun org-image-file-name-regexp (&optional extensions)
21093 "Return regexp matching the file names of images.
21094 If EXTENSIONS is given, only match these."
21095 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21096 (image-file-name-regexp)
21097 (let ((image-file-name-extensions
21098 (or extensions
21099 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21100 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21101 (concat "\\."
21102 (regexp-opt (nconc (mapcar 'upcase
21103 image-file-name-extensions)
21104 image-file-name-extensions)
21106 "\\'"))))
21108 (defun org-file-image-p (file &optional extensions)
21109 "Return non-nil if FILE is an image."
21110 (save-match-data
21111 (string-match (org-image-file-name-regexp extensions) file)))
21113 (defun org-get-cursor-date (&optional with-time)
21114 "Return the date at cursor in as a time.
21115 This works in the calendar and in the agenda, anywhere else it just
21116 returns the current time.
21117 If WITH-TIME is non-nil, returns the time of the event at point (in
21118 the agenda) or the current time of the day."
21119 (let (date day defd tp tm hod mod)
21120 (when with-time
21121 (setq tp (get-text-property (point) 'time))
21122 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21123 (setq hod (string-to-number (match-string 1 tp))
21124 mod (string-to-number (match-string 2 tp))))
21125 (or tp (setq hod (nth 2 (decode-time (current-time)))
21126 mod (nth 1 (decode-time (current-time))))))
21127 (cond
21128 ((eq major-mode 'calendar-mode)
21129 (setq date (calendar-cursor-to-date)
21130 defd (encode-time 0 (or mod 0) (or hod 0)
21131 (nth 1 date) (nth 0 date) (nth 2 date))))
21132 ((eq major-mode 'org-agenda-mode)
21133 (setq day (get-text-property (point) 'day))
21134 (if day
21135 (setq date (calendar-gregorian-from-absolute day)
21136 defd (encode-time 0 (or mod 0) (or hod 0)
21137 (nth 1 date) (nth 0 date) (nth 2 date))))))
21138 (or defd (current-time))))
21140 (defun org-mark-subtree (&optional up)
21141 "Mark the current subtree.
21142 This puts point at the start of the current subtree, and mark at
21143 the end. If a numeric prefix UP is given, move up into the
21144 hierarchy of headlines by UP levels before marking the subtree."
21145 (interactive "P")
21146 (org-with-limited-levels
21147 (cond ((org-at-heading-p) (beginning-of-line))
21148 ((org-before-first-heading-p) (error "Not in a subtree"))
21149 (t (outline-previous-visible-heading 1))))
21150 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21151 (if (org-called-interactively-p 'any)
21152 (call-interactively 'org-mark-element)
21153 (org-mark-element)))
21156 ;;; Macros
21158 ;; Macros are expanded with `org-macro-replace-all', which relies
21159 ;; internally on `org-macro-expand'.
21161 ;; Default templates for expansion are stored in the buffer-local
21162 ;; variable `org-macro-templates'. This variable is updated by
21163 ;; `org-macro-initialize-templates'.
21165 ;; Along with macros defined through #+MACRO: keyword, default
21166 ;; templates include the following hard-coded macros:
21167 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21168 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21170 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21171 ;; {{{title}}} will also be provided.
21174 (defvar org-macro-templates nil
21175 "Alist containing all macro templates in current buffer.
21176 Associations are in the shape of (NAME . TEMPLATE) where NAME
21177 stands for macro's name and template for its replacement value,
21178 both as strings. This is an internal variable. Do not set it
21179 directly, use instead:
21181 #+MACRO: name template")
21182 (make-variable-buffer-local 'org-macro-templates)
21184 (defun org-macro-expand (macro templates)
21185 "Return expanded MACRO, as a string.
21186 MACRO is an object, obtained, for example, with
21187 `org-element-context'. TEMPLATES is an alist of templates used
21188 for expansion. See `org-macro-templates' for a buffer-local
21189 default value. Return nil if no template was found."
21190 (let ((template
21191 ;; Macro names are case-insensitive.
21192 (cdr (assoc-string (org-element-property :key macro) templates t))))
21193 (when template
21194 (let ((value (replace-regexp-in-string
21195 "\\$[0-9]+"
21196 (lambda (arg)
21197 (or (nth (1- (string-to-number (substring arg 1)))
21198 (org-element-property :args macro))
21199 ;; No argument provided: remove
21200 ;; place-holder.
21201 ""))
21202 template)))
21203 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21204 (when (string-match "\\`(eval\\>" value)
21205 (setq value (eval (read value))))
21206 ;; Return string.
21207 (format "%s" (or value ""))))))
21209 (defun org-macro-replace-all (templates)
21210 "Replace all macros in current buffer by their expansion.
21211 TEMPLATES is an alist of templates used for expansion. See
21212 `org-macro-templates' for a buffer-local default value."
21213 (save-excursion
21214 (goto-char (point-min))
21215 (let (record)
21216 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21217 (let ((object (org-element-context)))
21218 (when (eq (org-element-type object) 'macro)
21219 (let* ((value (org-macro-expand object templates))
21220 (begin (org-element-property :begin object))
21221 (signature (list begin
21222 object
21223 (org-element-property :args object))))
21224 ;; Avoid circular dependencies by checking if the same
21225 ;; macro with the same arguments is expanded at the same
21226 ;; position twice.
21227 (if (member signature record)
21228 (error "Circular macro expansion: %s"
21229 (org-element-property :key object))
21230 (when value
21231 (push signature record)
21232 (delete-region
21233 begin
21234 ;; Preserve white spaces after the macro.
21235 (progn (goto-char (org-element-property :end object))
21236 (skip-chars-backward " \t")
21237 (point)))
21238 ;; Leave point before replacement in case of recursive
21239 ;; expansions.
21240 (save-excursion (insert value)))))))))))
21242 (defun org-macro-initialize-templates ()
21243 "Collect macro templates defined in current buffer.
21244 Templates are stored in buffer-local variable
21245 `org-macro-templates'. In addition to buffer-defined macros, the
21246 function installs the following ones: \"property\",
21247 \"time\". and, if the buffer is associated to a file,
21248 \"input-file\" and \"modification-time\"."
21249 (let ((case-fold-search t)
21250 (set-template
21251 (lambda (cell)
21252 ;; Add CELL to `org-macro-templates' if there's no
21253 ;; association matching its name already. Otherwise,
21254 ;; replace old association with the new one in that
21255 ;; variable.
21256 (let ((old-template (assoc (car cell) org-macro-templates)))
21257 (if old-template (setcdr old-template (cdr cell))
21258 (push cell org-macro-templates))))))
21259 ;; Install buffer-local macros.
21260 (org-with-wide-buffer
21261 (goto-char (point-min))
21262 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21263 (let ((element (org-element-at-point)))
21264 (when (eq (org-element-type element) 'keyword)
21265 (let ((value (org-element-property :value element)))
21266 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21267 (funcall set-template
21268 (cons (match-string 1 value)
21269 (or (match-string 2 value) "")))))))))
21270 ;; Install hard-coded macros.
21271 (mapc (lambda (cell) (funcall set-template cell))
21272 (list
21273 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21274 (cons "time" "(eval (format-time-string \"$1\"))")))
21275 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21276 (when (and visited-file (file-exists-p visited-file))
21277 (mapc (lambda (cell) (funcall set-template cell))
21278 (list
21279 (cons "input-file" (file-name-nondirectory visited-file))
21280 (cons "modification-time"
21281 (format "(eval (format-time-string \"$1\" '%s))"
21282 (prin1-to-string
21283 (nth 5 (file-attributes visited-file)))))))))))
21286 ;;; Indentation
21288 (defun org-indent-line ()
21289 "Indent line depending on context."
21290 (interactive)
21291 (let* ((pos (point))
21292 (itemp (org-at-item-p))
21293 (case-fold-search t)
21294 (org-drawer-regexp (or org-drawer-regexp "\000"))
21295 (inline-task-p (and (featurep 'org-inlinetask)
21296 (org-inlinetask-in-task-p)))
21297 (inline-re (and inline-task-p
21298 (org-inlinetask-outline-regexp)))
21299 column)
21300 (if (and orgstruct-is-++ (eq pos (point)))
21301 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21302 (indent-according-to-mode))
21303 (beginning-of-line 1)
21304 (cond
21305 ;; Headings
21306 ((looking-at org-outline-regexp) (setq column 0))
21307 ;; Included files
21308 ((looking-at "#\\+include:") (setq column 0))
21309 ;; Footnote definition
21310 ((looking-at org-footnote-definition-re) (setq column 0))
21311 ;; Literal examples
21312 ((looking-at "[ \t]*:\\( \\|$\\)")
21313 (setq column (org-get-indentation))) ; do nothing
21314 ;; Lists
21315 ((ignore-errors (goto-char (org-in-item-p)))
21316 (setq column (if itemp
21317 (org-get-indentation)
21318 (org-list-item-body-column (point))))
21319 (goto-char pos))
21320 ;; Drawers
21321 ((and (looking-at "[ \t]*:END:")
21322 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21323 (save-excursion
21324 (goto-char (1- (match-beginning 1)))
21325 (setq column (current-column))))
21326 ;; Special blocks
21327 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21328 (save-excursion
21329 (re-search-backward
21330 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21331 (setq column (org-get-indentation (match-string 0))))
21332 ((and (not (looking-at "[ \t]*#\\+begin_"))
21333 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21334 (save-excursion
21335 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21336 (setq column
21337 (cond ((equal (downcase (match-string 1)) "src")
21338 ;; src blocks: let `org-edit-src-exit' handle them
21339 (org-get-indentation))
21340 ((equal (downcase (match-string 1)) "example")
21341 (max (org-get-indentation)
21342 (org-get-indentation (match-string 0))))
21344 (org-get-indentation (match-string 0))))))
21345 ;; This line has nothing special, look at the previous relevant
21346 ;; line to compute indentation
21348 (beginning-of-line 0)
21349 (while (and (not (bobp))
21350 (not (looking-at org-drawer-regexp))
21351 ;; When point started in an inline task, do not move
21352 ;; above task starting line.
21353 (not (and inline-task-p (looking-at inline-re)))
21354 ;; Skip drawers, blocks, empty lines, verbatim,
21355 ;; comments, tables, footnotes definitions, lists,
21356 ;; inline tasks.
21357 (or (and (looking-at "[ \t]*:END:")
21358 (re-search-backward org-drawer-regexp nil t))
21359 (and (looking-at "[ \t]*#\\+end_")
21360 (re-search-backward "[ \t]*#\\+begin_"nil t))
21361 (looking-at "[ \t]*[\n:#|]")
21362 (looking-at org-footnote-definition-re)
21363 (and (ignore-errors (goto-char (org-in-item-p)))
21364 (goto-char
21365 (org-list-get-top-point (org-list-struct))))
21366 (and (not inline-task-p)
21367 (featurep 'org-inlinetask)
21368 (org-inlinetask-in-task-p)
21369 (or (org-inlinetask-goto-beginning) t))))
21370 (beginning-of-line 0))
21371 (cond
21372 ;; There was an heading above.
21373 ((looking-at "\\*+[ \t]+")
21374 (if (not org-adapt-indentation)
21375 (setq column 0)
21376 (goto-char (match-end 0))
21377 (setq column (current-column))))
21378 ;; A drawer had started and is unfinished
21379 ((looking-at org-drawer-regexp)
21380 (goto-char (1- (match-beginning 1)))
21381 (setq column (current-column)))
21382 ;; Else, nothing noticeable found: get indentation and go on.
21383 (t (setq column (org-get-indentation))))))
21384 ;; Now apply indentation and move cursor accordingly
21385 (goto-char pos)
21386 (if (<= (current-column) (current-indentation))
21387 (org-indent-line-to column)
21388 (save-excursion (org-indent-line-to column)))
21389 ;; Special polishing for properties, see `org-property-format'
21390 (setq column (current-column))
21391 (beginning-of-line 1)
21392 (if (looking-at
21393 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21394 (replace-match (concat (match-string 1)
21395 (format org-property-format
21396 (match-string 2) (match-string 3)))
21397 t t))
21398 (org-move-to-column column))))
21400 (defun org-indent-drawer ()
21401 "Indent the drawer at point."
21402 (interactive)
21403 (let ((p (point))
21404 (e (and (save-excursion (re-search-forward ":END:" nil t))
21405 (match-end 0)))
21406 (folded
21407 (save-excursion
21408 (end-of-line)
21409 (when (overlays-at (point))
21410 (member 'invisible (overlay-properties
21411 (car (overlays-at (point)))))))))
21412 (when folded (org-cycle))
21413 (indent-for-tab-command)
21414 (while (and (move-beginning-of-line 2) (< (point) e))
21415 (indent-for-tab-command))
21416 (goto-char p)
21417 (when folded (org-cycle)))
21418 (message "Drawer at point indented"))
21420 (defun org-indent-block ()
21421 "Indent the block at point."
21422 (interactive)
21423 (let ((p (point))
21424 (case-fold-search t)
21425 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21426 (match-end 0)))
21427 (folded
21428 (save-excursion
21429 (end-of-line)
21430 (when (overlays-at (point))
21431 (member 'invisible (overlay-properties
21432 (car (overlays-at (point)))))))))
21433 (when folded (org-cycle))
21434 (indent-for-tab-command)
21435 (while (and (move-beginning-of-line 2) (< (point) e))
21436 (indent-for-tab-command))
21437 (goto-char p)
21438 (when folded (org-cycle)))
21439 (message "Block at point indented"))
21441 (defun org-indent-region (start end)
21442 "Indent region."
21443 (interactive "r")
21444 (save-excursion
21445 (let ((line-end (org-current-line end)))
21446 (goto-char start)
21447 (while (< (org-current-line) line-end)
21448 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21449 (t (call-interactively 'org-indent-line)))
21450 (move-beginning-of-line 2)))))
21453 ;;; Filling
21455 ;; We use our own fill-paragraph and auto-fill functions.
21457 ;; `org-fill-paragraph' relies on adaptive filling and context
21458 ;; checking. Appropriate `fill-prefix' is computed with
21459 ;; `org-adaptive-fill-function'.
21461 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21462 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21463 ;; `org-adaptive-fill-function' value. Internally,
21464 ;; `org-comment-line-break-function' breaks the line.
21466 ;; `org-setup-filling' installs filling and auto-filling related
21467 ;; variables during `org-mode' initialization.
21469 (defun org-setup-filling ()
21470 (interactive)
21471 ;; Prevent auto-fill from inserting unwanted new items.
21472 (when (boundp 'fill-nobreak-predicate)
21473 (org-set-local
21474 'fill-nobreak-predicate
21475 (org-uniquify
21476 (append fill-nobreak-predicate
21477 '(org-fill-paragraph-separate-nobreak-p
21478 org-fill-line-break-nobreak-p)))))
21479 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21480 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21481 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21482 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21484 (defvar org-element-paragraph-separate) ; org-element.el
21485 (defun org-fill-paragraph-separate-nobreak-p ()
21486 "Non-nil when a line break at point would insert a new item."
21487 (looking-at (substring org-element-paragraph-separate 1)))
21489 (defun org-fill-line-break-nobreak-p ()
21490 "Non-nil when a line break at point would create an Org line break."
21491 (save-excursion
21492 (skip-chars-backward "[ \t]")
21493 (skip-chars-backward "\\\\")
21494 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21496 (declare-function message-in-body-p "message" ())
21497 (defun org-adaptive-fill-function ()
21498 "Compute a fill prefix for the current line.
21499 Return fill prefix, as a string, or nil if current line isn't
21500 meant to be filled."
21501 (org-with-wide-buffer
21502 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21503 ;; FIXME: This is really the job of orgstruct++-mode
21504 (let* ((p (line-beginning-position))
21505 (element (save-excursion (beginning-of-line)
21506 (org-element-at-point)))
21507 (type (org-element-type element))
21508 (post-affiliated (org-element-property :post-affiliated element)))
21509 (unless (and post-affiliated (< p post-affiliated))
21510 (case type
21511 (comment (looking-at "[ \t]*# ?") (match-string 0))
21512 (footnote-definition "")
21513 ((item plain-list)
21514 (make-string (org-list-item-body-column
21515 (or post-affiliated
21516 (org-element-property :begin element)))
21517 ? ))
21518 (paragraph
21519 ;; Fill prefix is usually the same as the current line,
21520 ;; except if the paragraph is at the beginning of an item.
21521 (let ((parent (org-element-property :parent element)))
21522 (cond ((eq (org-element-type parent) 'item)
21523 (make-string (org-list-item-body-column
21524 (org-element-property :begin parent))
21525 ? ))
21526 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21527 (match-string 0))
21528 (t ""))))
21529 (comment-block
21530 ;; Only fill contents if P is within block boundaries.
21531 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21532 (forward-line)
21533 (point)))
21534 (cend (save-excursion
21535 (goto-char (org-element-property :end element))
21536 (skip-chars-backward " \r\t\n")
21537 (line-beginning-position))))
21538 (when (and (>= p cbeg) (< p cend))
21539 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21540 (match-string 0)
21541 ""))))))))))
21543 (declare-function message-goto-body "message" ())
21544 (defvar message-cite-prefix-regexp) ; From message.el
21545 (defvar org-element-all-objects) ; From org-element.el
21546 (defun org-fill-paragraph (&optional justify)
21547 "Fill element at point, when applicable.
21549 This function only applies to comment blocks, comments, example
21550 blocks and paragraphs. Also, as a special case, re-align table
21551 when point is at one.
21553 If JUSTIFY is non-nil (interactively, with prefix argument),
21554 justify as well. If `sentence-end-double-space' is non-nil, then
21555 period followed by one space does not end a sentence, so don't
21556 break a line there. The variable `fill-column' controls the
21557 width for filling.
21559 For convenience, when point is at a plain list, an item or
21560 a footnote definition, try to fill the first paragraph within."
21561 (interactive)
21562 (if (and (derived-mode-p 'message-mode)
21563 (or (not (message-in-body-p))
21564 (save-excursion (move-beginning-of-line 1)
21565 (looking-at message-cite-prefix-regexp))))
21566 ;; First ensure filling is correct in message-mode.
21567 (let ((fill-paragraph-function
21568 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21569 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21570 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21571 (paragraph-separate
21572 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21573 (fill-paragraph nil))
21574 (save-excursion
21575 ;; Move to end of line in order to get the first paragraph
21576 ;; within a plain list or a footnote definition.
21577 (end-of-line)
21578 (let ((element (org-element-at-point)))
21579 ;; First check if point is in a blank line at the beginning of
21580 ;; the buffer. In that case, ignore filling.
21581 (if (< (point) (org-element-property :begin element)) t
21582 (case (org-element-type element)
21583 ;; Use major mode filling function is src blocks.
21584 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21585 ;; Align Org tables, leave table.el tables as-is.
21586 (table-row (org-table-align) t)
21587 (table
21588 (when (eq (org-element-property :type element) 'org)
21589 (org-table-align))
21591 (paragraph
21592 ;; Paragraphs may contain `line-break' type objects.
21593 (let ((beg (max (point-min)
21594 (org-element-property :contents-begin element)))
21595 (end (min (point-max)
21596 (org-element-property :contents-end element))))
21597 ;; Do nothing if point is at an affiliated keyword.
21598 (if (< (point) beg) t
21599 (when (derived-mode-p 'message-mode)
21600 ;; In `message-mode', do not fill following
21601 ;; citation in current paragraph nor text before
21602 ;; message body.
21603 (let ((body-start (save-excursion (message-goto-body))))
21604 (when body-start (setq beg (max body-start beg))))
21605 (when (save-excursion
21606 (re-search-forward
21607 (concat "^" message-cite-prefix-regexp) end t))
21608 (setq end (match-beginning 0))))
21609 ;; Fill paragraph, taking line breaks into
21610 ;; consideration. For that, slice the paragraph
21611 ;; using line breaks as separators, and fill the
21612 ;; parts in reverse order to avoid messing with
21613 ;; markers.
21614 (save-excursion
21615 (goto-char end)
21616 (mapc
21617 (lambda (pos)
21618 (fill-region-as-paragraph pos (point) justify)
21619 (goto-char pos))
21620 ;; Find the list of ending positions for line
21621 ;; breaks in the current paragraph. Add paragraph
21622 ;; beginning to include first slice.
21623 (nreverse
21624 (cons
21626 (org-element-map
21627 (org-element--parse-objects
21628 beg end nil org-element-all-objects)
21629 'line-break
21630 (lambda (lb) (org-element-property :end lb)))))))
21631 t)))
21632 ;; Contents of `comment-block' type elements should be
21633 ;; filled as plain text, but only if point is within block
21634 ;; markers.
21635 (comment-block
21636 (let* ((case-fold-search t)
21637 (beg (save-excursion
21638 (goto-char (org-element-property :begin element))
21639 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21640 (forward-line)
21641 (point)))
21642 (end (save-excursion
21643 (goto-char (org-element-property :end element))
21644 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21645 (line-beginning-position))))
21646 (when (and (>= (point) beg) (< (point) end))
21647 (fill-region-as-paragraph
21648 (save-excursion
21649 (end-of-line)
21650 (re-search-backward "^[ \t]*$" beg 'move)
21651 (line-beginning-position))
21652 (save-excursion
21653 (beginning-of-line)
21654 (re-search-forward "^[ \t]*$" end 'move)
21655 (line-beginning-position))
21656 justify)))
21658 ;; Fill comments.
21659 (comment (fill-comment-paragraph justify))
21660 ;; Ignore every other element.
21661 (otherwise t)))))))
21663 (defun org-auto-fill-function ()
21664 "Auto-fill function."
21665 ;; Check if auto-filling is meaningful.
21666 (let ((fc (current-fill-column)))
21667 (when (and fc (> (current-column) fc))
21668 (let* ((fill-prefix (org-adaptive-fill-function))
21669 ;; Enforce empty fill prefix, if required. Otherwise, it
21670 ;; will be computed again.
21671 (adaptive-fill-mode (not (equal fill-prefix ""))))
21672 (when fill-prefix (do-auto-fill))))))
21674 (defun org-comment-line-break-function (&optional soft)
21675 "Break line at point and indent, continuing comment if within one.
21676 The inserted newline is marked hard if variable
21677 `use-hard-newlines' is true, unless optional argument SOFT is
21678 non-nil."
21679 (if soft (insert-and-inherit ?\n) (newline 1))
21680 (save-excursion (forward-char -1) (delete-horizontal-space))
21681 (delete-horizontal-space)
21682 (indent-to-left-margin)
21683 (insert-before-markers-and-inherit fill-prefix))
21686 ;;; Comments
21688 ;; Org comments syntax is quite complex. It requires the entire line
21689 ;; to be just a comment. Also, even with the right syntax at the
21690 ;; beginning of line, some some elements (i.e. verse-block or
21691 ;; example-block) don't accept comments. Usual Emacs comment commands
21692 ;; cannot cope with those requirements. Therefore, Org replaces them.
21694 ;; Org still relies on `comment-dwim', but cannot trust
21695 ;; `comment-only-p'. So, `comment-region-function' and
21696 ;; `uncomment-region-function' both point
21697 ;; to`org-comment-or-uncomment-region'. Eventually,
21698 ;; `org-insert-comment' takes care of insertion of comments at the
21699 ;; beginning of line.
21701 ;; `org-setup-comments-handling' install comments related variables
21702 ;; during `org-mode' initialization.
21704 (defun org-setup-comments-handling ()
21705 (interactive)
21706 (org-set-local 'comment-use-syntax nil)
21707 (org-set-local 'comment-start "# ")
21708 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21709 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21710 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21711 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21713 (defun org-insert-comment ()
21714 "Insert an empty comment above current line.
21715 If the line is empty, insert comment at its beginning."
21716 (beginning-of-line)
21717 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21718 (org-indent-line)
21719 (insert "# "))
21721 (defvar comment-empty-lines) ; From newcomment.el.
21722 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21723 "Comment or uncomment each non-blank line in the region.
21724 Uncomment each non-blank line between BEG and END if it only
21725 contains commented lines. Otherwise, comment them."
21726 (save-restriction
21727 ;; Restrict region
21728 (narrow-to-region (save-excursion (goto-char beg)
21729 (skip-chars-forward " \r\t\n" end)
21730 (line-beginning-position))
21731 (save-excursion (goto-char end)
21732 (skip-chars-backward " \r\t\n" beg)
21733 (line-end-position)))
21734 (let ((uncommentp
21735 ;; UNCOMMENTP is non-nil when every non blank line between
21736 ;; BEG and END is a comment.
21737 (save-excursion
21738 (goto-char (point-min))
21739 (while (and (not (eobp))
21740 (let ((element (org-element-at-point)))
21741 (and (eq (org-element-type element) 'comment)
21742 (goto-char (min (point-max)
21743 (org-element-property
21744 :end element)))))))
21745 (eobp))))
21746 (if uncommentp
21747 ;; Only blank lines and comments in region: uncomment it.
21748 (save-excursion
21749 (goto-char (point-min))
21750 (while (not (eobp))
21751 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21752 (replace-match "" nil nil nil 1))
21753 (forward-line)))
21754 ;; Comment each line in region.
21755 (let ((min-indent (point-max)))
21756 ;; First find the minimum indentation across all lines.
21757 (save-excursion
21758 (goto-char (point-min))
21759 (while (and (not (eobp)) (not (zerop min-indent)))
21760 (unless (looking-at "[ \t]*$")
21761 (setq min-indent (min min-indent (current-indentation))))
21762 (forward-line)))
21763 ;; Then loop over all lines.
21764 (save-excursion
21765 (goto-char (point-min))
21766 (while (not (eobp))
21767 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21768 (org-move-to-column min-indent t)
21769 (insert comment-start))
21770 (forward-line))))))))
21773 ;;; Other stuff.
21775 (defun org-toggle-fixed-width-section (arg)
21776 "Toggle the fixed-width export.
21777 If there is no active region, the QUOTE keyword at the current headline is
21778 inserted or removed. When present, it causes the text between this headline
21779 and the next to be exported as fixed-width text, and unmodified.
21780 If there is an active region, this command adds or removes a colon as the
21781 first character of this line. If the first character of a line is a colon,
21782 this line is also exported in fixed-width font."
21783 (interactive "P")
21784 (let* ((cc 0)
21785 (regionp (org-region-active-p))
21786 (beg (if regionp (region-beginning) (point)))
21787 (end (if regionp (region-end)))
21788 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21789 (case-fold-search nil)
21790 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21791 off)
21792 (if regionp
21793 (save-excursion
21794 (goto-char beg)
21795 (setq cc (current-column))
21796 (beginning-of-line 1)
21797 (setq off (looking-at re))
21798 (while (> nlines 0)
21799 (setq nlines (1- nlines))
21800 (beginning-of-line 1)
21801 (cond
21802 (arg
21803 (org-move-to-column cc t)
21804 (insert ": \n")
21805 (forward-line -1))
21806 ((and off (looking-at re))
21807 (replace-match "" t t nil 1))
21808 ((not off) (org-move-to-column cc t) (insert ": ")))
21809 (forward-line 1)))
21810 (save-excursion
21811 (org-back-to-heading)
21812 (cond
21813 ((looking-at (format org-heading-keyword-regexp-format
21814 org-quote-string))
21815 (goto-char (match-end 1))
21816 (looking-at (concat " +" org-quote-string))
21817 (replace-match "" t t)
21818 (when (eolp) (insert " ")))
21819 ((looking-at org-outline-regexp)
21820 (goto-char (match-end 0))
21821 (insert org-quote-string " ")))))))
21823 (defun org-reftex-citation ()
21824 "Use reftex-citation to insert a citation into the buffer.
21825 This looks for a line like
21827 #+BIBLIOGRAPHY: foo plain option:-d
21829 and derives from it that foo.bib is the bibliography file relevant
21830 for this document. It then installs the necessary environment for RefTeX
21831 to work in this buffer and calls `reftex-citation' to insert a citation
21832 into the buffer.
21834 Export of such citations to both LaTeX and HTML is handled by the contributed
21835 package org-exp-bibtex by Taru Karttunen."
21836 (interactive)
21837 (let ((reftex-docstruct-symbol 'rds)
21838 (reftex-cite-format "\\cite{%l}")
21839 rds bib)
21840 (save-excursion
21841 (save-restriction
21842 (widen)
21843 (let ((case-fold-search t)
21844 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21845 (if (not (save-excursion
21846 (or (re-search-forward re nil t)
21847 (re-search-backward re nil t))))
21848 (error "No bibliography defined in file")
21849 (setq bib (concat (match-string 1) ".bib")
21850 rds (list (list 'bib bib)))))))
21851 (call-interactively 'reftex-citation)))
21853 ;;;; Functions extending outline functionality
21855 (defun org-beginning-of-line (&optional arg)
21856 "Go to the beginning of the current line. If that is invisible, continue
21857 to a visible line beginning. This makes the function of C-a more intuitive.
21858 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21859 first attempt, and only move to after the tags when the cursor is already
21860 beyond the end of the headline."
21861 (interactive "P")
21862 (let ((pos (point))
21863 (special (if (consp org-special-ctrl-a/e)
21864 (car org-special-ctrl-a/e)
21865 org-special-ctrl-a/e))
21866 refpos)
21867 (if (org-bound-and-true-p visual-line-mode)
21868 (beginning-of-visual-line 1)
21869 (beginning-of-line 1))
21870 (if (and arg (fboundp 'move-beginning-of-line))
21871 (call-interactively 'move-beginning-of-line)
21872 (if (bobp)
21874 (backward-char 1)
21875 (if (org-truely-invisible-p)
21876 (while (and (not (bobp)) (org-truely-invisible-p))
21877 (backward-char 1)
21878 (beginning-of-line 1))
21879 (forward-char 1))))
21880 (when special
21881 (cond
21882 ((and (looking-at org-complex-heading-regexp)
21883 (= (char-after (match-end 1)) ?\ ))
21884 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21885 (point-at-eol)))
21886 (goto-char
21887 (if (eq special t)
21888 (cond ((> pos refpos) refpos)
21889 ((= pos (point)) refpos)
21890 (t (point)))
21891 (cond ((> pos (point)) (point))
21892 ((not (eq last-command this-command)) (point))
21893 (t refpos)))))
21894 ((org-at-item-p)
21895 ;; Being at an item and not looking at an the item means point
21896 ;; was previously moved to beginning of a visual line, which
21897 ;; doesn't contain the item. Therefore, do nothing special,
21898 ;; just stay here.
21899 (when (looking-at org-list-full-item-re)
21900 ;; Set special position at first white space character after
21901 ;; bullet, and check-box, if any.
21902 (let ((after-bullet
21903 (let ((box (match-end 3)))
21904 (if (not box) (match-end 1)
21905 (let ((after (char-after box)))
21906 (if (and after (= after ? )) (1+ box) box))))))
21907 ;; Special case: Move point to special position when
21908 ;; currently after it or at beginning of line.
21909 (if (eq special t)
21910 (when (or (> pos after-bullet) (= (point) pos))
21911 (goto-char after-bullet))
21912 ;; Reversed case: Move point to special position when
21913 ;; point was already at beginning of line and command is
21914 ;; repeated.
21915 (when (and (= (point) pos) (eq last-command this-command))
21916 (goto-char after-bullet))))))))
21917 (org-no-warnings
21918 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21920 (defun org-end-of-line (&optional arg)
21921 "Go to the end of the line.
21922 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21923 tags on the first attempt, and only move to after the tags when
21924 the cursor is already beyond the end of the headline."
21925 (interactive "P")
21926 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21927 org-special-ctrl-a/e))
21928 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21929 'end-of-visual-line)
21930 ((fboundp 'move-end-of-line) 'move-end-of-line)
21931 (t 'end-of-line))))
21932 (if (or (not special) arg) (call-interactively move-fun)
21933 (let* ((element (save-excursion (beginning-of-line)
21934 (org-element-at-point)))
21935 (type (org-element-type element)))
21936 (cond
21937 ((memq type '(headline inlinetask))
21938 (let ((pos (point)))
21939 (beginning-of-line 1)
21940 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21941 (if (eq special t)
21942 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21943 (goto-char (match-beginning 1))
21944 (goto-char (match-end 0)))
21945 (if (or (< pos (match-end 0))
21946 (not (eq this-command last-command)))
21947 (goto-char (match-end 0))
21948 (goto-char (match-beginning 1))))
21949 (call-interactively move-fun))))
21950 ((org-element-property :hiddenp element)
21951 ;; If element is hidden, `move-end-of-line' would put point
21952 ;; after it. Use `end-of-line' to stay on current line.
21953 (call-interactively 'end-of-line))
21954 (t (call-interactively move-fun)))))
21955 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21957 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21958 (define-key org-mode-map "\C-e" 'org-end-of-line)
21960 (defun org-backward-sentence (&optional arg)
21961 "Go to beginning of sentence, or beginning of table field.
21962 This will call `backward-sentence' or `org-table-beginning-of-field',
21963 depending on context."
21964 (interactive "P")
21965 (cond
21966 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21967 (t (call-interactively 'backward-sentence))))
21969 (defun org-forward-sentence (&optional arg)
21970 "Go to end of sentence, or end of table field.
21971 This will call `forward-sentence' or `org-table-end-of-field',
21972 depending on context."
21973 (interactive "P")
21974 (cond
21975 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21976 (t (call-interactively 'forward-sentence))))
21978 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21979 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21981 (defun org-kill-line (&optional arg)
21982 "Kill line, to tags or end of line."
21983 (interactive "P")
21984 (cond
21985 ((or (not org-special-ctrl-k)
21986 (bolp)
21987 (not (org-at-heading-p)))
21988 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21989 org-ctrl-k-protect-subtree)
21990 (if (or (eq org-ctrl-k-protect-subtree 'error)
21991 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21992 (error "C-k aborted - would kill hidden subtree")))
21993 (call-interactively
21994 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21995 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21996 (kill-region (point) (match-beginning 1))
21997 (org-set-tags nil t))
21998 (t (kill-region (point) (point-at-eol)))))
22000 (define-key org-mode-map "\C-k" 'org-kill-line)
22002 (defun org-yank (&optional arg)
22003 "Yank. If the kill is a subtree, treat it specially.
22004 This command will look at the current kill and check if is a single
22005 subtree, or a series of subtrees[1]. If it passes the test, and if the
22006 cursor is at the beginning of a line or after the stars of a currently
22007 empty headline, then the yank is handled specially. How exactly depends
22008 on the value of the following variables, both set by default.
22010 org-yank-folded-subtrees
22011 When set, the subtree(s) will be folded after insertion, but only
22012 if doing so would now swallow text after the yanked text.
22014 org-yank-adjusted-subtrees
22015 When set, the subtree will be promoted or demoted in order to
22016 fit into the local outline tree structure, which means that the level
22017 will be adjusted so that it becomes the smaller one of the two
22018 *visible* surrounding headings.
22020 Any prefix to this command will cause `yank' to be called directly with
22021 no special treatment. In particular, a simple \\[universal-argument] prefix \
22022 will just
22023 plainly yank the text as it is.
22025 \[1] The test checks if the first non-white line is a heading
22026 and if there are no other headings with fewer stars."
22027 (interactive "P")
22028 (org-yank-generic 'yank arg))
22030 (defun org-yank-generic (command arg)
22031 "Perform some yank-like command.
22033 This function implements the behavior described in the `org-yank'
22034 documentation. However, it has been generalized to work for any
22035 interactive command with similar behavior."
22037 ;; pretend to be command COMMAND
22038 (setq this-command command)
22040 (if arg
22041 (call-interactively command)
22043 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22044 (and (org-kill-is-subtree-p)
22045 (or (bolp)
22046 (and (looking-at "[ \t]*$")
22047 (string-match
22048 "\\`\\*+\\'"
22049 (buffer-substring (point-at-bol) (point)))))))
22050 swallowp)
22051 (cond
22052 ((and subtreep org-yank-folded-subtrees)
22053 (let ((beg (point))
22054 end)
22055 (if (and subtreep org-yank-adjusted-subtrees)
22056 (org-paste-subtree nil nil 'for-yank)
22057 (call-interactively command))
22059 (setq end (point))
22060 (goto-char beg)
22061 (when (and (bolp) subtreep
22062 (not (setq swallowp
22063 (org-yank-folding-would-swallow-text beg end))))
22064 (org-with-limited-levels
22065 (or (looking-at org-outline-regexp)
22066 (re-search-forward org-outline-regexp-bol end t))
22067 (while (and (< (point) end) (looking-at org-outline-regexp))
22068 (hide-subtree)
22069 (org-cycle-show-empty-lines 'folded)
22070 (condition-case nil
22071 (outline-forward-same-level 1)
22072 (error (goto-char end))))))
22073 (when swallowp
22074 (message
22075 "Inserted text not folded because that would swallow text"))
22077 (goto-char end)
22078 (skip-chars-forward " \t\n\r")
22079 (beginning-of-line 1)
22080 (push-mark beg 'nomsg)))
22081 ((and subtreep org-yank-adjusted-subtrees)
22082 (let ((beg (point-at-bol)))
22083 (org-paste-subtree nil nil 'for-yank)
22084 (push-mark beg 'nomsg)))
22086 (call-interactively command))))))
22088 (defun org-yank-folding-would-swallow-text (beg end)
22089 "Would hide-subtree at BEG swallow any text after END?"
22090 (let (level)
22091 (org-with-limited-levels
22092 (save-excursion
22093 (goto-char beg)
22094 (when (or (looking-at org-outline-regexp)
22095 (re-search-forward org-outline-regexp-bol end t))
22096 (setq level (org-outline-level)))
22097 (goto-char end)
22098 (skip-chars-forward " \t\r\n\v\f")
22099 (if (or (eobp)
22100 (and (bolp) (looking-at org-outline-regexp)
22101 (<= (org-outline-level) level)))
22102 nil ; Nothing would be swallowed
22103 t))))) ; something would swallow
22105 (define-key org-mode-map "\C-y" 'org-yank)
22107 (defun org-truely-invisible-p ()
22108 "Check if point is at a character currently not visible.
22109 This version does not only check the character property, but also
22110 `visible-mode'."
22111 ;; Early versions of noutline don't have `outline-invisible-p'.
22112 (if (org-bound-and-true-p visible-mode)
22114 (outline-invisible-p)))
22116 (defun org-invisible-p2 ()
22117 "Check if point is at a character currently not visible."
22118 (save-excursion
22119 (if (and (eolp) (not (bobp))) (backward-char 1))
22120 ;; Early versions of noutline don't have `outline-invisible-p'.
22121 (outline-invisible-p)))
22123 (defun org-back-to-heading (&optional invisible-ok)
22124 "Call `outline-back-to-heading', but provide a better error message."
22125 (condition-case nil
22126 (outline-back-to-heading invisible-ok)
22127 (error (error "Before first headline at position %d in buffer %s"
22128 (point) (current-buffer)))))
22130 (defun org-before-first-heading-p ()
22131 "Before first heading?"
22132 (save-excursion
22133 (end-of-line)
22134 (null (re-search-backward org-outline-regexp-bol nil t))))
22136 (defun org-at-heading-p (&optional ignored)
22137 (outline-on-heading-p t))
22138 ;; Compatibility alias with Org versions < 7.8.03
22139 (defalias 'org-on-heading-p 'org-at-heading-p)
22141 (defun org-at-comment-p nil
22142 "Is cursor in a line starting with a # character?"
22143 (save-excursion
22144 (beginning-of-line)
22145 (looking-at "^#")))
22147 (defun org-at-drawer-p nil
22148 "Is cursor at a drawer keyword?"
22149 (save-excursion
22150 (move-beginning-of-line 1)
22151 (looking-at org-drawer-regexp)))
22153 (defun org-at-block-p nil
22154 "Is cursor at a block keyword?"
22155 (save-excursion
22156 (move-beginning-of-line 1)
22157 (looking-at org-block-regexp)))
22159 (defun org-point-at-end-of-empty-headline ()
22160 "If point is at the end of an empty headline, return t, else nil.
22161 If the heading only contains a TODO keyword, it is still still considered
22162 empty."
22163 (and (looking-at "[ \t]*$")
22164 (when org-todo-line-regexp
22165 (save-excursion
22166 (beginning-of-line 1)
22167 (let ((case-fold-search nil))
22168 (looking-at org-todo-line-regexp)
22169 (string= (match-string 3) ""))))))
22171 (defun org-at-heading-or-item-p ()
22172 (or (org-at-heading-p) (org-at-item-p)))
22174 (defun org-at-target-p ()
22175 (or (org-in-regexp org-radio-target-regexp)
22176 (org-in-regexp org-target-regexp)))
22177 ;; Compatibility alias with Org versions < 7.8.03
22178 (defalias 'org-on-target-p 'org-at-target-p)
22180 (defun org-up-heading-all (arg)
22181 "Move to the heading line of which the present line is a subheading.
22182 This function considers both visible and invisible heading lines.
22183 With argument, move up ARG levels."
22184 (if (fboundp 'outline-up-heading-all)
22185 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22186 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22188 (defun org-up-heading-safe ()
22189 "Move to the heading line of which the present line is a subheading.
22190 This version will not throw an error. It will return the level of the
22191 headline found, or nil if no higher level is found.
22193 Also, this function will be a lot faster than `outline-up-heading',
22194 because it relies on stars being the outline starters. This can really
22195 make a significant difference in outlines with very many siblings."
22196 (let (start-level re)
22197 (org-back-to-heading t)
22198 (setq start-level (funcall outline-level))
22199 (if (equal start-level 1)
22201 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22202 (if (re-search-backward re nil t)
22203 (funcall outline-level)))))
22205 (defun org-first-sibling-p ()
22206 "Is this heading the first child of its parents?"
22207 (interactive)
22208 (let ((re org-outline-regexp-bol)
22209 level l)
22210 (unless (org-at-heading-p t)
22211 (error "Not at a heading"))
22212 (setq level (funcall outline-level))
22213 (save-excursion
22214 (if (not (re-search-backward re nil t))
22216 (setq l (funcall outline-level))
22217 (< l level)))))
22219 (defun org-goto-sibling (&optional previous)
22220 "Goto the next sibling, even if it is invisible.
22221 When PREVIOUS is set, go to the previous sibling instead. Returns t
22222 when a sibling was found. When none is found, return nil and don't
22223 move point."
22224 (let ((fun (if previous 're-search-backward 're-search-forward))
22225 (pos (point))
22226 (re org-outline-regexp-bol)
22227 level l)
22228 (when (condition-case nil (org-back-to-heading t) (error nil))
22229 (setq level (funcall outline-level))
22230 (catch 'exit
22231 (or previous (forward-char 1))
22232 (while (funcall fun re nil t)
22233 (setq l (funcall outline-level))
22234 (when (< l level) (goto-char pos) (throw 'exit nil))
22235 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22236 (goto-char pos)
22237 nil))))
22239 (defun org-show-siblings ()
22240 "Show all siblings of the current headline."
22241 (save-excursion
22242 (while (org-goto-sibling) (org-flag-heading nil)))
22243 (save-excursion
22244 (while (org-goto-sibling 'previous)
22245 (org-flag-heading nil))))
22247 (defun org-goto-first-child ()
22248 "Goto the first child, even if it is invisible.
22249 Return t when a child was found. Otherwise don't move point and
22250 return nil."
22251 (let (level (pos (point)) (re org-outline-regexp-bol))
22252 (when (condition-case nil (org-back-to-heading t) (error nil))
22253 (setq level (outline-level))
22254 (forward-char 1)
22255 (if (and (re-search-forward re nil t) (> (outline-level) level))
22256 (progn (goto-char (match-beginning 0)) t)
22257 (goto-char pos) nil))))
22259 (defun org-show-hidden-entry ()
22260 "Show an entry where even the heading is hidden."
22261 (save-excursion
22262 (org-show-entry)))
22264 (defun org-flag-heading (flag &optional entry)
22265 "Flag the current heading. FLAG non-nil means make invisible.
22266 When ENTRY is non-nil, show the entire entry."
22267 (save-excursion
22268 (org-back-to-heading t)
22269 ;; Check if we should show the entire entry
22270 (if entry
22271 (progn
22272 (org-show-entry)
22273 (save-excursion
22274 (and (outline-next-heading)
22275 (org-flag-heading nil))))
22276 (outline-flag-region (max (point-min) (1- (point)))
22277 (save-excursion (outline-end-of-heading) (point))
22278 flag))))
22280 (defun org-get-next-sibling ()
22281 "Move to next heading of the same level, and return point.
22282 If there is no such heading, return nil.
22283 This is like outline-next-sibling, but invisible headings are ok."
22284 (let ((level (funcall outline-level)))
22285 (outline-next-heading)
22286 (while (and (not (eobp)) (> (funcall outline-level) level))
22287 (outline-next-heading))
22288 (if (or (eobp) (< (funcall outline-level) level))
22290 (point))))
22292 (defun org-get-last-sibling ()
22293 "Move to previous heading of the same level, and return point.
22294 If there is no such heading, return nil."
22295 (let ((opoint (point))
22296 (level (funcall outline-level)))
22297 (outline-previous-heading)
22298 (when (and (/= (point) opoint) (outline-on-heading-p t))
22299 (while (and (> (funcall outline-level) level)
22300 (not (bobp)))
22301 (outline-previous-heading))
22302 (if (< (funcall outline-level) level)
22304 (point)))))
22306 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22307 "Goto to the end of a subtree."
22308 ;; This contains an exact copy of the original function, but it uses
22309 ;; `org-back-to-heading', to make it work also in invisible
22310 ;; trees. And is uses an invisible-ok argument.
22311 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22312 ;; Furthermore, when used inside Org, finding the end of a large subtree
22313 ;; with many children and grandchildren etc, this can be much faster
22314 ;; than the outline version.
22315 (org-back-to-heading invisible-ok)
22316 (let ((first t)
22317 (level (funcall outline-level)))
22318 (if (and (derived-mode-p 'org-mode) (< level 1000))
22319 ;; A true heading (not a plain list item), in Org-mode
22320 ;; This means we can easily find the end by looking
22321 ;; only for the right number of stars. Using a regexp to do
22322 ;; this is so much faster than using a Lisp loop.
22323 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22324 (forward-char 1)
22325 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22326 ;; something else, do it the slow way
22327 (while (and (not (eobp))
22328 (or first (> (funcall outline-level) level)))
22329 (setq first nil)
22330 (outline-next-heading)))
22331 (unless to-heading
22332 (if (memq (preceding-char) '(?\n ?\^M))
22333 (progn
22334 ;; Go to end of line before heading
22335 (forward-char -1)
22336 (if (memq (preceding-char) '(?\n ?\^M))
22337 ;; leave blank line before heading
22338 (forward-char -1))))))
22339 (point))
22341 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22342 "Use Org version in org-mode, for dramatic speed-up."
22343 (if (derived-mode-p 'org-mode)
22344 (progn
22345 (org-end-of-subtree nil t)
22346 (unless (eobp) (backward-char 1)))
22347 ad-do-it))
22349 (defun org-end-of-meta-data-and-drawers ()
22350 "Jump to the first text after meta data and drawers in the current entry.
22351 This will move over empty lines, lines with planning time stamps,
22352 clocking lines, and drawers."
22353 (org-back-to-heading t)
22354 (let ((end (save-excursion (outline-next-heading) (point)))
22355 (re (concat "\\(" org-drawer-regexp "\\)"
22356 "\\|" "[ \t]*" org-keyword-time-regexp)))
22357 (forward-line 1)
22358 (while (re-search-forward re end t)
22359 (if (not (match-end 1))
22360 ;; empty or planning line
22361 (forward-line 1)
22362 ;; a drawer, find the end
22363 (re-search-forward "^[ \t]*:END:" end 'move)
22364 (forward-line 1)))
22365 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22366 (point)))
22368 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22369 "Move forward to the arg'th subheading at same level as this one.
22370 Stop at the first and last subheadings of a superior heading.
22371 Normally this only looks at visible headings, but when INVISIBLE-OK is
22372 non-nil it will also look at invisible ones."
22373 (interactive "p")
22374 (org-back-to-heading invisible-ok)
22375 (org-at-heading-p)
22376 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22377 (re (format "^\\*\\{1,%d\\} " level))
22379 (forward-char 1)
22380 (while (> arg 0)
22381 (while (and (re-search-forward re nil 'move)
22382 (setq l (- (match-end 0) (match-beginning 0) 1))
22383 (= l level)
22384 (not invisible-ok)
22385 (progn (backward-char 1) (outline-invisible-p)))
22386 (if (< l level) (setq arg 1)))
22387 (setq arg (1- arg)))
22388 (beginning-of-line 1)))
22390 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22391 "Move backward to the arg'th subheading at same level as this one.
22392 Stop at the first and last subheadings of a superior heading."
22393 (interactive "p")
22394 (org-back-to-heading)
22395 (org-at-heading-p)
22396 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22397 (re (format "^\\*\\{1,%d\\} " level))
22399 (while (> arg 0)
22400 (while (and (re-search-backward re nil 'move)
22401 (setq l (- (match-end 0) (match-beginning 0) 1))
22402 (= l level)
22403 (not invisible-ok)
22404 (outline-invisible-p))
22405 (if (< l level) (setq arg 1)))
22406 (setq arg (1- arg)))))
22408 (defun org-forward-element ()
22409 "Move forward by one element.
22410 Move to the next element at the same level, when possible."
22411 (interactive)
22412 (cond ((eobp) (error "Cannot move further down"))
22413 ((org-with-limited-levels (org-at-heading-p))
22414 (let ((origin (point)))
22415 (org-forward-heading-same-level 1)
22416 (unless (org-with-limited-levels (org-at-heading-p))
22417 (goto-char origin)
22418 (error "Cannot move further down"))))
22420 (let* ((elem (org-element-at-point))
22421 (end (org-element-property :end elem))
22422 (parent (org-element-property :parent elem)))
22423 (if (and parent (= (org-element-property :contents-end parent) end))
22424 (goto-char (org-element-property :end parent))
22425 (goto-char end))))))
22427 (defun org-backward-element ()
22428 "Move backward by one element.
22429 Move to the previous element at the same level, when possible."
22430 (interactive)
22431 (cond ((bobp) (error "Cannot move further up"))
22432 ((org-with-limited-levels (org-at-heading-p))
22433 ;; At an headline, move to the previous one, if any, or stay
22434 ;; here.
22435 (let ((origin (point)))
22436 (org-backward-heading-same-level 1)
22437 (unless (org-with-limited-levels (org-at-heading-p))
22438 (goto-char origin)
22439 (error "Cannot move further up"))))
22441 (let* ((trail (org-element-at-point 'keep-trail))
22442 (elem (car trail))
22443 (prev-elem (nth 1 trail))
22444 (beg (org-element-property :begin elem)))
22445 (cond
22446 ;; Move to beginning of current element if point isn't
22447 ;; there already.
22448 ((/= (point) beg) (goto-char beg))
22449 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22450 ((org-before-first-heading-p) (goto-char (point-min)))
22451 (t (org-back-to-heading)))))))
22453 (defun org-up-element ()
22454 "Move to upper element."
22455 (interactive)
22456 (if (org-with-limited-levels (org-at-heading-p))
22457 (unless (org-up-heading-safe) (error "No surrounding element"))
22458 (let* ((elem (org-element-at-point))
22459 (parent (org-element-property :parent elem)))
22460 (if parent (goto-char (org-element-property :begin parent))
22461 (if (org-with-limited-levels (org-before-first-heading-p))
22462 (error "No surrounding element")
22463 (org-with-limited-levels (org-back-to-heading)))))))
22465 (defvar org-element-greater-elements)
22466 (defun org-down-element ()
22467 "Move to inner element."
22468 (interactive)
22469 (let ((element (org-element-at-point)))
22470 (cond
22471 ((memq (org-element-type element) '(plain-list table))
22472 (goto-char (org-element-property :contents-begin element))
22473 (forward-char))
22474 ((memq (org-element-type element) org-element-greater-elements)
22475 ;; If contents are hidden, first disclose them.
22476 (when (org-element-property :hiddenp element) (org-cycle))
22477 (goto-char (or (org-element-property :contents-begin element)
22478 (error "No content for this element"))))
22479 (t (error "No inner element")))))
22481 (defun org-drag-element-backward ()
22482 "Move backward element at point."
22483 (interactive)
22484 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22485 (let* ((trail (org-element-at-point 'keep-trail))
22486 (elem (car trail))
22487 (prev-elem (nth 1 trail)))
22488 ;; Error out if no previous element or previous element is
22489 ;; a parent of the current one.
22490 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22491 (error "Cannot drag element backward")
22492 (let ((pos (point)))
22493 (org-element-swap-A-B prev-elem elem)
22494 (goto-char (+ (org-element-property :begin prev-elem)
22495 (- pos (org-element-property :begin elem)))))))))
22497 (defun org-drag-element-forward ()
22498 "Move forward element at point."
22499 (interactive)
22500 (let* ((pos (point))
22501 (elem (org-element-at-point)))
22502 (when (= (point-max) (org-element-property :end elem))
22503 (error "Cannot drag element forward"))
22504 (goto-char (org-element-property :end elem))
22505 (let ((next-elem (org-element-at-point)))
22506 (when (or (org-element-nested-p elem next-elem)
22507 (and (eq (org-element-type next-elem) 'headline)
22508 (not (eq (org-element-type elem) 'headline))))
22509 (goto-char pos)
22510 (error "Cannot drag element forward"))
22511 ;; Compute new position of point: it's shifted by NEXT-ELEM
22512 ;; body's length (without final blanks) and by the length of
22513 ;; blanks between ELEM and NEXT-ELEM.
22514 (let ((size-next (- (save-excursion
22515 (goto-char (org-element-property :end next-elem))
22516 (skip-chars-backward " \r\t\n")
22517 (forward-line)
22518 ;; Small correction if buffer doesn't end
22519 ;; with a newline character.
22520 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22521 (org-element-property :begin next-elem)))
22522 (size-blank (- (org-element-property :end elem)
22523 (save-excursion
22524 (goto-char (org-element-property :end elem))
22525 (skip-chars-backward " \r\t\n")
22526 (forward-line)
22527 (point)))))
22528 (org-element-swap-A-B elem next-elem)
22529 (goto-char (+ pos size-next size-blank))))))
22531 (defun org-mark-element ()
22532 "Put point at beginning of this element, mark at end.
22534 Interactively, if this command is repeated or (in Transient Mark
22535 mode) if the mark is active, it marks the next element after the
22536 ones already marked."
22537 (interactive)
22538 (let (deactivate-mark)
22539 (if (and (org-called-interactively-p 'any)
22540 (or (and (eq last-command this-command) (mark t))
22541 (and transient-mark-mode mark-active)))
22542 (set-mark
22543 (save-excursion
22544 (goto-char (mark))
22545 (goto-char (org-element-property :end (org-element-at-point)))))
22546 (let ((element (org-element-at-point)))
22547 (end-of-line)
22548 (push-mark (org-element-property :end element) t t)
22549 (goto-char (org-element-property :begin element))))))
22551 (defun org-narrow-to-element ()
22552 "Narrow buffer to current element."
22553 (interactive)
22554 (let ((elem (org-element-at-point)))
22555 (cond
22556 ((eq (car elem) 'headline)
22557 (narrow-to-region
22558 (org-element-property :begin elem)
22559 (org-element-property :end elem)))
22560 ((memq (car elem) org-element-greater-elements)
22561 (narrow-to-region
22562 (org-element-property :contents-begin elem)
22563 (org-element-property :contents-end elem)))
22565 (narrow-to-region
22566 (org-element-property :begin elem)
22567 (org-element-property :end elem))))))
22569 (defun org-transpose-words ()
22570 "Transpose words, using `org-mode' syntax table."
22571 (interactive)
22572 (with-syntax-table org-syntax-table
22573 (call-interactively 'transpose-words)))
22574 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22576 (defun org-transpose-element ()
22577 "Transpose current and previous elements, keeping blank lines between.
22578 Point is moved after both elements."
22579 (interactive)
22580 (org-skip-whitespace)
22581 (let ((end (org-element-property :end (org-element-at-point))))
22582 (org-drag-element-backward)
22583 (goto-char end)))
22585 (defun org-unindent-buffer ()
22586 "Un-indent the visible part of the buffer.
22587 Relative indentation (between items, inside blocks, etc.) isn't
22588 modified."
22589 (interactive)
22590 (unless (eq major-mode 'org-mode)
22591 (error "Cannot un-indent a buffer not in Org mode"))
22592 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22593 unindent-tree ; For byte-compiler.
22594 (unindent-tree
22595 (function
22596 (lambda (contents)
22597 (mapc
22598 (lambda (element)
22599 (if (memq (org-element-type element) '(headline section))
22600 (funcall unindent-tree (org-element-contents element))
22601 (save-excursion
22602 (save-restriction
22603 (narrow-to-region
22604 (org-element-property :begin element)
22605 (org-element-property :end element))
22606 (org-do-remove-indentation)))))
22607 (reverse contents))))))
22608 (funcall unindent-tree (org-element-contents parse-tree))))
22610 (defun org-show-subtree ()
22611 "Show everything after this heading at deeper levels."
22612 (interactive)
22613 (outline-flag-region
22614 (point)
22615 (save-excursion
22616 (org-end-of-subtree t t))
22617 nil))
22619 (defun org-show-entry ()
22620 "Show the body directly following this heading.
22621 Show the heading too, if it is currently invisible."
22622 (interactive)
22623 (save-excursion
22624 (condition-case nil
22625 (progn
22626 (org-back-to-heading t)
22627 (outline-flag-region
22628 (max (point-min) (1- (point)))
22629 (save-excursion
22630 (if (re-search-forward
22631 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22632 (match-beginning 1)
22633 (point-max)))
22634 nil)
22635 (org-cycle-hide-drawers 'children))
22636 (error nil))))
22638 (defun org-make-options-regexp (kwds &optional extra)
22639 "Make a regular expression for keyword lines."
22640 (concat
22641 "^#\\+\\("
22642 (mapconcat 'regexp-quote kwds "\\|")
22643 (if extra (concat "\\|" extra))
22644 "\\):[ \t]*\\(.*\\)"))
22646 ;; Make isearch reveal the necessary context
22647 (defun org-isearch-end ()
22648 "Reveal context after isearch exits."
22649 (when isearch-success ; only if search was successful
22650 (if (featurep 'xemacs)
22651 ;; Under XEmacs, the hook is run in the correct place,
22652 ;; we directly show the context.
22653 (org-show-context 'isearch)
22654 ;; In Emacs the hook runs *before* restoring the overlays.
22655 ;; So we have to use a one-time post-command-hook to do this.
22656 ;; (Emacs 22 has a special variable, see function `org-mode')
22657 (unless (and (boundp 'isearch-mode-end-hook-quit)
22658 isearch-mode-end-hook-quit)
22659 ;; Only when the isearch was not quitted.
22660 (org-add-hook 'post-command-hook 'org-isearch-post-command
22661 'append 'local)))))
22663 (defun org-isearch-post-command ()
22664 "Remove self from hook, and show context."
22665 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22666 (org-show-context 'isearch))
22669 ;;;; Integration with and fixes for other packages
22671 ;;; Imenu support
22673 (defvar org-imenu-markers nil
22674 "All markers currently used by Imenu.")
22675 (make-variable-buffer-local 'org-imenu-markers)
22677 (defun org-imenu-new-marker (&optional pos)
22678 "Return a new marker for use by Imenu, and remember the marker."
22679 (let ((m (make-marker)))
22680 (move-marker m (or pos (point)))
22681 (push m org-imenu-markers)
22684 (defun org-imenu-get-tree ()
22685 "Produce the index for Imenu."
22686 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22687 (setq org-imenu-markers nil)
22688 (let* ((n org-imenu-depth)
22689 (re (concat "^" (org-get-limited-outline-regexp)))
22690 (subs (make-vector (1+ n) nil))
22691 (last-level 0)
22692 m level head)
22693 (save-excursion
22694 (save-restriction
22695 (widen)
22696 (goto-char (point-max))
22697 (while (re-search-backward re nil t)
22698 (setq level (org-reduced-level (funcall outline-level)))
22699 (when (and (<= level n)
22700 (looking-at org-complex-heading-regexp))
22701 (setq head (org-link-display-format
22702 (org-match-string-no-properties 4))
22703 m (org-imenu-new-marker))
22704 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22705 (if (>= level last-level)
22706 (push (cons head m) (aref subs level))
22707 (push (cons head (aref subs (1+ level))) (aref subs level))
22708 (loop for i from (1+ level) to n do (aset subs i nil)))
22709 (setq last-level level)))))
22710 (aref subs 1)))
22712 (eval-after-load "imenu"
22713 '(progn
22714 (add-hook 'imenu-after-jump-hook
22715 (lambda ()
22716 (if (derived-mode-p 'org-mode)
22717 (org-show-context 'org-goto))))))
22719 (defun org-link-display-format (link)
22720 "Replace a link with either the description, or the link target
22721 if no description is present"
22722 (save-match-data
22723 (if (string-match org-bracket-link-analytic-regexp link)
22724 (replace-match (if (match-end 5)
22725 (match-string 5 link)
22726 (concat (match-string 1 link)
22727 (match-string 3 link)))
22728 nil t link)
22729 link)))
22731 (defun org-toggle-link-display ()
22732 "Toggle the literal or descriptive display of links."
22733 (interactive)
22734 (if org-descriptive-links
22735 (progn (org-remove-from-invisibility-spec '(org-link))
22736 (org-restart-font-lock)
22737 (setq org-descriptive-links nil))
22738 (progn (add-to-invisibility-spec '(org-link))
22739 (org-restart-font-lock)
22740 (setq org-descriptive-links t))))
22742 ;; Speedbar support
22744 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22745 "Overlay marking the agenda restriction line in speedbar.")
22746 (overlay-put org-speedbar-restriction-lock-overlay
22747 'face 'org-agenda-restriction-lock)
22748 (overlay-put org-speedbar-restriction-lock-overlay
22749 'help-echo "Agendas are currently limited to this item.")
22750 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22752 (defun org-speedbar-set-agenda-restriction ()
22753 "Restrict future agenda commands to the location at point in speedbar.
22754 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22755 (interactive)
22756 (require 'org-agenda)
22757 (let (p m tp np dir txt)
22758 (cond
22759 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22760 'org-imenu t))
22761 (setq m (get-text-property p 'org-imenu-marker))
22762 (with-current-buffer (marker-buffer m)
22763 (goto-char m)
22764 (org-agenda-set-restriction-lock 'subtree)))
22765 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22766 'speedbar-function 'speedbar-find-file))
22767 (setq tp (previous-single-property-change
22768 (1+ p) 'speedbar-function)
22769 np (next-single-property-change
22770 tp 'speedbar-function)
22771 dir (speedbar-line-directory)
22772 txt (buffer-substring-no-properties (or tp (point-min))
22773 (or np (point-max))))
22774 (with-current-buffer (find-file-noselect
22775 (let ((default-directory dir))
22776 (expand-file-name txt)))
22777 (unless (derived-mode-p 'org-mode)
22778 (error "Cannot restrict to non-Org-mode file"))
22779 (org-agenda-set-restriction-lock 'file)))
22780 (t (error "Don't know how to restrict Org-mode's agenda")))
22781 (move-overlay org-speedbar-restriction-lock-overlay
22782 (point-at-bol) (point-at-eol))
22783 (setq current-prefix-arg nil)
22784 (org-agenda-maybe-redo)))
22786 (eval-after-load "speedbar"
22787 '(progn
22788 (speedbar-add-supported-extension ".org")
22789 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22790 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22791 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22792 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22793 (add-hook 'speedbar-visiting-tag-hook
22794 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22796 ;;; Fixes and Hacks for problems with other packages
22798 ;; Make flyspell not check words in links, to not mess up our keymap
22799 (defun org-mode-flyspell-verify ()
22800 "Don't let flyspell put overlays at active buttons, or on
22801 {todo,all-time,additional-option-like}-keywords."
22802 (let ((pos (max (1- (point)) (point-min)))
22803 (word (thing-at-point 'word)))
22804 (and (not (get-text-property pos 'keymap))
22805 (not (get-text-property pos 'org-no-flyspell))
22806 (not (member word org-todo-keywords-1))
22807 (not (member word org-all-time-keywords))
22808 (not (member word org-options-keywords))
22809 (not (member word (mapcar 'car org-startup-options)))
22810 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22812 (defun org-remove-flyspell-overlays-in (beg end)
22813 "Remove flyspell overlays in region."
22814 (and (org-bound-and-true-p flyspell-mode)
22815 (fboundp 'flyspell-delete-region-overlays)
22816 (flyspell-delete-region-overlays beg end))
22817 (add-text-properties beg end '(org-no-flyspell t)))
22819 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22820 (eval-after-load "bookmark"
22821 '(if (boundp 'bookmark-after-jump-hook)
22822 ;; We can use the hook
22823 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22824 ;; Hook not available, use advice
22825 (defadvice bookmark-jump (after org-make-visible activate)
22826 "Make the position visible."
22827 (org-bookmark-jump-unhide))))
22829 ;; Make sure saveplace shows the location if it was hidden
22830 (eval-after-load "saveplace"
22831 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22832 "Make the position visible."
22833 (org-bookmark-jump-unhide)))
22835 ;; Make sure ecb shows the location if it was hidden
22836 (eval-after-load "ecb"
22837 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22838 "Make hierarchy visible when jumping into location from ECB tree buffer."
22839 (if (derived-mode-p 'org-mode)
22840 (org-show-context))))
22842 (defun org-bookmark-jump-unhide ()
22843 "Unhide the current position, to show the bookmark location."
22844 (and (derived-mode-p 'org-mode)
22845 (or (outline-invisible-p)
22846 (save-excursion (goto-char (max (point-min) (1- (point))))
22847 (outline-invisible-p)))
22848 (org-show-context 'bookmark-jump)))
22850 ;; Make session.el ignore our circular variable
22851 (eval-after-load "session"
22852 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22854 ;;;; Experimental code
22856 (defun org-closed-in-range ()
22857 "Sparse tree of items closed in a certain time range.
22858 Still experimental, may disappear in the future."
22859 (interactive)
22860 ;; Get the time interval from the user.
22861 (let* ((time1 (org-float-time
22862 (org-read-date nil 'to-time nil "Starting date: ")))
22863 (time2 (org-float-time
22864 (org-read-date nil 'to-time nil "End date:")))
22865 ;; callback function
22866 (callback (lambda ()
22867 (let ((time
22868 (org-float-time
22869 (apply 'encode-time
22870 (org-parse-time-string
22871 (match-string 1))))))
22872 ;; check if time in interval
22873 (and (>= time time1) (<= time time2))))))
22874 ;; make tree, check each match with the callback
22875 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22877 ;;;; Finish up
22879 (provide 'org)
22881 (run-hooks 'org-load-hook)
22883 ;;; org.el ends here