Compatibility: Use org-load-noerror-mustsuffix
[org-mode.git] / lisp / org.el
bloba446d760cdefc8d469847e81f04919e054fcc413
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 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 (require 'org-macs)
82 (require 'org-compat)
84 (let ((load-suffixes (list ".el")))
85 (org-load-noerror-mustsuffix "org-loaddefs"))
87 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
88 ;; some places -- e.g. see the macro org-with-limited-levels.
90 ;; In Org buffers, the value of `outline-regexp' is that of
91 ;; `org-outline-regexp'. The only function still directly relying on
92 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
93 ;; job when `orgstruct-mode' is active.
94 (defvar org-outline-regexp "\\*+ "
95 "Regexp to match Org headlines.")
97 (defvar org-outline-regexp-bol "^\\*+ "
98 "Regexp to match Org headlines.
99 This is similar to `org-outline-regexp' but additionally makes
100 sure that we are at the beginning of the line.")
102 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
103 "Matches an headline, putting stars and text into groups.
104 Stars are put in group 1 and the trimmed body in group 2.")
106 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
107 (when (fboundp 'defvaralias)
108 (unless (boundp 'calendar-view-holidays-initially-flag)
109 (defvaralias 'calendar-view-holidays-initially-flag
110 'view-calendar-holidays-initially))
111 (unless (boundp 'calendar-view-diary-initially-flag)
112 (defvaralias 'calendar-view-diary-initially-flag
113 'view-diary-entries-initially))
114 (unless (boundp 'diary-fancy-buffer)
115 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
117 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
118 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
119 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
120 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
121 (declare-function org-at-clock-log-p "org-clock" ())
122 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
123 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
124 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
125 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
127 (declare-function orgtbl-mode "org-table" (&optional arg))
128 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
129 (declare-function org-beamer-mode "org-beamer" ())
130 (declare-function org-table-edit-field "org-table" (arg))
131 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
132 (declare-function org-id-get-create "org-id" (&optional force))
133 (declare-function org-id-find-id-file "org-id" (id))
134 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
135 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
136 (declare-function org-table-align "org-table" ())
137 (declare-function org-table-paste-rectangle "org-table" ())
138 (declare-function org-table-maybe-eval-formula "org-table" ())
139 (declare-function org-table-maybe-recalculate-line "org-table" ())
141 (autoload 'org-element-at-point "org-element")
142 (autoload 'org-element-type "org-element")
144 (declare-function org-element-at-point "org-element" (&optional keep-trail))
145 (declare-function org-element-type "org-element" (element))
146 (declare-function org-element-context "org-element" ())
147 (declare-function org-element-contents "org-element" (element))
148 (declare-function org-element-property "org-element" (property element))
149 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
150 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
151 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
152 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
153 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
155 ;; load languages based on value of `org-babel-load-languages'
156 (defvar org-babel-load-languages)
158 ;;;###autoload
159 (defun org-babel-do-load-languages (sym value)
160 "Load the languages defined in `org-babel-load-languages'."
161 (set-default sym value)
162 (mapc (lambda (pair)
163 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
164 (if active
165 (progn
166 (require (intern (concat "ob-" lang))))
167 (progn
168 (funcall 'fmakunbound
169 (intern (concat "org-babel-execute:" lang)))
170 (funcall 'fmakunbound
171 (intern (concat "org-babel-expand-body:" lang)))))))
172 org-babel-load-languages))
174 (defcustom org-babel-load-languages '((emacs-lisp . t))
175 "Languages which can be evaluated in Org-mode buffers.
176 This list can be used to load support for any of the languages
177 below, note that each language will depend on a different set of
178 system executables and/or Emacs modes. When a language is
179 \"loaded\", then code blocks in that language can be evaluated
180 with `org-babel-execute-src-block' bound by default to C-c
181 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
182 be set to remove code block evaluation from the C-c C-c
183 keybinding. By default only Emacs Lisp (which has no
184 requirements) is loaded."
185 :group 'org-babel
186 :set 'org-babel-do-load-languages
187 :version "24.1"
188 :type '(alist :tag "Babel Languages"
189 :key-type
190 (choice
191 (const :tag "Awk" awk)
192 (const :tag "C" C)
193 (const :tag "R" R)
194 (const :tag "Asymptote" asymptote)
195 (const :tag "Calc" calc)
196 (const :tag "Clojure" clojure)
197 (const :tag "CSS" css)
198 (const :tag "Ditaa" ditaa)
199 (const :tag "Dot" dot)
200 (const :tag "Emacs Lisp" emacs-lisp)
201 (const :tag "Fortran" fortran)
202 (const :tag "Gnuplot" gnuplot)
203 (const :tag "Haskell" haskell)
204 (const :tag "IO" io)
205 (const :tag "Java" java)
206 (const :tag "Javascript" js)
207 (const :tag "LaTeX" latex)
208 (const :tag "Ledger" ledger)
209 (const :tag "Lilypond" lilypond)
210 (const :tag "Lisp" lisp)
211 (const :tag "Makefile" makefile)
212 (const :tag "Maxima" maxima)
213 (const :tag "Matlab" matlab)
214 (const :tag "Mscgen" mscgen)
215 (const :tag "Ocaml" ocaml)
216 (const :tag "Octave" octave)
217 (const :tag "Org" org)
218 (const :tag "Perl" perl)
219 (const :tag "Pico Lisp" picolisp)
220 (const :tag "PlantUML" plantuml)
221 (const :tag "Python" python)
222 (const :tag "Ruby" ruby)
223 (const :tag "Sass" sass)
224 (const :tag "Scala" scala)
225 (const :tag "Scheme" scheme)
226 (const :tag "Screen" screen)
227 (const :tag "Shell Script" sh)
228 (const :tag "Shen" shen)
229 (const :tag "Sql" sql)
230 (const :tag "Sqlite" sqlite))
231 :value-type (boolean :tag "Activate" :value t)))
233 ;;;; Customization variables
234 (defcustom org-clone-delete-id nil
235 "Remove ID property of clones of a subtree.
236 When non-nil, clones of a subtree don't inherit the ID property.
237 Otherwise they inherit the ID property with a new unique
238 identifier."
239 :type 'boolean
240 :version "24.1"
241 :group 'org-id)
243 ;;; Version
244 (org-check-version)
246 ;;;###autoload
247 (defun org-version (&optional here full message)
248 "Show the org-mode version in the echo area.
249 With prefix argument HERE, insert it at point.
250 When FULL is non-nil, use a verbose version string.
251 When MESSAGE is non-nil, display a message with the version."
252 (interactive "P")
253 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
254 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
255 (load-suffixes (list ".el"))
256 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
257 (org-trash (or
258 (and (fboundp 'org-release) (fboundp 'org-git-version))
259 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
260 (load-suffixes save-load-suffixes)
261 (org-version (org-release))
262 (git-version (org-git-version))
263 (version (format "Org-mode version %s (%s @ %s)"
264 org-version
265 git-version
266 (if org-install-dir
267 (if (string= org-dir org-install-dir)
268 org-install-dir
269 (concat "mixed installation! " org-install-dir " and " org-dir))
270 "org-loaddefs.el can not be found!")))
271 (_version (if full version org-version)))
272 (if (org-called-interactively-p 'interactive)
273 (if here
274 (insert version)
275 (message version))
276 (if message (message _version))
277 _version)))
279 (defconst org-version (org-version))
281 ;;; Compatibility constants
283 ;;; The custom variables
285 (defgroup org nil
286 "Outline-based notes management and organizer."
287 :tag "Org"
288 :group 'outlines
289 :group 'calendar)
291 (defcustom org-mode-hook nil
292 "Mode hook for Org-mode, run after the mode was turned on."
293 :group 'org
294 :type 'hook)
296 (defcustom org-load-hook nil
297 "Hook that is run after org.el has been loaded."
298 :group 'org
299 :type 'hook)
301 (defcustom org-log-buffer-setup-hook nil
302 "Hook that is run after an Org log buffer is created."
303 :group 'org
304 :version "24.1"
305 :type 'hook)
307 (defvar org-modules) ; defined below
308 (defvar org-modules-loaded nil
309 "Have the modules been loaded already?")
311 (defun org-load-modules-maybe (&optional force)
312 "Load all extensions listed in `org-modules'."
313 (when (or force (not org-modules-loaded))
314 (mapc (lambda (ext)
315 (condition-case nil (require ext)
316 (error (message "Problems while trying to load feature `%s'" ext))))
317 org-modules)
318 (setq org-modules-loaded t)))
320 (defun org-set-modules (var value)
321 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
322 (set var value)
323 (when (featurep 'org)
324 (org-load-modules-maybe 'force)))
326 (when (org-bound-and-true-p org-modules)
327 (let ((a (member 'org-infojs org-modules)))
328 (and a (setcar a 'org-jsinfo))))
330 (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)
331 "Modules that should always be loaded together with org.el.
332 If a description starts with <C>, the file is not part of Emacs
333 and loading it will require that you have downloaded and properly installed
334 the org-mode distribution.
336 You can also use this system to load external packages (i.e. neither Org
337 core modules, nor modules from the CONTRIB directory). Just add symbols
338 to the end of the list. If the package is called org-xyz.el, then you need
339 to add the symbol `xyz', and the package must have a call to
341 (provide 'org-xyz)"
342 :group 'org
343 :set 'org-set-modules
344 :type
345 '(set :greedy t
346 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
347 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
348 (const :tag " crypt: Encryption of subtrees" org-crypt)
349 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
350 (const :tag " docview: Links to doc-view buffers" org-docview)
351 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
352 (const :tag " id: Global IDs for identifying entries" org-id)
353 (const :tag " info: Links to Info nodes" org-info)
354 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
355 (const :tag " habit: Track your consistency with habits" org-habit)
356 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
357 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
358 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
359 (const :tag " mew Links to Mew folders/messages" org-mew)
360 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
361 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
362 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
363 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
364 (const :tag " vm: Links to VM folders/messages" org-vm)
365 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
366 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
367 (const :tag " mouse: Additional mouse support" org-mouse)
368 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
370 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
371 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
372 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
373 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
374 (const :tag "C collector: Collect properties into tables" org-collector)
375 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
376 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
377 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
378 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
379 (const :tag "C eval: Include command output as text" org-eval)
380 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
381 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
382 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
383 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
384 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
386 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
388 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
389 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
390 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
391 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
392 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
393 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
394 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
395 (const :tag "C mtags: Support for muse-like tags" org-mtags)
396 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
397 (const :tag "C registry: A registry for Org-mode links" org-registry)
398 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
399 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
400 (const :tag "C secretary: Team management with org-mode" org-secretary)
401 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
402 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
403 (const :tag "C track: Keep up with Org-mode development" org-track)
404 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
405 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
406 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
408 (defcustom org-support-shift-select nil
409 "Non-nil means make shift-cursor commands select text when possible.
411 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
412 start selecting a region, or enlarge regions started in this way.
413 In Org-mode, in special contexts, these same keys are used for
414 other purposes, important enough to compete with shift selection.
415 Org tries to balance these needs by supporting `shift-select-mode'
416 outside these special contexts, under control of this variable.
418 The default of this variable is nil, to avoid confusing behavior. Shifted
419 cursor keys will then execute Org commands in the following contexts:
420 - on a headline, changing TODO state (left/right) and priority (up/down)
421 - on a time stamp, changing the time
422 - in a plain list item, changing the bullet type
423 - in a property definition line, switching between allowed values
424 - in the BEGIN line of a clock table (changing the time block).
425 Outside these contexts, the commands will throw an error.
427 When this variable is t and the cursor is not in a special
428 context, Org-mode will support shift-selection for making and
429 enlarging regions. To make this more effective, the bullet
430 cycling will no longer happen anywhere in an item line, but only
431 if the cursor is exactly on the bullet.
433 If you set this variable to the symbol `always', then the keys
434 will not be special in headlines, property lines, and item lines,
435 to make shift selection work there as well. If this is what you
436 want, you can use the following alternative commands: `C-c C-t'
437 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
438 can be used to switch TODO sets, `C-c -' to cycle item bullet
439 types, and properties can be edited by hand or in column view.
441 However, when the cursor is on a timestamp, shift-cursor commands
442 will still edit the time stamp - this is just too good to give up.
444 XEmacs user should have this variable set to nil, because
445 `shift-select-mode' is in Emacs 23 or later only."
446 :group 'org
447 :type '(choice
448 (const :tag "Never" nil)
449 (const :tag "When outside special context" t)
450 (const :tag "Everywhere except timestamps" always)))
452 (defcustom org-loop-over-headlines-in-active-region nil
453 "Shall some commands act upon headlines in the active region?
455 When set to `t', some commands will be performed in all headlines
456 within the active region.
458 When set to `start-level', some commands will be performed in all
459 headlines within the active region, provided that these headlines
460 are of the same level than the first one.
462 When set to a string, those commands will be performed on the
463 matching headlines within the active region. Such string must be
464 a tags/property/todo match as it is used in the agenda tags view.
466 The list of commands is: `org-schedule', `org-deadline',
467 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
468 `org-archive-to-archive-sibling'. The archiving commands skip
469 already archived entries."
470 :type '(choice (const :tag "Don't loop" nil)
471 (const :tag "All headlines in active region" t)
472 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
473 (string :tag "Tags/Property/Todo matcher"))
474 :version "24.1"
475 :group 'org-todo
476 :group 'org-archive)
478 (defgroup org-startup nil
479 "Options concerning startup of Org-mode."
480 :tag "Org Startup"
481 :group 'org)
483 (defcustom org-startup-folded t
484 "Non-nil means entering Org-mode will switch to OVERVIEW.
485 This can also be configured on a per-file basis by adding one of
486 the following lines anywhere in the buffer:
488 #+STARTUP: fold (or `overview', this is equivalent)
489 #+STARTUP: nofold (or `showall', this is equivalent)
490 #+STARTUP: content
491 #+STARTUP: showeverything"
492 :group 'org-startup
493 :type '(choice
494 (const :tag "nofold: show all" nil)
495 (const :tag "fold: overview" t)
496 (const :tag "content: all headlines" content)
497 (const :tag "show everything, even drawers" showeverything)))
499 (defcustom org-startup-truncated t
500 "Non-nil means entering Org-mode will set `truncate-lines'.
501 This is useful since some lines containing links can be very long and
502 uninteresting. Also tables look terrible when wrapped."
503 :group 'org-startup
504 :type 'boolean)
506 (defcustom org-startup-indented nil
507 "Non-nil means turn on `org-indent-mode' on startup.
508 This can also be configured on a per-file basis by adding one of
509 the following lines anywhere in the buffer:
511 #+STARTUP: indent
512 #+STARTUP: noindent"
513 :group 'org-structure
514 :type '(choice
515 (const :tag "Not" nil)
516 (const :tag "Globally (slow on startup in large files)" t)))
518 (defcustom org-use-sub-superscripts t
519 "Non-nil means interpret \"_\" and \"^\" for export.
520 When this option is turned on, you can use TeX-like syntax for sub- and
521 superscripts. Several characters after \"_\" or \"^\" will be
522 considered as a single item - so grouping with {} is normally not
523 needed. For example, the following things will be parsed as single
524 sub- or superscripts.
526 10^24 or 10^tau several digits will be considered 1 item.
527 10^-12 or 10^-tau a leading sign with digits or a word
528 x^2-y^3 will be read as x^2 - y^3, because items are
529 terminated by almost any nonword/nondigit char.
530 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
532 Still, ambiguity is possible - so when in doubt use {} to enclose the
533 sub/superscript. If you set this variable to the symbol `{}',
534 the braces are *required* in order to trigger interpretations as
535 sub/superscript. This can be helpful in documents that need \"_\"
536 frequently in plain text.
538 Not all export backends support this, but HTML does.
540 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
541 :group 'org-startup
542 :group 'org-export-translation
543 :version "24.1"
544 :type '(choice
545 (const :tag "Always interpret" t)
546 (const :tag "Only with braces" {})
547 (const :tag "Never interpret" nil)))
549 (if (fboundp 'defvaralias)
550 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
553 (defcustom org-startup-with-beamer-mode nil
554 "Non-nil means turn on `org-beamer-mode' on startup.
555 This can also be configured on a per-file basis by adding one of
556 the following lines anywhere in the buffer:
558 #+STARTUP: beamer"
559 :group 'org-startup
560 :version "24.1"
561 :type 'boolean)
563 (defcustom org-startup-align-all-tables nil
564 "Non-nil means align all tables when visiting a file.
565 This is useful when the column width in tables is forced with <N> cookies
566 in table fields. Such tables will look correct only after the first re-align.
567 This can also be configured on a per-file basis by adding one of
568 the following lines anywhere in the buffer:
569 #+STARTUP: align
570 #+STARTUP: noalign"
571 :group 'org-startup
572 :type 'boolean)
574 (defcustom org-startup-with-inline-images nil
575 "Non-nil means show inline images when loading a new Org file.
576 This can also be configured on a per-file basis by adding one of
577 the following lines anywhere in the buffer:
578 #+STARTUP: inlineimages
579 #+STARTUP: noinlineimages"
580 :group 'org-startup
581 :version "24.1"
582 :type 'boolean)
584 (defcustom org-insert-mode-line-in-empty-file nil
585 "Non-nil means insert the first line setting Org-mode in empty files.
586 When the function `org-mode' is called interactively in an empty file, this
587 normally means that the file name does not automatically trigger Org-mode.
588 To ensure that the file will always be in Org-mode in the future, a
589 line enforcing Org-mode will be inserted into the buffer, if this option
590 has been set."
591 :group 'org-startup
592 :type 'boolean)
594 (defcustom org-replace-disputed-keys nil
595 "Non-nil means use alternative key bindings for some keys.
596 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
597 These keys are also used by other packages like shift-selection-mode'
598 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
599 If you want to use Org-mode together with one of these other modes,
600 or more generally if you would like to move some Org-mode commands to
601 other keys, set this variable and configure the keys with the variable
602 `org-disputed-keys'.
604 This option is only relevant at load-time of Org-mode, and must be set
605 *before* org.el is loaded. Changing it requires a restart of Emacs to
606 become effective."
607 :group 'org-startup
608 :type 'boolean)
610 (defcustom org-use-extra-keys nil
611 "Non-nil means use extra key sequence definitions for certain commands.
612 This happens automatically if you run XEmacs or if `window-system'
613 is nil. This variable lets you do the same manually. You must
614 set it before loading org.
616 Example: on Carbon Emacs 22 running graphically, with an external
617 keyboard on a Powerbook, the default way of setting M-left might
618 not work for either Alt or ESC. Setting this variable will make
619 it work for ESC."
620 :group 'org-startup
621 :type 'boolean)
623 (if (fboundp 'defvaralias)
624 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
626 (defcustom org-disputed-keys
627 '(([(shift up)] . [(meta p)])
628 ([(shift down)] . [(meta n)])
629 ([(shift left)] . [(meta -)])
630 ([(shift right)] . [(meta +)])
631 ([(control shift right)] . [(meta shift +)])
632 ([(control shift left)] . [(meta shift -)]))
633 "Keys for which Org-mode and other modes compete.
634 This is an alist, cars are the default keys, second element specifies
635 the alternative to use when `org-replace-disputed-keys' is t.
637 Keys can be specified in any syntax supported by `define-key'.
638 The value of this option takes effect only at Org-mode's startup,
639 therefore you'll have to restart Emacs to apply it after changing."
640 :group 'org-startup
641 :type 'alist)
643 (defun org-key (key)
644 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
645 Or return the original if not disputed.
646 Also apply the translations defined in `org-xemacs-key-equivalents'."
647 (when org-replace-disputed-keys
648 (let* ((nkey (key-description key))
649 (x (org-find-if (lambda (x)
650 (equal (key-description (car x)) nkey))
651 org-disputed-keys)))
652 (setq key (if x (cdr x) key))))
653 (when (featurep 'xemacs)
654 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
655 key)
657 (defun org-find-if (predicate seq)
658 (catch 'exit
659 (while seq
660 (if (funcall predicate (car seq))
661 (throw 'exit (car seq))
662 (pop seq)))))
664 (defun org-defkey (keymap key def)
665 "Define a key, possibly translated, as returned by `org-key'."
666 (define-key keymap (org-key key) def))
668 (defcustom org-ellipsis nil
669 "The ellipsis to use in the Org-mode outline.
670 When nil, just use the standard three dots. When a string, use that instead,
671 When a face, use the standard 3 dots, but with the specified face.
672 The change affects only Org-mode (which will then use its own display table).
673 Changing this requires executing `M-x org-mode' in a buffer to become
674 effective."
675 :group 'org-startup
676 :type '(choice (const :tag "Default" nil)
677 (face :tag "Face" :value org-warning)
678 (string :tag "String" :value "...#")))
680 (defvar org-display-table nil
681 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
683 (defgroup org-keywords nil
684 "Keywords in Org-mode."
685 :tag "Org Keywords"
686 :group 'org)
688 (defcustom org-deadline-string "DEADLINE:"
689 "String to mark deadline entries.
690 A deadline is this string, followed by a time stamp. Should be a word,
691 terminated by a colon. You can insert a schedule keyword and
692 a timestamp with \\[org-deadline].
693 Changes become only effective after restarting Emacs."
694 :group 'org-keywords
695 :type 'string)
697 (defcustom org-scheduled-string "SCHEDULED:"
698 "String to mark scheduled TODO entries.
699 A schedule is this string, followed by a time stamp. Should be a word,
700 terminated by a colon. You can insert a schedule keyword and
701 a timestamp with \\[org-schedule].
702 Changes become only effective after restarting Emacs."
703 :group 'org-keywords
704 :type 'string)
706 (defcustom org-closed-string "CLOSED:"
707 "String used as the prefix for timestamps logging closing a TODO entry."
708 :group 'org-keywords
709 :type 'string)
711 (defcustom org-clock-string "CLOCK:"
712 "String used as prefix for timestamps clocking work hours on an item."
713 :group 'org-keywords
714 :type 'string)
716 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
717 org-scheduled-string "\\|"
718 org-deadline-string "\\|"
719 org-closed-string "\\|"
720 org-clock-string "\\)")
721 "Matches a line with planning or clock info.")
723 (defcustom org-comment-string "COMMENT"
724 "Entries starting with this keyword will never be exported.
725 An entry can be toggled between COMMENT and normal with
726 \\[org-toggle-comment].
727 Changes become only effective after restarting Emacs."
728 :group 'org-keywords
729 :type 'string)
731 (defcustom org-quote-string "QUOTE"
732 "Entries starting with this keyword will be exported in fixed-width font.
733 Quoting applies only to the text in the entry following the headline, and does
734 not extend beyond the next headline, even if that is lower level.
735 An entry can be toggled between QUOTE and normal with
736 \\[org-toggle-fixed-width-section]."
737 :group 'org-keywords
738 :type 'string)
740 (defconst org-repeat-re
741 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
742 "Regular expression for specifying repeated events.
743 After a match, group 1 contains the repeat expression.")
745 (defgroup org-structure nil
746 "Options concerning the general structure of Org-mode files."
747 :tag "Org Structure"
748 :group 'org)
750 (defgroup org-reveal-location nil
751 "Options about how to make context of a location visible."
752 :tag "Org Reveal Location"
753 :group 'org-structure)
755 (defconst org-context-choice
756 '(choice
757 (const :tag "Always" t)
758 (const :tag "Never" nil)
759 (repeat :greedy t :tag "Individual contexts"
760 (cons
761 (choice :tag "Context"
762 (const agenda)
763 (const org-goto)
764 (const occur-tree)
765 (const tags-tree)
766 (const link-search)
767 (const mark-goto)
768 (const bookmark-jump)
769 (const isearch)
770 (const default))
771 (boolean))))
772 "Contexts for the reveal options.")
774 (defcustom org-show-hierarchy-above '((default . t))
775 "Non-nil means show full hierarchy when revealing a location.
776 Org-mode often shows locations in an org-mode file which might have
777 been invisible before. When this is set, the hierarchy of headings
778 above the exposed location is shown.
779 Turning this off for example for sparse trees makes them very compact.
780 Instead of t, this can also be an alist specifying this option for different
781 contexts. Valid contexts are
782 agenda when exposing an entry from the agenda
783 org-goto when using the command `org-goto' on key C-c C-j
784 occur-tree when using the command `org-occur' on key C-c /
785 tags-tree when constructing a sparse tree based on tags matches
786 link-search when exposing search matches associated with a link
787 mark-goto when exposing the jump goal of a mark
788 bookmark-jump when exposing a bookmark location
789 isearch when exiting from an incremental search
790 default default for all contexts not set explicitly"
791 :group 'org-reveal-location
792 :type org-context-choice)
794 (defcustom org-show-following-heading '((default . nil))
795 "Non-nil means show following heading when revealing a location.
796 Org-mode often shows locations in an org-mode file which might have
797 been invisible before. When this is set, the heading following the
798 match is shown.
799 Turning this off for example for sparse trees makes them very compact,
800 but makes it harder to edit the location of the match. In such a case,
801 use the command \\[org-reveal] to show more context.
802 Instead of t, this can also be an alist specifying this option for different
803 contexts. See `org-show-hierarchy-above' for valid contexts."
804 :group 'org-reveal-location
805 :type org-context-choice)
807 (defcustom org-show-siblings '((default . nil) (isearch t))
808 "Non-nil means show all sibling heading when revealing a location.
809 Org-mode often shows locations in an org-mode file which might have
810 been invisible before. When this is set, the sibling of the current entry
811 heading are all made visible. If `org-show-hierarchy-above' is t,
812 the same happens on each level of the hierarchy above the current entry.
814 By default this is on for the isearch context, off for all other contexts.
815 Turning this off for example for sparse trees makes them very compact,
816 but makes it harder to edit the location of the match. In such a case,
817 use the command \\[org-reveal] to show more context.
818 Instead of t, this can also be an alist specifying this option for different
819 contexts. See `org-show-hierarchy-above' for valid contexts."
820 :group 'org-reveal-location
821 :type org-context-choice)
823 (defcustom org-show-entry-below '((default . nil))
824 "Non-nil means show the entry below a headline when revealing a location.
825 Org-mode often shows locations in an org-mode file which might have
826 been invisible before. When this is set, the text below the headline that is
827 exposed is also shown.
829 By default this is off for all contexts.
830 Instead of t, this can also be an alist specifying this option for different
831 contexts. See `org-show-hierarchy-above' for valid contexts."
832 :group 'org-reveal-location
833 :type org-context-choice)
835 (defcustom org-indirect-buffer-display 'other-window
836 "How should indirect tree buffers be displayed?
837 This applies to indirect buffers created with the commands
838 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
839 Valid values are:
840 current-window Display in the current window
841 other-window Just display in another window.
842 dedicated-frame Create one new frame, and re-use it each time.
843 new-frame Make a new frame each time. Note that in this case
844 previously-made indirect buffers are kept, and you need to
845 kill these buffers yourself."
846 :group 'org-structure
847 :group 'org-agenda-windows
848 :type '(choice
849 (const :tag "In current window" current-window)
850 (const :tag "In current frame, other window" other-window)
851 (const :tag "Each time a new frame" new-frame)
852 (const :tag "One dedicated frame" dedicated-frame)))
854 (defcustom org-use-speed-commands nil
855 "Non-nil means activate single letter commands at beginning of a headline.
856 This may also be a function to test for appropriate locations where speed
857 commands should be active."
858 :group 'org-structure
859 :type '(choice
860 (const :tag "Never" nil)
861 (const :tag "At beginning of headline stars" t)
862 (function)))
864 (defcustom org-speed-commands-user nil
865 "Alist of additional speed commands.
866 This list will be checked before `org-speed-commands-default'
867 when the variable `org-use-speed-commands' is non-nil
868 and when the cursor is at the beginning of a headline.
869 The car if each entry is a string with a single letter, which must
870 be assigned to `self-insert-command' in the global map.
871 The cdr is either a command to be called interactively, a function
872 to be called, or a form to be evaluated.
873 An entry that is just a list with a single string will be interpreted
874 as a descriptive headline that will be added when listing the speed
875 commands in the Help buffer using the `?' speed command."
876 :group 'org-structure
877 :type '(repeat :value ("k" . ignore)
878 (choice :value ("k" . ignore)
879 (list :tag "Descriptive Headline" (string :tag "Headline"))
880 (cons :tag "Letter and Command"
881 (string :tag "Command letter")
882 (choice
883 (function)
884 (sexp))))))
886 (defgroup org-cycle nil
887 "Options concerning visibility cycling in Org-mode."
888 :tag "Org Cycle"
889 :group 'org-structure)
891 (defcustom org-cycle-skip-children-state-if-no-children t
892 "Non-nil means skip CHILDREN state in entries that don't have any."
893 :group 'org-cycle
894 :type 'boolean)
896 (defcustom org-cycle-max-level nil
897 "Maximum level which should still be subject to visibility cycling.
898 Levels higher than this will, for cycling, be treated as text, not a headline.
899 When `org-odd-levels-only' is set, a value of N in this variable actually
900 means 2N-1 stars as the limiting headline.
901 When nil, cycle all levels.
902 Note that the limiting level of cycling is also influenced by
903 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
904 `org-inlinetask-min-level' is, cycling will be limited to levels one less
905 than its value."
906 :group 'org-cycle
907 :type '(choice
908 (const :tag "No limit" nil)
909 (integer :tag "Maximum level")))
911 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
912 "Names of drawers. Drawers are not opened by cycling on the headline above.
913 Drawers only open with a TAB on the drawer line itself. A drawer looks like
914 this:
915 :DRAWERNAME:
916 .....
917 :END:
918 The drawer \"PROPERTIES\" is special for capturing properties through
919 the property API.
921 Drawers can be defined on the per-file basis with a line like:
923 #+DRAWERS: HIDDEN STATE PROPERTIES"
924 :group 'org-structure
925 :group 'org-cycle
926 :type '(repeat (string :tag "Drawer Name")))
928 (defcustom org-hide-block-startup nil
929 "Non-nil means entering Org-mode will fold all blocks.
930 This can also be set in on a per-file basis with
932 #+STARTUP: hideblocks
933 #+STARTUP: showblocks"
934 :group 'org-startup
935 :group 'org-cycle
936 :type 'boolean)
938 (defcustom org-cycle-global-at-bob nil
939 "Cycle globally if cursor is at beginning of buffer and not at a headline.
940 This makes it possible to do global cycling without having to use S-TAB or
941 \\[universal-argument] TAB. For this special case to work, the first line
942 of the buffer must not be a headline -- it may be empty or some other text.
943 When used in this way, `org-cycle-hook' is disabled temporarily to make
944 sure the cursor stays at the beginning of the buffer. When this option is
945 nil, don't do anything special at the beginning of the buffer."
946 :group 'org-cycle
947 :type 'boolean)
949 (defcustom org-cycle-level-after-item/entry-creation t
950 "Non-nil means cycle entry level or item indentation in new empty entries.
952 When the cursor is at the end of an empty headline, i.e with only stars
953 and maybe a TODO keyword, TAB will then switch the entry to become a child,
954 and then all possible ancestor states, before returning to the original state.
955 This makes data entry extremely fast: M-RET to create a new headline,
956 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
958 When the cursor is at the end of an empty plain list item, one TAB will
959 make it a subitem, two or more tabs will back up to make this an item
960 higher up in the item hierarchy."
961 :group 'org-cycle
962 :type 'boolean)
964 (defcustom org-cycle-emulate-tab t
965 "Where should `org-cycle' emulate TAB.
966 nil Never
967 white Only in completely white lines
968 whitestart Only at the beginning of lines, before the first non-white char
969 t Everywhere except in headlines
970 exc-hl-bol Everywhere except at the start of a headline
971 If TAB is used in a place where it does not emulate TAB, the current subtree
972 visibility is cycled."
973 :group 'org-cycle
974 :type '(choice (const :tag "Never" nil)
975 (const :tag "Only in completely white lines" white)
976 (const :tag "Before first char in a line" whitestart)
977 (const :tag "Everywhere except in headlines" t)
978 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
981 (defcustom org-cycle-separator-lines 2
982 "Number of empty lines needed to keep an empty line between collapsed trees.
983 If you leave an empty line between the end of a subtree and the following
984 headline, this empty line is hidden when the subtree is folded.
985 Org-mode will leave (exactly) one empty line visible if the number of
986 empty lines is equal or larger to the number given in this variable.
987 So the default 2 means at least 2 empty lines after the end of a subtree
988 are needed to produce free space between a collapsed subtree and the
989 following headline.
991 If the number is negative, and the number of empty lines is at least -N,
992 all empty lines are shown.
994 Special case: when 0, never leave empty lines in collapsed view."
995 :group 'org-cycle
996 :type 'integer)
997 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
999 (defcustom org-pre-cycle-hook nil
1000 "Hook that is run before visibility cycling is happening.
1001 The function(s) in this hook must accept a single argument which indicates
1002 the new state that will be set right after running this hook. The
1003 argument is a symbol. Before a global state change, it can have the values
1004 `overview', `content', or `all'. Before a local state change, it can have
1005 the values `folded', `children', or `subtree'."
1006 :group 'org-cycle
1007 :type 'hook)
1009 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1010 org-cycle-hide-drawers
1011 org-cycle-hide-inline-tasks
1012 org-cycle-show-empty-lines
1013 org-optimize-window-after-visibility-change)
1014 "Hook that is run after `org-cycle' has changed the buffer visibility.
1015 The function(s) in this hook must accept a single argument which indicates
1016 the new state that was set by the most recent `org-cycle' command. The
1017 argument is a symbol. After a global state change, it can have the values
1018 `overview', `contents', or `all'. After a local state change, it can have
1019 the values `folded', `children', or `subtree'."
1020 :group 'org-cycle
1021 :type 'hook)
1023 (defgroup org-edit-structure nil
1024 "Options concerning structure editing in Org-mode."
1025 :tag "Org Edit Structure"
1026 :group 'org-structure)
1028 (defcustom org-odd-levels-only nil
1029 "Non-nil means skip even levels and only use odd levels for the outline.
1030 This has the effect that two stars are being added/taken away in
1031 promotion/demotion commands. It also influences how levels are
1032 handled by the exporters.
1033 Changing it requires restart of `font-lock-mode' to become effective
1034 for fontification also in regions already fontified.
1035 You may also set this on a per-file basis by adding one of the following
1036 lines to the buffer:
1038 #+STARTUP: odd
1039 #+STARTUP: oddeven"
1040 :group 'org-edit-structure
1041 :group 'org-appearance
1042 :type 'boolean)
1044 (defcustom org-adapt-indentation t
1045 "Non-nil means adapt indentation to outline node level.
1047 When this variable is set, Org assumes that you write outlines by
1048 indenting text in each node to align with the headline (after the stars).
1049 The following issues are influenced by this variable:
1051 - When this is set and the *entire* text in an entry is indented, the
1052 indentation is increased by one space in a demotion command, and
1053 decreased by one in a promotion command. If any line in the entry
1054 body starts with text at column 0, indentation is not changed at all.
1056 - Property drawers and planning information is inserted indented when
1057 this variable s set. When nil, they will not be indented.
1059 - TAB indents a line relative to context. The lines below a headline
1060 will be indented when this variable is set.
1062 Note that this is all about true indentation, by adding and removing
1063 space characters. See also `org-indent.el' which does level-dependent
1064 indentation in a virtual way, i.e. at display time in Emacs."
1065 :group 'org-edit-structure
1066 :type 'boolean)
1068 (defcustom org-special-ctrl-a/e nil
1069 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1071 When t, `C-a' will bring back the cursor to the beginning of the
1072 headline text, i.e. after the stars and after a possible TODO
1073 keyword. In an item, this will be the position after bullet and
1074 check-box, if any. When the cursor is already at that position,
1075 another `C-a' will bring it to the beginning of the line.
1077 `C-e' will jump to the end of the headline, ignoring the presence
1078 of tags in the headline. A second `C-e' will then jump to the
1079 true end of the line, after any tags. This also means that, when
1080 this variable is non-nil, `C-e' also will never jump beyond the
1081 end of the heading of a folded section, i.e. not after the
1082 ellipses.
1084 When set to the symbol `reversed', the first `C-a' or `C-e' works
1085 normally, going to the true line boundary first. Only a directly
1086 following, identical keypress will bring the cursor to the
1087 special positions.
1089 This may also be a cons cell where the behavior for `C-a' and
1090 `C-e' is set separately."
1091 :group 'org-edit-structure
1092 :type '(choice
1093 (const :tag "off" nil)
1094 (const :tag "on: after stars/bullet and before tags first" t)
1095 (const :tag "reversed: true line boundary first" reversed)
1096 (cons :tag "Set C-a and C-e separately"
1097 (choice :tag "Special C-a"
1098 (const :tag "off" nil)
1099 (const :tag "on: after stars/bullet first" t)
1100 (const :tag "reversed: before stars/bullet first" reversed))
1101 (choice :tag "Special C-e"
1102 (const :tag "off" nil)
1103 (const :tag "on: before tags first" t)
1104 (const :tag "reversed: after tags first" reversed)))))
1105 (if (fboundp 'defvaralias)
1106 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1108 (defcustom org-special-ctrl-k nil
1109 "Non-nil means `C-k' will behave specially in headlines.
1110 When nil, `C-k' will call the default `kill-line' command.
1111 When t, the following will happen while the cursor is in the headline:
1113 - When the cursor is at the beginning of a headline, kill the entire
1114 line and possible the folded subtree below the line.
1115 - When in the middle of the headline text, kill the headline up to the tags.
1116 - When after the headline text, kill the tags."
1117 :group 'org-edit-structure
1118 :type 'boolean)
1120 (defcustom org-ctrl-k-protect-subtree nil
1121 "Non-nil means, do not delete a hidden subtree with C-k.
1122 When set to the symbol `error', simply throw an error when C-k is
1123 used to kill (part-of) a headline that has hidden text behind it.
1124 Any other non-nil value will result in a query to the user, if it is
1125 OK to kill that hidden subtree. When nil, kill without remorse."
1126 :group 'org-edit-structure
1127 :version "24.1"
1128 :type '(choice
1129 (const :tag "Do not protect hidden subtrees" nil)
1130 (const :tag "Protect hidden subtrees with a security query" t)
1131 (const :tag "Never kill a hidden subtree with C-k" error)))
1133 (defcustom org-catch-invisible-edits nil
1134 "Check if in invisible region before inserting or deleting a character.
1135 Valid values are:
1137 nil Do not check, so just do invisible edits.
1138 error Throw an error and do nothing.
1139 show Make point visible, and do the requested edit.
1140 show-and-error Make point visible, then throw an error and abort the edit.
1141 smart Make point visible, and do insertion/deletion if it is
1142 adjacent to visible text and the change feels predictable.
1143 Never delete a previously invisible character or add in the
1144 middle or right after an invisible region. Basically, this
1145 allows insertion and backward-delete right before ellipses.
1146 FIXME: maybe in this case we should not even show?"
1147 :group 'org-edit-structure
1148 :version "24.1"
1149 :type '(choice
1150 (const :tag "Do not check" nil)
1151 (const :tag "Throw error when trying to edit" error)
1152 (const :tag "Unhide, but do not do the edit" show-and-error)
1153 (const :tag "Show invisible part and do the edit" show)
1154 (const :tag "Be smart and do the right thing" smart)))
1156 (defcustom org-yank-folded-subtrees t
1157 "Non-nil means when yanking subtrees, fold them.
1158 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1159 it starts with a heading and all other headings in it are either children
1160 or siblings, then fold all the subtrees. However, do this only if no
1161 text after the yank would be swallowed into a folded tree by this action."
1162 :group 'org-edit-structure
1163 :type 'boolean)
1165 (defcustom org-yank-adjusted-subtrees nil
1166 "Non-nil means when yanking subtrees, adjust the level.
1167 With this setting, `org-paste-subtree' is used to insert the subtree, see
1168 this function for details."
1169 :group 'org-edit-structure
1170 :type 'boolean)
1172 (defcustom org-M-RET-may-split-line '((default . t))
1173 "Non-nil means M-RET will split the line at the cursor position.
1174 When nil, it will go to the end of the line before making a
1175 new line.
1176 You may also set this option in a different way for different
1177 contexts. Valid contexts are:
1179 headline when creating a new headline
1180 item when creating a new item
1181 table in a table field
1182 default the value to be used for all contexts not explicitly
1183 customized"
1184 :group 'org-structure
1185 :group 'org-table
1186 :type '(choice
1187 (const :tag "Always" t)
1188 (const :tag "Never" nil)
1189 (repeat :greedy t :tag "Individual contexts"
1190 (cons
1191 (choice :tag "Context"
1192 (const headline)
1193 (const item)
1194 (const table)
1195 (const default))
1196 (boolean)))))
1199 (defcustom org-insert-heading-respect-content nil
1200 "Non-nil means insert new headings after the current subtree.
1201 When nil, the new heading is created directly after the current line.
1202 The commands \\[org-insert-heading-respect-content] and
1203 \\[org-insert-todo-heading-respect-content] turn this variable on
1204 for the duration of the command."
1205 :group 'org-structure
1206 :type 'boolean)
1208 (defcustom org-blank-before-new-entry '((heading . auto)
1209 (plain-list-item . auto))
1210 "Should `org-insert-heading' leave a blank line before new heading/item?
1211 The value is an alist, with `heading' and `plain-list-item' as CAR,
1212 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1213 which case Org will look at the surrounding headings/items and try to
1214 make an intelligent decision whether to insert a blank line or not.
1216 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1217 set, the setting here is ignored and no empty line is inserted, to avoid
1218 breaking the list structure."
1219 :group 'org-edit-structure
1220 :type '(list
1221 (cons (const heading)
1222 (choice (const :tag "Never" nil)
1223 (const :tag "Always" t)
1224 (const :tag "Auto" auto)))
1225 (cons (const plain-list-item)
1226 (choice (const :tag "Never" nil)
1227 (const :tag "Always" t)
1228 (const :tag "Auto" auto)))))
1230 (defcustom org-insert-heading-hook nil
1231 "Hook being run after inserting a new heading."
1232 :group 'org-edit-structure
1233 :type 'hook)
1235 (defcustom org-enable-fixed-width-editor t
1236 "Non-nil means lines starting with \":\" are treated as fixed-width.
1237 This currently only means they are never auto-wrapped.
1238 When nil, such lines will be treated like ordinary lines.
1239 See also the QUOTE keyword."
1240 :group 'org-edit-structure
1241 :type 'boolean)
1243 (defcustom org-goto-auto-isearch t
1244 "Non-nil means typing characters in `org-goto' starts incremental search.
1245 When nil, you can use these keybindings to navigate the buffer:
1247 q Quit the org-goto interface
1248 n Go to the next visible heading
1249 p Go to the previous visible heading
1250 f Go one heading forward on same level
1251 b Go one heading backward on same level
1252 u Go one heading up"
1253 :group 'org-edit-structure
1254 :type 'boolean)
1256 (defgroup org-sparse-trees nil
1257 "Options concerning sparse trees in Org-mode."
1258 :tag "Org Sparse Trees"
1259 :group 'org-structure)
1261 (defcustom org-highlight-sparse-tree-matches t
1262 "Non-nil means highlight all matches that define a sparse tree.
1263 The highlights will automatically disappear the next time the buffer is
1264 changed by an edit command."
1265 :group 'org-sparse-trees
1266 :type 'boolean)
1268 (defcustom org-remove-highlights-with-change t
1269 "Non-nil means any change to the buffer will remove temporary highlights.
1270 Such highlights are created by `org-occur' and `org-clock-display'.
1271 When nil, `C-c C-c needs to be used to get rid of the highlights.
1272 The highlights created by `org-preview-latex-fragment' always need
1273 `C-c C-c' to be removed."
1274 :group 'org-sparse-trees
1275 :group 'org-time
1276 :type 'boolean)
1279 (defcustom org-occur-hook '(org-first-headline-recenter)
1280 "Hook that is run after `org-occur' has constructed a sparse tree.
1281 This can be used to recenter the window to show as much of the structure
1282 as possible."
1283 :group 'org-sparse-trees
1284 :type 'hook)
1286 (defgroup org-imenu-and-speedbar nil
1287 "Options concerning imenu and speedbar in Org-mode."
1288 :tag "Org Imenu and Speedbar"
1289 :group 'org-structure)
1291 (defcustom org-imenu-depth 2
1292 "The maximum level for Imenu access to Org-mode headlines.
1293 This also applied for speedbar access."
1294 :group 'org-imenu-and-speedbar
1295 :type 'integer)
1297 (defgroup org-table nil
1298 "Options concerning tables in Org-mode."
1299 :tag "Org Table"
1300 :group 'org)
1302 (defcustom org-enable-table-editor 'optimized
1303 "Non-nil means lines starting with \"|\" are handled by the table editor.
1304 When nil, such lines will be treated like ordinary lines.
1306 When equal to the symbol `optimized', the table editor will be optimized to
1307 do the following:
1308 - Automatic overwrite mode in front of whitespace in table fields.
1309 This makes the structure of the table stay in tact as long as the edited
1310 field does not exceed the column width.
1311 - Minimize the number of realigns. Normally, the table is aligned each time
1312 TAB or RET are pressed to move to another field. With optimization this
1313 happens only if changes to a field might have changed the column width.
1314 Optimization requires replacing the functions `self-insert-command',
1315 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1316 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1317 very good at guessing when a re-align will be necessary, but you can always
1318 force one with \\[org-ctrl-c-ctrl-c].
1320 If you would like to use the optimized version in Org-mode, but the
1321 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1323 This variable can be used to turn on and off the table editor during a session,
1324 but in order to toggle optimization, a restart is required.
1326 See also the variable `org-table-auto-blank-field'."
1327 :group 'org-table
1328 :type '(choice
1329 (const :tag "off" nil)
1330 (const :tag "on" t)
1331 (const :tag "on, optimized" optimized)))
1333 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1334 (version<= emacs-version "24.1"))
1335 "Non-nil means cluster self-insert commands for undo when possible.
1336 If this is set, then, like in the Emacs command loop, 20 consecutive
1337 characters will be undone together.
1338 This is configurable, because there is some impact on typing performance."
1339 :group 'org-table
1340 :type 'boolean)
1342 (defcustom org-table-tab-recognizes-table.el t
1343 "Non-nil means TAB will automatically notice a table.el table.
1344 When it sees such a table, it moves point into it and - if necessary -
1345 calls `table-recognize-table'."
1346 :group 'org-table-editing
1347 :type 'boolean)
1349 (defgroup org-link nil
1350 "Options concerning links in Org-mode."
1351 :tag "Org Link"
1352 :group 'org)
1354 (defvar org-link-abbrev-alist-local nil
1355 "Buffer-local version of `org-link-abbrev-alist', which see.
1356 The value of this is taken from the #+LINK lines.")
1357 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1359 (defcustom org-link-abbrev-alist nil
1360 "Alist of link abbreviations.
1361 The car of each element is a string, to be replaced at the start of a link.
1362 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1363 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1365 [[linkkey:tag][description]]
1367 The 'linkkey' must be a word word, starting with a letter, followed
1368 by letters, numbers, '-' or '_'.
1370 If REPLACE is a string, the tag will simply be appended to create the link.
1371 If the string contains \"%s\", the tag will be inserted there. If the string
1372 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1373 at that point (see the function `url-hexify-string'). If the string contains
1374 the specifier \"%(my-function)\", then the custom function `my-function' will
1375 be invoked: this function takes the tag as its only argument and must return
1376 a string.
1378 REPLACE may also be a function that will be called with the tag as the
1379 only argument to create the link, which should be returned as a string.
1381 See the manual for examples."
1382 :group 'org-link
1383 :type '(repeat
1384 (cons
1385 (string :tag "Protocol")
1386 (choice
1387 (string :tag "Format")
1388 (function)))))
1390 (defcustom org-descriptive-links t
1391 "Non-nil means Org will display descriptive links.
1392 E.g. [[http://orgmode.org][Org website]] will be displayed as
1393 \"Org Website\", hiding the link itself and just displaying its
1394 description. When set to `nil', Org will display the full links
1395 literally.
1397 You can interactively set the value of this variable by calling
1398 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1399 :group 'org-link
1400 :type 'boolean)
1402 (defcustom org-link-file-path-type 'adaptive
1403 "How the path name in file links should be stored.
1404 Valid values are:
1406 relative Relative to the current directory, i.e. the directory of the file
1407 into which the link is being inserted.
1408 absolute Absolute path, if possible with ~ for home directory.
1409 noabbrev Absolute path, no abbreviation of home directory.
1410 adaptive Use relative path for files in the current directory and sub-
1411 directories of it. For other files, use an absolute path."
1412 :group 'org-link
1413 :type '(choice
1414 (const relative)
1415 (const absolute)
1416 (const noabbrev)
1417 (const adaptive)))
1419 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1420 "Types of links that should be activated in Org-mode files.
1421 This is a list of symbols, each leading to the activation of a certain link
1422 type. In principle, it does not hurt to turn on most link types - there may
1423 be a small gain when turning off unused link types. The types are:
1425 bracket The recommended [[link][description]] or [[link]] links with hiding.
1426 angle Links in angular brackets that may contain whitespace like
1427 <bbdb:Carsten Dominik>.
1428 plain Plain links in normal text, no whitespace, like http://google.com.
1429 radio Text that is matched by a radio target, see manual for details.
1430 tag Tag settings in a headline (link to tag search).
1431 date Time stamps (link to calendar).
1432 footnote Footnote labels.
1434 Changing this variable requires a restart of Emacs to become effective."
1435 :group 'org-link
1436 :type '(set :greedy t
1437 (const :tag "Double bracket links" bracket)
1438 (const :tag "Angular bracket links" angle)
1439 (const :tag "Plain text links" plain)
1440 (const :tag "Radio target matches" radio)
1441 (const :tag "Tags" tag)
1442 (const :tag "Timestamps" date)
1443 (const :tag "Footnotes" footnote)))
1445 (defcustom org-make-link-description-function nil
1446 "Function to use for generating link descriptions from links.
1447 When nil, the link location will be used. This function must take
1448 two parameters: the first one is the link, the second one is the
1449 description generated by `org-insert-link'. The function should
1450 return the description to use."
1451 :group 'org-link
1452 :type 'function)
1454 (defgroup org-link-store nil
1455 "Options concerning storing links in Org-mode."
1456 :tag "Org Store Link"
1457 :group 'org-link)
1459 (defcustom org-url-hexify-p t
1460 "When non-nil, hexify URL when creating a link."
1461 :type 'boolean
1462 :version "24.3"
1463 :group 'org-link-store)
1465 (defcustom org-email-link-description-format "Email %c: %.30s"
1466 "Format of the description part of a link to an email or usenet message.
1467 The following %-escapes will be replaced by corresponding information:
1469 %F full \"From\" field
1470 %f name, taken from \"From\" field, address if no name
1471 %T full \"To\" field
1472 %t first name in \"To\" field, address if no name
1473 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1474 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1475 %s subject
1476 %d date
1477 %m message-id.
1479 You may use normal field width specification between the % and the letter.
1480 This is for example useful to limit the length of the subject.
1482 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1483 :group 'org-link-store
1484 :type 'string)
1486 (defcustom org-from-is-user-regexp
1487 (let (r1 r2)
1488 (when (and user-mail-address (not (string= user-mail-address "")))
1489 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1490 (when (and user-full-name (not (string= user-full-name "")))
1491 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1492 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1493 "Regexp matched against the \"From:\" header of an email or usenet message.
1494 It should match if the message is from the user him/herself."
1495 :group 'org-link-store
1496 :type 'regexp)
1498 (defcustom org-context-in-file-links t
1499 "Non-nil means file links from `org-store-link' contain context.
1500 A search string will be added to the file name with :: as separator and
1501 used to find the context when the link is activated by the command
1502 `org-open-at-point'. When this option is t, the entire active region
1503 will be placed in the search string of the file link. If set to a
1504 positive integer, only the first n lines of context will be stored.
1506 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1507 negates this setting for the duration of the command."
1508 :group 'org-link-store
1509 :type '(choice boolean integer))
1511 (defcustom org-keep-stored-link-after-insertion nil
1512 "Non-nil means keep link in list for entire session.
1514 The command `org-store-link' adds a link pointing to the current
1515 location to an internal list. These links accumulate during a session.
1516 The command `org-insert-link' can be used to insert links into any
1517 Org-mode file (offering completion for all stored links). When this
1518 option is nil, every link which has been inserted once using \\[org-insert-link]
1519 will be removed from the list, to make completing the unused links
1520 more efficient."
1521 :group 'org-link-store
1522 :type 'boolean)
1524 (defgroup org-link-follow nil
1525 "Options concerning following links in Org-mode."
1526 :tag "Org Follow Link"
1527 :group 'org-link)
1529 (defcustom org-link-translation-function nil
1530 "Function to translate links with different syntax to Org syntax.
1531 This can be used to translate links created for example by the Planner
1532 or emacs-wiki packages to Org syntax.
1533 The function must accept two parameters, a TYPE containing the link
1534 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1535 which is everything after the link protocol. It should return a cons
1536 with possibly modified values of type and path.
1537 Org contains a function for this, so if you set this variable to
1538 `org-translate-link-from-planner', you should be able follow many
1539 links created by planner."
1540 :group 'org-link-follow
1541 :type 'function)
1543 (defcustom org-follow-link-hook nil
1544 "Hook that is run after a link has been followed."
1545 :group 'org-link-follow
1546 :type 'hook)
1548 (defcustom org-tab-follows-link nil
1549 "Non-nil means on links TAB will follow the link.
1550 Needs to be set before org.el is loaded.
1551 This really should not be used, it does not make sense, and the
1552 implementation is bad."
1553 :group 'org-link-follow
1554 :type 'boolean)
1556 (defcustom org-return-follows-link nil
1557 "Non-nil means on links RET will follow the link."
1558 :group 'org-link-follow
1559 :type 'boolean)
1561 (defcustom org-mouse-1-follows-link
1562 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1563 "Non-nil means mouse-1 on a link will follow the link.
1564 A longer mouse click will still set point. Does not work on XEmacs.
1565 Needs to be set before org.el is loaded."
1566 :group 'org-link-follow
1567 :type 'boolean)
1569 (defcustom org-mark-ring-length 4
1570 "Number of different positions to be recorded in the ring.
1571 Changing this requires a restart of Emacs to work correctly."
1572 :group 'org-link-follow
1573 :type 'integer)
1575 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1576 "Non-nil means internal links in Org files must exactly match a headline.
1577 When nil, the link search tries to match a phrase with all words
1578 in the search text."
1579 :group 'org-link-follow
1580 :version "24.1"
1581 :type '(choice
1582 (const :tag "Use fuzzy text search" nil)
1583 (const :tag "Match only exact headline" t)
1584 (const :tag "Match exact headline or query to create it"
1585 query-to-create)))
1587 (defcustom org-link-frame-setup
1588 '((vm . vm-visit-folder-other-frame)
1589 (vm-imap . vm-visit-imap-folder-other-frame)
1590 (gnus . org-gnus-no-new-news)
1591 (file . find-file-other-window)
1592 (wl . wl-other-frame))
1593 "Setup the frame configuration for following links.
1594 When following a link with Emacs, it may often be useful to display
1595 this link in another window or frame. This variable can be used to
1596 set this up for the different types of links.
1597 For VM, use any of
1598 `vm-visit-folder'
1599 `vm-visit-folder-other-window'
1600 `vm-visit-folder-other-frame'
1601 For Gnus, use any of
1602 `gnus'
1603 `gnus-other-frame'
1604 `org-gnus-no-new-news'
1605 For FILE, use any of
1606 `find-file'
1607 `find-file-other-window'
1608 `find-file-other-frame'
1609 For Wanderlust use any of
1610 `wl'
1611 `wl-other-frame'
1612 For the calendar, use the variable `calendar-setup'.
1613 For BBDB, it is currently only possible to display the matches in
1614 another window."
1615 :group 'org-link-follow
1616 :type '(list
1617 (cons (const vm)
1618 (choice
1619 (const vm-visit-folder)
1620 (const vm-visit-folder-other-window)
1621 (const vm-visit-folder-other-frame)))
1622 (cons (const gnus)
1623 (choice
1624 (const gnus)
1625 (const gnus-other-frame)
1626 (const org-gnus-no-new-news)))
1627 (cons (const file)
1628 (choice
1629 (const find-file)
1630 (const find-file-other-window)
1631 (const find-file-other-frame)))
1632 (cons (const wl)
1633 (choice
1634 (const wl)
1635 (const wl-other-frame)))))
1637 (defcustom org-display-internal-link-with-indirect-buffer nil
1638 "Non-nil means use indirect buffer to display infile links.
1639 Activating internal links (from one location in a file to another location
1640 in the same file) normally just jumps to the location. When the link is
1641 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1642 is displayed in
1643 another window. When this option is set, the other window actually displays
1644 an indirect buffer clone of the current buffer, to avoid any visibility
1645 changes to the current buffer."
1646 :group 'org-link-follow
1647 :type 'boolean)
1649 (defcustom org-open-non-existing-files nil
1650 "Non-nil means `org-open-file' will open non-existing files.
1651 When nil, an error will be generated.
1652 This variable applies only to external applications because they
1653 might choke on non-existing files. If the link is to a file that
1654 will be opened in Emacs, the variable is ignored."
1655 :group 'org-link-follow
1656 :type 'boolean)
1658 (defcustom org-open-directory-means-index-dot-org nil
1659 "Non-nil means a link to a directory really means to index.org.
1660 When nil, following a directory link will run dired or open a finder/explorer
1661 window on that directory."
1662 :group 'org-link-follow
1663 :type 'boolean)
1665 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1666 "Function and arguments to call for following mailto links.
1667 This is a list with the first element being a Lisp function, and the
1668 remaining elements being arguments to the function. In string arguments,
1669 %a will be replaced by the address, and %s will be replaced by the subject
1670 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1671 :group 'org-link-follow
1672 :type '(choice
1673 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1674 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1675 (const :tag "message-mail" (message-mail "%a" "%s"))
1676 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1678 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1679 "Non-nil means ask for confirmation before executing shell links.
1680 Shell links can be dangerous: just think about a link
1682 [[shell:rm -rf ~/*][Google Search]]
1684 This link would show up in your Org-mode document as \"Google Search\",
1685 but really it would remove your entire home directory.
1686 Therefore we advise against setting this variable to nil.
1687 Just change it to `y-or-n-p' if you want to confirm with a
1688 single keystroke rather than having to type \"yes\"."
1689 :group 'org-link-follow
1690 :type '(choice
1691 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1692 (const :tag "with y-or-n (faster)" y-or-n-p)
1693 (const :tag "no confirmation (dangerous)" nil)))
1694 (put 'org-confirm-shell-link-function
1695 'safe-local-variable
1696 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1698 (defcustom org-confirm-shell-link-not-regexp ""
1699 "A regexp to skip confirmation for shell links."
1700 :group 'org-link-follow
1701 :version "24.1"
1702 :type 'regexp)
1704 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1705 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1706 Elisp links can be dangerous: just think about a link
1708 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1710 This link would show up in your Org-mode document as \"Google Search\",
1711 but really it would remove your entire home directory.
1712 Therefore we advise against setting this variable to nil.
1713 Just change it to `y-or-n-p' if you want to confirm with a
1714 single keystroke rather than having to type \"yes\"."
1715 :group 'org-link-follow
1716 :type '(choice
1717 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1718 (const :tag "with y-or-n (faster)" y-or-n-p)
1719 (const :tag "no confirmation (dangerous)" nil)))
1720 (put 'org-confirm-shell-link-function
1721 'safe-local-variable
1722 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1724 (defcustom org-confirm-elisp-link-not-regexp ""
1725 "A regexp to skip confirmation for Elisp links."
1726 :group 'org-link-follow
1727 :version "24.1"
1728 :type 'regexp)
1730 (defconst org-file-apps-defaults-gnu
1731 '((remote . emacs)
1732 (system . mailcap)
1733 (t . mailcap))
1734 "Default file applications on a UNIX or GNU/Linux system.
1735 See `org-file-apps'.")
1737 (defconst org-file-apps-defaults-macosx
1738 '((remote . emacs)
1739 (t . "open %s")
1740 (system . "open %s")
1741 ("ps.gz" . "gv %s")
1742 ("eps.gz" . "gv %s")
1743 ("dvi" . "xdvi %s")
1744 ("fig" . "xfig %s"))
1745 "Default file applications on a MacOS X system.
1746 The system \"open\" is known as a default, but we use X11 applications
1747 for some files for which the OS does not have a good default.
1748 See `org-file-apps'.")
1750 (defconst org-file-apps-defaults-windowsnt
1751 (list
1752 '(remote . emacs)
1753 (cons t
1754 (list (if (featurep 'xemacs)
1755 'mswindows-shell-execute
1756 'w32-shell-execute)
1757 "open" 'file))
1758 (cons 'system
1759 (list (if (featurep 'xemacs)
1760 'mswindows-shell-execute
1761 'w32-shell-execute)
1762 "open" 'file)))
1763 "Default file applications on a Windows NT system.
1764 The system \"open\" is used for most files.
1765 See `org-file-apps'.")
1767 (defcustom org-file-apps
1769 (auto-mode . emacs)
1770 ("\\.mm\\'" . default)
1771 ("\\.x?html?\\'" . default)
1772 ("\\.pdf\\'" . default)
1774 "External applications for opening `file:path' items in a document.
1775 Org-mode uses system defaults for different file types, but
1776 you can use this variable to set the application for a given file
1777 extension. The entries in this list are cons cells where the car identifies
1778 files and the cdr the corresponding command. Possible values for the
1779 file identifier are
1780 \"string\" A string as a file identifier can be interpreted in different
1781 ways, depending on its contents:
1783 - Alphanumeric characters only:
1784 Match links with this file extension.
1785 Example: (\"pdf\" . \"evince %s\")
1786 to open PDFs with evince.
1788 - Regular expression: Match links where the
1789 filename matches the regexp. If you want to
1790 use groups here, use shy groups.
1792 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1793 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1794 to open *.html and *.xhtml with firefox.
1796 - Regular expression which contains (non-shy) groups:
1797 Match links where the whole link, including \"::\", and
1798 anything after that, matches the regexp.
1799 In a custom command string, %1, %2, etc. are replaced with
1800 the parts of the link that were matched by the groups.
1801 For backwards compatibility, if a command string is given
1802 that does not use any of the group matches, this case is
1803 handled identically to the second one (i.e. match against
1804 file name only).
1805 In a custom lisp form, you can access the group matches with
1806 (match-string n link).
1808 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1809 to open [[file:document.pdf::5]] with evince at page 5.
1811 `directory' Matches a directory
1812 `remote' Matches a remote file, accessible through tramp or efs.
1813 Remote files most likely should be visited through Emacs
1814 because external applications cannot handle such paths.
1815 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1816 so all files Emacs knows how to handle. Using this with
1817 command `emacs' will open most files in Emacs. Beware that this
1818 will also open html files inside Emacs, unless you add
1819 (\"html\" . default) to the list as well.
1820 t Default for files not matched by any of the other options.
1821 `system' The system command to open files, like `open' on Windows
1822 and Mac OS X, and mailcap under GNU/Linux. This is the command
1823 that will be selected if you call `C-c C-o' with a double
1824 \\[universal-argument] \\[universal-argument] prefix.
1826 Possible values for the command are:
1827 `emacs' The file will be visited by the current Emacs process.
1828 `default' Use the default application for this file type, which is the
1829 association for t in the list, most likely in the system-specific
1830 part.
1831 This can be used to overrule an unwanted setting in the
1832 system-specific variable.
1833 `system' Use the system command for opening files, like \"open\".
1834 This command is specified by the entry whose car is `system'.
1835 Most likely, the system-specific version of this variable
1836 does define this command, but you can overrule/replace it
1837 here.
1838 string A command to be executed by a shell; %s will be replaced
1839 by the path to the file.
1840 sexp A Lisp form which will be evaluated. The file path will
1841 be available in the Lisp variable `file'.
1842 For more examples, see the system specific constants
1843 `org-file-apps-defaults-macosx'
1844 `org-file-apps-defaults-windowsnt'
1845 `org-file-apps-defaults-gnu'."
1846 :group 'org-link-follow
1847 :type '(repeat
1848 (cons (choice :value ""
1849 (string :tag "Extension")
1850 (const :tag "System command to open files" system)
1851 (const :tag "Default for unrecognized files" t)
1852 (const :tag "Remote file" remote)
1853 (const :tag "Links to a directory" directory)
1854 (const :tag "Any files that have Emacs modes"
1855 auto-mode))
1856 (choice :value ""
1857 (const :tag "Visit with Emacs" emacs)
1858 (const :tag "Use default" default)
1859 (const :tag "Use the system command" system)
1860 (string :tag "Command")
1861 (sexp :tag "Lisp form")))))
1863 (defcustom org-doi-server-url "http://dx.doi.org/"
1864 "The URL of the DOI server."
1865 :type 'string
1866 :version "24.3"
1867 :group 'org-link-follow)
1869 (defgroup org-refile nil
1870 "Options concerning refiling entries in Org-mode."
1871 :tag "Org Refile"
1872 :group 'org)
1874 (defcustom org-directory "~/org"
1875 "Directory with org files.
1876 This is just a default location to look for Org files. There is no need
1877 at all to put your files into this directory. It is only used in the
1878 following situations:
1880 1. When a capture template specifies a target file that is not an
1881 absolute path. The path will then be interpreted relative to
1882 `org-directory'
1883 2. When a capture note is filed away in an interactive way (when exiting the
1884 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1885 with `org-directory' as the default path."
1886 :group 'org-refile
1887 :group 'org-remember
1888 :group 'org-capture
1889 :type 'directory)
1891 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1892 "Default target for storing notes.
1893 Used as a fall back file for org-remember.el and org-capture.el, for
1894 templates that do not specify a target file."
1895 :group 'org-refile
1896 :group 'org-remember
1897 :group 'org-capture
1898 :type '(choice
1899 (const :tag "Default from remember-data-file" nil)
1900 file))
1902 (defcustom org-goto-interface 'outline
1903 "The default interface to be used for `org-goto'.
1904 Allowed values are:
1905 outline The interface shows an outline of the relevant file
1906 and the correct heading is found by moving through
1907 the outline or by searching with incremental search.
1908 outline-path-completion Headlines in the current buffer are offered via
1909 completion. This is the interface also used by
1910 the refile command."
1911 :group 'org-refile
1912 :type '(choice
1913 (const :tag "Outline" outline)
1914 (const :tag "Outline-path-completion" outline-path-completion)))
1916 (defcustom org-goto-max-level 5
1917 "Maximum target level when running `org-goto' with refile interface."
1918 :group 'org-refile
1919 :type 'integer)
1921 (defcustom org-reverse-note-order nil
1922 "Non-nil means store new notes at the beginning of a file or entry.
1923 When nil, new notes will be filed to the end of a file or entry.
1924 This can also be a list with cons cells of regular expressions that
1925 are matched against file names, and values."
1926 :group 'org-remember
1927 :group 'org-capture
1928 :group 'org-refile
1929 :type '(choice
1930 (const :tag "Reverse always" t)
1931 (const :tag "Reverse never" nil)
1932 (repeat :tag "By file name regexp"
1933 (cons regexp boolean))))
1935 (defcustom org-log-refile nil
1936 "Information to record when a task is refiled.
1938 Possible values are:
1940 nil Don't add anything
1941 time Add a time stamp to the task
1942 note Prompt for a note and add it with template `org-log-note-headings'
1944 This option can also be set with on a per-file-basis with
1946 #+STARTUP: nologrefile
1947 #+STARTUP: logrefile
1948 #+STARTUP: lognoterefile
1950 You can have local logging settings for a subtree by setting the LOGGING
1951 property to one or more of these keywords.
1953 When bulk-refiling from the agenda, the value `note' is forbidden and
1954 will temporarily be changed to `time'."
1955 :group 'org-refile
1956 :group 'org-progress
1957 :version "24.1"
1958 :type '(choice
1959 (const :tag "No logging" nil)
1960 (const :tag "Record timestamp" time)
1961 (const :tag "Record timestamp with note." note)))
1963 (defcustom org-refile-targets nil
1964 "Targets for refiling entries with \\[org-refile].
1965 This is a list of cons cells. Each cell contains:
1966 - a specification of the files to be considered, either a list of files,
1967 or a symbol whose function or variable value will be used to retrieve
1968 a file name or a list of file names. If you use `org-agenda-files' for
1969 that, all agenda files will be scanned for targets. Nil means consider
1970 headings in the current buffer.
1971 - A specification of how to find candidate refile targets. This may be
1972 any of:
1973 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1974 This tag has to be present in all target headlines, inheritance will
1975 not be considered.
1976 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1977 todo keyword.
1978 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1979 headlines that are refiling targets.
1980 - a cons cell (:level . N). Any headline of level N is considered a target.
1981 Note that, when `org-odd-levels-only' is set, level corresponds to
1982 order in hierarchy, not to the number of stars.
1983 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1984 Note that, when `org-odd-levels-only' is set, level corresponds to
1985 order in hierarchy, not to the number of stars.
1987 Each element of this list generates a set of possible targets.
1988 The union of these sets is presented (with completion) to
1989 the user by `org-refile'.
1991 You can set the variable `org-refile-target-verify-function' to a function
1992 to verify each headline found by the simple criteria above.
1994 When this variable is nil, all top-level headlines in the current buffer
1995 are used, equivalent to the value `((nil . (:level . 1))'."
1996 :group 'org-refile
1997 :type '(repeat
1998 (cons
1999 (choice :value org-agenda-files
2000 (const :tag "All agenda files" org-agenda-files)
2001 (const :tag "Current buffer" nil)
2002 (function) (variable) (file))
2003 (choice :tag "Identify target headline by"
2004 (cons :tag "Specific tag" (const :value :tag) (string))
2005 (cons :tag "TODO keyword" (const :value :todo) (string))
2006 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2007 (cons :tag "Level number" (const :value :level) (integer))
2008 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2010 (defcustom org-refile-target-verify-function nil
2011 "Function to verify if the headline at point should be a refile target.
2012 The function will be called without arguments, with point at the
2013 beginning of the headline. It should return t and leave point
2014 where it is if the headline is a valid target for refiling.
2016 If the target should not be selected, the function must return nil.
2017 In addition to this, it may move point to a place from where the search
2018 should be continued. For example, the function may decide that the entire
2019 subtree of the current entry should be excluded and move point to the end
2020 of the subtree."
2021 :group 'org-refile
2022 :type 'function)
2024 (defcustom org-refile-use-cache nil
2025 "Non-nil means cache refile targets to speed up the process.
2026 The cache for a particular file will be updated automatically when
2027 the buffer has been killed, or when any of the marker used for flagging
2028 refile targets no longer points at a live buffer.
2029 If you have added new entries to a buffer that might themselves be targets,
2030 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2031 find that easier, `C-u C-u C-u C-c C-w'."
2032 :group 'org-refile
2033 :version "24.1"
2034 :type 'boolean)
2036 (defcustom org-refile-use-outline-path nil
2037 "Non-nil means provide refile targets as paths.
2038 So a level 3 headline will be available as level1/level2/level3.
2040 When the value is `file', also include the file name (without directory)
2041 into the path. In this case, you can also stop the completion after
2042 the file name, to get entries inserted as top level in the file.
2044 When `full-file-path', include the full file path."
2045 :group 'org-refile
2046 :type '(choice
2047 (const :tag "Not" nil)
2048 (const :tag "Yes" t)
2049 (const :tag "Start with file name" file)
2050 (const :tag "Start with full file path" full-file-path)))
2052 (defcustom org-outline-path-complete-in-steps t
2053 "Non-nil means complete the outline path in hierarchical steps.
2054 When Org-mode uses the refile interface to select an outline path
2055 \(see variable `org-refile-use-outline-path'), the completion of
2056 the path can be done is a single go, or if can be done in steps down
2057 the headline hierarchy. Going in steps is probably the best if you
2058 do not use a special completion package like `ido' or `icicles'.
2059 However, when using these packages, going in one step can be very
2060 fast, while still showing the whole path to the entry."
2061 :group 'org-refile
2062 :type 'boolean)
2064 (defcustom org-refile-allow-creating-parent-nodes nil
2065 "Non-nil means allow to create new nodes as refile targets.
2066 New nodes are then created by adding \"/new node name\" to the completion
2067 of an existing node. When the value of this variable is `confirm',
2068 new node creation must be confirmed by the user (recommended)
2069 When nil, the completion must match an existing entry.
2071 Note that, if the new heading is not seen by the criteria
2072 listed in `org-refile-targets', multiple instances of the same
2073 heading would be created by trying again to file under the new
2074 heading."
2075 :group 'org-refile
2076 :type '(choice
2077 (const :tag "Never" nil)
2078 (const :tag "Always" t)
2079 (const :tag "Prompt for confirmation" confirm)))
2081 (defcustom org-refile-active-region-within-subtree nil
2082 "Non-nil means also refile active region within a subtree.
2084 By default `org-refile' doesn't allow refiling regions if they
2085 don't contain a set of subtrees, but it might be convenient to
2086 do so sometimes: in that case, the first line of the region is
2087 converted to a headline before refiling."
2088 :group 'org-refile
2089 :version "24.1"
2090 :type 'boolean)
2092 (defgroup org-todo nil
2093 "Options concerning TODO items in Org-mode."
2094 :tag "Org TODO"
2095 :group 'org)
2097 (defgroup org-progress nil
2098 "Options concerning Progress logging in Org-mode."
2099 :tag "Org Progress"
2100 :group 'org-time)
2102 (defvar org-todo-interpretation-widgets
2103 '((:tag "Sequence (cycling hits every state)" sequence)
2104 (:tag "Type (cycling directly to DONE)" type))
2105 "The available interpretation symbols for customizing `org-todo-keywords'.
2106 Interested libraries should add to this list.")
2108 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2109 "List of TODO entry keyword sequences and their interpretation.
2110 \\<org-mode-map>This is a list of sequences.
2112 Each sequence starts with a symbol, either `sequence' or `type',
2113 indicating if the keywords should be interpreted as a sequence of
2114 action steps, or as different types of TODO items. The first
2115 keywords are states requiring action - these states will select a headline
2116 for inclusion into the global TODO list Org-mode produces. If one of
2117 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2118 signify that no further action is necessary. If \"|\" is not found,
2119 the last keyword is treated as the only DONE state of the sequence.
2121 The command \\[org-todo] cycles an entry through these states, and one
2122 additional state where no keyword is present. For details about this
2123 cycling, see the manual.
2125 TODO keywords and interpretation can also be set on a per-file basis with
2126 the special #+SEQ_TODO and #+TYP_TODO lines.
2128 Each keyword can optionally specify a character for fast state selection
2129 \(in combination with the variable `org-use-fast-todo-selection')
2130 and specifiers for state change logging, using the same syntax that
2131 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2132 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2133 indicates to record a time stamp each time this state is selected.
2135 Each keyword may also specify if a timestamp or a note should be
2136 recorded when entering or leaving the state, by adding additional
2137 characters in the parenthesis after the keyword. This looks like this:
2138 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2139 record only the time of the state change. With X and Y being either
2140 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2141 Y when leaving the state if and only if the *target* state does not
2142 define X. You may omit any of the fast-selection key or X or /Y,
2143 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2145 For backward compatibility, this variable may also be just a list
2146 of keywords. In this case the interpretation (sequence or type) will be
2147 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2148 :group 'org-todo
2149 :group 'org-keywords
2150 :type '(choice
2151 (repeat :tag "Old syntax, just keywords"
2152 (string :tag "Keyword"))
2153 (repeat :tag "New syntax"
2154 (cons
2155 (choice
2156 :tag "Interpretation"
2157 ;;Quick and dirty way to see
2158 ;;`org-todo-interpretations'. This takes the
2159 ;;place of item arguments
2160 :convert-widget
2161 (lambda (widget)
2162 (widget-put widget
2163 :args (mapcar
2164 #'(lambda (x)
2165 (widget-convert
2166 (cons 'const x)))
2167 org-todo-interpretation-widgets))
2168 widget))
2169 (repeat
2170 (string :tag "Keyword"))))))
2172 (defvar org-todo-keywords-1 nil
2173 "All TODO and DONE keywords active in a buffer.")
2174 (make-variable-buffer-local 'org-todo-keywords-1)
2175 (defvar org-todo-keywords-for-agenda nil)
2176 (defvar org-done-keywords-for-agenda nil)
2177 (defvar org-drawers-for-agenda nil)
2178 (defvar org-todo-keyword-alist-for-agenda nil)
2179 (defvar org-tag-alist-for-agenda nil)
2180 (defvar org-agenda-contributing-files nil)
2181 (defvar org-not-done-keywords nil)
2182 (make-variable-buffer-local 'org-not-done-keywords)
2183 (defvar org-done-keywords nil)
2184 (make-variable-buffer-local 'org-done-keywords)
2185 (defvar org-todo-heads nil)
2186 (make-variable-buffer-local 'org-todo-heads)
2187 (defvar org-todo-sets nil)
2188 (make-variable-buffer-local 'org-todo-sets)
2189 (defvar org-todo-log-states nil)
2190 (make-variable-buffer-local 'org-todo-log-states)
2191 (defvar org-todo-kwd-alist nil)
2192 (make-variable-buffer-local 'org-todo-kwd-alist)
2193 (defvar org-todo-key-alist nil)
2194 (make-variable-buffer-local 'org-todo-key-alist)
2195 (defvar org-todo-key-trigger nil)
2196 (make-variable-buffer-local 'org-todo-key-trigger)
2198 (defcustom org-todo-interpretation 'sequence
2199 "Controls how TODO keywords are interpreted.
2200 This variable is in principle obsolete and is only used for
2201 backward compatibility, if the interpretation of todo keywords is
2202 not given already in `org-todo-keywords'. See that variable for
2203 more information."
2204 :group 'org-todo
2205 :group 'org-keywords
2206 :type '(choice (const sequence)
2207 (const type)))
2209 (defcustom org-use-fast-todo-selection t
2210 "Non-nil means use the fast todo selection scheme with C-c C-t.
2211 This variable describes if and under what circumstances the cycling
2212 mechanism for TODO keywords will be replaced by a single-key, direct
2213 selection scheme.
2215 When nil, fast selection is never used.
2217 When the symbol `prefix', it will be used when `org-todo' is called
2218 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2219 `C-u t' in an agenda buffer.
2221 When t, fast selection is used by default. In this case, the prefix
2222 argument forces cycling instead.
2224 In all cases, the special interface is only used if access keys have
2225 actually been assigned by the user, i.e. if keywords in the configuration
2226 are followed by a letter in parenthesis, like TODO(t)."
2227 :group 'org-todo
2228 :type '(choice
2229 (const :tag "Never" nil)
2230 (const :tag "By default" t)
2231 (const :tag "Only with C-u C-c C-t" prefix)))
2233 (defcustom org-provide-todo-statistics t
2234 "Non-nil means update todo statistics after insert and toggle.
2235 ALL-HEADLINES means update todo statistics by including headlines
2236 with no TODO keyword as well, counting them as not done.
2237 A list of TODO keywords means the same, but skip keywords that are
2238 not in this list.
2240 When this is set, todo statistics is updated in the parent of the
2241 current entry each time a todo state is changed."
2242 :group 'org-todo
2243 :type '(choice
2244 (const :tag "Yes, only for TODO entries" t)
2245 (const :tag "Yes, including all entries" 'all-headlines)
2246 (repeat :tag "Yes, for TODOs in this list"
2247 (string :tag "TODO keyword"))
2248 (other :tag "No TODO statistics" nil)))
2250 (defcustom org-hierarchical-todo-statistics t
2251 "Non-nil means TODO statistics covers just direct children.
2252 When nil, all entries in the subtree are considered.
2253 This has only an effect if `org-provide-todo-statistics' is set.
2254 To set this to nil for only a single subtree, use a COOKIE_DATA
2255 property and include the word \"recursive\" into the value."
2256 :group 'org-todo
2257 :type 'boolean)
2259 (defcustom org-after-todo-state-change-hook nil
2260 "Hook which is run after the state of a TODO item was changed.
2261 The new state (a string with a TODO keyword, or nil) is available in the
2262 Lisp variable `org-state'."
2263 :group 'org-todo
2264 :type 'hook)
2266 (defvar org-blocker-hook nil
2267 "Hook for functions that are allowed to block a state change.
2269 Functions in this hook should not modify the buffer.
2270 Each function gets as its single argument a property list,
2271 see `org-trigger-hook' for more information about this list.
2273 If any of the functions in this hook returns nil, the state change
2274 is blocked.")
2276 (defvar org-trigger-hook nil
2277 "Hook for functions that are triggered by a state change.
2279 Each function gets as its single argument a property list with at
2280 least the following elements:
2282 (:type type-of-change :position pos-at-entry-start
2283 :from old-state :to new-state)
2285 Depending on the type, more properties may be present.
2287 This mechanism is currently implemented for:
2289 TODO state changes
2290 ------------------
2291 :type todo-state-change
2292 :from previous state (keyword as a string), or nil, or a symbol
2293 'todo' or 'done', to indicate the general type of state.
2294 :to new state, like in :from")
2296 (defcustom org-enforce-todo-dependencies nil
2297 "Non-nil means undone TODO entries will block switching the parent to DONE.
2298 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2299 be blocked if any prior sibling is not yet done.
2300 Finally, if the parent is blocked because of ordered siblings of its own,
2301 the child will also be blocked."
2302 :set (lambda (var val)
2303 (set var val)
2304 (if val
2305 (add-hook 'org-blocker-hook
2306 'org-block-todo-from-children-or-siblings-or-parent)
2307 (remove-hook 'org-blocker-hook
2308 'org-block-todo-from-children-or-siblings-or-parent)))
2309 :group 'org-todo
2310 :type 'boolean)
2312 (defcustom org-enforce-todo-checkbox-dependencies nil
2313 "Non-nil means unchecked boxes will block switching the parent to DONE.
2314 When this is nil, checkboxes have no influence on switching TODO states.
2315 When non-nil, you first need to check off all check boxes before the TODO
2316 entry can be switched to DONE.
2317 This variable needs to be set before org.el is loaded, and you need to
2318 restart Emacs after a change to make the change effective. The only way
2319 to change is while Emacs is running is through the customize interface."
2320 :set (lambda (var val)
2321 (set var val)
2322 (if val
2323 (add-hook 'org-blocker-hook
2324 'org-block-todo-from-checkboxes)
2325 (remove-hook 'org-blocker-hook
2326 'org-block-todo-from-checkboxes)))
2327 :group 'org-todo
2328 :type 'boolean)
2330 (defcustom org-treat-insert-todo-heading-as-state-change nil
2331 "Non-nil means inserting a TODO heading is treated as state change.
2332 So when the command \\[org-insert-todo-heading] is used, state change
2333 logging will apply if appropriate. When nil, the new TODO item will
2334 be inserted directly, and no logging will take place."
2335 :group 'org-todo
2336 :type 'boolean)
2338 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2339 "Non-nil means switching TODO states with S-cursor counts as state change.
2340 This is the default behavior. However, setting this to nil allows a
2341 convenient way to select a TODO state and bypass any logging associated
2342 with that."
2343 :group 'org-todo
2344 :type 'boolean)
2346 (defcustom org-todo-state-tags-triggers nil
2347 "Tag changes that should be triggered by TODO state changes.
2348 This is a list. Each entry is
2350 (state-change (tag . flag) .......)
2352 State-change can be a string with a state, and empty string to indicate the
2353 state that has no TODO keyword, or it can be one of the symbols `todo'
2354 or `done', meaning any not-done or done state, respectively."
2355 :group 'org-todo
2356 :group 'org-tags
2357 :type '(repeat
2358 (cons (choice :tag "When changing to"
2359 (const :tag "Not-done state" todo)
2360 (const :tag "Done state" done)
2361 (string :tag "State"))
2362 (repeat
2363 (cons :tag "Tag action"
2364 (string :tag "Tag")
2365 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2367 (defcustom org-log-done nil
2368 "Information to record when a task moves to the DONE state.
2370 Possible values are:
2372 nil Don't add anything, just change the keyword
2373 time Add a time stamp to the task
2374 note Prompt for a note and add it with template `org-log-note-headings'
2376 This option can also be set with on a per-file-basis with
2378 #+STARTUP: nologdone
2379 #+STARTUP: logdone
2380 #+STARTUP: lognotedone
2382 You can have local logging settings for a subtree by setting the LOGGING
2383 property to one or more of these keywords."
2384 :group 'org-todo
2385 :group 'org-progress
2386 :type '(choice
2387 (const :tag "No logging" nil)
2388 (const :tag "Record CLOSED timestamp" time)
2389 (const :tag "Record CLOSED timestamp with note." note)))
2391 ;; Normalize old uses of org-log-done.
2392 (cond
2393 ((eq org-log-done t) (setq org-log-done 'time))
2394 ((and (listp org-log-done) (memq 'done org-log-done))
2395 (setq org-log-done 'note)))
2397 (defcustom org-log-reschedule nil
2398 "Information to record when the scheduling date of a tasks is modified.
2400 Possible values are:
2402 nil Don't add anything, just change the date
2403 time Add a time stamp to the task
2404 note Prompt for a note and add it with template `org-log-note-headings'
2406 This option can also be set with on a per-file-basis with
2408 #+STARTUP: nologreschedule
2409 #+STARTUP: logreschedule
2410 #+STARTUP: lognotereschedule"
2411 :group 'org-todo
2412 :group 'org-progress
2413 :type '(choice
2414 (const :tag "No logging" nil)
2415 (const :tag "Record timestamp" time)
2416 (const :tag "Record timestamp with note." note)))
2418 (defcustom org-log-redeadline nil
2419 "Information to record when the deadline date of a tasks is modified.
2421 Possible values are:
2423 nil Don't add anything, just change the date
2424 time Add a time stamp to the task
2425 note Prompt for a note and add it with template `org-log-note-headings'
2427 This option can also be set with on a per-file-basis with
2429 #+STARTUP: nologredeadline
2430 #+STARTUP: logredeadline
2431 #+STARTUP: lognoteredeadline
2433 You can have local logging settings for a subtree by setting the LOGGING
2434 property to one or more of these keywords."
2435 :group 'org-todo
2436 :group 'org-progress
2437 :type '(choice
2438 (const :tag "No logging" nil)
2439 (const :tag "Record timestamp" time)
2440 (const :tag "Record timestamp with note." note)))
2442 (defcustom org-log-note-clock-out nil
2443 "Non-nil means record a note when clocking out of an item.
2444 This can also be configured on a per-file basis by adding one of
2445 the following lines anywhere in the buffer:
2447 #+STARTUP: lognoteclock-out
2448 #+STARTUP: nolognoteclock-out"
2449 :group 'org-todo
2450 :group 'org-progress
2451 :type 'boolean)
2453 (defcustom org-log-done-with-time t
2454 "Non-nil means the CLOSED time stamp will contain date and time.
2455 When nil, only the date will be recorded."
2456 :group 'org-progress
2457 :type 'boolean)
2459 (defcustom org-log-note-headings
2460 '((done . "CLOSING NOTE %t")
2461 (state . "State %-12s from %-12S %t")
2462 (note . "Note taken on %t")
2463 (reschedule . "Rescheduled from %S on %t")
2464 (delschedule . "Not scheduled, was %S on %t")
2465 (redeadline . "New deadline from %S on %t")
2466 (deldeadline . "Removed deadline, was %S on %t")
2467 (refile . "Refiled on %t")
2468 (clock-out . ""))
2469 "Headings for notes added to entries.
2470 The value is an alist, with the car being a symbol indicating the note
2471 context, and the cdr is the heading to be used. The heading may also be the
2472 empty string.
2473 %t in the heading will be replaced by a time stamp.
2474 %T will be an active time stamp instead the default inactive one
2475 %d will be replaced by a short-format time stamp.
2476 %D will be replaced by an active short-format time stamp.
2477 %s will be replaced by the new TODO state, in double quotes.
2478 %S will be replaced by the old TODO state, in double quotes.
2479 %u will be replaced by the user name.
2480 %U will be replaced by the full user name.
2482 In fact, it is not a good idea to change the `state' entry, because
2483 agenda log mode depends on the format of these entries."
2484 :group 'org-todo
2485 :group 'org-progress
2486 :type '(list :greedy t
2487 (cons (const :tag "Heading when closing an item" done) string)
2488 (cons (const :tag
2489 "Heading when changing todo state (todo sequence only)"
2490 state) string)
2491 (cons (const :tag "Heading when just taking a note" note) string)
2492 (cons (const :tag "Heading when clocking out" clock-out) string)
2493 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2494 (cons (const :tag "Heading when rescheduling" reschedule) string)
2495 (cons (const :tag "Heading when changing deadline" redeadline) string)
2496 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2497 (cons (const :tag "Heading when refiling" refile) string)))
2499 (unless (assq 'note org-log-note-headings)
2500 (push '(note . "%t") org-log-note-headings))
2502 (defcustom org-log-into-drawer nil
2503 "Non-nil means insert state change notes and time stamps into a drawer.
2504 When nil, state changes notes will be inserted after the headline and
2505 any scheduling and clock lines, but not inside a drawer.
2507 The value of this variable should be the name of the drawer to use.
2508 LOGBOOK is proposed as the default drawer for this purpose, you can
2509 also set this to a string to define the drawer of your choice.
2511 A value of t is also allowed, representing \"LOGBOOK\".
2513 A value of t or nil can also be set with on a per-file-basis with
2515 #+STARTUP: logdrawer
2516 #+STARTUP: nologdrawer
2518 If this variable is set, `org-log-state-notes-insert-after-drawers'
2519 will be ignored.
2521 You can set the property LOG_INTO_DRAWER to overrule this setting for
2522 a subtree."
2523 :group 'org-todo
2524 :group 'org-progress
2525 :type '(choice
2526 (const :tag "Not into a drawer" nil)
2527 (const :tag "LOGBOOK" t)
2528 (string :tag "Other")))
2530 (if (fboundp 'defvaralias)
2531 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2533 (defun org-log-into-drawer ()
2534 "Return the value of `org-log-into-drawer', but let properties overrule.
2535 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2536 used instead of the default value."
2537 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2538 (cond
2539 ((not p) org-log-into-drawer)
2540 ((equal p "nil") nil)
2541 ((equal p "t") "LOGBOOK")
2542 (t p))))
2544 (defcustom org-log-state-notes-insert-after-drawers nil
2545 "Non-nil means insert state change notes after any drawers in entry.
2546 Only the drawers that *immediately* follow the headline and the
2547 deadline/scheduled line are skipped.
2548 When nil, insert notes right after the heading and perhaps the line
2549 with deadline/scheduling if present.
2551 This variable will have no effect if `org-log-into-drawer' is
2552 set."
2553 :group 'org-todo
2554 :group 'org-progress
2555 :type 'boolean)
2557 (defcustom org-log-states-order-reversed t
2558 "Non-nil means the latest state note will be directly after heading.
2559 When nil, the state change notes will be ordered according to time.
2561 This option can also be set with on a per-file-basis with
2563 #+STARTUP: logstatesreversed
2564 #+STARTUP: nologstatesreversed"
2565 :group 'org-todo
2566 :group 'org-progress
2567 :type 'boolean)
2569 (defcustom org-todo-repeat-to-state nil
2570 "The TODO state to which a repeater should return the repeating task.
2571 By default this is the first task in a TODO sequence, or the previous state
2572 in a TODO_TYP set. But you can specify another task here.
2573 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2574 :group 'org-todo
2575 :version "24.1"
2576 :type '(choice (const :tag "Head of sequence" nil)
2577 (string :tag "Specific state")))
2579 (defcustom org-log-repeat 'time
2580 "Non-nil means record moving through the DONE state when triggering repeat.
2581 An auto-repeating task is immediately switched back to TODO when
2582 marked DONE. If you are not logging state changes (by adding \"@\"
2583 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2584 record a closing note, there will be no record of the task moving
2585 through DONE. This variable forces taking a note anyway.
2587 nil Don't force a record
2588 time Record a time stamp
2589 note Prompt for a note and add it with template `org-log-note-headings'
2591 This option can also be set with on a per-file-basis with
2593 #+STARTUP: nologrepeat
2594 #+STARTUP: logrepeat
2595 #+STARTUP: lognoterepeat
2597 You can have local logging settings for a subtree by setting the LOGGING
2598 property to one or more of these keywords."
2599 :group 'org-todo
2600 :group 'org-progress
2601 :type '(choice
2602 (const :tag "Don't force a record" nil)
2603 (const :tag "Force recording the DONE state" time)
2604 (const :tag "Force recording a note with the DONE state" note)))
2607 (defgroup org-priorities nil
2608 "Priorities in Org-mode."
2609 :tag "Org Priorities"
2610 :group 'org-todo)
2612 (defcustom org-enable-priority-commands t
2613 "Non-nil means priority commands are active.
2614 When nil, these commands will be disabled, so that you never accidentally
2615 set a priority."
2616 :group 'org-priorities
2617 :type 'boolean)
2619 (defcustom org-highest-priority ?A
2620 "The highest priority of TODO items. A character like ?A, ?B etc.
2621 Must have a smaller ASCII number than `org-lowest-priority'."
2622 :group 'org-priorities
2623 :type 'character)
2625 (defcustom org-lowest-priority ?C
2626 "The lowest priority of TODO items. A character like ?A, ?B etc.
2627 Must have a larger ASCII number than `org-highest-priority'."
2628 :group 'org-priorities
2629 :type 'character)
2631 (defcustom org-default-priority ?B
2632 "The default priority of TODO items.
2633 This is the priority an item gets if no explicit priority is given.
2634 When starting to cycle on an empty priority the first step in the cycle
2635 depends on `org-priority-start-cycle-with-default'. The resulting first
2636 step priority must not exceed the range from `org-highest-priority' to
2637 `org-lowest-priority' which means that `org-default-priority' has to be
2638 in this range exclusive or inclusive the range boundaries. Else the
2639 first step refuses to set the default and the second will fall back
2640 to (depending on the command used) the highest or lowest priority."
2641 :group 'org-priorities
2642 :type 'character)
2644 (defcustom org-priority-start-cycle-with-default t
2645 "Non-nil means start with default priority when starting to cycle.
2646 When this is nil, the first step in the cycle will be (depending on the
2647 command used) one higher or lower than the default priority.
2648 See also `org-default-priority'."
2649 :group 'org-priorities
2650 :type 'boolean)
2652 (defcustom org-get-priority-function nil
2653 "Function to extract the priority from a string.
2654 The string is normally the headline. If this is nil Org computes the
2655 priority from the priority cookie like [#A] in the headline. It returns
2656 an integer, increasing by 1000 for each priority level.
2657 The user can set a different function here, which should take a string
2658 as an argument and return the numeric priority."
2659 :group 'org-priorities
2660 :version "24.1"
2661 :type 'function)
2663 (defgroup org-time nil
2664 "Options concerning time stamps and deadlines in Org-mode."
2665 :tag "Org Time"
2666 :group 'org)
2668 (defcustom org-insert-labeled-timestamps-at-point nil
2669 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2670 When nil, these labeled time stamps are forces into the second line of an
2671 entry, just after the headline. When scheduling from the global TODO list,
2672 the time stamp will always be forced into the second line."
2673 :group 'org-time
2674 :type 'boolean)
2676 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2677 "Formats for `format-time-string' which are used for time stamps.
2678 It is not recommended to change this constant.")
2680 (defcustom org-time-stamp-rounding-minutes '(0 5)
2681 "Number of minutes to round time stamps to.
2682 These are two values, the first applies when first creating a time stamp.
2683 The second applies when changing it with the commands `S-up' and `S-down'.
2684 When changing the time stamp, this means that it will change in steps
2685 of N minutes, as given by the second value.
2687 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2688 numbers should be factors of 60, so for example 5, 10, 15.
2690 When this is larger than 1, you can still force an exact time stamp by using
2691 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2692 and by using a prefix arg to `S-up/down' to specify the exact number
2693 of minutes to shift."
2694 :group 'org-time
2695 :get #'(lambda (var) ; Make sure both elements are there
2696 (if (integerp (default-value var))
2697 (list (default-value var) 5)
2698 (default-value var)))
2699 :type '(list
2700 (integer :tag "when inserting times")
2701 (integer :tag "when modifying times")))
2703 ;; Normalize old customizations of this variable.
2704 (when (integerp org-time-stamp-rounding-minutes)
2705 (setq org-time-stamp-rounding-minutes
2706 (list org-time-stamp-rounding-minutes
2707 org-time-stamp-rounding-minutes)))
2709 (defcustom org-display-custom-times nil
2710 "Non-nil means overlay custom formats over all time stamps.
2711 The formats are defined through the variable `org-time-stamp-custom-formats'.
2712 To turn this on on a per-file basis, insert anywhere in the file:
2713 #+STARTUP: customtime"
2714 :group 'org-time
2715 :set 'set-default
2716 :type 'sexp)
2717 (make-variable-buffer-local 'org-display-custom-times)
2719 (defcustom org-time-stamp-custom-formats
2720 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2721 "Custom formats for time stamps. See `format-time-string' for the syntax.
2722 These are overlaid over the default ISO format if the variable
2723 `org-display-custom-times' is set. Time like %H:%M should be at the
2724 end of the second format. The custom formats are also honored by export
2725 commands, if custom time display is turned on at the time of export."
2726 :group 'org-time
2727 :type 'sexp)
2729 (defun org-time-stamp-format (&optional long inactive)
2730 "Get the right format for a time string."
2731 (let ((f (if long (cdr org-time-stamp-formats)
2732 (car org-time-stamp-formats))))
2733 (if inactive
2734 (concat "[" (substring f 1 -1) "]")
2735 f)))
2737 (defcustom org-time-clocksum-format
2738 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2739 "The format string used when creating CLOCKSUM lines.
2740 This is also used when Org mode generates a time duration.
2742 The value can be a single format string containing two
2743 %-sequences, which will be filled with the number of hours and
2744 minutes in that order.
2746 Alternatively, the value can be a plist associating any of the
2747 keys :years, :months, :weeks, :days, :hours or :minutes with
2748 format strings. The time duration is formatted using only the
2749 time components that are needed and concatenating the results.
2750 If a time unit in absent, it falls back to the next smallest
2751 unit.
2753 The keys :require-years, :require-months, :require-days,
2754 :require-weeks, :require-hours, :require-minutes are also
2755 meaningful. A non-nil value for these keys indicates that the
2756 corresponding time component should always be included, even if
2757 its value is 0.
2760 For example,
2762 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2763 :require-minutes t)
2765 means durations longer than a day will be expressed in days,
2766 hours and minutes, and durations less than a day will always be
2767 expressed in hours and minutes (even for durations less than an
2768 hour).
2770 The value
2772 \(:days \"%dd\" :minutes \"%dm\")
2774 means durations longer than a day will be expressed in days and
2775 minutes, and durations less than a day will be expressed entirely
2776 in minutes (even for durations longer than an hour)."
2777 :group 'org-time
2778 :type '(choice (string :tag "Format string")
2779 (set :tag "Plist"
2780 (group :inline t (const :tag "Years" :years)
2781 (string :tag "Format string"))
2782 (group :inline t
2783 (const :tag "Always show years" :require-years)
2784 (const t))
2785 (group :inline t (const :tag "Months" :months)
2786 (string :tag "Format string"))
2787 (group :inline t
2788 (const :tag "Always show months" :require-months)
2789 (const t))
2790 (group :inline t (const :tag "Weeks" :weeks)
2791 (string :tag "Format string"))
2792 (group :inline t
2793 (const :tag "Always show weeks" :require-weeks)
2794 (const t))
2795 (group :inline t (const :tag "Days" :days)
2796 (string :tag "Format string"))
2797 (group :inline t
2798 (const :tag "Always show days" :require-days)
2799 (const t))
2800 (group :inline t (const :tag "Hours" :hours)
2801 (string :tag "Format string"))
2802 (group :inline t
2803 (const :tag "Always show hours" :require-hours)
2804 (const t))
2805 (group :inline t (const :tag "Minutes" :minutes)
2806 (string :tag "Format string"))
2807 (group :inline t
2808 (const :tag "Always show minutes" :require-minutes)
2809 (const t)))))
2811 (defcustom org-time-clocksum-use-fractional nil
2812 "If non-nil, \\[org-clock-display] uses fractional times.
2813 org-mode generates a time duration."
2814 :group 'org-time
2815 :type 'boolean)
2817 (defcustom org-time-clocksum-fractional-format "%.2f"
2818 "The format string used when creating CLOCKSUM lines,
2819 or when Org mode generates a time duration, if
2820 `org-time-clocksum-use-fractional' is enabled.
2822 The value can be a single format string containing one
2823 %-sequence, which will be filled with the number of hours as
2824 a float.
2826 Alternatively, the value can be a plist associating any of the
2827 keys :years, :months, :weeks, :days, :hours or :minutes with
2828 a format string. The time duration is formatted using the
2829 largest time unit which gives a non-zero integer part. If all
2830 specified formats have zero integer part, the smallest time unit
2831 is used."
2832 :group 'org-time
2833 :type '(choice (string :tag "Format string")
2834 (set (group :inline t (const :tag "Years" :years)
2835 (string :tag "Format string"))
2836 (group :inline t (const :tag "Months" :months)
2837 (string :tag "Format string"))
2838 (group :inline t (const :tag "Weeks" :weeks)
2839 (string :tag "Format string"))
2840 (group :inline t (const :tag "Days" :days)
2841 (string :tag "Format string"))
2842 (group :inline t (const :tag "Hours" :hours)
2843 (string :tag "Format string"))
2844 (group :inline t (const :tag "Minutes" :minutes)
2845 (string :tag "Format string")))))
2847 (defcustom org-deadline-warning-days 14
2848 "No. of days before expiration during which a deadline becomes active.
2849 This variable governs the display in sparse trees and in the agenda.
2850 When 0 or negative, it means use this number (the absolute value of it)
2851 even if a deadline has a different individual lead time specified.
2853 Custom commands can set this variable in the options section."
2854 :group 'org-time
2855 :group 'org-agenda-daily/weekly
2856 :type 'integer)
2858 (defcustom org-read-date-prefer-future t
2859 "Non-nil means assume future for incomplete date input from user.
2860 This affects the following situations:
2861 1. The user gives a month but not a year.
2862 For example, if it is April and you enter \"feb 2\", this will be read
2863 as Feb 2, *next* year. \"May 5\", however, will be this year.
2864 2. The user gives a day, but no month.
2865 For example, if today is the 15th, and you enter \"3\", Org-mode will
2866 read this as the third of *next* month. However, if you enter \"17\",
2867 it will be considered as *this* month.
2869 If you set this variable to the symbol `time', then also the following
2870 will work:
2872 3. If the user gives a time.
2873 If the time is before now, it will be interpreted as tomorrow.
2875 Currently none of this works for ISO week specifications.
2877 When this option is nil, the current day, month and year will always be
2878 used as defaults.
2880 See also `org-agenda-jump-prefer-future'."
2881 :group 'org-time
2882 :type '(choice
2883 (const :tag "Never" nil)
2884 (const :tag "Check month and day" t)
2885 (const :tag "Check month, day, and time" time)))
2887 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2888 "Should the agenda jump command prefer the future for incomplete dates?
2889 The default is to do the same as configured in `org-read-date-prefer-future'.
2890 But you can also set a deviating value here.
2891 This may t or nil, or the symbol `org-read-date-prefer-future'."
2892 :group 'org-agenda
2893 :group 'org-time
2894 :version "24.1"
2895 :type '(choice
2896 (const :tag "Use org-read-date-prefer-future"
2897 org-read-date-prefer-future)
2898 (const :tag "Never" nil)
2899 (const :tag "Always" t)))
2901 (defcustom org-read-date-force-compatible-dates t
2902 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2904 Depending on the system Emacs is running on, certain dates cannot
2905 be represented with the type used internally to represent time.
2906 Dates between 1970-1-1 and 2038-1-1 can always be represented
2907 correctly. Some systems allow for earlier dates, some for later,
2908 some for both. One way to find out it to insert any date into an
2909 Org buffer, putting the cursor on the year and hitting S-up and
2910 S-down to test the range.
2912 When this variable is set to t, the date/time prompt will not let
2913 you specify dates outside the 1970-2037 range, so it is certain that
2914 these dates will work in whatever version of Emacs you are
2915 running, and also that you can move a file from one Emacs implementation
2916 to another. WHenever Org is forcing the year for you, it will display
2917 a message and beep.
2919 When this variable is nil, Org will check if the date is
2920 representable in the specific Emacs implementation you are using.
2921 If not, it will force a year, usually the current year, and beep
2922 to remind you. Currently this setting is not recommended because
2923 the likelihood that you will open your Org files in an Emacs that
2924 has limited date range is not negligible.
2926 A workaround for this problem is to use diary sexp dates for time
2927 stamps outside of this range."
2928 :group 'org-time
2929 :version "24.1"
2930 :type 'boolean)
2932 (defcustom org-read-date-display-live t
2933 "Non-nil means display current interpretation of date prompt live.
2934 This display will be in an overlay, in the minibuffer."
2935 :group 'org-time
2936 :type 'boolean)
2938 (defcustom org-read-date-popup-calendar t
2939 "Non-nil means pop up a calendar when prompting for a date.
2940 In the calendar, the date can be selected with mouse-1. However, the
2941 minibuffer will also be active, and you can simply enter the date as well.
2942 When nil, only the minibuffer will be available."
2943 :group 'org-time
2944 :type 'boolean)
2945 (if (fboundp 'defvaralias)
2946 (defvaralias 'org-popup-calendar-for-date-prompt
2947 'org-read-date-popup-calendar))
2949 (defcustom org-read-date-minibuffer-setup-hook nil
2950 "Hook to be used to set up keys for the date/time interface.
2951 Add key definitions to `minibuffer-local-map', which will be a temporary
2952 copy."
2953 :group 'org-time
2954 :type 'hook)
2956 (defcustom org-extend-today-until 0
2957 "The hour when your day really ends. Must be an integer.
2958 This has influence for the following applications:
2959 - When switching the agenda to \"today\". It it is still earlier than
2960 the time given here, the day recognized as TODAY is actually yesterday.
2961 - When a date is read from the user and it is still before the time given
2962 here, the current date and time will be assumed to be yesterday, 23:59.
2963 Also, timestamps inserted in capture templates follow this rule.
2965 IMPORTANT: This is a feature whose implementation is and likely will
2966 remain incomplete. Really, it is only here because past midnight seems to
2967 be the favorite working time of John Wiegley :-)"
2968 :group 'org-time
2969 :type 'integer)
2971 (defcustom org-use-effective-time nil
2972 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2973 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2974 \"effective time\" of any timestamps between midnight and 8am will be
2975 23:59 of the previous day."
2976 :group 'org-time
2977 :version "24.1"
2978 :type 'boolean)
2980 (defcustom org-use-last-clock-out-time-as-effective-time nil
2981 "When non-nil, use the last clock out time for `org-todo'.
2982 Note that this option has precedence over the combined use of
2983 `org-use-effective-time' and `org-extend-today-until'."
2984 :group 'org-time
2985 ;; :version "24.3"
2986 :type 'boolean)
2988 (defcustom org-edit-timestamp-down-means-later nil
2989 "Non-nil means S-down will increase the time in a time stamp.
2990 When nil, S-up will increase."
2991 :group 'org-time
2992 :type 'boolean)
2994 (defcustom org-calendar-follow-timestamp-change t
2995 "Non-nil means make the calendar window follow timestamp changes.
2996 When a timestamp is modified and the calendar window is visible, it will be
2997 moved to the new date."
2998 :group 'org-time
2999 :type 'boolean)
3001 (defgroup org-tags nil
3002 "Options concerning tags in Org-mode."
3003 :tag "Org Tags"
3004 :group 'org)
3006 (defcustom org-tag-alist nil
3007 "List of tags allowed in Org-mode files.
3008 When this list is nil, Org-mode will base TAG input on what is already in the
3009 buffer.
3010 The value of this variable is an alist, the car of each entry must be a
3011 keyword as a string, the cdr may be a character that is used to select
3012 that tag through the fast-tag-selection interface.
3013 See the manual for details."
3014 :group 'org-tags
3015 :type '(repeat
3016 (choice
3017 (cons (string :tag "Tag name")
3018 (character :tag "Access char"))
3019 (list :tag "Start radio group"
3020 (const :startgroup)
3021 (option (string :tag "Group description")))
3022 (list :tag "End radio group"
3023 (const :endgroup)
3024 (option (string :tag "Group description")))
3025 (const :tag "New line" (:newline)))))
3027 (defcustom org-tag-persistent-alist nil
3028 "List of tags that will always appear in all Org-mode files.
3029 This is in addition to any in buffer settings or customizations
3030 of `org-tag-alist'.
3031 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3032 The value of this variable is an alist, the car of each entry must be a
3033 keyword as a string, the cdr may be a character that is used to select
3034 that tag through the fast-tag-selection interface.
3035 See the manual for details.
3036 To disable these tags on a per-file basis, insert anywhere in the file:
3037 #+STARTUP: noptag"
3038 :group 'org-tags
3039 :type '(repeat
3040 (choice
3041 (cons (string :tag "Tag name")
3042 (character :tag "Access char"))
3043 (const :tag "Start radio group" (:startgroup))
3044 (const :tag "End radio group" (:endgroup))
3045 (const :tag "New line" (:newline)))))
3047 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3048 "If non-nil, always offer completion for all tags of all agenda files.
3049 Instead of customizing this variable directly, you might want to
3050 set it locally for capture buffers, because there no list of
3051 tags in that file can be created dynamically (there are none).
3053 (add-hook 'org-capture-mode-hook
3054 (lambda ()
3055 (set (make-local-variable
3056 'org-complete-tags-always-offer-all-agenda-tags)
3057 t)))"
3058 :group 'org-tags
3059 :version "24.1"
3060 :type 'boolean)
3062 (defvar org-file-tags nil
3063 "List of tags that can be inherited by all entries in the file.
3064 The tags will be inherited if the variable `org-use-tag-inheritance'
3065 says they should be.
3066 This variable is populated from #+FILETAGS lines.")
3068 (defcustom org-use-fast-tag-selection 'auto
3069 "Non-nil means use fast tag selection scheme.
3070 This is a special interface to select and deselect tags with single keys.
3071 When nil, fast selection is never used.
3072 When the symbol `auto', fast selection is used if and only if selection
3073 characters for tags have been configured, either through the variable
3074 `org-tag-alist' or through a #+TAGS line in the buffer.
3075 When t, fast selection is always used and selection keys are assigned
3076 automatically if necessary."
3077 :group 'org-tags
3078 :type '(choice
3079 (const :tag "Always" t)
3080 (const :tag "Never" nil)
3081 (const :tag "When selection characters are configured" 'auto)))
3083 (defcustom org-fast-tag-selection-single-key nil
3084 "Non-nil means fast tag selection exits after first change.
3085 When nil, you have to press RET to exit it.
3086 During fast tag selection, you can toggle this flag with `C-c'.
3087 This variable can also have the value `expert'. In this case, the window
3088 displaying the tags menu is not even shown, until you press C-c again."
3089 :group 'org-tags
3090 :type '(choice
3091 (const :tag "No" nil)
3092 (const :tag "Yes" t)
3093 (const :tag "Expert" expert)))
3095 (defvar org-fast-tag-selection-include-todo nil
3096 "Non-nil means fast tags selection interface will also offer TODO states.
3097 This is an undocumented feature, you should not rely on it.")
3099 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3100 "The column to which tags should be indented in a headline.
3101 If this number is positive, it specifies the column. If it is negative,
3102 it means that the tags should be flushright to that column. For example,
3103 -80 works well for a normal 80 character screen.
3104 When 0, place tags directly after headline text, with only one space in
3105 between."
3106 :group 'org-tags
3107 :type 'integer)
3109 (defcustom org-auto-align-tags t
3110 "Non-nil keeps tags aligned when modifying headlines.
3111 Some operations (i.e. demoting) change the length of a headline and
3112 therefore shift the tags around. With this option turned on, after
3113 each such operation the tags are again aligned to `org-tags-column'."
3114 :group 'org-tags
3115 :type 'boolean)
3117 (defcustom org-use-tag-inheritance t
3118 "Non-nil means tags in levels apply also for sublevels.
3119 When nil, only the tags directly given in a specific line apply there.
3120 This may also be a list of tags that should be inherited, or a regexp that
3121 matches tags that should be inherited. Additional control is possible
3122 with the variable `org-tags-exclude-from-inheritance' which gives an
3123 explicit list of tags to be excluded from inheritance., even if the value of
3124 `org-use-tag-inheritance' would select it for inheritance.
3126 If this option is t, a match early-on in a tree can lead to a large
3127 number of matches in the subtree when constructing the agenda or creating
3128 a sparse tree. If you only want to see the first match in a tree during
3129 a search, check out the variable `org-tags-match-list-sublevels'."
3130 :group 'org-tags
3131 :type '(choice
3132 (const :tag "Not" nil)
3133 (const :tag "Always" t)
3134 (repeat :tag "Specific tags" (string :tag "Tag"))
3135 (regexp :tag "Tags matched by regexp")))
3137 (defcustom org-tags-exclude-from-inheritance nil
3138 "List of tags that should never be inherited.
3139 This is a way to exclude a few tags from inheritance. For way to do
3140 the opposite, to actively allow inheritance for selected tags,
3141 see the variable `org-use-tag-inheritance'."
3142 :group 'org-tags
3143 :type '(repeat (string :tag "Tag")))
3145 (defun org-tag-inherit-p (tag)
3146 "Check if TAG is one that should be inherited."
3147 (cond
3148 ((member tag org-tags-exclude-from-inheritance) nil)
3149 ((eq org-use-tag-inheritance t) t)
3150 ((not org-use-tag-inheritance) nil)
3151 ((stringp org-use-tag-inheritance)
3152 (string-match org-use-tag-inheritance tag))
3153 ((listp org-use-tag-inheritance)
3154 (member tag org-use-tag-inheritance))
3155 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3157 (defcustom org-tags-match-list-sublevels t
3158 "Non-nil means list also sublevels of headlines matching a search.
3159 This variable applies to tags/property searches, and also to stuck
3160 projects because this search is based on a tags match as well.
3162 When set to the symbol `indented', sublevels are indented with
3163 leading dots.
3165 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3166 the sublevels of a headline matching a tag search often also match
3167 the same search. Listing all of them can create very long lists.
3168 Setting this variable to nil causes subtrees of a match to be skipped.
3170 This variable is semi-obsolete and probably should always be true. It
3171 is better to limit inheritance to certain tags using the variables
3172 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3173 :group 'org-tags
3174 :type '(choice
3175 (const :tag "No, don't list them" nil)
3176 (const :tag "Yes, do list them" t)
3177 (const :tag "List them, indented with leading dots" indented)))
3179 (defcustom org-tags-sort-function nil
3180 "When set, tags are sorted using this function as a comparator."
3181 :group 'org-tags
3182 :type '(choice
3183 (const :tag "No sorting" nil)
3184 (const :tag "Alphabetical" string<)
3185 (const :tag "Reverse alphabetical" string>)
3186 (function :tag "Custom function" nil)))
3188 (defvar org-tags-history nil
3189 "History of minibuffer reads for tags.")
3190 (defvar org-last-tags-completion-table nil
3191 "The last used completion table for tags.")
3192 (defvar org-after-tags-change-hook nil
3193 "Hook that is run after the tags in a line have changed.")
3195 (defgroup org-properties nil
3196 "Options concerning properties in Org-mode."
3197 :tag "Org Properties"
3198 :group 'org)
3200 (defcustom org-property-format "%-10s %s"
3201 "How property key/value pairs should be formatted by `indent-line'.
3202 When `indent-line' hits a property definition, it will format the line
3203 according to this format, mainly to make sure that the values are
3204 lined-up with respect to each other."
3205 :group 'org-properties
3206 :type 'string)
3208 (defcustom org-properties-postprocess-alist nil
3209 "Alist of properties and functions to adjust inserted values.
3210 Elements of this alist must be of the form
3212 ([string] [function])
3214 where [string] must be a property name and [function] must be a
3215 lambda expression: this lambda expression must take one argument,
3216 the value to adjust, and return the new value as a string.
3218 For example, this element will allow the property \"Remaining\"
3219 to be updated wrt the relation between the \"Effort\" property
3220 and the clock summary:
3222 ((\"Remaining\" (lambda(value)
3223 (let ((clocksum (org-clock-sum-current-item))
3224 (effort (org-duration-string-to-minutes
3225 (org-entry-get (point) \"Effort\"))))
3226 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3227 :group 'org-properties
3228 :version "24.1"
3229 :type '(alist :key-type (string :tag "Property")
3230 :value-type (function :tag "Function")))
3232 (defcustom org-use-property-inheritance nil
3233 "Non-nil means properties apply also for sublevels.
3235 This setting is chiefly used during property searches. Turning it on can
3236 cause significant overhead when doing a search, which is why it is not
3237 on by default.
3239 When nil, only the properties directly given in the current entry count.
3240 When t, every property is inherited. The value may also be a list of
3241 properties that should have inheritance, or a regular expression matching
3242 properties that should be inherited.
3244 However, note that some special properties use inheritance under special
3245 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3246 and the properties ending in \"_ALL\" when they are used as descriptor
3247 for valid values of a property.
3249 Note for programmers:
3250 When querying an entry with `org-entry-get', you can control if inheritance
3251 should be used. By default, `org-entry-get' looks only at the local
3252 properties. You can request inheritance by setting the inherit argument
3253 to t (to force inheritance) or to `selective' (to respect the setting
3254 in this variable)."
3255 :group 'org-properties
3256 :type '(choice
3257 (const :tag "Not" nil)
3258 (const :tag "Always" t)
3259 (repeat :tag "Specific properties" (string :tag "Property"))
3260 (regexp :tag "Properties matched by regexp")))
3262 (defun org-property-inherit-p (property)
3263 "Check if PROPERTY is one that should be inherited."
3264 (cond
3265 ((eq org-use-property-inheritance t) t)
3266 ((not org-use-property-inheritance) nil)
3267 ((stringp org-use-property-inheritance)
3268 (string-match org-use-property-inheritance property))
3269 ((listp org-use-property-inheritance)
3270 (member property org-use-property-inheritance))
3271 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3273 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3274 "The default column format, if no other format has been defined.
3275 This variable can be set on the per-file basis by inserting a line
3277 #+COLUMNS: %25ITEM ....."
3278 :group 'org-properties
3279 :type 'string)
3281 (defcustom org-columns-ellipses ".."
3282 "The ellipses to be used when a field in column view is truncated.
3283 When this is the empty string, as many characters as possible are shown,
3284 but then there will be no visual indication that the field has been truncated.
3285 When this is a string of length N, the last N characters of a truncated
3286 field are replaced by this string. If the column is narrower than the
3287 ellipses string, only part of the ellipses string will be shown."
3288 :group 'org-properties
3289 :type 'string)
3291 (defcustom org-columns-modify-value-for-display-function nil
3292 "Function that modifies values for display in column view.
3293 For example, it can be used to cut out a certain part from a time stamp.
3294 The function must take 2 arguments:
3296 column-title The title of the column (*not* the property name)
3297 value The value that should be modified.
3299 The function should return the value that should be displayed,
3300 or nil if the normal value should be used."
3301 :group 'org-properties
3302 :type 'function)
3304 (defcustom org-effort-property "Effort"
3305 "The property that is being used to keep track of effort estimates.
3306 Effort estimates given in this property need to have the format H:MM."
3307 :group 'org-properties
3308 :group 'org-progress
3309 :type '(string :tag "Property"))
3311 (defconst org-global-properties-fixed
3312 '(("VISIBILITY_ALL" . "folded children content all")
3313 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3314 "List of property/value pairs that can be inherited by any entry.
3316 These are fixed values, for the preset properties. The user variable
3317 that can be used to add to this list is `org-global-properties'.
3319 The entries in this list are cons cells where the car is a property
3320 name and cdr is a string with the value. If the value represents
3321 multiple items like an \"_ALL\" property, separate the items by
3322 spaces.")
3324 (defcustom org-global-properties nil
3325 "List of property/value pairs that can be inherited by any entry.
3327 This list will be combined with the constant `org-global-properties-fixed'.
3329 The entries in this list are cons cells where the car is a property
3330 name and cdr is a string with the value.
3332 You can set buffer-local values for the same purpose in the variable
3333 `org-file-properties' this by adding lines like
3335 #+PROPERTY: NAME VALUE"
3336 :group 'org-properties
3337 :type '(repeat
3338 (cons (string :tag "Property")
3339 (string :tag "Value"))))
3341 (defvar org-file-properties nil
3342 "List of property/value pairs that can be inherited by any entry.
3343 Valid for the current buffer.
3344 This variable is populated from #+PROPERTY lines.")
3345 (make-variable-buffer-local 'org-file-properties)
3347 (defgroup org-agenda nil
3348 "Options concerning agenda views in Org-mode."
3349 :tag "Org Agenda"
3350 :group 'org)
3352 (defvar org-category nil
3353 "Variable used by org files to set a category for agenda display.
3354 Such files should use a file variable to set it, for example
3356 # -*- mode: org; org-category: \"ELisp\"
3358 or contain a special line
3360 #+CATEGORY: ELisp
3362 If the file does not specify a category, then file's base name
3363 is used instead.")
3364 (make-variable-buffer-local 'org-category)
3365 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3367 (defcustom org-agenda-files nil
3368 "The files to be used for agenda display.
3369 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3370 \\[org-remove-file]. You can also use customize to edit the list.
3372 If an entry is a directory, all files in that directory that are matched by
3373 `org-agenda-file-regexp' will be part of the file list.
3375 If the value of the variable is not a list but a single file name, then
3376 the list of agenda files is actually stored and maintained in that file, one
3377 agenda file per line. In this file paths can be given relative to
3378 `org-directory'. Tilde expansion and environment variable substitution
3379 are also made."
3380 :group 'org-agenda
3381 :type '(choice
3382 (repeat :tag "List of files and directories" file)
3383 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3385 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3386 "Regular expression to match files for `org-agenda-files'.
3387 If any element in the list in that variable contains a directory instead
3388 of a normal file, all files in that directory that are matched by this
3389 regular expression will be included."
3390 :group 'org-agenda
3391 :type 'regexp)
3393 (defcustom org-agenda-text-search-extra-files nil
3394 "List of extra files to be searched by text search commands.
3395 These files will be search in addition to the agenda files by the
3396 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3397 Note that these files will only be searched for text search commands,
3398 not for the other agenda views like todo lists, tag searches or the weekly
3399 agenda. This variable is intended to list notes and possibly archive files
3400 that should also be searched by these two commands.
3401 In fact, if the first element in the list is the symbol `agenda-archives',
3402 than all archive files of all agenda files will be added to the search
3403 scope."
3404 :group 'org-agenda
3405 :type '(set :greedy t
3406 (const :tag "Agenda Archives" agenda-archives)
3407 (repeat :inline t (file))))
3409 (if (fboundp 'defvaralias)
3410 (defvaralias 'org-agenda-multi-occur-extra-files
3411 'org-agenda-text-search-extra-files))
3413 (defcustom org-agenda-skip-unavailable-files nil
3414 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3415 A nil value means to remove them, after a query, from the list."
3416 :group 'org-agenda
3417 :type 'boolean)
3419 (defcustom org-calendar-to-agenda-key [?c]
3420 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3421 The command `org-calendar-goto-agenda' will be bound to this key. The
3422 default is the character `c' because then `c' can be used to switch back and
3423 forth between agenda and calendar."
3424 :group 'org-agenda
3425 :type 'sexp)
3427 (defcustom org-calendar-insert-diary-entry-key [?i]
3428 "The key to be installed in `calendar-mode-map' for adding diary entries.
3429 This option is irrelevant until `org-agenda-diary-file' has been configured
3430 to point to an Org-mode file. When that is the case, the command
3431 `org-agenda-diary-entry' will be bound to the key given here, by default
3432 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3433 if you want to continue doing this, you need to change this to a different
3434 key."
3435 :group 'org-agenda
3436 :type 'sexp)
3438 (defcustom org-agenda-diary-file 'diary-file
3439 "File to which to add new entries with the `i' key in agenda and calendar.
3440 When this is the symbol `diary-file', the functionality in the Emacs
3441 calendar will be used to add entries to the `diary-file'. But when this
3442 points to a file, `org-agenda-diary-entry' will be used instead."
3443 :group 'org-agenda
3444 :type '(choice
3445 (const :tag "The standard Emacs diary file" diary-file)
3446 (file :tag "Special Org file diary entries")))
3448 (eval-after-load "calendar"
3449 '(progn
3450 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3451 'org-calendar-goto-agenda)
3452 (add-hook 'calendar-mode-hook
3453 (lambda ()
3454 (unless (eq org-agenda-diary-file 'diary-file)
3455 (define-key calendar-mode-map
3456 org-calendar-insert-diary-entry-key
3457 'org-agenda-diary-entry))))))
3459 (defgroup org-latex nil
3460 "Options for embedding LaTeX code into Org-mode."
3461 :tag "Org LaTeX"
3462 :group 'org)
3464 (defcustom org-format-latex-options
3465 '(:foreground default :background default :scale 1.0
3466 :html-foreground "Black" :html-background "Transparent"
3467 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3468 "Options for creating images from LaTeX fragments.
3469 This is a property list with the following properties:
3470 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3471 `default' means use the foreground of the default face.
3472 `auto' means use the foreground from the text face.
3473 :background the background color, or \"Transparent\".
3474 `default' means use the background of the default face.
3475 `auto' means use the background from the text face.
3476 :scale a scaling factor for the size of the images, to get more pixels
3477 :html-foreground, :html-background, :html-scale
3478 the same numbers for HTML export.
3479 :matchers a list indicating which matchers should be used to
3480 find LaTeX fragments. Valid members of this list are:
3481 \"begin\" find environments
3482 \"$1\" find single characters surrounded by $.$
3483 \"$\" find math expressions surrounded by $...$
3484 \"$$\" find math expressions surrounded by $$....$$
3485 \"\\(\" find math expressions surrounded by \\(...\\)
3486 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3487 :group 'org-latex
3488 :type 'plist)
3490 (defcustom org-format-latex-signal-error t
3491 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3492 When nil, just push out a message."
3493 :group 'org-latex
3494 :version "24.1"
3495 :type 'boolean)
3497 (defcustom org-latex-to-mathml-jar-file nil
3498 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3499 Use this to specify additional executable file say a jar file.
3501 When using MathToWeb as the converter, specify the full-path to
3502 your mathtoweb.jar file."
3503 :group 'org-latex
3504 :version "24.1"
3505 :type '(choice
3506 (const :tag "None" nil)
3507 (file :tag "JAR file" :must-match t)))
3509 (defcustom org-latex-to-mathml-convert-command nil
3510 "Command to convert LaTeX fragments to MathML.
3511 Replace format-specifiers in the command as noted below and use
3512 `shell-command' to convert LaTeX to MathML.
3513 %j: Executable file in fully expanded form as specified by
3514 `org-latex-to-mathml-jar-file'.
3515 %I: Input LaTeX file in fully expanded form
3516 %o: Output MathML file
3517 This command is used by `org-create-math-formula'.
3519 When using MathToWeb as the converter, set this to
3520 \"java -jar %j -unicode -force -df %o %I\"."
3521 :group 'org-latex
3522 :version "24.1"
3523 :type '(choice
3524 (const :tag "None" nil)
3525 (string :tag "\nShell command")))
3527 (defcustom org-latex-create-formula-image-program 'dvipng
3528 "Program to convert LaTeX fragments with.
3530 dvipng Process the LaTeX fragments to dvi file, then convert
3531 dvi files to png files using dvipng.
3532 This will also include processing of non-math environments.
3533 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3534 to convert pdf files to png files"
3535 :group 'org-latex
3536 :version "24.1"
3537 :type '(choice
3538 (const :tag "dvipng" dvipng)
3539 (const :tag "imagemagick" imagemagick)))
3541 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3542 "Path to store latex preview images.
3543 A relative path here creates many directories relative to the
3544 processed org files paths. An absolute path puts all preview
3545 images at the same place."
3546 :group 'org-latex
3547 :version "24.3"
3548 :type 'string)
3550 (defun org-format-latex-mathml-available-p ()
3551 "Return t if `org-latex-to-mathml-convert-command' is usable."
3552 (save-match-data
3553 (when (and (boundp 'org-latex-to-mathml-convert-command)
3554 org-latex-to-mathml-convert-command)
3555 (let ((executable (car (split-string
3556 org-latex-to-mathml-convert-command))))
3557 (when (executable-find executable)
3558 (if (string-match
3559 "%j" org-latex-to-mathml-convert-command)
3560 (file-readable-p org-latex-to-mathml-jar-file)
3561 t))))))
3563 (defcustom org-format-latex-header "\\documentclass{article}
3564 \\usepackage[usenames]{color}
3565 \\usepackage{amsmath}
3566 \\usepackage[mathscr]{eucal}
3567 \\pagestyle{empty} % do not remove
3568 \[PACKAGES]
3569 \[DEFAULT-PACKAGES]
3570 % The settings below are copied from fullpage.sty
3571 \\setlength{\\textwidth}{\\paperwidth}
3572 \\addtolength{\\textwidth}{-3cm}
3573 \\setlength{\\oddsidemargin}{1.5cm}
3574 \\addtolength{\\oddsidemargin}{-2.54cm}
3575 \\setlength{\\evensidemargin}{\\oddsidemargin}
3576 \\setlength{\\textheight}{\\paperheight}
3577 \\addtolength{\\textheight}{-\\headheight}
3578 \\addtolength{\\textheight}{-\\headsep}
3579 \\addtolength{\\textheight}{-\\footskip}
3580 \\addtolength{\\textheight}{-3cm}
3581 \\setlength{\\topmargin}{1.5cm}
3582 \\addtolength{\\topmargin}{-2.54cm}"
3583 "The document header used for processing LaTeX fragments.
3584 It is imperative that this header make sure that no page number
3585 appears on the page. The package defined in the variables
3586 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3587 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3588 will be appended."
3589 :group 'org-latex
3590 :type 'string)
3592 (defvar org-format-latex-header-extra nil)
3594 (defun org-set-packages-alist (var val)
3595 "Set the packages alist and make sure it has 3 elements per entry."
3596 (set var (mapcar (lambda (x)
3597 (if (and (consp x) (= (length x) 2))
3598 (list (car x) (nth 1 x) t)
3600 val)))
3602 (defun org-get-packages-alist (var)
3604 "Get the packages alist and make sure it has 3 elements per entry."
3605 (mapcar (lambda (x)
3606 (if (and (consp x) (= (length x) 2))
3607 (list (car x) (nth 1 x) t)
3609 (default-value var)))
3611 ;; The following variables are defined here because is it also used
3612 ;; when formatting latex fragments. Originally it was part of the
3613 ;; LaTeX exporter, which is why the name includes "export".
3614 (defcustom org-export-latex-default-packages-alist
3615 '(("AUTO" "inputenc" t)
3616 ("T1" "fontenc" t)
3617 ("" "fixltx2e" nil)
3618 ("" "graphicx" t)
3619 ("" "longtable" nil)
3620 ("" "float" nil)
3621 ("" "wrapfig" nil)
3622 ("" "soul" t)
3623 ("" "textcomp" t)
3624 ("" "marvosym" t)
3625 ("" "wasysym" t)
3626 ("" "latexsym" t)
3627 ("" "amssymb" t)
3628 ("" "hyperref" nil)
3629 "\\tolerance=1000"
3631 "Alist of default packages to be inserted in the header.
3632 Change this only if one of the packages here causes an incompatibility
3633 with another package you are using.
3634 The packages in this list are needed by one part or another of Org-mode
3635 to function properly.
3637 - inputenc, fontenc: for basic font and character selection
3638 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3639 for interpreting the entities in `org-entities'. You can skip some of these
3640 packages if you don't use any of the symbols in it.
3641 - graphicx: for including images
3642 - float, wrapfig: for figure placement
3643 - longtable: for long tables
3644 - hyperref: for cross references
3646 Therefore you should not modify this variable unless you know what you
3647 are doing. The one reason to change it anyway is that you might be loading
3648 some other package that conflicts with one of the default packages.
3649 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3650 If SNIPPET-FLAG is t, the package also needs to be included when
3651 compiling LaTeX snippets into images for inclusion into HTML."
3652 :group 'org-export-latex
3653 :set 'org-set-packages-alist
3654 :get 'org-get-packages-alist
3655 :version "24.1"
3656 :type '(repeat
3657 (choice
3658 (list :tag "options/package pair"
3659 (string :tag "options")
3660 (string :tag "package")
3661 (boolean :tag "Snippet"))
3662 (string :tag "A line of LaTeX"))))
3664 (defcustom org-export-latex-packages-alist nil
3665 "Alist of packages to be inserted in every LaTeX header.
3666 These will be inserted after `org-export-latex-default-packages-alist'.
3667 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3668 SNIPPET-FLAG, when t, indicates that this package is also needed when
3669 turning LaTeX snippets into images for inclusion into HTML.
3670 Make sure that you only list packages here which:
3671 - you want in every file
3672 - do not conflict with the default packages in
3673 `org-export-latex-default-packages-alist'
3674 - do not conflict with the setup in `org-format-latex-header'."
3675 :group 'org-export-latex
3676 :set 'org-set-packages-alist
3677 :get 'org-get-packages-alist
3678 :type '(repeat
3679 (choice
3680 (list :tag "options/package pair"
3681 (string :tag "options")
3682 (string :tag "package")
3683 (boolean :tag "Snippet"))
3684 (string :tag "A line of LaTeX"))))
3687 (defgroup org-appearance nil
3688 "Settings for Org-mode appearance."
3689 :tag "Org Appearance"
3690 :group 'org)
3692 (defcustom org-level-color-stars-only nil
3693 "Non-nil means fontify only the stars in each headline.
3694 When nil, the entire headline is fontified.
3695 Changing it requires restart of `font-lock-mode' to become effective
3696 also in regions already fontified."
3697 :group 'org-appearance
3698 :type 'boolean)
3700 (defcustom org-hide-leading-stars nil
3701 "Non-nil means hide the first N-1 stars in a headline.
3702 This works by using the face `org-hide' for these stars. This
3703 face is white for a light background, and black for a dark
3704 background. You may have to customize the face `org-hide' to
3705 make this work.
3706 Changing it requires restart of `font-lock-mode' to become effective
3707 also in regions already fontified.
3708 You may also set this on a per-file basis by adding one of the following
3709 lines to the buffer:
3711 #+STARTUP: hidestars
3712 #+STARTUP: showstars"
3713 :group 'org-appearance
3714 :type 'boolean)
3716 (defcustom org-hidden-keywords nil
3717 "List of symbols corresponding to keywords to be hidden the org buffer.
3718 For example, a value '(title) for this list will make the document's title
3719 appear in the buffer without the initial #+TITLE: keyword."
3720 :group 'org-appearance
3721 :version "24.1"
3722 :type '(set (const :tag "#+AUTHOR" author)
3723 (const :tag "#+DATE" date)
3724 (const :tag "#+EMAIL" email)
3725 (const :tag "#+TITLE" title)))
3727 (defcustom org-custom-properties nil
3728 "List of properties (as strings) with a special meaning.
3729 The default use of these custom properties is to let the user
3730 hide them with `org-toggle-custom-properties-visibility'."
3731 :group 'org-properties
3732 :group 'org-appearance
3733 :version "24.3"
3734 :type '(repeat (string :tag "Property Name")))
3736 (defcustom org-fontify-done-headline nil
3737 "Non-nil means change the face of a headline if it is marked DONE.
3738 Normally, only the TODO/DONE keyword indicates the state of a headline.
3739 When this is non-nil, the headline after the keyword is set to the
3740 `org-headline-done' as an additional indication."
3741 :group 'org-appearance
3742 :type 'boolean)
3744 (defcustom org-fontify-emphasized-text t
3745 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3746 Changing this variable requires a restart of Emacs to take effect."
3747 :group 'org-appearance
3748 :type 'boolean)
3750 (defcustom org-fontify-whole-heading-line nil
3751 "Non-nil means fontify the whole line for headings.
3752 This is useful when setting a background color for the
3753 org-level-* faces."
3754 :group 'org-appearance
3755 :type 'boolean)
3757 (defcustom org-highlight-latex-fragments-and-specials nil
3758 "Non-nil means fontify what is treated specially by the exporters."
3759 :group 'org-appearance
3760 :type 'boolean)
3762 (defcustom org-hide-emphasis-markers nil
3763 "Non-nil mean font-lock should hide the emphasis marker characters."
3764 :group 'org-appearance
3765 :type 'boolean)
3767 (defcustom org-pretty-entities nil
3768 "Non-nil means show entities as UTF8 characters.
3769 When nil, the \\name form remains in the buffer."
3770 :group 'org-appearance
3771 :version "24.1"
3772 :type 'boolean)
3774 (defcustom org-pretty-entities-include-sub-superscripts t
3775 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3776 :group 'org-appearance
3777 :version "24.1"
3778 :type 'boolean)
3780 (defvar org-emph-re nil
3781 "Regular expression for matching emphasis.
3782 After a match, the match groups contain these elements:
3783 0 The match of the full regular expression, including the characters
3784 before and after the proper match
3785 1 The character before the proper match, or empty at beginning of line
3786 2 The proper match, including the leading and trailing markers
3787 3 The leading marker like * or /, indicating the type of highlighting
3788 4 The text between the emphasis markers, not including the markers
3789 5 The character after the match, empty at the end of a line")
3790 (defvar org-verbatim-re nil
3791 "Regular expression for matching verbatim text.")
3792 (defvar org-emphasis-regexp-components) ; defined just below
3793 (defvar org-emphasis-alist) ; defined just below
3794 (defun org-set-emph-re (var val)
3795 "Set variable and compute the emphasis regular expression."
3796 (set var val)
3797 (when (and (boundp 'org-emphasis-alist)
3798 (boundp 'org-emphasis-regexp-components)
3799 org-emphasis-alist org-emphasis-regexp-components)
3800 (let* ((e org-emphasis-regexp-components)
3801 (pre (car e))
3802 (post (nth 1 e))
3803 (border (nth 2 e))
3804 (body (nth 3 e))
3805 (nl (nth 4 e))
3806 (body1 (concat body "*?"))
3807 (markers (mapconcat 'car org-emphasis-alist ""))
3808 (vmarkers (mapconcat
3809 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3810 org-emphasis-alist "")))
3811 ;; make sure special characters appear at the right position in the class
3812 (if (string-match "\\^" markers)
3813 (setq markers (concat (replace-match "" t t markers) "^")))
3814 (if (string-match "-" markers)
3815 (setq markers (concat (replace-match "" t t markers) "-")))
3816 (if (string-match "\\^" vmarkers)
3817 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3818 (if (string-match "-" vmarkers)
3819 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3820 (if (> nl 0)
3821 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3822 (int-to-string nl) "\\}")))
3823 ;; Make the regexp
3824 (setq org-emph-re
3825 (concat "\\([" pre "]\\|^\\)"
3826 "\\("
3827 "\\([" markers "]\\)"
3828 "\\("
3829 "[^" border "]\\|"
3830 "[^" border "]"
3831 body1
3832 "[^" border "]"
3833 "\\)"
3834 "\\3\\)"
3835 "\\([" post "]\\|$\\)"))
3836 (setq org-verbatim-re
3837 (concat "\\([" pre "]\\|^\\)"
3838 "\\("
3839 "\\([" vmarkers "]\\)"
3840 "\\("
3841 "[^" border "]\\|"
3842 "[^" border "]"
3843 body1
3844 "[^" border "]"
3845 "\\)"
3846 "\\3\\)"
3847 "\\([" post "]\\|$\\)")))))
3849 (defcustom org-emphasis-regexp-components
3850 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3851 "Components used to build the regular expression for emphasis.
3852 This is a list with five entries. Terminology: In an emphasis string
3853 like \" *strong word* \", we call the initial space PREMATCH, the final
3854 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3855 and \"trong wor\" is the body. The different components in this variable
3856 specify what is allowed/forbidden in each part:
3858 pre Chars allowed as prematch. Beginning of line will be allowed too.
3859 post Chars allowed as postmatch. End of line will be allowed too.
3860 border The chars *forbidden* as border characters.
3861 body-regexp A regexp like \".\" to match a body character. Don't use
3862 non-shy groups here, and don't allow newline here.
3863 newline The maximum number of newlines allowed in an emphasis exp.
3865 Use customize to modify this, or restart Emacs after changing it."
3866 :group 'org-appearance
3867 :set 'org-set-emph-re
3868 :type '(list
3869 (sexp :tag "Allowed chars in pre ")
3870 (sexp :tag "Allowed chars in post ")
3871 (sexp :tag "Forbidden chars in border ")
3872 (sexp :tag "Regexp for body ")
3873 (integer :tag "number of newlines allowed")
3874 (option (boolean :tag "Please ignore this button"))))
3876 (defcustom org-emphasis-alist
3877 `(("*" bold "<b>" "</b>")
3878 ("/" italic "<i>" "</i>")
3879 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3880 ("=" org-code "<code>" "</code>" verbatim)
3881 ("~" org-verbatim "<code>" "</code>" verbatim)
3882 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3883 "<del>" "</del>")
3885 "Special syntax for emphasized text.
3886 Text starting and ending with a special character will be emphasized, for
3887 example *bold*, _underlined_ and /italic/. This variable sets the marker
3888 characters, the face to be used by font-lock for highlighting in Org-mode
3889 Emacs buffers, and the HTML tags to be used for this.
3890 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3891 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3892 Use customize to modify this, or restart Emacs after changing it."
3893 :group 'org-appearance
3894 :set 'org-set-emph-re
3895 :type '(repeat
3896 (list
3897 (string :tag "Marker character")
3898 (choice
3899 (face :tag "Font-lock-face")
3900 (plist :tag "Face property list"))
3901 (string :tag "HTML start tag")
3902 (string :tag "HTML end tag")
3903 (option (const verbatim)))))
3905 (defvar org-syntax-table
3906 (let ((st (make-syntax-table)))
3907 (mapc (lambda(c) (modify-syntax-entry
3908 (string-to-char (car c)) "w p" st))
3909 org-emphasis-alist)
3910 st))
3912 (defvar org-protecting-blocks
3913 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3914 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3915 This is needed for font-lock setup.")
3917 ;;; Miscellaneous options
3919 (defgroup org-completion nil
3920 "Completion in Org-mode."
3921 :tag "Org Completion"
3922 :group 'org)
3924 (defcustom org-completion-use-ido nil
3925 "Non-nil means use ido completion wherever possible.
3926 Note that `ido-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 See also `org-completion-use-iswitchb'."
3930 :group 'org-completion
3931 :type 'boolean)
3933 (defcustom org-completion-use-iswitchb nil
3934 "Non-nil means use iswitchb completion wherever possible.
3935 Note that `iswitchb-mode' must be active for this variable to be relevant.
3936 If you decide to turn this variable on, you might well want to turn off
3937 `org-outline-path-complete-in-steps'.
3938 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3939 :group 'org-completion
3940 :type 'boolean)
3942 (defcustom org-completion-fallback-command 'hippie-expand
3943 "The expansion command called by \\[pcomplete] in normal context.
3944 Normal means, no org-mode-specific context."
3945 :group 'org-completion
3946 :type 'function)
3948 ;;; Functions and variables from their packages
3949 ;; Declared here to avoid compiler warnings
3951 ;; XEmacs only
3952 (defvar outline-mode-menu-heading)
3953 (defvar outline-mode-menu-show)
3954 (defvar outline-mode-menu-hide)
3955 (defvar zmacs-regions) ; XEmacs regions
3957 ;; Emacs only
3958 (defvar mark-active)
3960 ;; Various packages
3961 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3962 (declare-function calendar-forward-day "cal-move" (arg))
3963 (declare-function calendar-goto-date "cal-move" (date))
3964 (declare-function calendar-goto-today "cal-move" ())
3965 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3966 (defvar calc-embedded-close-formula)
3967 (defvar calc-embedded-open-formula)
3968 (declare-function cdlatex-tab "ext:cdlatex" ())
3969 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3970 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3971 (defvar font-lock-unfontify-region-function)
3972 (declare-function iswitchb-read-buffer "iswitchb"
3973 (prompt &optional default require-match start matches-set))
3974 (defvar iswitchb-temp-buflist)
3975 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3976 (defvar org-agenda-tags-todo-honor-ignore-options)
3977 (declare-function org-agenda-skip "org-agenda" ())
3978 (declare-function
3979 org-agenda-format-item "org-agenda"
3980 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3981 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3982 (declare-function org-agenda-change-all-lines "org-agenda"
3983 (newhead hdmarker &optional fixface just-this))
3984 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3985 (declare-function org-agenda-maybe-redo "org-agenda" ())
3986 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3987 (beg end))
3988 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3989 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3990 "org-agenda" (&optional end))
3991 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3992 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3993 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3994 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3995 (declare-function org-indent-mode "org-indent" (&optional arg))
3996 (declare-function parse-time-string "parse-time" (string))
3997 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3998 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3999 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4000 (defvar remember-data-file)
4001 (defvar texmathp-why)
4002 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4003 (declare-function table--at-cell-p "table" (position &optional object at-column))
4005 (defvar org-latex-regexps)
4007 ;;; Autoload and prepare some org modules
4009 ;; Some table stuff that needs to be defined here, because it is used
4010 ;; by the functions setting up org-mode or checking for table context.
4012 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4013 "Detect an org-type or table-type table.")
4014 (defconst org-table-line-regexp "^[ \t]*|"
4015 "Detect an org-type table line.")
4016 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4017 "Detect an org-type table line.")
4018 (defconst org-table-hline-regexp "^[ \t]*|-"
4019 "Detect an org-type table hline.")
4020 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4021 "Detect a table-type table hline.")
4022 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4023 "Detect the first line outside a table when searching from within it.
4024 This works for both table types.")
4026 ;; Autoload the functions in org-table.el that are needed by functions here.
4028 (eval-and-compile
4029 (org-autoload "org-table"
4030 '(org-table-begin org-table-blank-field org-table-end)))
4032 ;;;###autoload
4033 (defun turn-on-orgtbl ()
4034 "Unconditionally turn on `orgtbl-mode'."
4035 (require 'org-table)
4036 (orgtbl-mode 1))
4038 (defun org-at-table-p (&optional table-type)
4039 "Return t if the cursor is inside an org-type table.
4040 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4041 (if org-enable-table-editor
4042 (save-excursion
4043 (beginning-of-line 1)
4044 (looking-at (if table-type org-table-any-line-regexp
4045 org-table-line-regexp)))
4046 nil))
4047 (defsubst org-table-p () (org-at-table-p))
4049 (defun org-at-table.el-p ()
4050 "Return t if and only if we are at a table.el table."
4051 (and (org-at-table-p 'any)
4052 (save-excursion
4053 (goto-char (org-table-begin 'any))
4054 (looking-at org-table1-hline-regexp))))
4055 (defun org-table-recognize-table.el ()
4056 "If there is a table.el table nearby, recognize it and move into it."
4057 (if org-table-tab-recognizes-table.el
4058 (if (org-at-table.el-p)
4059 (progn
4060 (beginning-of-line 1)
4061 (if (looking-at org-table-dataline-regexp)
4063 (if (looking-at org-table1-hline-regexp)
4064 (progn
4065 (beginning-of-line 2)
4066 (if (looking-at org-table-any-border-regexp)
4067 (beginning-of-line -1)))))
4068 (if (re-search-forward "|" (org-table-end t) t)
4069 (progn
4070 (require 'table)
4071 (if (table--at-cell-p (point))
4073 (message "recognizing table.el table...")
4074 (table-recognize-table)
4075 (message "recognizing table.el table...done")))
4076 (error "This should not happen"))
4078 nil)
4079 nil))
4081 (defun org-at-table-hline-p ()
4082 "Return t if the cursor is inside a hline in a table."
4083 (if org-enable-table-editor
4084 (save-excursion
4085 (beginning-of-line 1)
4086 (looking-at org-table-hline-regexp))
4087 nil))
4089 (defvar org-table-clean-did-remove-column nil)
4091 (defun org-table-map-tables (function &optional quietly)
4092 "Apply FUNCTION to the start of all tables in the buffer."
4093 (save-excursion
4094 (save-restriction
4095 (widen)
4096 (goto-char (point-min))
4097 (while (re-search-forward org-table-any-line-regexp nil t)
4098 (unless quietly
4099 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4100 (beginning-of-line 1)
4101 (when (and (looking-at org-table-line-regexp)
4102 ;; Exclude tables in src/example/verbatim/clocktable blocks
4103 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4104 (save-excursion (funcall function))
4105 (or (looking-at org-table-line-regexp)
4106 (forward-char 1)))
4107 (re-search-forward org-table-any-border-regexp nil 1))))
4108 (unless quietly (message "Mapping tables: done")))
4110 ;; Declare and autoload functions from org-exp.el & Co
4112 (declare-function org-default-export-plist "org-exp")
4113 (declare-function org-infile-export-plist "org-exp")
4114 (declare-function org-get-current-options "org-exp")
4116 ;; Declare and autoload functions from org-agenda.el
4118 (eval-and-compile
4119 (org-autoload "org-agenda"
4120 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4122 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4123 (declare-function org-clock-update-mode-line "org-clock" ())
4124 (declare-function org-resolve-clocks "org-clock"
4125 (&optional also-non-dangling-p prompt last-valid))
4126 (defvar org-clock-start-time)
4127 (defvar org-clock-marker (make-marker)
4128 "Marker recording the last clock-in.")
4129 (defvar org-clock-hd-marker (make-marker)
4130 "Marker recording the last clock-in, but the headline position.")
4131 (defvar org-clock-heading ""
4132 "The heading of the current clock entry.")
4133 (defun org-clock-is-active ()
4134 "Return non-nil if clock is currently running.
4135 The return value is actually the clock marker."
4136 (marker-buffer org-clock-marker))
4138 (eval-and-compile
4139 (org-autoload "org-clock" '(org-clock-remove-overlays
4140 org-clock-update-time-maybe
4141 org-clocktable-shift)))
4143 (defun org-check-running-clock ()
4144 "Check if the current buffer contains the running clock.
4145 If yes, offer to stop it and to save the buffer with the changes."
4146 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4147 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4148 (buffer-name))))
4149 (org-clock-out)
4150 (when (y-or-n-p "Save changed buffer?")
4151 (save-buffer))))
4153 (defun org-clocktable-try-shift (dir n)
4154 "Check if this line starts a clock table, if yes, shift the time block."
4155 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4156 (org-clocktable-shift dir n)))
4158 ;;;###autoload
4159 (defun org-clock-persistence-insinuate ()
4160 "Set up hooks for clock persistence."
4161 (require 'org-clock)
4162 (add-hook 'org-mode-hook 'org-clock-load)
4163 (add-hook 'kill-emacs-hook 'org-clock-save))
4165 ;; Define the variable already here, to make sure we have it.
4166 (defvar org-indent-mode nil
4167 "Non-nil if Org-Indent mode is enabled.
4168 Use the command `org-indent-mode' to change this variable.")
4170 ;; Autoload archiving code
4171 ;; The stuff that is needed for cycling and tags has to be defined here.
4173 (defgroup org-archive nil
4174 "Options concerning archiving in Org-mode."
4175 :tag "Org Archive"
4176 :group 'org-structure)
4178 (defcustom org-archive-location "%s_archive::"
4179 "The location where subtrees should be archived.
4181 The value of this variable is a string, consisting of two parts,
4182 separated by a double-colon. The first part is a filename and
4183 the second part is a headline.
4185 When the filename is omitted, archiving happens in the same file.
4186 %s in the filename will be replaced by the current file
4187 name (without the directory part). Archiving to a different file
4188 is useful to keep archived entries from contributing to the
4189 Org-mode Agenda.
4191 The archived entries will be filed as subtrees of the specified
4192 headline. When the headline is omitted, the subtrees are simply
4193 filed away at the end of the file, as top-level entries. Also in
4194 the heading you can use %s to represent the file name, this can be
4195 useful when using the same archive for a number of different files.
4197 Here are a few examples:
4198 \"%s_archive::\"
4199 If the current file is Projects.org, archive in file
4200 Projects.org_archive, as top-level trees. This is the default.
4202 \"::* Archived Tasks\"
4203 Archive in the current file, under the top-level headline
4204 \"* Archived Tasks\".
4206 \"~/org/archive.org::\"
4207 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4209 \"~/org/archive.org::* From %s\"
4210 Archive in file ~/org/archive.org (absolute path), under headlines
4211 \"From FILENAME\" where file name is the current file name.
4213 \"~/org/datetree.org::datetree/* Finished Tasks\"
4214 The \"datetree/\" string is special, signifying to archive
4215 items to the datetree. Items are placed in either the CLOSED
4216 date of the item, or the current date if there is no CLOSED date.
4217 The heading will be a subentry to the current date. There doesn't
4218 need to be a heading, but there always needs to be a slash after
4219 datetree. For example, to store archived items directly in the
4220 datetree, use \"~/org/datetree.org::datetree/\".
4222 \"basement::** Finished Tasks\"
4223 Archive in file ./basement (relative path), as level 3 trees
4224 below the level 2 heading \"** Finished Tasks\".
4226 You may set this option on a per-file basis by adding to the buffer a
4227 line like
4229 #+ARCHIVE: basement::** Finished Tasks
4231 You may also define it locally for a subtree by setting an ARCHIVE property
4232 in the entry. If such a property is found in an entry, or anywhere up
4233 the hierarchy, it will be used."
4234 :group 'org-archive
4235 :type 'string)
4237 (defcustom org-archive-tag "ARCHIVE"
4238 "The tag that marks a subtree as archived.
4239 An archived subtree does not open during visibility cycling, and does
4240 not contribute to the agenda listings.
4241 After changing this, font-lock must be restarted in the relevant buffers to
4242 get the proper fontification."
4243 :group 'org-archive
4244 :group 'org-keywords
4245 :type 'string)
4247 (defcustom org-agenda-skip-archived-trees t
4248 "Non-nil means the agenda will skip any items located in archived trees.
4249 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4250 variable is no longer recommended, you should leave it at the value t.
4251 Instead, use the key `v' to cycle the archives-mode in the agenda."
4252 :group 'org-archive
4253 :group 'org-agenda-skip
4254 :type 'boolean)
4256 (defcustom org-columns-skip-archived-trees t
4257 "Non-nil means ignore archived trees when creating column view."
4258 :group 'org-archive
4259 :group 'org-properties
4260 :type 'boolean)
4262 (defcustom org-cycle-open-archived-trees nil
4263 "Non-nil means `org-cycle' will open archived trees.
4264 An archived tree is a tree marked with the tag ARCHIVE.
4265 When nil, archived trees will stay folded. You can still open them with
4266 normal outline commands like `show-all', but not with the cycling commands."
4267 :group 'org-archive
4268 :group 'org-cycle
4269 :type 'boolean)
4271 (defcustom org-sparse-tree-open-archived-trees nil
4272 "Non-nil means sparse tree construction shows matches in archived trees.
4273 When nil, matches in these trees are highlighted, but the trees are kept in
4274 collapsed state."
4275 :group 'org-archive
4276 :group 'org-sparse-trees
4277 :type 'boolean)
4279 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4280 "The default date type when building a sparse tree.
4281 When this is nil, a date is a scheduled or a deadline timestamp.
4282 Otherwise, these types are allowed:
4284 all: all timestamps
4285 active: only active timestamps (<...>)
4286 inactive: only inactive timestamps (<...)
4287 scheduled: only scheduled timestamps
4288 deadline: only deadline timestamps"
4289 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4290 (const :tag "All timestamps" all)
4291 (const :tag "Only active timestamps" active)
4292 (const :tag "Only inactive timestamps" inactive)
4293 (const :tag "Only scheduled timestamps" scheduled)
4294 (const :tag "Only deadline timestamps" deadline))
4295 :version "24.3"
4296 :group 'org-sparse-trees)
4298 (defun org-cycle-hide-archived-subtrees (state)
4299 "Re-hide all archived subtrees after a visibility state change."
4300 (when (and (not org-cycle-open-archived-trees)
4301 (not (memq state '(overview folded))))
4302 (save-excursion
4303 (let* ((globalp (memq state '(contents all)))
4304 (beg (if globalp (point-min) (point)))
4305 (end (if globalp (point-max) (org-end-of-subtree t))))
4306 (org-hide-archived-subtrees beg end)
4307 (goto-char beg)
4308 (if (looking-at (concat ".*:" org-archive-tag ":"))
4309 (message "%s" (substitute-command-keys
4310 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4312 (defun org-force-cycle-archived ()
4313 "Cycle subtree even if it is archived."
4314 (interactive)
4315 (setq this-command 'org-cycle)
4316 (let ((org-cycle-open-archived-trees t))
4317 (call-interactively 'org-cycle)))
4319 (defun org-hide-archived-subtrees (beg end)
4320 "Re-hide all archived subtrees after a visibility state change."
4321 (save-excursion
4322 (let* ((re (concat ":" org-archive-tag ":")))
4323 (goto-char beg)
4324 (while (re-search-forward re end t)
4325 (when (org-at-heading-p)
4326 (org-flag-subtree t)
4327 (org-end-of-subtree t))))))
4329 (declare-function outline-end-of-heading "outline" ())
4330 (declare-function outline-flag-region "outline" (from to flag))
4331 (defun org-flag-subtree (flag)
4332 (save-excursion
4333 (org-back-to-heading t)
4334 (outline-end-of-heading)
4335 (outline-flag-region (point)
4336 (progn (org-end-of-subtree t) (point))
4337 flag)))
4339 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4341 (eval-and-compile
4342 (org-autoload "org-archive"
4343 '(org-add-archive-files)))
4345 ;; Autoload Column View Code
4347 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4348 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4349 (declare-function org-columns-compute "org-colview" (property))
4351 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4352 '(org-columns-number-to-string
4353 org-columns-get-format-and-top-level
4354 org-columns-compute
4355 org-columns-remove-overlays))
4357 ;; Autoload ID code
4359 (declare-function org-id-store-link "org-id")
4360 (declare-function org-id-locations-load "org-id")
4361 (declare-function org-id-locations-save "org-id")
4362 (defvar org-id-track-globally)
4363 (org-autoload "org-id"
4364 '(org-id-new
4365 org-id-copy
4366 org-id-get-with-outline-path-completion
4367 org-id-get-with-outline-drilling))
4369 ;;; Variables for pre-computed regular expressions, all buffer local
4371 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4372 "Matches first line of a hidden block.")
4373 (make-variable-buffer-local 'org-drawer-regexp)
4374 (defvar org-todo-regexp nil
4375 "Matches any of the TODO state keywords.")
4376 (make-variable-buffer-local 'org-todo-regexp)
4377 (defvar org-not-done-regexp nil
4378 "Matches any of the TODO state keywords except the last one.")
4379 (make-variable-buffer-local 'org-not-done-regexp)
4380 (defvar org-not-done-heading-regexp nil
4381 "Matches a TODO headline that is not done.")
4382 (make-variable-buffer-local 'org-not-done-regexp)
4383 (defvar org-todo-line-regexp nil
4384 "Matches a headline and puts TODO state into group 2 if present.")
4385 (make-variable-buffer-local 'org-todo-line-regexp)
4386 (defvar org-complex-heading-regexp nil
4387 "Matches a headline and puts everything into groups:
4388 group 1: the stars
4389 group 2: The todo keyword, maybe
4390 group 3: Priority cookie
4391 group 4: True headline
4392 group 5: Tags")
4393 (make-variable-buffer-local 'org-complex-heading-regexp)
4394 (defvar org-complex-heading-regexp-format nil
4395 "Printf format to make regexp to match an exact headline.
4396 This regexp will match the headline of any node which has the
4397 exact headline text that is put into the format, but may have any
4398 TODO state, priority and tags.")
4399 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4400 (defvar org-todo-line-tags-regexp nil
4401 "Matches a headline and puts TODO state into group 2 if present.
4402 Also put tags into group 4 if tags are present.")
4403 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4404 (defvar org-ds-keyword-length 12
4405 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4406 (make-variable-buffer-local 'org-ds-keyword-length)
4407 (defvar org-deadline-regexp nil
4408 "Matches the DEADLINE keyword.")
4409 (make-variable-buffer-local 'org-deadline-regexp)
4410 (defvar org-deadline-time-regexp nil
4411 "Matches the DEADLINE keyword together with a time stamp.")
4412 (make-variable-buffer-local 'org-deadline-time-regexp)
4413 (defvar org-deadline-line-regexp nil
4414 "Matches the DEADLINE keyword and the rest of the line.")
4415 (make-variable-buffer-local 'org-deadline-line-regexp)
4416 (defvar org-scheduled-regexp nil
4417 "Matches the SCHEDULED keyword.")
4418 (make-variable-buffer-local 'org-scheduled-regexp)
4419 (defvar org-scheduled-time-regexp nil
4420 "Matches the SCHEDULED keyword together with a time stamp.")
4421 (make-variable-buffer-local 'org-scheduled-time-regexp)
4422 (defvar org-closed-time-regexp nil
4423 "Matches the CLOSED keyword together with a time stamp.")
4424 (make-variable-buffer-local 'org-closed-time-regexp)
4426 (defvar org-keyword-time-regexp nil
4427 "Matches any of the 4 keywords, together with the time stamp.")
4428 (make-variable-buffer-local 'org-keyword-time-regexp)
4429 (defvar org-keyword-time-not-clock-regexp nil
4430 "Matches any of the 3 keywords, together with the time stamp.")
4431 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4432 (defvar org-maybe-keyword-time-regexp nil
4433 "Matches a timestamp, possibly preceded by a keyword.")
4434 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4435 (defvar org-all-time-keywords nil
4436 "List of time keywords.")
4437 (make-variable-buffer-local 'org-all-time-keywords)
4439 (defconst org-plain-time-of-day-regexp
4440 (concat
4441 "\\(\\<[012]?[0-9]"
4442 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4443 "\\(--?"
4444 "\\(\\<[012]?[0-9]"
4445 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4446 "\\)?")
4447 "Regular expression to match a plain time or time range.
4448 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4449 groups carry important information:
4450 0 the full match
4451 1 the first time, range or not
4452 8 the second time, if it is a range.")
4454 (defconst org-plain-time-extension-regexp
4455 (concat
4456 "\\(\\<[012]?[0-9]"
4457 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4458 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4459 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4460 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4461 groups carry important information:
4462 0 the full match
4463 7 hours of duration
4464 9 minutes of duration")
4466 (defconst org-stamp-time-of-day-regexp
4467 (concat
4468 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4469 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4470 "\\(--?"
4471 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4472 "Regular expression to match a timestamp time or time range.
4473 After a match, the following groups carry important information:
4474 0 the full match
4475 1 date plus weekday, for back referencing to make sure both times are on the same day
4476 2 the first time, range or not
4477 4 the second time, if it is a range.")
4479 (defconst org-startup-options
4480 '(("fold" org-startup-folded t)
4481 ("overview" org-startup-folded t)
4482 ("nofold" org-startup-folded nil)
4483 ("showall" org-startup-folded nil)
4484 ("showeverything" org-startup-folded showeverything)
4485 ("content" org-startup-folded content)
4486 ("indent" org-startup-indented t)
4487 ("noindent" org-startup-indented nil)
4488 ("hidestars" org-hide-leading-stars t)
4489 ("showstars" org-hide-leading-stars nil)
4490 ("odd" org-odd-levels-only t)
4491 ("oddeven" org-odd-levels-only nil)
4492 ("align" org-startup-align-all-tables t)
4493 ("noalign" org-startup-align-all-tables nil)
4494 ("inlineimages" org-startup-with-inline-images t)
4495 ("noinlineimages" org-startup-with-inline-images nil)
4496 ("customtime" org-display-custom-times t)
4497 ("logdone" org-log-done time)
4498 ("lognotedone" org-log-done note)
4499 ("nologdone" org-log-done nil)
4500 ("lognoteclock-out" org-log-note-clock-out t)
4501 ("nolognoteclock-out" org-log-note-clock-out nil)
4502 ("logrepeat" org-log-repeat state)
4503 ("lognoterepeat" org-log-repeat note)
4504 ("logdrawer" org-log-into-drawer t)
4505 ("nologdrawer" org-log-into-drawer nil)
4506 ("logstatesreversed" org-log-states-order-reversed t)
4507 ("nologstatesreversed" org-log-states-order-reversed nil)
4508 ("nologrepeat" org-log-repeat nil)
4509 ("logreschedule" org-log-reschedule time)
4510 ("lognotereschedule" org-log-reschedule note)
4511 ("nologreschedule" org-log-reschedule nil)
4512 ("logredeadline" org-log-redeadline time)
4513 ("lognoteredeadline" org-log-redeadline note)
4514 ("nologredeadline" org-log-redeadline nil)
4515 ("logrefile" org-log-refile time)
4516 ("lognoterefile" org-log-refile note)
4517 ("nologrefile" org-log-refile nil)
4518 ("fninline" org-footnote-define-inline t)
4519 ("nofninline" org-footnote-define-inline nil)
4520 ("fnlocal" org-footnote-section nil)
4521 ("fnauto" org-footnote-auto-label t)
4522 ("fnprompt" org-footnote-auto-label nil)
4523 ("fnconfirm" org-footnote-auto-label confirm)
4524 ("fnplain" org-footnote-auto-label plain)
4525 ("fnadjust" org-footnote-auto-adjust t)
4526 ("nofnadjust" org-footnote-auto-adjust nil)
4527 ("constcgs" constants-unit-system cgs)
4528 ("constSI" constants-unit-system SI)
4529 ("noptag" org-tag-persistent-alist nil)
4530 ("hideblocks" org-hide-block-startup t)
4531 ("nohideblocks" org-hide-block-startup nil)
4532 ("beamer" org-startup-with-beamer-mode t)
4533 ("entitiespretty" org-pretty-entities t)
4534 ("entitiesplain" org-pretty-entities nil))
4535 "Variable associated with STARTUP options for org-mode.
4536 Each element is a list of three items: the startup options (as written
4537 in the #+STARTUP line), the corresponding variable, and the value to set
4538 this variable to if the option is found. An optional forth element PUSH
4539 means to push this value onto the list in the variable.")
4541 (defun org-update-property-plist (key val props)
4542 "Update PROPS with KEY and VAL."
4543 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4544 (key (if appending (substring key 0 (- (length key) 1)) key))
4545 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4546 (previous (cdr (assoc key props))))
4547 (if appending
4548 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4549 (cons (cons key val) remainder))))
4551 (defconst org-block-regexp
4552 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4553 "Regular expression for hiding blocks.")
4554 (defconst org-heading-keyword-regexp-format
4555 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4556 "Printf format for a regexp matching an headline with some keyword.
4557 This regexp will match the headline of any node which has the
4558 exact keyword that is put into the format. The keyword isn't in
4559 any group by default, but the stars and the body are.")
4560 (defconst org-heading-keyword-maybe-regexp-format
4561 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4562 "Printf format for a regexp matching an headline, possibly with some keyword.
4563 This regexp can match any headline with the specified keyword, or
4564 without a keyword. The keyword isn't in any group by default,
4565 but the stars and the body are.")
4567 (defun org-set-regexps-and-options ()
4568 "Precompute regular expressions for current buffer."
4569 (when (derived-mode-p 'org-mode)
4570 (org-set-local 'org-todo-kwd-alist nil)
4571 (org-set-local 'org-todo-key-alist nil)
4572 (org-set-local 'org-todo-key-trigger nil)
4573 (org-set-local 'org-todo-keywords-1 nil)
4574 (org-set-local 'org-done-keywords nil)
4575 (org-set-local 'org-todo-heads nil)
4576 (org-set-local 'org-todo-sets nil)
4577 (org-set-local 'org-todo-log-states nil)
4578 (org-set-local 'org-file-properties nil)
4579 (org-set-local 'org-file-tags nil)
4580 (let ((re (org-make-options-regexp
4581 '("CATEGORY" "TODO" "COLUMNS"
4582 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4583 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4584 "OPTIONS")
4585 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4586 (splitre "[ \t]+")
4587 (scripts org-use-sub-superscripts)
4588 kwds kws0 kwsa key log value cat arch tags const links hw dws
4589 tail sep kws1 prio props ftags drawers beamer-p
4590 ext-setup-or-nil setup-contents (start 0))
4591 (save-excursion
4592 (save-restriction
4593 (widen)
4594 (goto-char (point-min))
4595 (while (or (and ext-setup-or-nil
4596 (string-match re ext-setup-or-nil start)
4597 (setq start (match-end 0)))
4598 (and (setq ext-setup-or-nil nil start 0)
4599 (re-search-forward re nil t)))
4600 (setq key (upcase (match-string 1 ext-setup-or-nil))
4601 value (org-match-string-no-properties 2 ext-setup-or-nil))
4602 (if (stringp value) (setq value (org-trim value)))
4603 (cond
4604 ((equal key "CATEGORY")
4605 (setq cat value))
4606 ((member key '("SEQ_TODO" "TODO"))
4607 (push (cons 'sequence (org-split-string value splitre)) kwds))
4608 ((equal key "TYP_TODO")
4609 (push (cons 'type (org-split-string value splitre)) kwds))
4610 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4611 ;; general TODO-like setup
4612 (push (cons (intern (downcase (match-string 1 key)))
4613 (org-split-string value splitre)) kwds))
4614 ((equal key "TAGS")
4615 (setq tags (append tags (if tags '("\\n") nil)
4616 (org-split-string value splitre))))
4617 ((equal key "COLUMNS")
4618 (org-set-local 'org-columns-default-format value))
4619 ((equal key "LINK")
4620 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4621 (push (cons (match-string 1 value)
4622 (org-trim (match-string 2 value)))
4623 links)))
4624 ((equal key "PRIORITIES")
4625 (setq prio (org-split-string value " +")))
4626 ((equal key "PROPERTY")
4627 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4628 (setq props (org-update-property-plist (match-string 1 value)
4629 (match-string 2 value)
4630 props))))
4631 ((equal key "FILETAGS")
4632 (when (string-match "\\S-" value)
4633 (setq ftags
4634 (append
4635 ftags
4636 (apply 'append
4637 (mapcar (lambda (x) (org-split-string x ":"))
4638 (org-split-string value)))))))
4639 ((equal key "DRAWERS")
4640 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4641 ((equal key "CONSTANTS")
4642 (setq const (append const (org-split-string value splitre))))
4643 ((equal key "STARTUP")
4644 (let ((opts (org-split-string value splitre))
4645 l var val)
4646 (while (setq l (pop opts))
4647 (when (setq l (assoc l org-startup-options))
4648 (setq var (nth 1 l) val (nth 2 l))
4649 (if (not (nth 3 l))
4650 (set (make-local-variable var) val)
4651 (if (not (listp (symbol-value var)))
4652 (set (make-local-variable var) nil))
4653 (set (make-local-variable var) (symbol-value var))
4654 (add-to-list var val))))))
4655 ((equal key "ARCHIVE")
4656 (setq arch value)
4657 (remove-text-properties 0 (length arch)
4658 '(face t fontified t) arch))
4659 ((equal key "LATEX_CLASS")
4660 (setq beamer-p (equal value "beamer")))
4661 ((equal key "OPTIONS")
4662 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4663 (setq scripts (read (match-string 2 value)))))
4664 ((equal key "SETUPFILE")
4665 (setq setup-contents (org-file-contents
4666 (expand-file-name
4667 (org-remove-double-quotes value))
4668 'noerror))
4669 (if (not ext-setup-or-nil)
4670 (setq ext-setup-or-nil setup-contents start 0)
4671 (setq ext-setup-or-nil
4672 (concat (substring ext-setup-or-nil 0 start)
4673 "\n" setup-contents "\n"
4674 (substring ext-setup-or-nil start)))))))
4675 ;; search for property blocks
4676 (goto-char (point-min))
4677 (while (re-search-forward org-block-regexp nil t)
4678 (when (equal "PROPERTY" (upcase (match-string 1)))
4679 (setq value (replace-regexp-in-string
4680 "[\n\r]" " " (match-string 4)))
4681 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4682 (setq props (org-update-property-plist (match-string 1 value)
4683 (match-string 2 value)
4684 props)))))))
4685 (org-set-local 'org-use-sub-superscripts scripts)
4686 (when cat
4687 (org-set-local 'org-category (intern cat))
4688 (push (cons "CATEGORY" cat) props))
4689 (when prio
4690 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4691 (setq prio (mapcar 'string-to-char prio))
4692 (org-set-local 'org-highest-priority (nth 0 prio))
4693 (org-set-local 'org-lowest-priority (nth 1 prio))
4694 (org-set-local 'org-default-priority (nth 2 prio)))
4695 (and props (org-set-local 'org-file-properties (nreverse props)))
4696 (and ftags (org-set-local 'org-file-tags
4697 (mapcar 'org-add-prop-inherited ftags)))
4698 (and drawers (org-set-local 'org-drawers drawers))
4699 (and arch (org-set-local 'org-archive-location arch))
4700 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4701 ;; Process the TODO keywords
4702 (unless kwds
4703 ;; Use the global values as if they had been given locally.
4704 (setq kwds (default-value 'org-todo-keywords))
4705 (if (stringp (car kwds))
4706 (setq kwds (list (cons org-todo-interpretation
4707 (default-value 'org-todo-keywords)))))
4708 (setq kwds (reverse kwds)))
4709 (setq kwds (nreverse kwds))
4710 (let (inter kws kw)
4711 (while (setq kws (pop kwds))
4712 (let ((kws (or
4713 (run-hook-with-args-until-success
4714 'org-todo-setup-filter-hook kws)
4715 kws)))
4716 (setq inter (pop kws) sep (member "|" kws)
4717 kws0 (delete "|" (copy-sequence kws))
4718 kwsa nil
4719 kws1 (mapcar
4720 (lambda (x)
4721 ;; 1 2
4722 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4723 (progn
4724 (setq kw (match-string 1 x)
4725 key (and (match-end 2) (match-string 2 x))
4726 log (org-extract-log-state-settings x))
4727 (push (cons kw (and key (string-to-char key))) kwsa)
4728 (and log (push log org-todo-log-states))
4730 (error "Invalid TODO keyword %s" x)))
4731 kws0)
4732 kwsa (if kwsa (append '((:startgroup))
4733 (nreverse kwsa)
4734 '((:endgroup))))
4735 hw (car kws1)
4736 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4737 tail (list inter hw (car dws) (org-last dws))))
4738 (add-to-list 'org-todo-heads hw 'append)
4739 (push kws1 org-todo-sets)
4740 (setq org-done-keywords (append org-done-keywords dws nil))
4741 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4742 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4743 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4744 (setq org-todo-sets (nreverse org-todo-sets)
4745 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4746 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4747 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4748 ;; Process the constants
4749 (when const
4750 (let (e cst)
4751 (while (setq e (pop const))
4752 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4753 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4754 (setq org-table-formula-constants-local cst)))
4756 ;; Process the tags.
4757 (when tags
4758 (let (e tgs)
4759 (while (setq e (pop tags))
4760 (cond
4761 ((equal e "{") (push '(:startgroup) tgs))
4762 ((equal e "}") (push '(:endgroup) tgs))
4763 ((equal e "\\n") (push '(:newline) tgs))
4764 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4765 (push (cons (match-string 1 e)
4766 (string-to-char (match-string 2 e)))
4767 tgs))
4768 (t (push (list e) tgs))))
4769 (org-set-local 'org-tag-alist nil)
4770 (while (setq e (pop tgs))
4771 (or (and (stringp (car e))
4772 (assoc (car e) org-tag-alist))
4773 (push e org-tag-alist)))))
4775 ;; Compute the regular expressions and other local variables.
4776 ;; Using `org-outline-regexp-bol' would complicate them much,
4777 ;; because of the fixed white space at the end of that string.
4778 (if (not org-done-keywords)
4779 (setq org-done-keywords (and org-todo-keywords-1
4780 (list (org-last org-todo-keywords-1)))))
4781 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4782 (length org-scheduled-string)
4783 (length org-clock-string)
4784 (length org-closed-string)))
4785 org-drawer-regexp
4786 (concat "^[ \t]*:\\("
4787 (mapconcat 'regexp-quote org-drawers "\\|")
4788 "\\):[ \t]*$")
4789 org-not-done-keywords
4790 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4791 org-todo-regexp
4792 (concat "\\("
4793 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4794 "\\)")
4795 org-not-done-regexp
4796 (concat "\\("
4797 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4798 "\\)")
4799 org-not-done-heading-regexp
4800 (format org-heading-keyword-regexp-format org-not-done-regexp)
4801 org-todo-line-regexp
4802 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4803 org-complex-heading-regexp
4804 (concat "^\\(\\*+\\)"
4805 "\\(?: +" org-todo-regexp "\\)?"
4806 "\\(?: +\\(\\[#.\\]\\)\\)?"
4807 "\\(?: +\\(.*?\\)\\)??"
4808 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4809 "[ \t]*$")
4810 org-complex-heading-regexp-format
4811 (concat "^\\(\\*+\\)"
4812 "\\(?: +" org-todo-regexp "\\)?"
4813 "\\(?: +\\(\\[#.\\]\\)\\)?"
4814 "\\(?: +"
4815 ;; Stats cookies can be stuck to body.
4816 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4817 "\\(%s\\)"
4818 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4819 "\\)"
4820 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4821 "[ \t]*$")
4822 org-todo-line-tags-regexp
4823 (concat "^\\(\\*+\\)"
4824 "\\(?: +" org-todo-regexp "\\)?"
4825 "\\(?: +\\(.*?\\)\\)??"
4826 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4827 "[ \t]*$")
4828 org-deadline-regexp (concat "\\<" org-deadline-string)
4829 org-deadline-time-regexp
4830 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4831 org-deadline-line-regexp
4832 (concat "\\<\\(" org-deadline-string "\\).*")
4833 org-scheduled-regexp
4834 (concat "\\<" org-scheduled-string)
4835 org-scheduled-time-regexp
4836 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4837 org-closed-time-regexp
4838 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4839 org-keyword-time-regexp
4840 (concat "\\<\\(" org-scheduled-string
4841 "\\|" org-deadline-string
4842 "\\|" org-closed-string
4843 "\\|" org-clock-string "\\)"
4844 " *[[<]\\([^]>]+\\)[]>]")
4845 org-keyword-time-not-clock-regexp
4846 (concat "\\<\\(" org-scheduled-string
4847 "\\|" org-deadline-string
4848 "\\|" org-closed-string
4849 "\\)"
4850 " *[[<]\\([^]>]+\\)[]>]")
4851 org-maybe-keyword-time-regexp
4852 (concat "\\(\\<\\(" org-scheduled-string
4853 "\\|" org-deadline-string
4854 "\\|" org-closed-string
4855 "\\|" org-clock-string "\\)\\)?"
4856 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4857 org-all-time-keywords
4858 (mapcar (lambda (w) (substring w 0 -1))
4859 (list org-scheduled-string org-deadline-string
4860 org-clock-string org-closed-string))
4862 (org-compute-latex-and-specials-regexp)
4863 (org-set-font-lock-defaults))))
4865 (defun org-file-contents (file &optional noerror)
4866 "Return the contents of FILE, as a string."
4867 (if (or (not file)
4868 (not (file-readable-p file)))
4869 (if noerror
4870 (progn
4871 (message "Cannot read file \"%s\"" file)
4872 (ding) (sit-for 2)
4874 (error "Cannot read file \"%s\"" file))
4875 (with-temp-buffer
4876 (insert-file-contents file)
4877 (buffer-string))))
4879 (defun org-extract-log-state-settings (x)
4880 "Extract the log state setting from a TODO keyword string.
4881 This will extract info from a string like \"WAIT(w@/!)\"."
4882 (let (kw key log1 log2)
4883 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4884 (setq kw (match-string 1 x)
4885 key (and (match-end 2) (match-string 2 x))
4886 log1 (and (match-end 3) (match-string 3 x))
4887 log2 (and (match-end 4) (match-string 4 x)))
4888 (and (or log1 log2)
4889 (list kw
4890 (and log1 (if (equal log1 "!") 'time 'note))
4891 (and log2 (if (equal log2 "!") 'time 'note)))))))
4893 (defun org-remove-keyword-keys (list)
4894 "Remove a pair of parenthesis at the end of each string in LIST."
4895 (mapcar (lambda (x)
4896 (if (string-match "(.*)$" x)
4897 (substring x 0 (match-beginning 0))
4899 list))
4901 (defun org-assign-fast-keys (alist)
4902 "Assign fast keys to a keyword-key alist.
4903 Respect keys that are already there."
4904 (let (new e (alt ?0))
4905 (while (setq e (pop alist))
4906 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4907 (cdr e)) ;; Key already assigned.
4908 (push e new)
4909 (let ((clist (string-to-list (downcase (car e))))
4910 (used (append new alist)))
4911 (when (= (car clist) ?@)
4912 (pop clist))
4913 (while (and clist (rassoc (car clist) used))
4914 (pop clist))
4915 (unless clist
4916 (while (rassoc alt used)
4917 (incf alt)))
4918 (push (cons (car e) (or (car clist) alt)) new))))
4919 (nreverse new)))
4921 ;;; Some variables used in various places
4923 (defvar org-window-configuration nil
4924 "Used in various places to store a window configuration.")
4925 (defvar org-selected-window nil
4926 "Used in various places to store a window configuration.")
4927 (defvar org-finish-function nil
4928 "Function to be called when `C-c C-c' is used.
4929 This is for getting out of special buffers like capture.")
4932 ;; FIXME: Occasionally check by commenting these, to make sure
4933 ;; no other functions uses these, forgetting to let-bind them.
4934 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4935 (defvar org-last-state)
4936 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4938 ;; Defined somewhere in this file, but used before definition.
4939 (defvar org-entities) ;; defined in org-entities.el
4940 (defvar org-struct-menu)
4941 (defvar org-org-menu)
4942 (defvar org-tbl-menu)
4944 ;;;; Define the Org-mode
4946 ;; We use a before-change function to check if a table might need
4947 ;; an update.
4948 (defvar org-table-may-need-update t
4949 "Indicates that a table might need an update.
4950 This variable is set by `org-before-change-function'.
4951 `org-table-align' sets it back to nil.")
4952 (defun org-before-change-function (beg end)
4953 "Every change indicates that a table might need an update."
4954 (setq org-table-may-need-update t))
4955 (defvar org-mode-map)
4956 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4957 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4958 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4959 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4960 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4961 (defvar org-table-buffer-is-an nil)
4963 (defvar bidi-paragraph-direction)
4964 (defvar buffer-face-mode-face)
4966 (require 'outline)
4967 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4968 (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"))
4969 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4971 ;; Other stuff we need.
4972 (require 'time-date)
4973 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4974 (require 'easymenu)
4975 (require 'overlay)
4977 ;; (require 'org-macs) moved higher up in the file before it is first used
4978 (require 'org-entities)
4979 ;; (require 'org-compat) moved higher up in the file before it is first used
4980 (require 'org-faces)
4981 (require 'org-list)
4982 (require 'org-pcomplete)
4983 (require 'org-src)
4984 (require 'org-footnote)
4986 ;; babel
4987 (require 'ob)
4989 ;;;###autoload
4990 (define-derived-mode org-mode outline-mode "Org"
4991 "Outline-based notes management and organizer, alias
4992 \"Carsten's outline-mode for keeping track of everything.\"
4994 Org-mode develops organizational tasks around a NOTES file which
4995 contains information about projects as plain text. Org-mode is
4996 implemented on top of outline-mode, which is ideal to keep the content
4997 of large files well structured. It supports ToDo items, deadlines and
4998 time stamps, which magically appear in the diary listing of the Emacs
4999 calendar. Tables are easily created with a built-in table editor.
5000 Plain text URL-like links connect to websites, emails (VM), Usenet
5001 messages (Gnus), BBDB entries, and any files related to the project.
5002 For printing and sharing of notes, an Org-mode file (or a part of it)
5003 can be exported as a structured ASCII or HTML file.
5005 The following commands are available:
5007 \\{org-mode-map}"
5009 ;; Get rid of Outline menus, they are not needed
5010 ;; Need to do this here because define-derived-mode sets up
5011 ;; the keymap so late. Still, it is a waste to call this each time
5012 ;; we switch another buffer into org-mode.
5013 (if (featurep 'xemacs)
5014 (when (boundp 'outline-mode-menu-heading)
5015 ;; Assume this is Greg's port, it uses easymenu
5016 (easy-menu-remove outline-mode-menu-heading)
5017 (easy-menu-remove outline-mode-menu-show)
5018 (easy-menu-remove outline-mode-menu-hide))
5019 (define-key org-mode-map [menu-bar headings] 'undefined)
5020 (define-key org-mode-map [menu-bar hide] 'undefined)
5021 (define-key org-mode-map [menu-bar show] 'undefined))
5023 (org-load-modules-maybe)
5024 (easy-menu-add org-org-menu)
5025 (easy-menu-add org-tbl-menu)
5026 (org-install-agenda-files-menu)
5027 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5028 (add-to-invisibility-spec '(org-cwidth))
5029 (add-to-invisibility-spec '(org-hide-block . t))
5030 (when (featurep 'xemacs)
5031 (org-set-local 'line-move-ignore-invisible t))
5032 (org-set-local 'outline-regexp org-outline-regexp)
5033 (org-set-local 'outline-level 'org-outline-level)
5034 (setq bidi-paragraph-direction 'left-to-right)
5035 (when (and org-ellipsis
5036 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5037 (fboundp 'make-glyph-code))
5038 (unless org-display-table
5039 (setq org-display-table (make-display-table)))
5040 (set-display-table-slot
5041 org-display-table 4
5042 (vconcat (mapcar
5043 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5044 org-ellipsis)))
5045 (if (stringp org-ellipsis) org-ellipsis "..."))))
5046 (setq buffer-display-table org-display-table))
5047 (org-set-regexps-and-options)
5048 (when (and org-tag-faces (not org-tags-special-faces-re))
5049 ;; tag faces set outside customize.... force initialization.
5050 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5051 ;; Calc embedded
5052 (org-set-local 'calc-embedded-open-mode "# ")
5053 (modify-syntax-entry ?@ "w")
5054 (modify-syntax-entry ?\" "\"")
5055 (if org-startup-truncated (setq truncate-lines t))
5056 (org-set-local 'font-lock-unfontify-region-function
5057 'org-unfontify-region)
5058 ;; Activate before-change-function
5059 (org-set-local 'org-table-may-need-update t)
5060 (org-add-hook 'before-change-functions 'org-before-change-function nil
5061 'local)
5062 ;; Check for running clock before killing a buffer
5063 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5064 ;; Initialize macros templates.
5065 (org-macro-initialize-templates)
5066 ;; Initialize radio targets.
5067 (org-update-radio-target-regexp)
5068 ;; Indentation.
5069 (org-set-local 'indent-line-function 'org-indent-line)
5070 (org-set-local 'indent-region-function 'org-indent-region)
5071 ;; Filling and auto-filling.
5072 (org-setup-filling)
5073 ;; Comments.
5074 (org-setup-comments-handling)
5075 ;; Beginning/end of defun
5076 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5077 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5078 ;; Next error for sparse trees
5079 (org-set-local 'next-error-function 'org-occur-next-match)
5080 ;; Make sure dependence stuff works reliably, even for users who set it
5081 ;; too late :-(
5082 (if org-enforce-todo-dependencies
5083 (add-hook 'org-blocker-hook
5084 'org-block-todo-from-children-or-siblings-or-parent)
5085 (remove-hook 'org-blocker-hook
5086 'org-block-todo-from-children-or-siblings-or-parent))
5087 (if org-enforce-todo-checkbox-dependencies
5088 (add-hook 'org-blocker-hook
5089 'org-block-todo-from-checkboxes)
5090 (remove-hook 'org-blocker-hook
5091 'org-block-todo-from-checkboxes))
5093 ;; Align options lines
5094 (org-set-local
5095 'align-mode-rules-list
5096 '((org-in-buffer-settings
5097 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5098 (modes . '(org-mode)))))
5100 ;; Imenu
5101 (org-set-local 'imenu-create-index-function
5102 'org-imenu-get-tree)
5104 ;; Make isearch reveal context
5105 (if (or (featurep 'xemacs)
5106 (not (boundp 'outline-isearch-open-invisible-function)))
5107 ;; Emacs 21 and XEmacs make use of the hook
5108 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5109 ;; Emacs 22 deals with this through a special variable
5110 (org-set-local 'outline-isearch-open-invisible-function
5111 (lambda (&rest ignore) (org-show-context 'isearch))))
5113 ;; Turn on org-beamer-mode?
5114 (and org-startup-with-beamer-mode (org-beamer-mode))
5116 ;; Setup the pcomplete hooks
5117 (set (make-local-variable 'pcomplete-command-completion-function)
5118 'org-pcomplete-initial)
5119 (set (make-local-variable 'pcomplete-command-name-function)
5120 'org-command-at-point)
5121 (set (make-local-variable 'pcomplete-default-completion-function)
5122 'ignore)
5123 (set (make-local-variable 'pcomplete-parse-arguments-function)
5124 'org-parse-arguments)
5125 (set (make-local-variable 'pcomplete-termination-string) "")
5126 (when (>= emacs-major-version 23)
5127 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5129 ;; If empty file that did not turn on org-mode automatically, make it to.
5130 (if (and org-insert-mode-line-in-empty-file
5131 (org-called-interactively-p 'any)
5132 (= (point-min) (point-max)))
5133 (insert "# -*- mode: org -*-\n\n"))
5134 (unless org-inhibit-startup
5135 (when org-startup-align-all-tables
5136 (let ((bmp (buffer-modified-p)))
5137 (org-table-map-tables 'org-table-align 'quietly)
5138 (set-buffer-modified-p bmp)))
5139 (when org-startup-with-inline-images
5140 (org-display-inline-images))
5141 (when org-startup-indented
5142 (require 'org-indent)
5143 (org-indent-mode 1))
5144 (unless org-inhibit-startup-visibility-stuff
5145 (org-set-startup-visibility)))
5146 ;; Try to set org-hide correctly
5147 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5149 (when (fboundp 'abbrev-table-put)
5150 (abbrev-table-put org-mode-abbrev-table
5151 :parents (list text-mode-abbrev-table)))
5153 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5156 (defun org-find-invisible-foreground ()
5157 (let ((candidates (remove
5158 "unspecified-bg"
5159 (nconc
5160 (list (face-background 'default)
5161 (face-background 'org-default))
5162 (mapcar
5163 (lambda (alist)
5164 (when (boundp alist)
5165 (cdr (assoc 'background-color (symbol-value alist)))))
5166 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5167 (list (face-foreground 'org-hide))))))
5168 (car (remove nil candidates))))
5170 (defun org-current-time (&optional rounding-minutes)
5171 "Current time, possibly rounded to ROUNDING-MINUTES.
5172 When ROUNDING-MINUTES is not an integer, fall back on the car of
5173 `org-time-stamp-rounding-minutes'."
5174 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5175 (car org-time-stamp-rounding-minutes)))
5176 (time (decode-time)))
5177 (if (> r 1)
5178 (apply 'encode-time
5179 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5180 (nthcdr 2 time)))
5181 (current-time))))
5183 (defun org-today ()
5184 "Return today date, considering `org-extend-today-until'."
5185 (time-to-days
5186 (time-subtract (current-time)
5187 (list 0 (* 3600 org-extend-today-until) 0))))
5189 ;;;; Font-Lock stuff, including the activators
5191 (defvar org-mouse-map (make-sparse-keymap))
5192 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5193 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5194 (when org-mouse-1-follows-link
5195 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5196 (when org-tab-follows-link
5197 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5198 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5200 (require 'font-lock)
5202 (defconst org-non-link-chars "]\t\n\r<>")
5203 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5204 "shell" "elisp" "doi" "message"))
5205 (defvar org-link-types-re nil
5206 "Matches a link that has a url-like prefix like \"http:\"")
5207 (defvar org-link-re-with-space nil
5208 "Matches a link with spaces, optional angular brackets around it.")
5209 (defvar org-link-re-with-space2 nil
5210 "Matches a link with spaces, optional angular brackets around it.")
5211 (defvar org-link-re-with-space3 nil
5212 "Matches a link with spaces, only for internal part in bracket links.")
5213 (defvar org-angle-link-re nil
5214 "Matches link with angular brackets, spaces are allowed.")
5215 (defvar org-plain-link-re nil
5216 "Matches plain link, without spaces.")
5217 (defvar org-bracket-link-regexp nil
5218 "Matches a link in double brackets.")
5219 (defvar org-bracket-link-analytic-regexp nil
5220 "Regular expression used to analyze links.
5221 Here is what the match groups contain after a match:
5222 1: http:
5223 2: http
5224 3: path
5225 4: [desc]
5226 5: desc")
5227 (defvar org-bracket-link-analytic-regexp++ nil
5228 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5229 (defvar org-any-link-re nil
5230 "Regular expression matching any link.")
5232 (defcustom org-match-sexp-depth 3
5233 "Number of stacked braces for sub/superscript matching.
5234 This has to be set before loading org.el to be effective."
5235 :group 'org-export-translation ; ??????????????????????????/
5236 :type 'integer)
5238 (defun org-create-multibrace-regexp (left right n)
5239 "Create a regular expression which will match a balanced sexp.
5240 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5241 as single character strings.
5242 The regexp returned will match the entire expression including the
5243 delimiters. It will also define a single group which contains the
5244 match except for the outermost delimiters. The maximum depth of
5245 stacked delimiters is N. Escaping delimiters is not possible."
5246 (let* ((nothing (concat "[^" left right "]*?"))
5247 (or "\\|")
5248 (re nothing)
5249 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5250 (while (> n 1)
5251 (setq n (1- n)
5252 re (concat re or next)
5253 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5254 (concat left "\\(" re "\\)" right)))
5256 (defvar org-match-substring-regexp
5257 (concat
5258 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5259 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5260 "\\|"
5261 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5262 "\\|"
5263 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5264 "The regular expression matching a sub- or superscript.")
5266 (defvar org-match-substring-with-braces-regexp
5267 (concat
5268 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5269 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5270 "\\)")
5271 "The regular expression matching a sub- or superscript, forcing braces.")
5273 (defun org-make-link-regexps ()
5274 "Update the link regular expressions.
5275 This should be called after the variable `org-link-types' has changed."
5276 (setq org-link-types-re
5277 (concat
5278 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5279 org-link-re-with-space
5280 (concat
5281 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5282 "\\([^" org-non-link-chars " ]"
5283 "[^" org-non-link-chars "]*"
5284 "[^" org-non-link-chars " ]\\)>?")
5285 org-link-re-with-space2
5286 (concat
5287 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5288 "\\([^" org-non-link-chars " ]"
5289 "[^\t\n\r]*"
5290 "[^" org-non-link-chars " ]\\)>?")
5291 org-link-re-with-space3
5292 (concat
5293 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5294 "\\([^" org-non-link-chars " ]"
5295 "[^\t\n\r]*\\)")
5296 org-angle-link-re
5297 (concat
5298 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5299 "\\([^" org-non-link-chars " ]"
5300 "[^" org-non-link-chars "]*"
5301 "\\)>")
5302 org-plain-link-re
5303 (concat
5304 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5305 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5306 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5307 org-bracket-link-regexp
5308 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5309 org-bracket-link-analytic-regexp
5310 (concat
5311 "\\[\\["
5312 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5313 "\\([^]]+\\)"
5314 "\\]"
5315 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5316 "\\]")
5317 org-bracket-link-analytic-regexp++
5318 (concat
5319 "\\[\\["
5320 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5321 "\\([^]]+\\)"
5322 "\\]"
5323 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5324 "\\]")
5325 org-any-link-re
5326 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5327 org-angle-link-re "\\)\\|\\("
5328 org-plain-link-re "\\)")))
5330 (org-make-link-regexps)
5332 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5333 "Regular expression for fast time stamp matching.")
5334 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5335 "Regular expression for fast time stamp matching.")
5336 (defconst org-ts-regexp0
5337 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5338 "Regular expression matching time strings for analysis.
5339 This one does not require the space after the date, so it can be used
5340 on a string that terminates immediately after the date.")
5341 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5342 "Regular expression matching time strings for analysis.")
5343 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5344 "Regular expression matching time stamps, with groups.")
5345 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5346 "Regular expression matching time stamps (also [..]), with groups.")
5347 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5348 "Regular expression matching a time stamp range.")
5349 (defconst org-tr-regexp-both
5350 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5351 "Regular expression matching a time stamp range.")
5352 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5353 org-ts-regexp "\\)?")
5354 "Regular expression matching a time stamp or time stamp range.")
5355 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5356 org-ts-regexp-both "\\)?")
5357 "Regular expression matching a time stamp or time stamp range.
5358 The time stamps may be either active or inactive.")
5360 (defvar org-emph-face nil)
5362 (defun org-do-emphasis-faces (limit)
5363 "Run through the buffer and add overlays to emphasized strings."
5364 (let (rtn a)
5365 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5366 (if (not (= (char-after (match-beginning 3))
5367 (char-after (match-beginning 4))))
5368 (progn
5369 (setq rtn t)
5370 (setq a (assoc (match-string 3) org-emphasis-alist))
5371 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5372 'face
5373 (nth 1 a))
5374 (and (nth 4 a)
5375 (org-remove-flyspell-overlays-in
5376 (match-beginning 0) (match-end 0)))
5377 (add-text-properties (match-beginning 2) (match-end 2)
5378 '(font-lock-multiline t org-emphasis t))
5379 (when org-hide-emphasis-markers
5380 (add-text-properties (match-end 4) (match-beginning 5)
5381 '(invisible org-link))
5382 (add-text-properties (match-beginning 3) (match-end 3)
5383 '(invisible org-link)))))
5384 (backward-char 1))
5385 rtn))
5387 (defun org-emphasize (&optional char)
5388 "Insert or change an emphasis, i.e. a font like bold or italic.
5389 If there is an active region, change that region to a new emphasis.
5390 If there is no region, just insert the marker characters and position
5391 the cursor between them.
5392 CHAR should be either the marker character, or the first character of the
5393 HTML tag associated with that emphasis. If CHAR is a space, the means
5394 to remove the emphasis of the selected region.
5395 If char is not given (for example in an interactive call) it
5396 will be prompted for."
5397 (interactive)
5398 (let ((eal org-emphasis-alist) e det
5399 (erc org-emphasis-regexp-components)
5400 (prompt "")
5401 (string "") beg end move tag c s)
5402 (if (org-region-active-p)
5403 (setq beg (region-beginning) end (region-end)
5404 string (buffer-substring beg end))
5405 (setq move t))
5407 (while (setq e (pop eal))
5408 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5409 c (aref tag 0))
5410 (push (cons c (string-to-char (car e))) det)
5411 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5412 (substring tag 1)))))
5413 (setq det (nreverse det))
5414 (unless char
5415 (message "%s" (concat "Emphasis marker or tag:" prompt))
5416 (setq char (read-char-exclusive)))
5417 (setq char (or (cdr (assoc char det)) char))
5418 (if (equal char ?\ )
5419 (setq s "" move nil)
5420 (unless (assoc (char-to-string char) org-emphasis-alist)
5421 (error "No such emphasis marker: \"%c\"" char))
5422 (setq s (char-to-string char)))
5423 (while (and (> (length string) 1)
5424 (equal (substring string 0 1) (substring string -1))
5425 (assoc (substring string 0 1) org-emphasis-alist))
5426 (setq string (substring string 1 -1)))
5427 (setq string (concat s string s))
5428 (if beg (delete-region beg end))
5429 (unless (or (bolp)
5430 (string-match (concat "[" (nth 0 erc) "\n]")
5431 (char-to-string (char-before (point)))))
5432 (insert " "))
5433 (unless (or (eobp)
5434 (string-match (concat "[" (nth 1 erc) "\n]")
5435 (char-to-string (char-after (point)))))
5436 (insert " ") (backward-char 1))
5437 (insert string)
5438 (and move (backward-char 1))))
5440 (defconst org-nonsticky-props
5441 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5443 (defsubst org-rear-nonsticky-at (pos)
5444 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5446 (defun org-activate-plain-links (limit)
5447 "Run through the buffer and add overlays to links."
5448 (catch 'exit
5449 (let (f hl)
5450 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5451 (not (org-in-src-block-p)))
5452 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5453 (setq f (get-text-property (match-beginning 0) 'face))
5454 (setq hl (org-match-string-no-properties 0))
5455 (if (or (eq f 'org-tag)
5456 (and (listp f) (memq 'org-tag f)))
5458 (add-text-properties (match-beginning 0) (match-end 0)
5459 (list 'mouse-face 'highlight
5460 'face 'org-link
5461 'htmlize-link `(:uri ,hl)
5462 'keymap org-mouse-map))
5463 (org-rear-nonsticky-at (match-end 0)))
5464 t))))
5466 (defun org-activate-code (limit)
5467 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5468 (progn
5469 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5470 (remove-text-properties (match-beginning 0) (match-end 0)
5471 '(display t invisible t intangible t))
5472 t)))
5474 (defcustom org-src-fontify-natively nil
5475 "When non-nil, fontify code in code blocks."
5476 :type 'boolean
5477 :version "24.1"
5478 :group 'org-appearance
5479 :group 'org-babel)
5481 (defcustom org-allow-promoting-top-level-subtree nil
5482 "When non-nil, allow promoting a top level subtree.
5483 The leading star of the top level headline will be replaced
5484 by a #."
5485 :type 'boolean
5486 :version "24.1"
5487 :group 'org-appearance)
5489 (defun org-fontify-meta-lines-and-blocks (limit)
5490 (condition-case nil
5491 (org-fontify-meta-lines-and-blocks-1 limit)
5492 (error (message "org-mode fontification error"))))
5494 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5495 "Fontify #+ lines and blocks, in the correct ways."
5496 (let ((case-fold-search t))
5497 (if (re-search-forward
5498 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5499 limit t)
5500 (let ((beg (match-beginning 0))
5501 (block-start (match-end 0))
5502 (block-end nil)
5503 (lang (match-string 7))
5504 (beg1 (line-beginning-position 2))
5505 (dc1 (downcase (match-string 2)))
5506 (dc3 (downcase (match-string 3)))
5507 end end1 quoting block-type ovl)
5508 (cond
5509 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5510 ;; a single line of backend-specific content
5511 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5512 (remove-text-properties (match-beginning 0) (match-end 0)
5513 '(display t invisible t intangible t))
5514 (add-text-properties (match-beginning 1) (match-end 3)
5515 '(font-lock-fontified t face org-meta-line))
5516 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5517 '(font-lock-fontified t face org-block))
5518 ; for backend-specific code
5520 ((and (match-end 4) (equal dc3 "+begin"))
5521 ;; Truly a block
5522 (setq block-type (downcase (match-string 5))
5523 quoting (member block-type org-protecting-blocks))
5524 (when (re-search-forward
5525 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5526 nil t) ;; on purpose, we look further than LIMIT
5527 (setq end (min (point-max) (match-end 0))
5528 end1 (min (point-max) (1- (match-beginning 0))))
5529 (setq block-end (match-beginning 0))
5530 (when quoting
5531 (remove-text-properties beg end
5532 '(display t invisible t intangible t)))
5533 (add-text-properties
5534 beg end
5535 '(font-lock-fontified t font-lock-multiline t))
5536 (add-text-properties beg beg1 '(face org-meta-line))
5537 (add-text-properties end1 (min (point-max) (1+ end))
5538 '(face org-meta-line)) ; for end_src
5539 (cond
5540 ((and lang (not (string= lang "")) org-src-fontify-natively)
5541 (org-src-font-lock-fontify-block lang block-start block-end)
5542 ;; remove old background overlays
5543 (mapc (lambda (ov)
5544 (if (eq (overlay-get ov 'face) 'org-block-background)
5545 (delete-overlay ov)))
5546 (overlays-at (/ (+ beg1 block-end) 2)))
5547 ;; add a background overlay
5548 (setq ovl (make-overlay beg1 block-end))
5549 (overlay-put ovl 'face 'org-block-background)
5550 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5551 (quoting
5552 (add-text-properties beg1 (min (point-max) (1+ end1))
5553 '(face org-block))) ; end of source block
5554 ((not org-fontify-quote-and-verse-blocks))
5555 ((string= block-type "quote")
5556 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5557 ((string= block-type "verse")
5558 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5559 (add-text-properties beg beg1 '(face org-block-begin-line))
5560 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5561 '(face org-block-end-line))
5563 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5564 (add-text-properties
5565 beg (match-end 3)
5566 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5567 '(font-lock-fontified t invisible t)
5568 '(font-lock-fontified t face org-document-info-keyword)))
5569 (add-text-properties
5570 (match-beginning 6) (1+ (match-end 6))
5571 (if (string-equal dc1 "+title:")
5572 '(font-lock-fontified t face org-document-title)
5573 '(font-lock-fontified t face org-document-info))))
5574 ((or (equal dc1 "+results")
5575 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5576 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5577 "+call:" "+header:" "+headers:" "+name:"))
5578 (and (match-end 4) (equal dc3 "+attr")))
5579 (add-text-properties
5580 beg (match-end 0)
5581 '(font-lock-fontified t face org-meta-line))
5583 ((member dc3 '(" " ""))
5584 (add-text-properties
5585 beg (match-end 0)
5586 '(font-lock-fontified t face font-lock-comment-face)))
5587 ((not (member (char-after beg) '(?\ ?\t)))
5588 ;; just any other in-buffer setting, but not indented
5589 (add-text-properties
5590 beg (match-end 0)
5591 '(font-lock-fontified t face org-meta-line))
5593 (t nil))))))
5595 (defun org-activate-angle-links (limit)
5596 "Run through the buffer and add overlays to links."
5597 (if (and (re-search-forward org-angle-link-re limit t)
5598 (not (org-in-src-block-p)))
5599 (progn
5600 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5601 (add-text-properties (match-beginning 0) (match-end 0)
5602 (list 'mouse-face 'highlight
5603 'keymap org-mouse-map))
5604 (org-rear-nonsticky-at (match-end 0))
5605 t)))
5607 (defun org-activate-footnote-links (limit)
5608 "Run through the buffer and add overlays to footnotes."
5609 (let ((fn (org-footnote-next-reference-or-definition limit)))
5610 (when fn
5611 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5612 (org-remove-flyspell-overlays-in beg end)
5613 (add-text-properties beg end
5614 (list 'mouse-face 'highlight
5615 'keymap org-mouse-map
5616 'help-echo
5617 (if (= (point-at-bol) beg)
5618 "Footnote definition"
5619 "Footnote reference")
5620 'font-lock-fontified t
5621 'font-lock-multiline t
5622 'face 'org-footnote))))))
5624 (defun org-activate-bracket-links (limit)
5625 "Run through the buffer and add overlays to bracketed links."
5626 (if (and (re-search-forward org-bracket-link-regexp limit t)
5627 (not (org-in-src-block-p)))
5628 (let* ((hl (org-match-string-no-properties 1))
5629 (help (concat "LINK: " hl))
5630 ;; FIXME: Above we should remove the escapes. But that
5631 ;; requires another match, protecting match data, a lot
5632 ;; of overhead for font-lock.
5633 (ip (org-maybe-intangible
5634 (list 'invisible 'org-link
5635 'keymap org-mouse-map 'mouse-face 'highlight
5636 'font-lock-multiline t 'help-echo help
5637 'htmlize-link `(:uri ,hl))))
5638 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5639 'font-lock-multiline t 'help-echo help
5640 'htmlize-link `(:uri ,hl))))
5641 ;; We need to remove the invisible property here. Table narrowing
5642 ;; may have made some of this invisible.
5643 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5644 (remove-text-properties (match-beginning 0) (match-end 0)
5645 '(invisible nil))
5646 (if (match-end 3)
5647 (progn
5648 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5649 (org-rear-nonsticky-at (match-beginning 3))
5650 (add-text-properties (match-beginning 3) (match-end 3) vp)
5651 (org-rear-nonsticky-at (match-end 3))
5652 (add-text-properties (match-end 3) (match-end 0) ip)
5653 (org-rear-nonsticky-at (match-end 0)))
5654 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5655 (org-rear-nonsticky-at (match-beginning 1))
5656 (add-text-properties (match-beginning 1) (match-end 1) vp)
5657 (org-rear-nonsticky-at (match-end 1))
5658 (add-text-properties (match-end 1) (match-end 0) ip)
5659 (org-rear-nonsticky-at (match-end 0)))
5660 t)))
5662 (defun org-activate-dates (limit)
5663 "Run through the buffer and add overlays to dates."
5664 (if (re-search-forward org-tsr-regexp-both limit t)
5665 (progn
5666 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5667 (add-text-properties (match-beginning 0) (match-end 0)
5668 (list 'mouse-face 'highlight
5669 'keymap org-mouse-map))
5670 (org-rear-nonsticky-at (match-end 0))
5671 (when org-display-custom-times
5672 (if (match-end 3)
5673 (org-display-custom-time (match-beginning 3) (match-end 3)))
5674 (org-display-custom-time (match-beginning 1) (match-end 1)))
5675 t)))
5677 (defvar org-target-link-regexp nil
5678 "Regular expression matching radio targets in plain text.")
5679 (make-variable-buffer-local 'org-target-link-regexp)
5680 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5681 "Regular expression matching a link target.")
5682 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5683 "Regular expression matching a radio target.")
5684 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5685 "Regular expression matching any target.")
5687 (defun org-activate-target-links (limit)
5688 "Run through the buffer and add overlays to target matches."
5689 (when org-target-link-regexp
5690 (let ((case-fold-search t))
5691 (if (re-search-forward org-target-link-regexp limit t)
5692 (progn
5693 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5694 (add-text-properties (match-beginning 0) (match-end 0)
5695 (list 'mouse-face 'highlight
5696 'keymap org-mouse-map
5697 'help-echo "Radio target link"
5698 'org-linked-text t))
5699 (org-rear-nonsticky-at (match-end 0))
5700 t)))))
5702 (defun org-update-radio-target-regexp ()
5703 "Find all radio targets in this file and update the regular expression."
5704 (interactive)
5705 (when (memq 'radio org-activate-links)
5706 (setq org-target-link-regexp
5707 (org-make-target-link-regexp (org-all-targets 'radio)))
5708 (org-restart-font-lock)))
5710 (defun org-hide-wide-columns (limit)
5711 (let (s e)
5712 (setq s (text-property-any (point) (or limit (point-max))
5713 'org-cwidth t))
5714 (when s
5715 (setq e (next-single-property-change s 'org-cwidth))
5716 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5717 (goto-char e)
5718 t)))
5720 (defvar org-latex-and-specials-regexp nil
5721 "Regular expression for highlighting export special stuff.")
5722 (defvar org-match-substring-regexp)
5723 (defvar org-match-substring-with-braces-regexp)
5725 ;; This should be with the exporter code, but we also use if for font-locking
5726 (defconst org-export-html-special-string-regexps
5727 '(("\\\\-" . "&shy;")
5728 ("---\\([^-]\\)" . "&mdash;\\1")
5729 ("--\\([^-]\\)" . "&ndash;\\1")
5730 ("\\.\\.\\." . "&hellip;"))
5731 "Regular expressions for special string conversion.")
5734 (defun org-compute-latex-and-specials-regexp ()
5735 "Compute regular expression for stuff treated specially by exporters."
5736 (if (not org-highlight-latex-fragments-and-specials)
5737 (org-set-local 'org-latex-and-specials-regexp nil)
5738 (require 'org-exp)
5739 (let*
5740 ((matchers (plist-get org-format-latex-options :matchers))
5741 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5742 org-latex-regexps)))
5743 (org-export-allow-BIND nil)
5744 (options (org-combine-plists (org-default-export-plist)
5745 (org-infile-export-plist)))
5746 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5747 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5748 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5749 (org-export-html-expand (plist-get options :expand-quoted-html))
5750 (org-export-with-special-strings (plist-get options :special-strings))
5751 (re-sub
5752 (cond
5753 ((equal org-export-with-sub-superscripts '{})
5754 (list org-match-substring-with-braces-regexp))
5755 (org-export-with-sub-superscripts
5756 (list org-match-substring-regexp))))
5757 (re-latex
5758 (if org-export-with-LaTeX-fragments
5759 (mapcar (lambda (x) (nth 1 x)) latexs)))
5760 (re-macros
5761 (if org-export-with-TeX-macros
5762 (list (concat "\\\\"
5763 (regexp-opt
5764 (append
5766 (delq nil
5767 (mapcar 'car-safe
5768 (append org-entities-user
5769 org-entities)))
5770 (if (boundp 'org-latex-entities)
5771 (mapcar (lambda (x)
5772 (or (car-safe x) x))
5773 org-latex-entities)
5774 nil))
5775 'words))) ; FIXME
5777 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5778 (re-special (if org-export-with-special-strings
5779 (mapcar (lambda (x) (car x))
5780 org-export-html-special-string-regexps)))
5781 (re-rest
5782 (delq nil
5783 (list
5784 (if org-export-html-expand "@<[^>\n]+>")
5785 ))))
5786 (org-set-local
5787 'org-latex-and-specials-regexp
5788 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5789 re-rest) "\\|")))))
5791 (defun org-do-latex-and-special-faces (limit)
5792 "Run through the buffer and add overlays to links."
5793 (when org-latex-and-specials-regexp
5794 (let (rtn d)
5795 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5796 limit t))
5797 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5798 'face))
5799 '(org-code org-verbatim underline)))
5800 (progn
5801 (setq rtn t
5802 d (cond ((member (char-after (1+ (match-beginning 0)))
5803 '(?_ ?^)) 1)
5804 (t 0)))
5805 (font-lock-prepend-text-property
5806 (+ d (match-beginning 0)) (match-end 0)
5807 'face 'org-latex-and-export-specials)
5808 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5809 '(font-lock-multiline t)))))
5810 rtn)))
5812 (defun org-restart-font-lock ()
5813 "Restart `font-lock-mode', to force refontification."
5814 (when (and (boundp 'font-lock-mode) font-lock-mode)
5815 (font-lock-mode -1)
5816 (font-lock-mode 1)))
5818 (defun org-all-targets (&optional radio)
5819 "Return a list of all targets in this file.
5820 When optional argument RADIO is non-nil, only find radio
5821 targets."
5822 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5823 (save-excursion
5824 (goto-char (point-min))
5825 (while (re-search-forward re nil t)
5826 ;; Make sure point is really within the object.
5827 (backward-char)
5828 (let ((obj (org-element-context)))
5829 (when (memq (org-element-type obj) '(radio-target target))
5830 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5831 rtn)))
5833 (defun org-make-target-link-regexp (targets)
5834 "Make regular expression matching all strings in TARGETS.
5835 The regular expression finds the targets also if there is a line break
5836 between words."
5837 (and targets
5838 (concat
5839 "\\<\\("
5840 (mapconcat
5841 (lambda (x)
5842 (setq x (regexp-quote x))
5843 (while (string-match " +" x)
5844 (setq x (replace-match "\\s-+" t t x)))
5846 targets
5847 "\\|")
5848 "\\)\\>")))
5850 (defun org-activate-tags (limit)
5851 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5852 (progn
5853 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5854 (add-text-properties (match-beginning 1) (match-end 1)
5855 (list 'mouse-face 'highlight
5856 'keymap org-mouse-map))
5857 (org-rear-nonsticky-at (match-end 1))
5858 t)))
5860 (defun org-outline-level ()
5861 "Compute the outline level of the heading at point.
5862 If this is called at a normal headline, the level is the number of stars.
5863 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5864 (save-excursion
5865 (if (not (condition-case nil
5866 (org-back-to-heading t)
5867 (error nil)))
5869 (looking-at org-outline-regexp)
5870 (1- (- (match-end 0) (match-beginning 0))))))
5872 (defvar org-font-lock-keywords nil)
5874 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5875 "Regular expression matching a property line.")
5877 (defvar org-font-lock-hook nil
5878 "Functions to be called for special font lock stuff.")
5880 (defvar org-font-lock-set-keywords-hook nil
5881 "Functions that can manipulate `org-font-lock-extra-keywords'.
5882 This is called after `org-font-lock-extra-keywords' is defined, but before
5883 it is installed to be used by font lock. This can be useful if something
5884 needs to be inserted at a specific position in the font-lock sequence.")
5886 (defun org-font-lock-hook (limit)
5887 "Run `org-font-lock-hook' within LIMIT."
5888 (run-hook-with-args 'org-font-lock-hook limit))
5890 (defun org-set-font-lock-defaults ()
5891 "Set font lock defaults for the current buffer."
5892 (let* ((em org-fontify-emphasized-text)
5893 (lk org-activate-links)
5894 (org-font-lock-extra-keywords
5895 (list
5896 ;; Call the hook
5897 '(org-font-lock-hook)
5898 ;; Headlines
5899 `(,(if org-fontify-whole-heading-line
5900 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5901 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5902 (1 (org-get-level-face 1))
5903 (2 (org-get-level-face 2))
5904 (3 (org-get-level-face 3)))
5905 ;; Table lines
5906 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5907 (1 'org-table t))
5908 ;; Table internals
5909 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5910 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5911 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5912 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5913 ;; Drawers
5914 (list org-drawer-regexp '(0 'org-special-keyword t))
5915 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5916 ;; Properties
5917 (list org-property-re
5918 '(1 'org-special-keyword t)
5919 '(3 'org-property-value t))
5920 ;; Links
5921 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5922 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5923 (if (memq 'plain lk) '(org-activate-plain-links))
5924 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5925 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5926 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5927 (if (memq 'footnote lk) '(org-activate-footnote-links))
5928 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5929 '(org-hide-wide-columns (0 nil append))
5930 ;; TODO keyword
5931 (list (format org-heading-keyword-regexp-format
5932 org-todo-regexp)
5933 '(2 (org-get-todo-face 2) t))
5934 ;; DONE
5935 (if org-fontify-done-headline
5936 (list (format org-heading-keyword-regexp-format
5937 (concat
5938 "\\(?:"
5939 (mapconcat 'regexp-quote org-done-keywords "\\|")
5940 "\\)"))
5941 '(2 'org-headline-done t))
5942 nil)
5943 ;; Priorities
5944 '(org-font-lock-add-priority-faces)
5945 ;; Tags
5946 '(org-font-lock-add-tag-faces)
5947 ;; Special keywords
5948 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5949 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5950 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5951 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5952 ;; Emphasis
5953 (if em
5954 (if (featurep 'xemacs)
5955 '(org-do-emphasis-faces (0 nil append))
5956 '(org-do-emphasis-faces)))
5957 ;; Checkboxes
5958 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5959 1 'org-checkbox prepend)
5960 (if (cdr (assq 'checkbox org-list-automatic-rules))
5961 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5962 (0 (org-get-checkbox-statistics-face) t)))
5963 ;; Description list items
5964 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5965 1 'org-list-dt prepend)
5966 ;; ARCHIVEd headings
5967 (list (concat
5968 org-outline-regexp-bol
5969 "\\(.*:" org-archive-tag ":.*\\)")
5970 '(1 'org-archived prepend))
5971 ;; Specials
5972 '(org-do-latex-and-special-faces)
5973 '(org-fontify-entities)
5974 '(org-raise-scripts)
5975 ;; Code
5976 '(org-activate-code (1 'org-code t))
5977 ;; COMMENT
5978 (list (format org-heading-keyword-regexp-format
5979 (concat "\\("
5980 org-comment-string "\\|" org-quote-string
5981 "\\)"))
5982 '(2 'org-special-keyword t))
5983 ;; Blocks and meta lines
5984 '(org-fontify-meta-lines-and-blocks)
5986 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5987 (run-hooks 'org-font-lock-set-keywords-hook)
5988 ;; Now set the full font-lock-keywords
5989 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5990 (org-set-local 'font-lock-defaults
5991 '(org-font-lock-keywords t nil nil backward-paragraph))
5992 (kill-local-variable 'font-lock-keywords) nil))
5994 (defun org-toggle-pretty-entities ()
5995 "Toggle the composition display of entities as UTF8 characters."
5996 (interactive)
5997 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5998 (org-restart-font-lock)
5999 (if org-pretty-entities
6000 (message "Entities are displayed as UTF8 characters")
6001 (save-restriction
6002 (widen)
6003 (org-decompose-region (point-min) (point-max))
6004 (message "Entities are displayed plain"))))
6006 (defvar org-custom-properties-overlays nil
6007 "List of overlays used for custom properties.")
6008 (make-variable-buffer-local 'org-custom-properties-overlays)
6010 (defun org-toggle-custom-properties-visibility ()
6011 "Display or hide properties in `org-custom-properties'."
6012 (interactive)
6013 (if org-custom-properties-overlays
6014 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6015 (setq org-custom-properties-overlays nil))
6016 (unless (not org-custom-properties)
6017 (save-excursion
6018 (save-restriction
6019 (widen)
6020 (goto-char (point-min))
6021 (while (re-search-forward org-property-re nil t)
6022 (mapc (lambda(p)
6023 (when (equal p (substring (match-string 1) 1 -1))
6024 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6025 (overlay-put o 'invisible t)
6026 (overlay-put o 'org-custom-property t)
6027 (push o org-custom-properties-overlays))))
6028 org-custom-properties)))))))
6030 (defun org-fontify-entities (limit)
6031 "Find an entity to fontify."
6032 (let (ee)
6033 (when org-pretty-entities
6034 (catch 'match
6035 (while (re-search-forward
6036 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6037 limit t)
6038 (if (and (not (org-in-indented-comment-line))
6039 (setq ee (org-entity-get (match-string 1)))
6040 (= (length (nth 6 ee)) 1))
6041 (let*
6042 ((end (if (equal (match-string 2) "{}")
6043 (match-end 2)
6044 (match-end 1))))
6045 (add-text-properties
6046 (match-beginning 0) end
6047 (list 'font-lock-fontified t))
6048 (compose-region (match-beginning 0) end
6049 (nth 6 ee) nil)
6050 (backward-char 1)
6051 (throw 'match t))))
6052 nil))))
6054 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6055 "Fontify string S like in Org-mode."
6056 (with-temp-buffer
6057 (insert s)
6058 (let ((org-odd-levels-only odd-levels))
6059 (org-mode)
6060 (font-lock-fontify-buffer)
6061 (buffer-string))))
6063 (defvar org-m nil)
6064 (defvar org-l nil)
6065 (defvar org-f nil)
6066 (defun org-get-level-face (n)
6067 "Get the right face for match N in font-lock matching of headlines."
6068 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6069 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6070 (if org-cycle-level-faces
6071 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6072 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6073 (cond
6074 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6075 ((eq n 2) org-f)
6076 (t (if org-level-color-stars-only nil org-f))))
6079 (defun org-get-todo-face (kwd)
6080 "Get the right face for a TODO keyword KWD.
6081 If KWD is a number, get the corresponding match group."
6082 (if (numberp kwd) (setq kwd (match-string kwd)))
6083 (or (org-face-from-face-or-color
6084 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6085 (and (member kwd org-done-keywords) 'org-done)
6086 'org-todo))
6088 (defun org-face-from-face-or-color (context inherit face-or-color)
6089 "Create a face list that inherits INHERIT, but sets the foreground color.
6090 When FACE-OR-COLOR is not a string, just return it."
6091 (if (stringp face-or-color)
6092 (list :inherit inherit
6093 (cdr (assoc context org-faces-easy-properties))
6094 face-or-color)
6095 face-or-color))
6097 (defun org-font-lock-add-tag-faces (limit)
6098 "Add the special tag faces."
6099 (when (and org-tag-faces org-tags-special-faces-re)
6100 (while (re-search-forward org-tags-special-faces-re limit t)
6101 (add-text-properties (match-beginning 1) (match-end 1)
6102 (list 'face (org-get-tag-face 1)
6103 'font-lock-fontified t))
6104 (backward-char 1))))
6106 (defun org-font-lock-add-priority-faces (limit)
6107 "Add the special priority faces."
6108 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6109 (when (save-match-data (org-at-heading-p))
6110 (add-text-properties
6111 (match-beginning 0) (match-end 0)
6112 (list 'face (or (org-face-from-face-or-color
6113 'priority 'org-special-keyword
6114 (cdr (assoc (char-after (match-beginning 1))
6115 org-priority-faces)))
6116 'org-special-keyword)
6117 'font-lock-fontified t)))))
6119 (defun org-get-tag-face (kwd)
6120 "Get the right face for a TODO keyword KWD.
6121 If KWD is a number, get the corresponding match group."
6122 (if (numberp kwd) (setq kwd (match-string kwd)))
6123 (or (org-face-from-face-or-color
6124 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6125 'org-tag))
6127 (defun org-unfontify-region (beg end &optional maybe_loudly)
6128 "Remove fontification and activation overlays from links."
6129 (font-lock-default-unfontify-region beg end)
6130 (let* ((buffer-undo-list t)
6131 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6132 (inhibit-modification-hooks t)
6133 deactivate-mark buffer-file-name buffer-file-truename)
6134 (org-decompose-region beg end)
6135 (remove-text-properties beg end
6136 '(mouse-face t keymap t org-linked-text t
6137 invisible t intangible t
6138 org-no-flyspell t org-emphasis t))
6139 (org-remove-font-lock-display-properties beg end)))
6141 (defconst org-script-display '(((raise -0.3) (height 0.7))
6142 ((raise 0.3) (height 0.7))
6143 ((raise -0.5))
6144 ((raise 0.5)))
6145 "Display properties for showing superscripts and subscripts.")
6147 (defun org-remove-font-lock-display-properties (beg end)
6148 "Remove specific display properties that have been added by font lock.
6149 The will remove the raise properties that are used to show superscripts
6150 and subscripts."
6151 (let (next prop)
6152 (while (< beg end)
6153 (setq next (next-single-property-change beg 'display nil end)
6154 prop (get-text-property beg 'display))
6155 (if (member prop org-script-display)
6156 (put-text-property beg next 'display nil))
6157 (setq beg next))))
6159 (defun org-raise-scripts (limit)
6160 "Add raise properties to sub/superscripts."
6161 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6162 (if (re-search-forward
6163 (if (eq org-use-sub-superscripts t)
6164 org-match-substring-regexp
6165 org-match-substring-with-braces-regexp)
6166 limit t)
6167 (let* ((pos (point)) table-p comment-p
6168 (mpos (match-beginning 3))
6169 (emph-p (get-text-property mpos 'org-emphasis))
6170 (link-p (get-text-property mpos 'mouse-face))
6171 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6172 (goto-char (point-at-bol))
6173 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6174 comment-p (org-looking-at-p "[ \t]*#"))
6175 (goto-char pos)
6176 ;; FIXME: Should we go back one character here, for a_b^c
6177 ;; (goto-char (1- pos)) ;????????????????????
6178 (if (or comment-p emph-p link-p keyw-p)
6180 (put-text-property (match-beginning 3) (match-end 0)
6181 'display
6182 (if (equal (char-after (match-beginning 2)) ?^)
6183 (nth (if table-p 3 1) org-script-display)
6184 (nth (if table-p 2 0) org-script-display)))
6185 (add-text-properties (match-beginning 2) (match-end 2)
6186 (list 'invisible t
6187 'org-dwidth t 'org-dwidth-n 1))
6188 (if (and (eq (char-after (match-beginning 3)) ?{)
6189 (eq (char-before (match-end 3)) ?}))
6190 (progn
6191 (add-text-properties
6192 (match-beginning 3) (1+ (match-beginning 3))
6193 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6194 (add-text-properties
6195 (1- (match-end 3)) (match-end 3)
6196 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6197 t)))))
6199 ;;;; Visibility cycling, including org-goto and indirect buffer
6201 ;;; Cycling
6203 (defvar org-cycle-global-status nil)
6204 (make-variable-buffer-local 'org-cycle-global-status)
6205 (defvar org-cycle-subtree-status nil)
6206 (make-variable-buffer-local 'org-cycle-subtree-status)
6208 (defvar org-inlinetask-min-level)
6210 ;;;###autoload
6211 (defun org-cycle (&optional arg)
6212 "TAB-action and visibility cycling for Org-mode.
6214 This is the command invoked in Org-mode by the TAB key. Its main purpose
6215 is outline visibility cycling, but it also invokes other actions
6216 in special contexts.
6218 - When this function is called with a prefix argument, rotate the entire
6219 buffer through 3 states (global cycling)
6220 1. OVERVIEW: Show only top-level headlines.
6221 2. CONTENTS: Show all headlines of all levels, but no body text.
6222 3. SHOW ALL: Show everything.
6223 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6224 determined by the variable `org-startup-folded', and by any VISIBILITY
6225 properties in the buffer.
6226 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6227 including any drawers.
6229 - When inside a table, re-align the table and move to the next field.
6231 - When point is at the beginning of a headline, rotate the subtree started
6232 by this line through 3 different states (local cycling)
6233 1. FOLDED: Only the main headline is shown.
6234 2. CHILDREN: The main headline and the direct children are shown.
6235 From this state, you can move to one of the children
6236 and zoom in further.
6237 3. SUBTREE: Show the entire subtree, including body text.
6238 If there is no subtree, switch directly from CHILDREN to FOLDED.
6240 - When point is at the beginning of an empty headline and the variable
6241 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6242 of the headline by demoting and promoting it to likely levels. This
6243 speeds up creation document structure by pressing TAB once or several
6244 times right after creating a new headline.
6246 - When there is a numeric prefix, go up to a heading with level ARG, do
6247 a `show-subtree' and return to the previous cursor position. If ARG
6248 is negative, go up that many levels.
6250 - When point is not at the beginning of a headline, execute the global
6251 binding for TAB, which is re-indenting the line. See the option
6252 `org-cycle-emulate-tab' for details.
6254 - Special case: if point is at the beginning of the buffer and there is
6255 no headline in line 1, this function will act as if called with prefix arg
6256 (C-u TAB, same as S-TAB) also when called without prefix arg.
6257 But only if also the variable `org-cycle-global-at-bob' is t."
6258 (interactive "P")
6259 (org-load-modules-maybe)
6260 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6261 (and org-cycle-level-after-item/entry-creation
6262 (or (org-cycle-level)
6263 (org-cycle-item-indentation))))
6264 (let* (message-log-max ; Don't populate the *Messages* buffer
6265 (limit-level
6266 (or org-cycle-max-level
6267 (and (boundp 'org-inlinetask-min-level)
6268 org-inlinetask-min-level
6269 (1- org-inlinetask-min-level))))
6270 (nstars (and limit-level
6271 (if org-odd-levels-only
6272 (and limit-level (1- (* limit-level 2)))
6273 limit-level)))
6274 (org-outline-regexp
6275 (if (not (derived-mode-p 'org-mode))
6276 outline-regexp
6277 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6278 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6279 (not (looking-at org-outline-regexp))))
6280 (org-cycle-hook
6281 (if bob-special
6282 (delq 'org-optimize-window-after-visibility-change
6283 (copy-sequence org-cycle-hook))
6284 org-cycle-hook))
6285 (pos (point)))
6287 (if (or bob-special (equal arg '(4)))
6288 ;; special case: use global cycling
6289 (setq arg t))
6291 (cond
6293 ((equal arg '(16))
6294 (setq last-command 'dummy)
6295 (org-set-startup-visibility)
6296 (message "Startup visibility, plus VISIBILITY properties"))
6298 ((equal arg '(64))
6299 (show-all)
6300 (message "Entire buffer visible, including drawers"))
6302 ;; Table: enter it or move to the next field.
6303 ((org-at-table-p 'any)
6304 (if (org-at-table.el-p)
6305 (message "Use C-c ' to edit table.el tables")
6306 (if arg (org-table-edit-field t)
6307 (org-table-justify-field-maybe)
6308 (call-interactively 'org-table-next-field))))
6310 ((run-hook-with-args-until-success
6311 'org-tab-after-check-for-table-hook))
6313 ;; Global cycling: delegate to `org-cycle-internal-global'.
6314 ((eq arg t) (org-cycle-internal-global))
6316 ;; Drawers: delegate to `org-flag-drawer'.
6317 ((and org-drawers org-drawer-regexp
6318 (save-excursion
6319 (beginning-of-line 1)
6320 (looking-at org-drawer-regexp)))
6321 (org-flag-drawer ; toggle block visibility
6322 (not (get-char-property (match-end 0) 'invisible))))
6324 ;; Show-subtree, ARG levels up from here.
6325 ((integerp arg)
6326 (save-excursion
6327 (org-back-to-heading)
6328 (outline-up-heading (if (< arg 0) (- arg)
6329 (- (funcall outline-level) arg)))
6330 (org-show-subtree)))
6332 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6333 ((and (featurep 'org-inlinetask)
6334 (org-inlinetask-at-task-p)
6335 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6336 (org-inlinetask-toggle-visibility))
6338 ((org-try-cdlatex-tab))
6340 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6341 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6342 (save-excursion (beginning-of-line 1)
6343 (looking-at org-outline-regexp)))
6344 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6345 (org-cycle-internal-local))
6347 ;; From there: TAB emulation and template completion.
6348 (buffer-read-only (org-back-to-heading))
6350 ((run-hook-with-args-until-success
6351 'org-tab-after-check-for-cycling-hook))
6353 ((org-try-structure-completion))
6355 ((run-hook-with-args-until-success
6356 'org-tab-before-tab-emulation-hook))
6358 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6359 (or (not (bolp))
6360 (not (looking-at org-outline-regexp))))
6361 (call-interactively (global-key-binding "\t")))
6363 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6364 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6365 (or (and (eq org-cycle-emulate-tab 'white)
6366 (= (match-end 0) (point-at-eol)))
6367 (and (eq org-cycle-emulate-tab 'whitestart)
6368 (>= (match-end 0) pos))))
6370 (eq org-cycle-emulate-tab t))
6371 (call-interactively (global-key-binding "\t")))
6373 (t (save-excursion
6374 (org-back-to-heading)
6375 (org-cycle)))))))
6377 (defun org-cycle-internal-global ()
6378 "Do the global cycling action."
6379 ;; Hack to avoid display of messages for .org attachments in Gnus
6380 (let (message-log-max ; Don't populate the *Messages* buffer
6381 (ga (string-match "\\*fontification" (buffer-name))))
6382 (cond
6383 ((and (eq last-command this-command)
6384 (eq org-cycle-global-status 'overview))
6385 ;; We just created the overview - now do table of contents
6386 ;; This can be slow in very large buffers, so indicate action
6387 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6388 (unless ga (message "CONTENTS..."))
6389 (org-content)
6390 (unless ga (message "CONTENTS...done"))
6391 (setq org-cycle-global-status 'contents)
6392 (run-hook-with-args 'org-cycle-hook 'contents))
6394 ((and (eq last-command this-command)
6395 (eq org-cycle-global-status 'contents))
6396 ;; We just showed the table of contents - now show everything
6397 (run-hook-with-args 'org-pre-cycle-hook 'all)
6398 (show-all)
6399 (unless ga (message "SHOW ALL"))
6400 (setq org-cycle-global-status 'all)
6401 (run-hook-with-args 'org-cycle-hook 'all))
6404 ;; Default action: go to overview
6405 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6406 (org-overview)
6407 (unless ga (message "OVERVIEW"))
6408 (setq org-cycle-global-status 'overview)
6409 (run-hook-with-args 'org-cycle-hook 'overview)))))
6411 (defun org-cycle-internal-local ()
6412 "Do the local cycling action."
6413 (let (message-log-max ; Don't populate the *Messages* buffer
6414 (goal-column 0) eoh eol eos has-children children-skipped struct)
6415 ;; First, determine end of headline (EOH), end of subtree or item
6416 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6417 (save-excursion
6418 (if (org-at-item-p)
6419 (progn
6420 (beginning-of-line)
6421 (setq struct (org-list-struct))
6422 (setq eoh (point-at-eol))
6423 (setq eos (org-list-get-item-end-before-blank (point) struct))
6424 (setq has-children (org-list-has-child-p (point) struct)))
6425 (org-back-to-heading)
6426 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6427 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6428 (setq has-children
6429 (or (save-excursion
6430 (let ((level (funcall outline-level)))
6431 (outline-next-heading)
6432 (and (org-at-heading-p t)
6433 (> (funcall outline-level) level))))
6434 (save-excursion
6435 (org-list-search-forward (org-item-beginning-re) eos t)))))
6436 ;; Determine end invisible part of buffer (EOL)
6437 (beginning-of-line 2)
6438 ;; XEmacs doesn't have `next-single-char-property-change'
6439 (if (featurep 'xemacs)
6440 (while (and (not (eobp)) ;; this is like `next-line'
6441 (get-char-property (1- (point)) 'invisible))
6442 (beginning-of-line 2))
6443 (while (and (not (eobp)) ;; this is like `next-line'
6444 (get-char-property (1- (point)) 'invisible))
6445 (goto-char (next-single-char-property-change (point) 'invisible))
6446 (and (eolp) (beginning-of-line 2))))
6447 (setq eol (point)))
6448 ;; Find out what to do next and set `this-command'
6449 (cond
6450 ((= eos eoh)
6451 ;; Nothing is hidden behind this heading
6452 (unless (org-before-first-heading-p)
6453 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6454 (message "EMPTY ENTRY")
6455 (setq org-cycle-subtree-status nil)
6456 (save-excursion
6457 (goto-char eos)
6458 (outline-next-heading)
6459 (if (outline-invisible-p) (org-flag-heading nil))))
6460 ((and (or (>= eol eos)
6461 (not (string-match "\\S-" (buffer-substring eol eos))))
6462 (or has-children
6463 (not (setq children-skipped
6464 org-cycle-skip-children-state-if-no-children))))
6465 ;; Entire subtree is hidden in one line: children view
6466 (unless (org-before-first-heading-p)
6467 (run-hook-with-args 'org-pre-cycle-hook 'children))
6468 (if (org-at-item-p)
6469 (org-list-set-item-visibility (point-at-bol) struct 'children)
6470 (org-show-entry)
6471 (org-with-limited-levels (show-children))
6472 ;; FIXME: This slows down the func way too much.
6473 ;; How keep drawers hidden in subtree anyway?
6474 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6475 ;; (org-cycle-hide-drawers 'subtree))
6477 ;; Fold every list in subtree to top-level items.
6478 (when (eq org-cycle-include-plain-lists 'integrate)
6479 (save-excursion
6480 (org-back-to-heading)
6481 (while (org-list-search-forward (org-item-beginning-re) eos t)
6482 (beginning-of-line 1)
6483 (let* ((struct (org-list-struct))
6484 (prevs (org-list-prevs-alist struct))
6485 (end (org-list-get-bottom-point struct)))
6486 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6487 (org-list-get-all-items (point) struct prevs))
6488 (goto-char end))))))
6489 (message "CHILDREN")
6490 (save-excursion
6491 (goto-char eos)
6492 (outline-next-heading)
6493 (if (outline-invisible-p) (org-flag-heading nil)))
6494 (setq org-cycle-subtree-status 'children)
6495 (unless (org-before-first-heading-p)
6496 (run-hook-with-args 'org-cycle-hook 'children)))
6497 ((or children-skipped
6498 (and (eq last-command this-command)
6499 (eq org-cycle-subtree-status 'children)))
6500 ;; We just showed the children, or no children are there,
6501 ;; now show everything.
6502 (unless (org-before-first-heading-p)
6503 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6504 (outline-flag-region eoh eos nil)
6505 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6506 (setq org-cycle-subtree-status 'subtree)
6507 (unless (org-before-first-heading-p)
6508 (run-hook-with-args 'org-cycle-hook 'subtree)))
6510 ;; Default action: hide the subtree.
6511 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6512 (outline-flag-region eoh eos t)
6513 (message "FOLDED")
6514 (setq org-cycle-subtree-status 'folded)
6515 (unless (org-before-first-heading-p)
6516 (run-hook-with-args 'org-cycle-hook 'folded))))))
6518 ;;;###autoload
6519 (defun org-global-cycle (&optional arg)
6520 "Cycle the global visibility. For details see `org-cycle'.
6521 With \\[universal-argument] prefix arg, switch to startup visibility.
6522 With a numeric prefix, show all headlines up to that level."
6523 (interactive "P")
6524 (let ((org-cycle-include-plain-lists
6525 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6526 (cond
6527 ((integerp arg)
6528 (show-all)
6529 (hide-sublevels arg)
6530 (setq org-cycle-global-status 'contents))
6531 ((equal arg '(4))
6532 (org-set-startup-visibility)
6533 (message "Startup visibility, plus VISIBILITY properties."))
6535 (org-cycle '(4))))))
6537 (defun org-set-startup-visibility ()
6538 "Set the visibility required by startup options and properties."
6539 (cond
6540 ((eq org-startup-folded t)
6541 (org-cycle '(4)))
6542 ((eq org-startup-folded 'content)
6543 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6544 (org-cycle '(4)) (org-cycle '(4)))))
6545 (unless (eq org-startup-folded 'showeverything)
6546 (if org-hide-block-startup (org-hide-block-all))
6547 (org-set-visibility-according-to-property 'no-cleanup)
6548 (org-cycle-hide-archived-subtrees 'all)
6549 (org-cycle-hide-drawers 'all)
6550 (org-cycle-show-empty-lines t)))
6552 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6553 "Switch subtree visibilities according to :VISIBILITY: property."
6554 (interactive)
6555 (let (org-show-entry-below state)
6556 (save-excursion
6557 (goto-char (point-min))
6558 (while (re-search-forward
6559 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6560 nil t)
6561 (setq state (match-string 1))
6562 (save-excursion
6563 (org-back-to-heading t)
6564 (hide-subtree)
6565 (org-reveal)
6566 (cond
6567 ((equal state '("fold" "folded"))
6568 (hide-subtree))
6569 ((equal state "children")
6570 (org-show-hidden-entry)
6571 (show-children))
6572 ((equal state "content")
6573 (save-excursion
6574 (save-restriction
6575 (org-narrow-to-subtree)
6576 (org-content))))
6577 ((member state '("all" "showall"))
6578 (show-subtree)))))
6579 (unless no-cleanup
6580 (org-cycle-hide-archived-subtrees 'all)
6581 (org-cycle-hide-drawers 'all)
6582 (org-cycle-show-empty-lines 'all)))))
6584 ;; This function uses outline-regexp instead of the more fundamental
6585 ;; org-outline-regexp so that org-cycle-global works outside of Org
6586 ;; buffers, where outline-regexp is needed.
6587 (defun org-overview ()
6588 "Switch to overview mode, showing only top-level headlines.
6589 Really, this shows all headlines with level equal or greater than the level
6590 of the first headline in the buffer. This is important, because if the
6591 first headline is not level one, then (hide-sublevels 1) gives confusing
6592 results."
6593 (interactive)
6594 (let ((level (save-excursion
6595 (goto-char (point-min))
6596 (if (re-search-forward (concat "^" outline-regexp) nil t)
6597 (progn
6598 (goto-char (match-beginning 0))
6599 (funcall outline-level))))))
6600 (and level (hide-sublevels level))))
6602 (defun org-content (&optional arg)
6603 "Show all headlines in the buffer, like a table of contents.
6604 With numerical argument N, show content up to level N."
6605 (interactive "P")
6606 (save-excursion
6607 ;; Visit all headings and show their offspring
6608 (and (integerp arg) (org-overview))
6609 (goto-char (point-max))
6610 (catch 'exit
6611 (while (and (progn (condition-case nil
6612 (outline-previous-visible-heading 1)
6613 (error (goto-char (point-min))))
6615 (looking-at org-outline-regexp))
6616 (if (integerp arg)
6617 (show-children (1- arg))
6618 (show-branches))
6619 (if (bobp) (throw 'exit nil))))))
6622 (defun org-optimize-window-after-visibility-change (state)
6623 "Adjust the window after a change in outline visibility.
6624 This function is the default value of the hook `org-cycle-hook'."
6625 (when (get-buffer-window (current-buffer))
6626 (cond
6627 ((eq state 'content) nil)
6628 ((eq state 'all) nil)
6629 ((eq state 'folded) nil)
6630 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6631 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6633 (defun org-remove-empty-overlays-at (pos)
6634 "Remove outline overlays that do not contain non-white stuff."
6635 (mapc
6636 (lambda (o)
6637 (and (eq 'outline (overlay-get o 'invisible))
6638 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6639 (overlay-end o))))
6640 (delete-overlay o)))
6641 (overlays-at pos)))
6643 (defun org-clean-visibility-after-subtree-move ()
6644 "Fix visibility issues after moving a subtree."
6645 ;; First, find a reasonable region to look at:
6646 ;; Start two siblings above, end three below
6647 (let* ((beg (save-excursion
6648 (and (org-get-last-sibling)
6649 (org-get-last-sibling))
6650 (point)))
6651 (end (save-excursion
6652 (and (org-get-next-sibling)
6653 (org-get-next-sibling)
6654 (org-get-next-sibling))
6655 (if (org-at-heading-p)
6656 (point-at-eol)
6657 (point))))
6658 (level (looking-at "\\*+"))
6659 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6660 (save-excursion
6661 (save-restriction
6662 (narrow-to-region beg end)
6663 (when re
6664 ;; Properly fold already folded siblings
6665 (goto-char (point-min))
6666 (while (re-search-forward re nil t)
6667 (if (and (not (outline-invisible-p))
6668 (save-excursion
6669 (goto-char (point-at-eol)) (outline-invisible-p)))
6670 (hide-entry))))
6671 (org-cycle-show-empty-lines 'overview)
6672 (org-cycle-hide-drawers 'overview)))))
6674 (defun org-cycle-show-empty-lines (state)
6675 "Show empty lines above all visible headlines.
6676 The region to be covered depends on STATE when called through
6677 `org-cycle-hook'. Lisp program can use t for STATE to get the
6678 entire buffer covered. Note that an empty line is only shown if there
6679 are at least `org-cycle-separator-lines' empty lines before the headline."
6680 (when (not (= org-cycle-separator-lines 0))
6681 (save-excursion
6682 (let* ((n (abs org-cycle-separator-lines))
6683 (re (cond
6684 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6685 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6686 (t (let ((ns (number-to-string (- n 2))))
6687 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6688 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6689 beg end b e)
6690 (cond
6691 ((memq state '(overview contents t))
6692 (setq beg (point-min) end (point-max)))
6693 ((memq state '(children folded))
6694 (setq beg (point) end (progn (org-end-of-subtree t t)
6695 (beginning-of-line 2)
6696 (point)))))
6697 (when beg
6698 (goto-char beg)
6699 (while (re-search-forward re end t)
6700 (unless (get-char-property (match-end 1) 'invisible)
6701 (setq e (match-end 1))
6702 (if (< org-cycle-separator-lines 0)
6703 (setq b (save-excursion
6704 (goto-char (match-beginning 0))
6705 (org-back-over-empty-lines)
6706 (if (save-excursion
6707 (goto-char (max (point-min) (1- (point))))
6708 (org-at-heading-p))
6709 (1- (point))
6710 (point))))
6711 (setq b (match-beginning 1)))
6712 (outline-flag-region b e nil)))))))
6713 ;; Never hide empty lines at the end of the file.
6714 (save-excursion
6715 (goto-char (point-max))
6716 (outline-previous-heading)
6717 (outline-end-of-heading)
6718 (if (and (looking-at "[ \t\n]+")
6719 (= (match-end 0) (point-max)))
6720 (outline-flag-region (point) (match-end 0) nil))))
6722 (defun org-show-empty-lines-in-parent ()
6723 "Move to the parent and re-show empty lines before visible headlines."
6724 (save-excursion
6725 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6726 (org-cycle-show-empty-lines context))))
6728 (defun org-files-list ()
6729 "Return `org-agenda-files' list, plus all open org-mode files.
6730 This is useful for operations that need to scan all of a user's
6731 open and agenda-wise Org files."
6732 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6733 (dolist (buf (buffer-list))
6734 (with-current-buffer buf
6735 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6736 (let ((file (expand-file-name (buffer-file-name))))
6737 (unless (member file files)
6738 (push file files))))))
6739 files))
6741 (defsubst org-entry-beginning-position ()
6742 "Return the beginning position of the current entry."
6743 (save-excursion (outline-back-to-heading t) (point)))
6745 (defsubst org-entry-end-position ()
6746 "Return the end position of the current entry."
6747 (save-excursion (outline-next-heading) (point)))
6749 (defun org-cycle-hide-drawers (state)
6750 "Re-hide all drawers after a visibility state change."
6751 (when (and (derived-mode-p 'org-mode)
6752 (not (memq state '(overview folded contents))))
6753 (save-excursion
6754 (let* ((globalp (memq state '(contents all)))
6755 (beg (if globalp (point-min) (point)))
6756 (end (if globalp (point-max)
6757 (if (eq state 'children)
6758 (save-excursion (outline-next-heading) (point))
6759 (org-end-of-subtree t)))))
6760 (goto-char beg)
6761 (while (re-search-forward org-drawer-regexp end t)
6762 (org-flag-drawer t))))))
6764 (defun org-cycle-hide-inline-tasks (state)
6765 "Re-hide inline task when switching to 'contents visibility state."
6766 (when (and (eq state 'contents)
6767 (boundp 'org-inlinetask-min-level)
6768 org-inlinetask-min-level)
6769 (hide-sublevels (1- org-inlinetask-min-level))))
6771 (defun org-flag-drawer (flag)
6772 "When FLAG is non-nil, hide the drawer we are within.
6773 Otherwise make it visible."
6774 (save-excursion
6775 (beginning-of-line 1)
6776 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6777 (let ((b (match-end 0)))
6778 (if (re-search-forward
6779 "^[ \t]*:END:"
6780 (save-excursion (outline-next-heading) (point)) t)
6781 (outline-flag-region b (point-at-eol) flag)
6782 (error ":END: line missing at position %s" b))))))
6784 (defun org-subtree-end-visible-p ()
6785 "Is the end of the current subtree visible?"
6786 (pos-visible-in-window-p
6787 (save-excursion (org-end-of-subtree t) (point))))
6789 (defun org-first-headline-recenter (&optional N)
6790 "Move cursor to the first headline and recenter the headline.
6791 Optional argument N means put the headline into the Nth line of the window."
6792 (goto-char (point-min))
6793 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6794 (beginning-of-line)
6795 (recenter (prefix-numeric-value N))))
6797 ;;; Saving and restoring visibility
6799 (defun org-outline-overlay-data (&optional use-markers)
6800 "Return a list of the locations of all outline overlays.
6801 These are overlays with the `invisible' property value `outline'.
6802 The return value is a list of cons cells, with start and stop
6803 positions for each overlay.
6804 If USE-MARKERS is set, return the positions as markers."
6805 (let (beg end)
6806 (save-excursion
6807 (save-restriction
6808 (widen)
6809 (delq nil
6810 (mapcar (lambda (o)
6811 (when (eq (overlay-get o 'invisible) 'outline)
6812 (setq beg (overlay-start o)
6813 end (overlay-end o))
6814 (and beg end (> end beg)
6815 (if use-markers
6816 (cons (move-marker (make-marker) beg)
6817 (move-marker (make-marker) end))
6818 (cons beg end)))))
6819 (overlays-in (point-min) (point-max))))))))
6821 (defun org-set-outline-overlay-data (data)
6822 "Create visibility overlays for all positions in DATA.
6823 DATA should have been made by `org-outline-overlay-data'."
6824 (let (o)
6825 (save-excursion
6826 (save-restriction
6827 (widen)
6828 (show-all)
6829 (mapc (lambda (c)
6830 (outline-flag-region (car c) (cdr c) t))
6831 data)))))
6833 ;;; Folding of blocks
6835 (defvar org-hide-block-overlays nil
6836 "Overlays hiding blocks.")
6837 (make-variable-buffer-local 'org-hide-block-overlays)
6839 (defun org-block-map (function &optional start end)
6840 "Call FUNCTION at the head of all source blocks in the current buffer.
6841 Optional arguments START and END can be used to limit the range."
6842 (let ((start (or start (point-min)))
6843 (end (or end (point-max))))
6844 (save-excursion
6845 (goto-char start)
6846 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6847 (save-excursion
6848 (save-match-data
6849 (goto-char (match-beginning 0))
6850 (funcall function)))))))
6852 (defun org-hide-block-toggle-all ()
6853 "Toggle the visibility of all blocks in the current buffer."
6854 (org-block-map #'org-hide-block-toggle))
6856 (defun org-hide-block-all ()
6857 "Fold all blocks in the current buffer."
6858 (interactive)
6859 (org-show-block-all)
6860 (org-block-map #'org-hide-block-toggle-maybe))
6862 (defun org-show-block-all ()
6863 "Unfold all blocks in the current buffer."
6864 (interactive)
6865 (mapc 'delete-overlay org-hide-block-overlays)
6866 (setq org-hide-block-overlays nil))
6868 (defun org-hide-block-toggle-maybe ()
6869 "Toggle visibility of block at point."
6870 (interactive)
6871 (let ((case-fold-search t))
6872 (if (save-excursion
6873 (beginning-of-line 1)
6874 (looking-at org-block-regexp))
6875 (progn (org-hide-block-toggle)
6876 t) ;; to signal that we took action
6877 nil))) ;; to signal that we did not
6879 (defun org-hide-block-toggle (&optional force)
6880 "Toggle the visibility of the current block."
6881 (interactive)
6882 (save-excursion
6883 (beginning-of-line)
6884 (if (re-search-forward org-block-regexp nil t)
6885 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6886 (end (match-end 0)) ;; end of entire body
6888 (if (memq t (mapcar (lambda (overlay)
6889 (eq (overlay-get overlay 'invisible)
6890 'org-hide-block))
6891 (overlays-at start)))
6892 (if (or (not force) (eq force 'off))
6893 (mapc (lambda (ov)
6894 (when (member ov org-hide-block-overlays)
6895 (setq org-hide-block-overlays
6896 (delq ov org-hide-block-overlays)))
6897 (when (eq (overlay-get ov 'invisible)
6898 'org-hide-block)
6899 (delete-overlay ov)))
6900 (overlays-at start)))
6901 (setq ov (make-overlay start end))
6902 (overlay-put ov 'invisible 'org-hide-block)
6903 ;; make the block accessible to isearch
6904 (overlay-put
6905 ov 'isearch-open-invisible
6906 (lambda (ov)
6907 (when (member ov org-hide-block-overlays)
6908 (setq org-hide-block-overlays
6909 (delq ov org-hide-block-overlays)))
6910 (when (eq (overlay-get ov 'invisible)
6911 'org-hide-block)
6912 (delete-overlay ov))))
6913 (push ov org-hide-block-overlays)))
6914 (error "Not looking at a source block"))))
6916 ;; org-tab-after-check-for-cycling-hook
6917 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6918 ;; Remove overlays when changing major mode
6919 (add-hook 'org-mode-hook
6920 (lambda () (org-add-hook 'change-major-mode-hook
6921 'org-show-block-all 'append 'local)))
6923 ;;; Org-goto
6925 (defvar org-goto-window-configuration nil)
6926 (defvar org-goto-marker nil)
6927 (defvar org-goto-map)
6928 (defun org-goto-map ()
6929 "Set the keymap `org-goto'."
6930 (setq org-goto-map
6931 (let ((map (make-sparse-keymap)))
6932 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6933 mouse-drag-region universal-argument org-occur))
6934 cmd)
6935 (while (setq cmd (pop cmds))
6936 (substitute-key-definition cmd cmd map global-map)))
6937 (suppress-keymap map)
6938 (org-defkey map "\C-m" 'org-goto-ret)
6939 (org-defkey map [(return)] 'org-goto-ret)
6940 (org-defkey map [(left)] 'org-goto-left)
6941 (org-defkey map [(right)] 'org-goto-right)
6942 (org-defkey map [(control ?g)] 'org-goto-quit)
6943 (org-defkey map "\C-i" 'org-cycle)
6944 (org-defkey map [(tab)] 'org-cycle)
6945 (org-defkey map [(down)] 'outline-next-visible-heading)
6946 (org-defkey map [(up)] 'outline-previous-visible-heading)
6947 (if org-goto-auto-isearch
6948 (if (fboundp 'define-key-after)
6949 (define-key-after map [t] 'org-goto-local-auto-isearch)
6950 nil)
6951 (org-defkey map "q" 'org-goto-quit)
6952 (org-defkey map "n" 'outline-next-visible-heading)
6953 (org-defkey map "p" 'outline-previous-visible-heading)
6954 (org-defkey map "f" 'outline-forward-same-level)
6955 (org-defkey map "b" 'outline-backward-same-level)
6956 (org-defkey map "u" 'outline-up-heading))
6957 (org-defkey map "/" 'org-occur)
6958 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6959 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6960 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6961 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6962 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6963 map)))
6965 (defconst org-goto-help
6966 "Browse buffer copy, to find location or copy text.%s
6967 RET=jump to location C-g=quit and return to previous location
6968 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6970 (defvar org-goto-start-pos) ; dynamically scoped parameter
6972 ;; FIXME: Docstring does not mention both interfaces
6973 (defun org-goto (&optional alternative-interface)
6974 "Look up a different location in the current file, keeping current visibility.
6976 When you want look-up or go to a different location in a
6977 document, the fastest way is often to fold the entire buffer and
6978 then dive into the tree. This method has the disadvantage, that
6979 the previous location will be folded, which may not be what you
6980 want.
6982 This command works around this by showing a copy of the current
6983 buffer in an indirect buffer, in overview mode. You can dive
6984 into the tree in that copy, use org-occur and incremental search
6985 to find a location. When pressing RET or `Q', the command
6986 returns to the original buffer in which the visibility is still
6987 unchanged. After RET it will also jump to the location selected
6988 in the indirect buffer and expose the headline hierarchy above.
6990 With a prefix argument, use the alternative interface: e.g. if
6991 `org-goto-interface' is 'outline use 'outline-path-completion."
6992 (interactive "P")
6993 (org-goto-map)
6994 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6995 (org-refile-use-outline-path t)
6996 (org-refile-target-verify-function nil)
6997 (interface
6998 (if (not alternative-interface)
6999 org-goto-interface
7000 (if (eq org-goto-interface 'outline)
7001 'outline-path-completion
7002 'outline)))
7003 (org-goto-start-pos (point))
7004 (selected-point
7005 (if (eq interface 'outline)
7006 (car (org-get-location (current-buffer) org-goto-help))
7007 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7008 (org-refile-check-position pa)
7009 (nth 3 pa)))))
7010 (if selected-point
7011 (progn
7012 (org-mark-ring-push org-goto-start-pos)
7013 (goto-char selected-point)
7014 (if (or (outline-invisible-p) (org-invisible-p2))
7015 (org-show-context 'org-goto)))
7016 (message "Quit"))))
7018 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7019 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7020 (defvar org-goto-local-auto-isearch-map) ; defined below
7022 (defun org-get-location (buf help)
7023 "Let the user select a location in the Org-mode buffer BUF.
7024 This function uses a recursive edit. It returns the selected position
7025 or nil."
7026 (org-no-popups
7027 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7028 (isearch-hide-immediately nil)
7029 (isearch-search-fun-function
7030 (lambda () 'org-goto-local-search-headings))
7031 (org-goto-selected-point org-goto-exit-command))
7032 (save-excursion
7033 (save-window-excursion
7034 (delete-other-windows)
7035 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7036 (org-pop-to-buffer-same-window
7037 (condition-case nil
7038 (make-indirect-buffer (current-buffer) "*org-goto*")
7039 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7040 (with-output-to-temp-buffer "*Org Help*"
7041 (princ (format help (if org-goto-auto-isearch
7042 " Just type for auto-isearch."
7043 " n/p/f/b/u to navigate, q to quit."))))
7044 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7045 (setq buffer-read-only nil)
7046 (let ((org-startup-truncated t)
7047 (org-startup-folded nil)
7048 (org-startup-align-all-tables nil))
7049 (org-mode)
7050 (org-overview))
7051 (setq buffer-read-only t)
7052 (if (and (boundp 'org-goto-start-pos)
7053 (integer-or-marker-p org-goto-start-pos))
7054 (let ((org-show-hierarchy-above t)
7055 (org-show-siblings t)
7056 (org-show-following-heading t))
7057 (goto-char org-goto-start-pos)
7058 (and (outline-invisible-p) (org-show-context)))
7059 (goto-char (point-min)))
7060 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7061 (message "Select location and press RET")
7062 (use-local-map org-goto-map)
7063 (recursive-edit)))
7064 (kill-buffer "*org-goto*")
7065 (cons org-goto-selected-point org-goto-exit-command))))
7067 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7068 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7069 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7070 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7072 (defun org-goto-local-search-headings (string bound noerror)
7073 "Search and make sure that any matches are in headlines."
7074 (catch 'return
7075 (while (if isearch-forward
7076 (search-forward string bound noerror)
7077 (search-backward string bound noerror))
7078 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7079 (and (member :headline context)
7080 (not (member :tags context))))
7081 (throw 'return (point))))))
7083 (defun org-goto-local-auto-isearch ()
7084 "Start isearch."
7085 (interactive)
7086 (goto-char (point-min))
7087 (let ((keys (this-command-keys)))
7088 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7089 (isearch-mode t)
7090 (isearch-process-search-char (string-to-char keys)))))
7092 (defun org-goto-ret (&optional arg)
7093 "Finish `org-goto' by going to the new location."
7094 (interactive "P")
7095 (setq org-goto-selected-point (point)
7096 org-goto-exit-command 'return)
7097 (throw 'exit nil))
7099 (defun org-goto-left ()
7100 "Finish `org-goto' by going to the new location."
7101 (interactive)
7102 (if (org-at-heading-p)
7103 (progn
7104 (beginning-of-line 1)
7105 (setq org-goto-selected-point (point)
7106 org-goto-exit-command 'left)
7107 (throw 'exit nil))
7108 (error "Not on a heading")))
7110 (defun org-goto-right ()
7111 "Finish `org-goto' by going to the new location."
7112 (interactive)
7113 (if (org-at-heading-p)
7114 (progn
7115 (setq org-goto-selected-point (point)
7116 org-goto-exit-command 'right)
7117 (throw 'exit nil))
7118 (error "Not on a heading")))
7120 (defun org-goto-quit ()
7121 "Finish `org-goto' without cursor motion."
7122 (interactive)
7123 (setq org-goto-selected-point nil)
7124 (setq org-goto-exit-command 'quit)
7125 (throw 'exit nil))
7127 ;;; Indirect buffer display of subtrees
7129 (defvar org-indirect-dedicated-frame nil
7130 "This is the frame being used for indirect tree display.")
7131 (defvar org-last-indirect-buffer nil)
7133 (defun org-tree-to-indirect-buffer (&optional arg)
7134 "Create indirect buffer and narrow it to current subtree.
7135 With a numerical prefix ARG, go up to this level and then take that tree.
7136 If ARG is negative, go up that many levels.
7138 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7139 indirect buffer previously made with this command, to avoid proliferation of
7140 indirect buffers. However, when you call the command with a \
7141 \\[universal-argument] prefix, or
7142 when `org-indirect-buffer-display' is `new-frame', the last buffer
7143 is kept so that you can work with several indirect buffers at the same time.
7144 If `org-indirect-buffer-display' is `dedicated-frame', the \
7145 \\[universal-argument] prefix also
7146 requests that a new frame be made for the new buffer, so that the dedicated
7147 frame is not changed."
7148 (interactive "P")
7149 (let ((cbuf (current-buffer))
7150 (cwin (selected-window))
7151 (pos (point))
7152 beg end level heading ibuf)
7153 (save-excursion
7154 (org-back-to-heading t)
7155 (when (numberp arg)
7156 (setq level (org-outline-level))
7157 (if (< arg 0) (setq arg (+ level arg)))
7158 (while (> (setq level (org-outline-level)) arg)
7159 (org-up-heading-safe)))
7160 (setq beg (point)
7161 heading (org-get-heading))
7162 (org-end-of-subtree t t)
7163 (if (org-at-heading-p) (backward-char 1))
7164 (setq end (point)))
7165 (if (and (buffer-live-p org-last-indirect-buffer)
7166 (not (eq org-indirect-buffer-display 'new-frame))
7167 (not arg))
7168 (kill-buffer org-last-indirect-buffer))
7169 (setq ibuf (org-get-indirect-buffer cbuf)
7170 org-last-indirect-buffer ibuf)
7171 (cond
7172 ((or (eq org-indirect-buffer-display 'new-frame)
7173 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7174 (select-frame (make-frame))
7175 (delete-other-windows)
7176 (org-pop-to-buffer-same-window ibuf)
7177 (org-set-frame-title heading))
7178 ((eq org-indirect-buffer-display 'dedicated-frame)
7179 (raise-frame
7180 (select-frame (or (and org-indirect-dedicated-frame
7181 (frame-live-p org-indirect-dedicated-frame)
7182 org-indirect-dedicated-frame)
7183 (setq org-indirect-dedicated-frame (make-frame)))))
7184 (delete-other-windows)
7185 (org-pop-to-buffer-same-window ibuf)
7186 (org-set-frame-title (concat "Indirect: " heading)))
7187 ((eq org-indirect-buffer-display 'current-window)
7188 (org-pop-to-buffer-same-window ibuf))
7189 ((eq org-indirect-buffer-display 'other-window)
7190 (pop-to-buffer ibuf))
7191 (t (error "Invalid value")))
7192 (if (featurep 'xemacs)
7193 (save-excursion (org-mode) (turn-on-font-lock)))
7194 (narrow-to-region beg end)
7195 (show-all)
7196 (goto-char pos)
7197 (run-hook-with-args 'org-cycle-hook 'all)
7198 (and (window-live-p cwin) (select-window cwin))))
7200 (defun org-get-indirect-buffer (&optional buffer)
7201 (setq buffer (or buffer (current-buffer)))
7202 (let ((n 1) (base (buffer-name buffer)) bname)
7203 (while (buffer-live-p
7204 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7205 (setq n (1+ n)))
7206 (condition-case nil
7207 (make-indirect-buffer buffer bname 'clone)
7208 (error (make-indirect-buffer buffer bname)))))
7210 (defun org-set-frame-title (title)
7211 "Set the title of the current frame to the string TITLE."
7212 ;; FIXME: how to name a single frame in XEmacs???
7213 (unless (featurep 'xemacs)
7214 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7216 ;;;; Structure editing
7218 ;;; Inserting headlines
7220 (defun org-previous-line-empty-p ()
7221 (save-excursion
7222 (and (not (bobp))
7223 (or (beginning-of-line 0) t)
7224 (save-match-data
7225 (looking-at "[ \t]*$")))))
7227 (defun org-insert-heading (&optional force-heading invisible-ok)
7228 "Insert a new heading or item with same depth at point.
7229 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7230 If point is at the beginning of a headline, insert a sibling before the
7231 current headline. If point is not at the beginning, split the line,
7232 create the new headline with the text in the current line after point
7233 \(but see also the variable `org-M-RET-may-split-line').
7235 With a double prefix arg, force the heading to be inserted at the
7236 end of the parent subtree.
7238 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7239 This is important for non-interactive uses of the command."
7240 (interactive "P")
7241 (if (or (= (buffer-size) 0)
7242 (and (not (save-excursion
7243 (and (ignore-errors (org-back-to-heading invisible-ok))
7244 (org-at-heading-p))))
7245 (or force-heading (not (org-in-item-p)))))
7246 (progn
7247 (insert "\n* ")
7248 (run-hooks 'org-insert-heading-hook))
7249 (when (or force-heading (not (org-insert-item)))
7250 (let* ((empty-line-p nil)
7251 (level nil)
7252 (on-heading (org-at-heading-p))
7253 (head (save-excursion
7254 (condition-case nil
7255 (progn
7256 (org-back-to-heading invisible-ok)
7257 (when (and (not on-heading)
7258 (featurep 'org-inlinetask)
7259 (integerp org-inlinetask-min-level)
7260 (>= (length (match-string 0))
7261 org-inlinetask-min-level))
7262 ;; Find a heading level before the inline task
7263 (while (and (setq level (org-up-heading-safe))
7264 (>= level org-inlinetask-min-level)))
7265 (if (org-at-heading-p)
7266 (org-back-to-heading invisible-ok)
7267 (error "This should not happen")))
7268 (setq empty-line-p (org-previous-line-empty-p))
7269 (match-string 0))
7270 (error "*"))))
7271 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7272 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7273 pos hide-previous previous-pos)
7274 (cond
7275 ((and (org-at-heading-p) (bolp)
7276 (or (bobp)
7277 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7278 ;; insert before the current line
7279 (open-line (if blank 2 1)))
7280 ((and (bolp)
7281 (not org-insert-heading-respect-content)
7282 (or (bobp)
7283 (save-excursion
7284 (backward-char 1) (not (outline-invisible-p)))))
7285 ;; insert right here
7286 nil)
7288 ;; somewhere in the line
7289 (save-excursion
7290 (setq previous-pos (point-at-bol))
7291 (end-of-line)
7292 (setq hide-previous (outline-invisible-p)))
7293 (and org-insert-heading-respect-content (org-show-subtree))
7294 (let ((split
7295 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7296 (save-excursion
7297 (let ((p (point)))
7298 (goto-char (point-at-bol))
7299 (and (looking-at org-complex-heading-regexp)
7300 (match-beginning 4)
7301 (> p (match-beginning 4)))))))
7302 tags pos)
7303 (cond
7304 (org-insert-heading-respect-content
7305 (if (not (equal force-heading '(16)))
7306 (org-end-of-subtree nil t)
7307 (org-up-heading-safe)
7308 (org-end-of-subtree nil t))
7309 (when (featurep 'org-inlinetask)
7310 (while (and (not (eobp))
7311 (looking-at "\\(\\*+\\)[ \t]+")
7312 (>= (length (match-string 1))
7313 org-inlinetask-min-level))
7314 (org-end-of-subtree nil t)))
7315 (or (bolp) (newline))
7316 (or (org-previous-line-empty-p)
7317 (and blank (newline)))
7318 (open-line 1))
7319 ((org-at-heading-p)
7320 (when hide-previous
7321 (show-children)
7322 (org-show-entry))
7323 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7324 (setq tags (and (match-end 2) (match-string 2)))
7325 (and (match-end 1)
7326 (delete-region (match-beginning 1) (match-end 1)))
7327 (setq pos (point-at-bol))
7328 (or split (end-of-line 1))
7329 (delete-horizontal-space)
7330 (if (string-match "\\`\\*+\\'"
7331 (buffer-substring (point-at-bol) (point)))
7332 (insert " "))
7333 (newline (if blank 2 1))
7334 (when tags
7335 (save-excursion
7336 (goto-char pos)
7337 (end-of-line 1)
7338 (insert " " tags)
7339 (org-set-tags nil 'align))))
7341 (or split (end-of-line 1))
7342 (newline (if blank 2 1)))))))
7343 (insert head) (just-one-space)
7344 (setq pos (point))
7345 (end-of-line 1)
7346 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7347 (when (and org-insert-heading-respect-content hide-previous)
7348 (save-excursion
7349 (goto-char previous-pos)
7350 (hide-subtree)))
7351 (run-hooks 'org-insert-heading-hook)))))
7353 (defun org-get-heading (&optional no-tags no-todo)
7354 "Return the heading of the current entry, without the stars.
7355 When NO-TAGS is non-nil, don't include tags.
7356 When NO-TODO is non-nil, don't include TODO keywords."
7357 (save-excursion
7358 (org-back-to-heading t)
7359 (cond
7360 ((and no-tags no-todo)
7361 (looking-at org-complex-heading-regexp)
7362 (match-string 4))
7363 (no-tags
7364 (looking-at (concat org-outline-regexp
7365 "\\(.*?\\)"
7366 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7367 (match-string 1))
7368 (no-todo
7369 (looking-at org-todo-line-regexp)
7370 (match-string 3))
7371 (t (looking-at org-heading-regexp)
7372 (match-string 2)))))
7374 (defun org-heading-components ()
7375 "Return the components of the current heading.
7376 This is a list with the following elements:
7377 - the level as an integer
7378 - the reduced level, different if `org-odd-levels-only' is set.
7379 - the TODO keyword, or nil
7380 - the priority character, like ?A, or nil if no priority is given
7381 - the headline text itself, or the tags string if no headline text
7382 - the tags string, or nil."
7383 (save-excursion
7384 (org-back-to-heading t)
7385 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7386 (list (length (match-string 1))
7387 (org-reduced-level (length (match-string 1)))
7388 (org-match-string-no-properties 2)
7389 (and (match-end 3) (aref (match-string 3) 2))
7390 (org-match-string-no-properties 4)
7391 (org-match-string-no-properties 5)))))
7393 (defun org-get-entry ()
7394 "Get the entry text, after heading, entire subtree."
7395 (save-excursion
7396 (org-back-to-heading t)
7397 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7399 (defun org-insert-heading-after-current ()
7400 "Insert a new heading with same level as current, after current subtree."
7401 (interactive)
7402 (org-back-to-heading)
7403 (org-insert-heading)
7404 (org-move-subtree-down)
7405 (end-of-line 1))
7407 (defun org-insert-heading-respect-content ()
7408 (interactive)
7409 (let ((org-insert-heading-respect-content t))
7410 (org-insert-heading t)))
7412 (defun org-insert-todo-heading-respect-content (&optional force-state)
7413 (interactive "P")
7414 (let ((org-insert-heading-respect-content t))
7415 (org-insert-todo-heading force-state t)))
7417 (defun org-insert-todo-heading (arg &optional force-heading)
7418 "Insert a new heading with the same level and TODO state as current heading.
7419 If the heading has no TODO state, or if the state is DONE, use the first
7420 state (TODO by default). Also one prefix arg, force first state. With two
7421 prefix args, force inserting at the end of the parent subtree."
7422 (interactive "P")
7423 (when (or force-heading (not (org-insert-item 'checkbox)))
7424 (org-insert-heading (or (and (equal arg '(16)) '(16))
7425 force-heading))
7426 (save-excursion
7427 (org-back-to-heading)
7428 (outline-previous-heading)
7429 (looking-at org-todo-line-regexp))
7430 (let*
7431 ((new-mark-x
7432 (if (or arg
7433 (not (match-beginning 2))
7434 (member (match-string 2) org-done-keywords))
7435 (car org-todo-keywords-1)
7436 (match-string 2)))
7437 (new-mark
7439 (run-hook-with-args-until-success
7440 'org-todo-get-default-hook new-mark-x nil)
7441 new-mark-x)))
7442 (beginning-of-line 1)
7443 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7444 (if org-treat-insert-todo-heading-as-state-change
7445 (org-todo new-mark)
7446 (insert new-mark " "))))
7447 (when org-provide-todo-statistics
7448 (org-update-parent-todo-statistics))))
7450 (defun org-insert-subheading (arg)
7451 "Insert a new subheading and demote it.
7452 Works for outline headings and for plain lists alike."
7453 (interactive "P")
7454 (org-insert-heading arg)
7455 (cond
7456 ((org-at-heading-p) (org-do-demote))
7457 ((org-at-item-p) (org-indent-item))))
7459 (defun org-insert-todo-subheading (arg)
7460 "Insert a new subheading with TODO keyword or checkbox and demote it.
7461 Works for outline headings and for plain lists alike."
7462 (interactive "P")
7463 (org-insert-todo-heading arg)
7464 (cond
7465 ((org-at-heading-p) (org-do-demote))
7466 ((org-at-item-p) (org-indent-item))))
7468 ;;; Promotion and Demotion
7470 (defvar org-after-demote-entry-hook nil
7471 "Hook run after an entry has been demoted.
7472 The cursor will be at the beginning of the entry.
7473 When a subtree is being demoted, the hook will be called for each node.")
7475 (defvar org-after-promote-entry-hook nil
7476 "Hook run after an entry has been promoted.
7477 The cursor will be at the beginning of the entry.
7478 When a subtree is being promoted, the hook will be called for each node.")
7480 (defun org-promote-subtree ()
7481 "Promote the entire subtree.
7482 See also `org-promote'."
7483 (interactive)
7484 (save-excursion
7485 (org-with-limited-levels (org-map-tree 'org-promote)))
7486 (org-fix-position-after-promote))
7488 (defun org-demote-subtree ()
7489 "Demote the entire subtree. See `org-demote'.
7490 See also `org-promote'."
7491 (interactive)
7492 (save-excursion
7493 (org-with-limited-levels (org-map-tree 'org-demote)))
7494 (org-fix-position-after-promote))
7497 (defun org-do-promote ()
7498 "Promote the current heading higher up the tree.
7499 If the region is active in `transient-mark-mode', promote all headings
7500 in the region."
7501 (interactive)
7502 (save-excursion
7503 (if (org-region-active-p)
7504 (org-map-region 'org-promote (region-beginning) (region-end))
7505 (org-promote)))
7506 (org-fix-position-after-promote))
7508 (defun org-do-demote ()
7509 "Demote the current heading lower down the tree.
7510 If the region is active in `transient-mark-mode', demote all headings
7511 in the region."
7512 (interactive)
7513 (save-excursion
7514 (if (org-region-active-p)
7515 (org-map-region 'org-demote (region-beginning) (region-end))
7516 (org-demote)))
7517 (org-fix-position-after-promote))
7519 (defun org-fix-position-after-promote ()
7520 "Make sure that after pro/demotion cursor position is right."
7521 (let ((pos (point)))
7522 (when (save-excursion
7523 (beginning-of-line 1)
7524 (looking-at org-todo-line-regexp)
7525 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7526 (cond ((eobp) (insert " "))
7527 ((eolp) (insert " "))
7528 ((equal (char-after) ?\ ) (forward-char 1))))))
7530 (defun org-current-level ()
7531 "Return the level of the current entry, or nil if before the first headline.
7532 The level is the number of stars at the beginning of the headline."
7533 (save-excursion
7534 (org-with-limited-levels
7535 (if (ignore-errors (org-back-to-heading t))
7536 (funcall outline-level)))))
7538 (defun org-get-previous-line-level ()
7539 "Return the outline depth of the last headline before the current line.
7540 Returns 0 for the first headline in the buffer, and nil if before the
7541 first headline."
7542 (let ((current-level (org-current-level))
7543 (prev-level (when (> (line-number-at-pos) 1)
7544 (save-excursion
7545 (beginning-of-line 0)
7546 (org-current-level)))))
7547 (cond ((null current-level) nil) ; Before first headline
7548 ((null prev-level) 0) ; At first headline
7549 (prev-level))))
7551 (defun org-reduced-level (l)
7552 "Compute the effective level of a heading.
7553 This takes into account the setting of `org-odd-levels-only'."
7554 (cond
7555 ((zerop l) 0)
7556 (org-odd-levels-only (1+ (floor (/ l 2))))
7557 (t l)))
7559 (defun org-level-increment ()
7560 "Return the number of stars that will be added or removed at a
7561 time to headlines when structure editing, based on the value of
7562 `org-odd-levels-only'."
7563 (if org-odd-levels-only 2 1))
7565 (defun org-get-valid-level (level &optional change)
7566 "Rectify a level change under the influence of `org-odd-levels-only'
7567 LEVEL is a current level, CHANGE is by how much the level should be
7568 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7569 even level numbers will become the next higher odd number."
7570 (if org-odd-levels-only
7571 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7572 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7573 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7574 (max 1 (+ level (or change 0)))))
7576 (org-define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
7578 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7579 ;; ̀org-with-limited-levels'
7580 (defun org-promote ()
7581 "Promote the current heading higher up the tree.
7582 If the region is active in `transient-mark-mode', promote all headings
7583 in the region."
7584 (org-back-to-heading t)
7585 (let* ((level (save-match-data (funcall outline-level)))
7586 (after-change-functions (remove 'flyspell-after-change-function
7587 after-change-functions))
7588 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7589 (diff (abs (- level (length up-head) -1))))
7590 (cond ((and (= level 1) org-called-with-limited-levels
7591 org-allow-promoting-top-level-subtree)
7592 (replace-match "# " nil t))
7593 ((= level 1)
7594 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7595 (t (replace-match up-head nil t)))
7596 ;; Fixup tag positioning
7597 (unless (= level 1)
7598 (and org-auto-align-tags (org-set-tags nil t))
7599 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7600 (run-hooks 'org-after-promote-entry-hook)))
7602 (defun org-demote ()
7603 "Demote the current heading lower down the tree.
7604 If the region is active in `transient-mark-mode', demote all headings
7605 in the region."
7606 (org-back-to-heading t)
7607 (let* ((level (save-match-data (funcall outline-level)))
7608 (after-change-functions (remove 'flyspell-after-change-function
7609 after-change-functions))
7610 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7611 (diff (abs (- level (length down-head) -1))))
7612 (replace-match down-head nil t)
7613 ;; Fixup tag positioning
7614 (and org-auto-align-tags (org-set-tags nil t))
7615 (if org-adapt-indentation (org-fixup-indentation diff))
7616 (run-hooks 'org-after-demote-entry-hook)))
7618 (defun org-cycle-level ()
7619 "Cycle the level of an empty headline through possible states.
7620 This goes first to child, then to parent, level, then up the hierarchy.
7621 After top level, it switches back to sibling level."
7622 (interactive)
7623 (let ((org-adapt-indentation nil))
7624 (when (org-point-at-end-of-empty-headline)
7625 (setq this-command 'org-cycle-level) ; Only needed for caching
7626 (let ((cur-level (org-current-level))
7627 (prev-level (org-get-previous-line-level)))
7628 (cond
7629 ;; If first headline in file, promote to top-level.
7630 ((= prev-level 0)
7631 (loop repeat (/ (- cur-level 1) (org-level-increment))
7632 do (org-do-promote)))
7633 ;; If same level as prev, demote one.
7634 ((= prev-level cur-level)
7635 (org-do-demote))
7636 ;; If parent is top-level, promote to top level if not already.
7637 ((= prev-level 1)
7638 (loop repeat (/ (- cur-level 1) (org-level-increment))
7639 do (org-do-promote)))
7640 ;; If top-level, return to prev-level.
7641 ((= cur-level 1)
7642 (loop repeat (/ (- prev-level 1) (org-level-increment))
7643 do (org-do-demote)))
7644 ;; If less than prev-level, promote one.
7645 ((< cur-level prev-level)
7646 (org-do-promote))
7647 ;; If deeper than prev-level, promote until higher than
7648 ;; prev-level.
7649 ((> cur-level prev-level)
7650 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7651 do (org-do-promote))))
7652 t))))
7654 (defun org-map-tree (fun)
7655 "Call FUN for every heading underneath the current one."
7656 (org-back-to-heading)
7657 (let ((level (funcall outline-level)))
7658 (save-excursion
7659 (funcall fun)
7660 (while (and (progn
7661 (outline-next-heading)
7662 (> (funcall outline-level) level))
7663 (not (eobp)))
7664 (funcall fun)))))
7666 (defun org-map-region (fun beg end)
7667 "Call FUN for every heading between BEG and END."
7668 (let ((org-ignore-region t))
7669 (save-excursion
7670 (setq end (copy-marker end))
7671 (goto-char beg)
7672 (if (and (re-search-forward org-outline-regexp-bol nil t)
7673 (< (point) end))
7674 (funcall fun))
7675 (while (and (progn
7676 (outline-next-heading)
7677 (< (point) end))
7678 (not (eobp)))
7679 (funcall fun)))))
7681 (defvar org-property-end-re) ; silence byte-compiler
7682 (defun org-fixup-indentation (diff)
7683 "Change the indentation in the current entry by DIFF.
7684 However, if any line in the current entry has no indentation, or if it
7685 would end up with no indentation after the change, nothing at all is done."
7686 (save-excursion
7687 (let ((end (save-excursion (outline-next-heading)
7688 (point-marker)))
7689 (prohibit (if (> diff 0)
7690 "^\\S-"
7691 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7692 col)
7693 (unless (save-excursion (end-of-line 1)
7694 (re-search-forward prohibit end t))
7695 (while (and (< (point) end)
7696 (re-search-forward "^[ \t]+" end t))
7697 (goto-char (match-end 0))
7698 (setq col (current-column))
7699 (if (< diff 0) (replace-match ""))
7700 (org-indent-to-column (+ diff col))))
7701 (move-marker end nil))))
7703 (defun org-convert-to-odd-levels ()
7704 "Convert an org-mode file with all levels allowed to one with odd levels.
7705 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7706 level 5 etc."
7707 (interactive)
7708 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7709 (let ((outline-level 'org-outline-level)
7710 (org-odd-levels-only nil) n)
7711 (save-excursion
7712 (goto-char (point-min))
7713 (while (re-search-forward "^\\*\\*+ " nil t)
7714 (setq n (- (length (match-string 0)) 2))
7715 (while (>= (setq n (1- n)) 0)
7716 (org-demote))
7717 (end-of-line 1))))))
7719 (defun org-convert-to-oddeven-levels ()
7720 "Convert an org-mode file with only odd levels to one with odd/even levels.
7721 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7722 file contains a section with an even level, conversion would
7723 destroy the structure of the file. An error is signaled in this
7724 case."
7725 (interactive)
7726 (goto-char (point-min))
7727 ;; First check if there are no even levels
7728 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7729 (org-show-context t)
7730 (error "Not all levels are odd in this file. Conversion not possible"))
7731 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7732 (let ((outline-regexp org-outline-regexp)
7733 (outline-level 'org-outline-level)
7734 (org-odd-levels-only nil) n)
7735 (save-excursion
7736 (goto-char (point-min))
7737 (while (re-search-forward "^\\*\\*+ " nil t)
7738 (setq n (/ (1- (length (match-string 0))) 2))
7739 (while (>= (setq n (1- n)) 0)
7740 (org-promote))
7741 (end-of-line 1))))))
7743 (defun org-tr-level (n)
7744 "Make N odd if required."
7745 (if org-odd-levels-only (1+ (/ n 2)) n))
7747 ;;; Vertical tree motion, cutting and pasting of subtrees
7749 (defun org-move-subtree-up (&optional arg)
7750 "Move the current subtree up past ARG headlines of the same level."
7751 (interactive "p")
7752 (org-move-subtree-down (- (prefix-numeric-value arg))))
7754 (defun org-move-subtree-down (&optional arg)
7755 "Move the current subtree down past ARG headlines of the same level."
7756 (interactive "p")
7757 (setq arg (prefix-numeric-value arg))
7758 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7759 'org-get-last-sibling))
7760 (ins-point (make-marker))
7761 (cnt (abs arg))
7762 (col (current-column))
7763 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7764 ;; Select the tree
7765 (org-back-to-heading)
7766 (setq beg0 (point))
7767 (save-excursion
7768 (setq ne-beg (org-back-over-empty-lines))
7769 (setq beg (point)))
7770 (save-match-data
7771 (save-excursion (outline-end-of-heading)
7772 (setq folded (outline-invisible-p)))
7773 (outline-end-of-subtree))
7774 (outline-next-heading)
7775 (setq ne-end (org-back-over-empty-lines))
7776 (setq end (point))
7777 (goto-char beg0)
7778 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7779 ;; include less whitespace
7780 (save-excursion
7781 (goto-char beg)
7782 (forward-line (- ne-beg ne-end))
7783 (setq beg (point))))
7784 ;; Find insertion point, with error handling
7785 (while (> cnt 0)
7786 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7787 (progn (goto-char beg0)
7788 (error "Cannot move past superior level or buffer limit")))
7789 (setq cnt (1- cnt)))
7790 (if (> arg 0)
7791 ;; Moving forward - still need to move over subtree
7792 (progn (org-end-of-subtree t t)
7793 (save-excursion
7794 (org-back-over-empty-lines)
7795 (or (bolp) (newline)))))
7796 (setq ne-ins (org-back-over-empty-lines))
7797 (move-marker ins-point (point))
7798 (setq txt (buffer-substring beg end))
7799 (org-save-markers-in-region beg end)
7800 (delete-region beg end)
7801 (org-remove-empty-overlays-at beg)
7802 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7803 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7804 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7805 (let ((bbb (point)))
7806 (insert-before-markers txt)
7807 (org-reinstall-markers-in-region bbb)
7808 (move-marker ins-point bbb))
7809 (or (bolp) (insert "\n"))
7810 (setq ins-end (point))
7811 (goto-char ins-point)
7812 (org-skip-whitespace)
7813 (when (and (< arg 0)
7814 (org-first-sibling-p)
7815 (> ne-ins ne-beg))
7816 ;; Move whitespace back to beginning
7817 (save-excursion
7818 (goto-char ins-end)
7819 (let ((kill-whole-line t))
7820 (kill-line (- ne-ins ne-beg)) (point)))
7821 (insert (make-string (- ne-ins ne-beg) ?\n)))
7822 (move-marker ins-point nil)
7823 (if folded
7824 (hide-subtree)
7825 (org-show-entry)
7826 (show-children)
7827 (org-cycle-hide-drawers 'children))
7828 (org-clean-visibility-after-subtree-move)
7829 ;; move back to the initial column we were at
7830 (move-to-column col)))
7832 (defvar org-subtree-clip ""
7833 "Clipboard for cut and paste of subtrees.
7834 This is actually only a copy of the kill, because we use the normal kill
7835 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7837 (defvar org-subtree-clip-folded nil
7838 "Was the last copied subtree folded?
7839 This is used to fold the tree back after pasting.")
7841 (defun org-cut-subtree (&optional n)
7842 "Cut the current subtree into the clipboard.
7843 With prefix arg N, cut this many sequential subtrees.
7844 This is a short-hand for marking the subtree and then cutting it."
7845 (interactive "p")
7846 (org-copy-subtree n 'cut))
7848 (defun org-copy-subtree (&optional n cut force-store-markers)
7849 "Cut the current subtree into the clipboard.
7850 With prefix arg N, cut this many sequential subtrees.
7851 This is a short-hand for marking the subtree and then copying it.
7852 If CUT is non-nil, actually cut the subtree.
7853 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7854 of some markers in the region, even if CUT is non-nil. This is
7855 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7856 (interactive "p")
7857 (let (beg end folded (beg0 (point)))
7858 (if (org-called-interactively-p 'any)
7859 (org-back-to-heading nil) ; take what looks like a subtree
7860 (org-back-to-heading t)) ; take what is really there
7861 (setq beg (point))
7862 (skip-chars-forward " \t\r\n")
7863 (save-match-data
7864 (save-excursion (outline-end-of-heading)
7865 (setq folded (outline-invisible-p)))
7866 (condition-case nil
7867 (org-forward-heading-same-level (1- n) t)
7868 (error nil))
7869 (org-end-of-subtree t t))
7870 (setq end (point))
7871 (goto-char beg0)
7872 (when (> end beg)
7873 (setq org-subtree-clip-folded folded)
7874 (when (or cut force-store-markers)
7875 (org-save-markers-in-region beg end))
7876 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7877 (setq org-subtree-clip (current-kill 0))
7878 (message "%s: Subtree(s) with %d characters"
7879 (if cut "Cut" "Copied")
7880 (length org-subtree-clip)))))
7882 (defun org-paste-subtree (&optional level tree for-yank)
7883 "Paste the clipboard as a subtree, with modification of headline level.
7884 The entire subtree is promoted or demoted in order to match a new headline
7885 level.
7887 If the cursor is at the beginning of a headline, the same level as
7888 that headline is used to paste the tree
7890 If not, the new level is derived from the *visible* headings
7891 before and after the insertion point, and taken to be the inferior headline
7892 level of the two. So if the previous visible heading is level 3 and the
7893 next is level 4 (or vice versa), level 4 will be used for insertion.
7894 This makes sure that the subtree remains an independent subtree and does
7895 not swallow low level entries.
7897 You can also force a different level, either by using a numeric prefix
7898 argument, or by inserting the heading marker by hand. For example, if the
7899 cursor is after \"*****\", then the tree will be shifted to level 5.
7901 If optional TREE is given, use this text instead of the kill ring.
7903 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7904 move back over whitespace before inserting, and move point to the end of
7905 the inserted text when done."
7906 (interactive "P")
7907 (setq tree (or tree (and kill-ring (current-kill 0))))
7908 (unless (org-kill-is-subtree-p tree)
7909 (error "%s"
7910 (substitute-command-keys
7911 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7912 (org-with-limited-levels
7913 (let* ((visp (not (outline-invisible-p)))
7914 (txt tree)
7915 (^re_ "\\(\\*+\\)[ \t]*")
7916 (old-level (if (string-match org-outline-regexp-bol txt)
7917 (- (match-end 0) (match-beginning 0) 1)
7918 -1))
7919 (force-level (cond (level (prefix-numeric-value level))
7920 ((and (looking-at "[ \t]*$")
7921 (string-match
7922 "^\\*+$" (buffer-substring
7923 (point-at-bol) (point))))
7924 (- (match-end 1) (match-beginning 1)))
7925 ((and (bolp)
7926 (looking-at org-outline-regexp))
7927 (- (match-end 0) (point) 1))))
7928 (previous-level (save-excursion
7929 (condition-case nil
7930 (progn
7931 (outline-previous-visible-heading 1)
7932 (if (looking-at ^re_)
7933 (- (match-end 0) (match-beginning 0) 1)
7935 (error 1))))
7936 (next-level (save-excursion
7937 (condition-case nil
7938 (progn
7939 (or (looking-at org-outline-regexp)
7940 (outline-next-visible-heading 1))
7941 (if (looking-at ^re_)
7942 (- (match-end 0) (match-beginning 0) 1)
7944 (error 1))))
7945 (new-level (or force-level (max previous-level next-level)))
7946 (shift (if (or (= old-level -1)
7947 (= new-level -1)
7948 (= old-level new-level))
7950 (- new-level old-level)))
7951 (delta (if (> shift 0) -1 1))
7952 (func (if (> shift 0) 'org-demote 'org-promote))
7953 (org-odd-levels-only nil)
7954 beg end newend)
7955 ;; Remove the forced level indicator
7956 (if force-level
7957 (delete-region (point-at-bol) (point)))
7958 ;; Paste
7959 (beginning-of-line (if (bolp) 1 2))
7960 (setq beg (point))
7961 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7962 (insert-before-markers txt)
7963 (unless (string-match "\n\\'" txt) (insert "\n"))
7964 (setq newend (point))
7965 (org-reinstall-markers-in-region beg)
7966 (setq end (point))
7967 (goto-char beg)
7968 (skip-chars-forward " \t\n\r")
7969 (setq beg (point))
7970 (if (and (outline-invisible-p) visp)
7971 (save-excursion (outline-show-heading)))
7972 ;; Shift if necessary
7973 (unless (= shift 0)
7974 (save-restriction
7975 (narrow-to-region beg end)
7976 (while (not (= shift 0))
7977 (org-map-region func (point-min) (point-max))
7978 (setq shift (+ delta shift)))
7979 (goto-char (point-min))
7980 (setq newend (point-max))))
7981 (when (or (org-called-interactively-p 'interactive) for-yank)
7982 (message "Clipboard pasted as level %d subtree" new-level))
7983 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7984 kill-ring
7985 (eq org-subtree-clip (current-kill 0))
7986 org-subtree-clip-folded)
7987 ;; The tree was folded before it was killed/copied
7988 (hide-subtree))
7989 (and for-yank (goto-char newend)))))
7991 (defun org-kill-is-subtree-p (&optional txt)
7992 "Check if the current kill is an outline subtree, or a set of trees.
7993 Returns nil if kill does not start with a headline, or if the first
7994 headline level is not the largest headline level in the tree.
7995 So this will actually accept several entries of equal levels as well,
7996 which is OK for `org-paste-subtree'.
7997 If optional TXT is given, check this string instead of the current kill."
7998 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7999 (re (org-get-limited-outline-regexp))
8000 (^re (concat "^" re))
8001 (start-level (and kill
8002 (string-match
8003 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8004 kill)
8005 (- (match-end 2) (match-beginning 2) 1)))
8006 (start (1+ (or (match-beginning 2) -1))))
8007 (if (not start-level)
8008 (progn
8009 nil) ;; does not even start with a heading
8010 (catch 'exit
8011 (while (setq start (string-match ^re kill (1+ start)))
8012 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8013 (throw 'exit nil)))
8014 t))))
8016 (defvar org-markers-to-move nil
8017 "Markers that should be moved with a cut-and-paste operation.
8018 Those markers are stored together with their positions relative to
8019 the start of the region.")
8021 (defun org-save-markers-in-region (beg end)
8022 "Check markers in region.
8023 If these markers are between BEG and END, record their position relative
8024 to BEG, so that after moving the block of text, we can put the markers back
8025 into place.
8026 This function gets called just before an entry or tree gets cut from the
8027 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8028 called immediately, to move the markers with the entries."
8029 (setq org-markers-to-move nil)
8030 (when (featurep 'org-clock)
8031 (org-clock-save-markers-for-cut-and-paste beg end))
8032 (when (featurep 'org-agenda)
8033 (org-agenda-save-markers-for-cut-and-paste beg end)))
8035 (defun org-check-and-save-marker (marker beg end)
8036 "Check if MARKER is between BEG and END.
8037 If yes, remember the marker and the distance to BEG."
8038 (when (and (marker-buffer marker)
8039 (equal (marker-buffer marker) (current-buffer)))
8040 (if (and (>= marker beg) (< marker end))
8041 (push (cons marker (- marker beg)) org-markers-to-move))))
8043 (defun org-reinstall-markers-in-region (beg)
8044 "Move all remembered markers to their position relative to BEG."
8045 (mapc (lambda (x)
8046 (move-marker (car x) (+ beg (cdr x))))
8047 org-markers-to-move)
8048 (setq org-markers-to-move nil))
8050 (defun org-narrow-to-subtree ()
8051 "Narrow buffer to the current subtree."
8052 (interactive)
8053 (save-excursion
8054 (save-match-data
8055 (org-with-limited-levels
8056 (narrow-to-region
8057 (progn (org-back-to-heading t) (point))
8058 (progn (org-end-of-subtree t t)
8059 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8060 (point)))))))
8062 (defun org-narrow-to-block ()
8063 "Narrow buffer to the current block."
8064 (interactive)
8065 (let* ((case-fold-search t)
8066 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8067 "^[ \t]*#\\+end_.*")))
8068 (if blockp
8069 (narrow-to-region (car blockp) (cdr blockp))
8070 (error "Not in a block"))))
8072 (eval-when-compile
8073 (defvar org-property-drawer-re))
8075 (defvar org-property-start-re) ;; defined below
8076 (defun org-clone-subtree-with-time-shift (n &optional shift)
8077 "Clone the task (subtree) at point N times.
8078 The clones will be inserted as siblings.
8080 In interactive use, the user will be prompted for the number of
8081 clones to be produced, and for a time SHIFT, which may be a
8082 repeater as used in time stamps, for example `+3d'.
8084 When a valid repeater is given and the entry contains any time
8085 stamps, the clones will become a sequence in time, with time
8086 stamps in the subtree shifted for each clone produced. If SHIFT
8087 is nil or the empty string, time stamps will be left alone. The
8088 ID property of the original subtree is removed.
8090 If the original subtree did contain time stamps with a repeater,
8091 the following will happen:
8092 - the repeater will be removed in each clone
8093 - an additional clone will be produced, with the current, unshifted
8094 date(s) in the entry.
8095 - the original entry will be placed *after* all the clones, with
8096 repeater intact.
8097 - the start days in the repeater in the original entry will be shifted
8098 to past the last clone.
8099 In this way you can spell out a number of instances of a repeating task,
8100 and still retain the repeater to cover future instances of the task."
8101 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8102 (let (beg end template task idprop
8103 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8104 (drawer-re org-drawer-regexp))
8105 (if (not (and (integerp n) (> n 0)))
8106 (error "Invalid number of replications %s" n))
8107 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8108 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8109 shift)))
8110 (error "Invalid shift specification %s" shift))
8111 (when doshift
8112 (setq shift-n (string-to-number (match-string 1 shift))
8113 shift-what (cdr (assoc (match-string 2 shift)
8114 '(("d" . day) ("w" . week)
8115 ("m" . month) ("y" . year))))))
8116 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8117 (setq nmin 1 nmax n)
8118 (org-back-to-heading t)
8119 (setq beg (point))
8120 (setq idprop (org-entry-get nil "ID"))
8121 (org-end-of-subtree t t)
8122 (or (bolp) (insert "\n"))
8123 (setq end (point))
8124 (setq template (buffer-substring beg end))
8125 (when (and doshift
8126 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8127 (delete-region beg end)
8128 (setq end beg)
8129 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8130 (goto-char end)
8131 (loop for n from nmin to nmax do
8132 ;; prepare clone
8133 (with-temp-buffer
8134 (insert template)
8135 (org-mode)
8136 (goto-char (point-min))
8137 (org-show-subtree)
8138 (and idprop (if org-clone-delete-id
8139 (org-entry-delete nil "ID")
8140 (org-id-get-create t)))
8141 (unless (= n 0)
8142 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8143 (kill-whole-line))
8144 (goto-char (point-min))
8145 (while (re-search-forward drawer-re nil t)
8146 (mapc (lambda (d)
8147 (org-remove-empty-drawer-at d (point))) org-drawers)))
8148 (goto-char (point-min))
8149 (when doshift
8150 (while (re-search-forward org-ts-regexp-both nil t)
8151 (org-timestamp-change (* n shift-n) shift-what))
8152 (unless (= n n-no-remove)
8153 (goto-char (point-min))
8154 (while (re-search-forward org-ts-regexp nil t)
8155 (save-excursion
8156 (goto-char (match-beginning 0))
8157 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8158 (delete-region (match-beginning 1) (match-end 1)))))))
8159 (setq task (buffer-string)))
8160 (insert task))
8161 (goto-char beg)))
8163 ;;; Outline Sorting
8165 (defun org-sort (with-case)
8166 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8167 Optional argument WITH-CASE means sort case-sensitively."
8168 (interactive "P")
8169 (cond
8170 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8171 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8173 (org-call-with-arg 'org-sort-entries with-case))))
8175 (defun org-sort-remove-invisible (s)
8176 (remove-text-properties 0 (length s) org-rm-props s)
8177 (while (string-match org-bracket-link-regexp s)
8178 (setq s (replace-match (if (match-end 2)
8179 (match-string 3 s)
8180 (match-string 1 s)) t t s)))
8183 (defvar org-priority-regexp) ; defined later in the file
8185 (defvar org-after-sorting-entries-or-items-hook nil
8186 "Hook that is run after a bunch of entries or items have been sorted.
8187 When children are sorted, the cursor is in the parent line when this
8188 hook gets called. When a region or a plain list is sorted, the cursor
8189 will be in the first entry of the sorted region/list.")
8191 (defun org-sort-entries
8192 (&optional with-case sorting-type getkey-func compare-func property)
8193 "Sort entries on a certain level of an outline tree.
8194 If there is an active region, the entries in the region are sorted.
8195 Else, if the cursor is before the first entry, sort the top-level items.
8196 Else, the children of the entry at point are sorted.
8198 Sorting can be alphabetically, numerically, by date/time as given by
8199 a time stamp, by a property or by priority.
8201 The command prompts for the sorting type unless it has been given to the
8202 function through the SORTING-TYPE argument, which needs to be a character,
8203 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8204 precise meaning of each character:
8206 n Numerically, by converting the beginning of the entry/item to a number.
8207 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8208 o By order of TODO keywords.
8209 t By date/time, either the first active time stamp in the entry, or, if
8210 none exist, by the first inactive one.
8211 s By the scheduled date/time.
8212 d By deadline date/time.
8213 c By creation time, which is assumed to be the first inactive time stamp
8214 at the beginning of a line.
8215 p By priority according to the cookie.
8216 r By the value of a property.
8218 Capital letters will reverse the sort order.
8220 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8221 called with point at the beginning of the record. It must return either
8222 a string or a number that should serve as the sorting key for that record.
8224 Comparing entries ignores case by default. However, with an optional argument
8225 WITH-CASE, the sorting considers case as well."
8226 (interactive "P")
8227 (let ((case-func (if with-case 'identity 'downcase))
8228 (cmstr
8229 ;; The clock marker is lost when using `sort-subr', let's
8230 ;; store the clocking string.
8231 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8232 (save-excursion
8233 (goto-char org-clock-marker)
8234 (looking-back "^.*") (match-string-no-properties 0))))
8235 start beg end stars re re2
8236 txt what tmp)
8237 ;; Find beginning and end of region to sort
8238 (cond
8239 ((org-region-active-p)
8240 ;; we will sort the region
8241 (setq end (region-end)
8242 what "region")
8243 (goto-char (region-beginning))
8244 (if (not (org-at-heading-p)) (outline-next-heading))
8245 (setq start (point)))
8246 ((or (org-at-heading-p)
8247 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8248 ;; we will sort the children of the current headline
8249 (org-back-to-heading)
8250 (setq start (point)
8251 end (progn (org-end-of-subtree t t)
8252 (or (bolp) (insert "\n"))
8253 (org-back-over-empty-lines)
8254 (point))
8255 what "children")
8256 (goto-char start)
8257 (show-subtree)
8258 (outline-next-heading))
8260 ;; we will sort the top-level entries in this file
8261 (goto-char (point-min))
8262 (or (org-at-heading-p) (outline-next-heading))
8263 (setq start (point))
8264 (goto-char (point-max))
8265 (beginning-of-line 1)
8266 (when (looking-at ".*?\\S-")
8267 ;; File ends in a non-white line
8268 (end-of-line 1)
8269 (insert "\n"))
8270 (setq end (point-max))
8271 (setq what "top-level")
8272 (goto-char start)
8273 (show-all)))
8275 (setq beg (point))
8276 (if (>= beg end) (error "Nothing to sort"))
8278 (looking-at "\\(\\*+\\)")
8279 (setq stars (match-string 1)
8280 re (concat "^" (regexp-quote stars) " +")
8281 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8282 txt (buffer-substring beg end))
8283 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8284 (if (and (not (equal stars "*")) (string-match re2 txt))
8285 (error "Region to sort contains a level above the first entry"))
8287 (unless sorting-type
8288 (message
8289 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8290 [t]ime [s]cheduled [d]eadline [c]reated
8291 A/N/P/R/O/F/T/S/D/C means reversed:"
8292 what)
8293 (setq sorting-type (read-char-exclusive))
8295 (unless getkey-func
8296 (and (= (downcase sorting-type) ?f)
8297 (setq getkey-func
8298 (org-icompleting-read "Sort using function: "
8299 obarray 'fboundp t nil nil))
8300 (setq getkey-func (intern getkey-func))))
8302 (and (= (downcase sorting-type) ?r)
8303 (not property)
8304 (setq property
8305 (org-icompleting-read "Property: "
8306 (mapcar 'list (org-buffer-property-keys t))
8307 nil t))))
8309 (message "Sorting entries...")
8311 (save-restriction
8312 (narrow-to-region start end)
8313 (let ((dcst (downcase sorting-type))
8314 (case-fold-search nil)
8315 (now (current-time)))
8316 (sort-subr
8317 (/= dcst sorting-type)
8318 ;; This function moves to the beginning character of the "record" to
8319 ;; be sorted.
8320 (lambda nil
8321 (if (re-search-forward re nil t)
8322 (goto-char (match-beginning 0))
8323 (goto-char (point-max))))
8324 ;; This function moves to the last character of the "record" being
8325 ;; sorted.
8326 (lambda nil
8327 (save-match-data
8328 (condition-case nil
8329 (outline-forward-same-level 1)
8330 (error
8331 (goto-char (point-max))))))
8332 ;; This function returns the value that gets sorted against.
8333 (lambda nil
8334 (cond
8335 ((= dcst ?n)
8336 (if (looking-at org-complex-heading-regexp)
8337 (string-to-number (match-string 4))
8338 nil))
8339 ((= dcst ?a)
8340 (if (looking-at org-complex-heading-regexp)
8341 (funcall case-func (match-string 4))
8342 nil))
8343 ((= dcst ?t)
8344 (let ((end (save-excursion (outline-next-heading) (point))))
8345 (if (or (re-search-forward org-ts-regexp end t)
8346 (re-search-forward org-ts-regexp-both end t))
8347 (org-time-string-to-seconds (match-string 0))
8348 (org-float-time now))))
8349 ((= dcst ?c)
8350 (let ((end (save-excursion (outline-next-heading) (point))))
8351 (if (re-search-forward
8352 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8353 end t)
8354 (org-time-string-to-seconds (match-string 0))
8355 (org-float-time now))))
8356 ((= dcst ?s)
8357 (let ((end (save-excursion (outline-next-heading) (point))))
8358 (if (re-search-forward org-scheduled-time-regexp end t)
8359 (org-time-string-to-seconds (match-string 1))
8360 (org-float-time now))))
8361 ((= dcst ?d)
8362 (let ((end (save-excursion (outline-next-heading) (point))))
8363 (if (re-search-forward org-deadline-time-regexp end t)
8364 (org-time-string-to-seconds (match-string 1))
8365 (org-float-time now))))
8366 ((= dcst ?p)
8367 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8368 (string-to-char (match-string 2))
8369 org-default-priority))
8370 ((= dcst ?r)
8371 (or (org-entry-get nil property) ""))
8372 ((= dcst ?o)
8373 (if (looking-at org-complex-heading-regexp)
8374 (- 9999 (length (member (match-string 2)
8375 org-todo-keywords-1)))))
8376 ((= dcst ?f)
8377 (if getkey-func
8378 (progn
8379 (setq tmp (funcall getkey-func))
8380 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8381 tmp)
8382 (error "Invalid key function `%s'" getkey-func)))
8383 (t (error "Invalid sorting type `%c'" sorting-type))))
8385 (cond
8386 ((= dcst ?a) 'string<)
8387 ((= dcst ?f) compare-func)
8388 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8389 (run-hooks 'org-after-sorting-entries-or-items-hook)
8390 ;; Reset the clock marker if needed
8391 (when cmstr
8392 (save-excursion
8393 (goto-char start)
8394 (search-forward cmstr nil t)
8395 (move-marker org-clock-marker (point))))
8396 (message "Sorting entries...done")))
8398 (defun org-do-sort (table what &optional with-case sorting-type)
8399 "Sort TABLE of WHAT according to SORTING-TYPE.
8400 The user will be prompted for the SORTING-TYPE if the call to this
8401 function does not specify it. WHAT is only for the prompt, to indicate
8402 what is being sorted. The sorting key will be extracted from
8403 the car of the elements of the table.
8404 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8405 (unless sorting-type
8406 (message
8407 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8408 what)
8409 (setq sorting-type (read-char-exclusive)))
8410 (let ((dcst (downcase sorting-type))
8411 extractfun comparefun)
8412 ;; Define the appropriate functions
8413 (cond
8414 ((= dcst ?n)
8415 (setq extractfun 'string-to-number
8416 comparefun (if (= dcst sorting-type) '< '>)))
8417 ((= dcst ?a)
8418 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8419 (lambda(x) (downcase (org-sort-remove-invisible x))))
8420 comparefun (if (= dcst sorting-type)
8421 'string<
8422 (lambda (a b) (and (not (string< a b))
8423 (not (string= a b)))))))
8424 ((= dcst ?t)
8425 (setq extractfun
8426 (lambda (x)
8427 (if (or (string-match org-ts-regexp x)
8428 (string-match org-ts-regexp-both x))
8429 (org-float-time
8430 (org-time-string-to-time (match-string 0 x)))
8432 comparefun (if (= dcst sorting-type) '< '>)))
8433 (t (error "Invalid sorting type `%c'" sorting-type)))
8435 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8436 table)
8437 (lambda (a b) (funcall comparefun (car a) (car b))))))
8440 ;;; The orgstruct minor mode
8442 ;; Define a minor mode which can be used in other modes in order to
8443 ;; integrate the org-mode structure editing commands.
8445 ;; This is really a hack, because the org-mode structure commands use
8446 ;; keys which normally belong to the major mode. Here is how it
8447 ;; works: The minor mode defines all the keys necessary to operate the
8448 ;; structure commands, but wraps the commands into a function which
8449 ;; tests if the cursor is currently at a headline or a plain list
8450 ;; item. If that is the case, the structure command is used,
8451 ;; temporarily setting many Org-mode variables like regular
8452 ;; expressions for filling etc. However, when any of those keys is
8453 ;; used at a different location, function uses `key-binding' to look
8454 ;; up if the key has an associated command in another currently active
8455 ;; keymap (minor modes, major mode, global), and executes that
8456 ;; command. There might be problems if any of the keys is otherwise
8457 ;; used as a prefix key.
8459 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8460 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8461 ;; addresses this by checking explicitly for both bindings.
8463 (defvar orgstruct-mode-map (make-sparse-keymap)
8464 "Keymap for the minor `orgstruct-mode'.")
8466 (defvar org-local-vars nil
8467 "List of local variables, for use by `orgstruct-mode'.")
8469 ;;;###autoload
8470 (define-minor-mode orgstruct-mode
8471 "Toggle the minor mode `orgstruct-mode'.
8472 This mode is for using Org-mode structure commands in other
8473 modes. The following keys behave as if Org-mode were active, if
8474 the cursor is on a headline, or on a plain list item (both as
8475 defined by Org-mode).
8477 M-up Move entry/item up
8478 M-down Move entry/item down
8479 M-left Promote
8480 M-right Demote
8481 M-S-up Move entry/item up
8482 M-S-down Move entry/item down
8483 M-S-left Promote subtree
8484 M-S-right Demote subtree
8485 M-q Fill paragraph and items like in Org-mode
8486 C-c ^ Sort entries
8487 C-c - Cycle list bullet
8488 TAB Cycle item visibility
8489 M-RET Insert new heading/item
8490 S-M-RET Insert new TODO heading / Checkbox item
8491 C-c C-c Set tags / toggle checkbox"
8492 nil " OrgStruct" nil
8493 (org-load-modules-maybe)
8494 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8496 ;;;###autoload
8497 (defun turn-on-orgstruct ()
8498 "Unconditionally turn on `orgstruct-mode'."
8499 (orgstruct-mode 1))
8501 (defvar org-fb-vars nil)
8502 (make-variable-buffer-local 'org-fb-vars)
8503 (defun orgstruct++-mode (&optional arg)
8504 "Toggle `orgstruct-mode', the enhanced version of it.
8505 In addition to setting orgstruct-mode, this also exports all
8506 indentation and autofilling variables from org-mode into the
8507 buffer. It will also recognize item context in multiline items."
8508 (interactive "P")
8509 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8510 (if (< arg 1)
8511 (progn (orgstruct-mode -1)
8512 (mapc (lambda(v)
8513 (org-set-local (car v)
8514 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8515 org-fb-vars))
8516 (orgstruct-mode 1)
8517 (setq org-fb-vars nil)
8518 (let (var val)
8519 (mapc
8520 (lambda (x)
8521 (when (string-match
8522 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8523 (symbol-name (car x)))
8524 (setq var (car x) val (nth 1 x))
8525 (push (list var `(quote ,(eval var))) org-fb-vars)
8526 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8527 org-local-vars)
8528 (org-set-local 'orgstruct-is-++ t))))
8530 (defvar orgstruct-is-++ nil
8531 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8532 (make-variable-buffer-local 'orgstruct-is-++)
8534 ;;;###autoload
8535 (defun turn-on-orgstruct++ ()
8536 "Unconditionally turn on `orgstruct++-mode'."
8537 (orgstruct++-mode 1))
8539 (defun orgstruct-error ()
8540 "Error when there is no default binding for a structure key."
8541 (interactive)
8542 (error "This key has no function outside structure elements"))
8544 (defun orgstruct-setup ()
8545 "Setup orgstruct keymaps."
8546 (let ((nfunc 0)
8547 (bindings
8548 (list
8549 '([(meta up)] org-metaup)
8550 '([(meta down)] org-metadown)
8551 '([(meta left)] org-metaleft)
8552 '([(meta right)] org-metaright)
8553 '([(meta shift up)] org-shiftmetaup)
8554 '([(meta shift down)] org-shiftmetadown)
8555 '([(meta shift left)] org-shiftmetaleft)
8556 '([(meta shift right)] org-shiftmetaright)
8557 '([?\e (up)] org-metaup)
8558 '([?\e (down)] org-metadown)
8559 '([?\e (left)] org-metaleft)
8560 '([?\e (right)] org-metaright)
8561 '([?\e (shift up)] org-shiftmetaup)
8562 '([?\e (shift down)] org-shiftmetadown)
8563 '([?\e (shift left)] org-shiftmetaleft)
8564 '([?\e (shift right)] org-shiftmetaright)
8565 '([(shift up)] org-shiftup)
8566 '([(shift down)] org-shiftdown)
8567 '([(shift left)] org-shiftleft)
8568 '([(shift right)] org-shiftright)
8569 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8570 '("\M-q" fill-paragraph)
8571 '("\C-c^" org-sort)
8572 '("\C-c-" org-cycle-list-bullet)))
8573 elt key fun cmd)
8574 (while (setq elt (pop bindings))
8575 (setq nfunc (1+ nfunc))
8576 (setq key (org-key (car elt))
8577 fun (nth 1 elt)
8578 cmd (orgstruct-make-binding fun nfunc key))
8579 (org-defkey orgstruct-mode-map key cmd))
8581 ;; Prevent an error for users who forgot to make autoloads
8582 (require 'org-element)
8584 ;; Special treatment needed for TAB and RET
8585 (org-defkey orgstruct-mode-map [(tab)]
8586 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8587 (org-defkey orgstruct-mode-map "\C-i"
8588 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8590 (org-defkey orgstruct-mode-map "\M-\C-m"
8591 (orgstruct-make-binding 'org-insert-heading 105
8592 "\M-\C-m" [(meta return)]))
8593 (org-defkey orgstruct-mode-map [(meta return)]
8594 (orgstruct-make-binding 'org-insert-heading 106
8595 [(meta return)] "\M-\C-m"))
8597 (org-defkey orgstruct-mode-map [(shift meta return)]
8598 (orgstruct-make-binding 'org-insert-todo-heading 107
8599 [(meta return)] "\M-\C-m"))
8601 (org-defkey orgstruct-mode-map "\e\C-m"
8602 (orgstruct-make-binding 'org-insert-heading 108
8603 "\e\C-m" [?\e (return)]))
8604 (org-defkey orgstruct-mode-map [?\e (return)]
8605 (orgstruct-make-binding 'org-insert-heading 109
8606 [?\e (return)] "\e\C-m"))
8607 (org-defkey orgstruct-mode-map [?\e (shift return)]
8608 (orgstruct-make-binding 'org-insert-todo-heading 110
8609 [?\e (return)] "\e\C-m"))
8611 (unless org-local-vars
8612 (setq org-local-vars (org-get-local-variables)))
8616 (defun orgstruct-make-binding (fun n &rest keys)
8617 "Create a function for binding in the structure minor mode.
8618 FUN is the command to call inside a table. N is used to create a unique
8619 command name. KEYS are keys that should be checked in for a command
8620 to execute outside of tables."
8621 (eval
8622 (list 'defun
8623 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8624 '(arg)
8625 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8626 "Outside of structure, run the binding of `"
8627 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8628 "'.")
8629 '(interactive "p")
8630 (list 'if
8631 `(org-context-p 'headline 'item
8632 (and orgstruct-is-++
8633 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8634 'item-body))
8635 (list 'org-run-like-in-org-mode (list 'quote fun))
8636 (list 'let '(orgstruct-mode)
8637 (list 'call-interactively
8638 (append '(or)
8639 (mapcar (lambda (k)
8640 (list 'key-binding k))
8641 keys)
8642 '('orgstruct-error))))))))
8644 (defun org-contextualize-keys (alist contexts)
8645 "Return valid elements in ALIST depending on CONTEXTS.
8647 `org-agenda-custom-commands' or `org-capture-templates' are the
8648 values used for ALIST, and `org-agenda-custom-commands-contexts'
8649 or `org-capture-templates-contexts' are the associated contexts
8650 definitions."
8651 (let ((contexts
8652 ;; normalize contexts
8653 (mapcar
8654 (lambda(c) (cond ((listp (cadr c))
8655 (list (car c) (car c) (cadr c)))
8656 ((string= "" (cadr c))
8657 (list (car c) (car c) (caddr c)))
8658 (t c))) contexts))
8659 (a alist) c r s)
8660 ;; loop over all commands or templates
8661 (while (setq c (pop a))
8662 (let (vrules repl)
8663 (cond
8664 ((not (assoc (car c) contexts))
8665 (push c r))
8666 ((and (assoc (car c) contexts)
8667 (setq vrules (org-contextualize-validate-key
8668 (car c) contexts)))
8669 (mapc (lambda (vr)
8670 (when (not (equal (car vr) (cadr vr)))
8671 (setq repl vr))) vrules)
8672 (if (not repl) (push c r)
8673 (push (cadr repl) s)
8674 (push
8675 (cons (car c)
8676 (cdr (or (assoc (cadr repl) alist)
8677 (error "Undefined key `%s' as contextual replacement for `%s'"
8678 (cadr repl) (car c)))))
8679 r))))))
8680 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8681 (delq
8683 (delete-dups
8684 (mapcar (lambda (x)
8685 (let ((tpl (car x)))
8686 (when (not (delq
8688 (mapcar (lambda(y)
8689 (equal y tpl)) s))) x)))
8690 (reverse r))))))
8692 (defun org-contextualize-validate-key (key contexts)
8693 "Check CONTEXTS for agenda or capture KEY."
8694 (let (r rr res)
8695 (while (setq r (pop contexts))
8696 (mapc
8697 (lambda (rr)
8698 (when
8699 (and (equal key (car r))
8700 (if (functionp rr) (funcall rr)
8701 (or (and (eq (car rr) 'in-file)
8702 (buffer-file-name)
8703 (string-match (cdr rr) (buffer-file-name)))
8704 (and (eq (car rr) 'in-mode)
8705 (string-match (cdr rr) (symbol-name major-mode)))
8706 (when (and (eq (car rr) 'not-in-file)
8707 (buffer-file-name))
8708 (not (string-match (cdr rr) (buffer-file-name))))
8709 (when (eq (car rr) 'not-in-mode)
8710 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8711 (push r res)))
8712 (car (last r))))
8713 (delete-dups (delq nil res))))
8715 (defun org-context-p (&rest contexts)
8716 "Check if local context is any of CONTEXTS.
8717 Possible values in the list of contexts are `table', `headline', and `item'."
8718 (let ((pos (point)))
8719 (goto-char (point-at-bol))
8720 (prog1 (or (and (memq 'table contexts)
8721 (looking-at "[ \t]*|"))
8722 (and (memq 'headline contexts)
8723 (looking-at org-outline-regexp))
8724 (and (memq 'item contexts)
8725 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8726 (and (memq 'item-body contexts)
8727 (org-in-item-p)))
8728 (goto-char pos))))
8730 (defun org-get-local-variables ()
8731 "Return a list of all local variables in an Org mode buffer."
8732 (let (varlist)
8733 (with-current-buffer (get-buffer-create "*Org tmp*")
8734 (erase-buffer)
8735 (org-mode)
8736 (setq varlist (buffer-local-variables)))
8737 (kill-buffer "*Org tmp*")
8738 (delq nil
8739 (mapcar
8740 (lambda (x)
8741 (setq x
8742 (if (symbolp x)
8743 (list x)
8744 (list (car x) (list 'quote (cdr x)))))
8745 (if (string-match
8746 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8747 (symbol-name (car x)))
8748 x nil))
8749 varlist))))
8751 (defun org-clone-local-variables (from-buffer &optional regexp)
8752 "Clone local variables from FROM-BUFFER.
8753 Optional argument REGEXP selects variables to clone."
8754 (mapc
8755 (lambda (pair)
8756 (and (symbolp (car pair))
8757 (or (null regexp)
8758 (string-match regexp (symbol-name (car pair))))
8759 (set (make-local-variable (car pair))
8760 (cdr pair))))
8761 (buffer-local-variables from-buffer)))
8763 ;;;###autoload
8764 (defun org-run-like-in-org-mode (cmd)
8765 "Run a command, pretending that the current buffer is in Org-mode.
8766 This will temporarily bind local variables that are typically bound in
8767 Org-mode to the values they have in Org-mode, and then interactively
8768 call CMD."
8769 (org-load-modules-maybe)
8770 (unless org-local-vars
8771 (setq org-local-vars (org-get-local-variables)))
8772 (eval (list 'let org-local-vars
8773 (list 'call-interactively (list 'quote cmd)))))
8775 ;;;; Archiving
8777 (defun org-get-category (&optional pos force-refresh)
8778 "Get the category applying to position POS."
8779 (save-match-data
8780 (if force-refresh (org-refresh-category-properties))
8781 (let ((pos (or pos (point))))
8782 (or (get-text-property pos 'org-category)
8783 (progn (org-refresh-category-properties)
8784 (get-text-property pos 'org-category))))))
8786 (defun org-refresh-category-properties ()
8787 "Refresh category text properties in the buffer."
8788 (let ((case-fold-search t)
8789 (inhibit-read-only t)
8790 (def-cat (cond
8791 ((null org-category)
8792 (if buffer-file-name
8793 (file-name-sans-extension
8794 (file-name-nondirectory buffer-file-name))
8795 "???"))
8796 ((symbolp org-category) (symbol-name org-category))
8797 (t org-category)))
8798 beg end cat pos optionp)
8799 (org-unmodified
8800 (save-excursion
8801 (save-restriction
8802 (widen)
8803 (goto-char (point-min))
8804 (put-text-property (point) (point-max) 'org-category def-cat)
8805 (while (re-search-forward
8806 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8807 (setq pos (match-end 0)
8808 optionp (equal (char-after (match-beginning 0)) ?#)
8809 cat (org-trim (match-string 2)))
8810 (if optionp
8811 (setq beg (point-at-bol) end (point-max))
8812 (org-back-to-heading t)
8813 (setq beg (point) end (org-end-of-subtree t t)))
8814 (put-text-property beg end 'org-category cat)
8815 (put-text-property beg end 'org-category-position beg)
8816 (goto-char pos)))))))
8819 ;;;; Link Stuff
8821 ;;; Link abbreviations
8823 (defun org-link-expand-abbrev (link)
8824 "Apply replacements as defined in `org-link-abbrev-alist'."
8825 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8826 (let* ((key (match-string 1 link))
8827 (as (or (assoc key org-link-abbrev-alist-local)
8828 (assoc key org-link-abbrev-alist)))
8829 (tag (and (match-end 2) (match-string 3 link)))
8830 rpl)
8831 (if (not as)
8832 link
8833 (setq rpl (cdr as))
8834 (cond
8835 ((symbolp rpl) (funcall rpl tag))
8836 ((string-match "%(\\([^)]+\\))" rpl)
8837 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8838 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8839 ((string-match "%h" rpl)
8840 (replace-match (url-hexify-string (or tag "")) t t rpl))
8841 (t (concat rpl tag)))))
8842 link))
8844 ;;; Storing and inserting links
8846 (defvar org-insert-link-history nil
8847 "Minibuffer history for links inserted with `org-insert-link'.")
8849 (defvar org-stored-links nil
8850 "Contains the links stored with `org-store-link'.")
8852 (defvar org-store-link-plist nil
8853 "Plist with info about the most recently link created with `org-store-link'.")
8855 (defvar org-link-protocols nil
8856 "Link protocols added to Org-mode using `org-add-link-type'.")
8858 (defvar org-store-link-functions nil
8859 "List of functions that are called to create and store a link.
8860 Each function will be called in turn until one returns a non-nil
8861 value. Each function should check if it is responsible for creating
8862 this link (for example by looking at the major mode).
8863 If not, it must exit and return nil.
8864 If yes, it should return a non-nil value after a calling
8865 `org-store-link-props' with a list of properties and values.
8866 Special properties are:
8868 :type The link prefix, like \"http\". This must be given.
8869 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8870 This is obligatory as well.
8871 :description Optional default description for the second pair
8872 of brackets in an Org-mode link. The user can still change
8873 this when inserting this link into an Org-mode buffer.
8875 In addition to these, any additional properties can be specified
8876 and then used in capture templates.")
8878 (defun org-add-link-type (type &optional follow export)
8879 "Add TYPE to the list of `org-link-types'.
8880 Re-compute all regular expressions depending on `org-link-types'
8882 FOLLOW and EXPORT are two functions.
8884 FOLLOW should take the link path as the single argument and do whatever
8885 is necessary to follow the link, for example find a file or display
8886 a mail message.
8888 EXPORT should format the link path for export to one of the export formats.
8889 It should be a function accepting three arguments:
8891 path the path of the link, the text after the prefix (like \"http:\")
8892 desc the description of the link, if any, or a description added by
8893 org-export-normalize-links if there is none
8894 format the export format, a symbol like `html' or `latex' or `ascii'..
8896 The function may use the FORMAT information to return different values
8897 depending on the format. The return value will be put literally into
8898 the exported file. If the return value is nil, this means Org should
8899 do what it normally does with links which do not have EXPORT defined.
8901 Org-mode has a built-in default for exporting links. If you are happy with
8902 this default, there is no need to define an export function for the link
8903 type. For a simple example of an export function, see `org-bbdb.el'."
8904 (add-to-list 'org-link-types type t)
8905 (org-make-link-regexps)
8906 (if (assoc type org-link-protocols)
8907 (setcdr (assoc type org-link-protocols) (list follow export))
8908 (push (list type follow export) org-link-protocols)))
8910 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8911 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8913 ;;;###autoload
8914 (defun org-store-link (arg)
8915 "\\<org-mode-map>Store an org-link to the current location.
8916 This link is added to `org-stored-links' and can later be inserted
8917 into an org-buffer with \\[org-insert-link].
8919 For some link types, a prefix arg is interpreted.
8920 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8921 For file links, arg negates `org-context-in-file-links'.
8923 A double prefix arg force skipping storing functions that are not
8924 part of Org's core."
8925 (interactive "P")
8926 (org-load-modules-maybe)
8927 (setq org-store-link-plist nil) ; reset
8928 (org-with-limited-levels
8929 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8930 (cond
8931 ((and (not (equal arg '(16)))
8932 (setq sfuns
8933 (delq
8934 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8935 org-store-link-functions))
8936 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8937 (or (and (cdr sfuns)
8938 (funcall (intern
8939 (completing-read "Which function for creating the link? "
8940 sfunsn t (car sfunsn)))))
8941 (funcall (caar sfuns)))
8942 (setq link (plist-get org-store-link-plist :link)
8943 desc (or (plist-get org-store-link-plist :description) link))))
8944 ((org-src-edit-buffer-p)
8945 (let (label gc)
8946 (while (or (not label)
8947 (save-excursion
8948 (save-restriction
8949 (widen)
8950 (goto-char (point-min))
8951 (re-search-forward
8952 (regexp-quote (format org-coderef-label-format label))
8953 nil t))))
8954 (when label (message "Label exists already") (sit-for 2))
8955 (setq label (read-string "Code line label: " label)))
8956 (end-of-line 1)
8957 (setq link (format org-coderef-label-format label))
8958 (setq gc (- 79 (length link)))
8959 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8960 (insert link)
8961 (setq link (concat "(" label ")") desc nil)))
8963 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8964 ;; We are in the agenda, link to referenced location
8965 (let ((m (or (get-text-property (point) 'org-hd-marker)
8966 (get-text-property (point) 'org-marker))))
8967 (when m
8968 (org-with-point-at m
8969 (setq agenda-link
8970 (if (org-called-interactively-p 'any)
8971 (call-interactively 'org-store-link)
8972 (org-store-link nil)))))))
8974 ((eq major-mode 'calendar-mode)
8975 (let ((cd (calendar-cursor-to-date)))
8976 (setq link
8977 (format-time-string
8978 (car org-time-stamp-formats)
8979 (apply 'encode-time
8980 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8981 nil nil nil))))
8982 (org-store-link-props :type "calendar" :date cd)))
8984 ((eq major-mode 'help-mode)
8985 (setq link (concat "help:" (save-excursion
8986 (goto-char (point-min))
8987 (looking-at "^[^ ]+")
8988 (match-string 0))))
8989 (org-store-link-props :type "help"))
8991 ((eq major-mode 'w3-mode)
8992 (setq cpltxt (if (and (buffer-name)
8993 (not (string-match "Untitled" (buffer-name))))
8994 (buffer-name)
8995 (url-view-url t))
8996 link (url-view-url t))
8997 (org-store-link-props :type "w3" :url (url-view-url t)))
8999 ((setq search (run-hook-with-args-until-success
9000 'org-create-file-search-functions))
9001 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9002 "::" search))
9003 (setq cpltxt (or description link)))
9005 ((eq major-mode 'image-mode)
9006 (setq cpltxt (concat "file:"
9007 (abbreviate-file-name buffer-file-name))
9008 link cpltxt)
9009 (org-store-link-props :type "image" :file buffer-file-name))
9011 ((eq major-mode 'dired-mode)
9012 ;; link to the file in the current line
9013 (let ((file (dired-get-filename nil t)))
9014 (setq file (if file
9015 (abbreviate-file-name
9016 (expand-file-name (dired-get-filename nil t)))
9017 ;; otherwise, no file so use current directory.
9018 default-directory))
9019 (setq cpltxt (concat "file:" file)
9020 link cpltxt)))
9022 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9023 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9024 (cond
9025 ((org-in-regexp "<<\\(.*?\\)>>")
9026 (setq cpltxt
9027 (concat "file:"
9028 (abbreviate-file-name
9029 (buffer-file-name (buffer-base-buffer)))
9030 "::" (match-string 1))
9031 link cpltxt))
9032 ((and (featurep 'org-id)
9033 (or (eq org-id-link-to-org-use-id t)
9034 (and (org-called-interactively-p 'any)
9035 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9036 (and (eq org-id-link-to-org-use-id
9037 'create-if-interactive-and-no-custom-id)
9038 (not custom-id))))
9039 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9040 ;; We can make a link using the ID.
9041 (setq link (condition-case nil
9042 (prog1 (org-id-store-link)
9043 (setq desc (plist-get org-store-link-plist :description)))
9044 (error
9045 ;; probably before first headline, link to file only
9046 (concat "file:"
9047 (abbreviate-file-name
9048 (buffer-file-name (buffer-base-buffer))))))))
9050 ;; Just link to current headline
9051 (setq cpltxt (concat "file:"
9052 (abbreviate-file-name
9053 (buffer-file-name (buffer-base-buffer)))))
9054 ;; Add a context search string
9055 (when (org-xor org-context-in-file-links arg)
9056 (let* ((ee (org-element-at-point))
9057 (et (org-element-type ee))
9058 (ev (plist-get (cadr ee) :value)))
9059 (setq txt (cond
9060 ((org-at-heading-p) nil)
9061 ((eq et 'keyword) ev)
9062 ((org-region-active-p)
9063 (buffer-substring (region-beginning) (region-end)))))
9064 (when (or (null txt) (string-match "\\S-" txt))
9065 (setq cpltxt
9066 (concat cpltxt "::"
9067 (condition-case nil
9068 (org-make-org-heading-search-string txt)
9069 (error "")))
9070 desc (or (and (eq et 'keyword) ev)
9071 (nth 4 (ignore-errors (org-heading-components)))
9072 "NONE")))))
9073 (if (string-match "::\\'" cpltxt)
9074 (setq cpltxt (substring cpltxt 0 -2)))
9075 (setq link cpltxt))))
9077 ((buffer-file-name (buffer-base-buffer))
9078 ;; Just link to this file here.
9079 (setq cpltxt (concat "file:"
9080 (abbreviate-file-name
9081 (buffer-file-name (buffer-base-buffer)))))
9082 ;; Add a context string
9083 (when (org-xor org-context-in-file-links arg)
9084 (setq txt (if (org-region-active-p)
9085 (buffer-substring (region-beginning) (region-end))
9086 (buffer-substring (point-at-bol) (point-at-eol))))
9087 ;; Only use search option if there is some text.
9088 (when (string-match "\\S-" txt)
9089 (setq cpltxt
9090 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9091 desc "NONE")))
9092 (setq link cpltxt))
9094 ((org-called-interactively-p 'interactive)
9095 (user-error "No method for storing a link from this buffer"))
9097 (t (setq link nil)))
9099 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9100 (setq link (or link cpltxt)
9101 desc (or desc cpltxt))
9102 (cond ((equal desc "NONE") (setq desc nil))
9103 ((string-match org-bracket-link-regexp desc)
9104 (setq desc (replace-regexp-in-string
9105 org-bracket-link-regexp
9106 (concat "\\3" (if (equal (length (match-string 0 desc))
9107 (length desc)) "*" "")) desc))))
9109 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9110 (progn
9111 (setq org-stored-links
9112 (cons (list link desc) org-stored-links))
9113 (message "Stored: %s" (or desc link))
9114 (when custom-id
9115 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9116 "::#" custom-id))
9117 (setq org-stored-links
9118 (cons (list link desc) org-stored-links))))
9119 (or agenda-link (and link (org-make-link-string link desc)))))))
9121 (defun org-store-link-props (&rest plist)
9122 "Store link properties, extract names and addresses."
9123 (let (x adr)
9124 (when (setq x (plist-get plist :from))
9125 (setq adr (mail-extract-address-components x))
9126 (setq plist (plist-put plist :fromname (car adr)))
9127 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9128 (when (setq x (plist-get plist :to))
9129 (setq adr (mail-extract-address-components x))
9130 (setq plist (plist-put plist :toname (car adr)))
9131 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9132 (let ((from (plist-get plist :from))
9133 (to (plist-get plist :to)))
9134 (when (and from to org-from-is-user-regexp)
9135 (setq plist
9136 (plist-put plist :fromto
9137 (if (string-match org-from-is-user-regexp from)
9138 (concat "to %t")
9139 (concat "from %f"))))))
9140 (setq org-store-link-plist plist))
9142 (defun org-add-link-props (&rest plist)
9143 "Add these properties to the link property list."
9144 (let (key value)
9145 (while plist
9146 (setq key (pop plist) value (pop plist))
9147 (setq org-store-link-plist
9148 (plist-put org-store-link-plist key value)))))
9150 (defun org-email-link-description (&optional fmt)
9151 "Return the description part of an email link.
9152 This takes information from `org-store-link-plist' and formats it
9153 according to FMT (default from `org-email-link-description-format')."
9154 (setq fmt (or fmt org-email-link-description-format))
9155 (let* ((p org-store-link-plist)
9156 (to (plist-get p :toaddress))
9157 (from (plist-get p :fromaddress))
9158 (table
9159 (list
9160 (cons "%c" (plist-get p :fromto))
9161 (cons "%F" (plist-get p :from))
9162 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9163 (cons "%T" (plist-get p :to))
9164 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9165 (cons "%s" (plist-get p :subject))
9166 (cons "%d" (plist-get p :date))
9167 (cons "%m" (plist-get p :message-id)))))
9168 (when (string-match "%c" fmt)
9169 ;; Check if the user wrote this message
9170 (if (and org-from-is-user-regexp from to
9171 (save-match-data (string-match org-from-is-user-regexp from)))
9172 (setq fmt (replace-match "to %t" t t fmt))
9173 (setq fmt (replace-match "from %f" t t fmt))))
9174 (org-replace-escapes fmt table)))
9176 (defun org-make-org-heading-search-string (&optional string)
9177 "Make search string for the current headline or STRING."
9178 (let ((s (or string
9179 (and (derived-mode-p 'org-mode)
9180 (save-excursion
9181 (org-back-to-heading t)
9182 (plist-get (cadr (org-element-at-point))
9183 :raw-value)))))
9184 (lines org-context-in-file-links))
9185 (or string (setq s (concat "*" s))) ; Add * for headlines
9186 (when (and string (integerp lines) (> lines 0))
9187 (let ((slines (org-split-string s "\n")))
9188 (when (< lines (length slines))
9189 (setq s (mapconcat
9190 'identity
9191 (reverse (nthcdr (- (length slines) lines)
9192 (reverse slines))) "\n")))))
9193 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9195 (defun org-make-link-string (link &optional description)
9196 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9197 (unless (string-match "\\S-" link)
9198 (error "Empty link"))
9199 (when (and description
9200 (stringp description)
9201 (not (string-match "\\S-" description)))
9202 (setq description nil))
9203 (when (stringp description)
9204 ;; Remove brackets from the description, they are fatal.
9205 (while (string-match "\\[" description)
9206 (setq description (replace-match "{" t t description)))
9207 (while (string-match "\\]" description)
9208 (setq description (replace-match "}" t t description))))
9209 (when (equal link description)
9210 ;; No description needed, it is identical
9211 (setq description nil))
9212 (when (and (not description)
9213 (not (string-match (org-image-file-name-regexp) link))
9214 (not (equal link (org-link-escape link))))
9215 (setq description (org-extract-attributes link)))
9216 (setq link
9217 (cond ((string-match (org-image-file-name-regexp) link) link)
9218 ((string-match org-link-types-re link)
9219 (concat (match-string 1 link)
9220 (org-link-escape (substring link (match-end 1)))))
9221 (t (org-link-escape link))))
9222 (concat "[[" link "]"
9223 (if description (concat "[" description "]") "")
9224 "]"))
9226 (defconst org-link-escape-chars
9227 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9228 "List of characters that should be escaped in link.
9229 This is the list that is used for internal purposes.")
9231 (defconst org-link-escape-chars-browser
9232 '(?\ )
9233 "List of escapes for characters that are problematic in links.
9234 This is the list that is used before handing over to the browser.")
9236 (defun org-link-escape (text &optional table merge)
9237 "Return percent escaped representation of TEXT.
9238 TEXT is a string with the text to escape.
9239 Optional argument TABLE is a list with characters that should be
9240 escaped. When nil, `org-link-escape-chars' is used.
9241 If optional argument MERGE is set, merge TABLE into
9242 `org-link-escape-chars'."
9243 (cond
9244 ((and table merge)
9245 (mapc (lambda (defchr)
9246 (unless (member defchr table)
9247 (setq table (cons defchr table)))) org-link-escape-chars))
9248 ((null table)
9249 (setq table org-link-escape-chars)))
9250 (mapconcat
9251 (lambda (char)
9252 (if (or (member char table)
9253 (and (or (< char 32) (= char 37) (> char 126))
9254 org-url-hexify-p))
9255 (mapconcat (lambda (sequence-element)
9256 (format "%%%.2X" sequence-element))
9257 (or (encode-coding-char char 'utf-8)
9258 (error "Unable to percent escape character: %s"
9259 (char-to-string char))) "")
9260 (char-to-string char))) text ""))
9262 (defun org-link-unescape (str)
9263 "Unhex hexified Unicode strings as returned from the JavaScript function
9264 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9265 (unless (and (null str) (string= "" str))
9266 (let ((pos 0) (case-fold-search t) unhexed)
9267 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9268 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9269 (setq str (replace-match unhexed t t str))
9270 (setq pos (+ pos (length unhexed))))))
9271 str)
9273 (defun org-link-unescape-compound (hex)
9274 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9275 Note: this function also decodes single byte encodings like
9276 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9277 (save-match-data
9278 (let* ((bytes (cdr (split-string hex "%")))
9279 (ret "")
9280 (eat 0)
9281 (sum 0))
9282 (while bytes
9283 (let* ((val (string-to-number (pop bytes) 16))
9284 (shift-xor
9285 (if (= 0 eat)
9286 (cond
9287 ((>= val 252) (cons 6 252))
9288 ((>= val 248) (cons 5 248))
9289 ((>= val 240) (cons 4 240))
9290 ((>= val 224) (cons 3 224))
9291 ((>= val 192) (cons 2 192))
9292 (t (cons 0 0)))
9293 (cons 6 128))))
9294 (if (>= val 192) (setq eat (car shift-xor)))
9295 (setq val (logxor val (cdr shift-xor)))
9296 (setq sum (+ (lsh sum (car shift-xor)) val))
9297 (if (> eat 0) (setq eat (- eat 1)))
9298 (cond
9299 ((= 0 eat) ;multi byte
9300 (setq ret (concat ret (org-char-to-string sum)))
9301 (setq sum 0))
9302 ((not bytes) ; single byte(s)
9303 (setq ret (org-link-unescape-single-byte-sequence hex))))
9304 )) ;; end (while bytes
9305 ret )))
9307 (defun org-link-unescape-single-byte-sequence (hex)
9308 "Unhexify hex-encoded single byte character sequences."
9309 (mapconcat (lambda (byte)
9310 (char-to-string (string-to-number byte 16)))
9311 (cdr (split-string hex "%")) ""))
9313 (defun org-xor (a b)
9314 "Exclusive or."
9315 (if a (not b) b))
9317 (defun org-fixup-message-id-for-http (s)
9318 "Replace special characters in a message id, so it can be used in an http query."
9319 (when (string-match "%" s)
9320 (setq s (mapconcat (lambda (c)
9321 (if (eq c ?%)
9322 "%25"
9323 (char-to-string c)))
9324 s "")))
9325 (while (string-match "<" s)
9326 (setq s (replace-match "%3C" t t s)))
9327 (while (string-match ">" s)
9328 (setq s (replace-match "%3E" t t s)))
9329 (while (string-match "@" s)
9330 (setq s (replace-match "%40" t t s)))
9333 (defun org-link-prettify (link)
9334 "Return a human-readable representation of LINK.
9335 The car of LINK must be a raw link the cdr of LINK must be either
9336 a link description or nil."
9337 (let ((desc (or (cadr link) "<no description>")))
9338 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9339 "<" (car link) ">")))
9341 ;;;###autoload
9342 (defun org-insert-link-global ()
9343 "Insert a link like Org-mode does.
9344 This command can be called in any mode to insert a link in Org-mode syntax."
9345 (interactive)
9346 (org-load-modules-maybe)
9347 (org-run-like-in-org-mode 'org-insert-link))
9349 (defun org-insert-all-links (&optional keep)
9350 "Insert all links in `org-stored-links'."
9351 (interactive "P")
9352 (let ((links (copy-sequence org-stored-links)) l)
9353 (while (setq l (if keep (pop links) (pop org-stored-links)))
9354 (insert "- ")
9355 (org-insert-link nil (car l) (cadr l))
9356 (insert "\n"))))
9358 (defun org-link-fontify-links-to-this-file ()
9359 "Fontify links to the current file in `org-stored-links'."
9360 (let ((f (buffer-file-name)) a b)
9361 (setq a (mapcar (lambda(l)
9362 (let ((ll (car l)))
9363 (when (and (string-match "^file:\\(.+\\)::" ll)
9364 (equal f (expand-file-name (match-string 1 ll))))
9365 ll)))
9366 org-stored-links))
9367 (when (featurep 'org-id)
9368 (setq b (mapcar (lambda(l)
9369 (let ((ll (car l)))
9370 (when (and (string-match "^id:\\(.+\\)$" ll)
9371 (equal f (expand-file-name
9372 (or (org-id-find-id-file
9373 (match-string 1 ll)) ""))))
9374 ll)))
9375 org-stored-links)))
9376 (mapcar (lambda(l)
9377 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9378 (delq nil (append a b)))))
9380 (defvar org-link-links-in-this-file nil)
9381 (defun org-insert-link (&optional complete-file link-location default-description)
9382 "Insert a link. At the prompt, enter the link.
9384 Completion can be used to insert any of the link protocol prefixes like
9385 http or ftp in use.
9387 The history can be used to select a link previously stored with
9388 `org-store-link'. When the empty string is entered (i.e. if you just
9389 press RET at the prompt), the link defaults to the most recently
9390 stored link. As SPC triggers completion in the minibuffer, you need to
9391 use M-SPC or C-q SPC to force the insertion of a space character.
9393 You will also be prompted for a description, and if one is given, it will
9394 be displayed in the buffer instead of the link.
9396 If there is already a link at point, this command will allow you to edit link
9397 and description parts.
9399 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9400 be selected using completion. The path to the file will be relative to the
9401 current directory if the file is in the current directory or a subdirectory.
9402 Otherwise, the link will be the absolute path as completed in the minibuffer
9403 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9404 option `org-link-file-path-type'.
9406 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9407 the current directory or below.
9409 With three \\[universal-argument] prefixes, negate the meaning of
9410 `org-keep-stored-link-after-insertion'.
9412 If `org-make-link-description-function' is non-nil, this function will be
9413 called with the link target, and the result will be the default
9414 link description.
9416 If the LINK-LOCATION parameter is non-nil, this value will be
9417 used as the link location instead of reading one interactively.
9419 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9420 be used as the default description."
9421 (interactive "P")
9422 (let* ((wcf (current-window-configuration))
9423 (origbuf (current-buffer))
9424 (region (if (org-region-active-p)
9425 (buffer-substring (region-beginning) (region-end))))
9426 (remove (and region (list (region-beginning) (region-end))))
9427 (desc region)
9428 tmphist ; byte-compile incorrectly complains about this
9429 (link link-location)
9430 (abbrevs org-link-abbrev-alist-local)
9431 entry file all-prefixes auto-desc)
9432 (cond
9433 (link-location) ; specified by arg, just use it.
9434 ((org-in-regexp org-bracket-link-regexp 1)
9435 ;; We do have a link at point, and we are going to edit it.
9436 (setq remove (list (match-beginning 0) (match-end 0)))
9437 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9438 (setq link (read-string "Link: "
9439 (org-link-unescape
9440 (org-match-string-no-properties 1)))))
9441 ((or (org-in-regexp org-angle-link-re)
9442 (org-in-regexp org-plain-link-re))
9443 ;; Convert to bracket link
9444 (setq remove (list (match-beginning 0) (match-end 0))
9445 link (read-string "Link: "
9446 (org-remove-angle-brackets (match-string 0)))))
9447 ((member complete-file '((4) (16)))
9448 ;; Completing read for file names.
9449 (setq link (org-file-complete-link complete-file)))
9451 ;; Read link, with completion for stored links.
9452 (org-link-fontify-links-to-this-file)
9453 (org-switch-to-buffer-other-window "*Org Links*")
9454 (with-current-buffer "*Org Links*"
9455 (erase-buffer)
9456 (insert "Insert a link.
9457 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9458 (when org-stored-links
9459 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9460 (insert (mapconcat 'org-link-prettify
9461 (reverse org-stored-links) "\n")))
9462 (goto-char (point-min)))
9463 (let ((cw (selected-window)))
9464 (select-window (get-buffer-window "*Org Links*" 'visible))
9465 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9466 (unless (pos-visible-in-window-p (point-max))
9467 (org-fit-window-to-buffer))
9468 (and (window-live-p cw) (select-window cw)))
9469 ;; Fake a link history, containing the stored links.
9470 (setq tmphist (append (mapcar 'car org-stored-links)
9471 org-insert-link-history))
9472 (setq all-prefixes (append (mapcar 'car abbrevs)
9473 (mapcar 'car org-link-abbrev-alist)
9474 org-link-types))
9475 (unwind-protect
9476 (progn
9477 (setq link
9478 (org-completing-read
9479 "Link: "
9480 (append
9481 (mapcar (lambda (x) (concat x ":"))
9482 all-prefixes)
9483 (mapcar 'car org-stored-links))
9484 nil nil nil
9485 'tmphist
9486 (caar org-stored-links)))
9487 (if (not (string-match "\\S-" link))
9488 (error "No link selected"))
9489 (mapc (lambda(l)
9490 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9491 org-stored-links)
9492 (if (or (member link all-prefixes)
9493 (and (equal ":" (substring link -1))
9494 (member (substring link 0 -1) all-prefixes)
9495 (setq link (substring link 0 -1))))
9496 (setq link (with-current-buffer origbuf
9497 (org-link-try-special-completion link)))))
9498 (set-window-configuration wcf)
9499 (kill-buffer "*Org Links*"))
9500 (setq entry (assoc link org-stored-links))
9501 (or entry (push link org-insert-link-history))
9502 (setq desc (or desc (nth 1 entry)))))
9504 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9505 (not org-keep-stored-link-after-insertion))
9506 (setq org-stored-links (delq (assoc link org-stored-links)
9507 org-stored-links)))
9509 (if (string-match org-plain-link-re link)
9510 ;; URL-like link, normalize the use of angular brackets.
9511 (setq link (org-remove-angle-brackets link)))
9513 ;; Check if we are linking to the current file with a search
9514 ;; option If yes, simplify the link by using only the search
9515 ;; option.
9516 (when (and buffer-file-name
9517 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9518 (let* ((path (match-string 1 link))
9519 (case-fold-search nil)
9520 (search (match-string 2 link)))
9521 (save-match-data
9522 (if (equal (file-truename buffer-file-name) (file-truename path))
9523 ;; We are linking to this same file, with a search option
9524 (setq link search)))))
9526 ;; Check if we can/should use a relative path. If yes, simplify the link
9527 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9528 (let* ((type (match-string 1 link))
9529 (path (match-string 2 link))
9530 (origpath path)
9531 (case-fold-search nil))
9532 (cond
9533 ((or (eq org-link-file-path-type 'absolute)
9534 (equal complete-file '(16)))
9535 (setq path (abbreviate-file-name (expand-file-name path))))
9536 ((eq org-link-file-path-type 'noabbrev)
9537 (setq path (expand-file-name path)))
9538 ((eq org-link-file-path-type 'relative)
9539 (setq path (file-relative-name path)))
9541 (save-match-data
9542 (if (string-match (concat "^" (regexp-quote
9543 (expand-file-name
9544 (file-name-as-directory
9545 default-directory))))
9546 (expand-file-name path))
9547 ;; We are linking a file with relative path name.
9548 (setq path (substring (expand-file-name path)
9549 (match-end 0)))
9550 (setq path (abbreviate-file-name (expand-file-name path)))))))
9551 (setq link (concat type path))
9552 (if (equal desc origpath)
9553 (setq desc path))))
9555 (if org-make-link-description-function
9556 (setq desc
9557 (or (condition-case nil
9558 (funcall org-make-link-description-function link desc)
9559 (error (progn (message "Can't get link description from `%s'"
9560 (symbol-name org-make-link-description-function))
9561 (sit-for 2) nil)))
9562 (read-string "Description: " default-description)))
9563 (if default-description (setq desc default-description)
9564 (setq desc (or (and auto-desc desc)
9565 (read-string "Description: " desc)))))
9567 (unless (string-match "\\S-" desc) (setq desc nil))
9568 (if remove (apply 'delete-region remove))
9569 (insert (org-make-link-string link desc))))
9571 (defun org-link-try-special-completion (type)
9572 "If there is completion support for link type TYPE, offer it."
9573 (let ((fun (intern (concat "org-" type "-complete-link"))))
9574 (if (functionp fun)
9575 (funcall fun)
9576 (read-string "Link (no completion support): " (concat type ":")))))
9578 (defun org-file-complete-link (&optional arg)
9579 "Create a file link using completion."
9580 (let (file link)
9581 (setq file (org-iread-file-name "File: "))
9582 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9583 (pwd1 (file-name-as-directory (abbreviate-file-name
9584 (expand-file-name ".")))))
9585 (cond
9586 ((equal arg '(16))
9587 (setq link (concat
9588 "file:"
9589 (abbreviate-file-name (expand-file-name file)))))
9590 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9591 (setq link (concat "file:" (match-string 1 file))))
9592 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9593 (expand-file-name file))
9594 (setq link (concat
9595 "file:" (match-string 1 (expand-file-name file)))))
9596 (t (setq link (concat "file:" file)))))
9597 link))
9599 (defun org-iread-file-name (&rest args)
9600 "Read-file-name using `ido-mode' speedup if available.
9601 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9602 See `read-file-name' for a description of parameters."
9603 (org-without-partial-completion
9604 (if (and org-completion-use-ido
9605 (fboundp 'ido-read-file-name)
9606 (boundp 'ido-mode) ido-mode
9607 (listp (second args)))
9608 (let ((ido-enter-matching-directory nil))
9609 (apply 'ido-read-file-name args))
9610 (apply 'read-file-name args))))
9612 (defun org-completing-read (&rest args)
9613 "Completing-read with SPACE being a normal character."
9614 (let ((enable-recursive-minibuffers t)
9615 (minibuffer-local-completion-map
9616 (copy-keymap minibuffer-local-completion-map)))
9617 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9618 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9619 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9620 (apply 'org-icompleting-read args)))
9622 (defun org-completing-read-no-i (&rest args)
9623 (let (org-completion-use-ido org-completion-use-iswitchb)
9624 (apply 'org-completing-read args)))
9626 (defun org-iswitchb-completing-read (prompt choices &rest args)
9627 "Use iswitch as a completing-read replacement to choose from choices.
9628 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9629 from."
9630 (let* ((iswitchb-use-virtual-buffers nil)
9631 (iswitchb-make-buflist-hook
9632 (lambda ()
9633 (setq iswitchb-temp-buflist choices))))
9634 (iswitchb-read-buffer prompt)))
9636 (defun org-icompleting-read (&rest args)
9637 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9638 (org-without-partial-completion
9639 (if (and org-completion-use-ido
9640 (fboundp 'ido-completing-read)
9641 (boundp 'ido-mode) ido-mode
9642 (listp (second args)))
9643 (let ((ido-enter-matching-directory nil))
9644 (apply 'ido-completing-read (concat (car args))
9645 (if (consp (car (nth 1 args)))
9646 (mapcar 'car (nth 1 args))
9647 (nth 1 args))
9648 (cddr args)))
9649 (if (and org-completion-use-iswitchb
9650 (boundp 'iswitchb-mode) iswitchb-mode
9651 (listp (second args)))
9652 (apply 'org-iswitchb-completing-read (concat (car args))
9653 (if (consp (car (nth 1 args)))
9654 (mapcar 'car (nth 1 args))
9655 (nth 1 args))
9656 (cddr args))
9657 (apply 'completing-read args)))))
9659 (defun org-extract-attributes (s)
9660 "Extract the attributes cookie from a string and set as text property."
9661 (let (a attr (start 0) key value)
9662 (save-match-data
9663 (when (string-match "{{\\([^}]+\\)}}$" s)
9664 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9665 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9666 (setq key (match-string 1 a) value (match-string 2 a)
9667 start (match-end 0)
9668 attr (plist-put attr (intern key) value))))
9669 (org-add-props s nil 'org-attr attr))
9672 (defun org-extract-attributes-from-string (tag)
9673 (let (key value attr)
9674 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9675 (setq key (match-string 1 tag) value (match-string 2 tag)
9676 tag (replace-match "" t t tag)
9677 attr (plist-put attr (intern key) value)))
9678 (cons tag attr)))
9680 (defun org-attributes-to-string (plist)
9681 "Format a property list into an HTML attribute list."
9682 (let ((s "") key value)
9683 (while plist
9684 (setq key (pop plist) value (pop plist))
9685 (and value
9686 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9689 ;;; Opening/following a link
9691 (defvar org-link-search-failed nil)
9693 (defvar org-open-link-functions nil
9694 "Hook for functions finding a plain text link.
9695 These functions must take a single argument, the link content.
9696 They will be called for links that look like [[link text][description]]
9697 when LINK TEXT does not have a protocol like \"http:\" and does not look
9698 like a filename (e.g. \"./blue.png\").
9700 These functions will be called *before* Org attempts to resolve the
9701 link by doing text searches in the current buffer - so if you want a
9702 link \"[[target]]\" to still find \"<<target>>\", your function should
9703 handle this as a special case.
9705 When the function does handle the link, it must return a non-nil value.
9706 If it decides that it is not responsible for this link, it must return
9707 nil to indicate that that Org-mode can continue with other options
9708 like exact and fuzzy text search.")
9710 (defun org-next-link ()
9711 "Move forward to the next link.
9712 If the link is in hidden text, expose it."
9713 (interactive)
9714 (when (and org-link-search-failed (eq this-command last-command))
9715 (goto-char (point-min))
9716 (message "Link search wrapped back to beginning of buffer"))
9717 (setq org-link-search-failed nil)
9718 (let* ((pos (point))
9719 (ct (org-context))
9720 (a (assoc :link ct)))
9721 (if a (goto-char (nth 2 a)))
9722 (if (re-search-forward org-any-link-re nil t)
9723 (progn
9724 (goto-char (match-beginning 0))
9725 (if (outline-invisible-p) (org-show-context)))
9726 (goto-char pos)
9727 (setq org-link-search-failed t)
9728 (error "No further link found"))))
9730 (defun org-previous-link ()
9731 "Move backward to the previous link.
9732 If the link is in hidden text, expose it."
9733 (interactive)
9734 (when (and org-link-search-failed (eq this-command last-command))
9735 (goto-char (point-max))
9736 (message "Link search wrapped back to end of buffer"))
9737 (setq org-link-search-failed nil)
9738 (let* ((pos (point))
9739 (ct (org-context))
9740 (a (assoc :link ct)))
9741 (if a (goto-char (nth 1 a)))
9742 (if (re-search-backward org-any-link-re nil t)
9743 (progn
9744 (goto-char (match-beginning 0))
9745 (if (outline-invisible-p) (org-show-context)))
9746 (goto-char pos)
9747 (setq org-link-search-failed t)
9748 (error "No further link found"))))
9750 (defun org-translate-link (s)
9751 "Translate a link string if a translation function has been defined."
9752 (if (and org-link-translation-function
9753 (fboundp org-link-translation-function)
9754 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9755 (progn
9756 (setq s (funcall org-link-translation-function
9757 (match-string 1 s) (match-string 2 s)))
9758 (concat (car s) ":" (cdr s)))
9761 (defun org-translate-link-from-planner (type path)
9762 "Translate a link from Emacs Planner syntax so that Org can follow it.
9763 This is still an experimental function, your mileage may vary."
9764 (cond
9765 ((member type '("http" "https" "news" "ftp"))
9766 ;; standard Internet links are the same.
9767 nil)
9768 ((and (equal type "irc") (string-match "^//" path))
9769 ;; Planner has two / at the beginning of an irc link, we have 1.
9770 ;; We should have zero, actually....
9771 (setq path (substring path 1)))
9772 ((and (equal type "lisp") (string-match "^/" path))
9773 ;; Planner has a slash, we do not.
9774 (setq type "elisp" path (substring path 1)))
9775 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9776 ;; A typical message link. Planner has the id after the final slash,
9777 ;; we separate it with a hash mark
9778 (setq path (concat (match-string 1 path) "#"
9779 (org-remove-angle-brackets (match-string 2 path)))))
9781 (cons type path))
9783 (defun org-find-file-at-mouse (ev)
9784 "Open file link or URL at mouse."
9785 (interactive "e")
9786 (mouse-set-point ev)
9787 (org-open-at-point 'in-emacs))
9789 (defun org-open-at-mouse (ev)
9790 "Open file link or URL at mouse.
9791 See the docstring of `org-open-file' for details."
9792 (interactive "e")
9793 (mouse-set-point ev)
9794 (if (eq major-mode 'org-agenda-mode)
9795 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9796 (org-open-at-point))
9798 (defvar org-window-config-before-follow-link nil
9799 "The window configuration before following a link.
9800 This is saved in case the need arises to restore it.")
9802 (defvar org-open-link-marker (make-marker)
9803 "Marker pointing to the location where `org-open-at-point; was called.")
9805 ;;;###autoload
9806 (defun org-open-at-point-global ()
9807 "Follow a link like Org-mode does.
9808 This command can be called in any mode to follow a link that has
9809 Org-mode syntax."
9810 (interactive)
9811 (org-run-like-in-org-mode 'org-open-at-point))
9813 ;;;###autoload
9814 (defun org-open-link-from-string (s &optional arg reference-buffer)
9815 "Open a link in the string S, as if it was in Org-mode."
9816 (interactive "sLink: \nP")
9817 (let ((reference-buffer (or reference-buffer (current-buffer))))
9818 (with-temp-buffer
9819 (let ((org-inhibit-startup (not reference-buffer)))
9820 (org-mode)
9821 (insert s)
9822 (goto-char (point-min))
9823 (when reference-buffer
9824 (setq org-link-abbrev-alist-local
9825 (with-current-buffer reference-buffer
9826 org-link-abbrev-alist-local)))
9827 (org-open-at-point arg reference-buffer)))))
9829 (defvar org-open-at-point-functions nil
9830 "Hook that is run when following a link at point.
9832 Functions in this hook must return t if they identify and follow
9833 a link at point. If they don't find anything interesting at point,
9834 they must return nil.")
9836 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9837 (defun org-open-at-point (&optional arg reference-buffer)
9838 "Open link at or after point.
9839 If there is no link at point, this function will search forward up to
9840 the end of the current line.
9841 Normally, files will be opened by an appropriate application. If the
9842 optional prefix argument ARG is non-nil, Emacs will visit the file.
9843 With a double prefix argument, try to open outside of Emacs, in the
9844 application the system uses for this file type."
9845 (interactive "P")
9846 ;; if in a code block, then open the block's results
9847 (unless (call-interactively #'org-babel-open-src-block-result)
9848 (org-load-modules-maybe)
9849 (move-marker org-open-link-marker (point))
9850 (setq org-window-config-before-follow-link (current-window-configuration))
9851 (org-remove-occur-highlights nil nil t)
9852 (cond
9853 ((and (org-at-heading-p)
9854 (not (org-at-timestamp-p t))
9855 (not (org-in-regexp
9856 (concat org-plain-link-re "\\|"
9857 org-bracket-link-regexp "\\|"
9858 org-angle-link-re "\\|"
9859 "[ \t]:[^ \t\n]+:[ \t]*$")))
9860 (not (get-text-property (point) 'org-linked-text)))
9861 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9862 (lk (car lkall))
9863 (lkend (cdr lkall)))
9864 (when lk
9865 (prog1 (search-forward lk nil lkend)
9866 (goto-char (match-beginning 0))
9867 (org-open-at-point))))
9868 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9869 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9870 ((and (org-at-timestamp-p t)
9871 (not (org-in-regexp org-bracket-link-regexp)))
9872 (org-follow-timestamp-link))
9873 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9874 (not (org-in-regexp org-any-link-re)))
9875 (org-footnote-action))
9877 (let (type path link line search (pos (point)))
9878 (catch 'match
9879 (save-excursion
9880 (skip-chars-forward "^]\n\r")
9881 (when (org-in-regexp org-bracket-link-regexp 1)
9882 (setq link (org-extract-attributes
9883 (org-link-unescape (org-match-string-no-properties 1))))
9884 (while (string-match " *\n *" link)
9885 (setq link (replace-match " " t t link)))
9886 (setq link (org-link-expand-abbrev link))
9887 (cond
9888 ((or (file-name-absolute-p link)
9889 (string-match "^\\.\\.?/" link))
9890 (setq type "file" path link))
9891 ((string-match org-link-re-with-space3 link)
9892 (setq type (match-string 1 link) path (match-string 2 link)))
9893 ((string-match "^help:+\\(.+\\)" link)
9894 (setq type "help" path (match-string 1 link)))
9895 (t (setq type "thisfile" path link)))
9896 (throw 'match t)))
9898 (when (get-text-property (point) 'org-linked-text)
9899 (setq type "thisfile"
9900 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9901 (1+ (point)) (point))
9902 path (buffer-substring
9903 (or (previous-single-property-change pos 'org-linked-text)
9904 (point-min))
9905 (or (next-single-property-change pos 'org-linked-text)
9906 (point-max))))
9907 (throw 'match t))
9909 (save-excursion
9910 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9911 (when (or (org-in-regexp org-angle-link-re)
9912 (and plinkpos (goto-char (car plinkpos))
9913 (save-match-data (not (looking-back "\\[\\[")))))
9914 (setq type (match-string 1)
9915 path (org-link-unescape (match-string 2)))
9916 (throw 'match t))))
9917 (save-excursion
9918 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9919 (setq type "tags"
9920 path (match-string 1))
9921 (while (string-match ":" path)
9922 (setq path (replace-match "+" t t path)))
9923 (throw 'match t)))
9924 (when (org-in-regexp "<\\([^><\n]+\\)>")
9925 (setq type "tree-match"
9926 path (match-string 1))
9927 (throw 'match t)))
9928 (unless path
9929 (user-error "No link found"))
9931 ;; switch back to reference buffer
9932 ;; needed when if called in a temporary buffer through
9933 ;; org-open-link-from-string
9934 (with-current-buffer (or reference-buffer (current-buffer))
9936 ;; Remove any trailing spaces in path
9937 (if (string-match " +\\'" path)
9938 (setq path (replace-match "" t t path)))
9939 (if (and org-link-translation-function
9940 (fboundp org-link-translation-function))
9941 ;; Check if we need to translate the link
9942 (let ((tmp (funcall org-link-translation-function type path)))
9943 (setq type (car tmp) path (cdr tmp))))
9945 (cond
9947 ((assoc type org-link-protocols)
9948 (funcall (nth 1 (assoc type org-link-protocols)) path))
9950 ((equal type "help")
9951 (let ((f-or-v (intern path)))
9952 (cond ((fboundp f-or-v)
9953 (describe-function f-or-v))
9954 ((boundp f-or-v)
9955 (describe-variable f-or-v))
9956 (t (error "Not a known function or variable")))))
9958 ((equal type "mailto")
9959 (let ((cmd (car org-link-mailto-program))
9960 (args (cdr org-link-mailto-program)) args1
9961 (address path) (subject "") a)
9962 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9963 (setq address (match-string 1 path)
9964 subject (org-link-escape (match-string 2 path))))
9965 (while args
9966 (cond
9967 ((not (stringp (car args))) (push (pop args) args1))
9968 (t (setq a (pop args))
9969 (if (string-match "%a" a)
9970 (setq a (replace-match address t t a)))
9971 (if (string-match "%s" a)
9972 (setq a (replace-match subject t t a)))
9973 (push a args1))))
9974 (apply cmd (nreverse args1))))
9976 ((member type '("http" "https" "ftp" "news"))
9977 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9978 (org-link-escape
9979 path org-link-escape-chars-browser)
9980 path))))
9982 ((string= type "doi")
9983 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9984 (org-link-escape
9985 path org-link-escape-chars-browser)
9986 path))))
9988 ((member type '("message"))
9989 (browse-url (concat type ":" path)))
9991 ((string= type "tags")
9992 (org-tags-view arg path))
9994 ((string= type "tree-match")
9995 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9997 ((string= type "file")
9998 (if (string-match "::\\([0-9]+\\)\\'" path)
9999 (setq line (string-to-number (match-string 1 path))
10000 path (substring path 0 (match-beginning 0)))
10001 (if (string-match "::\\(.+\\)\\'" path)
10002 (setq search (match-string 1 path)
10003 path (substring path 0 (match-beginning 0)))))
10004 (if (string-match "[*?{]" (file-name-nondirectory path))
10005 (dired path)
10006 (org-open-file path arg line search)))
10008 ((string= type "shell")
10009 (let ((buf (generate-new-buffer "*Org Shell Output"))
10010 (cmd path))
10011 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10012 (string-match org-confirm-shell-link-not-regexp cmd))
10013 (not org-confirm-shell-link-function)
10014 (funcall org-confirm-shell-link-function
10015 (format "Execute \"%s\" in shell? "
10016 (org-add-props cmd nil
10017 'face 'org-warning))))
10018 (progn
10019 (message "Executing %s" cmd)
10020 (shell-command cmd buf)
10021 (if (featurep 'midnight)
10022 (setq clean-buffer-list-kill-buffer-names
10023 (cons buf clean-buffer-list-kill-buffer-names))))
10024 (error "Abort"))))
10026 ((string= type "elisp")
10027 (let ((cmd path))
10028 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10029 (string-match org-confirm-elisp-link-not-regexp cmd))
10030 (not org-confirm-elisp-link-function)
10031 (funcall org-confirm-elisp-link-function
10032 (format "Execute \"%s\" as elisp? "
10033 (org-add-props cmd nil
10034 'face 'org-warning))))
10035 (message "%s => %s" cmd
10036 (if (equal (string-to-char cmd) ?\()
10037 (eval (read cmd))
10038 (call-interactively (read cmd))))
10039 (error "Abort"))))
10041 ((and (string= type "thisfile")
10042 (run-hook-with-args-until-success
10043 'org-open-link-functions path)))
10045 ((string= type "thisfile")
10046 (if arg
10047 (switch-to-buffer-other-window
10048 (org-get-buffer-for-internal-link (current-buffer)))
10049 (org-mark-ring-push))
10050 (let ((cmd `(org-link-search
10051 ,path
10052 ,(cond ((equal arg '(4)) ''occur)
10053 ((equal arg '(16)) ''org-occur))
10054 ,pos)))
10055 (condition-case nil (let ((org-link-search-inhibit-query t))
10056 (eval cmd))
10057 (error (progn (widen) (eval cmd))))))
10059 (t (browse-url-at-point)))))))
10060 (move-marker org-open-link-marker nil)
10061 (run-hook-with-args 'org-follow-link-hook)))
10063 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10064 "Offer links in the current entry and return the selected link.
10065 If there is only one link, return it.
10066 If NTH is an integer, return the NTH link found.
10067 If ZERO is a string, check also this string for a link, and if
10068 there is one, return it."
10069 (with-current-buffer buffer
10070 (save-excursion
10071 (save-restriction
10072 (widen)
10073 (goto-char marker)
10074 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10075 "\\(" org-angle-link-re "\\)\\|"
10076 "\\(" org-plain-link-re "\\)"))
10077 (cnt ?0)
10078 (in-emacs (if (integerp nth) nil nth))
10079 have-zero end links link c)
10080 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10081 (push (match-string 0 zero) links)
10082 (setq cnt (1- cnt) have-zero t))
10083 (save-excursion
10084 (org-back-to-heading t)
10085 (setq end (save-excursion (outline-next-heading) (point)))
10086 (while (re-search-forward re end t)
10087 (push (match-string 0) links))
10088 (setq links (org-uniquify (reverse links))))
10089 (cond
10090 ((null links)
10091 (message "No links"))
10092 ((equal (length links) 1)
10093 (setq link (car links)))
10094 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10095 (setq link (nth (if have-zero nth (1- nth)) links)))
10096 (t ; we have to select a link
10097 (save-excursion
10098 (save-window-excursion
10099 (delete-other-windows)
10100 (with-output-to-temp-buffer "*Select Link*"
10101 (mapc (lambda (l)
10102 (if (not (string-match org-bracket-link-regexp l))
10103 (princ (format "[%c] %s\n" (incf cnt)
10104 (org-remove-angle-brackets l)))
10105 (if (match-end 3)
10106 (princ (format "[%c] %s (%s)\n" (incf cnt)
10107 (match-string 3 l) (match-string 1 l)))
10108 (princ (format "[%c] %s\n" (incf cnt)
10109 (match-string 1 l))))))
10110 links))
10111 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10112 (message "Select link to open, RET to open all:")
10113 (setq c (read-char-exclusive))
10114 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10115 (when (equal c ?q) (error "Abort"))
10116 (if (equal c ?\C-m)
10117 (setq link links)
10118 (setq nth (- c ?0))
10119 (if have-zero (setq nth (1+ nth)))
10120 (unless (and (integerp nth) (>= (length links) nth))
10121 (error "Invalid link selection"))
10122 (setq link (nth (1- nth) links)))))
10123 (cons link end))))))
10125 ;; Add special file links that specify the way of opening
10127 (org-add-link-type "file+sys" 'org-open-file-with-system)
10128 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10129 (defun org-open-file-with-system (path)
10130 "Open file at PATH using the system way of opening it."
10131 (org-open-file path 'system))
10132 (defun org-open-file-with-emacs (path)
10133 "Open file at PATH in Emacs."
10134 (org-open-file path 'emacs))
10135 (defun org-remove-file-link-modifiers ()
10136 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10137 (goto-char (point-min))
10138 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10139 (org-if-unprotected
10140 (replace-match "file:" t t))))
10141 (eval-after-load "org-exp"
10142 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10143 'org-remove-file-link-modifiers))
10145 ;;;; Time estimates
10147 (defun org-get-effort (&optional pom)
10148 "Get the effort estimate for the current entry."
10149 (org-entry-get pom org-effort-property))
10151 ;;; File search
10153 (defvar org-create-file-search-functions nil
10154 "List of functions to construct the right search string for a file link.
10155 These functions are called in turn with point at the location to
10156 which the link should point.
10158 A function in the hook should first test if it would like to
10159 handle this file type, for example by checking the `major-mode'
10160 or the file extension. If it decides not to handle this file, it
10161 should just return nil to give other functions a chance. If it
10162 does handle the file, it must return the search string to be used
10163 when following the link. The search string will be part of the
10164 file link, given after a double colon, and `org-open-at-point'
10165 will automatically search for it. If special measures must be
10166 taken to make the search successful, another function should be
10167 added to the companion hook `org-execute-file-search-functions',
10168 which see.
10170 A function in this hook may also use `setq' to set the variable
10171 `description' to provide a suggestion for the descriptive text to
10172 be used for this link when it gets inserted into an Org-mode
10173 buffer with \\[org-insert-link].")
10175 (defvar org-execute-file-search-functions nil
10176 "List of functions to execute a file search triggered by a link.
10178 Functions added to this hook must accept a single argument, the
10179 search string that was part of the file link, the part after the
10180 double colon. The function must first check if it would like to
10181 handle this search, for example by checking the `major-mode' or
10182 the file extension. If it decides not to handle this search, it
10183 should just return nil to give other functions a chance. If it
10184 does handle the search, it must return a non-nil value to keep
10185 other functions from trying.
10187 Each function can access the current prefix argument through the
10188 variable `current-prefix-argument'. Note that a single prefix is
10189 used to force opening a link in Emacs, so it may be good to only
10190 use a numeric or double prefix to guide the search function.
10192 In case this is needed, a function in this hook can also restore
10193 the window configuration before `org-open-at-point' was called using:
10195 (set-window-configuration org-window-config-before-follow-link)")
10197 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10198 (defun org-link-search (s &optional type avoid-pos stealth)
10199 "Search for a link search option.
10200 If S is surrounded by forward slashes, it is interpreted as a
10201 regular expression. In org-mode files, this will create an `org-occur'
10202 sparse tree. In ordinary files, `occur' will be used to list matches.
10203 If the current buffer is in `dired-mode', grep will be used to search
10204 in all files. If AVOID-POS is given, ignore matches near that position.
10206 When optional argument STEALTH is non-nil, do not modify
10207 visibility around point, thus ignoring
10208 `org-show-hierarchy-above', `org-show-following-heading' and
10209 `org-show-siblings' variables."
10210 (let ((case-fold-search t)
10211 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10212 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10213 (append '(("") (" ") ("\t") ("\n"))
10214 org-emphasis-alist)
10215 "\\|") "\\)"))
10216 (pos (point))
10217 (pre nil) (post nil)
10218 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10219 (cond
10220 ;; First check if there are any special search functions
10221 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10222 ;; Now try the builtin stuff
10223 ((and (equal (string-to-char s0) ?#)
10224 (> (length s0) 1)
10225 (save-excursion
10226 (goto-char (point-min))
10227 (and
10228 (re-search-forward
10229 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10230 (setq type 'dedicated
10231 pos (match-beginning 0))))
10232 ;; There is an exact target for this
10233 (goto-char pos)
10234 (org-back-to-heading t)))
10235 ((save-excursion
10236 (goto-char (point-min))
10237 (and
10238 (re-search-forward
10239 (concat "<<" (regexp-quote s0) ">>") nil t)
10240 (setq type 'dedicated
10241 pos (match-beginning 0))))
10242 ;; There is an exact target for this
10243 (goto-char pos))
10244 ((save-excursion
10245 (goto-char (point-min))
10246 (and
10247 (re-search-forward
10248 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10249 (setq type 'dedicated pos (match-beginning 0))))
10250 ;; Found an invisible target.
10251 (goto-char pos))
10252 ((save-excursion
10253 (goto-char (point-min))
10254 (and
10255 (re-search-forward
10256 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10257 (setq type 'dedicated pos (match-beginning 0))))
10258 ;; Found an element with a matching #+name affiliated keyword.
10259 (goto-char pos))
10260 ((and (string-match "^(\\(.*\\))$" s0)
10261 (save-excursion
10262 (goto-char (point-min))
10263 (and
10264 (re-search-forward
10265 (concat "[^[]" (regexp-quote
10266 (format org-coderef-label-format
10267 (match-string 1 s0))))
10268 nil t)
10269 (setq type 'dedicated
10270 pos (1+ (match-beginning 0))))))
10271 ;; There is a coderef target for this
10272 (goto-char pos))
10273 ((string-match "^/\\(.*\\)/$" s)
10274 ;; A regular expression
10275 (cond
10276 ((derived-mode-p 'org-mode)
10277 (org-occur (match-string 1 s)))
10278 ;;((eq major-mode 'dired-mode)
10279 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10280 (t (org-do-occur (match-string 1 s)))))
10281 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10282 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10283 (goto-char (point-min))
10284 (cond
10285 ((let (case-fold-search)
10286 (re-search-forward (format org-complex-heading-regexp-format
10287 (regexp-quote s))
10288 nil t))
10289 ;; OK, found a match
10290 (setq type 'dedicated)
10291 (goto-char (match-beginning 0)))
10292 ((and (not org-link-search-inhibit-query)
10293 (eq org-link-search-must-match-exact-headline 'query-to-create)
10294 (y-or-n-p "No match - create this as a new heading? "))
10295 (goto-char (point-max))
10296 (or (bolp) (newline))
10297 (insert "* " s "\n")
10298 (beginning-of-line 0))
10300 (goto-char pos)
10301 (error "No match"))))
10303 ;; A normal search string
10304 (when (equal (string-to-char s) ?*)
10305 ;; Anchor on headlines, post may include tags.
10306 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10307 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10308 s (substring s 1)))
10309 (remove-text-properties
10310 0 (length s)
10311 '(face nil mouse-face nil keymap nil fontified nil) s)
10312 ;; Make a series of regular expressions to find a match
10313 (setq words (org-split-string s "[ \n\r\t]+")
10315 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10316 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10317 "\\)" markers)
10318 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10319 re2a (concat "[ \t\r\n]" re2a_)
10320 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10321 re4 (concat "[^a-zA-Z_]" re4_)
10323 re1 (concat pre re2 post)
10324 re3 (concat pre (if pre re4_ re4) post)
10325 re5 (concat pre ".*" re4)
10326 re2 (concat pre re2)
10327 re2a (concat pre (if pre re2a_ re2a))
10328 re4 (concat pre (if pre re4_ re4))
10329 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10330 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10331 re5 "\\)"
10333 (cond
10334 ((eq type 'org-occur) (org-occur reall))
10335 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10336 (t (goto-char (point-min))
10337 (setq type 'fuzzy)
10338 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10339 (org-search-not-self 1 re1 nil t)
10340 (org-search-not-self 1 re2 nil t)
10341 (org-search-not-self 1 re2a nil t)
10342 (org-search-not-self 1 re3 nil t)
10343 (org-search-not-self 1 re4 nil t)
10344 (org-search-not-self 1 re5 nil t)
10346 (goto-char (match-beginning 1))
10347 (goto-char pos)
10348 (error "No match"))))))
10349 (and (derived-mode-p 'org-mode)
10350 (not stealth)
10351 (org-show-context 'link-search))
10352 type))
10354 (defun org-search-not-self (group &rest args)
10355 "Execute `re-search-forward', but only accept matches that do not
10356 enclose the position of `org-open-link-marker'."
10357 (let ((m org-open-link-marker))
10358 (catch 'exit
10359 (while (apply 're-search-forward args)
10360 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10361 (goto-char (match-end group))
10362 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10363 (> (match-beginning 0) (marker-position m))
10364 (< (match-end 0) (marker-position m)))
10365 (save-match-data
10366 (or (not (org-in-regexp
10367 org-bracket-link-analytic-regexp 1))
10368 (not (match-end 4)) ; no description
10369 (and (<= (match-beginning 4) (point))
10370 (>= (match-end 4) (point))))))
10371 (throw 'exit (point))))))))
10373 (defun org-get-buffer-for-internal-link (buffer)
10374 "Return a buffer to be used for displaying the link target of internal links."
10375 (cond
10376 ((not org-display-internal-link-with-indirect-buffer)
10377 buffer)
10378 ((string-match "(Clone)$" (buffer-name buffer))
10379 (message "Buffer is already a clone, not making another one")
10380 ;; we also do not modify visibility in this case
10381 buffer)
10382 (t ; make a new indirect buffer for displaying the link
10383 (let* ((bn (buffer-name buffer))
10384 (ibn (concat bn "(Clone)"))
10385 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10386 (with-current-buffer ib (org-overview))
10387 ib))))
10389 (defun org-do-occur (regexp &optional cleanup)
10390 "Call the Emacs command `occur'.
10391 If CLEANUP is non-nil, remove the printout of the regular expression
10392 in the *Occur* buffer. This is useful if the regex is long and not useful
10393 to read."
10394 (occur regexp)
10395 (when cleanup
10396 (let ((cwin (selected-window)) win beg end)
10397 (when (setq win (get-buffer-window "*Occur*"))
10398 (select-window win))
10399 (goto-char (point-min))
10400 (when (re-search-forward "match[a-z]+" nil t)
10401 (setq beg (match-end 0))
10402 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10403 (setq end (1- (match-beginning 0)))))
10404 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10405 (goto-char (point-min))
10406 (select-window cwin))))
10408 ;;; The mark ring for links jumps
10410 (defvar org-mark-ring nil
10411 "Mark ring for positions before jumps in Org-mode.")
10412 (defvar org-mark-ring-last-goto nil
10413 "Last position in the mark ring used to go back.")
10414 ;; Fill and close the ring
10415 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10416 (loop for i from 1 to org-mark-ring-length do
10417 (push (make-marker) org-mark-ring))
10418 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10419 org-mark-ring)
10421 (defun org-mark-ring-push (&optional pos buffer)
10422 "Put the current position or POS into the mark ring and rotate it."
10423 (interactive)
10424 (setq pos (or pos (point)))
10425 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10426 (move-marker (car org-mark-ring)
10427 (or pos (point))
10428 (or buffer (current-buffer)))
10429 (message "%s"
10430 (substitute-command-keys
10431 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10433 (defun org-mark-ring-goto (&optional n)
10434 "Jump to the previous position in the mark ring.
10435 With prefix arg N, jump back that many stored positions. When
10436 called several times in succession, walk through the entire ring.
10437 Org-mode commands jumping to a different position in the current file,
10438 or to another Org-mode file, automatically push the old position
10439 onto the ring."
10440 (interactive "p")
10441 (let (p m)
10442 (if (eq last-command this-command)
10443 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10444 (setq p org-mark-ring))
10445 (setq org-mark-ring-last-goto p)
10446 (setq m (car p))
10447 (org-pop-to-buffer-same-window (marker-buffer m))
10448 (goto-char m)
10449 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10451 (defun org-remove-angle-brackets (s)
10452 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10453 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10455 (defun org-add-angle-brackets (s)
10456 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10457 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10459 (defun org-remove-double-quotes (s)
10460 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10461 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10464 ;;; Following specific links
10466 (defun org-follow-timestamp-link ()
10467 "Open an agenda view for the time-stamp date/range at point."
10468 (cond
10469 ((org-at-date-range-p t)
10470 (let ((org-agenda-start-on-weekday)
10471 (t1 (match-string 1))
10472 (t2 (match-string 2)) tt1 tt2)
10473 (setq tt1 (time-to-days (org-time-string-to-time t1))
10474 tt2 (time-to-days (org-time-string-to-time t2)))
10475 (let ((org-agenda-buffer-tmp-name
10476 (format "*Org Agenda(a:%s)"
10477 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10478 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10479 ((org-at-timestamp-p t)
10480 (let ((org-agenda-buffer-tmp-name
10481 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10482 (org-agenda-list nil (time-to-days (org-time-string-to-time
10483 (substring (match-string 1) 0 10)))
10484 1)))
10485 (t (error "This should not happen"))))
10488 ;;; Following file links
10489 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10490 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10491 (declare-function mailcap-mime-info
10492 "mailcap" (string &optional request no-decode))
10493 (defvar org-wait nil)
10494 (defun org-open-file (path &optional in-emacs line search)
10495 "Open the file at PATH.
10496 First, this expands any special file name abbreviations. Then the
10497 configuration variable `org-file-apps' is checked if it contains an
10498 entry for this file type, and if yes, the corresponding command is launched.
10500 If no application is found, Emacs simply visits the file.
10502 With optional prefix argument IN-EMACS, Emacs will visit the file.
10503 With a double \\[universal-argument] \\[universal-argument] \
10504 prefix arg, Org tries to avoid opening in Emacs
10505 and to use an external application to visit the file.
10507 Optional LINE specifies a line to go to, optional SEARCH a string
10508 to search for. If LINE or SEARCH is given, the file will be
10509 opened in Emacs, unless an entry from org-file-apps that makes
10510 use of groups in a regexp matches.
10512 If you want to change the way frames are used when following a
10513 link, please customize `org-link-frame-setup'.
10515 If the file does not exist, an error is thrown."
10516 (let* ((file (if (equal path "")
10517 buffer-file-name
10518 (substitute-in-file-name (expand-file-name path))))
10519 (file-apps (append org-file-apps (org-default-apps)))
10520 (apps (org-remove-if
10521 'org-file-apps-entry-match-against-dlink-p file-apps))
10522 (apps-dlink (org-remove-if-not
10523 'org-file-apps-entry-match-against-dlink-p file-apps))
10524 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10525 (dirp (if remp nil (file-directory-p file)))
10526 (file (if (and dirp org-open-directory-means-index-dot-org)
10527 (concat (file-name-as-directory file) "index.org")
10528 file))
10529 (a-m-a-p (assq 'auto-mode apps))
10530 (dfile (downcase file))
10531 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10532 (link (cond ((and (eq line nil)
10533 (eq search nil))
10534 file)
10535 (line
10536 (concat file "::" (number-to-string line)))
10537 (search
10538 (concat file "::" search))))
10539 (dlink (downcase link))
10540 (old-buffer (current-buffer))
10541 (old-pos (point))
10542 (old-mode major-mode)
10543 ext cmd link-match-data)
10544 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10545 (setq ext (match-string 1 dfile))
10546 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10547 (setq ext (match-string 1 dfile))))
10548 (cond
10549 ((member in-emacs '((16) system))
10550 (setq cmd (cdr (assoc 'system apps))))
10551 (in-emacs (setq cmd 'emacs))
10553 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10554 (and dirp (cdr (assoc 'directory apps)))
10555 ; first, try matching against apps-dlink
10556 ; if we get a match here, store the match data for later
10557 (let ((match (assoc-default dlink apps-dlink
10558 'string-match)))
10559 (if match
10560 (progn (setq link-match-data (match-data))
10561 match)
10562 (progn (setq in-emacs (or in-emacs line search))
10563 nil))) ; if we have no match in apps-dlink,
10564 ; always open the file in emacs if line or search
10565 ; is given (for backwards compatibility)
10566 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10567 'string-match)
10568 (cdr (assoc ext apps))
10569 (cdr (assoc t apps))))))
10570 (when (eq cmd 'system)
10571 (setq cmd (cdr (assoc 'system apps))))
10572 (when (eq cmd 'default)
10573 (setq cmd (cdr (assoc t apps))))
10574 (when (eq cmd 'mailcap)
10575 (require 'mailcap)
10576 (mailcap-parse-mailcaps)
10577 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10578 (command (mailcap-mime-info mime-type)))
10579 (if (stringp command)
10580 (setq cmd command)
10581 (setq cmd 'emacs))))
10582 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10583 (not (file-exists-p file))
10584 (not org-open-non-existing-files))
10585 (error "No such file: %s" file))
10586 (cond
10587 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10588 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10589 (while (string-match "['\"]%s['\"]" cmd)
10590 (setq cmd (replace-match "%s" t t cmd)))
10591 (while (string-match "%s" cmd)
10592 (setq cmd (replace-match
10593 (save-match-data
10594 (shell-quote-argument
10595 (convert-standard-filename file)))
10596 t t cmd)))
10598 ;; Replace "%1", "%2" etc. in command with group matches from regex
10599 (save-match-data
10600 (let ((match-index 1)
10601 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10602 (set-match-data link-match-data)
10603 (while (<= match-index number-of-groups)
10604 (let ((regex (concat "%" (number-to-string match-index)))
10605 (replace-with (match-string match-index dlink)))
10606 (while (string-match regex cmd)
10607 (setq cmd (replace-match replace-with t t cmd))))
10608 (setq match-index (+ match-index 1)))))
10610 (save-window-excursion
10611 (message "Running %s...done" cmd)
10612 (start-process-shell-command cmd nil cmd)
10613 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10614 ((or (stringp cmd)
10615 (eq cmd 'emacs))
10616 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10617 (widen)
10618 (if line (org-goto-line line)
10619 (if search (org-link-search search))))
10620 ((consp cmd)
10621 (let ((file (convert-standard-filename file)))
10622 (save-match-data
10623 (set-match-data link-match-data)
10624 (eval cmd))))
10625 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10626 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10627 (or (not (equal old-buffer (current-buffer)))
10628 (not (equal old-pos (point))))
10629 (org-mark-ring-push old-pos old-buffer))))
10631 (defun org-file-apps-entry-match-against-dlink-p (entry)
10632 "This function returns non-nil if `entry' uses a regular
10633 expression which should be matched against the whole link by
10634 org-open-file.
10636 It assumes that is the case when the entry uses a regular
10637 expression which has at least one grouping construct and the
10638 action is either a lisp form or a command string containing
10639 '%1', i.e. using at least one subexpression match as a
10640 parameter."
10641 (let ((selector (car entry))
10642 (action (cdr entry)))
10643 (if (stringp selector)
10644 (and (> (regexp-opt-depth selector) 0)
10645 (or (and (stringp action)
10646 (string-match "%[0-9]" action))
10647 (consp action)))
10648 nil)))
10650 (defun org-default-apps ()
10651 "Return the default applications for this operating system."
10652 (cond
10653 ((eq system-type 'darwin)
10654 org-file-apps-defaults-macosx)
10655 ((eq system-type 'windows-nt)
10656 org-file-apps-defaults-windowsnt)
10657 (t org-file-apps-defaults-gnu)))
10659 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10660 "Convert extensions to regular expressions in the cars of LIST.
10661 Also, weed out any non-string entries, because the return value is used
10662 only for regexp matching.
10663 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10664 point to the symbol `emacs', indicating that the file should
10665 be opened in Emacs."
10666 (append
10667 (delq nil
10668 (mapcar (lambda (x)
10669 (if (not (stringp (car x)))
10671 (if (string-match "\\W" (car x))
10673 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10674 list))
10675 (if add-auto-mode
10676 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10678 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10679 (defun org-file-remote-p (file)
10680 "Test whether FILE specifies a location on a remote system.
10681 Return non-nil if the location is indeed remote.
10683 For example, the filename \"/user@host:/foo\" specifies a location
10684 on the system \"/user@host:\"."
10685 (cond ((fboundp 'file-remote-p)
10686 (file-remote-p file))
10687 ((fboundp 'tramp-handle-file-remote-p)
10688 (tramp-handle-file-remote-p file))
10689 ((and (boundp 'ange-ftp-name-format)
10690 (string-match (car ange-ftp-name-format) file))
10691 t)))
10694 ;;;; Refiling
10696 (defun org-get-org-file ()
10697 "Read a filename, with default directory `org-directory'."
10698 (let ((default (or org-default-notes-file remember-data-file)))
10699 (read-file-name (format "File name [%s]: " default)
10700 (file-name-as-directory org-directory)
10701 default)))
10703 (defun org-notes-order-reversed-p ()
10704 "Check if the current file should receive notes in reversed order."
10705 (cond
10706 ((not org-reverse-note-order) nil)
10707 ((eq t org-reverse-note-order) t)
10708 ((not (listp org-reverse-note-order)) nil)
10709 (t (catch 'exit
10710 (let ((all org-reverse-note-order)
10711 entry)
10712 (while (setq entry (pop all))
10713 (if (string-match (car entry) buffer-file-name)
10714 (throw 'exit (cdr entry))))
10715 nil)))))
10717 (defvar org-refile-target-table nil
10718 "The list of refile targets, created by `org-refile'.")
10720 (defvar org-agenda-new-buffers nil
10721 "Buffers created to visit agenda files.")
10723 (defvar org-refile-cache nil
10724 "Cache for refile targets.")
10726 (defvar org-refile-markers nil
10727 "All the markers used for caching refile locations.")
10729 (defun org-refile-marker (pos)
10730 "Get a new refile marker, but only if caching is in use."
10731 (if (not org-refile-use-cache)
10733 (let ((m (make-marker)))
10734 (move-marker m pos)
10735 (push m org-refile-markers)
10736 m)))
10738 (defun org-refile-cache-clear ()
10739 "Clear the refile cache and disable all the markers."
10740 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10741 (setq org-refile-markers nil)
10742 (setq org-refile-cache nil)
10743 (message "Refile cache has been cleared"))
10745 (defun org-refile-cache-check-set (set)
10746 "Check if all the markers in the cache still have live buffers."
10747 (let (marker)
10748 (catch 'exit
10749 (while (and set (setq marker (nth 3 (pop set))))
10750 ;; if org-refile-use-outline-path is 'file, marker may be nil
10751 (when (and marker (null (marker-buffer marker)))
10752 (message "not found") (sit-for 3)
10753 (throw 'exit nil)))
10754 t)))
10756 (defun org-refile-cache-put (set &rest identifiers)
10757 "Push the refile targets SET into the cache, under IDENTIFIERS."
10758 (let* ((key (sha1 (prin1-to-string identifiers)))
10759 (entry (assoc key org-refile-cache)))
10760 (if entry
10761 (setcdr entry set)
10762 (push (cons key set) org-refile-cache))))
10764 (defun org-refile-cache-get (&rest identifiers)
10765 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10766 (cond
10767 ((not org-refile-cache) nil)
10768 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10770 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10771 org-refile-cache))))
10772 (and set (org-refile-cache-check-set set) set)))))
10774 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10775 "Produce a table with refile targets."
10776 (let ((case-fold-search nil)
10777 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10778 (entries (or org-refile-targets '((nil . (:level . 1)))))
10779 targets tgs txt re files f desc descre fast-path-p level pos0)
10780 (message "Getting targets...")
10781 (with-current-buffer (or default-buffer (current-buffer))
10782 (while (setq entry (pop entries))
10783 (setq files (car entry) desc (cdr entry))
10784 (setq fast-path-p nil)
10785 (cond
10786 ((null files) (setq files (list (current-buffer))))
10787 ((eq files 'org-agenda-files)
10788 (setq files (org-agenda-files 'unrestricted)))
10789 ((and (symbolp files) (fboundp files))
10790 (setq files (funcall files)))
10791 ((and (symbolp files) (boundp files))
10792 (setq files (symbol-value files))))
10793 (if (stringp files) (setq files (list files)))
10794 (cond
10795 ((eq (car desc) :tag)
10796 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10797 ((eq (car desc) :todo)
10798 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10799 ((eq (car desc) :regexp)
10800 (setq descre (cdr desc)))
10801 ((eq (car desc) :level)
10802 (setq descre (concat "^\\*\\{" (number-to-string
10803 (if org-odd-levels-only
10804 (1- (* 2 (cdr desc)))
10805 (cdr desc)))
10806 "\\}[ \t]")))
10807 ((eq (car desc) :maxlevel)
10808 (setq fast-path-p t)
10809 (setq descre (concat "^\\*\\{1," (number-to-string
10810 (if org-odd-levels-only
10811 (1- (* 2 (cdr desc)))
10812 (cdr desc)))
10813 "\\}[ \t]")))
10814 (t (error "Bad refiling target description %s" desc)))
10815 (while (setq f (pop files))
10816 (with-current-buffer
10817 (if (bufferp f) f (org-get-agenda-file-buffer f))
10819 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10820 (progn
10821 (if (bufferp f) (setq f (buffer-file-name
10822 (buffer-base-buffer f))))
10823 (setq f (and f (expand-file-name f)))
10824 (if (eq org-refile-use-outline-path 'file)
10825 (push (list (file-name-nondirectory f) f nil nil) tgs))
10826 (save-excursion
10827 (save-restriction
10828 (widen)
10829 (goto-char (point-min))
10830 (while (re-search-forward descre nil t)
10831 (goto-char (setq pos0 (point-at-bol)))
10832 (catch 'next
10833 (when org-refile-target-verify-function
10834 (save-match-data
10835 (or (funcall org-refile-target-verify-function)
10836 (throw 'next t))))
10837 (when (and (looking-at org-complex-heading-regexp)
10838 (not (member (match-string 4) excluded-entries))
10839 (match-string 4))
10840 (setq level (org-reduced-level
10841 (- (match-end 1) (match-beginning 1)))
10842 txt (org-link-display-format (match-string 4))
10843 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10844 re (format org-complex-heading-regexp-format
10845 (regexp-quote (match-string 4))))
10846 (when org-refile-use-outline-path
10847 (setq txt (mapconcat
10848 'org-protect-slash
10849 (append
10850 (if (eq org-refile-use-outline-path
10851 'file)
10852 (list (file-name-nondirectory
10853 (buffer-file-name
10854 (buffer-base-buffer))))
10855 (if (eq org-refile-use-outline-path
10856 'full-file-path)
10857 (list (buffer-file-name
10858 (buffer-base-buffer)))))
10859 (org-get-outline-path fast-path-p
10860 level txt)
10861 (list txt))
10862 "/")))
10863 (push (list txt f re (org-refile-marker (point)))
10864 tgs)))
10865 (when (= (point) pos0)
10866 ;; verification function has not moved point
10867 (goto-char (point-at-eol))))))))
10868 (when org-refile-use-cache
10869 (org-refile-cache-put tgs (buffer-file-name) descre))
10870 (setq targets (append tgs targets))
10871 ))))
10872 (message "Getting targets...done")
10873 (nreverse targets)))
10875 (defun org-protect-slash (s)
10876 (while (string-match "/" s)
10877 (setq s (replace-match "\\" t t s)))
10880 (defvar org-olpa (make-vector 20 nil))
10882 (defun org-get-outline-path (&optional fastp level heading)
10883 "Return the outline path to the current entry, as a list.
10885 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10886 routine which makes outline path derivations for an entire file,
10887 avoiding backtracing. Refile target collection makes use of that."
10888 (if fastp
10889 (progn
10890 (if (> level 19)
10891 (error "Outline path failure, more than 19 levels"))
10892 (loop for i from level upto 19 do
10893 (aset org-olpa i nil))
10894 (prog1
10895 (delq nil (append org-olpa nil))
10896 (aset org-olpa level heading)))
10897 (let (rtn case-fold-search)
10898 (save-excursion
10899 (save-restriction
10900 (widen)
10901 (while (org-up-heading-safe)
10902 (when (looking-at org-complex-heading-regexp)
10903 (push (org-match-string-no-properties 4) rtn)))
10904 rtn)))))
10906 (defun org-format-outline-path (path &optional width prefix separator)
10907 "Format the outline path PATH for display.
10908 WIDTH is the maximum number of characters that is available.
10909 PREFIX is a prefix to be included in the returned string,
10910 such as the file name.
10911 SEPARATOR is inserted between the different parts of the path,
10912 the default is \"/\"."
10913 (setq width (or width 79))
10914 (if prefix (setq width (- width (length prefix))))
10915 (if (not path)
10916 (or prefix "")
10917 (let* ((nsteps (length path))
10918 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10919 (maxwidth (if (<= total-width width)
10920 10000 ;; everything fits
10921 ;; we need to shorten the level headings
10922 (/ (- width nsteps) nsteps)))
10923 (org-odd-levels-only nil)
10924 (n 0)
10925 (total (1+ (length prefix))))
10926 (setq maxwidth (max maxwidth 10))
10927 (concat prefix
10928 (if prefix (or separator "/"))
10929 (mapconcat
10930 (lambda (h)
10931 (setq n (1+ n))
10932 (if (and (= n nsteps) (< maxwidth 10000))
10933 (setq maxwidth (- total-width total)))
10934 (if (< (length h) maxwidth)
10935 (progn (setq total (+ total (length h) 1)) h)
10936 (setq h (substring h 0 (- maxwidth 2))
10937 total (+ total maxwidth 1))
10938 (if (string-match "[ \t]+\\'" h)
10939 (setq h (substring h 0 (match-beginning 0))))
10940 (setq h (concat h "..")))
10941 (org-add-props h nil 'face
10942 (nth (% (1- n) org-n-level-faces)
10943 org-level-faces))
10945 path (or separator "/"))))))
10947 (defun org-display-outline-path (&optional file current separator just-return-string)
10948 "Display the current outline path in the echo area.
10950 If FILE is non-nil, prepend the output with the file name.
10951 If CURRENT is non-nil, append the current heading to the output.
10952 SEPARATOR is passed through to `org-format-outline-path'. It separates
10953 the different parts of the path and defaults to \"/\".
10954 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10955 (interactive "P")
10956 (let* (case-fold-search
10957 message-log-max ; Don't populate the *Messages* buffer
10958 (bfn (buffer-file-name (buffer-base-buffer)))
10959 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10960 res)
10961 (if current (setq path (append path
10962 (save-excursion
10963 (org-back-to-heading t)
10964 (if (looking-at org-complex-heading-regexp)
10965 (list (match-string 4)))))))
10966 (setq res
10967 (org-format-outline-path
10968 path
10969 (1- (frame-width))
10970 (and file bfn (concat (file-name-nondirectory bfn) separator))
10971 separator))
10972 (if just-return-string
10973 (org-no-properties res)
10974 (message "%s" res))))
10976 (defvar org-refile-history nil
10977 "History for refiling operations.")
10979 (defvar org-after-refile-insert-hook nil
10980 "Hook run after `org-refile' has inserted its stuff at the new location.
10981 Note that this is still *before* the stuff will be removed from
10982 the *old* location.")
10984 (defvar org-capture-last-stored-marker)
10985 (defvar org-refile-keep nil
10986 "Non-nil means `org-refile' will copy instead of refile.")
10988 (defun org-copy ()
10989 "Like `org-refile', but copy."
10990 (interactive)
10991 (let ((org-refile-keep t))
10992 (funcall 'org-refile nil nil nil "Copy")))
10994 (defun org-refile (&optional goto default-buffer rfloc msg)
10995 "Move the entry or entries at point to another heading.
10996 The list of target headings is compiled using the information in
10997 `org-refile-targets', which see.
10999 At the target location, the entry is filed as a subitem of the target
11000 heading. Depending on `org-reverse-note-order', the new subitem will
11001 either be the first or the last subitem.
11003 If there is an active region, all entries in that region will be moved.
11004 However, the region must fulfill the requirement that the first heading
11005 is the first one sets the top-level of the moved text - at most siblings
11006 below it are allowed.
11008 With prefix arg GOTO, the command will only visit the target location
11009 and not actually move anything.
11011 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11012 go to the location where the last refiling operation has put the subtree.
11013 With a prefix argument of `2', refile to the running clock.
11015 RFLOC can be a refile location obtained in a different way.
11017 MSG is a string to replace \"Refile\" in the default prompt with
11018 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11020 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11022 If you are using target caching (see `org-refile-use-cache'),
11023 you have to clear the target cache in order to find new targets.
11024 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11025 prefix argument (`C-u C-u C-u C-c C-w')."
11027 (interactive "P")
11028 (if (member goto '(0 (64)))
11029 (org-refile-cache-clear)
11030 (let* ((actionmsg (or msg "Refile"))
11031 (cbuf (current-buffer))
11032 (regionp (org-region-active-p))
11033 (region-start (and regionp (region-beginning)))
11034 (region-end (and regionp (region-end)))
11035 (region-length (and regionp (- region-end region-start)))
11036 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11037 pos it nbuf file re level reversed)
11038 (setq last-command nil)
11039 (when regionp
11040 (goto-char region-start)
11041 (or (bolp) (goto-char (point-at-bol)))
11042 (setq region-start (point))
11043 (unless (or (org-kill-is-subtree-p
11044 (buffer-substring region-start region-end))
11045 (prog1 org-refile-active-region-within-subtree
11046 (org-toggle-heading)))
11047 (error "The region is not a (sequence of) subtree(s)")))
11048 (if (equal goto '(16))
11049 (org-refile-goto-last-stored)
11050 (when (or
11051 (and (equal goto 2)
11052 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11053 (prog1
11054 (setq it (list (or org-clock-heading "running clock")
11055 (buffer-file-name
11056 (marker-buffer org-clock-hd-marker))
11058 (marker-position org-clock-hd-marker)))
11059 (setq goto nil)))
11060 (setq it (or rfloc
11061 (let (heading-text)
11062 (save-excursion
11063 (unless goto
11064 (org-back-to-heading t)
11065 (setq heading-text
11066 (nth 4 (org-heading-components))))
11068 (org-refile-get-location
11069 (cond (goto "Goto")
11070 (regionp (concat actionmsg " region to"))
11071 (t (concat actionmsg " subtree \""
11072 heading-text "\" to")))
11073 default-buffer
11074 (and (not (equal '(4) goto))
11075 org-refile-allow-creating-parent-nodes)
11076 goto))))))
11077 (setq file (nth 1 it)
11078 re (nth 2 it)
11079 pos (nth 3 it))
11080 (if (and (not goto)
11082 (equal (buffer-file-name) file)
11083 (if regionp
11084 (and (>= pos region-start)
11085 (<= pos region-end))
11086 (and (>= pos (point))
11087 (< pos (save-excursion
11088 (org-end-of-subtree t t))))))
11089 (error "Cannot refile to position inside the tree or region"))
11091 (setq nbuf (or (find-buffer-visiting file)
11092 (find-file-noselect file)))
11093 (if goto
11094 (progn
11095 (org-pop-to-buffer-same-window nbuf)
11096 (goto-char pos)
11097 (org-show-context 'org-goto))
11098 (if regionp
11099 (progn
11100 (org-kill-new (buffer-substring region-start region-end))
11101 (org-save-markers-in-region region-start region-end))
11102 (org-copy-subtree 1 nil t))
11103 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11104 (find-file-noselect file)))
11105 (setq reversed (org-notes-order-reversed-p))
11106 (save-excursion
11107 (save-restriction
11108 (widen)
11109 (if pos
11110 (progn
11111 (goto-char pos)
11112 (looking-at org-outline-regexp)
11113 (setq level (org-get-valid-level (funcall outline-level) 1))
11114 (goto-char
11115 (if reversed
11116 (or (outline-next-heading) (point-max))
11117 (or (save-excursion (org-get-next-sibling))
11118 (org-end-of-subtree t t)
11119 (point-max)))))
11120 (setq level 1)
11121 (if (not reversed)
11122 (goto-char (point-max))
11123 (goto-char (point-min))
11124 (or (outline-next-heading) (goto-char (point-max)))))
11125 (if (not (bolp)) (newline))
11126 (org-paste-subtree level)
11127 (when org-log-refile
11128 (org-add-log-setup 'refile nil nil 'findpos
11129 org-log-refile)
11130 (unless (eq org-log-refile 'note)
11131 (save-excursion (org-add-log-note))))
11132 (and org-auto-align-tags
11133 (let ((org-loop-over-headlines-in-active-region nil))
11134 (org-set-tags nil t)))
11135 (with-demoted-errors
11136 (bookmark-set "org-refile-last-stored"))
11137 ;; If we are refiling for capture, make sure that the
11138 ;; last-capture pointers point here
11139 (when (org-bound-and-true-p org-refile-for-capture)
11140 (with-demoted-errors
11141 (bookmark-set "org-capture-last-stored-marker"))
11142 (move-marker org-capture-last-stored-marker (point)))
11143 (if (fboundp 'deactivate-mark) (deactivate-mark))
11144 (run-hooks 'org-after-refile-insert-hook))))
11145 (unless org-refile-keep
11146 (if regionp
11147 (delete-region (point) (+ (point) region-length))
11148 (org-cut-subtree)))
11149 (when (featurep 'org-inlinetask)
11150 (org-inlinetask-remove-END-maybe))
11151 (setq org-markers-to-move nil)
11152 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11154 (defun org-refile-goto-last-stored ()
11155 "Go to the location where the last refile was stored."
11156 (interactive)
11157 (bookmark-jump "org-refile-last-stored")
11158 (message "This is the location of the last refile"))
11160 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11161 no-exclude)
11162 "Prompt the user for a refile location, using PROMPT.
11163 PROMPT should not be suffixed with a colon and a space, because
11164 this function appends the default value from
11165 `org-refile-history' automatically, if that is not empty.
11166 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11167 this is used for the GOTO interface."
11168 (let ((org-refile-targets org-refile-targets)
11169 (org-refile-use-outline-path org-refile-use-outline-path)
11170 excluded-entries)
11171 (when (and (derived-mode-p 'org-mode)
11172 (not org-refile-use-cache)
11173 (not no-exclude))
11174 (org-map-tree
11175 (lambda()
11176 (setq excluded-entries
11177 (append excluded-entries (list (org-get-heading t t)))))))
11178 (setq org-refile-target-table
11179 (org-refile-get-targets default-buffer excluded-entries)))
11180 (unless org-refile-target-table
11181 (error "No refile targets"))
11182 (let* ((cbuf (current-buffer))
11183 (partial-completion-mode nil)
11184 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11185 (cfunc (if (and org-refile-use-outline-path
11186 org-outline-path-complete-in-steps)
11187 'org-olpath-completing-read
11188 'org-icompleting-read))
11189 (extra (if org-refile-use-outline-path "/" ""))
11190 (cbnex (concat (buffer-name) extra))
11191 (filename (and cfn (expand-file-name cfn)))
11192 (tbl (mapcar
11193 (lambda (x)
11194 (if (and (not (member org-refile-use-outline-path
11195 '(file full-file-path)))
11196 (not (equal filename (nth 1 x))))
11197 (cons (concat (car x) extra " ("
11198 (file-name-nondirectory (nth 1 x)) ")")
11199 (cdr x))
11200 (cons (concat (car x) extra) (cdr x))))
11201 org-refile-target-table))
11202 (completion-ignore-case t)
11203 cdef
11204 (prompt (concat prompt
11205 (or (and (car org-refile-history)
11206 (concat " (default " (car org-refile-history) ")"))
11207 (and (assoc cbnex tbl) (setq cdef cbnex)
11208 (concat " (default " cbnex ")"))) ": "))
11209 pa answ parent-target child parent old-hist)
11210 (setq old-hist org-refile-history)
11211 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11212 nil 'org-refile-history (or cdef (car org-refile-history))))
11213 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11214 (org-refile-check-position pa)
11215 (if pa
11216 (progn
11217 (when (or (not org-refile-history)
11218 (not (eq old-hist org-refile-history))
11219 (not (equal (car pa) (car org-refile-history))))
11220 (setq org-refile-history
11221 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11222 org-refile-history
11223 (cdr org-refile-history))))
11224 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11225 (pop org-refile-history)))
11227 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11228 (progn
11229 (setq parent (match-string 1 answ)
11230 child (match-string 2 answ))
11231 (setq parent-target (or (assoc parent tbl)
11232 (assoc (concat parent "/") tbl)))
11233 (when (and parent-target
11234 (or (eq new-nodes t)
11235 (and (eq new-nodes 'confirm)
11236 (y-or-n-p (format "Create new node \"%s\"? "
11237 child)))))
11238 (org-refile-new-child parent-target child)))
11239 (error "Invalid target location")))))
11241 (declare-function org-string-nw-p "org-macs" (s))
11242 (defun org-refile-check-position (refile-pointer)
11243 "Check if the refile pointer matches the headline to which it points."
11244 (let* ((file (nth 1 refile-pointer))
11245 (re (nth 2 refile-pointer))
11246 (pos (nth 3 refile-pointer))
11247 buffer)
11248 (if (and (not (markerp pos)) (not file))
11249 (error "Please save the buffer to a file before refiling")
11250 (when (org-string-nw-p re)
11251 (setq buffer (if (markerp pos)
11252 (marker-buffer pos)
11253 (or (find-buffer-visiting file)
11254 (find-file-noselect file))))
11255 (with-current-buffer buffer
11256 (save-excursion
11257 (save-restriction
11258 (widen)
11259 (goto-char pos)
11260 (beginning-of-line 1)
11261 (unless (org-looking-at-p re)
11262 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11264 (defun org-refile-new-child (parent-target child)
11265 "Use refile target PARENT-TARGET to add new CHILD below it."
11266 (unless parent-target
11267 (error "Cannot find parent for new node"))
11268 (let ((file (nth 1 parent-target))
11269 (pos (nth 3 parent-target))
11270 level)
11271 (with-current-buffer (or (find-buffer-visiting file)
11272 (find-file-noselect file))
11273 (save-excursion
11274 (save-restriction
11275 (widen)
11276 (if pos
11277 (goto-char pos)
11278 (goto-char (point-max))
11279 (if (not (bolp)) (newline)))
11280 (when (looking-at org-outline-regexp)
11281 (setq level (funcall outline-level))
11282 (org-end-of-subtree t t))
11283 (org-back-over-empty-lines)
11284 (insert "\n" (make-string
11285 (if pos (org-get-valid-level level 1) 1) ?*)
11286 " " child "\n")
11287 (beginning-of-line 0)
11288 (list (concat (car parent-target) "/" child) file "" (point)))))))
11290 (defun org-olpath-completing-read (prompt collection &rest args)
11291 "Read an outline path like a file name."
11292 (let ((thetable collection)
11293 (org-completion-use-ido nil) ; does not work with ido.
11294 (org-completion-use-iswitchb nil)) ; or iswitchb
11295 (apply
11296 'org-icompleting-read prompt
11297 (lambda (string predicate &optional flag)
11298 (let (rtn r f (l (length string)))
11299 (cond
11300 ((eq flag nil)
11301 ;; try completion
11302 (try-completion string thetable))
11303 ((eq flag t)
11304 ;; all-completions
11305 (setq rtn (all-completions string thetable predicate))
11306 (mapcar
11307 (lambda (x)
11308 (setq r (substring x l))
11309 (if (string-match " ([^)]*)$" x)
11310 (setq f (match-string 0 x))
11311 (setq f ""))
11312 (if (string-match "/" r)
11313 (concat string (substring r 0 (match-end 0)) f)
11315 rtn))
11316 ((eq flag 'lambda)
11317 ;; exact match?
11318 (assoc string thetable)))))
11319 args)))
11321 ;;;; Dynamic blocks
11323 (defun org-find-dblock (name)
11324 "Find the first dynamic block with name NAME in the buffer.
11325 If not found, stay at current position and return nil."
11326 (let ((case-fold-search t) pos)
11327 (save-excursion
11328 (goto-char (point-min))
11329 (setq pos (and (re-search-forward
11330 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11331 (match-beginning 0))))
11332 (if pos (goto-char pos))
11333 pos))
11335 (defconst org-dblock-start-re
11336 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11337 "Matches the start line of a dynamic block, with parameters.")
11339 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11340 "Matches the end of a dynamic block.")
11342 (defun org-create-dblock (plist)
11343 "Create a dynamic block section, with parameters taken from PLIST.
11344 PLIST must contain a :name entry which is used as name of the block."
11345 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11346 (end-of-line 1)
11347 (newline))
11348 (let ((col (current-column))
11349 (name (plist-get plist :name)))
11350 (insert "#+BEGIN: " name)
11351 (while plist
11352 (if (eq (car plist) :name)
11353 (setq plist (cddr plist))
11354 (insert " " (prin1-to-string (pop plist)))))
11355 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11356 (beginning-of-line -2)))
11358 (defun org-prepare-dblock ()
11359 "Prepare dynamic block for refresh.
11360 This empties the block, puts the cursor at the insert position and returns
11361 the property list including an extra property :name with the block name."
11362 (unless (looking-at org-dblock-start-re)
11363 (error "Not at a dynamic block"))
11364 (let* ((begdel (1+ (match-end 0)))
11365 (name (org-no-properties (match-string 1)))
11366 (params (append (list :name name)
11367 (read (concat "(" (match-string 3) ")")))))
11368 (save-excursion
11369 (beginning-of-line 1)
11370 (skip-chars-forward " \t")
11371 (setq params (plist-put params :indentation-column (current-column))))
11372 (unless (re-search-forward org-dblock-end-re nil t)
11373 (error "Dynamic block not terminated"))
11374 (setq params
11375 (append params
11376 (list :content (buffer-substring
11377 begdel (match-beginning 0)))))
11378 (delete-region begdel (match-beginning 0))
11379 (goto-char begdel)
11380 (open-line 1)
11381 params))
11383 (defun org-map-dblocks (&optional command)
11384 "Apply COMMAND to all dynamic blocks in the current buffer.
11385 If COMMAND is not given, use `org-update-dblock'."
11386 (let ((cmd (or command 'org-update-dblock)))
11387 (save-excursion
11388 (goto-char (point-min))
11389 (while (re-search-forward org-dblock-start-re nil t)
11390 (goto-char (match-beginning 0))
11391 (save-excursion
11392 (condition-case nil
11393 (funcall cmd)
11394 (error (message "Error during update of dynamic block"))))
11395 (unless (re-search-forward org-dblock-end-re nil t)
11396 (error "Dynamic block not terminated"))))))
11398 (defun org-dblock-update (&optional arg)
11399 "User command for updating dynamic blocks.
11400 Update the dynamic block at point. With prefix ARG, update all dynamic
11401 blocks in the buffer."
11402 (interactive "P")
11403 (if arg
11404 (org-update-all-dblocks)
11405 (or (looking-at org-dblock-start-re)
11406 (org-beginning-of-dblock))
11407 (org-update-dblock)))
11409 (defun org-update-dblock ()
11410 "Update the dynamic block at point.
11411 This means to empty the block, parse for parameters and then call
11412 the correct writing function."
11413 (interactive)
11414 (save-window-excursion
11415 (let* ((pos (point))
11416 (line (org-current-line))
11417 (params (org-prepare-dblock))
11418 (name (plist-get params :name))
11419 (indent (plist-get params :indentation-column))
11420 (cmd (intern (concat "org-dblock-write:" name))))
11421 (message "Updating dynamic block `%s' at line %d..." name line)
11422 (funcall cmd params)
11423 (message "Updating dynamic block `%s' at line %d...done" name line)
11424 (goto-char pos)
11425 (when (and indent (> indent 0))
11426 (setq indent (make-string indent ?\ ))
11427 (save-excursion
11428 (org-beginning-of-dblock)
11429 (forward-line 1)
11430 (while (not (looking-at org-dblock-end-re))
11431 (insert indent)
11432 (beginning-of-line 2))
11433 (when (looking-at org-dblock-end-re)
11434 (and (looking-at "[ \t]+")
11435 (replace-match ""))
11436 (insert indent)))))))
11438 (defun org-beginning-of-dblock ()
11439 "Find the beginning of the dynamic block at point.
11440 Error if there is no such block at point."
11441 (let ((pos (point))
11442 beg)
11443 (end-of-line 1)
11444 (if (and (re-search-backward org-dblock-start-re nil t)
11445 (setq beg (match-beginning 0))
11446 (re-search-forward org-dblock-end-re nil t)
11447 (> (match-end 0) pos))
11448 (goto-char beg)
11449 (goto-char pos)
11450 (error "Not in a dynamic block"))))
11452 (defun org-update-all-dblocks ()
11453 "Update all dynamic blocks in the buffer.
11454 This function can be used in a hook."
11455 (interactive)
11456 (when (derived-mode-p 'org-mode)
11457 (org-map-dblocks 'org-update-dblock)))
11460 ;;;; Completion
11462 (defconst org-additional-option-like-keywords
11463 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11464 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11465 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11466 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11467 "BEGIN:" "END:"
11468 "ORGTBL" "TBLFM:" "TBLNAME:"
11469 "BEGIN_EXAMPLE" "END_EXAMPLE"
11470 "BEGIN_VERBATIM" "END_VERBATIM"
11471 "BEGIN_QUOTE" "END_QUOTE"
11472 "BEGIN_VERSE" "END_VERSE"
11473 "BEGIN_CENTER" "END_CENTER"
11474 "BEGIN_SRC" "END_SRC"
11475 "BEGIN_RESULT" "END_RESULT"
11476 "BEGIN_lstlisting" "END_lstlisting"
11477 "NAME:" "RESULTS:"
11478 "HEADER:" "HEADERS:"
11479 "COLUMNS:" "PROPERTY:"
11480 "CAPTION:" "LABEL:"
11481 "SETUPFILE:"
11482 "INCLUDE:" "INDEX:"
11483 "BIND:"
11484 "MACRO:"))
11486 (defconst org-options-keywords
11487 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11488 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11489 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11490 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11491 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11492 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11493 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11495 (defconst org-additional-option-like-keywords-for-flyspell
11496 (delete-dups
11497 (split-string
11498 (mapconcat (lambda(k)
11499 (replace-regexp-in-string
11500 "_\\|:" " "
11501 (concat k " " (downcase k) " " (upcase k))))
11502 (append org-options-keywords org-additional-option-like-keywords)
11503 " ")
11504 " +" t)))
11506 (defcustom org-structure-template-alist
11507 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11508 "<src lang=\"?\">\n\n</src>")
11509 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11510 "<example>\n?\n</example>")
11511 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11512 "<quote>\n?\n</quote>")
11513 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11514 "<verse>\n?\n</verse>")
11515 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11516 "<verbatim>\n?\n</verbatim>")
11517 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11518 "<center>\n?\n</center>")
11519 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11520 "<literal style=\"latex\">\n?\n</literal>")
11521 ("L" "#+LaTeX: "
11522 "<literal style=\"latex\">?</literal>")
11523 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11524 "<literal style=\"html\">\n?\n</literal>")
11525 ("H" "#+HTML: "
11526 "<literal style=\"html\">?</literal>")
11527 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11528 ("A" "#+ASCII: ")
11529 ("i" "#+INDEX: ?"
11530 "#+INDEX: ?")
11531 ("I" "#+INCLUDE: %file ?"
11532 "<include file=%file markup=\"?\">"))
11533 "Structure completion elements.
11534 This is a list of abbreviation keys and values. The value gets inserted
11535 if you type `<' followed by the key and then press the completion key,
11536 usually `M-TAB'. %file will be replaced by a file name after prompting
11537 for the file using completion. The cursor will be placed at the position
11538 of the `?` in the template.
11539 There are two templates for each key, the first uses the original Org syntax,
11540 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11541 the default when the /org-mtags.el/ module has been loaded. See also the
11542 variable `org-mtags-prefer-muse-templates'."
11543 :group 'org-completion
11544 :type '(repeat
11545 (string :tag "Key")
11546 (string :tag "Template")
11547 (string :tag "Muse Template")))
11549 (defun org-try-structure-completion ()
11550 "Try to complete a structure template before point.
11551 This looks for strings like \"<e\" on an otherwise empty line and
11552 expands them."
11553 (let ((l (buffer-substring (point-at-bol) (point)))
11555 (when (and (looking-at "[ \t]*$")
11556 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11557 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11558 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11559 (match-beginning 1)) a)
11560 t)))
11562 (defun org-complete-expand-structure-template (start cell)
11563 "Expand a structure template."
11564 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11565 (rpl (nth (if musep 2 1) cell))
11566 (ind ""))
11567 (delete-region start (point))
11568 (when (string-match "\\`#\\+" rpl)
11569 (cond
11570 ((bolp))
11571 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11572 (setq ind (buffer-substring (point-at-bol) (point))))
11573 (t (newline))))
11574 (setq start (point))
11575 (if (string-match "%file" rpl)
11576 (setq rpl (replace-match
11577 (concat
11578 "\""
11579 (save-match-data
11580 (abbreviate-file-name (read-file-name "Include file: ")))
11581 "\"")
11582 t t rpl)))
11583 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11584 (concat "\n" ind)))
11585 (insert rpl)
11586 (if (re-search-backward "\\?" start t) (delete-char 1))))
11588 ;;;; TODO, DEADLINE, Comments
11590 (defun org-toggle-comment ()
11591 "Change the COMMENT state of an entry."
11592 (interactive)
11593 (save-excursion
11594 (org-back-to-heading)
11595 (let (case-fold-search)
11596 (cond
11597 ((looking-at (format org-heading-keyword-regexp-format
11598 org-comment-string))
11599 (goto-char (match-end 1))
11600 (looking-at (concat " +" org-comment-string))
11601 (replace-match "" t t)
11602 (when (eolp) (insert " ")))
11603 ((looking-at org-outline-regexp)
11604 (goto-char (match-end 0))
11605 (insert org-comment-string " "))))))
11607 (defvar org-last-todo-state-is-todo nil
11608 "This is non-nil when the last TODO state change led to a TODO state.
11609 If the last change removed the TODO tag or switched to DONE, then
11610 this is nil.")
11612 (defvar org-setting-tags nil) ; dynamically skipped
11614 (defvar org-todo-setup-filter-hook nil
11615 "Hook for functions that pre-filter todo specs.
11616 Each function takes a todo spec and returns either nil or the spec
11617 transformed into canonical form." )
11619 (defvar org-todo-get-default-hook nil
11620 "Hook for functions that get a default item for todo.
11621 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11622 nil or a string to be used for the todo mark." )
11624 (defvar org-agenda-headline-snapshot-before-repeat)
11626 (defun org-current-effective-time ()
11627 "Return current time adjusted for `org-extend-today-until' variable."
11628 (let* ((ct (org-current-time))
11629 (dct (decode-time ct))
11630 (ct1
11631 (cond
11632 (org-use-last-clock-out-time-as-effective-time
11633 (or (org-clock-get-last-clock-out-time) ct))
11634 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11635 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11636 (t ct))))
11637 ct1))
11639 (defun org-todo-yesterday (&optional arg)
11640 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11641 (interactive "P")
11642 (if (eq major-mode 'org-agenda-mode)
11643 (apply 'org-agenda-todo-yesterday arg)
11644 (let* ((hour (third (decode-time
11645 (org-current-time))))
11646 (org-extend-today-until (1+ hour)))
11647 (org-todo arg))))
11649 (defvar org-block-entry-blocking ""
11650 "First entry preventing the TODO state change.")
11652 (defun org-todo (&optional arg)
11653 "Change the TODO state of an item.
11654 The state of an item is given by a keyword at the start of the heading,
11655 like
11656 *** TODO Write paper
11657 *** DONE Call mom
11659 The different keywords are specified in the variable `org-todo-keywords'.
11660 By default the available states are \"TODO\" and \"DONE\".
11661 So for this example: when the item starts with TODO, it is changed to DONE.
11662 When it starts with DONE, the DONE is removed. And when neither TODO nor
11663 DONE are present, add TODO at the beginning of the heading.
11665 With \\[universal-argument] prefix arg, use completion to determine the new \
11666 state.
11667 With numeric prefix arg, switch to that state.
11668 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11669 keywords (nextset).
11670 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11671 With a numeric prefix arg of 0, inhibit note taking for the change.
11673 For calling through lisp, arg is also interpreted in the following way:
11674 'none -> empty state
11675 \"\"(empty string) -> switch to empty state
11676 'done -> switch to DONE
11677 'nextset -> switch to the next set of keywords
11678 'previousset -> switch to the previous set of keywords
11679 \"WAITING\" -> switch to the specified keyword, but only if it
11680 really is a member of `org-todo-keywords'."
11681 (interactive "P")
11682 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11683 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11684 'region-start-level 'region))
11685 org-loop-over-headlines-in-active-region)
11686 (org-map-entries
11687 `(org-todo ,arg)
11688 org-loop-over-headlines-in-active-region
11689 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11690 (if (equal arg '(16)) (setq arg 'nextset))
11691 (let ((org-blocker-hook org-blocker-hook)
11692 commentp
11693 case-fold-search)
11694 (when (equal arg '(64))
11695 (setq arg nil org-blocker-hook nil))
11696 (when (and org-blocker-hook
11697 (or org-inhibit-blocking
11698 (org-entry-get nil "NOBLOCKING")))
11699 (setq org-blocker-hook nil))
11700 (save-excursion
11701 (catch 'exit
11702 (org-back-to-heading t)
11703 (when (looking-at (concat "^\\*+ " org-comment-string))
11704 (org-toggle-comment)
11705 (setq commentp t))
11706 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11707 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11708 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11709 (let* ((match-data (match-data))
11710 (startpos (point-at-bol))
11711 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11712 (org-log-done org-log-done)
11713 (org-log-repeat org-log-repeat)
11714 (org-todo-log-states org-todo-log-states)
11715 (org-inhibit-logging
11716 (if (equal arg 0)
11717 (progn (setq arg nil) 'note) org-inhibit-logging))
11718 (this (match-string 1))
11719 (hl-pos (match-beginning 0))
11720 (head (org-get-todo-sequence-head this))
11721 (ass (assoc head org-todo-kwd-alist))
11722 (interpret (nth 1 ass))
11723 (done-word (nth 3 ass))
11724 (final-done-word (nth 4 ass))
11725 (org-last-state (or this ""))
11726 (completion-ignore-case t)
11727 (member (member this org-todo-keywords-1))
11728 (tail (cdr member))
11729 (org-state (cond
11730 ((and org-todo-key-trigger
11731 (or (and (equal arg '(4))
11732 (eq org-use-fast-todo-selection 'prefix))
11733 (and (not arg) org-use-fast-todo-selection
11734 (not (eq org-use-fast-todo-selection
11735 'prefix)))))
11736 ;; Use fast selection
11737 (org-fast-todo-selection))
11738 ((and (equal arg '(4))
11739 (or (not org-use-fast-todo-selection)
11740 (not org-todo-key-trigger)))
11741 ;; Read a state with completion
11742 (org-icompleting-read
11743 "State: " (mapcar (lambda(x) (list x))
11744 org-todo-keywords-1)
11745 nil t))
11746 ((eq arg 'right)
11747 (if this
11748 (if tail (car tail) nil)
11749 (car org-todo-keywords-1)))
11750 ((eq arg 'left)
11751 (if (equal member org-todo-keywords-1)
11753 (if this
11754 (nth (- (length org-todo-keywords-1)
11755 (length tail) 2)
11756 org-todo-keywords-1)
11757 (org-last org-todo-keywords-1))))
11758 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11759 (setq arg nil))) ; hack to fall back to cycling
11760 (arg
11761 ;; user or caller requests a specific state
11762 (cond
11763 ((equal arg "") nil)
11764 ((eq arg 'none) nil)
11765 ((eq arg 'done) (or done-word (car org-done-keywords)))
11766 ((eq arg 'nextset)
11767 (or (car (cdr (member head org-todo-heads)))
11768 (car org-todo-heads)))
11769 ((eq arg 'previousset)
11770 (let ((org-todo-heads (reverse org-todo-heads)))
11771 (or (car (cdr (member head org-todo-heads)))
11772 (car org-todo-heads))))
11773 ((car (member arg org-todo-keywords-1)))
11774 ((stringp arg)
11775 (error "State `%s' not valid in this file" arg))
11776 ((nth (1- (prefix-numeric-value arg))
11777 org-todo-keywords-1))))
11778 ((null member) (or head (car org-todo-keywords-1)))
11779 ((equal this final-done-word) nil) ;; -> make empty
11780 ((null tail) nil) ;; -> first entry
11781 ((memq interpret '(type priority))
11782 (if (eq this-command last-command)
11783 (car tail)
11784 (if (> (length tail) 0)
11785 (or done-word (car org-done-keywords))
11786 nil)))
11788 (car tail))))
11789 (org-state (or
11790 (run-hook-with-args-until-success
11791 'org-todo-get-default-hook org-state org-last-state)
11792 org-state))
11793 (next (if org-state (concat " " org-state " ") " "))
11794 (change-plist (list :type 'todo-state-change :from this :to org-state
11795 :position startpos))
11796 dolog now-done-p)
11797 (when org-blocker-hook
11798 (setq org-last-todo-state-is-todo
11799 (not (member this org-done-keywords)))
11800 (unless (save-excursion
11801 (save-match-data
11802 (org-with-wide-buffer
11803 (run-hook-with-args-until-failure
11804 'org-blocker-hook change-plist))))
11805 (if (org-called-interactively-p 'interactive)
11806 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11807 this org-state org-block-entry-blocking)
11808 ;; fail silently
11809 (message "TODO state change from %s to %s blocked (by \"%s\")"
11810 this org-state org-block-entry-blocking)
11811 (throw 'exit nil))))
11812 (store-match-data match-data)
11813 (replace-match next t t)
11814 (unless (pos-visible-in-window-p hl-pos)
11815 (message "TODO state changed to %s" (org-trim next)))
11816 (unless head
11817 (setq head (org-get-todo-sequence-head org-state)
11818 ass (assoc head org-todo-kwd-alist)
11819 interpret (nth 1 ass)
11820 done-word (nth 3 ass)
11821 final-done-word (nth 4 ass)))
11822 (when (memq arg '(nextset previousset))
11823 (message "Keyword-Set %d/%d: %s"
11824 (- (length org-todo-sets) -1
11825 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11826 (length org-todo-sets)
11827 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11828 (setq org-last-todo-state-is-todo
11829 (not (member org-state org-done-keywords)))
11830 (setq now-done-p (and (member org-state org-done-keywords)
11831 (not (member this org-done-keywords))))
11832 (and logging (org-local-logging logging))
11833 (when (and (or org-todo-log-states org-log-done)
11834 (not (eq org-inhibit-logging t))
11835 (not (memq arg '(nextset previousset))))
11836 ;; we need to look at recording a time and note
11837 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11838 (nth 2 (assoc this org-todo-log-states))))
11839 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11840 (setq dolog 'time))
11841 (when (and org-state
11842 (member org-state org-not-done-keywords)
11843 (not (member this org-not-done-keywords)))
11844 ;; This is now a todo state and was not one before
11845 ;; If there was a CLOSED time stamp, get rid of it.
11846 (org-add-planning-info nil nil 'closed))
11847 (when (and now-done-p org-log-done)
11848 ;; It is now done, and it was not done before
11849 (org-add-planning-info 'closed (org-current-effective-time))
11850 (if (and (not dolog) (eq 'note org-log-done))
11851 (org-add-log-setup 'done org-state this 'findpos 'note)))
11852 (when (and org-state dolog)
11853 ;; This is a non-nil state, and we need to log it
11854 (org-add-log-setup 'state org-state this 'findpos dolog)))
11855 ;; Fixup tag positioning
11856 (org-todo-trigger-tag-changes org-state)
11857 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11858 (when org-provide-todo-statistics
11859 (org-update-parent-todo-statistics))
11860 (run-hooks 'org-after-todo-state-change-hook)
11861 (if (and arg (not (member org-state org-done-keywords)))
11862 (setq head (org-get-todo-sequence-head org-state)))
11863 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11864 ;; Do we need to trigger a repeat?
11865 (when now-done-p
11866 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11867 ;; This is for the agenda, take a snapshot of the headline.
11868 (save-match-data
11869 (setq org-agenda-headline-snapshot-before-repeat
11870 (org-get-heading))))
11871 (org-auto-repeat-maybe org-state))
11872 ;; Fixup cursor location if close to the keyword
11873 (if (and (outline-on-heading-p)
11874 (not (bolp))
11875 (save-excursion (beginning-of-line 1)
11876 (looking-at org-todo-line-regexp))
11877 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11878 (progn
11879 (goto-char (or (match-end 2) (match-end 1)))
11880 (and (looking-at " ") (just-one-space))))
11881 (when org-trigger-hook
11882 (save-excursion
11883 (run-hook-with-args 'org-trigger-hook change-plist)))
11884 (when commentp (org-toggle-comment))))))))
11886 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11887 "Block turning an entry into a TODO, using the hierarchy.
11888 This checks whether the current task should be blocked from state
11889 changes. Such blocking occurs when:
11891 1. The task has children which are not all in a completed state.
11893 2. A task has a parent with the property :ORDERED:, and there
11894 are siblings prior to the current task with incomplete
11895 status.
11897 3. The parent of the task is blocked because it has siblings that should
11898 be done first, or is child of a block grandparent TODO entry."
11900 (if (not org-enforce-todo-dependencies)
11901 t ; if locally turned off don't block
11902 (catch 'dont-block
11903 ;; If this is not a todo state change, or if this entry is already DONE,
11904 ;; do not block
11905 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11906 (member (plist-get change-plist :from)
11907 (cons 'done org-done-keywords))
11908 (member (plist-get change-plist :to)
11909 (cons 'todo org-not-done-keywords))
11910 (not (plist-get change-plist :to)))
11911 (throw 'dont-block t))
11912 ;; If this task has children, and any are undone, it's blocked
11913 (save-excursion
11914 (org-back-to-heading t)
11915 (let ((this-level (funcall outline-level)))
11916 (outline-next-heading)
11917 (let ((child-level (funcall outline-level)))
11918 (while (and (not (eobp))
11919 (> child-level this-level))
11920 ;; this todo has children, check whether they are all
11921 ;; completed
11922 (if (and (not (org-entry-is-done-p))
11923 (org-entry-is-todo-p))
11924 (progn (setq org-block-entry-blocking (org-get-heading))
11925 (throw 'dont-block nil)))
11926 (outline-next-heading)
11927 (setq child-level (funcall outline-level))))))
11928 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11929 ;; any previous siblings are undone, it's blocked
11930 (save-excursion
11931 (org-back-to-heading t)
11932 (let* ((pos (point))
11933 (parent-pos (and (org-up-heading-safe) (point))))
11934 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11935 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11936 (forward-line 1)
11937 (re-search-forward org-not-done-heading-regexp pos t))
11938 (setq org-block-entry-blocking (match-string 0))
11939 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11940 ;; Search further up the hierarchy, to see if an ancestor is blocked
11941 (while t
11942 (goto-char parent-pos)
11943 (if (not (looking-at org-not-done-heading-regexp))
11944 (throw 'dont-block t)) ; do not block, parent is not a TODO
11945 (setq pos (point))
11946 (setq parent-pos (and (org-up-heading-safe) (point)))
11947 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11948 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11949 (forward-line 1)
11950 (re-search-forward org-not-done-heading-regexp pos t)
11951 (setq org-block-entry-blocking (org-get-heading)))
11952 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11954 (defcustom org-track-ordered-property-with-tag nil
11955 "Should the ORDERED property also be shown as a tag?
11956 The ORDERED property decides if an entry should require subtasks to be
11957 completed in sequence. Since a property is not very visible, setting
11958 this option means that toggling the ORDERED property with the command
11959 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11960 not relevant for the behavior, but it makes things more visible.
11962 Note that toggling the tag with tags commands will not change the property
11963 and therefore not influence behavior!
11965 This can be t, meaning the tag ORDERED should be used, It can also be a
11966 string to select a different tag for this task."
11967 :group 'org-todo
11968 :type '(choice
11969 (const :tag "No tracking" nil)
11970 (const :tag "Track with ORDERED tag" t)
11971 (string :tag "Use other tag")))
11973 (defun org-toggle-ordered-property ()
11974 "Toggle the ORDERED property of the current entry.
11975 For better visibility, you can track the value of this property with a tag.
11976 See variable `org-track-ordered-property-with-tag'."
11977 (interactive)
11978 (let* ((t1 org-track-ordered-property-with-tag)
11979 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11980 (save-excursion
11981 (org-back-to-heading)
11982 (if (org-entry-get nil "ORDERED")
11983 (progn
11984 (org-delete-property "ORDERED")
11985 (and tag (org-toggle-tag tag 'off))
11986 (message "Subtasks can be completed in arbitrary order"))
11987 (org-entry-put nil "ORDERED" "t")
11988 (and tag (org-toggle-tag tag 'on))
11989 (message "Subtasks must be completed in sequence")))))
11991 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11992 (defun org-block-todo-from-checkboxes (change-plist)
11993 "Block turning an entry into a TODO, using checkboxes.
11994 This checks whether the current task should be blocked from state
11995 changes because there are unchecked boxes in this entry."
11996 (if (not org-enforce-todo-checkbox-dependencies)
11997 t ; if locally turned off don't block
11998 (catch 'dont-block
11999 ;; If this is not a todo state change, or if this entry is already DONE,
12000 ;; do not block
12001 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12002 (member (plist-get change-plist :from)
12003 (cons 'done org-done-keywords))
12004 (member (plist-get change-plist :to)
12005 (cons 'todo org-not-done-keywords))
12006 (not (plist-get change-plist :to)))
12007 (throw 'dont-block t))
12008 ;; If this task has checkboxes that are not checked, it's blocked
12009 (save-excursion
12010 (org-back-to-heading t)
12011 (let ((beg (point)) end)
12012 (outline-next-heading)
12013 (setq end (point))
12014 (goto-char beg)
12015 (if (org-list-search-forward
12016 (concat (org-item-beginning-re)
12017 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12018 "\\[[- ]\\]")
12019 end t)
12020 (progn
12021 (if (boundp 'org-blocked-by-checkboxes)
12022 (setq org-blocked-by-checkboxes t))
12023 (throw 'dont-block nil)))))
12024 t))) ; do not block
12026 (defun org-entry-blocked-p ()
12027 "Is the current entry blocked?"
12028 (org-with-buffer-modified-unmodified
12029 (if (org-entry-get nil "NOBLOCKING")
12030 nil ;; Never block this entry
12031 (not
12032 (run-hook-with-args-until-failure
12033 'org-blocker-hook
12034 (list :type 'todo-state-change
12035 :position (point)
12036 :from 'todo
12037 :to 'done))))))
12039 (defun org-update-statistics-cookies (all)
12040 "Update the statistics cookie, either from TODO or from checkboxes.
12041 This should be called with the cursor in a line with a statistics cookie."
12042 (interactive "P")
12043 (if all
12044 (progn
12045 (org-update-checkbox-count 'all)
12046 (org-map-entries 'org-update-parent-todo-statistics))
12047 (if (not (org-at-heading-p))
12048 (org-update-checkbox-count)
12049 (let ((pos (point-marker))
12050 end l1 l2)
12051 (ignore-errors (org-back-to-heading t))
12052 (if (not (org-at-heading-p))
12053 (org-update-checkbox-count)
12054 (setq l1 (org-outline-level))
12055 (setq end (save-excursion
12056 (outline-next-heading)
12057 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12058 (point)))
12059 (if (and (save-excursion
12060 (re-search-forward
12061 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12062 (not (save-excursion (re-search-forward
12063 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12064 (org-update-checkbox-count)
12065 (if (and l2 (> l2 l1))
12066 (progn
12067 (goto-char end)
12068 (org-update-parent-todo-statistics))
12069 (goto-char pos)
12070 (beginning-of-line 1)
12071 (while (re-search-forward
12072 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12073 (point-at-eol) t)
12074 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12075 (goto-char pos)
12076 (move-marker pos nil)))))
12078 (defvar org-entry-property-inherited-from) ;; defined below
12079 (defun org-update-parent-todo-statistics ()
12080 "Update any statistics cookie in the parent of the current headline.
12081 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12082 the entire subtree and this will travel up the hierarchy and update
12083 statistics everywhere."
12084 (let* ((prop (save-excursion (org-up-heading-safe)
12085 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12086 (recursive (or (not org-hierarchical-todo-statistics)
12087 (and prop (string-match "\\<recursive\\>" prop))))
12088 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12090 (first t)
12091 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12092 level ltoggle l1 new ndel
12093 (cnt-all 0) (cnt-done 0) is-percent kwd
12094 checkbox-beg ov ovs ove cookie-present)
12095 (catch 'exit
12096 (save-excursion
12097 (beginning-of-line 1)
12098 (setq ltoggle (funcall outline-level))
12099 ;; Three situations are to consider:
12101 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12102 ;; to the top-level ancestor on the headline;
12104 ;; 2. If parent has "recursive" property, repeat up to the
12105 ;; headline setting that property, taking inheritance into
12106 ;; account;
12108 ;; 3. Else, move up to direct parent and proceed only once.
12109 (while (and (setq level (org-up-heading-safe))
12110 (or recursive first)
12111 (>= (point) lim))
12112 (setq first nil cookie-present nil)
12113 (unless (and level
12114 (not (string-match
12115 "\\<checkbox\\>"
12116 (downcase (or (org-entry-get nil "COOKIE_DATA")
12117 "")))))
12118 (throw 'exit nil))
12119 (while (re-search-forward box-re (point-at-eol) t)
12120 (setq cnt-all 0 cnt-done 0 cookie-present t)
12121 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12122 (save-match-data
12123 (unless (outline-next-heading) (throw 'exit nil))
12124 (while (and (looking-at org-complex-heading-regexp)
12125 (> (setq l1 (length (match-string 1))) level))
12126 (setq kwd (and (or recursive (= l1 ltoggle))
12127 (match-string 2)))
12128 (if (or (eq org-provide-todo-statistics 'all-headlines)
12129 (and (listp org-provide-todo-statistics)
12130 (or (member kwd org-provide-todo-statistics)
12131 (member kwd org-done-keywords))))
12132 (setq cnt-all (1+ cnt-all))
12133 (if (eq org-provide-todo-statistics t)
12134 (and kwd (setq cnt-all (1+ cnt-all)))))
12135 (and (member kwd org-done-keywords)
12136 (setq cnt-done (1+ cnt-done)))
12137 (outline-next-heading)))
12138 (setq new
12139 (if is-percent
12140 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12141 (format "[%d/%d]" cnt-done cnt-all))
12142 ndel (- (match-end 0) checkbox-beg))
12143 ;; handle overlays when updating cookie from column view
12144 (when (setq ov (car (overlays-at checkbox-beg)))
12145 (setq ovs (overlay-start ov) ove (overlay-end ov))
12146 (delete-overlay ov))
12147 (goto-char checkbox-beg)
12148 (insert new)
12149 (delete-region (point) (+ (point) ndel))
12150 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12151 (when ov (move-overlay ov ovs ove)))
12152 (when cookie-present
12153 (run-hook-with-args 'org-after-todo-statistics-hook
12154 cnt-done (- cnt-all cnt-done))))))
12155 (run-hooks 'org-todo-statistics-hook)))
12157 (defvar org-after-todo-statistics-hook nil
12158 "Hook that is called after a TODO statistics cookie has been updated.
12159 Each function is called with two arguments: the number of not-done entries
12160 and the number of done entries.
12162 For example, the following function, when added to this hook, will switch
12163 an entry to DONE when all children are done, and back to TODO when new
12164 entries are set to a TODO status. Note that this hook is only called
12165 when there is a statistics cookie in the headline!
12167 (defun org-summary-todo (n-done n-not-done)
12168 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12169 (let (org-log-done org-log-states) ; turn off logging
12170 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12173 (defvar org-todo-statistics-hook nil
12174 "Hook that is run whenever Org thinks TODO statistics should be updated.
12175 This hook runs even if there is no statistics cookie present, in which case
12176 `org-after-todo-statistics-hook' would not run.")
12178 (defun org-todo-trigger-tag-changes (state)
12179 "Apply the changes defined in `org-todo-state-tags-triggers'."
12180 (let ((l org-todo-state-tags-triggers)
12181 changes)
12182 (when (or (not state) (equal state ""))
12183 (setq changes (append changes (cdr (assoc "" l)))))
12184 (when (and (stringp state) (> (length state) 0))
12185 (setq changes (append changes (cdr (assoc state l)))))
12186 (when (member state org-not-done-keywords)
12187 (setq changes (append changes (cdr (assoc 'todo l)))))
12188 (when (member state org-done-keywords)
12189 (setq changes (append changes (cdr (assoc 'done l)))))
12190 (dolist (c changes)
12191 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12193 (defun org-local-logging (value)
12194 "Get logging settings from a property VALUE."
12195 (let* (words w a)
12196 ;; directly set the variables, they are already local.
12197 (setq org-log-done nil
12198 org-log-repeat nil
12199 org-todo-log-states nil)
12200 (setq words (org-split-string value))
12201 (while (setq w (pop words))
12202 (cond
12203 ((setq a (assoc w org-startup-options))
12204 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12205 (set (nth 1 a) (nth 2 a))))
12206 ((setq a (org-extract-log-state-settings w))
12207 (and (member (car a) org-todo-keywords-1)
12208 (push a org-todo-log-states)))))))
12210 (defun org-get-todo-sequence-head (kwd)
12211 "Return the head of the TODO sequence to which KWD belongs.
12212 If KWD is not set, check if there is a text property remembering the
12213 right sequence."
12214 (let (p)
12215 (cond
12216 ((not kwd)
12217 (or (get-text-property (point-at-bol) 'org-todo-head)
12218 (progn
12219 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12220 nil (point-at-eol)))
12221 (get-text-property p 'org-todo-head))))
12222 ((not (member kwd org-todo-keywords-1))
12223 (car org-todo-keywords-1))
12224 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12226 (defun org-fast-todo-selection ()
12227 "Fast TODO keyword selection with single keys.
12228 Returns the new TODO keyword, or nil if no state change should occur."
12229 (let* ((fulltable org-todo-key-alist)
12230 (done-keywords org-done-keywords) ;; needed for the faces.
12231 (maxlen (apply 'max (mapcar
12232 (lambda (x)
12233 (if (stringp (car x)) (string-width (car x)) 0))
12234 fulltable)))
12235 (expert nil)
12236 (fwidth (+ maxlen 3 1 3))
12237 (ncol (/ (- (window-width) 4) fwidth))
12238 tg cnt e c tbl
12239 groups ingroup)
12240 (save-excursion
12241 (save-window-excursion
12242 (if expert
12243 (set-buffer (get-buffer-create " *Org todo*"))
12244 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12245 (erase-buffer)
12246 (org-set-local 'org-done-keywords done-keywords)
12247 (setq tbl fulltable cnt 0)
12248 (while (setq e (pop tbl))
12249 (cond
12250 ((equal e '(:startgroup))
12251 (push '() groups) (setq ingroup t)
12252 (when (not (= cnt 0))
12253 (setq cnt 0)
12254 (insert "\n"))
12255 (insert "{ "))
12256 ((equal e '(:endgroup))
12257 (setq ingroup nil cnt 0)
12258 (insert "}\n"))
12259 ((equal e '(:newline))
12260 (when (not (= cnt 0))
12261 (setq cnt 0)
12262 (insert "\n")
12263 (setq e (car tbl))
12264 (while (equal (car tbl) '(:newline))
12265 (insert "\n")
12266 (setq tbl (cdr tbl)))))
12268 (setq tg (car e) c (cdr e))
12269 (if ingroup (push tg (car groups)))
12270 (setq tg (org-add-props tg nil 'face
12271 (org-get-todo-face tg)))
12272 (if (and (= cnt 0) (not ingroup)) (insert " "))
12273 (insert "[" c "] " tg (make-string
12274 (- fwidth 4 (length tg)) ?\ ))
12275 (when (= (setq cnt (1+ cnt)) ncol)
12276 (insert "\n")
12277 (if ingroup (insert " "))
12278 (setq cnt 0)))))
12279 (insert "\n")
12280 (goto-char (point-min))
12281 (if (not expert) (org-fit-window-to-buffer))
12282 (message "[a-z..]:Set [SPC]:clear")
12283 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12284 (cond
12285 ((or (= c ?\C-g)
12286 (and (= c ?q) (not (rassoc c fulltable))))
12287 (setq quit-flag t))
12288 ((= c ?\ ) nil)
12289 ((setq e (rassoc c fulltable) tg (car e))
12291 (t (setq quit-flag t)))))))
12293 (defun org-entry-is-todo-p ()
12294 (member (org-get-todo-state) org-not-done-keywords))
12296 (defun org-entry-is-done-p ()
12297 (member (org-get-todo-state) org-done-keywords))
12299 (defun org-get-todo-state ()
12300 (save-excursion
12301 (org-back-to-heading t)
12302 (and (looking-at org-todo-line-regexp)
12303 (match-end 2)
12304 (match-string 2))))
12306 (defun org-at-date-range-p (&optional inactive-ok)
12307 "Is the cursor inside a date range?"
12308 (interactive)
12309 (save-excursion
12310 (catch 'exit
12311 (let ((pos (point)))
12312 (skip-chars-backward "^[<\r\n")
12313 (skip-chars-backward "<[")
12314 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12315 (>= (match-end 0) pos)
12316 (throw 'exit t))
12317 (skip-chars-backward "^<[\r\n")
12318 (skip-chars-backward "<[")
12319 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12320 (>= (match-end 0) pos)
12321 (throw 'exit t)))
12322 nil)))
12324 (defun org-get-repeat (&optional tagline)
12325 "Check if there is a deadline/schedule with repeater in this entry."
12326 (save-match-data
12327 (save-excursion
12328 (org-back-to-heading t)
12329 (and (re-search-forward (if tagline
12330 (concat tagline "\\s-*" org-repeat-re)
12331 org-repeat-re)
12332 (org-entry-end-position) t)
12333 (match-string-no-properties 1)))))
12335 (defvar org-last-changed-timestamp)
12336 (defvar org-last-inserted-timestamp)
12337 (defvar org-log-post-message)
12338 (defvar org-log-note-purpose)
12339 (defvar org-log-note-how)
12340 (defvar org-log-note-extra)
12341 (defun org-auto-repeat-maybe (done-word)
12342 "Check if the current headline contains a repeated deadline/schedule.
12343 If yes, set TODO state back to what it was and change the base date
12344 of repeating deadline/scheduled time stamps to new date.
12345 This function is run automatically after each state change to a DONE state."
12346 ;; last-state is dynamically scoped into this function
12347 (let* ((repeat (org-get-repeat))
12348 (aa (assoc org-last-state org-todo-kwd-alist))
12349 (interpret (nth 1 aa))
12350 (head (nth 2 aa))
12351 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12352 (msg "Entry repeats: ")
12353 (org-log-done nil)
12354 (org-todo-log-states nil)
12355 re type n what ts time to-state)
12356 (when repeat
12357 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12358 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12359 org-todo-repeat-to-state))
12360 (unless (and to-state (member to-state org-todo-keywords-1))
12361 (setq to-state (if (eq interpret 'type) org-last-state head)))
12362 (org-todo to-state)
12363 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12364 (org-entry-put nil "LAST_REPEAT" (format-time-string
12365 (org-time-stamp-format t t))))
12366 (when org-log-repeat
12367 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12368 (memq 'org-add-log-note post-command-hook))
12369 ;; OK, we are already setup for some record
12370 (if (eq org-log-repeat 'note)
12371 ;; make sure we take a note, not only a time stamp
12372 (setq org-log-note-how 'note))
12373 ;; Set up for taking a record
12374 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12375 org-last-state
12376 'findpos org-log-repeat)))
12377 (org-back-to-heading t)
12378 (org-add-planning-info nil nil 'closed)
12379 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12380 org-deadline-time-regexp "\\)\\|\\("
12381 org-ts-regexp "\\)"))
12382 (while (re-search-forward
12383 re (save-excursion (outline-next-heading) (point)) t)
12384 (setq type (if (match-end 1) org-scheduled-string
12385 (if (match-end 3) org-deadline-string "Plain:"))
12386 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12387 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12388 (setq n (string-to-number (match-string 2 ts))
12389 what (match-string 3 ts))
12390 (if (equal what "w") (setq n (* n 7) what "d"))
12391 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12392 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12393 ;; Preparation, see if we need to modify the start date for the change
12394 (when (match-end 1)
12395 (setq time (save-match-data (org-time-string-to-time ts)))
12396 (cond
12397 ((equal (match-string 1 ts) ".")
12398 ;; Shift starting date to today
12399 (org-timestamp-change
12400 (- (org-today) (time-to-days time))
12401 'day))
12402 ((equal (match-string 1 ts) "+")
12403 (let ((nshiftmax 10) (nshift 0))
12404 (while (or (= nshift 0)
12405 (<= (time-to-days time)
12406 (time-to-days (current-time))))
12407 (when (= (incf nshift) nshiftmax)
12408 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12409 (error "Abort")))
12410 (org-timestamp-change n (cdr (assoc what whata)))
12411 (org-at-timestamp-p t)
12412 (setq ts (match-string 1))
12413 (setq time (save-match-data (org-time-string-to-time ts)))))
12414 (org-timestamp-change (- n) (cdr (assoc what whata)))
12415 ;; rematch, so that we have everything in place for the real shift
12416 (org-at-timestamp-p t)
12417 (setq ts (match-string 1))
12418 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12419 (org-timestamp-change n (cdr (assoc what whata)))
12420 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12421 (setq org-log-post-message msg)
12422 (message "%s" msg))))
12424 (defun org-show-todo-tree (arg)
12425 "Make a compact tree which shows all headlines marked with TODO.
12426 The tree will show the lines where the regexp matches, and all higher
12427 headlines above the match.
12428 With a \\[universal-argument] prefix, prompt for a regexp to match.
12429 With a numeric prefix N, construct a sparse tree for the Nth element
12430 of `org-todo-keywords-1'."
12431 (interactive "P")
12432 (let ((case-fold-search nil)
12433 (kwd-re
12434 (cond ((null arg) org-not-done-regexp)
12435 ((equal arg '(4))
12436 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12437 (mapcar 'list org-todo-keywords-1))))
12438 (concat "\\("
12439 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12440 "\\)\\>")))
12441 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12442 (regexp-quote (nth (1- (prefix-numeric-value arg))
12443 org-todo-keywords-1)))
12444 (t (error "Invalid prefix argument: %s" arg)))))
12445 (message "%d TODO entries found"
12446 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12448 (defun org-deadline (&optional remove time)
12449 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12450 With argument REMOVE, remove any deadline from the item.
12451 With argument TIME, set the deadline at the corresponding date. TIME
12452 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12453 (interactive "P")
12454 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12455 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12456 'region-start-level 'region))
12457 org-loop-over-headlines-in-active-region)
12458 (org-map-entries
12459 `(org-deadline ',remove ,time)
12460 org-loop-over-headlines-in-active-region
12461 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12462 (let* ((old-date (org-entry-get nil "DEADLINE"))
12463 (repeater (and old-date
12464 (string-match
12465 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12466 old-date)
12467 (match-string 1 old-date))))
12468 (if remove
12469 (progn
12470 (when (and old-date org-log-redeadline)
12471 (org-add-log-setup 'deldeadline nil old-date 'findpos
12472 org-log-redeadline))
12473 (org-remove-timestamp-with-keyword org-deadline-string)
12474 (message "Item no longer has a deadline."))
12475 (org-add-planning-info 'deadline time 'closed)
12476 (when (and old-date org-log-redeadline
12477 (not (equal old-date
12478 (substring org-last-inserted-timestamp 1 -1))))
12479 (org-add-log-setup 'redeadline nil old-date 'findpos
12480 org-log-redeadline))
12481 (when repeater
12482 (save-excursion
12483 (org-back-to-heading t)
12484 (when (re-search-forward (concat org-deadline-string " "
12485 org-last-inserted-timestamp)
12486 (save-excursion
12487 (outline-next-heading) (point)) t)
12488 (goto-char (1- (match-end 0)))
12489 (insert " " repeater)
12490 (setq org-last-inserted-timestamp
12491 (concat (substring org-last-inserted-timestamp 0 -1)
12492 " " repeater
12493 (substring org-last-inserted-timestamp -1))))))
12494 (message "Deadline on %s" org-last-inserted-timestamp)))))
12496 (defun org-schedule (&optional remove time)
12497 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12498 With argument REMOVE, remove any scheduling date from the item.
12499 With argument TIME, scheduled at the corresponding date. TIME can
12500 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12501 (interactive "P")
12502 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12503 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12504 'region-start-level 'region))
12505 org-loop-over-headlines-in-active-region)
12506 (org-map-entries
12507 `(org-schedule ',remove ,time)
12508 org-loop-over-headlines-in-active-region
12509 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12510 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12511 (repeater (and old-date
12512 (string-match
12513 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12514 old-date)
12515 (match-string 1 old-date))))
12516 (if remove
12517 (progn
12518 (when (and old-date org-log-reschedule)
12519 (org-add-log-setup 'delschedule nil old-date 'findpos
12520 org-log-reschedule))
12521 (org-remove-timestamp-with-keyword org-scheduled-string)
12522 (message "Item is no longer scheduled."))
12523 (org-add-planning-info 'scheduled time 'closed)
12524 (when (and old-date org-log-reschedule
12525 (not (equal old-date
12526 (substring org-last-inserted-timestamp 1 -1))))
12527 (org-add-log-setup 'reschedule nil old-date 'findpos
12528 org-log-reschedule))
12529 (when repeater
12530 (save-excursion
12531 (org-back-to-heading t)
12532 (when (re-search-forward (concat org-scheduled-string " "
12533 org-last-inserted-timestamp)
12534 (save-excursion
12535 (outline-next-heading) (point)) t)
12536 (goto-char (1- (match-end 0)))
12537 (insert " " repeater)
12538 (setq org-last-inserted-timestamp
12539 (concat (substring org-last-inserted-timestamp 0 -1)
12540 " " repeater
12541 (substring org-last-inserted-timestamp -1))))))
12542 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12544 (defun org-get-scheduled-time (pom &optional inherit)
12545 "Get the scheduled time as a time tuple, of a format suitable
12546 for calling org-schedule with, or if there is no scheduling,
12547 returns nil."
12548 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12549 (when time
12550 (apply 'encode-time (org-parse-time-string time)))))
12552 (defun org-get-deadline-time (pom &optional inherit)
12553 "Get the deadline as a time tuple, of a format suitable for
12554 calling org-deadline with, or if there is no scheduling, returns
12555 nil."
12556 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12557 (when time
12558 (apply 'encode-time (org-parse-time-string time)))))
12560 (defun org-remove-timestamp-with-keyword (keyword)
12561 "Remove all time stamps with KEYWORD in the current entry."
12562 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12563 beg)
12564 (save-excursion
12565 (org-back-to-heading t)
12566 (setq beg (point))
12567 (outline-next-heading)
12568 (while (re-search-backward re beg t)
12569 (replace-match "")
12570 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12571 (equal (char-before) ?\ ))
12572 (backward-delete-char 1)
12573 (if (string-match "^[ \t]*$" (buffer-substring
12574 (point-at-bol) (point-at-eol)))
12575 (delete-region (point-at-bol)
12576 (min (point-max) (1+ (point-at-eol))))))))))
12578 (defun org-add-planning-info (what &optional time &rest remove)
12579 "Insert new timestamp with keyword in the line directly after the headline.
12580 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12581 If non is given, the user is prompted for a date.
12582 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12583 be removed."
12584 (interactive)
12585 (let (org-time-was-given org-end-time-was-given ts
12586 end default-time default-input)
12588 (catch 'exit
12589 (when (and (memq what '(scheduled deadline))
12590 (or (not time)
12591 (and (stringp time)
12592 (string-match "^[-+]+[0-9]" time))))
12593 ;; Try to get a default date/time from existing timestamp
12594 (save-excursion
12595 (org-back-to-heading t)
12596 (setq end (save-excursion (outline-next-heading) (point)))
12597 (when (re-search-forward (if (eq what 'scheduled)
12598 org-scheduled-time-regexp
12599 org-deadline-time-regexp)
12600 end t)
12601 (setq ts (match-string 1)
12602 default-time
12603 (apply 'encode-time (org-parse-time-string ts))
12604 default-input (and ts (org-get-compact-tod ts))))))
12605 (when what
12606 (setq time
12607 (if (stringp time)
12608 ;; This is a string (relative or absolute), set proper date
12609 (apply 'encode-time
12610 (org-read-date-analyze
12611 time default-time (decode-time default-time)))
12612 ;; If necessary, get the time from the user
12613 (or time (org-read-date nil 'to-time nil nil
12614 default-time default-input)))))
12616 (when (and org-insert-labeled-timestamps-at-point
12617 (member what '(scheduled deadline)))
12618 (insert
12619 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12620 (org-insert-time-stamp time org-time-was-given
12621 nil nil nil (list org-end-time-was-given))
12622 (setq what nil))
12623 (save-excursion
12624 (save-restriction
12625 (let (col list elt ts buffer-invisibility-spec)
12626 (org-back-to-heading t)
12627 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12628 (goto-char (match-end 1))
12629 (setq col (current-column))
12630 (goto-char (match-end 0))
12631 (if (eobp) (insert "\n") (forward-char 1))
12632 (when (and (not what)
12633 (not (looking-at
12634 (concat "[ \t]*"
12635 org-keyword-time-not-clock-regexp))))
12636 ;; Nothing to add, nothing to remove...... :-)
12637 (throw 'exit nil))
12638 (if (and (not (looking-at org-outline-regexp))
12639 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12640 "[^\r\n]*"))
12641 (not (equal (match-string 1) org-clock-string)))
12642 (narrow-to-region (match-beginning 0) (match-end 0))
12643 (insert-before-markers "\n")
12644 (backward-char 1)
12645 (narrow-to-region (point) (point))
12646 (and org-adapt-indentation (org-indent-to-column col)))
12647 ;; Check if we have to remove something.
12648 (setq list (cons what remove))
12649 (while list
12650 (setq elt (pop list))
12651 (when (or (and (eq elt 'scheduled)
12652 (re-search-forward org-scheduled-time-regexp nil t))
12653 (and (eq elt 'deadline)
12654 (re-search-forward org-deadline-time-regexp nil t))
12655 (and (eq elt 'closed)
12656 (re-search-forward org-closed-time-regexp nil t)))
12657 (replace-match "")
12658 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12659 (and (looking-at "[ \t]+") (replace-match ""))
12660 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12661 (when what
12662 (insert
12663 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12664 (cond ((eq what 'scheduled) org-scheduled-string)
12665 ((eq what 'deadline) org-deadline-string)
12666 ((eq what 'closed) org-closed-string))
12667 " ")
12668 (setq ts (org-insert-time-stamp
12669 time
12670 (or org-time-was-given
12671 (and (eq what 'closed) org-log-done-with-time))
12672 (eq what 'closed)
12673 nil nil (list org-end-time-was-given)))
12674 (insert
12675 (if (not (or (bolp) (eq (char-before) ?\ )
12676 (memq (char-after) '(32 10))
12677 (eobp))) " " ""))
12678 (end-of-line 1))
12679 (goto-char (point-min))
12680 (widen)
12681 (if (and (looking-at "[ \t]*\n")
12682 (equal (char-before) ?\n))
12683 (delete-region (1- (point)) (point-at-eol)))
12684 ts))))))
12686 (defvar org-log-note-marker (make-marker))
12687 (defvar org-log-note-purpose nil)
12688 (defvar org-log-note-state nil)
12689 (defvar org-log-note-previous-state nil)
12690 (defvar org-log-note-how nil)
12691 (defvar org-log-note-extra nil)
12692 (defvar org-log-note-window-configuration nil)
12693 (defvar org-log-note-return-to (make-marker))
12694 (defvar org-log-note-effective-time nil
12695 "Remembered current time so that dynamically scoped
12696 `org-extend-today-until' affects tha timestamps in state change
12697 log")
12699 (defvar org-log-post-message nil
12700 "Message to be displayed after a log note has been stored.
12701 The auto-repeater uses this.")
12703 (defun org-add-note ()
12704 "Add a note to the current entry.
12705 This is done in the same way as adding a state change note."
12706 (interactive)
12707 (org-add-log-setup 'note nil nil 'findpos nil))
12709 (defvar org-property-end-re)
12710 (defun org-add-log-setup (&optional purpose state prev-state
12711 findpos how extra)
12712 "Set up the post command hook to take a note.
12713 If this is about to TODO state change, the new state is expected in STATE.
12714 When FINDPOS is non-nil, find the correct position for the note in
12715 the current entry. If not, assume that it can be inserted at point.
12716 HOW is an indicator what kind of note should be created.
12717 EXTRA is additional text that will be inserted into the notes buffer."
12718 (let* ((org-log-into-drawer (org-log-into-drawer))
12719 (drawer (cond ((stringp org-log-into-drawer)
12720 org-log-into-drawer)
12721 (org-log-into-drawer "LOGBOOK"))))
12722 (save-restriction
12723 (save-excursion
12724 (when findpos
12725 (org-back-to-heading t)
12726 (narrow-to-region (point) (save-excursion
12727 (outline-next-heading) (point)))
12728 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12729 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12730 "[^\r\n]*\\)?"))
12731 (goto-char (match-end 0))
12732 (cond
12733 (drawer
12734 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12735 nil t)
12736 (progn
12737 (goto-char (match-end 0))
12738 (or org-log-states-order-reversed
12739 (and (re-search-forward org-property-end-re nil t)
12740 (goto-char (1- (match-beginning 0))))))
12741 (insert "\n:" drawer ":\n:END:")
12742 (beginning-of-line 0)
12743 (org-indent-line)
12744 (beginning-of-line 2)
12745 (org-indent-line)
12746 (end-of-line 0)))
12747 ((and org-log-state-notes-insert-after-drawers
12748 (save-excursion
12749 (forward-line) (looking-at org-drawer-regexp)))
12750 (forward-line)
12751 (while (looking-at org-drawer-regexp)
12752 (goto-char (match-end 0))
12753 (re-search-forward org-property-end-re (point-max) t)
12754 (forward-line))
12755 (forward-line -1)))
12756 (unless org-log-states-order-reversed
12757 (and (= (char-after) ?\n) (forward-char 1))
12758 (org-skip-over-state-notes)
12759 (skip-chars-backward " \t\n\r")))
12760 (move-marker org-log-note-marker (point))
12761 (setq org-log-note-purpose purpose
12762 org-log-note-state state
12763 org-log-note-previous-state prev-state
12764 org-log-note-how how
12765 org-log-note-extra extra
12766 org-log-note-effective-time (org-current-effective-time))
12767 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12769 (defun org-skip-over-state-notes ()
12770 "Skip past the list of State notes in an entry."
12771 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12772 (when (ignore-errors (goto-char (org-in-item-p)))
12773 (let* ((struct (org-list-struct))
12774 (prevs (org-list-prevs-alist struct)))
12775 (while (looking-at "[ \t]*- State")
12776 (goto-char (or (org-list-get-next-item (point) struct prevs)
12777 (org-list-get-item-end (point) struct)))))))
12779 (defun org-add-log-note (&optional purpose)
12780 "Pop up a window for taking a note, and add this note later at point."
12781 (remove-hook 'post-command-hook 'org-add-log-note)
12782 (setq org-log-note-window-configuration (current-window-configuration))
12783 (delete-other-windows)
12784 (move-marker org-log-note-return-to (point))
12785 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12786 (goto-char org-log-note-marker)
12787 (org-switch-to-buffer-other-window "*Org Note*")
12788 (erase-buffer)
12789 (if (memq org-log-note-how '(time state))
12790 (let (current-prefix-arg) (org-store-log-note))
12791 (let ((org-inhibit-startup t)) (org-mode))
12792 (insert (format "# Insert note for %s.
12793 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12794 (cond
12795 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12796 ((eq org-log-note-purpose 'done) "closed todo item")
12797 ((eq org-log-note-purpose 'state)
12798 (format "state change from \"%s\" to \"%s\""
12799 (or org-log-note-previous-state "")
12800 (or org-log-note-state "")))
12801 ((eq org-log-note-purpose 'reschedule)
12802 "rescheduling")
12803 ((eq org-log-note-purpose 'delschedule)
12804 "no longer scheduled")
12805 ((eq org-log-note-purpose 'redeadline)
12806 "changing deadline")
12807 ((eq org-log-note-purpose 'deldeadline)
12808 "removing deadline")
12809 ((eq org-log-note-purpose 'refile)
12810 "refiling")
12811 ((eq org-log-note-purpose 'note)
12812 "this entry")
12813 (t (error "This should not happen")))))
12814 (if org-log-note-extra (insert org-log-note-extra))
12815 (org-set-local 'org-finish-function 'org-store-log-note)
12816 (run-hooks 'org-log-buffer-setup-hook)))
12818 (defvar org-note-abort nil) ; dynamically scoped
12819 (defun org-store-log-note ()
12820 "Finish taking a log note, and insert it to where it belongs."
12821 (let ((txt (buffer-string)))
12822 (kill-buffer (current-buffer))
12823 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12824 lines ind bul)
12825 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12826 (setq txt (replace-match "" t t txt)))
12827 (if (string-match "\\s-+\\'" txt)
12828 (setq txt (replace-match "" t t txt)))
12829 (setq lines (org-split-string txt "\n"))
12830 (when (and note (string-match "\\S-" note))
12831 (setq note
12832 (org-replace-escapes
12833 note
12834 (list (cons "%u" (user-login-name))
12835 (cons "%U" user-full-name)
12836 (cons "%t" (format-time-string
12837 (org-time-stamp-format 'long 'inactive)
12838 org-log-note-effective-time))
12839 (cons "%T" (format-time-string
12840 (org-time-stamp-format 'long nil)
12841 org-log-note-effective-time))
12842 (cons "%d" (format-time-string
12843 (org-time-stamp-format nil 'inactive)
12844 org-log-note-effective-time))
12845 (cons "%D" (format-time-string
12846 (org-time-stamp-format nil nil)
12847 org-log-note-effective-time))
12848 (cons "%s" (if org-log-note-state
12849 (concat "\"" org-log-note-state "\"")
12850 ""))
12851 (cons "%S" (if org-log-note-previous-state
12852 (concat "\"" org-log-note-previous-state "\"")
12853 "\"\"")))))
12854 (if lines (setq note (concat note " \\\\")))
12855 (push note lines))
12856 (when (or current-prefix-arg org-note-abort)
12857 (when org-log-into-drawer
12858 (org-remove-empty-drawer-at
12859 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12860 org-log-note-marker))
12861 (setq lines nil))
12862 (when lines
12863 (with-current-buffer (marker-buffer org-log-note-marker)
12864 (save-excursion
12865 (goto-char org-log-note-marker)
12866 (move-marker org-log-note-marker nil)
12867 (end-of-line 1)
12868 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12869 (setq ind (save-excursion
12870 (if (ignore-errors (goto-char (org-in-item-p)))
12871 (let ((struct (org-list-struct)))
12872 (org-list-get-ind
12873 (org-list-get-top-point struct) struct))
12874 (skip-chars-backward " \r\t\n")
12875 (cond
12876 ((and (org-at-heading-p)
12877 org-adapt-indentation)
12878 (1+ (org-current-level)))
12879 ((org-at-heading-p) 0)
12880 (t (org-get-indentation))))))
12881 (setq bul (org-list-bullet-string "-"))
12882 (org-indent-line-to ind)
12883 (insert bul (pop lines))
12884 (let ((ind-body (+ (length bul) ind)))
12885 (while lines
12886 (insert "\n")
12887 (org-indent-line-to ind-body)
12888 (insert (pop lines))))
12889 (message "Note stored")
12890 (org-back-to-heading t)
12891 (org-cycle-hide-drawers 'children))))))
12892 (set-window-configuration org-log-note-window-configuration)
12893 (with-current-buffer (marker-buffer org-log-note-return-to)
12894 (goto-char org-log-note-return-to))
12895 (move-marker org-log-note-return-to nil)
12896 (and org-log-post-message (message "%s" org-log-post-message)))
12898 (defun org-remove-empty-drawer-at (drawer pos)
12899 "Remove an empty drawer DRAWER at position POS.
12900 POS may also be a marker."
12901 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12902 (save-excursion
12903 (save-restriction
12904 (widen)
12905 (goto-char pos)
12906 (if (org-in-regexp
12907 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12908 (replace-match ""))))))
12910 (defvar org-ts-type nil)
12911 (defun org-sparse-tree (&optional arg type)
12912 "Create a sparse tree, prompt for the details.
12913 This command can create sparse trees. You first need to select the type
12914 of match used to create the tree:
12916 t Show all TODO entries.
12917 T Show entries with a specific TODO keyword.
12918 m Show entries selected by a tags/property match.
12919 p Enter a property name and its value (both with completion on existing
12920 names/values) and show entries with that property.
12921 r Show entries matching a regular expression (`/' can be used as well).
12922 b Show deadlines and scheduled items before a date.
12923 a Show deadlines and scheduled items after a date.
12924 d Show deadlines due within `org-deadline-warning-days'.
12925 D Show deadlines and scheduled items between a date range."
12926 (interactive "P")
12927 (let (ans kwd value ts-type)
12928 (setq type (or type org-sparse-tree-default-date-type))
12929 (setq org-ts-type type)
12930 (message "Sparse tree: [/]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"
12931 (cond ((eq type 'all) "all timestamps")
12932 ((eq type 'scheduled) "only scheduled")
12933 ((eq type 'deadline) "only deadline")
12934 ((eq type 'active) "only active timestamps")
12935 ((eq type 'inactive) "only inactive timestamps")
12936 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12937 (t "scheduled/deadline")))
12938 (setq ans (read-char-exclusive))
12939 (cond
12940 ((equal ans ?c)
12941 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12942 ((equal ans ?d)
12943 (call-interactively 'org-check-deadlines))
12944 ((equal ans ?b)
12945 (call-interactively 'org-check-before-date))
12946 ((equal ans ?a)
12947 (call-interactively 'org-check-after-date))
12948 ((equal ans ?D)
12949 (call-interactively 'org-check-dates-range))
12950 ((equal ans ?t)
12951 (call-interactively 'org-show-todo-tree))
12952 ((equal ans ?T)
12953 (org-show-todo-tree '(4)))
12954 ((member ans '(?T ?m))
12955 (call-interactively 'org-match-sparse-tree))
12956 ((member ans '(?p ?P))
12957 (setq kwd (org-icompleting-read "Property: "
12958 (mapcar 'list (org-buffer-property-keys))))
12959 (setq value (org-icompleting-read "Value: "
12960 (mapcar 'list (org-property-values kwd))))
12961 (unless (string-match "\\`{.*}\\'" value)
12962 (setq value (concat "\"" value "\"")))
12963 (org-match-sparse-tree arg (concat kwd "=" value)))
12964 ((member ans '(?r ?R ?/))
12965 (call-interactively 'org-occur))
12966 (t (error "No such sparse tree command \"%c\"" ans)))))
12968 (defvar org-occur-highlights nil
12969 "List of overlays used for occur matches.")
12970 (make-variable-buffer-local 'org-occur-highlights)
12971 (defvar org-occur-parameters nil
12972 "Parameters of the active org-occur calls.
12973 This is a list, each call to org-occur pushes as cons cell,
12974 containing the regular expression and the callback, onto the list.
12975 The list can contain several entries if `org-occur' has been called
12976 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12977 will only contain one set of parameters. When the highlights are
12978 removed (for example with `C-c C-c', or with the next edit (depending
12979 on `org-remove-highlights-with-change'), this variable is emptied
12980 as well.")
12981 (make-variable-buffer-local 'org-occur-parameters)
12983 (defun org-occur (regexp &optional keep-previous callback)
12984 "Make a compact tree which shows all matches of REGEXP.
12985 The tree will show the lines where the regexp matches, and all higher
12986 headlines above the match. It will also show the heading after the match,
12987 to make sure editing the matching entry is easy.
12988 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12989 call to `org-occur' will be kept, to allow stacking of calls to this
12990 command.
12991 If CALLBACK is non-nil, it is a function which is called to confirm
12992 that the match should indeed be shown."
12993 (interactive "sRegexp: \nP")
12994 (when (equal regexp "")
12995 (error "Regexp cannot be empty"))
12996 (unless keep-previous
12997 (org-remove-occur-highlights nil nil t))
12998 (push (cons regexp callback) org-occur-parameters)
12999 (let ((cnt 0))
13000 (save-excursion
13001 (goto-char (point-min))
13002 (if (or (not keep-previous) ; do not want to keep
13003 (not org-occur-highlights)) ; no previous matches
13004 ;; hide everything
13005 (org-overview))
13006 (while (re-search-forward regexp nil t)
13007 (when (or (not callback)
13008 (save-match-data (funcall callback)))
13009 (setq cnt (1+ cnt))
13010 (when org-highlight-sparse-tree-matches
13011 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13012 (org-show-context 'occur-tree))))
13013 (when org-remove-highlights-with-change
13014 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13015 nil 'local))
13016 (unless org-sparse-tree-open-archived-trees
13017 (org-hide-archived-subtrees (point-min) (point-max)))
13018 (run-hooks 'org-occur-hook)
13019 (if (org-called-interactively-p 'interactive)
13020 (message "%d match(es) for regexp %s" cnt regexp))
13021 cnt))
13023 (defun org-occur-next-match (&optional n reset)
13024 "Function for `next-error-function' to find sparse tree matches.
13025 N is the number of matches to move, when negative move backwards.
13026 RESET is entirely ignored - this function always goes back to the
13027 starting point when no match is found."
13028 (let* ((limit (if (< n 0) (point-min) (point-max)))
13029 (search-func (if (< n 0)
13030 'previous-single-char-property-change
13031 'next-single-char-property-change))
13032 (n (abs n))
13033 (pos (point))
13035 (catch 'exit
13036 (while (setq p1 (funcall search-func (point) 'org-type))
13037 (when (equal p1 limit)
13038 (goto-char pos)
13039 (error "No more matches"))
13040 (when (equal (get-char-property p1 'org-type) 'org-occur)
13041 (setq n (1- n))
13042 (when (= n 0)
13043 (goto-char p1)
13044 (throw 'exit (point))))
13045 (goto-char p1))
13046 (goto-char p1)
13047 (error "No more matches"))))
13049 (defun org-show-context (&optional key)
13050 "Make sure point and context are visible.
13051 How much context is shown depends upon the variables
13052 `org-show-hierarchy-above', `org-show-following-heading',
13053 `org-show-entry-below' and `org-show-siblings'."
13054 (let ((heading-p (org-at-heading-p t))
13055 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13056 (following-p (org-get-alist-option org-show-following-heading key))
13057 (entry-p (org-get-alist-option org-show-entry-below key))
13058 (siblings-p (org-get-alist-option org-show-siblings key)))
13059 (catch 'exit
13060 ;; Show heading or entry text
13061 (if (and heading-p (not entry-p))
13062 (org-flag-heading nil) ; only show the heading
13063 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13064 (org-show-hidden-entry))) ; show entire entry
13065 (when following-p
13066 ;; Show next sibling, or heading below text
13067 (save-excursion
13068 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13069 (org-flag-heading nil))))
13070 (when siblings-p (org-show-siblings))
13071 (when hierarchy-p
13072 ;; show all higher headings, possibly with siblings
13073 (save-excursion
13074 (while (and (condition-case nil
13075 (progn (org-up-heading-all 1) t)
13076 (error nil))
13077 (not (bobp)))
13078 (org-flag-heading nil)
13079 (when siblings-p (org-show-siblings))))))))
13081 (defvar org-reveal-start-hook nil
13082 "Hook run before revealing a location.")
13084 (defun org-reveal (&optional siblings)
13085 "Show current entry, hierarchy above it, and the following headline.
13086 This can be used to show a consistent set of context around locations
13087 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13088 not t for the search context.
13090 With optional argument SIBLINGS, on each level of the hierarchy all
13091 siblings are shown. This repairs the tree structure to what it would
13092 look like when opened with hierarchical calls to `org-cycle'.
13093 With double optional argument \\[universal-argument] \\[universal-argument], \
13094 go to the parent and show the
13095 entire tree."
13096 (interactive "P")
13097 (run-hooks 'org-reveal-start-hook)
13098 (let ((org-show-hierarchy-above t)
13099 (org-show-following-heading t)
13100 (org-show-siblings (if siblings t org-show-siblings)))
13101 (org-show-context nil))
13102 (when (equal siblings '(16))
13103 (save-excursion
13104 (when (org-up-heading-safe)
13105 (org-show-subtree)
13106 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13108 (defun org-highlight-new-match (beg end)
13109 "Highlight from BEG to END and mark the highlight is an occur headline."
13110 (let ((ov (make-overlay beg end)))
13111 (overlay-put ov 'face 'secondary-selection)
13112 (overlay-put ov 'org-type 'org-occur)
13113 (push ov org-occur-highlights)))
13115 (defun org-remove-occur-highlights (&optional beg end noremove)
13116 "Remove the occur highlights from the buffer.
13117 BEG and END are ignored. If NOREMOVE is nil, remove this function
13118 from the `before-change-functions' in the current buffer."
13119 (interactive)
13120 (unless org-inhibit-highlight-removal
13121 (mapc 'delete-overlay org-occur-highlights)
13122 (setq org-occur-highlights nil)
13123 (setq org-occur-parameters nil)
13124 (unless noremove
13125 (remove-hook 'before-change-functions
13126 'org-remove-occur-highlights 'local))))
13128 ;;;; Priorities
13130 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13131 "Regular expression matching the priority indicator.")
13133 (defvar org-remove-priority-next-time nil)
13135 (defun org-priority-up ()
13136 "Increase the priority of the current item."
13137 (interactive)
13138 (org-priority 'up))
13140 (defun org-priority-down ()
13141 "Decrease the priority of the current item."
13142 (interactive)
13143 (org-priority 'down))
13145 (defun org-priority (&optional action show)
13146 "Change the priority of an item.
13147 ACTION can be `set', `up', `down', or a character."
13148 (interactive "P")
13149 (if (equal action '(4))
13150 (org-show-priority)
13151 (unless org-enable-priority-commands
13152 (error "Priority commands are disabled"))
13153 (setq action (or action 'set))
13154 (let (current new news have remove)
13155 (save-excursion
13156 (org-back-to-heading t)
13157 (if (looking-at org-priority-regexp)
13158 (setq current (string-to-char (match-string 2))
13159 have t))
13160 (cond
13161 ((eq action 'remove)
13162 (setq remove t new ?\ ))
13163 ((or (eq action 'set)
13164 (if (featurep 'xemacs) (characterp action) (integerp action)))
13165 (if (not (eq action 'set))
13166 (setq new action)
13167 (message "Priority %c-%c, SPC to remove: "
13168 org-highest-priority org-lowest-priority)
13169 (save-match-data
13170 (setq new (read-char-exclusive))))
13171 (if (and (= (upcase org-highest-priority) org-highest-priority)
13172 (= (upcase org-lowest-priority) org-lowest-priority))
13173 (setq new (upcase new)))
13174 (cond ((equal new ?\ ) (setq remove t))
13175 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13176 (error "Priority must be between `%c' and `%c'"
13177 org-highest-priority org-lowest-priority))))
13178 ((eq action 'up)
13179 (setq new (if have
13180 (1- current) ; normal cycling
13181 ;; last priority was empty
13182 (if (eq last-command this-command)
13183 org-lowest-priority ; wrap around empty to lowest
13184 ;; default
13185 (if org-priority-start-cycle-with-default
13186 org-default-priority
13187 (1- org-default-priority))))))
13188 ((eq action 'down)
13189 (setq new (if have
13190 (1+ current) ; normal cycling
13191 ;; last priority was empty
13192 (if (eq last-command this-command)
13193 org-highest-priority ; wrap around empty to highest
13194 ;; default
13195 (if org-priority-start-cycle-with-default
13196 org-default-priority
13197 (1+ org-default-priority))))))
13198 (t (error "Invalid action")))
13199 (if (or (< (upcase new) org-highest-priority)
13200 (> (upcase new) org-lowest-priority))
13201 (if (and (memq action '(up down))
13202 (not have) (not (eq last-command this-command)))
13203 ;; `new' is from default priority
13204 (error
13205 "The default can not be set, see `org-default-priority' why")
13206 ;; normal cycling: `new' is beyond highest/lowest priority
13207 ;; and is wrapped around to the empty priority
13208 (setq remove t)))
13209 (setq news (format "%c" new))
13210 (if have
13211 (if remove
13212 (replace-match "" t t nil 1)
13213 (replace-match news t t nil 2))
13214 (if remove
13215 (error "No priority cookie found in line")
13216 (let ((case-fold-search nil))
13217 (looking-at org-todo-line-regexp))
13218 (if (match-end 2)
13219 (progn
13220 (goto-char (match-end 2))
13221 (insert " [#" news "]"))
13222 (goto-char (match-beginning 3))
13223 (insert "[#" news "] "))))
13224 (org-preserve-lc (org-set-tags nil 'align)))
13225 (if remove
13226 (message "Priority removed")
13227 (message "Priority of current item set to %s" news)))))
13229 (defun org-show-priority ()
13230 "Show the priority of the current item.
13231 This priority is composed of the main priority given with the [#A] cookies,
13232 and by additional input from the age of a schedules or deadline entry."
13233 (interactive)
13234 (let ((pri (if (eq major-mode 'org-agenda-mode)
13235 (org-get-at-bol 'priority)
13236 (save-excursion
13237 (save-match-data
13238 (beginning-of-line)
13239 (and (looking-at org-heading-regexp)
13240 (org-get-priority (match-string 0))))))))
13241 (message "Priority is %d" (if pri pri -1000))))
13243 (defun org-get-priority (s)
13244 "Find priority cookie and return priority."
13245 (save-match-data
13246 (if (functionp org-get-priority-function)
13247 (funcall org-get-priority-function)
13248 (if (not (string-match org-priority-regexp s))
13249 (* 1000 (- org-lowest-priority org-default-priority))
13250 (* 1000 (- org-lowest-priority
13251 (string-to-char (match-string 2 s))))))))
13253 ;;;; Tags
13255 (defvar org-agenda-archives-mode)
13256 (defvar org-map-continue-from nil
13257 "Position from where mapping should continue.
13258 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13260 (defvar org-scanner-tags nil
13261 "The current tag list while the tags scanner is running.")
13262 (defvar org-trust-scanner-tags nil
13263 "Should `org-get-tags-at' use the tags for the scanner.
13264 This is for internal dynamical scoping only.
13265 When this is non-nil, the function `org-get-tags-at' will return the value
13266 of `org-scanner-tags' instead of building the list by itself. This
13267 can lead to large speed-ups when the tags scanner is used in a file with
13268 many entries, and when the list of tags is retrieved, for example to
13269 obtain a list of properties. Building the tags list for each entry in such
13270 a file becomes an N^2 operation - but with this variable set, it scales
13271 as N.")
13273 (defun org-scan-tags (action matcher todo-only &optional start-level)
13274 "Scan headline tags with inheritance and produce output ACTION.
13276 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13277 or `agenda' to produce an entry list for an agenda view. It can also be
13278 a Lisp form or a function that should be called at each matched headline, in
13279 this case the return value is a list of all return values from these calls.
13281 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13282 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13283 only lines with a not-done TODO keyword are included in the output.
13284 This should be the same variable that was scoped into
13285 and set by `org-make-tags-matcher' when it constructed MATCHER.
13287 START-LEVEL can be a string with asterisks, reducing the scope to
13288 headlines matching this string."
13289 (require 'org-agenda)
13290 (let* ((re (concat "^"
13291 (if start-level
13292 ;; Get the correct level to match
13293 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13294 org-outline-regexp)
13295 " *\\(\\<\\("
13296 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13297 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13298 (props (list 'face 'default
13299 'done-face 'org-agenda-done
13300 'undone-face 'default
13301 'mouse-face 'highlight
13302 'org-not-done-regexp org-not-done-regexp
13303 'org-todo-regexp org-todo-regexp
13304 'org-complex-heading-regexp org-complex-heading-regexp
13305 'help-echo
13306 (format "mouse-2 or RET jump to org file %s"
13307 (abbreviate-file-name
13308 (or (buffer-file-name (buffer-base-buffer))
13309 (buffer-name (buffer-base-buffer)))))))
13310 (case-fold-search nil)
13311 (org-map-continue-from nil)
13312 lspos tags tags-list
13313 (tags-alist (list (cons 0 org-file-tags)))
13314 (llast 0) rtn rtn1 level category i txt
13315 todo marker entry priority)
13316 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13317 (setq action (list 'lambda nil action)))
13318 (save-excursion
13319 (goto-char (point-min))
13320 (when (eq action 'sparse-tree)
13321 (org-overview)
13322 (org-remove-occur-highlights))
13323 (while (re-search-forward re nil t)
13324 (setq org-map-continue-from nil)
13325 (catch :skip
13326 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13327 tags (if (match-end 4) (org-match-string-no-properties 4)))
13328 (goto-char (setq lspos (match-beginning 0)))
13329 (setq level (org-reduced-level (org-outline-level))
13330 category (org-get-category))
13331 (setq i llast llast level)
13332 ;; remove tag lists from same and sublevels
13333 (while (>= i level)
13334 (when (setq entry (assoc i tags-alist))
13335 (setq tags-alist (delete entry tags-alist)))
13336 (setq i (1- i)))
13337 ;; add the next tags
13338 (when tags
13339 (setq tags (org-split-string tags ":")
13340 tags-alist
13341 (cons (cons level tags) tags-alist)))
13342 ;; compile tags for current headline
13343 (setq tags-list
13344 (if org-use-tag-inheritance
13345 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13346 tags)
13347 org-scanner-tags tags-list)
13348 (when org-use-tag-inheritance
13349 (setcdr (car tags-alist)
13350 (mapcar (lambda (x)
13351 (setq x (copy-sequence x))
13352 (org-add-prop-inherited x))
13353 (cdar tags-alist))))
13354 (when (and tags org-use-tag-inheritance
13355 (or (not (eq t org-use-tag-inheritance))
13356 org-tags-exclude-from-inheritance))
13357 ;; selective inheritance, remove uninherited ones
13358 (setcdr (car tags-alist)
13359 (org-remove-uninherited-tags (cdar tags-alist))))
13360 (when (and
13362 ;; eval matcher only when the todo condition is OK
13363 (and (or (not todo-only) (member todo org-not-done-keywords))
13364 (let ((case-fold-search t) (org-trust-scanner-tags t))
13365 (eval matcher)))
13367 ;; Call the skipper, but return t if it does not skip,
13368 ;; so that the `and' form continues evaluating
13369 (progn
13370 (unless (eq action 'sparse-tree) (org-agenda-skip))
13373 ;; Check if timestamps are deselecting this entry
13374 (or (not todo-only)
13375 (and (member todo org-not-done-keywords)
13376 (or (not org-agenda-tags-todo-honor-ignore-options)
13377 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13379 ;; Extra check for the archive tag
13380 ;; FIXME: Does the skipper already do this????
13382 (not (member org-archive-tag tags-list))
13383 ;; we have an archive tag, should we use this anyway?
13384 (or (not org-agenda-skip-archived-trees)
13385 (and (eq action 'agenda) org-agenda-archives-mode))))
13387 ;; select this headline
13388 (cond
13389 ((eq action 'sparse-tree)
13390 (and org-highlight-sparse-tree-matches
13391 (org-get-heading) (match-end 0)
13392 (org-highlight-new-match
13393 (match-beginning 1) (match-end 1)))
13394 (org-show-context 'tags-tree))
13395 ((eq action 'agenda)
13396 (setq txt (org-agenda-format-item
13398 (concat
13399 (if (eq org-tags-match-list-sublevels 'indented)
13400 (make-string (1- level) ?.) "")
13401 (org-get-heading))
13402 level category
13403 tags-list)
13404 priority (org-get-priority txt))
13405 (goto-char lspos)
13406 (setq marker (org-agenda-new-marker))
13407 (org-add-props txt props
13408 'org-marker marker 'org-hd-marker marker 'org-category category
13409 'todo-state todo
13410 'priority priority 'type "tagsmatch")
13411 (push txt rtn))
13412 ((functionp action)
13413 (setq org-map-continue-from nil)
13414 (save-excursion
13415 (setq rtn1 (funcall action))
13416 (push rtn1 rtn)))
13417 (t (error "Invalid action")))
13419 ;; if we are to skip sublevels, jump to end of subtree
13420 (unless org-tags-match-list-sublevels
13421 (org-end-of-subtree t)
13422 (backward-char 1))))
13423 ;; Get the correct position from where to continue
13424 (if org-map-continue-from
13425 (goto-char org-map-continue-from)
13426 (and (= (point) lspos) (end-of-line 1)))))
13427 (when (and (eq action 'sparse-tree)
13428 (not org-sparse-tree-open-archived-trees))
13429 (org-hide-archived-subtrees (point-min) (point-max)))
13430 (nreverse rtn)))
13432 (defun org-remove-uninherited-tags (tags)
13433 "Remove all tags that are not inherited from the list TAGS."
13434 (cond
13435 ((eq org-use-tag-inheritance t)
13436 (if org-tags-exclude-from-inheritance
13437 (org-delete-all org-tags-exclude-from-inheritance tags)
13438 tags))
13439 ((not org-use-tag-inheritance) nil)
13440 ((stringp org-use-tag-inheritance)
13441 (delq nil (mapcar
13442 (lambda (x)
13443 (if (and (string-match org-use-tag-inheritance x)
13444 (not (member x org-tags-exclude-from-inheritance)))
13445 x nil))
13446 tags)))
13447 ((listp org-use-tag-inheritance)
13448 (delq nil (mapcar
13449 (lambda (x)
13450 (if (member x org-use-tag-inheritance) x nil))
13451 tags)))))
13453 (defun org-match-sparse-tree (&optional todo-only match)
13454 "Create a sparse tree according to tags string MATCH.
13455 MATCH can contain positive and negative selection of tags, like
13456 \"+WORK+URGENT-WITHBOSS\".
13457 If optional argument TODO-ONLY is non-nil, only select lines that are
13458 also TODO lines."
13459 (interactive "P")
13460 (org-agenda-prepare-buffers (list (current-buffer)))
13461 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13463 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13465 (defvar org-cached-props nil)
13466 (defun org-cached-entry-get (pom property)
13467 (if (or (eq t org-use-property-inheritance)
13468 (and (stringp org-use-property-inheritance)
13469 (string-match org-use-property-inheritance property))
13470 (and (listp org-use-property-inheritance)
13471 (member property org-use-property-inheritance)))
13472 ;; Caching is not possible, check it directly
13473 (org-entry-get pom property 'inherit)
13474 ;; Get all properties, so that we can do complicated checks easily
13475 (cdr (assoc property (or org-cached-props
13476 (setq org-cached-props
13477 (org-entry-properties pom)))))))
13479 (defun org-global-tags-completion-table (&optional files)
13480 "Return the list of all tags in all agenda buffer/files.
13481 Optional FILES argument is a list of files which can be used
13482 instead of the agenda files."
13483 (save-excursion
13484 (org-uniquify
13485 (delq nil
13486 (apply 'append
13487 (mapcar
13488 (lambda (file)
13489 (set-buffer (find-file-noselect file))
13490 (append (org-get-buffer-tags)
13491 (mapcar (lambda (x) (if (stringp (car-safe x))
13492 (list (car-safe x)) nil))
13493 org-tag-alist)))
13494 (if (and files (car files))
13495 files
13496 (org-agenda-files))))))))
13498 (defun org-make-tags-matcher (match)
13499 "Create the TAGS/TODO matcher form for the selection string MATCH.
13501 The variable `todo-only' is scoped dynamically into this function.
13502 It will be set to t if the matcher restricts matching to TODO entries,
13503 otherwise will not be touched.
13505 Returns a cons of the selection string MATCH and the constructed
13506 lisp form implementing the matcher. The matcher is to be evaluated
13507 at an Org entry, with point on the headline, and returns t if the
13508 entry matches the selection string MATCH. The returned lisp form
13509 references two variables with information about the entry, which
13510 must be bound around the form's evaluation: todo, the TODO keyword
13511 at the entry (or nil of none); and tags-list, the list of all tags
13512 at the entry including inherited ones. Additionally, the category
13513 of the entry (if any) must be specified as the text property
13514 'org-category on the headline.
13516 See also `org-scan-tags'.
13518 (declare (special todo-only))
13519 (unless (boundp 'todo-only)
13520 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13521 (unless match
13522 ;; Get a new match request, with completion
13523 (let ((org-last-tags-completion-table
13524 (org-global-tags-completion-table)))
13525 (setq match (org-completing-read-no-i
13526 "Match: " 'org-tags-completion-function nil nil nil
13527 'org-tags-history))))
13529 ;; Parse the string and create a lisp form
13530 (let ((match0 match)
13531 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13532 minus tag mm
13533 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13534 orterms term orlist re-p str-p level-p level-op time-p
13535 prop-p pn pv po gv rest)
13536 (if (string-match "/+" match)
13537 ;; match contains also a todo-matching request
13538 (progn
13539 (setq tagsmatch (substring match 0 (match-beginning 0))
13540 todomatch (substring match (match-end 0)))
13541 (if (string-match "^!" todomatch)
13542 (setq todo-only t todomatch (substring todomatch 1)))
13543 (if (string-match "^\\s-*$" todomatch)
13544 (setq todomatch nil)))
13545 ;; only matching tags
13546 (setq tagsmatch match todomatch nil))
13548 ;; Make the tags matcher
13549 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13550 (setq tagsmatcher t)
13551 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13552 (while (setq term (pop orterms))
13553 (while (and (equal (substring term -1) "\\") orterms)
13554 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13555 (while (string-match re term)
13556 (setq rest (substring term (match-end 0))
13557 minus (and (match-end 1)
13558 (equal (match-string 1 term) "-"))
13559 tag (save-match-data (replace-regexp-in-string
13560 "\\\\-" "-"
13561 (match-string 2 term)))
13562 re-p (equal (string-to-char tag) ?{)
13563 level-p (match-end 4)
13564 prop-p (match-end 5)
13565 mm (cond
13566 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13567 (level-p
13568 (setq level-op (org-op-to-function (match-string 3 term)))
13569 `(,level-op level ,(string-to-number
13570 (match-string 4 term))))
13571 (prop-p
13572 (setq pn (match-string 5 term)
13573 po (match-string 6 term)
13574 pv (match-string 7 term)
13575 re-p (equal (string-to-char pv) ?{)
13576 str-p (equal (string-to-char pv) ?\")
13577 time-p (save-match-data
13578 (string-match "^\"[[<].*[]>]\"$" pv))
13579 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13580 (if time-p (setq pv (org-matcher-time pv)))
13581 (setq po (org-op-to-function po (if time-p 'time str-p)))
13582 (cond
13583 ((equal pn "CATEGORY")
13584 (setq gv '(get-text-property (point) 'org-category)))
13585 ((equal pn "TODO")
13586 (setq gv 'todo))
13588 (setq gv `(org-cached-entry-get nil ,pn))))
13589 (if re-p
13590 (if (eq po 'org<>)
13591 `(not (string-match ,pv (or ,gv "")))
13592 `(string-match ,pv (or ,gv "")))
13593 (if str-p
13594 `(,po (or ,gv "") ,pv)
13595 `(,po (string-to-number (or ,gv ""))
13596 ,(string-to-number pv) ))))
13597 (t `(member ,tag tags-list)))
13598 mm (if minus (list 'not mm) mm)
13599 term rest)
13600 (push mm tagsmatcher))
13601 (push (if (> (length tagsmatcher) 1)
13602 (cons 'and tagsmatcher)
13603 (car tagsmatcher))
13604 orlist)
13605 (setq tagsmatcher nil))
13606 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13607 (setq tagsmatcher
13608 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13609 ;; Make the todo matcher
13610 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13611 (setq todomatcher t)
13612 (setq orterms (org-split-string todomatch "|") orlist nil)
13613 (while (setq term (pop orterms))
13614 (while (string-match re term)
13615 (setq minus (and (match-end 1)
13616 (equal (match-string 1 term) "-"))
13617 kwd (match-string 2 term)
13618 re-p (equal (string-to-char kwd) ?{)
13619 term (substring term (match-end 0))
13620 mm (if re-p
13621 `(string-match ,(substring kwd 1 -1) todo)
13622 (list 'equal 'todo kwd))
13623 mm (if minus (list 'not mm) mm))
13624 (push mm todomatcher))
13625 (push (if (> (length todomatcher) 1)
13626 (cons 'and todomatcher)
13627 (car todomatcher))
13628 orlist)
13629 (setq todomatcher nil))
13630 (setq todomatcher (if (> (length orlist) 1)
13631 (cons 'or orlist) (car orlist))))
13633 ;; Return the string and lisp forms of the matcher
13634 (setq matcher (if todomatcher
13635 (list 'and tagsmatcher todomatcher)
13636 tagsmatcher))
13637 (when todo-only
13638 (setq matcher (list 'and '(member todo org-not-done-keywords)
13639 matcher)))
13640 (cons match0 matcher)))
13642 (defun org-op-to-function (op &optional stringp)
13643 "Turn an operator into the appropriate function."
13644 (setq op
13645 (cond
13646 ((equal op "<" ) '(< string< org-time<))
13647 ((equal op ">" ) '(> org-string> org-time>))
13648 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13649 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13650 ((member op '("=" "==")) '(= string= org-time=))
13651 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13652 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13654 (defun org<> (a b) (not (= a b)))
13655 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13656 (defun org-string>= (a b) (not (string< a b)))
13657 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13658 (defun org-string<> (a b) (not (string= a b)))
13659 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13660 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13661 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13662 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13663 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13664 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13665 (defun org-2ft (s)
13666 "Convert S to a floating point time.
13667 If S is already a number, just return it. If it is a string, parse
13668 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13669 (cond
13670 ((numberp s) s)
13671 ((stringp s)
13672 (condition-case nil
13673 (float-time (apply 'encode-time (org-parse-time-string s)))
13674 (error 0.)))
13675 (t 0.)))
13677 (defun org-time-today ()
13678 "Time in seconds today at 0:00.
13679 Returns the float number of seconds since the beginning of the
13680 epoch to the beginning of today (00:00)."
13681 (float-time (apply 'encode-time
13682 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13684 (defun org-matcher-time (s)
13685 "Interpret a time comparison value."
13686 (save-match-data
13687 (cond
13688 ((string= s "<now>") (float-time))
13689 ((string= s "<today>") (org-time-today))
13690 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13691 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13692 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13693 (+ (org-time-today)
13694 (* (string-to-number (match-string 1 s))
13695 (cdr (assoc (match-string 2 s)
13696 '(("d" . 86400.0) ("w" . 604800.0)
13697 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13698 (t (org-2ft s)))))
13700 (defun org-match-any-p (re list)
13701 "Does re match any element of list?"
13702 (setq list (mapcar (lambda (x) (string-match re x)) list))
13703 (delq nil list))
13705 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13706 (defvar org-tags-overlay (make-overlay 1 1))
13707 (org-detach-overlay org-tags-overlay)
13709 (defun org-get-local-tags-at (&optional pos)
13710 "Get a list of tags defined in the current headline."
13711 (org-get-tags-at pos 'local))
13713 (defun org-get-local-tags ()
13714 "Get a list of tags defined in the current headline."
13715 (org-get-tags-at nil 'local))
13717 (defun org-get-tags-at (&optional pos local)
13718 "Get a list of all headline tags applicable at POS.
13719 POS defaults to point. If tags are inherited, the list contains
13720 the targets in the same sequence as the headlines appear, i.e.
13721 the tags of the current headline come last.
13722 When LOCAL is non-nil, only return tags from the current headline,
13723 ignore inherited ones."
13724 (interactive)
13725 (if (and org-trust-scanner-tags
13726 (or (not pos) (equal pos (point)))
13727 (not local))
13728 org-scanner-tags
13729 (let (tags ltags lastpos parent)
13730 (save-excursion
13731 (save-restriction
13732 (widen)
13733 (goto-char (or pos (point)))
13734 (save-match-data
13735 (catch 'done
13736 (condition-case nil
13737 (progn
13738 (org-back-to-heading t)
13739 (while (not (equal lastpos (point)))
13740 (setq lastpos (point))
13741 (when (looking-at
13742 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13743 (setq ltags (org-split-string
13744 (org-match-string-no-properties 1) ":"))
13745 (when parent
13746 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13747 (setq tags (append
13748 (if parent
13749 (org-remove-uninherited-tags ltags)
13750 ltags)
13751 tags)))
13752 (or org-use-tag-inheritance (throw 'done t))
13753 (if local (throw 'done t))
13754 (or (org-up-heading-safe) (error nil))
13755 (setq parent t)))
13756 (error nil)))))
13757 (if local
13758 tags
13759 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13761 (defun org-add-prop-inherited (s)
13762 (add-text-properties 0 (length s) '(inherited t) s)
13765 (defun org-toggle-tag (tag &optional onoff)
13766 "Toggle the tag TAG for the current line.
13767 If ONOFF is `on' or `off', don't toggle but set to this state."
13768 (let (res current)
13769 (save-excursion
13770 (org-back-to-heading t)
13771 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13772 (point-at-eol) t)
13773 (progn
13774 (setq current (match-string 1))
13775 (replace-match ""))
13776 (setq current ""))
13777 (setq current (nreverse (org-split-string current ":")))
13778 (cond
13779 ((eq onoff 'on)
13780 (setq res t)
13781 (or (member tag current) (push tag current)))
13782 ((eq onoff 'off)
13783 (or (not (member tag current)) (setq current (delete tag current))))
13784 (t (if (member tag current)
13785 (setq current (delete tag current))
13786 (setq res t)
13787 (push tag current))))
13788 (end-of-line 1)
13789 (if current
13790 (progn
13791 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13792 (org-set-tags nil t))
13793 (delete-horizontal-space))
13794 (run-hooks 'org-after-tags-change-hook))
13795 res))
13797 (defun org-align-tags-here (to-col)
13798 ;; Assumes that this is a headline
13799 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13800 (beginning-of-line 1)
13801 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13802 (< pos (match-beginning 2)))
13803 (progn
13804 (setq tags-l (- (match-end 2) (match-beginning 2)))
13805 (goto-char (match-beginning 1))
13806 (insert " ")
13807 (delete-region (point) (1+ (match-beginning 2)))
13808 (setq ncol (max (current-column)
13809 (1+ col)
13810 (if (> to-col 0)
13811 to-col
13812 (- (abs to-col) tags-l))))
13813 (setq p (point))
13814 (insert (make-string (- ncol (current-column)) ?\ ))
13815 (setq ncol (current-column))
13816 (when indent-tabs-mode (tabify p (point-at-eol)))
13817 (org-move-to-column (min ncol col) t))
13818 (goto-char pos))))
13820 (defun org-set-tags-command (&optional arg just-align)
13821 "Call the set-tags command for the current entry."
13822 (interactive "P")
13823 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13824 (org-set-tags arg just-align)
13825 (save-excursion
13826 (org-back-to-heading t)
13827 (org-set-tags arg just-align))))
13829 (defun org-set-tags-to (data)
13830 "Set the tags of the current entry to DATA, replacing the current tags.
13831 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13832 If DATA is nil or the empty string, any tags will be removed."
13833 (interactive "sTags: ")
13834 (setq data
13835 (cond
13836 ((eq data nil) "")
13837 ((equal data "") "")
13838 ((stringp data)
13839 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13840 ":"))
13841 ((listp data)
13842 (concat ":" (mapconcat 'identity data ":") ":"))))
13843 (when data
13844 (save-excursion
13845 (org-back-to-heading t)
13846 (when (looking-at org-complex-heading-regexp)
13847 (if (match-end 5)
13848 (progn
13849 (goto-char (match-beginning 5))
13850 (insert data)
13851 (delete-region (point) (point-at-eol))
13852 (org-set-tags nil 'align))
13853 (goto-char (point-at-eol))
13854 (insert " " data)
13855 (org-set-tags nil 'align)))
13856 (beginning-of-line 1)
13857 (if (looking-at ".*?\\([ \t]+\\)$")
13858 (delete-region (match-beginning 1) (match-end 1))))))
13860 (defun org-align-all-tags ()
13861 "Align the tags i all headings."
13862 (interactive)
13863 (save-excursion
13864 (or (ignore-errors (org-back-to-heading t))
13865 (outline-next-heading))
13866 (if (org-at-heading-p)
13867 (org-set-tags t)
13868 (message "No headings"))))
13870 (defvar org-indent-indentation-per-level)
13871 (defun org-set-tags (&optional arg just-align)
13872 "Set the tags for the current headline.
13873 With prefix ARG, realign all tags in headings in the current buffer."
13874 (interactive "P")
13875 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13876 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13877 'region-start-level 'region))
13878 org-loop-over-headlines-in-active-region)
13879 (org-map-entries
13880 ;; We don't use ARG and JUST-ALIGN here these args are not
13881 ;; useful when looping over headlines
13882 `(org-set-tags)
13883 org-loop-over-headlines-in-active-region
13884 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13885 (let* ((re org-outline-regexp-bol)
13886 (current (unless arg (org-get-tags-string)))
13887 (col (current-column))
13888 (org-setting-tags t)
13889 table current-tags inherited-tags ; computed below when needed
13890 tags p0 c0 c1 rpl di tc level)
13891 (if arg
13892 (save-excursion
13893 (goto-char (point-min))
13894 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13895 (while (re-search-forward re nil t)
13896 (org-set-tags nil t)
13897 (end-of-line 1)))
13898 (message "All tags realigned to column %d" org-tags-column))
13899 (if just-align
13900 (setq tags current)
13901 ;; Get a new set of tags from the user
13902 (save-excursion
13903 (setq table (append org-tag-persistent-alist
13904 (or org-tag-alist (org-get-buffer-tags))
13905 (and
13906 org-complete-tags-always-offer-all-agenda-tags
13907 (org-global-tags-completion-table
13908 (org-agenda-files))))
13909 org-last-tags-completion-table table
13910 current-tags (org-split-string current ":")
13911 inherited-tags (nreverse
13912 (nthcdr (length current-tags)
13913 (nreverse (org-get-tags-at))))
13914 tags
13915 (if (or (eq t org-use-fast-tag-selection)
13916 (and org-use-fast-tag-selection
13917 (delq nil (mapcar 'cdr table))))
13918 (org-fast-tag-selection
13919 current-tags inherited-tags table
13920 (if org-fast-tag-selection-include-todo
13921 org-todo-key-alist))
13922 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13923 (org-trim
13924 (org-icompleting-read "Tags: "
13925 'org-tags-completion-function
13926 nil nil current 'org-tags-history))))))
13927 (while (string-match "[-+&]+" tags)
13928 ;; No boolean logic, just a list
13929 (setq tags (replace-match ":" t t tags))))
13931 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13933 (if org-tags-sort-function
13934 (setq tags (mapconcat 'identity
13935 (sort (org-split-string
13936 tags (org-re "[^[:alnum:]_@#%]+"))
13937 org-tags-sort-function) ":")))
13939 (if (string-match "\\`[\t ]*\\'" tags)
13940 (setq tags "")
13941 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13942 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13944 ;; Insert new tags at the correct column
13945 (beginning-of-line 1)
13946 (setq level (or (and (looking-at org-outline-regexp)
13947 (- (match-end 0) (point) 1))
13949 (cond
13950 ((and (equal current "") (equal tags "")))
13951 ((re-search-forward
13952 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13953 (point-at-eol) t)
13954 (if (equal tags "")
13955 (setq rpl "")
13956 (goto-char (match-beginning 0))
13957 (setq c0 (current-column)
13958 ;; compute offset for the case of org-indent-mode active
13959 di (if org-indent-mode
13960 (* (1- org-indent-indentation-per-level) (1- level))
13962 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13963 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13964 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13965 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13966 (replace-match rpl t t)
13967 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13968 tags)
13969 (t (error "Tags alignment failed")))
13970 (org-move-to-column col)
13971 (unless just-align
13972 (run-hooks 'org-after-tags-change-hook))))))
13974 (defun org-change-tag-in-region (beg end tag off)
13975 "Add or remove TAG for each entry in the region.
13976 This works in the agenda, and also in an org-mode buffer."
13977 (interactive
13978 (list (region-beginning) (region-end)
13979 (let ((org-last-tags-completion-table
13980 (if (derived-mode-p 'org-mode)
13981 (org-get-buffer-tags)
13982 (org-global-tags-completion-table))))
13983 (org-icompleting-read
13984 "Tag: " 'org-tags-completion-function nil nil nil
13985 'org-tags-history))
13986 (progn
13987 (message "[s]et or [r]emove? ")
13988 (equal (read-char-exclusive) ?r))))
13989 (if (fboundp 'deactivate-mark) (deactivate-mark))
13990 (let ((agendap (equal major-mode 'org-agenda-mode))
13991 l1 l2 m buf pos newhead (cnt 0))
13992 (goto-char end)
13993 (setq l2 (1- (org-current-line)))
13994 (goto-char beg)
13995 (setq l1 (org-current-line))
13996 (loop for l from l1 to l2 do
13997 (org-goto-line l)
13998 (setq m (get-text-property (point) 'org-hd-marker))
13999 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14000 (and agendap m))
14001 (setq buf (if agendap (marker-buffer m) (current-buffer))
14002 pos (if agendap m (point)))
14003 (with-current-buffer buf
14004 (save-excursion
14005 (save-restriction
14006 (goto-char pos)
14007 (setq cnt (1+ cnt))
14008 (org-toggle-tag tag (if off 'off 'on))
14009 (setq newhead (org-get-heading)))))
14010 (and agendap (org-agenda-change-all-lines newhead m))))
14011 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14013 (defun org-tags-completion-function (string predicate &optional flag)
14014 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14015 (confirm (lambda (x) (stringp (car x)))))
14016 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14017 (setq s1 (match-string 1 string)
14018 s2 (match-string 2 string))
14019 (setq s1 "" s2 string))
14020 (cond
14021 ((eq flag nil)
14022 ;; try completion
14023 (setq rtn (try-completion s2 ctable confirm))
14024 (if (stringp rtn)
14025 (setq rtn
14026 (concat s1 s2 (substring rtn (length s2))
14027 (if (and org-add-colon-after-tag-completion
14028 (assoc rtn ctable))
14029 ":" ""))))
14030 rtn)
14031 ((eq flag t)
14032 ;; all-completions
14033 (all-completions s2 ctable confirm)
14035 ((eq flag 'lambda)
14036 ;; exact match?
14037 (assoc s2 ctable)))
14040 (defun org-fast-tag-insert (kwd tags face &optional end)
14041 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14042 (insert (format "%-12s" (concat kwd ":"))
14043 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14044 (or end "")))
14046 (defun org-fast-tag-show-exit (flag)
14047 (save-excursion
14048 (org-goto-line 3)
14049 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14050 (replace-match ""))
14051 (when flag
14052 (end-of-line 1)
14053 (org-move-to-column (- (window-width) 19) t)
14054 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14056 (defun org-set-current-tags-overlay (current prefix)
14057 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14058 (if (featurep 'xemacs)
14059 (org-overlay-display org-tags-overlay (concat prefix s)
14060 'secondary-selection)
14061 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14062 (org-overlay-display org-tags-overlay (concat prefix s)))))
14064 (defvar org-last-tag-selection-key nil)
14065 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14066 "Fast tag selection with single keys.
14067 CURRENT is the current list of tags in the headline, INHERITED is the
14068 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14069 possibly with grouping information. TODO-TABLE is a similar table with
14070 TODO keywords, should these have keys assigned to them.
14071 If the keys are nil, a-z are automatically assigned.
14072 Returns the new tags string, or nil to not change the current settings."
14073 (let* ((fulltable (append table todo-table))
14074 (maxlen (apply 'max (mapcar
14075 (lambda (x)
14076 (if (stringp (car x)) (string-width (car x)) 0))
14077 fulltable)))
14078 (buf (current-buffer))
14079 (expert (eq org-fast-tag-selection-single-key 'expert))
14080 (buffer-tags nil)
14081 (fwidth (+ maxlen 3 1 3))
14082 (ncol (/ (- (window-width) 4) fwidth))
14083 (i-face 'org-done)
14084 (c-face 'org-todo)
14085 tg cnt e c char c1 c2 ntable tbl rtn
14086 ov-start ov-end ov-prefix
14087 (exit-after-next org-fast-tag-selection-single-key)
14088 (done-keywords org-done-keywords)
14089 groups ingroup)
14090 (save-excursion
14091 (beginning-of-line 1)
14092 (if (looking-at
14093 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14094 (setq ov-start (match-beginning 1)
14095 ov-end (match-end 1)
14096 ov-prefix "")
14097 (setq ov-start (1- (point-at-eol))
14098 ov-end (1+ ov-start))
14099 (skip-chars-forward "^\n\r")
14100 (setq ov-prefix
14101 (concat
14102 (buffer-substring (1- (point)) (point))
14103 (if (> (current-column) org-tags-column)
14105 (make-string (- org-tags-column (current-column)) ?\ ))))))
14106 (move-overlay org-tags-overlay ov-start ov-end)
14107 (save-window-excursion
14108 (if expert
14109 (set-buffer (get-buffer-create " *Org tags*"))
14110 (delete-other-windows)
14111 (split-window-vertically)
14112 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14113 (erase-buffer)
14114 (org-set-local 'org-done-keywords done-keywords)
14115 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14116 (org-fast-tag-insert "Current" current c-face "\n\n")
14117 (org-fast-tag-show-exit exit-after-next)
14118 (org-set-current-tags-overlay current ov-prefix)
14119 (setq tbl fulltable char ?a cnt 0)
14120 (while (setq e (pop tbl))
14121 (cond
14122 ((equal (car e) :startgroup)
14123 (push '() groups) (setq ingroup t)
14124 (when (not (= cnt 0))
14125 (setq cnt 0)
14126 (insert "\n"))
14127 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14128 ((equal (car e) :endgroup)
14129 (setq ingroup nil cnt 0)
14130 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14131 ((equal e '(:newline))
14132 (when (not (= cnt 0))
14133 (setq cnt 0)
14134 (insert "\n")
14135 (setq e (car tbl))
14136 (while (equal (car tbl) '(:newline))
14137 (insert "\n")
14138 (setq tbl (cdr tbl)))))
14140 (setq tg (copy-sequence (car e)) c2 nil)
14141 (if (cdr e)
14142 (setq c (cdr e))
14143 ;; automatically assign a character.
14144 (setq c1 (string-to-char
14145 (downcase (substring
14146 tg (if (= (string-to-char tg) ?@) 1 0)))))
14147 (if (or (rassoc c1 ntable) (rassoc c1 table))
14148 (while (or (rassoc char ntable) (rassoc char table))
14149 (setq char (1+ char)))
14150 (setq c2 c1))
14151 (setq c (or c2 char)))
14152 (if ingroup (push tg (car groups)))
14153 (setq tg (org-add-props tg nil 'face
14154 (cond
14155 ((not (assoc tg table))
14156 (org-get-todo-face tg))
14157 ((member tg current) c-face)
14158 ((member tg inherited) i-face))))
14159 (if (and (= cnt 0) (not ingroup)) (insert " "))
14160 (insert "[" c "] " tg (make-string
14161 (- fwidth 4 (length tg)) ?\ ))
14162 (push (cons tg c) ntable)
14163 (when (= (setq cnt (1+ cnt)) ncol)
14164 (insert "\n")
14165 (if ingroup (insert " "))
14166 (setq cnt 0)))))
14167 (setq ntable (nreverse ntable))
14168 (insert "\n")
14169 (goto-char (point-min))
14170 (if (not expert) (org-fit-window-to-buffer))
14171 (setq rtn
14172 (catch 'exit
14173 (while t
14174 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14175 (if (not groups) "no " "")
14176 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14177 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14178 (setq org-last-tag-selection-key c)
14179 (cond
14180 ((= c ?\r) (throw 'exit t))
14181 ((= c ?!)
14182 (setq groups (not groups))
14183 (goto-char (point-min))
14184 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14185 ((= c ?\C-c)
14186 (if (not expert)
14187 (org-fast-tag-show-exit
14188 (setq exit-after-next (not exit-after-next)))
14189 (setq expert nil)
14190 (delete-other-windows)
14191 (set-window-buffer (split-window-vertically) " *Org tags*")
14192 (org-switch-to-buffer-other-window " *Org tags*")
14193 (org-fit-window-to-buffer)))
14194 ((or (= c ?\C-g)
14195 (and (= c ?q) (not (rassoc c ntable))))
14196 (org-detach-overlay org-tags-overlay)
14197 (setq quit-flag t))
14198 ((= c ?\ )
14199 (setq current nil)
14200 (if exit-after-next (setq exit-after-next 'now)))
14201 ((= c ?\t)
14202 (condition-case nil
14203 (setq tg (org-icompleting-read
14204 "Tag: "
14205 (or buffer-tags
14206 (with-current-buffer buf
14207 (org-get-buffer-tags)))))
14208 (quit (setq tg "")))
14209 (when (string-match "\\S-" tg)
14210 (add-to-list 'buffer-tags (list tg))
14211 (if (member tg current)
14212 (setq current (delete tg current))
14213 (push tg current)))
14214 (if exit-after-next (setq exit-after-next 'now)))
14215 ((setq e (rassoc c todo-table) tg (car e))
14216 (with-current-buffer buf
14217 (save-excursion (org-todo tg)))
14218 (if exit-after-next (setq exit-after-next 'now)))
14219 ((setq e (rassoc c ntable) tg (car e))
14220 (if (member tg current)
14221 (setq current (delete tg current))
14222 (loop for g in groups do
14223 (if (member tg g)
14224 (mapc (lambda (x)
14225 (setq current (delete x current)))
14226 g)))
14227 (push tg current))
14228 (if exit-after-next (setq exit-after-next 'now))))
14230 ;; Create a sorted list
14231 (setq current
14232 (sort current
14233 (lambda (a b)
14234 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14235 (if (eq exit-after-next 'now) (throw 'exit t))
14236 (goto-char (point-min))
14237 (beginning-of-line 2)
14238 (delete-region (point) (point-at-eol))
14239 (org-fast-tag-insert "Current" current c-face)
14240 (org-set-current-tags-overlay current ov-prefix)
14241 (while (re-search-forward
14242 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14243 (setq tg (match-string 1))
14244 (add-text-properties
14245 (match-beginning 1) (match-end 1)
14246 (list 'face
14247 (cond
14248 ((member tg current) c-face)
14249 ((member tg inherited) i-face)
14250 (t (get-text-property (match-beginning 1) 'face))))))
14251 (goto-char (point-min)))))
14252 (org-detach-overlay org-tags-overlay)
14253 (if rtn
14254 (mapconcat 'identity current ":")
14255 nil))))
14257 (defun org-get-tags-string ()
14258 "Get the TAGS string in the current headline."
14259 (unless (org-at-heading-p t)
14260 (error "Not on a heading"))
14261 (save-excursion
14262 (beginning-of-line 1)
14263 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14264 (org-match-string-no-properties 1)
14265 "")))
14267 (defun org-get-tags ()
14268 "Get the list of tags specified in the current headline."
14269 (org-split-string (org-get-tags-string) ":"))
14271 (defun org-get-buffer-tags ()
14272 "Get a table of all tags used in the buffer, for completion."
14273 (let (tags)
14274 (save-excursion
14275 (goto-char (point-min))
14276 (while (re-search-forward
14277 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14278 (when (equal (char-after (point-at-bol 0)) ?*)
14279 (mapc (lambda (x) (add-to-list 'tags x))
14280 (org-split-string (org-match-string-no-properties 1) ":")))))
14281 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14282 (mapcar 'list tags)))
14284 ;;;; The mapping API
14286 (defun org-map-entries (func &optional match scope &rest skip)
14287 "Call FUNC at each headline selected by MATCH in SCOPE.
14289 FUNC is a function or a lisp form. The function will be called without
14290 arguments, with the cursor positioned at the beginning of the headline.
14291 The return values of all calls to the function will be collected and
14292 returned as a list.
14294 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14295 does not need to preserve point. After evaluation, the cursor will be
14296 moved to the end of the line (presumably of the headline of the
14297 processed entry) and search continues from there. Under some
14298 circumstances, this may not produce the wanted results. For example,
14299 if you have removed (e.g. archived) the current (sub)tree it could
14300 mean that the next entry will be skipped entirely. In such cases, you
14301 can specify the position from where search should continue by making
14302 FUNC set the variable `org-map-continue-from' to the desired buffer
14303 position.
14305 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14306 Only headlines that are matched by this query will be considered during
14307 the iteration. When MATCH is nil or t, all headlines will be
14308 visited by the iteration.
14310 SCOPE determines the scope of this command. It can be any of:
14312 nil The current buffer, respecting the restriction if any
14313 tree The subtree started with the entry at point
14314 region The entries within the active region, if any
14315 region-start-level
14316 The entries within the active region, but only those at
14317 the same level than the first one.
14318 file The current buffer, without restriction
14319 file-with-archives
14320 The current buffer, and any archives associated with it
14321 agenda All agenda files
14322 agenda-with-archives
14323 All agenda files with any archive files associated with them
14324 \(file1 file2 ...)
14325 If this is a list, all files in the list will be scanned
14327 The remaining args are treated as settings for the skipping facilities of
14328 the scanner. The following items can be given here:
14330 archive skip trees with the archive tag.
14331 comment skip trees with the COMMENT keyword
14332 function or Emacs Lisp form:
14333 will be used as value for `org-agenda-skip-function', so whenever
14334 the function returns t, FUNC will not be called for that
14335 entry and search will continue from the point where the
14336 function leaves it.
14338 If your function needs to retrieve the tags including inherited tags
14339 at the *current* entry, you can use the value of the variable
14340 `org-scanner-tags' which will be much faster than getting the value
14341 with `org-get-tags-at'. If your function gets properties with
14342 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14343 to t around the call to `org-entry-properties' to get the same speedup.
14344 Note that if your function moves around to retrieve tags and properties at
14345 a *different* entry, you cannot use these techniques."
14346 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14347 (not (org-region-active-p)))
14348 (let* ((org-agenda-archives-mode nil) ; just to make sure
14349 (org-agenda-skip-archived-trees (memq 'archive skip))
14350 (org-agenda-skip-comment-trees (memq 'comment skip))
14351 (org-agenda-skip-function
14352 (car (org-delete-all '(comment archive) skip)))
14353 (org-tags-match-list-sublevels t)
14354 (start-level (eq scope 'region-start-level))
14355 matcher file res
14356 org-todo-keywords-for-agenda
14357 org-done-keywords-for-agenda
14358 org-todo-keyword-alist-for-agenda
14359 org-drawers-for-agenda
14360 org-tag-alist-for-agenda
14361 todo-only)
14363 (cond
14364 ((eq match t) (setq matcher t))
14365 ((eq match nil) (setq matcher t))
14366 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14368 (save-excursion
14369 (save-restriction
14370 (cond ((eq scope 'tree)
14371 (org-back-to-heading t)
14372 (org-narrow-to-subtree)
14373 (setq scope nil))
14374 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14375 (org-region-active-p))
14376 ;; If needed, set start-level to a string like "2"
14377 (when start-level
14378 (save-excursion
14379 (goto-char (region-beginning))
14380 (unless (org-at-heading-p) (outline-next-heading))
14381 (setq start-level (org-current-level))))
14382 (narrow-to-region (region-beginning)
14383 (save-excursion
14384 (goto-char (region-end))
14385 (unless (and (bolp) (org-at-heading-p))
14386 (outline-next-heading))
14387 (point)))
14388 (setq scope nil)))
14390 (if (not scope)
14391 (progn
14392 (org-agenda-prepare-buffers
14393 (list (buffer-file-name (current-buffer))))
14394 (setq res (org-scan-tags func matcher todo-only start-level)))
14395 ;; Get the right scope
14396 (cond
14397 ((and scope (listp scope) (symbolp (car scope)))
14398 (setq scope (eval scope)))
14399 ((eq scope 'agenda)
14400 (setq scope (org-agenda-files t)))
14401 ((eq scope 'agenda-with-archives)
14402 (setq scope (org-agenda-files t))
14403 (setq scope (org-add-archive-files scope)))
14404 ((eq scope 'file)
14405 (setq scope (list (buffer-file-name))))
14406 ((eq scope 'file-with-archives)
14407 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14408 (org-agenda-prepare-buffers scope)
14409 (while (setq file (pop scope))
14410 (with-current-buffer (org-find-base-buffer-visiting file)
14411 (save-excursion
14412 (save-restriction
14413 (widen)
14414 (goto-char (point-min))
14415 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14416 res)))
14418 ;;;; Properties
14420 ;;; Setting and retrieving properties
14422 (defconst org-special-properties
14423 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14424 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14425 "The special properties valid in Org-mode.
14427 These are properties that are not defined in the property drawer,
14428 but in some other way.")
14430 (defconst org-default-properties
14431 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14432 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14433 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14434 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14435 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14436 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14437 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14438 "Some properties that are used by Org-mode for various purposes.
14439 Being in this list makes sure that they are offered for completion.")
14441 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14442 "Regular expression matching the first line of a property drawer.")
14444 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14445 "Regular expression matching the last line of a property drawer.")
14447 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14448 "Regular expression matching the first line of a property drawer.")
14450 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14451 "Regular expression matching the first line of a property drawer.")
14453 (defconst org-property-drawer-re
14454 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14455 org-property-end-re "\\)\n?")
14456 "Matches an entire property drawer.")
14458 (defconst org-clock-drawer-re
14459 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14460 org-property-end-re "\\)\n?")
14461 "Matches an entire clock drawer.")
14463 (defsubst org-re-property (property)
14464 "Return a regexp matching a PROPERTY line.
14465 Match group 1 will be set to the value."
14466 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14468 (defsubst org-re-property-keyword (property)
14469 "Return a regexp matching a PROPERTY line, possibly with no
14470 value for the property."
14471 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14473 (defun org-property-action ()
14474 "Do an action on properties."
14475 (interactive)
14476 (let (c)
14477 (org-at-property-p)
14478 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14479 (setq c (read-char-exclusive))
14480 (cond
14481 ((equal c ?s)
14482 (call-interactively 'org-set-property))
14483 ((equal c ?d)
14484 (call-interactively 'org-delete-property))
14485 ((equal c ?D)
14486 (call-interactively 'org-delete-property-globally))
14487 ((equal c ?c)
14488 (call-interactively 'org-compute-property-at-point))
14489 (t (error "No such property action %c" c)))))
14491 (defun org-inc-effort ()
14492 "Increment the value of the effort property in the current entry."
14493 (interactive)
14494 (org-set-effort nil t))
14496 (defun org-set-effort (&optional value increment)
14497 "Set the effort property of the current entry.
14498 With numerical prefix arg, use the nth allowed value, 0 stands for the
14499 10th allowed value.
14501 When INCREMENT is non-nil, set the property to the next allowed value."
14502 (interactive "P")
14503 (if (equal value 0) (setq value 10))
14504 (let* ((completion-ignore-case t)
14505 (prop org-effort-property)
14506 (cur (org-entry-get nil prop))
14507 (allowed (org-property-get-allowed-values nil prop 'table))
14508 (existing (mapcar 'list (org-property-values prop)))
14510 (val (cond
14511 ((stringp value) value)
14512 ((and allowed (integerp value))
14513 (or (car (nth (1- value) allowed))
14514 (car (org-last allowed))))
14515 ((and allowed increment)
14516 (or (caadr (member (list cur) allowed))
14517 (error "Allowed effort values are not set")))
14518 (allowed
14519 (message "Select 1-9,0, [RET%s]: %s"
14520 (if cur (concat "=" cur) "")
14521 (mapconcat 'car allowed " "))
14522 (setq rpl (read-char-exclusive))
14523 (if (equal rpl ?\r)
14525 (setq rpl (- rpl ?0))
14526 (if (equal rpl 0) (setq rpl 10))
14527 (if (and (> rpl 0) (<= rpl (length allowed)))
14528 (car (nth (1- rpl) allowed))
14529 (org-completing-read "Effort: " allowed nil))))
14531 (let (org-completion-use-ido org-completion-use-iswitchb)
14532 (org-completing-read
14533 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14534 (concat "[" cur "]") "")
14535 ": ")
14536 existing nil nil "" nil cur))))))
14537 (unless (equal (org-entry-get nil prop) val)
14538 (org-entry-put nil prop val))
14539 (message "%s is now %s" prop val)))
14541 (defun org-at-property-p ()
14542 "Is cursor inside a property drawer?"
14543 (save-excursion
14544 (beginning-of-line 1)
14545 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14546 (save-match-data ;; Used by calling procedures
14547 (let ((p (point))
14548 (range (unless (org-before-first-heading-p)
14549 (org-get-property-block))))
14550 (and range (<= (car range) p) (< p (cdr range))))))))
14552 (defun org-get-property-block (&optional beg end force)
14553 "Return the (beg . end) range of the body of the property drawer.
14554 BEG and END are the beginning and end of the current subtree, or of
14555 the part before the first headline. If they are not given, they will
14556 be found. If the drawer does not exist and FORCE is non-nil, create
14557 the drawer."
14558 (catch 'exit
14559 (save-excursion
14560 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14561 (progn (org-back-to-heading t) (point))))
14562 (end (or end (and (not (outline-next-heading)) (point-max))
14563 (point))))
14564 (goto-char beg)
14565 (if (re-search-forward org-property-start-re end t)
14566 (setq beg (1+ (match-end 0)))
14567 (if force
14568 (save-excursion
14569 (org-insert-property-drawer)
14570 (setq end (progn (outline-next-heading) (point))))
14571 (throw 'exit nil))
14572 (goto-char beg)
14573 (if (re-search-forward org-property-start-re end t)
14574 (setq beg (1+ (match-end 0)))))
14575 (if (re-search-forward org-property-end-re end t)
14576 (setq end (match-beginning 0))
14577 (or force (throw 'exit nil))
14578 (goto-char beg)
14579 (setq end beg)
14580 (org-indent-line)
14581 (insert ":END:\n"))
14582 (cons beg end)))))
14584 (defun org-entry-properties (&optional pom which specific)
14585 "Get all properties of the entry at point-or-marker POM.
14586 This includes the TODO keyword, the tags, time strings for deadline,
14587 scheduled, and clocking, and any additional properties defined in the
14588 entry. The return value is an alist, keys may occur multiple times
14589 if the property key was used several times.
14590 POM may also be nil, in which case the current entry is used.
14591 If WHICH is nil or `all', get all properties. If WHICH is
14592 `special' or `standard', only get that subclass. If WHICH
14593 is a string only get exactly this property. SPECIFIC can be a string, the
14594 specific property we are interested in. Specifying it can speed
14595 things up because then unnecessary parsing is avoided."
14596 (setq which (or which 'all))
14597 (org-with-point-at pom
14598 (let ((clockstr (substring org-clock-string 0 -1))
14599 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14600 (case-fold-search nil)
14601 beg end range props sum-props key key1 value string clocksum clocksumt)
14602 (save-excursion
14603 (when (condition-case nil
14604 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14605 (error nil))
14606 (setq beg (point))
14607 (setq sum-props (get-text-property (point) 'org-summaries))
14608 (setq clocksum (get-text-property (point) :org-clock-minutes)
14609 clocksumt (get-text-property (point) :org-clock-minutes-today))
14610 (outline-next-heading)
14611 (setq end (point))
14612 (when (memq which '(all special))
14613 ;; Get the special properties, like TODO and tags
14614 (goto-char beg)
14615 (when (and (or (not specific) (string= specific "TODO"))
14616 (looking-at org-todo-line-regexp) (match-end 2))
14617 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14618 (when (and (or (not specific) (string= specific "PRIORITY"))
14619 (looking-at org-priority-regexp))
14620 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14621 (when (or (not specific) (string= specific "FILE"))
14622 (push (cons "FILE" buffer-file-name) props))
14623 (when (and (or (not specific) (string= specific "TAGS"))
14624 (setq value (org-get-tags-string))
14625 (string-match "\\S-" value))
14626 (push (cons "TAGS" value) props))
14627 (when (and (or (not specific) (string= specific "ALLTAGS"))
14628 (setq value (org-get-tags-at)))
14629 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14630 ":"))
14631 props))
14632 (when (or (not specific) (string= specific "BLOCKED"))
14633 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14634 (when (or (not specific)
14635 (member specific
14636 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14637 "TIMESTAMP" "TIMESTAMP_IA")))
14638 (catch 'match
14639 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14640 (setq key (if (match-end 1)
14641 (substring (org-match-string-no-properties 1)
14642 0 -1))
14643 string (if (equal key clockstr)
14644 (org-trim
14645 (buffer-substring-no-properties
14646 (match-beginning 3) (goto-char
14647 (point-at-eol))))
14648 (substring (org-match-string-no-properties 3)
14649 1 -1)))
14650 ;; Get the correct property name from the key. This is
14651 ;; necessary if the user has configured time keywords.
14652 (setq key1 (concat key ":"))
14653 (cond
14654 ((not key)
14655 (setq key
14656 (if (= (char-after (match-beginning 3)) ?\[)
14657 "TIMESTAMP_IA" "TIMESTAMP")))
14658 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14659 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14660 ((equal key1 org-closed-string) (setq key "CLOSED"))
14661 ((equal key1 org-clock-string) (setq key "CLOCK")))
14662 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14663 (progn
14664 (push (cons key string) props)
14665 ;; no need to search further if match is found
14666 (throw 'match t))
14667 (when (or (equal key "CLOCK") (not (assoc key props)))
14668 (push (cons key string) props)))))))
14670 (when (memq which '(all standard))
14671 ;; Get the standard properties, like :PROP: ...
14672 (setq range (org-get-property-block beg end))
14673 (when range
14674 (goto-char (car range))
14675 (while (re-search-forward
14676 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14677 (cdr range) t)
14678 (setq key (org-match-string-no-properties 1)
14679 value (org-trim (or (org-match-string-no-properties 2) "")))
14680 (unless (member key excluded)
14681 (push (cons key (or value "")) props)))))
14682 (if clocksum
14683 (push (cons "CLOCKSUM"
14684 (org-columns-number-to-string (/ (float clocksum) 60.)
14685 'add_times))
14686 props))
14687 (if clocksumt
14688 (push (cons "CLOCKSUM_T"
14689 (org-columns-number-to-string (/ (float clocksumt) 60.)
14690 'add_times))
14691 props))
14692 (unless (assoc "CATEGORY" props)
14693 (push (cons "CATEGORY" (org-get-category)) props))
14694 (append sum-props (nreverse props)))))))
14696 (defun org-entry-get (pom property &optional inherit literal-nil)
14697 "Get value of PROPERTY for entry or content at point-or-marker POM.
14698 If INHERIT is non-nil and the entry does not have the property,
14699 then also check higher levels of the hierarchy.
14700 If INHERIT is the symbol `selective', use inheritance only if the setting
14701 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14702 If the property is present but empty, the return value is the empty string.
14703 If the property is not present at all, nil is returned.
14705 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14706 do not interpret it as the list atom nil. This is used for inheritance
14707 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14708 (org-with-point-at pom
14709 (if (and inherit (if (eq inherit 'selective)
14710 (org-property-inherit-p property)
14712 (org-entry-get-with-inheritance property literal-nil)
14713 (if (member property org-special-properties)
14714 ;; We need a special property. Use `org-entry-properties' to
14715 ;; retrieve it, but specify the wanted property
14716 (cdr (assoc property (org-entry-properties nil 'special property)))
14717 (let* ((range (org-get-property-block))
14718 (props (list (or (assoc property org-file-properties)
14719 (assoc property org-global-properties)
14720 (assoc property org-global-properties-fixed))))
14721 (ap (lambda (key)
14722 (when (re-search-forward
14723 (org-re-property key) (cdr range) t)
14724 (setq props
14725 (org-update-property-plist
14727 (if (match-end 1)
14728 (org-match-string-no-properties 1) "")
14729 props)))))
14730 val)
14731 (when (and range (goto-char (car range)))
14732 (funcall ap property)
14733 (goto-char (car range))
14734 (while (funcall ap (concat property "+")))
14735 (setq val (cdr (assoc property props)))
14736 (when val (if literal-nil val (org-not-nil val)))))))))
14738 (defun org-property-or-variable-value (var &optional inherit)
14739 "Check if there is a property fixing the value of VAR.
14740 If yes, return this value. If not, return the current value of the variable."
14741 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14742 (if (and prop (stringp prop) (string-match "\\S-" prop))
14743 (read prop)
14744 (symbol-value var))))
14746 (defun org-entry-delete (pom property)
14747 "Delete the property PROPERTY from entry at point-or-marker POM."
14748 (org-with-point-at pom
14749 (if (member property org-special-properties)
14750 nil ; cannot delete these properties.
14751 (let ((range (org-get-property-block)))
14752 (if (and range
14753 (goto-char (car range))
14754 (re-search-forward
14755 (org-re-property property)
14756 (cdr range) t))
14757 (progn
14758 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14760 nil)))))
14762 ;; Multi-values properties are properties that contain multiple values
14763 ;; These values are assumed to be single words, separated by whitespace.
14764 (defun org-entry-add-to-multivalued-property (pom property value)
14765 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14766 (let* ((old (org-entry-get pom property))
14767 (values (and old (org-split-string old "[ \t]"))))
14768 (setq value (org-entry-protect-space value))
14769 (unless (member value values)
14770 (setq values (cons value values))
14771 (org-entry-put pom property
14772 (mapconcat 'identity values " ")))))
14774 (defun org-entry-remove-from-multivalued-property (pom property value)
14775 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14776 (let* ((old (org-entry-get pom property))
14777 (values (and old (org-split-string old "[ \t]"))))
14778 (setq value (org-entry-protect-space value))
14779 (when (member value values)
14780 (setq values (delete value values))
14781 (org-entry-put pom property
14782 (mapconcat 'identity values " ")))))
14784 (defun org-entry-member-in-multivalued-property (pom property value)
14785 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14786 (let* ((old (org-entry-get pom property))
14787 (values (and old (org-split-string old "[ \t]"))))
14788 (setq value (org-entry-protect-space value))
14789 (member value values)))
14791 (defun org-entry-get-multivalued-property (pom property)
14792 "Return a list of values in a multivalued property."
14793 (let* ((value (org-entry-get pom property))
14794 (values (and value (org-split-string value "[ \t]"))))
14795 (mapcar 'org-entry-restore-space values)))
14797 (defun org-entry-put-multivalued-property (pom property &rest values)
14798 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14799 VALUES should be a list of strings. Spaces will be protected."
14800 (org-entry-put pom property
14801 (mapconcat 'org-entry-protect-space values " "))
14802 (let* ((value (org-entry-get pom property))
14803 (values (and value (org-split-string value "[ \t]"))))
14804 (mapcar 'org-entry-restore-space values)))
14806 (defun org-entry-protect-space (s)
14807 "Protect spaces and newline in string S."
14808 (while (string-match " " s)
14809 (setq s (replace-match "%20" t t s)))
14810 (while (string-match "\n" s)
14811 (setq s (replace-match "%0A" t t s)))
14814 (defun org-entry-restore-space (s)
14815 "Restore spaces and newline in string S."
14816 (while (string-match "%20" s)
14817 (setq s (replace-match " " t t s)))
14818 (while (string-match "%0A" s)
14819 (setq s (replace-match "\n" t t s)))
14822 (defvar org-entry-property-inherited-from (make-marker)
14823 "Marker pointing to the entry from where a property was inherited.
14824 Each call to `org-entry-get-with-inheritance' will set this marker to the
14825 location of the entry where the inheritance search matched. If there was
14826 no match, the marker will point nowhere.
14827 Note that also `org-entry-get' calls this function, if the INHERIT flag
14828 is set.")
14830 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14831 "Get PROPERTY of entry or content at point, search higher levels if needed.
14832 The search will stop at the first ancestor which has the property defined.
14833 If the value found is \"nil\", return nil to show that the property
14834 should be considered as undefined (this is the meaning of nil here).
14835 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14836 (move-marker org-entry-property-inherited-from nil)
14837 (let (tmp)
14838 (save-excursion
14839 (save-restriction
14840 (widen)
14841 (catch 'ex
14842 (while t
14843 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14844 (or (ignore-errors (org-back-to-heading t))
14845 (goto-char (point-min)))
14846 (move-marker org-entry-property-inherited-from (point))
14847 (throw 'ex tmp))
14848 (or (ignore-errors (org-up-heading-safe))
14849 (throw 'ex nil))))))
14850 (setq tmp (or tmp
14851 (cdr (assoc property org-file-properties))
14852 (cdr (assoc property org-global-properties))
14853 (cdr (assoc property org-global-properties-fixed))))
14854 (if literal-nil tmp (org-not-nil tmp))))
14856 (defvar org-property-changed-functions nil
14857 "Hook called when the value of a property has changed.
14858 Each hook function should accept two arguments, the name of the property
14859 and the new value.")
14861 (defun org-entry-put (pom property value)
14862 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14863 (org-with-point-at pom
14864 (org-back-to-heading t)
14865 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14866 range)
14867 (cond
14868 ((equal property "TODO")
14869 (when (and (stringp value) (string-match "\\S-" value)
14870 (not (member value org-todo-keywords-1)))
14871 (error "\"%s\" is not a valid TODO state" value))
14872 (if (or (not value)
14873 (not (string-match "\\S-" value)))
14874 (setq value 'none))
14875 (org-todo value)
14876 (org-set-tags nil 'align))
14877 ((equal property "PRIORITY")
14878 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14879 (string-to-char value) ?\ ))
14880 (org-set-tags nil 'align))
14881 ((equal property "CLOCKSUM")
14882 (if (not (re-search-forward
14883 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14884 (error "Cannot find a clock log")
14885 (goto-char (- (match-end 1) 2))
14886 (cond
14887 ((eq value 'earlier) (org-timestamp-down))
14888 ((eq value 'later) (org-timestamp-up)))
14889 (org-clock-sum-current-item)))
14890 ((equal property "SCHEDULED")
14891 (if (re-search-forward org-scheduled-time-regexp end t)
14892 (cond
14893 ((eq value 'earlier) (org-timestamp-change -1 'day))
14894 ((eq value 'later) (org-timestamp-change 1 'day))
14895 (t (call-interactively 'org-schedule)))
14896 (call-interactively 'org-schedule)))
14897 ((equal property "DEADLINE")
14898 (if (re-search-forward org-deadline-time-regexp end t)
14899 (cond
14900 ((eq value 'earlier) (org-timestamp-change -1 'day))
14901 ((eq value 'later) (org-timestamp-change 1 'day))
14902 (t (call-interactively 'org-deadline)))
14903 (call-interactively 'org-deadline)))
14904 ((member property org-special-properties)
14905 (error "The %s property can not yet be set with `org-entry-put'"
14906 property))
14907 (t ; a non-special property
14908 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14909 (setq range (org-get-property-block beg end 'force))
14910 (goto-char (car range))
14911 (if (re-search-forward
14912 (org-re-property-keyword property) (cdr range) t)
14913 (progn
14914 (delete-region (match-beginning 0) (match-end 0))
14915 (goto-char (match-beginning 0)))
14916 (goto-char (cdr range))
14917 (insert "\n")
14918 (backward-char 1)
14919 (org-indent-line))
14920 (insert ":" property ":")
14921 (and value (insert " " value))
14922 (org-indent-line)))))
14923 (run-hook-with-args 'org-property-changed-functions property value)))
14925 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14926 "Get all property keys in the current buffer.
14927 With INCLUDE-SPECIALS, also list the special properties that reflect things
14928 like tags and TODO state.
14929 With INCLUDE-DEFAULTS, also include properties that has special meaning
14930 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14931 and others.
14932 With INCLUDE-COLUMNS, also include property names given in COLUMN
14933 formats in the current buffer."
14934 (let (rtn range cfmt s p)
14935 (save-excursion
14936 (save-restriction
14937 (widen)
14938 (goto-char (point-min))
14939 (while (re-search-forward org-property-start-re nil t)
14940 (setq range (org-get-property-block))
14941 (goto-char (car range))
14942 (while (re-search-forward
14943 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14944 (cdr range) t)
14945 (add-to-list 'rtn (org-match-string-no-properties 1)))
14946 (outline-next-heading))))
14948 (when include-specials
14949 (setq rtn (append org-special-properties rtn)))
14951 (when include-defaults
14952 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14953 (add-to-list 'rtn org-effort-property))
14955 (when include-columns
14956 (save-excursion
14957 (save-restriction
14958 (widen)
14959 (goto-char (point-min))
14960 (while (re-search-forward
14961 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14962 nil t)
14963 (setq cfmt (match-string 2) s 0)
14964 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14965 cfmt s)
14966 (setq s (match-end 0)
14967 p (match-string 1 cfmt))
14968 (unless (or (equal p "ITEM")
14969 (member p org-special-properties))
14970 (add-to-list 'rtn (match-string 1 cfmt))))))))
14972 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14974 (defun org-property-values (key)
14975 "Return a list of all values of property KEY in the current buffer."
14976 (save-excursion
14977 (save-restriction
14978 (widen)
14979 (goto-char (point-min))
14980 (let ((re (org-re-property key))
14981 values)
14982 (while (re-search-forward re nil t)
14983 (add-to-list 'values (org-trim (match-string 1))))
14984 (delete "" values)))))
14986 (defun org-insert-property-drawer ()
14987 "Insert a property drawer into the current entry."
14988 (org-back-to-heading t)
14989 (looking-at org-outline-regexp)
14990 (let ((indent (if org-adapt-indentation
14991 (- (match-end 0) (match-beginning 0))
14993 (beg (point))
14994 (re (concat "^[ \t]*" org-keyword-time-regexp))
14995 end hiddenp)
14996 (outline-next-heading)
14997 (setq end (point))
14998 (goto-char beg)
14999 (while (re-search-forward re end t))
15000 (setq hiddenp (outline-invisible-p))
15001 (end-of-line 1)
15002 (and (equal (char-after) ?\n) (forward-char 1))
15003 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15004 (if (member (match-string 1) '("CLOCK:" ":END:"))
15005 ;; just skip this line
15006 (beginning-of-line 2)
15007 ;; Drawer start, find the end
15008 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15009 (beginning-of-line 1)))
15010 (org-skip-over-state-notes)
15011 (skip-chars-backward " \t\n\r")
15012 (if (eq (char-before) ?*) (forward-char 1))
15013 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15014 (beginning-of-line 0)
15015 (org-indent-to-column indent)
15016 (beginning-of-line 2)
15017 (org-indent-to-column indent)
15018 (beginning-of-line 0)
15019 (if hiddenp
15020 (save-excursion
15021 (org-back-to-heading t)
15022 (hide-entry))
15023 (org-flag-drawer t))))
15025 (defun org-insert-drawer (&optional arg drawer)
15026 "Insert a drawer at point.
15028 Optional argument DRAWER, when non-nil, is a string representing
15029 drawer's name. Otherwise, the user is prompted for a name.
15031 If a region is active, insert the drawer around that region
15032 instead.
15034 Point is left between drawer's boundaries."
15035 (interactive "P")
15036 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15037 "LOGBOOK"))
15038 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15039 ;; internally by Org. They are meant to be inserted
15040 ;; automatically.
15041 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15042 ;; Remove system drawers from list. Note: For some reason,
15043 ;; `org-completing-read' ignores the predicate while
15044 ;; `completing-read' handles it fine.
15045 (drawer (if arg "PROPERTIES"
15046 (or drawer
15047 (completing-read
15048 "Drawer: " org-drawers
15049 (lambda (d) (not (member d system-drawers))))))))
15050 (cond
15051 ;; With C-u, fall back on `org-insert-property-drawer'
15052 (arg (org-insert-property-drawer))
15053 ;; With an active region, insert a drawer at point.
15054 ((not (org-region-active-p))
15055 (progn
15056 (unless (bolp) (insert "\n"))
15057 (insert (format ":%s:\n\n:END:\n" drawer))
15058 (forward-line -2)))
15059 ;; Otherwise, insert the drawer at point
15061 (let ((rbeg (region-beginning))
15062 (rend (copy-marker (region-end))))
15063 (unwind-protect
15064 (progn
15065 (goto-char rbeg)
15066 (beginning-of-line)
15067 (when (save-excursion
15068 (re-search-forward org-outline-regexp-bol rend t))
15069 (error "Drawers cannot contain headlines"))
15070 ;; Position point at the beginning of the first
15071 ;; non-blank line in region. Insert drawer's opening
15072 ;; there, then indent it.
15073 (org-skip-whitespace)
15074 (beginning-of-line)
15075 (insert ":" drawer ":\n")
15076 (forward-line -1)
15077 (indent-for-tab-command)
15078 ;; Move point to the beginning of the first blank line
15079 ;; after the last non-blank line in region. Insert
15080 ;; drawer's closing, then indent it.
15081 (goto-char rend)
15082 (skip-chars-backward " \r\t\n")
15083 (insert "\n:END:")
15084 (deactivate-mark t)
15085 (indent-for-tab-command)
15086 (unless (eolp) (insert "\n")))
15087 ;; Clear marker, whatever the outcome of insertion is.
15088 (set-marker rend nil)))))))
15090 (defvar org-property-set-functions-alist nil
15091 "Property set function alist.
15092 Each entry should have the following format:
15094 (PROPERTY . READ-FUNCTION)
15096 The read function will be called with the same argument as
15097 `org-completing-read'.")
15099 (defun org-set-property-function (property)
15100 "Get the function that should be used to set PROPERTY.
15101 This is computed according to `org-property-set-functions-alist'."
15102 (or (cdr (assoc property org-property-set-functions-alist))
15103 'org-completing-read))
15105 (defun org-read-property-value (property)
15106 "Read PROPERTY value from user."
15107 (let* ((completion-ignore-case t)
15108 (allowed (org-property-get-allowed-values nil property 'table))
15109 (cur (org-entry-get nil property))
15110 (prompt (concat property " value"
15111 (if (and cur (string-match "\\S-" cur))
15112 (concat " [" cur "]") "") ": "))
15113 (set-function (org-set-property-function property))
15114 (val (if allowed
15115 (funcall set-function prompt allowed nil
15116 (not (get-text-property 0 'org-unrestricted
15117 (caar allowed))))
15118 (let (org-completion-use-ido org-completion-use-iswitchb)
15119 (funcall set-function prompt
15120 (mapcar 'list (org-property-values property))
15121 nil nil "" nil cur)))))
15122 (if (equal val "")
15124 val)))
15126 (defvar org-last-set-property nil)
15127 (defvar org-last-set-property-value nil)
15128 (defun org-read-property-name ()
15129 "Read a property name."
15130 (let* ((completion-ignore-case t)
15131 (keys (org-buffer-property-keys nil t t))
15132 (default-prop (or (save-excursion
15133 (save-match-data
15134 (beginning-of-line)
15135 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15136 (null (string= (match-string 1) "END"))
15137 (match-string 1))))
15138 org-last-set-property))
15139 (property (org-icompleting-read
15140 (concat "Property"
15141 (if default-prop (concat " [" default-prop "]") "")
15142 ": ")
15143 (mapcar 'list keys)
15144 nil nil nil nil
15145 default-prop)))
15146 (if (member property keys)
15147 property
15148 (or (cdr (assoc (downcase property)
15149 (mapcar (lambda (x) (cons (downcase x) x))
15150 keys)))
15151 property))))
15153 (defun org-set-property-and-value (use-last)
15154 "Allow to set [PROPERTY]: [value] direction from prompt.
15155 When use-default, don't even ask, just use the last
15156 \"[PROPERTY]: [value]\" string from the history."
15157 (interactive "P")
15158 (let* ((completion-ignore-case t)
15159 (pv (or (and use-last org-last-set-property-value)
15160 (org-completing-read
15161 "Enter a \"[Property]: [value]\" pair: "
15162 nil nil nil nil nil
15163 org-last-set-property-value)))
15164 prop val)
15165 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15166 (setq prop (match-string 1 pv)
15167 val (match-string 2 pv))
15168 (org-set-property prop val))))
15170 (defun org-set-property (property value)
15171 "In the current entry, set PROPERTY to VALUE.
15172 When called interactively, this will prompt for a property name, offering
15173 completion on existing and default properties. And then it will prompt
15174 for a value, offering completion either on allowed values (via an inherited
15175 xxx_ALL property) or on existing values in other instances of this property
15176 in the current file."
15177 (interactive (list nil nil))
15178 (let* ((property (or property (org-read-property-name)))
15179 (value (or value (org-read-property-value property)))
15180 (fn (cdr (assoc property org-properties-postprocess-alist))))
15181 (setq org-last-set-property property)
15182 (setq org-last-set-property-value (concat property ": " value))
15183 ;; Possibly postprocess the inserted value:
15184 (when fn (setq value (funcall fn value)))
15185 (unless (equal (org-entry-get nil property) value)
15186 (org-entry-put nil property value))))
15188 (defun org-delete-property (property)
15189 "In the current entry, delete PROPERTY."
15190 (interactive
15191 (let* ((completion-ignore-case t)
15192 (prop (org-icompleting-read "Property: "
15193 (org-entry-properties nil 'standard))))
15194 (list prop)))
15195 (message "Property %s %s" property
15196 (if (org-entry-delete nil property)
15197 "deleted"
15198 "was not present in the entry")))
15200 (defun org-delete-property-globally (property)
15201 "Remove PROPERTY globally, from all entries."
15202 (interactive
15203 (let* ((completion-ignore-case t)
15204 (prop (org-icompleting-read
15205 "Globally remove property: "
15206 (mapcar 'list (org-buffer-property-keys)))))
15207 (list prop)))
15208 (save-excursion
15209 (save-restriction
15210 (widen)
15211 (goto-char (point-min))
15212 (let ((cnt 0))
15213 (while (re-search-forward
15214 (org-re-property property)
15215 nil t)
15216 (setq cnt (1+ cnt))
15217 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15218 (message "Property \"%s\" removed from %d entries" property cnt)))))
15220 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15222 (defun org-compute-property-at-point ()
15223 "Compute the property at point.
15224 This looks for an enclosing column format, extracts the operator and
15225 then applies it to the property in the column format's scope."
15226 (interactive)
15227 (unless (org-at-property-p)
15228 (error "Not at a property"))
15229 (let ((prop (org-match-string-no-properties 2)))
15230 (org-columns-get-format-and-top-level)
15231 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15232 (error "No operator defined for property %s" prop))
15233 (org-columns-compute prop)))
15235 (defvar org-property-allowed-value-functions nil
15236 "Hook for functions supplying allowed values for a specific property.
15237 The functions must take a single argument, the name of the property, and
15238 return a flat list of allowed values. If \":ETC\" is one of
15239 the values, this means that these values are intended as defaults for
15240 completion, but that other values should be allowed too.
15241 The functions must return nil if they are not responsible for this
15242 property.")
15244 (defun org-property-get-allowed-values (pom property &optional table)
15245 "Get allowed values for the property PROPERTY.
15246 When TABLE is non-nil, return an alist that can directly be used for
15247 completion."
15248 (let (vals)
15249 (cond
15250 ((equal property "TODO")
15251 (setq vals (org-with-point-at pom
15252 (append org-todo-keywords-1 '("")))))
15253 ((equal property "PRIORITY")
15254 (let ((n org-lowest-priority))
15255 (while (>= n org-highest-priority)
15256 (push (char-to-string n) vals)
15257 (setq n (1- n)))))
15258 ((member property org-special-properties))
15259 ((setq vals (run-hook-with-args-until-success
15260 'org-property-allowed-value-functions property)))
15262 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15263 (when (and vals (string-match "\\S-" vals))
15264 (setq vals (car (read-from-string (concat "(" vals ")"))))
15265 (setq vals (mapcar (lambda (x)
15266 (cond ((stringp x) x)
15267 ((numberp x) (number-to-string x))
15268 ((symbolp x) (symbol-name x))
15269 (t "???")))
15270 vals)))))
15271 (when (member ":ETC" vals)
15272 (setq vals (remove ":ETC" vals))
15273 (org-add-props (car vals) '(org-unrestricted t)))
15274 (if table (mapcar 'list vals) vals)))
15276 (defun org-property-previous-allowed-value (&optional previous)
15277 "Switch to the next allowed value for this property."
15278 (interactive)
15279 (org-property-next-allowed-value t))
15281 (defun org-property-next-allowed-value (&optional previous)
15282 "Switch to the next allowed value for this property."
15283 (interactive)
15284 (unless (org-at-property-p)
15285 (error "Not at a property"))
15286 (let* ((key (match-string 2))
15287 (value (match-string 3))
15288 (allowed (or (org-property-get-allowed-values (point) key)
15289 (and (member value '("[ ]" "[-]" "[X]"))
15290 '("[ ]" "[X]"))))
15291 nval)
15292 (unless allowed
15293 (error "Allowed values for this property have not been defined"))
15294 (if previous (setq allowed (reverse allowed)))
15295 (if (member value allowed)
15296 (setq nval (car (cdr (member value allowed)))))
15297 (setq nval (or nval (car allowed)))
15298 (if (equal nval value)
15299 (error "Only one allowed value for this property"))
15300 (org-at-property-p)
15301 (replace-match (concat " :" key ": " nval) t t)
15302 (org-indent-line)
15303 (beginning-of-line 1)
15304 (skip-chars-forward " \t")
15305 (run-hook-with-args 'org-property-changed-functions key nval)))
15307 (defun org-find-olp (path &optional this-buffer)
15308 "Return a marker pointing to the entry at outline path OLP.
15309 If anything goes wrong, throw an error.
15310 You can wrap this call to catch the error like this:
15312 (condition-case msg
15313 (org-mobile-locate-entry (match-string 4))
15314 (error (nth 1 msg)))
15316 The return value will then be either a string with the error message,
15317 or a marker if everything is OK.
15319 If THIS-BUFFER is set, the outline path does not contain a file,
15320 only headings."
15321 (let* ((file (if this-buffer buffer-file-name (pop path)))
15322 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15323 (level 1)
15324 (lmin 1)
15325 (lmax 1)
15326 limit re end found pos heading cnt flevel)
15327 (unless buffer (error "File not found :%s" file))
15328 (with-current-buffer buffer
15329 (save-excursion
15330 (save-restriction
15331 (widen)
15332 (setq limit (point-max))
15333 (goto-char (point-min))
15334 (while (setq heading (pop path))
15335 (setq re (format org-complex-heading-regexp-format
15336 (regexp-quote heading)))
15337 (setq cnt 0 pos (point))
15338 (while (re-search-forward re end t)
15339 (setq level (- (match-end 1) (match-beginning 1)))
15340 (if (and (>= level lmin) (<= level lmax))
15341 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15342 (when (= cnt 0) (error "Heading not found on level %d: %s"
15343 lmax heading))
15344 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15345 lmax heading))
15346 (goto-char found)
15347 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15348 (setq end (save-excursion (org-end-of-subtree t t))))
15349 (when (org-at-heading-p)
15350 (point-marker)))))))
15352 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15353 "Find node HEADING in BUFFER.
15354 Return a marker to the heading if it was found, or nil if not.
15355 If POS-ONLY is set, return just the position instead of a marker.
15357 The heading text must match exact, but it may have a TODO keyword,
15358 a priority cookie and tags in the standard locations."
15359 (with-current-buffer (or buffer (current-buffer))
15360 (save-excursion
15361 (save-restriction
15362 (widen)
15363 (goto-char (point-min))
15364 (let (case-fold-search)
15365 (if (re-search-forward
15366 (format org-complex-heading-regexp-format
15367 (regexp-quote heading)) nil t)
15368 (if pos-only
15369 (match-beginning 0)
15370 (move-marker (make-marker) (match-beginning 0)))))))))
15372 (defun org-find-exact-heading-in-directory (heading &optional dir)
15373 "Find Org node headline HEADING in all .org files in directory DIR.
15374 When the target headline is found, return a marker to this location."
15375 (let ((files (directory-files (or dir default-directory)
15376 nil "\\`[^.#].*\\.org\\'"))
15377 file visiting m buffer)
15378 (catch 'found
15379 (while (setq file (pop files))
15380 (message "trying %s" file)
15381 (setq visiting (org-find-base-buffer-visiting file))
15382 (setq buffer (or visiting (find-file-noselect file)))
15383 (setq m (org-find-exact-headline-in-buffer
15384 heading buffer))
15385 (when (and (not m) (not visiting)) (kill-buffer buffer))
15386 (and m (throw 'found m))))))
15388 (defun org-find-entry-with-id (ident)
15389 "Locate the entry that contains the ID property with exact value IDENT.
15390 IDENT can be a string, a symbol or a number, this function will search for
15391 the string representation of it.
15392 Return the position where this entry starts, or nil if there is no such entry."
15393 (interactive "sID: ")
15394 (let ((id (cond
15395 ((stringp ident) ident)
15396 ((symbol-name ident) (symbol-name ident))
15397 ((numberp ident) (number-to-string ident))
15398 (t (error "IDENT %s must be a string, symbol or number" ident))))
15399 (case-fold-search nil))
15400 (save-excursion
15401 (save-restriction
15402 (widen)
15403 (goto-char (point-min))
15404 (when (re-search-forward
15405 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15406 nil t)
15407 (org-back-to-heading t)
15408 (point))))))
15410 ;;;; Timestamps
15412 (defvar org-last-changed-timestamp nil)
15413 (defvar org-last-inserted-timestamp nil
15414 "The last time stamp inserted with `org-insert-time-stamp'.")
15415 (defvar org-time-was-given) ; dynamically scoped parameter
15416 (defvar org-end-time-was-given) ; dynamically scoped parameter
15417 (defvar org-ts-what) ; dynamically scoped parameter
15419 (defun org-time-stamp (arg &optional inactive)
15420 "Prompt for a date/time and insert a time stamp.
15421 If the user specifies a time like HH:MM or if this command is
15422 called with at least one prefix argument, the time stamp contains
15423 the date and the time. Otherwise, only the date is be included.
15425 All parts of a date not specified by the user is filled in from
15426 the current date/time. So if you just press return without
15427 typing anything, the time stamp will represent the current
15428 date/time.
15430 If there is already a timestamp at the cursor, it will be
15431 modified.
15433 With two universal prefix arguments, insert an active timestamp
15434 with the current time without prompting the user."
15435 (interactive "P")
15436 (let* ((ts nil)
15437 (default-time
15438 ;; Default time is either today, or, when entering a range,
15439 ;; the range start.
15440 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15441 (save-excursion
15442 (re-search-backward
15443 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15444 (- (point) 20) t)))
15445 (apply 'encode-time (org-parse-time-string (match-string 1)))
15446 (current-time)))
15447 (default-input (and ts (org-get-compact-tod ts)))
15448 (repeater (save-excursion
15449 (save-match-data
15450 (beginning-of-line)
15451 (when (re-search-forward
15452 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15453 (save-excursion (progn (end-of-line) (point))) t)
15454 (match-string 0)))))
15455 org-time-was-given org-end-time-was-given time)
15456 (cond
15457 ((and (org-at-timestamp-p t)
15458 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15459 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15460 (insert "--")
15461 (setq time (let ((this-command this-command))
15462 (org-read-date arg 'totime nil nil
15463 default-time default-input inactive)))
15464 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15465 ((org-at-timestamp-p t)
15466 (setq time (let ((this-command this-command))
15467 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15468 (when (org-at-timestamp-p t) ; just to get the match data
15469 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15470 (replace-match "")
15471 (setq org-last-changed-timestamp
15472 (org-insert-time-stamp
15473 time (or org-time-was-given arg)
15474 inactive nil nil (list org-end-time-was-given)))
15475 (when repeater (goto-char (1- (point))) (insert " " repeater)
15476 (setq org-last-changed-timestamp
15477 (concat (substring org-last-inserted-timestamp 0 -1)
15478 " " repeater ">"))))
15479 (message "Timestamp updated"))
15480 ((equal arg '(16))
15481 (org-insert-time-stamp (current-time) t))
15483 (setq time (let ((this-command this-command))
15484 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15485 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15486 nil nil (list org-end-time-was-given))))))
15488 ;; FIXME: can we use this for something else, like computing time differences?
15489 (defun org-get-compact-tod (s)
15490 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15491 (let* ((t1 (match-string 1 s))
15492 (h1 (string-to-number (match-string 2 s)))
15493 (m1 (string-to-number (match-string 3 s)))
15494 (t2 (and (match-end 4) (match-string 5 s)))
15495 (h2 (and t2 (string-to-number (match-string 6 s))))
15496 (m2 (and t2 (string-to-number (match-string 7 s))))
15497 dh dm)
15498 (if (not t2)
15500 (setq dh (- h2 h1) dm (- m2 m1))
15501 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15502 (concat t1 "+" (number-to-string dh)
15503 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15505 (defun org-time-stamp-inactive (&optional arg)
15506 "Insert an inactive time stamp.
15507 An inactive time stamp is enclosed in square brackets instead of angle
15508 brackets. It is inactive in the sense that it does not trigger agenda entries,
15509 does not link to the calendar and cannot be changed with the S-cursor keys.
15510 So these are more for recording a certain time/date."
15511 (interactive "P")
15512 (org-time-stamp arg 'inactive))
15514 (defvar org-date-ovl (make-overlay 1 1))
15515 (overlay-put org-date-ovl 'face 'org-date-selected)
15516 (org-detach-overlay org-date-ovl)
15518 (defvar org-ans1) ; dynamically scoped parameter
15519 (defvar org-ans2) ; dynamically scoped parameter
15521 (defvar org-plain-time-of-day-regexp) ; defined below
15523 (defvar org-overriding-default-time nil) ; dynamically scoped
15524 (defvar org-read-date-overlay nil)
15525 (defvar org-dcst nil) ; dynamically scoped
15526 (defvar org-read-date-history nil)
15527 (defvar org-read-date-final-answer nil)
15528 (defvar org-read-date-analyze-futurep nil)
15529 (defvar org-read-date-analyze-forced-year nil)
15530 (defvar org-read-date-inactive)
15532 (defun org-read-date (&optional org-with-time to-time from-string prompt
15533 default-time default-input inactive)
15534 "Read a date, possibly a time, and make things smooth for the user.
15535 The prompt will suggest to enter an ISO date, but you can also enter anything
15536 which will at least partially be understood by `parse-time-string'.
15537 Unrecognized parts of the date will default to the current day, month, year,
15538 hour and minute. If this command is called to replace a timestamp at point,
15539 or to enter the second timestamp of a range, the default time is taken
15540 from the existing stamp. Furthermore, the command prefers the future,
15541 so if you are giving a date where the year is not given, and the day-month
15542 combination is already past in the current year, it will assume you
15543 mean next year. For details, see the manual. A few examples:
15545 3-2-5 --> 2003-02-05
15546 feb 15 --> currentyear-02-15
15547 2/15 --> currentyear-02-15
15548 sep 12 9 --> 2009-09-12
15549 12:45 --> today 12:45
15550 22 sept 0:34 --> currentyear-09-22 0:34
15551 12 --> currentyear-currentmonth-12
15552 Fri --> nearest Friday (today or later)
15553 etc.
15555 Furthermore you can specify a relative date by giving, as the *first* thing
15556 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15557 change in days weeks, months, years.
15558 With a single plus or minus, the date is relative to today. With a double
15559 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15560 +4d --> four days from today
15561 +4 --> same as above
15562 +2w --> two weeks from today
15563 ++5 --> five days from default date
15565 The function understands only English month and weekday abbreviations.
15567 While prompting, a calendar is popped up - you can also select the
15568 date with the mouse (button 1). The calendar shows a period of three
15569 months. To scroll it to other months, use the keys `>' and `<'.
15570 If you don't like the calendar, turn it off with
15571 \(setq org-read-date-popup-calendar nil)
15573 With optional argument TO-TIME, the date will immediately be converted
15574 to an internal time.
15575 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15576 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15577 still enter a time, and this function will inform the calling routine
15578 about this change. The calling routine may then choose to change the
15579 format used to insert the time stamp into the buffer to include the time.
15580 With optional argument FROM-STRING, read from this string instead from
15581 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15582 the time/date that is used for everything that is not specified by the
15583 user."
15584 (require 'parse-time)
15585 (let* ((org-time-stamp-rounding-minutes
15586 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15587 (org-dcst org-display-custom-times)
15588 (ct (org-current-time))
15589 (org-def (or org-overriding-default-time default-time ct))
15590 (org-defdecode (decode-time org-def))
15591 (dummy (progn
15592 (when (< (nth 2 org-defdecode) org-extend-today-until)
15593 (setcar (nthcdr 2 org-defdecode) -1)
15594 (setcar (nthcdr 1 org-defdecode) 59)
15595 (setq org-def (apply 'encode-time org-defdecode)
15596 org-defdecode (decode-time org-def)))))
15597 (mouse-autoselect-window nil) ; Don't let the mouse jump
15598 (calendar-frame-setup nil)
15599 (calendar-setup nil)
15600 (calendar-move-hook nil)
15601 (calendar-view-diary-initially-flag nil)
15602 (calendar-view-holidays-initially-flag nil)
15603 (timestr (format-time-string
15604 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15605 (prompt (concat (if prompt (concat prompt " ") "")
15606 (format "Date+time [%s]: " timestr)))
15607 ans (org-ans0 "") org-ans1 org-ans2 final)
15609 (cond
15610 (from-string (setq ans from-string))
15611 (org-read-date-popup-calendar
15612 (save-excursion
15613 (save-window-excursion
15614 (calendar)
15615 (org-eval-in-calendar '(setq cursor-type nil) t)
15616 (unwind-protect
15617 (progn
15618 (calendar-forward-day (- (time-to-days org-def)
15619 (calendar-absolute-from-gregorian
15620 (calendar-current-date))))
15621 (org-eval-in-calendar nil t)
15622 (let* ((old-map (current-local-map))
15623 (map (copy-keymap calendar-mode-map))
15624 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15625 (org-defkey map (kbd "RET") 'org-calendar-select)
15626 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15627 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15628 (org-defkey minibuffer-local-map [(meta shift left)]
15629 (lambda () (interactive)
15630 (org-eval-in-calendar '(calendar-backward-month 1))))
15631 (org-defkey minibuffer-local-map [(meta shift right)]
15632 (lambda () (interactive)
15633 (org-eval-in-calendar '(calendar-forward-month 1))))
15634 (org-defkey minibuffer-local-map [(meta shift up)]
15635 (lambda () (interactive)
15636 (org-eval-in-calendar '(calendar-backward-year 1))))
15637 (org-defkey minibuffer-local-map [(meta shift down)]
15638 (lambda () (interactive)
15639 (org-eval-in-calendar '(calendar-forward-year 1))))
15640 (org-defkey minibuffer-local-map [?\e (shift left)]
15641 (lambda () (interactive)
15642 (org-eval-in-calendar '(calendar-backward-month 1))))
15643 (org-defkey minibuffer-local-map [?\e (shift right)]
15644 (lambda () (interactive)
15645 (org-eval-in-calendar '(calendar-forward-month 1))))
15646 (org-defkey minibuffer-local-map [?\e (shift up)]
15647 (lambda () (interactive)
15648 (org-eval-in-calendar '(calendar-backward-year 1))))
15649 (org-defkey minibuffer-local-map [?\e (shift down)]
15650 (lambda () (interactive)
15651 (org-eval-in-calendar '(calendar-forward-year 1))))
15652 (org-defkey minibuffer-local-map [(shift up)]
15653 (lambda () (interactive)
15654 (org-eval-in-calendar '(calendar-backward-week 1))))
15655 (org-defkey minibuffer-local-map [(shift down)]
15656 (lambda () (interactive)
15657 (org-eval-in-calendar '(calendar-forward-week 1))))
15658 (org-defkey minibuffer-local-map [(shift left)]
15659 (lambda () (interactive)
15660 (org-eval-in-calendar '(calendar-backward-day 1))))
15661 (org-defkey minibuffer-local-map [(shift right)]
15662 (lambda () (interactive)
15663 (org-eval-in-calendar '(calendar-forward-day 1))))
15664 (org-defkey minibuffer-local-map ">"
15665 (lambda () (interactive)
15666 (org-eval-in-calendar '(scroll-calendar-left 1))))
15667 (org-defkey minibuffer-local-map "<"
15668 (lambda () (interactive)
15669 (org-eval-in-calendar '(scroll-calendar-right 1))))
15670 (org-defkey minibuffer-local-map "\C-v"
15671 (lambda () (interactive)
15672 (org-eval-in-calendar
15673 '(calendar-scroll-left-three-months 1))))
15674 (org-defkey minibuffer-local-map "\M-v"
15675 (lambda () (interactive)
15676 (org-eval-in-calendar
15677 '(calendar-scroll-right-three-months 1))))
15678 (run-hooks 'org-read-date-minibuffer-setup-hook)
15679 (unwind-protect
15680 (progn
15681 (use-local-map map)
15682 (setq org-read-date-inactive inactive)
15683 (add-hook 'post-command-hook 'org-read-date-display)
15684 (setq org-ans0 (read-string prompt default-input
15685 'org-read-date-history nil))
15686 ;; org-ans0: from prompt
15687 ;; org-ans1: from mouse click
15688 ;; org-ans2: from calendar motion
15689 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15690 (remove-hook 'post-command-hook 'org-read-date-display)
15691 (use-local-map old-map)
15692 (when org-read-date-overlay
15693 (delete-overlay org-read-date-overlay)
15694 (setq org-read-date-overlay nil)))))
15695 (bury-buffer "*Calendar*")))))
15697 (t ; Naked prompt only
15698 (unwind-protect
15699 (setq ans (read-string prompt default-input
15700 'org-read-date-history timestr))
15701 (when org-read-date-overlay
15702 (delete-overlay org-read-date-overlay)
15703 (setq org-read-date-overlay nil)))))
15705 (setq final (org-read-date-analyze ans org-def org-defdecode))
15707 (when org-read-date-analyze-forced-year
15708 (message "Year was forced into %s"
15709 (if org-read-date-force-compatible-dates
15710 "compatible range (1970-2037)"
15711 "range representable on this machine"))
15712 (ding))
15714 ;; One round trip to get rid of 34th of August and stuff like that....
15715 (setq final (decode-time (apply 'encode-time final)))
15717 (setq org-read-date-final-answer ans)
15719 (if to-time
15720 (apply 'encode-time final)
15721 (if (and (boundp 'org-time-was-given) org-time-was-given)
15722 (format "%04d-%02d-%02d %02d:%02d"
15723 (nth 5 final) (nth 4 final) (nth 3 final)
15724 (nth 2 final) (nth 1 final))
15725 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15727 (defvar org-def)
15728 (defvar org-defdecode)
15729 (defvar org-with-time)
15730 (defun org-read-date-display ()
15731 "Display the current date prompt interpretation in the minibuffer."
15732 (when org-read-date-display-live
15733 (when org-read-date-overlay
15734 (delete-overlay org-read-date-overlay))
15735 (when (minibufferp (current-buffer))
15736 (save-excursion
15737 (end-of-line 1)
15738 (while (not (equal (buffer-substring
15739 (max (point-min) (- (point) 4)) (point))
15740 " "))
15741 (insert " ")))
15742 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15743 " " (or org-ans1 org-ans2)))
15744 (org-end-time-was-given nil)
15745 (f (org-read-date-analyze ans org-def org-defdecode))
15746 (fmts (if org-dcst
15747 org-time-stamp-custom-formats
15748 org-time-stamp-formats))
15749 (fmt (if (or org-with-time
15750 (and (boundp 'org-time-was-given) org-time-was-given))
15751 (cdr fmts)
15752 (car fmts)))
15753 (txt (format-time-string fmt (apply 'encode-time f)))
15754 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15755 (txt (concat "=> " txt)))
15756 (when (and org-end-time-was-given
15757 (string-match org-plain-time-of-day-regexp txt))
15758 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15759 org-end-time-was-given
15760 (substring txt (match-end 0)))))
15761 (when org-read-date-analyze-futurep
15762 (setq txt (concat txt " (=>F)")))
15763 (setq org-read-date-overlay
15764 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15765 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15767 (defun org-read-date-analyze (ans org-def org-defdecode)
15768 "Analyze the combined answer of the date prompt."
15769 ;; FIXME: cleanup and comment
15770 (let ((nowdecode (decode-time (current-time)))
15771 delta deltan deltaw deltadef year month day
15772 hour minute second wday pm h2 m2 tl wday1
15773 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15774 (setq org-read-date-analyze-futurep nil
15775 org-read-date-analyze-forced-year nil)
15776 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15777 (setq ans "+0"))
15779 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15780 (setq ans (replace-match "" t t ans)
15781 deltan (car delta)
15782 deltaw (nth 1 delta)
15783 deltadef (nth 2 delta)))
15785 ;; Check if there is an iso week date in there. If yes, store the
15786 ;; info and postpone interpreting it until the rest of the parsing
15787 ;; is done.
15788 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15789 (setq iso-year (if (match-end 1)
15790 (org-small-year-to-year
15791 (string-to-number (match-string 1 ans))))
15792 iso-weekday (if (match-end 3)
15793 (string-to-number (match-string 3 ans)))
15794 iso-week (string-to-number (match-string 2 ans)))
15795 (setq ans (replace-match "" t t ans)))
15797 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15798 (when (string-match
15799 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15800 (setq year (if (match-end 2)
15801 (string-to-number (match-string 2 ans))
15802 (progn (setq kill-year t)
15803 (string-to-number (format-time-string "%Y"))))
15804 month (string-to-number (match-string 3 ans))
15805 day (string-to-number (match-string 4 ans)))
15806 (if (< year 100) (setq year (+ 2000 year)))
15807 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15808 t nil ans)))
15810 ;; Help matching dotted european dates
15811 (when (string-match
15812 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15813 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15814 (setq kill-year t)
15815 (string-to-number (format-time-string "%Y")))
15816 day (string-to-number (match-string 1 ans))
15817 month (string-to-number (match-string 2 ans))
15818 ans (replace-match (format "%04d-%02d-%02d" year month day)
15819 t nil ans)))
15821 ;; Help matching american dates, like 5/30 or 5/30/7
15822 (when (string-match
15823 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15824 (setq year (if (match-end 4)
15825 (string-to-number (match-string 4 ans))
15826 (progn (setq kill-year t)
15827 (string-to-number (format-time-string "%Y"))))
15828 month (string-to-number (match-string 1 ans))
15829 day (string-to-number (match-string 2 ans)))
15830 (if (< year 100) (setq year (+ 2000 year)))
15831 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15832 t nil ans)))
15833 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15834 ;; If there is a time with am/pm, and *no* time without it, we convert
15835 ;; so that matching will be successful.
15836 (loop for i from 1 to 2 do ; twice, for end time as well
15837 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15838 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15839 (setq hour (string-to-number (match-string 1 ans))
15840 minute (if (match-end 3)
15841 (string-to-number (match-string 3 ans))
15843 pm (equal ?p
15844 (string-to-char (downcase (match-string 4 ans)))))
15845 (if (and (= hour 12) (not pm))
15846 (setq hour 0)
15847 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15848 (setq ans (replace-match (format "%02d:%02d" hour minute)
15849 t t ans))))
15851 ;; Check if a time range is given as a duration
15852 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15853 (setq hour (string-to-number (match-string 1 ans))
15854 h2 (+ hour (string-to-number (match-string 3 ans)))
15855 minute (string-to-number (match-string 2 ans))
15856 m2 (+ minute (if (match-end 5) (string-to-number
15857 (match-string 5 ans))0)))
15858 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15859 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15860 t t ans)))
15862 ;; Check if there is a time range
15863 (when (boundp 'org-end-time-was-given)
15864 (setq org-time-was-given nil)
15865 (when (and (string-match org-plain-time-of-day-regexp ans)
15866 (match-end 8))
15867 (setq org-end-time-was-given (match-string 8 ans))
15868 (setq ans (concat (substring ans 0 (match-beginning 7))
15869 (substring ans (match-end 7))))))
15871 (setq tl (parse-time-string ans)
15872 day (or (nth 3 tl) (nth 3 org-defdecode))
15873 month (or (nth 4 tl)
15874 (if (and org-read-date-prefer-future
15875 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15876 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15877 (nth 4 org-defdecode)))
15878 year (or (and (not kill-year) (nth 5 tl))
15879 (if (and org-read-date-prefer-future
15880 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15881 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15882 (nth 5 org-defdecode)))
15883 hour (or (nth 2 tl) (nth 2 org-defdecode))
15884 minute (or (nth 1 tl) (nth 1 org-defdecode))
15885 second (or (nth 0 tl) 0)
15886 wday (nth 6 tl))
15888 (when (and (eq org-read-date-prefer-future 'time)
15889 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15890 (equal day (nth 3 nowdecode))
15891 (equal month (nth 4 nowdecode))
15892 (equal year (nth 5 nowdecode))
15893 (nth 2 tl)
15894 (or (< (nth 2 tl) (nth 2 nowdecode))
15895 (and (= (nth 2 tl) (nth 2 nowdecode))
15896 (nth 1 tl)
15897 (< (nth 1 tl) (nth 1 nowdecode)))))
15898 (setq day (1+ day)
15899 futurep t))
15901 ;; Special date definitions below
15902 (cond
15903 (iso-week
15904 ;; There was an iso week
15905 (require 'cal-iso)
15906 (setq futurep nil)
15907 (setq year (or iso-year year)
15908 day (or iso-weekday wday 1)
15909 wday nil ; to make sure that the trigger below does not match
15910 iso-date (calendar-gregorian-from-absolute
15911 (calendar-absolute-from-iso
15912 (list iso-week day year))))
15913 ; FIXME: Should we also push ISO weeks into the future?
15914 ; (when (and org-read-date-prefer-future
15915 ; (not iso-year)
15916 ; (< (calendar-absolute-from-gregorian iso-date)
15917 ; (time-to-days (current-time))))
15918 ; (setq year (1+ year)
15919 ; iso-date (calendar-gregorian-from-absolute
15920 ; (calendar-absolute-from-iso
15921 ; (list iso-week day year)))))
15922 (setq month (car iso-date)
15923 year (nth 2 iso-date)
15924 day (nth 1 iso-date)))
15925 (deltan
15926 (setq futurep nil)
15927 (unless deltadef
15928 (let ((now (decode-time (current-time))))
15929 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15930 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15931 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15932 ((equal deltaw "m") (setq month (+ month deltan)))
15933 ((equal deltaw "y") (setq year (+ year deltan)))))
15934 ((and wday (not (nth 3 tl)))
15935 ;; Weekday was given, but no day, so pick that day in the week
15936 ;; on or after the derived date.
15937 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15938 (unless (equal wday wday1)
15939 (setq day (+ day (% (- wday wday1 -7) 7))))))
15940 (if (and (boundp 'org-time-was-given)
15941 (nth 2 tl))
15942 (setq org-time-was-given t))
15943 (if (< year 100) (setq year (+ 2000 year)))
15944 ;; Check of the date is representable
15945 (if org-read-date-force-compatible-dates
15946 (progn
15947 (if (< year 1970)
15948 (setq year 1970 org-read-date-analyze-forced-year t))
15949 (if (> year 2037)
15950 (setq year 2037 org-read-date-analyze-forced-year t)))
15951 (condition-case nil
15952 (ignore (encode-time second minute hour day month year))
15953 (error
15954 (setq year (nth 5 org-defdecode))
15955 (setq org-read-date-analyze-forced-year t))))
15956 (setq org-read-date-analyze-futurep futurep)
15957 (list second minute hour day month year)))
15959 (defvar parse-time-weekdays)
15960 (defun org-read-date-get-relative (s today default)
15961 "Check string S for special relative date string.
15962 TODAY and DEFAULT are internal times, for today and for a default.
15963 Return shift list (N what def-flag)
15964 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15965 N is the number of WHATs to shift.
15966 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15967 the DEFAULT date rather than TODAY."
15968 (require 'parse-time)
15969 (when (and
15970 (string-match
15971 (concat
15972 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15973 "\\([0-9]+\\)?"
15974 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15975 "\\([ \t]\\|$\\)") s)
15976 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15977 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15978 (string-to-char (substring (match-string 1 s) -1))
15979 ?+))
15980 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15981 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15982 (what (if (match-end 3) (match-string 3 s) "d"))
15983 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15984 (date (if rel default today))
15985 (wday (nth 6 (decode-time date)))
15986 delta)
15987 (if wday1
15988 (progn
15989 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15990 (if (= dir ?-) (setq delta (- delta 7)))
15991 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15992 (list delta "d" rel))
15993 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15995 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15996 "Turn a user-specified date into the internal representation.
15997 The internal representation needed by the calendar is (month day year).
15998 This is a wrapper to handle the brain-dead convention in calendar that
15999 user function argument order change dependent on argument order."
16000 (if (boundp 'calendar-date-style)
16001 (cond
16002 ((eq calendar-date-style 'american)
16003 (list arg1 arg2 arg3))
16004 ((eq calendar-date-style 'european)
16005 (list arg2 arg1 arg3))
16006 ((eq calendar-date-style 'iso)
16007 (list arg2 arg3 arg1)))
16008 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16009 (if (org-bound-and-true-p european-calendar-style)
16010 (list arg2 arg1 arg3)
16011 (list arg1 arg2 arg3)))))
16013 (defun org-eval-in-calendar (form &optional keepdate)
16014 "Eval FORM in the calendar window and return to current window.
16015 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16016 otherwise stick to the current value of `org-ans2'."
16017 (let ((sf (selected-frame))
16018 (sw (selected-window)))
16019 (select-window (get-buffer-window "*Calendar*" t))
16020 (eval form)
16021 (when (and (not keepdate) (calendar-cursor-to-date))
16022 (let* ((date (calendar-cursor-to-date))
16023 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16024 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16025 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16026 (select-window sw)
16027 (org-select-frame-set-input-focus sf)))
16029 (defun org-calendar-select ()
16030 "Return to `org-read-date' with the date currently selected.
16031 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16032 (interactive)
16033 (when (calendar-cursor-to-date)
16034 (let* ((date (calendar-cursor-to-date))
16035 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16036 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16037 (if (active-minibuffer-window) (exit-minibuffer))))
16039 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16040 "Insert a date stamp for the date given by the internal TIME.
16041 WITH-HM means use the stamp format that includes the time of the day.
16042 INACTIVE means use square brackets instead of angular ones, so that the
16043 stamp will not contribute to the agenda.
16044 PRE and POST are optional strings to be inserted before and after the
16045 stamp.
16046 The command returns the inserted time stamp."
16047 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16048 stamp)
16049 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16050 (insert-before-markers (or pre ""))
16051 (when (listp extra)
16052 (setq extra (car extra))
16053 (if (and (stringp extra)
16054 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16055 (setq extra (format "-%02d:%02d"
16056 (string-to-number (match-string 1 extra))
16057 (string-to-number (match-string 2 extra))))
16058 (setq extra nil)))
16059 (when extra
16060 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16061 (insert-before-markers (setq stamp (format-time-string fmt time)))
16062 (insert-before-markers (or post ""))
16063 (setq org-last-inserted-timestamp stamp)))
16065 (defun org-toggle-time-stamp-overlays ()
16066 "Toggle the use of custom time stamp formats."
16067 (interactive)
16068 (setq org-display-custom-times (not org-display-custom-times))
16069 (unless org-display-custom-times
16070 (let ((p (point-min)) (bmp (buffer-modified-p)))
16071 (while (setq p (next-single-property-change p 'display))
16072 (if (and (get-text-property p 'display)
16073 (eq (get-text-property p 'face) 'org-date))
16074 (remove-text-properties
16075 p (setq p (next-single-property-change p 'display))
16076 '(display t))))
16077 (set-buffer-modified-p bmp)))
16078 (if (featurep 'xemacs)
16079 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16080 (org-restart-font-lock)
16081 (setq org-table-may-need-update t)
16082 (if org-display-custom-times
16083 (message "Time stamps are overlaid with custom format")
16084 (message "Time stamp overlays removed")))
16086 (defun org-display-custom-time (beg end)
16087 "Overlay modified time stamp format over timestamp between BEG and END."
16088 (let* ((ts (buffer-substring beg end))
16089 t1 w1 with-hm tf time str w2 (off 0))
16090 (save-match-data
16091 (setq t1 (org-parse-time-string ts t))
16092 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16093 (setq off (- (match-end 0) (match-beginning 0)))))
16094 (setq end (- end off))
16095 (setq w1 (- end beg)
16096 with-hm (and (nth 1 t1) (nth 2 t1))
16097 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16098 time (org-fix-decoded-time t1)
16099 str (org-add-props
16100 (format-time-string
16101 (substring tf 1 -1) (apply 'encode-time time))
16102 nil 'mouse-face 'highlight)
16103 w2 (length str))
16104 (if (not (= w2 w1))
16105 (add-text-properties (1+ beg) (+ 2 beg)
16106 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16107 (if (featurep 'xemacs)
16108 (progn
16109 (put-text-property beg end 'invisible t)
16110 (put-text-property beg end 'end-glyph (make-glyph str)))
16111 (put-text-property beg end 'display str))))
16113 (defun org-translate-time (string)
16114 "Translate all timestamps in STRING to custom format.
16115 But do this only if the variable `org-display-custom-times' is set."
16116 (when org-display-custom-times
16117 (save-match-data
16118 (let* ((start 0)
16119 (re org-ts-regexp-both)
16120 t1 with-hm inactive tf time str beg end)
16121 (while (setq start (string-match re string start))
16122 (setq beg (match-beginning 0)
16123 end (match-end 0)
16124 t1 (save-match-data
16125 (org-parse-time-string (substring string beg end) t))
16126 with-hm (and (nth 1 t1) (nth 2 t1))
16127 inactive (equal (substring string beg (1+ beg)) "[")
16128 tf (funcall (if with-hm 'cdr 'car)
16129 org-time-stamp-custom-formats)
16130 time (org-fix-decoded-time t1)
16131 str (format-time-string
16132 (concat
16133 (if inactive "[" "<") (substring tf 1 -1)
16134 (if inactive "]" ">"))
16135 (apply 'encode-time time))
16136 string (replace-match str t t string)
16137 start (+ start (length str)))))))
16138 string)
16140 (defun org-fix-decoded-time (time)
16141 "Set 0 instead of nil for the first 6 elements of time.
16142 Don't touch the rest."
16143 (let ((n 0))
16144 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16146 (org-define-obsolete-function-alias
16147 'org-days-to-time 'org-time-stamp-to-now "24.3")
16149 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16150 "Difference between TIMESTAMP-STRING and now in days.
16151 If SECONDS is non-nil, return the difference in seconds."
16152 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16153 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16154 (funcall fdiff (current-time)))))
16156 (defun org-deadline-close (timestamp-string &optional ndays)
16157 "Is the time in TIMESTAMP-STRING close to the current date?"
16158 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16159 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16160 (not (org-entry-is-done-p))))
16162 (defun org-get-wdays (ts)
16163 "Get the deadline lead time appropriate for timestring TS."
16164 (cond
16165 ((<= org-deadline-warning-days 0)
16166 ;; 0 or negative, enforce this value no matter what
16167 (- org-deadline-warning-days))
16168 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16169 ;; lead time is specified.
16170 (floor (* (string-to-number (match-string 1 ts))
16171 (cdr (assoc (match-string 2 ts)
16172 '(("d" . 1) ("w" . 7)
16173 ("m" . 30.4) ("y" . 365.25)))))))
16174 ;; go for the default.
16175 (t org-deadline-warning-days)))
16177 (defun org-calendar-select-mouse (ev)
16178 "Return to `org-read-date' with the date currently selected.
16179 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16180 (interactive "e")
16181 (mouse-set-point ev)
16182 (when (calendar-cursor-to-date)
16183 (let* ((date (calendar-cursor-to-date))
16184 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16185 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16186 (if (active-minibuffer-window) (exit-minibuffer))))
16188 (defun org-check-deadlines (ndays)
16189 "Check if there are any deadlines due or past due.
16190 A deadline is considered due if it happens within `org-deadline-warning-days'
16191 days from today's date. If the deadline appears in an entry marked DONE,
16192 it is not shown. The prefix arg NDAYS can be used to test that many
16193 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16194 (interactive "P")
16195 (let* ((org-warn-days
16196 (cond
16197 ((equal ndays '(4)) 100000)
16198 (ndays (prefix-numeric-value ndays))
16199 (t (abs org-deadline-warning-days))))
16200 (case-fold-search nil)
16201 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16202 (callback
16203 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16205 (message "%d deadlines past-due or due within %d days"
16206 (org-occur regexp nil callback)
16207 org-warn-days)))
16209 (defsubst org-re-timestamp (type)
16210 "Return a regexp for timestamp TYPE.
16211 Allowed values for TYPE are:
16213 all: all timestamps
16214 active: only active timestamps (<...>)
16215 inactive: only inactive timestamps ([...])
16216 scheduled: only scheduled timestamps
16217 deadline: only deadline timestamps
16219 When TYPE is nil, fall back on returning a regexp that matches
16220 both scheduled and deadline timestamps."
16221 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16222 ((eq type 'active) org-ts-regexp)
16223 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16224 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16225 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16226 ((eq type 'scheduled-or-deadline)
16227 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16229 (defun org-check-before-date (date)
16230 "Check if there are deadlines or scheduled entries before DATE."
16231 (interactive (list (org-read-date)))
16232 (let ((case-fold-search nil)
16233 (regexp (org-re-timestamp org-ts-type))
16234 (callback
16235 (lambda () (time-less-p
16236 (org-time-string-to-time (match-string 1))
16237 (org-time-string-to-time date)))))
16238 (message "%d entries before %s"
16239 (org-occur regexp nil callback) date)))
16241 (defun org-check-after-date (date)
16242 "Check if there are deadlines or scheduled entries after DATE."
16243 (interactive (list (org-read-date)))
16244 (let ((case-fold-search nil)
16245 (regexp (org-re-timestamp org-ts-type))
16246 (callback
16247 (lambda () (not
16248 (time-less-p
16249 (org-time-string-to-time (match-string 1))
16250 (org-time-string-to-time date))))))
16251 (message "%d entries after %s"
16252 (org-occur regexp nil callback) date)))
16254 (defun org-check-dates-range (start-date end-date)
16255 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16256 (interactive (list (org-read-date nil nil nil "Range starts")
16257 (org-read-date nil nil nil "Range end")))
16258 (let ((case-fold-search nil)
16259 (regexp (org-re-timestamp org-ts-type))
16260 (callback
16261 (lambda ()
16262 (let ((match (match-string 1)))
16263 (and
16264 (not (time-less-p
16265 (org-time-string-to-time match)
16266 (org-time-string-to-time start-date)))
16267 (time-less-p
16268 (org-time-string-to-time match)
16269 (org-time-string-to-time end-date)))))))
16270 (message "%d entries between %s and %s"
16271 (org-occur regexp nil callback) start-date end-date)))
16273 (defun org-evaluate-time-range (&optional to-buffer)
16274 "Evaluate a time range by computing the difference between start and end.
16275 Normally the result is just printed in the echo area, but with prefix arg
16276 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16277 If the time range is actually in a table, the result is inserted into the
16278 next column.
16279 For time difference computation, a year is assumed to be exactly 365
16280 days in order to avoid rounding problems."
16281 (interactive "P")
16283 (org-clock-update-time-maybe)
16284 (save-excursion
16285 (unless (org-at-date-range-p t)
16286 (goto-char (point-at-bol))
16287 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16288 (if (not (org-at-date-range-p t))
16289 (error "Not at a time-stamp range, and none found in current line")))
16290 (let* ((ts1 (match-string 1))
16291 (ts2 (match-string 2))
16292 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16293 (match-end (match-end 0))
16294 (time1 (org-time-string-to-time ts1))
16295 (time2 (org-time-string-to-time ts2))
16296 (t1 (org-float-time time1))
16297 (t2 (org-float-time time2))
16298 (diff (abs (- t2 t1)))
16299 (negative (< (- t2 t1) 0))
16300 ;; (ys (floor (* 365 24 60 60)))
16301 (ds (* 24 60 60))
16302 (hs (* 60 60))
16303 (fy "%dy %dd %02d:%02d")
16304 (fy1 "%dy %dd")
16305 (fd "%dd %02d:%02d")
16306 (fd1 "%dd")
16307 (fh "%02d:%02d")
16308 y d h m align)
16309 (if havetime
16310 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16312 d (floor (/ diff ds)) diff (mod diff ds)
16313 h (floor (/ diff hs)) diff (mod diff hs)
16314 m (floor (/ diff 60)))
16315 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16317 d (floor (+ (/ diff ds) 0.5))
16318 h 0 m 0))
16319 (if (not to-buffer)
16320 (message "%s" (org-make-tdiff-string y d h m))
16321 (if (org-at-table-p)
16322 (progn
16323 (goto-char match-end)
16324 (setq align t)
16325 (and (looking-at " *|") (goto-char (match-end 0))))
16326 (goto-char match-end))
16327 (if (looking-at
16328 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16329 (replace-match ""))
16330 (if negative (insert " -"))
16331 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16332 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16333 (insert " " (format fh h m))))
16334 (if align (org-table-align))
16335 (message "Time difference inserted")))))
16337 (defun org-make-tdiff-string (y d h m)
16338 (let ((fmt "")
16339 (l nil))
16340 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16341 l (push y l)))
16342 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16343 l (push d l)))
16344 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16345 l (push h l)))
16346 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16347 l (push m l)))
16348 (apply 'format fmt (nreverse l))))
16350 (defun org-time-string-to-time (s &optional buffer pos)
16351 "Convert a timestamp string into internal time."
16352 (condition-case errdata
16353 (apply 'encode-time (org-parse-time-string s))
16354 (error (error "Bad timestamp `%s'%s\nError was: %s"
16355 s (if (not (and buffer pos))
16357 (format " at %d in buffer `%s'" pos buffer))
16358 (cdr errdata)))))
16360 (defun org-time-string-to-seconds (s)
16361 "Convert a timestamp string to a number of seconds."
16362 (org-float-time (org-time-string-to-time s)))
16364 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16365 "Convert a time stamp to an absolute day number.
16366 If there is a specifier for a cyclic time stamp, get the closest date to
16367 DAYNR.
16368 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16369 The variable date is bound by the calendar when this is called."
16370 (cond
16371 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16372 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16373 daynr
16374 (+ daynr 1000)))
16375 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16376 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16377 (time-to-days (current-time))) (match-string 0 s)
16378 prefer show-all))
16379 (t (time-to-days
16380 (condition-case errdata
16381 (apply 'encode-time (org-parse-time-string s))
16382 (error (error "Bad timestamp `%s'%s\nError was: %s"
16383 s (if (not (and buffer pos))
16385 (format " at %d in buffer `%s'" pos buffer))
16386 (cdr errdata))))))))
16388 (defun org-days-to-iso-week (days)
16389 "Return the iso week number."
16390 (require 'cal-iso)
16391 (car (calendar-iso-from-absolute days)))
16393 (defun org-small-year-to-year (year)
16394 "Convert 2-digit years into 4-digit years.
16395 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16396 The year 2000 cannot be abbreviated. Any year larger than 99
16397 is returned unchanged."
16398 (if (< year 38)
16399 (setq year (+ 2000 year))
16400 (if (< year 100)
16401 (setq year (+ 1900 year))))
16402 year)
16404 (defun org-time-from-absolute (d)
16405 "Return the time corresponding to date D.
16406 D may be an absolute day number, or a calendar-type list (month day year)."
16407 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16408 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16410 (defun org-calendar-holiday ()
16411 "List of holidays, for Diary display in Org-mode."
16412 (require 'holidays)
16413 (let ((hl (funcall
16414 (if (fboundp 'calendar-check-holidays)
16415 'calendar-check-holidays 'check-calendar-holidays) date)))
16416 (if hl (mapconcat 'identity hl "; "))))
16418 (defun org-diary-sexp-entry (sexp entry date)
16419 "Process a SEXP diary ENTRY for DATE."
16420 (require 'diary-lib)
16421 (let ((result (if calendar-debug-sexp
16422 (let ((stack-trace-on-error t))
16423 (eval (car (read-from-string sexp))))
16424 (condition-case nil
16425 (eval (car (read-from-string sexp)))
16426 (error
16427 (beep)
16428 (message "Bad sexp at line %d in %s: %s"
16429 (org-current-line)
16430 (buffer-file-name) sexp)
16431 (sleep-for 2))))))
16432 (cond ((stringp result) (split-string result "; "))
16433 ((and (consp result)
16434 (not (consp (cdr result)))
16435 (stringp (cdr result))) (cdr result))
16436 ((and (consp result)
16437 (stringp (car result))) result)
16438 (result entry))))
16440 (defun org-diary-to-ical-string (frombuf)
16441 "Get iCalendar entries from diary entries in buffer FROMBUF.
16442 This uses the icalendar.el library."
16443 (let* ((tmpdir (if (featurep 'xemacs)
16444 (temp-directory)
16445 temporary-file-directory))
16446 (tmpfile (make-temp-name
16447 (expand-file-name "orgics" tmpdir)))
16448 buf rtn b e)
16449 (with-current-buffer frombuf
16450 (icalendar-export-region (point-min) (point-max) tmpfile)
16451 (setq buf (find-buffer-visiting tmpfile))
16452 (set-buffer buf)
16453 (goto-char (point-min))
16454 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16455 (setq b (match-beginning 0)))
16456 (goto-char (point-max))
16457 (if (re-search-backward "^END:VEVENT" nil t)
16458 (setq e (match-end 0)))
16459 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16460 (kill-buffer buf)
16461 (delete-file tmpfile)
16462 rtn))
16464 (defun org-closest-date (start current change prefer show-all)
16465 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16466 When PREFER is `past', return a date that is either CURRENT or past.
16467 When PREFER is `future', return a date that is either CURRENT or future.
16468 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16469 ;; Make the proper lists from the dates
16470 (catch 'exit
16471 (let ((a1 '(("h" . hour)
16472 ("d" . day)
16473 ("w" . week)
16474 ("m" . month)
16475 ("y" . year)))
16476 (shour (nth 2 (org-parse-time-string start)))
16477 dn dw sday cday n1 n2 n0
16478 d m y y1 y2 date1 date2 nmonths nm ny m2)
16480 (setq start (org-date-to-gregorian start)
16481 current (org-date-to-gregorian
16482 (if show-all
16483 current
16484 (time-to-days (current-time))))
16485 sday (calendar-absolute-from-gregorian start)
16486 cday (calendar-absolute-from-gregorian current))
16488 (if (<= cday sday) (throw 'exit sday))
16490 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16491 (setq dn (string-to-number (match-string 1 change))
16492 dw (cdr (assoc (match-string 2 change) a1)))
16493 (error "Invalid change specifier: %s" change))
16494 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16495 (cond
16496 ((eq dw 'hour)
16497 (let ((missing-hours
16498 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16499 dn)))
16500 (setq n1 (if (zerop missing-hours) cday
16501 (- cday (1+ (floor (/ missing-hours 24)))))
16502 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16503 ((eq dw 'day)
16504 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16505 n2 (+ n1 dn)))
16506 ((eq dw 'year)
16507 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16508 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16509 (setq date1 (list m d y1)
16510 n1 (calendar-absolute-from-gregorian date1)
16511 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16512 n2 (calendar-absolute-from-gregorian date2)))
16513 ((eq dw 'month)
16514 ;; approx number of month between the two dates
16515 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16516 ;; How often does dn fit in there?
16517 (setq d (nth 1 start) m (car start) y (nth 2 start)
16518 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16519 m (+ m nm)
16520 ny (floor (/ m 12))
16521 y (+ y ny)
16522 m (- m (* ny 12)))
16523 (while (> m 12) (setq m (- m 12) y (1+ y)))
16524 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16525 (setq m2 (+ m dn) y2 y)
16526 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16527 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16528 (while (<= n2 cday)
16529 (setq n1 n2 m m2 y y2)
16530 (setq m2 (+ m dn) y2 y)
16531 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16532 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16533 ;; Make sure n1 is the earlier date
16534 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16535 (if show-all
16536 (cond
16537 ((eq prefer 'past) (if (= cday n2) n2 n1))
16538 ((eq prefer 'future) (if (= cday n1) n1 n2))
16539 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16540 (cond
16541 ((eq prefer 'past) (if (= cday n2) n2 n1))
16542 ((eq prefer 'future) (if (= cday n1) n1 n2))
16543 (t (if (= cday n1) n1 n2)))))))
16545 (defun org-date-to-gregorian (date)
16546 "Turn any specification of DATE into a Gregorian date for the calendar."
16547 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16548 ((and (listp date) (= (length date) 3)) date)
16549 ((stringp date)
16550 (setq date (org-parse-time-string date))
16551 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16552 ((listp date)
16553 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16555 (defun org-parse-time-string (s &optional nodefault)
16556 "Parse the standard Org-mode time string.
16557 This should be a lot faster than the normal `parse-time-string'.
16558 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16559 hour and minute fields will be nil if not given."
16560 (cond ((string-match org-ts-regexp0 s)
16561 (list 0
16562 (if (or (match-beginning 8) (not nodefault))
16563 (string-to-number (or (match-string 8 s) "0")))
16564 (if (or (match-beginning 7) (not nodefault))
16565 (string-to-number (or (match-string 7 s) "0")))
16566 (string-to-number (match-string 4 s))
16567 (string-to-number (match-string 3 s))
16568 (string-to-number (match-string 2 s))
16569 nil nil nil))
16570 ((string-match "^<[^>]+>$" s)
16571 (decode-time (seconds-to-time (org-matcher-time s))))
16572 (t (error "Not a standard Org-mode time string: %s" s))))
16574 (defun org-timestamp-up (&optional arg)
16575 "Increase the date item at the cursor by one.
16576 If the cursor is on the year, change the year. If it is on the month,
16577 the day or the time, change that.
16578 With prefix ARG, change by that many units."
16579 (interactive "p")
16580 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16582 (defun org-timestamp-down (&optional arg)
16583 "Decrease the date item at the cursor by one.
16584 If the cursor is on the year, change the year. If it is on the month,
16585 the day or the time, change that.
16586 With prefix ARG, change by that many units."
16587 (interactive "p")
16588 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16590 (defun org-timestamp-up-day (&optional arg)
16591 "Increase the date in the time stamp by one day.
16592 With prefix ARG, change that many days."
16593 (interactive "p")
16594 (if (and (not (org-at-timestamp-p t))
16595 (org-at-heading-p))
16596 (org-todo 'up)
16597 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16599 (defun org-timestamp-down-day (&optional arg)
16600 "Decrease the date in the time stamp by one day.
16601 With prefix ARG, change that many days."
16602 (interactive "p")
16603 (if (and (not (org-at-timestamp-p t))
16604 (org-at-heading-p))
16605 (org-todo 'down)
16606 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16608 (defun org-at-timestamp-p (&optional inactive-ok)
16609 "Determine if the cursor is in or at a timestamp."
16610 (interactive)
16611 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16612 (pos (point))
16613 (ans (or (looking-at tsr)
16614 (save-excursion
16615 (skip-chars-backward "^[<\n\r\t")
16616 (if (> (point) (point-min)) (backward-char 1))
16617 (and (looking-at tsr)
16618 (> (- (match-end 0) pos) -1))))))
16619 (and ans
16620 (boundp 'org-ts-what)
16621 (setq org-ts-what
16622 (cond
16623 ((= pos (match-beginning 0)) 'bracket)
16624 ;; Point is considered to be "on the bracket" whether
16625 ;; it's really on it or right after it.
16626 ((= pos (1- (match-end 0))) 'bracket)
16627 ((= pos (match-end 0)) 'after)
16628 ((org-pos-in-match-range pos 2) 'year)
16629 ((org-pos-in-match-range pos 3) 'month)
16630 ((org-pos-in-match-range pos 7) 'hour)
16631 ((org-pos-in-match-range pos 8) 'minute)
16632 ((or (org-pos-in-match-range pos 4)
16633 (org-pos-in-match-range pos 5)) 'day)
16634 ((and (> pos (or (match-end 8) (match-end 5)))
16635 (< pos (match-end 0)))
16636 (- pos (or (match-end 8) (match-end 5))))
16637 (t 'day))))
16638 ans))
16640 (defun org-toggle-timestamp-type ()
16641 "Toggle the type (<active> or [inactive]) of a time stamp."
16642 (interactive)
16643 (when (org-at-timestamp-p t)
16644 (let ((beg (match-beginning 0)) (end (match-end 0))
16645 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16646 (save-excursion
16647 (goto-char beg)
16648 (while (re-search-forward "[][<>]" end t)
16649 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16650 t t)))
16651 (message "Timestamp is now %sactive"
16652 (if (equal (char-after beg) ?<) "" "in")))))
16654 (defvar org-clock-history) ; defined in org-clock.el
16655 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16656 (defun org-timestamp-change (n &optional what updown)
16657 "Change the date in the time stamp at point.
16658 The date will be changed by N times WHAT. WHAT can be `day', `month',
16659 `year', `minute', `second'. If WHAT is not given, the cursor position
16660 in the timestamp determines what will be changed."
16661 (let ((origin (point)) origin-cat
16662 with-hm inactive
16663 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16664 org-ts-what
16665 extra rem
16666 ts time time0 fixnext clrgx)
16667 (if (not (org-at-timestamp-p t))
16668 (error "Not at a timestamp"))
16669 (if (and (not what) (eq org-ts-what 'bracket))
16670 (org-toggle-timestamp-type)
16671 ;; Point isn't on brackets. Remember the part of the time-stamp
16672 ;; the point was in. Indeed, size of time-stamps may change,
16673 ;; but point must be kept in the same category nonetheless.
16674 (setq origin-cat org-ts-what)
16675 (if (and (not what) (not (eq org-ts-what 'day))
16676 org-display-custom-times
16677 (get-text-property (point) 'display)
16678 (not (get-text-property (1- (point)) 'display)))
16679 (setq org-ts-what 'day))
16680 (setq org-ts-what (or what org-ts-what)
16681 inactive (= (char-after (match-beginning 0)) ?\[)
16682 ts (match-string 0))
16683 (replace-match "")
16684 (if (string-match
16685 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16687 (setq extra (match-string 1 ts)))
16688 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16689 (setq with-hm t))
16690 (setq time0 (org-parse-time-string ts))
16691 (when (and updown
16692 (eq org-ts-what 'minute)
16693 (not current-prefix-arg))
16694 ;; This looks like s-up and s-down. Change by one rounding step.
16695 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16696 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16697 (setcar (cdr time0) (+ (nth 1 time0)
16698 (if (> n 0) (- rem) (- dm rem))))))
16699 (setq time
16700 (encode-time (or (car time0) 0)
16701 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16702 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16703 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16704 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16705 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16706 (nthcdr 6 time0)))
16707 (when (and (member org-ts-what '(hour minute))
16708 extra
16709 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16710 (setq extra (org-modify-ts-extra
16711 extra
16712 (if (eq org-ts-what 'hour) 2 5)
16713 n dm)))
16714 (when (integerp org-ts-what)
16715 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16716 (if (eq what 'calendar)
16717 (let ((cal-date (org-get-date-from-calendar)))
16718 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16719 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16720 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16721 (setcar time0 (or (car time0) 0))
16722 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16723 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16724 (setq time (apply 'encode-time time0))))
16725 ;; Insert the new time-stamp, and ensure point stays in the same
16726 ;; category as before (i.e. not after the last position in that
16727 ;; category).
16728 (let ((pos (point)))
16729 ;; Stay before inserted string. `save-excursion' is of no use.
16730 (setq org-last-changed-timestamp
16731 (org-insert-time-stamp time with-hm inactive nil nil extra))
16732 (goto-char pos))
16733 (save-match-data
16734 (looking-at org-ts-regexp3)
16735 (goto-char (cond
16736 ;; `day' category ends before `hour' if any, or at
16737 ;; the end of the day name.
16738 ((eq origin-cat 'day)
16739 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16740 ((eq origin-cat 'hour) (min (match-end 7) origin))
16741 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16742 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16743 ;; `year' and `month' have both fixed size: point
16744 ;; couldn't have moved into another part.
16745 (t origin))))
16746 ;; Update clock if on a CLOCK line.
16747 (org-clock-update-time-maybe)
16748 ;; Maybe adjust the closest clock in `org-clock-history'
16749 (when org-clock-adjust-closest
16750 (if (not (and (org-at-clock-log-p)
16751 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16752 org-clock-history))))))
16753 (message "No clock to adjust")
16754 (cond ((save-excursion ; fix previous clock?
16755 (re-search-backward org-ts-regexp0 nil t)
16756 (org-looking-back (concat org-clock-string " \\[")))
16757 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16758 ((save-excursion ; fix next clock?
16759 (re-search-backward org-ts-regexp0 nil t)
16760 (looking-at (concat org-ts-regexp0 "\\] =>")))
16761 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16762 (save-window-excursion
16763 ;; Find closest clock to point, adjust the previous/next one in history
16764 (let* ((p (save-excursion (org-back-to-heading t)))
16765 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16766 (clfixnth
16767 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16768 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16769 (if (not clfixpos)
16770 (message "No clock to adjust")
16771 (save-excursion
16772 (org-goto-marker-or-bmk clfixpos)
16773 (org-show-subtree)
16774 (when (re-search-forward clrgx nil t)
16775 (goto-char (match-beginning 1))
16776 (let (org-clock-adjust-closest)
16777 (org-timestamp-change n org-ts-what updown))
16778 (message "Clock adjusted in %s for heading: %s"
16779 (file-name-nondirectory (buffer-file-name))
16780 (org-get-heading t t)))))))))
16781 ;; Try to recenter the calendar window, if any.
16782 (if (and org-calendar-follow-timestamp-change
16783 (get-buffer-window "*Calendar*" t)
16784 (memq org-ts-what '(day month year)))
16785 (org-recenter-calendar (time-to-days time))))))
16787 (defun org-modify-ts-extra (s pos n dm)
16788 "Change the different parts of the lead-time and repeat fields in timestamp."
16789 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16790 ng h m new rem)
16791 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16792 (cond
16793 ((or (org-pos-in-match-range pos 2)
16794 (org-pos-in-match-range pos 3))
16795 (setq m (string-to-number (match-string 3 s))
16796 h (string-to-number (match-string 2 s)))
16797 (if (org-pos-in-match-range pos 2)
16798 (setq h (+ h n))
16799 (setq n (* dm (org-no-warnings (signum n))))
16800 (when (not (= 0 (setq rem (% m dm))))
16801 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16802 (setq m (+ m n)))
16803 (if (< m 0) (setq m (+ m 60) h (1- h)))
16804 (if (> m 59) (setq m (- m 60) h (1+ h)))
16805 (setq h (min 24 (max 0 h)))
16806 (setq ng 1 new (format "-%02d:%02d" h m)))
16807 ((org-pos-in-match-range pos 6)
16808 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16809 ((org-pos-in-match-range pos 5)
16810 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16812 ((org-pos-in-match-range pos 9)
16813 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16814 ((org-pos-in-match-range pos 8)
16815 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16817 (when ng
16818 (setq s (concat
16819 (substring s 0 (match-beginning ng))
16821 (substring s (match-end ng))))))
16824 (defun org-recenter-calendar (date)
16825 "If the calendar is visible, recenter it to DATE."
16826 (let ((cwin (get-buffer-window "*Calendar*" t)))
16827 (when cwin
16828 (let ((calendar-move-hook nil))
16829 (with-selected-window cwin
16830 (calendar-goto-date (if (listp date) date
16831 (calendar-gregorian-from-absolute date))))))))
16833 (defun org-goto-calendar (&optional arg)
16834 "Go to the Emacs calendar at the current date.
16835 If there is a time stamp in the current line, go to that date.
16836 A prefix ARG can be used to force the current date."
16837 (interactive "P")
16838 (let ((tsr org-ts-regexp) diff
16839 (calendar-move-hook nil)
16840 (calendar-view-holidays-initially-flag nil)
16841 (calendar-view-diary-initially-flag nil))
16842 (if (or (org-at-timestamp-p)
16843 (save-excursion
16844 (beginning-of-line 1)
16845 (looking-at (concat ".*" tsr))))
16846 (let ((d1 (time-to-days (current-time)))
16847 (d2 (time-to-days
16848 (org-time-string-to-time (match-string 1)))))
16849 (setq diff (- d2 d1))))
16850 (calendar)
16851 (calendar-goto-today)
16852 (if (and diff (not arg)) (calendar-forward-day diff))))
16854 (defun org-get-date-from-calendar ()
16855 "Return a list (month day year) of date at point in calendar."
16856 (with-current-buffer "*Calendar*"
16857 (save-match-data
16858 (calendar-cursor-to-date))))
16860 (defun org-date-from-calendar ()
16861 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16862 If there is already a time stamp at the cursor position, update it."
16863 (interactive)
16864 (if (org-at-timestamp-p t)
16865 (org-timestamp-change 0 'calendar)
16866 (let ((cal-date (org-get-date-from-calendar)))
16867 (org-insert-time-stamp
16868 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16870 (defun org-minutes-to-clocksum-string (m)
16871 "Format number of minutes as a clocksum string.
16872 The format is determined by `org-time-clocksum-format',
16873 `org-time-clocksum-use-fractional' and
16874 `org-time-clocksum-fractional-format'."
16875 (let ((clocksum "") fmt n)
16876 ;; fractional format
16877 (if org-time-clocksum-use-fractional
16878 (cond
16879 ;; single format string
16880 ((stringp org-time-clocksum-fractional-format)
16881 (format org-time-clocksum-fractional-format (/ m 60.0)))
16882 ;; choice of fractional formats for different time units
16883 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
16884 (> (/ (truncate m) (* 365 24 60)) 0))
16885 (format fmt (/ m (* 365 24 60.0))))
16886 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
16887 (> (/ (truncate m) (* 30 24 60)) 0))
16888 (format fmt (/ m (* 30 24 60.0))))
16889 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16890 (> (/ (truncate m) (* 7 24 60)) 0))
16891 (format fmt (/ m (* 7 24 60.0))))
16892 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
16893 (> (/ (truncate m) (* 24 60)) 0))
16894 (format fmt (/ m (* 24 60.0))))
16895 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16896 (> (/ (truncate m) 60) 0))
16897 (format fmt (/ m 60.0)))
16898 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
16899 (format fmt m))
16900 ;; fall back to smallest time unit with a format
16901 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16902 (format fmt (/ m 60.0)))
16903 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
16904 (format fmt (/ m (* 24 60.0))))
16905 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16906 (format fmt (/ m (* 7 24 60.0))))
16907 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
16908 (format fmt (/ m (* 30 24 60.0))))
16909 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
16910 (format fmt (/ m (* 365 24 60.0)))))
16911 ;; standard (non-fractional) format, with single format string
16912 (if (stringp org-time-clocksum-format)
16913 (format org-time-clocksum-format (setq n (/ m 60)) (- m (* 60 n)))
16914 ;; separate formats components
16915 (and (setq fmt (plist-get org-time-clocksum-format :years))
16916 (or (> (setq n (/ (truncate m) (* 365 24 60))) 0)
16917 (plist-get org-time-clocksum-format :require-years))
16918 (setq clocksum (concat clocksum (format fmt n))
16919 m (- m (* n 365 24 60))))
16920 (and (setq fmt (plist-get org-time-clocksum-format :months))
16921 (or (> (setq n (/ (truncate m) (* 30 24 60))) 0)
16922 (plist-get org-time-clocksum-format :require-months))
16923 (setq clocksum (concat clocksum (format fmt n))
16924 m (- m (* n 30 24 60))))
16925 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
16926 (or (> (setq n (/ (truncate m) (* 7 24 60))) 0)
16927 (plist-get org-time-clocksum-format :require-weeks))
16928 (setq clocksum (concat clocksum (format fmt n))
16929 m (- m (* n 7 24 60))))
16930 (and (setq fmt (plist-get org-time-clocksum-format :days))
16931 (or (> (setq n (/ (truncate m) (* 24 60))) 0)
16932 (plist-get org-time-clocksum-format :require-days))
16933 (setq clocksum (concat clocksum (format fmt n))
16934 m (- m (* n 24 60))))
16935 (and (setq fmt (plist-get org-time-clocksum-format :hours))
16936 (or (> (setq n (/ (truncate m) 60)) 0)
16937 (plist-get org-time-clocksum-format :require-hours))
16938 (setq clocksum (concat clocksum (format fmt n))
16939 m (- m (* n 60))))
16940 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
16941 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
16942 (setq clocksum (concat clocksum (format fmt m))))
16943 ;; return formatted time duration
16944 clocksum))))
16946 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
16947 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
16948 "Org mode version 8.0")
16950 (defun org-hours-to-clocksum-string (n)
16951 (org-minutes-to-clocksum-string (* n 60)))
16953 (defun org-hh:mm-string-to-minutes (s)
16954 "Convert a string H:MM to a number of minutes.
16955 If the string is just a number, interpret it as minutes.
16956 In fact, the first hh:mm or number in the string will be taken,
16957 there can be extra stuff in the string.
16958 If no number is found, the return value is 0."
16959 (cond
16960 ((integerp s) s)
16961 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16962 (+ (* (string-to-number (match-string 1 s)) 60)
16963 (string-to-number (match-string 2 s))))
16964 ((string-match "\\([0-9]+\\)" s)
16965 (string-to-number (match-string 1 s)))
16966 (t 0)))
16968 (defcustom org-effort-durations
16969 `(("h" . 60)
16970 ("d" . ,(* 60 8))
16971 ("w" . ,(* 60 8 5))
16972 ("m" . ,(* 60 8 5 4))
16973 ("y" . ,(* 60 8 5 40)))
16974 "Conversion factor to minutes for an effort modifier.
16976 Each entry has the form (MODIFIER . MINUTES).
16978 In an effort string, a number followed by MODIFIER is multiplied
16979 by the specified number of MINUTES to obtain an effort in
16980 minutes.
16982 For example, if the value of this variable is ((\"hours\" . 60)), then an
16983 effort string \"2hours\" is equivalent to 120 minutes."
16984 :group 'org-agenda
16985 :version "24.1"
16986 :type '(alist :key-type (string :tag "Modifier")
16987 :value-type (number :tag "Minutes")))
16989 (defcustom org-image-actual-width t
16990 "Should we use the actual width of images when inlining them?
16992 When set to `t', always use the image width.
16994 When set to a number, use imagemagick (when available) to set
16995 the image's width to this value.
16997 When set to a number in a list, try to get the width from the
16998 #+ATTR.* keyword if it matches a width specification like
16999 width=\"[0-9]+\", and fall back on that number if none is found.
17001 When set to nil, try to get the width from an #+ATTR.* keyword
17002 and fall back on the original width if none is found.
17004 This requires Emacs >= 24.1, build with imagemagick support."
17005 :group 'org-appearance
17006 :version "24.3"
17007 :type '(choice
17008 (const :tag "Use the image width" t)
17009 (integer :tag "Use a number of pixels")
17010 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17011 (const :tag "Use #+ATTR* or don't resize" nil)))
17013 (defun org-duration-string-to-minutes (s &optional output-to-string)
17014 "Convert a duration string S to minutes.
17016 A bare number is interpreted as minutes, modifiers can be set by
17017 customizing `org-effort-durations' (which see).
17019 Entries containing a colon are interpreted as H:MM by
17020 `org-hh:mm-string-to-minutes'."
17021 (let ((result 0)
17022 (re (concat "\\([0-9.]+\\) *\\("
17023 (regexp-opt (mapcar 'car org-effort-durations))
17024 "\\)")))
17025 (while (string-match re s)
17026 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17027 (string-to-number (match-string 1 s))))
17028 (setq s (replace-match "" nil t s)))
17029 (setq result (floor result))
17030 (incf result (org-hh:mm-string-to-minutes s))
17031 (if output-to-string (number-to-string result) result)))
17033 ;;;; Files
17035 (defun org-save-all-org-buffers ()
17036 "Save all Org-mode buffers without user confirmation."
17037 (interactive)
17038 (message "Saving all Org-mode buffers...")
17039 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17040 (when (featurep 'org-id) (org-id-locations-save))
17041 (message "Saving all Org-mode buffers... done"))
17043 (defun org-revert-all-org-buffers ()
17044 "Revert all Org-mode buffers.
17045 Prompt for confirmation when there are unsaved changes.
17046 Be sure you know what you are doing before letting this function
17047 overwrite your changes.
17049 This function is useful in a setup where one tracks org files
17050 with a version control system, to revert on one machine after pulling
17051 changes from another. I believe the procedure must be like this:
17053 1. M-x org-save-all-org-buffers
17054 2. Pull changes from the other machine, resolve conflicts
17055 3. M-x org-revert-all-org-buffers"
17056 (interactive)
17057 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17058 (error "Abort"))
17059 (save-excursion
17060 (save-window-excursion
17061 (mapc
17062 (lambda (b)
17063 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17064 (with-current-buffer b buffer-file-name))
17065 (org-pop-to-buffer-same-window b)
17066 (revert-buffer t 'no-confirm)))
17067 (buffer-list))
17068 (when (and (featurep 'org-id) org-id-track-globally)
17069 (org-id-locations-load)))))
17071 ;;;; Agenda files
17073 ;;;###autoload
17074 (defun org-switchb (&optional arg)
17075 "Switch between Org buffers.
17076 With one prefix argument, restrict available buffers to files.
17077 With two prefix arguments, restrict available buffers to agenda files.
17079 Defaults to `iswitchb' for buffer name completion.
17080 Set `org-completion-use-ido' to make it use ido instead."
17081 (interactive "P")
17082 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17083 ((equal arg '(16)) (org-buffer-list 'agenda))
17084 (t (org-buffer-list))))
17085 (org-completion-use-iswitchb org-completion-use-iswitchb)
17086 (org-completion-use-ido org-completion-use-ido))
17087 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17088 (setq org-completion-use-iswitchb t))
17089 (org-pop-to-buffer-same-window
17090 (org-icompleting-read "Org buffer: "
17091 (mapcar 'list (mapcar 'buffer-name blist))
17092 nil t))))
17094 ;;; Define some older names previously used for this functionality
17095 ;;;###autoload
17096 (defalias 'org-ido-switchb 'org-switchb)
17097 ;;;###autoload
17098 (defalias 'org-iswitchb 'org-switchb)
17100 (defun org-buffer-list (&optional predicate exclude-tmp)
17101 "Return a list of Org buffers.
17102 PREDICATE can be `export', `files' or `agenda'.
17104 export restrict the list to Export buffers.
17105 files restrict the list to buffers visiting Org files.
17106 agenda restrict the list to buffers visiting agenda files.
17108 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17109 (let* ((bfn nil)
17110 (agenda-files (and (eq predicate 'agenda)
17111 (mapcar 'file-truename (org-agenda-files t))))
17112 (filter
17113 (cond
17114 ((eq predicate 'files)
17115 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17116 ((eq predicate 'export)
17117 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17118 ((eq predicate 'agenda)
17119 (lambda (b)
17120 (with-current-buffer b
17121 (and (derived-mode-p 'org-mode)
17122 (setq bfn (buffer-file-name b))
17123 (member (file-truename bfn) agenda-files)))))
17124 (t (lambda (b) (with-current-buffer b
17125 (or (derived-mode-p 'org-mode)
17126 (string-match "\*Org .*Export"
17127 (buffer-name b)))))))))
17128 (delq nil
17129 (mapcar
17130 (lambda(b)
17131 (if (and (funcall filter b)
17132 (or (not exclude-tmp)
17133 (not (string-match "tmp" (buffer-name b)))))
17135 nil))
17136 (buffer-list)))))
17138 (defun org-agenda-files (&optional unrestricted archives)
17139 "Get the list of agenda files.
17140 Optional UNRESTRICTED means return the full list even if a restriction
17141 is currently in place.
17142 When ARCHIVES is t, include all archive files that are really being
17143 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17144 `org-agenda-archives-mode' is t."
17145 (let ((files
17146 (cond
17147 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17148 ((stringp org-agenda-files) (org-read-agenda-file-list))
17149 ((listp org-agenda-files) org-agenda-files)
17150 (t (error "Invalid value of `org-agenda-files'")))))
17151 (setq files (apply 'append
17152 (mapcar (lambda (f)
17153 (if (file-directory-p f)
17154 (directory-files
17155 f t org-agenda-file-regexp)
17156 (list f)))
17157 files)))
17158 (when org-agenda-skip-unavailable-files
17159 (setq files (delq nil
17160 (mapcar (function
17161 (lambda (file)
17162 (and (file-readable-p file) file)))
17163 files))))
17164 (when (or (eq archives t)
17165 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17166 (setq files (org-add-archive-files files)))
17167 files))
17169 (defun org-agenda-file-p (&optional file)
17170 "Return non-nil, if FILE is an agenda file.
17171 If FILE is omitted, use the file associated with the current
17172 buffer."
17173 (member (or file (buffer-file-name))
17174 (org-agenda-files t)))
17176 (defun org-edit-agenda-file-list ()
17177 "Edit the list of agenda files.
17178 Depending on setup, this either uses customize to edit the variable
17179 `org-agenda-files', or it visits the file that is holding the list. In the
17180 latter case, the buffer is set up in a way that saving it automatically kills
17181 the buffer and restores the previous window configuration."
17182 (interactive)
17183 (if (stringp org-agenda-files)
17184 (let ((cw (current-window-configuration)))
17185 (find-file org-agenda-files)
17186 (org-set-local 'org-window-configuration cw)
17187 (org-add-hook 'after-save-hook
17188 (lambda ()
17189 (set-window-configuration
17190 (prog1 org-window-configuration
17191 (kill-buffer (current-buffer))))
17192 (org-install-agenda-files-menu)
17193 (message "New agenda file list installed"))
17194 nil 'local)
17195 (message "%s" (substitute-command-keys
17196 "Edit list and finish with \\[save-buffer]")))
17197 (customize-variable 'org-agenda-files)))
17199 (defun org-store-new-agenda-file-list (list)
17200 "Set new value for the agenda file list and save it correctly."
17201 (if (stringp org-agenda-files)
17202 (let ((fe (org-read-agenda-file-list t)) b u)
17203 (while (setq b (find-buffer-visiting org-agenda-files))
17204 (kill-buffer b))
17205 (with-temp-file org-agenda-files
17206 (insert
17207 (mapconcat
17208 (lambda (f) ;; Keep un-expanded entries.
17209 (if (setq u (assoc f fe))
17210 (cdr u)
17212 list "\n")
17213 "\n")))
17214 (let ((org-mode-hook nil) (org-inhibit-startup t)
17215 (org-insert-mode-line-in-empty-file nil))
17216 (setq org-agenda-files list)
17217 (customize-save-variable 'org-agenda-files org-agenda-files))))
17219 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17220 "Read the list of agenda files from a file.
17221 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17222 filenames, used by `org-store-new-agenda-file-list' to write back
17223 un-expanded file names."
17224 (when (file-directory-p org-agenda-files)
17225 (error "`org-agenda-files' cannot be a single directory"))
17226 (when (stringp org-agenda-files)
17227 (with-temp-buffer
17228 (insert-file-contents org-agenda-files)
17229 (mapcar
17230 (lambda (f)
17231 (let ((e (expand-file-name (substitute-in-file-name f)
17232 org-directory)))
17233 (if pair-with-expansion
17234 (cons e f)
17235 e)))
17236 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17238 ;;;###autoload
17239 (defun org-cycle-agenda-files ()
17240 "Cycle through the files in `org-agenda-files'.
17241 If the current buffer visits an agenda file, find the next one in the list.
17242 If the current buffer does not, find the first agenda file."
17243 (interactive)
17244 (let* ((fs (org-agenda-files t))
17245 (files (append fs (list (car fs))))
17246 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17247 file)
17248 (unless files (error "No agenda files"))
17249 (catch 'exit
17250 (while (setq file (pop files))
17251 (if (equal (file-truename file) tcf)
17252 (when (car files)
17253 (find-file (car files))
17254 (throw 'exit t))))
17255 (find-file (car fs)))
17256 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17258 (defun org-agenda-file-to-front (&optional to-end)
17259 "Move/add the current file to the top of the agenda file list.
17260 If the file is not present in the list, it is added to the front. If it is
17261 present, it is moved there. With optional argument TO-END, add/move to the
17262 end of the list."
17263 (interactive "P")
17264 (let ((org-agenda-skip-unavailable-files nil)
17265 (file-alist (mapcar (lambda (x)
17266 (cons (file-truename x) x))
17267 (org-agenda-files t)))
17268 (ctf (file-truename
17269 (or buffer-file-name
17270 (error "Please save the current buffer to a file"))))
17271 x had)
17272 (setq x (assoc ctf file-alist) had x)
17274 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17275 (if to-end
17276 (setq file-alist (append (delq x file-alist) (list x)))
17277 (setq file-alist (cons x (delq x file-alist))))
17278 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17279 (org-install-agenda-files-menu)
17280 (message "File %s to %s of agenda file list"
17281 (if had "moved" "added") (if to-end "end" "front"))))
17283 (defun org-remove-file (&optional file)
17284 "Remove current file from the list of files in variable `org-agenda-files'.
17285 These are the files which are being checked for agenda entries.
17286 Optional argument FILE means use this file instead of the current."
17287 (interactive)
17288 (let* ((org-agenda-skip-unavailable-files nil)
17289 (file (or file buffer-file-name
17290 (error "Current buffer does not visit a file")))
17291 (true-file (file-truename file))
17292 (afile (abbreviate-file-name file))
17293 (files (delq nil (mapcar
17294 (lambda (x)
17295 (if (equal true-file
17296 (file-truename x))
17297 nil x))
17298 (org-agenda-files t)))))
17299 (if (not (= (length files) (length (org-agenda-files t))))
17300 (progn
17301 (org-store-new-agenda-file-list files)
17302 (org-install-agenda-files-menu)
17303 (message "Removed file: %s" afile))
17304 (message "File was not in list: %s (not removed)" afile))))
17306 (defun org-file-menu-entry (file)
17307 (vector file (list 'find-file file) t))
17309 (defun org-check-agenda-file (file)
17310 "Make sure FILE exists. If not, ask user what to do."
17311 (when (not (file-exists-p file))
17312 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17313 (abbreviate-file-name file))
17314 (let ((r (downcase (read-char-exclusive))))
17315 (cond
17316 ((equal r ?r)
17317 (org-remove-file file)
17318 (throw 'nextfile t))
17319 (t (error "Abort"))))))
17321 (defun org-get-agenda-file-buffer (file)
17322 "Get a buffer visiting FILE. If the buffer needs to be created, add
17323 it to the list of buffers which might be released later."
17324 (let ((buf (org-find-base-buffer-visiting file)))
17325 (if buf
17326 buf ; just return it
17327 ;; Make a new buffer and remember it
17328 (setq buf (find-file-noselect file))
17329 (if buf (push buf org-agenda-new-buffers))
17330 buf)))
17332 (defun org-release-buffers (blist)
17333 "Release all buffers in list, asking the user for confirmation when needed.
17334 When a buffer is unmodified, it is just killed. When modified, it is saved
17335 \(if the user agrees) and then killed."
17336 (let (buf file)
17337 (while (setq buf (pop blist))
17338 (setq file (buffer-file-name buf))
17339 (when (and (buffer-modified-p buf)
17340 file
17341 (y-or-n-p (format "Save file %s? " file)))
17342 (with-current-buffer buf (save-buffer)))
17343 (kill-buffer buf))))
17345 (defun org-agenda-prepare-buffers (files)
17346 "Create buffers for all agenda files, protect archived trees and comments."
17347 (interactive)
17348 (let ((pa '(:org-archived t))
17349 (pc '(:org-comment t))
17350 (pall '(:org-archived t :org-comment t))
17351 (inhibit-read-only t)
17352 (rea (concat ":" org-archive-tag ":"))
17353 bmp file re)
17354 (save-excursion
17355 (save-restriction
17356 (while (setq file (pop files))
17357 (catch 'nextfile
17358 (if (bufferp file)
17359 (set-buffer file)
17360 (org-check-agenda-file file)
17361 (set-buffer (org-get-agenda-file-buffer file)))
17362 (widen)
17363 (setq bmp (buffer-modified-p))
17364 (org-refresh-category-properties)
17365 (setq org-todo-keywords-for-agenda
17366 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17367 (setq org-done-keywords-for-agenda
17368 (append org-done-keywords-for-agenda org-done-keywords))
17369 (setq org-todo-keyword-alist-for-agenda
17370 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17371 (setq org-drawers-for-agenda
17372 (append org-drawers-for-agenda org-drawers))
17373 (setq org-tag-alist-for-agenda
17374 (append org-tag-alist-for-agenda org-tag-alist))
17376 (save-excursion
17377 (remove-text-properties (point-min) (point-max) pall)
17378 (when org-agenda-skip-archived-trees
17379 (goto-char (point-min))
17380 (while (re-search-forward rea nil t)
17381 (if (org-at-heading-p t)
17382 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17383 (goto-char (point-min))
17384 (setq re (format org-heading-keyword-regexp-format
17385 org-comment-string))
17386 (while (re-search-forward re nil t)
17387 (add-text-properties
17388 (match-beginning 0) (org-end-of-subtree t) pc)))
17389 (set-buffer-modified-p bmp)))))
17390 (setq org-todo-keywords-for-agenda
17391 (org-uniquify org-todo-keywords-for-agenda))
17392 (setq org-todo-keyword-alist-for-agenda
17393 (org-uniquify org-todo-keyword-alist-for-agenda)
17394 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17396 ;;;; Embedded LaTeX
17398 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17399 "Keymap for the minor `org-cdlatex-mode'.")
17401 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17402 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17403 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17404 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17405 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17407 (defvar org-cdlatex-texmathp-advice-is-done nil
17408 "Flag remembering if we have applied the advice to texmathp already.")
17410 (define-minor-mode org-cdlatex-mode
17411 "Toggle the minor `org-cdlatex-mode'.
17412 This mode supports entering LaTeX environment and math in LaTeX fragments
17413 in Org-mode.
17414 \\{org-cdlatex-mode-map}"
17415 nil " OCDL" nil
17416 (when org-cdlatex-mode
17417 (require 'cdlatex)
17418 (run-hooks 'cdlatex-mode-hook)
17419 (cdlatex-compute-tables))
17420 (unless org-cdlatex-texmathp-advice-is-done
17421 (setq org-cdlatex-texmathp-advice-is-done t)
17422 (defadvice texmathp (around org-math-always-on activate)
17423 "Always return t in org-mode buffers.
17424 This is because we want to insert math symbols without dollars even outside
17425 the LaTeX math segments. If Orgmode thinks that point is actually inside
17426 an embedded LaTeX fragment, let texmathp do its job.
17427 \\[org-cdlatex-mode-map]"
17428 (interactive)
17429 (let (p)
17430 (cond
17431 ((not (derived-mode-p 'org-mode)) ad-do-it)
17432 ((eq this-command 'cdlatex-math-symbol)
17433 (setq ad-return-value t
17434 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17436 (let ((p (org-inside-LaTeX-fragment-p)))
17437 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17438 (setq ad-return-value t
17439 texmathp-why '("Org-mode embedded math" . 0))
17440 (if p ad-do-it)))))))))
17442 (defun turn-on-org-cdlatex ()
17443 "Unconditionally turn on `org-cdlatex-mode'."
17444 (org-cdlatex-mode 1))
17446 (defun org-inside-LaTeX-fragment-p ()
17447 "Test if point is inside a LaTeX fragment.
17448 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17449 sequence appearing also before point.
17450 Even though the matchers for math are configurable, this function assumes
17451 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17452 delimiters are skipped when they have been removed by customization.
17453 The return value is nil, or a cons cell with the delimiter and the
17454 position of this delimiter.
17456 This function does a reasonably good job, but can locally be fooled by
17457 for example currency specifications. For example it will assume being in
17458 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17459 fragments that are properly closed, but during editing, we have to live
17460 with the uncertainty caused by missing closing delimiters. This function
17461 looks only before point, not after."
17462 (catch 'exit
17463 (let ((pos (point))
17464 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17465 (lim (progn
17466 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17467 (point)))
17468 dd-on str (start 0) m re)
17469 (goto-char pos)
17470 (when dodollar
17471 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17472 re (nth 1 (assoc "$" org-latex-regexps)))
17473 (while (string-match re str start)
17474 (cond
17475 ((= (match-end 0) (length str))
17476 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17477 ((= (match-end 0) (- (length str) 5))
17478 (throw 'exit nil))
17479 (t (setq start (match-end 0))))))
17480 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17481 (goto-char pos)
17482 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17483 (and (match-beginning 2) (throw 'exit nil))
17484 ;; count $$
17485 (while (re-search-backward "\\$\\$" lim t)
17486 (setq dd-on (not dd-on)))
17487 (goto-char pos)
17488 (if dd-on (cons "$$" m))))))
17490 (defun org-inside-latex-macro-p ()
17491 "Is point inside a LaTeX macro or its arguments?"
17492 (save-match-data
17493 (org-in-regexp
17494 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17496 (defun org-try-cdlatex-tab ()
17497 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17498 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17499 - inside a LaTeX fragment, or
17500 - after the first word in a line, where an abbreviation expansion could
17501 insert a LaTeX environment."
17502 (when org-cdlatex-mode
17503 (cond
17504 ;; Before any word on the line: No expansion possible.
17505 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17506 ;; Just after first word on the line: Expand it. Make sure it
17507 ;; cannot happen on headlines, though.
17508 ((save-excursion
17509 (skip-chars-backward "a-zA-Z0-9*")
17510 (skip-chars-backward " \t")
17511 (and (bolp) (not (org-at-heading-p))))
17512 (cdlatex-tab) t)
17513 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17515 (defun org-cdlatex-underscore-caret (&optional arg)
17516 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17517 Revert to the normal definition outside of these fragments."
17518 (interactive "P")
17519 (if (org-inside-LaTeX-fragment-p)
17520 (call-interactively 'cdlatex-sub-superscript)
17521 (let (org-cdlatex-mode)
17522 (call-interactively (key-binding (vector last-input-event))))))
17524 (defun org-cdlatex-math-modify (&optional arg)
17525 "Execute `cdlatex-math-modify' in LaTeX fragments.
17526 Revert to the normal definition outside of these fragments."
17527 (interactive "P")
17528 (if (org-inside-LaTeX-fragment-p)
17529 (call-interactively 'cdlatex-math-modify)
17530 (let (org-cdlatex-mode)
17531 (call-interactively (key-binding (vector last-input-event))))))
17533 (defvar org-latex-fragment-image-overlays nil
17534 "List of overlays carrying the images of latex fragments.")
17535 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17537 (defun org-remove-latex-fragment-image-overlays ()
17538 "Remove all overlays with LaTeX fragment images in current buffer."
17539 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17540 (setq org-latex-fragment-image-overlays nil))
17542 (defun org-preview-latex-fragment (&optional subtree)
17543 "Preview the LaTeX fragment at point, or all locally or globally.
17544 If the cursor is in a LaTeX fragment, create the image and overlay
17545 it over the source code. If there is no fragment at point, display
17546 all fragments in the current text, from one headline to the next. With
17547 prefix SUBTREE, display all fragments in the current subtree. With a
17548 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17549 the cursor is before the first headline,
17550 display all fragments in the buffer.
17551 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17552 (interactive "P")
17553 (unless buffer-file-name
17554 (error "Can't preview LaTeX fragment in a non-file buffer"))
17555 (org-remove-latex-fragment-image-overlays)
17556 (save-excursion
17557 (save-restriction
17558 (let (beg end at msg)
17559 (cond
17560 ((or (equal subtree '(16))
17561 (not (save-excursion
17562 (re-search-backward org-outline-regexp-bol nil t))))
17563 (setq beg (point-min) end (point-max)
17564 msg "Creating images for buffer...%s"))
17565 ((equal subtree '(4))
17566 (org-back-to-heading)
17567 (setq beg (point) end (org-end-of-subtree t)
17568 msg "Creating images for subtree...%s"))
17570 (if (setq at (org-inside-LaTeX-fragment-p))
17571 (goto-char (max (point-min) (- (cdr at) 2)))
17572 (org-back-to-heading))
17573 (setq beg (point) end (progn (outline-next-heading) (point))
17574 msg (if at "Creating image...%s"
17575 "Creating images for entry...%s"))))
17576 (message msg "")
17577 (narrow-to-region beg end)
17578 (goto-char beg)
17579 (org-format-latex
17580 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17581 (file-name-nondirectory
17582 buffer-file-name)))
17583 default-directory 'overlays msg at 'forbuffer
17584 org-latex-create-formula-image-program)
17585 (message msg "done. Use `C-c C-c' to remove images.")))))
17587 (defvar org-latex-regexps
17588 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17589 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17590 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17591 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17592 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17593 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17594 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17595 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17596 "Regular expressions for matching embedded LaTeX.")
17598 (defvar org-export-have-math nil) ;; dynamic scoping
17599 (defun org-format-latex (prefix &optional dir overlays msg at
17600 forbuffer processing-type)
17601 "Replace LaTeX fragments with links to an image, and produce images.
17602 Some of the options can be changed using the variable
17603 `org-format-latex-options'."
17604 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17605 (let* ((prefixnodir (file-name-nondirectory prefix))
17606 (absprefix (expand-file-name prefix dir))
17607 (todir (file-name-directory absprefix))
17608 (opt org-format-latex-options)
17609 (optnew org-format-latex-options)
17610 (matchers (plist-get opt :matchers))
17611 (re-list org-latex-regexps)
17612 (org-format-latex-header-extra
17613 (plist-get (org-infile-export-plist) :latex-header-extra))
17614 (cnt 0) txt hash link beg end re e checkdir
17615 string
17616 m n block-type block linkfile movefile ov)
17617 ;; Check the different regular expressions
17618 (while (setq e (pop re-list))
17619 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17620 block (if block-type "\n\n" ""))
17621 (when (member m matchers)
17622 (goto-char (point-min))
17623 (while (re-search-forward re nil t)
17624 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17625 (not (get-text-property (match-beginning n)
17626 'org-protected))
17627 (or (not overlays)
17628 (not (eq (get-char-property (match-beginning n)
17629 'org-overlay-type)
17630 'org-latex-overlay))))
17631 (setq org-export-have-math t)
17632 (cond
17633 ((eq processing-type 'verbatim)
17634 ;; Leave the text verbatim, just protect it
17635 (add-text-properties (match-beginning n) (match-end n)
17636 '(org-protected t)))
17637 ((eq processing-type 'mathjax)
17638 ;; Prepare for MathJax processing
17639 (setq string (match-string n))
17640 (if (member m '("$" "$1"))
17641 (save-excursion
17642 (delete-region (match-beginning n) (match-end n))
17643 (goto-char (match-beginning n))
17644 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17645 "\\)")
17646 '(org-protected t))))
17647 (add-text-properties (match-beginning n) (match-end n)
17648 '(org-protected t))))
17649 ((or (eq processing-type 'dvipng)
17650 (eq processing-type 'imagemagick))
17651 ;; Process to an image
17652 (setq txt (match-string n)
17653 beg (match-beginning n) end (match-end n)
17654 cnt (1+ cnt))
17655 (let ((face (face-at-point))
17656 (fg (plist-get opt :foreground))
17657 (bg (plist-get opt :background))
17658 print-length print-level) ; make sure full list is printed
17659 (when forbuffer
17660 ; Get the colors from the face at point
17661 (goto-char beg)
17662 (when (eq fg 'auto)
17663 (setq fg (face-attribute face :foreground nil 'default)))
17664 (when (eq bg 'auto)
17665 (setq bg (face-attribute face :background nil 'default)))
17666 (setq optnew (copy-sequence opt))
17667 (plist-put optnew :foreground fg)
17668 (plist-put optnew :background bg))
17669 (setq hash (sha1 (prin1-to-string
17670 (list org-format-latex-header
17671 org-format-latex-header-extra
17672 org-export-latex-default-packages-alist
17673 org-export-latex-packages-alist
17674 org-format-latex-options
17675 forbuffer txt fg bg)))
17676 linkfile (format "%s_%s.png" prefix hash)
17677 movefile (format "%s_%s.png" absprefix hash)))
17678 (setq link (concat block "[[file:" linkfile "]]" block))
17679 (if msg (message msg cnt))
17680 (goto-char beg)
17681 (unless checkdir ; make sure the directory exists
17682 (setq checkdir t)
17683 (or (file-directory-p todir) (make-directory todir t)))
17684 (unless (file-exists-p movefile)
17685 (org-create-formula-image
17686 txt movefile optnew forbuffer processing-type))
17687 (if overlays
17688 (progn
17689 (mapc (lambda (o)
17690 (if (eq (overlay-get o 'org-overlay-type)
17691 'org-latex-overlay)
17692 (delete-overlay o)))
17693 (overlays-in beg end))
17694 (setq ov (make-overlay beg end))
17695 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17696 (if (featurep 'xemacs)
17697 (progn
17698 (overlay-put ov 'invisible t)
17699 (overlay-put
17700 ov 'end-glyph
17701 (make-glyph (vector 'png :file movefile))))
17702 (overlay-put
17703 ov 'display
17704 (list 'image :type 'png :file movefile :ascent 'center)))
17705 (push ov org-latex-fragment-image-overlays)
17706 (goto-char end))
17707 (delete-region beg end)
17708 (insert (org-add-props link
17709 (list 'org-latex-src
17710 (replace-regexp-in-string
17711 "\"" "" txt)
17712 'org-latex-src-embed-type
17713 (if block-type 'paragraph 'character))))))
17714 ((eq processing-type 'mathml)
17715 ;; Process to MathML
17716 (unless (save-match-data (org-format-latex-mathml-available-p))
17717 (error "LaTeX to MathML converter not configured"))
17718 (setq txt (match-string n)
17719 beg (match-beginning n) end (match-end n)
17720 cnt (1+ cnt))
17721 (if msg (message msg cnt))
17722 (goto-char beg)
17723 (delete-region beg end)
17724 (insert (org-format-latex-as-mathml
17725 txt block-type prefix dir)))
17727 (error "Unknown conversion type %s for latex fragments"
17728 processing-type)))))))))
17730 (defun org-create-math-formula (latex-frag &optional mathml-file)
17731 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17732 Use `org-latex-to-mathml-convert-command'. If the conversion is
17733 sucessful, return the portion between \"<math...> </math>\"
17734 elements otherwise return nil. When MATHML-FILE is specified,
17735 write the results in to that file. When invoked as an
17736 interactive command, prompt for LATEX-FRAG, with initial value
17737 set to the current active region and echo the results for user
17738 inspection."
17739 (interactive (list (let ((frag (when (org-region-active-p)
17740 (buffer-substring-no-properties
17741 (region-beginning) (region-end)))))
17742 (read-string "LaTeX Fragment: " frag nil frag))))
17743 (unless latex-frag (error "Invalid latex-frag"))
17744 (let* ((tmp-in-file (file-relative-name
17745 (make-temp-name (expand-file-name "ltxmathml-in"))))
17746 (ignore (write-region latex-frag nil tmp-in-file))
17747 (tmp-out-file (file-relative-name
17748 (make-temp-name (expand-file-name "ltxmathml-out"))))
17749 (cmd (format-spec
17750 org-latex-to-mathml-convert-command
17751 `((?j . ,(shell-quote-argument
17752 (expand-file-name org-latex-to-mathml-jar-file)))
17753 (?I . ,(shell-quote-argument tmp-in-file))
17754 (?o . ,(shell-quote-argument tmp-out-file)))))
17755 mathml shell-command-output)
17756 (when (org-called-interactively-p 'any)
17757 (unless (org-format-latex-mathml-available-p)
17758 (error "LaTeX to MathML converter not configured")))
17759 (message "Running %s" cmd)
17760 (setq shell-command-output (shell-command-to-string cmd))
17761 (setq mathml
17762 (when (file-readable-p tmp-out-file)
17763 (with-current-buffer (find-file-noselect tmp-out-file t)
17764 (goto-char (point-min))
17765 (when (re-search-forward
17766 (concat
17767 (regexp-quote
17768 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17769 "\\(.\\|\n\\)*"
17770 (regexp-quote "</math>")) nil t)
17771 (prog1 (match-string 0) (kill-buffer))))))
17772 (cond
17773 (mathml
17774 (setq mathml
17775 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17776 (when mathml-file
17777 (write-region mathml nil mathml-file))
17778 (when (org-called-interactively-p 'any)
17779 (message mathml)))
17780 ((message "LaTeX to MathML conversion failed")
17781 (message shell-command-output)))
17782 (delete-file tmp-in-file)
17783 (when (file-exists-p tmp-out-file)
17784 (delete-file tmp-out-file))
17785 mathml))
17787 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17788 prefix &optional dir)
17789 "Use `org-create-math-formula' but check local cache first."
17790 (let* ((absprefix (expand-file-name prefix dir))
17791 (print-length nil) (print-level nil)
17792 (formula-id (concat
17793 "formula-"
17794 (sha1
17795 (prin1-to-string
17796 (list latex-frag
17797 org-latex-to-mathml-convert-command)))))
17798 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17799 (formula-cache-dir (file-name-directory formula-cache)))
17801 (unless (file-directory-p formula-cache-dir)
17802 (make-directory formula-cache-dir t))
17804 (unless (file-exists-p formula-cache)
17805 (org-create-math-formula latex-frag formula-cache))
17807 (if (file-exists-p formula-cache)
17808 ;; Successful conversion. Return the link to MathML file.
17809 (org-add-props
17810 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17811 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17812 'org-latex-src-embed-type (if latex-frag-type
17813 'paragraph 'character)))
17814 ;; Failed conversion. Return the LaTeX fragment verbatim
17815 (add-text-properties
17816 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17817 latex-frag)))
17819 (defun org-create-formula-image (string tofile options buffer &optional type)
17820 "Create an image from LaTeX source using dvipng or convert.
17821 This function calls either `org-create-formula-image-with-dvipng'
17822 or `org-create-formula-image-with-imagemagick' depending on the
17823 value of `org-latex-create-formula-image-program' or on the value
17824 of the optional TYPE variable.
17826 Note: ultimately these two function should be combined as they
17827 share a good deal of logic."
17828 (org-check-external-command
17829 "latex" "needed to convert LaTeX fragments to images")
17830 (funcall
17831 (case (or type org-latex-create-formula-image-program)
17832 ('dvipng
17833 (org-check-external-command
17834 "dvipng" "needed to convert LaTeX fragments to images")
17835 #'org-create-formula-image-with-dvipng)
17836 ('imagemagick
17837 (org-check-external-command
17838 "convert" "you need to install imagemagick")
17839 #'org-create-formula-image-with-imagemagick)
17840 (t (error
17841 "invalid value of `org-latex-create-formula-image-program'")))
17842 string tofile options buffer))
17844 ;; This function borrows from Ganesh Swami's latex2png.el
17845 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17846 "This calls dvipng."
17847 (require 'org-latex)
17848 (let* ((tmpdir (if (featurep 'xemacs)
17849 (temp-directory)
17850 temporary-file-directory))
17851 (texfilebase (make-temp-name
17852 (expand-file-name "orgtex" tmpdir)))
17853 (texfile (concat texfilebase ".tex"))
17854 (dvifile (concat texfilebase ".dvi"))
17855 (pngfile (concat texfilebase ".png"))
17856 (fnh (if (featurep 'xemacs)
17857 (font-height (face-font 'default))
17858 (face-attribute 'default :height nil)))
17859 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17860 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17861 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17862 "Black"))
17863 (bg (or (plist-get options (if buffer :background :html-background))
17864 "Transparent")))
17865 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17866 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17867 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17868 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17869 (with-temp-file texfile
17870 (insert (org-splice-latex-header
17871 org-format-latex-header
17872 org-export-latex-default-packages-alist
17873 org-export-latex-packages-alist t
17874 org-format-latex-header-extra))
17875 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17876 (require 'org-latex)
17877 (org-export-latex-fix-inputenc))
17878 (let ((dir default-directory))
17879 (condition-case nil
17880 (progn
17881 (cd tmpdir)
17882 (call-process "latex" nil nil nil texfile))
17883 (error nil))
17884 (cd dir))
17885 (if (not (file-exists-p dvifile))
17886 (progn (message "Failed to create dvi file from %s" texfile) nil)
17887 (condition-case nil
17888 (if (featurep 'xemacs)
17889 (call-process "dvipng" nil nil nil
17890 "-fg" fg "-bg" bg
17891 "-T" "tight"
17892 "-o" pngfile
17893 dvifile)
17894 (call-process "dvipng" nil nil nil
17895 "-fg" fg "-bg" bg
17896 "-D" dpi
17897 ;;"-x" scale "-y" scale
17898 "-T" "tight"
17899 "-o" pngfile
17900 dvifile))
17901 (error nil))
17902 (if (not (file-exists-p pngfile))
17903 (if org-format-latex-signal-error
17904 (error "Failed to create png file from %s" texfile)
17905 (message "Failed to create png file from %s" texfile)
17906 nil)
17907 ;; Use the requested file name and clean up
17908 (copy-file pngfile tofile 'replace)
17909 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17910 (if (file-exists-p (concat texfilebase e))
17911 (delete-file (concat texfilebase e))))
17912 pngfile))))
17914 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17915 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17916 "This calls convert, which is included into imagemagick."
17917 (require 'org-latex)
17918 (let* ((tmpdir (if (featurep 'xemacs)
17919 (temp-directory)
17920 temporary-file-directory))
17921 (texfilebase (make-temp-name
17922 (expand-file-name "orgtex" tmpdir)))
17923 (texfile (concat texfilebase ".tex"))
17924 (pdffile (concat texfilebase ".pdf"))
17925 (pngfile (concat texfilebase ".png"))
17926 (fnh (if (featurep 'xemacs)
17927 (font-height (face-font 'default))
17928 (face-attribute 'default :height nil)))
17929 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17930 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17931 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17932 "black"))
17933 (bg (or (plist-get options (if buffer :background :html-background))
17934 "white")))
17935 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17936 (setq fg (org-latex-color-format fg)))
17937 (if (eq bg 'default) (setq bg (org-latex-color :background))
17938 (setq bg (org-latex-color-format
17939 (if (string= bg "Transparent") "white" bg))))
17940 (with-temp-file texfile
17941 (insert (org-splice-latex-header
17942 org-format-latex-header
17943 org-export-latex-default-packages-alist
17944 org-export-latex-packages-alist t
17945 org-format-latex-header-extra))
17946 (insert "\n\\begin{document}\n"
17947 "\\definecolor{fg}{rgb}{" fg "}\n"
17948 "\\definecolor{bg}{rgb}{" bg "}\n"
17949 "\n\\pagecolor{bg}\n"
17950 "\n{\\color{fg}\n"
17951 string
17952 "\n}\n"
17953 "\n\\end{document}\n" )
17954 (require 'org-latex)
17955 (org-export-latex-fix-inputenc))
17956 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17957 (condition-case nil
17958 (progn
17959 (cd tmpdir)
17960 (setq cmds org-latex-to-pdf-process)
17961 (while cmds
17962 (setq latex-frags-cmds (pop cmds))
17963 (if (listp latex-frags-cmds)
17964 (setq cmds nil)
17965 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17966 (while latex-frags-cmds
17967 (setq cmd (pop latex-frags-cmds))
17968 (while (string-match "%b" cmd)
17969 (setq cmd (replace-match
17970 (save-match-data
17971 (shell-quote-argument texfile))
17972 t t cmd)))
17973 (while (string-match "%f" cmd)
17974 (setq cmd (replace-match
17975 (save-match-data
17976 (shell-quote-argument (file-name-nondirectory texfile)))
17977 t t cmd)))
17978 (while (string-match "%o" cmd)
17979 (setq cmd (replace-match
17980 (save-match-data
17981 (shell-quote-argument (file-name-directory texfile)))
17982 t t cmd)))
17983 (setq cmd (split-string cmd))
17984 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17985 (error nil))
17986 (cd dir))
17987 (if (not (file-exists-p pdffile))
17988 (progn (message "Failed to create pdf file from %s" texfile) nil)
17989 (condition-case nil
17990 (if (featurep 'xemacs)
17991 (call-process "convert" nil nil nil
17992 "-density" "96"
17993 "-trim"
17994 "-antialias"
17995 pdffile
17996 "-quality" "100"
17997 ;; "-sharpen" "0x1.0"
17998 pngfile)
17999 (call-process "convert" nil nil nil
18000 "-density" dpi
18001 "-trim"
18002 "-antialias"
18003 pdffile
18004 "-quality" "100"
18005 ; "-sharpen" "0x1.0"
18006 pngfile))
18007 (error nil))
18008 (if (not (file-exists-p pngfile))
18009 (if org-format-latex-signal-error
18010 (error "Failed to create png file from %s" texfile)
18011 (message "Failed to create png file from %s" texfile)
18012 nil)
18013 ;; Use the requested file name and clean up
18014 (copy-file pngfile tofile 'replace)
18015 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18016 (if (file-exists-p (concat texfilebase e))
18017 (delete-file (concat texfilebase e))))
18018 pngfile))))
18020 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18021 "Fill a LaTeX header template TPL.
18022 In the template, the following place holders will be recognized:
18024 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18025 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18026 [PACKAGES] \\usepackage statements for PKG
18027 [NO-PACKAGES] do not include PKG
18028 [EXTRA] the string EXTRA
18029 [NO-EXTRA] do not include EXTRA
18031 For backward compatibility, if both the positive and the negative place
18032 holder is missing, the positive one (without the \"NO-\") will be
18033 assumed to be present at the end of the template.
18034 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18035 EXTRA is a string.
18036 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18037 (let (rpl (end ""))
18038 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18039 (setq rpl (if (or (match-end 1) (not def-pkg))
18040 "" (org-latex-packages-to-string def-pkg snippets-p t))
18041 tpl (replace-match rpl t t tpl))
18042 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18044 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18045 (setq rpl (if (or (match-end 1) (not pkg))
18046 "" (org-latex-packages-to-string pkg snippets-p t))
18047 tpl (replace-match rpl t t tpl))
18048 (if pkg (setq end
18049 (concat end "\n"
18050 (org-latex-packages-to-string pkg snippets-p)))))
18052 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18053 (setq rpl (if (or (match-end 1) (not extra))
18054 "" (concat extra "\n"))
18055 tpl (replace-match rpl t t tpl))
18056 (if (and extra (string-match "\\S-" extra))
18057 (setq end (concat end "\n" extra))))
18059 (if (string-match "\\S-" end)
18060 (concat tpl "\n" end)
18061 tpl)))
18063 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18064 "Turn an alist of packages into a string with the \\usepackage macros."
18065 (setq pkg (mapconcat (lambda(p)
18066 (cond
18067 ((stringp p) p)
18068 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18069 (format "%% Package %s omitted" (cadr p)))
18070 ((equal "" (car p))
18071 (format "\\usepackage{%s}" (cadr p)))
18073 (format "\\usepackage[%s]{%s}"
18074 (car p) (cadr p)))))
18076 "\n"))
18077 (if newline (concat pkg "\n") pkg))
18079 (defun org-dvipng-color (attr)
18080 "Return a RGB color specification for dvipng."
18081 (apply 'format "rgb %s %s %s"
18082 (mapcar 'org-normalize-color
18083 (if (featurep 'xemacs)
18084 (color-rgb-components
18085 (face-property 'default
18086 (cond ((eq attr :foreground) 'foreground)
18087 ((eq attr :background) 'background))))
18088 (color-values (face-attribute 'default attr nil))))))
18090 (defun org-dvipng-color-format (color-name)
18091 "Convert COLOR-NAME to a RGB color value for dvipng."
18092 (apply 'format "rgb %s %s %s"
18093 (mapcar 'org-normalize-color
18094 (color-values color-name))))
18096 (defun org-latex-color (attr)
18097 "Return a RGB color for the LaTeX color package."
18098 (apply 'format "%s,%s,%s"
18099 (mapcar 'org-normalize-color
18100 (if (featurep 'xemacs)
18101 (color-rgb-components
18102 (face-property 'default
18103 (cond ((eq attr :foreground) 'foreground)
18104 ((eq attr :background) 'background))))
18105 (color-values (face-attribute 'default attr nil))))))
18107 (defun org-latex-color-format (color-name)
18108 "Convert COLOR-NAME to a RGB color value."
18109 (apply 'format "%s,%s,%s"
18110 (mapcar 'org-normalize-color
18111 (color-values color-name))))
18113 (defun org-normalize-color (value)
18114 "Return string to be used as color value for an RGB component."
18115 (format "%g" (/ value 65535.0)))
18117 ;; Image display
18120 (defvar org-inline-image-overlays nil)
18121 (make-variable-buffer-local 'org-inline-image-overlays)
18123 (defun org-toggle-inline-images (&optional include-linked)
18124 "Toggle the display of inline images.
18125 INCLUDE-LINKED is passed to `org-display-inline-images'."
18126 (interactive "P")
18127 (if org-inline-image-overlays
18128 (progn
18129 (org-remove-inline-images)
18130 (message "Inline image display turned off"))
18131 (org-display-inline-images include-linked)
18132 (if (and (org-called-interactively-p)
18133 org-inline-image-overlays)
18134 (message "%d images displayed inline"
18135 (length org-inline-image-overlays))
18136 (message "No images to display inline"))))
18138 (defun org-redisplay-inline-images ()
18139 "Refresh the display of inline images."
18140 (interactive)
18141 (if (not org-inline-image-overlays)
18142 (org-toggle-inline-images)
18143 (org-toggle-inline-images)
18144 (org-toggle-inline-images)))
18146 (defun org-display-inline-images (&optional include-linked refresh beg end)
18147 "Display inline images.
18148 Normally only links without a description part are inlined, because this
18149 is how it will work for export. When INCLUDE-LINKED is set, also links
18150 with a description part will be inlined. This can be nice for a quick
18151 look at those images, but it does not reflect what exported files will look
18152 like.
18153 When REFRESH is set, refresh existing images between BEG and END.
18154 This will create new image displays only if necessary.
18155 BEG and END default to the buffer boundaries."
18156 (interactive "P")
18157 (unless refresh
18158 (org-remove-inline-images)
18159 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18160 (save-excursion
18161 (save-restriction
18162 (widen)
18163 (setq beg (or beg (point-min)) end (or end (point-max)))
18164 (goto-char beg)
18165 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18166 (substring (org-image-file-name-regexp) 0 -2)
18167 "\\)\\]" (if include-linked "" "\\]")))
18168 old file ov img type attrwidth width)
18169 (while (re-search-forward re end t)
18170 (setq old (get-char-property-and-overlay (match-beginning 1)
18171 'org-image-overlay)
18172 file (expand-file-name
18173 (concat (or (match-string 3) "") (match-string 4))))
18174 (when (image-type-available-p 'imagemagick)
18175 (setq attrwidth (if (or (listp org-image-actual-width)
18176 (null org-image-actual-width))
18177 (save-excursion
18178 (save-match-data
18179 (when (re-search-backward
18180 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18181 (save-excursion
18182 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18183 (string-to-number (match-string 1))))))
18184 width (cond ((eq org-image-actual-width t) nil)
18185 ((null org-image-actual-width) attrwidth)
18186 ((numberp org-image-actual-width)
18187 org-image-actual-width)
18188 ((listp org-image-actual-width)
18189 (or attrwidth (car org-image-actual-width))))
18190 type (if width 'imagemagick)))
18191 (when (file-exists-p file)
18192 (if (and (car-safe old) refresh)
18193 (image-refresh (overlay-get (cdr old) 'display))
18194 (setq img (save-match-data (create-image file type nil :width width)))
18195 (when img
18196 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18197 (overlay-put ov 'display img)
18198 (overlay-put ov 'face 'default)
18199 (overlay-put ov 'org-image-overlay t)
18200 (overlay-put ov 'modification-hooks
18201 (list 'org-display-inline-remove-overlay))
18202 (push ov org-inline-image-overlays)))))))))
18204 (org-define-obsolete-function-alias
18205 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18207 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18208 "Remove inline-display overlay if a corresponding region is modified."
18209 (let ((inhibit-modification-hooks t))
18210 (when (and ov after)
18211 (delete ov org-inline-image-overlays)
18212 (delete-overlay ov))))
18214 (defun org-remove-inline-images ()
18215 "Remove inline display of images."
18216 (interactive)
18217 (mapc 'delete-overlay org-inline-image-overlays)
18218 (setq org-inline-image-overlays nil))
18220 ;;;; Key bindings
18222 ;; Outline functions from `outline-mode-prefix-map'
18223 ;; that can be remapped in Org:
18224 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18225 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18226 (define-key org-mode-map [remap outline-forward-same-level]
18227 'org-forward-heading-same-level)
18228 (define-key org-mode-map [remap outline-backward-same-level]
18229 'org-backward-heading-same-level)
18230 (define-key org-mode-map [remap show-branches]
18231 'org-kill-note-or-show-branches)
18232 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18233 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18234 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18236 ;; Outline functions from `outline-mode-prefix-map' that can not
18237 ;; be remapped in Org:
18239 ;; - the column "key binding" shows whether the Outline function is still
18240 ;; available in Org mode on the same key that it has been bound to in
18241 ;; Outline mode:
18242 ;; - "overridden": key used for a different functionality in Org mode
18243 ;; - else: key still bound to the same Outline function in Org mode
18245 ;; | Outline function | key binding | Org replacement |
18246 ;; |------------------------------------+-------------+-----------------------|
18247 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18248 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18249 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18250 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18251 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18252 ;; | `show-entry' | overridden | no replacement |
18253 ;; | `show-children' | `C-c C-i' | visibility cycling |
18254 ;; | `show-branches' | `C-c C-k' | still same function |
18255 ;; | `show-subtree' | overridden | visibility cycling |
18256 ;; | `show-all' | overridden | no replacement |
18257 ;; | `hide-subtree' | overridden | visibility cycling |
18258 ;; | `hide-body' | overridden | no replacement |
18259 ;; | `hide-entry' | overridden | visibility cycling |
18260 ;; | `hide-leaves' | overridden | no replacement |
18261 ;; | `hide-sublevels' | overridden | no replacement |
18262 ;; | `hide-other' | overridden | no replacement |
18264 ;; Make `C-c C-x' a prefix key
18265 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18267 ;; TAB key with modifiers
18268 (org-defkey org-mode-map "\C-i" 'org-cycle)
18269 (org-defkey org-mode-map [(tab)] 'org-cycle)
18270 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18271 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18272 ;; The following line is necessary under Suse GNU/Linux
18273 (unless (featurep 'xemacs)
18274 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18275 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18276 (define-key org-mode-map [backtab] 'org-shifttab)
18278 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18279 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18280 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18282 ;; Cursor keys with modifiers
18283 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18284 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18285 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18286 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18288 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18289 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18290 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18291 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18293 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18294 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18295 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18296 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18298 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18299 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18300 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18301 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18303 ;; Babel keys
18304 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18305 (mapc (lambda (pair)
18306 (define-key org-babel-map (car pair) (cdr pair)))
18307 org-babel-key-bindings)
18309 ;;; Extra keys for tty access.
18310 ;; We only set them when really needed because otherwise the
18311 ;; menus don't show the simple keys
18313 (when (or org-use-extra-keys
18314 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18315 (not window-system))
18316 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18317 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18318 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18319 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18320 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18321 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18322 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18323 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18324 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18325 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18326 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18327 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18328 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18329 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18330 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18331 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18332 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18333 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18334 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18335 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18336 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18337 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18338 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18339 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18340 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18341 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18342 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18343 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18345 ;; All the other keys
18347 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18348 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18349 (if (boundp 'narrow-map)
18350 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18351 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18352 (if (boundp 'narrow-map)
18353 (org-defkey narrow-map "b" 'org-narrow-to-block)
18354 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18355 (if (boundp 'narrow-map)
18356 (org-defkey narrow-map "e" 'org-narrow-to-element)
18357 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18358 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18359 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18360 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18361 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18362 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18363 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18364 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18365 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18366 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18367 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18368 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18369 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18370 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18371 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18372 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18373 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18374 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18375 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18376 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18377 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18378 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18379 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18380 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18381 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18382 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18383 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18384 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18385 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18386 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18387 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18388 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18389 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18390 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18391 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18392 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18393 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18394 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18395 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18396 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18397 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18398 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18399 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18400 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18401 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18402 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18403 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18404 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18405 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18406 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18407 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18408 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18409 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18410 (org-defkey org-mode-map "\C-c^" 'org-sort)
18411 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18412 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18413 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18414 (org-defkey org-mode-map "\C-m" 'org-return)
18415 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18416 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18417 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18418 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18419 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18420 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18421 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18422 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18423 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18424 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18425 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18426 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18427 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18428 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18429 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18430 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18431 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18432 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18433 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18434 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18435 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18436 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18437 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18439 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18440 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18441 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18443 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18444 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18445 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18446 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18447 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18448 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18449 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18450 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18451 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18452 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18453 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18454 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18455 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18456 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18457 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18458 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18459 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18460 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18461 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18462 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18463 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18464 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18465 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18467 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18468 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18469 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18470 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18471 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18473 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18475 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18477 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18478 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18480 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18483 (when (featurep 'xemacs)
18484 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18487 (defconst org-speed-commands-default
18489 ("Outline Navigation")
18490 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18491 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18492 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18493 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18494 ("u" . (org-speed-move-safe 'outline-up-heading))
18495 ("j" . org-goto)
18496 ("g" . (org-refile t))
18497 ("Outline Visibility")
18498 ("c" . org-cycle)
18499 ("C" . org-shifttab)
18500 (" " . org-display-outline-path)
18501 ("=" . org-columns)
18502 ("Outline Structure Editing")
18503 ("U" . org-shiftmetaup)
18504 ("D" . org-shiftmetadown)
18505 ("r" . org-metaright)
18506 ("l" . org-metaleft)
18507 ("R" . org-shiftmetaright)
18508 ("L" . org-shiftmetaleft)
18509 ("i" . (progn (forward-char 1) (call-interactively
18510 'org-insert-heading-respect-content)))
18511 ("^" . org-sort)
18512 ("w" . org-refile)
18513 ("a" . org-archive-subtree-default-with-confirmation)
18514 ("." . org-mark-subtree)
18515 ("#" . org-toggle-comment)
18516 ("Clock Commands")
18517 ("I" . org-clock-in)
18518 ("O" . org-clock-out)
18519 ("Meta Data Editing")
18520 ("t" . org-todo)
18521 ("," . (org-priority))
18522 ("0" . (org-priority ?\ ))
18523 ("1" . (org-priority ?A))
18524 ("2" . (org-priority ?B))
18525 ("3" . (org-priority ?C))
18526 (":" . org-set-tags-command)
18527 ("e" . org-set-effort)
18528 ("E" . org-inc-effort)
18529 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18530 (org-entry-put (point) "APPT_WARNTIME" m)))
18531 ("Agenda Views etc")
18532 ("v" . org-agenda)
18533 ("/" . org-sparse-tree)
18534 ("Misc")
18535 ("o" . org-open-at-point)
18536 ("?" . org-speed-command-help)
18537 ("<" . (org-agenda-set-restriction-lock 'subtree))
18538 (">" . (org-agenda-remove-restriction-lock))
18540 "The default speed commands.")
18542 (defun org-print-speed-command (e)
18543 (if (> (length (car e)) 1)
18544 (progn
18545 (princ "\n")
18546 (princ (car e))
18547 (princ "\n")
18548 (princ (make-string (length (car e)) ?-))
18549 (princ "\n"))
18550 (princ (car e))
18551 (princ " ")
18552 (if (symbolp (cdr e))
18553 (princ (symbol-name (cdr e)))
18554 (prin1 (cdr e)))
18555 (princ "\n")))
18557 (defun org-speed-command-help ()
18558 "Show the available speed commands."
18559 (interactive)
18560 (if (not org-use-speed-commands)
18561 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18562 (with-output-to-temp-buffer "*Help*"
18563 (princ "User-defined Speed commands\n===========================\n")
18564 (mapc 'org-print-speed-command org-speed-commands-user)
18565 (princ "\n")
18566 (princ "Built-in Speed commands\n=======================\n")
18567 (mapc 'org-print-speed-command org-speed-commands-default))
18568 (with-current-buffer "*Help*"
18569 (setq truncate-lines t))))
18571 (defun org-speed-move-safe (cmd)
18572 "Execute CMD, but make sure that the cursor always ends up in a headline.
18573 If not, return to the original position and throw an error."
18574 (interactive)
18575 (let ((pos (point)))
18576 (call-interactively cmd)
18577 (unless (and (bolp) (org-at-heading-p))
18578 (goto-char pos)
18579 (error "Boundary reached while executing %s" cmd))))
18581 (defvar org-self-insert-command-undo-counter 0)
18583 (defvar org-table-auto-blank-field) ; defined in org-table.el
18584 (defvar org-speed-command nil)
18586 (org-define-obsolete-function-alias
18587 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18589 (defun org-speed-command-activate (keys)
18590 "Hook for activating single-letter speed commands.
18591 `org-speed-commands-default' specifies a minimal command set.
18592 Use `org-speed-commands-user' for further customization."
18593 (when (or (and (bolp) (looking-at org-outline-regexp))
18594 (and (functionp org-use-speed-commands)
18595 (funcall org-use-speed-commands)))
18596 (cdr (assoc keys (append org-speed-commands-user
18597 org-speed-commands-default)))))
18599 (org-define-obsolete-function-alias
18600 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18602 (defun org-babel-speed-command-activate (keys)
18603 "Hook for activating single-letter code block commands."
18604 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18605 (cdr (assoc keys org-babel-key-bindings))))
18607 (defcustom org-speed-command-hook
18608 '(org-speed-command-default-hook org-babel-speed-command-hook)
18609 "Hook for activating speed commands at strategic locations.
18610 Hook functions are called in sequence until a valid handler is
18611 found.
18613 Each hook takes a single argument, a user-pressed command key
18614 which is also a `self-insert-command' from the global map.
18616 Within the hook, examine the cursor position and the command key
18617 and return nil or a valid handler as appropriate. Handler could
18618 be one of an interactive command, a function, or a form.
18620 Set `org-use-speed-commands' to non-nil value to enable this
18621 hook. The default setting is `org-speed-command-activate'."
18622 :group 'org-structure
18623 :version "24.1"
18624 :type 'hook)
18626 (defun org-self-insert-command (N)
18627 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18628 If the cursor is in a table looking at whitespace, the whitespace is
18629 overwritten, and the table is not marked as requiring realignment."
18630 (interactive "p")
18631 (org-check-before-invisible-edit 'insert)
18632 (cond
18633 ((and org-use-speed-commands
18634 (setq org-speed-command
18635 (run-hook-with-args-until-success
18636 'org-speed-command-hook (this-command-keys))))
18637 (cond
18638 ((commandp org-speed-command)
18639 (setq this-command org-speed-command)
18640 (call-interactively org-speed-command))
18641 ((functionp org-speed-command)
18642 (funcall org-speed-command))
18643 ((and org-speed-command (listp org-speed-command))
18644 (eval org-speed-command))
18645 (t (let (org-use-speed-commands)
18646 (call-interactively 'org-self-insert-command)))))
18647 ((and
18648 (org-table-p)
18649 (progn
18650 ;; check if we blank the field, and if that triggers align
18651 (and (featurep 'org-table) org-table-auto-blank-field
18652 (member last-command
18653 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18654 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18655 ;; got extra space, this field does not determine column width
18656 (let (org-table-may-need-update) (org-table-blank-field))
18657 ;; no extra space, this field may determine column width
18658 (org-table-blank-field)))
18660 (eq N 1)
18661 (looking-at "[^|\n]* |"))
18662 (let (org-table-may-need-update)
18663 (goto-char (1- (match-end 0)))
18664 (backward-delete-char 1)
18665 (goto-char (match-beginning 0))
18666 (self-insert-command N)))
18668 (setq org-table-may-need-update t)
18669 (self-insert-command N)
18670 (org-fix-tags-on-the-fly)
18671 (if org-self-insert-cluster-for-undo
18672 (if (not (eq last-command 'org-self-insert-command))
18673 (setq org-self-insert-command-undo-counter 1)
18674 (if (>= org-self-insert-command-undo-counter 20)
18675 (setq org-self-insert-command-undo-counter 1)
18676 (and (> org-self-insert-command-undo-counter 0)
18677 buffer-undo-list (listp buffer-undo-list)
18678 (not (cadr buffer-undo-list)) ; remove nil entry
18679 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18680 (setq org-self-insert-command-undo-counter
18681 (1+ org-self-insert-command-undo-counter))))))))
18683 (defun org-check-before-invisible-edit (kind)
18684 "Check is editing if kind KIND would be dangerous with invisible text around.
18685 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18686 ;; First, try to get out of here as quickly as possible, to reduce overhead
18687 (if (and org-catch-invisible-edits
18688 (or (not (boundp 'visible-mode)) (not visible-mode))
18689 (or (get-char-property (point) 'invisible)
18690 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18691 ;; OK, we need to take a closer look
18692 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18693 (invisible-before-point (if (bobp) nil (get-char-property
18694 (1- (point)) 'invisible)))
18695 (border-and-ok-direction
18697 ;; Check if we are acting predictably before invisible text
18698 (and invisible-at-point (not invisible-before-point)
18699 (memq kind '(insert delete-backward)))
18700 ;; Check if we are acting predictably after invisible text
18701 ;; This works not well, and I have turned it off. It seems
18702 ;; better to always show and stop after invisible text.
18703 ;; (and (not invisible-at-point) invisible-before-point
18704 ;; (memq kind '(insert delete)))
18706 (when (or (memq invisible-at-point '(outline org-hide-block t))
18707 (memq invisible-before-point '(outline org-hide-block t)))
18708 (if (eq org-catch-invisible-edits 'error)
18709 (error "Editing in invisible areas is prohibited - make visible first"))
18710 (if (and org-custom-properties-overlays
18711 (y-or-n-p "Display invisible properties in this buffer? "))
18712 (org-toggle-custom-properties-visibility)
18713 ;; Make the area visible
18714 (save-excursion
18715 (if invisible-before-point
18716 (goto-char (previous-single-char-property-change
18717 (point) 'invisible)))
18718 (org-cycle))
18719 (cond
18720 ((eq org-catch-invisible-edits 'show)
18721 ;; That's it, we do the edit after showing
18722 (message
18723 "Unfolding invisible region around point before editing")
18724 (sit-for 1))
18725 ((and (eq org-catch-invisible-edits 'smart)
18726 border-and-ok-direction)
18727 (message "Unfolding invisible region around point before editing"))
18729 ;; Don't do the edit, make the user repeat it in full visibility
18730 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18732 (defun org-fix-tags-on-the-fly ()
18733 (when (and (equal (char-after (point-at-bol)) ?*)
18734 (org-at-heading-p))
18735 (org-align-tags-here org-tags-column)))
18737 (defun org-delete-backward-char (N)
18738 "Like `delete-backward-char', insert whitespace at field end in tables.
18739 When deleting backwards, in tables this function will insert whitespace in
18740 front of the next \"|\" separator, to keep the table aligned. The table will
18741 still be marked for re-alignment if the field did fill the entire column,
18742 because, in this case the deletion might narrow the column."
18743 (interactive "p")
18744 (save-match-data
18745 (org-check-before-invisible-edit 'delete-backward)
18746 (if (and (org-table-p)
18747 (eq N 1)
18748 (string-match "|" (buffer-substring (point-at-bol) (point)))
18749 (looking-at ".*?|"))
18750 (let ((pos (point))
18751 (noalign (looking-at "[^|\n\r]* |"))
18752 (c org-table-may-need-update))
18753 (backward-delete-char N)
18754 (if (not overwrite-mode)
18755 (progn
18756 (skip-chars-forward "^|")
18757 (insert " ")
18758 (goto-char (1- pos))))
18759 ;; noalign: if there were two spaces at the end, this field
18760 ;; does not determine the width of the column.
18761 (if noalign (setq org-table-may-need-update c)))
18762 (backward-delete-char N)
18763 (org-fix-tags-on-the-fly))))
18765 (defun org-delete-char (N)
18766 "Like `delete-char', but insert whitespace at field end in tables.
18767 When deleting characters, in tables this function will insert whitespace in
18768 front of the next \"|\" separator, to keep the table aligned. The table will
18769 still be marked for re-alignment if the field did fill the entire column,
18770 because, in this case the deletion might narrow the column."
18771 (interactive "p")
18772 (save-match-data
18773 (org-check-before-invisible-edit 'delete)
18774 (if (and (org-table-p)
18775 (not (bolp))
18776 (not (= (char-after) ?|))
18777 (eq N 1))
18778 (if (looking-at ".*?|")
18779 (let ((pos (point))
18780 (noalign (looking-at "[^|\n\r]* |"))
18781 (c org-table-may-need-update))
18782 (replace-match (concat
18783 (substring (match-string 0) 1 -1)
18784 " |"))
18785 (goto-char pos)
18786 ;; noalign: if there were two spaces at the end, this field
18787 ;; does not determine the width of the column.
18788 (if noalign (setq org-table-may-need-update c)))
18789 (delete-char N))
18790 (delete-char N)
18791 (org-fix-tags-on-the-fly))))
18793 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18794 (put 'org-self-insert-command 'delete-selection t)
18795 (put 'orgtbl-self-insert-command 'delete-selection t)
18796 (put 'org-delete-char 'delete-selection 'supersede)
18797 (put 'org-delete-backward-char 'delete-selection 'supersede)
18798 (put 'org-yank 'delete-selection 'yank)
18800 ;; Make `flyspell-mode' delay after some commands
18801 (put 'org-self-insert-command 'flyspell-delayed t)
18802 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18803 (put 'org-delete-char 'flyspell-delayed t)
18804 (put 'org-delete-backward-char 'flyspell-delayed t)
18806 ;; Make pabbrev-mode expand after org-mode commands
18807 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18808 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18810 ;; How to do this: Measure non-white length of current string
18811 ;; If equal to column width, we should realign.
18813 (defun org-remap (map &rest commands)
18814 "In MAP, remap the functions given in COMMANDS.
18815 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18816 (let (new old)
18817 (while commands
18818 (setq old (pop commands) new (pop commands))
18819 (if (fboundp 'command-remapping)
18820 (org-defkey map (vector 'remap old) new)
18821 (substitute-key-definition old new map global-map)))))
18823 (when (eq org-enable-table-editor 'optimized)
18824 ;; If the user wants maximum table support, we need to hijack
18825 ;; some standard editing functions
18826 (org-remap org-mode-map
18827 'self-insert-command 'org-self-insert-command
18828 'delete-char 'org-delete-char
18829 'delete-backward-char 'org-delete-backward-char)
18830 (org-defkey org-mode-map "|" 'org-force-self-insert))
18832 (defvar org-ctrl-c-ctrl-c-hook nil
18833 "Hook for functions attaching themselves to `C-c C-c'.
18835 This can be used to add additional functionality to the C-c C-c
18836 key which executes context-dependent commands. This hook is run
18837 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18838 run after the last test.
18840 Each function will be called with no arguments. The function
18841 must check if the context is appropriate for it to act. If yes,
18842 it should do its thing and then return a non-nil value. If the
18843 context is wrong, just do nothing and return nil.")
18845 (defvar org-ctrl-c-ctrl-c-final-hook nil
18846 "Hook for functions attaching themselves to `C-c C-c'.
18848 This can be used to add additional functionality to the C-c C-c
18849 key which executes context-dependent commands. This hook is run
18850 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18851 before the first test.
18853 Each function will be called with no arguments. The function
18854 must check if the context is appropriate for it to act. If yes,
18855 it should do its thing and then return a non-nil value. If the
18856 context is wrong, just do nothing and return nil.")
18858 (defvar org-tab-first-hook nil
18859 "Hook for functions to attach themselves to TAB.
18860 See `org-ctrl-c-ctrl-c-hook' for more information.
18861 This hook runs as the first action when TAB is pressed, even before
18862 `org-cycle' messes around with the `outline-regexp' to cater for
18863 inline tasks and plain list item folding.
18864 If any function in this hook returns t, any other actions that
18865 would have been caused by TAB (such as table field motion or visibility
18866 cycling) will not occur.")
18868 (defvar org-tab-after-check-for-table-hook nil
18869 "Hook for functions to attach themselves to TAB.
18870 See `org-ctrl-c-ctrl-c-hook' for more information.
18871 This hook runs after it has been established that the cursor is not in a
18872 table, but before checking if the cursor is in a headline or if global cycling
18873 should be done.
18874 If any function in this hook returns t, not other actions like visibility
18875 cycling will be done.")
18877 (defvar org-tab-after-check-for-cycling-hook nil
18878 "Hook for functions to attach themselves to TAB.
18879 See `org-ctrl-c-ctrl-c-hook' for more information.
18880 This hook runs after it has been established that not table field motion and
18881 not visibility should be done because of current context. This is probably
18882 the place where a package like yasnippets can hook in.")
18884 (defvar org-tab-before-tab-emulation-hook nil
18885 "Hook for functions to attach themselves to TAB.
18886 See `org-ctrl-c-ctrl-c-hook' for more information.
18887 This hook runs after every other options for TAB have been exhausted, but
18888 before indentation and \t insertion takes place.")
18890 (defvar org-metaleft-hook nil
18891 "Hook for functions attaching themselves to `M-left'.
18892 See `org-ctrl-c-ctrl-c-hook' for more information.")
18893 (defvar org-metaright-hook nil
18894 "Hook for functions attaching themselves to `M-right'.
18895 See `org-ctrl-c-ctrl-c-hook' for more information.")
18896 (defvar org-metaup-hook nil
18897 "Hook for functions attaching themselves to `M-up'.
18898 See `org-ctrl-c-ctrl-c-hook' for more information.")
18899 (defvar org-metadown-hook nil
18900 "Hook for functions attaching themselves to `M-down'.
18901 See `org-ctrl-c-ctrl-c-hook' for more information.")
18902 (defvar org-shiftmetaleft-hook nil
18903 "Hook for functions attaching themselves to `M-S-left'.
18904 See `org-ctrl-c-ctrl-c-hook' for more information.")
18905 (defvar org-shiftmetaright-hook nil
18906 "Hook for functions attaching themselves to `M-S-right'.
18907 See `org-ctrl-c-ctrl-c-hook' for more information.")
18908 (defvar org-shiftmetaup-hook nil
18909 "Hook for functions attaching themselves to `M-S-up'.
18910 See `org-ctrl-c-ctrl-c-hook' for more information.")
18911 (defvar org-shiftmetadown-hook nil
18912 "Hook for functions attaching themselves to `M-S-down'.
18913 See `org-ctrl-c-ctrl-c-hook' for more information.")
18914 (defvar org-metareturn-hook nil
18915 "Hook for functions attaching themselves to `M-RET'.
18916 See `org-ctrl-c-ctrl-c-hook' for more information.")
18917 (defvar org-shiftup-hook nil
18918 "Hook for functions attaching themselves to `S-up'.
18919 See `org-ctrl-c-ctrl-c-hook' for more information.")
18920 (defvar org-shiftup-final-hook nil
18921 "Hook for functions attaching themselves to `S-up'.
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.")
18924 (defvar org-shiftdown-hook nil
18925 "Hook for functions attaching themselves to `S-down'.
18926 See `org-ctrl-c-ctrl-c-hook' for more information.")
18927 (defvar org-shiftdown-final-hook nil
18928 "Hook for functions attaching themselves to `S-down'.
18929 This one runs after all other options except shift-select have been excluded.
18930 See `org-ctrl-c-ctrl-c-hook' for more information.")
18931 (defvar org-shiftleft-hook nil
18932 "Hook for functions attaching themselves to `S-left'.
18933 See `org-ctrl-c-ctrl-c-hook' for more information.")
18934 (defvar org-shiftleft-final-hook nil
18935 "Hook for functions attaching themselves to `S-left'.
18936 This one runs after all other options except shift-select have been excluded.
18937 See `org-ctrl-c-ctrl-c-hook' for more information.")
18938 (defvar org-shiftright-hook nil
18939 "Hook for functions attaching themselves to `S-right'.
18940 See `org-ctrl-c-ctrl-c-hook' for more information.")
18941 (defvar org-shiftright-final-hook nil
18942 "Hook for functions attaching themselves to `S-right'.
18943 This one runs after all other options except shift-select have been excluded.
18944 See `org-ctrl-c-ctrl-c-hook' for more information.")
18946 (defun org-modifier-cursor-error ()
18947 "Throw an error, a modified cursor command was applied in wrong context."
18948 (error "This command is active in special context like tables, headlines or items"))
18950 (defun org-shiftselect-error ()
18951 "Throw an error because Shift-Cursor command was applied in wrong context."
18952 (if (and (boundp 'shift-select-mode) shift-select-mode)
18953 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18954 (error "This command works only in special context like headlines or timestamps")))
18956 (defun org-call-for-shift-select (cmd)
18957 (let ((this-command-keys-shift-translated t))
18958 (call-interactively cmd)))
18960 (defun org-shifttab (&optional arg)
18961 "Global visibility cycling or move to previous table field.
18962 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18963 on context.
18964 See the individual commands for more information."
18965 (interactive "P")
18966 (cond
18967 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18968 ((integerp arg)
18969 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18970 (message "Content view to level: %d" arg)
18971 (org-content (prefix-numeric-value arg2))
18972 (setq org-cycle-global-status 'overview)))
18973 (t (call-interactively 'org-global-cycle))))
18975 (defun org-shiftmetaleft ()
18976 "Promote subtree or delete table column.
18977 Calls `org-promote-subtree', `org-outdent-item-tree', or
18978 `org-table-delete-column', depending on context. See the
18979 individual commands for more information."
18980 (interactive)
18981 (cond
18982 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18983 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18984 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18985 ((if (not (org-region-active-p)) (org-at-item-p)
18986 (save-excursion (goto-char (region-beginning))
18987 (org-at-item-p)))
18988 (call-interactively 'org-outdent-item-tree))
18989 (t (org-modifier-cursor-error))))
18991 (defun org-shiftmetaright ()
18992 "Demote subtree or insert table column.
18993 Calls `org-demote-subtree', `org-indent-item-tree', or
18994 `org-table-insert-column', depending on context. See the
18995 individual commands for more information."
18996 (interactive)
18997 (cond
18998 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18999 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19000 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19001 ((if (not (org-region-active-p)) (org-at-item-p)
19002 (save-excursion (goto-char (region-beginning))
19003 (org-at-item-p)))
19004 (call-interactively 'org-indent-item-tree))
19005 (t (org-modifier-cursor-error))))
19007 (defun org-shiftmetaup (&optional arg)
19008 "Move subtree up or kill table row.
19009 Calls `org-move-subtree-up' or `org-table-kill-row' or
19010 `org-move-item-up' or `org-timestamp-up', depending on context.
19011 See the individual commands for more information."
19012 (interactive "P")
19013 (cond
19014 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19015 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19016 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19017 ((org-at-item-p) (call-interactively 'org-move-item-up))
19018 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19019 (call-interactively 'org-timestamp-up)))
19020 (t (org-modifier-cursor-error))))
19022 (defun org-shiftmetadown (&optional arg)
19023 "Move subtree down or insert table row.
19024 Calls `org-move-subtree-down' or `org-table-insert-row' or
19025 `org-move-item-down' or `org-timestamp-up', depending on context.
19026 See the individual commands for more information."
19027 (interactive "P")
19028 (cond
19029 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19030 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19031 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19032 ((org-at-item-p) (call-interactively 'org-move-item-down))
19033 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19034 (call-interactively 'org-timestamp-down)))
19035 (t (org-modifier-cursor-error))))
19037 (defsubst org-hidden-tree-error ()
19038 (error
19039 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19041 (defun org-metaleft (&optional arg)
19042 "Promote heading or move table column to left.
19043 Calls `org-do-promote' or `org-table-move-column', depending on context.
19044 With no specific context, calls the Emacs default `backward-word'.
19045 See the individual commands for more information."
19046 (interactive "P")
19047 (cond
19048 ((run-hook-with-args-until-success 'org-metaleft-hook))
19049 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19050 ((org-with-limited-levels
19051 (or (org-at-heading-p)
19052 (and (org-region-active-p)
19053 (save-excursion
19054 (goto-char (region-beginning))
19055 (org-at-heading-p)))))
19056 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19057 (call-interactively 'org-do-promote))
19058 ;; At an inline task.
19059 ((org-at-heading-p)
19060 (call-interactively 'org-inlinetask-promote))
19061 ((or (org-at-item-p)
19062 (and (org-region-active-p)
19063 (save-excursion
19064 (goto-char (region-beginning))
19065 (org-at-item-p))))
19066 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19067 (call-interactively 'org-outdent-item))
19068 (t (call-interactively 'backward-word))))
19070 (defun org-metaright (&optional arg)
19071 "Demote a subtree, a list item or move table column to right.
19072 In front of a drawer or a block keyword, indent it correctly.
19073 With no specific context, calls the Emacs default `forward-word'.
19074 See the individual commands for more information."
19075 (interactive "P")
19076 (cond
19077 ((run-hook-with-args-until-success 'org-metaright-hook))
19078 ((org-at-table-p) (call-interactively 'org-table-move-column))
19079 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19080 ((org-at-block-p) (call-interactively 'org-indent-block))
19081 ((org-with-limited-levels
19082 (or (org-at-heading-p)
19083 (and (org-region-active-p)
19084 (save-excursion
19085 (goto-char (region-beginning))
19086 (org-at-heading-p)))))
19087 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19088 (call-interactively 'org-do-demote))
19089 ;; At an inline task.
19090 ((org-at-heading-p)
19091 (call-interactively 'org-inlinetask-demote))
19092 ((or (org-at-item-p)
19093 (and (org-region-active-p)
19094 (save-excursion
19095 (goto-char (region-beginning))
19096 (org-at-item-p))))
19097 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19098 (call-interactively 'org-indent-item))
19099 (t (call-interactively 'forward-word))))
19101 (defun org-check-for-hidden (what)
19102 "Check if there are hidden headlines/items in the current visual line.
19103 WHAT can be either `headlines' or `items'. If the current line is
19104 an outline or item heading and it has a folded subtree below it,
19105 this function returns t, nil otherwise."
19106 (let ((re (cond
19107 ((eq what 'headlines) org-outline-regexp-bol)
19108 ((eq what 'items) (org-item-beginning-re))
19109 (t (error "This should not happen"))))
19110 beg end)
19111 (save-excursion
19112 (catch 'exit
19113 (unless (org-region-active-p)
19114 (setq beg (point-at-bol))
19115 (beginning-of-line 2)
19116 (while (and (not (eobp)) ;; this is like `next-line'
19117 (get-char-property (1- (point)) 'invisible))
19118 (beginning-of-line 2))
19119 (setq end (point))
19120 (goto-char beg)
19121 (goto-char (point-at-eol))
19122 (setq end (max end (point)))
19123 (while (re-search-forward re end t)
19124 (if (get-char-property (match-beginning 0) 'invisible)
19125 (throw 'exit t))))
19126 nil))))
19128 (defun org-metaup (&optional arg)
19129 "Move subtree up or move table row up.
19130 Calls `org-move-subtree-up' or `org-table-move-row' or
19131 `org-move-item-up', depending on context. See the individual commands
19132 for more information."
19133 (interactive "P")
19134 (cond
19135 ((run-hook-with-args-until-success 'org-metaup-hook))
19136 ((org-region-active-p)
19137 (let* ((a (min (region-beginning) (region-end)))
19138 (b (1- (max (region-beginning) (region-end))))
19139 (c (save-excursion (goto-char a)
19140 (move-beginning-of-line 0)))
19141 (d (save-excursion (goto-char a)
19142 (move-end-of-line 0) (point))))
19143 (transpose-regions a b c d)
19144 (goto-char c)))
19145 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19146 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19147 ((org-at-item-p) (call-interactively 'org-move-item-up))
19148 (t (org-drag-element-backward))))
19150 (defun org-metadown (&optional arg)
19151 "Move subtree down or move table row down.
19152 Calls `org-move-subtree-down' or `org-table-move-row' or
19153 `org-move-item-down', depending on context. See the individual
19154 commands for more information."
19155 (interactive "P")
19156 (cond
19157 ((run-hook-with-args-until-success 'org-metadown-hook))
19158 ((org-region-active-p)
19159 (let* ((a (min (region-beginning) (region-end)))
19160 (b (max (region-beginning) (region-end)))
19161 (c (save-excursion (goto-char b)
19162 (move-beginning-of-line 1)))
19163 (d (save-excursion (goto-char b)
19164 (move-end-of-line 1) (1+ (point)))))
19165 (transpose-regions a b c d)
19166 (goto-char d)))
19167 ((org-at-table-p) (call-interactively 'org-table-move-row))
19168 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19169 ((org-at-item-p) (call-interactively 'org-move-item-down))
19170 (t (org-drag-element-forward))))
19172 (defun org-shiftup (&optional arg)
19173 "Increase item in timestamp or increase priority of current headline.
19174 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19175 depending on context. See the individual commands for more information."
19176 (interactive "P")
19177 (cond
19178 ((run-hook-with-args-until-success 'org-shiftup-hook))
19179 ((and org-support-shift-select (org-region-active-p))
19180 (org-call-for-shift-select 'previous-line))
19181 ((org-at-timestamp-p t)
19182 (call-interactively (if org-edit-timestamp-down-means-later
19183 'org-timestamp-down 'org-timestamp-up)))
19184 ((and (not (eq org-support-shift-select 'always))
19185 org-enable-priority-commands
19186 (org-at-heading-p))
19187 (call-interactively 'org-priority-up))
19188 ((and (not org-support-shift-select) (org-at-item-p))
19189 (call-interactively 'org-previous-item))
19190 ((org-clocktable-try-shift 'up arg))
19191 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19192 (org-support-shift-select
19193 (org-call-for-shift-select 'previous-line))
19194 (t (org-shiftselect-error))))
19196 (defun org-shiftdown (&optional arg)
19197 "Decrease item in timestamp or decrease priority of current headline.
19198 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19199 depending on context. See the individual commands for more information."
19200 (interactive "P")
19201 (cond
19202 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19203 ((and org-support-shift-select (org-region-active-p))
19204 (org-call-for-shift-select 'next-line))
19205 ((org-at-timestamp-p t)
19206 (call-interactively (if org-edit-timestamp-down-means-later
19207 'org-timestamp-up 'org-timestamp-down)))
19208 ((and (not (eq org-support-shift-select 'always))
19209 org-enable-priority-commands
19210 (org-at-heading-p))
19211 (call-interactively 'org-priority-down))
19212 ((and (not org-support-shift-select) (org-at-item-p))
19213 (call-interactively 'org-next-item))
19214 ((org-clocktable-try-shift 'down arg))
19215 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19216 (org-support-shift-select
19217 (org-call-for-shift-select 'next-line))
19218 (t (org-shiftselect-error))))
19220 (defun org-shiftright (&optional arg)
19221 "Cycle the thing at point or in the current line, depending on context.
19222 Depending on context, this does one of the following:
19224 - switch a timestamp at point one day into the future
19225 - on a headline, switch to the next TODO keyword.
19226 - on an item, switch entire list to the next bullet type
19227 - on a property line, switch to the next allowed value
19228 - on a clocktable definition line, move time block into the future"
19229 (interactive "P")
19230 (cond
19231 ((run-hook-with-args-until-success 'org-shiftright-hook))
19232 ((and org-support-shift-select (org-region-active-p))
19233 (org-call-for-shift-select 'forward-char))
19234 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19235 ((and (not (eq org-support-shift-select 'always))
19236 (org-at-heading-p))
19237 (let ((org-inhibit-logging
19238 (not org-treat-S-cursor-todo-selection-as-state-change))
19239 (org-inhibit-blocking
19240 (not org-treat-S-cursor-todo-selection-as-state-change)))
19241 (org-call-with-arg 'org-todo 'right)))
19242 ((or (and org-support-shift-select
19243 (not (eq org-support-shift-select 'always))
19244 (org-at-item-bullet-p))
19245 (and (not org-support-shift-select) (org-at-item-p)))
19246 (org-call-with-arg 'org-cycle-list-bullet nil))
19247 ((and (not (eq org-support-shift-select 'always))
19248 (org-at-property-p))
19249 (call-interactively 'org-property-next-allowed-value))
19250 ((org-clocktable-try-shift 'right arg))
19251 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19252 (org-support-shift-select
19253 (org-call-for-shift-select 'forward-char))
19254 (t (org-shiftselect-error))))
19256 (defun org-shiftleft (&optional arg)
19257 "Cycle the thing at point or in the current line, depending on context.
19258 Depending on context, this does one of the following:
19260 - switch a timestamp at point one day into the past
19261 - on a headline, switch to the previous TODO keyword.
19262 - on an item, switch entire list to the previous bullet type
19263 - on a property line, switch to the previous allowed value
19264 - on a clocktable definition line, move time block into the past"
19265 (interactive "P")
19266 (cond
19267 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19268 ((and org-support-shift-select (org-region-active-p))
19269 (org-call-for-shift-select 'backward-char))
19270 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19271 ((and (not (eq org-support-shift-select 'always))
19272 (org-at-heading-p))
19273 (let ((org-inhibit-logging
19274 (not org-treat-S-cursor-todo-selection-as-state-change))
19275 (org-inhibit-blocking
19276 (not org-treat-S-cursor-todo-selection-as-state-change)))
19277 (org-call-with-arg 'org-todo 'left)))
19278 ((or (and org-support-shift-select
19279 (not (eq org-support-shift-select 'always))
19280 (org-at-item-bullet-p))
19281 (and (not org-support-shift-select) (org-at-item-p)))
19282 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19283 ((and (not (eq org-support-shift-select 'always))
19284 (org-at-property-p))
19285 (call-interactively 'org-property-previous-allowed-value))
19286 ((org-clocktable-try-shift 'left arg))
19287 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19288 (org-support-shift-select
19289 (org-call-for-shift-select 'backward-char))
19290 (t (org-shiftselect-error))))
19292 (defun org-shiftcontrolright ()
19293 "Switch to next TODO set."
19294 (interactive)
19295 (cond
19296 ((and org-support-shift-select (org-region-active-p))
19297 (org-call-for-shift-select 'forward-word))
19298 ((and (not (eq org-support-shift-select 'always))
19299 (org-at-heading-p))
19300 (org-call-with-arg 'org-todo 'nextset))
19301 (org-support-shift-select
19302 (org-call-for-shift-select 'forward-word))
19303 (t (org-shiftselect-error))))
19305 (defun org-shiftcontrolleft ()
19306 "Switch to previous TODO set."
19307 (interactive)
19308 (cond
19309 ((and org-support-shift-select (org-region-active-p))
19310 (org-call-for-shift-select 'backward-word))
19311 ((and (not (eq org-support-shift-select 'always))
19312 (org-at-heading-p))
19313 (org-call-with-arg 'org-todo 'previousset))
19314 (org-support-shift-select
19315 (org-call-for-shift-select 'backward-word))
19316 (t (org-shiftselect-error))))
19318 (defun org-shiftcontrolup (&optional n)
19319 "Change timestamps synchronously up in CLOCK log lines.
19320 Optional argument N tells to change by that many units."
19321 (interactive "P")
19322 (cond ((and (not org-support-shift-select)
19323 (org-at-clock-log-p)
19324 (org-at-timestamp-p t))
19325 (org-clock-timestamps-up n))
19326 (t (org-shiftselect-error))))
19328 (defun org-shiftcontroldown (&optional n)
19329 "Change timestamps synchronously down in CLOCK log lines.
19330 Optional argument N tells to change by that many units."
19331 (interactive "P")
19332 (cond ((and (not org-support-shift-select)
19333 (org-at-clock-log-p)
19334 (org-at-timestamp-p t))
19335 (org-clock-timestamps-down n))
19336 (t (org-shiftselect-error))))
19338 (defun org-ctrl-c-ret ()
19339 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19340 (interactive)
19341 (cond
19342 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19343 (t (call-interactively 'org-insert-heading))))
19345 (defun org-find-visible ()
19346 (let ((s (point)))
19347 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19348 (get-char-property s 'invisible)))
19350 (defun org-find-invisible ()
19351 (let ((s (point)))
19352 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19353 (not (get-char-property s 'invisible))))
19356 (defun org-copy-visible (beg end)
19357 "Copy the visible parts of the region."
19358 (interactive "r")
19359 (let (snippets s)
19360 (save-excursion
19361 (save-restriction
19362 (narrow-to-region beg end)
19363 (setq s (goto-char (point-min)))
19364 (while (not (= (point) (point-max)))
19365 (goto-char (org-find-invisible))
19366 (push (buffer-substring s (point)) snippets)
19367 (setq s (goto-char (org-find-visible))))))
19368 (kill-new (apply 'concat (nreverse snippets)))))
19370 (defun org-copy-special ()
19371 "Copy region in table or copy current subtree.
19372 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19373 See the individual commands for more information."
19374 (interactive)
19375 (call-interactively
19376 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19378 (defun org-cut-special ()
19379 "Cut region in table or cut current subtree.
19380 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19381 See the individual commands for more information."
19382 (interactive)
19383 (call-interactively
19384 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19386 (defun org-paste-special (arg)
19387 "Paste rectangular region into table, or past subtree relative to level.
19388 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19389 See the individual commands for more information."
19390 (interactive "P")
19391 (if (org-at-table-p)
19392 (org-table-paste-rectangle)
19393 (org-paste-subtree arg)))
19395 (defsubst org-in-fixed-width-region-p ()
19396 "Is point in a fixed-width region?"
19397 (save-match-data
19398 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19400 (defun org-edit-special (&optional arg)
19401 "Call a special editor for the stuff at point.
19402 When at a table, call the formula editor with `org-table-edit-formulas'.
19403 When in a source code block, call `org-edit-src-code'.
19404 When in a fixed-width region, call `org-edit-fixed-width-region'.
19405 When in an #+include line, visit the included file.
19406 On a link, call `ffap' to visit the link at point.
19407 Otherwise, return a user error."
19408 (interactive)
19409 ;; possibly prep session before editing source
19410 (when (and (org-in-src-block-p) arg)
19411 (let* ((info (org-babel-get-src-block-info))
19412 (lang (nth 0 info))
19413 (params (nth 2 info))
19414 (session (cdr (assoc :session params))))
19415 (when (and info session) ;; we are in a source-code block with a session
19416 (funcall
19417 (intern (concat "org-babel-prep-session:" lang)) session params))))
19418 (cond ;; proceed with `org-edit-special'
19419 ((save-excursion
19420 (beginning-of-line 1)
19421 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19422 (find-file (org-trim (match-string 1))))
19423 ((or (org-at-table-p)
19424 (save-excursion
19425 (beginning-of-line 1)
19426 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19427 (call-interactively 'org-table-edit-formulas))
19428 ((or (org-in-block-p '("src" "example" "latex" "html"))
19429 (org-at-table.el-p))
19430 (org-edit-src-code))
19431 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19432 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19433 (t (user-error "No special environment to edit here"))))
19435 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19436 (defun org-ctrl-c-ctrl-c (&optional arg)
19437 "Set tags in headline, or update according to changed information at point.
19439 This command does many different things, depending on context:
19441 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19442 this is what we do.
19444 - If the cursor is on a statistics cookie, update it.
19446 - If the cursor is in a headline, prompt for tags and insert them
19447 into the current line, aligned to `org-tags-column'. When called
19448 with prefix arg, realign all tags in the current buffer.
19450 - If the cursor is in one of the special #+KEYWORD lines, this
19451 triggers scanning the buffer for these lines and updating the
19452 information.
19454 - If the cursor is inside a table, realign the table. This command
19455 works even if the automatic table editor has been turned off.
19457 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19458 the entire table.
19460 - If the cursor is at a footnote reference or definition, jump to
19461 the corresponding definition or references, respectively.
19463 - If the cursor is a the beginning of a dynamic block, update it.
19465 - If the current buffer is a capture buffer, close note and file it.
19467 - If the cursor is on a <<<target>>>, update radio targets and
19468 corresponding links in this buffer.
19470 - If the cursor is on a numbered item in a plain list, renumber the
19471 ordered list.
19473 - If the cursor is on a checkbox, toggle it.
19475 - If the cursor is on a code block, evaluate it. The variable
19476 `org-confirm-babel-evaluate' can be used to control prompting
19477 before code block evaluation, by default every code block
19478 evaluation requires confirmation. Code block evaluation can be
19479 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19480 (interactive "P")
19481 (let ((org-enable-table-editor t))
19482 (cond
19483 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19484 org-occur-highlights
19485 org-latex-fragment-image-overlays)
19486 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19487 (org-remove-occur-highlights)
19488 (org-remove-latex-fragment-image-overlays)
19489 (message "Temporary highlights/overlays removed from current buffer"))
19490 ((and (local-variable-p 'org-finish-function (current-buffer))
19491 (fboundp org-finish-function))
19492 (funcall org-finish-function))
19493 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19494 ((org-in-regexp org-ts-regexp-both)
19495 (org-timestamp-change 0 'day))
19496 ((or (looking-at org-property-start-re)
19497 (org-at-property-p))
19498 (call-interactively 'org-property-action))
19499 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19500 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19501 (or (org-at-heading-p) (org-at-item-p)))
19502 (call-interactively 'org-update-statistics-cookies))
19503 ((org-at-heading-p) (call-interactively 'org-set-tags))
19504 ((org-at-table.el-p)
19505 (message "Use C-c ' to edit table.el tables"))
19506 ((org-at-table-p)
19507 (org-table-maybe-eval-formula)
19508 (if arg
19509 (call-interactively 'org-table-recalculate)
19510 (org-table-maybe-recalculate-line))
19511 (call-interactively 'org-table-align)
19512 (orgtbl-send-table 'maybe))
19513 ((or (org-footnote-at-reference-p)
19514 (org-footnote-at-definition-p))
19515 (call-interactively 'org-footnote-action))
19516 ((org-at-item-checkbox-p)
19517 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19518 ;; list only if at top item.
19519 (let* ((cbox (match-string 1))
19520 (struct (org-list-struct))
19521 (old-struct (copy-tree struct))
19522 (parents (org-list-parents-alist struct))
19523 (orderedp (org-entry-get nil "ORDERED"))
19524 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19525 block-item)
19526 ;; Use a light version of `org-toggle-checkbox' to avoid
19527 ;; computing list structure twice.
19528 (let ((new-box (cond
19529 ((equal arg '(16)) "[-]")
19530 ((equal arg '(4)) nil)
19531 ((equal "[X]" cbox) "[ ]")
19532 (t "[X]"))))
19533 (if (and firstp arg)
19534 ;; If at first item of sub-list, remove check-box from
19535 ;; every item at the same level.
19536 (mapc
19537 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19538 (org-list-get-all-items
19539 (point-at-bol) struct (org-list-prevs-alist struct)))
19540 (org-list-set-checkbox (point-at-bol) struct new-box)))
19541 ;; Replicate `org-list-write-struct', while grabbing a return
19542 ;; value from `org-list-struct-fix-box'.
19543 (org-list-struct-fix-ind struct parents 2)
19544 (org-list-struct-fix-item-end struct)
19545 (let ((prevs (org-list-prevs-alist struct)))
19546 (org-list-struct-fix-bul struct prevs)
19547 (org-list-struct-fix-ind struct parents)
19548 (setq block-item
19549 (org-list-struct-fix-box struct parents prevs orderedp)))
19550 (if (equal struct old-struct)
19551 (user-error "Cannot toggle this checkbox (unchecked subitems?)")
19552 (org-list-struct-apply-struct struct old-struct)
19553 (org-update-checkbox-count-maybe))
19554 (when block-item
19555 (message
19556 "Checkboxes were removed due to unchecked box at line %d"
19557 (org-current-line block-item)))
19558 (when firstp (org-list-send-list 'maybe))))
19559 ((org-at-item-p)
19560 ;; Cursor at an item: repair list. Do checkbox related actions
19561 ;; only if function was called with an argument. Send list only
19562 ;; if at top item.
19563 (let* ((struct (org-list-struct))
19564 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19565 old-struct)
19566 (when arg
19567 (setq old-struct (copy-tree struct))
19568 (if firstp
19569 ;; If at first item of sub-list, add check-box to every
19570 ;; item at the same level.
19571 (mapc
19572 (lambda (pos)
19573 (unless (org-list-get-checkbox pos struct)
19574 (org-list-set-checkbox pos struct "[ ]")))
19575 (org-list-get-all-items
19576 (point-at-bol) struct (org-list-prevs-alist struct)))
19577 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19578 (org-list-write-struct
19579 struct (org-list-parents-alist struct) old-struct)
19580 (when arg (org-update-checkbox-count-maybe))
19581 (when firstp (org-list-send-list 'maybe))))
19582 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19583 ;; Dynamic block
19584 (beginning-of-line 1)
19585 (save-excursion (org-update-dblock)))
19586 ((save-excursion
19587 (let ((case-fold-search t))
19588 (beginning-of-line 1)
19589 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19590 (cond
19591 ((or (equal (match-string 1) "TBLFM")
19592 (equal (match-string 1) "tblfm"))
19593 ;; Recalculate the table before this line
19594 (save-excursion
19595 (beginning-of-line 1)
19596 (skip-chars-backward " \r\n\t")
19597 (if (org-at-table-p)
19598 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19600 (let ((org-inhibit-startup-visibility-stuff t)
19601 (org-startup-align-all-tables nil))
19602 (when (boundp 'org-table-coordinate-overlays)
19603 (mapc 'delete-overlay org-table-coordinate-overlays)
19604 (setq org-table-coordinate-overlays nil))
19605 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19606 (message "Local setup has been refreshed"))))
19607 ((org-clock-update-time-maybe))
19609 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19610 (error "C-c C-c can do nothing useful at this location"))))))
19612 (defun org-mode-restart ()
19613 "Restart Org-mode, to scan again for special lines.
19614 Also updates the keyword regular expressions."
19615 (interactive)
19616 (org-mode)
19617 (message "Org-mode restarted"))
19619 (defun org-kill-note-or-show-branches ()
19620 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19621 (interactive)
19622 (if (not org-finish-function)
19623 (progn
19624 (hide-subtree)
19625 (call-interactively 'show-branches))
19626 (let ((org-note-abort t))
19627 (funcall org-finish-function))))
19629 (defun org-return (&optional indent)
19630 "Goto next table row or insert a newline.
19631 Calls `org-table-next-row' or `newline', depending on context.
19632 See the individual commands for more information."
19633 (interactive)
19634 (let (org-ts-what)
19635 (cond
19636 ((or (bobp) (org-in-src-block-p))
19637 (if indent (newline-and-indent) (newline)))
19638 ((org-at-table-p)
19639 (org-table-justify-field-maybe)
19640 (call-interactively 'org-table-next-row))
19641 ;; when `newline-and-indent' is called within a list, make sure
19642 ;; text moved stays inside the item.
19643 ((and (org-in-item-p) indent)
19644 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19645 (progn
19646 (save-match-data (newline))
19647 (org-indent-line-to (length (match-string 0))))
19648 (let ((ind (org-get-indentation)))
19649 (newline)
19650 (if (org-looking-back org-list-end-re)
19651 (org-indent-line)
19652 (org-indent-line-to ind)))))
19653 ((and org-return-follows-link
19654 (org-at-timestamp-p t)
19655 (not (eq org-ts-what 'after)))
19656 (org-follow-timestamp-link))
19657 ((and org-return-follows-link
19658 (let ((tprop (get-text-property (point) 'face)))
19659 (or (eq tprop 'org-link)
19660 (and (listp tprop) (memq 'org-link tprop)))))
19661 (call-interactively 'org-open-at-point))
19662 ((and (org-at-heading-p)
19663 (looking-at
19664 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19665 (org-show-entry)
19666 (end-of-line 1)
19667 (newline))
19668 (t (if indent (newline-and-indent) (newline))))))
19670 (defun org-return-indent ()
19671 "Goto next table row or insert a newline and indent.
19672 Calls `org-table-next-row' or `newline-and-indent', depending on
19673 context. See the individual commands for more information."
19674 (interactive)
19675 (org-return t))
19677 (defun org-ctrl-c-star ()
19678 "Compute table, or change heading status of lines.
19679 Calls `org-table-recalculate' or `org-toggle-heading',
19680 depending on context."
19681 (interactive)
19682 (cond
19683 ((org-at-table-p)
19684 (call-interactively 'org-table-recalculate))
19686 ;; Convert all lines in region to list items
19687 (call-interactively 'org-toggle-heading))))
19689 (defun org-ctrl-c-minus ()
19690 "Insert separator line in table or modify bullet status of line.
19691 Also turns a plain line or a region of lines into list items.
19692 Calls `org-table-insert-hline', `org-toggle-item', or
19693 `org-cycle-list-bullet', depending on context."
19694 (interactive)
19695 (cond
19696 ((org-at-table-p)
19697 (call-interactively 'org-table-insert-hline))
19698 ((org-region-active-p)
19699 (call-interactively 'org-toggle-item))
19700 ((org-in-item-p)
19701 (call-interactively 'org-cycle-list-bullet))
19703 (call-interactively 'org-toggle-item))))
19705 (defun org-toggle-item (arg)
19706 "Convert headings or normal lines to items, items to normal lines.
19707 If there is no active region, only the current line is considered.
19709 If the first non blank line in the region is an headline, convert
19710 all headlines to items, shifting text accordingly.
19712 If it is an item, convert all items to normal lines.
19714 If it is normal text, change region into an item. With a prefix
19715 argument ARG, change each line in region into an item."
19716 (interactive "P")
19717 (let ((shift-text
19718 (function
19719 ;; Shift text in current section to IND, from point to END.
19720 ;; The function leaves point to END line.
19721 (lambda (ind end)
19722 (let ((min-i 1000) (end (copy-marker end)))
19723 ;; First determine the minimum indentation (MIN-I) of
19724 ;; the text.
19725 (save-excursion
19726 (catch 'exit
19727 (while (< (point) end)
19728 (let ((i (org-get-indentation)))
19729 (cond
19730 ;; Skip blank lines and inline tasks.
19731 ((looking-at "^[ \t]*$"))
19732 ((looking-at org-outline-regexp-bol))
19733 ;; We can't find less than 0 indentation.
19734 ((zerop i) (throw 'exit (setq min-i 0)))
19735 ((< i min-i) (setq min-i i))))
19736 (forward-line))))
19737 ;; Then indent each line so that a line indented to
19738 ;; MIN-I becomes indented to IND. Ignore blank lines
19739 ;; and inline tasks in the process.
19740 (let ((delta (- ind min-i)))
19741 (while (< (point) end)
19742 (unless (or (looking-at "^[ \t]*$")
19743 (looking-at org-outline-regexp-bol))
19744 (org-indent-line-to (+ (org-get-indentation) delta)))
19745 (forward-line)))))))
19746 (skip-blanks
19747 (function
19748 ;; Return beginning of first non-blank line, starting from
19749 ;; line at POS.
19750 (lambda (pos)
19751 (save-excursion
19752 (goto-char pos)
19753 (skip-chars-forward " \r\t\n")
19754 (point-at-bol)))))
19755 beg end)
19756 ;; Determine boundaries of changes.
19757 (if (org-region-active-p)
19758 (setq beg (funcall skip-blanks (region-beginning))
19759 end (copy-marker (region-end)))
19760 (setq beg (funcall skip-blanks (point-at-bol))
19761 end (copy-marker (point-at-eol))))
19762 ;; Depending on the starting line, choose an action on the text
19763 ;; between BEG and END.
19764 (org-with-limited-levels
19765 (save-excursion
19766 (goto-char beg)
19767 (cond
19768 ;; Case 1. Start at an item: de-itemize. Note that it only
19769 ;; happens when a region is active: `org-ctrl-c-minus'
19770 ;; would call `org-cycle-list-bullet' otherwise.
19771 ((org-at-item-p)
19772 (while (< (point) end)
19773 (when (org-at-item-p)
19774 (skip-chars-forward " \t")
19775 (delete-region (point) (match-end 0)))
19776 (forward-line)))
19777 ;; Case 2. Start at an heading: convert to items.
19778 ((org-at-heading-p)
19779 (let* ((bul (org-list-bullet-string "-"))
19780 (bul-len (length bul))
19781 ;; Indentation of the first heading. It should be
19782 ;; relative to the indentation of its parent, if any.
19783 (start-ind (save-excursion
19784 (cond
19785 ((not org-adapt-indentation) 0)
19786 ((not (outline-previous-heading)) 0)
19787 (t (length (match-string 0))))))
19788 ;; Level of first heading. Further headings will be
19789 ;; compared to it to determine hierarchy in the list.
19790 (ref-level (org-reduced-level (org-outline-level))))
19791 (while (< (point) end)
19792 (let* ((level (org-reduced-level (org-outline-level)))
19793 (delta (max 0 (- level ref-level))))
19794 ;; If current headline is less indented than the first
19795 ;; one, set it as reference, in order to preserve
19796 ;; subtrees.
19797 (when (< level ref-level) (setq ref-level level))
19798 (replace-match bul t t)
19799 (org-indent-line-to (+ start-ind (* delta bul-len)))
19800 ;; Ensure all text down to END (or SECTION-END) belongs
19801 ;; to the newly created item.
19802 (let ((section-end (save-excursion
19803 (or (outline-next-heading) (point)))))
19804 (forward-line)
19805 (funcall shift-text
19806 (+ start-ind (* (1+ delta) bul-len))
19807 (min end section-end)))))))
19808 ;; Case 3. Normal line with ARG: turn each non-item line into
19809 ;; an item.
19810 (arg
19811 (while (< (point) end)
19812 (unless (or (org-at-heading-p) (org-at-item-p))
19813 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19814 (replace-match
19815 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19816 (forward-line)))
19817 ;; Case 4. Normal line without ARG: make the first line of
19818 ;; region an item, and shift indentation of others
19819 ;; lines to set them as item's body.
19820 (t (let* ((bul (org-list-bullet-string "-"))
19821 (bul-len (length bul))
19822 (ref-ind (org-get-indentation)))
19823 (skip-chars-forward " \t")
19824 (insert bul)
19825 (forward-line)
19826 (while (< (point) end)
19827 ;; Ensure that lines less indented than first one
19828 ;; still get included in item body.
19829 (funcall shift-text
19830 (+ ref-ind bul-len)
19831 (min end (save-excursion (or (outline-next-heading)
19832 (point)))))
19833 (forward-line)))))))))
19835 (defun org-toggle-heading (&optional nstars)
19836 "Convert headings to normal text, or items or text to headings.
19837 If there is no active region, only the current line is considered.
19839 With a \\[universal-argument] prefix, convert the whole list at
19840 point into heading.
19842 In a region:
19844 - If the first non blank line is an headline, remove the stars
19845 from all headlines in the region.
19847 - If it is a normal line turn each and every normal line (i.e. not an
19848 heading or an item) in the region into a heading.
19850 - If it is a plain list item, turn all plain list items into headings.
19852 When converting a line into a heading, the number of stars is chosen
19853 such that the lines become children of the current entry. However,
19854 when a prefix argument is given, its value determines the number of
19855 stars to add."
19856 (interactive "P")
19857 (let ((skip-blanks
19858 (function
19859 ;; Return beginning of first non-blank line, starting from
19860 ;; line at POS.
19861 (lambda (pos)
19862 (save-excursion
19863 (goto-char pos)
19864 (while (org-at-comment-p) (forward-line))
19865 (skip-chars-forward " \r\t\n")
19866 (point-at-bol)))))
19867 beg end toggled)
19868 ;; Determine boundaries of changes. If a universal prefix has
19869 ;; been given, put the list in a region. If region ends at a bol,
19870 ;; do not consider the last line to be in the region.
19872 (when (and current-prefix-arg (org-at-item-p))
19873 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19874 (org-mark-element))
19876 (if (org-region-active-p)
19877 (setq beg (funcall skip-blanks (region-beginning))
19878 end (copy-marker (save-excursion
19879 (goto-char (region-end))
19880 (if (bolp) (point) (point-at-eol)))))
19881 (setq beg (funcall skip-blanks (point-at-bol))
19882 end (copy-marker (point-at-eol))))
19883 ;; Ensure inline tasks don't count as headings.
19884 (org-with-limited-levels
19885 (save-excursion
19886 (goto-char beg)
19887 (cond
19888 ;; Case 1. Started at an heading: de-star headings.
19889 ((org-at-heading-p)
19890 (while (< (point) end)
19891 (when (org-at-heading-p t)
19892 (looking-at org-outline-regexp) (replace-match "")
19893 (setq toggled t))
19894 (forward-line)))
19895 ;; Case 2. Started at an item: change items into headlines.
19896 ;; One star will be added by `org-list-to-subtree'.
19897 ((org-at-item-p)
19898 (let* ((stars (make-string
19899 (if nstars
19900 ;; subtract the star that will be added again by
19901 ;; `org-list-to-subtree'
19902 (1- (prefix-numeric-value current-prefix-arg))
19903 (or (org-current-level) 0))
19904 ?*))
19905 (add-stars
19906 (cond (nstars "") ; stars from prefix only
19907 ((equal stars "") "") ; before first heading
19908 (org-odd-levels-only "*") ; inside heading, odd
19909 (t "")))) ; inside heading, oddeven
19910 (while (< (point) end)
19911 (when (org-at-item-p)
19912 ;; Pay attention to cases when region ends before list.
19913 (let* ((struct (org-list-struct))
19914 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19915 (save-restriction
19916 (narrow-to-region (point) list-end)
19917 (insert
19918 (org-list-to-subtree
19919 (org-list-parse-list t)
19920 '(:istart (concat stars add-stars (funcall get-stars depth))
19921 :icount (concat stars add-stars (funcall get-stars depth)))))))
19922 (setq toggled t))
19923 (forward-line))))
19924 ;; Case 3. Started at normal text: make every line an heading,
19925 ;; skipping headlines and items.
19926 (t (let* ((stars (make-string
19927 (if nstars
19928 (prefix-numeric-value current-prefix-arg)
19929 (or (org-current-level) 0))
19930 ?*))
19931 (add-stars
19932 (cond (nstars "") ; stars from prefix only
19933 ((equal stars "") "*") ; before first heading
19934 (org-odd-levels-only "**") ; inside heading, odd
19935 (t "*"))) ; inside heading, oddeven
19936 (rpl (concat stars add-stars " ")))
19937 (while (< (point) end)
19938 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19939 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19940 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19941 (forward-line)))))))
19942 (unless toggled (message "Cannot toggle heading from here"))))
19944 (defun org-meta-return (&optional arg)
19945 "Insert a new heading or wrap a region in a table.
19946 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19947 See the individual commands for more information."
19948 (interactive "P")
19949 (cond
19950 ((run-hook-with-args-until-success 'org-metareturn-hook))
19951 ((or (org-at-drawer-p) (org-at-property-p))
19952 (newline-and-indent))
19953 ((org-at-table-p)
19954 (call-interactively 'org-table-wrap-region))
19955 (t (call-interactively 'org-insert-heading))))
19957 ;;; Menu entries
19959 (defsubst org-in-subtree-not-table-p ()
19960 "Are we in a subtree and not in a table?"
19961 (and (not (org-before-first-heading-p))
19962 (not (org-at-table-p))))
19964 ;; Define the Org-mode menus
19965 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19966 '("Tbl"
19967 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19968 ["Next Field" org-cycle (org-at-table-p)]
19969 ["Previous Field" org-shifttab (org-at-table-p)]
19970 ["Next Row" org-return (org-at-table-p)]
19971 "--"
19972 ["Blank Field" org-table-blank-field (org-at-table-p)]
19973 ["Edit Field" org-table-edit-field (org-at-table-p)]
19974 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19975 "--"
19976 ("Column"
19977 ["Move Column Left" org-metaleft (org-at-table-p)]
19978 ["Move Column Right" org-metaright (org-at-table-p)]
19979 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19980 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19981 ("Row"
19982 ["Move Row Up" org-metaup (org-at-table-p)]
19983 ["Move Row Down" org-metadown (org-at-table-p)]
19984 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19985 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19986 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19987 "--"
19988 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19989 ("Rectangle"
19990 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19991 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19992 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19993 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19994 "--"
19995 ("Calculate"
19996 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19997 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19998 ["Edit Formulas" org-edit-special (org-at-table-p)]
19999 "--"
20000 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20001 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20002 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20003 "--"
20004 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20005 "--"
20006 ["Sum Column/Rectangle" org-table-sum
20007 (or (org-at-table-p) (org-region-active-p))]
20008 ["Which Column?" org-table-current-column (org-at-table-p)])
20009 ["Debug Formulas"
20010 org-table-toggle-formula-debugger
20011 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20012 ["Show Col/Row Numbers"
20013 org-table-toggle-coordinate-overlays
20014 :style toggle
20015 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20016 "--"
20017 ["Create" org-table-create (and (not (org-at-table-p))
20018 org-enable-table-editor)]
20019 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20020 ["Import from File" org-table-import (not (org-at-table-p))]
20021 ["Export to File" org-table-export (org-at-table-p)]
20022 "--"
20023 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20025 (easy-menu-define org-org-menu org-mode-map "Org menu"
20026 '("Org"
20027 ("Show/Hide"
20028 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20029 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20030 ["Sparse Tree..." org-sparse-tree t]
20031 ["Reveal Context" org-reveal t]
20032 ["Show All" show-all t]
20033 "--"
20034 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20035 "--"
20036 ["New Heading" org-insert-heading t]
20037 ("Navigate Headings"
20038 ["Up" outline-up-heading t]
20039 ["Next" outline-next-visible-heading t]
20040 ["Previous" outline-previous-visible-heading t]
20041 ["Next Same Level" outline-forward-same-level t]
20042 ["Previous Same Level" outline-backward-same-level t]
20043 "--"
20044 ["Jump" org-goto t])
20045 ("Edit Structure"
20046 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20047 "--"
20048 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20049 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20050 "--"
20051 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20052 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20053 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20054 "--"
20055 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20056 "--"
20057 ["Copy visible text" org-copy-visible t]
20058 "--"
20059 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20060 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20061 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20062 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20063 "--"
20064 ["Sort Region/Children" org-sort t]
20065 "--"
20066 ["Convert to odd levels" org-convert-to-odd-levels t]
20067 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20068 ("Editing"
20069 ["Emphasis..." org-emphasize t]
20070 ["Edit Source Example" org-edit-special t]
20071 "--"
20072 ["Footnote new/jump" org-footnote-action t]
20073 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20074 ("Archive"
20075 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20076 "--"
20077 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20078 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20079 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20081 "--"
20082 ("Hyperlinks"
20083 ["Store Link (Global)" org-store-link t]
20084 ["Find existing link to here" org-occur-link-in-agenda-files t]
20085 ["Insert Link" org-insert-link t]
20086 ["Follow Link" org-open-at-point t]
20087 "--"
20088 ["Next link" org-next-link t]
20089 ["Previous link" org-previous-link t]
20090 "--"
20091 ["Descriptive Links"
20092 org-toggle-link-display
20093 :style radio
20094 :selected org-descriptive-links
20096 ["Literal Links"
20097 org-toggle-link-display
20098 :style radio
20099 :selected (not org-descriptive-links)])
20100 "--"
20101 ("TODO Lists"
20102 ["TODO/DONE/-" org-todo t]
20103 ("Select keyword"
20104 ["Next keyword" org-shiftright (org-at-heading-p)]
20105 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20106 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20107 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20108 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20109 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20110 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20111 "--"
20112 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20113 :selected org-enforce-todo-dependencies :style toggle :active t]
20114 "Settings for tree at point"
20115 ["Do Children sequentially" org-toggle-ordered-property :style radio
20116 :selected (org-entry-get nil "ORDERED")
20117 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20118 ["Do Children parallel" org-toggle-ordered-property :style radio
20119 :selected (not (org-entry-get nil "ORDERED"))
20120 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20121 "--"
20122 ["Set Priority" org-priority t]
20123 ["Priority Up" org-shiftup t]
20124 ["Priority Down" org-shiftdown t]
20125 "--"
20126 ["Get news from all feeds" org-feed-update-all t]
20127 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20128 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20129 ("TAGS and Properties"
20130 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20131 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20132 "--"
20133 ["Set property" org-set-property (not (org-before-first-heading-p))]
20134 ["Column view of properties" org-columns t]
20135 ["Insert Column View DBlock" org-insert-columns-dblock t])
20136 ("Dates and Scheduling"
20137 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20138 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20139 ("Change Date"
20140 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20141 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20142 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20143 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20144 ["Compute Time Range" org-evaluate-time-range t]
20145 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20146 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20147 "--"
20148 ["Custom time format" org-toggle-time-stamp-overlays
20149 :style radio :selected org-display-custom-times]
20150 "--"
20151 ["Goto Calendar" org-goto-calendar t]
20152 ["Date from Calendar" org-date-from-calendar t]
20153 "--"
20154 ["Start/Restart Timer" org-timer-start t]
20155 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20156 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20157 ["Insert Timer String" org-timer t]
20158 ["Insert Timer Item" org-timer-item t])
20159 ("Logging work"
20160 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20161 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20162 ["Clock out" org-clock-out t]
20163 ["Clock cancel" org-clock-cancel t]
20164 "--"
20165 ["Mark as default task" org-clock-mark-default-task t]
20166 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20167 ["Goto running clock" org-clock-goto t]
20168 "--"
20169 ["Display times" org-clock-display t]
20170 ["Create clock table" org-clock-report t]
20171 "--"
20172 ["Record DONE time"
20173 (progn (setq org-log-done (not org-log-done))
20174 (message "Switching to %s will %s record a timestamp"
20175 (car org-done-keywords)
20176 (if org-log-done "automatically" "not")))
20177 :style toggle :selected org-log-done])
20178 "--"
20179 ["Agenda Command..." org-agenda t]
20180 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20181 ("File List for Agenda")
20182 ("Special views current file"
20183 ["TODO Tree" org-show-todo-tree t]
20184 ["Check Deadlines" org-check-deadlines t]
20185 ["Timeline" org-timeline t]
20186 ["Tags/Property tree" org-match-sparse-tree t])
20187 "--"
20188 ["Export/Publish..." org-export t]
20189 ("LaTeX"
20190 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20191 :selected org-cdlatex-mode]
20192 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20193 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20194 ["Modify math symbol" org-cdlatex-math-modify
20195 (org-inside-LaTeX-fragment-p)]
20196 ["Insert citation" org-reftex-citation t]
20197 "--"
20198 ["Template for BEAMER" (progn (require 'org-beamer)
20199 (org-insert-beamer-options-template)) t])
20200 "--"
20201 ("MobileOrg"
20202 ["Push Files and Views" org-mobile-push t]
20203 ["Get Captured and Flagged" org-mobile-pull t]
20204 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20205 "--"
20206 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20207 "--"
20208 ("Documentation"
20209 ["Show Version" org-version t]
20210 ["Info Documentation" org-info t])
20211 ("Customize"
20212 ["Browse Org Group" org-customize t]
20213 "--"
20214 ["Expand This Menu" org-create-customize-menu
20215 (fboundp 'customize-menu-create)])
20216 ["Send bug report" org-submit-bug-report t]
20217 "--"
20218 ("Refresh/Reload"
20219 ["Refresh setup current buffer" org-mode-restart t]
20220 ["Reload Org (after update)" org-reload t]
20221 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20224 (defun org-info (&optional node)
20225 "Read documentation for Org-mode in the info system.
20226 With optional NODE, go directly to that node."
20227 (interactive)
20228 (info (format "(org)%s" (or node ""))))
20230 ;;;###autoload
20231 (defun org-submit-bug-report ()
20232 "Submit a bug report on Org-mode via mail.
20234 Don't hesitate to report any problems or inaccurate documentation.
20236 If you don't have setup sending mail from (X)Emacs, please copy the
20237 output buffer into your mail program, as it gives us important
20238 information about your Org-mode version and configuration."
20239 (interactive)
20240 (require 'reporter)
20241 (org-load-modules-maybe)
20242 (org-require-autoloaded-modules)
20243 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20244 (reporter-submit-bug-report
20245 "emacs-orgmode@gnu.org"
20246 (org-version nil 'full)
20247 (let (list)
20248 (save-window-excursion
20249 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20250 (delete-other-windows)
20251 (erase-buffer)
20252 (insert "You are about to submit a bug report to the Org-mode mailing list.
20254 We would like to add your full Org-mode and Outline configuration to the
20255 bug report. This greatly simplifies the work of the maintainer and
20256 other experts on the mailing list.
20258 HOWEVER, some variables you have customized may contain private
20259 information. The names of customers, colleagues, or friends, might
20260 appear in the form of file names, tags, todo states, or search strings.
20261 If you answer yes to the prompt, you might want to check and remove
20262 such private information before sending the email.")
20263 (add-text-properties (point-min) (point-max) '(face org-warning))
20264 (when (yes-or-no-p "Include your Org-mode configuration ")
20265 (mapatoms
20266 (lambda (v)
20267 (and (boundp v)
20268 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20269 (or (and (symbol-value v)
20270 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20271 (and
20272 (get v 'custom-type) (get v 'standard-value)
20273 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20274 (push v list)))))
20275 (kill-buffer (get-buffer "*Warn about privacy*"))
20276 list))
20277 nil nil
20278 "Remember to cover the basics, that is, what you expected to happen and
20279 what in fact did happen. You don't know how to make a good report? See
20281 http://orgmode.org/manual/Feedback.html#Feedback
20283 Your bug report will be posted to the Org-mode mailing list.
20284 ------------------------------------------------------------------------")
20285 (save-excursion
20286 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20287 (replace-match "\\1Bug: \\3 [\\2]")))))
20290 (defun org-install-agenda-files-menu ()
20291 (let ((bl (buffer-list)))
20292 (save-excursion
20293 (while bl
20294 (set-buffer (pop bl))
20295 (if (derived-mode-p 'org-mode) (setq bl nil)))
20296 (when (derived-mode-p 'org-mode)
20297 (easy-menu-change
20298 '("Org") "File List for Agenda"
20299 (append
20300 (list
20301 ["Edit File List" (org-edit-agenda-file-list) t]
20302 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20303 ["Remove Current File from List" org-remove-file t]
20304 ["Cycle through agenda files" org-cycle-agenda-files t]
20305 ["Occur in all agenda files" org-occur-in-agenda-files t]
20306 "--")
20307 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20309 ;;;; Documentation
20311 (defun org-require-autoloaded-modules ()
20312 (interactive)
20313 (mapc 'require
20314 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20315 org-docbook org-exp org-html org-icalendar
20316 org-id org-latex
20317 org-publish org-remember org-table
20318 org-timer org-xoxo)))
20320 ;;;###autoload
20321 (defun org-reload (&optional uncompiled)
20322 "Reload all org lisp files.
20323 With prefix arg UNCOMPILED, load the uncompiled versions."
20324 (interactive "P")
20325 (require 'loadhist)
20326 (let* ((org-dir (org-find-library-dir "org"))
20327 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20328 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20329 (remove-re (mapconcat 'identity
20330 (mapcar (lambda (f) (concat "^" f "$"))
20331 (list (if (featurep 'xemacs)
20332 "org-colview"
20333 "org-colview-xemacs")
20334 "org" "org-loaddefs" "org-version"))
20335 "\\|"))
20336 (feats (delete-dups
20337 (mapcar 'file-name-sans-extension
20338 (mapcar 'file-name-nondirectory
20339 (delq nil
20340 (mapcar 'feature-file
20341 features))))))
20342 (lfeat (append
20343 (sort
20344 (setq feats
20345 (delq nil (mapcar
20346 (lambda (f)
20347 (if (and (string-match feature-re f)
20348 (not (string-match remove-re f)))
20349 f nil))
20350 feats)))
20351 'string-lessp)
20352 (list "org-version" "org")))
20353 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20354 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20355 load-uncore load-misses)
20356 (setq load-misses
20357 (delq 't
20358 (mapcar (lambda (f)
20359 (or (org-load-noerror-mustsuffix (concat org-dir f))
20360 (and (string= org-dir contrib-dir)
20361 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20362 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20363 (add-to-list 'load-uncore f 'append)
20366 lfeat)))
20367 (if load-uncore
20368 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20369 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20370 (if load-misses
20371 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20372 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20373 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20375 ;;;###autoload
20376 (defun org-customize ()
20377 "Call the customize function with org as argument."
20378 (interactive)
20379 (org-load-modules-maybe)
20380 (org-require-autoloaded-modules)
20381 (customize-browse 'org))
20383 (defun org-create-customize-menu ()
20384 "Create a full customization menu for Org-mode, insert it into the menu."
20385 (interactive)
20386 (org-load-modules-maybe)
20387 (org-require-autoloaded-modules)
20388 (if (fboundp 'customize-menu-create)
20389 (progn
20390 (easy-menu-change
20391 '("Org") "Customize"
20392 `(["Browse Org group" org-customize t]
20393 "--"
20394 ,(customize-menu-create 'org)
20395 ["Set" Custom-set t]
20396 ["Save" Custom-save t]
20397 ["Reset to Current" Custom-reset-current t]
20398 ["Reset to Saved" Custom-reset-saved t]
20399 ["Reset to Standard Settings" Custom-reset-standard t]))
20400 (message "\"Org\"-menu now contains full customization menu"))
20401 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20403 ;;;; Miscellaneous stuff
20405 ;;; Generally useful functions
20407 (defun org-get-at-bol (property)
20408 "Get text property PROPERTY at beginning of line."
20409 (get-text-property (point-at-bol) property))
20411 (defun org-find-text-property-in-string (prop s)
20412 "Return the first non-nil value of property PROP in string S."
20413 (or (get-text-property 0 prop s)
20414 (get-text-property (or (next-single-property-change 0 prop s) 0)
20415 prop s)))
20417 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20418 "Display the given MESSAGE as a warning."
20419 (if (fboundp 'display-warning)
20420 (display-warning 'org message
20421 (if (featurep 'xemacs) 'warning :warning))
20422 (let ((buf (get-buffer-create "*Org warnings*")))
20423 (with-current-buffer buf
20424 (goto-char (point-max))
20425 (insert "Warning (Org): " message)
20426 (unless (bolp)
20427 (newline)))
20428 (display-buffer buf)
20429 (sit-for 0))))
20431 (defun org-eval (form)
20432 "Eval FORM and return result."
20433 (condition-case error
20434 (eval form)
20435 (error (format "%%![Error: %s]" error))))
20437 (defun org-in-clocktable-p ()
20438 "Check if the cursor is in a clocktable."
20439 (let ((pos (point)) start)
20440 (save-excursion
20441 (end-of-line 1)
20442 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20443 (setq start (match-beginning 0))
20444 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20445 (>= (match-end 0) pos)
20446 start))))
20448 (defun org-in-commented-line ()
20449 "Is point in a line starting with `#'?"
20450 (equal (char-after (point-at-bol)) ?#))
20452 (defun org-in-indented-comment-line ()
20453 "Is point in a line starting with `#' after some white space?"
20454 (save-excursion
20455 (save-match-data
20456 (goto-char (point-at-bol))
20457 (looking-at "[ \t]*#"))))
20459 (defun org-in-verbatim-emphasis ()
20460 (save-match-data
20461 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20463 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20464 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20465 (if (and marker (marker-buffer marker)
20466 (buffer-live-p (marker-buffer marker)))
20467 (progn
20468 (org-pop-to-buffer-same-window (marker-buffer marker))
20469 (if (or (> marker (point-max)) (< marker (point-min)))
20470 (widen))
20471 (goto-char marker)
20472 (org-show-context 'org-goto))
20473 (if bookmark
20474 (bookmark-jump bookmark)
20475 (error "Cannot find location"))))
20477 (defun org-quote-csv-field (s)
20478 "Quote field for inclusion in CSV material."
20479 (if (string-match "[\",]" s)
20480 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20483 (defun org-force-self-insert (N)
20484 "Needed to enforce self-insert under remapping."
20485 (interactive "p")
20486 (self-insert-command N))
20488 (defun org-string-width (s)
20489 "Compute width of string, ignoring invisible characters.
20490 This ignores character with invisibility property `org-link', and also
20491 characters with property `org-cwidth', because these will become invisible
20492 upon the next fontification round."
20493 (let (b l)
20494 (when (or (eq t buffer-invisibility-spec)
20495 (assq 'org-link buffer-invisibility-spec))
20496 (while (setq b (text-property-any 0 (length s)
20497 'invisible 'org-link s))
20498 (setq s (concat (substring s 0 b)
20499 (substring s (or (next-single-property-change
20500 b 'invisible s) (length s)))))))
20501 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20502 (setq s (concat (substring s 0 b)
20503 (substring s (or (next-single-property-change
20504 b 'org-cwidth s) (length s))))))
20505 (setq l (string-width s) b -1)
20506 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20507 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20510 (defun org-shorten-string (s maxlength)
20511 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20512 If the string is shorter or has length MAXLENGTH, just return the
20513 original string. If it is longer, the functions finds a space in the
20514 string, breaks this string off at that locations and adds three dots
20515 as ellipsis. Including the ellipsis, the string will not be longer
20516 than MAXLENGTH. If finding a good breaking point in the string does
20517 not work, the string is just chopped off in the middle of a word
20518 if necessary."
20519 (if (<= (length s) maxlength)
20521 (let* ((n (max (- maxlength 4) 1))
20522 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20523 (if (string-match re s)
20524 (concat (match-string 1 s) "...")
20525 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20527 (defun org-get-indentation (&optional line)
20528 "Get the indentation of the current line, interpreting tabs.
20529 When LINE is given, assume it represents a line and compute its indentation."
20530 (if line
20531 (if (string-match "^ *" (org-remove-tabs line))
20532 (match-end 0))
20533 (save-excursion
20534 (beginning-of-line 1)
20535 (skip-chars-forward " \t")
20536 (current-column))))
20538 (defun org-get-string-indentation (s)
20539 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20540 (let ((n -1) (i 0) (w tab-width) c)
20541 (catch 'exit
20542 (while (< (setq n (1+ n)) (length s))
20543 (setq c (aref s n))
20544 (cond ((= c ?\ ) (setq i (1+ i)))
20545 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20546 (t (throw 'exit t)))))
20549 (defun org-remove-tabs (s &optional width)
20550 "Replace tabulators in S with spaces.
20551 Assumes that s is a single line, starting in column 0."
20552 (setq width (or width tab-width))
20553 (while (string-match "\t" s)
20554 (setq s (replace-match
20555 (make-string
20556 (- (* width (/ (+ (match-beginning 0) width) width))
20557 (match-beginning 0)) ?\ )
20558 t t s)))
20561 (defun org-fix-indentation (line ind)
20562 "Fix indentation in LINE.
20563 IND is a cons cell with target and minimum indentation.
20564 If the current indentation in LINE is smaller than the minimum,
20565 leave it alone. If it is larger than ind, set it to the target."
20566 (let* ((l (org-remove-tabs line))
20567 (i (org-get-indentation l))
20568 (i1 (car ind)) (i2 (cdr ind)))
20569 (if (>= i i2) (setq l (substring line i2)))
20570 (if (> i1 0)
20571 (concat (make-string i1 ?\ ) l)
20572 l)))
20574 (defun org-remove-indentation (code &optional n)
20575 "Remove the maximum common indentation from the lines in CODE.
20576 N may optionally be the number of spaces to remove."
20577 (with-temp-buffer
20578 (insert code)
20579 (org-do-remove-indentation n)
20580 (buffer-string)))
20582 (defun org-do-remove-indentation (&optional n)
20583 "Remove the maximum common indentation from the buffer."
20584 (untabify (point-min) (point-max))
20585 (let ((min 10000) re)
20586 (if n
20587 (setq min n)
20588 (goto-char (point-min))
20589 (while (re-search-forward "^ *[^ \n]" nil t)
20590 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20591 (unless (or (= min 0) (= min 10000))
20592 (setq re (format "^ \\{%d\\}" min))
20593 (goto-char (point-min))
20594 (while (re-search-forward re nil t)
20595 (replace-match "")
20596 (end-of-line 1))
20597 min)))
20599 (defun org-fill-template (template alist)
20600 "Find each %key of ALIST in TEMPLATE and replace it."
20601 (let ((case-fold-search nil)
20602 entry key value)
20603 (setq alist (sort (copy-sequence alist)
20604 (lambda (a b) (< (length (car a)) (length (car b))))))
20605 (while (setq entry (pop alist))
20606 (setq template
20607 (replace-regexp-in-string
20608 (concat "%" (regexp-quote (car entry)))
20609 (or (cdr entry) "") template t t)))
20610 template))
20612 (defun org-base-buffer (buffer)
20613 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20614 (if (not buffer)
20615 buffer
20616 (or (buffer-base-buffer buffer)
20617 buffer)))
20619 (defun org-trim (s)
20620 "Remove whitespace at beginning and end of string."
20621 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20622 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20625 (defun org-wrap (string &optional width lines)
20626 "Wrap string to either a number of lines, or a width in characters.
20627 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20628 that costs. If there is a word longer than WIDTH, the text is actually
20629 wrapped to the length of that word.
20630 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20631 many lines, whatever width that takes.
20632 The return value is a list of lines, without newlines at the end."
20633 (let* ((words (org-split-string string "[ \t\n]+"))
20634 (maxword (apply 'max (mapcar 'org-string-width words)))
20635 w ll)
20636 (cond (width
20637 (org-do-wrap words (max maxword width)))
20638 (lines
20639 (setq w maxword)
20640 (setq ll (org-do-wrap words maxword))
20641 (if (<= (length ll) lines)
20643 (setq ll words)
20644 (while (> (length ll) lines)
20645 (setq w (1+ w))
20646 (setq ll (org-do-wrap words w)))
20647 ll))
20648 (t (error "Cannot wrap this")))))
20650 (defun org-do-wrap (words width)
20651 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20652 (let (lines line)
20653 (while words
20654 (setq line (pop words))
20655 (while (and words (< (+ (length line) (length (car words))) width))
20656 (setq line (concat line " " (pop words))))
20657 (setq lines (push line lines)))
20658 (nreverse lines)))
20660 (defun org-split-string (string &optional separators)
20661 "Splits STRING into substrings at SEPARATORS.
20662 No empty strings are returned if there are matches at the beginning
20663 and end of string."
20664 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20665 (start 0)
20666 notfirst
20667 (list nil))
20668 (while (and (string-match rexp string
20669 (if (and notfirst
20670 (= start (match-beginning 0))
20671 (< start (length string)))
20672 (1+ start) start))
20673 (< (match-beginning 0) (length string)))
20674 (setq notfirst t)
20675 (or (eq (match-beginning 0) 0)
20676 (and (eq (match-beginning 0) (match-end 0))
20677 (eq (match-beginning 0) start))
20678 (setq list
20679 (cons (substring string start (match-beginning 0))
20680 list)))
20681 (setq start (match-end 0)))
20682 (or (eq start (length string))
20683 (setq list
20684 (cons (substring string start)
20685 list)))
20686 (nreverse list)))
20688 (defun org-quote-vert (s)
20689 "Replace \"|\" with \"\\vert\"."
20690 (while (string-match "|" s)
20691 (setq s (replace-match "\\vert" t t s)))
20694 (defun org-uuidgen-p (s)
20695 "Is S an ID created by UUIDGEN?"
20696 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20698 (defun org-in-src-block-p (&optional inside)
20699 "Whether point is in a code source block.
20700 When INSIDE is non-nil, don't consider we are within a src block
20701 when point is at #+BEGIN_SRC or #+END_SRC."
20702 (let ((case-fold-search t) ov)
20703 (or (and (setq ov (overlays-at (point)))
20704 (memq 'org-block-background
20705 (overlay-properties (car ov))))
20706 (and (not inside)
20707 (save-match-data
20708 (save-excursion
20709 (beginning-of-line)
20710 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20712 (defun org-context ()
20713 "Return a list of contexts of the current cursor position.
20714 If several contexts apply, all are returned.
20715 Each context entry is a list with a symbol naming the context, and
20716 two positions indicating start and end of the context. Possible
20717 contexts are:
20719 :headline anywhere in a headline
20720 :headline-stars on the leading stars in a headline
20721 :todo-keyword on a TODO keyword (including DONE) in a headline
20722 :tags on the TAGS in a headline
20723 :priority on the priority cookie in a headline
20724 :item on the first line of a plain list item
20725 :item-bullet on the bullet/number of a plain list item
20726 :checkbox on the checkbox in a plain list item
20727 :table in an org-mode table
20728 :table-special on a special filed in a table
20729 :table-table in a table.el table
20730 :clocktable in a clocktable
20731 :src-block in a source block
20732 :link on a hyperlink
20733 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20734 :target on a <<target>>
20735 :radio-target on a <<<radio-target>>>
20736 :latex-fragment on a LaTeX fragment
20737 :latex-preview on a LaTeX fragment with overlaid preview image
20739 This function expects the position to be visible because it uses font-lock
20740 faces as a help to recognize the following contexts: :table-special, :link,
20741 and :keyword."
20742 (let* ((f (get-text-property (point) 'face))
20743 (faces (if (listp f) f (list f)))
20744 (case-fold-search t)
20745 (p (point)) clist o)
20746 ;; First the large context
20747 (cond
20748 ((org-at-heading-p t)
20749 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20750 (when (progn
20751 (beginning-of-line 1)
20752 (looking-at org-todo-line-tags-regexp))
20753 (push (org-point-in-group p 1 :headline-stars) clist)
20754 (push (org-point-in-group p 2 :todo-keyword) clist)
20755 (push (org-point-in-group p 4 :tags) clist))
20756 (goto-char p)
20757 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20758 (if (looking-at "\\[#[A-Z0-9]\\]")
20759 (push (org-point-in-group p 0 :priority) clist)))
20761 ((org-at-item-p)
20762 (push (org-point-in-group p 2 :item-bullet) clist)
20763 (push (list :item (point-at-bol)
20764 (save-excursion (org-end-of-item) (point)))
20765 clist)
20766 (and (org-at-item-checkbox-p)
20767 (push (org-point-in-group p 0 :checkbox) clist)))
20769 ((org-at-table-p)
20770 (push (list :table (org-table-begin) (org-table-end)) clist)
20771 (if (memq 'org-formula faces)
20772 (push (list :table-special
20773 (previous-single-property-change p 'face)
20774 (next-single-property-change p 'face)) clist)))
20775 ((org-at-table-p 'any)
20776 (push (list :table-table) clist)))
20777 (goto-char p)
20779 (let ((case-fold-search t))
20780 ;; New the "medium" contexts: clocktables, source blocks
20781 (cond ((org-in-clocktable-p)
20782 (push (list :clocktable
20783 (and (or (looking-at "#\\+BEGIN: clocktable")
20784 (search-backward "#+BEGIN: clocktable" nil t))
20785 (match-beginning 0))
20786 (and (re-search-forward "#\\+END:?" nil t)
20787 (match-end 0))) clist))
20788 ((org-in-src-block-p)
20789 (push (list :src-block
20790 (and (or (looking-at "#\\+BEGIN_SRC")
20791 (search-backward "#+BEGIN_SRC" nil t))
20792 (match-beginning 0))
20793 (and (search-forward "#+END_SRC" nil t)
20794 (match-beginning 0))) clist))))
20795 (goto-char p)
20797 ;; Now the small context
20798 (cond
20799 ((org-at-timestamp-p)
20800 (push (org-point-in-group p 0 :timestamp) clist))
20801 ((memq 'org-link faces)
20802 (push (list :link
20803 (previous-single-property-change p 'face)
20804 (next-single-property-change p 'face)) clist))
20805 ((memq 'org-special-keyword faces)
20806 (push (list :keyword
20807 (previous-single-property-change p 'face)
20808 (next-single-property-change p 'face)) clist))
20809 ((org-at-target-p)
20810 (push (org-point-in-group p 0 :target) clist)
20811 (goto-char (1- (match-beginning 0)))
20812 (if (looking-at org-radio-target-regexp)
20813 (push (org-point-in-group p 0 :radio-target) clist))
20814 (goto-char p))
20815 ((setq o (car (delq nil
20816 (mapcar
20817 (lambda (x)
20818 (if (memq x org-latex-fragment-image-overlays) x))
20819 (overlays-at (point))))))
20820 (push (list :latex-fragment
20821 (overlay-start o) (overlay-end o)) clist)
20822 (push (list :latex-preview
20823 (overlay-start o) (overlay-end o)) clist))
20824 ((org-inside-LaTeX-fragment-p)
20825 ;; FIXME: positions wrong.
20826 (push (list :latex-fragment (point) (point)) clist)))
20828 (setq clist (nreverse (delq nil clist)))
20829 clist))
20831 ;; FIXME: Compare with at-regexp-p Do we need both?
20832 (defun org-in-regexp (re &optional nlines visually)
20833 "Check if point is inside a match of regexp.
20834 Normally only the current line is checked, but you can include NLINES extra
20835 lines both before and after point into the search.
20836 If VISUALLY is set, require that the cursor is not after the match but
20837 really on, so that the block visually is on the match."
20838 (catch 'exit
20839 (let ((pos (point))
20840 (eol (point-at-eol (+ 1 (or nlines 0))))
20841 (inc (if visually 1 0)))
20842 (save-excursion
20843 (beginning-of-line (- 1 (or nlines 0)))
20844 (while (re-search-forward re eol t)
20845 (if (and (<= (match-beginning 0) pos)
20846 (>= (+ inc (match-end 0)) pos))
20847 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20849 (defun org-at-regexp-p (regexp)
20850 "Is point inside a match of REGEXP in the current line?"
20851 (catch 'exit
20852 (save-excursion
20853 (let ((pos (point)) (end (point-at-eol)))
20854 (beginning-of-line 1)
20855 (while (re-search-forward regexp end t)
20856 (if (and (<= (match-beginning 0) pos)
20857 (>= (match-end 0) pos))
20858 (throw 'exit t)))
20859 nil))))
20861 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20862 "Non-nil when point is between matches of START-RE and END-RE.
20864 Also return a non-nil value when point is on one of the matches.
20866 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20867 buffer positions. Default values are the positions of headlines
20868 surrounding the point.
20870 The functions returns a cons cell whose car (resp. cdr) is the
20871 position before START-RE (resp. after END-RE)."
20872 (save-match-data
20873 (let ((pos (point))
20874 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20875 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20876 beg end)
20877 (save-excursion
20878 ;; Point is on a block when on START-RE or if START-RE can be
20879 ;; found before it...
20880 (and (or (org-at-regexp-p start-re)
20881 (re-search-backward start-re limit-up t))
20882 (setq beg (match-beginning 0))
20883 ;; ... and END-RE after it...
20884 (goto-char (match-end 0))
20885 (re-search-forward end-re limit-down t)
20886 (> (setq end (match-end 0)) pos)
20887 ;; ... without another START-RE in-between.
20888 (goto-char (match-beginning 0))
20889 (not (re-search-backward start-re (1+ beg) t))
20890 ;; Return value.
20891 (cons beg end))))))
20893 (defun org-in-block-p (names)
20894 "Non-nil when point belongs to a block whose name belongs to NAMES.
20896 NAMES is a list of strings containing names of blocks.
20898 Return first block name matched, or nil. Beware that in case of
20899 nested blocks, the returned name may not belong to the closest
20900 block from point."
20901 (save-match-data
20902 (catch 'exit
20903 (let ((case-fold-search t)
20904 (lim-up (save-excursion (outline-previous-heading)))
20905 (lim-down (save-excursion (outline-next-heading))))
20906 (mapc (lambda (name)
20907 (let ((n (regexp-quote name)))
20908 (when (org-between-regexps-p
20909 (concat "^[ \t]*#\\+begin_" n)
20910 (concat "^[ \t]*#\\+end_" n)
20911 lim-up lim-down)
20912 (throw 'exit n))))
20913 names))
20914 nil)))
20916 (defun org-occur-in-agenda-files (regexp &optional nlines)
20917 "Call `multi-occur' with buffers for all agenda files."
20918 (interactive "sOrg-files matching: \np")
20919 (let* ((files (org-agenda-files))
20920 (tnames (mapcar 'file-truename files))
20921 (extra org-agenda-text-search-extra-files)
20923 (when (eq (car extra) 'agenda-archives)
20924 (setq extra (cdr extra))
20925 (setq files (org-add-archive-files files)))
20926 (while (setq f (pop extra))
20927 (unless (member (file-truename f) tnames)
20928 (add-to-list 'files f 'append)
20929 (add-to-list 'tnames (file-truename f) 'append)))
20930 (multi-occur
20931 (mapcar (lambda (x)
20932 (with-current-buffer
20933 (or (get-file-buffer x) (find-file-noselect x))
20934 (widen)
20935 (current-buffer)))
20936 files)
20937 regexp)))
20939 (if (boundp 'occur-mode-find-occurrence-hook)
20940 ;; Emacs 23
20941 (add-hook 'occur-mode-find-occurrence-hook
20942 (lambda ()
20943 (when (derived-mode-p 'org-mode)
20944 (org-reveal))))
20945 ;; Emacs 22
20946 (defadvice occur-mode-goto-occurrence
20947 (after org-occur-reveal activate)
20948 (and (derived-mode-p 'org-mode) (org-reveal)))
20949 (defadvice occur-mode-goto-occurrence-other-window
20950 (after org-occur-reveal activate)
20951 (and (derived-mode-p 'org-mode) (org-reveal)))
20952 (defadvice occur-mode-display-occurrence
20953 (after org-occur-reveal activate)
20954 (when (derived-mode-p 'org-mode)
20955 (let ((pos (occur-mode-find-occurrence)))
20956 (with-current-buffer (marker-buffer pos)
20957 (save-excursion
20958 (goto-char pos)
20959 (org-reveal)))))))
20961 (defun org-occur-link-in-agenda-files ()
20962 "Create a link and search for it in the agendas.
20963 The link is not stored in `org-stored-links', it is just created
20964 for the search purpose."
20965 (interactive)
20966 (let ((link (condition-case nil
20967 (org-store-link nil)
20968 (error "Unable to create a link to here"))))
20969 (org-occur-in-agenda-files (regexp-quote link))))
20971 (defun org-uniquify (list)
20972 "Remove duplicate elements from LIST."
20973 (let (res)
20974 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20975 res))
20977 (defun org-delete-all (elts list)
20978 "Remove all elements in ELTS from LIST."
20979 (while elts
20980 (setq list (delete (pop elts) list)))
20981 list)
20983 (defun org-count (cl-item cl-seq)
20984 "Count the number of occurrences of ITEM in SEQ.
20985 Taken from `count' in cl-seq.el with all keyword arguments removed."
20986 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20987 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20988 (while (< cl-start cl-end)
20989 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20990 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20991 (setq cl-start (1+ cl-start)))
20992 cl-count))
20994 (defun org-remove-if (predicate seq)
20995 "Remove everything from SEQ that fulfills PREDICATE."
20996 (let (res e)
20997 (while seq
20998 (setq e (pop seq))
20999 (if (not (funcall predicate e)) (push e res)))
21000 (nreverse res)))
21002 (defun org-remove-if-not (predicate seq)
21003 "Remove everything from SEQ that does not fulfill PREDICATE."
21004 (let (res e)
21005 (while seq
21006 (setq e (pop seq))
21007 (if (funcall predicate e) (push e res)))
21008 (nreverse res)))
21010 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21011 "Reduce two-argument FUNCTION across SEQ.
21012 Taken from `reduce' in cl-seq.el with all keyword arguments but
21013 \":initial-value\" removed."
21014 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21015 (cadr (memq :initial-value cl-keys)))
21016 (cl-seq (pop cl-seq))
21017 (t (funcall cl-func)))))
21018 (while cl-seq
21019 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21020 cl-accum))
21022 (defun org-back-over-empty-lines ()
21023 "Move backwards over whitespace, to the beginning of the first empty line.
21024 Returns the number of empty lines passed."
21025 (let ((pos (point)))
21026 (if (cdr (assoc 'heading org-blank-before-new-entry))
21027 (skip-chars-backward " \t\n\r")
21028 (unless (eobp)
21029 (forward-line -1)))
21030 (beginning-of-line 2)
21031 (goto-char (min (point) pos))
21032 (count-lines (point) pos)))
21034 (defun org-skip-whitespace ()
21035 (skip-chars-forward " \t\n\r"))
21037 (defun org-point-in-group (point group &optional context)
21038 "Check if POINT is in match-group GROUP.
21039 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21040 match. If the match group does not exist or point is not inside it,
21041 return nil."
21042 (and (match-beginning group)
21043 (>= point (match-beginning group))
21044 (<= point (match-end group))
21045 (if context
21046 (list context (match-beginning group) (match-end group))
21047 t)))
21049 (defun org-switch-to-buffer-other-window (&rest args)
21050 "Switch to buffer in a second window on the current frame.
21051 In particular, do not allow pop-up frames.
21052 Returns the newly created buffer."
21053 (org-no-popups
21054 (apply 'switch-to-buffer-other-window args)))
21056 (defun org-combine-plists (&rest plists)
21057 "Create a single property list from all plists in PLISTS.
21058 The process starts by copying the first list, and then setting properties
21059 from the other lists. Settings in the last list are the most significant
21060 ones and overrule settings in the other lists."
21061 (let ((rtn (copy-sequence (pop plists)))
21062 p v ls)
21063 (while plists
21064 (setq ls (pop plists))
21065 (while ls
21066 (setq p (pop ls) v (pop ls))
21067 (setq rtn (plist-put rtn p v))))
21068 rtn))
21070 (defun org-replace-escapes (string table)
21071 "Replace %-escapes in STRING with values in TABLE.
21072 TABLE is an association list with keys like \"%a\" and string values.
21073 The sequences in STRING may contain normal field width and padding information,
21074 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21075 so values can contain further %-escapes if they are define later in TABLE."
21076 (let ((tbl (copy-alist table))
21077 (case-fold-search nil)
21078 (pchg 0)
21079 e re rpl)
21080 (while (setq e (pop tbl))
21081 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21082 (when (and (cdr e) (string-match re (cdr e)))
21083 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21084 (safe "SREF"))
21085 (add-text-properties 0 3 (list 'sref sref) safe)
21086 (setcdr e (replace-match safe t t (cdr e)))))
21087 (while (string-match re string)
21088 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21089 (cdr e)))
21090 (setq string (replace-match rpl t t string))))
21091 (while (setq pchg (next-property-change pchg string))
21092 (let ((sref (get-text-property pchg 'sref string)))
21093 (when (and sref (string-match "SREF" string pchg))
21094 (setq string (replace-match sref t t string)))))
21095 string))
21097 (defun org-sublist (list start end)
21098 "Return a section of LIST, from START to END.
21099 Counting starts at 1."
21100 (let (rtn (c start))
21101 (setq list (nthcdr (1- start) list))
21102 (while (and list (<= c end))
21103 (push (pop list) rtn)
21104 (setq c (1+ c)))
21105 (nreverse rtn)))
21107 (defun org-find-base-buffer-visiting (file)
21108 "Like `find-buffer-visiting' but always return the base buffer and
21109 not an indirect buffer."
21110 (let ((buf (or (get-file-buffer file)
21111 (find-buffer-visiting file))))
21112 (if buf
21113 (or (buffer-base-buffer buf) buf)
21114 nil)))
21116 (defun org-image-file-name-regexp (&optional extensions)
21117 "Return regexp matching the file names of images.
21118 If EXTENSIONS is given, only match these."
21119 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21120 (image-file-name-regexp)
21121 (let ((image-file-name-extensions
21122 (or extensions
21123 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21124 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21125 (concat "\\."
21126 (regexp-opt (nconc (mapcar 'upcase
21127 image-file-name-extensions)
21128 image-file-name-extensions)
21130 "\\'"))))
21132 (defun org-file-image-p (file &optional extensions)
21133 "Return non-nil if FILE is an image."
21134 (save-match-data
21135 (string-match (org-image-file-name-regexp extensions) file)))
21137 (defun org-get-cursor-date (&optional with-time)
21138 "Return the date at cursor in as a time.
21139 This works in the calendar and in the agenda, anywhere else it just
21140 returns the current time.
21141 If WITH-TIME is non-nil, returns the time of the event at point (in
21142 the agenda) or the current time of the day."
21143 (let (date day defd tp tm hod mod)
21144 (when with-time
21145 (setq tp (get-text-property (point) 'time))
21146 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21147 (setq hod (string-to-number (match-string 1 tp))
21148 mod (string-to-number (match-string 2 tp))))
21149 (or tp (setq hod (nth 2 (decode-time (current-time)))
21150 mod (nth 1 (decode-time (current-time))))))
21151 (cond
21152 ((eq major-mode 'calendar-mode)
21153 (setq date (calendar-cursor-to-date)
21154 defd (encode-time 0 (or mod 0) (or hod 0)
21155 (nth 1 date) (nth 0 date) (nth 2 date))))
21156 ((eq major-mode 'org-agenda-mode)
21157 (setq day (get-text-property (point) 'day))
21158 (if day
21159 (setq date (calendar-gregorian-from-absolute day)
21160 defd (encode-time 0 (or mod 0) (or hod 0)
21161 (nth 1 date) (nth 0 date) (nth 2 date))))))
21162 (or defd (current-time))))
21164 (defun org-mark-subtree (&optional up)
21165 "Mark the current subtree.
21166 This puts point at the start of the current subtree, and mark at
21167 the end. If a numeric prefix UP is given, move up into the
21168 hierarchy of headlines by UP levels before marking the subtree."
21169 (interactive "P")
21170 (org-with-limited-levels
21171 (cond ((org-at-heading-p) (beginning-of-line))
21172 ((org-before-first-heading-p) (error "Not in a subtree"))
21173 (t (outline-previous-visible-heading 1))))
21174 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21175 (if (org-called-interactively-p 'any)
21176 (call-interactively 'org-mark-element)
21177 (org-mark-element)))
21180 ;;; Macros
21182 ;; Macros are expanded with `org-macro-replace-all', which relies
21183 ;; internally on `org-macro-expand'.
21185 ;; Default templates for expansion are stored in the buffer-local
21186 ;; variable `org-macro-templates'. This variable is updated by
21187 ;; `org-macro-initialize-templates'.
21189 ;; Along with macros defined through #+MACRO: keyword, default
21190 ;; templates include the following hard-coded macros:
21191 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21192 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21194 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21195 ;; {{{title}}} will also be provided.
21198 (defvar org-macro-templates nil
21199 "Alist containing all macro templates in current buffer.
21200 Associations are in the shape of (NAME . TEMPLATE) where NAME
21201 stands for macro's name and template for its replacement value,
21202 both as strings. This is an internal variable. Do not set it
21203 directly, use instead:
21205 #+MACRO: name template")
21206 (make-variable-buffer-local 'org-macro-templates)
21208 (defun org-macro-expand (macro templates)
21209 "Return expanded MACRO, as a string.
21210 MACRO is an object, obtained, for example, with
21211 `org-element-context'. TEMPLATES is an alist of templates used
21212 for expansion. See `org-macro-templates' for a buffer-local
21213 default value. Return nil if no template was found."
21214 (let ((template
21215 ;; Macro names are case-insensitive.
21216 (cdr (assoc-string (org-element-property :key macro) templates t))))
21217 (when template
21218 (let ((value (replace-regexp-in-string
21219 "\\$[0-9]+"
21220 (lambda (arg)
21221 (or (nth (1- (string-to-number (substring arg 1)))
21222 (org-element-property :args macro))
21223 ;; No argument provided: remove
21224 ;; place-holder.
21225 ""))
21226 template)))
21227 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21228 (when (string-match "\\`(eval\\>" value)
21229 (setq value (eval (read value))))
21230 ;; Return string.
21231 (format "%s" (or value ""))))))
21233 (defun org-macro-replace-all (templates)
21234 "Replace all macros in current buffer by their expansion.
21235 TEMPLATES is an alist of templates used for expansion. See
21236 `org-macro-templates' for a buffer-local default value."
21237 (save-excursion
21238 (goto-char (point-min))
21239 (let (record)
21240 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21241 (let ((object (org-element-context)))
21242 (when (eq (org-element-type object) 'macro)
21243 (let* ((value (org-macro-expand object templates))
21244 (begin (org-element-property :begin object))
21245 (signature (list begin
21246 object
21247 (org-element-property :args object))))
21248 ;; Avoid circular dependencies by checking if the same
21249 ;; macro with the same arguments is expanded at the same
21250 ;; position twice.
21251 (if (member signature record)
21252 (error "Circular macro expansion: %s"
21253 (org-element-property :key object))
21254 (when value
21255 (push signature record)
21256 (delete-region
21257 begin
21258 ;; Preserve white spaces after the macro.
21259 (progn (goto-char (org-element-property :end object))
21260 (skip-chars-backward " \t")
21261 (point)))
21262 ;; Leave point before replacement in case of recursive
21263 ;; expansions.
21264 (save-excursion (insert value)))))))))))
21266 (defun org-macro-initialize-templates ()
21267 "Collect macro templates defined in current buffer.
21268 Templates are stored in buffer-local variable
21269 `org-macro-templates'. In addition to buffer-defined macros, the
21270 function installs the following ones: \"property\",
21271 \"time\". and, if the buffer is associated to a file,
21272 \"input-file\" and \"modification-time\"."
21273 (let ((case-fold-search t)
21274 (set-template
21275 (lambda (cell)
21276 ;; Add CELL to `org-macro-templates' if there's no
21277 ;; association matching its name already. Otherwise,
21278 ;; replace old association with the new one in that
21279 ;; variable.
21280 (let ((old-template (assoc (car cell) org-macro-templates)))
21281 (if old-template (setcdr old-template (cdr cell))
21282 (push cell org-macro-templates))))))
21283 ;; Install buffer-local macros.
21284 (org-with-wide-buffer
21285 (goto-char (point-min))
21286 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21287 (let ((element (org-element-at-point)))
21288 (when (eq (org-element-type element) 'keyword)
21289 (let ((value (org-element-property :value element)))
21290 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21291 (funcall set-template
21292 (cons (match-string 1 value)
21293 (or (match-string 2 value) "")))))))))
21294 ;; Install hard-coded macros.
21295 (mapc (lambda (cell) (funcall set-template cell))
21296 (list
21297 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21298 (cons "time" "(eval (format-time-string \"$1\"))")))
21299 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21300 (when (and visited-file (file-exists-p visited-file))
21301 (mapc (lambda (cell) (funcall set-template cell))
21302 (list
21303 (cons "input-file" (file-name-nondirectory visited-file))
21304 (cons "modification-time"
21305 (format "(eval (format-time-string \"$1\" '%s))"
21306 (prin1-to-string
21307 (nth 5 (file-attributes visited-file)))))))))))
21310 ;;; Indentation
21312 (defun org-indent-line ()
21313 "Indent line depending on context."
21314 (interactive)
21315 (let* ((pos (point))
21316 (itemp (org-at-item-p))
21317 (case-fold-search t)
21318 (org-drawer-regexp (or org-drawer-regexp "\000"))
21319 (inline-task-p (and (featurep 'org-inlinetask)
21320 (org-inlinetask-in-task-p)))
21321 (inline-re (and inline-task-p
21322 (org-inlinetask-outline-regexp)))
21323 column)
21324 (if (and orgstruct-is-++ (eq pos (point)))
21325 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21326 (indent-according-to-mode))
21327 (beginning-of-line 1)
21328 (cond
21329 ;; Headings
21330 ((looking-at org-outline-regexp) (setq column 0))
21331 ;; Included files
21332 ((looking-at "#\\+include:") (setq column 0))
21333 ;; Footnote definition
21334 ((looking-at org-footnote-definition-re) (setq column 0))
21335 ;; Literal examples
21336 ((looking-at "[ \t]*:\\( \\|$\\)")
21337 (setq column (org-get-indentation))) ; do nothing
21338 ;; Lists
21339 ((ignore-errors (goto-char (org-in-item-p)))
21340 (setq column (if itemp
21341 (org-get-indentation)
21342 (org-list-item-body-column (point))))
21343 (goto-char pos))
21344 ;; Drawers
21345 ((and (looking-at "[ \t]*:END:")
21346 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21347 (save-excursion
21348 (goto-char (1- (match-beginning 1)))
21349 (setq column (current-column))))
21350 ;; Special blocks
21351 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21352 (save-excursion
21353 (re-search-backward
21354 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21355 (setq column (org-get-indentation (match-string 0))))
21356 ((and (not (looking-at "[ \t]*#\\+begin_"))
21357 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21358 (save-excursion
21359 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21360 (setq column
21361 (cond ((equal (downcase (match-string 1)) "src")
21362 ;; src blocks: let `org-edit-src-exit' handle them
21363 (org-get-indentation))
21364 ((equal (downcase (match-string 1)) "example")
21365 (max (org-get-indentation)
21366 (org-get-indentation (match-string 0))))
21368 (org-get-indentation (match-string 0))))))
21369 ;; This line has nothing special, look at the previous relevant
21370 ;; line to compute indentation
21372 (beginning-of-line 0)
21373 (while (and (not (bobp))
21374 (not (looking-at org-table-line-regexp))
21375 (not (looking-at org-drawer-regexp))
21376 ;; When point started in an inline task, do not move
21377 ;; above task starting line.
21378 (not (and inline-task-p (looking-at inline-re)))
21379 ;; Skip drawers, blocks, empty lines, verbatim,
21380 ;; comments, tables, footnotes definitions, lists,
21381 ;; inline tasks.
21382 (or (and (looking-at "[ \t]*:END:")
21383 (re-search-backward org-drawer-regexp nil t))
21384 (and (looking-at "[ \t]*#\\+end_")
21385 (re-search-backward "[ \t]*#\\+begin_"nil t))
21386 (looking-at "[ \t]*[\n:#|]")
21387 (looking-at org-footnote-definition-re)
21388 (and (ignore-errors (goto-char (org-in-item-p)))
21389 (goto-char
21390 (org-list-get-top-point (org-list-struct))))
21391 (and (not inline-task-p)
21392 (featurep 'org-inlinetask)
21393 (org-inlinetask-in-task-p)
21394 (or (org-inlinetask-goto-beginning) t))))
21395 (beginning-of-line 0))
21396 (cond
21397 ;; There was an heading above.
21398 ((looking-at "\\*+[ \t]+")
21399 (if (not org-adapt-indentation)
21400 (setq column 0)
21401 (goto-char (match-end 0))
21402 (setq column (current-column))))
21403 ;; A drawer had started and is unfinished
21404 ((looking-at org-drawer-regexp)
21405 (goto-char (1- (match-beginning 1)))
21406 (setq column (current-column)))
21407 ;; Else, nothing noticeable found: get indentation and go on.
21408 (t (setq column (org-get-indentation))))))
21409 ;; Now apply indentation and move cursor accordingly
21410 (goto-char pos)
21411 (if (<= (current-column) (current-indentation))
21412 (org-indent-line-to column)
21413 (save-excursion (org-indent-line-to column)))
21414 ;; Special polishing for properties, see `org-property-format'
21415 (setq column (current-column))
21416 (beginning-of-line 1)
21417 (if (looking-at
21418 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21419 (replace-match (concat (match-string 1)
21420 (format org-property-format
21421 (match-string 2) (match-string 3)))
21422 t t))
21423 (org-move-to-column column))))
21425 (defun org-indent-drawer ()
21426 "Indent the drawer at point."
21427 (interactive)
21428 (let ((p (point))
21429 (e (and (save-excursion (re-search-forward ":END:" nil t))
21430 (match-end 0)))
21431 (folded
21432 (save-excursion
21433 (end-of-line)
21434 (when (overlays-at (point))
21435 (member 'invisible (overlay-properties
21436 (car (overlays-at (point)))))))))
21437 (when folded (org-cycle))
21438 (indent-for-tab-command)
21439 (while (and (move-beginning-of-line 2) (< (point) e))
21440 (indent-for-tab-command))
21441 (goto-char p)
21442 (when folded (org-cycle)))
21443 (message "Drawer at point indented"))
21445 (defun org-indent-block ()
21446 "Indent the block at point."
21447 (interactive)
21448 (let ((p (point))
21449 (case-fold-search t)
21450 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21451 (match-end 0)))
21452 (folded
21453 (save-excursion
21454 (end-of-line)
21455 (when (overlays-at (point))
21456 (member 'invisible (overlay-properties
21457 (car (overlays-at (point)))))))))
21458 (when folded (org-cycle))
21459 (indent-for-tab-command)
21460 (while (and (move-beginning-of-line 2) (< (point) e))
21461 (indent-for-tab-command))
21462 (goto-char p)
21463 (when folded (org-cycle)))
21464 (message "Block at point indented"))
21466 (defun org-indent-region (start end)
21467 "Indent region."
21468 (interactive "r")
21469 (save-excursion
21470 (let ((line-end (org-current-line end)))
21471 (goto-char start)
21472 (while (< (org-current-line) line-end)
21473 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21474 (t (call-interactively 'org-indent-line)))
21475 (move-beginning-of-line 2)))))
21478 ;;; Filling
21480 ;; We use our own fill-paragraph and auto-fill functions.
21482 ;; `org-fill-paragraph' relies on adaptive filling and context
21483 ;; checking. Appropriate `fill-prefix' is computed with
21484 ;; `org-adaptive-fill-function'.
21486 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21487 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21488 ;; `org-adaptive-fill-function' value. Internally,
21489 ;; `org-comment-line-break-function' breaks the line.
21491 ;; `org-setup-filling' installs filling and auto-filling related
21492 ;; variables during `org-mode' initialization.
21494 (defun org-setup-filling ()
21495 (interactive)
21496 ;; Prevent auto-fill from inserting unwanted new items.
21497 (when (boundp 'fill-nobreak-predicate)
21498 (org-set-local
21499 'fill-nobreak-predicate
21500 (org-uniquify
21501 (append fill-nobreak-predicate
21502 '(org-fill-paragraph-separate-nobreak-p
21503 org-fill-line-break-nobreak-p)))))
21504 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21505 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21506 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21507 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21509 (defvar org-element-paragraph-separate) ; org-element.el
21510 (defun org-fill-paragraph-separate-nobreak-p ()
21511 "Non-nil when a line break at point would insert a new item."
21512 (looking-at (substring org-element-paragraph-separate 1)))
21514 (defun org-fill-line-break-nobreak-p ()
21515 "Non-nil when a line break at point would create an Org line break."
21516 (save-excursion
21517 (skip-chars-backward "[ \t]")
21518 (skip-chars-backward "\\\\")
21519 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21521 (declare-function message-in-body-p "message" ())
21522 (defun org-adaptive-fill-function ()
21523 "Compute a fill prefix for the current line.
21524 Return fill prefix, as a string, or nil if current line isn't
21525 meant to be filled."
21526 (let (prefix)
21527 (when (and (derived-mode-p 'message-mode) (message-in-body-p))
21528 (save-excursion
21529 (beginning-of-line)
21530 (cond ((looking-at message-cite-prefix-regexp)
21531 (setq prefix (match-string-no-properties 0)))
21532 ((looking-at org-outline-regexp)
21533 (setq prefix "")))))
21534 (or prefix
21535 (org-with-wide-buffer
21536 (let* ((p (line-beginning-position))
21537 (element (save-excursion (beginning-of-line)
21538 (org-element-at-point)))
21539 (type (org-element-type element))
21540 (post-affiliated (org-element-property :post-affiliated element)))
21541 (unless (and post-affiliated (< p post-affiliated))
21542 (case type
21543 (comment (looking-at "[ \t]*# ?") (match-string 0))
21544 (footnote-definition "")
21545 ((item plain-list)
21546 (make-string (org-list-item-body-column
21547 (or post-affiliated
21548 (org-element-property :begin element)))
21549 ? ))
21550 (paragraph
21551 ;; Fill prefix is usually the same as the current line,
21552 ;; except if the paragraph is at the beginning of an item.
21553 (let ((parent (org-element-property :parent element)))
21554 (cond ((eq (org-element-type parent) 'item)
21555 (make-string (org-list-item-body-column
21556 (org-element-property :begin parent))
21557 ? ))
21558 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21559 (match-string 0))
21560 (t ""))))
21561 (comment-block
21562 ;; Only fill contents if P is within block boundaries.
21563 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21564 (forward-line)
21565 (point)))
21566 (cend (save-excursion
21567 (goto-char (org-element-property :end element))
21568 (skip-chars-backward " \r\t\n")
21569 (line-beginning-position))))
21570 (when (and (>= p cbeg) (< p cend))
21571 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21572 (match-string 0)
21573 "")))))))))))
21575 (declare-function message-goto-body "message" ())
21576 (defvar message-cite-prefix-regexp) ; From message.el
21577 (defvar org-element-all-objects) ; From org-element.el
21578 (defun org-fill-paragraph (&optional justify)
21579 "Fill element at point, when applicable.
21581 This function only applies to comment blocks, comments, example
21582 blocks and paragraphs. Also, as a special case, re-align table
21583 when point is at one.
21585 If JUSTIFY is non-nil (interactively, with prefix argument),
21586 justify as well. If `sentence-end-double-space' is non-nil, then
21587 period followed by one space does not end a sentence, so don't
21588 break a line there. The variable `fill-column' controls the
21589 width for filling.
21591 For convenience, when point is at a plain list, an item or
21592 a footnote definition, try to fill the first paragraph within."
21593 (interactive)
21594 (if (and (derived-mode-p 'message-mode)
21595 (or (not (message-in-body-p))
21596 (save-excursion (move-beginning-of-line 1)
21597 (looking-at message-cite-prefix-regexp))))
21598 ;; First ensure filling is correct in message-mode.
21599 (let ((fill-paragraph-function
21600 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21601 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21602 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21603 (paragraph-separate
21604 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21605 (fill-paragraph nil))
21606 (save-excursion
21607 ;; Move to end of line in order to get the first paragraph
21608 ;; within a plain list or a footnote definition.
21609 (end-of-line)
21610 (let ((element (org-element-at-point)))
21611 ;; First check if point is in a blank line at the beginning of
21612 ;; the buffer. In that case, ignore filling.
21613 (if (< (point) (org-element-property :begin element)) t
21614 (case (org-element-type element)
21615 ;; Use major mode filling function is src blocks.
21616 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21617 ;; Align Org tables, leave table.el tables as-is.
21618 (table-row (org-table-align) t)
21619 (table
21620 (when (eq (org-element-property :type element) 'org)
21621 (org-table-align))
21623 (paragraph
21624 ;; Paragraphs may contain `line-break' type objects.
21625 (let ((beg (max (point-min)
21626 (org-element-property :contents-begin element)))
21627 (end (min (point-max)
21628 (org-element-property :contents-end element))))
21629 ;; Do nothing if point is at an affiliated keyword.
21630 (if (< (point) beg) t
21631 (when (derived-mode-p 'message-mode)
21632 ;; In `message-mode', do not fill following
21633 ;; citation in current paragraph nor text before
21634 ;; message body.
21635 (let ((body-start (save-excursion (message-goto-body))))
21636 (when body-start (setq beg (max body-start beg))))
21637 (when (save-excursion
21638 (re-search-forward
21639 (concat "^" message-cite-prefix-regexp) end t))
21640 (setq end (match-beginning 0))))
21641 ;; Fill paragraph, taking line breaks into
21642 ;; consideration. For that, slice the paragraph
21643 ;; using line breaks as separators, and fill the
21644 ;; parts in reverse order to avoid messing with
21645 ;; markers.
21646 (save-excursion
21647 (goto-char end)
21648 (mapc
21649 (lambda (pos)
21650 (fill-region-as-paragraph pos (point) justify)
21651 (goto-char pos))
21652 ;; Find the list of ending positions for line
21653 ;; breaks in the current paragraph. Add paragraph
21654 ;; beginning to include first slice.
21655 (nreverse
21656 (cons
21658 (org-element-map
21659 (org-element--parse-objects
21660 beg end nil org-element-all-objects)
21661 'line-break
21662 (lambda (lb) (org-element-property :end lb)))))))
21663 t)))
21664 ;; Contents of `comment-block' type elements should be
21665 ;; filled as plain text, but only if point is within block
21666 ;; markers.
21667 (comment-block
21668 (let* ((case-fold-search t)
21669 (beg (save-excursion
21670 (goto-char (org-element-property :begin element))
21671 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21672 (forward-line)
21673 (point)))
21674 (end (save-excursion
21675 (goto-char (org-element-property :end element))
21676 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21677 (line-beginning-position))))
21678 (when (and (>= (point) beg) (< (point) end))
21679 (fill-region-as-paragraph
21680 (save-excursion
21681 (end-of-line)
21682 (re-search-backward "^[ \t]*$" beg 'move)
21683 (line-beginning-position))
21684 (save-excursion
21685 (beginning-of-line)
21686 (re-search-forward "^[ \t]*$" end 'move)
21687 (line-beginning-position))
21688 justify)))
21690 ;; Fill comments.
21691 (comment (fill-comment-paragraph justify))
21692 ;; Ignore every other element.
21693 (otherwise t)))))))
21695 (defun org-auto-fill-function ()
21696 "Auto-fill function."
21697 ;; Check if auto-filling is meaningful.
21698 (let ((fc (current-fill-column)))
21699 (when (and fc (> (current-column) fc))
21700 (let* ((fill-prefix (org-adaptive-fill-function))
21701 ;; Enforce empty fill prefix, if required. Otherwise, it
21702 ;; will be computed again.
21703 (adaptive-fill-mode (not (equal fill-prefix ""))))
21704 (when fill-prefix (do-auto-fill))))))
21706 (defun org-comment-line-break-function (&optional soft)
21707 "Break line at point and indent, continuing comment if within one.
21708 The inserted newline is marked hard if variable
21709 `use-hard-newlines' is true, unless optional argument SOFT is
21710 non-nil."
21711 (if soft (insert-and-inherit ?\n) (newline 1))
21712 (save-excursion (forward-char -1) (delete-horizontal-space))
21713 (delete-horizontal-space)
21714 (indent-to-left-margin)
21715 (insert-before-markers-and-inherit fill-prefix))
21718 ;;; Comments
21720 ;; Org comments syntax is quite complex. It requires the entire line
21721 ;; to be just a comment. Also, even with the right syntax at the
21722 ;; beginning of line, some some elements (i.e. verse-block or
21723 ;; example-block) don't accept comments. Usual Emacs comment commands
21724 ;; cannot cope with those requirements. Therefore, Org replaces them.
21726 ;; Org still relies on `comment-dwim', but cannot trust
21727 ;; `comment-only-p'. So, `comment-region-function' and
21728 ;; `uncomment-region-function' both point
21729 ;; to`org-comment-or-uncomment-region'. Eventually,
21730 ;; `org-insert-comment' takes care of insertion of comments at the
21731 ;; beginning of line.
21733 ;; `org-setup-comments-handling' install comments related variables
21734 ;; during `org-mode' initialization.
21736 (defun org-setup-comments-handling ()
21737 (interactive)
21738 (org-set-local 'comment-use-syntax nil)
21739 (org-set-local 'comment-start "# ")
21740 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21741 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21742 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21743 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21745 (defun org-insert-comment ()
21746 "Insert an empty comment above current line.
21747 If the line is empty, insert comment at its beginning."
21748 (beginning-of-line)
21749 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21750 (org-indent-line)
21751 (insert "# "))
21753 (defvar comment-empty-lines) ; From newcomment.el.
21754 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21755 "Comment or uncomment each non-blank line in the region.
21756 Uncomment each non-blank line between BEG and END if it only
21757 contains commented lines. Otherwise, comment them."
21758 (save-restriction
21759 ;; Restrict region
21760 (narrow-to-region (save-excursion (goto-char beg)
21761 (skip-chars-forward " \r\t\n" end)
21762 (line-beginning-position))
21763 (save-excursion (goto-char end)
21764 (skip-chars-backward " \r\t\n" beg)
21765 (line-end-position)))
21766 (let ((uncommentp
21767 ;; UNCOMMENTP is non-nil when every non blank line between
21768 ;; BEG and END is a comment.
21769 (save-excursion
21770 (goto-char (point-min))
21771 (while (and (not (eobp))
21772 (let ((element (org-element-at-point)))
21773 (and (eq (org-element-type element) 'comment)
21774 (goto-char (min (point-max)
21775 (org-element-property
21776 :end element)))))))
21777 (eobp))))
21778 (if uncommentp
21779 ;; Only blank lines and comments in region: uncomment it.
21780 (save-excursion
21781 (goto-char (point-min))
21782 (while (not (eobp))
21783 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21784 (replace-match "" nil nil nil 1))
21785 (forward-line)))
21786 ;; Comment each line in region.
21787 (let ((min-indent (point-max)))
21788 ;; First find the minimum indentation across all lines.
21789 (save-excursion
21790 (goto-char (point-min))
21791 (while (and (not (eobp)) (not (zerop min-indent)))
21792 (unless (looking-at "[ \t]*$")
21793 (setq min-indent (min min-indent (current-indentation))))
21794 (forward-line)))
21795 ;; Then loop over all lines.
21796 (save-excursion
21797 (goto-char (point-min))
21798 (while (not (eobp))
21799 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21800 (org-move-to-column min-indent t)
21801 (insert comment-start))
21802 (forward-line))))))))
21805 ;;; Other stuff.
21807 (defun org-toggle-fixed-width-section (arg)
21808 "Toggle the fixed-width export.
21809 If there is no active region, the QUOTE keyword at the current headline is
21810 inserted or removed. When present, it causes the text between this headline
21811 and the next to be exported as fixed-width text, and unmodified.
21812 If there is an active region, this command adds or removes a colon as the
21813 first character of this line. If the first character of a line is a colon,
21814 this line is also exported in fixed-width font."
21815 (interactive "P")
21816 (let* ((cc 0)
21817 (regionp (org-region-active-p))
21818 (beg (if regionp (region-beginning) (point)))
21819 (end (if regionp (region-end)))
21820 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21821 (case-fold-search nil)
21822 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21823 off)
21824 (if regionp
21825 (save-excursion
21826 (goto-char beg)
21827 (setq cc (current-column))
21828 (beginning-of-line 1)
21829 (setq off (looking-at re))
21830 (while (> nlines 0)
21831 (setq nlines (1- nlines))
21832 (beginning-of-line 1)
21833 (cond
21834 (arg
21835 (org-move-to-column cc t)
21836 (insert ": \n")
21837 (forward-line -1))
21838 ((and off (looking-at re))
21839 (replace-match "" t t nil 1))
21840 ((not off) (org-move-to-column cc t) (insert ": ")))
21841 (forward-line 1)))
21842 (save-excursion
21843 (org-back-to-heading)
21844 (cond
21845 ((looking-at (format org-heading-keyword-regexp-format
21846 org-quote-string))
21847 (goto-char (match-end 1))
21848 (looking-at (concat " +" org-quote-string))
21849 (replace-match "" t t)
21850 (when (eolp) (insert " ")))
21851 ((looking-at org-outline-regexp)
21852 (goto-char (match-end 0))
21853 (insert org-quote-string " ")))))))
21855 (defun org-reftex-citation ()
21856 "Use reftex-citation to insert a citation into the buffer.
21857 This looks for a line like
21859 #+BIBLIOGRAPHY: foo plain option:-d
21861 and derives from it that foo.bib is the bibliography file relevant
21862 for this document. It then installs the necessary environment for RefTeX
21863 to work in this buffer and calls `reftex-citation' to insert a citation
21864 into the buffer.
21866 Export of such citations to both LaTeX and HTML is handled by the contributed
21867 package org-exp-bibtex by Taru Karttunen."
21868 (interactive)
21869 (let ((reftex-docstruct-symbol 'rds)
21870 (reftex-cite-format "\\cite{%l}")
21871 rds bib)
21872 (save-excursion
21873 (save-restriction
21874 (widen)
21875 (let ((case-fold-search t)
21876 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21877 (if (not (save-excursion
21878 (or (re-search-forward re nil t)
21879 (re-search-backward re nil t))))
21880 (error "No bibliography defined in file")
21881 (setq bib (concat (match-string 1) ".bib")
21882 rds (list (list 'bib bib)))))))
21883 (call-interactively 'reftex-citation)))
21885 ;;;; Functions extending outline functionality
21887 (defun org-beginning-of-line (&optional arg)
21888 "Go to the beginning of the current line. If that is invisible, continue
21889 to a visible line beginning. This makes the function of C-a more intuitive.
21890 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21891 first attempt, and only move to after the tags when the cursor is already
21892 beyond the end of the headline."
21893 (interactive "P")
21894 (let ((pos (point))
21895 (special (if (consp org-special-ctrl-a/e)
21896 (car org-special-ctrl-a/e)
21897 org-special-ctrl-a/e))
21898 refpos)
21899 (if (org-bound-and-true-p visual-line-mode)
21900 (beginning-of-visual-line 1)
21901 (beginning-of-line 1))
21902 (if (and arg (fboundp 'move-beginning-of-line))
21903 (call-interactively 'move-beginning-of-line)
21904 (if (bobp)
21906 (backward-char 1)
21907 (if (org-truely-invisible-p)
21908 (while (and (not (bobp)) (org-truely-invisible-p))
21909 (backward-char 1)
21910 (beginning-of-line 1))
21911 (forward-char 1))))
21912 (when special
21913 (cond
21914 ((and (looking-at org-complex-heading-regexp)
21915 (= (char-after (match-end 1)) ?\ ))
21916 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21917 (point-at-eol)))
21918 (goto-char
21919 (if (eq special t)
21920 (cond ((> pos refpos) refpos)
21921 ((= pos (point)) refpos)
21922 (t (point)))
21923 (cond ((> pos (point)) (point))
21924 ((not (eq last-command this-command)) (point))
21925 (t refpos)))))
21926 ((org-at-item-p)
21927 ;; Being at an item and not looking at an the item means point
21928 ;; was previously moved to beginning of a visual line, which
21929 ;; doesn't contain the item. Therefore, do nothing special,
21930 ;; just stay here.
21931 (when (looking-at org-list-full-item-re)
21932 ;; Set special position at first white space character after
21933 ;; bullet, and check-box, if any.
21934 (let ((after-bullet
21935 (let ((box (match-end 3)))
21936 (if (not box) (match-end 1)
21937 (let ((after (char-after box)))
21938 (if (and after (= after ? )) (1+ box) box))))))
21939 ;; Special case: Move point to special position when
21940 ;; currently after it or at beginning of line.
21941 (if (eq special t)
21942 (when (or (> pos after-bullet) (= (point) pos))
21943 (goto-char after-bullet))
21944 ;; Reversed case: Move point to special position when
21945 ;; point was already at beginning of line and command is
21946 ;; repeated.
21947 (when (and (= (point) pos) (eq last-command this-command))
21948 (goto-char after-bullet))))))))
21949 (org-no-warnings
21950 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21952 (defun org-end-of-line (&optional arg)
21953 "Go to the end of the line.
21954 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21955 tags on the first attempt, and only move to after the tags when
21956 the cursor is already beyond the end of the headline."
21957 (interactive "P")
21958 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21959 org-special-ctrl-a/e))
21960 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21961 'end-of-visual-line)
21962 ((fboundp 'move-end-of-line) 'move-end-of-line)
21963 (t 'end-of-line))))
21964 (if (or (not special) arg) (call-interactively move-fun)
21965 (let* ((element (save-excursion (beginning-of-line)
21966 (org-element-at-point)))
21967 (type (org-element-type element)))
21968 (cond
21969 ((memq type '(headline inlinetask))
21970 (let ((pos (point)))
21971 (beginning-of-line 1)
21972 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21973 (if (eq special t)
21974 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21975 (goto-char (match-beginning 1))
21976 (goto-char (match-end 0)))
21977 (if (or (< pos (match-end 0))
21978 (not (eq this-command last-command)))
21979 (goto-char (match-end 0))
21980 (goto-char (match-beginning 1))))
21981 (call-interactively move-fun))))
21982 ((org-element-property :hiddenp element)
21983 ;; If element is hidden, `move-end-of-line' would put point
21984 ;; after it. Use `end-of-line' to stay on current line.
21985 (call-interactively 'end-of-line))
21986 (t (call-interactively move-fun)))))
21987 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21989 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21990 (define-key org-mode-map "\C-e" 'org-end-of-line)
21992 (defun org-backward-sentence (&optional arg)
21993 "Go to beginning of sentence, or beginning of table field.
21994 This will call `backward-sentence' or `org-table-beginning-of-field',
21995 depending on context."
21996 (interactive "P")
21997 (cond
21998 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21999 (t (call-interactively 'backward-sentence))))
22001 (defun org-forward-sentence (&optional arg)
22002 "Go to end of sentence, or end of table field.
22003 This will call `forward-sentence' or `org-table-end-of-field',
22004 depending on context."
22005 (interactive "P")
22006 (cond
22007 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22008 (t (call-interactively 'forward-sentence))))
22010 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22011 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22013 (defun org-kill-line (&optional arg)
22014 "Kill line, to tags or end of line."
22015 (interactive "P")
22016 (cond
22017 ((or (not org-special-ctrl-k)
22018 (bolp)
22019 (not (org-at-heading-p)))
22020 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22021 org-ctrl-k-protect-subtree)
22022 (if (or (eq org-ctrl-k-protect-subtree 'error)
22023 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22024 (error "C-k aborted - would kill hidden subtree")))
22025 (call-interactively
22026 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22027 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22028 (kill-region (point) (match-beginning 1))
22029 (org-set-tags nil t))
22030 (t (kill-region (point) (point-at-eol)))))
22032 (define-key org-mode-map "\C-k" 'org-kill-line)
22034 (defun org-yank (&optional arg)
22035 "Yank. If the kill is a subtree, treat it specially.
22036 This command will look at the current kill and check if is a single
22037 subtree, or a series of subtrees[1]. If it passes the test, and if the
22038 cursor is at the beginning of a line or after the stars of a currently
22039 empty headline, then the yank is handled specially. How exactly depends
22040 on the value of the following variables, both set by default.
22042 org-yank-folded-subtrees
22043 When set, the subtree(s) will be folded after insertion, but only
22044 if doing so would now swallow text after the yanked text.
22046 org-yank-adjusted-subtrees
22047 When set, the subtree will be promoted or demoted in order to
22048 fit into the local outline tree structure, which means that the level
22049 will be adjusted so that it becomes the smaller one of the two
22050 *visible* surrounding headings.
22052 Any prefix to this command will cause `yank' to be called directly with
22053 no special treatment. In particular, a simple \\[universal-argument] prefix \
22054 will just
22055 plainly yank the text as it is.
22057 \[1] The test checks if the first non-white line is a heading
22058 and if there are no other headings with fewer stars."
22059 (interactive "P")
22060 (org-yank-generic 'yank arg))
22062 (defun org-yank-generic (command arg)
22063 "Perform some yank-like command.
22065 This function implements the behavior described in the `org-yank'
22066 documentation. However, it has been generalized to work for any
22067 interactive command with similar behavior."
22069 ;; pretend to be command COMMAND
22070 (setq this-command command)
22072 (if arg
22073 (call-interactively command)
22075 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22076 (and (org-kill-is-subtree-p)
22077 (or (bolp)
22078 (and (looking-at "[ \t]*$")
22079 (string-match
22080 "\\`\\*+\\'"
22081 (buffer-substring (point-at-bol) (point)))))))
22082 swallowp)
22083 (cond
22084 ((and subtreep org-yank-folded-subtrees)
22085 (let ((beg (point))
22086 end)
22087 (if (and subtreep org-yank-adjusted-subtrees)
22088 (org-paste-subtree nil nil 'for-yank)
22089 (call-interactively command))
22091 (setq end (point))
22092 (goto-char beg)
22093 (when (and (bolp) subtreep
22094 (not (setq swallowp
22095 (org-yank-folding-would-swallow-text beg end))))
22096 (org-with-limited-levels
22097 (or (looking-at org-outline-regexp)
22098 (re-search-forward org-outline-regexp-bol end t))
22099 (while (and (< (point) end) (looking-at org-outline-regexp))
22100 (hide-subtree)
22101 (org-cycle-show-empty-lines 'folded)
22102 (condition-case nil
22103 (outline-forward-same-level 1)
22104 (error (goto-char end))))))
22105 (when swallowp
22106 (message
22107 "Inserted text not folded because that would swallow text"))
22109 (goto-char end)
22110 (skip-chars-forward " \t\n\r")
22111 (beginning-of-line 1)
22112 (push-mark beg 'nomsg)))
22113 ((and subtreep org-yank-adjusted-subtrees)
22114 (let ((beg (point-at-bol)))
22115 (org-paste-subtree nil nil 'for-yank)
22116 (push-mark beg 'nomsg)))
22118 (call-interactively command))))))
22120 (defun org-yank-folding-would-swallow-text (beg end)
22121 "Would hide-subtree at BEG swallow any text after END?"
22122 (let (level)
22123 (org-with-limited-levels
22124 (save-excursion
22125 (goto-char beg)
22126 (when (or (looking-at org-outline-regexp)
22127 (re-search-forward org-outline-regexp-bol end t))
22128 (setq level (org-outline-level)))
22129 (goto-char end)
22130 (skip-chars-forward " \t\r\n\v\f")
22131 (if (or (eobp)
22132 (and (bolp) (looking-at org-outline-regexp)
22133 (<= (org-outline-level) level)))
22134 nil ; Nothing would be swallowed
22135 t))))) ; something would swallow
22137 (define-key org-mode-map "\C-y" 'org-yank)
22139 (defun org-truely-invisible-p ()
22140 "Check if point is at a character currently not visible.
22141 This version does not only check the character property, but also
22142 `visible-mode'."
22143 ;; Early versions of noutline don't have `outline-invisible-p'.
22144 (if (org-bound-and-true-p visible-mode)
22146 (outline-invisible-p)))
22148 (defun org-invisible-p2 ()
22149 "Check if point is at a character currently not visible."
22150 (save-excursion
22151 (if (and (eolp) (not (bobp))) (backward-char 1))
22152 ;; Early versions of noutline don't have `outline-invisible-p'.
22153 (outline-invisible-p)))
22155 (defun org-back-to-heading (&optional invisible-ok)
22156 "Call `outline-back-to-heading', but provide a better error message."
22157 (condition-case nil
22158 (outline-back-to-heading invisible-ok)
22159 (error (error "Before first headline at position %d in buffer %s"
22160 (point) (current-buffer)))))
22162 (defun org-before-first-heading-p ()
22163 "Before first heading?"
22164 (save-excursion
22165 (end-of-line)
22166 (null (re-search-backward org-outline-regexp-bol nil t))))
22168 (defun org-at-heading-p (&optional ignored)
22169 (outline-on-heading-p t))
22170 ;; Compatibility alias with Org versions < 7.8.03
22171 (defalias 'org-on-heading-p 'org-at-heading-p)
22173 (defun org-at-comment-p nil
22174 "Is cursor in a line starting with a # character?"
22175 (save-excursion
22176 (beginning-of-line)
22177 (looking-at "^#")))
22179 (defun org-at-drawer-p nil
22180 "Is cursor at a drawer keyword?"
22181 (save-excursion
22182 (move-beginning-of-line 1)
22183 (looking-at org-drawer-regexp)))
22185 (defun org-at-block-p nil
22186 "Is cursor at a block keyword?"
22187 (save-excursion
22188 (move-beginning-of-line 1)
22189 (looking-at org-block-regexp)))
22191 (defun org-point-at-end-of-empty-headline ()
22192 "If point is at the end of an empty headline, return t, else nil.
22193 If the heading only contains a TODO keyword, it is still still considered
22194 empty."
22195 (and (looking-at "[ \t]*$")
22196 (when org-todo-line-regexp
22197 (save-excursion
22198 (beginning-of-line 1)
22199 (let ((case-fold-search nil))
22200 (looking-at org-todo-line-regexp)
22201 (string= (match-string 3) ""))))))
22203 (defun org-at-heading-or-item-p ()
22204 (or (org-at-heading-p) (org-at-item-p)))
22206 (defun org-at-target-p ()
22207 (or (org-in-regexp org-radio-target-regexp)
22208 (org-in-regexp org-target-regexp)))
22209 ;; Compatibility alias with Org versions < 7.8.03
22210 (defalias 'org-on-target-p 'org-at-target-p)
22212 (defun org-up-heading-all (arg)
22213 "Move to the heading line of which the present line is a subheading.
22214 This function considers both visible and invisible heading lines.
22215 With argument, move up ARG levels."
22216 (if (fboundp 'outline-up-heading-all)
22217 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22218 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22220 (defun org-up-heading-safe ()
22221 "Move to the heading line of which the present line is a subheading.
22222 This version will not throw an error. It will return the level of the
22223 headline found, or nil if no higher level is found.
22225 Also, this function will be a lot faster than `outline-up-heading',
22226 because it relies on stars being the outline starters. This can really
22227 make a significant difference in outlines with very many siblings."
22228 (let (start-level re)
22229 (org-back-to-heading t)
22230 (setq start-level (funcall outline-level))
22231 (if (equal start-level 1)
22233 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22234 (if (re-search-backward re nil t)
22235 (funcall outline-level)))))
22237 (defun org-first-sibling-p ()
22238 "Is this heading the first child of its parents?"
22239 (interactive)
22240 (let ((re org-outline-regexp-bol)
22241 level l)
22242 (unless (org-at-heading-p t)
22243 (error "Not at a heading"))
22244 (setq level (funcall outline-level))
22245 (save-excursion
22246 (if (not (re-search-backward re nil t))
22248 (setq l (funcall outline-level))
22249 (< l level)))))
22251 (defun org-goto-sibling (&optional previous)
22252 "Goto the next sibling, even if it is invisible.
22253 When PREVIOUS is set, go to the previous sibling instead. Returns t
22254 when a sibling was found. When none is found, return nil and don't
22255 move point."
22256 (let ((fun (if previous 're-search-backward 're-search-forward))
22257 (pos (point))
22258 (re org-outline-regexp-bol)
22259 level l)
22260 (when (condition-case nil (org-back-to-heading t) (error nil))
22261 (setq level (funcall outline-level))
22262 (catch 'exit
22263 (or previous (forward-char 1))
22264 (while (funcall fun re nil t)
22265 (setq l (funcall outline-level))
22266 (when (< l level) (goto-char pos) (throw 'exit nil))
22267 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22268 (goto-char pos)
22269 nil))))
22271 (defun org-show-siblings ()
22272 "Show all siblings of the current headline."
22273 (save-excursion
22274 (while (org-goto-sibling) (org-flag-heading nil)))
22275 (save-excursion
22276 (while (org-goto-sibling 'previous)
22277 (org-flag-heading nil))))
22279 (defun org-goto-first-child ()
22280 "Goto the first child, even if it is invisible.
22281 Return t when a child was found. Otherwise don't move point and
22282 return nil."
22283 (let (level (pos (point)) (re org-outline-regexp-bol))
22284 (when (condition-case nil (org-back-to-heading t) (error nil))
22285 (setq level (outline-level))
22286 (forward-char 1)
22287 (if (and (re-search-forward re nil t) (> (outline-level) level))
22288 (progn (goto-char (match-beginning 0)) t)
22289 (goto-char pos) nil))))
22291 (defun org-show-hidden-entry ()
22292 "Show an entry where even the heading is hidden."
22293 (save-excursion
22294 (org-show-entry)))
22296 (defun org-flag-heading (flag &optional entry)
22297 "Flag the current heading. FLAG non-nil means make invisible.
22298 When ENTRY is non-nil, show the entire entry."
22299 (save-excursion
22300 (org-back-to-heading t)
22301 ;; Check if we should show the entire entry
22302 (if entry
22303 (progn
22304 (org-show-entry)
22305 (save-excursion
22306 (and (outline-next-heading)
22307 (org-flag-heading nil))))
22308 (outline-flag-region (max (point-min) (1- (point)))
22309 (save-excursion (outline-end-of-heading) (point))
22310 flag))))
22312 (defun org-get-next-sibling ()
22313 "Move to next heading of the same level, and return point.
22314 If there is no such heading, return nil.
22315 This is like outline-next-sibling, but invisible headings are ok."
22316 (let ((level (funcall outline-level)))
22317 (outline-next-heading)
22318 (while (and (not (eobp)) (> (funcall outline-level) level))
22319 (outline-next-heading))
22320 (if (or (eobp) (< (funcall outline-level) level))
22322 (point))))
22324 (defun org-get-last-sibling ()
22325 "Move to previous heading of the same level, and return point.
22326 If there is no such heading, return nil."
22327 (let ((opoint (point))
22328 (level (funcall outline-level)))
22329 (outline-previous-heading)
22330 (when (and (/= (point) opoint) (outline-on-heading-p t))
22331 (while (and (> (funcall outline-level) level)
22332 (not (bobp)))
22333 (outline-previous-heading))
22334 (if (< (funcall outline-level) level)
22336 (point)))))
22338 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22339 "Goto to the end of a subtree."
22340 ;; This contains an exact copy of the original function, but it uses
22341 ;; `org-back-to-heading', to make it work also in invisible
22342 ;; trees. And is uses an invisible-ok argument.
22343 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22344 ;; Furthermore, when used inside Org, finding the end of a large subtree
22345 ;; with many children and grandchildren etc, this can be much faster
22346 ;; than the outline version.
22347 (org-back-to-heading invisible-ok)
22348 (let ((first t)
22349 (level (funcall outline-level)))
22350 (if (and (derived-mode-p 'org-mode) (< level 1000))
22351 ;; A true heading (not a plain list item), in Org-mode
22352 ;; This means we can easily find the end by looking
22353 ;; only for the right number of stars. Using a regexp to do
22354 ;; this is so much faster than using a Lisp loop.
22355 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22356 (forward-char 1)
22357 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22358 ;; something else, do it the slow way
22359 (while (and (not (eobp))
22360 (or first (> (funcall outline-level) level)))
22361 (setq first nil)
22362 (outline-next-heading)))
22363 (unless to-heading
22364 (if (memq (preceding-char) '(?\n ?\^M))
22365 (progn
22366 ;; Go to end of line before heading
22367 (forward-char -1)
22368 (if (memq (preceding-char) '(?\n ?\^M))
22369 ;; leave blank line before heading
22370 (forward-char -1))))))
22371 (point))
22373 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22374 "Use Org version in org-mode, for dramatic speed-up."
22375 (if (derived-mode-p 'org-mode)
22376 (progn
22377 (org-end-of-subtree nil t)
22378 (unless (eobp) (backward-char 1)))
22379 ad-do-it))
22381 (defun org-end-of-meta-data-and-drawers ()
22382 "Jump to the first text after meta data and drawers in the current entry.
22383 This will move over empty lines, lines with planning time stamps,
22384 clocking lines, and drawers."
22385 (org-back-to-heading t)
22386 (let ((end (save-excursion (outline-next-heading) (point)))
22387 (re (concat "\\(" org-drawer-regexp "\\)"
22388 "\\|" "[ \t]*" org-keyword-time-regexp)))
22389 (forward-line 1)
22390 (while (re-search-forward re end t)
22391 (if (not (match-end 1))
22392 ;; empty or planning line
22393 (forward-line 1)
22394 ;; a drawer, find the end
22395 (re-search-forward "^[ \t]*:END:" end 'move)
22396 (forward-line 1)))
22397 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22398 (point)))
22400 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22401 "Move forward to the arg'th subheading at same level as this one.
22402 Stop at the first and last subheadings of a superior heading.
22403 Normally this only looks at visible headings, but when INVISIBLE-OK is
22404 non-nil it will also look at invisible ones."
22405 (interactive "p")
22406 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22407 (outline-next-heading)
22408 (org-at-heading-p)
22409 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22410 (re (format "^\\*\\{1,%d\\} " level))
22412 (forward-char 1)
22413 (while (> arg 0)
22414 (while (and (re-search-forward re nil 'move)
22415 (setq l (- (match-end 0) (match-beginning 0) 1))
22416 (= l level)
22417 (not invisible-ok)
22418 (progn (backward-char 1) (outline-invisible-p)))
22419 (if (< l level) (setq arg 1)))
22420 (setq arg (1- arg)))
22421 (beginning-of-line 1))))
22423 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22424 "Move backward to the arg'th subheading at same level as this one.
22425 Stop at the first and last subheadings of a superior heading."
22426 (interactive "p")
22427 (if (not (ignore-errors (org-back-to-heading)))
22428 (goto-char (point-min))
22429 (org-at-heading-p)
22430 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22431 (re (format "^\\*\\{1,%d\\} " level))
22433 (while (> arg 0)
22434 (while (and (re-search-backward re nil 'move)
22435 (setq l (- (match-end 0) (match-beginning 0) 1))
22436 (= l level)
22437 (not invisible-ok)
22438 (outline-invisible-p))
22439 (if (< l level) (setq arg 1)))
22440 (setq arg (1- arg))))))
22442 (defun org-forward-element ()
22443 "Move forward by one element.
22444 Move to the next element at the same level, when possible."
22445 (interactive)
22446 (cond ((eobp) (error "Cannot move further down"))
22447 ((org-with-limited-levels (org-at-heading-p))
22448 (let ((origin (point)))
22449 (org-forward-heading-same-level 1)
22450 (unless (org-with-limited-levels (org-at-heading-p))
22451 (goto-char origin)
22452 (error "Cannot move further down"))))
22454 (let* ((elem (org-element-at-point))
22455 (end (org-element-property :end elem))
22456 (parent (org-element-property :parent elem)))
22457 (if (and parent (= (org-element-property :contents-end parent) end))
22458 (goto-char (org-element-property :end parent))
22459 (goto-char end))))))
22461 (defun org-backward-element ()
22462 "Move backward by one element.
22463 Move to the previous element at the same level, when possible."
22464 (interactive)
22465 (cond ((bobp) (error "Cannot move further up"))
22466 ((org-with-limited-levels (org-at-heading-p))
22467 ;; At an headline, move to the previous one, if any, or stay
22468 ;; here.
22469 (let ((origin (point)))
22470 (org-backward-heading-same-level 1)
22471 (unless (org-with-limited-levels (org-at-heading-p))
22472 (goto-char origin)
22473 (error "Cannot move further up"))))
22475 (let* ((trail (org-element-at-point 'keep-trail))
22476 (elem (car trail))
22477 (prev-elem (nth 1 trail))
22478 (beg (org-element-property :begin elem)))
22479 (cond
22480 ;; Move to beginning of current element if point isn't
22481 ;; there already.
22482 ((/= (point) beg) (goto-char beg))
22483 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22484 ((org-before-first-heading-p) (goto-char (point-min)))
22485 (t (org-back-to-heading)))))))
22487 (defun org-up-element ()
22488 "Move to upper element."
22489 (interactive)
22490 (if (org-with-limited-levels (org-at-heading-p))
22491 (unless (org-up-heading-safe) (error "No surrounding element"))
22492 (let* ((elem (org-element-at-point))
22493 (parent (org-element-property :parent elem)))
22494 (if parent (goto-char (org-element-property :begin parent))
22495 (if (org-with-limited-levels (org-before-first-heading-p))
22496 (error "No surrounding element")
22497 (org-with-limited-levels (org-back-to-heading)))))))
22499 (defvar org-element-greater-elements)
22500 (defun org-down-element ()
22501 "Move to inner element."
22502 (interactive)
22503 (let ((element (org-element-at-point)))
22504 (cond
22505 ((memq (org-element-type element) '(plain-list table))
22506 (goto-char (org-element-property :contents-begin element))
22507 (forward-char))
22508 ((memq (org-element-type element) org-element-greater-elements)
22509 ;; If contents are hidden, first disclose them.
22510 (when (org-element-property :hiddenp element) (org-cycle))
22511 (goto-char (or (org-element-property :contents-begin element)
22512 (error "No content for this element"))))
22513 (t (error "No inner element")))))
22515 (defun org-drag-element-backward ()
22516 "Move backward element at point."
22517 (interactive)
22518 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22519 (let* ((trail (org-element-at-point 'keep-trail))
22520 (elem (car trail))
22521 (prev-elem (nth 1 trail)))
22522 ;; Error out if no previous element or previous element is
22523 ;; a parent of the current one.
22524 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22525 (error "Cannot drag element backward")
22526 (let ((pos (point)))
22527 (org-element-swap-A-B prev-elem elem)
22528 (goto-char (+ (org-element-property :begin prev-elem)
22529 (- pos (org-element-property :begin elem)))))))))
22531 (defun org-drag-element-forward ()
22532 "Move forward element at point."
22533 (interactive)
22534 (let* ((pos (point))
22535 (elem (org-element-at-point)))
22536 (when (= (point-max) (org-element-property :end elem))
22537 (error "Cannot drag element forward"))
22538 (goto-char (org-element-property :end elem))
22539 (let ((next-elem (org-element-at-point)))
22540 (when (or (org-element-nested-p elem next-elem)
22541 (and (eq (org-element-type next-elem) 'headline)
22542 (not (eq (org-element-type elem) 'headline))))
22543 (goto-char pos)
22544 (error "Cannot drag element forward"))
22545 ;; Compute new position of point: it's shifted by NEXT-ELEM
22546 ;; body's length (without final blanks) and by the length of
22547 ;; blanks between ELEM and NEXT-ELEM.
22548 (let ((size-next (- (save-excursion
22549 (goto-char (org-element-property :end next-elem))
22550 (skip-chars-backward " \r\t\n")
22551 (forward-line)
22552 ;; Small correction if buffer doesn't end
22553 ;; with a newline character.
22554 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22555 (org-element-property :begin next-elem)))
22556 (size-blank (- (org-element-property :end elem)
22557 (save-excursion
22558 (goto-char (org-element-property :end elem))
22559 (skip-chars-backward " \r\t\n")
22560 (forward-line)
22561 (point)))))
22562 (org-element-swap-A-B elem next-elem)
22563 (goto-char (+ pos size-next size-blank))))))
22565 (defun org-mark-element ()
22566 "Put point at beginning of this element, mark at end.
22568 Interactively, if this command is repeated or (in Transient Mark
22569 mode) if the mark is active, it marks the next element after the
22570 ones already marked."
22571 (interactive)
22572 (let (deactivate-mark)
22573 (if (and (org-called-interactively-p 'any)
22574 (or (and (eq last-command this-command) (mark t))
22575 (and transient-mark-mode mark-active)))
22576 (set-mark
22577 (save-excursion
22578 (goto-char (mark))
22579 (goto-char (org-element-property :end (org-element-at-point)))))
22580 (let ((element (org-element-at-point)))
22581 (end-of-line)
22582 (push-mark (org-element-property :end element) t t)
22583 (goto-char (org-element-property :begin element))))))
22585 (defun org-narrow-to-element ()
22586 "Narrow buffer to current element."
22587 (interactive)
22588 (let ((elem (org-element-at-point)))
22589 (cond
22590 ((eq (car elem) 'headline)
22591 (narrow-to-region
22592 (org-element-property :begin elem)
22593 (org-element-property :end elem)))
22594 ((memq (car elem) org-element-greater-elements)
22595 (narrow-to-region
22596 (org-element-property :contents-begin elem)
22597 (org-element-property :contents-end elem)))
22599 (narrow-to-region
22600 (org-element-property :begin elem)
22601 (org-element-property :end elem))))))
22603 (defun org-transpose-words ()
22604 "Transpose words, using `org-mode' syntax table."
22605 (interactive)
22606 (with-syntax-table org-syntax-table
22607 (call-interactively 'transpose-words)))
22608 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22610 (defun org-transpose-element ()
22611 "Transpose current and previous elements, keeping blank lines between.
22612 Point is moved after both elements."
22613 (interactive)
22614 (org-skip-whitespace)
22615 (let ((end (org-element-property :end (org-element-at-point))))
22616 (org-drag-element-backward)
22617 (goto-char end)))
22619 (defun org-unindent-buffer ()
22620 "Un-indent the visible part of the buffer.
22621 Relative indentation (between items, inside blocks, etc.) isn't
22622 modified."
22623 (interactive)
22624 (unless (eq major-mode 'org-mode)
22625 (error "Cannot un-indent a buffer not in Org mode"))
22626 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22627 unindent-tree ; For byte-compiler.
22628 (unindent-tree
22629 (function
22630 (lambda (contents)
22631 (mapc
22632 (lambda (element)
22633 (if (memq (org-element-type element) '(headline section))
22634 (funcall unindent-tree (org-element-contents element))
22635 (save-excursion
22636 (save-restriction
22637 (narrow-to-region
22638 (org-element-property :begin element)
22639 (org-element-property :end element))
22640 (org-do-remove-indentation)))))
22641 (reverse contents))))))
22642 (funcall unindent-tree (org-element-contents parse-tree))))
22644 (defun org-show-subtree ()
22645 "Show everything after this heading at deeper levels."
22646 (interactive)
22647 (outline-flag-region
22648 (point)
22649 (save-excursion
22650 (org-end-of-subtree t t))
22651 nil))
22653 (defun org-show-entry ()
22654 "Show the body directly following this heading.
22655 Show the heading too, if it is currently invisible."
22656 (interactive)
22657 (save-excursion
22658 (condition-case nil
22659 (progn
22660 (org-back-to-heading t)
22661 (outline-flag-region
22662 (max (point-min) (1- (point)))
22663 (save-excursion
22664 (if (re-search-forward
22665 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22666 (match-beginning 1)
22667 (point-max)))
22668 nil)
22669 (org-cycle-hide-drawers 'children))
22670 (error nil))))
22672 (defun org-make-options-regexp (kwds &optional extra)
22673 "Make a regular expression for keyword lines."
22674 (concat
22675 "^#\\+\\("
22676 (mapconcat 'regexp-quote kwds "\\|")
22677 (if extra (concat "\\|" extra))
22678 "\\):[ \t]*\\(.*\\)"))
22680 ;; Make isearch reveal the necessary context
22681 (defun org-isearch-end ()
22682 "Reveal context after isearch exits."
22683 (when isearch-success ; only if search was successful
22684 (if (featurep 'xemacs)
22685 ;; Under XEmacs, the hook is run in the correct place,
22686 ;; we directly show the context.
22687 (org-show-context 'isearch)
22688 ;; In Emacs the hook runs *before* restoring the overlays.
22689 ;; So we have to use a one-time post-command-hook to do this.
22690 ;; (Emacs 22 has a special variable, see function `org-mode')
22691 (unless (and (boundp 'isearch-mode-end-hook-quit)
22692 isearch-mode-end-hook-quit)
22693 ;; Only when the isearch was not quitted.
22694 (org-add-hook 'post-command-hook 'org-isearch-post-command
22695 'append 'local)))))
22697 (defun org-isearch-post-command ()
22698 "Remove self from hook, and show context."
22699 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22700 (org-show-context 'isearch))
22703 ;;;; Integration with and fixes for other packages
22705 ;;; Imenu support
22707 (defvar org-imenu-markers nil
22708 "All markers currently used by Imenu.")
22709 (make-variable-buffer-local 'org-imenu-markers)
22711 (defun org-imenu-new-marker (&optional pos)
22712 "Return a new marker for use by Imenu, and remember the marker."
22713 (let ((m (make-marker)))
22714 (move-marker m (or pos (point)))
22715 (push m org-imenu-markers)
22718 (defun org-imenu-get-tree ()
22719 "Produce the index for Imenu."
22720 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22721 (setq org-imenu-markers nil)
22722 (let* ((n org-imenu-depth)
22723 (re (concat "^" (org-get-limited-outline-regexp)))
22724 (subs (make-vector (1+ n) nil))
22725 (last-level 0)
22726 m level head)
22727 (save-excursion
22728 (save-restriction
22729 (widen)
22730 (goto-char (point-max))
22731 (while (re-search-backward re nil t)
22732 (setq level (org-reduced-level (funcall outline-level)))
22733 (when (and (<= level n)
22734 (looking-at org-complex-heading-regexp))
22735 (setq head (org-link-display-format
22736 (org-match-string-no-properties 4))
22737 m (org-imenu-new-marker))
22738 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22739 (if (>= level last-level)
22740 (push (cons head m) (aref subs level))
22741 (push (cons head (aref subs (1+ level))) (aref subs level))
22742 (loop for i from (1+ level) to n do (aset subs i nil)))
22743 (setq last-level level)))))
22744 (aref subs 1)))
22746 (eval-after-load "imenu"
22747 '(progn
22748 (add-hook 'imenu-after-jump-hook
22749 (lambda ()
22750 (if (derived-mode-p 'org-mode)
22751 (org-show-context 'org-goto))))))
22753 (defun org-link-display-format (link)
22754 "Replace a link with either the description, or the link target
22755 if no description is present"
22756 (save-match-data
22757 (if (string-match org-bracket-link-analytic-regexp link)
22758 (replace-match (if (match-end 5)
22759 (match-string 5 link)
22760 (concat (match-string 1 link)
22761 (match-string 3 link)))
22762 nil t link)
22763 link)))
22765 (defun org-toggle-link-display ()
22766 "Toggle the literal or descriptive display of links."
22767 (interactive)
22768 (if org-descriptive-links
22769 (progn (org-remove-from-invisibility-spec '(org-link))
22770 (org-restart-font-lock)
22771 (setq org-descriptive-links nil))
22772 (progn (add-to-invisibility-spec '(org-link))
22773 (org-restart-font-lock)
22774 (setq org-descriptive-links t))))
22776 ;; Speedbar support
22778 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22779 "Overlay marking the agenda restriction line in speedbar.")
22780 (overlay-put org-speedbar-restriction-lock-overlay
22781 'face 'org-agenda-restriction-lock)
22782 (overlay-put org-speedbar-restriction-lock-overlay
22783 'help-echo "Agendas are currently limited to this item.")
22784 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22786 (defun org-speedbar-set-agenda-restriction ()
22787 "Restrict future agenda commands to the location at point in speedbar.
22788 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22789 (interactive)
22790 (require 'org-agenda)
22791 (let (p m tp np dir txt)
22792 (cond
22793 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22794 'org-imenu t))
22795 (setq m (get-text-property p 'org-imenu-marker))
22796 (with-current-buffer (marker-buffer m)
22797 (goto-char m)
22798 (org-agenda-set-restriction-lock 'subtree)))
22799 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22800 'speedbar-function 'speedbar-find-file))
22801 (setq tp (previous-single-property-change
22802 (1+ p) 'speedbar-function)
22803 np (next-single-property-change
22804 tp 'speedbar-function)
22805 dir (speedbar-line-directory)
22806 txt (buffer-substring-no-properties (or tp (point-min))
22807 (or np (point-max))))
22808 (with-current-buffer (find-file-noselect
22809 (let ((default-directory dir))
22810 (expand-file-name txt)))
22811 (unless (derived-mode-p 'org-mode)
22812 (error "Cannot restrict to non-Org-mode file"))
22813 (org-agenda-set-restriction-lock 'file)))
22814 (t (error "Don't know how to restrict Org-mode's agenda")))
22815 (move-overlay org-speedbar-restriction-lock-overlay
22816 (point-at-bol) (point-at-eol))
22817 (setq current-prefix-arg nil)
22818 (org-agenda-maybe-redo)))
22820 (eval-after-load "speedbar"
22821 '(progn
22822 (speedbar-add-supported-extension ".org")
22823 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22824 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22825 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22826 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22827 (add-hook 'speedbar-visiting-tag-hook
22828 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22830 ;;; Fixes and Hacks for problems with other packages
22832 ;; Make flyspell not check words in links, to not mess up our keymap
22833 (defun org-mode-flyspell-verify ()
22834 "Don't let flyspell put overlays at active buttons, or on
22835 {todo,all-time,additional-option-like}-keywords."
22836 (let ((pos (max (1- (point)) (point-min)))
22837 (word (thing-at-point 'word)))
22838 (and (not (get-text-property pos 'keymap))
22839 (not (get-text-property pos 'org-no-flyspell))
22840 (not (member word org-todo-keywords-1))
22841 (not (member word org-all-time-keywords))
22842 (not (member word org-options-keywords))
22843 (not (member word (mapcar 'car org-startup-options)))
22844 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22846 (defun org-remove-flyspell-overlays-in (beg end)
22847 "Remove flyspell overlays in region."
22848 (and (org-bound-and-true-p flyspell-mode)
22849 (fboundp 'flyspell-delete-region-overlays)
22850 (flyspell-delete-region-overlays beg end))
22851 (add-text-properties beg end '(org-no-flyspell t)))
22853 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22854 (eval-after-load "bookmark"
22855 '(if (boundp 'bookmark-after-jump-hook)
22856 ;; We can use the hook
22857 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22858 ;; Hook not available, use advice
22859 (defadvice bookmark-jump (after org-make-visible activate)
22860 "Make the position visible."
22861 (org-bookmark-jump-unhide))))
22863 ;; Make sure saveplace shows the location if it was hidden
22864 (eval-after-load "saveplace"
22865 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22866 "Make the position visible."
22867 (org-bookmark-jump-unhide)))
22869 ;; Make sure ecb shows the location if it was hidden
22870 (eval-after-load "ecb"
22871 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22872 "Make hierarchy visible when jumping into location from ECB tree buffer."
22873 (if (derived-mode-p 'org-mode)
22874 (org-show-context))))
22876 (defun org-bookmark-jump-unhide ()
22877 "Unhide the current position, to show the bookmark location."
22878 (and (derived-mode-p 'org-mode)
22879 (or (outline-invisible-p)
22880 (save-excursion (goto-char (max (point-min) (1- (point))))
22881 (outline-invisible-p)))
22882 (org-show-context 'bookmark-jump)))
22884 ;; Make session.el ignore our circular variable
22885 (eval-after-load "session"
22886 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22888 ;;;; Experimental code
22890 (defun org-closed-in-range ()
22891 "Sparse tree of items closed in a certain time range.
22892 Still experimental, may disappear in the future."
22893 (interactive)
22894 ;; Get the time interval from the user.
22895 (let* ((time1 (org-float-time
22896 (org-read-date nil 'to-time nil "Starting date: ")))
22897 (time2 (org-float-time
22898 (org-read-date nil 'to-time nil "End date:")))
22899 ;; callback function
22900 (callback (lambda ()
22901 (let ((time
22902 (org-float-time
22903 (apply 'encode-time
22904 (org-parse-time-string
22905 (match-string 1))))))
22906 ;; check if time in interval
22907 (and (>= time time1) (<= time time2))))))
22908 ;; make tree, check each match with the callback
22909 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22911 ;;;; Finish up
22913 (provide 'org)
22915 (run-hooks 'org-load-hook)
22917 ;;; org.el ends here