Use `delq nil' instead of `delete nil' in a few functions
[org-mode.git] / lisp / org.el
blob79f66059867c3ab38b0500e14b6fc61faacd2ffa
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (let ((load-suffixes (list ".el")))
82 (load "org-loaddefs" 'noerror nil nil 'mustsuffix))
84 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
85 ;; some places -- e.g. see the macro org-with-limited-levels.
87 ;; In Org buffers, the value of `outline-regexp' is that of
88 ;; `org-outline-regexp'. The only function still directly relying on
89 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
90 ;; job when `orgstruct-mode' is active.
91 (defvar org-outline-regexp "\\*+ "
92 "Regexp to match Org headlines.")
94 (defvar org-outline-regexp-bol "^\\*+ "
95 "Regexp to match Org headlines.
96 This is similar to `org-outline-regexp' but additionally makes
97 sure that we are at the beginning of the line.")
99 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
100 "Matches an headline, putting stars and text into groups.
101 Stars are put in group 1 and the trimmed body in group 2.")
103 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
104 (when (fboundp 'defvaralias)
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-at-clock-log-p "org-clock" ())
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
121 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function orgtbl-mode "org-table" (&optional arg))
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-beamer-mode "org-beamer" ())
127 (declare-function org-table-edit-field "org-table" (arg))
128 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
129 (declare-function org-id-get-create "org-id" (&optional force))
130 (declare-function org-id-find-id-file "org-id" (id))
131 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
132 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
133 (declare-function org-table-align "org-table" ())
134 (declare-function org-table-paste-rectangle "org-table" ())
135 (declare-function org-table-maybe-eval-formula "org-table" ())
136 (declare-function org-table-maybe-recalculate-line "org-table" ())
138 (autoload 'org-element-at-point "org-element")
139 (autoload 'org-element-type "org-element")
141 (declare-function org-element-at-point "org-element" (&optional keep-trail))
142 (declare-function org-element-type "org-element" (element))
143 (declare-function org-element-context "org-element" ())
144 (declare-function org-element-contents "org-element" (element))
145 (declare-function org-element-property "org-element" (property element))
146 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
147 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
150 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
152 ;; load languages based on value of `org-babel-load-languages'
153 (defvar org-babel-load-languages)
155 ;;;###autoload
156 (defun org-babel-do-load-languages (sym value)
157 "Load the languages defined in `org-babel-load-languages'."
158 (set-default sym value)
159 (mapc (lambda (pair)
160 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
161 (if active
162 (progn
163 (require (intern (concat "ob-" lang))))
164 (progn
165 (funcall 'fmakunbound
166 (intern (concat "org-babel-execute:" lang)))
167 (funcall 'fmakunbound
168 (intern (concat "org-babel-expand-body:" lang)))))))
169 org-babel-load-languages))
171 (defcustom org-babel-load-languages '((emacs-lisp . t))
172 "Languages which can be evaluated in Org-mode buffers.
173 This list can be used to load support for any of the languages
174 below, note that each language will depend on a different set of
175 system executables and/or Emacs modes. When a language is
176 \"loaded\", then code blocks in that language can be evaluated
177 with `org-babel-execute-src-block' bound by default to C-c
178 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
179 be set to remove code block evaluation from the C-c C-c
180 keybinding. By default only Emacs Lisp (which has no
181 requirements) is loaded."
182 :group 'org-babel
183 :set 'org-babel-do-load-languages
184 :version "24.1"
185 :type '(alist :tag "Babel Languages"
186 :key-type
187 (choice
188 (const :tag "Awk" awk)
189 (const :tag "C" C)
190 (const :tag "R" R)
191 (const :tag "Asymptote" asymptote)
192 (const :tag "Calc" calc)
193 (const :tag "Clojure" clojure)
194 (const :tag "CSS" css)
195 (const :tag "Ditaa" ditaa)
196 (const :tag "Dot" dot)
197 (const :tag "Emacs Lisp" emacs-lisp)
198 (const :tag "Fortran" fortran)
199 (const :tag "Gnuplot" gnuplot)
200 (const :tag "Haskell" haskell)
201 (const :tag "IO" io)
202 (const :tag "Java" java)
203 (const :tag "Javascript" js)
204 (const :tag "LaTeX" latex)
205 (const :tag "Ledger" ledger)
206 (const :tag "Lilypond" lilypond)
207 (const :tag "Lisp" lisp)
208 (const :tag "Makefile" makefile)
209 (const :tag "Maxima" maxima)
210 (const :tag "Matlab" matlab)
211 (const :tag "Mscgen" mscgen)
212 (const :tag "Ocaml" ocaml)
213 (const :tag "Octave" octave)
214 (const :tag "Org" org)
215 (const :tag "Perl" perl)
216 (const :tag "Pico Lisp" picolisp)
217 (const :tag "PlantUML" plantuml)
218 (const :tag "Python" python)
219 (const :tag "Ruby" ruby)
220 (const :tag "Sass" sass)
221 (const :tag "Scala" scala)
222 (const :tag "Scheme" scheme)
223 (const :tag "Screen" screen)
224 (const :tag "Shell Script" sh)
225 (const :tag "Shen" shen)
226 (const :tag "Sql" sql)
227 (const :tag "Sqlite" sqlite))
228 :value-type (boolean :tag "Activate" :value t)))
230 ;;;; Customization variables
231 (defcustom org-clone-delete-id nil
232 "Remove ID property of clones of a subtree.
233 When non-nil, clones of a subtree don't inherit the ID property.
234 Otherwise they inherit the ID property with a new unique
235 identifier."
236 :type 'boolean
237 :version "24.1"
238 :group 'org-id)
240 ;;; Version
241 (require 'org-compat)
242 (org-check-version)
244 ;;;###autoload
245 (defun org-version (&optional here full message)
246 "Show the org-mode version in the echo area.
247 With prefix argument HERE, insert it at point.
248 When FULL is non-nil, use a verbose version string.
249 When MESSAGE is non-nil, display a message with the version."
250 (interactive "P")
251 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
252 (save-load-suffixes load-suffixes)
253 (load-suffixes (list ".el"))
254 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
255 (org-trash (or
256 (and (fboundp 'org-release) (fboundp 'org-git-version))
257 (load (concat org-dir "org-version")
258 'noerror 'nomessage nil 'mustsuffix)))
259 (load-suffixes save-load-suffixes)
260 (org-version (org-release))
261 (git-version (org-git-version))
262 (version (format "Org-mode version %s (%s @ %s)"
263 org-version
264 git-version
265 (if org-install-dir
266 (if (string= org-dir org-install-dir)
267 org-install-dir
268 (concat "mixed installation! " org-install-dir " and " org-dir))
269 "org-loaddefs.el can not be found!")))
270 (_version (if full version org-version)))
271 (if (org-called-interactively-p 'interactive)
272 (if here
273 (insert version)
274 (message version))
275 (if message (message _version))
276 _version)))
278 (defconst org-version (org-version))
280 ;;; Compatibility constants
282 ;;; The custom variables
284 (defgroup org nil
285 "Outline-based notes management and organizer."
286 :tag "Org"
287 :group 'outlines
288 :group 'calendar)
290 (defcustom org-mode-hook nil
291 "Mode hook for Org-mode, run after the mode was turned on."
292 :group 'org
293 :type 'hook)
295 (defcustom org-load-hook nil
296 "Hook that is run after org.el has been loaded."
297 :group 'org
298 :type 'hook)
300 (defcustom org-log-buffer-setup-hook nil
301 "Hook that is run after an Org log buffer is created."
302 :group 'org
303 :version "24.1"
304 :type 'hook)
306 (defvar org-modules) ; defined below
307 (defvar org-modules-loaded nil
308 "Have the modules been loaded already?")
310 (defun org-load-modules-maybe (&optional force)
311 "Load all extensions listed in `org-modules'."
312 (when (or force (not org-modules-loaded))
313 (mapc (lambda (ext)
314 (condition-case nil (require ext)
315 (error (message "Problems while trying to load feature `%s'" ext))))
316 org-modules)
317 (setq org-modules-loaded t)))
319 (defun org-set-modules (var value)
320 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
321 (set var value)
322 (when (featurep 'org)
323 (org-load-modules-maybe 'force)))
325 (when (org-bound-and-true-p org-modules)
326 (let ((a (member 'org-infojs org-modules)))
327 (and a (setcar a 'org-jsinfo))))
329 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
330 "Modules that should always be loaded together with org.el.
331 If a description starts with <C>, the file is not part of Emacs
332 and loading it will require that you have downloaded and properly installed
333 the org-mode distribution.
335 You can also use this system to load external packages (i.e. neither Org
336 core modules, nor modules from the CONTRIB directory). Just add symbols
337 to the end of the list. If the package is called org-xyz.el, then you need
338 to add the symbol `xyz', and the package must have a call to
340 (provide 'org-xyz)"
341 :group 'org
342 :set 'org-set-modules
343 :type
344 '(set :greedy t
345 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
346 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
347 (const :tag " crypt: Encryption of subtrees" org-crypt)
348 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
349 (const :tag " docview: Links to doc-view buffers" org-docview)
350 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
351 (const :tag " id: Global IDs for identifying entries" org-id)
352 (const :tag " info: Links to Info nodes" org-info)
353 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
354 (const :tag " habit: Track your consistency with habits" org-habit)
355 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
356 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
357 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
358 (const :tag " mew Links to Mew folders/messages" org-mew)
359 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
360 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
361 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
362 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
363 (const :tag " vm: Links to VM folders/messages" org-vm)
364 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
365 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
366 (const :tag " mouse: Additional mouse support" org-mouse)
367 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
369 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
370 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
371 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
372 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
373 (const :tag "C collector: Collect properties into tables" org-collector)
374 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
375 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
376 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
377 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
378 (const :tag "C eval: Include command output as text" org-eval)
379 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
380 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
381 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
382 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
383 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
385 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
387 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
388 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
389 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
390 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
391 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
392 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
393 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
394 (const :tag "C mtags: Support for muse-like tags" org-mtags)
395 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
396 (const :tag "C registry: A registry for Org-mode links" org-registry)
397 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
398 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
399 (const :tag "C secretary: Team management with org-mode" org-secretary)
400 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
401 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
402 (const :tag "C track: Keep up with Org-mode development" org-track)
403 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
404 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
405 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
407 (defcustom org-support-shift-select nil
408 "Non-nil means make shift-cursor commands select text when possible.
410 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
411 start selecting a region, or enlarge regions started in this way.
412 In Org-mode, in special contexts, these same keys are used for
413 other purposes, important enough to compete with shift selection.
414 Org tries to balance these needs by supporting `shift-select-mode'
415 outside these special contexts, under control of this variable.
417 The default of this variable is nil, to avoid confusing behavior. Shifted
418 cursor keys will then execute Org commands in the following contexts:
419 - on a headline, changing TODO state (left/right) and priority (up/down)
420 - on a time stamp, changing the time
421 - in a plain list item, changing the bullet type
422 - in a property definition line, switching between allowed values
423 - in the BEGIN line of a clock table (changing the time block).
424 Outside these contexts, the commands will throw an error.
426 When this variable is t and the cursor is not in a special
427 context, Org-mode will support shift-selection for making and
428 enlarging regions. To make this more effective, the bullet
429 cycling will no longer happen anywhere in an item line, but only
430 if the cursor is exactly on the bullet.
432 If you set this variable to the symbol `always', then the keys
433 will not be special in headlines, property lines, and item lines,
434 to make shift selection work there as well. If this is what you
435 want, you can use the following alternative commands: `C-c C-t'
436 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
437 can be used to switch TODO sets, `C-c -' to cycle item bullet
438 types, and properties can be edited by hand or in column view.
440 However, when the cursor is on a timestamp, shift-cursor commands
441 will still edit the time stamp - this is just too good to give up.
443 XEmacs user should have this variable set to nil, because
444 `shift-select-mode' is in Emacs 23 or later only."
445 :group 'org
446 :type '(choice
447 (const :tag "Never" nil)
448 (const :tag "When outside special context" t)
449 (const :tag "Everywhere except timestamps" always)))
451 (defcustom org-loop-over-headlines-in-active-region nil
452 "Shall some commands act upon headlines in the active region?
454 When set to `t', some commands will be performed in all headlines
455 within the active region.
457 When set to `start-level', some commands will be performed in all
458 headlines within the active region, provided that these headlines
459 are of the same level than the first one.
461 When set to a string, those commands will be performed on the
462 matching headlines within the active region. Such string must be
463 a tags/property/todo match as it is used in the agenda tags view.
465 The list of commands is: `org-schedule', `org-deadline',
466 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
467 `org-archive-to-archive-sibling'. The archiving commands skip
468 already archived entries."
469 :type '(choice (const :tag "Don't loop" nil)
470 (const :tag "All headlines in active region" t)
471 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
472 (string :tag "Tags/Property/Todo matcher"))
473 :version "24.1"
474 :group 'org-todo
475 :group 'org-archive)
477 (defgroup org-startup nil
478 "Options concerning startup of Org-mode."
479 :tag "Org Startup"
480 :group 'org)
482 (defcustom org-startup-folded t
483 "Non-nil means entering Org-mode will switch to OVERVIEW.
484 This can also be configured on a per-file basis by adding one of
485 the following lines anywhere in the buffer:
487 #+STARTUP: fold (or `overview', this is equivalent)
488 #+STARTUP: nofold (or `showall', this is equivalent)
489 #+STARTUP: content
490 #+STARTUP: showeverything"
491 :group 'org-startup
492 :type '(choice
493 (const :tag "nofold: show all" nil)
494 (const :tag "fold: overview" t)
495 (const :tag "content: all headlines" content)
496 (const :tag "show everything, even drawers" showeverything)))
498 (defcustom org-startup-truncated t
499 "Non-nil means entering Org-mode will set `truncate-lines'.
500 This is useful since some lines containing links can be very long and
501 uninteresting. Also tables look terrible when wrapped."
502 :group 'org-startup
503 :type 'boolean)
505 (defcustom org-startup-indented nil
506 "Non-nil means turn on `org-indent-mode' on startup.
507 This can also be configured on a per-file basis by adding one of
508 the following lines anywhere in the buffer:
510 #+STARTUP: indent
511 #+STARTUP: noindent"
512 :group 'org-structure
513 :type '(choice
514 (const :tag "Not" nil)
515 (const :tag "Globally (slow on startup in large files)" t)))
517 (defcustom org-use-sub-superscripts t
518 "Non-nil means interpret \"_\" and \"^\" for export.
519 When this option is turned on, you can use TeX-like syntax for sub- and
520 superscripts. Several characters after \"_\" or \"^\" will be
521 considered as a single item - so grouping with {} is normally not
522 needed. For example, the following things will be parsed as single
523 sub- or superscripts.
525 10^24 or 10^tau several digits will be considered 1 item.
526 10^-12 or 10^-tau a leading sign with digits or a word
527 x^2-y^3 will be read as x^2 - y^3, because items are
528 terminated by almost any nonword/nondigit char.
529 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
531 Still, ambiguity is possible - so when in doubt use {} to enclose the
532 sub/superscript. If you set this variable to the symbol `{}',
533 the braces are *required* in order to trigger interpretations as
534 sub/superscript. This can be helpful in documents that need \"_\"
535 frequently in plain text.
537 Not all export backends support this, but HTML does.
539 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
540 :group 'org-startup
541 :group 'org-export-translation
542 :version "24.1"
543 :type '(choice
544 (const :tag "Always interpret" t)
545 (const :tag "Only with braces" {})
546 (const :tag "Never interpret" nil)))
548 (if (fboundp 'defvaralias)
549 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
552 (defcustom org-startup-with-beamer-mode nil
553 "Non-nil means turn on `org-beamer-mode' on startup.
554 This can also be configured on a per-file basis by adding one of
555 the following lines anywhere in the buffer:
557 #+STARTUP: beamer"
558 :group 'org-startup
559 :version "24.1"
560 :type 'boolean)
562 (defcustom org-startup-align-all-tables nil
563 "Non-nil means align all tables when visiting a file.
564 This is useful when the column width in tables is forced with <N> cookies
565 in table fields. Such tables will look correct only after the first re-align.
566 This can also be configured on a per-file basis by adding one of
567 the following lines anywhere in the buffer:
568 #+STARTUP: align
569 #+STARTUP: noalign"
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-startup-with-inline-images nil
574 "Non-nil means show inline images when loading a new Org file.
575 This can also be configured on a per-file basis by adding one of
576 the following lines anywhere in the buffer:
577 #+STARTUP: inlineimages
578 #+STARTUP: noinlineimages"
579 :group 'org-startup
580 :version "24.1"
581 :type 'boolean)
583 (defcustom org-insert-mode-line-in-empty-file nil
584 "Non-nil means insert the first line setting Org-mode in empty files.
585 When the function `org-mode' is called interactively in an empty file, this
586 normally means that the file name does not automatically trigger Org-mode.
587 To ensure that the file will always be in Org-mode in the future, a
588 line enforcing Org-mode will be inserted into the buffer, if this option
589 has been set."
590 :group 'org-startup
591 :type 'boolean)
593 (defcustom org-replace-disputed-keys nil
594 "Non-nil means use alternative key bindings for some keys.
595 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
596 These keys are also used by other packages like shift-selection-mode'
597 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
598 If you want to use Org-mode together with one of these other modes,
599 or more generally if you would like to move some Org-mode commands to
600 other keys, set this variable and configure the keys with the variable
601 `org-disputed-keys'.
603 This option is only relevant at load-time of Org-mode, and must be set
604 *before* org.el is loaded. Changing it requires a restart of Emacs to
605 become effective."
606 :group 'org-startup
607 :type 'boolean)
609 (defcustom org-use-extra-keys nil
610 "Non-nil means use extra key sequence definitions for certain commands.
611 This happens automatically if you run XEmacs or if `window-system'
612 is nil. This variable lets you do the same manually. You must
613 set it before loading org.
615 Example: on Carbon Emacs 22 running graphically, with an external
616 keyboard on a Powerbook, the default way of setting M-left might
617 not work for either Alt or ESC. Setting this variable will make
618 it work for ESC."
619 :group 'org-startup
620 :type 'boolean)
622 (if (fboundp 'defvaralias)
623 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
625 (defcustom org-disputed-keys
626 '(([(shift up)] . [(meta p)])
627 ([(shift down)] . [(meta n)])
628 ([(shift left)] . [(meta -)])
629 ([(shift right)] . [(meta +)])
630 ([(control shift right)] . [(meta shift +)])
631 ([(control shift left)] . [(meta shift -)]))
632 "Keys for which Org-mode and other modes compete.
633 This is an alist, cars are the default keys, second element specifies
634 the alternative to use when `org-replace-disputed-keys' is t.
636 Keys can be specified in any syntax supported by `define-key'.
637 The value of this option takes effect only at Org-mode's startup,
638 therefore you'll have to restart Emacs to apply it after changing."
639 :group 'org-startup
640 :type 'alist)
642 (defun org-key (key)
643 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
644 Or return the original if not disputed.
645 Also apply the translations defined in `org-xemacs-key-equivalents'."
646 (when org-replace-disputed-keys
647 (let* ((nkey (key-description key))
648 (x (org-find-if (lambda (x)
649 (equal (key-description (car x)) nkey))
650 org-disputed-keys)))
651 (setq key (if x (cdr x) key))))
652 (when (featurep 'xemacs)
653 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
654 key)
656 (defun org-find-if (predicate seq)
657 (catch 'exit
658 (while seq
659 (if (funcall predicate (car seq))
660 (throw 'exit (car seq))
661 (pop seq)))))
663 (defun org-defkey (keymap key def)
664 "Define a key, possibly translated, as returned by `org-key'."
665 (define-key keymap (org-key key) def))
667 (defcustom org-ellipsis nil
668 "The ellipsis to use in the Org-mode outline.
669 When nil, just use the standard three dots. When a string, use that instead,
670 When a face, use the standard 3 dots, but with the specified face.
671 The change affects only Org-mode (which will then use its own display table).
672 Changing this requires executing `M-x org-mode' in a buffer to become
673 effective."
674 :group 'org-startup
675 :type '(choice (const :tag "Default" nil)
676 (face :tag "Face" :value org-warning)
677 (string :tag "String" :value "...#")))
679 (defvar org-display-table nil
680 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
682 (defgroup org-keywords nil
683 "Keywords in Org-mode."
684 :tag "Org Keywords"
685 :group 'org)
687 (defcustom org-deadline-string "DEADLINE:"
688 "String to mark deadline entries.
689 A deadline is this string, followed by a time stamp. Should be a word,
690 terminated by a colon. You can insert a schedule keyword and
691 a timestamp with \\[org-deadline].
692 Changes become only effective after restarting Emacs."
693 :group 'org-keywords
694 :type 'string)
696 (defcustom org-scheduled-string "SCHEDULED:"
697 "String to mark scheduled TODO entries.
698 A schedule is this string, followed by a time stamp. Should be a word,
699 terminated by a colon. You can insert a schedule keyword and
700 a timestamp with \\[org-schedule].
701 Changes become only effective after restarting Emacs."
702 :group 'org-keywords
703 :type 'string)
705 (defcustom org-closed-string "CLOSED:"
706 "String used as the prefix for timestamps logging closing a TODO entry."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-clock-string "CLOCK:"
711 "String used as prefix for timestamps clocking work hours on an item."
712 :group 'org-keywords
713 :type 'string)
715 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
716 org-scheduled-string "\\|"
717 org-deadline-string "\\|"
718 org-closed-string "\\|"
719 org-clock-string "\\)")
720 "Matches a line with planning or clock info.")
722 (defcustom org-comment-string "COMMENT"
723 "Entries starting with this keyword will never be exported.
724 An entry can be toggled between COMMENT and normal with
725 \\[org-toggle-comment].
726 Changes become only effective after restarting Emacs."
727 :group 'org-keywords
728 :type 'string)
730 (defcustom org-quote-string "QUOTE"
731 "Entries starting with this keyword will be exported in fixed-width font.
732 Quoting applies only to the text in the entry following the headline, and does
733 not extend beyond the next headline, even if that is lower level.
734 An entry can be toggled between QUOTE and normal with
735 \\[org-toggle-fixed-width-section]."
736 :group 'org-keywords
737 :type 'string)
739 (defconst org-repeat-re
740 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
741 "Regular expression for specifying repeated events.
742 After a match, group 1 contains the repeat expression.")
744 (defgroup org-structure nil
745 "Options concerning the general structure of Org-mode files."
746 :tag "Org Structure"
747 :group 'org)
749 (defgroup org-reveal-location nil
750 "Options about how to make context of a location visible."
751 :tag "Org Reveal Location"
752 :group 'org-structure)
754 (defconst org-context-choice
755 '(choice
756 (const :tag "Always" t)
757 (const :tag "Never" nil)
758 (repeat :greedy t :tag "Individual contexts"
759 (cons
760 (choice :tag "Context"
761 (const agenda)
762 (const org-goto)
763 (const occur-tree)
764 (const tags-tree)
765 (const link-search)
766 (const mark-goto)
767 (const bookmark-jump)
768 (const isearch)
769 (const default))
770 (boolean))))
771 "Contexts for the reveal options.")
773 (defcustom org-show-hierarchy-above '((default . t))
774 "Non-nil means show full hierarchy when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the hierarchy of headings
777 above the exposed location is shown.
778 Turning this off for example for sparse trees makes them very compact.
779 Instead of t, this can also be an alist specifying this option for different
780 contexts. Valid contexts are
781 agenda when exposing an entry from the agenda
782 org-goto when using the command `org-goto' on key C-c C-j
783 occur-tree when using the command `org-occur' on key C-c /
784 tags-tree when constructing a sparse tree based on tags matches
785 link-search when exposing search matches associated with a link
786 mark-goto when exposing the jump goal of a mark
787 bookmark-jump when exposing a bookmark location
788 isearch when exiting from an incremental search
789 default default for all contexts not set explicitly"
790 :group 'org-reveal-location
791 :type org-context-choice)
793 (defcustom org-show-following-heading '((default . nil))
794 "Non-nil means show following heading when revealing a location.
795 Org-mode often shows locations in an org-mode file which might have
796 been invisible before. When this is set, the heading following the
797 match is shown.
798 Turning this off for example for sparse trees makes them very compact,
799 but makes it harder to edit the location of the match. In such a case,
800 use the command \\[org-reveal] to show more context.
801 Instead of t, this can also be an alist specifying this option for different
802 contexts. See `org-show-hierarchy-above' for valid contexts."
803 :group 'org-reveal-location
804 :type org-context-choice)
806 (defcustom org-show-siblings '((default . nil) (isearch t))
807 "Non-nil means show all sibling heading when revealing a location.
808 Org-mode often shows locations in an org-mode file which might have
809 been invisible before. When this is set, the sibling of the current entry
810 heading are all made visible. If `org-show-hierarchy-above' is t,
811 the same happens on each level of the hierarchy above the current entry.
813 By default this is on for the isearch context, off for all other contexts.
814 Turning this off for example for sparse trees makes them very compact,
815 but makes it harder to edit the location of the match. In such a case,
816 use the command \\[org-reveal] to show more context.
817 Instead of t, this can also be an alist specifying this option for different
818 contexts. See `org-show-hierarchy-above' for valid contexts."
819 :group 'org-reveal-location
820 :type org-context-choice)
822 (defcustom org-show-entry-below '((default . nil))
823 "Non-nil means show the entry below a headline when revealing a location.
824 Org-mode often shows locations in an org-mode file which might have
825 been invisible before. When this is set, the text below the headline that is
826 exposed is also shown.
828 By default this is off for all contexts.
829 Instead of t, this can also be an alist specifying this option for different
830 contexts. See `org-show-hierarchy-above' for valid contexts."
831 :group 'org-reveal-location
832 :type org-context-choice)
834 (defcustom org-indirect-buffer-display 'other-window
835 "How should indirect tree buffers be displayed?
836 This applies to indirect buffers created with the commands
837 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
838 Valid values are:
839 current-window Display in the current window
840 other-window Just display in another window.
841 dedicated-frame Create one new frame, and re-use it each time.
842 new-frame Make a new frame each time. Note that in this case
843 previously-made indirect buffers are kept, and you need to
844 kill these buffers yourself."
845 :group 'org-structure
846 :group 'org-agenda-windows
847 :type '(choice
848 (const :tag "In current window" current-window)
849 (const :tag "In current frame, other window" other-window)
850 (const :tag "Each time a new frame" new-frame)
851 (const :tag "One dedicated frame" dedicated-frame)))
853 (defcustom org-use-speed-commands nil
854 "Non-nil means activate single letter commands at beginning of a headline.
855 This may also be a function to test for appropriate locations where speed
856 commands should be active."
857 :group 'org-structure
858 :type '(choice
859 (const :tag "Never" nil)
860 (const :tag "At beginning of headline stars" t)
861 (function)))
863 (defcustom org-speed-commands-user nil
864 "Alist of additional speed commands.
865 This list will be checked before `org-speed-commands-default'
866 when the variable `org-use-speed-commands' is non-nil
867 and when the cursor is at the beginning of a headline.
868 The car if each entry is a string with a single letter, which must
869 be assigned to `self-insert-command' in the global map.
870 The cdr is either a command to be called interactively, a function
871 to be called, or a form to be evaluated.
872 An entry that is just a list with a single string will be interpreted
873 as a descriptive headline that will be added when listing the speed
874 commands in the Help buffer using the `?' speed command."
875 :group 'org-structure
876 :type '(repeat :value ("k" . ignore)
877 (choice :value ("k" . ignore)
878 (list :tag "Descriptive Headline" (string :tag "Headline"))
879 (cons :tag "Letter and Command"
880 (string :tag "Command letter")
881 (choice
882 (function)
883 (sexp))))))
885 (defgroup org-cycle nil
886 "Options concerning visibility cycling in Org-mode."
887 :tag "Org Cycle"
888 :group 'org-structure)
890 (defcustom org-cycle-skip-children-state-if-no-children t
891 "Non-nil means skip CHILDREN state in entries that don't have any."
892 :group 'org-cycle
893 :type 'boolean)
895 (defcustom org-cycle-max-level nil
896 "Maximum level which should still be subject to visibility cycling.
897 Levels higher than this will, for cycling, be treated as text, not a headline.
898 When `org-odd-levels-only' is set, a value of N in this variable actually
899 means 2N-1 stars as the limiting headline.
900 When nil, cycle all levels.
901 Note that the limiting level of cycling is also influenced by
902 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
903 `org-inlinetask-min-level' is, cycling will be limited to levels one less
904 than its value."
905 :group 'org-cycle
906 :type '(choice
907 (const :tag "No limit" nil)
908 (integer :tag "Maximum level")))
910 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
911 "Names of drawers. Drawers are not opened by cycling on the headline above.
912 Drawers only open with a TAB on the drawer line itself. A drawer looks like
913 this:
914 :DRAWERNAME:
915 .....
916 :END:
917 The drawer \"PROPERTIES\" is special for capturing properties through
918 the property API.
920 Drawers can be defined on the per-file basis with a line like:
922 #+DRAWERS: HIDDEN STATE PROPERTIES"
923 :group 'org-structure
924 :group 'org-cycle
925 :type '(repeat (string :tag "Drawer Name")))
927 (defcustom org-hide-block-startup nil
928 "Non-nil means entering Org-mode will fold all blocks.
929 This can also be set in on a per-file basis with
931 #+STARTUP: hideblocks
932 #+STARTUP: showblocks"
933 :group 'org-startup
934 :group 'org-cycle
935 :type 'boolean)
937 (defcustom org-cycle-global-at-bob nil
938 "Cycle globally if cursor is at beginning of buffer and not at a headline.
939 This makes it possible to do global cycling without having to use S-TAB or
940 \\[universal-argument] TAB. For this special case to work, the first line
941 of the buffer must not be a headline -- it may be empty or some other text.
942 When used in this way, `org-cycle-hook' is disabled temporarily to make
943 sure the cursor stays at the beginning of the buffer. When this option is
944 nil, don't do anything special at the beginning of the buffer."
945 :group 'org-cycle
946 :type 'boolean)
948 (defcustom org-cycle-level-after-item/entry-creation t
949 "Non-nil means cycle entry level or item indentation in new empty entries.
951 When the cursor is at the end of an empty headline, i.e with only stars
952 and maybe a TODO keyword, TAB will then switch the entry to become a child,
953 and then all possible ancestor states, before returning to the original state.
954 This makes data entry extremely fast: M-RET to create a new headline,
955 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
957 When the cursor is at the end of an empty plain list item, one TAB will
958 make it a subitem, two or more tabs will back up to make this an item
959 higher up in the item hierarchy."
960 :group 'org-cycle
961 :type 'boolean)
963 (defcustom org-cycle-emulate-tab t
964 "Where should `org-cycle' emulate TAB.
965 nil Never
966 white Only in completely white lines
967 whitestart Only at the beginning of lines, before the first non-white char
968 t Everywhere except in headlines
969 exc-hl-bol Everywhere except at the start of a headline
970 If TAB is used in a place where it does not emulate TAB, the current subtree
971 visibility is cycled."
972 :group 'org-cycle
973 :type '(choice (const :tag "Never" nil)
974 (const :tag "Only in completely white lines" white)
975 (const :tag "Before first char in a line" whitestart)
976 (const :tag "Everywhere except in headlines" t)
977 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
980 (defcustom org-cycle-separator-lines 2
981 "Number of empty lines needed to keep an empty line between collapsed trees.
982 If you leave an empty line between the end of a subtree and the following
983 headline, this empty line is hidden when the subtree is folded.
984 Org-mode will leave (exactly) one empty line visible if the number of
985 empty lines is equal or larger to the number given in this variable.
986 So the default 2 means at least 2 empty lines after the end of a subtree
987 are needed to produce free space between a collapsed subtree and the
988 following headline.
990 If the number is negative, and the number of empty lines is at least -N,
991 all empty lines are shown.
993 Special case: when 0, never leave empty lines in collapsed view."
994 :group 'org-cycle
995 :type 'integer)
996 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
998 (defcustom org-pre-cycle-hook nil
999 "Hook that is run before visibility cycling is happening.
1000 The function(s) in this hook must accept a single argument which indicates
1001 the new state that will be set right after running this hook. The
1002 argument is a symbol. Before a global state change, it can have the values
1003 `overview', `content', or `all'. Before a local state change, it can have
1004 the values `folded', `children', or `subtree'."
1005 :group 'org-cycle
1006 :type 'hook)
1008 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1009 org-cycle-hide-drawers
1010 org-cycle-hide-inline-tasks
1011 org-cycle-show-empty-lines
1012 org-optimize-window-after-visibility-change)
1013 "Hook that is run after `org-cycle' has changed the buffer visibility.
1014 The function(s) in this hook must accept a single argument which indicates
1015 the new state that was set by the most recent `org-cycle' command. The
1016 argument is a symbol. After a global state change, it can have the values
1017 `overview', `contents', or `all'. After a local state change, it can have
1018 the values `folded', `children', or `subtree'."
1019 :group 'org-cycle
1020 :type 'hook)
1022 (defgroup org-edit-structure nil
1023 "Options concerning structure editing in Org-mode."
1024 :tag "Org Edit Structure"
1025 :group 'org-structure)
1027 (defcustom org-odd-levels-only nil
1028 "Non-nil means skip even levels and only use odd levels for the outline.
1029 This has the effect that two stars are being added/taken away in
1030 promotion/demotion commands. It also influences how levels are
1031 handled by the exporters.
1032 Changing it requires restart of `font-lock-mode' to become effective
1033 for fontification also in regions already fontified.
1034 You may also set this on a per-file basis by adding one of the following
1035 lines to the buffer:
1037 #+STARTUP: odd
1038 #+STARTUP: oddeven"
1039 :group 'org-edit-structure
1040 :group 'org-appearance
1041 :type 'boolean)
1043 (defcustom org-adapt-indentation t
1044 "Non-nil means adapt indentation to outline node level.
1046 When this variable is set, Org assumes that you write outlines by
1047 indenting text in each node to align with the headline (after the stars).
1048 The following issues are influenced by this variable:
1050 - When this is set and the *entire* text in an entry is indented, the
1051 indentation is increased by one space in a demotion command, and
1052 decreased by one in a promotion command. If any line in the entry
1053 body starts with text at column 0, indentation is not changed at all.
1055 - Property drawers and planning information is inserted indented when
1056 this variable s set. When nil, they will not be indented.
1058 - TAB indents a line relative to context. The lines below a headline
1059 will be indented when this variable is set.
1061 Note that this is all about true indentation, by adding and removing
1062 space characters. See also `org-indent.el' which does level-dependent
1063 indentation in a virtual way, i.e. at display time in Emacs."
1064 :group 'org-edit-structure
1065 :type 'boolean)
1067 (defcustom org-special-ctrl-a/e nil
1068 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1070 When t, `C-a' will bring back the cursor to the beginning of the
1071 headline text, i.e. after the stars and after a possible TODO
1072 keyword. In an item, this will be the position after bullet and
1073 check-box, if any. When the cursor is already at that position,
1074 another `C-a' will bring it to the beginning of the line.
1076 `C-e' will jump to the end of the headline, ignoring the presence
1077 of tags in the headline. A second `C-e' will then jump to the
1078 true end of the line, after any tags. This also means that, when
1079 this variable is non-nil, `C-e' also will never jump beyond the
1080 end of the heading of a folded section, i.e. not after the
1081 ellipses.
1083 When set to the symbol `reversed', the first `C-a' or `C-e' works
1084 normally, going to the true line boundary first. Only a directly
1085 following, identical keypress will bring the cursor to the
1086 special positions.
1088 This may also be a cons cell where the behavior for `C-a' and
1089 `C-e' is set separately."
1090 :group 'org-edit-structure
1091 :type '(choice
1092 (const :tag "off" nil)
1093 (const :tag "on: after stars/bullet and before tags first" t)
1094 (const :tag "reversed: true line boundary first" reversed)
1095 (cons :tag "Set C-a and C-e separately"
1096 (choice :tag "Special C-a"
1097 (const :tag "off" nil)
1098 (const :tag "on: after stars/bullet first" t)
1099 (const :tag "reversed: before stars/bullet first" reversed))
1100 (choice :tag "Special C-e"
1101 (const :tag "off" nil)
1102 (const :tag "on: before tags first" t)
1103 (const :tag "reversed: after tags first" reversed)))))
1104 (if (fboundp 'defvaralias)
1105 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1107 (defcustom org-special-ctrl-k nil
1108 "Non-nil means `C-k' will behave specially in headlines.
1109 When nil, `C-k' will call the default `kill-line' command.
1110 When t, the following will happen while the cursor is in the headline:
1112 - When the cursor is at the beginning of a headline, kill the entire
1113 line and possible the folded subtree below the line.
1114 - When in the middle of the headline text, kill the headline up to the tags.
1115 - When after the headline text, kill the tags."
1116 :group 'org-edit-structure
1117 :type 'boolean)
1119 (defcustom org-ctrl-k-protect-subtree nil
1120 "Non-nil means, do not delete a hidden subtree with C-k.
1121 When set to the symbol `error', simply throw an error when C-k is
1122 used to kill (part-of) a headline that has hidden text behind it.
1123 Any other non-nil value will result in a query to the user, if it is
1124 OK to kill that hidden subtree. When nil, kill without remorse."
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not protect hidden subtrees" nil)
1129 (const :tag "Protect hidden subtrees with a security query" t)
1130 (const :tag "Never kill a hidden subtree with C-k" error)))
1132 (defcustom org-catch-invisible-edits nil
1133 "Check if in invisible region before inserting or deleting a character.
1134 Valid values are:
1136 nil Do not check, so just do invisible edits.
1137 error Throw an error and do nothing.
1138 show Make point visible, and do the requested edit.
1139 show-and-error Make point visible, then throw an error and abort the edit.
1140 smart Make point visible, and do insertion/deletion if it is
1141 adjacent to visible text and the change feels predictable.
1142 Never delete a previously invisible character or add in the
1143 middle or right after an invisible region. Basically, this
1144 allows insertion and backward-delete right before ellipses.
1145 FIXME: maybe in this case we should not even show?"
1146 :group 'org-edit-structure
1147 :version "24.1"
1148 :type '(choice
1149 (const :tag "Do not check" nil)
1150 (const :tag "Throw error when trying to edit" error)
1151 (const :tag "Unhide, but do not do the edit" show-and-error)
1152 (const :tag "Show invisible part and do the edit" show)
1153 (const :tag "Be smart and do the right thing" smart)))
1155 (defcustom org-yank-folded-subtrees t
1156 "Non-nil means when yanking subtrees, fold them.
1157 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1158 it starts with a heading and all other headings in it are either children
1159 or siblings, then fold all the subtrees. However, do this only if no
1160 text after the yank would be swallowed into a folded tree by this action."
1161 :group 'org-edit-structure
1162 :type 'boolean)
1164 (defcustom org-yank-adjusted-subtrees nil
1165 "Non-nil means when yanking subtrees, adjust the level.
1166 With this setting, `org-paste-subtree' is used to insert the subtree, see
1167 this function for details."
1168 :group 'org-edit-structure
1169 :type 'boolean)
1171 (defcustom org-M-RET-may-split-line '((default . t))
1172 "Non-nil means M-RET will split the line at the cursor position.
1173 When nil, it will go to the end of the line before making a
1174 new line.
1175 You may also set this option in a different way for different
1176 contexts. Valid contexts are:
1178 headline when creating a new headline
1179 item when creating a new item
1180 table in a table field
1181 default the value to be used for all contexts not explicitly
1182 customized"
1183 :group 'org-structure
1184 :group 'org-table
1185 :type '(choice
1186 (const :tag "Always" t)
1187 (const :tag "Never" nil)
1188 (repeat :greedy t :tag "Individual contexts"
1189 (cons
1190 (choice :tag "Context"
1191 (const headline)
1192 (const item)
1193 (const table)
1194 (const default))
1195 (boolean)))))
1198 (defcustom org-insert-heading-respect-content nil
1199 "Non-nil means insert new headings after the current subtree.
1200 When nil, the new heading is created directly after the current line.
1201 The commands \\[org-insert-heading-respect-content] and
1202 \\[org-insert-todo-heading-respect-content] turn this variable on
1203 for the duration of the command."
1204 :group 'org-structure
1205 :type 'boolean)
1207 (defcustom org-blank-before-new-entry '((heading . auto)
1208 (plain-list-item . auto))
1209 "Should `org-insert-heading' leave a blank line before new heading/item?
1210 The value is an alist, with `heading' and `plain-list-item' as CAR,
1211 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1212 which case Org will look at the surrounding headings/items and try to
1213 make an intelligent decision whether to insert a blank line or not.
1215 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1216 set, the setting here is ignored and no empty line is inserted, to avoid
1217 breaking the list structure."
1218 :group 'org-edit-structure
1219 :type '(list
1220 (cons (const heading)
1221 (choice (const :tag "Never" nil)
1222 (const :tag "Always" t)
1223 (const :tag "Auto" auto)))
1224 (cons (const plain-list-item)
1225 (choice (const :tag "Never" nil)
1226 (const :tag "Always" t)
1227 (const :tag "Auto" auto)))))
1229 (defcustom org-insert-heading-hook nil
1230 "Hook being run after inserting a new heading."
1231 :group 'org-edit-structure
1232 :type 'hook)
1234 (defcustom org-enable-fixed-width-editor t
1235 "Non-nil means lines starting with \":\" are treated as fixed-width.
1236 This currently only means they are never auto-wrapped.
1237 When nil, such lines will be treated like ordinary lines.
1238 See also the QUOTE keyword."
1239 :group 'org-edit-structure
1240 :type 'boolean)
1242 (defcustom org-goto-auto-isearch t
1243 "Non-nil means typing characters in `org-goto' starts incremental search."
1244 :group 'org-edit-structure
1245 :type 'boolean)
1247 (defgroup org-sparse-trees nil
1248 "Options concerning sparse trees in Org-mode."
1249 :tag "Org Sparse Trees"
1250 :group 'org-structure)
1252 (defcustom org-highlight-sparse-tree-matches t
1253 "Non-nil means highlight all matches that define a sparse tree.
1254 The highlights will automatically disappear the next time the buffer is
1255 changed by an edit command."
1256 :group 'org-sparse-trees
1257 :type 'boolean)
1259 (defcustom org-remove-highlights-with-change t
1260 "Non-nil means any change to the buffer will remove temporary highlights.
1261 Such highlights are created by `org-occur' and `org-clock-display'.
1262 When nil, `C-c C-c needs to be used to get rid of the highlights.
1263 The highlights created by `org-preview-latex-fragment' always need
1264 `C-c C-c' to be removed."
1265 :group 'org-sparse-trees
1266 :group 'org-time
1267 :type 'boolean)
1270 (defcustom org-occur-hook '(org-first-headline-recenter)
1271 "Hook that is run after `org-occur' has constructed a sparse tree.
1272 This can be used to recenter the window to show as much of the structure
1273 as possible."
1274 :group 'org-sparse-trees
1275 :type 'hook)
1277 (defgroup org-imenu-and-speedbar nil
1278 "Options concerning imenu and speedbar in Org-mode."
1279 :tag "Org Imenu and Speedbar"
1280 :group 'org-structure)
1282 (defcustom org-imenu-depth 2
1283 "The maximum level for Imenu access to Org-mode headlines.
1284 This also applied for speedbar access."
1285 :group 'org-imenu-and-speedbar
1286 :type 'integer)
1288 (defgroup org-table nil
1289 "Options concerning tables in Org-mode."
1290 :tag "Org Table"
1291 :group 'org)
1293 (defcustom org-enable-table-editor 'optimized
1294 "Non-nil means lines starting with \"|\" are handled by the table editor.
1295 When nil, such lines will be treated like ordinary lines.
1297 When equal to the symbol `optimized', the table editor will be optimized to
1298 do the following:
1299 - Automatic overwrite mode in front of whitespace in table fields.
1300 This makes the structure of the table stay in tact as long as the edited
1301 field does not exceed the column width.
1302 - Minimize the number of realigns. Normally, the table is aligned each time
1303 TAB or RET are pressed to move to another field. With optimization this
1304 happens only if changes to a field might have changed the column width.
1305 Optimization requires replacing the functions `self-insert-command',
1306 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1307 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1308 very good at guessing when a re-align will be necessary, but you can always
1309 force one with \\[org-ctrl-c-ctrl-c].
1311 If you would like to use the optimized version in Org-mode, but the
1312 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1314 This variable can be used to turn on and off the table editor during a session,
1315 but in order to toggle optimization, a restart is required.
1317 See also the variable `org-table-auto-blank-field'."
1318 :group 'org-table
1319 :type '(choice
1320 (const :tag "off" nil)
1321 (const :tag "on" t)
1322 (const :tag "on, optimized" optimized)))
1324 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1325 (version<= emacs-version "24.1"))
1326 "Non-nil means cluster self-insert commands for undo when possible.
1327 If this is set, then, like in the Emacs command loop, 20 consecutive
1328 characters will be undone together.
1329 This is configurable, because there is some impact on typing performance."
1330 :group 'org-table
1331 :type 'boolean)
1333 (defcustom org-table-tab-recognizes-table.el t
1334 "Non-nil means TAB will automatically notice a table.el table.
1335 When it sees such a table, it moves point into it and - if necessary -
1336 calls `table-recognize-table'."
1337 :group 'org-table-editing
1338 :type 'boolean)
1340 (defgroup org-link nil
1341 "Options concerning links in Org-mode."
1342 :tag "Org Link"
1343 :group 'org)
1345 (defvar org-link-abbrev-alist-local nil
1346 "Buffer-local version of `org-link-abbrev-alist', which see.
1347 The value of this is taken from the #+LINK lines.")
1348 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1350 (defcustom org-link-abbrev-alist nil
1351 "Alist of link abbreviations.
1352 The car of each element is a string, to be replaced at the start of a link.
1353 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1354 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1356 [[linkkey:tag][description]]
1358 The 'linkkey' must be a word word, starting with a letter, followed
1359 by letters, numbers, '-' or '_'.
1361 If REPLACE is a string, the tag will simply be appended to create the link.
1362 If the string contains \"%s\", the tag will be inserted there. If the string
1363 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1364 at that point (see the function `url-hexify-string'). If the string contains
1365 the specifier \"%(my-function)\", then the custom function `my-function' will
1366 be invoked: this function takes the tag as its only argument and must return
1367 a string.
1369 REPLACE may also be a function that will be called with the tag as the
1370 only argument to create the link, which should be returned as a string.
1372 See the manual for examples."
1373 :group 'org-link
1374 :type '(repeat
1375 (cons
1376 (string :tag "Protocol")
1377 (choice
1378 (string :tag "Format")
1379 (function)))))
1381 (defcustom org-descriptive-links t
1382 "Non-nil means Org will display descriptive links.
1383 E.g. [[http://orgmode.org][Org website]] will be displayed as
1384 \"Org Website\", hiding the link itself and just displaying its
1385 description. When set to `nil', Org will display the full links
1386 literally.
1388 You can interactively set the value of this variable by calling
1389 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1390 :group 'org-link
1391 :type 'boolean)
1393 (defcustom org-link-file-path-type 'adaptive
1394 "How the path name in file links should be stored.
1395 Valid values are:
1397 relative Relative to the current directory, i.e. the directory of the file
1398 into which the link is being inserted.
1399 absolute Absolute path, if possible with ~ for home directory.
1400 noabbrev Absolute path, no abbreviation of home directory.
1401 adaptive Use relative path for files in the current directory and sub-
1402 directories of it. For other files, use an absolute path."
1403 :group 'org-link
1404 :type '(choice
1405 (const relative)
1406 (const absolute)
1407 (const noabbrev)
1408 (const adaptive)))
1410 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1411 "Types of links that should be activated in Org-mode files.
1412 This is a list of symbols, each leading to the activation of a certain link
1413 type. In principle, it does not hurt to turn on most link types - there may
1414 be a small gain when turning off unused link types. The types are:
1416 bracket The recommended [[link][description]] or [[link]] links with hiding.
1417 angle Links in angular brackets that may contain whitespace like
1418 <bbdb:Carsten Dominik>.
1419 plain Plain links in normal text, no whitespace, like http://google.com.
1420 radio Text that is matched by a radio target, see manual for details.
1421 tag Tag settings in a headline (link to tag search).
1422 date Time stamps (link to calendar).
1423 footnote Footnote labels.
1425 Changing this variable requires a restart of Emacs to become effective."
1426 :group 'org-link
1427 :type '(set :greedy t
1428 (const :tag "Double bracket links" bracket)
1429 (const :tag "Angular bracket links" angle)
1430 (const :tag "Plain text links" plain)
1431 (const :tag "Radio target matches" radio)
1432 (const :tag "Tags" tag)
1433 (const :tag "Timestamps" date)
1434 (const :tag "Footnotes" footnote)))
1436 (defcustom org-make-link-description-function nil
1437 "Function to use for generating link descriptions from links.
1438 When nil, the link location will be used. This function must take
1439 two parameters: the first one is the link, the second one is the
1440 description generated by `org-insert-link'. The function should
1441 return the description to use."
1442 :group 'org-link
1443 :type 'function)
1445 (defgroup org-link-store nil
1446 "Options concerning storing links in Org-mode."
1447 :tag "Org Store Link"
1448 :group 'org-link)
1450 (defcustom org-url-hexify-p t
1451 "When non-nil, hexify URL when creating a link."
1452 :type 'boolean
1453 :version "24.3"
1454 :group 'org-link-store)
1456 (defcustom org-email-link-description-format "Email %c: %.30s"
1457 "Format of the description part of a link to an email or usenet message.
1458 The following %-escapes will be replaced by corresponding information:
1460 %F full \"From\" field
1461 %f name, taken from \"From\" field, address if no name
1462 %T full \"To\" field
1463 %t first name in \"To\" field, address if no name
1464 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1465 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1466 %s subject
1467 %d date
1468 %m message-id.
1470 You may use normal field width specification between the % and the letter.
1471 This is for example useful to limit the length of the subject.
1473 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1474 :group 'org-link-store
1475 :type 'string)
1477 (defcustom org-from-is-user-regexp
1478 (let (r1 r2)
1479 (when (and user-mail-address (not (string= user-mail-address "")))
1480 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1481 (when (and user-full-name (not (string= user-full-name "")))
1482 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1483 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1484 "Regexp matched against the \"From:\" header of an email or usenet message.
1485 It should match if the message is from the user him/herself."
1486 :group 'org-link-store
1487 :type 'regexp)
1489 (defcustom org-context-in-file-links t
1490 "Non-nil means file links from `org-store-link' contain context.
1491 A search string will be added to the file name with :: as separator and
1492 used to find the context when the link is activated by the command
1493 `org-open-at-point'. When this option is t, the entire active region
1494 will be placed in the search string of the file link. If set to a
1495 positive integer, only the first n lines of context will be stored.
1497 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1498 negates this setting for the duration of the command."
1499 :group 'org-link-store
1500 :type '(choice boolean integer))
1502 (defcustom org-keep-stored-link-after-insertion nil
1503 "Non-nil means keep link in list for entire session.
1505 The command `org-store-link' adds a link pointing to the current
1506 location to an internal list. These links accumulate during a session.
1507 The command `org-insert-link' can be used to insert links into any
1508 Org-mode file (offering completion for all stored links). When this
1509 option is nil, every link which has been inserted once using \\[org-insert-link]
1510 will be removed from the list, to make completing the unused links
1511 more efficient."
1512 :group 'org-link-store
1513 :type 'boolean)
1515 (defgroup org-link-follow nil
1516 "Options concerning following links in Org-mode."
1517 :tag "Org Follow Link"
1518 :group 'org-link)
1520 (defcustom org-link-translation-function nil
1521 "Function to translate links with different syntax to Org syntax.
1522 This can be used to translate links created for example by the Planner
1523 or emacs-wiki packages to Org syntax.
1524 The function must accept two parameters, a TYPE containing the link
1525 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1526 which is everything after the link protocol. It should return a cons
1527 with possibly modified values of type and path.
1528 Org contains a function for this, so if you set this variable to
1529 `org-translate-link-from-planner', you should be able follow many
1530 links created by planner."
1531 :group 'org-link-follow
1532 :type 'function)
1534 (defcustom org-follow-link-hook nil
1535 "Hook that is run after a link has been followed."
1536 :group 'org-link-follow
1537 :type 'hook)
1539 (defcustom org-tab-follows-link nil
1540 "Non-nil means on links TAB will follow the link.
1541 Needs to be set before org.el is loaded.
1542 This really should not be used, it does not make sense, and the
1543 implementation is bad."
1544 :group 'org-link-follow
1545 :type 'boolean)
1547 (defcustom org-return-follows-link nil
1548 "Non-nil means on links RET will follow the link."
1549 :group 'org-link-follow
1550 :type 'boolean)
1552 (defcustom org-mouse-1-follows-link
1553 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1554 "Non-nil means mouse-1 on a link will follow the link.
1555 A longer mouse click will still set point. Does not work on XEmacs.
1556 Needs to be set before org.el is loaded."
1557 :group 'org-link-follow
1558 :type 'boolean)
1560 (defcustom org-mark-ring-length 4
1561 "Number of different positions to be recorded in the ring.
1562 Changing this requires a restart of Emacs to work correctly."
1563 :group 'org-link-follow
1564 :type 'integer)
1566 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1567 "Non-nil means internal links in Org files must exactly match a headline.
1568 When nil, the link search tries to match a phrase with all words
1569 in the search text."
1570 :group 'org-link-follow
1571 :version "24.1"
1572 :type '(choice
1573 (const :tag "Use fuzzy text search" nil)
1574 (const :tag "Match only exact headline" t)
1575 (const :tag "Match exact headline or query to create it"
1576 query-to-create)))
1578 (defcustom org-link-frame-setup
1579 '((vm . vm-visit-folder-other-frame)
1580 (vm-imap . vm-visit-imap-folder-other-frame)
1581 (gnus . org-gnus-no-new-news)
1582 (file . find-file-other-window)
1583 (wl . wl-other-frame))
1584 "Setup the frame configuration for following links.
1585 When following a link with Emacs, it may often be useful to display
1586 this link in another window or frame. This variable can be used to
1587 set this up for the different types of links.
1588 For VM, use any of
1589 `vm-visit-folder'
1590 `vm-visit-folder-other-window'
1591 `vm-visit-folder-other-frame'
1592 For Gnus, use any of
1593 `gnus'
1594 `gnus-other-frame'
1595 `org-gnus-no-new-news'
1596 For FILE, use any of
1597 `find-file'
1598 `find-file-other-window'
1599 `find-file-other-frame'
1600 For Wanderlust use any of
1601 `wl'
1602 `wl-other-frame'
1603 For the calendar, use the variable `calendar-setup'.
1604 For BBDB, it is currently only possible to display the matches in
1605 another window."
1606 :group 'org-link-follow
1607 :type '(list
1608 (cons (const vm)
1609 (choice
1610 (const vm-visit-folder)
1611 (const vm-visit-folder-other-window)
1612 (const vm-visit-folder-other-frame)))
1613 (cons (const gnus)
1614 (choice
1615 (const gnus)
1616 (const gnus-other-frame)
1617 (const org-gnus-no-new-news)))
1618 (cons (const file)
1619 (choice
1620 (const find-file)
1621 (const find-file-other-window)
1622 (const find-file-other-frame)))
1623 (cons (const wl)
1624 (choice
1625 (const wl)
1626 (const wl-other-frame)))))
1628 (defcustom org-display-internal-link-with-indirect-buffer nil
1629 "Non-nil means use indirect buffer to display infile links.
1630 Activating internal links (from one location in a file to another location
1631 in the same file) normally just jumps to the location. When the link is
1632 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1633 is displayed in
1634 another window. When this option is set, the other window actually displays
1635 an indirect buffer clone of the current buffer, to avoid any visibility
1636 changes to the current buffer."
1637 :group 'org-link-follow
1638 :type 'boolean)
1640 (defcustom org-open-non-existing-files nil
1641 "Non-nil means `org-open-file' will open non-existing files.
1642 When nil, an error will be generated.
1643 This variable applies only to external applications because they
1644 might choke on non-existing files. If the link is to a file that
1645 will be opened in Emacs, the variable is ignored."
1646 :group 'org-link-follow
1647 :type 'boolean)
1649 (defcustom org-open-directory-means-index-dot-org nil
1650 "Non-nil means a link to a directory really means to index.org.
1651 When nil, following a directory link will run dired or open a finder/explorer
1652 window on that directory."
1653 :group 'org-link-follow
1654 :type 'boolean)
1656 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1657 "Function and arguments to call for following mailto links.
1658 This is a list with the first element being a Lisp function, and the
1659 remaining elements being arguments to the function. In string arguments,
1660 %a will be replaced by the address, and %s will be replaced by the subject
1661 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1662 :group 'org-link-follow
1663 :type '(choice
1664 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1665 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1666 (const :tag "message-mail" (message-mail "%a" "%s"))
1667 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1669 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1670 "Non-nil means ask for confirmation before executing shell links.
1671 Shell links can be dangerous: just think about a link
1673 [[shell:rm -rf ~/*][Google Search]]
1675 This link would show up in your Org-mode document as \"Google Search\",
1676 but really it would remove your entire home directory.
1677 Therefore we advise against setting this variable to nil.
1678 Just change it to `y-or-n-p' if you want to confirm with a
1679 single keystroke rather than having to type \"yes\"."
1680 :group 'org-link-follow
1681 :type '(choice
1682 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1683 (const :tag "with y-or-n (faster)" y-or-n-p)
1684 (const :tag "no confirmation (dangerous)" nil)))
1685 (put 'org-confirm-shell-link-function
1686 'safe-local-variable
1687 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1689 (defcustom org-confirm-shell-link-not-regexp ""
1690 "A regexp to skip confirmation for shell links."
1691 :group 'org-link-follow
1692 :version "24.1"
1693 :type 'regexp)
1695 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1696 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1697 Elisp links can be dangerous: just think about a link
1699 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1701 This link would show up in your Org-mode document as \"Google Search\",
1702 but really it would remove your entire home directory.
1703 Therefore we advise against setting this variable to nil.
1704 Just change it to `y-or-n-p' if you want to confirm with a
1705 single keystroke rather than having to type \"yes\"."
1706 :group 'org-link-follow
1707 :type '(choice
1708 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1709 (const :tag "with y-or-n (faster)" y-or-n-p)
1710 (const :tag "no confirmation (dangerous)" nil)))
1711 (put 'org-confirm-shell-link-function
1712 'safe-local-variable
1713 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1715 (defcustom org-confirm-elisp-link-not-regexp ""
1716 "A regexp to skip confirmation for Elisp links."
1717 :group 'org-link-follow
1718 :version "24.1"
1719 :type 'regexp)
1721 (defconst org-file-apps-defaults-gnu
1722 '((remote . emacs)
1723 (system . mailcap)
1724 (t . mailcap))
1725 "Default file applications on a UNIX or GNU/Linux system.
1726 See `org-file-apps'.")
1728 (defconst org-file-apps-defaults-macosx
1729 '((remote . emacs)
1730 (t . "open %s")
1731 (system . "open %s")
1732 ("ps.gz" . "gv %s")
1733 ("eps.gz" . "gv %s")
1734 ("dvi" . "xdvi %s")
1735 ("fig" . "xfig %s"))
1736 "Default file applications on a MacOS X system.
1737 The system \"open\" is known as a default, but we use X11 applications
1738 for some files for which the OS does not have a good default.
1739 See `org-file-apps'.")
1741 (defconst org-file-apps-defaults-windowsnt
1742 (list
1743 '(remote . emacs)
1744 (cons t
1745 (list (if (featurep 'xemacs)
1746 'mswindows-shell-execute
1747 'w32-shell-execute)
1748 "open" 'file))
1749 (cons 'system
1750 (list (if (featurep 'xemacs)
1751 'mswindows-shell-execute
1752 'w32-shell-execute)
1753 "open" 'file)))
1754 "Default file applications on a Windows NT system.
1755 The system \"open\" is used for most files.
1756 See `org-file-apps'.")
1758 (defcustom org-file-apps
1760 (auto-mode . emacs)
1761 ("\\.mm\\'" . default)
1762 ("\\.x?html?\\'" . default)
1763 ("\\.pdf\\'" . default)
1765 "External applications for opening `file:path' items in a document.
1766 Org-mode uses system defaults for different file types, but
1767 you can use this variable to set the application for a given file
1768 extension. The entries in this list are cons cells where the car identifies
1769 files and the cdr the corresponding command. Possible values for the
1770 file identifier are
1771 \"string\" A string as a file identifier can be interpreted in different
1772 ways, depending on its contents:
1774 - Alphanumeric characters only:
1775 Match links with this file extension.
1776 Example: (\"pdf\" . \"evince %s\")
1777 to open PDFs with evince.
1779 - Regular expression: Match links where the
1780 filename matches the regexp. If you want to
1781 use groups here, use shy groups.
1783 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1784 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1785 to open *.html and *.xhtml with firefox.
1787 - Regular expression which contains (non-shy) groups:
1788 Match links where the whole link, including \"::\", and
1789 anything after that, matches the regexp.
1790 In a custom command string, %1, %2, etc. are replaced with
1791 the parts of the link that were matched by the groups.
1792 For backwards compatibility, if a command string is given
1793 that does not use any of the group matches, this case is
1794 handled identically to the second one (i.e. match against
1795 file name only).
1796 In a custom lisp form, you can access the group matches with
1797 (match-string n link).
1799 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1800 to open [[file:document.pdf::5]] with evince at page 5.
1802 `directory' Matches a directory
1803 `remote' Matches a remote file, accessible through tramp or efs.
1804 Remote files most likely should be visited through Emacs
1805 because external applications cannot handle such paths.
1806 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1807 so all files Emacs knows how to handle. Using this with
1808 command `emacs' will open most files in Emacs. Beware that this
1809 will also open html files inside Emacs, unless you add
1810 (\"html\" . default) to the list as well.
1811 t Default for files not matched by any of the other options.
1812 `system' The system command to open files, like `open' on Windows
1813 and Mac OS X, and mailcap under GNU/Linux. This is the command
1814 that will be selected if you call `C-c C-o' with a double
1815 \\[universal-argument] \\[universal-argument] prefix.
1817 Possible values for the command are:
1818 `emacs' The file will be visited by the current Emacs process.
1819 `default' Use the default application for this file type, which is the
1820 association for t in the list, most likely in the system-specific
1821 part.
1822 This can be used to overrule an unwanted setting in the
1823 system-specific variable.
1824 `system' Use the system command for opening files, like \"open\".
1825 This command is specified by the entry whose car is `system'.
1826 Most likely, the system-specific version of this variable
1827 does define this command, but you can overrule/replace it
1828 here.
1829 string A command to be executed by a shell; %s will be replaced
1830 by the path to the file.
1831 sexp A Lisp form which will be evaluated. The file path will
1832 be available in the Lisp variable `file'.
1833 For more examples, see the system specific constants
1834 `org-file-apps-defaults-macosx'
1835 `org-file-apps-defaults-windowsnt'
1836 `org-file-apps-defaults-gnu'."
1837 :group 'org-link-follow
1838 :type '(repeat
1839 (cons (choice :value ""
1840 (string :tag "Extension")
1841 (const :tag "System command to open files" system)
1842 (const :tag "Default for unrecognized files" t)
1843 (const :tag "Remote file" remote)
1844 (const :tag "Links to a directory" directory)
1845 (const :tag "Any files that have Emacs modes"
1846 auto-mode))
1847 (choice :value ""
1848 (const :tag "Visit with Emacs" emacs)
1849 (const :tag "Use default" default)
1850 (const :tag "Use the system command" system)
1851 (string :tag "Command")
1852 (sexp :tag "Lisp form")))))
1854 (defcustom org-doi-server-url "http://dx.doi.org/"
1855 "The URL of the DOI server."
1856 :type 'string
1857 :version "24.3"
1858 :group 'org-link-follow)
1860 (defgroup org-refile nil
1861 "Options concerning refiling entries in Org-mode."
1862 :tag "Org Refile"
1863 :group 'org)
1865 (defcustom org-directory "~/org"
1866 "Directory with org files.
1867 This is just a default location to look for Org files. There is no need
1868 at all to put your files into this directory. It is only used in the
1869 following situations:
1871 1. When a capture template specifies a target file that is not an
1872 absolute path. The path will then be interpreted relative to
1873 `org-directory'
1874 2. When a capture note is filed away in an interactive way (when exiting the
1875 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1876 with `org-directory' as the default path."
1877 :group 'org-refile
1878 :group 'org-remember
1879 :group 'org-capture
1880 :type 'directory)
1882 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1883 "Default target for storing notes.
1884 Used as a fall back file for org-remember.el and org-capture.el, for
1885 templates that do not specify a target file."
1886 :group 'org-refile
1887 :group 'org-remember
1888 :group 'org-capture
1889 :type '(choice
1890 (const :tag "Default from remember-data-file" nil)
1891 file))
1893 (defcustom org-goto-interface 'outline
1894 "The default interface to be used for `org-goto'.
1895 Allowed values are:
1896 outline The interface shows an outline of the relevant file
1897 and the correct heading is found by moving through
1898 the outline or by searching with incremental search.
1899 outline-path-completion Headlines in the current buffer are offered via
1900 completion. This is the interface also used by
1901 the refile command."
1902 :group 'org-refile
1903 :type '(choice
1904 (const :tag "Outline" outline)
1905 (const :tag "Outline-path-completion" outline-path-completion)))
1907 (defcustom org-goto-max-level 5
1908 "Maximum target level when running `org-goto' with refile interface."
1909 :group 'org-refile
1910 :type 'integer)
1912 (defcustom org-reverse-note-order nil
1913 "Non-nil means store new notes at the beginning of a file or entry.
1914 When nil, new notes will be filed to the end of a file or entry.
1915 This can also be a list with cons cells of regular expressions that
1916 are matched against file names, and values."
1917 :group 'org-remember
1918 :group 'org-capture
1919 :group 'org-refile
1920 :type '(choice
1921 (const :tag "Reverse always" t)
1922 (const :tag "Reverse never" nil)
1923 (repeat :tag "By file name regexp"
1924 (cons regexp boolean))))
1926 (defcustom org-log-refile nil
1927 "Information to record when a task is refiled.
1929 Possible values are:
1931 nil Don't add anything
1932 time Add a time stamp to the task
1933 note Prompt for a note and add it with template `org-log-note-headings'
1935 This option can also be set with on a per-file-basis with
1937 #+STARTUP: nologrefile
1938 #+STARTUP: logrefile
1939 #+STARTUP: lognoterefile
1941 You can have local logging settings for a subtree by setting the LOGGING
1942 property to one or more of these keywords.
1944 When bulk-refiling from the agenda, the value `note' is forbidden and
1945 will temporarily be changed to `time'."
1946 :group 'org-refile
1947 :group 'org-progress
1948 :version "24.1"
1949 :type '(choice
1950 (const :tag "No logging" nil)
1951 (const :tag "Record timestamp" time)
1952 (const :tag "Record timestamp with note." note)))
1954 (defcustom org-refile-targets nil
1955 "Targets for refiling entries with \\[org-refile].
1956 This is a list of cons cells. Each cell contains:
1957 - a specification of the files to be considered, either a list of files,
1958 or a symbol whose function or variable value will be used to retrieve
1959 a file name or a list of file names. If you use `org-agenda-files' for
1960 that, all agenda files will be scanned for targets. Nil means consider
1961 headings in the current buffer.
1962 - A specification of how to find candidate refile targets. This may be
1963 any of:
1964 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1965 This tag has to be present in all target headlines, inheritance will
1966 not be considered.
1967 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1968 todo keyword.
1969 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1970 headlines that are refiling targets.
1971 - a cons cell (:level . N). Any headline of level N is considered a target.
1972 Note that, when `org-odd-levels-only' is set, level corresponds to
1973 order in hierarchy, not to the number of stars.
1974 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1975 Note that, when `org-odd-levels-only' is set, level corresponds to
1976 order in hierarchy, not to the number of stars.
1978 Each element of this list generates a set of possible targets.
1979 The union of these sets is presented (with completion) to
1980 the user by `org-refile'.
1982 You can set the variable `org-refile-target-verify-function' to a function
1983 to verify each headline found by the simple criteria above.
1985 When this variable is nil, all top-level headlines in the current buffer
1986 are used, equivalent to the value `((nil . (:level . 1))'."
1987 :group 'org-refile
1988 :type '(repeat
1989 (cons
1990 (choice :value org-agenda-files
1991 (const :tag "All agenda files" org-agenda-files)
1992 (const :tag "Current buffer" nil)
1993 (function) (variable) (file))
1994 (choice :tag "Identify target headline by"
1995 (cons :tag "Specific tag" (const :value :tag) (string))
1996 (cons :tag "TODO keyword" (const :value :todo) (string))
1997 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1998 (cons :tag "Level number" (const :value :level) (integer))
1999 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2001 (defcustom org-refile-target-verify-function nil
2002 "Function to verify if the headline at point should be a refile target.
2003 The function will be called without arguments, with point at the
2004 beginning of the headline. It should return t and leave point
2005 where it is if the headline is a valid target for refiling.
2007 If the target should not be selected, the function must return nil.
2008 In addition to this, it may move point to a place from where the search
2009 should be continued. For example, the function may decide that the entire
2010 subtree of the current entry should be excluded and move point to the end
2011 of the subtree."
2012 :group 'org-refile
2013 :type 'function)
2015 (defcustom org-refile-use-cache nil
2016 "Non-nil means cache refile targets to speed up the process.
2017 The cache for a particular file will be updated automatically when
2018 the buffer has been killed, or when any of the marker used for flagging
2019 refile targets no longer points at a live buffer.
2020 If you have added new entries to a buffer that might themselves be targets,
2021 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2022 find that easier, `C-u C-u C-u C-c C-w'."
2023 :group 'org-refile
2024 :version "24.1"
2025 :type 'boolean)
2027 (defcustom org-refile-use-outline-path nil
2028 "Non-nil means provide refile targets as paths.
2029 So a level 3 headline will be available as level1/level2/level3.
2031 When the value is `file', also include the file name (without directory)
2032 into the path. In this case, you can also stop the completion after
2033 the file name, to get entries inserted as top level in the file.
2035 When `full-file-path', include the full file path."
2036 :group 'org-refile
2037 :type '(choice
2038 (const :tag "Not" nil)
2039 (const :tag "Yes" t)
2040 (const :tag "Start with file name" file)
2041 (const :tag "Start with full file path" full-file-path)))
2043 (defcustom org-outline-path-complete-in-steps t
2044 "Non-nil means complete the outline path in hierarchical steps.
2045 When Org-mode uses the refile interface to select an outline path
2046 \(see variable `org-refile-use-outline-path'), the completion of
2047 the path can be done is a single go, or if can be done in steps down
2048 the headline hierarchy. Going in steps is probably the best if you
2049 do not use a special completion package like `ido' or `icicles'.
2050 However, when using these packages, going in one step can be very
2051 fast, while still showing the whole path to the entry."
2052 :group 'org-refile
2053 :type 'boolean)
2055 (defcustom org-refile-allow-creating-parent-nodes nil
2056 "Non-nil means allow to create new nodes as refile targets.
2057 New nodes are then created by adding \"/new node name\" to the completion
2058 of an existing node. When the value of this variable is `confirm',
2059 new node creation must be confirmed by the user (recommended)
2060 When nil, the completion must match an existing entry.
2062 Note that, if the new heading is not seen by the criteria
2063 listed in `org-refile-targets', multiple instances of the same
2064 heading would be created by trying again to file under the new
2065 heading."
2066 :group 'org-refile
2067 :type '(choice
2068 (const :tag "Never" nil)
2069 (const :tag "Always" t)
2070 (const :tag "Prompt for confirmation" confirm)))
2072 (defcustom org-refile-active-region-within-subtree nil
2073 "Non-nil means also refile active region within a subtree.
2075 By default `org-refile' doesn't allow refiling regions if they
2076 don't contain a set of subtrees, but it might be convenient to
2077 do so sometimes: in that case, the first line of the region is
2078 converted to a headline before refiling."
2079 :group 'org-refile
2080 :version "24.1"
2081 :type 'boolean)
2083 (defgroup org-todo nil
2084 "Options concerning TODO items in Org-mode."
2085 :tag "Org TODO"
2086 :group 'org)
2088 (defgroup org-progress nil
2089 "Options concerning Progress logging in Org-mode."
2090 :tag "Org Progress"
2091 :group 'org-time)
2093 (defvar org-todo-interpretation-widgets
2094 '((:tag "Sequence (cycling hits every state)" sequence)
2095 (:tag "Type (cycling directly to DONE)" type))
2096 "The available interpretation symbols for customizing `org-todo-keywords'.
2097 Interested libraries should add to this list.")
2099 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2100 "List of TODO entry keyword sequences and their interpretation.
2101 \\<org-mode-map>This is a list of sequences.
2103 Each sequence starts with a symbol, either `sequence' or `type',
2104 indicating if the keywords should be interpreted as a sequence of
2105 action steps, or as different types of TODO items. The first
2106 keywords are states requiring action - these states will select a headline
2107 for inclusion into the global TODO list Org-mode produces. If one of
2108 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2109 signify that no further action is necessary. If \"|\" is not found,
2110 the last keyword is treated as the only DONE state of the sequence.
2112 The command \\[org-todo] cycles an entry through these states, and one
2113 additional state where no keyword is present. For details about this
2114 cycling, see the manual.
2116 TODO keywords and interpretation can also be set on a per-file basis with
2117 the special #+SEQ_TODO and #+TYP_TODO lines.
2119 Each keyword can optionally specify a character for fast state selection
2120 \(in combination with the variable `org-use-fast-todo-selection')
2121 and specifiers for state change logging, using the same syntax that
2122 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2123 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2124 indicates to record a time stamp each time this state is selected.
2126 Each keyword may also specify if a timestamp or a note should be
2127 recorded when entering or leaving the state, by adding additional
2128 characters in the parenthesis after the keyword. This looks like this:
2129 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2130 record only the time of the state change. With X and Y being either
2131 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2132 Y when leaving the state if and only if the *target* state does not
2133 define X. You may omit any of the fast-selection key or X or /Y,
2134 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2136 For backward compatibility, this variable may also be just a list
2137 of keywords. In this case the interpretation (sequence or type) will be
2138 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2139 :group 'org-todo
2140 :group 'org-keywords
2141 :type '(choice
2142 (repeat :tag "Old syntax, just keywords"
2143 (string :tag "Keyword"))
2144 (repeat :tag "New syntax"
2145 (cons
2146 (choice
2147 :tag "Interpretation"
2148 ;;Quick and dirty way to see
2149 ;;`org-todo-interpretations'. This takes the
2150 ;;place of item arguments
2151 :convert-widget
2152 (lambda (widget)
2153 (widget-put widget
2154 :args (mapcar
2155 #'(lambda (x)
2156 (widget-convert
2157 (cons 'const x)))
2158 org-todo-interpretation-widgets))
2159 widget))
2160 (repeat
2161 (string :tag "Keyword"))))))
2163 (defvar org-todo-keywords-1 nil
2164 "All TODO and DONE keywords active in a buffer.")
2165 (make-variable-buffer-local 'org-todo-keywords-1)
2166 (defvar org-todo-keywords-for-agenda nil)
2167 (defvar org-done-keywords-for-agenda nil)
2168 (defvar org-drawers-for-agenda nil)
2169 (defvar org-todo-keyword-alist-for-agenda nil)
2170 (defvar org-tag-alist-for-agenda nil)
2171 (defvar org-agenda-contributing-files nil)
2172 (defvar org-not-done-keywords nil)
2173 (make-variable-buffer-local 'org-not-done-keywords)
2174 (defvar org-done-keywords nil)
2175 (make-variable-buffer-local 'org-done-keywords)
2176 (defvar org-todo-heads nil)
2177 (make-variable-buffer-local 'org-todo-heads)
2178 (defvar org-todo-sets nil)
2179 (make-variable-buffer-local 'org-todo-sets)
2180 (defvar org-todo-log-states nil)
2181 (make-variable-buffer-local 'org-todo-log-states)
2182 (defvar org-todo-kwd-alist nil)
2183 (make-variable-buffer-local 'org-todo-kwd-alist)
2184 (defvar org-todo-key-alist nil)
2185 (make-variable-buffer-local 'org-todo-key-alist)
2186 (defvar org-todo-key-trigger nil)
2187 (make-variable-buffer-local 'org-todo-key-trigger)
2189 (defcustom org-todo-interpretation 'sequence
2190 "Controls how TODO keywords are interpreted.
2191 This variable is in principle obsolete and is only used for
2192 backward compatibility, if the interpretation of todo keywords is
2193 not given already in `org-todo-keywords'. See that variable for
2194 more information."
2195 :group 'org-todo
2196 :group 'org-keywords
2197 :type '(choice (const sequence)
2198 (const type)))
2200 (defcustom org-use-fast-todo-selection t
2201 "Non-nil means use the fast todo selection scheme with C-c C-t.
2202 This variable describes if and under what circumstances the cycling
2203 mechanism for TODO keywords will be replaced by a single-key, direct
2204 selection scheme.
2206 When nil, fast selection is never used.
2208 When the symbol `prefix', it will be used when `org-todo' is called
2209 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2210 `C-u t' in an agenda buffer.
2212 When t, fast selection is used by default. In this case, the prefix
2213 argument forces cycling instead.
2215 In all cases, the special interface is only used if access keys have
2216 actually been assigned by the user, i.e. if keywords in the configuration
2217 are followed by a letter in parenthesis, like TODO(t)."
2218 :group 'org-todo
2219 :type '(choice
2220 (const :tag "Never" nil)
2221 (const :tag "By default" t)
2222 (const :tag "Only with C-u C-c C-t" prefix)))
2224 (defcustom org-provide-todo-statistics t
2225 "Non-nil means update todo statistics after insert and toggle.
2226 ALL-HEADLINES means update todo statistics by including headlines
2227 with no TODO keyword as well, counting them as not done.
2228 A list of TODO keywords means the same, but skip keywords that are
2229 not in this list.
2231 When this is set, todo statistics is updated in the parent of the
2232 current entry each time a todo state is changed."
2233 :group 'org-todo
2234 :type '(choice
2235 (const :tag "Yes, only for TODO entries" t)
2236 (const :tag "Yes, including all entries" 'all-headlines)
2237 (repeat :tag "Yes, for TODOs in this list"
2238 (string :tag "TODO keyword"))
2239 (other :tag "No TODO statistics" nil)))
2241 (defcustom org-hierarchical-todo-statistics t
2242 "Non-nil means TODO statistics covers just direct children.
2243 When nil, all entries in the subtree are considered.
2244 This has only an effect if `org-provide-todo-statistics' is set.
2245 To set this to nil for only a single subtree, use a COOKIE_DATA
2246 property and include the word \"recursive\" into the value."
2247 :group 'org-todo
2248 :type 'boolean)
2250 (defcustom org-after-todo-state-change-hook nil
2251 "Hook which is run after the state of a TODO item was changed.
2252 The new state (a string with a TODO keyword, or nil) is available in the
2253 Lisp variable `org-state'."
2254 :group 'org-todo
2255 :type 'hook)
2257 (defvar org-blocker-hook nil
2258 "Hook for functions that are allowed to block a state change.
2260 Each function gets as its single argument a property list, see
2261 `org-trigger-hook' for more information about this list.
2263 If any of the functions in this hook returns nil, the state change
2264 is blocked.")
2266 (defvar org-trigger-hook nil
2267 "Hook for functions that are triggered by a state change.
2269 Each function gets as its single argument a property list with at least
2270 the following elements:
2272 (:type type-of-change :position pos-at-entry-start
2273 :from old-state :to new-state)
2275 Depending on the type, more properties may be present.
2277 This mechanism is currently implemented for:
2279 TODO state changes
2280 ------------------
2281 :type todo-state-change
2282 :from previous state (keyword as a string), or nil, or a symbol
2283 'todo' or 'done', to indicate the general type of state.
2284 :to new state, like in :from")
2286 (defcustom org-enforce-todo-dependencies nil
2287 "Non-nil means undone TODO entries will block switching the parent to DONE.
2288 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2289 be blocked if any prior sibling is not yet done.
2290 Finally, if the parent is blocked because of ordered siblings of its own,
2291 the child will also be blocked."
2292 :set (lambda (var val)
2293 (set var val)
2294 (if val
2295 (add-hook 'org-blocker-hook
2296 'org-block-todo-from-children-or-siblings-or-parent)
2297 (remove-hook 'org-blocker-hook
2298 'org-block-todo-from-children-or-siblings-or-parent)))
2299 :group 'org-todo
2300 :type 'boolean)
2302 (defcustom org-enforce-todo-checkbox-dependencies nil
2303 "Non-nil means unchecked boxes will block switching the parent to DONE.
2304 When this is nil, checkboxes have no influence on switching TODO states.
2305 When non-nil, you first need to check off all check boxes before the TODO
2306 entry can be switched to DONE.
2307 This variable needs to be set before org.el is loaded, and you need to
2308 restart Emacs after a change to make the change effective. The only way
2309 to change is while Emacs is running is through the customize interface."
2310 :set (lambda (var val)
2311 (set var val)
2312 (if val
2313 (add-hook 'org-blocker-hook
2314 'org-block-todo-from-checkboxes)
2315 (remove-hook 'org-blocker-hook
2316 'org-block-todo-from-checkboxes)))
2317 :group 'org-todo
2318 :type 'boolean)
2320 (defcustom org-treat-insert-todo-heading-as-state-change nil
2321 "Non-nil means inserting a TODO heading is treated as state change.
2322 So when the command \\[org-insert-todo-heading] is used, state change
2323 logging will apply if appropriate. When nil, the new TODO item will
2324 be inserted directly, and no logging will take place."
2325 :group 'org-todo
2326 :type 'boolean)
2328 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2329 "Non-nil means switching TODO states with S-cursor counts as state change.
2330 This is the default behavior. However, setting this to nil allows a
2331 convenient way to select a TODO state and bypass any logging associated
2332 with that."
2333 :group 'org-todo
2334 :type 'boolean)
2336 (defcustom org-todo-state-tags-triggers nil
2337 "Tag changes that should be triggered by TODO state changes.
2338 This is a list. Each entry is
2340 (state-change (tag . flag) .......)
2342 State-change can be a string with a state, and empty string to indicate the
2343 state that has no TODO keyword, or it can be one of the symbols `todo'
2344 or `done', meaning any not-done or done state, respectively."
2345 :group 'org-todo
2346 :group 'org-tags
2347 :type '(repeat
2348 (cons (choice :tag "When changing to"
2349 (const :tag "Not-done state" todo)
2350 (const :tag "Done state" done)
2351 (string :tag "State"))
2352 (repeat
2353 (cons :tag "Tag action"
2354 (string :tag "Tag")
2355 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2357 (defcustom org-log-done nil
2358 "Information to record when a task moves to the DONE state.
2360 Possible values are:
2362 nil Don't add anything, just change the keyword
2363 time Add a time stamp to the task
2364 note Prompt for a note and add it with template `org-log-note-headings'
2366 This option can also be set with on a per-file-basis with
2368 #+STARTUP: nologdone
2369 #+STARTUP: logdone
2370 #+STARTUP: lognotedone
2372 You can have local logging settings for a subtree by setting the LOGGING
2373 property to one or more of these keywords."
2374 :group 'org-todo
2375 :group 'org-progress
2376 :type '(choice
2377 (const :tag "No logging" nil)
2378 (const :tag "Record CLOSED timestamp" time)
2379 (const :tag "Record CLOSED timestamp with note." note)))
2381 ;; Normalize old uses of org-log-done.
2382 (cond
2383 ((eq org-log-done t) (setq org-log-done 'time))
2384 ((and (listp org-log-done) (memq 'done org-log-done))
2385 (setq org-log-done 'note)))
2387 (defcustom org-log-reschedule nil
2388 "Information to record when the scheduling date of a tasks is modified.
2390 Possible values are:
2392 nil Don't add anything, just change the date
2393 time Add a time stamp to the task
2394 note Prompt for a note and add it with template `org-log-note-headings'
2396 This option can also be set with on a per-file-basis with
2398 #+STARTUP: nologreschedule
2399 #+STARTUP: logreschedule
2400 #+STARTUP: lognotereschedule"
2401 :group 'org-todo
2402 :group 'org-progress
2403 :type '(choice
2404 (const :tag "No logging" nil)
2405 (const :tag "Record timestamp" time)
2406 (const :tag "Record timestamp with note." note)))
2408 (defcustom org-log-redeadline nil
2409 "Information to record when the deadline date of a tasks is modified.
2411 Possible values are:
2413 nil Don't add anything, just change the date
2414 time Add a time stamp to the task
2415 note Prompt for a note and add it with template `org-log-note-headings'
2417 This option can also be set with on a per-file-basis with
2419 #+STARTUP: nologredeadline
2420 #+STARTUP: logredeadline
2421 #+STARTUP: lognoteredeadline
2423 You can have local logging settings for a subtree by setting the LOGGING
2424 property to one or more of these keywords."
2425 :group 'org-todo
2426 :group 'org-progress
2427 :type '(choice
2428 (const :tag "No logging" nil)
2429 (const :tag "Record timestamp" time)
2430 (const :tag "Record timestamp with note." note)))
2432 (defcustom org-log-note-clock-out nil
2433 "Non-nil means record a note when clocking out of an item.
2434 This can also be configured on a per-file basis by adding one of
2435 the following lines anywhere in the buffer:
2437 #+STARTUP: lognoteclock-out
2438 #+STARTUP: nolognoteclock-out"
2439 :group 'org-todo
2440 :group 'org-progress
2441 :type 'boolean)
2443 (defcustom org-log-done-with-time t
2444 "Non-nil means the CLOSED time stamp will contain date and time.
2445 When nil, only the date will be recorded."
2446 :group 'org-progress
2447 :type 'boolean)
2449 (defcustom org-log-note-headings
2450 '((done . "CLOSING NOTE %t")
2451 (state . "State %-12s from %-12S %t")
2452 (note . "Note taken on %t")
2453 (reschedule . "Rescheduled from %S on %t")
2454 (delschedule . "Not scheduled, was %S on %t")
2455 (redeadline . "New deadline from %S on %t")
2456 (deldeadline . "Removed deadline, was %S on %t")
2457 (refile . "Refiled on %t")
2458 (clock-out . ""))
2459 "Headings for notes added to entries.
2460 The value is an alist, with the car being a symbol indicating the note
2461 context, and the cdr is the heading to be used. The heading may also be the
2462 empty string.
2463 %t in the heading will be replaced by a time stamp.
2464 %T will be an active time stamp instead the default inactive one
2465 %d will be replaced by a short-format time stamp.
2466 %D will be replaced by an active short-format time stamp.
2467 %s will be replaced by the new TODO state, in double quotes.
2468 %S will be replaced by the old TODO state, in double quotes.
2469 %u will be replaced by the user name.
2470 %U will be replaced by the full user name.
2472 In fact, it is not a good idea to change the `state' entry, because
2473 agenda log mode depends on the format of these entries."
2474 :group 'org-todo
2475 :group 'org-progress
2476 :type '(list :greedy t
2477 (cons (const :tag "Heading when closing an item" done) string)
2478 (cons (const :tag
2479 "Heading when changing todo state (todo sequence only)"
2480 state) string)
2481 (cons (const :tag "Heading when just taking a note" note) string)
2482 (cons (const :tag "Heading when clocking out" clock-out) string)
2483 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2484 (cons (const :tag "Heading when rescheduling" reschedule) string)
2485 (cons (const :tag "Heading when changing deadline" redeadline) string)
2486 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2487 (cons (const :tag "Heading when refiling" refile) string)))
2489 (unless (assq 'note org-log-note-headings)
2490 (push '(note . "%t") org-log-note-headings))
2492 (defcustom org-log-into-drawer nil
2493 "Non-nil means insert state change notes and time stamps into a drawer.
2494 When nil, state changes notes will be inserted after the headline and
2495 any scheduling and clock lines, but not inside a drawer.
2497 The value of this variable should be the name of the drawer to use.
2498 LOGBOOK is proposed as the default drawer for this purpose, you can
2499 also set this to a string to define the drawer of your choice.
2501 A value of t is also allowed, representing \"LOGBOOK\".
2503 If this variable is set, `org-log-state-notes-insert-after-drawers'
2504 will be ignored.
2506 You can set the property LOG_INTO_DRAWER to overrule this setting for
2507 a subtree."
2508 :group 'org-todo
2509 :group 'org-progress
2510 :type '(choice
2511 (const :tag "Not into a drawer" nil)
2512 (const :tag "LOGBOOK" t)
2513 (string :tag "Other")))
2515 (if (fboundp 'defvaralias)
2516 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2518 (defun org-log-into-drawer ()
2519 "Return the value of `org-log-into-drawer', but let properties overrule.
2520 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2521 used instead of the default value."
2522 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2523 (cond
2524 ((not p) org-log-into-drawer)
2525 ((equal p "nil") nil)
2526 ((equal p "t") "LOGBOOK")
2527 (t p))))
2529 (defcustom org-log-state-notes-insert-after-drawers nil
2530 "Non-nil means insert state change notes after any drawers in entry.
2531 Only the drawers that *immediately* follow the headline and the
2532 deadline/scheduled line are skipped.
2533 When nil, insert notes right after the heading and perhaps the line
2534 with deadline/scheduling if present.
2536 This variable will have no effect if `org-log-into-drawer' is
2537 set."
2538 :group 'org-todo
2539 :group 'org-progress
2540 :type 'boolean)
2542 (defcustom org-log-states-order-reversed t
2543 "Non-nil means the latest state note will be directly after heading.
2544 When nil, the state change notes will be ordered according to time."
2545 :group 'org-todo
2546 :group 'org-progress
2547 :type 'boolean)
2549 (defcustom org-todo-repeat-to-state nil
2550 "The TODO state to which a repeater should return the repeating task.
2551 By default this is the first task in a TODO sequence, or the previous state
2552 in a TODO_TYP set. But you can specify another task here.
2553 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2554 :group 'org-todo
2555 :version "24.1"
2556 :type '(choice (const :tag "Head of sequence" nil)
2557 (string :tag "Specific state")))
2559 (defcustom org-log-repeat 'time
2560 "Non-nil means record moving through the DONE state when triggering repeat.
2561 An auto-repeating task is immediately switched back to TODO when
2562 marked DONE. If you are not logging state changes (by adding \"@\"
2563 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2564 record a closing note, there will be no record of the task moving
2565 through DONE. This variable forces taking a note anyway.
2567 nil Don't force a record
2568 time Record a time stamp
2569 note Prompt for a note and add it with template `org-log-note-headings'
2571 This option can also be set with on a per-file-basis with
2573 #+STARTUP: nologrepeat
2574 #+STARTUP: logrepeat
2575 #+STARTUP: lognoterepeat
2577 You can have local logging settings for a subtree by setting the LOGGING
2578 property to one or more of these keywords."
2579 :group 'org-todo
2580 :group 'org-progress
2581 :type '(choice
2582 (const :tag "Don't force a record" nil)
2583 (const :tag "Force recording the DONE state" time)
2584 (const :tag "Force recording a note with the DONE state" note)))
2587 (defgroup org-priorities nil
2588 "Priorities in Org-mode."
2589 :tag "Org Priorities"
2590 :group 'org-todo)
2592 (defcustom org-enable-priority-commands t
2593 "Non-nil means priority commands are active.
2594 When nil, these commands will be disabled, so that you never accidentally
2595 set a priority."
2596 :group 'org-priorities
2597 :type 'boolean)
2599 (defcustom org-highest-priority ?A
2600 "The highest priority of TODO items. A character like ?A, ?B etc.
2601 Must have a smaller ASCII number than `org-lowest-priority'."
2602 :group 'org-priorities
2603 :type 'character)
2605 (defcustom org-lowest-priority ?C
2606 "The lowest priority of TODO items. A character like ?A, ?B etc.
2607 Must have a larger ASCII number than `org-highest-priority'."
2608 :group 'org-priorities
2609 :type 'character)
2611 (defcustom org-default-priority ?B
2612 "The default priority of TODO items.
2613 This is the priority an item gets if no explicit priority is given.
2614 When starting to cycle on an empty priority the first step in the cycle
2615 depends on `org-priority-start-cycle-with-default'. The resulting first
2616 step priority must not exceed the range from `org-highest-priority' to
2617 `org-lowest-priority' which means that `org-default-priority' has to be
2618 in this range exclusive or inclusive the range boundaries. Else the
2619 first step refuses to set the default and the second will fall back
2620 to (depending on the command used) the highest or lowest priority."
2621 :group 'org-priorities
2622 :type 'character)
2624 (defcustom org-priority-start-cycle-with-default t
2625 "Non-nil means start with default priority when starting to cycle.
2626 When this is nil, the first step in the cycle will be (depending on the
2627 command used) one higher or lower than the default priority.
2628 See also `org-default-priority'."
2629 :group 'org-priorities
2630 :type 'boolean)
2632 (defcustom org-get-priority-function nil
2633 "Function to extract the priority from a string.
2634 The string is normally the headline. If this is nil Org computes the
2635 priority from the priority cookie like [#A] in the headline. It returns
2636 an integer, increasing by 1000 for each priority level.
2637 The user can set a different function here, which should take a string
2638 as an argument and return the numeric priority."
2639 :group 'org-priorities
2640 :version "24.1"
2641 :type 'function)
2643 (defgroup org-time nil
2644 "Options concerning time stamps and deadlines in Org-mode."
2645 :tag "Org Time"
2646 :group 'org)
2648 (defcustom org-insert-labeled-timestamps-at-point nil
2649 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2650 When nil, these labeled time stamps are forces into the second line of an
2651 entry, just after the headline. When scheduling from the global TODO list,
2652 the time stamp will always be forced into the second line."
2653 :group 'org-time
2654 :type 'boolean)
2656 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2657 "Formats for `format-time-string' which are used for time stamps.
2658 It is not recommended to change this constant.")
2660 (defcustom org-time-stamp-rounding-minutes '(0 5)
2661 "Number of minutes to round time stamps to.
2662 These are two values, the first applies when first creating a time stamp.
2663 The second applies when changing it with the commands `S-up' and `S-down'.
2664 When changing the time stamp, this means that it will change in steps
2665 of N minutes, as given by the second value.
2667 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2668 numbers should be factors of 60, so for example 5, 10, 15.
2670 When this is larger than 1, you can still force an exact time stamp by using
2671 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2672 and by using a prefix arg to `S-up/down' to specify the exact number
2673 of minutes to shift."
2674 :group 'org-time
2675 :get #'(lambda (var) ; Make sure both elements are there
2676 (if (integerp (default-value var))
2677 (list (default-value var) 5)
2678 (default-value var)))
2679 :type '(list
2680 (integer :tag "when inserting times")
2681 (integer :tag "when modifying times")))
2683 ;; Normalize old customizations of this variable.
2684 (when (integerp org-time-stamp-rounding-minutes)
2685 (setq org-time-stamp-rounding-minutes
2686 (list org-time-stamp-rounding-minutes
2687 org-time-stamp-rounding-minutes)))
2689 (defcustom org-display-custom-times nil
2690 "Non-nil means overlay custom formats over all time stamps.
2691 The formats are defined through the variable `org-time-stamp-custom-formats'.
2692 To turn this on on a per-file basis, insert anywhere in the file:
2693 #+STARTUP: customtime"
2694 :group 'org-time
2695 :set 'set-default
2696 :type 'sexp)
2697 (make-variable-buffer-local 'org-display-custom-times)
2699 (defcustom org-time-stamp-custom-formats
2700 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2701 "Custom formats for time stamps. See `format-time-string' for the syntax.
2702 These are overlaid over the default ISO format if the variable
2703 `org-display-custom-times' is set. Time like %H:%M should be at the
2704 end of the second format. The custom formats are also honored by export
2705 commands, if custom time display is turned on at the time of export."
2706 :group 'org-time
2707 :type 'sexp)
2709 (defun org-time-stamp-format (&optional long inactive)
2710 "Get the right format for a time string."
2711 (let ((f (if long (cdr org-time-stamp-formats)
2712 (car org-time-stamp-formats))))
2713 (if inactive
2714 (concat "[" (substring f 1 -1) "]")
2715 f)))
2717 (defcustom org-time-clocksum-format
2718 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2719 "The format string used when creating CLOCKSUM lines.
2720 This is also used when Org mode generates a time duration.
2722 The value can be a single format string containing two
2723 %-sequences, which will be filled with the number of hours and
2724 minutes in that order.
2726 Alternatively, the value can be a plist associating any of the
2727 keys :years, :months, :weeks, :days, :hours or :minutes with
2728 format strings. The time duration is formatted using only the
2729 time components that are needed and concatenating the results.
2730 If a time unit in absent, it falls back to the next smallest
2731 unit.
2733 The keys :require-years, :require-months, :require-days,
2734 :require-weeks, :require-hours, :require-minutes are also
2735 meaningful. A non-nil value for these keys indicates that the
2736 corresponding time component should always be included, even if
2737 its value is 0.
2740 For example,
2742 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2743 :require-minutes t)
2745 means durations longer than a day will be expressed in days,
2746 hours and minutes, and durations less than a day will always be
2747 expressed in hours and minutes (even for durations less than an
2748 hour).
2750 The value
2752 \(:days \"%dd\" :minutes \"%dm\")
2754 means durations longer than a day will be expressed in days and
2755 minutes, and durations less than a day will be expressed entirely
2756 in minutes (even for durations longer than an hour)."
2757 :group 'org-time
2758 :type '(choice (string :tag "Format string")
2759 (set :tag "Plist"
2760 (group :inline t (const :tag "Years" :years)
2761 (string :tag "Format string"))
2762 (group :inline t
2763 (const :tag "Always show years" :require-years)
2764 (const t))
2765 (group :inline t (const :tag "Months" :months)
2766 (string :tag "Format string"))
2767 (group :inline t
2768 (const :tag "Always show months" :require-months)
2769 (const t))
2770 (group :inline t (const :tag "Weeks" :weeks)
2771 (string :tag "Format string"))
2772 (group :inline t
2773 (const :tag "Always show weeks" :require-weeks)
2774 (const t))
2775 (group :inline t (const :tag "Days" :days)
2776 (string :tag "Format string"))
2777 (group :inline t
2778 (const :tag "Always show days" :require-days)
2779 (const t))
2780 (group :inline t (const :tag "Hours" :hours)
2781 (string :tag "Format string"))
2782 (group :inline t
2783 (const :tag "Always show hours" :require-hours)
2784 (const t))
2785 (group :inline t (const :tag "Minutes" :minutes)
2786 (string :tag "Format string"))
2787 (group :inline t
2788 (const :tag "Always show minutes" :require-minutes)
2789 (const t)))))
2791 (defcustom org-time-clocksum-use-fractional nil
2792 "If non-nil, \\[org-clock-display] uses fractional times.
2793 org-mode generates a time duration."
2794 :group 'org-time
2795 :type 'boolean)
2797 (defcustom org-time-clocksum-fractional-format "%.2f"
2798 "The format string used when creating CLOCKSUM lines,
2799 or when Org mode generates a time duration, if
2800 `org-time-clocksum-use-fractional' is enabled.
2802 The value can be a single format string containing one
2803 %-sequence, which will be filled with the number of hours as
2804 a float.
2806 Alternatively, the value can be a plist associating any of the
2807 keys :years, :months, :weeks, :days, :hours or :minutes with
2808 a format string. The time duration is formatted using the
2809 largest time unit which gives a non-zero integer part. If all
2810 specified formats have zero integer part, the smallest time unit
2811 is used."
2812 :group 'org-time
2813 :type '(choice (string :tag "Format string")
2814 (set (group :inline t (const :tag "Years" :years)
2815 (string :tag "Format string"))
2816 (group :inline t (const :tag "Months" :months)
2817 (string :tag "Format string"))
2818 (group :inline t (const :tag "Weeks" :weeks)
2819 (string :tag "Format string"))
2820 (group :inline t (const :tag "Days" :days)
2821 (string :tag "Format string"))
2822 (group :inline t (const :tag "Hours" :hours)
2823 (string :tag "Format string"))
2824 (group :inline t (const :tag "Minutes" :minutes)
2825 (string :tag "Format string")))))
2827 (defcustom org-deadline-warning-days 14
2828 "No. of days before expiration during which a deadline becomes active.
2829 This variable governs the display in sparse trees and in the agenda.
2830 When 0 or negative, it means use this number (the absolute value of it)
2831 even if a deadline has a different individual lead time specified.
2833 Custom commands can set this variable in the options section."
2834 :group 'org-time
2835 :group 'org-agenda-daily/weekly
2836 :type 'integer)
2838 (defcustom org-read-date-prefer-future t
2839 "Non-nil means assume future for incomplete date input from user.
2840 This affects the following situations:
2841 1. The user gives a month but not a year.
2842 For example, if it is April and you enter \"feb 2\", this will be read
2843 as Feb 2, *next* year. \"May 5\", however, will be this year.
2844 2. The user gives a day, but no month.
2845 For example, if today is the 15th, and you enter \"3\", Org-mode will
2846 read this as the third of *next* month. However, if you enter \"17\",
2847 it will be considered as *this* month.
2849 If you set this variable to the symbol `time', then also the following
2850 will work:
2852 3. If the user gives a time.
2853 If the time is before now, it will be interpreted as tomorrow.
2855 Currently none of this works for ISO week specifications.
2857 When this option is nil, the current day, month and year will always be
2858 used as defaults.
2860 See also `org-agenda-jump-prefer-future'."
2861 :group 'org-time
2862 :type '(choice
2863 (const :tag "Never" nil)
2864 (const :tag "Check month and day" t)
2865 (const :tag "Check month, day, and time" time)))
2867 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2868 "Should the agenda jump command prefer the future for incomplete dates?
2869 The default is to do the same as configured in `org-read-date-prefer-future'.
2870 But you can also set a deviating value here.
2871 This may t or nil, or the symbol `org-read-date-prefer-future'."
2872 :group 'org-agenda
2873 :group 'org-time
2874 :version "24.1"
2875 :type '(choice
2876 (const :tag "Use org-read-date-prefer-future"
2877 org-read-date-prefer-future)
2878 (const :tag "Never" nil)
2879 (const :tag "Always" t)))
2881 (defcustom org-read-date-force-compatible-dates t
2882 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2884 Depending on the system Emacs is running on, certain dates cannot
2885 be represented with the type used internally to represent time.
2886 Dates between 1970-1-1 and 2038-1-1 can always be represented
2887 correctly. Some systems allow for earlier dates, some for later,
2888 some for both. One way to find out it to insert any date into an
2889 Org buffer, putting the cursor on the year and hitting S-up and
2890 S-down to test the range.
2892 When this variable is set to t, the date/time prompt will not let
2893 you specify dates outside the 1970-2037 range, so it is certain that
2894 these dates will work in whatever version of Emacs you are
2895 running, and also that you can move a file from one Emacs implementation
2896 to another. WHenever Org is forcing the year for you, it will display
2897 a message and beep.
2899 When this variable is nil, Org will check if the date is
2900 representable in the specific Emacs implementation you are using.
2901 If not, it will force a year, usually the current year, and beep
2902 to remind you. Currently this setting is not recommended because
2903 the likelihood that you will open your Org files in an Emacs that
2904 has limited date range is not negligible.
2906 A workaround for this problem is to use diary sexp dates for time
2907 stamps outside of this range."
2908 :group 'org-time
2909 :version "24.1"
2910 :type 'boolean)
2912 (defcustom org-read-date-display-live t
2913 "Non-nil means display current interpretation of date prompt live.
2914 This display will be in an overlay, in the minibuffer."
2915 :group 'org-time
2916 :type 'boolean)
2918 (defcustom org-read-date-popup-calendar t
2919 "Non-nil means pop up a calendar when prompting for a date.
2920 In the calendar, the date can be selected with mouse-1. However, the
2921 minibuffer will also be active, and you can simply enter the date as well.
2922 When nil, only the minibuffer will be available."
2923 :group 'org-time
2924 :type 'boolean)
2925 (if (fboundp 'defvaralias)
2926 (defvaralias 'org-popup-calendar-for-date-prompt
2927 'org-read-date-popup-calendar))
2929 (defcustom org-read-date-minibuffer-setup-hook nil
2930 "Hook to be used to set up keys for the date/time interface.
2931 Add key definitions to `minibuffer-local-map', which will be a temporary
2932 copy."
2933 :group 'org-time
2934 :type 'hook)
2936 (defcustom org-extend-today-until 0
2937 "The hour when your day really ends. Must be an integer.
2938 This has influence for the following applications:
2939 - When switching the agenda to \"today\". It it is still earlier than
2940 the time given here, the day recognized as TODAY is actually yesterday.
2941 - When a date is read from the user and it is still before the time given
2942 here, the current date and time will be assumed to be yesterday, 23:59.
2943 Also, timestamps inserted in capture templates follow this rule.
2945 IMPORTANT: This is a feature whose implementation is and likely will
2946 remain incomplete. Really, it is only here because past midnight seems to
2947 be the favorite working time of John Wiegley :-)"
2948 :group 'org-time
2949 :type 'integer)
2951 (defcustom org-use-effective-time nil
2952 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2953 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2954 \"effective time\" of any timestamps between midnight and 8am will be
2955 23:59 of the previous day."
2956 :group 'org-time
2957 :version "24.1"
2958 :type 'boolean)
2960 (defcustom org-use-last-clock-out-time-as-effective-time nil
2961 "When non-nil, use the last clock out time for `org-todo'.
2962 Note that this option has precedence over the combined use of
2963 `org-use-effective-time' and `org-extend-today-until'."
2964 :group 'org-time
2965 ;; :version "24.3"
2966 :type 'boolean)
2968 (defcustom org-edit-timestamp-down-means-later nil
2969 "Non-nil means S-down will increase the time in a time stamp.
2970 When nil, S-up will increase."
2971 :group 'org-time
2972 :type 'boolean)
2974 (defcustom org-calendar-follow-timestamp-change t
2975 "Non-nil means make the calendar window follow timestamp changes.
2976 When a timestamp is modified and the calendar window is visible, it will be
2977 moved to the new date."
2978 :group 'org-time
2979 :type 'boolean)
2981 (defgroup org-tags nil
2982 "Options concerning tags in Org-mode."
2983 :tag "Org Tags"
2984 :group 'org)
2986 (defcustom org-tag-alist nil
2987 "List of tags allowed in Org-mode files.
2988 When this list is nil, Org-mode will base TAG input on what is already in the
2989 buffer.
2990 The value of this variable is an alist, the car of each entry must be a
2991 keyword as a string, the cdr may be a character that is used to select
2992 that tag through the fast-tag-selection interface.
2993 See the manual for details."
2994 :group 'org-tags
2995 :type '(repeat
2996 (choice
2997 (cons (string :tag "Tag name")
2998 (character :tag "Access char"))
2999 (list :tag "Start radio group"
3000 (const :startgroup)
3001 (option (string :tag "Group description")))
3002 (list :tag "End radio group"
3003 (const :endgroup)
3004 (option (string :tag "Group description")))
3005 (const :tag "New line" (:newline)))))
3007 (defcustom org-tag-persistent-alist nil
3008 "List of tags that will always appear in all Org-mode files.
3009 This is in addition to any in buffer settings or customizations
3010 of `org-tag-alist'.
3011 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3012 The value of this variable is an alist, the car of each entry must be a
3013 keyword as a string, the cdr may be a character that is used to select
3014 that tag through the fast-tag-selection interface.
3015 See the manual for details.
3016 To disable these tags on a per-file basis, insert anywhere in the file:
3017 #+STARTUP: noptag"
3018 :group 'org-tags
3019 :type '(repeat
3020 (choice
3021 (cons (string :tag "Tag name")
3022 (character :tag "Access char"))
3023 (const :tag "Start radio group" (:startgroup))
3024 (const :tag "End radio group" (:endgroup))
3025 (const :tag "New line" (:newline)))))
3027 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3028 "If non-nil, always offer completion for all tags of all agenda files.
3029 Instead of customizing this variable directly, you might want to
3030 set it locally for capture buffers, because there no list of
3031 tags in that file can be created dynamically (there are none).
3033 (add-hook 'org-capture-mode-hook
3034 (lambda ()
3035 (set (make-local-variable
3036 'org-complete-tags-always-offer-all-agenda-tags)
3037 t)))"
3038 :group 'org-tags
3039 :version "24.1"
3040 :type 'boolean)
3042 (defvar org-file-tags nil
3043 "List of tags that can be inherited by all entries in the file.
3044 The tags will be inherited if the variable `org-use-tag-inheritance'
3045 says they should be.
3046 This variable is populated from #+FILETAGS lines.")
3048 (defcustom org-use-fast-tag-selection 'auto
3049 "Non-nil means use fast tag selection scheme.
3050 This is a special interface to select and deselect tags with single keys.
3051 When nil, fast selection is never used.
3052 When the symbol `auto', fast selection is used if and only if selection
3053 characters for tags have been configured, either through the variable
3054 `org-tag-alist' or through a #+TAGS line in the buffer.
3055 When t, fast selection is always used and selection keys are assigned
3056 automatically if necessary."
3057 :group 'org-tags
3058 :type '(choice
3059 (const :tag "Always" t)
3060 (const :tag "Never" nil)
3061 (const :tag "When selection characters are configured" 'auto)))
3063 (defcustom org-fast-tag-selection-single-key nil
3064 "Non-nil means fast tag selection exits after first change.
3065 When nil, you have to press RET to exit it.
3066 During fast tag selection, you can toggle this flag with `C-c'.
3067 This variable can also have the value `expert'. In this case, the window
3068 displaying the tags menu is not even shown, until you press C-c again."
3069 :group 'org-tags
3070 :type '(choice
3071 (const :tag "No" nil)
3072 (const :tag "Yes" t)
3073 (const :tag "Expert" expert)))
3075 (defvar org-fast-tag-selection-include-todo nil
3076 "Non-nil means fast tags selection interface will also offer TODO states.
3077 This is an undocumented feature, you should not rely on it.")
3079 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3080 "The column to which tags should be indented in a headline.
3081 If this number is positive, it specifies the column. If it is negative,
3082 it means that the tags should be flushright to that column. For example,
3083 -80 works well for a normal 80 character screen.
3084 When 0, place tags directly after headline text, with only one space in
3085 between."
3086 :group 'org-tags
3087 :type 'integer)
3089 (defcustom org-auto-align-tags t
3090 "Non-nil keeps tags aligned when modifying headlines.
3091 Some operations (i.e. demoting) change the length of a headline and
3092 therefore shift the tags around. With this option turned on, after
3093 each such operation the tags are again aligned to `org-tags-column'."
3094 :group 'org-tags
3095 :type 'boolean)
3097 (defcustom org-use-tag-inheritance t
3098 "Non-nil means tags in levels apply also for sublevels.
3099 When nil, only the tags directly given in a specific line apply there.
3100 This may also be a list of tags that should be inherited, or a regexp that
3101 matches tags that should be inherited. Additional control is possible
3102 with the variable `org-tags-exclude-from-inheritance' which gives an
3103 explicit list of tags to be excluded from inheritance., even if the value of
3104 `org-use-tag-inheritance' would select it for inheritance.
3106 If this option is t, a match early-on in a tree can lead to a large
3107 number of matches in the subtree when constructing the agenda or creating
3108 a sparse tree. If you only want to see the first match in a tree during
3109 a search, check out the variable `org-tags-match-list-sublevels'."
3110 :group 'org-tags
3111 :type '(choice
3112 (const :tag "Not" nil)
3113 (const :tag "Always" t)
3114 (repeat :tag "Specific tags" (string :tag "Tag"))
3115 (regexp :tag "Tags matched by regexp")))
3117 (defcustom org-tags-exclude-from-inheritance nil
3118 "List of tags that should never be inherited.
3119 This is a way to exclude a few tags from inheritance. For way to do
3120 the opposite, to actively allow inheritance for selected tags,
3121 see the variable `org-use-tag-inheritance'."
3122 :group 'org-tags
3123 :type '(repeat (string :tag "Tag")))
3125 (defun org-tag-inherit-p (tag)
3126 "Check if TAG is one that should be inherited."
3127 (cond
3128 ((member tag org-tags-exclude-from-inheritance) nil)
3129 ((eq org-use-tag-inheritance t) t)
3130 ((not org-use-tag-inheritance) nil)
3131 ((stringp org-use-tag-inheritance)
3132 (string-match org-use-tag-inheritance tag))
3133 ((listp org-use-tag-inheritance)
3134 (member tag org-use-tag-inheritance))
3135 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3137 (defcustom org-tags-match-list-sublevels t
3138 "Non-nil means list also sublevels of headlines matching a search.
3139 This variable applies to tags/property searches, and also to stuck
3140 projects because this search is based on a tags match as well.
3142 When set to the symbol `indented', sublevels are indented with
3143 leading dots.
3145 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3146 the sublevels of a headline matching a tag search often also match
3147 the same search. Listing all of them can create very long lists.
3148 Setting this variable to nil causes subtrees of a match to be skipped.
3150 This variable is semi-obsolete and probably should always be true. It
3151 is better to limit inheritance to certain tags using the variables
3152 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3153 :group 'org-tags
3154 :type '(choice
3155 (const :tag "No, don't list them" nil)
3156 (const :tag "Yes, do list them" t)
3157 (const :tag "List them, indented with leading dots" indented)))
3159 (defcustom org-tags-sort-function nil
3160 "When set, tags are sorted using this function as a comparator."
3161 :group 'org-tags
3162 :type '(choice
3163 (const :tag "No sorting" nil)
3164 (const :tag "Alphabetical" string<)
3165 (const :tag "Reverse alphabetical" string>)
3166 (function :tag "Custom function" nil)))
3168 (defvar org-tags-history nil
3169 "History of minibuffer reads for tags.")
3170 (defvar org-last-tags-completion-table nil
3171 "The last used completion table for tags.")
3172 (defvar org-after-tags-change-hook nil
3173 "Hook that is run after the tags in a line have changed.")
3175 (defgroup org-properties nil
3176 "Options concerning properties in Org-mode."
3177 :tag "Org Properties"
3178 :group 'org)
3180 (defcustom org-property-format "%-10s %s"
3181 "How property key/value pairs should be formatted by `indent-line'.
3182 When `indent-line' hits a property definition, it will format the line
3183 according to this format, mainly to make sure that the values are
3184 lined-up with respect to each other."
3185 :group 'org-properties
3186 :type 'string)
3188 (defcustom org-properties-postprocess-alist nil
3189 "Alist of properties and functions to adjust inserted values.
3190 Elements of this alist must be of the form
3192 ([string] [function])
3194 where [string] must be a property name and [function] must be a
3195 lambda expression: this lambda expression must take one argument,
3196 the value to adjust, and return the new value as a string.
3198 For example, this element will allow the property \"Remaining\"
3199 to be updated wrt the relation between the \"Effort\" property
3200 and the clock summary:
3202 ((\"Remaining\" (lambda(value)
3203 (let ((clocksum (org-clock-sum-current-item))
3204 (effort (org-duration-string-to-minutes
3205 (org-entry-get (point) \"Effort\"))))
3206 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3207 :group 'org-properties
3208 :version "24.1"
3209 :type '(alist :key-type (string :tag "Property")
3210 :value-type (function :tag "Function")))
3212 (defcustom org-use-property-inheritance nil
3213 "Non-nil means properties apply also for sublevels.
3215 This setting is chiefly used during property searches. Turning it on can
3216 cause significant overhead when doing a search, which is why it is not
3217 on by default.
3219 When nil, only the properties directly given in the current entry count.
3220 When t, every property is inherited. The value may also be a list of
3221 properties that should have inheritance, or a regular expression matching
3222 properties that should be inherited.
3224 However, note that some special properties use inheritance under special
3225 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3226 and the properties ending in \"_ALL\" when they are used as descriptor
3227 for valid values of a property.
3229 Note for programmers:
3230 When querying an entry with `org-entry-get', you can control if inheritance
3231 should be used. By default, `org-entry-get' looks only at the local
3232 properties. You can request inheritance by setting the inherit argument
3233 to t (to force inheritance) or to `selective' (to respect the setting
3234 in this variable)."
3235 :group 'org-properties
3236 :type '(choice
3237 (const :tag "Not" nil)
3238 (const :tag "Always" t)
3239 (repeat :tag "Specific properties" (string :tag "Property"))
3240 (regexp :tag "Properties matched by regexp")))
3242 (defun org-property-inherit-p (property)
3243 "Check if PROPERTY is one that should be inherited."
3244 (cond
3245 ((eq org-use-property-inheritance t) t)
3246 ((not org-use-property-inheritance) nil)
3247 ((stringp org-use-property-inheritance)
3248 (string-match org-use-property-inheritance property))
3249 ((listp org-use-property-inheritance)
3250 (member property org-use-property-inheritance))
3251 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3253 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3254 "The default column format, if no other format has been defined.
3255 This variable can be set on the per-file basis by inserting a line
3257 #+COLUMNS: %25ITEM ....."
3258 :group 'org-properties
3259 :type 'string)
3261 (defcustom org-columns-ellipses ".."
3262 "The ellipses to be used when a field in column view is truncated.
3263 When this is the empty string, as many characters as possible are shown,
3264 but then there will be no visual indication that the field has been truncated.
3265 When this is a string of length N, the last N characters of a truncated
3266 field are replaced by this string. If the column is narrower than the
3267 ellipses string, only part of the ellipses string will be shown."
3268 :group 'org-properties
3269 :type 'string)
3271 (defcustom org-columns-modify-value-for-display-function nil
3272 "Function that modifies values for display in column view.
3273 For example, it can be used to cut out a certain part from a time stamp.
3274 The function must take 2 arguments:
3276 column-title The title of the column (*not* the property name)
3277 value The value that should be modified.
3279 The function should return the value that should be displayed,
3280 or nil if the normal value should be used."
3281 :group 'org-properties
3282 :type 'function)
3284 (defcustom org-effort-property "Effort"
3285 "The property that is being used to keep track of effort estimates.
3286 Effort estimates given in this property need to have the format H:MM."
3287 :group 'org-properties
3288 :group 'org-progress
3289 :type '(string :tag "Property"))
3291 (defconst org-global-properties-fixed
3292 '(("VISIBILITY_ALL" . "folded children content all")
3293 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3294 "List of property/value pairs that can be inherited by any entry.
3296 These are fixed values, for the preset properties. The user variable
3297 that can be used to add to this list is `org-global-properties'.
3299 The entries in this list are cons cells where the car is a property
3300 name and cdr is a string with the value. If the value represents
3301 multiple items like an \"_ALL\" property, separate the items by
3302 spaces.")
3304 (defcustom org-global-properties nil
3305 "List of property/value pairs that can be inherited by any entry.
3307 This list will be combined with the constant `org-global-properties-fixed'.
3309 The entries in this list are cons cells where the car is a property
3310 name and cdr is a string with the value.
3312 You can set buffer-local values for the same purpose in the variable
3313 `org-file-properties' this by adding lines like
3315 #+PROPERTY: NAME VALUE"
3316 :group 'org-properties
3317 :type '(repeat
3318 (cons (string :tag "Property")
3319 (string :tag "Value"))))
3321 (defvar org-file-properties nil
3322 "List of property/value pairs that can be inherited by any entry.
3323 Valid for the current buffer.
3324 This variable is populated from #+PROPERTY lines.")
3325 (make-variable-buffer-local 'org-file-properties)
3327 (defgroup org-agenda nil
3328 "Options concerning agenda views in Org-mode."
3329 :tag "Org Agenda"
3330 :group 'org)
3332 (defvar org-category nil
3333 "Variable used by org files to set a category for agenda display.
3334 Such files should use a file variable to set it, for example
3336 # -*- mode: org; org-category: \"ELisp\"
3338 or contain a special line
3340 #+CATEGORY: ELisp
3342 If the file does not specify a category, then file's base name
3343 is used instead.")
3344 (make-variable-buffer-local 'org-category)
3345 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3347 (defcustom org-agenda-files nil
3348 "The files to be used for agenda display.
3349 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3350 \\[org-remove-file]. You can also use customize to edit the list.
3352 If an entry is a directory, all files in that directory that are matched by
3353 `org-agenda-file-regexp' will be part of the file list.
3355 If the value of the variable is not a list but a single file name, then
3356 the list of agenda files is actually stored and maintained in that file, one
3357 agenda file per line. In this file paths can be given relative to
3358 `org-directory'. Tilde expansion and environment variable substitution
3359 are also made."
3360 :group 'org-agenda
3361 :type '(choice
3362 (repeat :tag "List of files and directories" file)
3363 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3365 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3366 "Regular expression to match files for `org-agenda-files'.
3367 If any element in the list in that variable contains a directory instead
3368 of a normal file, all files in that directory that are matched by this
3369 regular expression will be included."
3370 :group 'org-agenda
3371 :type 'regexp)
3373 (defcustom org-agenda-text-search-extra-files nil
3374 "List of extra files to be searched by text search commands.
3375 These files will be search in addition to the agenda files by the
3376 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3377 Note that these files will only be searched for text search commands,
3378 not for the other agenda views like todo lists, tag searches or the weekly
3379 agenda. This variable is intended to list notes and possibly archive files
3380 that should also be searched by these two commands.
3381 In fact, if the first element in the list is the symbol `agenda-archives',
3382 than all archive files of all agenda files will be added to the search
3383 scope."
3384 :group 'org-agenda
3385 :type '(set :greedy t
3386 (const :tag "Agenda Archives" agenda-archives)
3387 (repeat :inline t (file))))
3389 (if (fboundp 'defvaralias)
3390 (defvaralias 'org-agenda-multi-occur-extra-files
3391 'org-agenda-text-search-extra-files))
3393 (defcustom org-agenda-skip-unavailable-files nil
3394 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3395 A nil value means to remove them, after a query, from the list."
3396 :group 'org-agenda
3397 :type 'boolean)
3399 (defcustom org-calendar-to-agenda-key [?c]
3400 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3401 The command `org-calendar-goto-agenda' will be bound to this key. The
3402 default is the character `c' because then `c' can be used to switch back and
3403 forth between agenda and calendar."
3404 :group 'org-agenda
3405 :type 'sexp)
3407 (defcustom org-calendar-insert-diary-entry-key [?i]
3408 "The key to be installed in `calendar-mode-map' for adding diary entries.
3409 This option is irrelevant until `org-agenda-diary-file' has been configured
3410 to point to an Org-mode file. When that is the case, the command
3411 `org-agenda-diary-entry' will be bound to the key given here, by default
3412 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3413 if you want to continue doing this, you need to change this to a different
3414 key."
3415 :group 'org-agenda
3416 :type 'sexp)
3418 (defcustom org-agenda-diary-file 'diary-file
3419 "File to which to add new entries with the `i' key in agenda and calendar.
3420 When this is the symbol `diary-file', the functionality in the Emacs
3421 calendar will be used to add entries to the `diary-file'. But when this
3422 points to a file, `org-agenda-diary-entry' will be used instead."
3423 :group 'org-agenda
3424 :type '(choice
3425 (const :tag "The standard Emacs diary file" diary-file)
3426 (file :tag "Special Org file diary entries")))
3428 (eval-after-load "calendar"
3429 '(progn
3430 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3431 'org-calendar-goto-agenda)
3432 (add-hook 'calendar-mode-hook
3433 (lambda ()
3434 (unless (eq org-agenda-diary-file 'diary-file)
3435 (define-key calendar-mode-map
3436 org-calendar-insert-diary-entry-key
3437 'org-agenda-diary-entry))))))
3439 (defgroup org-latex nil
3440 "Options for embedding LaTeX code into Org-mode."
3441 :tag "Org LaTeX"
3442 :group 'org)
3444 (defcustom org-format-latex-options
3445 '(:foreground default :background default :scale 1.0
3446 :html-foreground "Black" :html-background "Transparent"
3447 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3448 "Options for creating images from LaTeX fragments.
3449 This is a property list with the following properties:
3450 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3451 `default' means use the foreground of the default face.
3452 `auto' means use the foreground from the text face.
3453 :background the background color, or \"Transparent\".
3454 `default' means use the background of the default face.
3455 `auto' means use the background from the text face.
3456 :scale a scaling factor for the size of the images, to get more pixels
3457 :html-foreground, :html-background, :html-scale
3458 the same numbers for HTML export.
3459 :matchers a list indicating which matchers should be used to
3460 find LaTeX fragments. Valid members of this list are:
3461 \"begin\" find environments
3462 \"$1\" find single characters surrounded by $.$
3463 \"$\" find math expressions surrounded by $...$
3464 \"$$\" find math expressions surrounded by $$....$$
3465 \"\\(\" find math expressions surrounded by \\(...\\)
3466 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3467 :group 'org-latex
3468 :type 'plist)
3470 (defcustom org-format-latex-signal-error t
3471 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3472 When nil, just push out a message."
3473 :group 'org-latex
3474 :version "24.1"
3475 :type 'boolean)
3477 (defcustom org-latex-to-mathml-jar-file nil
3478 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3479 Use this to specify additional executable file say a jar file.
3481 When using MathToWeb as the converter, specify the full-path to
3482 your mathtoweb.jar file."
3483 :group 'org-latex
3484 :version "24.1"
3485 :type '(choice
3486 (const :tag "None" nil)
3487 (file :tag "JAR file" :must-match t)))
3489 (defcustom org-latex-to-mathml-convert-command nil
3490 "Command to convert LaTeX fragments to MathML.
3491 Replace format-specifiers in the command as noted below and use
3492 `shell-command' to convert LaTeX to MathML.
3493 %j: Executable file in fully expanded form as specified by
3494 `org-latex-to-mathml-jar-file'.
3495 %I: Input LaTeX file in fully expanded form
3496 %o: Output MathML file
3497 This command is used by `org-create-math-formula'.
3499 When using MathToWeb as the converter, set this to
3500 \"java -jar %j -unicode -force -df %o %I\"."
3501 :group 'org-latex
3502 :version "24.1"
3503 :type '(choice
3504 (const :tag "None" nil)
3505 (string :tag "\nShell command")))
3507 (defcustom org-latex-create-formula-image-program 'dvipng
3508 "Program to convert LaTeX fragments with.
3510 dvipng Process the LaTeX fragments to dvi file, then convert
3511 dvi files to png files using dvipng.
3512 This will also include processing of non-math environments.
3513 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3514 to convert pdf files to png files"
3515 :group 'org-latex
3516 :version "24.1"
3517 :type '(choice
3518 (const :tag "dvipng" dvipng)
3519 (const :tag "imagemagick" imagemagick)))
3521 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3522 "Path to store latex preview images.
3523 A relative path here creates many directories relative to the
3524 processed org files paths. An absolute path puts all preview
3525 images at the same place."
3526 :group 'org-latex
3527 :version "24.3"
3528 :type 'string)
3530 (defun org-format-latex-mathml-available-p ()
3531 "Return t if `org-latex-to-mathml-convert-command' is usable."
3532 (save-match-data
3533 (when (and (boundp 'org-latex-to-mathml-convert-command)
3534 org-latex-to-mathml-convert-command)
3535 (let ((executable (car (split-string
3536 org-latex-to-mathml-convert-command))))
3537 (when (executable-find executable)
3538 (if (string-match
3539 "%j" org-latex-to-mathml-convert-command)
3540 (file-readable-p org-latex-to-mathml-jar-file)
3541 t))))))
3543 (defcustom org-format-latex-header "\\documentclass{article}
3544 \\usepackage[usenames]{color}
3545 \\usepackage{amsmath}
3546 \\usepackage[mathscr]{eucal}
3547 \\pagestyle{empty} % do not remove
3548 \[PACKAGES]
3549 \[DEFAULT-PACKAGES]
3550 % The settings below are copied from fullpage.sty
3551 \\setlength{\\textwidth}{\\paperwidth}
3552 \\addtolength{\\textwidth}{-3cm}
3553 \\setlength{\\oddsidemargin}{1.5cm}
3554 \\addtolength{\\oddsidemargin}{-2.54cm}
3555 \\setlength{\\evensidemargin}{\\oddsidemargin}
3556 \\setlength{\\textheight}{\\paperheight}
3557 \\addtolength{\\textheight}{-\\headheight}
3558 \\addtolength{\\textheight}{-\\headsep}
3559 \\addtolength{\\textheight}{-\\footskip}
3560 \\addtolength{\\textheight}{-3cm}
3561 \\setlength{\\topmargin}{1.5cm}
3562 \\addtolength{\\topmargin}{-2.54cm}"
3563 "The document header used for processing LaTeX fragments.
3564 It is imperative that this header make sure that no page number
3565 appears on the page. The package defined in the variables
3566 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3567 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3568 will be appended."
3569 :group 'org-latex
3570 :type 'string)
3572 (defvar org-format-latex-header-extra nil)
3574 (defun org-set-packages-alist (var val)
3575 "Set the packages alist and make sure it has 3 elements per entry."
3576 (set var (mapcar (lambda (x)
3577 (if (and (consp x) (= (length x) 2))
3578 (list (car x) (nth 1 x) t)
3580 val)))
3582 (defun org-get-packages-alist (var)
3584 "Get the packages alist and make sure it has 3 elements per entry."
3585 (mapcar (lambda (x)
3586 (if (and (consp x) (= (length x) 2))
3587 (list (car x) (nth 1 x) t)
3589 (default-value var)))
3591 ;; The following variables are defined here because is it also used
3592 ;; when formatting latex fragments. Originally it was part of the
3593 ;; LaTeX exporter, which is why the name includes "export".
3594 (defcustom org-export-latex-default-packages-alist
3595 '(("AUTO" "inputenc" t)
3596 ("T1" "fontenc" t)
3597 ("" "fixltx2e" nil)
3598 ("" "graphicx" t)
3599 ("" "longtable" nil)
3600 ("" "float" nil)
3601 ("" "wrapfig" nil)
3602 ("" "soul" t)
3603 ("" "textcomp" t)
3604 ("" "marvosym" t)
3605 ("" "wasysym" t)
3606 ("" "latexsym" t)
3607 ("" "amssymb" t)
3608 ("" "hyperref" nil)
3609 "\\tolerance=1000"
3611 "Alist of default packages to be inserted in the header.
3612 Change this only if one of the packages here causes an incompatibility
3613 with another package you are using.
3614 The packages in this list are needed by one part or another of Org-mode
3615 to function properly.
3617 - inputenc, fontenc: for basic font and character selection
3618 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3619 for interpreting the entities in `org-entities'. You can skip some of these
3620 packages if you don't use any of the symbols in it.
3621 - graphicx: for including images
3622 - float, wrapfig: for figure placement
3623 - longtable: for long tables
3624 - hyperref: for cross references
3626 Therefore you should not modify this variable unless you know what you
3627 are doing. The one reason to change it anyway is that you might be loading
3628 some other package that conflicts with one of the default packages.
3629 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3630 If SNIPPET-FLAG is t, the package also needs to be included when
3631 compiling LaTeX snippets into images for inclusion into HTML."
3632 :group 'org-export-latex
3633 :set 'org-set-packages-alist
3634 :get 'org-get-packages-alist
3635 :version "24.1"
3636 :type '(repeat
3637 (choice
3638 (list :tag "options/package pair"
3639 (string :tag "options")
3640 (string :tag "package")
3641 (boolean :tag "Snippet"))
3642 (string :tag "A line of LaTeX"))))
3644 (defcustom org-export-latex-packages-alist nil
3645 "Alist of packages to be inserted in every LaTeX header.
3646 These will be inserted after `org-export-latex-default-packages-alist'.
3647 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3648 SNIPPET-FLAG, when t, indicates that this package is also needed when
3649 turning LaTeX snippets into images for inclusion into HTML.
3650 Make sure that you only list packages here which:
3651 - you want in every file
3652 - do not conflict with the default packages in
3653 `org-export-latex-default-packages-alist'
3654 - do not conflict with the setup in `org-format-latex-header'."
3655 :group 'org-export-latex
3656 :set 'org-set-packages-alist
3657 :get 'org-get-packages-alist
3658 :type '(repeat
3659 (choice
3660 (list :tag "options/package pair"
3661 (string :tag "options")
3662 (string :tag "package")
3663 (boolean :tag "Snippet"))
3664 (string :tag "A line of LaTeX"))))
3667 (defgroup org-appearance nil
3668 "Settings for Org-mode appearance."
3669 :tag "Org Appearance"
3670 :group 'org)
3672 (defcustom org-level-color-stars-only nil
3673 "Non-nil means fontify only the stars in each headline.
3674 When nil, the entire headline is fontified.
3675 Changing it requires restart of `font-lock-mode' to become effective
3676 also in regions already fontified."
3677 :group 'org-appearance
3678 :type 'boolean)
3680 (defcustom org-hide-leading-stars nil
3681 "Non-nil means hide the first N-1 stars in a headline.
3682 This works by using the face `org-hide' for these stars. This
3683 face is white for a light background, and black for a dark
3684 background. You may have to customize the face `org-hide' to
3685 make this work.
3686 Changing it requires restart of `font-lock-mode' to become effective
3687 also in regions already fontified.
3688 You may also set this on a per-file basis by adding one of the following
3689 lines to the buffer:
3691 #+STARTUP: hidestars
3692 #+STARTUP: showstars"
3693 :group 'org-appearance
3694 :type 'boolean)
3696 (defcustom org-hidden-keywords nil
3697 "List of symbols corresponding to keywords to be hidden the org buffer.
3698 For example, a value '(title) for this list will make the document's title
3699 appear in the buffer without the initial #+TITLE: keyword."
3700 :group 'org-appearance
3701 :version "24.1"
3702 :type '(set (const :tag "#+AUTHOR" author)
3703 (const :tag "#+DATE" date)
3704 (const :tag "#+EMAIL" email)
3705 (const :tag "#+TITLE" title)))
3707 (defcustom org-custom-properties nil
3708 "List of properties (as strings) with a special meaning.
3709 The default use of these custom properties is to let the user
3710 hide them with `org-toggle-custom-properties-visibility'."
3711 :group 'org-properties
3712 :group 'org-appearance
3713 :version "24.3"
3714 :type '(repeat (string :tag "Property Name")))
3716 (defcustom org-fontify-done-headline nil
3717 "Non-nil means change the face of a headline if it is marked DONE.
3718 Normally, only the TODO/DONE keyword indicates the state of a headline.
3719 When this is non-nil, the headline after the keyword is set to the
3720 `org-headline-done' as an additional indication."
3721 :group 'org-appearance
3722 :type 'boolean)
3724 (defcustom org-fontify-emphasized-text t
3725 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3726 Changing this variable requires a restart of Emacs to take effect."
3727 :group 'org-appearance
3728 :type 'boolean)
3730 (defcustom org-fontify-whole-heading-line nil
3731 "Non-nil means fontify the whole line for headings.
3732 This is useful when setting a background color for the
3733 org-level-* faces."
3734 :group 'org-appearance
3735 :type 'boolean)
3737 (defcustom org-highlight-latex-fragments-and-specials nil
3738 "Non-nil means fontify what is treated specially by the exporters."
3739 :group 'org-appearance
3740 :type 'boolean)
3742 (defcustom org-hide-emphasis-markers nil
3743 "Non-nil mean font-lock should hide the emphasis marker characters."
3744 :group 'org-appearance
3745 :type 'boolean)
3747 (defcustom org-pretty-entities nil
3748 "Non-nil means show entities as UTF8 characters.
3749 When nil, the \\name form remains in the buffer."
3750 :group 'org-appearance
3751 :version "24.1"
3752 :type 'boolean)
3754 (defcustom org-pretty-entities-include-sub-superscripts t
3755 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3756 :group 'org-appearance
3757 :version "24.1"
3758 :type 'boolean)
3760 (defvar org-emph-re nil
3761 "Regular expression for matching emphasis.
3762 After a match, the match groups contain these elements:
3763 0 The match of the full regular expression, including the characters
3764 before and after the proper match
3765 1 The character before the proper match, or empty at beginning of line
3766 2 The proper match, including the leading and trailing markers
3767 3 The leading marker like * or /, indicating the type of highlighting
3768 4 The text between the emphasis markers, not including the markers
3769 5 The character after the match, empty at the end of a line")
3770 (defvar org-verbatim-re nil
3771 "Regular expression for matching verbatim text.")
3772 (defvar org-emphasis-regexp-components) ; defined just below
3773 (defvar org-emphasis-alist) ; defined just below
3774 (defun org-set-emph-re (var val)
3775 "Set variable and compute the emphasis regular expression."
3776 (set var val)
3777 (when (and (boundp 'org-emphasis-alist)
3778 (boundp 'org-emphasis-regexp-components)
3779 org-emphasis-alist org-emphasis-regexp-components)
3780 (let* ((e org-emphasis-regexp-components)
3781 (pre (car e))
3782 (post (nth 1 e))
3783 (border (nth 2 e))
3784 (body (nth 3 e))
3785 (nl (nth 4 e))
3786 (body1 (concat body "*?"))
3787 (markers (mapconcat 'car org-emphasis-alist ""))
3788 (vmarkers (mapconcat
3789 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3790 org-emphasis-alist "")))
3791 ;; make sure special characters appear at the right position in the class
3792 (if (string-match "\\^" markers)
3793 (setq markers (concat (replace-match "" t t markers) "^")))
3794 (if (string-match "-" markers)
3795 (setq markers (concat (replace-match "" t t markers) "-")))
3796 (if (string-match "\\^" vmarkers)
3797 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3798 (if (string-match "-" vmarkers)
3799 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3800 (if (> nl 0)
3801 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3802 (int-to-string nl) "\\}")))
3803 ;; Make the regexp
3804 (setq org-emph-re
3805 (concat "\\([" pre "]\\|^\\)"
3806 "\\("
3807 "\\([" markers "]\\)"
3808 "\\("
3809 "[^" border "]\\|"
3810 "[^" border "]"
3811 body1
3812 "[^" border "]"
3813 "\\)"
3814 "\\3\\)"
3815 "\\([" post "]\\|$\\)"))
3816 (setq org-verbatim-re
3817 (concat "\\([" pre "]\\|^\\)"
3818 "\\("
3819 "\\([" vmarkers "]\\)"
3820 "\\("
3821 "[^" border "]\\|"
3822 "[^" border "]"
3823 body1
3824 "[^" border "]"
3825 "\\)"
3826 "\\3\\)"
3827 "\\([" post "]\\|$\\)")))))
3829 (defcustom org-emphasis-regexp-components
3830 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3831 "Components used to build the regular expression for emphasis.
3832 This is a list with five entries. Terminology: In an emphasis string
3833 like \" *strong word* \", we call the initial space PREMATCH, the final
3834 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3835 and \"trong wor\" is the body. The different components in this variable
3836 specify what is allowed/forbidden in each part:
3838 pre Chars allowed as prematch. Beginning of line will be allowed too.
3839 post Chars allowed as postmatch. End of line will be allowed too.
3840 border The chars *forbidden* as border characters.
3841 body-regexp A regexp like \".\" to match a body character. Don't use
3842 non-shy groups here, and don't allow newline here.
3843 newline The maximum number of newlines allowed in an emphasis exp.
3845 Use customize to modify this, or restart Emacs after changing it."
3846 :group 'org-appearance
3847 :set 'org-set-emph-re
3848 :type '(list
3849 (sexp :tag "Allowed chars in pre ")
3850 (sexp :tag "Allowed chars in post ")
3851 (sexp :tag "Forbidden chars in border ")
3852 (sexp :tag "Regexp for body ")
3853 (integer :tag "number of newlines allowed")
3854 (option (boolean :tag "Please ignore this button"))))
3856 (defcustom org-emphasis-alist
3857 `(("*" bold "<b>" "</b>")
3858 ("/" italic "<i>" "</i>")
3859 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3860 ("=" org-code "<code>" "</code>" verbatim)
3861 ("~" org-verbatim "<code>" "</code>" verbatim)
3862 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3863 "<del>" "</del>")
3865 "Special syntax for emphasized text.
3866 Text starting and ending with a special character will be emphasized, for
3867 example *bold*, _underlined_ and /italic/. This variable sets the marker
3868 characters, the face to be used by font-lock for highlighting in Org-mode
3869 Emacs buffers, and the HTML tags to be used for this.
3870 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3871 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3872 Use customize to modify this, or restart Emacs after changing it."
3873 :group 'org-appearance
3874 :set 'org-set-emph-re
3875 :type '(repeat
3876 (list
3877 (string :tag "Marker character")
3878 (choice
3879 (face :tag "Font-lock-face")
3880 (plist :tag "Face property list"))
3881 (string :tag "HTML start tag")
3882 (string :tag "HTML end tag")
3883 (option (const verbatim)))))
3885 (defvar org-protecting-blocks
3886 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3887 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3888 This is needed for font-lock setup.")
3890 ;;; Miscellaneous options
3892 (defgroup org-completion nil
3893 "Completion in Org-mode."
3894 :tag "Org Completion"
3895 :group 'org)
3897 (defcustom org-completion-use-ido nil
3898 "Non-nil means use ido completion wherever possible.
3899 Note that `ido-mode' must be active for this variable to be relevant.
3900 If you decide to turn this variable on, you might well want to turn off
3901 `org-outline-path-complete-in-steps'.
3902 See also `org-completion-use-iswitchb'."
3903 :group 'org-completion
3904 :type 'boolean)
3906 (defcustom org-completion-use-iswitchb nil
3907 "Non-nil means use iswitchb completion wherever possible.
3908 Note that `iswitchb-mode' must be active for this variable to be relevant.
3909 If you decide to turn this variable on, you might well want to turn off
3910 `org-outline-path-complete-in-steps'.
3911 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3912 :group 'org-completion
3913 :type 'boolean)
3915 (defcustom org-completion-fallback-command 'hippie-expand
3916 "The expansion command called by \\[pcomplete] in normal context.
3917 Normal means, no org-mode-specific context."
3918 :group 'org-completion
3919 :type 'function)
3921 ;;; Functions and variables from their packages
3922 ;; Declared here to avoid compiler warnings
3924 ;; XEmacs only
3925 (defvar outline-mode-menu-heading)
3926 (defvar outline-mode-menu-show)
3927 (defvar outline-mode-menu-hide)
3928 (defvar zmacs-regions) ; XEmacs regions
3930 ;; Emacs only
3931 (defvar mark-active)
3933 ;; Various packages
3934 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3935 (declare-function calendar-forward-day "cal-move" (arg))
3936 (declare-function calendar-goto-date "cal-move" (date))
3937 (declare-function calendar-goto-today "cal-move" ())
3938 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3939 (defvar calc-embedded-close-formula)
3940 (defvar calc-embedded-open-formula)
3941 (declare-function cdlatex-tab "ext:cdlatex" ())
3942 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3943 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3944 (defvar font-lock-unfontify-region-function)
3945 (declare-function iswitchb-read-buffer "iswitchb"
3946 (prompt &optional default require-match start matches-set))
3947 (defvar iswitchb-temp-buflist)
3948 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3949 (defvar org-agenda-tags-todo-honor-ignore-options)
3950 (declare-function org-agenda-skip "org-agenda" ())
3951 (declare-function
3952 org-agenda-format-item "org-agenda"
3953 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3954 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3955 (declare-function org-agenda-change-all-lines "org-agenda"
3956 (newhead hdmarker &optional fixface just-this))
3957 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3958 (declare-function org-agenda-maybe-redo "org-agenda" ())
3959 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3960 (beg end))
3961 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3962 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3963 "org-agenda" (&optional end))
3964 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3965 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3966 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3967 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3968 (declare-function org-indent-mode "org-indent" (&optional arg))
3969 (declare-function parse-time-string "parse-time" (string))
3970 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3971 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3972 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3973 (defvar remember-data-file)
3974 (defvar texmathp-why)
3975 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3976 (declare-function table--at-cell-p "table" (position &optional object at-column))
3978 (defvar w3m-current-url)
3979 (defvar w3m-current-title)
3981 (defvar org-latex-regexps)
3983 ;;; Autoload and prepare some org modules
3985 ;; Some table stuff that needs to be defined here, because it is used
3986 ;; by the functions setting up org-mode or checking for table context.
3988 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3989 "Detect an org-type or table-type table.")
3990 (defconst org-table-line-regexp "^[ \t]*|"
3991 "Detect an org-type table line.")
3992 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3993 "Detect an org-type table line.")
3994 (defconst org-table-hline-regexp "^[ \t]*|-"
3995 "Detect an org-type table hline.")
3996 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3997 "Detect a table-type table hline.")
3998 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3999 "Detect the first line outside a table when searching from within it.
4000 This works for both table types.")
4002 ;; Autoload the functions in org-table.el that are needed by functions here.
4004 (eval-and-compile
4005 (org-autoload "org-table"
4006 '(org-table-begin org-table-blank-field org-table-end)))
4008 ;;;###autoload
4009 (defun turn-on-orgtbl ()
4010 "Unconditionally turn on `orgtbl-mode'."
4011 (require 'org-table)
4012 (orgtbl-mode 1))
4014 (defun org-at-table-p (&optional table-type)
4015 "Return t if the cursor is inside an org-type table.
4016 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4017 (if org-enable-table-editor
4018 (save-excursion
4019 (beginning-of-line 1)
4020 (looking-at (if table-type org-table-any-line-regexp
4021 org-table-line-regexp)))
4022 nil))
4023 (defsubst org-table-p () (org-at-table-p))
4025 (defun org-at-table.el-p ()
4026 "Return t if and only if we are at a table.el table."
4027 (and (org-at-table-p 'any)
4028 (save-excursion
4029 (goto-char (org-table-begin 'any))
4030 (looking-at org-table1-hline-regexp))))
4031 (defun org-table-recognize-table.el ()
4032 "If there is a table.el table nearby, recognize it and move into it."
4033 (if org-table-tab-recognizes-table.el
4034 (if (org-at-table.el-p)
4035 (progn
4036 (beginning-of-line 1)
4037 (if (looking-at org-table-dataline-regexp)
4039 (if (looking-at org-table1-hline-regexp)
4040 (progn
4041 (beginning-of-line 2)
4042 (if (looking-at org-table-any-border-regexp)
4043 (beginning-of-line -1)))))
4044 (if (re-search-forward "|" (org-table-end t) t)
4045 (progn
4046 (require 'table)
4047 (if (table--at-cell-p (point))
4049 (message "recognizing table.el table...")
4050 (table-recognize-table)
4051 (message "recognizing table.el table...done")))
4052 (error "This should not happen"))
4054 nil)
4055 nil))
4057 (defun org-at-table-hline-p ()
4058 "Return t if the cursor is inside a hline in a table."
4059 (if org-enable-table-editor
4060 (save-excursion
4061 (beginning-of-line 1)
4062 (looking-at org-table-hline-regexp))
4063 nil))
4065 (defvar org-table-clean-did-remove-column nil)
4067 (defun org-table-map-tables (function &optional quietly)
4068 "Apply FUNCTION to the start of all tables in the buffer."
4069 (save-excursion
4070 (save-restriction
4071 (widen)
4072 (goto-char (point-min))
4073 (while (re-search-forward org-table-any-line-regexp nil t)
4074 (unless quietly
4075 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4076 (beginning-of-line 1)
4077 (when (and (looking-at org-table-line-regexp)
4078 ;; Exclude tables in src/example/verbatim/clocktable blocks
4079 (not (org-in-block-p '("src" "example"))))
4080 (save-excursion (funcall function))
4081 (or (looking-at org-table-line-regexp)
4082 (forward-char 1)))
4083 (re-search-forward org-table-any-border-regexp nil 1))))
4084 (unless quietly (message "Mapping tables: done")))
4086 ;; Declare and autoload functions from org-exp.el & Co
4088 (declare-function org-default-export-plist "org-exp")
4089 (declare-function org-infile-export-plist "org-exp")
4090 (declare-function org-get-current-options "org-exp")
4092 ;; Declare and autoload functions from org-agenda.el
4094 (eval-and-compile
4095 (org-autoload "org-agenda"
4096 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4098 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4099 (declare-function org-clock-update-mode-line "org-clock" ())
4100 (declare-function org-resolve-clocks "org-clock"
4101 (&optional also-non-dangling-p prompt last-valid))
4102 (defvar org-clock-start-time)
4103 (defvar org-clock-marker (make-marker)
4104 "Marker recording the last clock-in.")
4105 (defvar org-clock-hd-marker (make-marker)
4106 "Marker recording the last clock-in, but the headline position.")
4107 (defvar org-clock-heading ""
4108 "The heading of the current clock entry.")
4109 (defun org-clock-is-active ()
4110 "Return non-nil if clock is currently running.
4111 The return value is actually the clock marker."
4112 (marker-buffer org-clock-marker))
4114 (eval-and-compile
4115 (org-autoload "org-clock" '(org-clock-remove-overlays
4116 org-clock-update-time-maybe
4117 org-clocktable-shift)))
4119 (defun org-check-running-clock ()
4120 "Check if the current buffer contains the running clock.
4121 If yes, offer to stop it and to save the buffer with the changes."
4122 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4123 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4124 (buffer-name))))
4125 (org-clock-out)
4126 (when (y-or-n-p "Save changed buffer?")
4127 (save-buffer))))
4129 (defun org-clocktable-try-shift (dir n)
4130 "Check if this line starts a clock table, if yes, shift the time block."
4131 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4132 (org-clocktable-shift dir n)))
4134 ;;;###autoload
4135 (defun org-clock-persistence-insinuate ()
4136 "Set up hooks for clock persistence."
4137 (require 'org-clock)
4138 (add-hook 'org-mode-hook 'org-clock-load)
4139 (add-hook 'kill-emacs-hook 'org-clock-save))
4141 ;; Define the variable already here, to make sure we have it.
4142 (defvar org-indent-mode nil
4143 "Non-nil if Org-Indent mode is enabled.
4144 Use the command `org-indent-mode' to change this variable.")
4146 ;; Autoload archiving code
4147 ;; The stuff that is needed for cycling and tags has to be defined here.
4149 (defgroup org-archive nil
4150 "Options concerning archiving in Org-mode."
4151 :tag "Org Archive"
4152 :group 'org-structure)
4154 (defcustom org-archive-location "%s_archive::"
4155 "The location where subtrees should be archived.
4157 The value of this variable is a string, consisting of two parts,
4158 separated by a double-colon. The first part is a filename and
4159 the second part is a headline.
4161 When the filename is omitted, archiving happens in the same file.
4162 %s in the filename will be replaced by the current file
4163 name (without the directory part). Archiving to a different file
4164 is useful to keep archived entries from contributing to the
4165 Org-mode Agenda.
4167 The archived entries will be filed as subtrees of the specified
4168 headline. When the headline is omitted, the subtrees are simply
4169 filed away at the end of the file, as top-level entries. Also in
4170 the heading you can use %s to represent the file name, this can be
4171 useful when using the same archive for a number of different files.
4173 Here are a few examples:
4174 \"%s_archive::\"
4175 If the current file is Projects.org, archive in file
4176 Projects.org_archive, as top-level trees. This is the default.
4178 \"::* Archived Tasks\"
4179 Archive in the current file, under the top-level headline
4180 \"* Archived Tasks\".
4182 \"~/org/archive.org::\"
4183 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4185 \"~/org/archive.org::* From %s\"
4186 Archive in file ~/org/archive.org (absolute path), under headlines
4187 \"From FILENAME\" where file name is the current file name.
4189 \"~/org/datetree.org::datetree/* Finished Tasks\"
4190 The \"datetree/\" string is special, signifying to archive
4191 items to the datetree. Items are placed in either the CLOSED
4192 date of the item, or the current date if there is no CLOSED date.
4193 The heading will be a subentry to the current date. There doesn't
4194 need to be a heading, but there always needs to be a slash after
4195 datetree. For example, to store archived items directly in the
4196 datetree, use \"~/org/datetree.org::datetree/\".
4198 \"basement::** Finished Tasks\"
4199 Archive in file ./basement (relative path), as level 3 trees
4200 below the level 2 heading \"** Finished Tasks\".
4202 You may set this option on a per-file basis by adding to the buffer a
4203 line like
4205 #+ARCHIVE: basement::** Finished Tasks
4207 You may also define it locally for a subtree by setting an ARCHIVE property
4208 in the entry. If such a property is found in an entry, or anywhere up
4209 the hierarchy, it will be used."
4210 :group 'org-archive
4211 :type 'string)
4213 (defcustom org-archive-tag "ARCHIVE"
4214 "The tag that marks a subtree as archived.
4215 An archived subtree does not open during visibility cycling, and does
4216 not contribute to the agenda listings.
4217 After changing this, font-lock must be restarted in the relevant buffers to
4218 get the proper fontification."
4219 :group 'org-archive
4220 :group 'org-keywords
4221 :type 'string)
4223 (defcustom org-agenda-skip-archived-trees t
4224 "Non-nil means the agenda will skip any items located in archived trees.
4225 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4226 variable is no longer recommended, you should leave it at the value t.
4227 Instead, use the key `v' to cycle the archives-mode in the agenda."
4228 :group 'org-archive
4229 :group 'org-agenda-skip
4230 :type 'boolean)
4232 (defcustom org-columns-skip-archived-trees t
4233 "Non-nil means ignore archived trees when creating column view."
4234 :group 'org-archive
4235 :group 'org-properties
4236 :type 'boolean)
4238 (defcustom org-cycle-open-archived-trees nil
4239 "Non-nil means `org-cycle' will open archived trees.
4240 An archived tree is a tree marked with the tag ARCHIVE.
4241 When nil, archived trees will stay folded. You can still open them with
4242 normal outline commands like `show-all', but not with the cycling commands."
4243 :group 'org-archive
4244 :group 'org-cycle
4245 :type 'boolean)
4247 (defcustom org-sparse-tree-open-archived-trees nil
4248 "Non-nil means sparse tree construction shows matches in archived trees.
4249 When nil, matches in these trees are highlighted, but the trees are kept in
4250 collapsed state."
4251 :group 'org-archive
4252 :group 'org-sparse-trees
4253 :type 'boolean)
4255 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4256 "The default date type when building a sparse tree.
4257 When this is nil, a date is a scheduled or a deadline timestamp.
4258 Otherwise, these types are allowed:
4260 all: all timestamps
4261 active: only active timestamps (<...>)
4262 inactive: only inactive timestamps (<...)
4263 scheduled: only scheduled timestamps
4264 deadline: only deadline timestamps"
4265 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4266 (const :tag "All timestamps" all)
4267 (const :tag "Only active timestamps" active)
4268 (const :tag "Only inactive timestamps" inactive)
4269 (const :tag "Only scheduled timestamps" scheduled)
4270 (const :tag "Only deadline timestamps" deadline))
4271 :version "24.3"
4272 :group 'org-sparse-trees)
4274 (defun org-cycle-hide-archived-subtrees (state)
4275 "Re-hide all archived subtrees after a visibility state change."
4276 (when (and (not org-cycle-open-archived-trees)
4277 (not (memq state '(overview folded))))
4278 (save-excursion
4279 (let* ((globalp (memq state '(contents all)))
4280 (beg (if globalp (point-min) (point)))
4281 (end (if globalp (point-max) (org-end-of-subtree t))))
4282 (org-hide-archived-subtrees beg end)
4283 (goto-char beg)
4284 (if (looking-at (concat ".*:" org-archive-tag ":"))
4285 (message "%s" (substitute-command-keys
4286 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4288 (defun org-force-cycle-archived ()
4289 "Cycle subtree even if it is archived."
4290 (interactive)
4291 (setq this-command 'org-cycle)
4292 (let ((org-cycle-open-archived-trees t))
4293 (call-interactively 'org-cycle)))
4295 (defun org-hide-archived-subtrees (beg end)
4296 "Re-hide all archived subtrees after a visibility state change."
4297 (save-excursion
4298 (let* ((re (concat ":" org-archive-tag ":")))
4299 (goto-char beg)
4300 (while (re-search-forward re end t)
4301 (when (org-at-heading-p)
4302 (org-flag-subtree t)
4303 (org-end-of-subtree t))))))
4305 (declare-function outline-end-of-heading "outline" ())
4306 (declare-function outline-flag-region "outline" (from to flag))
4307 (defun org-flag-subtree (flag)
4308 (save-excursion
4309 (org-back-to-heading t)
4310 (outline-end-of-heading)
4311 (outline-flag-region (point)
4312 (progn (org-end-of-subtree t) (point))
4313 flag)))
4315 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4317 (eval-and-compile
4318 (org-autoload "org-archive"
4319 '(org-add-archive-files)))
4321 ;; Autoload Column View Code
4323 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4324 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4325 (declare-function org-columns-compute "org-colview" (property))
4327 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4328 '(org-columns-number-to-string
4329 org-columns-get-format-and-top-level
4330 org-columns-compute
4331 org-columns-remove-overlays))
4333 ;; Autoload ID code
4335 (declare-function org-id-store-link "org-id")
4336 (declare-function org-id-locations-load "org-id")
4337 (declare-function org-id-locations-save "org-id")
4338 (defvar org-id-track-globally)
4339 (org-autoload "org-id"
4340 '(org-id-new
4341 org-id-copy
4342 org-id-get-with-outline-path-completion
4343 org-id-get-with-outline-drilling))
4345 ;;; Variables for pre-computed regular expressions, all buffer local
4347 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4348 "Matches first line of a hidden block.")
4349 (make-variable-buffer-local 'org-drawer-regexp)
4350 (defvar org-todo-regexp nil
4351 "Matches any of the TODO state keywords.")
4352 (make-variable-buffer-local 'org-todo-regexp)
4353 (defvar org-not-done-regexp nil
4354 "Matches any of the TODO state keywords except the last one.")
4355 (make-variable-buffer-local 'org-not-done-regexp)
4356 (defvar org-not-done-heading-regexp nil
4357 "Matches a TODO headline that is not done.")
4358 (make-variable-buffer-local 'org-not-done-regexp)
4359 (defvar org-todo-line-regexp nil
4360 "Matches a headline and puts TODO state into group 2 if present.")
4361 (make-variable-buffer-local 'org-todo-line-regexp)
4362 (defvar org-complex-heading-regexp nil
4363 "Matches a headline and puts everything into groups:
4364 group 1: the stars
4365 group 2: The todo keyword, maybe
4366 group 3: Priority cookie
4367 group 4: True headline
4368 group 5: Tags")
4369 (make-variable-buffer-local 'org-complex-heading-regexp)
4370 (defvar org-complex-heading-regexp-format nil
4371 "Printf format to make regexp to match an exact headline.
4372 This regexp will match the headline of any node which has the
4373 exact headline text that is put into the format, but may have any
4374 TODO state, priority and tags.")
4375 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4376 (defvar org-todo-line-tags-regexp nil
4377 "Matches a headline and puts TODO state into group 2 if present.
4378 Also put tags into group 4 if tags are present.")
4379 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4380 (defvar org-ds-keyword-length 12
4381 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4382 (make-variable-buffer-local 'org-ds-keyword-length)
4383 (defvar org-deadline-regexp nil
4384 "Matches the DEADLINE keyword.")
4385 (make-variable-buffer-local 'org-deadline-regexp)
4386 (defvar org-deadline-time-regexp nil
4387 "Matches the DEADLINE keyword together with a time stamp.")
4388 (make-variable-buffer-local 'org-deadline-time-regexp)
4389 (defvar org-deadline-line-regexp nil
4390 "Matches the DEADLINE keyword and the rest of the line.")
4391 (make-variable-buffer-local 'org-deadline-line-regexp)
4392 (defvar org-scheduled-regexp nil
4393 "Matches the SCHEDULED keyword.")
4394 (make-variable-buffer-local 'org-scheduled-regexp)
4395 (defvar org-scheduled-time-regexp nil
4396 "Matches the SCHEDULED keyword together with a time stamp.")
4397 (make-variable-buffer-local 'org-scheduled-time-regexp)
4398 (defvar org-closed-time-regexp nil
4399 "Matches the CLOSED keyword together with a time stamp.")
4400 (make-variable-buffer-local 'org-closed-time-regexp)
4402 (defvar org-keyword-time-regexp nil
4403 "Matches any of the 4 keywords, together with the time stamp.")
4404 (make-variable-buffer-local 'org-keyword-time-regexp)
4405 (defvar org-keyword-time-not-clock-regexp nil
4406 "Matches any of the 3 keywords, together with the time stamp.")
4407 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4408 (defvar org-maybe-keyword-time-regexp nil
4409 "Matches a timestamp, possibly preceded by a keyword.")
4410 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4411 (defvar org-all-time-keywords nil
4412 "List of time keywords.")
4413 (make-variable-buffer-local 'org-all-time-keywords)
4415 (defconst org-plain-time-of-day-regexp
4416 (concat
4417 "\\(\\<[012]?[0-9]"
4418 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4419 "\\(--?"
4420 "\\(\\<[012]?[0-9]"
4421 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4422 "\\)?")
4423 "Regular expression to match a plain time or time range.
4424 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4425 groups carry important information:
4426 0 the full match
4427 1 the first time, range or not
4428 8 the second time, if it is a range.")
4430 (defconst org-plain-time-extension-regexp
4431 (concat
4432 "\\(\\<[012]?[0-9]"
4433 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4434 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4435 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4436 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4437 groups carry important information:
4438 0 the full match
4439 7 hours of duration
4440 9 minutes of duration")
4442 (defconst org-stamp-time-of-day-regexp
4443 (concat
4444 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4445 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4446 "\\(--?"
4447 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4448 "Regular expression to match a timestamp time or time range.
4449 After a match, the following groups carry important information:
4450 0 the full match
4451 1 date plus weekday, for back referencing to make sure both times are on the same day
4452 2 the first time, range or not
4453 4 the second time, if it is a range.")
4455 (defconst org-startup-options
4456 '(("fold" org-startup-folded t)
4457 ("overview" org-startup-folded t)
4458 ("nofold" org-startup-folded nil)
4459 ("showall" org-startup-folded nil)
4460 ("showeverything" org-startup-folded showeverything)
4461 ("content" org-startup-folded content)
4462 ("indent" org-startup-indented t)
4463 ("noindent" org-startup-indented nil)
4464 ("hidestars" org-hide-leading-stars t)
4465 ("showstars" org-hide-leading-stars nil)
4466 ("odd" org-odd-levels-only t)
4467 ("oddeven" org-odd-levels-only nil)
4468 ("align" org-startup-align-all-tables t)
4469 ("noalign" org-startup-align-all-tables nil)
4470 ("inlineimages" org-startup-with-inline-images t)
4471 ("noinlineimages" org-startup-with-inline-images nil)
4472 ("customtime" org-display-custom-times t)
4473 ("logdone" org-log-done time)
4474 ("lognotedone" org-log-done note)
4475 ("nologdone" org-log-done nil)
4476 ("lognoteclock-out" org-log-note-clock-out t)
4477 ("nolognoteclock-out" org-log-note-clock-out nil)
4478 ("logrepeat" org-log-repeat state)
4479 ("lognoterepeat" org-log-repeat note)
4480 ("nologrepeat" org-log-repeat nil)
4481 ("logreschedule" org-log-reschedule time)
4482 ("lognotereschedule" org-log-reschedule note)
4483 ("nologreschedule" org-log-reschedule nil)
4484 ("logredeadline" org-log-redeadline time)
4485 ("lognoteredeadline" org-log-redeadline note)
4486 ("nologredeadline" org-log-redeadline nil)
4487 ("logrefile" org-log-refile time)
4488 ("lognoterefile" org-log-refile note)
4489 ("nologrefile" org-log-refile nil)
4490 ("fninline" org-footnote-define-inline t)
4491 ("nofninline" org-footnote-define-inline nil)
4492 ("fnlocal" org-footnote-section nil)
4493 ("fnauto" org-footnote-auto-label t)
4494 ("fnprompt" org-footnote-auto-label nil)
4495 ("fnconfirm" org-footnote-auto-label confirm)
4496 ("fnplain" org-footnote-auto-label plain)
4497 ("fnadjust" org-footnote-auto-adjust t)
4498 ("nofnadjust" org-footnote-auto-adjust nil)
4499 ("constcgs" constants-unit-system cgs)
4500 ("constSI" constants-unit-system SI)
4501 ("noptag" org-tag-persistent-alist nil)
4502 ("hideblocks" org-hide-block-startup t)
4503 ("nohideblocks" org-hide-block-startup nil)
4504 ("beamer" org-startup-with-beamer-mode t)
4505 ("entitiespretty" org-pretty-entities t)
4506 ("entitiesplain" org-pretty-entities nil))
4507 "Variable associated with STARTUP options for org-mode.
4508 Each element is a list of three items: the startup options (as written
4509 in the #+STARTUP line), the corresponding variable, and the value to set
4510 this variable to if the option is found. An optional forth element PUSH
4511 means to push this value onto the list in the variable.")
4513 (defun org-update-property-plist (key val props)
4514 "Update PROPS with KEY and VAL."
4515 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4516 (key (if appending (substring key 0 (- (length key) 1)) key))
4517 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4518 (previous (cdr (assoc key props))))
4519 (if appending
4520 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4521 (cons (cons key val) remainder))))
4523 (defconst org-block-regexp
4524 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4525 "Regular expression for hiding blocks.")
4526 (defconst org-heading-keyword-regexp-format
4527 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4528 "Printf format for a regexp matching an headline with some keyword.
4529 This regexp will match the headline of any node which has the
4530 exact keyword that is put into the format. The keyword isn't in
4531 any group by default, but the stars and the body are.")
4532 (defconst org-heading-keyword-maybe-regexp-format
4533 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4534 "Printf format for a regexp matching an headline, possibly with some keyword.
4535 This regexp can match any headline with the specified keyword, or
4536 without a keyword. The keyword isn't in any group by default,
4537 but the stars and the body are.")
4539 (defun org-set-regexps-and-options ()
4540 "Precompute regular expressions for current buffer."
4541 (when (derived-mode-p 'org-mode)
4542 (org-set-local 'org-todo-kwd-alist nil)
4543 (org-set-local 'org-todo-key-alist nil)
4544 (org-set-local 'org-todo-key-trigger nil)
4545 (org-set-local 'org-todo-keywords-1 nil)
4546 (org-set-local 'org-done-keywords nil)
4547 (org-set-local 'org-todo-heads nil)
4548 (org-set-local 'org-todo-sets nil)
4549 (org-set-local 'org-todo-log-states nil)
4550 (org-set-local 'org-file-properties nil)
4551 (org-set-local 'org-file-tags nil)
4552 (let ((re (org-make-options-regexp
4553 '("CATEGORY" "TODO" "COLUMNS"
4554 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4555 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4556 "OPTIONS")
4557 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4558 (splitre "[ \t]+")
4559 (scripts org-use-sub-superscripts)
4560 kwds kws0 kwsa key log value cat arch tags const links hw dws
4561 tail sep kws1 prio props ftags drawers beamer-p
4562 ext-setup-or-nil setup-contents (start 0))
4563 (save-excursion
4564 (save-restriction
4565 (widen)
4566 (goto-char (point-min))
4567 (while (or (and ext-setup-or-nil
4568 (string-match re ext-setup-or-nil start)
4569 (setq start (match-end 0)))
4570 (and (setq ext-setup-or-nil nil start 0)
4571 (re-search-forward re nil t)))
4572 (setq key (upcase (match-string 1 ext-setup-or-nil))
4573 value (org-match-string-no-properties 2 ext-setup-or-nil))
4574 (if (stringp value) (setq value (org-trim value)))
4575 (cond
4576 ((equal key "CATEGORY")
4577 (setq cat value))
4578 ((member key '("SEQ_TODO" "TODO"))
4579 (push (cons 'sequence (org-split-string value splitre)) kwds))
4580 ((equal key "TYP_TODO")
4581 (push (cons 'type (org-split-string value splitre)) kwds))
4582 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4583 ;; general TODO-like setup
4584 (push (cons (intern (downcase (match-string 1 key)))
4585 (org-split-string value splitre)) kwds))
4586 ((equal key "TAGS")
4587 (setq tags (append tags (if tags '("\\n") nil)
4588 (org-split-string value splitre))))
4589 ((equal key "COLUMNS")
4590 (org-set-local 'org-columns-default-format value))
4591 ((equal key "LINK")
4592 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4593 (push (cons (match-string 1 value)
4594 (org-trim (match-string 2 value)))
4595 links)))
4596 ((equal key "PRIORITIES")
4597 (setq prio (org-split-string value " +")))
4598 ((equal key "PROPERTY")
4599 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4600 (setq props (org-update-property-plist (match-string 1 value)
4601 (match-string 2 value)
4602 props))))
4603 ((equal key "FILETAGS")
4604 (when (string-match "\\S-" value)
4605 (setq ftags
4606 (append
4607 ftags
4608 (apply 'append
4609 (mapcar (lambda (x) (org-split-string x ":"))
4610 (org-split-string value)))))))
4611 ((equal key "DRAWERS")
4612 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4613 ((equal key "CONSTANTS")
4614 (setq const (append const (org-split-string value splitre))))
4615 ((equal key "STARTUP")
4616 (let ((opts (org-split-string value splitre))
4617 l var val)
4618 (while (setq l (pop opts))
4619 (when (setq l (assoc l org-startup-options))
4620 (setq var (nth 1 l) val (nth 2 l))
4621 (if (not (nth 3 l))
4622 (set (make-local-variable var) val)
4623 (if (not (listp (symbol-value var)))
4624 (set (make-local-variable var) nil))
4625 (set (make-local-variable var) (symbol-value var))
4626 (add-to-list var val))))))
4627 ((equal key "ARCHIVE")
4628 (setq arch value)
4629 (remove-text-properties 0 (length arch)
4630 '(face t fontified t) arch))
4631 ((equal key "LATEX_CLASS")
4632 (setq beamer-p (equal value "beamer")))
4633 ((equal key "OPTIONS")
4634 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4635 (setq scripts (read (match-string 2 value)))))
4636 ((equal key "SETUPFILE")
4637 (setq setup-contents (org-file-contents
4638 (expand-file-name
4639 (org-remove-double-quotes value))
4640 'noerror))
4641 (if (not ext-setup-or-nil)
4642 (setq ext-setup-or-nil setup-contents start 0)
4643 (setq ext-setup-or-nil
4644 (concat (substring ext-setup-or-nil 0 start)
4645 "\n" setup-contents "\n"
4646 (substring ext-setup-or-nil start)))))))
4647 ;; search for property blocks
4648 (goto-char (point-min))
4649 (while (re-search-forward org-block-regexp nil t)
4650 (when (equal "PROPERTY" (upcase (match-string 1)))
4651 (setq value (replace-regexp-in-string
4652 "[\n\r]" " " (match-string 4)))
4653 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4654 (setq props (org-update-property-plist (match-string 1 value)
4655 (match-string 2 value)
4656 props)))))))
4657 (org-set-local 'org-use-sub-superscripts scripts)
4658 (when cat
4659 (org-set-local 'org-category (intern cat))
4660 (push (cons "CATEGORY" cat) props))
4661 (when prio
4662 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4663 (setq prio (mapcar 'string-to-char prio))
4664 (org-set-local 'org-highest-priority (nth 0 prio))
4665 (org-set-local 'org-lowest-priority (nth 1 prio))
4666 (org-set-local 'org-default-priority (nth 2 prio)))
4667 (and props (org-set-local 'org-file-properties (nreverse props)))
4668 (and ftags (org-set-local 'org-file-tags
4669 (mapcar 'org-add-prop-inherited ftags)))
4670 (and drawers (org-set-local 'org-drawers drawers))
4671 (and arch (org-set-local 'org-archive-location arch))
4672 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4673 ;; Process the TODO keywords
4674 (unless kwds
4675 ;; Use the global values as if they had been given locally.
4676 (setq kwds (default-value 'org-todo-keywords))
4677 (if (stringp (car kwds))
4678 (setq kwds (list (cons org-todo-interpretation
4679 (default-value 'org-todo-keywords)))))
4680 (setq kwds (reverse kwds)))
4681 (setq kwds (nreverse kwds))
4682 (let (inter kws kw)
4683 (while (setq kws (pop kwds))
4684 (let ((kws (or
4685 (run-hook-with-args-until-success
4686 'org-todo-setup-filter-hook kws)
4687 kws)))
4688 (setq inter (pop kws) sep (member "|" kws)
4689 kws0 (delete "|" (copy-sequence kws))
4690 kwsa nil
4691 kws1 (mapcar
4692 (lambda (x)
4693 ;; 1 2
4694 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4695 (progn
4696 (setq kw (match-string 1 x)
4697 key (and (match-end 2) (match-string 2 x))
4698 log (org-extract-log-state-settings x))
4699 (push (cons kw (and key (string-to-char key))) kwsa)
4700 (and log (push log org-todo-log-states))
4702 (error "Invalid TODO keyword %s" x)))
4703 kws0)
4704 kwsa (if kwsa (append '((:startgroup))
4705 (nreverse kwsa)
4706 '((:endgroup))))
4707 hw (car kws1)
4708 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4709 tail (list inter hw (car dws) (org-last dws))))
4710 (add-to-list 'org-todo-heads hw 'append)
4711 (push kws1 org-todo-sets)
4712 (setq org-done-keywords (append org-done-keywords dws nil))
4713 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4714 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4715 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4716 (setq org-todo-sets (nreverse org-todo-sets)
4717 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4718 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4719 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4720 ;; Process the constants
4721 (when const
4722 (let (e cst)
4723 (while (setq e (pop const))
4724 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4725 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4726 (setq org-table-formula-constants-local cst)))
4728 ;; Process the tags.
4729 (when tags
4730 (let (e tgs)
4731 (while (setq e (pop tags))
4732 (cond
4733 ((equal e "{") (push '(:startgroup) tgs))
4734 ((equal e "}") (push '(:endgroup) tgs))
4735 ((equal e "\\n") (push '(:newline) tgs))
4736 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4737 (push (cons (match-string 1 e)
4738 (string-to-char (match-string 2 e)))
4739 tgs))
4740 (t (push (list e) tgs))))
4741 (org-set-local 'org-tag-alist nil)
4742 (while (setq e (pop tgs))
4743 (or (and (stringp (car e))
4744 (assoc (car e) org-tag-alist))
4745 (push e org-tag-alist)))))
4747 ;; Compute the regular expressions and other local variables.
4748 ;; Using `org-outline-regexp-bol' would complicate them much,
4749 ;; because of the fixed white space at the end of that string.
4750 (if (not org-done-keywords)
4751 (setq org-done-keywords (and org-todo-keywords-1
4752 (list (org-last org-todo-keywords-1)))))
4753 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4754 (length org-scheduled-string)
4755 (length org-clock-string)
4756 (length org-closed-string)))
4757 org-drawer-regexp
4758 (concat "^[ \t]*:\\("
4759 (mapconcat 'regexp-quote org-drawers "\\|")
4760 "\\):[ \t]*$")
4761 org-not-done-keywords
4762 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4763 org-todo-regexp
4764 (concat "\\("
4765 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4766 "\\)")
4767 org-not-done-regexp
4768 (concat "\\("
4769 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4770 "\\)")
4771 org-not-done-heading-regexp
4772 (format org-heading-keyword-regexp-format org-not-done-regexp)
4773 org-todo-line-regexp
4774 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4775 org-complex-heading-regexp
4776 (concat "^\\(\\*+\\)"
4777 "\\(?: +" org-todo-regexp "\\)?"
4778 "\\(?: +\\(\\[#.\\]\\)\\)?"
4779 "\\(?: +\\(.*?\\)\\)??"
4780 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4781 "[ \t]*$")
4782 org-complex-heading-regexp-format
4783 (concat "^\\(\\*+\\)"
4784 "\\(?: +" org-todo-regexp "\\)?"
4785 "\\(?: +\\(\\[#.\\]\\)\\)?"
4786 "\\(?: +"
4787 ;; Stats cookies can be stuck to body.
4788 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4789 "\\(%s\\)"
4790 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4791 "\\)"
4792 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4793 "[ \t]*$")
4794 org-todo-line-tags-regexp
4795 (concat "^\\(\\*+\\)"
4796 "\\(?: +" org-todo-regexp "\\)?"
4797 "\\(?: +\\(.*?\\)\\)??"
4798 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4799 "[ \t]*$")
4800 org-deadline-regexp (concat "\\<" org-deadline-string)
4801 org-deadline-time-regexp
4802 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4803 org-deadline-line-regexp
4804 (concat "\\<\\(" org-deadline-string "\\).*")
4805 org-scheduled-regexp
4806 (concat "\\<" org-scheduled-string)
4807 org-scheduled-time-regexp
4808 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4809 org-closed-time-regexp
4810 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4811 org-keyword-time-regexp
4812 (concat "\\<\\(" org-scheduled-string
4813 "\\|" org-deadline-string
4814 "\\|" org-closed-string
4815 "\\|" org-clock-string "\\)"
4816 " *[[<]\\([^]>]+\\)[]>]")
4817 org-keyword-time-not-clock-regexp
4818 (concat "\\<\\(" org-scheduled-string
4819 "\\|" org-deadline-string
4820 "\\|" org-closed-string
4821 "\\)"
4822 " *[[<]\\([^]>]+\\)[]>]")
4823 org-maybe-keyword-time-regexp
4824 (concat "\\(\\<\\(" org-scheduled-string
4825 "\\|" org-deadline-string
4826 "\\|" org-closed-string
4827 "\\|" org-clock-string "\\)\\)?"
4828 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4829 org-all-time-keywords
4830 (mapcar (lambda (w) (substring w 0 -1))
4831 (list org-scheduled-string org-deadline-string
4832 org-clock-string org-closed-string))
4834 (org-compute-latex-and-specials-regexp)
4835 (org-set-font-lock-defaults))))
4837 (defun org-file-contents (file &optional noerror)
4838 "Return the contents of FILE, as a string."
4839 (if (or (not file)
4840 (not (file-readable-p file)))
4841 (if noerror
4842 (progn
4843 (message "Cannot read file \"%s\"" file)
4844 (ding) (sit-for 2)
4846 (error "Cannot read file \"%s\"" file))
4847 (with-temp-buffer
4848 (insert-file-contents file)
4849 (buffer-string))))
4851 (defun org-extract-log-state-settings (x)
4852 "Extract the log state setting from a TODO keyword string.
4853 This will extract info from a string like \"WAIT(w@/!)\"."
4854 (let (kw key log1 log2)
4855 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4856 (setq kw (match-string 1 x)
4857 key (and (match-end 2) (match-string 2 x))
4858 log1 (and (match-end 3) (match-string 3 x))
4859 log2 (and (match-end 4) (match-string 4 x)))
4860 (and (or log1 log2)
4861 (list kw
4862 (and log1 (if (equal log1 "!") 'time 'note))
4863 (and log2 (if (equal log2 "!") 'time 'note)))))))
4865 (defun org-remove-keyword-keys (list)
4866 "Remove a pair of parenthesis at the end of each string in LIST."
4867 (mapcar (lambda (x)
4868 (if (string-match "(.*)$" x)
4869 (substring x 0 (match-beginning 0))
4871 list))
4873 (defun org-assign-fast-keys (alist)
4874 "Assign fast keys to a keyword-key alist.
4875 Respect keys that are already there."
4876 (let (new e (alt ?0))
4877 (while (setq e (pop alist))
4878 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4879 (cdr e)) ;; Key already assigned.
4880 (push e new)
4881 (let ((clist (string-to-list (downcase (car e))))
4882 (used (append new alist)))
4883 (when (= (car clist) ?@)
4884 (pop clist))
4885 (while (and clist (rassoc (car clist) used))
4886 (pop clist))
4887 (unless clist
4888 (while (rassoc alt used)
4889 (incf alt)))
4890 (push (cons (car e) (or (car clist) alt)) new))))
4891 (nreverse new)))
4893 ;;; Some variables used in various places
4895 (defvar org-window-configuration nil
4896 "Used in various places to store a window configuration.")
4897 (defvar org-selected-window nil
4898 "Used in various places to store a window configuration.")
4899 (defvar org-finish-function nil
4900 "Function to be called when `C-c C-c' is used.
4901 This is for getting out of special buffers like capture.")
4904 ;; FIXME: Occasionally check by commenting these, to make sure
4905 ;; no other functions uses these, forgetting to let-bind them.
4906 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4907 (defvar org-last-state)
4908 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4910 ;; Defined somewhere in this file, but used before definition.
4911 (defvar org-entities) ;; defined in org-entities.el
4912 (defvar org-struct-menu)
4913 (defvar org-org-menu)
4914 (defvar org-tbl-menu)
4916 ;;;; Define the Org-mode
4918 ;; We use a before-change function to check if a table might need
4919 ;; an update.
4920 (defvar org-table-may-need-update t
4921 "Indicates that a table might need an update.
4922 This variable is set by `org-before-change-function'.
4923 `org-table-align' sets it back to nil.")
4924 (defun org-before-change-function (beg end)
4925 "Every change indicates that a table might need an update."
4926 (setq org-table-may-need-update t))
4927 (defvar org-mode-map)
4928 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4929 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4930 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4931 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4932 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4933 (defvar org-table-buffer-is-an nil)
4935 (defvar bidi-paragraph-direction)
4936 (defvar buffer-face-mode-face)
4938 (require 'outline)
4939 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4940 (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"))
4941 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4943 ;; Other stuff we need.
4944 (require 'time-date)
4945 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4946 (require 'easymenu)
4947 (require 'overlay)
4949 (require 'org-macs)
4950 (require 'org-entities)
4951 ;; (require 'org-compat) moved higher up in the file before it is first used
4952 (require 'org-faces)
4953 (require 'org-list)
4954 (require 'org-pcomplete)
4955 (require 'org-src)
4956 (require 'org-footnote)
4958 ;; babel
4959 (require 'ob)
4961 ;;;###autoload
4962 (define-derived-mode org-mode outline-mode "Org"
4963 "Outline-based notes management and organizer, alias
4964 \"Carsten's outline-mode for keeping track of everything.\"
4966 Org-mode develops organizational tasks around a NOTES file which
4967 contains information about projects as plain text. Org-mode is
4968 implemented on top of outline-mode, which is ideal to keep the content
4969 of large files well structured. It supports ToDo items, deadlines and
4970 time stamps, which magically appear in the diary listing of the Emacs
4971 calendar. Tables are easily created with a built-in table editor.
4972 Plain text URL-like links connect to websites, emails (VM), Usenet
4973 messages (Gnus), BBDB entries, and any files related to the project.
4974 For printing and sharing of notes, an Org-mode file (or a part of it)
4975 can be exported as a structured ASCII or HTML file.
4977 The following commands are available:
4979 \\{org-mode-map}"
4981 ;; Get rid of Outline menus, they are not needed
4982 ;; Need to do this here because define-derived-mode sets up
4983 ;; the keymap so late. Still, it is a waste to call this each time
4984 ;; we switch another buffer into org-mode.
4985 (if (featurep 'xemacs)
4986 (when (boundp 'outline-mode-menu-heading)
4987 ;; Assume this is Greg's port, it uses easymenu
4988 (easy-menu-remove outline-mode-menu-heading)
4989 (easy-menu-remove outline-mode-menu-show)
4990 (easy-menu-remove outline-mode-menu-hide))
4991 (define-key org-mode-map [menu-bar headings] 'undefined)
4992 (define-key org-mode-map [menu-bar hide] 'undefined)
4993 (define-key org-mode-map [menu-bar show] 'undefined))
4995 (org-load-modules-maybe)
4996 (easy-menu-add org-org-menu)
4997 (easy-menu-add org-tbl-menu)
4998 (org-install-agenda-files-menu)
4999 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5000 (add-to-invisibility-spec '(org-cwidth))
5001 (add-to-invisibility-spec '(org-hide-block . t))
5002 (when (featurep 'xemacs)
5003 (org-set-local 'line-move-ignore-invisible t))
5004 (org-set-local 'outline-regexp org-outline-regexp)
5005 (org-set-local 'outline-level 'org-outline-level)
5006 (setq bidi-paragraph-direction 'left-to-right)
5007 (when (and org-ellipsis
5008 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5009 (fboundp 'make-glyph-code))
5010 (unless org-display-table
5011 (setq org-display-table (make-display-table)))
5012 (set-display-table-slot
5013 org-display-table 4
5014 (vconcat (mapcar
5015 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5016 org-ellipsis)))
5017 (if (stringp org-ellipsis) org-ellipsis "..."))))
5018 (setq buffer-display-table org-display-table))
5019 (org-set-regexps-and-options)
5020 (when (and org-tag-faces (not org-tags-special-faces-re))
5021 ;; tag faces set outside customize.... force initialization.
5022 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5023 ;; Calc embedded
5024 (org-set-local 'calc-embedded-open-mode "# ")
5025 (modify-syntax-entry ?@ "w")
5026 (modify-syntax-entry ?\" "\"")
5027 (if org-startup-truncated (setq truncate-lines t))
5028 (org-set-local 'font-lock-unfontify-region-function
5029 'org-unfontify-region)
5030 ;; Activate before-change-function
5031 (org-set-local 'org-table-may-need-update t)
5032 (org-add-hook 'before-change-functions 'org-before-change-function nil
5033 'local)
5034 ;; Check for running clock before killing a buffer
5035 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5036 ;; Initialize macros templates.
5037 (org-macro-initialize-templates)
5038 ;; Initialize radio targets.
5039 (org-update-radio-target-regexp)
5040 ;; Indentation.
5041 (org-set-local 'indent-line-function 'org-indent-line)
5042 (org-set-local 'indent-region-function 'org-indent-region)
5043 ;; Filling and auto-filling.
5044 (org-setup-filling)
5045 ;; Comments.
5046 (org-setup-comments-handling)
5047 ;; Beginning/end of defun
5048 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5049 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5050 ;; Next error for sparse trees
5051 (org-set-local 'next-error-function 'org-occur-next-match)
5052 ;; Make sure dependence stuff works reliably, even for users who set it
5053 ;; too late :-(
5054 (if org-enforce-todo-dependencies
5055 (add-hook 'org-blocker-hook
5056 'org-block-todo-from-children-or-siblings-or-parent)
5057 (remove-hook 'org-blocker-hook
5058 'org-block-todo-from-children-or-siblings-or-parent))
5059 (if org-enforce-todo-checkbox-dependencies
5060 (add-hook 'org-blocker-hook
5061 'org-block-todo-from-checkboxes)
5062 (remove-hook 'org-blocker-hook
5063 'org-block-todo-from-checkboxes))
5065 ;; Align options lines
5066 (org-set-local
5067 'align-mode-rules-list
5068 '((org-in-buffer-settings
5069 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5070 (modes . '(org-mode)))))
5072 ;; Imenu
5073 (org-set-local 'imenu-create-index-function
5074 'org-imenu-get-tree)
5076 ;; Make isearch reveal context
5077 (if (or (featurep 'xemacs)
5078 (not (boundp 'outline-isearch-open-invisible-function)))
5079 ;; Emacs 21 and XEmacs make use of the hook
5080 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5081 ;; Emacs 22 deals with this through a special variable
5082 (org-set-local 'outline-isearch-open-invisible-function
5083 (lambda (&rest ignore) (org-show-context 'isearch))))
5085 ;; Turn on org-beamer-mode?
5086 (and org-startup-with-beamer-mode (org-beamer-mode))
5088 ;; Setup the pcomplete hooks
5089 (set (make-local-variable 'pcomplete-command-completion-function)
5090 'org-pcomplete-initial)
5091 (set (make-local-variable 'pcomplete-command-name-function)
5092 'org-command-at-point)
5093 (set (make-local-variable 'pcomplete-default-completion-function)
5094 'ignore)
5095 (set (make-local-variable 'pcomplete-parse-arguments-function)
5096 'org-parse-arguments)
5097 (set (make-local-variable 'pcomplete-termination-string) "")
5098 (when (>= emacs-major-version 23)
5099 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5101 ;; If empty file that did not turn on org-mode automatically, make it to.
5102 (if (and org-insert-mode-line-in-empty-file
5103 (org-called-interactively-p 'any)
5104 (= (point-min) (point-max)))
5105 (insert "# -*- mode: org -*-\n\n"))
5106 (unless org-inhibit-startup
5107 (when org-startup-align-all-tables
5108 (let ((bmp (buffer-modified-p)))
5109 (org-table-map-tables 'org-table-align 'quietly)
5110 (set-buffer-modified-p bmp)))
5111 (when org-startup-with-inline-images
5112 (org-display-inline-images))
5113 (when org-startup-indented
5114 (require 'org-indent)
5115 (org-indent-mode 1))
5116 (unless org-inhibit-startup-visibility-stuff
5117 (org-set-startup-visibility)))
5118 ;; Try to set org-hide correctly
5119 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5121 (when (fboundp 'abbrev-table-put)
5122 (abbrev-table-put org-mode-abbrev-table
5123 :parents (list text-mode-abbrev-table)))
5125 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5128 (defun org-find-invisible-foreground ()
5129 (let ((candidates (remove
5130 "unspecified-bg"
5131 (nconc
5132 (list (face-background 'default)
5133 (face-background 'org-default))
5134 (mapcar
5135 (lambda (alist)
5136 (when (boundp alist)
5137 (cdr (assoc 'background-color (symbol-value alist)))))
5138 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5139 (list (face-foreground 'org-hide))))))
5140 (car (remove nil candidates))))
5142 (defun org-current-time ()
5143 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5144 (if (> (car org-time-stamp-rounding-minutes) 1)
5145 (let ((r (car org-time-stamp-rounding-minutes))
5146 (time (decode-time)))
5147 (apply 'encode-time
5148 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5149 (nthcdr 2 time))))
5150 (current-time)))
5152 (defun org-today ()
5153 "Return today date, considering `org-extend-today-until'."
5154 (time-to-days
5155 (time-subtract (current-time)
5156 (list 0 (* 3600 org-extend-today-until) 0))))
5158 ;;;; Font-Lock stuff, including the activators
5160 (defvar org-mouse-map (make-sparse-keymap))
5161 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5162 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5163 (when org-mouse-1-follows-link
5164 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5165 (when org-tab-follows-link
5166 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5167 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5169 (require 'font-lock)
5171 (defconst org-non-link-chars "]\t\n\r<>")
5172 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5173 "shell" "elisp" "doi" "message"))
5174 (defvar org-link-types-re nil
5175 "Matches a link that has a url-like prefix like \"http:\"")
5176 (defvar org-link-re-with-space nil
5177 "Matches a link with spaces, optional angular brackets around it.")
5178 (defvar org-link-re-with-space2 nil
5179 "Matches a link with spaces, optional angular brackets around it.")
5180 (defvar org-link-re-with-space3 nil
5181 "Matches a link with spaces, only for internal part in bracket links.")
5182 (defvar org-angle-link-re nil
5183 "Matches link with angular brackets, spaces are allowed.")
5184 (defvar org-plain-link-re nil
5185 "Matches plain link, without spaces.")
5186 (defvar org-bracket-link-regexp nil
5187 "Matches a link in double brackets.")
5188 (defvar org-bracket-link-analytic-regexp nil
5189 "Regular expression used to analyze links.
5190 Here is what the match groups contain after a match:
5191 1: http:
5192 2: http
5193 3: path
5194 4: [desc]
5195 5: desc")
5196 (defvar org-bracket-link-analytic-regexp++ nil
5197 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5198 (defvar org-any-link-re nil
5199 "Regular expression matching any link.")
5201 (defcustom org-match-sexp-depth 3
5202 "Number of stacked braces for sub/superscript matching.
5203 This has to be set before loading org.el to be effective."
5204 :group 'org-export-translation ; ??????????????????????????/
5205 :type 'integer)
5207 (defun org-create-multibrace-regexp (left right n)
5208 "Create a regular expression which will match a balanced sexp.
5209 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5210 as single character strings.
5211 The regexp returned will match the entire expression including the
5212 delimiters. It will also define a single group which contains the
5213 match except for the outermost delimiters. The maximum depth of
5214 stacked delimiters is N. Escaping delimiters is not possible."
5215 (let* ((nothing (concat "[^" left right "]*?"))
5216 (or "\\|")
5217 (re nothing)
5218 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5219 (while (> n 1)
5220 (setq n (1- n)
5221 re (concat re or next)
5222 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5223 (concat left "\\(" re "\\)" right)))
5225 (defvar org-match-substring-regexp
5226 (concat
5227 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5228 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5229 "\\|"
5230 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5231 "\\|"
5232 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5233 "The regular expression matching a sub- or superscript.")
5235 (defvar org-match-substring-with-braces-regexp
5236 (concat
5237 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5238 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5239 "\\)")
5240 "The regular expression matching a sub- or superscript, forcing braces.")
5242 (defun org-make-link-regexps ()
5243 "Update the link regular expressions.
5244 This should be called after the variable `org-link-types' has changed."
5245 (setq org-link-types-re
5246 (concat
5247 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5248 org-link-re-with-space
5249 (concat
5250 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5251 "\\([^" org-non-link-chars " ]"
5252 "[^" org-non-link-chars "]*"
5253 "[^" org-non-link-chars " ]\\)>?")
5254 org-link-re-with-space2
5255 (concat
5256 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5257 "\\([^" org-non-link-chars " ]"
5258 "[^\t\n\r]*"
5259 "[^" org-non-link-chars " ]\\)>?")
5260 org-link-re-with-space3
5261 (concat
5262 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5263 "\\([^" org-non-link-chars " ]"
5264 "[^\t\n\r]*\\)")
5265 org-angle-link-re
5266 (concat
5267 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5268 "\\([^" org-non-link-chars " ]"
5269 "[^" org-non-link-chars "]*"
5270 "\\)>")
5271 org-plain-link-re
5272 (concat
5273 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5274 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5275 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5276 org-bracket-link-regexp
5277 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5278 org-bracket-link-analytic-regexp
5279 (concat
5280 "\\[\\["
5281 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5282 "\\([^]]+\\)"
5283 "\\]"
5284 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5285 "\\]")
5286 org-bracket-link-analytic-regexp++
5287 (concat
5288 "\\[\\["
5289 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5290 "\\([^]]+\\)"
5291 "\\]"
5292 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5293 "\\]")
5294 org-any-link-re
5295 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5296 org-angle-link-re "\\)\\|\\("
5297 org-plain-link-re "\\)")))
5299 (org-make-link-regexps)
5301 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5302 "Regular expression for fast time stamp matching.")
5303 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5304 "Regular expression for fast time stamp matching.")
5305 (defconst org-ts-regexp0
5306 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5307 "Regular expression matching time strings for analysis.
5308 This one does not require the space after the date, so it can be used
5309 on a string that terminates immediately after the date.")
5310 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5311 "Regular expression matching time strings for analysis.")
5312 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5313 "Regular expression matching time stamps, with groups.")
5314 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5315 "Regular expression matching time stamps (also [..]), with groups.")
5316 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5317 "Regular expression matching a time stamp range.")
5318 (defconst org-tr-regexp-both
5319 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5320 "Regular expression matching a time stamp range.")
5321 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5322 org-ts-regexp "\\)?")
5323 "Regular expression matching a time stamp or time stamp range.")
5324 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5325 org-ts-regexp-both "\\)?")
5326 "Regular expression matching a time stamp or time stamp range.
5327 The time stamps may be either active or inactive.")
5329 (defvar org-emph-face nil)
5331 (defun org-do-emphasis-faces (limit)
5332 "Run through the buffer and add overlays to emphasized strings."
5333 (let (rtn a)
5334 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5335 (if (not (= (char-after (match-beginning 3))
5336 (char-after (match-beginning 4))))
5337 (progn
5338 (setq rtn t)
5339 (setq a (assoc (match-string 3) org-emphasis-alist))
5340 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5341 'face
5342 (nth 1 a))
5343 (and (nth 4 a)
5344 (org-remove-flyspell-overlays-in
5345 (match-beginning 0) (match-end 0)))
5346 (add-text-properties (match-beginning 2) (match-end 2)
5347 '(font-lock-multiline t org-emphasis t))
5348 (when org-hide-emphasis-markers
5349 (add-text-properties (match-end 4) (match-beginning 5)
5350 '(invisible org-link))
5351 (add-text-properties (match-beginning 3) (match-end 3)
5352 '(invisible org-link)))))
5353 (backward-char 1))
5354 rtn))
5356 (defun org-emphasize (&optional char)
5357 "Insert or change an emphasis, i.e. a font like bold or italic.
5358 If there is an active region, change that region to a new emphasis.
5359 If there is no region, just insert the marker characters and position
5360 the cursor between them.
5361 CHAR should be either the marker character, or the first character of the
5362 HTML tag associated with that emphasis. If CHAR is a space, the means
5363 to remove the emphasis of the selected region.
5364 If char is not given (for example in an interactive call) it
5365 will be prompted for."
5366 (interactive)
5367 (let ((eal org-emphasis-alist) e det
5368 (erc org-emphasis-regexp-components)
5369 (prompt "")
5370 (string "") beg end move tag c s)
5371 (if (org-region-active-p)
5372 (setq beg (region-beginning) end (region-end)
5373 string (buffer-substring beg end))
5374 (setq move t))
5376 (while (setq e (pop eal))
5377 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5378 c (aref tag 0))
5379 (push (cons c (string-to-char (car e))) det)
5380 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5381 (substring tag 1)))))
5382 (setq det (nreverse det))
5383 (unless char
5384 (message "%s" (concat "Emphasis marker or tag:" prompt))
5385 (setq char (read-char-exclusive)))
5386 (setq char (or (cdr (assoc char det)) char))
5387 (if (equal char ?\ )
5388 (setq s "" move nil)
5389 (unless (assoc (char-to-string char) org-emphasis-alist)
5390 (error "No such emphasis marker: \"%c\"" char))
5391 (setq s (char-to-string char)))
5392 (while (and (> (length string) 1)
5393 (equal (substring string 0 1) (substring string -1))
5394 (assoc (substring string 0 1) org-emphasis-alist))
5395 (setq string (substring string 1 -1)))
5396 (setq string (concat s string s))
5397 (if beg (delete-region beg end))
5398 (unless (or (bolp)
5399 (string-match (concat "[" (nth 0 erc) "\n]")
5400 (char-to-string (char-before (point)))))
5401 (insert " "))
5402 (unless (or (eobp)
5403 (string-match (concat "[" (nth 1 erc) "\n]")
5404 (char-to-string (char-after (point)))))
5405 (insert " ") (backward-char 1))
5406 (insert string)
5407 (and move (backward-char 1))))
5409 (defconst org-nonsticky-props
5410 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5412 (defsubst org-rear-nonsticky-at (pos)
5413 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5415 (defun org-activate-plain-links (limit)
5416 "Run through the buffer and add overlays to links."
5417 (catch 'exit
5418 (let (f hl)
5419 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5420 (not (org-in-src-block-p)))
5421 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5422 (setq f (get-text-property (match-beginning 0) 'face))
5423 (setq hl (org-match-string-no-properties 0))
5424 (if (or (eq f 'org-tag)
5425 (and (listp f) (memq 'org-tag f)))
5427 (add-text-properties (match-beginning 0) (match-end 0)
5428 (list 'mouse-face 'highlight
5429 'face 'org-link
5430 'htmlize-link `(:uri ,hl)
5431 'keymap org-mouse-map))
5432 (org-rear-nonsticky-at (match-end 0)))
5433 t))))
5435 (defun org-activate-code (limit)
5436 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5437 (progn
5438 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5439 (remove-text-properties (match-beginning 0) (match-end 0)
5440 '(display t invisible t intangible t))
5441 t)))
5443 (defcustom org-src-fontify-natively nil
5444 "When non-nil, fontify code in code blocks."
5445 :type 'boolean
5446 :version "24.1"
5447 :group 'org-appearance
5448 :group 'org-babel)
5450 (defcustom org-allow-promoting-top-level-subtree nil
5451 "When non-nil, allow promoting a top level subtree.
5452 The leading star of the top level headline will be replaced
5453 by a #."
5454 :type 'boolean
5455 :version "24.1"
5456 :group 'org-appearance)
5458 (defun org-fontify-meta-lines-and-blocks (limit)
5459 (condition-case nil
5460 (org-fontify-meta-lines-and-blocks-1 limit)
5461 (error (message "org-mode fontification error"))))
5463 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5464 "Fontify #+ lines and blocks, in the correct ways."
5465 (let ((case-fold-search t))
5466 (if (re-search-forward
5467 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5468 limit t)
5469 (let ((beg (match-beginning 0))
5470 (block-start (match-end 0))
5471 (block-end nil)
5472 (lang (match-string 7))
5473 (beg1 (line-beginning-position 2))
5474 (dc1 (downcase (match-string 2)))
5475 (dc3 (downcase (match-string 3)))
5476 end end1 quoting block-type ovl)
5477 (cond
5478 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5479 ;; a single line of backend-specific content
5480 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5481 (remove-text-properties (match-beginning 0) (match-end 0)
5482 '(display t invisible t intangible t))
5483 (add-text-properties (match-beginning 1) (match-end 3)
5484 '(font-lock-fontified t face org-meta-line))
5485 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5486 '(font-lock-fontified t face org-block))
5487 ; for backend-specific code
5489 ((and (match-end 4) (equal dc3 "+begin"))
5490 ;; Truly a block
5491 (setq block-type (downcase (match-string 5))
5492 quoting (member block-type org-protecting-blocks))
5493 (when (re-search-forward
5494 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5495 nil t) ;; on purpose, we look further than LIMIT
5496 (setq end (min (point-max) (match-end 0))
5497 end1 (min (point-max) (1- (match-beginning 0))))
5498 (setq block-end (match-beginning 0))
5499 (when quoting
5500 (remove-text-properties beg end
5501 '(display t invisible t intangible t)))
5502 (add-text-properties
5503 beg end
5504 '(font-lock-fontified t font-lock-multiline t))
5505 (add-text-properties beg beg1 '(face org-meta-line))
5506 (add-text-properties end1 (min (point-max) (1+ end))
5507 '(face org-meta-line)) ; for end_src
5508 (cond
5509 ((and lang (not (string= lang "")) org-src-fontify-natively)
5510 (org-src-font-lock-fontify-block lang block-start block-end)
5511 ;; remove old background overlays
5512 (mapc (lambda (ov)
5513 (if (eq (overlay-get ov 'face) 'org-block-background)
5514 (delete-overlay ov)))
5515 (overlays-at (/ (+ beg1 block-end) 2)))
5516 ;; add a background overlay
5517 (setq ovl (make-overlay beg1 block-end))
5518 (overlay-put ovl 'face 'org-block-background)
5519 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5520 (quoting
5521 (add-text-properties beg1 (min (point-max) (1+ end1))
5522 '(face org-block))) ; end of source block
5523 ((not org-fontify-quote-and-verse-blocks))
5524 ((string= block-type "quote")
5525 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5526 ((string= block-type "verse")
5527 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5528 (add-text-properties beg beg1 '(face org-block-begin-line))
5529 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5530 '(face org-block-end-line))
5532 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5533 (add-text-properties
5534 beg (match-end 3)
5535 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5536 '(font-lock-fontified t invisible t)
5537 '(font-lock-fontified t face org-document-info-keyword)))
5538 (add-text-properties
5539 (match-beginning 6) (match-end 6)
5540 (if (string-equal dc1 "+title:")
5541 '(font-lock-fontified t face org-document-title)
5542 '(font-lock-fontified t face org-document-info))))
5543 ((or (equal dc1 "+results")
5544 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5545 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5546 "+call:" "+header:" "+headers:" "+name:"))
5547 (and (match-end 4) (equal dc3 "+attr")))
5548 (add-text-properties
5549 beg (match-end 0)
5550 '(font-lock-fontified t face org-meta-line))
5552 ((member dc3 '(" " ""))
5553 (add-text-properties
5554 beg (match-end 0)
5555 '(font-lock-fontified t face font-lock-comment-face)))
5556 ((not (member (char-after beg) '(?\ ?\t)))
5557 ;; just any other in-buffer setting, but not indented
5558 (add-text-properties
5559 beg (match-end 0)
5560 '(font-lock-fontified t face org-meta-line))
5562 (t nil))))))
5564 (defun org-activate-angle-links (limit)
5565 "Run through the buffer and add overlays to links."
5566 (if (and (re-search-forward org-angle-link-re limit t)
5567 (not (org-in-src-block-p)))
5568 (progn
5569 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5570 (add-text-properties (match-beginning 0) (match-end 0)
5571 (list 'mouse-face 'highlight
5572 'keymap org-mouse-map))
5573 (org-rear-nonsticky-at (match-end 0))
5574 t)))
5576 (defun org-activate-footnote-links (limit)
5577 "Run through the buffer and add overlays to footnotes."
5578 (let ((fn (org-footnote-next-reference-or-definition limit)))
5579 (when fn
5580 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5581 (org-remove-flyspell-overlays-in beg end)
5582 (add-text-properties beg end
5583 (list 'mouse-face 'highlight
5584 'keymap org-mouse-map
5585 'help-echo
5586 (if (= (point-at-bol) beg)
5587 "Footnote definition"
5588 "Footnote reference")
5589 'font-lock-fontified t
5590 'font-lock-multiline t
5591 'face 'org-footnote))))))
5593 (defun org-activate-bracket-links (limit)
5594 "Run through the buffer and add overlays to bracketed links."
5595 (if (and (re-search-forward org-bracket-link-regexp limit t)
5596 (not (org-in-src-block-p)))
5597 (let* ((hl (org-match-string-no-properties 1))
5598 (help (concat "LINK: " hl))
5599 ;; FIXME: Above we should remove the escapes. But that
5600 ;; requires another match, protecting match data, a lot
5601 ;; of overhead for font-lock.
5602 (ip (org-maybe-intangible
5603 (list 'invisible 'org-link
5604 'keymap org-mouse-map 'mouse-face 'highlight
5605 'font-lock-multiline t 'help-echo help
5606 'htmlize-link `(:uri ,hl))))
5607 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5608 'font-lock-multiline t 'help-echo help
5609 'htmlize-link `(:uri ,hl))))
5610 ;; We need to remove the invisible property here. Table narrowing
5611 ;; may have made some of this invisible.
5612 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5613 (remove-text-properties (match-beginning 0) (match-end 0)
5614 '(invisible nil))
5615 (if (match-end 3)
5616 (progn
5617 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5618 (org-rear-nonsticky-at (match-beginning 3))
5619 (add-text-properties (match-beginning 3) (match-end 3) vp)
5620 (org-rear-nonsticky-at (match-end 3))
5621 (add-text-properties (match-end 3) (match-end 0) ip)
5622 (org-rear-nonsticky-at (match-end 0)))
5623 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5624 (org-rear-nonsticky-at (match-beginning 1))
5625 (add-text-properties (match-beginning 1) (match-end 1) vp)
5626 (org-rear-nonsticky-at (match-end 1))
5627 (add-text-properties (match-end 1) (match-end 0) ip)
5628 (org-rear-nonsticky-at (match-end 0)))
5629 t)))
5631 (defun org-activate-dates (limit)
5632 "Run through the buffer and add overlays to dates."
5633 (if (re-search-forward org-tsr-regexp-both limit t)
5634 (progn
5635 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5636 (add-text-properties (match-beginning 0) (match-end 0)
5637 (list 'mouse-face 'highlight
5638 'keymap org-mouse-map))
5639 (org-rear-nonsticky-at (match-end 0))
5640 (when org-display-custom-times
5641 (if (match-end 3)
5642 (org-display-custom-time (match-beginning 3) (match-end 3)))
5643 (org-display-custom-time (match-beginning 1) (match-end 1)))
5644 t)))
5646 (defvar org-target-link-regexp nil
5647 "Regular expression matching radio targets in plain text.")
5648 (make-variable-buffer-local 'org-target-link-regexp)
5649 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5650 "Regular expression matching a link target.")
5651 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5652 "Regular expression matching a radio target.")
5653 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5654 "Regular expression matching any target.")
5656 (defun org-activate-target-links (limit)
5657 "Run through the buffer and add overlays to target matches."
5658 (when org-target-link-regexp
5659 (let ((case-fold-search t))
5660 (if (re-search-forward org-target-link-regexp limit t)
5661 (progn
5662 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5663 (add-text-properties (match-beginning 0) (match-end 0)
5664 (list 'mouse-face 'highlight
5665 'keymap org-mouse-map
5666 'help-echo "Radio target link"
5667 'org-linked-text t))
5668 (org-rear-nonsticky-at (match-end 0))
5669 t)))))
5671 (defun org-update-radio-target-regexp ()
5672 "Find all radio targets in this file and update the regular expression."
5673 (interactive)
5674 (when (memq 'radio org-activate-links)
5675 (setq org-target-link-regexp
5676 (org-make-target-link-regexp (org-all-targets 'radio)))
5677 (org-restart-font-lock)))
5679 (defun org-hide-wide-columns (limit)
5680 (let (s e)
5681 (setq s (text-property-any (point) (or limit (point-max))
5682 'org-cwidth t))
5683 (when s
5684 (setq e (next-single-property-change s 'org-cwidth))
5685 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5686 (goto-char e)
5687 t)))
5689 (defvar org-latex-and-specials-regexp nil
5690 "Regular expression for highlighting export special stuff.")
5691 (defvar org-match-substring-regexp)
5692 (defvar org-match-substring-with-braces-regexp)
5694 ;; This should be with the exporter code, but we also use if for font-locking
5695 (defconst org-export-html-special-string-regexps
5696 '(("\\\\-" . "&shy;")
5697 ("---\\([^-]\\)" . "&mdash;\\1")
5698 ("--\\([^-]\\)" . "&ndash;\\1")
5699 ("\\.\\.\\." . "&hellip;"))
5700 "Regular expressions for special string conversion.")
5703 (defun org-compute-latex-and-specials-regexp ()
5704 "Compute regular expression for stuff treated specially by exporters."
5705 (if (not org-highlight-latex-fragments-and-specials)
5706 (org-set-local 'org-latex-and-specials-regexp nil)
5707 (require 'org-exp)
5708 (let*
5709 ((matchers (plist-get org-format-latex-options :matchers))
5710 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5711 org-latex-regexps)))
5712 (org-export-allow-BIND nil)
5713 (options (org-combine-plists (org-default-export-plist)
5714 (org-infile-export-plist)))
5715 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5716 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5717 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5718 (org-export-html-expand (plist-get options :expand-quoted-html))
5719 (org-export-with-special-strings (plist-get options :special-strings))
5720 (re-sub
5721 (cond
5722 ((equal org-export-with-sub-superscripts '{})
5723 (list org-match-substring-with-braces-regexp))
5724 (org-export-with-sub-superscripts
5725 (list org-match-substring-regexp))))
5726 (re-latex
5727 (if org-export-with-LaTeX-fragments
5728 (mapcar (lambda (x) (nth 1 x)) latexs)))
5729 (re-macros
5730 (if org-export-with-TeX-macros
5731 (list (concat "\\\\"
5732 (regexp-opt
5733 (append
5735 (delq nil
5736 (mapcar 'car-safe
5737 (append org-entities-user
5738 org-entities)))
5739 (if (boundp 'org-latex-entities)
5740 (mapcar (lambda (x)
5741 (or (car-safe x) x))
5742 org-latex-entities)
5743 nil))
5744 'words))) ; FIXME
5746 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5747 (re-special (if org-export-with-special-strings
5748 (mapcar (lambda (x) (car x))
5749 org-export-html-special-string-regexps)))
5750 (re-rest
5751 (delq nil
5752 (list
5753 (if org-export-html-expand "@<[^>\n]+>")
5754 ))))
5755 (org-set-local
5756 'org-latex-and-specials-regexp
5757 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5758 re-rest) "\\|")))))
5760 (defun org-do-latex-and-special-faces (limit)
5761 "Run through the buffer and add overlays to links."
5762 (when org-latex-and-specials-regexp
5763 (let (rtn d)
5764 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5765 limit t))
5766 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5767 'face))
5768 '(org-code org-verbatim underline)))
5769 (progn
5770 (setq rtn t
5771 d (cond ((member (char-after (1+ (match-beginning 0)))
5772 '(?_ ?^)) 1)
5773 (t 0)))
5774 (font-lock-prepend-text-property
5775 (+ d (match-beginning 0)) (match-end 0)
5776 'face 'org-latex-and-export-specials)
5777 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5778 '(font-lock-multiline t)))))
5779 rtn)))
5781 (defun org-restart-font-lock ()
5782 "Restart `font-lock-mode', to force refontification."
5783 (when (and (boundp 'font-lock-mode) font-lock-mode)
5784 (font-lock-mode -1)
5785 (font-lock-mode 1)))
5787 (defun org-all-targets (&optional radio)
5788 "Return a list of all targets in this file.
5789 When optional argument RADIO is non-nil, only find radio
5790 targets."
5791 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5792 (save-excursion
5793 (goto-char (point-min))
5794 (while (re-search-forward re nil t)
5795 ;; Make sure point is really within the object.
5796 (backward-char)
5797 (let ((obj (org-element-context)))
5798 (when (memq (org-element-type obj) '(radio-target target))
5799 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5800 rtn)))
5802 (defun org-make-target-link-regexp (targets)
5803 "Make regular expression matching all strings in TARGETS.
5804 The regular expression finds the targets also if there is a line break
5805 between words."
5806 (and targets
5807 (concat
5808 "\\<\\("
5809 (mapconcat
5810 (lambda (x)
5811 (setq x (regexp-quote x))
5812 (while (string-match " +" x)
5813 (setq x (replace-match "\\s-+" t t x)))
5815 targets
5816 "\\|")
5817 "\\)\\>")))
5819 (defun org-activate-tags (limit)
5820 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5821 (progn
5822 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5823 (add-text-properties (match-beginning 1) (match-end 1)
5824 (list 'mouse-face 'highlight
5825 'keymap org-mouse-map))
5826 (org-rear-nonsticky-at (match-end 1))
5827 t)))
5829 (defun org-outline-level ()
5830 "Compute the outline level of the heading at point.
5831 If this is called at a normal headline, the level is the number of stars.
5832 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5833 (save-excursion
5834 (if (not (condition-case nil
5835 (org-back-to-heading t)
5836 (error nil)))
5838 (looking-at org-outline-regexp)
5839 (1- (- (match-end 0) (match-beginning 0))))))
5841 (defvar org-font-lock-keywords nil)
5843 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5844 "Regular expression matching a property line.")
5846 (defvar org-font-lock-hook nil
5847 "Functions to be called for special font lock stuff.")
5849 (defvar org-font-lock-set-keywords-hook nil
5850 "Functions that can manipulate `org-font-lock-extra-keywords'.
5851 This is called after `org-font-lock-extra-keywords' is defined, but before
5852 it is installed to be used by font lock. This can be useful if something
5853 needs to be inserted at a specific position in the font-lock sequence.")
5855 (defun org-font-lock-hook (limit)
5856 "Run `org-font-lock-hook' within LIMIT."
5857 (run-hook-with-args 'org-font-lock-hook limit))
5859 (defun org-set-font-lock-defaults ()
5860 "Set font lock defaults for the current buffer."
5861 (let* ((em org-fontify-emphasized-text)
5862 (lk org-activate-links)
5863 (org-font-lock-extra-keywords
5864 (list
5865 ;; Call the hook
5866 '(org-font-lock-hook)
5867 ;; Headlines
5868 `(,(if org-fontify-whole-heading-line
5869 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5870 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5871 (1 (org-get-level-face 1))
5872 (2 (org-get-level-face 2))
5873 (3 (org-get-level-face 3)))
5874 ;; Table lines
5875 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5876 (1 'org-table t))
5877 ;; Table internals
5878 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5879 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5880 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5881 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5882 ;; Drawers
5883 (list org-drawer-regexp '(0 'org-special-keyword t))
5884 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5885 ;; Properties
5886 (list org-property-re
5887 '(1 'org-special-keyword t)
5888 '(3 'org-property-value t))
5889 ;; Links
5890 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5891 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5892 (if (memq 'plain lk) '(org-activate-plain-links))
5893 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5894 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5895 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5896 (if (memq 'footnote lk) '(org-activate-footnote-links))
5897 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5898 '(org-hide-wide-columns (0 nil append))
5899 ;; TODO keyword
5900 (list (format org-heading-keyword-regexp-format
5901 org-todo-regexp)
5902 '(2 (org-get-todo-face 2) t))
5903 ;; DONE
5904 (if org-fontify-done-headline
5905 (list (format org-heading-keyword-regexp-format
5906 (concat
5907 "\\(?:"
5908 (mapconcat 'regexp-quote org-done-keywords "\\|")
5909 "\\)"))
5910 '(2 'org-headline-done t))
5911 nil)
5912 ;; Priorities
5913 '(org-font-lock-add-priority-faces)
5914 ;; Tags
5915 '(org-font-lock-add-tag-faces)
5916 ;; Special keywords
5917 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5918 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5919 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5920 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5921 ;; Emphasis
5922 (if em
5923 (if (featurep 'xemacs)
5924 '(org-do-emphasis-faces (0 nil append))
5925 '(org-do-emphasis-faces)))
5926 ;; Checkboxes
5927 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5928 1 'org-checkbox prepend)
5929 (if (cdr (assq 'checkbox org-list-automatic-rules))
5930 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5931 (0 (org-get-checkbox-statistics-face) t)))
5932 ;; Description list items
5933 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5934 1 'org-list-dt prepend)
5935 ;; ARCHIVEd headings
5936 (list (concat
5937 org-outline-regexp-bol
5938 "\\(.*:" org-archive-tag ":.*\\)")
5939 '(1 'org-archived prepend))
5940 ;; Specials
5941 '(org-do-latex-and-special-faces)
5942 '(org-fontify-entities)
5943 '(org-raise-scripts)
5944 ;; Code
5945 '(org-activate-code (1 'org-code t))
5946 ;; COMMENT
5947 (list (format org-heading-keyword-regexp-format
5948 (concat "\\("
5949 org-comment-string "\\|" org-quote-string
5950 "\\)"))
5951 '(2 'org-special-keyword t))
5952 ;; Blocks and meta lines
5953 '(org-fontify-meta-lines-and-blocks)
5955 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5956 (run-hooks 'org-font-lock-set-keywords-hook)
5957 ;; Now set the full font-lock-keywords
5958 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5959 (org-set-local 'font-lock-defaults
5960 '(org-font-lock-keywords t nil nil backward-paragraph))
5961 (kill-local-variable 'font-lock-keywords) nil))
5963 (defun org-toggle-pretty-entities ()
5964 "Toggle the composition display of entities as UTF8 characters."
5965 (interactive)
5966 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5967 (org-restart-font-lock)
5968 (if org-pretty-entities
5969 (message "Entities are displayed as UTF8 characters")
5970 (save-restriction
5971 (widen)
5972 (org-decompose-region (point-min) (point-max))
5973 (message "Entities are displayed plain"))))
5975 (defvar org-custom-properties-overlays nil
5976 "List of overlays used for custom properties.")
5977 (make-variable-buffer-local 'org-custom-properties-overlays)
5979 (defun org-toggle-custom-properties-visibility ()
5980 "Display or hide properties in `org-custom-properties'."
5981 (interactive)
5982 (if org-custom-properties-overlays
5983 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5984 (setq org-custom-properties-overlays nil))
5985 (unless (not org-custom-properties)
5986 (save-excursion
5987 (save-restriction
5988 (widen)
5989 (goto-char (point-min))
5990 (while (re-search-forward org-property-re nil t)
5991 (mapc (lambda(p)
5992 (when (equal p (substring (match-string 1) 1 -1))
5993 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5994 (overlay-put o 'invisible t)
5995 (overlay-put o 'org-custom-property t)
5996 (push o org-custom-properties-overlays))))
5997 org-custom-properties)))))))
5999 (defun org-fontify-entities (limit)
6000 "Find an entity to fontify."
6001 (let (ee)
6002 (when org-pretty-entities
6003 (catch 'match
6004 (while (re-search-forward
6005 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6006 limit t)
6007 (if (and (not (org-in-indented-comment-line))
6008 (setq ee (org-entity-get (match-string 1)))
6009 (= (length (nth 6 ee)) 1))
6010 (let*
6011 ((end (if (equal (match-string 2) "{}")
6012 (match-end 2)
6013 (match-end 1))))
6014 (add-text-properties
6015 (match-beginning 0) end
6016 (list 'font-lock-fontified t))
6017 (compose-region (match-beginning 0) end
6018 (nth 6 ee) nil)
6019 (backward-char 1)
6020 (throw 'match t))))
6021 nil))))
6023 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6024 "Fontify string S like in Org-mode."
6025 (with-temp-buffer
6026 (insert s)
6027 (let ((org-odd-levels-only odd-levels))
6028 (org-mode)
6029 (font-lock-fontify-buffer)
6030 (buffer-string))))
6032 (defvar org-m nil)
6033 (defvar org-l nil)
6034 (defvar org-f nil)
6035 (defun org-get-level-face (n)
6036 "Get the right face for match N in font-lock matching of headlines."
6037 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6038 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6039 (if org-cycle-level-faces
6040 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6041 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6042 (cond
6043 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6044 ((eq n 2) org-f)
6045 (t (if org-level-color-stars-only nil org-f))))
6048 (defun org-get-todo-face (kwd)
6049 "Get the right face for a TODO keyword KWD.
6050 If KWD is a number, get the corresponding match group."
6051 (if (numberp kwd) (setq kwd (match-string kwd)))
6052 (or (org-face-from-face-or-color
6053 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6054 (and (member kwd org-done-keywords) 'org-done)
6055 'org-todo))
6057 (defun org-face-from-face-or-color (context inherit face-or-color)
6058 "Create a face list that inherits INHERIT, but sets the foreground color.
6059 When FACE-OR-COLOR is not a string, just return it."
6060 (if (stringp face-or-color)
6061 (list :inherit inherit
6062 (cdr (assoc context org-faces-easy-properties))
6063 face-or-color)
6064 face-or-color))
6066 (defun org-font-lock-add-tag-faces (limit)
6067 "Add the special tag faces."
6068 (when (and org-tag-faces org-tags-special-faces-re)
6069 (while (re-search-forward org-tags-special-faces-re limit t)
6070 (add-text-properties (match-beginning 1) (match-end 1)
6071 (list 'face (org-get-tag-face 1)
6072 'font-lock-fontified t))
6073 (backward-char 1))))
6075 (defun org-font-lock-add-priority-faces (limit)
6076 "Add the special priority faces."
6077 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6078 (when (save-match-data (org-at-heading-p))
6079 (add-text-properties
6080 (match-beginning 0) (match-end 0)
6081 (list 'face (or (org-face-from-face-or-color
6082 'priority 'org-special-keyword
6083 (cdr (assoc (char-after (match-beginning 1))
6084 org-priority-faces)))
6085 'org-special-keyword)
6086 'font-lock-fontified t)))))
6088 (defun org-get-tag-face (kwd)
6089 "Get the right face for a TODO keyword KWD.
6090 If KWD is a number, get the corresponding match group."
6091 (if (numberp kwd) (setq kwd (match-string kwd)))
6092 (or (org-face-from-face-or-color
6093 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6094 'org-tag))
6096 (defun org-unfontify-region (beg end &optional maybe_loudly)
6097 "Remove fontification and activation overlays from links."
6098 (font-lock-default-unfontify-region beg end)
6099 (let* ((buffer-undo-list t)
6100 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6101 (inhibit-modification-hooks t)
6102 deactivate-mark buffer-file-name buffer-file-truename)
6103 (org-decompose-region beg end)
6104 (remove-text-properties beg end
6105 '(mouse-face t keymap t org-linked-text t
6106 invisible t intangible t
6107 org-no-flyspell t org-emphasis t))
6108 (org-remove-font-lock-display-properties beg end)))
6110 (defconst org-script-display '(((raise -0.3) (height 0.7))
6111 ((raise 0.3) (height 0.7))
6112 ((raise -0.5))
6113 ((raise 0.5)))
6114 "Display properties for showing superscripts and subscripts.")
6116 (defun org-remove-font-lock-display-properties (beg end)
6117 "Remove specific display properties that have been added by font lock.
6118 The will remove the raise properties that are used to show superscripts
6119 and subscripts."
6120 (let (next prop)
6121 (while (< beg end)
6122 (setq next (next-single-property-change beg 'display nil end)
6123 prop (get-text-property beg 'display))
6124 (if (member prop org-script-display)
6125 (put-text-property beg next 'display nil))
6126 (setq beg next))))
6128 (defun org-raise-scripts (limit)
6129 "Add raise properties to sub/superscripts."
6130 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6131 (if (re-search-forward
6132 (if (eq org-use-sub-superscripts t)
6133 org-match-substring-regexp
6134 org-match-substring-with-braces-regexp)
6135 limit t)
6136 (let* ((pos (point)) table-p comment-p
6137 (mpos (match-beginning 3))
6138 (emph-p (get-text-property mpos 'org-emphasis))
6139 (link-p (get-text-property mpos 'mouse-face))
6140 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6141 (goto-char (point-at-bol))
6142 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6143 comment-p (org-looking-at-p "[ \t]*#"))
6144 (goto-char pos)
6145 ;; FIXME: Should we go back one character here, for a_b^c
6146 ;; (goto-char (1- pos)) ;????????????????????
6147 (if (or comment-p emph-p link-p keyw-p)
6149 (put-text-property (match-beginning 3) (match-end 0)
6150 'display
6151 (if (equal (char-after (match-beginning 2)) ?^)
6152 (nth (if table-p 3 1) org-script-display)
6153 (nth (if table-p 2 0) org-script-display)))
6154 (add-text-properties (match-beginning 2) (match-end 2)
6155 (list 'invisible t
6156 'org-dwidth t 'org-dwidth-n 1))
6157 (if (and (eq (char-after (match-beginning 3)) ?{)
6158 (eq (char-before (match-end 3)) ?}))
6159 (progn
6160 (add-text-properties
6161 (match-beginning 3) (1+ (match-beginning 3))
6162 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6163 (add-text-properties
6164 (1- (match-end 3)) (match-end 3)
6165 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6166 t)))))
6168 ;;;; Visibility cycling, including org-goto and indirect buffer
6170 ;;; Cycling
6172 (defvar org-cycle-global-status nil)
6173 (make-variable-buffer-local 'org-cycle-global-status)
6174 (defvar org-cycle-subtree-status nil)
6175 (make-variable-buffer-local 'org-cycle-subtree-status)
6177 (defvar org-inlinetask-min-level)
6179 ;;;###autoload
6180 (defun org-cycle (&optional arg)
6181 "TAB-action and visibility cycling for Org-mode.
6183 This is the command invoked in Org-mode by the TAB key. Its main purpose
6184 is outline visibility cycling, but it also invokes other actions
6185 in special contexts.
6187 - When this function is called with a prefix argument, rotate the entire
6188 buffer through 3 states (global cycling)
6189 1. OVERVIEW: Show only top-level headlines.
6190 2. CONTENTS: Show all headlines of all levels, but no body text.
6191 3. SHOW ALL: Show everything.
6192 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6193 determined by the variable `org-startup-folded', and by any VISIBILITY
6194 properties in the buffer.
6195 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6196 including any drawers.
6198 - When inside a table, re-align the table and move to the next field.
6200 - When point is at the beginning of a headline, rotate the subtree started
6201 by this line through 3 different states (local cycling)
6202 1. FOLDED: Only the main headline is shown.
6203 2. CHILDREN: The main headline and the direct children are shown.
6204 From this state, you can move to one of the children
6205 and zoom in further.
6206 3. SUBTREE: Show the entire subtree, including body text.
6207 If there is no subtree, switch directly from CHILDREN to FOLDED.
6209 - When point is at the beginning of an empty headline and the variable
6210 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6211 of the headline by demoting and promoting it to likely levels. This
6212 speeds up creation document structure by pressing TAB once or several
6213 times right after creating a new headline.
6215 - When there is a numeric prefix, go up to a heading with level ARG, do
6216 a `show-subtree' and return to the previous cursor position. If ARG
6217 is negative, go up that many levels.
6219 - When point is not at the beginning of a headline, execute the global
6220 binding for TAB, which is re-indenting the line. See the option
6221 `org-cycle-emulate-tab' for details.
6223 - Special case: if point is at the beginning of the buffer and there is
6224 no headline in line 1, this function will act as if called with prefix arg
6225 (C-u TAB, same as S-TAB) also when called without prefix arg.
6226 But only if also the variable `org-cycle-global-at-bob' is t."
6227 (interactive "P")
6228 (org-load-modules-maybe)
6229 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6230 (and org-cycle-level-after-item/entry-creation
6231 (or (org-cycle-level)
6232 (org-cycle-item-indentation))))
6233 (let* (message-log-max ; Don't populate the *Messages* buffer
6234 (limit-level
6235 (or org-cycle-max-level
6236 (and (boundp 'org-inlinetask-min-level)
6237 org-inlinetask-min-level
6238 (1- org-inlinetask-min-level))))
6239 (nstars (and limit-level
6240 (if org-odd-levels-only
6241 (and limit-level (1- (* limit-level 2)))
6242 limit-level)))
6243 (org-outline-regexp
6244 (if (not (derived-mode-p 'org-mode))
6245 outline-regexp
6246 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6247 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6248 (not (looking-at org-outline-regexp))))
6249 (org-cycle-hook
6250 (if bob-special
6251 (delq 'org-optimize-window-after-visibility-change
6252 (copy-sequence org-cycle-hook))
6253 org-cycle-hook))
6254 (pos (point)))
6256 (if (or bob-special (equal arg '(4)))
6257 ;; special case: use global cycling
6258 (setq arg t))
6260 (cond
6262 ((equal arg '(16))
6263 (setq last-command 'dummy)
6264 (org-set-startup-visibility)
6265 (message "Startup visibility, plus VISIBILITY properties"))
6267 ((equal arg '(64))
6268 (show-all)
6269 (message "Entire buffer visible, including drawers"))
6271 ;; Table: enter it or move to the next field.
6272 ((org-at-table-p 'any)
6273 (if (org-at-table.el-p)
6274 (message "Use C-c ' to edit table.el tables")
6275 (if arg (org-table-edit-field t)
6276 (org-table-justify-field-maybe)
6277 (call-interactively 'org-table-next-field))))
6279 ((run-hook-with-args-until-success
6280 'org-tab-after-check-for-table-hook))
6282 ;; Global cycling: delegate to `org-cycle-internal-global'.
6283 ((eq arg t) (org-cycle-internal-global))
6285 ;; Drawers: delegate to `org-flag-drawer'.
6286 ((and org-drawers org-drawer-regexp
6287 (save-excursion
6288 (beginning-of-line 1)
6289 (looking-at org-drawer-regexp)))
6290 (org-flag-drawer ; toggle block visibility
6291 (not (get-char-property (match-end 0) 'invisible))))
6293 ;; Show-subtree, ARG levels up from here.
6294 ((integerp arg)
6295 (save-excursion
6296 (org-back-to-heading)
6297 (outline-up-heading (if (< arg 0) (- arg)
6298 (- (funcall outline-level) arg)))
6299 (org-show-subtree)))
6301 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6302 ((and (featurep 'org-inlinetask)
6303 (org-inlinetask-at-task-p)
6304 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6305 (org-inlinetask-toggle-visibility))
6307 ((org-try-cdlatex-tab))
6309 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6310 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6311 (save-excursion (beginning-of-line 1)
6312 (looking-at org-outline-regexp)))
6313 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6314 (org-cycle-internal-local))
6316 ;; From there: TAB emulation and template completion.
6317 (buffer-read-only (org-back-to-heading))
6319 ((run-hook-with-args-until-success
6320 'org-tab-after-check-for-cycling-hook))
6322 ((org-try-structure-completion))
6324 ((run-hook-with-args-until-success
6325 'org-tab-before-tab-emulation-hook))
6327 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6328 (or (not (bolp))
6329 (not (looking-at org-outline-regexp))))
6330 (call-interactively (global-key-binding "\t")))
6332 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6333 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6334 (or (and (eq org-cycle-emulate-tab 'white)
6335 (= (match-end 0) (point-at-eol)))
6336 (and (eq org-cycle-emulate-tab 'whitestart)
6337 (>= (match-end 0) pos))))
6339 (eq org-cycle-emulate-tab t))
6340 (call-interactively (global-key-binding "\t")))
6342 (t (save-excursion
6343 (org-back-to-heading)
6344 (org-cycle)))))))
6346 (defun org-cycle-internal-global ()
6347 "Do the global cycling action."
6348 ;; Hack to avoid display of messages for .org attachments in Gnus
6349 (let (message-log-max ; Don't populate the *Messages* buffer
6350 (ga (string-match "\\*fontification" (buffer-name))))
6351 (cond
6352 ((and (eq last-command this-command)
6353 (eq org-cycle-global-status 'overview))
6354 ;; We just created the overview - now do table of contents
6355 ;; This can be slow in very large buffers, so indicate action
6356 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6357 (unless ga (message "CONTENTS..."))
6358 (org-content)
6359 (unless ga (message "CONTENTS...done"))
6360 (setq org-cycle-global-status 'contents)
6361 (run-hook-with-args 'org-cycle-hook 'contents))
6363 ((and (eq last-command this-command)
6364 (eq org-cycle-global-status 'contents))
6365 ;; We just showed the table of contents - now show everything
6366 (run-hook-with-args 'org-pre-cycle-hook 'all)
6367 (show-all)
6368 (unless ga (message "SHOW ALL"))
6369 (setq org-cycle-global-status 'all)
6370 (run-hook-with-args 'org-cycle-hook 'all))
6373 ;; Default action: go to overview
6374 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6375 (org-overview)
6376 (unless ga (message "OVERVIEW"))
6377 (setq org-cycle-global-status 'overview)
6378 (run-hook-with-args 'org-cycle-hook 'overview)))))
6380 (defun org-cycle-internal-local ()
6381 "Do the local cycling action."
6382 (let (message-log-max ; Don't populate the *Messages* buffer
6383 (goal-column 0) eoh eol eos has-children children-skipped struct)
6384 ;; First, determine end of headline (EOH), end of subtree or item
6385 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6386 (save-excursion
6387 (if (org-at-item-p)
6388 (progn
6389 (beginning-of-line)
6390 (setq struct (org-list-struct))
6391 (setq eoh (point-at-eol))
6392 (setq eos (org-list-get-item-end-before-blank (point) struct))
6393 (setq has-children (org-list-has-child-p (point) struct)))
6394 (org-back-to-heading)
6395 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6396 (setq eos (save-excursion
6397 (org-end-of-subtree t)
6398 (unless (eobp)
6399 (skip-chars-forward " \t\n"))
6400 (if (eobp) (point) (1- (point)))))
6401 (setq has-children
6402 (or (save-excursion
6403 (let ((level (funcall outline-level)))
6404 (outline-next-heading)
6405 (and (org-at-heading-p t)
6406 (> (funcall outline-level) level))))
6407 (save-excursion
6408 (org-list-search-forward (org-item-beginning-re) eos t)))))
6409 ;; Determine end invisible part of buffer (EOL)
6410 (beginning-of-line 2)
6411 ;; XEmacs doesn't have `next-single-char-property-change'
6412 (if (featurep 'xemacs)
6413 (while (and (not (eobp)) ;; this is like `next-line'
6414 (get-char-property (1- (point)) 'invisible))
6415 (beginning-of-line 2))
6416 (while (and (not (eobp)) ;; this is like `next-line'
6417 (get-char-property (1- (point)) 'invisible))
6418 (goto-char (next-single-char-property-change (point) 'invisible))
6419 (and (eolp) (beginning-of-line 2))))
6420 (setq eol (point)))
6421 ;; Find out what to do next and set `this-command'
6422 (cond
6423 ((= eos eoh)
6424 ;; Nothing is hidden behind this heading
6425 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6426 (message "EMPTY ENTRY")
6427 (setq org-cycle-subtree-status nil)
6428 (save-excursion
6429 (goto-char eos)
6430 (outline-next-heading)
6431 (if (outline-invisible-p) (org-flag-heading nil))))
6432 ((and (or (>= eol eos)
6433 (not (string-match "\\S-" (buffer-substring eol eos))))
6434 (or has-children
6435 (not (setq children-skipped
6436 org-cycle-skip-children-state-if-no-children))))
6437 ;; Entire subtree is hidden in one line: children view
6438 (run-hook-with-args 'org-pre-cycle-hook 'children)
6439 (if (org-at-item-p)
6440 (org-list-set-item-visibility (point-at-bol) struct 'children)
6441 (org-show-entry)
6442 (org-with-limited-levels (show-children))
6443 ;; FIXME: This slows down the func way too much.
6444 ;; How keep drawers hidden in subtree anyway?
6445 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6446 ;; (org-cycle-hide-drawers 'subtree))
6448 ;; Fold every list in subtree to top-level items.
6449 (when (eq org-cycle-include-plain-lists 'integrate)
6450 (save-excursion
6451 (org-back-to-heading)
6452 (while (org-list-search-forward (org-item-beginning-re) eos t)
6453 (beginning-of-line 1)
6454 (let* ((struct (org-list-struct))
6455 (prevs (org-list-prevs-alist struct))
6456 (end (org-list-get-bottom-point struct)))
6457 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6458 (org-list-get-all-items (point) struct prevs))
6459 (goto-char end))))))
6460 (message "CHILDREN")
6461 (save-excursion
6462 (goto-char eos)
6463 (outline-next-heading)
6464 (if (outline-invisible-p) (org-flag-heading nil)))
6465 (setq org-cycle-subtree-status 'children)
6466 (run-hook-with-args 'org-cycle-hook 'children))
6467 ((or children-skipped
6468 (and (eq last-command this-command)
6469 (eq org-cycle-subtree-status 'children)))
6470 ;; We just showed the children, or no children are there,
6471 ;; now show everything.
6472 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6473 (outline-flag-region eoh eos nil)
6474 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6475 (setq org-cycle-subtree-status 'subtree)
6476 (run-hook-with-args 'org-cycle-hook 'subtree))
6478 ;; Default action: hide the subtree.
6479 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6480 (outline-flag-region eoh eos t)
6481 (message "FOLDED")
6482 (setq org-cycle-subtree-status 'folded)
6483 (run-hook-with-args 'org-cycle-hook 'folded)))))
6485 ;;;###autoload
6486 (defun org-global-cycle (&optional arg)
6487 "Cycle the global visibility. For details see `org-cycle'.
6488 With \\[universal-argument] prefix arg, switch to startup visibility.
6489 With a numeric prefix, show all headlines up to that level."
6490 (interactive "P")
6491 (let ((org-cycle-include-plain-lists
6492 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6493 (cond
6494 ((integerp arg)
6495 (show-all)
6496 (hide-sublevels arg)
6497 (setq org-cycle-global-status 'contents))
6498 ((equal arg '(4))
6499 (org-set-startup-visibility)
6500 (message "Startup visibility, plus VISIBILITY properties."))
6502 (org-cycle '(4))))))
6504 (defun org-set-startup-visibility ()
6505 "Set the visibility required by startup options and properties."
6506 (cond
6507 ((eq org-startup-folded t)
6508 (org-cycle '(4)))
6509 ((eq org-startup-folded 'content)
6510 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6511 (org-cycle '(4)) (org-cycle '(4)))))
6512 (unless (eq org-startup-folded 'showeverything)
6513 (if org-hide-block-startup (org-hide-block-all))
6514 (org-set-visibility-according-to-property 'no-cleanup)
6515 (org-cycle-hide-archived-subtrees 'all)
6516 (org-cycle-hide-drawers 'all)
6517 (org-cycle-show-empty-lines t)))
6519 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6520 "Switch subtree visibilities according to :VISIBILITY: property."
6521 (interactive)
6522 (let (org-show-entry-below state)
6523 (save-excursion
6524 (goto-char (point-min))
6525 (while (re-search-forward
6526 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6527 nil t)
6528 (setq state (match-string 1))
6529 (save-excursion
6530 (org-back-to-heading t)
6531 (hide-subtree)
6532 (org-reveal)
6533 (cond
6534 ((equal state '("fold" "folded"))
6535 (hide-subtree))
6536 ((equal state "children")
6537 (org-show-hidden-entry)
6538 (show-children))
6539 ((equal state "content")
6540 (save-excursion
6541 (save-restriction
6542 (org-narrow-to-subtree)
6543 (org-content))))
6544 ((member state '("all" "showall"))
6545 (show-subtree)))))
6546 (unless no-cleanup
6547 (org-cycle-hide-archived-subtrees 'all)
6548 (org-cycle-hide-drawers 'all)
6549 (org-cycle-show-empty-lines 'all)))))
6551 ;; This function uses outline-regexp instead of the more fundamental
6552 ;; org-outline-regexp so that org-cycle-global works outside of Org
6553 ;; buffers, where outline-regexp is needed.
6554 (defun org-overview ()
6555 "Switch to overview mode, showing only top-level headlines.
6556 Really, this shows all headlines with level equal or greater than the level
6557 of the first headline in the buffer. This is important, because if the
6558 first headline is not level one, then (hide-sublevels 1) gives confusing
6559 results."
6560 (interactive)
6561 (let ((level (save-excursion
6562 (goto-char (point-min))
6563 (if (re-search-forward (concat "^" outline-regexp) nil t)
6564 (progn
6565 (goto-char (match-beginning 0))
6566 (funcall outline-level))))))
6567 (and level (hide-sublevels level))))
6569 (defun org-content (&optional arg)
6570 "Show all headlines in the buffer, like a table of contents.
6571 With numerical argument N, show content up to level N."
6572 (interactive "P")
6573 (save-excursion
6574 ;; Visit all headings and show their offspring
6575 (and (integerp arg) (org-overview))
6576 (goto-char (point-max))
6577 (catch 'exit
6578 (while (and (progn (condition-case nil
6579 (outline-previous-visible-heading 1)
6580 (error (goto-char (point-min))))
6582 (looking-at org-outline-regexp))
6583 (if (integerp arg)
6584 (show-children (1- arg))
6585 (show-branches))
6586 (if (bobp) (throw 'exit nil))))))
6589 (defun org-optimize-window-after-visibility-change (state)
6590 "Adjust the window after a change in outline visibility.
6591 This function is the default value of the hook `org-cycle-hook'."
6592 (when (get-buffer-window (current-buffer))
6593 (cond
6594 ((eq state 'content) nil)
6595 ((eq state 'all) nil)
6596 ((eq state 'folded) nil)
6597 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6598 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6600 (defun org-remove-empty-overlays-at (pos)
6601 "Remove outline overlays that do not contain non-white stuff."
6602 (mapc
6603 (lambda (o)
6604 (and (eq 'outline (overlay-get o 'invisible))
6605 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6606 (overlay-end o))))
6607 (delete-overlay o)))
6608 (overlays-at pos)))
6610 (defun org-clean-visibility-after-subtree-move ()
6611 "Fix visibility issues after moving a subtree."
6612 ;; First, find a reasonable region to look at:
6613 ;; Start two siblings above, end three below
6614 (let* ((beg (save-excursion
6615 (and (org-get-last-sibling)
6616 (org-get-last-sibling))
6617 (point)))
6618 (end (save-excursion
6619 (and (org-get-next-sibling)
6620 (org-get-next-sibling)
6621 (org-get-next-sibling))
6622 (if (org-at-heading-p)
6623 (point-at-eol)
6624 (point))))
6625 (level (looking-at "\\*+"))
6626 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6627 (save-excursion
6628 (save-restriction
6629 (narrow-to-region beg end)
6630 (when re
6631 ;; Properly fold already folded siblings
6632 (goto-char (point-min))
6633 (while (re-search-forward re nil t)
6634 (if (and (not (outline-invisible-p))
6635 (save-excursion
6636 (goto-char (point-at-eol)) (outline-invisible-p)))
6637 (hide-entry))))
6638 (org-cycle-show-empty-lines 'overview)
6639 (org-cycle-hide-drawers 'overview)))))
6641 (defun org-cycle-show-empty-lines (state)
6642 "Show empty lines above all visible headlines.
6643 The region to be covered depends on STATE when called through
6644 `org-cycle-hook'. Lisp program can use t for STATE to get the
6645 entire buffer covered. Note that an empty line is only shown if there
6646 are at least `org-cycle-separator-lines' empty lines before the headline."
6647 (when (not (= org-cycle-separator-lines 0))
6648 (save-excursion
6649 (let* ((n (abs org-cycle-separator-lines))
6650 (re (cond
6651 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6652 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6653 (t (let ((ns (number-to-string (- n 2))))
6654 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6655 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6656 beg end b e)
6657 (cond
6658 ((memq state '(overview contents t))
6659 (setq beg (point-min) end (point-max)))
6660 ((memq state '(children folded))
6661 (setq beg (point) end (progn (org-end-of-subtree t t)
6662 (beginning-of-line 2)
6663 (point)))))
6664 (when beg
6665 (goto-char beg)
6666 (while (re-search-forward re end t)
6667 (unless (get-char-property (match-end 1) 'invisible)
6668 (setq e (match-end 1))
6669 (if (< org-cycle-separator-lines 0)
6670 (setq b (save-excursion
6671 (goto-char (match-beginning 0))
6672 (org-back-over-empty-lines)
6673 (if (save-excursion
6674 (goto-char (max (point-min) (1- (point))))
6675 (org-at-heading-p))
6676 (1- (point))
6677 (point))))
6678 (setq b (match-beginning 1)))
6679 (outline-flag-region b e nil)))))))
6680 ;; Never hide empty lines at the end of the file.
6681 (save-excursion
6682 (goto-char (point-max))
6683 (outline-previous-heading)
6684 (outline-end-of-heading)
6685 (if (and (looking-at "[ \t\n]+")
6686 (= (match-end 0) (point-max)))
6687 (outline-flag-region (point) (match-end 0) nil))))
6689 (defun org-show-empty-lines-in-parent ()
6690 "Move to the parent and re-show empty lines before visible headlines."
6691 (save-excursion
6692 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6693 (org-cycle-show-empty-lines context))))
6695 (defun org-files-list ()
6696 "Return `org-agenda-files' list, plus all open org-mode files.
6697 This is useful for operations that need to scan all of a user's
6698 open and agenda-wise Org files."
6699 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6700 (dolist (buf (buffer-list))
6701 (with-current-buffer buf
6702 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6703 (let ((file (expand-file-name (buffer-file-name))))
6704 (unless (member file files)
6705 (push file files))))))
6706 files))
6708 (defsubst org-entry-beginning-position ()
6709 "Return the beginning position of the current entry."
6710 (save-excursion (outline-back-to-heading t) (point)))
6712 (defsubst org-entry-end-position ()
6713 "Return the end position of the current entry."
6714 (save-excursion (outline-next-heading) (point)))
6716 (defun org-cycle-hide-drawers (state)
6717 "Re-hide all drawers after a visibility state change."
6718 (when (and (derived-mode-p 'org-mode)
6719 (not (memq state '(overview folded contents))))
6720 (save-excursion
6721 (let* ((globalp (memq state '(contents all)))
6722 (beg (if globalp (point-min) (point)))
6723 (end (if globalp (point-max)
6724 (if (eq state 'children)
6725 (save-excursion (outline-next-heading) (point))
6726 (org-end-of-subtree t)))))
6727 (goto-char beg)
6728 (while (re-search-forward org-drawer-regexp end t)
6729 (org-flag-drawer t))))))
6731 (defun org-cycle-hide-inline-tasks (state)
6732 "Re-hide inline task when switching to 'contents visibility state."
6733 (when (and (eq state 'contents)
6734 (boundp 'org-inlinetask-min-level)
6735 org-inlinetask-min-level)
6736 (hide-sublevels (1- org-inlinetask-min-level))))
6738 (defun org-flag-drawer (flag)
6739 "When FLAG is non-nil, hide the drawer we are within.
6740 Otherwise make it visible."
6741 (save-excursion
6742 (beginning-of-line 1)
6743 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6744 (let ((b (match-end 0)))
6745 (if (re-search-forward
6746 "^[ \t]*:END:"
6747 (save-excursion (outline-next-heading) (point)) t)
6748 (outline-flag-region b (point-at-eol) flag)
6749 (error ":END: line missing at position %s" b))))))
6751 (defun org-subtree-end-visible-p ()
6752 "Is the end of the current subtree visible?"
6753 (pos-visible-in-window-p
6754 (save-excursion (org-end-of-subtree t) (point))))
6756 (defun org-first-headline-recenter (&optional N)
6757 "Move cursor to the first headline and recenter the headline.
6758 Optional argument N means put the headline into the Nth line of the window."
6759 (goto-char (point-min))
6760 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6761 (beginning-of-line)
6762 (recenter (prefix-numeric-value N))))
6764 ;;; Saving and restoring visibility
6766 (defun org-outline-overlay-data (&optional use-markers)
6767 "Return a list of the locations of all outline overlays.
6768 These are overlays with the `invisible' property value `outline'.
6769 The return value is a list of cons cells, with start and stop
6770 positions for each overlay.
6771 If USE-MARKERS is set, return the positions as markers."
6772 (let (beg end)
6773 (save-excursion
6774 (save-restriction
6775 (widen)
6776 (delq nil
6777 (mapcar (lambda (o)
6778 (when (eq (overlay-get o 'invisible) 'outline)
6779 (setq beg (overlay-start o)
6780 end (overlay-end o))
6781 (and beg end (> end beg)
6782 (if use-markers
6783 (cons (move-marker (make-marker) beg)
6784 (move-marker (make-marker) end))
6785 (cons beg end)))))
6786 (overlays-in (point-min) (point-max))))))))
6788 (defun org-set-outline-overlay-data (data)
6789 "Create visibility overlays for all positions in DATA.
6790 DATA should have been made by `org-outline-overlay-data'."
6791 (let (o)
6792 (save-excursion
6793 (save-restriction
6794 (widen)
6795 (show-all)
6796 (mapc (lambda (c)
6797 (outline-flag-region (car c) (cdr c) t))
6798 data)))))
6800 ;;; Folding of blocks
6802 (defvar org-hide-block-overlays nil
6803 "Overlays hiding blocks.")
6804 (make-variable-buffer-local 'org-hide-block-overlays)
6806 (defun org-block-map (function &optional start end)
6807 "Call FUNCTION at the head of all source blocks in the current buffer.
6808 Optional arguments START and END can be used to limit the range."
6809 (let ((start (or start (point-min)))
6810 (end (or end (point-max))))
6811 (save-excursion
6812 (goto-char start)
6813 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6814 (save-excursion
6815 (save-match-data
6816 (goto-char (match-beginning 0))
6817 (funcall function)))))))
6819 (defun org-hide-block-toggle-all ()
6820 "Toggle the visibility of all blocks in the current buffer."
6821 (org-block-map #'org-hide-block-toggle))
6823 (defun org-hide-block-all ()
6824 "Fold all blocks in the current buffer."
6825 (interactive)
6826 (org-show-block-all)
6827 (org-block-map #'org-hide-block-toggle-maybe))
6829 (defun org-show-block-all ()
6830 "Unfold all blocks in the current buffer."
6831 (interactive)
6832 (mapc 'delete-overlay org-hide-block-overlays)
6833 (setq org-hide-block-overlays nil))
6835 (defun org-hide-block-toggle-maybe ()
6836 "Toggle visibility of block at point."
6837 (interactive)
6838 (let ((case-fold-search t))
6839 (if (save-excursion
6840 (beginning-of-line 1)
6841 (looking-at org-block-regexp))
6842 (progn (org-hide-block-toggle)
6843 t) ;; to signal that we took action
6844 nil))) ;; to signal that we did not
6846 (defun org-hide-block-toggle (&optional force)
6847 "Toggle the visibility of the current block."
6848 (interactive)
6849 (save-excursion
6850 (beginning-of-line)
6851 (if (re-search-forward org-block-regexp nil t)
6852 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6853 (end (match-end 0)) ;; end of entire body
6855 (if (memq t (mapcar (lambda (overlay)
6856 (eq (overlay-get overlay 'invisible)
6857 'org-hide-block))
6858 (overlays-at start)))
6859 (if (or (not force) (eq force 'off))
6860 (mapc (lambda (ov)
6861 (when (member ov org-hide-block-overlays)
6862 (setq org-hide-block-overlays
6863 (delq ov org-hide-block-overlays)))
6864 (when (eq (overlay-get ov 'invisible)
6865 'org-hide-block)
6866 (delete-overlay ov)))
6867 (overlays-at start)))
6868 (setq ov (make-overlay start end))
6869 (overlay-put ov 'invisible 'org-hide-block)
6870 ;; make the block accessible to isearch
6871 (overlay-put
6872 ov 'isearch-open-invisible
6873 (lambda (ov)
6874 (when (member ov org-hide-block-overlays)
6875 (setq org-hide-block-overlays
6876 (delq ov org-hide-block-overlays)))
6877 (when (eq (overlay-get ov 'invisible)
6878 'org-hide-block)
6879 (delete-overlay ov))))
6880 (push ov org-hide-block-overlays)))
6881 (error "Not looking at a source block"))))
6883 ;; org-tab-after-check-for-cycling-hook
6884 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6885 ;; Remove overlays when changing major mode
6886 (add-hook 'org-mode-hook
6887 (lambda () (org-add-hook 'change-major-mode-hook
6888 'org-show-block-all 'append 'local)))
6890 ;;; Org-goto
6892 (defvar org-goto-window-configuration nil)
6893 (defvar org-goto-marker nil)
6894 (defvar org-goto-map
6895 (let ((map (make-sparse-keymap)))
6896 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6897 (while (setq cmd (pop cmds))
6898 (substitute-key-definition cmd cmd map global-map)))
6899 (suppress-keymap map)
6900 (org-defkey map "\C-m" 'org-goto-ret)
6901 (org-defkey map [(return)] 'org-goto-ret)
6902 (org-defkey map [(left)] 'org-goto-left)
6903 (org-defkey map [(right)] 'org-goto-right)
6904 (org-defkey map [(control ?g)] 'org-goto-quit)
6905 (org-defkey map "\C-i" 'org-cycle)
6906 (org-defkey map [(tab)] 'org-cycle)
6907 (org-defkey map [(down)] 'outline-next-visible-heading)
6908 (org-defkey map [(up)] 'outline-previous-visible-heading)
6909 (if org-goto-auto-isearch
6910 (if (fboundp 'define-key-after)
6911 (define-key-after map [t] 'org-goto-local-auto-isearch)
6912 nil)
6913 (org-defkey map "q" 'org-goto-quit)
6914 (org-defkey map "n" 'outline-next-visible-heading)
6915 (org-defkey map "p" 'outline-previous-visible-heading)
6916 (org-defkey map "f" 'outline-forward-same-level)
6917 (org-defkey map "b" 'outline-backward-same-level)
6918 (org-defkey map "u" 'outline-up-heading))
6919 (org-defkey map "/" 'org-occur)
6920 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6921 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6922 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6923 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6924 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6925 map))
6927 (defconst org-goto-help
6928 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6929 RET=jump to location [Q]uit and return to previous location
6930 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6932 (defvar org-goto-start-pos) ; dynamically scoped parameter
6934 ;; FIXME: Docstring does not mention both interfaces
6935 (defun org-goto (&optional alternative-interface)
6936 "Look up a different location in the current file, keeping current visibility.
6938 When you want look-up or go to a different location in a
6939 document, the fastest way is often to fold the entire buffer and
6940 then dive into the tree. This method has the disadvantage, that
6941 the previous location will be folded, which may not be what you
6942 want.
6944 This command works around this by showing a copy of the current
6945 buffer in an indirect buffer, in overview mode. You can dive
6946 into the tree in that copy, use org-occur and incremental search
6947 to find a location. When pressing RET or `Q', the command
6948 returns to the original buffer in which the visibility is still
6949 unchanged. After RET it will also jump to the location selected
6950 in the indirect buffer and expose the headline hierarchy above.
6952 With a prefix argument, use the alternative interface: e.g. if
6953 `org-goto-interface' is 'outline use 'outline-path-completion."
6954 (interactive "P")
6955 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6956 (org-refile-use-outline-path t)
6957 (org-refile-target-verify-function nil)
6958 (interface
6959 (if (not alternative-interface)
6960 org-goto-interface
6961 (if (eq org-goto-interface 'outline)
6962 'outline-path-completion
6963 'outline)))
6964 (org-goto-start-pos (point))
6965 (selected-point
6966 (if (eq interface 'outline)
6967 (car (org-get-location (current-buffer) org-goto-help))
6968 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6969 (org-refile-check-position pa)
6970 (nth 3 pa)))))
6971 (if selected-point
6972 (progn
6973 (org-mark-ring-push org-goto-start-pos)
6974 (goto-char selected-point)
6975 (if (or (outline-invisible-p) (org-invisible-p2))
6976 (org-show-context 'org-goto)))
6977 (message "Quit"))))
6979 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6980 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6981 (defvar org-goto-local-auto-isearch-map) ; defined below
6983 (defun org-get-location (buf help)
6984 "Let the user select a location in the Org-mode buffer BUF.
6985 This function uses a recursive edit. It returns the selected position
6986 or nil."
6987 (org-no-popups
6988 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6989 (isearch-hide-immediately nil)
6990 (isearch-search-fun-function
6991 (lambda () 'org-goto-local-search-headings))
6992 (org-goto-selected-point org-goto-exit-command))
6993 (save-excursion
6994 (save-window-excursion
6995 (delete-other-windows)
6996 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6997 (org-pop-to-buffer-same-window
6998 (condition-case nil
6999 (make-indirect-buffer (current-buffer) "*org-goto*")
7000 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7001 (with-output-to-temp-buffer "*Help*"
7002 (princ help))
7003 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7004 (setq buffer-read-only nil)
7005 (let ((org-startup-truncated t)
7006 (org-startup-folded nil)
7007 (org-startup-align-all-tables nil))
7008 (org-mode)
7009 (org-overview))
7010 (setq buffer-read-only t)
7011 (if (and (boundp 'org-goto-start-pos)
7012 (integer-or-marker-p org-goto-start-pos))
7013 (let ((org-show-hierarchy-above t)
7014 (org-show-siblings t)
7015 (org-show-following-heading t))
7016 (goto-char org-goto-start-pos)
7017 (and (outline-invisible-p) (org-show-context)))
7018 (goto-char (point-min)))
7019 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7020 (message "Select location and press RET")
7021 (use-local-map org-goto-map)
7022 (recursive-edit)
7024 (kill-buffer "*org-goto*")
7025 (cons org-goto-selected-point org-goto-exit-command))))
7027 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7028 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7029 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7030 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7032 (defun org-goto-local-search-headings (string bound noerror)
7033 "Search and make sure that any matches are in headlines."
7034 (catch 'return
7035 (while (if isearch-forward
7036 (search-forward string bound noerror)
7037 (search-backward string bound noerror))
7038 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7039 (and (member :headline context)
7040 (not (member :tags context))))
7041 (throw 'return (point))))))
7043 (defun org-goto-local-auto-isearch ()
7044 "Start isearch."
7045 (interactive)
7046 (goto-char (point-min))
7047 (let ((keys (this-command-keys)))
7048 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7049 (isearch-mode t)
7050 (isearch-process-search-char (string-to-char keys)))))
7052 (defun org-goto-ret (&optional arg)
7053 "Finish `org-goto' by going to the new location."
7054 (interactive "P")
7055 (setq org-goto-selected-point (point)
7056 org-goto-exit-command 'return)
7057 (throw 'exit nil))
7059 (defun org-goto-left ()
7060 "Finish `org-goto' by going to the new location."
7061 (interactive)
7062 (if (org-at-heading-p)
7063 (progn
7064 (beginning-of-line 1)
7065 (setq org-goto-selected-point (point)
7066 org-goto-exit-command 'left)
7067 (throw 'exit nil))
7068 (error "Not on a heading")))
7070 (defun org-goto-right ()
7071 "Finish `org-goto' by going to the new location."
7072 (interactive)
7073 (if (org-at-heading-p)
7074 (progn
7075 (setq org-goto-selected-point (point)
7076 org-goto-exit-command 'right)
7077 (throw 'exit nil))
7078 (error "Not on a heading")))
7080 (defun org-goto-quit ()
7081 "Finish `org-goto' without cursor motion."
7082 (interactive)
7083 (setq org-goto-selected-point nil)
7084 (setq org-goto-exit-command 'quit)
7085 (throw 'exit nil))
7087 ;;; Indirect buffer display of subtrees
7089 (defvar org-indirect-dedicated-frame nil
7090 "This is the frame being used for indirect tree display.")
7091 (defvar org-last-indirect-buffer nil)
7093 (defun org-tree-to-indirect-buffer (&optional arg)
7094 "Create indirect buffer and narrow it to current subtree.
7095 With a numerical prefix ARG, go up to this level and then take that tree.
7096 If ARG is negative, go up that many levels.
7098 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7099 indirect buffer previously made with this command, to avoid proliferation of
7100 indirect buffers. However, when you call the command with a \
7101 \\[universal-argument] prefix, or
7102 when `org-indirect-buffer-display' is `new-frame', the last buffer
7103 is kept so that you can work with several indirect buffers at the same time.
7104 If `org-indirect-buffer-display' is `dedicated-frame', the \
7105 \\[universal-argument] prefix also
7106 requests that a new frame be made for the new buffer, so that the dedicated
7107 frame is not changed."
7108 (interactive "P")
7109 (let ((cbuf (current-buffer))
7110 (cwin (selected-window))
7111 (pos (point))
7112 beg end level heading ibuf)
7113 (save-excursion
7114 (org-back-to-heading t)
7115 (when (numberp arg)
7116 (setq level (org-outline-level))
7117 (if (< arg 0) (setq arg (+ level arg)))
7118 (while (> (setq level (org-outline-level)) arg)
7119 (org-up-heading-safe)))
7120 (setq beg (point)
7121 heading (org-get-heading))
7122 (org-end-of-subtree t t)
7123 (if (org-at-heading-p) (backward-char 1))
7124 (setq end (point)))
7125 (if (and (buffer-live-p org-last-indirect-buffer)
7126 (not (eq org-indirect-buffer-display 'new-frame))
7127 (not arg))
7128 (kill-buffer org-last-indirect-buffer))
7129 (setq ibuf (org-get-indirect-buffer cbuf)
7130 org-last-indirect-buffer ibuf)
7131 (cond
7132 ((or (eq org-indirect-buffer-display 'new-frame)
7133 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7134 (select-frame (make-frame))
7135 (delete-other-windows)
7136 (org-pop-to-buffer-same-window ibuf)
7137 (org-set-frame-title heading))
7138 ((eq org-indirect-buffer-display 'dedicated-frame)
7139 (raise-frame
7140 (select-frame (or (and org-indirect-dedicated-frame
7141 (frame-live-p org-indirect-dedicated-frame)
7142 org-indirect-dedicated-frame)
7143 (setq org-indirect-dedicated-frame (make-frame)))))
7144 (delete-other-windows)
7145 (org-pop-to-buffer-same-window ibuf)
7146 (org-set-frame-title (concat "Indirect: " heading)))
7147 ((eq org-indirect-buffer-display 'current-window)
7148 (org-pop-to-buffer-same-window ibuf))
7149 ((eq org-indirect-buffer-display 'other-window)
7150 (pop-to-buffer ibuf))
7151 (t (error "Invalid value")))
7152 (if (featurep 'xemacs)
7153 (save-excursion (org-mode) (turn-on-font-lock)))
7154 (narrow-to-region beg end)
7155 (show-all)
7156 (goto-char pos)
7157 (run-hook-with-args 'org-cycle-hook 'all)
7158 (and (window-live-p cwin) (select-window cwin))))
7160 (defun org-get-indirect-buffer (&optional buffer)
7161 (setq buffer (or buffer (current-buffer)))
7162 (let ((n 1) (base (buffer-name buffer)) bname)
7163 (while (buffer-live-p
7164 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7165 (setq n (1+ n)))
7166 (condition-case nil
7167 (make-indirect-buffer buffer bname 'clone)
7168 (error (make-indirect-buffer buffer bname)))))
7170 (defun org-set-frame-title (title)
7171 "Set the title of the current frame to the string TITLE."
7172 ;; FIXME: how to name a single frame in XEmacs???
7173 (unless (featurep 'xemacs)
7174 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7176 ;;;; Structure editing
7178 ;;; Inserting headlines
7180 (defun org-previous-line-empty-p ()
7181 (save-excursion
7182 (and (not (bobp))
7183 (or (beginning-of-line 0) t)
7184 (save-match-data
7185 (looking-at "[ \t]*$")))))
7187 (defun org-insert-heading (&optional force-heading invisible-ok)
7188 "Insert a new heading or item with same depth at point.
7189 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7190 If point is at the beginning of a headline, insert a sibling before the
7191 current headline. If point is not at the beginning, split the line,
7192 create the new headline with the text in the current line after point
7193 \(but see also the variable `org-M-RET-may-split-line').
7195 With a double prefix arg, force the heading to be inserted at the
7196 end of the parent subtree.
7198 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7199 This is important for non-interactive uses of the command."
7200 (interactive "P")
7201 (if (or (= (buffer-size) 0)
7202 (and (not (save-excursion
7203 (and (ignore-errors (org-back-to-heading invisible-ok))
7204 (org-at-heading-p))))
7205 (or force-heading (not (org-in-item-p)))))
7206 (progn
7207 (insert "\n* ")
7208 (run-hooks 'org-insert-heading-hook))
7209 (when (or force-heading (not (org-insert-item)))
7210 (let* ((empty-line-p nil)
7211 (level nil)
7212 (on-heading (org-at-heading-p))
7213 (head (save-excursion
7214 (condition-case nil
7215 (progn
7216 (org-back-to-heading invisible-ok)
7217 (when (and (not on-heading)
7218 (featurep 'org-inlinetask)
7219 (integerp org-inlinetask-min-level)
7220 (>= (length (match-string 0))
7221 org-inlinetask-min-level))
7222 ;; Find a heading level before the inline task
7223 (while (and (setq level (org-up-heading-safe))
7224 (>= level org-inlinetask-min-level)))
7225 (if (org-at-heading-p)
7226 (org-back-to-heading invisible-ok)
7227 (error "This should not happen")))
7228 (setq empty-line-p (org-previous-line-empty-p))
7229 (match-string 0))
7230 (error "*"))))
7231 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7232 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7233 pos hide-previous previous-pos)
7234 (cond
7235 ((and (org-at-heading-p) (bolp)
7236 (or (bobp)
7237 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7238 ;; insert before the current line
7239 (open-line (if blank 2 1)))
7240 ((and (bolp)
7241 (not org-insert-heading-respect-content)
7242 (or (bobp)
7243 (save-excursion
7244 (backward-char 1) (not (outline-invisible-p)))))
7245 ;; insert right here
7246 nil)
7248 ;; somewhere in the line
7249 (save-excursion
7250 (setq previous-pos (point-at-bol))
7251 (end-of-line)
7252 (setq hide-previous (outline-invisible-p)))
7253 (and org-insert-heading-respect-content (org-show-subtree))
7254 (let ((split
7255 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7256 (save-excursion
7257 (let ((p (point)))
7258 (goto-char (point-at-bol))
7259 (and (looking-at org-complex-heading-regexp)
7260 (match-beginning 4)
7261 (> p (match-beginning 4)))))))
7262 tags pos)
7263 (cond
7264 (org-insert-heading-respect-content
7265 (if (not (equal force-heading '(16)))
7266 (org-end-of-subtree nil t)
7267 (org-up-heading-safe)
7268 (org-end-of-subtree nil t))
7269 (when (featurep 'org-inlinetask)
7270 (while (and (not (eobp))
7271 (looking-at "\\(\\*+\\)[ \t]+")
7272 (>= (length (match-string 1))
7273 org-inlinetask-min-level))
7274 (org-end-of-subtree nil t)))
7275 (or (bolp) (newline))
7276 (or (org-previous-line-empty-p)
7277 (and blank (newline)))
7278 (open-line 1))
7279 ((org-at-heading-p)
7280 (when hide-previous
7281 (show-children)
7282 (org-show-entry))
7283 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7284 (setq tags (and (match-end 2) (match-string 2)))
7285 (and (match-end 1)
7286 (delete-region (match-beginning 1) (match-end 1)))
7287 (setq pos (point-at-bol))
7288 (or split (end-of-line 1))
7289 (delete-horizontal-space)
7290 (if (string-match "\\`\\*+\\'"
7291 (buffer-substring (point-at-bol) (point)))
7292 (insert " "))
7293 (newline (if blank 2 1))
7294 (when tags
7295 (save-excursion
7296 (goto-char pos)
7297 (end-of-line 1)
7298 (insert " " tags)
7299 (org-set-tags nil 'align))))
7301 (or split (end-of-line 1))
7302 (newline (if blank 2 1)))))))
7303 (insert head) (just-one-space)
7304 (setq pos (point))
7305 (end-of-line 1)
7306 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7307 (when (and org-insert-heading-respect-content hide-previous)
7308 (save-excursion
7309 (goto-char previous-pos)
7310 (hide-subtree)))
7311 (run-hooks 'org-insert-heading-hook)))))
7313 (defun org-get-heading (&optional no-tags no-todo)
7314 "Return the heading of the current entry, without the stars.
7315 When NO-TAGS is non-nil, don't include tags.
7316 When NO-TODO is non-nil, don't include TODO keywords."
7317 (save-excursion
7318 (org-back-to-heading t)
7319 (cond
7320 ((and no-tags no-todo)
7321 (looking-at org-complex-heading-regexp)
7322 (match-string 4))
7323 (no-tags
7324 (looking-at (concat org-outline-regexp
7325 "\\(.*?\\)"
7326 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7327 (match-string 1))
7328 (no-todo
7329 (looking-at org-todo-line-regexp)
7330 (match-string 3))
7331 (t (looking-at org-heading-regexp)
7332 (match-string 2)))))
7334 (defun org-heading-components ()
7335 "Return the components of the current heading.
7336 This is a list with the following elements:
7337 - the level as an integer
7338 - the reduced level, different if `org-odd-levels-only' is set.
7339 - the TODO keyword, or nil
7340 - the priority character, like ?A, or nil if no priority is given
7341 - the headline text itself, or the tags string if no headline text
7342 - the tags string, or nil."
7343 (save-excursion
7344 (org-back-to-heading t)
7345 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7346 (list (length (match-string 1))
7347 (org-reduced-level (length (match-string 1)))
7348 (org-match-string-no-properties 2)
7349 (and (match-end 3) (aref (match-string 3) 2))
7350 (org-match-string-no-properties 4)
7351 (org-match-string-no-properties 5)))))
7353 (defun org-get-entry ()
7354 "Get the entry text, after heading, entire subtree."
7355 (save-excursion
7356 (org-back-to-heading t)
7357 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7359 (defun org-insert-heading-after-current ()
7360 "Insert a new heading with same level as current, after current subtree."
7361 (interactive)
7362 (org-back-to-heading)
7363 (org-insert-heading)
7364 (org-move-subtree-down)
7365 (end-of-line 1))
7367 (defun org-insert-heading-respect-content ()
7368 (interactive)
7369 (let ((org-insert-heading-respect-content t))
7370 (org-insert-heading t)))
7372 (defun org-insert-todo-heading-respect-content (&optional force-state)
7373 (interactive "P")
7374 (let ((org-insert-heading-respect-content t))
7375 (org-insert-todo-heading force-state t)))
7377 (defun org-insert-todo-heading (arg &optional force-heading)
7378 "Insert a new heading with the same level and TODO state as current heading.
7379 If the heading has no TODO state, or if the state is DONE, use the first
7380 state (TODO by default). Also one prefix arg, force first state. With two
7381 prefix args, force inserting at the end of the parent subtree."
7382 (interactive "P")
7383 (when (or force-heading (not (org-insert-item 'checkbox)))
7384 (org-insert-heading (or (and (equal arg '(16)) '(16))
7385 force-heading))
7386 (save-excursion
7387 (org-back-to-heading)
7388 (outline-previous-heading)
7389 (looking-at org-todo-line-regexp))
7390 (let*
7391 ((new-mark-x
7392 (if (or arg
7393 (not (match-beginning 2))
7394 (member (match-string 2) org-done-keywords))
7395 (car org-todo-keywords-1)
7396 (match-string 2)))
7397 (new-mark
7399 (run-hook-with-args-until-success
7400 'org-todo-get-default-hook new-mark-x nil)
7401 new-mark-x)))
7402 (beginning-of-line 1)
7403 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7404 (if org-treat-insert-todo-heading-as-state-change
7405 (org-todo new-mark)
7406 (insert new-mark " "))))
7407 (when org-provide-todo-statistics
7408 (org-update-parent-todo-statistics))))
7410 (defun org-insert-subheading (arg)
7411 "Insert a new subheading and demote it.
7412 Works for outline headings and for plain lists alike."
7413 (interactive "P")
7414 (org-insert-heading arg)
7415 (cond
7416 ((org-at-heading-p) (org-do-demote))
7417 ((org-at-item-p) (org-indent-item))))
7419 (defun org-insert-todo-subheading (arg)
7420 "Insert a new subheading with TODO keyword or checkbox and demote it.
7421 Works for outline headings and for plain lists alike."
7422 (interactive "P")
7423 (org-insert-todo-heading arg)
7424 (cond
7425 ((org-at-heading-p) (org-do-demote))
7426 ((org-at-item-p) (org-indent-item))))
7428 ;;; Promotion and Demotion
7430 (defvar org-after-demote-entry-hook nil
7431 "Hook run after an entry has been demoted.
7432 The cursor will be at the beginning of the entry.
7433 When a subtree is being demoted, the hook will be called for each node.")
7435 (defvar org-after-promote-entry-hook nil
7436 "Hook run after an entry has been promoted.
7437 The cursor will be at the beginning of the entry.
7438 When a subtree is being promoted, the hook will be called for each node.")
7440 (defun org-promote-subtree ()
7441 "Promote the entire subtree.
7442 See also `org-promote'."
7443 (interactive)
7444 (save-excursion
7445 (org-with-limited-levels (org-map-tree 'org-promote)))
7446 (org-fix-position-after-promote))
7448 (defun org-demote-subtree ()
7449 "Demote the entire subtree. See `org-demote'.
7450 See also `org-promote'."
7451 (interactive)
7452 (save-excursion
7453 (org-with-limited-levels (org-map-tree 'org-demote)))
7454 (org-fix-position-after-promote))
7457 (defun org-do-promote ()
7458 "Promote the current heading higher up the tree.
7459 If the region is active in `transient-mark-mode', promote all headings
7460 in the region."
7461 (interactive)
7462 (save-excursion
7463 (if (org-region-active-p)
7464 (org-map-region 'org-promote (region-beginning) (region-end))
7465 (org-promote)))
7466 (org-fix-position-after-promote))
7468 (defun org-do-demote ()
7469 "Demote the current heading lower down the tree.
7470 If the region is active in `transient-mark-mode', demote all headings
7471 in the region."
7472 (interactive)
7473 (save-excursion
7474 (if (org-region-active-p)
7475 (org-map-region 'org-demote (region-beginning) (region-end))
7476 (org-demote)))
7477 (org-fix-position-after-promote))
7479 (defun org-fix-position-after-promote ()
7480 "Make sure that after pro/demotion cursor position is right."
7481 (let ((pos (point)))
7482 (when (save-excursion
7483 (beginning-of-line 1)
7484 (looking-at org-todo-line-regexp)
7485 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7486 (cond ((eobp) (insert " "))
7487 ((eolp) (insert " "))
7488 ((equal (char-after) ?\ ) (forward-char 1))))))
7490 (defun org-current-level ()
7491 "Return the level of the current entry, or nil if before the first headline.
7492 The level is the number of stars at the beginning of the headline."
7493 (save-excursion
7494 (org-with-limited-levels
7495 (if (ignore-errors (org-back-to-heading t))
7496 (funcall outline-level)))))
7498 (defun org-get-previous-line-level ()
7499 "Return the outline depth of the last headline before the current line.
7500 Returns 0 for the first headline in the buffer, and nil if before the
7501 first headline."
7502 (let ((current-level (org-current-level))
7503 (prev-level (when (> (line-number-at-pos) 1)
7504 (save-excursion
7505 (beginning-of-line 0)
7506 (org-current-level)))))
7507 (cond ((null current-level) nil) ; Before first headline
7508 ((null prev-level) 0) ; At first headline
7509 (prev-level))))
7511 (defun org-reduced-level (l)
7512 "Compute the effective level of a heading.
7513 This takes into account the setting of `org-odd-levels-only'."
7514 (cond
7515 ((zerop l) 0)
7516 (org-odd-levels-only (1+ (floor (/ l 2))))
7517 (t l)))
7519 (defun org-level-increment ()
7520 "Return the number of stars that will be added or removed at a
7521 time to headlines when structure editing, based on the value of
7522 `org-odd-levels-only'."
7523 (if org-odd-levels-only 2 1))
7525 (defun org-get-valid-level (level &optional change)
7526 "Rectify a level change under the influence of `org-odd-levels-only'
7527 LEVEL is a current level, CHANGE is by how much the level should be
7528 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7529 even level numbers will become the next higher odd number."
7530 (if org-odd-levels-only
7531 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7532 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7533 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7534 (max 1 (+ level (or change 0)))))
7536 (if (boundp 'define-obsolete-function-alias)
7537 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7538 (define-obsolete-function-alias 'org-get-legal-level
7539 'org-get-valid-level)
7540 (define-obsolete-function-alias 'org-get-legal-level
7541 'org-get-valid-level "23.1")))
7543 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7544 ;; ̀org-with-limited-levels'
7545 (defun org-promote ()
7546 "Promote the current heading higher up the tree.
7547 If the region is active in `transient-mark-mode', promote all headings
7548 in the region."
7549 (org-back-to-heading t)
7550 (let* ((level (save-match-data (funcall outline-level)))
7551 (after-change-functions (remove 'flyspell-after-change-function
7552 after-change-functions))
7553 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7554 (diff (abs (- level (length up-head) -1))))
7555 (cond ((and (= level 1) org-called-with-limited-levels
7556 org-allow-promoting-top-level-subtree)
7557 (replace-match "# " nil t))
7558 ((= level 1)
7559 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7560 (t (replace-match up-head nil t)))
7561 ;; Fixup tag positioning
7562 (unless (= level 1)
7563 (and org-auto-align-tags (org-set-tags nil t))
7564 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7565 (run-hooks 'org-after-promote-entry-hook)))
7567 (defun org-demote ()
7568 "Demote the current heading lower down the tree.
7569 If the region is active in `transient-mark-mode', demote all headings
7570 in the region."
7571 (org-back-to-heading t)
7572 (let* ((level (save-match-data (funcall outline-level)))
7573 (after-change-functions (remove 'flyspell-after-change-function
7574 after-change-functions))
7575 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7576 (diff (abs (- level (length down-head) -1))))
7577 (replace-match down-head nil t)
7578 ;; Fixup tag positioning
7579 (and org-auto-align-tags (org-set-tags nil t))
7580 (if org-adapt-indentation (org-fixup-indentation diff))
7581 (run-hooks 'org-after-demote-entry-hook)))
7583 (defun org-cycle-level ()
7584 "Cycle the level of an empty headline through possible states.
7585 This goes first to child, then to parent, level, then up the hierarchy.
7586 After top level, it switches back to sibling level."
7587 (interactive)
7588 (let ((org-adapt-indentation nil))
7589 (when (org-point-at-end-of-empty-headline)
7590 (setq this-command 'org-cycle-level) ; Only needed for caching
7591 (let ((cur-level (org-current-level))
7592 (prev-level (org-get-previous-line-level)))
7593 (cond
7594 ;; If first headline in file, promote to top-level.
7595 ((= prev-level 0)
7596 (loop repeat (/ (- cur-level 1) (org-level-increment))
7597 do (org-do-promote)))
7598 ;; If same level as prev, demote one.
7599 ((= prev-level cur-level)
7600 (org-do-demote))
7601 ;; If parent is top-level, promote to top level if not already.
7602 ((= prev-level 1)
7603 (loop repeat (/ (- cur-level 1) (org-level-increment))
7604 do (org-do-promote)))
7605 ;; If top-level, return to prev-level.
7606 ((= cur-level 1)
7607 (loop repeat (/ (- prev-level 1) (org-level-increment))
7608 do (org-do-demote)))
7609 ;; If less than prev-level, promote one.
7610 ((< cur-level prev-level)
7611 (org-do-promote))
7612 ;; If deeper than prev-level, promote until higher than
7613 ;; prev-level.
7614 ((> cur-level prev-level)
7615 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7616 do (org-do-promote))))
7617 t))))
7619 (defun org-map-tree (fun)
7620 "Call FUN for every heading underneath the current one."
7621 (org-back-to-heading)
7622 (let ((level (funcall outline-level)))
7623 (save-excursion
7624 (funcall fun)
7625 (while (and (progn
7626 (outline-next-heading)
7627 (> (funcall outline-level) level))
7628 (not (eobp)))
7629 (funcall fun)))))
7631 (defun org-map-region (fun beg end)
7632 "Call FUN for every heading between BEG and END."
7633 (let ((org-ignore-region t))
7634 (save-excursion
7635 (setq end (copy-marker end))
7636 (goto-char beg)
7637 (if (and (re-search-forward org-outline-regexp-bol nil t)
7638 (< (point) end))
7639 (funcall fun))
7640 (while (and (progn
7641 (outline-next-heading)
7642 (< (point) end))
7643 (not (eobp)))
7644 (funcall fun)))))
7646 (defvar org-property-end-re) ; silence byte-compiler
7647 (defun org-fixup-indentation (diff)
7648 "Change the indentation in the current entry by DIFF.
7649 However, if any line in the current entry has no indentation, or if it
7650 would end up with no indentation after the change, nothing at all is done."
7651 (save-excursion
7652 (let ((end (save-excursion (outline-next-heading)
7653 (point-marker)))
7654 (prohibit (if (> diff 0)
7655 "^\\S-"
7656 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7657 col)
7658 (unless (save-excursion (end-of-line 1)
7659 (re-search-forward prohibit end t))
7660 (while (and (< (point) end)
7661 (re-search-forward "^[ \t]+" end t))
7662 (goto-char (match-end 0))
7663 (setq col (current-column))
7664 (if (< diff 0) (replace-match ""))
7665 (org-indent-to-column (+ diff col))))
7666 (move-marker end nil))))
7668 (defun org-convert-to-odd-levels ()
7669 "Convert an org-mode file with all levels allowed to one with odd levels.
7670 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7671 level 5 etc."
7672 (interactive)
7673 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7674 (let ((outline-level 'org-outline-level)
7675 (org-odd-levels-only nil) n)
7676 (save-excursion
7677 (goto-char (point-min))
7678 (while (re-search-forward "^\\*\\*+ " nil t)
7679 (setq n (- (length (match-string 0)) 2))
7680 (while (>= (setq n (1- n)) 0)
7681 (org-demote))
7682 (end-of-line 1))))))
7684 (defun org-convert-to-oddeven-levels ()
7685 "Convert an org-mode file with only odd levels to one with odd/even levels.
7686 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7687 file contains a section with an even level, conversion would
7688 destroy the structure of the file. An error is signaled in this
7689 case."
7690 (interactive)
7691 (goto-char (point-min))
7692 ;; First check if there are no even levels
7693 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7694 (org-show-context t)
7695 (error "Not all levels are odd in this file. Conversion not possible"))
7696 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7697 (let ((outline-regexp org-outline-regexp)
7698 (outline-level 'org-outline-level)
7699 (org-odd-levels-only nil) n)
7700 (save-excursion
7701 (goto-char (point-min))
7702 (while (re-search-forward "^\\*\\*+ " nil t)
7703 (setq n (/ (1- (length (match-string 0))) 2))
7704 (while (>= (setq n (1- n)) 0)
7705 (org-promote))
7706 (end-of-line 1))))))
7708 (defun org-tr-level (n)
7709 "Make N odd if required."
7710 (if org-odd-levels-only (1+ (/ n 2)) n))
7712 ;;; Vertical tree motion, cutting and pasting of subtrees
7714 (defun org-move-subtree-up (&optional arg)
7715 "Move the current subtree up past ARG headlines of the same level."
7716 (interactive "p")
7717 (org-move-subtree-down (- (prefix-numeric-value arg))))
7719 (defun org-move-subtree-down (&optional arg)
7720 "Move the current subtree down past ARG headlines of the same level."
7721 (interactive "p")
7722 (setq arg (prefix-numeric-value arg))
7723 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7724 'org-get-last-sibling))
7725 (ins-point (make-marker))
7726 (cnt (abs arg))
7727 (col (current-column))
7728 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7729 ;; Select the tree
7730 (org-back-to-heading)
7731 (setq beg0 (point))
7732 (save-excursion
7733 (setq ne-beg (org-back-over-empty-lines))
7734 (setq beg (point)))
7735 (save-match-data
7736 (save-excursion (outline-end-of-heading)
7737 (setq folded (outline-invisible-p)))
7738 (outline-end-of-subtree))
7739 (outline-next-heading)
7740 (setq ne-end (org-back-over-empty-lines))
7741 (setq end (point))
7742 (goto-char beg0)
7743 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7744 ;; include less whitespace
7745 (save-excursion
7746 (goto-char beg)
7747 (forward-line (- ne-beg ne-end))
7748 (setq beg (point))))
7749 ;; Find insertion point, with error handling
7750 (while (> cnt 0)
7751 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7752 (progn (goto-char beg0)
7753 (error "Cannot move past superior level or buffer limit")))
7754 (setq cnt (1- cnt)))
7755 (if (> arg 0)
7756 ;; Moving forward - still need to move over subtree
7757 (progn (org-end-of-subtree t t)
7758 (save-excursion
7759 (org-back-over-empty-lines)
7760 (or (bolp) (newline)))))
7761 (setq ne-ins (org-back-over-empty-lines))
7762 (move-marker ins-point (point))
7763 (setq txt (buffer-substring beg end))
7764 (org-save-markers-in-region beg end)
7765 (delete-region beg end)
7766 (org-remove-empty-overlays-at beg)
7767 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7768 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7769 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7770 (let ((bbb (point)))
7771 (insert-before-markers txt)
7772 (org-reinstall-markers-in-region bbb)
7773 (move-marker ins-point bbb))
7774 (or (bolp) (insert "\n"))
7775 (setq ins-end (point))
7776 (goto-char ins-point)
7777 (org-skip-whitespace)
7778 (when (and (< arg 0)
7779 (org-first-sibling-p)
7780 (> ne-ins ne-beg))
7781 ;; Move whitespace back to beginning
7782 (save-excursion
7783 (goto-char ins-end)
7784 (let ((kill-whole-line t))
7785 (kill-line (- ne-ins ne-beg)) (point)))
7786 (insert (make-string (- ne-ins ne-beg) ?\n)))
7787 (move-marker ins-point nil)
7788 (if folded
7789 (hide-subtree)
7790 (org-show-entry)
7791 (show-children)
7792 (org-cycle-hide-drawers 'children))
7793 (org-clean-visibility-after-subtree-move)
7794 ;; move back to the initial column we were at
7795 (move-to-column col)))
7797 (defvar org-subtree-clip ""
7798 "Clipboard for cut and paste of subtrees.
7799 This is actually only a copy of the kill, because we use the normal kill
7800 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7802 (defvar org-subtree-clip-folded nil
7803 "Was the last copied subtree folded?
7804 This is used to fold the tree back after pasting.")
7806 (defun org-cut-subtree (&optional n)
7807 "Cut the current subtree into the clipboard.
7808 With prefix arg N, cut this many sequential subtrees.
7809 This is a short-hand for marking the subtree and then cutting it."
7810 (interactive "p")
7811 (org-copy-subtree n 'cut))
7813 (defun org-copy-subtree (&optional n cut force-store-markers)
7814 "Cut the current subtree into the clipboard.
7815 With prefix arg N, cut this many sequential subtrees.
7816 This is a short-hand for marking the subtree and then copying it.
7817 If CUT is non-nil, actually cut the subtree.
7818 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7819 of some markers in the region, even if CUT is non-nil. This is
7820 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7821 (interactive "p")
7822 (let (beg end folded (beg0 (point)))
7823 (if (org-called-interactively-p 'any)
7824 (org-back-to-heading nil) ; take what looks like a subtree
7825 (org-back-to-heading t)) ; take what is really there
7826 (org-back-over-empty-lines)
7827 (setq beg (point))
7828 (skip-chars-forward " \t\r\n")
7829 (save-match-data
7830 (save-excursion (outline-end-of-heading)
7831 (setq folded (outline-invisible-p)))
7832 (condition-case nil
7833 (org-forward-heading-same-level (1- n) t)
7834 (error nil))
7835 (org-end-of-subtree t t))
7836 (org-back-over-empty-lines)
7837 (setq end (point))
7838 (goto-char beg0)
7839 (when (> end beg)
7840 (setq org-subtree-clip-folded folded)
7841 (when (or cut force-store-markers)
7842 (org-save-markers-in-region beg end))
7843 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7844 (setq org-subtree-clip (current-kill 0))
7845 (message "%s: Subtree(s) with %d characters"
7846 (if cut "Cut" "Copied")
7847 (length org-subtree-clip)))))
7849 (defun org-paste-subtree (&optional level tree for-yank)
7850 "Paste the clipboard as a subtree, with modification of headline level.
7851 The entire subtree is promoted or demoted in order to match a new headline
7852 level.
7854 If the cursor is at the beginning of a headline, the same level as
7855 that headline is used to paste the tree
7857 If not, the new level is derived from the *visible* headings
7858 before and after the insertion point, and taken to be the inferior headline
7859 level of the two. So if the previous visible heading is level 3 and the
7860 next is level 4 (or vice versa), level 4 will be used for insertion.
7861 This makes sure that the subtree remains an independent subtree and does
7862 not swallow low level entries.
7864 You can also force a different level, either by using a numeric prefix
7865 argument, or by inserting the heading marker by hand. For example, if the
7866 cursor is after \"*****\", then the tree will be shifted to level 5.
7868 If optional TREE is given, use this text instead of the kill ring.
7870 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7871 move back over whitespace before inserting, and move point to the end of
7872 the inserted text when done."
7873 (interactive "P")
7874 (setq tree (or tree (and kill-ring (current-kill 0))))
7875 (unless (org-kill-is-subtree-p tree)
7876 (error "%s"
7877 (substitute-command-keys
7878 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7879 (org-with-limited-levels
7880 (let* ((visp (not (outline-invisible-p)))
7881 (txt tree)
7882 (^re_ "\\(\\*+\\)[ \t]*")
7883 (old-level (if (string-match org-outline-regexp-bol txt)
7884 (- (match-end 0) (match-beginning 0) 1)
7885 -1))
7886 (force-level (cond (level (prefix-numeric-value level))
7887 ((and (looking-at "[ \t]*$")
7888 (string-match
7889 "^\\*+$" (buffer-substring
7890 (point-at-bol) (point))))
7891 (- (match-end 1) (match-beginning 1)))
7892 ((and (bolp)
7893 (looking-at org-outline-regexp))
7894 (- (match-end 0) (point) 1))))
7895 (previous-level (save-excursion
7896 (condition-case nil
7897 (progn
7898 (outline-previous-visible-heading 1)
7899 (if (looking-at ^re_)
7900 (- (match-end 0) (match-beginning 0) 1)
7902 (error 1))))
7903 (next-level (save-excursion
7904 (condition-case nil
7905 (progn
7906 (or (looking-at org-outline-regexp)
7907 (outline-next-visible-heading 1))
7908 (if (looking-at ^re_)
7909 (- (match-end 0) (match-beginning 0) 1)
7911 (error 1))))
7912 (new-level (or force-level (max previous-level next-level)))
7913 (shift (if (or (= old-level -1)
7914 (= new-level -1)
7915 (= old-level new-level))
7917 (- new-level old-level)))
7918 (delta (if (> shift 0) -1 1))
7919 (func (if (> shift 0) 'org-demote 'org-promote))
7920 (org-odd-levels-only nil)
7921 beg end newend)
7922 ;; Remove the forced level indicator
7923 (if force-level
7924 (delete-region (point-at-bol) (point)))
7925 ;; Paste
7926 (beginning-of-line (if (bolp) 1 2))
7927 (unless for-yank (org-back-over-empty-lines))
7928 (setq beg (point))
7929 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7930 (insert-before-markers txt)
7931 (unless (string-match "\n\\'" txt) (insert "\n"))
7932 (setq newend (point))
7933 (org-reinstall-markers-in-region beg)
7934 (setq end (point))
7935 (goto-char beg)
7936 (skip-chars-forward " \t\n\r")
7937 (setq beg (point))
7938 (if (and (outline-invisible-p) visp)
7939 (save-excursion (outline-show-heading)))
7940 ;; Shift if necessary
7941 (unless (= shift 0)
7942 (save-restriction
7943 (narrow-to-region beg end)
7944 (while (not (= shift 0))
7945 (org-map-region func (point-min) (point-max))
7946 (setq shift (+ delta shift)))
7947 (goto-char (point-min))
7948 (setq newend (point-max))))
7949 (when (or (org-called-interactively-p 'interactive) for-yank)
7950 (message "Clipboard pasted as level %d subtree" new-level))
7951 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7952 kill-ring
7953 (eq org-subtree-clip (current-kill 0))
7954 org-subtree-clip-folded)
7955 ;; The tree was folded before it was killed/copied
7956 (hide-subtree))
7957 (and for-yank (goto-char newend)))))
7959 (defun org-kill-is-subtree-p (&optional txt)
7960 "Check if the current kill is an outline subtree, or a set of trees.
7961 Returns nil if kill does not start with a headline, or if the first
7962 headline level is not the largest headline level in the tree.
7963 So this will actually accept several entries of equal levels as well,
7964 which is OK for `org-paste-subtree'.
7965 If optional TXT is given, check this string instead of the current kill."
7966 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7967 (re (org-get-limited-outline-regexp))
7968 (^re (concat "^" re))
7969 (start-level (and kill
7970 (string-match
7971 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7972 kill)
7973 (- (match-end 2) (match-beginning 2) 1)))
7974 (start (1+ (or (match-beginning 2) -1))))
7975 (if (not start-level)
7976 (progn
7977 nil) ;; does not even start with a heading
7978 (catch 'exit
7979 (while (setq start (string-match ^re kill (1+ start)))
7980 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7981 (throw 'exit nil)))
7982 t))))
7984 (defvar org-markers-to-move nil
7985 "Markers that should be moved with a cut-and-paste operation.
7986 Those markers are stored together with their positions relative to
7987 the start of the region.")
7989 (defun org-save-markers-in-region (beg end)
7990 "Check markers in region.
7991 If these markers are between BEG and END, record their position relative
7992 to BEG, so that after moving the block of text, we can put the markers back
7993 into place.
7994 This function gets called just before an entry or tree gets cut from the
7995 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7996 called immediately, to move the markers with the entries."
7997 (setq org-markers-to-move nil)
7998 (when (featurep 'org-clock)
7999 (org-clock-save-markers-for-cut-and-paste beg end))
8000 (when (featurep 'org-agenda)
8001 (org-agenda-save-markers-for-cut-and-paste beg end)))
8003 (defun org-check-and-save-marker (marker beg end)
8004 "Check if MARKER is between BEG and END.
8005 If yes, remember the marker and the distance to BEG."
8006 (when (and (marker-buffer marker)
8007 (equal (marker-buffer marker) (current-buffer)))
8008 (if (and (>= marker beg) (< marker end))
8009 (push (cons marker (- marker beg)) org-markers-to-move))))
8011 (defun org-reinstall-markers-in-region (beg)
8012 "Move all remembered markers to their position relative to BEG."
8013 (mapc (lambda (x)
8014 (move-marker (car x) (+ beg (cdr x))))
8015 org-markers-to-move)
8016 (setq org-markers-to-move nil))
8018 (defun org-narrow-to-subtree ()
8019 "Narrow buffer to the current subtree."
8020 (interactive)
8021 (save-excursion
8022 (save-match-data
8023 (org-with-limited-levels
8024 (narrow-to-region
8025 (progn (org-back-to-heading t) (point))
8026 (progn (org-end-of-subtree t t)
8027 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8028 (point)))))))
8030 (defun org-narrow-to-block ()
8031 "Narrow buffer to the current block."
8032 (interactive)
8033 (let* ((case-fold-search t)
8034 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8035 "^[ \t]*#\\+end_.*")))
8036 (if blockp
8037 (narrow-to-region (car blockp) (cdr blockp))
8038 (error "Not in a block"))))
8040 (eval-when-compile
8041 (defvar org-property-drawer-re))
8043 (defvar org-property-start-re) ;; defined below
8044 (defun org-clone-subtree-with-time-shift (n &optional shift)
8045 "Clone the task (subtree) at point N times.
8046 The clones will be inserted as siblings.
8048 In interactive use, the user will be prompted for the number of
8049 clones to be produced, and for a time SHIFT, which may be a
8050 repeater as used in time stamps, for example `+3d'.
8052 When a valid repeater is given and the entry contains any time
8053 stamps, the clones will become a sequence in time, with time
8054 stamps in the subtree shifted for each clone produced. If SHIFT
8055 is nil or the empty string, time stamps will be left alone. The
8056 ID property of the original subtree is removed.
8058 If the original subtree did contain time stamps with a repeater,
8059 the following will happen:
8060 - the repeater will be removed in each clone
8061 - an additional clone will be produced, with the current, unshifted
8062 date(s) in the entry.
8063 - the original entry will be placed *after* all the clones, with
8064 repeater intact.
8065 - the start days in the repeater in the original entry will be shifted
8066 to past the last clone.
8067 In this way you can spell out a number of instances of a repeating task,
8068 and still retain the repeater to cover future instances of the task."
8069 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8070 (let (beg end template task idprop
8071 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8072 (drawer-re org-drawer-regexp))
8073 (if (not (and (integerp n) (> n 0)))
8074 (error "Invalid number of replications %s" n))
8075 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8076 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8077 shift)))
8078 (error "Invalid shift specification %s" shift))
8079 (when doshift
8080 (setq shift-n (string-to-number (match-string 1 shift))
8081 shift-what (cdr (assoc (match-string 2 shift)
8082 '(("d" . day) ("w" . week)
8083 ("m" . month) ("y" . year))))))
8084 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8085 (setq nmin 1 nmax n)
8086 (org-back-to-heading t)
8087 (setq beg (point))
8088 (setq idprop (org-entry-get nil "ID"))
8089 (org-end-of-subtree t t)
8090 (or (bolp) (insert "\n"))
8091 (setq end (point))
8092 (setq template (buffer-substring beg end))
8093 (when (and doshift
8094 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8095 (delete-region beg end)
8096 (setq end beg)
8097 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8098 (goto-char end)
8099 (loop for n from nmin to nmax do
8100 ;; prepare clone
8101 (with-temp-buffer
8102 (insert template)
8103 (org-mode)
8104 (goto-char (point-min))
8105 (org-show-subtree)
8106 (and idprop (if org-clone-delete-id
8107 (org-entry-delete nil "ID")
8108 (org-id-get-create t)))
8109 (unless (= n 0)
8110 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8111 (kill-whole-line))
8112 (goto-char (point-min))
8113 (while (re-search-forward drawer-re nil t)
8114 (mapc (lambda (d)
8115 (org-remove-empty-drawer-at d (point))) org-drawers)))
8116 (goto-char (point-min))
8117 (when doshift
8118 (while (re-search-forward org-ts-regexp-both nil t)
8119 (org-timestamp-change (* n shift-n) shift-what))
8120 (unless (= n n-no-remove)
8121 (goto-char (point-min))
8122 (while (re-search-forward org-ts-regexp nil t)
8123 (save-excursion
8124 (goto-char (match-beginning 0))
8125 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8126 (delete-region (match-beginning 1) (match-end 1)))))))
8127 (setq task (buffer-string)))
8128 (insert task))
8129 (goto-char beg)))
8131 ;;; Outline Sorting
8133 (defun org-sort (with-case)
8134 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8135 Optional argument WITH-CASE means sort case-sensitively."
8136 (interactive "P")
8137 (cond
8138 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8139 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8141 (org-call-with-arg 'org-sort-entries with-case))))
8143 (defun org-sort-remove-invisible (s)
8144 (remove-text-properties 0 (length s) org-rm-props s)
8145 (while (string-match org-bracket-link-regexp s)
8146 (setq s (replace-match (if (match-end 2)
8147 (match-string 3 s)
8148 (match-string 1 s)) t t s)))
8151 (defvar org-priority-regexp) ; defined later in the file
8153 (defvar org-after-sorting-entries-or-items-hook nil
8154 "Hook that is run after a bunch of entries or items have been sorted.
8155 When children are sorted, the cursor is in the parent line when this
8156 hook gets called. When a region or a plain list is sorted, the cursor
8157 will be in the first entry of the sorted region/list.")
8159 (defun org-sort-entries
8160 (&optional with-case sorting-type getkey-func compare-func property)
8161 "Sort entries on a certain level of an outline tree.
8162 If there is an active region, the entries in the region are sorted.
8163 Else, if the cursor is before the first entry, sort the top-level items.
8164 Else, the children of the entry at point are sorted.
8166 Sorting can be alphabetically, numerically, by date/time as given by
8167 a time stamp, by a property or by priority.
8169 The command prompts for the sorting type unless it has been given to the
8170 function through the SORTING-TYPE argument, which needs to be a character,
8171 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8172 precise meaning of each character:
8174 n Numerically, by converting the beginning of the entry/item to a number.
8175 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8176 o By order of TODO keywords.
8177 t By date/time, either the first active time stamp in the entry, or, if
8178 none exist, by the first inactive one.
8179 s By the scheduled date/time.
8180 d By deadline date/time.
8181 c By creation time, which is assumed to be the first inactive time stamp
8182 at the beginning of a line.
8183 p By priority according to the cookie.
8184 r By the value of a property.
8186 Capital letters will reverse the sort order.
8188 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8189 called with point at the beginning of the record. It must return either
8190 a string or a number that should serve as the sorting key for that record.
8192 Comparing entries ignores case by default. However, with an optional argument
8193 WITH-CASE, the sorting considers case as well."
8194 (interactive "P")
8195 (let ((case-func (if with-case 'identity 'downcase))
8196 (cmstr
8197 ;; The clock marker is lost when using `sort-subr', let's
8198 ;; store the clocking string.
8199 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8200 (save-excursion
8201 (goto-char org-clock-marker)
8202 (looking-back "^.*") (match-string-no-properties 0))))
8203 start beg end stars re re2
8204 txt what tmp)
8205 ;; Find beginning and end of region to sort
8206 (cond
8207 ((org-region-active-p)
8208 ;; we will sort the region
8209 (setq end (region-end)
8210 what "region")
8211 (goto-char (region-beginning))
8212 (if (not (org-at-heading-p)) (outline-next-heading))
8213 (setq start (point)))
8214 ((or (org-at-heading-p)
8215 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8216 ;; we will sort the children of the current headline
8217 (org-back-to-heading)
8218 (setq start (point)
8219 end (progn (org-end-of-subtree t t)
8220 (or (bolp) (insert "\n"))
8221 (org-back-over-empty-lines)
8222 (point))
8223 what "children")
8224 (goto-char start)
8225 (show-subtree)
8226 (outline-next-heading))
8228 ;; we will sort the top-level entries in this file
8229 (goto-char (point-min))
8230 (or (org-at-heading-p) (outline-next-heading))
8231 (setq start (point))
8232 (goto-char (point-max))
8233 (beginning-of-line 1)
8234 (when (looking-at ".*?\\S-")
8235 ;; File ends in a non-white line
8236 (end-of-line 1)
8237 (insert "\n"))
8238 (setq end (point-max))
8239 (setq what "top-level")
8240 (goto-char start)
8241 (show-all)))
8243 (setq beg (point))
8244 (if (>= beg end) (error "Nothing to sort"))
8246 (looking-at "\\(\\*+\\)")
8247 (setq stars (match-string 1)
8248 re (concat "^" (regexp-quote stars) " +")
8249 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8250 txt (buffer-substring beg end))
8251 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8252 (if (and (not (equal stars "*")) (string-match re2 txt))
8253 (error "Region to sort contains a level above the first entry"))
8255 (unless sorting-type
8256 (message
8257 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8258 [t]ime [s]cheduled [d]eadline [c]reated
8259 A/N/P/R/O/F/T/S/D/C means reversed:"
8260 what)
8261 (setq sorting-type (read-char-exclusive))
8263 (unless getkey-func
8264 (and (= (downcase sorting-type) ?f)
8265 (setq getkey-func
8266 (org-icompleting-read "Sort using function: "
8267 obarray 'fboundp t nil nil))
8268 (setq getkey-func (intern getkey-func))))
8270 (and (= (downcase sorting-type) ?r)
8271 (not property)
8272 (setq property
8273 (org-icompleting-read "Property: "
8274 (mapcar 'list (org-buffer-property-keys t))
8275 nil t))))
8277 (message "Sorting entries...")
8279 (save-restriction
8280 (narrow-to-region start end)
8281 (let ((dcst (downcase sorting-type))
8282 (case-fold-search nil)
8283 (now (current-time)))
8284 (sort-subr
8285 (/= dcst sorting-type)
8286 ;; This function moves to the beginning character of the "record" to
8287 ;; be sorted.
8288 (lambda nil
8289 (if (re-search-forward re nil t)
8290 (goto-char (match-beginning 0))
8291 (goto-char (point-max))))
8292 ;; This function moves to the last character of the "record" being
8293 ;; sorted.
8294 (lambda nil
8295 (save-match-data
8296 (condition-case nil
8297 (outline-forward-same-level 1)
8298 (error
8299 (goto-char (point-max))))))
8300 ;; This function returns the value that gets sorted against.
8301 (lambda nil
8302 (cond
8303 ((= dcst ?n)
8304 (if (looking-at org-complex-heading-regexp)
8305 (string-to-number (match-string 4))
8306 nil))
8307 ((= dcst ?a)
8308 (if (looking-at org-complex-heading-regexp)
8309 (funcall case-func (match-string 4))
8310 nil))
8311 ((= dcst ?t)
8312 (let ((end (save-excursion (outline-next-heading) (point))))
8313 (if (or (re-search-forward org-ts-regexp end t)
8314 (re-search-forward org-ts-regexp-both end t))
8315 (org-time-string-to-seconds (match-string 0))
8316 (org-float-time now))))
8317 ((= dcst ?c)
8318 (let ((end (save-excursion (outline-next-heading) (point))))
8319 (if (re-search-forward
8320 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8321 end t)
8322 (org-time-string-to-seconds (match-string 0))
8323 (org-float-time now))))
8324 ((= dcst ?s)
8325 (let ((end (save-excursion (outline-next-heading) (point))))
8326 (if (re-search-forward org-scheduled-time-regexp end t)
8327 (org-time-string-to-seconds (match-string 1))
8328 (org-float-time now))))
8329 ((= dcst ?d)
8330 (let ((end (save-excursion (outline-next-heading) (point))))
8331 (if (re-search-forward org-deadline-time-regexp end t)
8332 (org-time-string-to-seconds (match-string 1))
8333 (org-float-time now))))
8334 ((= dcst ?p)
8335 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8336 (string-to-char (match-string 2))
8337 org-default-priority))
8338 ((= dcst ?r)
8339 (or (org-entry-get nil property) ""))
8340 ((= dcst ?o)
8341 (if (looking-at org-complex-heading-regexp)
8342 (- 9999 (length (member (match-string 2)
8343 org-todo-keywords-1)))))
8344 ((= dcst ?f)
8345 (if getkey-func
8346 (progn
8347 (setq tmp (funcall getkey-func))
8348 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8349 tmp)
8350 (error "Invalid key function `%s'" getkey-func)))
8351 (t (error "Invalid sorting type `%c'" sorting-type))))
8353 (cond
8354 ((= dcst ?a) 'string<)
8355 ((= dcst ?f) compare-func)
8356 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8357 (run-hooks 'org-after-sorting-entries-or-items-hook)
8358 ;; Reset the clock marker if needed
8359 (when cmstr
8360 (save-excursion
8361 (goto-char start)
8362 (search-forward cmstr nil t)
8363 (move-marker org-clock-marker (point))))
8364 (message "Sorting entries...done")))
8366 (defun org-do-sort (table what &optional with-case sorting-type)
8367 "Sort TABLE of WHAT according to SORTING-TYPE.
8368 The user will be prompted for the SORTING-TYPE if the call to this
8369 function does not specify it. WHAT is only for the prompt, to indicate
8370 what is being sorted. The sorting key will be extracted from
8371 the car of the elements of the table.
8372 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8373 (unless sorting-type
8374 (message
8375 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8376 what)
8377 (setq sorting-type (read-char-exclusive)))
8378 (let ((dcst (downcase sorting-type))
8379 extractfun comparefun)
8380 ;; Define the appropriate functions
8381 (cond
8382 ((= dcst ?n)
8383 (setq extractfun 'string-to-number
8384 comparefun (if (= dcst sorting-type) '< '>)))
8385 ((= dcst ?a)
8386 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8387 (lambda(x) (downcase (org-sort-remove-invisible x))))
8388 comparefun (if (= dcst sorting-type)
8389 'string<
8390 (lambda (a b) (and (not (string< a b))
8391 (not (string= a b)))))))
8392 ((= dcst ?t)
8393 (setq extractfun
8394 (lambda (x)
8395 (if (or (string-match org-ts-regexp x)
8396 (string-match org-ts-regexp-both x))
8397 (org-float-time
8398 (org-time-string-to-time (match-string 0 x)))
8400 comparefun (if (= dcst sorting-type) '< '>)))
8401 (t (error "Invalid sorting type `%c'" sorting-type)))
8403 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8404 table)
8405 (lambda (a b) (funcall comparefun (car a) (car b))))))
8408 ;;; The orgstruct minor mode
8410 ;; Define a minor mode which can be used in other modes in order to
8411 ;; integrate the org-mode structure editing commands.
8413 ;; This is really a hack, because the org-mode structure commands use
8414 ;; keys which normally belong to the major mode. Here is how it
8415 ;; works: The minor mode defines all the keys necessary to operate the
8416 ;; structure commands, but wraps the commands into a function which
8417 ;; tests if the cursor is currently at a headline or a plain list
8418 ;; item. If that is the case, the structure command is used,
8419 ;; temporarily setting many Org-mode variables like regular
8420 ;; expressions for filling etc. However, when any of those keys is
8421 ;; used at a different location, function uses `key-binding' to look
8422 ;; up if the key has an associated command in another currently active
8423 ;; keymap (minor modes, major mode, global), and executes that
8424 ;; command. There might be problems if any of the keys is otherwise
8425 ;; used as a prefix key.
8427 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8428 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8429 ;; addresses this by checking explicitly for both bindings.
8431 (defvar orgstruct-mode-map (make-sparse-keymap)
8432 "Keymap for the minor `orgstruct-mode'.")
8434 (defvar org-local-vars nil
8435 "List of local variables, for use by `orgstruct-mode'.")
8437 ;;;###autoload
8438 (define-minor-mode orgstruct-mode
8439 "Toggle the minor mode `orgstruct-mode'.
8440 This mode is for using Org-mode structure commands in other
8441 modes. The following keys behave as if Org-mode were active, if
8442 the cursor is on a headline, or on a plain list item (both as
8443 defined by Org-mode).
8445 M-up Move entry/item up
8446 M-down Move entry/item down
8447 M-left Promote
8448 M-right Demote
8449 M-S-up Move entry/item up
8450 M-S-down Move entry/item down
8451 M-S-left Promote subtree
8452 M-S-right Demote subtree
8453 M-q Fill paragraph and items like in Org-mode
8454 C-c ^ Sort entries
8455 C-c - Cycle list bullet
8456 TAB Cycle item visibility
8457 M-RET Insert new heading/item
8458 S-M-RET Insert new TODO heading / Checkbox item
8459 C-c C-c Set tags / toggle checkbox"
8460 nil " OrgStruct" nil
8461 (org-load-modules-maybe)
8462 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8464 ;;;###autoload
8465 (defun turn-on-orgstruct ()
8466 "Unconditionally turn on `orgstruct-mode'."
8467 (orgstruct-mode 1))
8469 (defvar org-fb-vars nil)
8470 (make-variable-buffer-local 'org-fb-vars)
8471 (defun orgstruct++-mode (&optional arg)
8472 "Toggle `orgstruct-mode', the enhanced version of it.
8473 In addition to setting orgstruct-mode, this also exports all
8474 indentation and autofilling variables from org-mode into the
8475 buffer. It will also recognize item context in multiline items."
8476 (interactive "P")
8477 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8478 (if (< arg 1)
8479 (progn (orgstruct-mode -1)
8480 (mapc (lambda(v)
8481 (org-set-local (car v)
8482 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8483 org-fb-vars))
8484 (orgstruct-mode 1)
8485 (setq org-fb-vars nil)
8486 (let (var val)
8487 (mapc
8488 (lambda (x)
8489 (when (string-match
8490 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8491 (symbol-name (car x)))
8492 (setq var (car x) val (nth 1 x))
8493 (push (list var `(quote ,(eval var))) org-fb-vars)
8494 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8495 org-local-vars)
8496 (org-set-local 'orgstruct-is-++ t))))
8498 (defvar orgstruct-is-++ nil
8499 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8500 (make-variable-buffer-local 'orgstruct-is-++)
8502 ;;;###autoload
8503 (defun turn-on-orgstruct++ ()
8504 "Unconditionally turn on `orgstruct++-mode'."
8505 (orgstruct++-mode 1))
8507 (defun orgstruct-error ()
8508 "Error when there is no default binding for a structure key."
8509 (interactive)
8510 (error "This key has no function outside structure elements"))
8512 (defun orgstruct-setup ()
8513 "Setup orgstruct keymaps."
8514 (let ((nfunc 0)
8515 (bindings
8516 (list
8517 '([(meta up)] org-metaup)
8518 '([(meta down)] org-metadown)
8519 '([(meta left)] org-metaleft)
8520 '([(meta right)] org-metaright)
8521 '([(meta shift up)] org-shiftmetaup)
8522 '([(meta shift down)] org-shiftmetadown)
8523 '([(meta shift left)] org-shiftmetaleft)
8524 '([(meta shift right)] org-shiftmetaright)
8525 '([?\e (up)] org-metaup)
8526 '([?\e (down)] org-metadown)
8527 '([?\e (left)] org-metaleft)
8528 '([?\e (right)] org-metaright)
8529 '([?\e (shift up)] org-shiftmetaup)
8530 '([?\e (shift down)] org-shiftmetadown)
8531 '([?\e (shift left)] org-shiftmetaleft)
8532 '([?\e (shift right)] org-shiftmetaright)
8533 '([(shift up)] org-shiftup)
8534 '([(shift down)] org-shiftdown)
8535 '([(shift left)] org-shiftleft)
8536 '([(shift right)] org-shiftright)
8537 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8538 '("\M-q" fill-paragraph)
8539 '("\C-c^" org-sort)
8540 '("\C-c-" org-cycle-list-bullet)))
8541 elt key fun cmd)
8542 (while (setq elt (pop bindings))
8543 (setq nfunc (1+ nfunc))
8544 (setq key (org-key (car elt))
8545 fun (nth 1 elt)
8546 cmd (orgstruct-make-binding fun nfunc key))
8547 (org-defkey orgstruct-mode-map key cmd))
8549 ;; Prevent an error for users who forgot to make autoloads
8550 (require 'org-element)
8552 ;; Special treatment needed for TAB and RET
8553 (org-defkey orgstruct-mode-map [(tab)]
8554 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8555 (org-defkey orgstruct-mode-map "\C-i"
8556 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8558 (org-defkey orgstruct-mode-map "\M-\C-m"
8559 (orgstruct-make-binding 'org-insert-heading 105
8560 "\M-\C-m" [(meta return)]))
8561 (org-defkey orgstruct-mode-map [(meta return)]
8562 (orgstruct-make-binding 'org-insert-heading 106
8563 [(meta return)] "\M-\C-m"))
8565 (org-defkey orgstruct-mode-map [(shift meta return)]
8566 (orgstruct-make-binding 'org-insert-todo-heading 107
8567 [(meta return)] "\M-\C-m"))
8569 (org-defkey orgstruct-mode-map "\e\C-m"
8570 (orgstruct-make-binding 'org-insert-heading 108
8571 "\e\C-m" [?\e (return)]))
8572 (org-defkey orgstruct-mode-map [?\e (return)]
8573 (orgstruct-make-binding 'org-insert-heading 109
8574 [?\e (return)] "\e\C-m"))
8575 (org-defkey orgstruct-mode-map [?\e (shift return)]
8576 (orgstruct-make-binding 'org-insert-todo-heading 110
8577 [?\e (return)] "\e\C-m"))
8579 (unless org-local-vars
8580 (setq org-local-vars (org-get-local-variables)))
8584 (defun orgstruct-make-binding (fun n &rest keys)
8585 "Create a function for binding in the structure minor mode.
8586 FUN is the command to call inside a table. N is used to create a unique
8587 command name. KEYS are keys that should be checked in for a command
8588 to execute outside of tables."
8589 (eval
8590 (list 'defun
8591 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8592 '(arg)
8593 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8594 "Outside of structure, run the binding of `"
8595 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8596 "'.")
8597 '(interactive "p")
8598 (list 'if
8599 `(org-context-p 'headline 'item
8600 (and orgstruct-is-++
8601 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8602 'item-body))
8603 (list 'org-run-like-in-org-mode (list 'quote fun))
8604 (list 'let '(orgstruct-mode)
8605 (list 'call-interactively
8606 (append '(or)
8607 (mapcar (lambda (k)
8608 (list 'key-binding k))
8609 keys)
8610 '('orgstruct-error))))))))
8612 (defun org-contextualize-keys (alist contexts)
8613 "Return valid elements in ALIST depending on CONTEXTS.
8615 `org-agenda-custom-commands' or `org-capture-templates' are the
8616 values used for ALIST, and `org-agenda-custom-commands-contexts'
8617 or `org-capture-templates-contexts' are the associated contexts
8618 definitions."
8619 (let ((contexts
8620 ;; normalize contexts
8621 (mapcar
8622 (lambda(c) (cond ((listp (cadr c))
8623 (list (car c) (car c) (cadr c)))
8624 ((string= "" (cadr c))
8625 (list (car c) (car c) (caddr c)))
8626 (t c))) contexts))
8627 (a alist) c r s)
8628 ;; loop over all commands or templates
8629 (while (setq c (pop a))
8630 (let (vrules repl)
8631 (cond
8632 ((not (assoc (car c) contexts))
8633 (push c r))
8634 ((and (assoc (car c) contexts)
8635 (setq vrules (org-contextualize-validate-key
8636 (car c) contexts)))
8637 (mapc (lambda (vr)
8638 (when (not (equal (car vr) (cadr vr)))
8639 (setq repl vr))) vrules)
8640 (if (not repl) (push c r)
8641 (push (cadr repl) s)
8642 (push
8643 (cons (car c)
8644 (cdr (or (assoc (cadr repl) alist)
8645 (error "Undefined key `%s' as contextual replacement for `%s'"
8646 (cadr repl) (car c)))))
8647 r))))))
8648 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8649 (delq
8651 (delete-dups
8652 (mapcar (lambda (x)
8653 (let ((tpl (car x)))
8654 (when (not (delq
8656 (mapcar (lambda(y)
8657 (equal y tpl)) s))) x)))
8658 (reverse r))))))
8660 (defun org-contextualize-validate-key (key contexts)
8661 "Check CONTEXTS for agenda or capture KEY."
8662 (let (r rr res)
8663 (while (setq r (pop contexts))
8664 (mapc
8665 (lambda (rr)
8666 (when
8667 (and (equal key (car r))
8668 (if (functionp rr) (funcall rr)
8669 (or (and (eq (car rr) 'in-file)
8670 (buffer-file-name)
8671 (string-match (cdr rr) (buffer-file-name)))
8672 (and (eq (car rr) 'in-mode)
8673 (string-match (cdr rr) (symbol-name major-mode)))
8674 (when (and (eq (car rr) 'not-in-file)
8675 (buffer-file-name))
8676 (not (string-match (cdr rr) (buffer-file-name))))
8677 (when (eq (car rr) 'not-in-mode)
8678 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8679 (push r res)))
8680 (car (last r))))
8681 (delete-dups (delq nil res))))
8683 (defun org-context-p (&rest contexts)
8684 "Check if local context is any of CONTEXTS.
8685 Possible values in the list of contexts are `table', `headline', and `item'."
8686 (let ((pos (point)))
8687 (goto-char (point-at-bol))
8688 (prog1 (or (and (memq 'table contexts)
8689 (looking-at "[ \t]*|"))
8690 (and (memq 'headline contexts)
8691 (looking-at org-outline-regexp))
8692 (and (memq 'item contexts)
8693 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8694 (and (memq 'item-body contexts)
8695 (org-in-item-p)))
8696 (goto-char pos))))
8698 (defun org-get-local-variables ()
8699 "Return a list of all local variables in an Org mode buffer."
8700 (let (varlist)
8701 (with-current-buffer (get-buffer-create "*Org tmp*")
8702 (erase-buffer)
8703 (org-mode)
8704 (setq varlist (buffer-local-variables)))
8705 (kill-buffer "*Org tmp*")
8706 (delq nil
8707 (mapcar
8708 (lambda (x)
8709 (setq x
8710 (if (symbolp x)
8711 (list x)
8712 (list (car x) (list 'quote (cdr x)))))
8713 (if (string-match
8714 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8715 (symbol-name (car x)))
8716 x nil))
8717 varlist))))
8719 (defun org-clone-local-variables (from-buffer &optional regexp)
8720 "Clone local variables from FROM-BUFFER.
8721 Optional argument REGEXP selects variables to clone."
8722 (mapc
8723 (lambda (pair)
8724 (and (symbolp (car pair))
8725 (or (null regexp)
8726 (string-match regexp (symbol-name (car pair))))
8727 (set (make-local-variable (car pair))
8728 (cdr pair))))
8729 (buffer-local-variables from-buffer)))
8731 ;;;###autoload
8732 (defun org-run-like-in-org-mode (cmd)
8733 "Run a command, pretending that the current buffer is in Org-mode.
8734 This will temporarily bind local variables that are typically bound in
8735 Org-mode to the values they have in Org-mode, and then interactively
8736 call CMD."
8737 (org-load-modules-maybe)
8738 (unless org-local-vars
8739 (setq org-local-vars (org-get-local-variables)))
8740 (eval (list 'let org-local-vars
8741 (list 'call-interactively (list 'quote cmd)))))
8743 ;;;; Archiving
8745 (defun org-get-category (&optional pos force-refresh)
8746 "Get the category applying to position POS."
8747 (save-match-data
8748 (if force-refresh (org-refresh-category-properties))
8749 (let ((pos (or pos (point))))
8750 (or (get-text-property pos 'org-category)
8751 (progn (org-refresh-category-properties)
8752 (get-text-property pos 'org-category))))))
8754 (defun org-refresh-category-properties ()
8755 "Refresh category text properties in the buffer."
8756 (let ((case-fold-search t)
8757 (inhibit-read-only t)
8758 (def-cat (cond
8759 ((null org-category)
8760 (if buffer-file-name
8761 (file-name-sans-extension
8762 (file-name-nondirectory buffer-file-name))
8763 "???"))
8764 ((symbolp org-category) (symbol-name org-category))
8765 (t org-category)))
8766 beg end cat pos optionp)
8767 (org-unmodified
8768 (save-excursion
8769 (save-restriction
8770 (widen)
8771 (goto-char (point-min))
8772 (put-text-property (point) (point-max) 'org-category def-cat)
8773 (while (re-search-forward
8774 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8775 (setq pos (match-end 0)
8776 optionp (equal (char-after (match-beginning 0)) ?#)
8777 cat (org-trim (match-string 2)))
8778 (if optionp
8779 (setq beg (point-at-bol) end (point-max))
8780 (org-back-to-heading t)
8781 (setq beg (point) end (org-end-of-subtree t t)))
8782 (put-text-property beg end 'org-category cat)
8783 (put-text-property beg end 'org-category-position beg)
8784 (goto-char pos)))))))
8787 ;;;; Link Stuff
8789 ;;; Link abbreviations
8791 (defun org-link-expand-abbrev (link)
8792 "Apply replacements as defined in `org-link-abbrev-alist'."
8793 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8794 (let* ((key (match-string 1 link))
8795 (as (or (assoc key org-link-abbrev-alist-local)
8796 (assoc key org-link-abbrev-alist)))
8797 (tag (and (match-end 2) (match-string 3 link)))
8798 rpl)
8799 (if (not as)
8800 link
8801 (setq rpl (cdr as))
8802 (cond
8803 ((symbolp rpl) (funcall rpl tag))
8804 ((string-match "%(\\([^)]+\\))" rpl)
8805 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8806 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8807 ((string-match "%h" rpl)
8808 (replace-match (url-hexify-string (or tag "")) t t rpl))
8809 (t (concat rpl tag)))))
8810 link))
8812 ;;; Storing and inserting links
8814 (defvar org-insert-link-history nil
8815 "Minibuffer history for links inserted with `org-insert-link'.")
8817 (defvar org-stored-links nil
8818 "Contains the links stored with `org-store-link'.")
8820 (defvar org-store-link-plist nil
8821 "Plist with info about the most recently link created with `org-store-link'.")
8823 (defvar org-link-protocols nil
8824 "Link protocols added to Org-mode using `org-add-link-type'.")
8826 (defvar org-store-link-functions nil
8827 "List of functions that are called to create and store a link.
8828 Each function will be called in turn until one returns a non-nil
8829 value. Each function should check if it is responsible for creating
8830 this link (for example by looking at the major mode).
8831 If not, it must exit and return nil.
8832 If yes, it should return a non-nil value after a calling
8833 `org-store-link-props' with a list of properties and values.
8834 Special properties are:
8836 :type The link prefix, like \"http\". This must be given.
8837 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8838 This is obligatory as well.
8839 :description Optional default description for the second pair
8840 of brackets in an Org-mode link. The user can still change
8841 this when inserting this link into an Org-mode buffer.
8843 In addition to these, any additional properties can be specified
8844 and then used in capture templates.")
8846 (defun org-add-link-type (type &optional follow export)
8847 "Add TYPE to the list of `org-link-types'.
8848 Re-compute all regular expressions depending on `org-link-types'
8850 FOLLOW and EXPORT are two functions.
8852 FOLLOW should take the link path as the single argument and do whatever
8853 is necessary to follow the link, for example find a file or display
8854 a mail message.
8856 EXPORT should format the link path for export to one of the export formats.
8857 It should be a function accepting three arguments:
8859 path the path of the link, the text after the prefix (like \"http:\")
8860 desc the description of the link, if any, or a description added by
8861 org-export-normalize-links if there is none
8862 format the export format, a symbol like `html' or `latex' or `ascii'..
8864 The function may use the FORMAT information to return different values
8865 depending on the format. The return value will be put literally into
8866 the exported file. If the return value is nil, this means Org should
8867 do what it normally does with links which do not have EXPORT defined.
8869 Org-mode has a built-in default for exporting links. If you are happy with
8870 this default, there is no need to define an export function for the link
8871 type. For a simple example of an export function, see `org-bbdb.el'."
8872 (add-to-list 'org-link-types type t)
8873 (org-make-link-regexps)
8874 (if (assoc type org-link-protocols)
8875 (setcdr (assoc type org-link-protocols) (list follow export))
8876 (push (list type follow export) org-link-protocols)))
8878 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8879 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8881 ;;;###autoload
8882 (defun org-store-link (arg)
8883 "\\<org-mode-map>Store an org-link to the current location.
8884 This link is added to `org-stored-links' and can later be inserted
8885 into an org-buffer with \\[org-insert-link].
8887 For some link types, a prefix arg is interpreted.
8888 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8889 For file links, arg negates `org-context-in-file-links'.
8891 A double prefix arg force skipping storing functions that are not
8892 part of Org's core."
8893 (interactive "P")
8894 (org-load-modules-maybe)
8895 (setq org-store-link-plist nil) ; reset
8896 (org-with-limited-levels
8897 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8898 (cond
8899 ((and (not (equal arg '(16)))
8900 (setq sfuns
8901 (delq
8902 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8903 org-store-link-functions))
8904 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8905 (or (and (cdr sfuns)
8906 (funcall (intern
8907 (completing-read "Which function for creating the link? "
8908 sfunsn t (car sfunsn)))))
8909 (funcall (caar sfuns)))
8910 (setq link (plist-get org-store-link-plist :link)
8911 desc (or (plist-get org-store-link-plist :description) link))))
8912 ((org-src-edit-buffer-p)
8913 (let (label gc)
8914 (while (or (not label)
8915 (save-excursion
8916 (save-restriction
8917 (widen)
8918 (goto-char (point-min))
8919 (re-search-forward
8920 (regexp-quote (format org-coderef-label-format label))
8921 nil t))))
8922 (when label (message "Label exists already") (sit-for 2))
8923 (setq label (read-string "Code line label: " label)))
8924 (end-of-line 1)
8925 (setq link (format org-coderef-label-format label))
8926 (setq gc (- 79 (length link)))
8927 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8928 (insert link)
8929 (setq link (concat "(" label ")") desc nil)))
8931 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8932 ;; We are in the agenda, link to referenced location
8933 (let ((m (or (get-text-property (point) 'org-hd-marker)
8934 (get-text-property (point) 'org-marker))))
8935 (when m
8936 (org-with-point-at m
8937 (setq agenda-link
8938 (if (org-called-interactively-p 'any)
8939 (call-interactively 'org-store-link)
8940 (org-store-link nil)))))))
8942 ((eq major-mode 'calendar-mode)
8943 (let ((cd (calendar-cursor-to-date)))
8944 (setq link
8945 (format-time-string
8946 (car org-time-stamp-formats)
8947 (apply 'encode-time
8948 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8949 nil nil nil))))
8950 (org-store-link-props :type "calendar" :date cd)))
8952 ((eq major-mode 'help-mode)
8953 (setq link (concat "help:" (save-excursion
8954 (goto-char (point-min))
8955 (looking-at "^[^ ]+")
8956 (match-string 0))))
8957 (org-store-link-props :type "help"))
8959 ((eq major-mode 'w3-mode)
8960 (setq cpltxt (if (and (buffer-name)
8961 (not (string-match "Untitled" (buffer-name))))
8962 (buffer-name)
8963 (url-view-url t))
8964 link (url-view-url t))
8965 (org-store-link-props :type "w3" :url (url-view-url t)))
8967 ((setq search (run-hook-with-args-until-success
8968 'org-create-file-search-functions))
8969 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8970 "::" search))
8971 (setq cpltxt (or description link)))
8973 ((eq major-mode 'image-mode)
8974 (setq cpltxt (concat "file:"
8975 (abbreviate-file-name buffer-file-name))
8976 link cpltxt)
8977 (org-store-link-props :type "image" :file buffer-file-name))
8979 ((eq major-mode 'dired-mode)
8980 ;; link to the file in the current line
8981 (let ((file (dired-get-filename nil t)))
8982 (setq file (if file
8983 (abbreviate-file-name
8984 (expand-file-name (dired-get-filename nil t)))
8985 ;; otherwise, no file so use current directory.
8986 default-directory))
8987 (setq cpltxt (concat "file:" file)
8988 link cpltxt)))
8990 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8991 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8992 (cond
8993 ((org-in-regexp "<<\\(.*?\\)>>")
8994 (setq cpltxt
8995 (concat "file:"
8996 (abbreviate-file-name
8997 (buffer-file-name (buffer-base-buffer)))
8998 "::" (match-string 1))
8999 link cpltxt))
9000 ((and (featurep 'org-id)
9001 (or (eq org-link-to-org-use-id t)
9002 (and (org-called-interactively-p 'any)
9003 (or (eq org-link-to-org-use-id 'create-if-interactive)
9004 (and (eq org-link-to-org-use-id
9005 'create-if-interactive-and-no-custom-id)
9006 (not custom-id))))
9007 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
9008 ;; We can make a link using the ID.
9009 (setq link (condition-case nil
9010 (prog1 (org-id-store-link)
9011 (setq desc (plist-get org-store-link-plist :description)))
9012 (error
9013 ;; probably before first headline, link to file only
9014 (concat "file:"
9015 (abbreviate-file-name
9016 (buffer-file-name (buffer-base-buffer))))))))
9018 ;; Just link to current headline
9019 (setq cpltxt (concat "file:"
9020 (abbreviate-file-name
9021 (buffer-file-name (buffer-base-buffer)))))
9022 ;; Add a context search string
9023 (when (org-xor org-context-in-file-links arg)
9024 (setq txt (cond
9025 ((org-at-heading-p) nil)
9026 ((org-region-active-p)
9027 (buffer-substring (region-beginning) (region-end)))))
9028 (when (or (null txt) (string-match "\\S-" txt))
9029 (setq cpltxt
9030 (concat cpltxt "::"
9031 (condition-case nil
9032 (org-make-org-heading-search-string txt)
9033 (error "")))
9034 desc (or (nth 4 (ignore-errors
9035 (org-heading-components))) "NONE"))))
9036 (if (string-match "::\\'" cpltxt)
9037 (setq cpltxt (substring cpltxt 0 -2)))
9038 (setq link cpltxt))))
9040 ((buffer-file-name (buffer-base-buffer))
9041 ;; Just link to this file here.
9042 (setq cpltxt (concat "file:"
9043 (abbreviate-file-name
9044 (buffer-file-name (buffer-base-buffer)))))
9045 ;; Add a context string
9046 (when (org-xor org-context-in-file-links arg)
9047 (setq txt (if (org-region-active-p)
9048 (buffer-substring (region-beginning) (region-end))
9049 (buffer-substring (point-at-bol) (point-at-eol))))
9050 ;; Only use search option if there is some text.
9051 (when (string-match "\\S-" txt)
9052 (setq cpltxt
9053 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9054 desc "NONE")))
9055 (setq link cpltxt))
9057 ((org-called-interactively-p 'interactive)
9058 (user-error "No method for storing a link from this buffer"))
9060 (t (setq link nil)))
9062 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9063 (setq link (or link cpltxt)
9064 desc (or desc cpltxt))
9065 (cond ((equal desc "NONE") (setq desc nil))
9066 ((string-match org-bracket-link-regexp desc)
9067 (setq desc (replace-regexp-in-string
9068 org-bracket-link-regexp
9069 (concat "\\3" (if (equal (length (match-string 0 desc))
9070 (length desc)) "*" "")) desc))))
9072 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9073 (progn
9074 (setq org-stored-links
9075 (cons (list link desc) org-stored-links))
9076 (message "Stored: %s" (or desc link))
9077 (when custom-id
9078 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9079 "::#" custom-id))
9080 (setq org-stored-links
9081 (cons (list link desc) org-stored-links))))
9082 (or agenda-link (and link (org-make-link-string link desc)))))))
9084 (defun org-store-link-props (&rest plist)
9085 "Store link properties, extract names and addresses."
9086 (let (x adr)
9087 (when (setq x (plist-get plist :from))
9088 (setq adr (mail-extract-address-components x))
9089 (setq plist (plist-put plist :fromname (car adr)))
9090 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9091 (when (setq x (plist-get plist :to))
9092 (setq adr (mail-extract-address-components x))
9093 (setq plist (plist-put plist :toname (car adr)))
9094 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9095 (let ((from (plist-get plist :from))
9096 (to (plist-get plist :to)))
9097 (when (and from to org-from-is-user-regexp)
9098 (setq plist
9099 (plist-put plist :fromto
9100 (if (string-match org-from-is-user-regexp from)
9101 (concat "to %t")
9102 (concat "from %f"))))))
9103 (setq org-store-link-plist plist))
9105 (defun org-add-link-props (&rest plist)
9106 "Add these properties to the link property list."
9107 (let (key value)
9108 (while plist
9109 (setq key (pop plist) value (pop plist))
9110 (setq org-store-link-plist
9111 (plist-put org-store-link-plist key value)))))
9113 (defun org-email-link-description (&optional fmt)
9114 "Return the description part of an email link.
9115 This takes information from `org-store-link-plist' and formats it
9116 according to FMT (default from `org-email-link-description-format')."
9117 (setq fmt (or fmt org-email-link-description-format))
9118 (let* ((p org-store-link-plist)
9119 (to (plist-get p :toaddress))
9120 (from (plist-get p :fromaddress))
9121 (table
9122 (list
9123 (cons "%c" (plist-get p :fromto))
9124 (cons "%F" (plist-get p :from))
9125 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9126 (cons "%T" (plist-get p :to))
9127 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9128 (cons "%s" (plist-get p :subject))
9129 (cons "%d" (plist-get p :date))
9130 (cons "%m" (plist-get p :message-id)))))
9131 (when (string-match "%c" fmt)
9132 ;; Check if the user wrote this message
9133 (if (and org-from-is-user-regexp from to
9134 (save-match-data (string-match org-from-is-user-regexp from)))
9135 (setq fmt (replace-match "to %t" t t fmt))
9136 (setq fmt (replace-match "from %f" t t fmt))))
9137 (org-replace-escapes fmt table)))
9139 (defun org-make-org-heading-search-string (&optional string heading)
9140 "Make search string for STRING or current headline."
9141 (interactive)
9142 (let ((s (or string (org-get-heading)))
9143 (lines org-context-in-file-links))
9144 (unless (and string (not heading))
9145 ;; We are using a headline, clean up garbage in there.
9146 (if (string-match org-todo-regexp s)
9147 (setq s (replace-match "" t t s)))
9148 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9149 (setq s (replace-match "" t t s)))
9150 (setq s (org-trim s))
9151 (if (string-match (concat "^\\(" org-quote-string "\\|"
9152 org-comment-string "\\)") s)
9153 (setq s (replace-match "" t t s)))
9154 (while (string-match org-ts-regexp s)
9155 (setq s (replace-match "" t t s))))
9156 (or string (setq s (concat "*" s))) ; Add * for headlines
9157 (when (and string (integerp lines) (> lines 0))
9158 (let ((slines (org-split-string s "\n")))
9159 (when (< lines (length slines))
9160 (setq s (mapconcat
9161 'identity
9162 (reverse (nthcdr (- (length slines) lines)
9163 (reverse slines))) "\n")))))
9164 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9166 (defun org-make-link-string (link &optional description)
9167 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9168 (unless (string-match "\\S-" link)
9169 (error "Empty link"))
9170 (when (and description
9171 (stringp description)
9172 (not (string-match "\\S-" description)))
9173 (setq description nil))
9174 (when (stringp description)
9175 ;; Remove brackets from the description, they are fatal.
9176 (while (string-match "\\[" description)
9177 (setq description (replace-match "{" t t description)))
9178 (while (string-match "\\]" description)
9179 (setq description (replace-match "}" t t description))))
9180 (when (equal link description)
9181 ;; No description needed, it is identical
9182 (setq description nil))
9183 (when (and (not description)
9184 (not (string-match (org-image-file-name-regexp) link))
9185 (not (equal link (org-link-escape link))))
9186 (setq description (org-extract-attributes link)))
9187 (setq link
9188 (cond ((string-match (org-image-file-name-regexp) link) link)
9189 ((string-match org-link-types-re link)
9190 (concat (match-string 1 link)
9191 (org-link-escape (substring link (match-end 1)))))
9192 (t (org-link-escape link))))
9193 (concat "[[" link "]"
9194 (if description (concat "[" description "]") "")
9195 "]"))
9197 (defconst org-link-escape-chars
9198 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9199 "List of characters that should be escaped in link.
9200 This is the list that is used for internal purposes.")
9202 (defconst org-link-escape-chars-browser
9203 '(?\ )
9204 "List of escapes for characters that are problematic in links.
9205 This is the list that is used before handing over to the browser.")
9207 (defun org-link-escape (text &optional table merge)
9208 "Return percent escaped representation of TEXT.
9209 TEXT is a string with the text to escape.
9210 Optional argument TABLE is a list with characters that should be
9211 escaped. When nil, `org-link-escape-chars' is used.
9212 If optional argument MERGE is set, merge TABLE into
9213 `org-link-escape-chars'."
9214 (cond
9215 ((and table merge)
9216 (mapc (lambda (defchr)
9217 (unless (member defchr table)
9218 (setq table (cons defchr table)))) org-link-escape-chars))
9219 ((null table)
9220 (setq table org-link-escape-chars)))
9221 (mapconcat
9222 (lambda (char)
9223 (if (or (member char table)
9224 (and (or (< char 32) (= char 37) (> char 126))
9225 org-url-hexify-p))
9226 (mapconcat (lambda (sequence-element)
9227 (format "%%%.2X" sequence-element))
9228 (or (encode-coding-char char 'utf-8)
9229 (error "Unable to percent escape character: %s"
9230 (char-to-string char))) "")
9231 (char-to-string char))) text ""))
9233 (defun org-link-unescape (str)
9234 "Unhex hexified Unicode strings as returned from the JavaScript function
9235 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9236 (unless (and (null str) (string= "" str))
9237 (let ((pos 0) (case-fold-search t) unhexed)
9238 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9239 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9240 (setq str (replace-match unhexed t t str))
9241 (setq pos (+ pos (length unhexed))))))
9242 str)
9244 (defun org-link-unescape-compound (hex)
9245 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9246 Note: this function also decodes single byte encodings like
9247 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9248 (save-match-data
9249 (let* ((bytes (cdr (split-string hex "%")))
9250 (ret "")
9251 (eat 0)
9252 (sum 0))
9253 (while bytes
9254 (let* ((val (string-to-number (pop bytes) 16))
9255 (shift-xor
9256 (if (= 0 eat)
9257 (cond
9258 ((>= val 252) (cons 6 252))
9259 ((>= val 248) (cons 5 248))
9260 ((>= val 240) (cons 4 240))
9261 ((>= val 224) (cons 3 224))
9262 ((>= val 192) (cons 2 192))
9263 (t (cons 0 0)))
9264 (cons 6 128))))
9265 (if (>= val 192) (setq eat (car shift-xor)))
9266 (setq val (logxor val (cdr shift-xor)))
9267 (setq sum (+ (lsh sum (car shift-xor)) val))
9268 (if (> eat 0) (setq eat (- eat 1)))
9269 (cond
9270 ((= 0 eat) ;multi byte
9271 (setq ret (concat ret (org-char-to-string sum)))
9272 (setq sum 0))
9273 ((not bytes) ; single byte(s)
9274 (setq ret (org-link-unescape-single-byte-sequence hex))))
9275 )) ;; end (while bytes
9276 ret )))
9278 (defun org-link-unescape-single-byte-sequence (hex)
9279 "Unhexify hex-encoded single byte character sequences."
9280 (mapconcat (lambda (byte)
9281 (char-to-string (string-to-number byte 16)))
9282 (cdr (split-string hex "%")) ""))
9284 (defun org-xor (a b)
9285 "Exclusive or."
9286 (if a (not b) b))
9288 (defun org-fixup-message-id-for-http (s)
9289 "Replace special characters in a message id, so it can be used in an http query."
9290 (when (string-match "%" s)
9291 (setq s (mapconcat (lambda (c)
9292 (if (eq c ?%)
9293 "%25"
9294 (char-to-string c)))
9295 s "")))
9296 (while (string-match "<" s)
9297 (setq s (replace-match "%3C" t t s)))
9298 (while (string-match ">" s)
9299 (setq s (replace-match "%3E" t t s)))
9300 (while (string-match "@" s)
9301 (setq s (replace-match "%40" t t s)))
9304 (defun org-link-prettify (link)
9305 "Return a human-readable representation of LINK.
9306 The car of LINK must be a raw link the cdr of LINK must be either
9307 a link description or nil."
9308 (let ((desc (or (cadr link) "<no description>")))
9309 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9310 "<" (car link) ">")))
9312 ;;;###autoload
9313 (defun org-insert-link-global ()
9314 "Insert a link like Org-mode does.
9315 This command can be called in any mode to insert a link in Org-mode syntax."
9316 (interactive)
9317 (org-load-modules-maybe)
9318 (org-run-like-in-org-mode 'org-insert-link))
9320 (defun org-insert-all-links (&optional keep)
9321 "Insert all links in `org-stored-links'."
9322 (interactive "P")
9323 (let ((links (copy-sequence org-stored-links)) l)
9324 (while (setq l (if keep (pop links) (pop org-stored-links)))
9325 (insert "- ")
9326 (org-insert-link nil (car l) (cadr l))
9327 (insert "\n"))))
9329 (defun org-link-fontify-links-to-this-file ()
9330 "Fontify links to the current file in `org-stored-links'."
9331 (let ((f (buffer-file-name)) a b)
9332 (setq a (mapcar (lambda(l)
9333 (let ((ll (car l)))
9334 (when (and (string-match "^file:\\(.+\\)::" ll)
9335 (equal f (expand-file-name (match-string 1 ll))))
9336 ll)))
9337 org-stored-links))
9338 (when (featurep 'org-id)
9339 (setq b (mapcar (lambda(l)
9340 (let ((ll (car l)))
9341 (when (and (string-match "^id:\\(.+\\)$" ll)
9342 (equal f (expand-file-name
9343 (or (org-id-find-id-file
9344 (match-string 1 ll)) ""))))
9345 ll)))
9346 org-stored-links)))
9347 (mapcar (lambda(l)
9348 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9349 (delq nil (append a b)))))
9351 (defvar org-link-links-in-this-file nil)
9352 (defun org-insert-link (&optional complete-file link-location default-description)
9353 "Insert a link. At the prompt, enter the link.
9355 Completion can be used to insert any of the link protocol prefixes like
9356 http or ftp in use.
9358 The history can be used to select a link previously stored with
9359 `org-store-link'. When the empty string is entered (i.e. if you just
9360 press RET at the prompt), the link defaults to the most recently
9361 stored link. As SPC triggers completion in the minibuffer, you need to
9362 use M-SPC or C-q SPC to force the insertion of a space character.
9364 You will also be prompted for a description, and if one is given, it will
9365 be displayed in the buffer instead of the link.
9367 If there is already a link at point, this command will allow you to edit link
9368 and description parts.
9370 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9371 be selected using completion. The path to the file will be relative to the
9372 current directory if the file is in the current directory or a subdirectory.
9373 Otherwise, the link will be the absolute path as completed in the minibuffer
9374 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9375 option `org-link-file-path-type'.
9377 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9378 the current directory or below.
9380 With three \\[universal-argument] prefixes, negate the meaning of
9381 `org-keep-stored-link-after-insertion'.
9383 If `org-make-link-description-function' is non-nil, this function will be
9384 called with the link target, and the result will be the default
9385 link description.
9387 If the LINK-LOCATION parameter is non-nil, this value will be
9388 used as the link location instead of reading one interactively.
9390 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9391 be used as the default description."
9392 (interactive "P")
9393 (let* ((wcf (current-window-configuration))
9394 (origbuf (current-buffer))
9395 (region (if (org-region-active-p)
9396 (buffer-substring (region-beginning) (region-end))))
9397 (remove (and region (list (region-beginning) (region-end))))
9398 (desc region)
9399 tmphist ; byte-compile incorrectly complains about this
9400 (link link-location)
9401 (abbrevs org-link-abbrev-alist-local)
9402 entry file all-prefixes auto-desc)
9403 (cond
9404 (link-location) ; specified by arg, just use it.
9405 ((org-in-regexp org-bracket-link-regexp 1)
9406 ;; We do have a link at point, and we are going to edit it.
9407 (setq remove (list (match-beginning 0) (match-end 0)))
9408 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9409 (setq link (read-string "Link: "
9410 (org-link-unescape
9411 (org-match-string-no-properties 1)))))
9412 ((or (org-in-regexp org-angle-link-re)
9413 (org-in-regexp org-plain-link-re))
9414 ;; Convert to bracket link
9415 (setq remove (list (match-beginning 0) (match-end 0))
9416 link (read-string "Link: "
9417 (org-remove-angle-brackets (match-string 0)))))
9418 ((member complete-file '((4) (16)))
9419 ;; Completing read for file names.
9420 (setq link (org-file-complete-link complete-file)))
9422 ;; Read link, with completion for stored links.
9423 (org-link-fontify-links-to-this-file)
9424 (org-switch-to-buffer-other-window "*Org Links*")
9425 (with-current-buffer "*Org Links*"
9426 (erase-buffer)
9427 (insert "Insert a link.
9428 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9429 (when org-stored-links
9430 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9431 (insert (mapconcat 'org-link-prettify
9432 (reverse org-stored-links) "\n")))
9433 (goto-char (point-min)))
9434 (let ((cw (selected-window)))
9435 (select-window (get-buffer-window "*Org Links*" 'visible))
9436 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9437 (unless (pos-visible-in-window-p (point-max))
9438 (org-fit-window-to-buffer))
9439 (and (window-live-p cw) (select-window cw)))
9440 ;; Fake a link history, containing the stored links.
9441 (setq tmphist (append (mapcar 'car org-stored-links)
9442 org-insert-link-history))
9443 (setq all-prefixes (append (mapcar 'car abbrevs)
9444 (mapcar 'car org-link-abbrev-alist)
9445 org-link-types))
9446 (unwind-protect
9447 (progn
9448 (setq link
9449 (org-completing-read
9450 "Link: "
9451 (append
9452 (mapcar (lambda (x) (concat x ":"))
9453 all-prefixes)
9454 (mapcar 'car org-stored-links))
9455 nil nil nil
9456 'tmphist
9457 (caar org-stored-links)))
9458 (if (not (string-match "\\S-" link))
9459 (error "No link selected"))
9460 (mapc (lambda(l)
9461 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9462 org-stored-links)
9463 (if (or (member link all-prefixes)
9464 (and (equal ":" (substring link -1))
9465 (member (substring link 0 -1) all-prefixes)
9466 (setq link (substring link 0 -1))))
9467 (setq link (with-current-buffer origbuf
9468 (org-link-try-special-completion link)))))
9469 (set-window-configuration wcf)
9470 (kill-buffer "*Org Links*"))
9471 (setq entry (assoc link org-stored-links))
9472 (or entry (push link org-insert-link-history))
9473 (setq desc (or desc (nth 1 entry)))))
9475 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9476 (not org-keep-stored-link-after-insertion))
9477 (setq org-stored-links (delq (assoc link org-stored-links)
9478 org-stored-links)))
9480 (if (string-match org-plain-link-re link)
9481 ;; URL-like link, normalize the use of angular brackets.
9482 (setq link (org-remove-angle-brackets link)))
9484 ;; Check if we are linking to the current file with a search option
9485 ;; If yes, simplify the link by using only the search option.
9486 (when (and buffer-file-name
9487 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9488 (let* ((path (match-string 1 link))
9489 (case-fold-search nil)
9490 (search (match-string 2 link)))
9491 (save-match-data
9492 (if (equal (file-truename buffer-file-name) (file-truename path))
9493 ;; We are linking to this same file, with a search option
9494 (setq link search)))))
9496 ;; Check if we can/should use a relative path. If yes, simplify the link
9497 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9498 (let* ((type (match-string 1 link))
9499 (path (match-string 2 link))
9500 (origpath path)
9501 (case-fold-search nil))
9502 (cond
9503 ((or (eq org-link-file-path-type 'absolute)
9504 (equal complete-file '(16)))
9505 (setq path (abbreviate-file-name (expand-file-name path))))
9506 ((eq org-link-file-path-type 'noabbrev)
9507 (setq path (expand-file-name path)))
9508 ((eq org-link-file-path-type 'relative)
9509 (setq path (file-relative-name path)))
9511 (save-match-data
9512 (if (string-match (concat "^" (regexp-quote
9513 (expand-file-name
9514 (file-name-as-directory
9515 default-directory))))
9516 (expand-file-name path))
9517 ;; We are linking a file with relative path name.
9518 (setq path (substring (expand-file-name path)
9519 (match-end 0)))
9520 (setq path (abbreviate-file-name (expand-file-name path)))))))
9521 (setq link (concat type path))
9522 (if (equal desc origpath)
9523 (setq desc path))))
9525 (if org-make-link-description-function
9526 (setq desc
9527 (or (condition-case nil
9528 (funcall org-make-link-description-function link desc)
9529 (error (progn (message "Can't get link description from `%s'"
9530 (symbol-name org-make-link-description-function))
9531 (sit-for 2) nil)))
9532 (read-string "Description: " default-description)))
9533 (if default-description (setq desc default-description)
9534 (setq desc (or (and auto-desc desc)
9535 (read-string "Description: " desc)))))
9537 (unless (string-match "\\S-" desc) (setq desc nil))
9538 (if remove (apply 'delete-region remove))
9539 (insert (org-make-link-string link desc))))
9541 (defun org-link-try-special-completion (type)
9542 "If there is completion support for link type TYPE, offer it."
9543 (let ((fun (intern (concat "org-" type "-complete-link"))))
9544 (if (functionp fun)
9545 (funcall fun)
9546 (read-string "Link (no completion support): " (concat type ":")))))
9548 (defun org-file-complete-link (&optional arg)
9549 "Create a file link using completion."
9550 (let (file link)
9551 (setq file (org-iread-file-name "File: "))
9552 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9553 (pwd1 (file-name-as-directory (abbreviate-file-name
9554 (expand-file-name ".")))))
9555 (cond
9556 ((equal arg '(16))
9557 (setq link (concat
9558 "file:"
9559 (abbreviate-file-name (expand-file-name file)))))
9560 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9561 (setq link (concat "file:" (match-string 1 file))))
9562 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9563 (expand-file-name file))
9564 (setq link (concat
9565 "file:" (match-string 1 (expand-file-name file)))))
9566 (t (setq link (concat "file:" file)))))
9567 link))
9569 (defun org-iread-file-name (&rest args)
9570 "Read-file-name using `ido-mode' speedup if available.
9571 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9572 See `read-file-name' for a description of parameters."
9573 (org-without-partial-completion
9574 (if (and org-completion-use-ido
9575 (fboundp 'ido-read-file-name)
9576 (boundp 'ido-mode) ido-mode
9577 (listp (second args)))
9578 (let ((ido-enter-matching-directory nil))
9579 (apply 'ido-read-file-name args))
9580 (apply 'read-file-name args))))
9582 (defun org-completing-read (&rest args)
9583 "Completing-read with SPACE being a normal character."
9584 (let ((enable-recursive-minibuffers t)
9585 (minibuffer-local-completion-map
9586 (copy-keymap minibuffer-local-completion-map)))
9587 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9588 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9589 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9590 (apply 'org-icompleting-read args)))
9592 (defun org-completing-read-no-i (&rest args)
9593 (let (org-completion-use-ido org-completion-use-iswitchb)
9594 (apply 'org-completing-read args)))
9596 (defun org-iswitchb-completing-read (prompt choices &rest args)
9597 "Use iswitch as a completing-read replacement to choose from choices.
9598 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9599 from."
9600 (let* ((iswitchb-use-virtual-buffers nil)
9601 (iswitchb-make-buflist-hook
9602 (lambda ()
9603 (setq iswitchb-temp-buflist choices))))
9604 (iswitchb-read-buffer prompt)))
9606 (defun org-icompleting-read (&rest args)
9607 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9608 (org-without-partial-completion
9609 (if (and org-completion-use-ido
9610 (fboundp 'ido-completing-read)
9611 (boundp 'ido-mode) ido-mode
9612 (listp (second args)))
9613 (let ((ido-enter-matching-directory nil))
9614 (apply 'ido-completing-read (concat (car args))
9615 (if (consp (car (nth 1 args)))
9616 (mapcar 'car (nth 1 args))
9617 (nth 1 args))
9618 (cddr args)))
9619 (if (and org-completion-use-iswitchb
9620 (boundp 'iswitchb-mode) iswitchb-mode
9621 (listp (second args)))
9622 (apply 'org-iswitchb-completing-read (concat (car args))
9623 (if (consp (car (nth 1 args)))
9624 (mapcar 'car (nth 1 args))
9625 (nth 1 args))
9626 (cddr args))
9627 (apply 'completing-read args)))))
9629 (defun org-extract-attributes (s)
9630 "Extract the attributes cookie from a string and set as text property."
9631 (let (a attr (start 0) key value)
9632 (save-match-data
9633 (when (string-match "{{\\([^}]+\\)}}$" s)
9634 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9635 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9636 (setq key (match-string 1 a) value (match-string 2 a)
9637 start (match-end 0)
9638 attr (plist-put attr (intern key) value))))
9639 (org-add-props s nil 'org-attr attr))
9642 (defun org-extract-attributes-from-string (tag)
9643 (let (key value attr)
9644 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9645 (setq key (match-string 1 tag) value (match-string 2 tag)
9646 tag (replace-match "" t t tag)
9647 attr (plist-put attr (intern key) value)))
9648 (cons tag attr)))
9650 (defun org-attributes-to-string (plist)
9651 "Format a property list into an HTML attribute list."
9652 (let ((s "") key value)
9653 (while plist
9654 (setq key (pop plist) value (pop plist))
9655 (and value
9656 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9659 ;;; Opening/following a link
9661 (defvar org-link-search-failed nil)
9663 (defvar org-open-link-functions nil
9664 "Hook for functions finding a plain text link.
9665 These functions must take a single argument, the link content.
9666 They will be called for links that look like [[link text][description]]
9667 when LINK TEXT does not have a protocol like \"http:\" and does not look
9668 like a filename (e.g. \"./blue.png\").
9670 These functions will be called *before* Org attempts to resolve the
9671 link by doing text searches in the current buffer - so if you want a
9672 link \"[[target]]\" to still find \"<<target>>\", your function should
9673 handle this as a special case.
9675 When the function does handle the link, it must return a non-nil value.
9676 If it decides that it is not responsible for this link, it must return
9677 nil to indicate that that Org-mode can continue with other options
9678 like exact and fuzzy text search.")
9680 (defun org-next-link ()
9681 "Move forward to the next link.
9682 If the link is in hidden text, expose it."
9683 (interactive)
9684 (when (and org-link-search-failed (eq this-command last-command))
9685 (goto-char (point-min))
9686 (message "Link search wrapped back to beginning of buffer"))
9687 (setq org-link-search-failed nil)
9688 (let* ((pos (point))
9689 (ct (org-context))
9690 (a (assoc :link ct)))
9691 (if a (goto-char (nth 2 a)))
9692 (if (re-search-forward org-any-link-re nil t)
9693 (progn
9694 (goto-char (match-beginning 0))
9695 (if (outline-invisible-p) (org-show-context)))
9696 (goto-char pos)
9697 (setq org-link-search-failed t)
9698 (error "No further link found"))))
9700 (defun org-previous-link ()
9701 "Move backward to the previous link.
9702 If the link is in hidden text, expose it."
9703 (interactive)
9704 (when (and org-link-search-failed (eq this-command last-command))
9705 (goto-char (point-max))
9706 (message "Link search wrapped back to end of buffer"))
9707 (setq org-link-search-failed nil)
9708 (let* ((pos (point))
9709 (ct (org-context))
9710 (a (assoc :link ct)))
9711 (if a (goto-char (nth 1 a)))
9712 (if (re-search-backward org-any-link-re nil t)
9713 (progn
9714 (goto-char (match-beginning 0))
9715 (if (outline-invisible-p) (org-show-context)))
9716 (goto-char pos)
9717 (setq org-link-search-failed t)
9718 (error "No further link found"))))
9720 (defun org-translate-link (s)
9721 "Translate a link string if a translation function has been defined."
9722 (if (and org-link-translation-function
9723 (fboundp org-link-translation-function)
9724 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9725 (progn
9726 (setq s (funcall org-link-translation-function
9727 (match-string 1 s) (match-string 2 s)))
9728 (concat (car s) ":" (cdr s)))
9731 (defun org-translate-link-from-planner (type path)
9732 "Translate a link from Emacs Planner syntax so that Org can follow it.
9733 This is still an experimental function, your mileage may vary."
9734 (cond
9735 ((member type '("http" "https" "news" "ftp"))
9736 ;; standard Internet links are the same.
9737 nil)
9738 ((and (equal type "irc") (string-match "^//" path))
9739 ;; Planner has two / at the beginning of an irc link, we have 1.
9740 ;; We should have zero, actually....
9741 (setq path (substring path 1)))
9742 ((and (equal type "lisp") (string-match "^/" path))
9743 ;; Planner has a slash, we do not.
9744 (setq type "elisp" path (substring path 1)))
9745 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9746 ;; A typical message link. Planner has the id after the final slash,
9747 ;; we separate it with a hash mark
9748 (setq path (concat (match-string 1 path) "#"
9749 (org-remove-angle-brackets (match-string 2 path)))))
9751 (cons type path))
9753 (defun org-find-file-at-mouse (ev)
9754 "Open file link or URL at mouse."
9755 (interactive "e")
9756 (mouse-set-point ev)
9757 (org-open-at-point 'in-emacs))
9759 (defun org-open-at-mouse (ev)
9760 "Open file link or URL at mouse.
9761 See the docstring of `org-open-file' for details."
9762 (interactive "e")
9763 (mouse-set-point ev)
9764 (if (eq major-mode 'org-agenda-mode)
9765 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9766 (org-open-at-point))
9768 (defvar org-window-config-before-follow-link nil
9769 "The window configuration before following a link.
9770 This is saved in case the need arises to restore it.")
9772 (defvar org-open-link-marker (make-marker)
9773 "Marker pointing to the location where `org-open-at-point; was called.")
9775 ;;;###autoload
9776 (defun org-open-at-point-global ()
9777 "Follow a link like Org-mode does.
9778 This command can be called in any mode to follow a link that has
9779 Org-mode syntax."
9780 (interactive)
9781 (org-run-like-in-org-mode 'org-open-at-point))
9783 ;;;###autoload
9784 (defun org-open-link-from-string (s &optional arg reference-buffer)
9785 "Open a link in the string S, as if it was in Org-mode."
9786 (interactive "sLink: \nP")
9787 (let ((reference-buffer (or reference-buffer (current-buffer))))
9788 (with-temp-buffer
9789 (let ((org-inhibit-startup (not reference-buffer)))
9790 (org-mode)
9791 (insert s)
9792 (goto-char (point-min))
9793 (when reference-buffer
9794 (setq org-link-abbrev-alist-local
9795 (with-current-buffer reference-buffer
9796 org-link-abbrev-alist-local)))
9797 (org-open-at-point arg reference-buffer)))))
9799 (defvar org-open-at-point-functions nil
9800 "Hook that is run when following a link at point.
9802 Functions in this hook must return t if they identify and follow
9803 a link at point. If they don't find anything interesting at point,
9804 they must return nil.")
9806 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9807 (defun org-open-at-point (&optional arg reference-buffer)
9808 "Open link at or after point.
9809 If there is no link at point, this function will search forward up to
9810 the end of the current line.
9811 Normally, files will be opened by an appropriate application. If the
9812 optional prefix argument ARG is non-nil, Emacs will visit the file.
9813 With a double prefix argument, try to open outside of Emacs, in the
9814 application the system uses for this file type."
9815 (interactive "P")
9816 ;; if in a code block, then open the block's results
9817 (unless (call-interactively #'org-babel-open-src-block-result)
9818 (org-load-modules-maybe)
9819 (move-marker org-open-link-marker (point))
9820 (setq org-window-config-before-follow-link (current-window-configuration))
9821 (org-remove-occur-highlights nil nil t)
9822 (cond
9823 ((and (org-at-heading-p)
9824 (not (org-at-timestamp-p t))
9825 (not (org-in-regexp
9826 (concat org-plain-link-re "\\|"
9827 org-bracket-link-regexp "\\|"
9828 org-angle-link-re "\\|"
9829 "[ \t]:[^ \t\n]+:[ \t]*$")))
9830 (not (get-text-property (point) 'org-linked-text)))
9831 (or (org-offer-links-in-entry arg)
9832 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9833 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9834 ((and (org-at-timestamp-p t)
9835 (not (org-in-regexp org-bracket-link-regexp)))
9836 (org-follow-timestamp-link))
9837 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9838 (not (org-in-regexp org-any-link-re)))
9839 (org-footnote-action))
9841 (let (type path link line search (pos (point)))
9842 (catch 'match
9843 (save-excursion
9844 (skip-chars-forward "^]\n\r")
9845 (when (org-in-regexp org-bracket-link-regexp 1)
9846 (setq link (org-extract-attributes
9847 (org-link-unescape (org-match-string-no-properties 1))))
9848 (while (string-match " *\n *" link)
9849 (setq link (replace-match " " t t link)))
9850 (setq link (org-link-expand-abbrev link))
9851 (cond
9852 ((or (file-name-absolute-p link)
9853 (string-match "^\\.\\.?/" link))
9854 (setq type "file" path link))
9855 ((string-match org-link-re-with-space3 link)
9856 (setq type (match-string 1 link) path (match-string 2 link)))
9857 ((string-match "^help:+\\(.+\\)" link)
9858 (setq type "help" path (match-string 1 link)))
9859 (t (setq type "thisfile" path link)))
9860 (throw 'match t)))
9862 (when (get-text-property (point) 'org-linked-text)
9863 (setq type "thisfile"
9864 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9865 (1+ (point)) (point))
9866 path (buffer-substring
9867 (or (previous-single-property-change pos 'org-linked-text)
9868 (point-min))
9869 (or (next-single-property-change pos 'org-linked-text)
9870 (point-max))))
9871 (throw 'match t))
9873 (save-excursion
9874 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9875 (when (or (org-in-regexp org-angle-link-re)
9876 (and plinkpos (goto-char (car plinkpos))
9877 (save-match-data (not (looking-back "\\[\\[")))))
9878 (setq type (match-string 1)
9879 path (org-link-unescape (match-string 2)))
9880 (throw 'match t))))
9881 (save-excursion
9882 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9883 (setq type "tags"
9884 path (match-string 1))
9885 (while (string-match ":" path)
9886 (setq path (replace-match "+" t t path)))
9887 (throw 'match t)))
9888 (when (org-in-regexp "<\\([^><\n]+\\)>")
9889 (setq type "tree-match"
9890 path (match-string 1))
9891 (throw 'match t)))
9892 (unless path
9893 (user-error "No link found"))
9895 ;; switch back to reference buffer
9896 ;; needed when if called in a temporary buffer through
9897 ;; org-open-link-from-string
9898 (with-current-buffer (or reference-buffer (current-buffer))
9900 ;; Remove any trailing spaces in path
9901 (if (string-match " +\\'" path)
9902 (setq path (replace-match "" t t path)))
9903 (if (and org-link-translation-function
9904 (fboundp org-link-translation-function))
9905 ;; Check if we need to translate the link
9906 (let ((tmp (funcall org-link-translation-function type path)))
9907 (setq type (car tmp) path (cdr tmp))))
9909 (cond
9911 ((assoc type org-link-protocols)
9912 (funcall (nth 1 (assoc type org-link-protocols)) path))
9914 ((equal type "help")
9915 (let ((f-or-v (intern path)))
9916 (cond ((fboundp f-or-v)
9917 (describe-function f-or-v))
9918 ((boundp f-or-v)
9919 (describe-variable f-or-v))
9920 (t (error "Not a known function or variable")))))
9922 ((equal type "mailto")
9923 (let ((cmd (car org-link-mailto-program))
9924 (args (cdr org-link-mailto-program)) args1
9925 (address path) (subject "") a)
9926 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9927 (setq address (match-string 1 path)
9928 subject (org-link-escape (match-string 2 path))))
9929 (while args
9930 (cond
9931 ((not (stringp (car args))) (push (pop args) args1))
9932 (t (setq a (pop args))
9933 (if (string-match "%a" a)
9934 (setq a (replace-match address t t a)))
9935 (if (string-match "%s" a)
9936 (setq a (replace-match subject t t a)))
9937 (push a args1))))
9938 (apply cmd (nreverse args1))))
9940 ((member type '("http" "https" "ftp" "news"))
9941 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9942 (org-link-escape
9943 path org-link-escape-chars-browser)
9944 path))))
9946 ((string= type "doi")
9947 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9948 (org-link-escape
9949 path org-link-escape-chars-browser)
9950 path))))
9952 ((member type '("message"))
9953 (browse-url (concat type ":" path)))
9955 ((string= type "tags")
9956 (org-tags-view arg path))
9958 ((string= type "tree-match")
9959 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9961 ((string= type "file")
9962 (if (string-match "::\\([0-9]+\\)\\'" path)
9963 (setq line (string-to-number (match-string 1 path))
9964 path (substring path 0 (match-beginning 0)))
9965 (if (string-match "::\\(.+\\)\\'" path)
9966 (setq search (match-string 1 path)
9967 path (substring path 0 (match-beginning 0)))))
9968 (if (string-match "[*?{]" (file-name-nondirectory path))
9969 (dired path)
9970 (org-open-file path arg line search)))
9972 ((string= type "shell")
9973 (let ((buf (generate-new-buffer "*Org Shell Output"))
9974 (cmd path))
9975 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9976 (string-match org-confirm-shell-link-not-regexp cmd))
9977 (not org-confirm-shell-link-function)
9978 (funcall org-confirm-shell-link-function
9979 (format "Execute \"%s\" in shell? "
9980 (org-add-props cmd nil
9981 'face 'org-warning))))
9982 (progn
9983 (message "Executing %s" cmd)
9984 (shell-command cmd buf)
9985 (if (featurep 'midnight)
9986 (setq clean-buffer-list-kill-buffer-names
9987 (cons buf clean-buffer-list-kill-buffer-names))))
9988 (error "Abort"))))
9990 ((string= type "elisp")
9991 (let ((cmd path))
9992 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9993 (string-match org-confirm-elisp-link-not-regexp cmd))
9994 (not org-confirm-elisp-link-function)
9995 (funcall org-confirm-elisp-link-function
9996 (format "Execute \"%s\" as elisp? "
9997 (org-add-props cmd nil
9998 'face 'org-warning))))
9999 (message "%s => %s" cmd
10000 (if (equal (string-to-char cmd) ?\()
10001 (eval (read cmd))
10002 (call-interactively (read cmd))))
10003 (error "Abort"))))
10005 ((and (string= type "thisfile")
10006 (run-hook-with-args-until-success
10007 'org-open-link-functions path)))
10009 ((string= type "thisfile")
10010 (if arg
10011 (switch-to-buffer-other-window
10012 (org-get-buffer-for-internal-link (current-buffer)))
10013 (org-mark-ring-push))
10014 (let ((cmd `(org-link-search
10015 ,path
10016 ,(cond ((equal arg '(4)) ''occur)
10017 ((equal arg '(16)) ''org-occur))
10018 ,pos)))
10019 (condition-case nil (let ((org-link-search-inhibit-query t))
10020 (eval cmd))
10021 (error (progn (widen) (eval cmd))))))
10023 (t (browse-url-at-point)))))))
10024 (move-marker org-open-link-marker nil)
10025 (run-hook-with-args 'org-follow-link-hook)))
10027 (defun org-offer-links-in-entry (&optional nth zero)
10028 "Offer links in the current entry and follow the selected link.
10029 If there is only one link, follow it immediately as well.
10030 If NTH is an integer, immediately pick the NTH link found.
10031 If ZERO is a string, check also this string for a link, and if
10032 there is one, offer it as link number zero."
10033 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10034 "\\(" org-angle-link-re "\\)\\|"
10035 "\\(" org-plain-link-re "\\)"))
10036 (cnt ?0)
10037 (in-emacs (if (integerp nth) nil nth))
10038 have-zero end links link c)
10039 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10040 (push (match-string 0 zero) links)
10041 (setq cnt (1- cnt) have-zero t))
10042 (save-excursion
10043 (org-back-to-heading t)
10044 (setq end (save-excursion (outline-next-heading) (point)))
10045 (while (re-search-forward re end t)
10046 (push (match-string 0) links))
10047 (setq links (org-uniquify (reverse links))))
10049 (cond
10050 ((null links)
10051 (message "No links"))
10052 ((equal (length links) 1)
10053 (setq link (list (car links))))
10054 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10055 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10056 (t ; we have to select a link
10057 (save-excursion
10058 (save-window-excursion
10059 (delete-other-windows)
10060 (with-output-to-temp-buffer "*Select Link*"
10061 (mapc (lambda (l)
10062 (if (not (string-match org-bracket-link-regexp l))
10063 (princ (format "[%c] %s\n" (incf cnt)
10064 (org-remove-angle-brackets l)))
10065 (if (match-end 3)
10066 (princ (format "[%c] %s (%s)\n" (incf cnt)
10067 (match-string 3 l) (match-string 1 l)))
10068 (princ (format "[%c] %s\n" (incf cnt)
10069 (match-string 1 l))))))
10070 links))
10071 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10072 (message "Select link to open, RET to open all:")
10073 (setq c (read-char-exclusive))
10074 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10075 (when (equal c ?q) (error "Abort"))
10076 (if (equal c ?\C-m)
10077 (setq link links)
10078 (setq nth (- c ?0))
10079 (if have-zero (setq nth (1+ nth)))
10080 (unless (and (integerp nth) (>= (length links) nth))
10081 (error "Invalid link selection"))
10082 (setq link (list (nth (1- nth) links))))))
10083 (if link
10084 (let ((buf (current-buffer)))
10085 (dolist (l link)
10086 (org-open-link-from-string l in-emacs buf))
10088 nil)))
10090 ;; Add special file links that specify the way of opening
10092 (org-add-link-type "file+sys" 'org-open-file-with-system)
10093 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10094 (defun org-open-file-with-system (path)
10095 "Open file at PATH using the system way of opening it."
10096 (org-open-file path 'system))
10097 (defun org-open-file-with-emacs (path)
10098 "Open file at PATH in Emacs."
10099 (org-open-file path 'emacs))
10100 (defun org-remove-file-link-modifiers ()
10101 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10102 (goto-char (point-min))
10103 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10104 (org-if-unprotected
10105 (replace-match "file:" t t))))
10106 (eval-after-load "org-exp"
10107 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10108 'org-remove-file-link-modifiers))
10110 ;;;; Time estimates
10112 (defun org-get-effort (&optional pom)
10113 "Get the effort estimate for the current entry."
10114 (org-entry-get pom org-effort-property))
10116 ;;; File search
10118 (defvar org-create-file-search-functions nil
10119 "List of functions to construct the right search string for a file link.
10120 These functions are called in turn with point at the location to
10121 which the link should point.
10123 A function in the hook should first test if it would like to
10124 handle this file type, for example by checking the `major-mode'
10125 or the file extension. If it decides not to handle this file, it
10126 should just return nil to give other functions a chance. If it
10127 does handle the file, it must return the search string to be used
10128 when following the link. The search string will be part of the
10129 file link, given after a double colon, and `org-open-at-point'
10130 will automatically search for it. If special measures must be
10131 taken to make the search successful, another function should be
10132 added to the companion hook `org-execute-file-search-functions',
10133 which see.
10135 A function in this hook may also use `setq' to set the variable
10136 `description' to provide a suggestion for the descriptive text to
10137 be used for this link when it gets inserted into an Org-mode
10138 buffer with \\[org-insert-link].")
10140 (defvar org-execute-file-search-functions nil
10141 "List of functions to execute a file search triggered by a link.
10143 Functions added to this hook must accept a single argument, the
10144 search string that was part of the file link, the part after the
10145 double colon. The function must first check if it would like to
10146 handle this search, for example by checking the `major-mode' or
10147 the file extension. If it decides not to handle this search, it
10148 should just return nil to give other functions a chance. If it
10149 does handle the search, it must return a non-nil value to keep
10150 other functions from trying.
10152 Each function can access the current prefix argument through the
10153 variable `current-prefix-argument'. Note that a single prefix is
10154 used to force opening a link in Emacs, so it may be good to only
10155 use a numeric or double prefix to guide the search function.
10157 In case this is needed, a function in this hook can also restore
10158 the window configuration before `org-open-at-point' was called using:
10160 (set-window-configuration org-window-config-before-follow-link)")
10162 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10163 (defun org-link-search (s &optional type avoid-pos stealth)
10164 "Search for a link search option.
10165 If S is surrounded by forward slashes, it is interpreted as a
10166 regular expression. In org-mode files, this will create an `org-occur'
10167 sparse tree. In ordinary files, `occur' will be used to list matches.
10168 If the current buffer is in `dired-mode', grep will be used to search
10169 in all files. If AVOID-POS is given, ignore matches near that position.
10171 When optional argument STEALTH is non-nil, do not modify
10172 visibility around point, thus ignoring
10173 `org-show-hierarchy-above', `org-show-following-heading' and
10174 `org-show-siblings' variables."
10175 (let ((case-fold-search t)
10176 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10177 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10178 (append '(("") (" ") ("\t") ("\n"))
10179 org-emphasis-alist)
10180 "\\|") "\\)"))
10181 (pos (point))
10182 (pre nil) (post nil)
10183 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10184 (cond
10185 ;; First check if there are any special search functions
10186 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10187 ;; Now try the builtin stuff
10188 ((and (equal (string-to-char s0) ?#)
10189 (> (length s0) 1)
10190 (save-excursion
10191 (goto-char (point-min))
10192 (and
10193 (re-search-forward
10194 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10195 (setq type 'dedicated
10196 pos (match-beginning 0))))
10197 ;; There is an exact target for this
10198 (goto-char pos)
10199 (org-back-to-heading t)))
10200 ((save-excursion
10201 (goto-char (point-min))
10202 (and
10203 (re-search-forward
10204 (concat "<<" (regexp-quote s0) ">>") nil t)
10205 (setq type 'dedicated
10206 pos (match-beginning 0))))
10207 ;; There is an exact target for this
10208 (goto-char pos))
10209 ((save-excursion
10210 (goto-char (point-min))
10211 (and
10212 (re-search-forward
10213 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10214 (setq type 'dedicated pos (match-beginning 0))))
10215 ;; Found an invisible target.
10216 (goto-char pos))
10217 ((save-excursion
10218 (goto-char (point-min))
10219 (and
10220 (re-search-forward
10221 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10222 (setq type 'dedicated pos (match-beginning 0))))
10223 ;; Found an element with a matching #+name affiliated keyword.
10224 (goto-char pos))
10225 ((and (string-match "^(\\(.*\\))$" s0)
10226 (save-excursion
10227 (goto-char (point-min))
10228 (and
10229 (re-search-forward
10230 (concat "[^[]" (regexp-quote
10231 (format org-coderef-label-format
10232 (match-string 1 s0))))
10233 nil t)
10234 (setq type 'dedicated
10235 pos (1+ (match-beginning 0))))))
10236 ;; There is a coderef target for this
10237 (goto-char pos))
10238 ((string-match "^/\\(.*\\)/$" s)
10239 ;; A regular expression
10240 (cond
10241 ((derived-mode-p 'org-mode)
10242 (org-occur (match-string 1 s)))
10243 ;;((eq major-mode 'dired-mode)
10244 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10245 (t (org-do-occur (match-string 1 s)))))
10246 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10247 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10248 (goto-char (point-min))
10249 (cond
10250 ((let (case-fold-search)
10251 (re-search-forward (format org-complex-heading-regexp-format
10252 (regexp-quote s))
10253 nil t))
10254 ;; OK, found a match
10255 (setq type 'dedicated)
10256 (goto-char (match-beginning 0)))
10257 ((and (not org-link-search-inhibit-query)
10258 (eq org-link-search-must-match-exact-headline 'query-to-create)
10259 (y-or-n-p "No match - create this as a new heading? "))
10260 (goto-char (point-max))
10261 (or (bolp) (newline))
10262 (insert "* " s "\n")
10263 (beginning-of-line 0))
10265 (goto-char pos)
10266 (error "No match"))))
10268 ;; A normal search string
10269 (when (equal (string-to-char s) ?*)
10270 ;; Anchor on headlines, post may include tags.
10271 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10272 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10273 s (substring s 1)))
10274 (remove-text-properties
10275 0 (length s)
10276 '(face nil mouse-face nil keymap nil fontified nil) s)
10277 ;; Make a series of regular expressions to find a match
10278 (setq words (org-split-string s "[ \n\r\t]+")
10280 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10281 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10282 "\\)" markers)
10283 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10284 re2a (concat "[ \t\r\n]" re2a_)
10285 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10286 re4 (concat "[^a-zA-Z_]" re4_)
10288 re1 (concat pre re2 post)
10289 re3 (concat pre (if pre re4_ re4) post)
10290 re5 (concat pre ".*" re4)
10291 re2 (concat pre re2)
10292 re2a (concat pre (if pre re2a_ re2a))
10293 re4 (concat pre (if pre re4_ re4))
10294 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10295 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10296 re5 "\\)"
10298 (cond
10299 ((eq type 'org-occur) (org-occur reall))
10300 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10301 (t (goto-char (point-min))
10302 (setq type 'fuzzy)
10303 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10304 (org-search-not-self 1 re1 nil t)
10305 (org-search-not-self 1 re2 nil t)
10306 (org-search-not-self 1 re2a nil t)
10307 (org-search-not-self 1 re3 nil t)
10308 (org-search-not-self 1 re4 nil t)
10309 (org-search-not-self 1 re5 nil t)
10311 (goto-char (match-beginning 1))
10312 (goto-char pos)
10313 (error "No match"))))))
10314 (and (derived-mode-p 'org-mode)
10315 (not stealth)
10316 (org-show-context 'link-search))
10317 type))
10319 (defun org-search-not-self (group &rest args)
10320 "Execute `re-search-forward', but only accept matches that do not
10321 enclose the position of `org-open-link-marker'."
10322 (let ((m org-open-link-marker))
10323 (catch 'exit
10324 (while (apply 're-search-forward args)
10325 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10326 (goto-char (match-end group))
10327 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10328 (> (match-beginning 0) (marker-position m))
10329 (< (match-end 0) (marker-position m)))
10330 (save-match-data
10331 (or (not (org-in-regexp
10332 org-bracket-link-analytic-regexp 1))
10333 (not (match-end 4)) ; no description
10334 (and (<= (match-beginning 4) (point))
10335 (>= (match-end 4) (point))))))
10336 (throw 'exit (point))))))))
10338 (defun org-get-buffer-for-internal-link (buffer)
10339 "Return a buffer to be used for displaying the link target of internal links."
10340 (cond
10341 ((not org-display-internal-link-with-indirect-buffer)
10342 buffer)
10343 ((string-match "(Clone)$" (buffer-name buffer))
10344 (message "Buffer is already a clone, not making another one")
10345 ;; we also do not modify visibility in this case
10346 buffer)
10347 (t ; make a new indirect buffer for displaying the link
10348 (let* ((bn (buffer-name buffer))
10349 (ibn (concat bn "(Clone)"))
10350 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10351 (with-current-buffer ib (org-overview))
10352 ib))))
10354 (defun org-do-occur (regexp &optional cleanup)
10355 "Call the Emacs command `occur'.
10356 If CLEANUP is non-nil, remove the printout of the regular expression
10357 in the *Occur* buffer. This is useful if the regex is long and not useful
10358 to read."
10359 (occur regexp)
10360 (when cleanup
10361 (let ((cwin (selected-window)) win beg end)
10362 (when (setq win (get-buffer-window "*Occur*"))
10363 (select-window win))
10364 (goto-char (point-min))
10365 (when (re-search-forward "match[a-z]+" nil t)
10366 (setq beg (match-end 0))
10367 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10368 (setq end (1- (match-beginning 0)))))
10369 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10370 (goto-char (point-min))
10371 (select-window cwin))))
10373 ;;; The mark ring for links jumps
10375 (defvar org-mark-ring nil
10376 "Mark ring for positions before jumps in Org-mode.")
10377 (defvar org-mark-ring-last-goto nil
10378 "Last position in the mark ring used to go back.")
10379 ;; Fill and close the ring
10380 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10381 (loop for i from 1 to org-mark-ring-length do
10382 (push (make-marker) org-mark-ring))
10383 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10384 org-mark-ring)
10386 (defun org-mark-ring-push (&optional pos buffer)
10387 "Put the current position or POS into the mark ring and rotate it."
10388 (interactive)
10389 (setq pos (or pos (point)))
10390 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10391 (move-marker (car org-mark-ring)
10392 (or pos (point))
10393 (or buffer (current-buffer)))
10394 (message "%s"
10395 (substitute-command-keys
10396 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10398 (defun org-mark-ring-goto (&optional n)
10399 "Jump to the previous position in the mark ring.
10400 With prefix arg N, jump back that many stored positions. When
10401 called several times in succession, walk through the entire ring.
10402 Org-mode commands jumping to a different position in the current file,
10403 or to another Org-mode file, automatically push the old position
10404 onto the ring."
10405 (interactive "p")
10406 (let (p m)
10407 (if (eq last-command this-command)
10408 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10409 (setq p org-mark-ring))
10410 (setq org-mark-ring-last-goto p)
10411 (setq m (car p))
10412 (org-pop-to-buffer-same-window (marker-buffer m))
10413 (goto-char m)
10414 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10416 (defun org-remove-angle-brackets (s)
10417 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10418 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10420 (defun org-add-angle-brackets (s)
10421 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10422 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10424 (defun org-remove-double-quotes (s)
10425 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10426 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10429 ;;; Following specific links
10431 (defun org-follow-timestamp-link ()
10432 "Open an agenda view for the time-stamp date/range at point."
10433 (cond
10434 ((org-at-date-range-p t)
10435 (let ((org-agenda-start-on-weekday)
10436 (t1 (match-string 1))
10437 (t2 (match-string 2)) tt1 tt2)
10438 (setq tt1 (time-to-days (org-time-string-to-time t1))
10439 tt2 (time-to-days (org-time-string-to-time t2)))
10440 (let ((org-agenda-buffer-tmp-name
10441 (format "*Org Agenda(a:%s)"
10442 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10443 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10444 ((org-at-timestamp-p t)
10445 (let ((org-agenda-buffer-tmp-name
10446 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10447 (org-agenda-list nil (time-to-days (org-time-string-to-time
10448 (substring (match-string 1) 0 10)))
10449 1)))
10450 (t (error "This should not happen"))))
10453 ;;; Following file links
10454 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10455 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10456 (declare-function mailcap-mime-info
10457 "mailcap" (string &optional request no-decode))
10458 (defvar org-wait nil)
10459 (defun org-open-file (path &optional in-emacs line search)
10460 "Open the file at PATH.
10461 First, this expands any special file name abbreviations. Then the
10462 configuration variable `org-file-apps' is checked if it contains an
10463 entry for this file type, and if yes, the corresponding command is launched.
10465 If no application is found, Emacs simply visits the file.
10467 With optional prefix argument IN-EMACS, Emacs will visit the file.
10468 With a double \\[universal-argument] \\[universal-argument] \
10469 prefix arg, Org tries to avoid opening in Emacs
10470 and to use an external application to visit the file.
10472 Optional LINE specifies a line to go to, optional SEARCH a string
10473 to search for. If LINE or SEARCH is given, the file will be
10474 opened in Emacs, unless an entry from org-file-apps that makes
10475 use of groups in a regexp matches.
10477 If you want to change the way frames are used when following a
10478 link, please customize `org-link-frame-setup'.
10480 If the file does not exist, an error is thrown."
10481 (let* ((file (if (equal path "")
10482 buffer-file-name
10483 (substitute-in-file-name (expand-file-name path))))
10484 (file-apps (append org-file-apps (org-default-apps)))
10485 (apps (org-remove-if
10486 'org-file-apps-entry-match-against-dlink-p file-apps))
10487 (apps-dlink (org-remove-if-not
10488 'org-file-apps-entry-match-against-dlink-p file-apps))
10489 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10490 (dirp (if remp nil (file-directory-p file)))
10491 (file (if (and dirp org-open-directory-means-index-dot-org)
10492 (concat (file-name-as-directory file) "index.org")
10493 file))
10494 (a-m-a-p (assq 'auto-mode apps))
10495 (dfile (downcase file))
10496 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10497 (link (cond ((and (eq line nil)
10498 (eq search nil))
10499 file)
10500 (line
10501 (concat file "::" (number-to-string line)))
10502 (search
10503 (concat file "::" search))))
10504 (dlink (downcase link))
10505 (old-buffer (current-buffer))
10506 (old-pos (point))
10507 (old-mode major-mode)
10508 ext cmd link-match-data)
10509 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10510 (setq ext (match-string 1 dfile))
10511 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10512 (setq ext (match-string 1 dfile))))
10513 (cond
10514 ((member in-emacs '((16) system))
10515 (setq cmd (cdr (assoc 'system apps))))
10516 (in-emacs (setq cmd 'emacs))
10518 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10519 (and dirp (cdr (assoc 'directory apps)))
10520 ; first, try matching against apps-dlink
10521 ; if we get a match here, store the match data for later
10522 (let ((match (assoc-default dlink apps-dlink
10523 'string-match)))
10524 (if match
10525 (progn (setq link-match-data (match-data))
10526 match)
10527 (progn (setq in-emacs (or in-emacs line search))
10528 nil))) ; if we have no match in apps-dlink,
10529 ; always open the file in emacs if line or search
10530 ; is given (for backwards compatibility)
10531 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10532 'string-match)
10533 (cdr (assoc ext apps))
10534 (cdr (assoc t apps))))))
10535 (when (eq cmd 'system)
10536 (setq cmd (cdr (assoc 'system apps))))
10537 (when (eq cmd 'default)
10538 (setq cmd (cdr (assoc t apps))))
10539 (when (eq cmd 'mailcap)
10540 (require 'mailcap)
10541 (mailcap-parse-mailcaps)
10542 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10543 (command (mailcap-mime-info mime-type)))
10544 (if (stringp command)
10545 (setq cmd command)
10546 (setq cmd 'emacs))))
10547 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10548 (not (file-exists-p file))
10549 (not org-open-non-existing-files))
10550 (error "No such file: %s" file))
10551 (cond
10552 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10553 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10554 (while (string-match "['\"]%s['\"]" cmd)
10555 (setq cmd (replace-match "%s" t t cmd)))
10556 (while (string-match "%s" cmd)
10557 (setq cmd (replace-match
10558 (save-match-data
10559 (shell-quote-argument
10560 (convert-standard-filename file)))
10561 t t cmd)))
10563 ;; Replace "%1", "%2" etc. in command with group matches from regex
10564 (save-match-data
10565 (let ((match-index 1)
10566 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10567 (set-match-data link-match-data)
10568 (while (<= match-index number-of-groups)
10569 (let ((regex (concat "%" (number-to-string match-index)))
10570 (replace-with (match-string match-index dlink)))
10571 (while (string-match regex cmd)
10572 (setq cmd (replace-match replace-with t t cmd))))
10573 (setq match-index (+ match-index 1)))))
10575 (save-window-excursion
10576 (message "Running %s...done" cmd)
10577 (start-process-shell-command cmd nil cmd)
10578 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10579 ((or (stringp cmd)
10580 (eq cmd 'emacs))
10581 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10582 (widen)
10583 (if line (org-goto-line line)
10584 (if search (org-link-search search))))
10585 ((consp cmd)
10586 (let ((file (convert-standard-filename file)))
10587 (save-match-data
10588 (set-match-data link-match-data)
10589 (eval cmd))))
10590 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10591 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10592 (or (not (equal old-buffer (current-buffer)))
10593 (not (equal old-pos (point))))
10594 (org-mark-ring-push old-pos old-buffer))))
10596 (defun org-file-apps-entry-match-against-dlink-p (entry)
10597 "This function returns non-nil if `entry' uses a regular
10598 expression which should be matched against the whole link by
10599 org-open-file.
10601 It assumes that is the case when the entry uses a regular
10602 expression which has at least one grouping construct and the
10603 action is either a lisp form or a command string containing
10604 '%1', i.e. using at least one subexpression match as a
10605 parameter."
10606 (let ((selector (car entry))
10607 (action (cdr entry)))
10608 (if (stringp selector)
10609 (and (> (regexp-opt-depth selector) 0)
10610 (or (and (stringp action)
10611 (string-match "%[0-9]" action))
10612 (consp action)))
10613 nil)))
10615 (defun org-default-apps ()
10616 "Return the default applications for this operating system."
10617 (cond
10618 ((eq system-type 'darwin)
10619 org-file-apps-defaults-macosx)
10620 ((eq system-type 'windows-nt)
10621 org-file-apps-defaults-windowsnt)
10622 (t org-file-apps-defaults-gnu)))
10624 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10625 "Convert extensions to regular expressions in the cars of LIST.
10626 Also, weed out any non-string entries, because the return value is used
10627 only for regexp matching.
10628 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10629 point to the symbol `emacs', indicating that the file should
10630 be opened in Emacs."
10631 (append
10632 (delq nil
10633 (mapcar (lambda (x)
10634 (if (not (stringp (car x)))
10636 (if (string-match "\\W" (car x))
10638 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10639 list))
10640 (if add-auto-mode
10641 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10643 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10644 (defun org-file-remote-p (file)
10645 "Test whether FILE specifies a location on a remote system.
10646 Return non-nil if the location is indeed remote.
10648 For example, the filename \"/user@host:/foo\" specifies a location
10649 on the system \"/user@host:\"."
10650 (cond ((fboundp 'file-remote-p)
10651 (file-remote-p file))
10652 ((fboundp 'tramp-handle-file-remote-p)
10653 (tramp-handle-file-remote-p file))
10654 ((and (boundp 'ange-ftp-name-format)
10655 (string-match (car ange-ftp-name-format) file))
10656 t)))
10659 ;;;; Refiling
10661 (defun org-get-org-file ()
10662 "Read a filename, with default directory `org-directory'."
10663 (let ((default (or org-default-notes-file remember-data-file)))
10664 (read-file-name (format "File name [%s]: " default)
10665 (file-name-as-directory org-directory)
10666 default)))
10668 (defun org-notes-order-reversed-p ()
10669 "Check if the current file should receive notes in reversed order."
10670 (cond
10671 ((not org-reverse-note-order) nil)
10672 ((eq t org-reverse-note-order) t)
10673 ((not (listp org-reverse-note-order)) nil)
10674 (t (catch 'exit
10675 (let ((all org-reverse-note-order)
10676 entry)
10677 (while (setq entry (pop all))
10678 (if (string-match (car entry) buffer-file-name)
10679 (throw 'exit (cdr entry))))
10680 nil)))))
10682 (defvar org-refile-target-table nil
10683 "The list of refile targets, created by `org-refile'.")
10685 (defvar org-agenda-new-buffers nil
10686 "Buffers created to visit agenda files.")
10688 (defvar org-refile-cache nil
10689 "Cache for refile targets.")
10691 (defvar org-refile-markers nil
10692 "All the markers used for caching refile locations.")
10694 (defun org-refile-marker (pos)
10695 "Get a new refile marker, but only if caching is in use."
10696 (if (not org-refile-use-cache)
10698 (let ((m (make-marker)))
10699 (move-marker m pos)
10700 (push m org-refile-markers)
10701 m)))
10703 (defun org-refile-cache-clear ()
10704 "Clear the refile cache and disable all the markers."
10705 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10706 (setq org-refile-markers nil)
10707 (setq org-refile-cache nil)
10708 (message "Refile cache has been cleared"))
10710 (defun org-refile-cache-check-set (set)
10711 "Check if all the markers in the cache still have live buffers."
10712 (let (marker)
10713 (catch 'exit
10714 (while (and set (setq marker (nth 3 (pop set))))
10715 ;; if org-refile-use-outline-path is 'file, marker may be nil
10716 (when (and marker (null (marker-buffer marker)))
10717 (message "not found") (sit-for 3)
10718 (throw 'exit nil)))
10719 t)))
10721 (defun org-refile-cache-put (set &rest identifiers)
10722 "Push the refile targets SET into the cache, under IDENTIFIERS."
10723 (let* ((key (sha1 (prin1-to-string identifiers)))
10724 (entry (assoc key org-refile-cache)))
10725 (if entry
10726 (setcdr entry set)
10727 (push (cons key set) org-refile-cache))))
10729 (defun org-refile-cache-get (&rest identifiers)
10730 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10731 (cond
10732 ((not org-refile-cache) nil)
10733 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10735 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10736 org-refile-cache))))
10737 (and set (org-refile-cache-check-set set) set)))))
10739 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10740 "Produce a table with refile targets."
10741 (let ((case-fold-search nil)
10742 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10743 (entries (or org-refile-targets '((nil . (:level . 1)))))
10744 targets tgs txt re files f desc descre fast-path-p level pos0)
10745 (message "Getting targets...")
10746 (with-current-buffer (or default-buffer (current-buffer))
10747 (while (setq entry (pop entries))
10748 (setq files (car entry) desc (cdr entry))
10749 (setq fast-path-p nil)
10750 (cond
10751 ((null files) (setq files (list (current-buffer))))
10752 ((eq files 'org-agenda-files)
10753 (setq files (org-agenda-files 'unrestricted)))
10754 ((and (symbolp files) (fboundp files))
10755 (setq files (funcall files)))
10756 ((and (symbolp files) (boundp files))
10757 (setq files (symbol-value files))))
10758 (if (stringp files) (setq files (list files)))
10759 (cond
10760 ((eq (car desc) :tag)
10761 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10762 ((eq (car desc) :todo)
10763 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10764 ((eq (car desc) :regexp)
10765 (setq descre (cdr desc)))
10766 ((eq (car desc) :level)
10767 (setq descre (concat "^\\*\\{" (number-to-string
10768 (if org-odd-levels-only
10769 (1- (* 2 (cdr desc)))
10770 (cdr desc)))
10771 "\\}[ \t]")))
10772 ((eq (car desc) :maxlevel)
10773 (setq fast-path-p t)
10774 (setq descre (concat "^\\*\\{1," (number-to-string
10775 (if org-odd-levels-only
10776 (1- (* 2 (cdr desc)))
10777 (cdr desc)))
10778 "\\}[ \t]")))
10779 (t (error "Bad refiling target description %s" desc)))
10780 (while (setq f (pop files))
10781 (with-current-buffer
10782 (if (bufferp f) f (org-get-agenda-file-buffer f))
10784 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10785 (progn
10786 (if (bufferp f) (setq f (buffer-file-name
10787 (buffer-base-buffer f))))
10788 (setq f (and f (expand-file-name f)))
10789 (if (eq org-refile-use-outline-path 'file)
10790 (push (list (file-name-nondirectory f) f nil nil) tgs))
10791 (save-excursion
10792 (save-restriction
10793 (widen)
10794 (goto-char (point-min))
10795 (while (re-search-forward descre nil t)
10796 (goto-char (setq pos0 (point-at-bol)))
10797 (catch 'next
10798 (when org-refile-target-verify-function
10799 (save-match-data
10800 (or (funcall org-refile-target-verify-function)
10801 (throw 'next t))))
10802 (when (and (looking-at org-complex-heading-regexp)
10803 (not (member (match-string 4) excluded-entries))
10804 (match-string 4))
10805 (setq level (org-reduced-level
10806 (- (match-end 1) (match-beginning 1)))
10807 txt (org-link-display-format (match-string 4))
10808 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10809 re (format org-complex-heading-regexp-format
10810 (regexp-quote (match-string 4))))
10811 (when org-refile-use-outline-path
10812 (setq txt (mapconcat
10813 'org-protect-slash
10814 (append
10815 (if (eq org-refile-use-outline-path
10816 'file)
10817 (list (file-name-nondirectory
10818 (buffer-file-name
10819 (buffer-base-buffer))))
10820 (if (eq org-refile-use-outline-path
10821 'full-file-path)
10822 (list (buffer-file-name
10823 (buffer-base-buffer)))))
10824 (org-get-outline-path fast-path-p
10825 level txt)
10826 (list txt))
10827 "/")))
10828 (push (list txt f re (org-refile-marker (point)))
10829 tgs)))
10830 (when (= (point) pos0)
10831 ;; verification function has not moved point
10832 (goto-char (point-at-eol))))))))
10833 (when org-refile-use-cache
10834 (org-refile-cache-put tgs (buffer-file-name) descre))
10835 (setq targets (append tgs targets))
10836 ))))
10837 (message "Getting targets...done")
10838 (nreverse targets)))
10840 (defun org-protect-slash (s)
10841 (while (string-match "/" s)
10842 (setq s (replace-match "\\" t t s)))
10845 (defvar org-olpa (make-vector 20 nil))
10847 (defun org-get-outline-path (&optional fastp level heading)
10848 "Return the outline path to the current entry, as a list.
10850 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10851 routine which makes outline path derivations for an entire file,
10852 avoiding backtracing. Refile target collection makes use of that."
10853 (if fastp
10854 (progn
10855 (if (> level 19)
10856 (error "Outline path failure, more than 19 levels"))
10857 (loop for i from level upto 19 do
10858 (aset org-olpa i nil))
10859 (prog1
10860 (delq nil (append org-olpa nil))
10861 (aset org-olpa level heading)))
10862 (let (rtn case-fold-search)
10863 (save-excursion
10864 (save-restriction
10865 (widen)
10866 (while (org-up-heading-safe)
10867 (when (looking-at org-complex-heading-regexp)
10868 (push (org-match-string-no-properties 4) rtn)))
10869 rtn)))))
10871 (defun org-format-outline-path (path &optional width prefix separator)
10872 "Format the outline path PATH for display.
10873 WIDTH is the maximum number of characters that is available.
10874 PREFIX is a prefix to be included in the returned string,
10875 such as the file name.
10876 SEPARATOR is inserted between the different parts of the path,
10877 the default is \"/\"."
10878 (setq width (or width 79))
10879 (if prefix (setq width (- width (length prefix))))
10880 (if (not path)
10881 (or prefix "")
10882 (let* ((nsteps (length path))
10883 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10884 (maxwidth (if (<= total-width width)
10885 10000 ;; everything fits
10886 ;; we need to shorten the level headings
10887 (/ (- width nsteps) nsteps)))
10888 (org-odd-levels-only nil)
10889 (n 0)
10890 (total (1+ (length prefix))))
10891 (setq maxwidth (max maxwidth 10))
10892 (concat prefix
10893 (if prefix (or separator "/"))
10894 (mapconcat
10895 (lambda (h)
10896 (setq n (1+ n))
10897 (if (and (= n nsteps) (< maxwidth 10000))
10898 (setq maxwidth (- total-width total)))
10899 (if (< (length h) maxwidth)
10900 (progn (setq total (+ total (length h) 1)) h)
10901 (setq h (substring h 0 (- maxwidth 2))
10902 total (+ total maxwidth 1))
10903 (if (string-match "[ \t]+\\'" h)
10904 (setq h (substring h 0 (match-beginning 0))))
10905 (setq h (concat h "..")))
10906 (org-add-props h nil 'face
10907 (nth (% (1- n) org-n-level-faces)
10908 org-level-faces))
10910 path (or separator "/"))))))
10912 (defun org-display-outline-path (&optional file current separator just-return-string)
10913 "Display the current outline path in the echo area.
10915 If FILE is non-nil, prepend the output with the file name.
10916 If CURRENT is non-nil, append the current heading to the output.
10917 SEPARATOR is passed through to `org-format-outline-path'. It separates
10918 the different parts of the path and defaults to \"/\".
10919 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10920 (interactive "P")
10921 (let* (case-fold-search
10922 message-log-max ; Don't populate the *Messages* buffer
10923 (bfn (buffer-file-name (buffer-base-buffer)))
10924 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10925 res)
10926 (if current (setq path (append path
10927 (save-excursion
10928 (org-back-to-heading t)
10929 (if (looking-at org-complex-heading-regexp)
10930 (list (match-string 4)))))))
10931 (setq res
10932 (org-format-outline-path
10933 path
10934 (1- (frame-width))
10935 (and file bfn (concat (file-name-nondirectory bfn) separator))
10936 separator))
10937 (if just-return-string
10938 (org-no-properties res)
10939 (message "%s" res))))
10941 (defvar org-refile-history nil
10942 "History for refiling operations.")
10944 (defvar org-after-refile-insert-hook nil
10945 "Hook run after `org-refile' has inserted its stuff at the new location.
10946 Note that this is still *before* the stuff will be removed from
10947 the *old* location.")
10949 (defvar org-capture-last-stored-marker)
10950 (defvar org-refile-keep nil
10951 "Non-nil means `org-refile' will copy instead of refile.")
10953 (defun org-copy ()
10954 "Like `org-refile', but copy."
10955 (interactive)
10956 (let ((org-refile-keep t))
10957 (funcall 'org-refile nil nil nil "Copy")))
10959 (defun org-refile (&optional goto default-buffer rfloc msg)
10960 "Move the entry or entries at point to another heading.
10961 The list of target headings is compiled using the information in
10962 `org-refile-targets', which see.
10964 At the target location, the entry is filed as a subitem of the target
10965 heading. Depending on `org-reverse-note-order', the new subitem will
10966 either be the first or the last subitem.
10968 If there is an active region, all entries in that region will be moved.
10969 However, the region must fulfill the requirement that the first heading
10970 is the first one sets the top-level of the moved text - at most siblings
10971 below it are allowed.
10973 With prefix arg GOTO, the command will only visit the target location
10974 and not actually move anything.
10976 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10977 go to the location where the last refiling operation has put the subtree.
10978 With a prefix argument of `2', refile to the running clock.
10980 RFLOC can be a refile location obtained in a different way.
10982 MSG is a string to replace \"Refile\" in the default prompt with
10983 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
10985 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10987 If you are using target caching (see `org-refile-use-cache'),
10988 you have to clear the target cache in order to find new targets.
10989 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10990 prefix argument (`C-u C-u C-u C-c C-w')."
10992 (interactive "P")
10993 (if (member goto '(0 (64)))
10994 (org-refile-cache-clear)
10995 (let* ((actionmsg (or msg "Refile"))
10996 (cbuf (current-buffer))
10997 (regionp (org-region-active-p))
10998 (region-start (and regionp (region-beginning)))
10999 (region-end (and regionp (region-end)))
11000 (region-length (and regionp (- region-end region-start)))
11001 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11002 pos it nbuf file re level reversed)
11003 (setq last-command nil)
11004 (when regionp
11005 (goto-char region-start)
11006 (or (bolp) (goto-char (point-at-bol)))
11007 (setq region-start (point))
11008 (unless (or (org-kill-is-subtree-p
11009 (buffer-substring region-start region-end))
11010 (prog1 org-refile-active-region-within-subtree
11011 (org-toggle-heading)))
11012 (error "The region is not a (sequence of) subtree(s)")))
11013 (if (equal goto '(16))
11014 (org-refile-goto-last-stored)
11015 (when (or
11016 (and (equal goto 2)
11017 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11018 (prog1
11019 (setq it (list (or org-clock-heading "running clock")
11020 (buffer-file-name
11021 (marker-buffer org-clock-hd-marker))
11023 (marker-position org-clock-hd-marker)))
11024 (setq goto nil)))
11025 (setq it (or rfloc
11026 (let (heading-text)
11027 (save-excursion
11028 (unless goto
11029 (org-back-to-heading t)
11030 (setq heading-text
11031 (nth 4 (org-heading-components))))
11033 (org-refile-get-location
11034 (cond (goto "Goto")
11035 (regionp (concat actionmsg " region to"))
11036 (t (concat actionmsg " subtree \""
11037 heading-text "\" to")))
11038 default-buffer
11039 (and (not (equal '(4) goto))
11040 org-refile-allow-creating-parent-nodes)
11041 goto))))))
11042 (setq file (nth 1 it)
11043 re (nth 2 it)
11044 pos (nth 3 it))
11045 (if (and (not goto)
11047 (equal (buffer-file-name) file)
11048 (if regionp
11049 (and (>= pos region-start)
11050 (<= pos region-end))
11051 (and (>= pos (point))
11052 (< pos (save-excursion
11053 (org-end-of-subtree t t))))))
11054 (error "Cannot refile to position inside the tree or region"))
11056 (setq nbuf (or (find-buffer-visiting file)
11057 (find-file-noselect file)))
11058 (if goto
11059 (progn
11060 (org-pop-to-buffer-same-window nbuf)
11061 (goto-char pos)
11062 (org-show-context 'org-goto))
11063 (if regionp
11064 (progn
11065 (org-kill-new (buffer-substring region-start region-end))
11066 (org-save-markers-in-region region-start region-end))
11067 (org-copy-subtree 1 nil t))
11068 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11069 (find-file-noselect file)))
11070 (setq reversed (org-notes-order-reversed-p))
11071 (save-excursion
11072 (save-restriction
11073 (widen)
11074 (if pos
11075 (progn
11076 (goto-char pos)
11077 (looking-at org-outline-regexp)
11078 (setq level (org-get-valid-level (funcall outline-level) 1))
11079 (goto-char
11080 (if reversed
11081 (or (outline-next-heading) (point-max))
11082 (or (save-excursion (org-get-next-sibling))
11083 (org-end-of-subtree t t)
11084 (point-max)))))
11085 (setq level 1)
11086 (if (not reversed)
11087 (goto-char (point-max))
11088 (goto-char (point-min))
11089 (or (outline-next-heading) (goto-char (point-max)))))
11090 (if (not (bolp)) (newline))
11091 (org-paste-subtree level)
11092 (when org-log-refile
11093 (org-add-log-setup 'refile nil nil 'findpos
11094 org-log-refile)
11095 (unless (eq org-log-refile 'note)
11096 (save-excursion (org-add-log-note))))
11097 (and org-auto-align-tags
11098 (let ((org-loop-over-headlines-in-active-region nil))
11099 (org-set-tags nil t)))
11100 (with-demoted-errors
11101 (bookmark-set "org-refile-last-stored"))
11102 ;; If we are refiling for capture, make sure that the
11103 ;; last-capture pointers point here
11104 (when (org-bound-and-true-p org-refile-for-capture)
11105 (with-demoted-errors
11106 (bookmark-set "org-capture-last-stored-marker"))
11107 (move-marker org-capture-last-stored-marker (point)))
11108 (if (fboundp 'deactivate-mark) (deactivate-mark))
11109 (run-hooks 'org-after-refile-insert-hook))))
11110 (unless org-refile-keep
11111 (if regionp
11112 (delete-region (point) (+ (point) region-length))
11113 (org-cut-subtree)))
11114 (when (featurep 'org-inlinetask)
11115 (org-inlinetask-remove-END-maybe))
11116 (setq org-markers-to-move nil)
11117 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11119 (defun org-refile-goto-last-stored ()
11120 "Go to the location where the last refile was stored."
11121 (interactive)
11122 (bookmark-jump "org-refile-last-stored")
11123 (message "This is the location of the last refile"))
11125 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11126 no-exclude)
11127 "Prompt the user for a refile location, using PROMPT.
11128 PROMPT should not be suffixed with a colon and a space, because
11129 this function appends the default value from
11130 `org-refile-history' automatically, if that is not empty.
11131 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11132 this is used for the GOTO interface."
11133 (let ((org-refile-targets org-refile-targets)
11134 (org-refile-use-outline-path org-refile-use-outline-path)
11135 excluded-entries)
11136 (when (and (derived-mode-p 'org-mode)
11137 (not org-refile-use-cache)
11138 (not no-exclude))
11139 (org-map-tree
11140 (lambda()
11141 (setq excluded-entries
11142 (append excluded-entries (list (org-get-heading t t)))))))
11143 (setq org-refile-target-table
11144 (org-refile-get-targets default-buffer excluded-entries)))
11145 (unless org-refile-target-table
11146 (error "No refile targets"))
11147 (let* ((cbuf (current-buffer))
11148 (partial-completion-mode nil)
11149 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11150 (cfunc (if (and org-refile-use-outline-path
11151 org-outline-path-complete-in-steps)
11152 'org-olpath-completing-read
11153 'org-icompleting-read))
11154 (extra (if org-refile-use-outline-path "/" ""))
11155 (cbnex (concat (buffer-name) extra))
11156 (filename (and cfn (expand-file-name cfn)))
11157 (tbl (mapcar
11158 (lambda (x)
11159 (if (and (not (member org-refile-use-outline-path
11160 '(file full-file-path)))
11161 (not (equal filename (nth 1 x))))
11162 (cons (concat (car x) extra " ("
11163 (file-name-nondirectory (nth 1 x)) ")")
11164 (cdr x))
11165 (cons (concat (car x) extra) (cdr x))))
11166 org-refile-target-table))
11167 (completion-ignore-case t)
11168 cdef
11169 (prompt (concat prompt
11170 (or (and (car org-refile-history)
11171 (concat " (default " (car org-refile-history) ")"))
11172 (and (assoc cbnex tbl) (setq cdef cbnex)
11173 (concat " (default " cbnex ")"))) ": "))
11174 pa answ parent-target child parent old-hist)
11175 (setq old-hist org-refile-history)
11176 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11177 nil 'org-refile-history (or cdef (car org-refile-history))))
11178 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11179 (org-refile-check-position pa)
11180 (if pa
11181 (progn
11182 (when (or (not org-refile-history)
11183 (not (eq old-hist org-refile-history))
11184 (not (equal (car pa) (car org-refile-history))))
11185 (setq org-refile-history
11186 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11187 org-refile-history
11188 (cdr org-refile-history))))
11189 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11190 (pop org-refile-history)))
11192 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11193 (progn
11194 (setq parent (match-string 1 answ)
11195 child (match-string 2 answ))
11196 (setq parent-target (or (assoc parent tbl)
11197 (assoc (concat parent "/") tbl)))
11198 (when (and parent-target
11199 (or (eq new-nodes t)
11200 (and (eq new-nodes 'confirm)
11201 (y-or-n-p (format "Create new node \"%s\"? "
11202 child)))))
11203 (org-refile-new-child parent-target child)))
11204 (error "Invalid target location")))))
11206 (declare-function org-string-nw-p "org-macs" (s))
11207 (defun org-refile-check-position (refile-pointer)
11208 "Check if the refile pointer matches the headline to which it points."
11209 (let* ((file (nth 1 refile-pointer))
11210 (re (nth 2 refile-pointer))
11211 (pos (nth 3 refile-pointer))
11212 buffer)
11213 (if (and (not (markerp pos)) (not file))
11214 (error "Please save the buffer to a file before refiling")
11215 (when (org-string-nw-p re)
11216 (setq buffer (if (markerp pos)
11217 (marker-buffer pos)
11218 (or (find-buffer-visiting file)
11219 (find-file-noselect file))))
11220 (with-current-buffer buffer
11221 (save-excursion
11222 (save-restriction
11223 (widen)
11224 (goto-char pos)
11225 (beginning-of-line 1)
11226 (unless (org-looking-at-p re)
11227 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11229 (defun org-refile-new-child (parent-target child)
11230 "Use refile target PARENT-TARGET to add new CHILD below it."
11231 (unless parent-target
11232 (error "Cannot find parent for new node"))
11233 (let ((file (nth 1 parent-target))
11234 (pos (nth 3 parent-target))
11235 level)
11236 (with-current-buffer (or (find-buffer-visiting file)
11237 (find-file-noselect file))
11238 (save-excursion
11239 (save-restriction
11240 (widen)
11241 (if pos
11242 (goto-char pos)
11243 (goto-char (point-max))
11244 (if (not (bolp)) (newline)))
11245 (when (looking-at org-outline-regexp)
11246 (setq level (funcall outline-level))
11247 (org-end-of-subtree t t))
11248 (org-back-over-empty-lines)
11249 (insert "\n" (make-string
11250 (if pos (org-get-valid-level level 1) 1) ?*)
11251 " " child "\n")
11252 (beginning-of-line 0)
11253 (list (concat (car parent-target) "/" child) file "" (point)))))))
11255 (defun org-olpath-completing-read (prompt collection &rest args)
11256 "Read an outline path like a file name."
11257 (let ((thetable collection)
11258 (org-completion-use-ido nil) ; does not work with ido.
11259 (org-completion-use-iswitchb nil)) ; or iswitchb
11260 (apply
11261 'org-icompleting-read prompt
11262 (lambda (string predicate &optional flag)
11263 (let (rtn r f (l (length string)))
11264 (cond
11265 ((eq flag nil)
11266 ;; try completion
11267 (try-completion string thetable))
11268 ((eq flag t)
11269 ;; all-completions
11270 (setq rtn (all-completions string thetable predicate))
11271 (mapcar
11272 (lambda (x)
11273 (setq r (substring x l))
11274 (if (string-match " ([^)]*)$" x)
11275 (setq f (match-string 0 x))
11276 (setq f ""))
11277 (if (string-match "/" r)
11278 (concat string (substring r 0 (match-end 0)) f)
11280 rtn))
11281 ((eq flag 'lambda)
11282 ;; exact match?
11283 (assoc string thetable)))))
11284 args)))
11286 ;;;; Dynamic blocks
11288 (defun org-find-dblock (name)
11289 "Find the first dynamic block with name NAME in the buffer.
11290 If not found, stay at current position and return nil."
11291 (let ((case-fold-search t) pos)
11292 (save-excursion
11293 (goto-char (point-min))
11294 (setq pos (and (re-search-forward
11295 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11296 (match-beginning 0))))
11297 (if pos (goto-char pos))
11298 pos))
11300 (defconst org-dblock-start-re
11301 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11302 "Matches the start line of a dynamic block, with parameters.")
11304 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11305 "Matches the end of a dynamic block.")
11307 (defun org-create-dblock (plist)
11308 "Create a dynamic block section, with parameters taken from PLIST.
11309 PLIST must contain a :name entry which is used as name of the block."
11310 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11311 (end-of-line 1)
11312 (newline))
11313 (let ((col (current-column))
11314 (name (plist-get plist :name)))
11315 (insert "#+BEGIN: " name)
11316 (while plist
11317 (if (eq (car plist) :name)
11318 (setq plist (cddr plist))
11319 (insert " " (prin1-to-string (pop plist)))))
11320 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11321 (beginning-of-line -2)))
11323 (defun org-prepare-dblock ()
11324 "Prepare dynamic block for refresh.
11325 This empties the block, puts the cursor at the insert position and returns
11326 the property list including an extra property :name with the block name."
11327 (unless (looking-at org-dblock-start-re)
11328 (error "Not at a dynamic block"))
11329 (let* ((begdel (1+ (match-end 0)))
11330 (name (org-no-properties (match-string 1)))
11331 (params (append (list :name name)
11332 (read (concat "(" (match-string 3) ")")))))
11333 (save-excursion
11334 (beginning-of-line 1)
11335 (skip-chars-forward " \t")
11336 (setq params (plist-put params :indentation-column (current-column))))
11337 (unless (re-search-forward org-dblock-end-re nil t)
11338 (error "Dynamic block not terminated"))
11339 (setq params
11340 (append params
11341 (list :content (buffer-substring
11342 begdel (match-beginning 0)))))
11343 (delete-region begdel (match-beginning 0))
11344 (goto-char begdel)
11345 (open-line 1)
11346 params))
11348 (defun org-map-dblocks (&optional command)
11349 "Apply COMMAND to all dynamic blocks in the current buffer.
11350 If COMMAND is not given, use `org-update-dblock'."
11351 (let ((cmd (or command 'org-update-dblock)))
11352 (save-excursion
11353 (goto-char (point-min))
11354 (while (re-search-forward org-dblock-start-re nil t)
11355 (goto-char (match-beginning 0))
11356 (save-excursion
11357 (condition-case nil
11358 (funcall cmd)
11359 (error (message "Error during update of dynamic block"))))
11360 (unless (re-search-forward org-dblock-end-re nil t)
11361 (error "Dynamic block not terminated"))))))
11363 (defun org-dblock-update (&optional arg)
11364 "User command for updating dynamic blocks.
11365 Update the dynamic block at point. With prefix ARG, update all dynamic
11366 blocks in the buffer."
11367 (interactive "P")
11368 (if arg
11369 (org-update-all-dblocks)
11370 (or (looking-at org-dblock-start-re)
11371 (org-beginning-of-dblock))
11372 (org-update-dblock)))
11374 (defun org-update-dblock ()
11375 "Update the dynamic block at point.
11376 This means to empty the block, parse for parameters and then call
11377 the correct writing function."
11378 (interactive)
11379 (save-window-excursion
11380 (let* ((pos (point))
11381 (line (org-current-line))
11382 (params (org-prepare-dblock))
11383 (name (plist-get params :name))
11384 (indent (plist-get params :indentation-column))
11385 (cmd (intern (concat "org-dblock-write:" name))))
11386 (message "Updating dynamic block `%s' at line %d..." name line)
11387 (funcall cmd params)
11388 (message "Updating dynamic block `%s' at line %d...done" name line)
11389 (goto-char pos)
11390 (when (and indent (> indent 0))
11391 (setq indent (make-string indent ?\ ))
11392 (save-excursion
11393 (org-beginning-of-dblock)
11394 (forward-line 1)
11395 (while (not (looking-at org-dblock-end-re))
11396 (insert indent)
11397 (beginning-of-line 2))
11398 (when (looking-at org-dblock-end-re)
11399 (and (looking-at "[ \t]+")
11400 (replace-match ""))
11401 (insert indent)))))))
11403 (defun org-beginning-of-dblock ()
11404 "Find the beginning of the dynamic block at point.
11405 Error if there is no such block at point."
11406 (let ((pos (point))
11407 beg)
11408 (end-of-line 1)
11409 (if (and (re-search-backward org-dblock-start-re nil t)
11410 (setq beg (match-beginning 0))
11411 (re-search-forward org-dblock-end-re nil t)
11412 (> (match-end 0) pos))
11413 (goto-char beg)
11414 (goto-char pos)
11415 (error "Not in a dynamic block"))))
11417 (defun org-update-all-dblocks ()
11418 "Update all dynamic blocks in the buffer.
11419 This function can be used in a hook."
11420 (interactive)
11421 (when (derived-mode-p 'org-mode)
11422 (org-map-dblocks 'org-update-dblock)))
11425 ;;;; Completion
11427 (defconst org-additional-option-like-keywords
11428 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11429 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11430 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11431 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11432 "BEGIN:" "END:"
11433 "ORGTBL" "TBLFM:" "TBLNAME:"
11434 "BEGIN_EXAMPLE" "END_EXAMPLE"
11435 "BEGIN_VERBATIM" "END_VERBATIM"
11436 "BEGIN_QUOTE" "END_QUOTE"
11437 "BEGIN_VERSE" "END_VERSE"
11438 "BEGIN_CENTER" "END_CENTER"
11439 "BEGIN_SRC" "END_SRC"
11440 "BEGIN_RESULT" "END_RESULT"
11441 "BEGIN_lstlisting" "END_lstlisting"
11442 "NAME:" "RESULTS:"
11443 "HEADER:" "HEADERS:"
11444 "COLUMNS:" "PROPERTY:"
11445 "CAPTION:" "LABEL:"
11446 "SETUPFILE:"
11447 "INCLUDE:" "INDEX:"
11448 "BIND:"
11449 "MACRO:"))
11451 (defconst org-options-keywords
11452 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11453 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11454 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11455 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11456 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11457 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11458 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11460 (defconst org-additional-option-like-keywords-for-flyspell
11461 (delete-dups
11462 (split-string
11463 (mapconcat (lambda(k)
11464 (replace-regexp-in-string
11465 "_\\|:" " "
11466 (concat k " " (downcase k) " " (upcase k))))
11467 (append org-options-keywords org-additional-option-like-keywords)
11468 " ")
11469 " +" t)))
11471 (defcustom org-structure-template-alist
11473 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11474 "<src lang=\"?\">\n\n</src>")
11475 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11476 "<example>\n?\n</example>")
11477 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11478 "<quote>\n?\n</quote>")
11479 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11480 "<verse>\n?\n</verse>")
11481 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11482 "<center>\n?\n</center>")
11483 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11484 "<literal style=\"latex\">\n?\n</literal>")
11485 ("L" "#+LaTeX: "
11486 "<literal style=\"latex\">?</literal>")
11487 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11488 "<literal style=\"html\">\n?\n</literal>")
11489 ("H" "#+HTML: "
11490 "<literal style=\"html\">?</literal>")
11491 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11492 ("A" "#+ASCII: ")
11493 ("i" "#+INDEX: ?"
11494 "#+INDEX: ?")
11495 ("I" "#+INCLUDE: %file ?"
11496 "<include file=%file markup=\"?\">")
11498 "Structure completion elements.
11499 This is a list of abbreviation keys and values. The value gets inserted
11500 if you type `<' followed by the key and then press the completion key,
11501 usually `M-TAB'. %file will be replaced by a file name after prompting
11502 for the file using completion. The cursor will be placed at the position
11503 of the `?` in the template.
11504 There are two templates for each key, the first uses the original Org syntax,
11505 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11506 the default when the /org-mtags.el/ module has been loaded. See also the
11507 variable `org-mtags-prefer-muse-templates'."
11508 :group 'org-completion
11509 :type '(repeat
11510 (string :tag "Key")
11511 (string :tag "Template")
11512 (string :tag "Muse Template")))
11514 (defun org-try-structure-completion ()
11515 "Try to complete a structure template before point.
11516 This looks for strings like \"<e\" on an otherwise empty line and
11517 expands them."
11518 (let ((l (buffer-substring (point-at-bol) (point)))
11520 (when (and (looking-at "[ \t]*$")
11521 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11522 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11523 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11524 (match-beginning 1)) a)
11525 t)))
11527 (defun org-complete-expand-structure-template (start cell)
11528 "Expand a structure template."
11529 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11530 (rpl (nth (if musep 2 1) cell))
11531 (ind ""))
11532 (delete-region start (point))
11533 (when (string-match "\\`#\\+" rpl)
11534 (cond
11535 ((bolp))
11536 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11537 (setq ind (buffer-substring (point-at-bol) (point))))
11538 (t (newline))))
11539 (setq start (point))
11540 (if (string-match "%file" rpl)
11541 (setq rpl (replace-match
11542 (concat
11543 "\""
11544 (save-match-data
11545 (abbreviate-file-name (read-file-name "Include file: ")))
11546 "\"")
11547 t t rpl)))
11548 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11549 (concat "\n" ind)))
11550 (insert rpl)
11551 (if (re-search-backward "\\?" start t) (delete-char 1))))
11553 ;;;; TODO, DEADLINE, Comments
11555 (defun org-toggle-comment ()
11556 "Change the COMMENT state of an entry."
11557 (interactive)
11558 (save-excursion
11559 (org-back-to-heading)
11560 (let (case-fold-search)
11561 (cond
11562 ((looking-at (format org-heading-keyword-regexp-format
11563 org-comment-string))
11564 (goto-char (match-end 1))
11565 (looking-at (concat " +" org-comment-string))
11566 (replace-match "" t t)
11567 (when (eolp) (insert " ")))
11568 ((looking-at org-outline-regexp)
11569 (goto-char (match-end 0))
11570 (insert org-comment-string " "))))))
11572 (defvar org-last-todo-state-is-todo nil
11573 "This is non-nil when the last TODO state change led to a TODO state.
11574 If the last change removed the TODO tag or switched to DONE, then
11575 this is nil.")
11577 (defvar org-setting-tags nil) ; dynamically skipped
11579 (defvar org-todo-setup-filter-hook nil
11580 "Hook for functions that pre-filter todo specs.
11581 Each function takes a todo spec and returns either nil or the spec
11582 transformed into canonical form." )
11584 (defvar org-todo-get-default-hook nil
11585 "Hook for functions that get a default item for todo.
11586 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11587 nil or a string to be used for the todo mark." )
11589 (defvar org-agenda-headline-snapshot-before-repeat)
11591 (defun org-current-effective-time ()
11592 "Return current time adjusted for `org-extend-today-until' variable."
11593 (let* ((ct (org-current-time))
11594 (dct (decode-time ct))
11595 (ct1
11596 (cond
11597 (org-use-last-clock-out-time-as-effective-time
11598 (or (org-clock-get-last-clock-out-time) ct))
11599 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11600 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11601 (t ct))))
11602 ct1))
11604 (defun org-todo-yesterday (&optional arg)
11605 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11606 (interactive "P")
11607 (if (eq major-mode 'org-agenda-mode)
11608 (apply 'org-agenda-todo-yesterday arg)
11609 (let* ((hour (third (decode-time
11610 (org-current-time))))
11611 (org-extend-today-until (1+ hour)))
11612 (org-todo arg))))
11614 (defvar org-block-entry-blocking ""
11615 "First entry preventing the TODO state change.")
11617 (defun org-todo (&optional arg)
11618 "Change the TODO state of an item.
11619 The state of an item is given by a keyword at the start of the heading,
11620 like
11621 *** TODO Write paper
11622 *** DONE Call mom
11624 The different keywords are specified in the variable `org-todo-keywords'.
11625 By default the available states are \"TODO\" and \"DONE\".
11626 So for this example: when the item starts with TODO, it is changed to DONE.
11627 When it starts with DONE, the DONE is removed. And when neither TODO nor
11628 DONE are present, add TODO at the beginning of the heading.
11630 With \\[universal-argument] prefix arg, use completion to determine the new \
11631 state.
11632 With numeric prefix arg, switch to that state.
11633 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11634 keywords (nextset).
11635 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11636 With a numeric prefix arg of 0, inhibit note taking for the change.
11638 For calling through lisp, arg is also interpreted in the following way:
11639 'none -> empty state
11640 \"\"(empty string) -> switch to empty state
11641 'done -> switch to DONE
11642 'nextset -> switch to the next set of keywords
11643 'previousset -> switch to the previous set of keywords
11644 \"WAITING\" -> switch to the specified keyword, but only if it
11645 really is a member of `org-todo-keywords'."
11646 (interactive "P")
11647 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11648 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11649 'region-start-level 'region))
11650 org-loop-over-headlines-in-active-region)
11651 (org-map-entries
11652 `(org-todo ,arg)
11653 org-loop-over-headlines-in-active-region
11654 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11655 (if (equal arg '(16)) (setq arg 'nextset))
11656 (let ((org-blocker-hook org-blocker-hook)
11657 (case-fold-search nil))
11658 (when (equal arg '(64))
11659 (setq arg nil org-blocker-hook nil))
11660 (when (and org-blocker-hook
11661 (or org-inhibit-blocking
11662 (org-entry-get nil "NOBLOCKING")))
11663 (setq org-blocker-hook nil))
11664 (save-excursion
11665 (catch 'exit
11666 (org-back-to-heading t)
11667 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11668 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11669 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11670 (let* ((match-data (match-data))
11671 (startpos (point-at-bol))
11672 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11673 (org-log-done org-log-done)
11674 (org-log-repeat org-log-repeat)
11675 (org-todo-log-states org-todo-log-states)
11676 (org-inhibit-logging
11677 (if (equal arg 0)
11678 (progn (setq arg nil) 'note) org-inhibit-logging))
11679 (this (match-string 1))
11680 (hl-pos (match-beginning 0))
11681 (head (org-get-todo-sequence-head this))
11682 (ass (assoc head org-todo-kwd-alist))
11683 (interpret (nth 1 ass))
11684 (done-word (nth 3 ass))
11685 (final-done-word (nth 4 ass))
11686 (org-last-state (or this ""))
11687 (completion-ignore-case t)
11688 (member (member this org-todo-keywords-1))
11689 (tail (cdr member))
11690 (org-state (cond
11691 ((and org-todo-key-trigger
11692 (or (and (equal arg '(4))
11693 (eq org-use-fast-todo-selection 'prefix))
11694 (and (not arg) org-use-fast-todo-selection
11695 (not (eq org-use-fast-todo-selection
11696 'prefix)))))
11697 ;; Use fast selection
11698 (org-fast-todo-selection))
11699 ((and (equal arg '(4))
11700 (or (not org-use-fast-todo-selection)
11701 (not org-todo-key-trigger)))
11702 ;; Read a state with completion
11703 (org-icompleting-read
11704 "State: " (mapcar (lambda(x) (list x))
11705 org-todo-keywords-1)
11706 nil t))
11707 ((eq arg 'right)
11708 (if this
11709 (if tail (car tail) nil)
11710 (car org-todo-keywords-1)))
11711 ((eq arg 'left)
11712 (if (equal member org-todo-keywords-1)
11714 (if this
11715 (nth (- (length org-todo-keywords-1)
11716 (length tail) 2)
11717 org-todo-keywords-1)
11718 (org-last org-todo-keywords-1))))
11719 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11720 (setq arg nil))) ; hack to fall back to cycling
11721 (arg
11722 ;; user or caller requests a specific state
11723 (cond
11724 ((equal arg "") nil)
11725 ((eq arg 'none) nil)
11726 ((eq arg 'done) (or done-word (car org-done-keywords)))
11727 ((eq arg 'nextset)
11728 (or (car (cdr (member head org-todo-heads)))
11729 (car org-todo-heads)))
11730 ((eq arg 'previousset)
11731 (let ((org-todo-heads (reverse org-todo-heads)))
11732 (or (car (cdr (member head org-todo-heads)))
11733 (car org-todo-heads))))
11734 ((car (member arg org-todo-keywords-1)))
11735 ((stringp arg)
11736 (error "State `%s' not valid in this file" arg))
11737 ((nth (1- (prefix-numeric-value arg))
11738 org-todo-keywords-1))))
11739 ((null member) (or head (car org-todo-keywords-1)))
11740 ((equal this final-done-word) nil) ;; -> make empty
11741 ((null tail) nil) ;; -> first entry
11742 ((memq interpret '(type priority))
11743 (if (eq this-command last-command)
11744 (car tail)
11745 (if (> (length tail) 0)
11746 (or done-word (car org-done-keywords))
11747 nil)))
11749 (car tail))))
11750 (org-state (or
11751 (run-hook-with-args-until-success
11752 'org-todo-get-default-hook org-state org-last-state)
11753 org-state))
11754 (next (if org-state (concat " " org-state " ") " "))
11755 (change-plist (list :type 'todo-state-change :from this :to org-state
11756 :position startpos))
11757 dolog now-done-p)
11758 (when org-blocker-hook
11759 (setq org-last-todo-state-is-todo
11760 (not (member this org-done-keywords)))
11761 (unless (save-excursion
11762 (save-match-data
11763 (org-with-wide-buffer
11764 (run-hook-with-args-until-failure
11765 'org-blocker-hook change-plist))))
11766 (if (org-called-interactively-p 'interactive)
11767 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11768 this org-state org-block-entry-blocking)
11769 ;; fail silently
11770 (message "TODO state change from %s to %s blocked (by \"%s\")"
11771 this org-state org-block-entry-blocking)
11772 (throw 'exit nil))))
11773 (store-match-data match-data)
11774 (replace-match next t t)
11775 (unless (pos-visible-in-window-p hl-pos)
11776 (message "TODO state changed to %s" (org-trim next)))
11777 (unless head
11778 (setq head (org-get-todo-sequence-head org-state)
11779 ass (assoc head org-todo-kwd-alist)
11780 interpret (nth 1 ass)
11781 done-word (nth 3 ass)
11782 final-done-word (nth 4 ass)))
11783 (when (memq arg '(nextset previousset))
11784 (message "Keyword-Set %d/%d: %s"
11785 (- (length org-todo-sets) -1
11786 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11787 (length org-todo-sets)
11788 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11789 (setq org-last-todo-state-is-todo
11790 (not (member org-state org-done-keywords)))
11791 (setq now-done-p (and (member org-state org-done-keywords)
11792 (not (member this org-done-keywords))))
11793 (and logging (org-local-logging logging))
11794 (when (and (or org-todo-log-states org-log-done)
11795 (not (eq org-inhibit-logging t))
11796 (not (memq arg '(nextset previousset))))
11797 ;; we need to look at recording a time and note
11798 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11799 (nth 2 (assoc this org-todo-log-states))))
11800 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11801 (setq dolog 'time))
11802 (when (and org-state
11803 (member org-state org-not-done-keywords)
11804 (not (member this org-not-done-keywords)))
11805 ;; This is now a todo state and was not one before
11806 ;; If there was a CLOSED time stamp, get rid of it.
11807 (org-add-planning-info nil nil 'closed))
11808 (when (and now-done-p org-log-done)
11809 ;; It is now done, and it was not done before
11810 (org-add-planning-info 'closed (org-current-effective-time))
11811 (if (and (not dolog) (eq 'note org-log-done))
11812 (org-add-log-setup 'done org-state this 'findpos 'note)))
11813 (when (and org-state dolog)
11814 ;; This is a non-nil state, and we need to log it
11815 (org-add-log-setup 'state org-state this 'findpos dolog)))
11816 ;; Fixup tag positioning
11817 (org-todo-trigger-tag-changes org-state)
11818 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11819 (when org-provide-todo-statistics
11820 (org-update-parent-todo-statistics))
11821 (run-hooks 'org-after-todo-state-change-hook)
11822 (if (and arg (not (member org-state org-done-keywords)))
11823 (setq head (org-get-todo-sequence-head org-state)))
11824 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11825 ;; Do we need to trigger a repeat?
11826 (when now-done-p
11827 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11828 ;; This is for the agenda, take a snapshot of the headline.
11829 (save-match-data
11830 (setq org-agenda-headline-snapshot-before-repeat
11831 (org-get-heading))))
11832 (org-auto-repeat-maybe org-state))
11833 ;; Fixup cursor location if close to the keyword
11834 (if (and (outline-on-heading-p)
11835 (not (bolp))
11836 (save-excursion (beginning-of-line 1)
11837 (looking-at org-todo-line-regexp))
11838 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11839 (progn
11840 (goto-char (or (match-end 2) (match-end 1)))
11841 (and (looking-at " ") (just-one-space))))
11842 (when org-trigger-hook
11843 (save-excursion
11844 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11846 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11847 "Block turning an entry into a TODO, using the hierarchy.
11848 This checks whether the current task should be blocked from state
11849 changes. Such blocking occurs when:
11851 1. The task has children which are not all in a completed state.
11853 2. A task has a parent with the property :ORDERED:, and there
11854 are siblings prior to the current task with incomplete
11855 status.
11857 3. The parent of the task is blocked because it has siblings that should
11858 be done first, or is child of a block grandparent TODO entry."
11860 (if (not org-enforce-todo-dependencies)
11861 t ; if locally turned off don't block
11862 (catch 'dont-block
11863 ;; If this is not a todo state change, or if this entry is already DONE,
11864 ;; do not block
11865 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11866 (member (plist-get change-plist :from)
11867 (cons 'done org-done-keywords))
11868 (member (plist-get change-plist :to)
11869 (cons 'todo org-not-done-keywords))
11870 (not (plist-get change-plist :to)))
11871 (throw 'dont-block t))
11872 ;; If this task has children, and any are undone, it's blocked
11873 (save-excursion
11874 (org-back-to-heading t)
11875 (let ((this-level (funcall outline-level)))
11876 (outline-next-heading)
11877 (let ((child-level (funcall outline-level)))
11878 (while (and (not (eobp))
11879 (> child-level this-level))
11880 ;; this todo has children, check whether they are all
11881 ;; completed
11882 (if (and (not (org-entry-is-done-p))
11883 (org-entry-is-todo-p))
11884 (progn (setq org-block-entry-blocking (org-get-heading))
11885 (throw 'dont-block nil)))
11886 (outline-next-heading)
11887 (setq child-level (funcall outline-level))))))
11888 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11889 ;; any previous siblings are undone, it's blocked
11890 (save-excursion
11891 (org-back-to-heading t)
11892 (let* ((pos (point))
11893 (parent-pos (and (org-up-heading-safe) (point))))
11894 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11895 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11896 (forward-line 1)
11897 (re-search-forward org-not-done-heading-regexp pos t))
11898 (setq org-block-entry-blocking (match-string 0))
11899 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11900 ;; Search further up the hierarchy, to see if an ancestor is blocked
11901 (while t
11902 (goto-char parent-pos)
11903 (if (not (looking-at org-not-done-heading-regexp))
11904 (throw 'dont-block t)) ; do not block, parent is not a TODO
11905 (setq pos (point))
11906 (setq parent-pos (and (org-up-heading-safe) (point)))
11907 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11908 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11909 (forward-line 1)
11910 (re-search-forward org-not-done-heading-regexp pos t)
11911 (setq org-block-entry-blocking (org-get-heading)))
11912 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11914 (defcustom org-track-ordered-property-with-tag nil
11915 "Should the ORDERED property also be shown as a tag?
11916 The ORDERED property decides if an entry should require subtasks to be
11917 completed in sequence. Since a property is not very visible, setting
11918 this option means that toggling the ORDERED property with the command
11919 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11920 not relevant for the behavior, but it makes things more visible.
11922 Note that toggling the tag with tags commands will not change the property
11923 and therefore not influence behavior!
11925 This can be t, meaning the tag ORDERED should be used, It can also be a
11926 string to select a different tag for this task."
11927 :group 'org-todo
11928 :type '(choice
11929 (const :tag "No tracking" nil)
11930 (const :tag "Track with ORDERED tag" t)
11931 (string :tag "Use other tag")))
11933 (defun org-toggle-ordered-property ()
11934 "Toggle the ORDERED property of the current entry.
11935 For better visibility, you can track the value of this property with a tag.
11936 See variable `org-track-ordered-property-with-tag'."
11937 (interactive)
11938 (let* ((t1 org-track-ordered-property-with-tag)
11939 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11940 (save-excursion
11941 (org-back-to-heading)
11942 (if (org-entry-get nil "ORDERED")
11943 (progn
11944 (org-delete-property "ORDERED")
11945 (and tag (org-toggle-tag tag 'off))
11946 (message "Subtasks can be completed in arbitrary order"))
11947 (org-entry-put nil "ORDERED" "t")
11948 (and tag (org-toggle-tag tag 'on))
11949 (message "Subtasks must be completed in sequence")))))
11951 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11952 (defun org-block-todo-from-checkboxes (change-plist)
11953 "Block turning an entry into a TODO, using checkboxes.
11954 This checks whether the current task should be blocked from state
11955 changes because there are unchecked boxes in this entry."
11956 (if (not org-enforce-todo-checkbox-dependencies)
11957 t ; if locally turned off don't block
11958 (catch 'dont-block
11959 ;; If this is not a todo state change, or if this entry is already DONE,
11960 ;; do not block
11961 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11962 (member (plist-get change-plist :from)
11963 (cons 'done org-done-keywords))
11964 (member (plist-get change-plist :to)
11965 (cons 'todo org-not-done-keywords))
11966 (not (plist-get change-plist :to)))
11967 (throw 'dont-block t))
11968 ;; If this task has checkboxes that are not checked, it's blocked
11969 (save-excursion
11970 (org-back-to-heading t)
11971 (let ((beg (point)) end)
11972 (outline-next-heading)
11973 (setq end (point))
11974 (goto-char beg)
11975 (if (org-list-search-forward
11976 (concat (org-item-beginning-re)
11977 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11978 "\\[[- ]\\]")
11979 end t)
11980 (progn
11981 (if (boundp 'org-blocked-by-checkboxes)
11982 (setq org-blocked-by-checkboxes t))
11983 (throw 'dont-block nil)))))
11984 t))) ; do not block
11986 (defun org-entry-blocked-p ()
11987 "Is the current entry blocked?"
11988 (if (org-entry-get nil "NOBLOCKING")
11989 nil ;; Never block this entry
11990 (not
11991 (run-hook-with-args-until-failure
11992 'org-blocker-hook
11993 (list :type 'todo-state-change
11994 :position (point)
11995 :from 'todo
11996 :to 'done)))))
11998 (defun org-update-statistics-cookies (all)
11999 "Update the statistics cookie, either from TODO or from checkboxes.
12000 This should be called with the cursor in a line with a statistics cookie."
12001 (interactive "P")
12002 (if all
12003 (progn
12004 (org-update-checkbox-count 'all)
12005 (org-map-entries 'org-update-parent-todo-statistics))
12006 (if (not (org-at-heading-p))
12007 (org-update-checkbox-count)
12008 (let ((pos (point-marker))
12009 end l1 l2)
12010 (ignore-errors (org-back-to-heading t))
12011 (if (not (org-at-heading-p))
12012 (org-update-checkbox-count)
12013 (setq l1 (org-outline-level))
12014 (setq end (save-excursion
12015 (outline-next-heading)
12016 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12017 (point)))
12018 (if (and (save-excursion
12019 (re-search-forward
12020 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12021 (not (save-excursion (re-search-forward
12022 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12023 (org-update-checkbox-count)
12024 (if (and l2 (> l2 l1))
12025 (progn
12026 (goto-char end)
12027 (org-update-parent-todo-statistics))
12028 (goto-char pos)
12029 (beginning-of-line 1)
12030 (while (re-search-forward
12031 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12032 (point-at-eol) t)
12033 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12034 (goto-char pos)
12035 (move-marker pos nil)))))
12037 (defvar org-entry-property-inherited-from) ;; defined below
12038 (defun org-update-parent-todo-statistics ()
12039 "Update any statistics cookie in the parent of the current headline.
12040 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12041 the entire subtree and this will travel up the hierarchy and update
12042 statistics everywhere."
12043 (let* ((prop (save-excursion (org-up-heading-safe)
12044 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12045 (recursive (or (not org-hierarchical-todo-statistics)
12046 (and prop (string-match "\\<recursive\\>" prop))))
12047 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12049 (first t)
12050 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12051 level ltoggle l1 new ndel
12052 (cnt-all 0) (cnt-done 0) is-percent kwd
12053 checkbox-beg ov ovs ove cookie-present)
12054 (catch 'exit
12055 (save-excursion
12056 (beginning-of-line 1)
12057 (setq ltoggle (funcall outline-level))
12058 ;; Three situations are to consider:
12060 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12061 ;; to the top-level ancestor on the headline;
12063 ;; 2. If parent has "recursive" property, repeat up to the
12064 ;; headline setting that property, taking inheritance into
12065 ;; account;
12067 ;; 3. Else, move up to direct parent and proceed only once.
12068 (while (and (setq level (org-up-heading-safe))
12069 (or recursive first)
12070 (>= (point) lim))
12071 (setq first nil cookie-present nil)
12072 (unless (and level
12073 (not (string-match
12074 "\\<checkbox\\>"
12075 (downcase (or (org-entry-get nil "COOKIE_DATA")
12076 "")))))
12077 (throw 'exit nil))
12078 (while (re-search-forward box-re (point-at-eol) t)
12079 (setq cnt-all 0 cnt-done 0 cookie-present t)
12080 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12081 (save-match-data
12082 (unless (outline-next-heading) (throw 'exit nil))
12083 (while (and (looking-at org-complex-heading-regexp)
12084 (> (setq l1 (length (match-string 1))) level))
12085 (setq kwd (and (or recursive (= l1 ltoggle))
12086 (match-string 2)))
12087 (if (or (eq org-provide-todo-statistics 'all-headlines)
12088 (and (listp org-provide-todo-statistics)
12089 (or (member kwd org-provide-todo-statistics)
12090 (member kwd org-done-keywords))))
12091 (setq cnt-all (1+ cnt-all))
12092 (if (eq org-provide-todo-statistics t)
12093 (and kwd (setq cnt-all (1+ cnt-all)))))
12094 (and (member kwd org-done-keywords)
12095 (setq cnt-done (1+ cnt-done)))
12096 (outline-next-heading)))
12097 (setq new
12098 (if is-percent
12099 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12100 (format "[%d/%d]" cnt-done cnt-all))
12101 ndel (- (match-end 0) checkbox-beg))
12102 ;; handle overlays when updating cookie from column view
12103 (when (setq ov (car (overlays-at checkbox-beg)))
12104 (setq ovs (overlay-start ov) ove (overlay-end ov))
12105 (delete-overlay ov))
12106 (goto-char checkbox-beg)
12107 (insert new)
12108 (delete-region (point) (+ (point) ndel))
12109 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12110 (when ov (move-overlay ov ovs ove)))
12111 (when cookie-present
12112 (run-hook-with-args 'org-after-todo-statistics-hook
12113 cnt-done (- cnt-all cnt-done))))))
12114 (run-hooks 'org-todo-statistics-hook)))
12116 (defvar org-after-todo-statistics-hook nil
12117 "Hook that is called after a TODO statistics cookie has been updated.
12118 Each function is called with two arguments: the number of not-done entries
12119 and the number of done entries.
12121 For example, the following function, when added to this hook, will switch
12122 an entry to DONE when all children are done, and back to TODO when new
12123 entries are set to a TODO status. Note that this hook is only called
12124 when there is a statistics cookie in the headline!
12126 (defun org-summary-todo (n-done n-not-done)
12127 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12128 (let (org-log-done org-log-states) ; turn off logging
12129 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12132 (defvar org-todo-statistics-hook nil
12133 "Hook that is run whenever Org thinks TODO statistics should be updated.
12134 This hook runs even if there is no statistics cookie present, in which case
12135 `org-after-todo-statistics-hook' would not run.")
12137 (defun org-todo-trigger-tag-changes (state)
12138 "Apply the changes defined in `org-todo-state-tags-triggers'."
12139 (let ((l org-todo-state-tags-triggers)
12140 changes)
12141 (when (or (not state) (equal state ""))
12142 (setq changes (append changes (cdr (assoc "" l)))))
12143 (when (and (stringp state) (> (length state) 0))
12144 (setq changes (append changes (cdr (assoc state l)))))
12145 (when (member state org-not-done-keywords)
12146 (setq changes (append changes (cdr (assoc 'todo l)))))
12147 (when (member state org-done-keywords)
12148 (setq changes (append changes (cdr (assoc 'done l)))))
12149 (dolist (c changes)
12150 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12152 (defun org-local-logging (value)
12153 "Get logging settings from a property VALUE."
12154 (let* (words w a)
12155 ;; directly set the variables, they are already local.
12156 (setq org-log-done nil
12157 org-log-repeat nil
12158 org-todo-log-states nil)
12159 (setq words (org-split-string value))
12160 (while (setq w (pop words))
12161 (cond
12162 ((setq a (assoc w org-startup-options))
12163 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12164 (set (nth 1 a) (nth 2 a))))
12165 ((setq a (org-extract-log-state-settings w))
12166 (and (member (car a) org-todo-keywords-1)
12167 (push a org-todo-log-states)))))))
12169 (defun org-get-todo-sequence-head (kwd)
12170 "Return the head of the TODO sequence to which KWD belongs.
12171 If KWD is not set, check if there is a text property remembering the
12172 right sequence."
12173 (let (p)
12174 (cond
12175 ((not kwd)
12176 (or (get-text-property (point-at-bol) 'org-todo-head)
12177 (progn
12178 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12179 nil (point-at-eol)))
12180 (get-text-property p 'org-todo-head))))
12181 ((not (member kwd org-todo-keywords-1))
12182 (car org-todo-keywords-1))
12183 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12185 (defun org-fast-todo-selection ()
12186 "Fast TODO keyword selection with single keys.
12187 Returns the new TODO keyword, or nil if no state change should occur."
12188 (let* ((fulltable org-todo-key-alist)
12189 (done-keywords org-done-keywords) ;; needed for the faces.
12190 (maxlen (apply 'max (mapcar
12191 (lambda (x)
12192 (if (stringp (car x)) (string-width (car x)) 0))
12193 fulltable)))
12194 (expert nil)
12195 (fwidth (+ maxlen 3 1 3))
12196 (ncol (/ (- (window-width) 4) fwidth))
12197 tg cnt e c tbl
12198 groups ingroup)
12199 (save-excursion
12200 (save-window-excursion
12201 (if expert
12202 (set-buffer (get-buffer-create " *Org todo*"))
12203 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12204 (erase-buffer)
12205 (org-set-local 'org-done-keywords done-keywords)
12206 (setq tbl fulltable cnt 0)
12207 (while (setq e (pop tbl))
12208 (cond
12209 ((equal e '(:startgroup))
12210 (push '() groups) (setq ingroup t)
12211 (when (not (= cnt 0))
12212 (setq cnt 0)
12213 (insert "\n"))
12214 (insert "{ "))
12215 ((equal e '(:endgroup))
12216 (setq ingroup nil cnt 0)
12217 (insert "}\n"))
12218 ((equal e '(:newline))
12219 (when (not (= cnt 0))
12220 (setq cnt 0)
12221 (insert "\n")
12222 (setq e (car tbl))
12223 (while (equal (car tbl) '(:newline))
12224 (insert "\n")
12225 (setq tbl (cdr tbl)))))
12227 (setq tg (car e) c (cdr e))
12228 (if ingroup (push tg (car groups)))
12229 (setq tg (org-add-props tg nil 'face
12230 (org-get-todo-face tg)))
12231 (if (and (= cnt 0) (not ingroup)) (insert " "))
12232 (insert "[" c "] " tg (make-string
12233 (- fwidth 4 (length tg)) ?\ ))
12234 (when (= (setq cnt (1+ cnt)) ncol)
12235 (insert "\n")
12236 (if ingroup (insert " "))
12237 (setq cnt 0)))))
12238 (insert "\n")
12239 (goto-char (point-min))
12240 (if (not expert) (org-fit-window-to-buffer))
12241 (message "[a-z..]:Set [SPC]:clear")
12242 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12243 (cond
12244 ((or (= c ?\C-g)
12245 (and (= c ?q) (not (rassoc c fulltable))))
12246 (setq quit-flag t))
12247 ((= c ?\ ) nil)
12248 ((setq e (rassoc c fulltable) tg (car e))
12250 (t (setq quit-flag t)))))))
12252 (defun org-entry-is-todo-p ()
12253 (member (org-get-todo-state) org-not-done-keywords))
12255 (defun org-entry-is-done-p ()
12256 (member (org-get-todo-state) org-done-keywords))
12258 (defun org-get-todo-state ()
12259 (save-excursion
12260 (org-back-to-heading t)
12261 (and (looking-at org-todo-line-regexp)
12262 (match-end 2)
12263 (match-string 2))))
12265 (defun org-at-date-range-p (&optional inactive-ok)
12266 "Is the cursor inside a date range?"
12267 (interactive)
12268 (save-excursion
12269 (catch 'exit
12270 (let ((pos (point)))
12271 (skip-chars-backward "^[<\r\n")
12272 (skip-chars-backward "<[")
12273 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12274 (>= (match-end 0) pos)
12275 (throw 'exit t))
12276 (skip-chars-backward "^<[\r\n")
12277 (skip-chars-backward "<[")
12278 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12279 (>= (match-end 0) pos)
12280 (throw 'exit t)))
12281 nil)))
12283 (defun org-get-repeat (&optional tagline)
12284 "Check if there is a deadline/schedule with repeater in this entry."
12285 (save-match-data
12286 (save-excursion
12287 (org-back-to-heading t)
12288 (and (re-search-forward (if tagline
12289 (concat tagline "\\s-*" org-repeat-re)
12290 org-repeat-re)
12291 (org-entry-end-position) t)
12292 (match-string-no-properties 1)))))
12294 (defvar org-last-changed-timestamp)
12295 (defvar org-last-inserted-timestamp)
12296 (defvar org-log-post-message)
12297 (defvar org-log-note-purpose)
12298 (defvar org-log-note-how)
12299 (defvar org-log-note-extra)
12300 (defun org-auto-repeat-maybe (done-word)
12301 "Check if the current headline contains a repeated deadline/schedule.
12302 If yes, set TODO state back to what it was and change the base date
12303 of repeating deadline/scheduled time stamps to new date.
12304 This function is run automatically after each state change to a DONE state."
12305 ;; last-state is dynamically scoped into this function
12306 (let* ((repeat (org-get-repeat))
12307 (aa (assoc org-last-state org-todo-kwd-alist))
12308 (interpret (nth 1 aa))
12309 (head (nth 2 aa))
12310 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12311 (msg "Entry repeats: ")
12312 (org-log-done nil)
12313 (org-todo-log-states nil)
12314 re type n what ts time to-state)
12315 (when repeat
12316 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12317 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12318 org-todo-repeat-to-state))
12319 (unless (and to-state (member to-state org-todo-keywords-1))
12320 (setq to-state (if (eq interpret 'type) org-last-state head)))
12321 (org-todo to-state)
12322 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12323 (org-entry-put nil "LAST_REPEAT" (format-time-string
12324 (org-time-stamp-format t t))))
12325 (when org-log-repeat
12326 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12327 (memq 'org-add-log-note post-command-hook))
12328 ;; OK, we are already setup for some record
12329 (if (eq org-log-repeat 'note)
12330 ;; make sure we take a note, not only a time stamp
12331 (setq org-log-note-how 'note))
12332 ;; Set up for taking a record
12333 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12334 org-last-state
12335 'findpos org-log-repeat)))
12336 (org-back-to-heading t)
12337 (org-add-planning-info nil nil 'closed)
12338 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12339 org-deadline-time-regexp "\\)\\|\\("
12340 org-ts-regexp "\\)"))
12341 (while (re-search-forward
12342 re (save-excursion (outline-next-heading) (point)) t)
12343 (setq type (if (match-end 1) org-scheduled-string
12344 (if (match-end 3) org-deadline-string "Plain:"))
12345 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12346 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12347 (setq n (string-to-number (match-string 2 ts))
12348 what (match-string 3 ts))
12349 (if (equal what "w") (setq n (* n 7) what "d"))
12350 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12351 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12352 ;; Preparation, see if we need to modify the start date for the change
12353 (when (match-end 1)
12354 (setq time (save-match-data (org-time-string-to-time ts)))
12355 (cond
12356 ((equal (match-string 1 ts) ".")
12357 ;; Shift starting date to today
12358 (org-timestamp-change
12359 (- (org-today) (time-to-days time))
12360 'day))
12361 ((equal (match-string 1 ts) "+")
12362 (let ((nshiftmax 10) (nshift 0))
12363 (while (or (= nshift 0)
12364 (<= (time-to-days time)
12365 (time-to-days (current-time))))
12366 (when (= (incf nshift) nshiftmax)
12367 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12368 (error "Abort")))
12369 (org-timestamp-change n (cdr (assoc what whata)))
12370 (org-at-timestamp-p t)
12371 (setq ts (match-string 1))
12372 (setq time (save-match-data (org-time-string-to-time ts)))))
12373 (org-timestamp-change (- n) (cdr (assoc what whata)))
12374 ;; rematch, so that we have everything in place for the real shift
12375 (org-at-timestamp-p t)
12376 (setq ts (match-string 1))
12377 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12378 (org-timestamp-change n (cdr (assoc what whata)))
12379 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12380 (setq org-log-post-message msg)
12381 (message "%s" msg))))
12383 (defun org-show-todo-tree (arg)
12384 "Make a compact tree which shows all headlines marked with TODO.
12385 The tree will show the lines where the regexp matches, and all higher
12386 headlines above the match.
12387 With a \\[universal-argument] prefix, prompt for a regexp to match.
12388 With a numeric prefix N, construct a sparse tree for the Nth element
12389 of `org-todo-keywords-1'."
12390 (interactive "P")
12391 (let ((case-fold-search nil)
12392 (kwd-re
12393 (cond ((null arg) org-not-done-regexp)
12394 ((equal arg '(4))
12395 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12396 (mapcar 'list org-todo-keywords-1))))
12397 (concat "\\("
12398 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12399 "\\)\\>")))
12400 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12401 (regexp-quote (nth (1- (prefix-numeric-value arg))
12402 org-todo-keywords-1)))
12403 (t (error "Invalid prefix argument: %s" arg)))))
12404 (message "%d TODO entries found"
12405 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12407 (defun org-deadline (&optional remove time)
12408 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12409 With argument REMOVE, remove any deadline from the item.
12410 With argument TIME, set the deadline at the corresponding date. TIME
12411 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12412 (interactive "P")
12413 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12414 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12415 'region-start-level 'region))
12416 org-loop-over-headlines-in-active-region)
12417 (org-map-entries
12418 `(org-deadline ',remove ,time)
12419 org-loop-over-headlines-in-active-region
12420 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12421 (let* ((old-date (org-entry-get nil "DEADLINE"))
12422 (repeater (and old-date
12423 (string-match
12424 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12425 old-date)
12426 (match-string 1 old-date))))
12427 (if remove
12428 (progn
12429 (when (and old-date org-log-redeadline)
12430 (org-add-log-setup 'deldeadline nil old-date 'findpos
12431 org-log-redeadline))
12432 (org-remove-timestamp-with-keyword org-deadline-string)
12433 (message "Item no longer has a deadline."))
12434 (org-add-planning-info 'deadline time 'closed)
12435 (when (and old-date org-log-redeadline
12436 (not (equal old-date
12437 (substring org-last-inserted-timestamp 1 -1))))
12438 (org-add-log-setup 'redeadline nil old-date 'findpos
12439 org-log-redeadline))
12440 (when repeater
12441 (save-excursion
12442 (org-back-to-heading t)
12443 (when (re-search-forward (concat org-deadline-string " "
12444 org-last-inserted-timestamp)
12445 (save-excursion
12446 (outline-next-heading) (point)) t)
12447 (goto-char (1- (match-end 0)))
12448 (insert " " repeater)
12449 (setq org-last-inserted-timestamp
12450 (concat (substring org-last-inserted-timestamp 0 -1)
12451 " " repeater
12452 (substring org-last-inserted-timestamp -1))))))
12453 (message "Deadline on %s" org-last-inserted-timestamp)))))
12455 (defun org-schedule (&optional remove time)
12456 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12457 With argument REMOVE, remove any scheduling date from the item.
12458 With argument TIME, scheduled at the corresponding date. TIME can
12459 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12460 (interactive "P")
12461 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12462 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12463 'region-start-level 'region))
12464 org-loop-over-headlines-in-active-region)
12465 (org-map-entries
12466 `(org-schedule ',remove ,time)
12467 org-loop-over-headlines-in-active-region
12468 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12469 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12470 (repeater (and old-date
12471 (string-match
12472 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12473 old-date)
12474 (match-string 1 old-date))))
12475 (if remove
12476 (progn
12477 (when (and old-date org-log-reschedule)
12478 (org-add-log-setup 'delschedule nil old-date 'findpos
12479 org-log-reschedule))
12480 (org-remove-timestamp-with-keyword org-scheduled-string)
12481 (message "Item is no longer scheduled."))
12482 (org-add-planning-info 'scheduled time 'closed)
12483 (when (and old-date org-log-reschedule
12484 (not (equal old-date
12485 (substring org-last-inserted-timestamp 1 -1))))
12486 (org-add-log-setup 'reschedule nil old-date 'findpos
12487 org-log-reschedule))
12488 (when repeater
12489 (save-excursion
12490 (org-back-to-heading t)
12491 (when (re-search-forward (concat org-scheduled-string " "
12492 org-last-inserted-timestamp)
12493 (save-excursion
12494 (outline-next-heading) (point)) t)
12495 (goto-char (1- (match-end 0)))
12496 (insert " " repeater)
12497 (setq org-last-inserted-timestamp
12498 (concat (substring org-last-inserted-timestamp 0 -1)
12499 " " repeater
12500 (substring org-last-inserted-timestamp -1))))))
12501 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12503 (defun org-get-scheduled-time (pom &optional inherit)
12504 "Get the scheduled time as a time tuple, of a format suitable
12505 for calling org-schedule with, or if there is no scheduling,
12506 returns nil."
12507 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12508 (when time
12509 (apply 'encode-time (org-parse-time-string time)))))
12511 (defun org-get-deadline-time (pom &optional inherit)
12512 "Get the deadline as a time tuple, of a format suitable for
12513 calling org-deadline with, or if there is no scheduling, returns
12514 nil."
12515 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12516 (when time
12517 (apply 'encode-time (org-parse-time-string time)))))
12519 (defun org-remove-timestamp-with-keyword (keyword)
12520 "Remove all time stamps with KEYWORD in the current entry."
12521 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12522 beg)
12523 (save-excursion
12524 (org-back-to-heading t)
12525 (setq beg (point))
12526 (outline-next-heading)
12527 (while (re-search-backward re beg t)
12528 (replace-match "")
12529 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12530 (equal (char-before) ?\ ))
12531 (backward-delete-char 1)
12532 (if (string-match "^[ \t]*$" (buffer-substring
12533 (point-at-bol) (point-at-eol)))
12534 (delete-region (point-at-bol)
12535 (min (point-max) (1+ (point-at-eol))))))))))
12537 (defun org-add-planning-info (what &optional time &rest remove)
12538 "Insert new timestamp with keyword in the line directly after the headline.
12539 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12540 If non is given, the user is prompted for a date.
12541 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12542 be removed."
12543 (interactive)
12544 (let (org-time-was-given org-end-time-was-given ts
12545 end default-time default-input)
12547 (catch 'exit
12548 (when (and (memq what '(scheduled deadline))
12549 (or (not time)
12550 (and (stringp time)
12551 (string-match "^[-+]+[0-9]" time))))
12552 ;; Try to get a default date/time from existing timestamp
12553 (save-excursion
12554 (org-back-to-heading t)
12555 (setq end (save-excursion (outline-next-heading) (point)))
12556 (when (re-search-forward (if (eq what 'scheduled)
12557 org-scheduled-time-regexp
12558 org-deadline-time-regexp)
12559 end t)
12560 (setq ts (match-string 1)
12561 default-time
12562 (apply 'encode-time (org-parse-time-string ts))
12563 default-input (and ts (org-get-compact-tod ts))))))
12564 (when what
12565 (setq time
12566 (if (stringp time)
12567 ;; This is a string (relative or absolute), set proper date
12568 (apply 'encode-time
12569 (org-read-date-analyze
12570 time default-time (decode-time default-time)))
12571 ;; If necessary, get the time from the user
12572 (or time (org-read-date nil 'to-time nil nil
12573 default-time default-input)))))
12575 (when (and org-insert-labeled-timestamps-at-point
12576 (member what '(scheduled deadline)))
12577 (insert
12578 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12579 (org-insert-time-stamp time org-time-was-given
12580 nil nil nil (list org-end-time-was-given))
12581 (setq what nil))
12582 (save-excursion
12583 (save-restriction
12584 (let (col list elt ts buffer-invisibility-spec)
12585 (org-back-to-heading t)
12586 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12587 (goto-char (match-end 1))
12588 (setq col (current-column))
12589 (goto-char (match-end 0))
12590 (if (eobp) (insert "\n") (forward-char 1))
12591 (when (and (not what)
12592 (not (looking-at
12593 (concat "[ \t]*"
12594 org-keyword-time-not-clock-regexp))))
12595 ;; Nothing to add, nothing to remove...... :-)
12596 (throw 'exit nil))
12597 (if (and (not (looking-at org-outline-regexp))
12598 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12599 "[^\r\n]*"))
12600 (not (equal (match-string 1) org-clock-string)))
12601 (narrow-to-region (match-beginning 0) (match-end 0))
12602 (insert-before-markers "\n")
12603 (backward-char 1)
12604 (narrow-to-region (point) (point))
12605 (and org-adapt-indentation (org-indent-to-column col)))
12606 ;; Check if we have to remove something.
12607 (setq list (cons what remove))
12608 (while list
12609 (setq elt (pop list))
12610 (when (or (and (eq elt 'scheduled)
12611 (re-search-forward org-scheduled-time-regexp nil t))
12612 (and (eq elt 'deadline)
12613 (re-search-forward org-deadline-time-regexp nil t))
12614 (and (eq elt 'closed)
12615 (re-search-forward org-closed-time-regexp nil t)))
12616 (replace-match "")
12617 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12618 (and (looking-at "[ \t]+") (replace-match ""))
12619 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12620 (when what
12621 (insert
12622 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12623 (cond ((eq what 'scheduled) org-scheduled-string)
12624 ((eq what 'deadline) org-deadline-string)
12625 ((eq what 'closed) org-closed-string))
12626 " ")
12627 (setq ts (org-insert-time-stamp
12628 time
12629 (or org-time-was-given
12630 (and (eq what 'closed) org-log-done-with-time))
12631 (eq what 'closed)
12632 nil nil (list org-end-time-was-given)))
12633 (insert
12634 (if (not (or (bolp) (eq (char-before) ?\ )
12635 (memq (char-after) '(32 10))
12636 (eobp))) " " ""))
12637 (end-of-line 1))
12638 (goto-char (point-min))
12639 (widen)
12640 (if (and (looking-at "[ \t]*\n")
12641 (equal (char-before) ?\n))
12642 (delete-region (1- (point)) (point-at-eol)))
12643 ts))))))
12645 (defvar org-log-note-marker (make-marker))
12646 (defvar org-log-note-purpose nil)
12647 (defvar org-log-note-state nil)
12648 (defvar org-log-note-previous-state nil)
12649 (defvar org-log-note-how nil)
12650 (defvar org-log-note-extra nil)
12651 (defvar org-log-note-window-configuration nil)
12652 (defvar org-log-note-return-to (make-marker))
12653 (defvar org-log-note-effective-time nil
12654 "Remembered current time so that dynamically scoped
12655 `org-extend-today-until' affects tha timestamps in state change
12656 log")
12658 (defvar org-log-post-message nil
12659 "Message to be displayed after a log note has been stored.
12660 The auto-repeater uses this.")
12662 (defun org-add-note ()
12663 "Add a note to the current entry.
12664 This is done in the same way as adding a state change note."
12665 (interactive)
12666 (org-add-log-setup 'note nil nil 'findpos nil))
12668 (defvar org-property-end-re)
12669 (defun org-add-log-setup (&optional purpose state prev-state
12670 findpos how extra)
12671 "Set up the post command hook to take a note.
12672 If this is about to TODO state change, the new state is expected in STATE.
12673 When FINDPOS is non-nil, find the correct position for the note in
12674 the current entry. If not, assume that it can be inserted at point.
12675 HOW is an indicator what kind of note should be created.
12676 EXTRA is additional text that will be inserted into the notes buffer."
12677 (let* ((org-log-into-drawer (org-log-into-drawer))
12678 (drawer (cond ((stringp org-log-into-drawer)
12679 org-log-into-drawer)
12680 (org-log-into-drawer "LOGBOOK"))))
12681 (save-restriction
12682 (save-excursion
12683 (when findpos
12684 (org-back-to-heading t)
12685 (narrow-to-region (point) (save-excursion
12686 (outline-next-heading) (point)))
12687 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12688 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12689 "[^\r\n]*\\)?"))
12690 (goto-char (match-end 0))
12691 (cond
12692 (drawer
12693 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12694 nil t)
12695 (progn
12696 (goto-char (match-end 0))
12697 (or org-log-states-order-reversed
12698 (and (re-search-forward org-property-end-re nil t)
12699 (goto-char (1- (match-beginning 0))))))
12700 (insert "\n:" drawer ":\n:END:")
12701 (beginning-of-line 0)
12702 (org-indent-line)
12703 (beginning-of-line 2)
12704 (org-indent-line)
12705 (end-of-line 0)))
12706 ((and org-log-state-notes-insert-after-drawers
12707 (save-excursion
12708 (forward-line) (looking-at org-drawer-regexp)))
12709 (forward-line)
12710 (while (looking-at org-drawer-regexp)
12711 (goto-char (match-end 0))
12712 (re-search-forward org-property-end-re (point-max) t)
12713 (forward-line))
12714 (forward-line -1)))
12715 (unless org-log-states-order-reversed
12716 (and (= (char-after) ?\n) (forward-char 1))
12717 (org-skip-over-state-notes)
12718 (skip-chars-backward " \t\n\r")))
12719 (move-marker org-log-note-marker (point))
12720 (setq org-log-note-purpose purpose
12721 org-log-note-state state
12722 org-log-note-previous-state prev-state
12723 org-log-note-how how
12724 org-log-note-extra extra
12725 org-log-note-effective-time (org-current-effective-time))
12726 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12728 (defun org-skip-over-state-notes ()
12729 "Skip past the list of State notes in an entry."
12730 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12731 (when (ignore-errors (goto-char (org-in-item-p)))
12732 (let* ((struct (org-list-struct))
12733 (prevs (org-list-prevs-alist struct)))
12734 (while (looking-at "[ \t]*- State")
12735 (goto-char (or (org-list-get-next-item (point) struct prevs)
12736 (org-list-get-item-end (point) struct)))))))
12738 (defun org-add-log-note (&optional purpose)
12739 "Pop up a window for taking a note, and add this note later at point."
12740 (remove-hook 'post-command-hook 'org-add-log-note)
12741 (setq org-log-note-window-configuration (current-window-configuration))
12742 (delete-other-windows)
12743 (move-marker org-log-note-return-to (point))
12744 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12745 (goto-char org-log-note-marker)
12746 (org-switch-to-buffer-other-window "*Org Note*")
12747 (erase-buffer)
12748 (if (memq org-log-note-how '(time state))
12749 (let (current-prefix-arg) (org-store-log-note))
12750 (let ((org-inhibit-startup t)) (org-mode))
12751 (insert (format "# Insert note for %s.
12752 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12753 (cond
12754 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12755 ((eq org-log-note-purpose 'done) "closed todo item")
12756 ((eq org-log-note-purpose 'state)
12757 (format "state change from \"%s\" to \"%s\""
12758 (or org-log-note-previous-state "")
12759 (or org-log-note-state "")))
12760 ((eq org-log-note-purpose 'reschedule)
12761 "rescheduling")
12762 ((eq org-log-note-purpose 'delschedule)
12763 "no longer scheduled")
12764 ((eq org-log-note-purpose 'redeadline)
12765 "changing deadline")
12766 ((eq org-log-note-purpose 'deldeadline)
12767 "removing deadline")
12768 ((eq org-log-note-purpose 'refile)
12769 "refiling")
12770 ((eq org-log-note-purpose 'note)
12771 "this entry")
12772 (t (error "This should not happen")))))
12773 (if org-log-note-extra (insert org-log-note-extra))
12774 (org-set-local 'org-finish-function 'org-store-log-note)
12775 (run-hooks 'org-log-buffer-setup-hook)))
12777 (defvar org-note-abort nil) ; dynamically scoped
12778 (defun org-store-log-note ()
12779 "Finish taking a log note, and insert it to where it belongs."
12780 (let ((txt (buffer-string)))
12781 (kill-buffer (current-buffer))
12782 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12783 lines ind bul)
12784 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12785 (setq txt (replace-match "" t t txt)))
12786 (if (string-match "\\s-+\\'" txt)
12787 (setq txt (replace-match "" t t txt)))
12788 (setq lines (org-split-string txt "\n"))
12789 (when (and note (string-match "\\S-" note))
12790 (setq note
12791 (org-replace-escapes
12792 note
12793 (list (cons "%u" (user-login-name))
12794 (cons "%U" user-full-name)
12795 (cons "%t" (format-time-string
12796 (org-time-stamp-format 'long 'inactive)
12797 org-log-note-effective-time))
12798 (cons "%T" (format-time-string
12799 (org-time-stamp-format 'long nil)
12800 org-log-note-effective-time))
12801 (cons "%d" (format-time-string
12802 (org-time-stamp-format nil 'inactive)
12803 org-log-note-effective-time))
12804 (cons "%D" (format-time-string
12805 (org-time-stamp-format nil nil)
12806 org-log-note-effective-time))
12807 (cons "%s" (if org-log-note-state
12808 (concat "\"" org-log-note-state "\"")
12809 ""))
12810 (cons "%S" (if org-log-note-previous-state
12811 (concat "\"" org-log-note-previous-state "\"")
12812 "\"\"")))))
12813 (if lines (setq note (concat note " \\\\")))
12814 (push note lines))
12815 (when (or current-prefix-arg org-note-abort)
12816 (when org-log-into-drawer
12817 (org-remove-empty-drawer-at
12818 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12819 org-log-note-marker))
12820 (setq lines nil))
12821 (when lines
12822 (with-current-buffer (marker-buffer org-log-note-marker)
12823 (save-excursion
12824 (goto-char org-log-note-marker)
12825 (move-marker org-log-note-marker nil)
12826 (end-of-line 1)
12827 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12828 (setq ind (save-excursion
12829 (if (ignore-errors (goto-char (org-in-item-p)))
12830 (let ((struct (org-list-struct)))
12831 (org-list-get-ind
12832 (org-list-get-top-point struct) struct))
12833 (skip-chars-backward " \r\t\n")
12834 (cond
12835 ((and (org-at-heading-p)
12836 org-adapt-indentation)
12837 (1+ (org-current-level)))
12838 ((org-at-heading-p) 0)
12839 (t (org-get-indentation))))))
12840 (setq bul (org-list-bullet-string "-"))
12841 (org-indent-line-to ind)
12842 (insert bul (pop lines))
12843 (let ((ind-body (+ (length bul) ind)))
12844 (while lines
12845 (insert "\n")
12846 (org-indent-line-to ind-body)
12847 (insert (pop lines))))
12848 (message "Note stored")
12849 (org-back-to-heading t)
12850 (org-cycle-hide-drawers 'children))))))
12851 (set-window-configuration org-log-note-window-configuration)
12852 (with-current-buffer (marker-buffer org-log-note-return-to)
12853 (goto-char org-log-note-return-to))
12854 (move-marker org-log-note-return-to nil)
12855 (and org-log-post-message (message "%s" org-log-post-message)))
12857 (defun org-remove-empty-drawer-at (drawer pos)
12858 "Remove an empty drawer DRAWER at position POS.
12859 POS may also be a marker."
12860 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12861 (save-excursion
12862 (save-restriction
12863 (widen)
12864 (goto-char pos)
12865 (if (org-in-regexp
12866 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12867 (replace-match ""))))))
12869 (defvar org-ts-type nil)
12870 (defun org-sparse-tree (&optional arg type)
12871 "Create a sparse tree, prompt for the details.
12872 This command can create sparse trees. You first need to select the type
12873 of match used to create the tree:
12875 t Show all TODO entries.
12876 T Show entries with a specific TODO keyword.
12877 m Show entries selected by a tags/property match.
12878 p Enter a property name and its value (both with completion on existing
12879 names/values) and show entries with that property.
12880 r Show entries matching a regular expression (`/' can be used as well).
12881 b Show deadlines and scheduled items before a date.
12882 a Show deadlines and scheduled items after a date.
12883 d Show deadlines due within `org-deadline-warning-days'.
12884 D Show deadlines and scheduled items between a date range."
12885 (interactive "P")
12886 (let (ans kwd value ts-type)
12887 (setq type (or type org-sparse-tree-default-date-type))
12888 (setq org-ts-type type)
12889 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
12890 (cond ((eq type 'all) "all timestamps")
12891 ((eq type 'scheduled) "only scheduled")
12892 ((eq type 'deadline) "only deadline")
12893 ((eq type 'active) "only active timestamps")
12894 ((eq type 'inactive) "only inactive timestamps")
12895 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12896 (t "scheduled/deadline")))
12897 (setq ans (read-char-exclusive))
12898 (cond
12899 ((equal ans ?c)
12900 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12901 ((equal ans ?d)
12902 (call-interactively 'org-check-deadlines))
12903 ((equal ans ?b)
12904 (call-interactively 'org-check-before-date))
12905 ((equal ans ?a)
12906 (call-interactively 'org-check-after-date))
12907 ((equal ans ?D)
12908 (call-interactively 'org-check-dates-range))
12909 ((equal ans ?t)
12910 (call-interactively 'org-show-todo-tree))
12911 ((equal ans ?T)
12912 (org-show-todo-tree '(4)))
12913 ((member ans '(?T ?m))
12914 (call-interactively 'org-match-sparse-tree))
12915 ((member ans '(?p ?P))
12916 (setq kwd (org-icompleting-read "Property: "
12917 (mapcar 'list (org-buffer-property-keys))))
12918 (setq value (org-icompleting-read "Value: "
12919 (mapcar 'list (org-property-values kwd))))
12920 (unless (string-match "\\`{.*}\\'" value)
12921 (setq value (concat "\"" value "\"")))
12922 (org-match-sparse-tree arg (concat kwd "=" value)))
12923 ((member ans '(?r ?R ?/))
12924 (call-interactively 'org-occur))
12925 (t (error "No such sparse tree command \"%c\"" ans)))))
12927 (defvar org-occur-highlights nil
12928 "List of overlays used for occur matches.")
12929 (make-variable-buffer-local 'org-occur-highlights)
12930 (defvar org-occur-parameters nil
12931 "Parameters of the active org-occur calls.
12932 This is a list, each call to org-occur pushes as cons cell,
12933 containing the regular expression and the callback, onto the list.
12934 The list can contain several entries if `org-occur' has been called
12935 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12936 will only contain one set of parameters. When the highlights are
12937 removed (for example with `C-c C-c', or with the next edit (depending
12938 on `org-remove-highlights-with-change'), this variable is emptied
12939 as well.")
12940 (make-variable-buffer-local 'org-occur-parameters)
12942 (defun org-occur (regexp &optional keep-previous callback)
12943 "Make a compact tree which shows all matches of REGEXP.
12944 The tree will show the lines where the regexp matches, and all higher
12945 headlines above the match. It will also show the heading after the match,
12946 to make sure editing the matching entry is easy.
12947 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12948 call to `org-occur' will be kept, to allow stacking of calls to this
12949 command.
12950 If CALLBACK is non-nil, it is a function which is called to confirm
12951 that the match should indeed be shown."
12952 (interactive "sRegexp: \nP")
12953 (when (equal regexp "")
12954 (error "Regexp cannot be empty"))
12955 (unless keep-previous
12956 (org-remove-occur-highlights nil nil t))
12957 (push (cons regexp callback) org-occur-parameters)
12958 (let ((cnt 0))
12959 (save-excursion
12960 (goto-char (point-min))
12961 (if (or (not keep-previous) ; do not want to keep
12962 (not org-occur-highlights)) ; no previous matches
12963 ;; hide everything
12964 (org-overview))
12965 (while (re-search-forward regexp nil t)
12966 (when (or (not callback)
12967 (save-match-data (funcall callback)))
12968 (setq cnt (1+ cnt))
12969 (when org-highlight-sparse-tree-matches
12970 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12971 (org-show-context 'occur-tree))))
12972 (when org-remove-highlights-with-change
12973 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12974 nil 'local))
12975 (unless org-sparse-tree-open-archived-trees
12976 (org-hide-archived-subtrees (point-min) (point-max)))
12977 (run-hooks 'org-occur-hook)
12978 (if (org-called-interactively-p 'interactive)
12979 (message "%d match(es) for regexp %s" cnt regexp))
12980 cnt))
12982 (defun org-occur-next-match (&optional n reset)
12983 "Function for `next-error-function' to find sparse tree matches.
12984 N is the number of matches to move, when negative move backwards.
12985 RESET is entirely ignored - this function always goes back to the
12986 starting point when no match is found."
12987 (let* ((limit (if (< n 0) (point-min) (point-max)))
12988 (search-func (if (< n 0)
12989 'previous-single-char-property-change
12990 'next-single-char-property-change))
12991 (n (abs n))
12992 (pos (point))
12994 (catch 'exit
12995 (while (setq p1 (funcall search-func (point) 'org-type))
12996 (when (equal p1 limit)
12997 (goto-char pos)
12998 (error "No more matches"))
12999 (when (equal (get-char-property p1 'org-type) 'org-occur)
13000 (setq n (1- n))
13001 (when (= n 0)
13002 (goto-char p1)
13003 (throw 'exit (point))))
13004 (goto-char p1))
13005 (goto-char p1)
13006 (error "No more matches"))))
13008 (defun org-show-context (&optional key)
13009 "Make sure point and context are visible.
13010 How much context is shown depends upon the variables
13011 `org-show-hierarchy-above', `org-show-following-heading',
13012 `org-show-entry-below' and `org-show-siblings'."
13013 (let ((heading-p (org-at-heading-p t))
13014 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13015 (following-p (org-get-alist-option org-show-following-heading key))
13016 (entry-p (org-get-alist-option org-show-entry-below key))
13017 (siblings-p (org-get-alist-option org-show-siblings key)))
13018 (catch 'exit
13019 ;; Show heading or entry text
13020 (if (and heading-p (not entry-p))
13021 (org-flag-heading nil) ; only show the heading
13022 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13023 (org-show-hidden-entry))) ; show entire entry
13024 (when following-p
13025 ;; Show next sibling, or heading below text
13026 (save-excursion
13027 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13028 (org-flag-heading nil))))
13029 (when siblings-p (org-show-siblings))
13030 (when hierarchy-p
13031 ;; show all higher headings, possibly with siblings
13032 (save-excursion
13033 (while (and (condition-case nil
13034 (progn (org-up-heading-all 1) t)
13035 (error nil))
13036 (not (bobp)))
13037 (org-flag-heading nil)
13038 (when siblings-p (org-show-siblings))))))))
13040 (defvar org-reveal-start-hook nil
13041 "Hook run before revealing a location.")
13043 (defun org-reveal (&optional siblings)
13044 "Show current entry, hierarchy above it, and the following headline.
13045 This can be used to show a consistent set of context around locations
13046 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13047 not t for the search context.
13049 With optional argument SIBLINGS, on each level of the hierarchy all
13050 siblings are shown. This repairs the tree structure to what it would
13051 look like when opened with hierarchical calls to `org-cycle'.
13052 With double optional argument \\[universal-argument] \\[universal-argument], \
13053 go to the parent and show the
13054 entire tree."
13055 (interactive "P")
13056 (run-hooks 'org-reveal-start-hook)
13057 (let ((org-show-hierarchy-above t)
13058 (org-show-following-heading t)
13059 (org-show-siblings (if siblings t org-show-siblings)))
13060 (org-show-context nil))
13061 (when (equal siblings '(16))
13062 (save-excursion
13063 (when (org-up-heading-safe)
13064 (org-show-subtree)
13065 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13067 (defun org-highlight-new-match (beg end)
13068 "Highlight from BEG to END and mark the highlight is an occur headline."
13069 (let ((ov (make-overlay beg end)))
13070 (overlay-put ov 'face 'secondary-selection)
13071 (overlay-put ov 'org-type 'org-occur)
13072 (push ov org-occur-highlights)))
13074 (defun org-remove-occur-highlights (&optional beg end noremove)
13075 "Remove the occur highlights from the buffer.
13076 BEG and END are ignored. If NOREMOVE is nil, remove this function
13077 from the `before-change-functions' in the current buffer."
13078 (interactive)
13079 (unless org-inhibit-highlight-removal
13080 (mapc 'delete-overlay org-occur-highlights)
13081 (setq org-occur-highlights nil)
13082 (setq org-occur-parameters nil)
13083 (unless noremove
13084 (remove-hook 'before-change-functions
13085 'org-remove-occur-highlights 'local))))
13087 ;;;; Priorities
13089 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13090 "Regular expression matching the priority indicator.")
13092 (defvar org-remove-priority-next-time nil)
13094 (defun org-priority-up ()
13095 "Increase the priority of the current item."
13096 (interactive)
13097 (org-priority 'up))
13099 (defun org-priority-down ()
13100 "Decrease the priority of the current item."
13101 (interactive)
13102 (org-priority 'down))
13104 (defun org-priority (&optional action show)
13105 "Change the priority of an item.
13106 ACTION can be `set', `up', `down', or a character."
13107 (interactive "P")
13108 (if (equal action '(4))
13109 (org-show-priority)
13110 (unless org-enable-priority-commands
13111 (error "Priority commands are disabled"))
13112 (setq action (or action 'set))
13113 (let (current new news have remove)
13114 (save-excursion
13115 (org-back-to-heading t)
13116 (if (looking-at org-priority-regexp)
13117 (setq current (string-to-char (match-string 2))
13118 have t))
13119 (cond
13120 ((eq action 'remove)
13121 (setq remove t new ?\ ))
13122 ((or (eq action 'set)
13123 (if (featurep 'xemacs) (characterp action) (integerp action)))
13124 (if (not (eq action 'set))
13125 (setq new action)
13126 (message "Priority %c-%c, SPC to remove: "
13127 org-highest-priority org-lowest-priority)
13128 (save-match-data
13129 (setq new (read-char-exclusive))))
13130 (if (and (= (upcase org-highest-priority) org-highest-priority)
13131 (= (upcase org-lowest-priority) org-lowest-priority))
13132 (setq new (upcase new)))
13133 (cond ((equal new ?\ ) (setq remove t))
13134 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13135 (error "Priority must be between `%c' and `%c'"
13136 org-highest-priority org-lowest-priority))))
13137 ((eq action 'up)
13138 (setq new (if have
13139 (1- current) ; normal cycling
13140 ;; last priority was empty
13141 (if (eq last-command this-command)
13142 org-lowest-priority ; wrap around empty to lowest
13143 ;; default
13144 (if org-priority-start-cycle-with-default
13145 org-default-priority
13146 (1- org-default-priority))))))
13147 ((eq action 'down)
13148 (setq new (if have
13149 (1+ current) ; normal cycling
13150 ;; last priority was empty
13151 (if (eq last-command this-command)
13152 org-highest-priority ; wrap around empty to highest
13153 ;; default
13154 (if org-priority-start-cycle-with-default
13155 org-default-priority
13156 (1+ org-default-priority))))))
13157 (t (error "Invalid action")))
13158 (if (or (< (upcase new) org-highest-priority)
13159 (> (upcase new) org-lowest-priority))
13160 (if (and (memq action '(up down))
13161 (not have) (not (eq last-command this-command)))
13162 ;; `new' is from default priority
13163 (error
13164 "The default can not be set, see `org-default-priority' why")
13165 ;; normal cycling: `new' is beyond highest/lowest priority
13166 ;; and is wrapped around to the empty priority
13167 (setq remove t)))
13168 (setq news (format "%c" new))
13169 (if have
13170 (if remove
13171 (replace-match "" t t nil 1)
13172 (replace-match news t t nil 2))
13173 (if remove
13174 (error "No priority cookie found in line")
13175 (let ((case-fold-search nil))
13176 (looking-at org-todo-line-regexp))
13177 (if (match-end 2)
13178 (progn
13179 (goto-char (match-end 2))
13180 (insert " [#" news "]"))
13181 (goto-char (match-beginning 3))
13182 (insert "[#" news "] "))))
13183 (org-preserve-lc (org-set-tags nil 'align)))
13184 (if remove
13185 (message "Priority removed")
13186 (message "Priority of current item set to %s" news)))))
13188 (defun org-show-priority ()
13189 "Show the priority of the current item.
13190 This priority is composed of the main priority given with the [#A] cookies,
13191 and by additional input from the age of a schedules or deadline entry."
13192 (interactive)
13193 (let ((pri (if (eq major-mode 'org-agenda-mode)
13194 (org-get-at-bol 'priority)
13195 (save-excursion
13196 (save-match-data
13197 (beginning-of-line)
13198 (and (looking-at org-heading-regexp)
13199 (org-get-priority (match-string 0))))))))
13200 (message "Priority is %d" (if pri pri -1000))))
13202 (defun org-get-priority (s)
13203 "Find priority cookie and return priority."
13204 (if (functionp org-get-priority-function)
13205 (funcall org-get-priority-function)
13206 (save-match-data
13207 (if (not (string-match org-priority-regexp s))
13208 (* 1000 (- org-lowest-priority org-default-priority))
13209 (* 1000 (- org-lowest-priority
13210 (string-to-char (match-string 2 s))))))))
13212 ;;;; Tags
13214 (defvar org-agenda-archives-mode)
13215 (defvar org-map-continue-from nil
13216 "Position from where mapping should continue.
13217 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13219 (defvar org-scanner-tags nil
13220 "The current tag list while the tags scanner is running.")
13221 (defvar org-trust-scanner-tags nil
13222 "Should `org-get-tags-at' use the tags for the scanner.
13223 This is for internal dynamical scoping only.
13224 When this is non-nil, the function `org-get-tags-at' will return the value
13225 of `org-scanner-tags' instead of building the list by itself. This
13226 can lead to large speed-ups when the tags scanner is used in a file with
13227 many entries, and when the list of tags is retrieved, for example to
13228 obtain a list of properties. Building the tags list for each entry in such
13229 a file becomes an N^2 operation - but with this variable set, it scales
13230 as N.")
13232 (defun org-scan-tags (action matcher todo-only &optional start-level)
13233 "Scan headline tags with inheritance and produce output ACTION.
13235 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13236 or `agenda' to produce an entry list for an agenda view. It can also be
13237 a Lisp form or a function that should be called at each matched headline, in
13238 this case the return value is a list of all return values from these calls.
13240 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13241 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13242 only lines with a not-done TODO keyword are included in the output.
13243 This should be the same variable that was scoped into
13244 and set by `org-make-tags-matcher' when it constructed MATCHER.
13246 START-LEVEL can be a string with asterisks, reducing the scope to
13247 headlines matching this string."
13248 (require 'org-agenda)
13249 (let* ((re (concat "^"
13250 (if start-level
13251 ;; Get the correct level to match
13252 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13253 org-outline-regexp)
13254 " *\\(\\<\\("
13255 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13256 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13257 (props (list 'face 'default
13258 'done-face 'org-agenda-done
13259 'undone-face 'default
13260 'mouse-face 'highlight
13261 'org-not-done-regexp org-not-done-regexp
13262 'org-todo-regexp org-todo-regexp
13263 'org-complex-heading-regexp org-complex-heading-regexp
13264 'help-echo
13265 (format "mouse-2 or RET jump to org file %s"
13266 (abbreviate-file-name
13267 (or (buffer-file-name (buffer-base-buffer))
13268 (buffer-name (buffer-base-buffer)))))))
13269 (case-fold-search nil)
13270 (org-map-continue-from nil)
13271 lspos tags tags-list
13272 (tags-alist (list (cons 0 org-file-tags)))
13273 (llast 0) rtn rtn1 level category i txt
13274 todo marker entry priority)
13275 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13276 (setq action (list 'lambda nil action)))
13277 (save-excursion
13278 (goto-char (point-min))
13279 (when (eq action 'sparse-tree)
13280 (org-overview)
13281 (org-remove-occur-highlights))
13282 (while (re-search-forward re nil t)
13283 (setq org-map-continue-from nil)
13284 (catch :skip
13285 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13286 tags (if (match-end 4) (org-match-string-no-properties 4)))
13287 (goto-char (setq lspos (match-beginning 0)))
13288 (setq level (org-reduced-level (org-outline-level))
13289 category (org-get-category))
13290 (setq i llast llast level)
13291 ;; remove tag lists from same and sublevels
13292 (while (>= i level)
13293 (when (setq entry (assoc i tags-alist))
13294 (setq tags-alist (delete entry tags-alist)))
13295 (setq i (1- i)))
13296 ;; add the next tags
13297 (when tags
13298 (setq tags (org-split-string tags ":")
13299 tags-alist
13300 (cons (cons level tags) tags-alist)))
13301 ;; compile tags for current headline
13302 (setq tags-list
13303 (if org-use-tag-inheritance
13304 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13305 tags)
13306 org-scanner-tags tags-list)
13307 (when org-use-tag-inheritance
13308 (setcdr (car tags-alist)
13309 (mapcar (lambda (x)
13310 (setq x (copy-sequence x))
13311 (org-add-prop-inherited x))
13312 (cdar tags-alist))))
13313 (when (and tags org-use-tag-inheritance
13314 (or (not (eq t org-use-tag-inheritance))
13315 org-tags-exclude-from-inheritance))
13316 ;; selective inheritance, remove uninherited ones
13317 (setcdr (car tags-alist)
13318 (org-remove-uninherited-tags (cdar tags-alist))))
13319 (when (and
13321 ;; eval matcher only when the todo condition is OK
13322 (and (or (not todo-only) (member todo org-not-done-keywords))
13323 (let ((case-fold-search t) (org-trust-scanner-tags t))
13324 (eval matcher)))
13326 ;; Call the skipper, but return t if it does not skip,
13327 ;; so that the `and' form continues evaluating
13328 (progn
13329 (unless (eq action 'sparse-tree) (org-agenda-skip))
13332 ;; Check if timestamps are deselecting this entry
13333 (or (not todo-only)
13334 (and (member todo org-not-done-keywords)
13335 (or (not org-agenda-tags-todo-honor-ignore-options)
13336 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13338 ;; Extra check for the archive tag
13339 ;; FIXME: Does the skipper already do this????
13341 (not (member org-archive-tag tags-list))
13342 ;; we have an archive tag, should we use this anyway?
13343 (or (not org-agenda-skip-archived-trees)
13344 (and (eq action 'agenda) org-agenda-archives-mode))))
13346 ;; select this headline
13347 (cond
13348 ((eq action 'sparse-tree)
13349 (and org-highlight-sparse-tree-matches
13350 (org-get-heading) (match-end 0)
13351 (org-highlight-new-match
13352 (match-beginning 1) (match-end 1)))
13353 (org-show-context 'tags-tree))
13354 ((eq action 'agenda)
13355 (setq txt (org-agenda-format-item
13357 (concat
13358 (if (eq org-tags-match-list-sublevels 'indented)
13359 (make-string (1- level) ?.) "")
13360 (org-get-heading))
13361 level category
13362 tags-list)
13363 priority (org-get-priority txt))
13364 (goto-char lspos)
13365 (setq marker (org-agenda-new-marker))
13366 (org-add-props txt props
13367 'org-marker marker 'org-hd-marker marker 'org-category category
13368 'todo-state todo
13369 'priority priority 'type "tagsmatch")
13370 (push txt rtn))
13371 ((functionp action)
13372 (setq org-map-continue-from nil)
13373 (save-excursion
13374 (setq rtn1 (funcall action))
13375 (push rtn1 rtn)))
13376 (t (error "Invalid action")))
13378 ;; if we are to skip sublevels, jump to end of subtree
13379 (unless org-tags-match-list-sublevels
13380 (org-end-of-subtree t)
13381 (backward-char 1))))
13382 ;; Get the correct position from where to continue
13383 (if org-map-continue-from
13384 (goto-char org-map-continue-from)
13385 (and (= (point) lspos) (end-of-line 1)))))
13386 (when (and (eq action 'sparse-tree)
13387 (not org-sparse-tree-open-archived-trees))
13388 (org-hide-archived-subtrees (point-min) (point-max)))
13389 (nreverse rtn)))
13391 (defun org-remove-uninherited-tags (tags)
13392 "Remove all tags that are not inherited from the list TAGS."
13393 (cond
13394 ((eq org-use-tag-inheritance t)
13395 (if org-tags-exclude-from-inheritance
13396 (org-delete-all org-tags-exclude-from-inheritance tags)
13397 tags))
13398 ((not org-use-tag-inheritance) nil)
13399 ((stringp org-use-tag-inheritance)
13400 (delq nil (mapcar
13401 (lambda (x)
13402 (if (and (string-match org-use-tag-inheritance x)
13403 (not (member x org-tags-exclude-from-inheritance)))
13404 x nil))
13405 tags)))
13406 ((listp org-use-tag-inheritance)
13407 (delq nil (mapcar
13408 (lambda (x)
13409 (if (member x org-use-tag-inheritance) x nil))
13410 tags)))))
13412 (defun org-match-sparse-tree (&optional todo-only match)
13413 "Create a sparse tree according to tags string MATCH.
13414 MATCH can contain positive and negative selection of tags, like
13415 \"+WORK+URGENT-WITHBOSS\".
13416 If optional argument TODO-ONLY is non-nil, only select lines that are
13417 also TODO lines."
13418 (interactive "P")
13419 (org-agenda-prepare-buffers (list (current-buffer)))
13420 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13422 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13424 (defvar org-cached-props nil)
13425 (defun org-cached-entry-get (pom property)
13426 (if (or (eq t org-use-property-inheritance)
13427 (and (stringp org-use-property-inheritance)
13428 (string-match org-use-property-inheritance property))
13429 (and (listp org-use-property-inheritance)
13430 (member property org-use-property-inheritance)))
13431 ;; Caching is not possible, check it directly
13432 (org-entry-get pom property 'inherit)
13433 ;; Get all properties, so that we can do complicated checks easily
13434 (cdr (assoc property (or org-cached-props
13435 (setq org-cached-props
13436 (org-entry-properties pom)))))))
13438 (defun org-global-tags-completion-table (&optional files)
13439 "Return the list of all tags in all agenda buffer/files.
13440 Optional FILES argument is a list of files which can be used
13441 instead of the agenda files."
13442 (save-excursion
13443 (org-uniquify
13444 (delq nil
13445 (apply 'append
13446 (mapcar
13447 (lambda (file)
13448 (set-buffer (find-file-noselect file))
13449 (append (org-get-buffer-tags)
13450 (mapcar (lambda (x) (if (stringp (car-safe x))
13451 (list (car-safe x)) nil))
13452 org-tag-alist)))
13453 (if (and files (car files))
13454 files
13455 (org-agenda-files))))))))
13457 (defun org-make-tags-matcher (match)
13458 "Create the TAGS/TODO matcher form for the selection string MATCH.
13460 The variable `todo-only' is scoped dynamically into this function.
13461 It will be set to t if the matcher restricts matching to TODO entries,
13462 otherwise will not be touched.
13464 Returns a cons of the selection string MATCH and the constructed
13465 lisp form implementing the matcher. The matcher is to be evaluated
13466 at an Org entry, with point on the headline, and returns t if the
13467 entry matches the selection string MATCH. The returned lisp form
13468 references two variables with information about the entry, which
13469 must be bound around the form's evaluation: todo, the TODO keyword
13470 at the entry (or nil of none); and tags-list, the list of all tags
13471 at the entry including inherited ones. Additionally, the category
13472 of the entry (if any) must be specified as the text property
13473 'org-category on the headline.
13475 See also `org-scan-tags'.
13477 (declare (special todo-only))
13478 (unless (boundp 'todo-only)
13479 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13480 (unless match
13481 ;; Get a new match request, with completion
13482 (let ((org-last-tags-completion-table
13483 (org-global-tags-completion-table)))
13484 (setq match (org-completing-read-no-i
13485 "Match: " 'org-tags-completion-function nil nil nil
13486 'org-tags-history))))
13488 ;; Parse the string and create a lisp form
13489 (let ((match0 match)
13490 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13491 minus tag mm
13492 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13493 orterms term orlist re-p str-p level-p level-op time-p
13494 prop-p pn pv po gv rest)
13495 (if (string-match "/+" match)
13496 ;; match contains also a todo-matching request
13497 (progn
13498 (setq tagsmatch (substring match 0 (match-beginning 0))
13499 todomatch (substring match (match-end 0)))
13500 (if (string-match "^!" todomatch)
13501 (setq todo-only t todomatch (substring todomatch 1)))
13502 (if (string-match "^\\s-*$" todomatch)
13503 (setq todomatch nil)))
13504 ;; only matching tags
13505 (setq tagsmatch match todomatch nil))
13507 ;; Make the tags matcher
13508 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13509 (setq tagsmatcher t)
13510 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13511 (while (setq term (pop orterms))
13512 (while (and (equal (substring term -1) "\\") orterms)
13513 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13514 (while (string-match re term)
13515 (setq rest (substring term (match-end 0))
13516 minus (and (match-end 1)
13517 (equal (match-string 1 term) "-"))
13518 tag (save-match-data (replace-regexp-in-string
13519 "\\\\-" "-"
13520 (match-string 2 term)))
13521 re-p (equal (string-to-char tag) ?{)
13522 level-p (match-end 4)
13523 prop-p (match-end 5)
13524 mm (cond
13525 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13526 (level-p
13527 (setq level-op (org-op-to-function (match-string 3 term)))
13528 `(,level-op level ,(string-to-number
13529 (match-string 4 term))))
13530 (prop-p
13531 (setq pn (match-string 5 term)
13532 po (match-string 6 term)
13533 pv (match-string 7 term)
13534 re-p (equal (string-to-char pv) ?{)
13535 str-p (equal (string-to-char pv) ?\")
13536 time-p (save-match-data
13537 (string-match "^\"[[<].*[]>]\"$" pv))
13538 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13539 (if time-p (setq pv (org-matcher-time pv)))
13540 (setq po (org-op-to-function po (if time-p 'time str-p)))
13541 (cond
13542 ((equal pn "CATEGORY")
13543 (setq gv '(get-text-property (point) 'org-category)))
13544 ((equal pn "TODO")
13545 (setq gv 'todo))
13547 (setq gv `(org-cached-entry-get nil ,pn))))
13548 (if re-p
13549 (if (eq po 'org<>)
13550 `(not (string-match ,pv (or ,gv "")))
13551 `(string-match ,pv (or ,gv "")))
13552 (if str-p
13553 `(,po (or ,gv "") ,pv)
13554 `(,po (string-to-number (or ,gv ""))
13555 ,(string-to-number pv) ))))
13556 (t `(member ,tag tags-list)))
13557 mm (if minus (list 'not mm) mm)
13558 term rest)
13559 (push mm tagsmatcher))
13560 (push (if (> (length tagsmatcher) 1)
13561 (cons 'and tagsmatcher)
13562 (car tagsmatcher))
13563 orlist)
13564 (setq tagsmatcher nil))
13565 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13566 (setq tagsmatcher
13567 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13568 ;; Make the todo matcher
13569 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13570 (setq todomatcher t)
13571 (setq orterms (org-split-string todomatch "|") orlist nil)
13572 (while (setq term (pop orterms))
13573 (while (string-match re term)
13574 (setq minus (and (match-end 1)
13575 (equal (match-string 1 term) "-"))
13576 kwd (match-string 2 term)
13577 re-p (equal (string-to-char kwd) ?{)
13578 term (substring term (match-end 0))
13579 mm (if re-p
13580 `(string-match ,(substring kwd 1 -1) todo)
13581 (list 'equal 'todo kwd))
13582 mm (if minus (list 'not mm) mm))
13583 (push mm todomatcher))
13584 (push (if (> (length todomatcher) 1)
13585 (cons 'and todomatcher)
13586 (car todomatcher))
13587 orlist)
13588 (setq todomatcher nil))
13589 (setq todomatcher (if (> (length orlist) 1)
13590 (cons 'or orlist) (car orlist))))
13592 ;; Return the string and lisp forms of the matcher
13593 (setq matcher (if todomatcher
13594 (list 'and tagsmatcher todomatcher)
13595 tagsmatcher))
13596 (when todo-only
13597 (setq matcher (list 'and '(member todo org-not-done-keywords)
13598 matcher)))
13599 (cons match0 matcher)))
13601 (defun org-op-to-function (op &optional stringp)
13602 "Turn an operator into the appropriate function."
13603 (setq op
13604 (cond
13605 ((equal op "<" ) '(< string< org-time<))
13606 ((equal op ">" ) '(> org-string> org-time>))
13607 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13608 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13609 ((member op '("=" "==")) '(= string= org-time=))
13610 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13611 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13613 (defun org<> (a b) (not (= a b)))
13614 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13615 (defun org-string>= (a b) (not (string< a b)))
13616 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13617 (defun org-string<> (a b) (not (string= a b)))
13618 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13619 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13620 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13621 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13622 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13623 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13624 (defun org-2ft (s)
13625 "Convert S to a floating point time.
13626 If S is already a number, just return it. If it is a string, parse
13627 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13628 (cond
13629 ((numberp s) s)
13630 ((stringp s)
13631 (condition-case nil
13632 (float-time (apply 'encode-time (org-parse-time-string s)))
13633 (error 0.)))
13634 (t 0.)))
13636 (defun org-time-today ()
13637 "Time in seconds today at 0:00.
13638 Returns the float number of seconds since the beginning of the
13639 epoch to the beginning of today (00:00)."
13640 (float-time (apply 'encode-time
13641 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13643 (defun org-matcher-time (s)
13644 "Interpret a time comparison value."
13645 (save-match-data
13646 (cond
13647 ((string= s "<now>") (float-time))
13648 ((string= s "<today>") (org-time-today))
13649 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13650 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13651 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13652 (+ (org-time-today)
13653 (* (string-to-number (match-string 1 s))
13654 (cdr (assoc (match-string 2 s)
13655 '(("d" . 86400.0) ("w" . 604800.0)
13656 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13657 (t (org-2ft s)))))
13659 (defun org-match-any-p (re list)
13660 "Does re match any element of list?"
13661 (setq list (mapcar (lambda (x) (string-match re x)) list))
13662 (delq nil list))
13664 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13665 (defvar org-tags-overlay (make-overlay 1 1))
13666 (org-detach-overlay org-tags-overlay)
13668 (defun org-get-local-tags-at (&optional pos)
13669 "Get a list of tags defined in the current headline."
13670 (org-get-tags-at pos 'local))
13672 (defun org-get-local-tags ()
13673 "Get a list of tags defined in the current headline."
13674 (org-get-tags-at nil 'local))
13676 (defun org-get-tags-at (&optional pos local)
13677 "Get a list of all headline tags applicable at POS.
13678 POS defaults to point. If tags are inherited, the list contains
13679 the targets in the same sequence as the headlines appear, i.e.
13680 the tags of the current headline come last.
13681 When LOCAL is non-nil, only return tags from the current headline,
13682 ignore inherited ones."
13683 (interactive)
13684 (if (and org-trust-scanner-tags
13685 (or (not pos) (equal pos (point)))
13686 (not local))
13687 org-scanner-tags
13688 (let (tags ltags lastpos parent)
13689 (save-excursion
13690 (save-restriction
13691 (widen)
13692 (goto-char (or pos (point)))
13693 (save-match-data
13694 (catch 'done
13695 (condition-case nil
13696 (progn
13697 (org-back-to-heading t)
13698 (while (not (equal lastpos (point)))
13699 (setq lastpos (point))
13700 (when (looking-at
13701 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13702 (setq ltags (org-split-string
13703 (org-match-string-no-properties 1) ":"))
13704 (when parent
13705 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13706 (setq tags (append
13707 (if parent
13708 (org-remove-uninherited-tags ltags)
13709 ltags)
13710 tags)))
13711 (or org-use-tag-inheritance (throw 'done t))
13712 (if local (throw 'done t))
13713 (or (org-up-heading-safe) (error nil))
13714 (setq parent t)))
13715 (error nil)))))
13716 (if local
13717 tags
13718 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13720 (defun org-add-prop-inherited (s)
13721 (add-text-properties 0 (length s) '(inherited t) s)
13724 (defun org-toggle-tag (tag &optional onoff)
13725 "Toggle the tag TAG for the current line.
13726 If ONOFF is `on' or `off', don't toggle but set to this state."
13727 (let (res current)
13728 (save-excursion
13729 (org-back-to-heading t)
13730 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13731 (point-at-eol) t)
13732 (progn
13733 (setq current (match-string 1))
13734 (replace-match ""))
13735 (setq current ""))
13736 (setq current (nreverse (org-split-string current ":")))
13737 (cond
13738 ((eq onoff 'on)
13739 (setq res t)
13740 (or (member tag current) (push tag current)))
13741 ((eq onoff 'off)
13742 (or (not (member tag current)) (setq current (delete tag current))))
13743 (t (if (member tag current)
13744 (setq current (delete tag current))
13745 (setq res t)
13746 (push tag current))))
13747 (end-of-line 1)
13748 (if current
13749 (progn
13750 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13751 (org-set-tags nil t))
13752 (delete-horizontal-space))
13753 (run-hooks 'org-after-tags-change-hook))
13754 res))
13756 (defun org-align-tags-here (to-col)
13757 ;; Assumes that this is a headline
13758 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13759 (beginning-of-line 1)
13760 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13761 (< pos (match-beginning 2)))
13762 (progn
13763 (setq tags-l (- (match-end 2) (match-beginning 2)))
13764 (goto-char (match-beginning 1))
13765 (insert " ")
13766 (delete-region (point) (1+ (match-beginning 2)))
13767 (setq ncol (max (current-column)
13768 (1+ col)
13769 (if (> to-col 0)
13770 to-col
13771 (- (abs to-col) tags-l))))
13772 (setq p (point))
13773 (insert (make-string (- ncol (current-column)) ?\ ))
13774 (setq ncol (current-column))
13775 (when indent-tabs-mode (tabify p (point-at-eol)))
13776 (org-move-to-column (min ncol col) t))
13777 (goto-char pos))))
13779 (defun org-set-tags-command (&optional arg just-align)
13780 "Call the set-tags command for the current entry."
13781 (interactive "P")
13782 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13783 (org-set-tags arg just-align)
13784 (save-excursion
13785 (org-back-to-heading t)
13786 (org-set-tags arg just-align))))
13788 (defun org-set-tags-to (data)
13789 "Set the tags of the current entry to DATA, replacing the current tags.
13790 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13791 If DATA is nil or the empty string, any tags will be removed."
13792 (interactive "sTags: ")
13793 (setq data
13794 (cond
13795 ((eq data nil) "")
13796 ((equal data "") "")
13797 ((stringp data)
13798 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13799 ":"))
13800 ((listp data)
13801 (concat ":" (mapconcat 'identity data ":") ":"))))
13802 (when data
13803 (save-excursion
13804 (org-back-to-heading t)
13805 (when (looking-at org-complex-heading-regexp)
13806 (if (match-end 5)
13807 (progn
13808 (goto-char (match-beginning 5))
13809 (insert data)
13810 (delete-region (point) (point-at-eol))
13811 (org-set-tags nil 'align))
13812 (goto-char (point-at-eol))
13813 (insert " " data)
13814 (org-set-tags nil 'align)))
13815 (beginning-of-line 1)
13816 (if (looking-at ".*?\\([ \t]+\\)$")
13817 (delete-region (match-beginning 1) (match-end 1))))))
13819 (defun org-align-all-tags ()
13820 "Align the tags i all headings."
13821 (interactive)
13822 (save-excursion
13823 (or (ignore-errors (org-back-to-heading t))
13824 (outline-next-heading))
13825 (if (org-at-heading-p)
13826 (org-set-tags t)
13827 (message "No headings"))))
13829 (defvar org-indent-indentation-per-level)
13830 (defun org-set-tags (&optional arg just-align)
13831 "Set the tags for the current headline.
13832 With prefix ARG, realign all tags in headings in the current buffer."
13833 (interactive "P")
13834 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13835 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13836 'region-start-level 'region))
13837 org-loop-over-headlines-in-active-region)
13838 (org-map-entries
13839 ;; We don't use ARG and JUST-ALIGN here these args are not
13840 ;; useful when looping over headlines
13841 `(org-set-tags)
13842 org-loop-over-headlines-in-active-region
13843 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13844 (let* ((re org-outline-regexp-bol)
13845 (current (unless arg (org-get-tags-string)))
13846 (col (current-column))
13847 (org-setting-tags t)
13848 table current-tags inherited-tags ; computed below when needed
13849 tags p0 c0 c1 rpl di tc level)
13850 (if arg
13851 (save-excursion
13852 (goto-char (point-min))
13853 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13854 (while (re-search-forward re nil t)
13855 (org-set-tags nil t)
13856 (end-of-line 1)))
13857 (message "All tags realigned to column %d" org-tags-column))
13858 (if just-align
13859 (setq tags current)
13860 ;; Get a new set of tags from the user
13861 (save-excursion
13862 (setq table (append org-tag-persistent-alist
13863 (or org-tag-alist (org-get-buffer-tags))
13864 (and
13865 org-complete-tags-always-offer-all-agenda-tags
13866 (org-global-tags-completion-table
13867 (org-agenda-files))))
13868 org-last-tags-completion-table table
13869 current-tags (org-split-string current ":")
13870 inherited-tags (nreverse
13871 (nthcdr (length current-tags)
13872 (nreverse (org-get-tags-at))))
13873 tags
13874 (if (or (eq t org-use-fast-tag-selection)
13875 (and org-use-fast-tag-selection
13876 (delq nil (mapcar 'cdr table))))
13877 (org-fast-tag-selection
13878 current-tags inherited-tags table
13879 (if org-fast-tag-selection-include-todo
13880 org-todo-key-alist))
13881 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13882 (org-trim
13883 (org-icompleting-read "Tags: "
13884 'org-tags-completion-function
13885 nil nil current 'org-tags-history))))))
13886 (while (string-match "[-+&]+" tags)
13887 ;; No boolean logic, just a list
13888 (setq tags (replace-match ":" t t tags))))
13890 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13892 (if org-tags-sort-function
13893 (setq tags (mapconcat 'identity
13894 (sort (org-split-string
13895 tags (org-re "[^[:alnum:]_@#%]+"))
13896 org-tags-sort-function) ":")))
13898 (if (string-match "\\`[\t ]*\\'" tags)
13899 (setq tags "")
13900 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13901 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13903 ;; Insert new tags at the correct column
13904 (beginning-of-line 1)
13905 (setq level (or (and (looking-at org-outline-regexp)
13906 (- (match-end 0) (point) 1))
13908 (cond
13909 ((and (equal current "") (equal tags "")))
13910 ((re-search-forward
13911 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13912 (point-at-eol) t)
13913 (if (equal tags "")
13914 (setq rpl "")
13915 (goto-char (match-beginning 0))
13916 (setq c0 (current-column)
13917 ;; compute offset for the case of org-indent-mode active
13918 di (if org-indent-mode
13919 (* (1- org-indent-indentation-per-level) (1- level))
13921 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13922 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13923 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13924 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13925 (replace-match rpl t t)
13926 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13927 tags)
13928 (t (error "Tags alignment failed")))
13929 (org-move-to-column col)
13930 (unless just-align
13931 (run-hooks 'org-after-tags-change-hook))))))
13933 (defun org-change-tag-in-region (beg end tag off)
13934 "Add or remove TAG for each entry in the region.
13935 This works in the agenda, and also in an org-mode buffer."
13936 (interactive
13937 (list (region-beginning) (region-end)
13938 (let ((org-last-tags-completion-table
13939 (if (derived-mode-p 'org-mode)
13940 (org-get-buffer-tags)
13941 (org-global-tags-completion-table))))
13942 (org-icompleting-read
13943 "Tag: " 'org-tags-completion-function nil nil nil
13944 'org-tags-history))
13945 (progn
13946 (message "[s]et or [r]emove? ")
13947 (equal (read-char-exclusive) ?r))))
13948 (if (fboundp 'deactivate-mark) (deactivate-mark))
13949 (let ((agendap (equal major-mode 'org-agenda-mode))
13950 l1 l2 m buf pos newhead (cnt 0))
13951 (goto-char end)
13952 (setq l2 (1- (org-current-line)))
13953 (goto-char beg)
13954 (setq l1 (org-current-line))
13955 (loop for l from l1 to l2 do
13956 (org-goto-line l)
13957 (setq m (get-text-property (point) 'org-hd-marker))
13958 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13959 (and agendap m))
13960 (setq buf (if agendap (marker-buffer m) (current-buffer))
13961 pos (if agendap m (point)))
13962 (with-current-buffer buf
13963 (save-excursion
13964 (save-restriction
13965 (goto-char pos)
13966 (setq cnt (1+ cnt))
13967 (org-toggle-tag tag (if off 'off 'on))
13968 (setq newhead (org-get-heading)))))
13969 (and agendap (org-agenda-change-all-lines newhead m))))
13970 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13972 (defun org-tags-completion-function (string predicate &optional flag)
13973 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13974 (confirm (lambda (x) (stringp (car x)))))
13975 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13976 (setq s1 (match-string 1 string)
13977 s2 (match-string 2 string))
13978 (setq s1 "" s2 string))
13979 (cond
13980 ((eq flag nil)
13981 ;; try completion
13982 (setq rtn (try-completion s2 ctable confirm))
13983 (if (stringp rtn)
13984 (setq rtn
13985 (concat s1 s2 (substring rtn (length s2))
13986 (if (and org-add-colon-after-tag-completion
13987 (assoc rtn ctable))
13988 ":" ""))))
13989 rtn)
13990 ((eq flag t)
13991 ;; all-completions
13992 (all-completions s2 ctable confirm)
13994 ((eq flag 'lambda)
13995 ;; exact match?
13996 (assoc s2 ctable)))
13999 (defun org-fast-tag-insert (kwd tags face &optional end)
14000 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14001 (insert (format "%-12s" (concat kwd ":"))
14002 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14003 (or end "")))
14005 (defun org-fast-tag-show-exit (flag)
14006 (save-excursion
14007 (org-goto-line 3)
14008 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14009 (replace-match ""))
14010 (when flag
14011 (end-of-line 1)
14012 (org-move-to-column (- (window-width) 19) t)
14013 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14015 (defun org-set-current-tags-overlay (current prefix)
14016 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14017 (if (featurep 'xemacs)
14018 (org-overlay-display org-tags-overlay (concat prefix s)
14019 'secondary-selection)
14020 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14021 (org-overlay-display org-tags-overlay (concat prefix s)))))
14023 (defvar org-last-tag-selection-key nil)
14024 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14025 "Fast tag selection with single keys.
14026 CURRENT is the current list of tags in the headline, INHERITED is the
14027 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14028 possibly with grouping information. TODO-TABLE is a similar table with
14029 TODO keywords, should these have keys assigned to them.
14030 If the keys are nil, a-z are automatically assigned.
14031 Returns the new tags string, or nil to not change the current settings."
14032 (let* ((fulltable (append table todo-table))
14033 (maxlen (apply 'max (mapcar
14034 (lambda (x)
14035 (if (stringp (car x)) (string-width (car x)) 0))
14036 fulltable)))
14037 (buf (current-buffer))
14038 (expert (eq org-fast-tag-selection-single-key 'expert))
14039 (buffer-tags nil)
14040 (fwidth (+ maxlen 3 1 3))
14041 (ncol (/ (- (window-width) 4) fwidth))
14042 (i-face 'org-done)
14043 (c-face 'org-todo)
14044 tg cnt e c char c1 c2 ntable tbl rtn
14045 ov-start ov-end ov-prefix
14046 (exit-after-next org-fast-tag-selection-single-key)
14047 (done-keywords org-done-keywords)
14048 groups ingroup)
14049 (save-excursion
14050 (beginning-of-line 1)
14051 (if (looking-at
14052 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14053 (setq ov-start (match-beginning 1)
14054 ov-end (match-end 1)
14055 ov-prefix "")
14056 (setq ov-start (1- (point-at-eol))
14057 ov-end (1+ ov-start))
14058 (skip-chars-forward "^\n\r")
14059 (setq ov-prefix
14060 (concat
14061 (buffer-substring (1- (point)) (point))
14062 (if (> (current-column) org-tags-column)
14064 (make-string (- org-tags-column (current-column)) ?\ ))))))
14065 (move-overlay org-tags-overlay ov-start ov-end)
14066 (save-window-excursion
14067 (if expert
14068 (set-buffer (get-buffer-create " *Org tags*"))
14069 (delete-other-windows)
14070 (split-window-vertically)
14071 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14072 (erase-buffer)
14073 (org-set-local 'org-done-keywords done-keywords)
14074 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14075 (org-fast-tag-insert "Current" current c-face "\n\n")
14076 (org-fast-tag-show-exit exit-after-next)
14077 (org-set-current-tags-overlay current ov-prefix)
14078 (setq tbl fulltable char ?a cnt 0)
14079 (while (setq e (pop tbl))
14080 (cond
14081 ((equal (car e) :startgroup)
14082 (push '() groups) (setq ingroup t)
14083 (when (not (= cnt 0))
14084 (setq cnt 0)
14085 (insert "\n"))
14086 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14087 ((equal (car e) :endgroup)
14088 (setq ingroup nil cnt 0)
14089 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14090 ((equal e '(:newline))
14091 (when (not (= cnt 0))
14092 (setq cnt 0)
14093 (insert "\n")
14094 (setq e (car tbl))
14095 (while (equal (car tbl) '(:newline))
14096 (insert "\n")
14097 (setq tbl (cdr tbl)))))
14099 (setq tg (copy-sequence (car e)) c2 nil)
14100 (if (cdr e)
14101 (setq c (cdr e))
14102 ;; automatically assign a character.
14103 (setq c1 (string-to-char
14104 (downcase (substring
14105 tg (if (= (string-to-char tg) ?@) 1 0)))))
14106 (if (or (rassoc c1 ntable) (rassoc c1 table))
14107 (while (or (rassoc char ntable) (rassoc char table))
14108 (setq char (1+ char)))
14109 (setq c2 c1))
14110 (setq c (or c2 char)))
14111 (if ingroup (push tg (car groups)))
14112 (setq tg (org-add-props tg nil 'face
14113 (cond
14114 ((not (assoc tg table))
14115 (org-get-todo-face tg))
14116 ((member tg current) c-face)
14117 ((member tg inherited) i-face))))
14118 (if (and (= cnt 0) (not ingroup)) (insert " "))
14119 (insert "[" c "] " tg (make-string
14120 (- fwidth 4 (length tg)) ?\ ))
14121 (push (cons tg c) ntable)
14122 (when (= (setq cnt (1+ cnt)) ncol)
14123 (insert "\n")
14124 (if ingroup (insert " "))
14125 (setq cnt 0)))))
14126 (setq ntable (nreverse ntable))
14127 (insert "\n")
14128 (goto-char (point-min))
14129 (if (not expert) (org-fit-window-to-buffer))
14130 (setq rtn
14131 (catch 'exit
14132 (while t
14133 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14134 (if (not groups) "no " "")
14135 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14136 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14137 (setq org-last-tag-selection-key c)
14138 (cond
14139 ((= c ?\r) (throw 'exit t))
14140 ((= c ?!)
14141 (setq groups (not groups))
14142 (goto-char (point-min))
14143 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14144 ((= c ?\C-c)
14145 (if (not expert)
14146 (org-fast-tag-show-exit
14147 (setq exit-after-next (not exit-after-next)))
14148 (setq expert nil)
14149 (delete-other-windows)
14150 (set-window-buffer (split-window-vertically) " *Org tags*")
14151 (org-switch-to-buffer-other-window " *Org tags*")
14152 (org-fit-window-to-buffer)))
14153 ((or (= c ?\C-g)
14154 (and (= c ?q) (not (rassoc c ntable))))
14155 (org-detach-overlay org-tags-overlay)
14156 (setq quit-flag t))
14157 ((= c ?\ )
14158 (setq current nil)
14159 (if exit-after-next (setq exit-after-next 'now)))
14160 ((= c ?\t)
14161 (condition-case nil
14162 (setq tg (org-icompleting-read
14163 "Tag: "
14164 (or buffer-tags
14165 (with-current-buffer buf
14166 (org-get-buffer-tags)))))
14167 (quit (setq tg "")))
14168 (when (string-match "\\S-" tg)
14169 (add-to-list 'buffer-tags (list tg))
14170 (if (member tg current)
14171 (setq current (delete tg current))
14172 (push tg current)))
14173 (if exit-after-next (setq exit-after-next 'now)))
14174 ((setq e (rassoc c todo-table) tg (car e))
14175 (with-current-buffer buf
14176 (save-excursion (org-todo tg)))
14177 (if exit-after-next (setq exit-after-next 'now)))
14178 ((setq e (rassoc c ntable) tg (car e))
14179 (if (member tg current)
14180 (setq current (delete tg current))
14181 (loop for g in groups do
14182 (if (member tg g)
14183 (mapc (lambda (x)
14184 (setq current (delete x current)))
14185 g)))
14186 (push tg current))
14187 (if exit-after-next (setq exit-after-next 'now))))
14189 ;; Create a sorted list
14190 (setq current
14191 (sort current
14192 (lambda (a b)
14193 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14194 (if (eq exit-after-next 'now) (throw 'exit t))
14195 (goto-char (point-min))
14196 (beginning-of-line 2)
14197 (delete-region (point) (point-at-eol))
14198 (org-fast-tag-insert "Current" current c-face)
14199 (org-set-current-tags-overlay current ov-prefix)
14200 (while (re-search-forward
14201 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14202 (setq tg (match-string 1))
14203 (add-text-properties
14204 (match-beginning 1) (match-end 1)
14205 (list 'face
14206 (cond
14207 ((member tg current) c-face)
14208 ((member tg inherited) i-face)
14209 (t (get-text-property (match-beginning 1) 'face))))))
14210 (goto-char (point-min)))))
14211 (org-detach-overlay org-tags-overlay)
14212 (if rtn
14213 (mapconcat 'identity current ":")
14214 nil))))
14216 (defun org-get-tags-string ()
14217 "Get the TAGS string in the current headline."
14218 (unless (org-at-heading-p t)
14219 (error "Not on a heading"))
14220 (save-excursion
14221 (beginning-of-line 1)
14222 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14223 (org-match-string-no-properties 1)
14224 "")))
14226 (defun org-get-tags ()
14227 "Get the list of tags specified in the current headline."
14228 (org-split-string (org-get-tags-string) ":"))
14230 (defun org-get-buffer-tags ()
14231 "Get a table of all tags used in the buffer, for completion."
14232 (let (tags)
14233 (save-excursion
14234 (goto-char (point-min))
14235 (while (re-search-forward
14236 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14237 (when (equal (char-after (point-at-bol 0)) ?*)
14238 (mapc (lambda (x) (add-to-list 'tags x))
14239 (org-split-string (org-match-string-no-properties 1) ":")))))
14240 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14241 (mapcar 'list tags)))
14243 ;;;; The mapping API
14245 (defun org-map-entries (func &optional match scope &rest skip)
14246 "Call FUNC at each headline selected by MATCH in SCOPE.
14248 FUNC is a function or a lisp form. The function will be called without
14249 arguments, with the cursor positioned at the beginning of the headline.
14250 The return values of all calls to the function will be collected and
14251 returned as a list.
14253 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14254 does not need to preserve point. After evaluation, the cursor will be
14255 moved to the end of the line (presumably of the headline of the
14256 processed entry) and search continues from there. Under some
14257 circumstances, this may not produce the wanted results. For example,
14258 if you have removed (e.g. archived) the current (sub)tree it could
14259 mean that the next entry will be skipped entirely. In such cases, you
14260 can specify the position from where search should continue by making
14261 FUNC set the variable `org-map-continue-from' to the desired buffer
14262 position.
14264 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14265 Only headlines that are matched by this query will be considered during
14266 the iteration. When MATCH is nil or t, all headlines will be
14267 visited by the iteration.
14269 SCOPE determines the scope of this command. It can be any of:
14271 nil The current buffer, respecting the restriction if any
14272 tree The subtree started with the entry at point
14273 region The entries within the active region, if any
14274 region-start-level
14275 The entries within the active region, but only those at
14276 the same level than the first one.
14277 file The current buffer, without restriction
14278 file-with-archives
14279 The current buffer, and any archives associated with it
14280 agenda All agenda files
14281 agenda-with-archives
14282 All agenda files with any archive files associated with them
14283 \(file1 file2 ...)
14284 If this is a list, all files in the list will be scanned
14286 The remaining args are treated as settings for the skipping facilities of
14287 the scanner. The following items can be given here:
14289 archive skip trees with the archive tag.
14290 comment skip trees with the COMMENT keyword
14291 function or Emacs Lisp form:
14292 will be used as value for `org-agenda-skip-function', so whenever
14293 the function returns t, FUNC will not be called for that
14294 entry and search will continue from the point where the
14295 function leaves it.
14297 If your function needs to retrieve the tags including inherited tags
14298 at the *current* entry, you can use the value of the variable
14299 `org-scanner-tags' which will be much faster than getting the value
14300 with `org-get-tags-at'. If your function gets properties with
14301 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14302 to t around the call to `org-entry-properties' to get the same speedup.
14303 Note that if your function moves around to retrieve tags and properties at
14304 a *different* entry, you cannot use these techniques."
14305 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14306 (not (org-region-active-p)))
14307 (let* ((org-agenda-archives-mode nil) ; just to make sure
14308 (org-agenda-skip-archived-trees (memq 'archive skip))
14309 (org-agenda-skip-comment-trees (memq 'comment skip))
14310 (org-agenda-skip-function
14311 (car (org-delete-all '(comment archive) skip)))
14312 (org-tags-match-list-sublevels t)
14313 (start-level (eq scope 'region-start-level))
14314 matcher file res
14315 org-todo-keywords-for-agenda
14316 org-done-keywords-for-agenda
14317 org-todo-keyword-alist-for-agenda
14318 org-drawers-for-agenda
14319 org-tag-alist-for-agenda
14320 todo-only)
14322 (cond
14323 ((eq match t) (setq matcher t))
14324 ((eq match nil) (setq matcher t))
14325 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14327 (save-excursion
14328 (save-restriction
14329 (cond ((eq scope 'tree)
14330 (org-back-to-heading t)
14331 (org-narrow-to-subtree)
14332 (setq scope nil))
14333 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14334 (org-region-active-p))
14335 ;; If needed, set start-level to a string like "2"
14336 (when start-level
14337 (save-excursion
14338 (goto-char (region-beginning))
14339 (unless (org-at-heading-p) (outline-next-heading))
14340 (setq start-level (org-current-level))))
14341 (narrow-to-region (region-beginning)
14342 (save-excursion
14343 (goto-char (region-end))
14344 (unless (and (bolp) (org-at-heading-p))
14345 (outline-next-heading))
14346 (point)))
14347 (setq scope nil)))
14349 (if (not scope)
14350 (progn
14351 (org-agenda-prepare-buffers
14352 (list (buffer-file-name (current-buffer))))
14353 (setq res (org-scan-tags func matcher todo-only start-level)))
14354 ;; Get the right scope
14355 (cond
14356 ((and scope (listp scope) (symbolp (car scope)))
14357 (setq scope (eval scope)))
14358 ((eq scope 'agenda)
14359 (setq scope (org-agenda-files t)))
14360 ((eq scope 'agenda-with-archives)
14361 (setq scope (org-agenda-files t))
14362 (setq scope (org-add-archive-files scope)))
14363 ((eq scope 'file)
14364 (setq scope (list (buffer-file-name))))
14365 ((eq scope 'file-with-archives)
14366 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14367 (org-agenda-prepare-buffers scope)
14368 (while (setq file (pop scope))
14369 (with-current-buffer (org-find-base-buffer-visiting file)
14370 (save-excursion
14371 (save-restriction
14372 (widen)
14373 (goto-char (point-min))
14374 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14375 res)))
14377 ;;;; Properties
14379 ;;; Setting and retrieving properties
14381 (defconst org-special-properties
14382 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14383 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14384 "The special properties valid in Org-mode.
14386 These are properties that are not defined in the property drawer,
14387 but in some other way.")
14389 (defconst org-default-properties
14390 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14391 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14392 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14393 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14394 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14395 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14396 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14397 "Some properties that are used by Org-mode for various purposes.
14398 Being in this list makes sure that they are offered for completion.")
14400 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14401 "Regular expression matching the first line of a property drawer.")
14403 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14404 "Regular expression matching the last line of a property drawer.")
14406 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14407 "Regular expression matching the first line of a property drawer.")
14409 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14410 "Regular expression matching the first line of a property drawer.")
14412 (defconst org-property-drawer-re
14413 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14414 org-property-end-re "\\)\n?")
14415 "Matches an entire property drawer.")
14417 (defconst org-clock-drawer-re
14418 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14419 org-property-end-re "\\)\n?")
14420 "Matches an entire clock drawer.")
14422 (defsubst org-re-property (property)
14423 "Return a regexp matching a PROPERTY line.
14424 Match group 1 will be set to the value."
14425 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14427 (defsubst org-re-property-keyword (property)
14428 "Return a regexp matching a PROPERTY line, possibly with no
14429 value for the property."
14430 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14432 (defun org-property-action ()
14433 "Do an action on properties."
14434 (interactive)
14435 (let (c)
14436 (org-at-property-p)
14437 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14438 (setq c (read-char-exclusive))
14439 (cond
14440 ((equal c ?s)
14441 (call-interactively 'org-set-property))
14442 ((equal c ?d)
14443 (call-interactively 'org-delete-property))
14444 ((equal c ?D)
14445 (call-interactively 'org-delete-property-globally))
14446 ((equal c ?c)
14447 (call-interactively 'org-compute-property-at-point))
14448 (t (error "No such property action %c" c)))))
14450 (defun org-inc-effort ()
14451 "Increment the value of the effort property in the current entry."
14452 (interactive)
14453 (org-set-effort nil t))
14455 (defun org-set-effort (&optional value increment)
14456 "Set the effort property of the current entry.
14457 With numerical prefix arg, use the nth allowed value, 0 stands for the
14458 10th allowed value.
14460 When INCREMENT is non-nil, set the property to the next allowed value."
14461 (interactive "P")
14462 (if (equal value 0) (setq value 10))
14463 (let* ((completion-ignore-case t)
14464 (prop org-effort-property)
14465 (cur (org-entry-get nil prop))
14466 (allowed (org-property-get-allowed-values nil prop 'table))
14467 (existing (mapcar 'list (org-property-values prop)))
14469 (val (cond
14470 ((stringp value) value)
14471 ((and allowed (integerp value))
14472 (or (car (nth (1- value) allowed))
14473 (car (org-last allowed))))
14474 ((and allowed increment)
14475 (or (caadr (member (list cur) allowed))
14476 (error "Allowed effort values are not set")))
14477 (allowed
14478 (message "Select 1-9,0, [RET%s]: %s"
14479 (if cur (concat "=" cur) "")
14480 (mapconcat 'car allowed " "))
14481 (setq rpl (read-char-exclusive))
14482 (if (equal rpl ?\r)
14484 (setq rpl (- rpl ?0))
14485 (if (equal rpl 0) (setq rpl 10))
14486 (if (and (> rpl 0) (<= rpl (length allowed)))
14487 (car (nth (1- rpl) allowed))
14488 (org-completing-read "Effort: " allowed nil))))
14490 (let (org-completion-use-ido org-completion-use-iswitchb)
14491 (org-completing-read
14492 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14493 (concat "[" cur "]") "")
14494 ": ")
14495 existing nil nil "" nil cur))))))
14496 (unless (equal (org-entry-get nil prop) val)
14497 (org-entry-put nil prop val))
14498 (message "%s is now %s" prop val)))
14500 (defun org-at-property-p ()
14501 "Is cursor inside a property drawer?"
14502 (save-excursion
14503 (beginning-of-line 1)
14504 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14505 (save-match-data ;; Used by calling procedures
14506 (let ((p (point))
14507 (range (unless (org-before-first-heading-p)
14508 (org-get-property-block))))
14509 (and range (<= (car range) p) (< p (cdr range))))))))
14511 (defun org-get-property-block (&optional beg end force)
14512 "Return the (beg . end) range of the body of the property drawer.
14513 BEG and END are the beginning and end of the current subtree, or of
14514 the part before the first headline. If they are not given, they will
14515 be found. If the drawer does not exist and FORCE is non-nil, create
14516 the drawer."
14517 (catch 'exit
14518 (save-excursion
14519 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14520 (progn (org-back-to-heading t) (point))))
14521 (end (or end (and (not (outline-next-heading)) (point-max))
14522 (point))))
14523 (goto-char beg)
14524 (if (re-search-forward org-property-start-re end t)
14525 (setq beg (1+ (match-end 0)))
14526 (if force
14527 (save-excursion
14528 (org-insert-property-drawer)
14529 (setq end (progn (outline-next-heading) (point))))
14530 (throw 'exit nil))
14531 (goto-char beg)
14532 (if (re-search-forward org-property-start-re end t)
14533 (setq beg (1+ (match-end 0)))))
14534 (if (re-search-forward org-property-end-re end t)
14535 (setq end (match-beginning 0))
14536 (or force (throw 'exit nil))
14537 (goto-char beg)
14538 (setq end beg)
14539 (org-indent-line)
14540 (insert ":END:\n"))
14541 (cons beg end)))))
14543 (defun org-entry-properties (&optional pom which specific)
14544 "Get all properties of the entry at point-or-marker POM.
14545 This includes the TODO keyword, the tags, time strings for deadline,
14546 scheduled, and clocking, and any additional properties defined in the
14547 entry. The return value is an alist, keys may occur multiple times
14548 if the property key was used several times.
14549 POM may also be nil, in which case the current entry is used.
14550 If WHICH is nil or `all', get all properties. If WHICH is
14551 `special' or `standard', only get that subclass. If WHICH
14552 is a string only get exactly this property. SPECIFIC can be a string, the
14553 specific property we are interested in. Specifying it can speed
14554 things up because then unnecessary parsing is avoided."
14555 (setq which (or which 'all))
14556 (org-with-point-at pom
14557 (let ((clockstr (substring org-clock-string 0 -1))
14558 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14559 (case-fold-search nil)
14560 beg end range props sum-props key key1 value string clocksum clocksumt)
14561 (save-excursion
14562 (when (condition-case nil
14563 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14564 (error nil))
14565 (setq beg (point))
14566 (setq sum-props (get-text-property (point) 'org-summaries))
14567 (setq clocksum (get-text-property (point) :org-clock-minutes)
14568 clocksumt (get-text-property (point) :org-clock-minutes-today))
14569 (outline-next-heading)
14570 (setq end (point))
14571 (when (memq which '(all special))
14572 ;; Get the special properties, like TODO and tags
14573 (goto-char beg)
14574 (when (and (or (not specific) (string= specific "TODO"))
14575 (looking-at org-todo-line-regexp) (match-end 2))
14576 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14577 (when (and (or (not specific) (string= specific "PRIORITY"))
14578 (looking-at org-priority-regexp))
14579 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14580 (when (or (not specific) (string= specific "FILE"))
14581 (push (cons "FILE" buffer-file-name) props))
14582 (when (and (or (not specific) (string= specific "TAGS"))
14583 (setq value (org-get-tags-string))
14584 (string-match "\\S-" value))
14585 (push (cons "TAGS" value) props))
14586 (when (and (or (not specific) (string= specific "ALLTAGS"))
14587 (setq value (org-get-tags-at)))
14588 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14589 ":"))
14590 props))
14591 (when (or (not specific) (string= specific "BLOCKED"))
14592 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14593 (when (or (not specific)
14594 (member specific
14595 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14596 "TIMESTAMP" "TIMESTAMP_IA")))
14597 (catch 'match
14598 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14599 (setq key (if (match-end 1)
14600 (substring (org-match-string-no-properties 1)
14601 0 -1))
14602 string (if (equal key clockstr)
14603 (org-trim
14604 (buffer-substring-no-properties
14605 (match-beginning 3) (goto-char
14606 (point-at-eol))))
14607 (substring (org-match-string-no-properties 3)
14608 1 -1)))
14609 ;; Get the correct property name from the key. This is
14610 ;; necessary if the user has configured time keywords.
14611 (setq key1 (concat key ":"))
14612 (cond
14613 ((not key)
14614 (setq key
14615 (if (= (char-after (match-beginning 3)) ?\[)
14616 "TIMESTAMP_IA" "TIMESTAMP")))
14617 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14618 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14619 ((equal key1 org-closed-string) (setq key "CLOSED"))
14620 ((equal key1 org-clock-string) (setq key "CLOCK")))
14621 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14622 (progn
14623 (push (cons key string) props)
14624 ;; no need to search further if match is found
14625 (throw 'match t))
14626 (when (or (equal key "CLOCK") (not (assoc key props)))
14627 (push (cons key string) props)))))))
14629 (when (memq which '(all standard))
14630 ;; Get the standard properties, like :PROP: ...
14631 (setq range (org-get-property-block beg end))
14632 (when range
14633 (goto-char (car range))
14634 (while (re-search-forward
14635 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14636 (cdr range) t)
14637 (setq key (org-match-string-no-properties 1)
14638 value (org-trim (or (org-match-string-no-properties 2) "")))
14639 (unless (member key excluded)
14640 (push (cons key (or value "")) props)))))
14641 (if clocksum
14642 (push (cons "CLOCKSUM"
14643 (org-columns-number-to-string (/ (float clocksum) 60.)
14644 'add_times))
14645 props))
14646 (if clocksumt
14647 (push (cons "CLOCKSUM_T"
14648 (org-columns-number-to-string (/ (float clocksumt) 60.)
14649 'add_times))
14650 props))
14651 (unless (assoc "CATEGORY" props)
14652 (push (cons "CATEGORY" (org-get-category)) props))
14653 (append sum-props (nreverse props)))))))
14655 (defun org-entry-get (pom property &optional inherit literal-nil)
14656 "Get value of PROPERTY for entry or content at point-or-marker POM.
14657 If INHERIT is non-nil and the entry does not have the property,
14658 then also check higher levels of the hierarchy.
14659 If INHERIT is the symbol `selective', use inheritance only if the setting
14660 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14661 If the property is present but empty, the return value is the empty string.
14662 If the property is not present at all, nil is returned.
14664 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14665 do not interpret it as the list atom nil. This is used for inheritance
14666 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14667 (org-with-point-at pom
14668 (if (and inherit (if (eq inherit 'selective)
14669 (org-property-inherit-p property)
14671 (org-entry-get-with-inheritance property literal-nil)
14672 (if (member property org-special-properties)
14673 ;; We need a special property. Use `org-entry-properties' to
14674 ;; retrieve it, but specify the wanted property
14675 (cdr (assoc property (org-entry-properties nil 'special property)))
14676 (let* ((range (org-get-property-block))
14677 (props (list (or (assoc property org-file-properties)
14678 (assoc property org-global-properties)
14679 (assoc property org-global-properties-fixed))))
14680 (ap (lambda (key)
14681 (when (re-search-forward
14682 (org-re-property key) (cdr range) t)
14683 (setq props
14684 (org-update-property-plist
14686 (if (match-end 1)
14687 (org-match-string-no-properties 1) "")
14688 props)))))
14689 val)
14690 (when (and range (goto-char (car range)))
14691 (funcall ap property)
14692 (goto-char (car range))
14693 (while (funcall ap (concat property "+")))
14694 (setq val (cdr (assoc property props)))
14695 (when val (if literal-nil val (org-not-nil val)))))))))
14697 (defun org-property-or-variable-value (var &optional inherit)
14698 "Check if there is a property fixing the value of VAR.
14699 If yes, return this value. If not, return the current value of the variable."
14700 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14701 (if (and prop (stringp prop) (string-match "\\S-" prop))
14702 (read prop)
14703 (symbol-value var))))
14705 (defun org-entry-delete (pom property)
14706 "Delete the property PROPERTY from entry at point-or-marker POM."
14707 (org-with-point-at pom
14708 (if (member property org-special-properties)
14709 nil ; cannot delete these properties.
14710 (let ((range (org-get-property-block)))
14711 (if (and range
14712 (goto-char (car range))
14713 (re-search-forward
14714 (org-re-property property)
14715 (cdr range) t))
14716 (progn
14717 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14719 nil)))))
14721 ;; Multi-values properties are properties that contain multiple values
14722 ;; These values are assumed to be single words, separated by whitespace.
14723 (defun org-entry-add-to-multivalued-property (pom property value)
14724 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14725 (let* ((old (org-entry-get pom property))
14726 (values (and old (org-split-string old "[ \t]"))))
14727 (setq value (org-entry-protect-space value))
14728 (unless (member value values)
14729 (setq values (cons value values))
14730 (org-entry-put pom property
14731 (mapconcat 'identity values " ")))))
14733 (defun org-entry-remove-from-multivalued-property (pom property value)
14734 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14735 (let* ((old (org-entry-get pom property))
14736 (values (and old (org-split-string old "[ \t]"))))
14737 (setq value (org-entry-protect-space value))
14738 (when (member value values)
14739 (setq values (delete value values))
14740 (org-entry-put pom property
14741 (mapconcat 'identity values " ")))))
14743 (defun org-entry-member-in-multivalued-property (pom property value)
14744 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14745 (let* ((old (org-entry-get pom property))
14746 (values (and old (org-split-string old "[ \t]"))))
14747 (setq value (org-entry-protect-space value))
14748 (member value values)))
14750 (defun org-entry-get-multivalued-property (pom property)
14751 "Return a list of values in a multivalued property."
14752 (let* ((value (org-entry-get pom property))
14753 (values (and value (org-split-string value "[ \t]"))))
14754 (mapcar 'org-entry-restore-space values)))
14756 (defun org-entry-put-multivalued-property (pom property &rest values)
14757 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14758 VALUES should be a list of strings. Spaces will be protected."
14759 (org-entry-put pom property
14760 (mapconcat 'org-entry-protect-space values " "))
14761 (let* ((value (org-entry-get pom property))
14762 (values (and value (org-split-string value "[ \t]"))))
14763 (mapcar 'org-entry-restore-space values)))
14765 (defun org-entry-protect-space (s)
14766 "Protect spaces and newline in string S."
14767 (while (string-match " " s)
14768 (setq s (replace-match "%20" t t s)))
14769 (while (string-match "\n" s)
14770 (setq s (replace-match "%0A" t t s)))
14773 (defun org-entry-restore-space (s)
14774 "Restore spaces and newline in string S."
14775 (while (string-match "%20" s)
14776 (setq s (replace-match " " t t s)))
14777 (while (string-match "%0A" s)
14778 (setq s (replace-match "\n" t t s)))
14781 (defvar org-entry-property-inherited-from (make-marker)
14782 "Marker pointing to the entry from where a property was inherited.
14783 Each call to `org-entry-get-with-inheritance' will set this marker to the
14784 location of the entry where the inheritance search matched. If there was
14785 no match, the marker will point nowhere.
14786 Note that also `org-entry-get' calls this function, if the INHERIT flag
14787 is set.")
14789 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14790 "Get PROPERTY of entry or content at point, search higher levels if needed.
14791 The search will stop at the first ancestor which has the property defined.
14792 If the value found is \"nil\", return nil to show that the property
14793 should be considered as undefined (this is the meaning of nil here).
14794 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14795 (move-marker org-entry-property-inherited-from nil)
14796 (let (tmp)
14797 (save-excursion
14798 (save-restriction
14799 (widen)
14800 (catch 'ex
14801 (while t
14802 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14803 (or (ignore-errors (org-back-to-heading t))
14804 (goto-char (point-min)))
14805 (move-marker org-entry-property-inherited-from (point))
14806 (throw 'ex tmp))
14807 (or (ignore-errors (org-up-heading-safe))
14808 (throw 'ex nil))))))
14809 (setq tmp (or tmp
14810 (cdr (assoc property org-file-properties))
14811 (cdr (assoc property org-global-properties))
14812 (cdr (assoc property org-global-properties-fixed))))
14813 (if literal-nil tmp (org-not-nil tmp))))
14815 (defvar org-property-changed-functions nil
14816 "Hook called when the value of a property has changed.
14817 Each hook function should accept two arguments, the name of the property
14818 and the new value.")
14820 (defun org-entry-put (pom property value)
14821 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14822 (org-with-point-at pom
14823 (org-back-to-heading t)
14824 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14825 range)
14826 (cond
14827 ((equal property "TODO")
14828 (when (and (stringp value) (string-match "\\S-" value)
14829 (not (member value org-todo-keywords-1)))
14830 (error "\"%s\" is not a valid TODO state" value))
14831 (if (or (not value)
14832 (not (string-match "\\S-" value)))
14833 (setq value 'none))
14834 (org-todo value)
14835 (org-set-tags nil 'align))
14836 ((equal property "PRIORITY")
14837 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14838 (string-to-char value) ?\ ))
14839 (org-set-tags nil 'align))
14840 ((equal property "CLOCKSUM")
14841 (if (not (re-search-forward
14842 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14843 (error "Cannot find a clock log")
14844 (goto-char (- (match-end 1) 2))
14845 (cond
14846 ((eq value 'earlier) (org-timestamp-down))
14847 ((eq value 'later) (org-timestamp-up)))
14848 (org-clock-sum-current-item)))
14849 ((equal property "SCHEDULED")
14850 (if (re-search-forward org-scheduled-time-regexp end t)
14851 (cond
14852 ((eq value 'earlier) (org-timestamp-change -1 'day))
14853 ((eq value 'later) (org-timestamp-change 1 'day))
14854 (t (call-interactively 'org-schedule)))
14855 (call-interactively 'org-schedule)))
14856 ((equal property "DEADLINE")
14857 (if (re-search-forward org-deadline-time-regexp end t)
14858 (cond
14859 ((eq value 'earlier) (org-timestamp-change -1 'day))
14860 ((eq value 'later) (org-timestamp-change 1 'day))
14861 (t (call-interactively 'org-deadline)))
14862 (call-interactively 'org-deadline)))
14863 ((member property org-special-properties)
14864 (error "The %s property can not yet be set with `org-entry-put'"
14865 property))
14866 (t ; a non-special property
14867 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14868 (setq range (org-get-property-block beg end 'force))
14869 (goto-char (car range))
14870 (if (re-search-forward
14871 (org-re-property-keyword property) (cdr range) t)
14872 (progn
14873 (delete-region (match-beginning 0) (match-end 0))
14874 (goto-char (match-beginning 0)))
14875 (goto-char (cdr range))
14876 (insert "\n")
14877 (backward-char 1)
14878 (org-indent-line))
14879 (insert ":" property ":")
14880 (and value (insert " " value))
14881 (org-indent-line)))))
14882 (run-hook-with-args 'org-property-changed-functions property value)))
14884 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14885 "Get all property keys in the current buffer.
14886 With INCLUDE-SPECIALS, also list the special properties that reflect things
14887 like tags and TODO state.
14888 With INCLUDE-DEFAULTS, also include properties that has special meaning
14889 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14890 and others.
14891 With INCLUDE-COLUMNS, also include property names given in COLUMN
14892 formats in the current buffer."
14893 (let (rtn range cfmt s p)
14894 (save-excursion
14895 (save-restriction
14896 (widen)
14897 (goto-char (point-min))
14898 (while (re-search-forward org-property-start-re nil t)
14899 (setq range (org-get-property-block))
14900 (goto-char (car range))
14901 (while (re-search-forward
14902 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14903 (cdr range) t)
14904 (add-to-list 'rtn (org-match-string-no-properties 1)))
14905 (outline-next-heading))))
14907 (when include-specials
14908 (setq rtn (append org-special-properties rtn)))
14910 (when include-defaults
14911 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14912 (add-to-list 'rtn org-effort-property))
14914 (when include-columns
14915 (save-excursion
14916 (save-restriction
14917 (widen)
14918 (goto-char (point-min))
14919 (while (re-search-forward
14920 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14921 nil t)
14922 (setq cfmt (match-string 2) s 0)
14923 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14924 cfmt s)
14925 (setq s (match-end 0)
14926 p (match-string 1 cfmt))
14927 (unless (or (equal p "ITEM")
14928 (member p org-special-properties))
14929 (add-to-list 'rtn (match-string 1 cfmt))))))))
14931 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14933 (defun org-property-values (key)
14934 "Return a list of all values of property KEY in the current buffer."
14935 (save-excursion
14936 (save-restriction
14937 (widen)
14938 (goto-char (point-min))
14939 (let ((re (org-re-property key))
14940 values)
14941 (while (re-search-forward re nil t)
14942 (add-to-list 'values (org-trim (match-string 1))))
14943 (delete "" values)))))
14945 (defun org-insert-property-drawer ()
14946 "Insert a property drawer into the current entry."
14947 (org-back-to-heading t)
14948 (looking-at org-outline-regexp)
14949 (let ((indent (if org-adapt-indentation
14950 (- (match-end 0) (match-beginning 0))
14952 (beg (point))
14953 (re (concat "^[ \t]*" org-keyword-time-regexp))
14954 end hiddenp)
14955 (outline-next-heading)
14956 (setq end (point))
14957 (goto-char beg)
14958 (while (re-search-forward re end t))
14959 (setq hiddenp (outline-invisible-p))
14960 (end-of-line 1)
14961 (and (equal (char-after) ?\n) (forward-char 1))
14962 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14963 (if (member (match-string 1) '("CLOCK:" ":END:"))
14964 ;; just skip this line
14965 (beginning-of-line 2)
14966 ;; Drawer start, find the end
14967 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14968 (beginning-of-line 1)))
14969 (org-skip-over-state-notes)
14970 (skip-chars-backward " \t\n\r")
14971 (if (eq (char-before) ?*) (forward-char 1))
14972 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14973 (beginning-of-line 0)
14974 (org-indent-to-column indent)
14975 (beginning-of-line 2)
14976 (org-indent-to-column indent)
14977 (beginning-of-line 0)
14978 (if hiddenp
14979 (save-excursion
14980 (org-back-to-heading t)
14981 (hide-entry))
14982 (org-flag-drawer t))))
14984 (defun org-insert-drawer (&optional arg drawer)
14985 "Insert a drawer at point.
14987 Optional argument DRAWER, when non-nil, is a string representing
14988 drawer's name. Otherwise, the user is prompted for a name.
14990 If a region is active, insert the drawer around that region
14991 instead.
14993 Point is left between drawer's boundaries."
14994 (interactive "P")
14995 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14996 "LOGBOOK"))
14997 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14998 ;; internally by Org. They are meant to be inserted
14999 ;; automatically.
15000 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15001 ;; Remove system drawers from list. Note: For some reason,
15002 ;; `org-completing-read' ignores the predicate while
15003 ;; `completing-read' handles it fine.
15004 (drawer (if arg "PROPERTIES"
15005 (or drawer
15006 (completing-read
15007 "Drawer: " org-drawers
15008 (lambda (d) (not (member d system-drawers))))))))
15009 (cond
15010 ;; With C-u, fall back on `org-insert-property-drawer'
15011 (arg (org-insert-property-drawer))
15012 ;; With an active region, insert a drawer at point.
15013 ((not (org-region-active-p))
15014 (progn
15015 (unless (bolp) (insert "\n"))
15016 (insert (format ":%s:\n\n:END:\n" drawer))
15017 (forward-line -2)))
15018 ;; Otherwise, insert the drawer at point
15020 (let ((rbeg (region-beginning))
15021 (rend (copy-marker (region-end))))
15022 (unwind-protect
15023 (progn
15024 (goto-char rbeg)
15025 (beginning-of-line)
15026 (when (save-excursion
15027 (re-search-forward org-outline-regexp-bol rend t))
15028 (error "Drawers cannot contain headlines"))
15029 ;; Position point at the beginning of the first
15030 ;; non-blank line in region. Insert drawer's opening
15031 ;; there, then indent it.
15032 (org-skip-whitespace)
15033 (beginning-of-line)
15034 (insert ":" drawer ":\n")
15035 (forward-line -1)
15036 (indent-for-tab-command)
15037 ;; Move point to the beginning of the first blank line
15038 ;; after the last non-blank line in region. Insert
15039 ;; drawer's closing, then indent it.
15040 (goto-char rend)
15041 (skip-chars-backward " \r\t\n")
15042 (insert "\n:END:")
15043 (deactivate-mark t)
15044 (indent-for-tab-command)
15045 (unless (eolp) (insert "\n")))
15046 ;; Clear marker, whatever the outcome of insertion is.
15047 (set-marker rend nil)))))))
15049 (defvar org-property-set-functions-alist nil
15050 "Property set function alist.
15051 Each entry should have the following format:
15053 (PROPERTY . READ-FUNCTION)
15055 The read function will be called with the same argument as
15056 `org-completing-read'.")
15058 (defun org-set-property-function (property)
15059 "Get the function that should be used to set PROPERTY.
15060 This is computed according to `org-property-set-functions-alist'."
15061 (or (cdr (assoc property org-property-set-functions-alist))
15062 'org-completing-read))
15064 (defun org-read-property-value (property)
15065 "Read PROPERTY value from user."
15066 (let* ((completion-ignore-case t)
15067 (allowed (org-property-get-allowed-values nil property 'table))
15068 (cur (org-entry-get nil property))
15069 (prompt (concat property " value"
15070 (if (and cur (string-match "\\S-" cur))
15071 (concat " [" cur "]") "") ": "))
15072 (set-function (org-set-property-function property))
15073 (val (if allowed
15074 (funcall set-function prompt allowed nil
15075 (not (get-text-property 0 'org-unrestricted
15076 (caar allowed))))
15077 (let (org-completion-use-ido org-completion-use-iswitchb)
15078 (funcall set-function prompt
15079 (mapcar 'list (org-property-values property))
15080 nil nil "" nil cur)))))
15081 (if (equal val "")
15083 val)))
15085 (defvar org-last-set-property nil)
15086 (defun org-read-property-name ()
15087 "Read a property name."
15088 (let* ((completion-ignore-case t)
15089 (keys (org-buffer-property-keys nil t t))
15090 (default-prop (or (save-excursion
15091 (save-match-data
15092 (beginning-of-line)
15093 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15094 (null (string= (match-string 1) "END"))
15095 (match-string 1))))
15096 org-last-set-property))
15097 (property (org-icompleting-read
15098 (concat "Property"
15099 (if default-prop (concat " [" default-prop "]") "")
15100 ": ")
15101 (mapcar 'list keys)
15102 nil nil nil nil
15103 default-prop
15105 (if (member property keys)
15106 property
15107 (or (cdr (assoc (downcase property)
15108 (mapcar (lambda (x) (cons (downcase x) x))
15109 keys)))
15110 property))))
15112 (defun org-set-property (property value)
15113 "In the current entry, set PROPERTY to VALUE.
15114 When called interactively, this will prompt for a property name, offering
15115 completion on existing and default properties. And then it will prompt
15116 for a value, offering completion either on allowed values (via an inherited
15117 xxx_ALL property) or on existing values in other instances of this property
15118 in the current file."
15119 (interactive (list nil nil))
15120 (let* ((property (or property (org-read-property-name)))
15121 (value (or value (org-read-property-value property)))
15122 (fn (cdr (assoc property org-properties-postprocess-alist))))
15123 (setq org-last-set-property property)
15124 ;; Possibly postprocess the inserted value:
15125 (when fn (setq value (funcall fn value)))
15126 (unless (equal (org-entry-get nil property) value)
15127 (org-entry-put nil property value))))
15129 (defun org-delete-property (property)
15130 "In the current entry, delete PROPERTY."
15131 (interactive
15132 (let* ((completion-ignore-case t)
15133 (prop (org-icompleting-read "Property: "
15134 (org-entry-properties nil 'standard))))
15135 (list prop)))
15136 (message "Property %s %s" property
15137 (if (org-entry-delete nil property)
15138 "deleted"
15139 "was not present in the entry")))
15141 (defun org-delete-property-globally (property)
15142 "Remove PROPERTY globally, from all entries."
15143 (interactive
15144 (let* ((completion-ignore-case t)
15145 (prop (org-icompleting-read
15146 "Globally remove property: "
15147 (mapcar 'list (org-buffer-property-keys)))))
15148 (list prop)))
15149 (save-excursion
15150 (save-restriction
15151 (widen)
15152 (goto-char (point-min))
15153 (let ((cnt 0))
15154 (while (re-search-forward
15155 (org-re-property property)
15156 nil t)
15157 (setq cnt (1+ cnt))
15158 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15159 (message "Property \"%s\" removed from %d entries" property cnt)))))
15161 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15163 (defun org-compute-property-at-point ()
15164 "Compute the property at point.
15165 This looks for an enclosing column format, extracts the operator and
15166 then applies it to the property in the column format's scope."
15167 (interactive)
15168 (unless (org-at-property-p)
15169 (error "Not at a property"))
15170 (let ((prop (org-match-string-no-properties 2)))
15171 (org-columns-get-format-and-top-level)
15172 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15173 (error "No operator defined for property %s" prop))
15174 (org-columns-compute prop)))
15176 (defvar org-property-allowed-value-functions nil
15177 "Hook for functions supplying allowed values for a specific property.
15178 The functions must take a single argument, the name of the property, and
15179 return a flat list of allowed values. If \":ETC\" is one of
15180 the values, this means that these values are intended as defaults for
15181 completion, but that other values should be allowed too.
15182 The functions must return nil if they are not responsible for this
15183 property.")
15185 (defun org-property-get-allowed-values (pom property &optional table)
15186 "Get allowed values for the property PROPERTY.
15187 When TABLE is non-nil, return an alist that can directly be used for
15188 completion."
15189 (let (vals)
15190 (cond
15191 ((equal property "TODO")
15192 (setq vals (org-with-point-at pom
15193 (append org-todo-keywords-1 '("")))))
15194 ((equal property "PRIORITY")
15195 (let ((n org-lowest-priority))
15196 (while (>= n org-highest-priority)
15197 (push (char-to-string n) vals)
15198 (setq n (1- n)))))
15199 ((member property org-special-properties))
15200 ((setq vals (run-hook-with-args-until-success
15201 'org-property-allowed-value-functions property)))
15203 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15204 (when (and vals (string-match "\\S-" vals))
15205 (setq vals (car (read-from-string (concat "(" vals ")"))))
15206 (setq vals (mapcar (lambda (x)
15207 (cond ((stringp x) x)
15208 ((numberp x) (number-to-string x))
15209 ((symbolp x) (symbol-name x))
15210 (t "???")))
15211 vals)))))
15212 (when (member ":ETC" vals)
15213 (setq vals (remove ":ETC" vals))
15214 (org-add-props (car vals) '(org-unrestricted t)))
15215 (if table (mapcar 'list vals) vals)))
15217 (defun org-property-previous-allowed-value (&optional previous)
15218 "Switch to the next allowed value for this property."
15219 (interactive)
15220 (org-property-next-allowed-value t))
15222 (defun org-property-next-allowed-value (&optional previous)
15223 "Switch to the next allowed value for this property."
15224 (interactive)
15225 (unless (org-at-property-p)
15226 (error "Not at a property"))
15227 (let* ((key (match-string 2))
15228 (value (match-string 3))
15229 (allowed (or (org-property-get-allowed-values (point) key)
15230 (and (member value '("[ ]" "[-]" "[X]"))
15231 '("[ ]" "[X]"))))
15232 nval)
15233 (unless allowed
15234 (error "Allowed values for this property have not been defined"))
15235 (if previous (setq allowed (reverse allowed)))
15236 (if (member value allowed)
15237 (setq nval (car (cdr (member value allowed)))))
15238 (setq nval (or nval (car allowed)))
15239 (if (equal nval value)
15240 (error "Only one allowed value for this property"))
15241 (org-at-property-p)
15242 (replace-match (concat " :" key ": " nval) t t)
15243 (org-indent-line)
15244 (beginning-of-line 1)
15245 (skip-chars-forward " \t")
15246 (run-hook-with-args 'org-property-changed-functions key nval)))
15248 (defun org-find-olp (path &optional this-buffer)
15249 "Return a marker pointing to the entry at outline path OLP.
15250 If anything goes wrong, throw an error.
15251 You can wrap this call to catch the error like this:
15253 (condition-case msg
15254 (org-mobile-locate-entry (match-string 4))
15255 (error (nth 1 msg)))
15257 The return value will then be either a string with the error message,
15258 or a marker if everything is OK.
15260 If THIS-BUFFER is set, the outline path does not contain a file,
15261 only headings."
15262 (let* ((file (if this-buffer buffer-file-name (pop path)))
15263 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15264 (level 1)
15265 (lmin 1)
15266 (lmax 1)
15267 limit re end found pos heading cnt flevel)
15268 (unless buffer (error "File not found :%s" file))
15269 (with-current-buffer buffer
15270 (save-excursion
15271 (save-restriction
15272 (widen)
15273 (setq limit (point-max))
15274 (goto-char (point-min))
15275 (while (setq heading (pop path))
15276 (setq re (format org-complex-heading-regexp-format
15277 (regexp-quote heading)))
15278 (setq cnt 0 pos (point))
15279 (while (re-search-forward re end t)
15280 (setq level (- (match-end 1) (match-beginning 1)))
15281 (if (and (>= level lmin) (<= level lmax))
15282 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15283 (when (= cnt 0) (error "Heading not found on level %d: %s"
15284 lmax heading))
15285 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15286 lmax heading))
15287 (goto-char found)
15288 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15289 (setq end (save-excursion (org-end-of-subtree t t))))
15290 (when (org-at-heading-p)
15291 (point-marker)))))))
15293 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15294 "Find node HEADING in BUFFER.
15295 Return a marker to the heading if it was found, or nil if not.
15296 If POS-ONLY is set, return just the position instead of a marker.
15298 The heading text must match exact, but it may have a TODO keyword,
15299 a priority cookie and tags in the standard locations."
15300 (with-current-buffer (or buffer (current-buffer))
15301 (save-excursion
15302 (save-restriction
15303 (widen)
15304 (goto-char (point-min))
15305 (let (case-fold-search)
15306 (if (re-search-forward
15307 (format org-complex-heading-regexp-format
15308 (regexp-quote heading)) nil t)
15309 (if pos-only
15310 (match-beginning 0)
15311 (move-marker (make-marker) (match-beginning 0)))))))))
15313 (defun org-find-exact-heading-in-directory (heading &optional dir)
15314 "Find Org node headline HEADING in all .org files in directory DIR.
15315 When the target headline is found, return a marker to this location."
15316 (let ((files (directory-files (or dir default-directory)
15317 nil "\\`[^.#].*\\.org\\'"))
15318 file visiting m buffer)
15319 (catch 'found
15320 (while (setq file (pop files))
15321 (message "trying %s" file)
15322 (setq visiting (org-find-base-buffer-visiting file))
15323 (setq buffer (or visiting (find-file-noselect file)))
15324 (setq m (org-find-exact-headline-in-buffer
15325 heading buffer))
15326 (when (and (not m) (not visiting)) (kill-buffer buffer))
15327 (and m (throw 'found m))))))
15329 (defun org-find-entry-with-id (ident)
15330 "Locate the entry that contains the ID property with exact value IDENT.
15331 IDENT can be a string, a symbol or a number, this function will search for
15332 the string representation of it.
15333 Return the position where this entry starts, or nil if there is no such entry."
15334 (interactive "sID: ")
15335 (let ((id (cond
15336 ((stringp ident) ident)
15337 ((symbol-name ident) (symbol-name ident))
15338 ((numberp ident) (number-to-string ident))
15339 (t (error "IDENT %s must be a string, symbol or number" ident))))
15340 (case-fold-search nil))
15341 (save-excursion
15342 (save-restriction
15343 (widen)
15344 (goto-char (point-min))
15345 (when (re-search-forward
15346 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15347 nil t)
15348 (org-back-to-heading t)
15349 (point))))))
15351 ;;;; Timestamps
15353 (defvar org-last-changed-timestamp nil)
15354 (defvar org-last-inserted-timestamp nil
15355 "The last time stamp inserted with `org-insert-time-stamp'.")
15356 (defvar org-time-was-given) ; dynamically scoped parameter
15357 (defvar org-end-time-was-given) ; dynamically scoped parameter
15358 (defvar org-ts-what) ; dynamically scoped parameter
15360 (defun org-time-stamp (arg &optional inactive)
15361 "Prompt for a date/time and insert a time stamp.
15362 If the user specifies a time like HH:MM or if this command is
15363 called with at least one prefix argument, the time stamp contains
15364 the date and the time. Otherwise, only the date is be included.
15366 All parts of a date not specified by the user is filled in from
15367 the current date/time. So if you just press return without
15368 typing anything, the time stamp will represent the current
15369 date/time.
15371 If there is already a timestamp at the cursor, it will be
15372 modified.
15374 With two universal prefix arguments, insert an active timestamp
15375 with the current time without prompting the user."
15376 (interactive "P")
15377 (let* ((ts nil)
15378 (default-time
15379 ;; Default time is either today, or, when entering a range,
15380 ;; the range start.
15381 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15382 (save-excursion
15383 (re-search-backward
15384 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15385 (- (point) 20) t)))
15386 (apply 'encode-time (org-parse-time-string (match-string 1)))
15387 (current-time)))
15388 (default-input (and ts (org-get-compact-tod ts)))
15389 (repeater (save-excursion
15390 (save-match-data
15391 (beginning-of-line)
15392 (when (re-search-forward
15393 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15394 (save-excursion (progn (end-of-line) (point))) t)
15395 (match-string 0)))))
15396 org-time-was-given org-end-time-was-given time)
15397 (cond
15398 ((and (org-at-timestamp-p t)
15399 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15400 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15401 (insert "--")
15402 (setq time (let ((this-command this-command))
15403 (org-read-date arg 'totime nil nil
15404 default-time default-input inactive)))
15405 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15406 ((org-at-timestamp-p t)
15407 (setq time (let ((this-command this-command))
15408 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15409 (when (org-at-timestamp-p t) ; just to get the match data
15410 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15411 (replace-match "")
15412 (setq org-last-changed-timestamp
15413 (org-insert-time-stamp
15414 time (or org-time-was-given arg)
15415 inactive nil nil (list org-end-time-was-given)))
15416 (when repeater (goto-char (1- (point))) (insert " " repeater)
15417 (setq org-last-changed-timestamp
15418 (concat (substring org-last-inserted-timestamp 0 -1)
15419 " " repeater ">"))))
15420 (message "Timestamp updated"))
15421 ((equal arg '(16))
15422 (org-insert-time-stamp (current-time) t))
15424 (setq time (let ((this-command this-command))
15425 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15426 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15427 nil nil (list org-end-time-was-given))))))
15429 ;; FIXME: can we use this for something else, like computing time differences?
15430 (defun org-get-compact-tod (s)
15431 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15432 (let* ((t1 (match-string 1 s))
15433 (h1 (string-to-number (match-string 2 s)))
15434 (m1 (string-to-number (match-string 3 s)))
15435 (t2 (and (match-end 4) (match-string 5 s)))
15436 (h2 (and t2 (string-to-number (match-string 6 s))))
15437 (m2 (and t2 (string-to-number (match-string 7 s))))
15438 dh dm)
15439 (if (not t2)
15441 (setq dh (- h2 h1) dm (- m2 m1))
15442 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15443 (concat t1 "+" (number-to-string dh)
15444 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15446 (defun org-time-stamp-inactive (&optional arg)
15447 "Insert an inactive time stamp.
15448 An inactive time stamp is enclosed in square brackets instead of angle
15449 brackets. It is inactive in the sense that it does not trigger agenda entries,
15450 does not link to the calendar and cannot be changed with the S-cursor keys.
15451 So these are more for recording a certain time/date."
15452 (interactive "P")
15453 (org-time-stamp arg 'inactive))
15455 (defvar org-date-ovl (make-overlay 1 1))
15456 (overlay-put org-date-ovl 'face 'org-date-selected)
15457 (org-detach-overlay org-date-ovl)
15459 (defvar org-ans1) ; dynamically scoped parameter
15460 (defvar org-ans2) ; dynamically scoped parameter
15462 (defvar org-plain-time-of-day-regexp) ; defined below
15464 (defvar org-overriding-default-time nil) ; dynamically scoped
15465 (defvar org-read-date-overlay nil)
15466 (defvar org-dcst nil) ; dynamically scoped
15467 (defvar org-read-date-history nil)
15468 (defvar org-read-date-final-answer nil)
15469 (defvar org-read-date-analyze-futurep nil)
15470 (defvar org-read-date-analyze-forced-year nil)
15471 (defvar org-read-date-inactive)
15473 (defun org-read-date (&optional org-with-time to-time from-string prompt
15474 default-time default-input inactive)
15475 "Read a date, possibly a time, and make things smooth for the user.
15476 The prompt will suggest to enter an ISO date, but you can also enter anything
15477 which will at least partially be understood by `parse-time-string'.
15478 Unrecognized parts of the date will default to the current day, month, year,
15479 hour and minute. If this command is called to replace a timestamp at point,
15480 or to enter the second timestamp of a range, the default time is taken
15481 from the existing stamp. Furthermore, the command prefers the future,
15482 so if you are giving a date where the year is not given, and the day-month
15483 combination is already past in the current year, it will assume you
15484 mean next year. For details, see the manual. A few examples:
15486 3-2-5 --> 2003-02-05
15487 feb 15 --> currentyear-02-15
15488 2/15 --> currentyear-02-15
15489 sep 12 9 --> 2009-09-12
15490 12:45 --> today 12:45
15491 22 sept 0:34 --> currentyear-09-22 0:34
15492 12 --> currentyear-currentmonth-12
15493 Fri --> nearest Friday (today or later)
15494 etc.
15496 Furthermore you can specify a relative date by giving, as the *first* thing
15497 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15498 change in days weeks, months, years.
15499 With a single plus or minus, the date is relative to today. With a double
15500 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15501 +4d --> four days from today
15502 +4 --> same as above
15503 +2w --> two weeks from today
15504 ++5 --> five days from default date
15506 The function understands only English month and weekday abbreviations.
15508 While prompting, a calendar is popped up - you can also select the
15509 date with the mouse (button 1). The calendar shows a period of three
15510 months. To scroll it to other months, use the keys `>' and `<'.
15511 If you don't like the calendar, turn it off with
15512 \(setq org-read-date-popup-calendar nil)
15514 With optional argument TO-TIME, the date will immediately be converted
15515 to an internal time.
15516 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15517 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15518 still enter a time, and this function will inform the calling routine
15519 about this change. The calling routine may then choose to change the
15520 format used to insert the time stamp into the buffer to include the time.
15521 With optional argument FROM-STRING, read from this string instead from
15522 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15523 the time/date that is used for everything that is not specified by the
15524 user."
15525 (require 'parse-time)
15526 (let* ((org-time-stamp-rounding-minutes
15527 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15528 (org-dcst org-display-custom-times)
15529 (ct (org-current-time))
15530 (org-def (or org-overriding-default-time default-time ct))
15531 (org-defdecode (decode-time org-def))
15532 (dummy (progn
15533 (when (< (nth 2 org-defdecode) org-extend-today-until)
15534 (setcar (nthcdr 2 org-defdecode) -1)
15535 (setcar (nthcdr 1 org-defdecode) 59)
15536 (setq org-def (apply 'encode-time org-defdecode)
15537 org-defdecode (decode-time org-def)))))
15538 (calendar-frame-setup nil)
15539 (calendar-setup nil)
15540 (calendar-move-hook nil)
15541 (calendar-view-diary-initially-flag nil)
15542 (calendar-view-holidays-initially-flag nil)
15543 (timestr (format-time-string
15544 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15545 (prompt (concat (if prompt (concat prompt " ") "")
15546 (format "Date+time [%s]: " timestr)))
15547 ans (org-ans0 "") org-ans1 org-ans2 final)
15549 (cond
15550 (from-string (setq ans from-string))
15551 (org-read-date-popup-calendar
15552 (save-excursion
15553 (save-window-excursion
15554 (calendar)
15555 (org-eval-in-calendar '(setq cursor-type nil) t)
15556 (unwind-protect
15557 (progn
15558 (calendar-forward-day (- (time-to-days org-def)
15559 (calendar-absolute-from-gregorian
15560 (calendar-current-date))))
15561 (org-eval-in-calendar nil t)
15562 (let* ((old-map (current-local-map))
15563 (map (copy-keymap calendar-mode-map))
15564 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15565 (org-defkey map (kbd "RET") 'org-calendar-select)
15566 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15567 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15568 (org-defkey minibuffer-local-map [(meta shift left)]
15569 (lambda () (interactive)
15570 (org-eval-in-calendar '(calendar-backward-month 1))))
15571 (org-defkey minibuffer-local-map [(meta shift right)]
15572 (lambda () (interactive)
15573 (org-eval-in-calendar '(calendar-forward-month 1))))
15574 (org-defkey minibuffer-local-map [(meta shift up)]
15575 (lambda () (interactive)
15576 (org-eval-in-calendar '(calendar-backward-year 1))))
15577 (org-defkey minibuffer-local-map [(meta shift down)]
15578 (lambda () (interactive)
15579 (org-eval-in-calendar '(calendar-forward-year 1))))
15580 (org-defkey minibuffer-local-map [?\e (shift left)]
15581 (lambda () (interactive)
15582 (org-eval-in-calendar '(calendar-backward-month 1))))
15583 (org-defkey minibuffer-local-map [?\e (shift right)]
15584 (lambda () (interactive)
15585 (org-eval-in-calendar '(calendar-forward-month 1))))
15586 (org-defkey minibuffer-local-map [?\e (shift up)]
15587 (lambda () (interactive)
15588 (org-eval-in-calendar '(calendar-backward-year 1))))
15589 (org-defkey minibuffer-local-map [?\e (shift down)]
15590 (lambda () (interactive)
15591 (org-eval-in-calendar '(calendar-forward-year 1))))
15592 (org-defkey minibuffer-local-map [(shift up)]
15593 (lambda () (interactive)
15594 (org-eval-in-calendar '(calendar-backward-week 1))))
15595 (org-defkey minibuffer-local-map [(shift down)]
15596 (lambda () (interactive)
15597 (org-eval-in-calendar '(calendar-forward-week 1))))
15598 (org-defkey minibuffer-local-map [(shift left)]
15599 (lambda () (interactive)
15600 (org-eval-in-calendar '(calendar-backward-day 1))))
15601 (org-defkey minibuffer-local-map [(shift right)]
15602 (lambda () (interactive)
15603 (org-eval-in-calendar '(calendar-forward-day 1))))
15604 (org-defkey minibuffer-local-map ">"
15605 (lambda () (interactive)
15606 (org-eval-in-calendar '(scroll-calendar-left 1))))
15607 (org-defkey minibuffer-local-map "<"
15608 (lambda () (interactive)
15609 (org-eval-in-calendar '(scroll-calendar-right 1))))
15610 (org-defkey minibuffer-local-map "\C-v"
15611 (lambda () (interactive)
15612 (org-eval-in-calendar
15613 '(calendar-scroll-left-three-months 1))))
15614 (org-defkey minibuffer-local-map "\M-v"
15615 (lambda () (interactive)
15616 (org-eval-in-calendar
15617 '(calendar-scroll-right-three-months 1))))
15618 (run-hooks 'org-read-date-minibuffer-setup-hook)
15619 (unwind-protect
15620 (progn
15621 (use-local-map map)
15622 (setq org-read-date-inactive inactive)
15623 (add-hook 'post-command-hook 'org-read-date-display)
15624 (setq org-ans0 (read-string prompt default-input
15625 'org-read-date-history nil))
15626 ;; org-ans0: from prompt
15627 ;; org-ans1: from mouse click
15628 ;; org-ans2: from calendar motion
15629 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15630 (remove-hook 'post-command-hook 'org-read-date-display)
15631 (use-local-map old-map)
15632 (when org-read-date-overlay
15633 (delete-overlay org-read-date-overlay)
15634 (setq org-read-date-overlay nil)))))
15635 (bury-buffer "*Calendar*")))))
15637 (t ; Naked prompt only
15638 (unwind-protect
15639 (setq ans (read-string prompt default-input
15640 'org-read-date-history timestr))
15641 (when org-read-date-overlay
15642 (delete-overlay org-read-date-overlay)
15643 (setq org-read-date-overlay nil)))))
15645 (setq final (org-read-date-analyze ans org-def org-defdecode))
15647 (when org-read-date-analyze-forced-year
15648 (message "Year was forced into %s"
15649 (if org-read-date-force-compatible-dates
15650 "compatible range (1970-2037)"
15651 "range representable on this machine"))
15652 (ding))
15654 ;; One round trip to get rid of 34th of August and stuff like that....
15655 (setq final (decode-time (apply 'encode-time final)))
15657 (setq org-read-date-final-answer ans)
15659 (if to-time
15660 (apply 'encode-time final)
15661 (if (and (boundp 'org-time-was-given) org-time-was-given)
15662 (format "%04d-%02d-%02d %02d:%02d"
15663 (nth 5 final) (nth 4 final) (nth 3 final)
15664 (nth 2 final) (nth 1 final))
15665 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15667 (defvar org-def)
15668 (defvar org-defdecode)
15669 (defvar org-with-time)
15670 (defun org-read-date-display ()
15671 "Display the current date prompt interpretation in the minibuffer."
15672 (when org-read-date-display-live
15673 (when org-read-date-overlay
15674 (delete-overlay org-read-date-overlay))
15675 (when (minibufferp (current-buffer))
15676 (save-excursion
15677 (end-of-line 1)
15678 (while (not (equal (buffer-substring
15679 (max (point-min) (- (point) 4)) (point))
15680 " "))
15681 (insert " ")))
15682 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15683 " " (or org-ans1 org-ans2)))
15684 (org-end-time-was-given nil)
15685 (f (org-read-date-analyze ans org-def org-defdecode))
15686 (fmts (if org-dcst
15687 org-time-stamp-custom-formats
15688 org-time-stamp-formats))
15689 (fmt (if (or org-with-time
15690 (and (boundp 'org-time-was-given) org-time-was-given))
15691 (cdr fmts)
15692 (car fmts)))
15693 (txt (format-time-string fmt (apply 'encode-time f)))
15694 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15695 (txt (concat "=> " txt)))
15696 (when (and org-end-time-was-given
15697 (string-match org-plain-time-of-day-regexp txt))
15698 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15699 org-end-time-was-given
15700 (substring txt (match-end 0)))))
15701 (when org-read-date-analyze-futurep
15702 (setq txt (concat txt " (=>F)")))
15703 (setq org-read-date-overlay
15704 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15705 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15707 (defun org-read-date-analyze (ans org-def org-defdecode)
15708 "Analyze the combined answer of the date prompt."
15709 ;; FIXME: cleanup and comment
15710 (let ((nowdecode (decode-time (current-time)))
15711 delta deltan deltaw deltadef year month day
15712 hour minute second wday pm h2 m2 tl wday1
15713 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15714 (setq org-read-date-analyze-futurep nil
15715 org-read-date-analyze-forced-year nil)
15716 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15717 (setq ans "+0"))
15719 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15720 (setq ans (replace-match "" t t ans)
15721 deltan (car delta)
15722 deltaw (nth 1 delta)
15723 deltadef (nth 2 delta)))
15725 ;; Check if there is an iso week date in there. If yes, store the
15726 ;; info and postpone interpreting it until the rest of the parsing
15727 ;; is done.
15728 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15729 (setq iso-year (if (match-end 1)
15730 (org-small-year-to-year
15731 (string-to-number (match-string 1 ans))))
15732 iso-weekday (if (match-end 3)
15733 (string-to-number (match-string 3 ans)))
15734 iso-week (string-to-number (match-string 2 ans)))
15735 (setq ans (replace-match "" t t ans)))
15737 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15738 (when (string-match
15739 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15740 (setq year (if (match-end 2)
15741 (string-to-number (match-string 2 ans))
15742 (progn (setq kill-year t)
15743 (string-to-number (format-time-string "%Y"))))
15744 month (string-to-number (match-string 3 ans))
15745 day (string-to-number (match-string 4 ans)))
15746 (if (< year 100) (setq year (+ 2000 year)))
15747 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15748 t nil ans)))
15750 ;; Help matching dotted european dates
15751 (when (string-match
15752 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15753 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15754 (setq kill-year t)
15755 (string-to-number (format-time-string "%Y")))
15756 day (string-to-number (match-string 1 ans))
15757 month (string-to-number (match-string 2 ans))
15758 ans (replace-match (format "%04d-%02d-%02d" year month day)
15759 t nil ans)))
15761 ;; Help matching american dates, like 5/30 or 5/30/7
15762 (when (string-match
15763 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15764 (setq year (if (match-end 4)
15765 (string-to-number (match-string 4 ans))
15766 (progn (setq kill-year t)
15767 (string-to-number (format-time-string "%Y"))))
15768 month (string-to-number (match-string 1 ans))
15769 day (string-to-number (match-string 2 ans)))
15770 (if (< year 100) (setq year (+ 2000 year)))
15771 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15772 t nil ans)))
15773 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15774 ;; If there is a time with am/pm, and *no* time without it, we convert
15775 ;; so that matching will be successful.
15776 (loop for i from 1 to 2 do ; twice, for end time as well
15777 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15778 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15779 (setq hour (string-to-number (match-string 1 ans))
15780 minute (if (match-end 3)
15781 (string-to-number (match-string 3 ans))
15783 pm (equal ?p
15784 (string-to-char (downcase (match-string 4 ans)))))
15785 (if (and (= hour 12) (not pm))
15786 (setq hour 0)
15787 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15788 (setq ans (replace-match (format "%02d:%02d" hour minute)
15789 t t ans))))
15791 ;; Check if a time range is given as a duration
15792 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15793 (setq hour (string-to-number (match-string 1 ans))
15794 h2 (+ hour (string-to-number (match-string 3 ans)))
15795 minute (string-to-number (match-string 2 ans))
15796 m2 (+ minute (if (match-end 5) (string-to-number
15797 (match-string 5 ans))0)))
15798 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15799 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15800 t t ans)))
15802 ;; Check if there is a time range
15803 (when (boundp 'org-end-time-was-given)
15804 (setq org-time-was-given nil)
15805 (when (and (string-match org-plain-time-of-day-regexp ans)
15806 (match-end 8))
15807 (setq org-end-time-was-given (match-string 8 ans))
15808 (setq ans (concat (substring ans 0 (match-beginning 7))
15809 (substring ans (match-end 7))))))
15811 (setq tl (parse-time-string ans)
15812 day (or (nth 3 tl) (nth 3 org-defdecode))
15813 month (or (nth 4 tl)
15814 (if (and org-read-date-prefer-future
15815 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15816 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15817 (nth 4 org-defdecode)))
15818 year (or (and (not kill-year) (nth 5 tl))
15819 (if (and org-read-date-prefer-future
15820 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15821 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15822 (nth 5 org-defdecode)))
15823 hour (or (nth 2 tl) (nth 2 org-defdecode))
15824 minute (or (nth 1 tl) (nth 1 org-defdecode))
15825 second (or (nth 0 tl) 0)
15826 wday (nth 6 tl))
15828 (when (and (eq org-read-date-prefer-future 'time)
15829 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15830 (equal day (nth 3 nowdecode))
15831 (equal month (nth 4 nowdecode))
15832 (equal year (nth 5 nowdecode))
15833 (nth 2 tl)
15834 (or (< (nth 2 tl) (nth 2 nowdecode))
15835 (and (= (nth 2 tl) (nth 2 nowdecode))
15836 (nth 1 tl)
15837 (< (nth 1 tl) (nth 1 nowdecode)))))
15838 (setq day (1+ day)
15839 futurep t))
15841 ;; Special date definitions below
15842 (cond
15843 (iso-week
15844 ;; There was an iso week
15845 (require 'cal-iso)
15846 (setq futurep nil)
15847 (setq year (or iso-year year)
15848 day (or iso-weekday wday 1)
15849 wday nil ; to make sure that the trigger below does not match
15850 iso-date (calendar-gregorian-from-absolute
15851 (calendar-absolute-from-iso
15852 (list iso-week day year))))
15853 ; FIXME: Should we also push ISO weeks into the future?
15854 ; (when (and org-read-date-prefer-future
15855 ; (not iso-year)
15856 ; (< (calendar-absolute-from-gregorian iso-date)
15857 ; (time-to-days (current-time))))
15858 ; (setq year (1+ year)
15859 ; iso-date (calendar-gregorian-from-absolute
15860 ; (calendar-absolute-from-iso
15861 ; (list iso-week day year)))))
15862 (setq month (car iso-date)
15863 year (nth 2 iso-date)
15864 day (nth 1 iso-date)))
15865 (deltan
15866 (setq futurep nil)
15867 (unless deltadef
15868 (let ((now (decode-time (current-time))))
15869 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15870 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15871 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15872 ((equal deltaw "m") (setq month (+ month deltan)))
15873 ((equal deltaw "y") (setq year (+ year deltan)))))
15874 ((and wday (not (nth 3 tl)))
15875 ;; Weekday was given, but no day, so pick that day in the week
15876 ;; on or after the derived date.
15877 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15878 (unless (equal wday wday1)
15879 (setq day (+ day (% (- wday wday1 -7) 7))))))
15880 (if (and (boundp 'org-time-was-given)
15881 (nth 2 tl))
15882 (setq org-time-was-given t))
15883 (if (< year 100) (setq year (+ 2000 year)))
15884 ;; Check of the date is representable
15885 (if org-read-date-force-compatible-dates
15886 (progn
15887 (if (< year 1970)
15888 (setq year 1970 org-read-date-analyze-forced-year t))
15889 (if (> year 2037)
15890 (setq year 2037 org-read-date-analyze-forced-year t)))
15891 (condition-case nil
15892 (ignore (encode-time second minute hour day month year))
15893 (error
15894 (setq year (nth 5 org-defdecode))
15895 (setq org-read-date-analyze-forced-year t))))
15896 (setq org-read-date-analyze-futurep futurep)
15897 (list second minute hour day month year)))
15899 (defvar parse-time-weekdays)
15900 (defun org-read-date-get-relative (s today default)
15901 "Check string S for special relative date string.
15902 TODAY and DEFAULT are internal times, for today and for a default.
15903 Return shift list (N what def-flag)
15904 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15905 N is the number of WHATs to shift.
15906 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15907 the DEFAULT date rather than TODAY."
15908 (require 'parse-time)
15909 (when (and
15910 (string-match
15911 (concat
15912 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15913 "\\([0-9]+\\)?"
15914 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15915 "\\([ \t]\\|$\\)") s)
15916 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15917 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15918 (string-to-char (substring (match-string 1 s) -1))
15919 ?+))
15920 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15921 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15922 (what (if (match-end 3) (match-string 3 s) "d"))
15923 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15924 (date (if rel default today))
15925 (wday (nth 6 (decode-time date)))
15926 delta)
15927 (if wday1
15928 (progn
15929 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15930 (if (= dir ?-) (setq delta (- delta 7)))
15931 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15932 (list delta "d" rel))
15933 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15935 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15936 "Turn a user-specified date into the internal representation.
15937 The internal representation needed by the calendar is (month day year).
15938 This is a wrapper to handle the brain-dead convention in calendar that
15939 user function argument order change dependent on argument order."
15940 (if (boundp 'calendar-date-style)
15941 (cond
15942 ((eq calendar-date-style 'american)
15943 (list arg1 arg2 arg3))
15944 ((eq calendar-date-style 'european)
15945 (list arg2 arg1 arg3))
15946 ((eq calendar-date-style 'iso)
15947 (list arg2 arg3 arg1)))
15948 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15949 (if (org-bound-and-true-p european-calendar-style)
15950 (list arg2 arg1 arg3)
15951 (list arg1 arg2 arg3)))))
15953 (defun org-eval-in-calendar (form &optional keepdate)
15954 "Eval FORM in the calendar window and return to current window.
15955 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15956 otherwise stick to the current value of `org-ans2'."
15957 (let ((sf (selected-frame))
15958 (sw (selected-window)))
15959 (select-window (get-buffer-window "*Calendar*" t))
15960 (eval form)
15961 (when (and (not keepdate) (calendar-cursor-to-date))
15962 (let* ((date (calendar-cursor-to-date))
15963 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15964 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15965 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15966 (select-window sw)
15967 (org-select-frame-set-input-focus sf)))
15969 (defun org-calendar-select ()
15970 "Return to `org-read-date' with the date currently selected.
15971 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15972 (interactive)
15973 (when (calendar-cursor-to-date)
15974 (let* ((date (calendar-cursor-to-date))
15975 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15976 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15977 (if (active-minibuffer-window) (exit-minibuffer))))
15979 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15980 "Insert a date stamp for the date given by the internal TIME.
15981 WITH-HM means use the stamp format that includes the time of the day.
15982 INACTIVE means use square brackets instead of angular ones, so that the
15983 stamp will not contribute to the agenda.
15984 PRE and POST are optional strings to be inserted before and after the
15985 stamp.
15986 The command returns the inserted time stamp."
15987 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15988 stamp)
15989 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15990 (insert-before-markers (or pre ""))
15991 (when (listp extra)
15992 (setq extra (car extra))
15993 (if (and (stringp extra)
15994 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15995 (setq extra (format "-%02d:%02d"
15996 (string-to-number (match-string 1 extra))
15997 (string-to-number (match-string 2 extra))))
15998 (setq extra nil)))
15999 (when extra
16000 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16001 (insert-before-markers (setq stamp (format-time-string fmt time)))
16002 (insert-before-markers (or post ""))
16003 (setq org-last-inserted-timestamp stamp)))
16005 (defun org-toggle-time-stamp-overlays ()
16006 "Toggle the use of custom time stamp formats."
16007 (interactive)
16008 (setq org-display-custom-times (not org-display-custom-times))
16009 (unless org-display-custom-times
16010 (let ((p (point-min)) (bmp (buffer-modified-p)))
16011 (while (setq p (next-single-property-change p 'display))
16012 (if (and (get-text-property p 'display)
16013 (eq (get-text-property p 'face) 'org-date))
16014 (remove-text-properties
16015 p (setq p (next-single-property-change p 'display))
16016 '(display t))))
16017 (set-buffer-modified-p bmp)))
16018 (if (featurep 'xemacs)
16019 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16020 (org-restart-font-lock)
16021 (setq org-table-may-need-update t)
16022 (if org-display-custom-times
16023 (message "Time stamps are overlaid with custom format")
16024 (message "Time stamp overlays removed")))
16026 (defun org-display-custom-time (beg end)
16027 "Overlay modified time stamp format over timestamp between BEG and END."
16028 (let* ((ts (buffer-substring beg end))
16029 t1 w1 with-hm tf time str w2 (off 0))
16030 (save-match-data
16031 (setq t1 (org-parse-time-string ts t))
16032 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16033 (setq off (- (match-end 0) (match-beginning 0)))))
16034 (setq end (- end off))
16035 (setq w1 (- end beg)
16036 with-hm (and (nth 1 t1) (nth 2 t1))
16037 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16038 time (org-fix-decoded-time t1)
16039 str (org-add-props
16040 (format-time-string
16041 (substring tf 1 -1) (apply 'encode-time time))
16042 nil 'mouse-face 'highlight)
16043 w2 (length str))
16044 (if (not (= w2 w1))
16045 (add-text-properties (1+ beg) (+ 2 beg)
16046 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16047 (if (featurep 'xemacs)
16048 (progn
16049 (put-text-property beg end 'invisible t)
16050 (put-text-property beg end 'end-glyph (make-glyph str)))
16051 (put-text-property beg end 'display str))))
16053 (defun org-translate-time (string)
16054 "Translate all timestamps in STRING to custom format.
16055 But do this only if the variable `org-display-custom-times' is set."
16056 (when org-display-custom-times
16057 (save-match-data
16058 (let* ((start 0)
16059 (re org-ts-regexp-both)
16060 t1 with-hm inactive tf time str beg end)
16061 (while (setq start (string-match re string start))
16062 (setq beg (match-beginning 0)
16063 end (match-end 0)
16064 t1 (save-match-data
16065 (org-parse-time-string (substring string beg end) t))
16066 with-hm (and (nth 1 t1) (nth 2 t1))
16067 inactive (equal (substring string beg (1+ beg)) "[")
16068 tf (funcall (if with-hm 'cdr 'car)
16069 org-time-stamp-custom-formats)
16070 time (org-fix-decoded-time t1)
16071 str (format-time-string
16072 (concat
16073 (if inactive "[" "<") (substring tf 1 -1)
16074 (if inactive "]" ">"))
16075 (apply 'encode-time time))
16076 string (replace-match str t t string)
16077 start (+ start (length str)))))))
16078 string)
16080 (defun org-fix-decoded-time (time)
16081 "Set 0 instead of nil for the first 6 elements of time.
16082 Don't touch the rest."
16083 (let ((n 0))
16084 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16086 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16088 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16089 "Difference between TIMESTAMP-STRING and now in days.
16090 If SECONDS is non-nil, return the difference in seconds."
16091 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16092 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16093 (funcall fdiff (current-time)))))
16095 (defun org-deadline-close (timestamp-string &optional ndays)
16096 "Is the time in TIMESTAMP-STRING close to the current date?"
16097 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16098 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16099 (not (org-entry-is-done-p))))
16101 (defun org-get-wdays (ts)
16102 "Get the deadline lead time appropriate for timestring TS."
16103 (cond
16104 ((<= org-deadline-warning-days 0)
16105 ;; 0 or negative, enforce this value no matter what
16106 (- org-deadline-warning-days))
16107 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16108 ;; lead time is specified.
16109 (floor (* (string-to-number (match-string 1 ts))
16110 (cdr (assoc (match-string 2 ts)
16111 '(("d" . 1) ("w" . 7)
16112 ("m" . 30.4) ("y" . 365.25)))))))
16113 ;; go for the default.
16114 (t org-deadline-warning-days)))
16116 (defun org-calendar-select-mouse (ev)
16117 "Return to `org-read-date' with the date currently selected.
16118 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16119 (interactive "e")
16120 (mouse-set-point ev)
16121 (when (calendar-cursor-to-date)
16122 (let* ((date (calendar-cursor-to-date))
16123 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16124 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16125 (if (active-minibuffer-window) (exit-minibuffer))))
16127 (defun org-check-deadlines (ndays)
16128 "Check if there are any deadlines due or past due.
16129 A deadline is considered due if it happens within `org-deadline-warning-days'
16130 days from today's date. If the deadline appears in an entry marked DONE,
16131 it is not shown. The prefix arg NDAYS can be used to test that many
16132 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16133 (interactive "P")
16134 (let* ((org-warn-days
16135 (cond
16136 ((equal ndays '(4)) 100000)
16137 (ndays (prefix-numeric-value ndays))
16138 (t (abs org-deadline-warning-days))))
16139 (case-fold-search nil)
16140 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16141 (callback
16142 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16144 (message "%d deadlines past-due or due within %d days"
16145 (org-occur regexp nil callback)
16146 org-warn-days)))
16148 (defsubst org-re-timestamp (type)
16149 "Return a regexp for timestamp TYPE.
16150 Allowed values for TYPE are:
16152 all: all timestamps
16153 active: only active timestamps (<...>)
16154 inactive: only inactive timestamps ([...])
16155 scheduled: only scheduled timestamps
16156 deadline: only deadline timestamps
16158 When TYPE is nil, fall back on returning a regexp that matches
16159 both scheduled and deadline timestamps."
16160 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16161 ((eq type 'active) org-ts-regexp)
16162 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16163 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16164 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16165 ((eq type 'scheduled-or-deadline)
16166 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16168 (defun org-check-before-date (date)
16169 "Check if there are deadlines or scheduled entries before DATE."
16170 (interactive (list (org-read-date)))
16171 (let ((case-fold-search nil)
16172 (regexp (org-re-timestamp org-ts-type))
16173 (callback
16174 (lambda () (time-less-p
16175 (org-time-string-to-time (match-string 1))
16176 (org-time-string-to-time date)))))
16177 (message "%d entries before %s"
16178 (org-occur regexp nil callback) date)))
16180 (defun org-check-after-date (date)
16181 "Check if there are deadlines or scheduled entries after DATE."
16182 (interactive (list (org-read-date)))
16183 (let ((case-fold-search nil)
16184 (regexp (org-re-timestamp org-ts-type))
16185 (callback
16186 (lambda () (not
16187 (time-less-p
16188 (org-time-string-to-time (match-string 1))
16189 (org-time-string-to-time date))))))
16190 (message "%d entries after %s"
16191 (org-occur regexp nil callback) date)))
16193 (defun org-check-dates-range (start-date end-date)
16194 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16195 (interactive (list (org-read-date nil nil nil "Range starts")
16196 (org-read-date nil nil nil "Range end")))
16197 (let ((case-fold-search nil)
16198 (regexp (org-re-timestamp org-ts-type))
16199 (callback
16200 (lambda ()
16201 (let ((match (match-string 1)))
16202 (and
16203 (not (time-less-p
16204 (org-time-string-to-time match)
16205 (org-time-string-to-time start-date)))
16206 (time-less-p
16207 (org-time-string-to-time match)
16208 (org-time-string-to-time end-date)))))))
16209 (message "%d entries between %s and %s"
16210 (org-occur regexp nil callback) start-date end-date)))
16212 (defun org-evaluate-time-range (&optional to-buffer)
16213 "Evaluate a time range by computing the difference between start and end.
16214 Normally the result is just printed in the echo area, but with prefix arg
16215 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16216 If the time range is actually in a table, the result is inserted into the
16217 next column.
16218 For time difference computation, a year is assumed to be exactly 365
16219 days in order to avoid rounding problems."
16220 (interactive "P")
16222 (org-clock-update-time-maybe)
16223 (save-excursion
16224 (unless (org-at-date-range-p t)
16225 (goto-char (point-at-bol))
16226 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16227 (if (not (org-at-date-range-p t))
16228 (error "Not at a time-stamp range, and none found in current line")))
16229 (let* ((ts1 (match-string 1))
16230 (ts2 (match-string 2))
16231 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16232 (match-end (match-end 0))
16233 (time1 (org-time-string-to-time ts1))
16234 (time2 (org-time-string-to-time ts2))
16235 (t1 (org-float-time time1))
16236 (t2 (org-float-time time2))
16237 (diff (abs (- t2 t1)))
16238 (negative (< (- t2 t1) 0))
16239 ;; (ys (floor (* 365 24 60 60)))
16240 (ds (* 24 60 60))
16241 (hs (* 60 60))
16242 (fy "%dy %dd %02d:%02d")
16243 (fy1 "%dy %dd")
16244 (fd "%dd %02d:%02d")
16245 (fd1 "%dd")
16246 (fh "%02d:%02d")
16247 y d h m align)
16248 (if havetime
16249 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16251 d (floor (/ diff ds)) diff (mod diff ds)
16252 h (floor (/ diff hs)) diff (mod diff hs)
16253 m (floor (/ diff 60)))
16254 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16256 d (floor (+ (/ diff ds) 0.5))
16257 h 0 m 0))
16258 (if (not to-buffer)
16259 (message "%s" (org-make-tdiff-string y d h m))
16260 (if (org-at-table-p)
16261 (progn
16262 (goto-char match-end)
16263 (setq align t)
16264 (and (looking-at " *|") (goto-char (match-end 0))))
16265 (goto-char match-end))
16266 (if (looking-at
16267 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16268 (replace-match ""))
16269 (if negative (insert " -"))
16270 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16271 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16272 (insert " " (format fh h m))))
16273 (if align (org-table-align))
16274 (message "Time difference inserted")))))
16276 (defun org-make-tdiff-string (y d h m)
16277 (let ((fmt "")
16278 (l nil))
16279 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16280 l (push y l)))
16281 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16282 l (push d l)))
16283 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16284 l (push h l)))
16285 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16286 l (push m l)))
16287 (apply 'format fmt (nreverse l))))
16289 (defun org-time-string-to-time (s &optional buffer pos)
16290 "Convert a timestamp string into internal time."
16291 (condition-case errdata
16292 (apply 'encode-time (org-parse-time-string s))
16293 (error (error "Bad timestamp `%s'%s\nError was: %s"
16294 s (if (not (and buffer pos))
16296 (format " at %d in buffer `%s'" pos buffer))
16297 (cdr errdata)))))
16299 (defun org-time-string-to-seconds (s)
16300 "Convert a timestamp string to a number of seconds."
16301 (org-float-time (org-time-string-to-time s)))
16303 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16304 "Convert a time stamp to an absolute day number.
16305 If there is a specifier for a cyclic time stamp, get the closest date to
16306 DAYNR.
16307 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16308 The variable date is bound by the calendar when this is called."
16309 (cond
16310 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16311 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16312 daynr
16313 (+ daynr 1000)))
16314 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16315 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16316 (time-to-days (current-time))) (match-string 0 s)
16317 prefer show-all))
16318 (t (time-to-days
16319 (condition-case errdata
16320 (apply 'encode-time (org-parse-time-string s))
16321 (error (error "Bad timestamp `%s'%s\nError was: %s"
16322 s (if (not (and buffer pos))
16324 (format " at %d in buffer `%s'" pos buffer))
16325 (cdr errdata))))))))
16327 (defun org-days-to-iso-week (days)
16328 "Return the iso week number."
16329 (require 'cal-iso)
16330 (car (calendar-iso-from-absolute days)))
16332 (defun org-small-year-to-year (year)
16333 "Convert 2-digit years into 4-digit years.
16334 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16335 The year 2000 cannot be abbreviated. Any year larger than 99
16336 is returned unchanged."
16337 (if (< year 38)
16338 (setq year (+ 2000 year))
16339 (if (< year 100)
16340 (setq year (+ 1900 year))))
16341 year)
16343 (defun org-time-from-absolute (d)
16344 "Return the time corresponding to date D.
16345 D may be an absolute day number, or a calendar-type list (month day year)."
16346 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16347 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16349 (defun org-calendar-holiday ()
16350 "List of holidays, for Diary display in Org-mode."
16351 (require 'holidays)
16352 (let ((hl (funcall
16353 (if (fboundp 'calendar-check-holidays)
16354 'calendar-check-holidays 'check-calendar-holidays) date)))
16355 (if hl (mapconcat 'identity hl "; "))))
16357 (defun org-diary-sexp-entry (sexp entry date)
16358 "Process a SEXP diary ENTRY for DATE."
16359 (require 'diary-lib)
16360 (let ((result (if calendar-debug-sexp
16361 (let ((stack-trace-on-error t))
16362 (eval (car (read-from-string sexp))))
16363 (condition-case nil
16364 (eval (car (read-from-string sexp)))
16365 (error
16366 (beep)
16367 (message "Bad sexp at line %d in %s: %s"
16368 (org-current-line)
16369 (buffer-file-name) sexp)
16370 (sleep-for 2))))))
16371 (cond ((stringp result) (split-string result "; "))
16372 ((and (consp result)
16373 (not (consp (cdr result)))
16374 (stringp (cdr result))) (cdr result))
16375 ((and (consp result)
16376 (stringp (car result))) result)
16377 (result entry))))
16379 (defun org-diary-to-ical-string (frombuf)
16380 "Get iCalendar entries from diary entries in buffer FROMBUF.
16381 This uses the icalendar.el library."
16382 (let* ((tmpdir (if (featurep 'xemacs)
16383 (temp-directory)
16384 temporary-file-directory))
16385 (tmpfile (make-temp-name
16386 (expand-file-name "orgics" tmpdir)))
16387 buf rtn b e)
16388 (with-current-buffer frombuf
16389 (icalendar-export-region (point-min) (point-max) tmpfile)
16390 (setq buf (find-buffer-visiting tmpfile))
16391 (set-buffer buf)
16392 (goto-char (point-min))
16393 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16394 (setq b (match-beginning 0)))
16395 (goto-char (point-max))
16396 (if (re-search-backward "^END:VEVENT" nil t)
16397 (setq e (match-end 0)))
16398 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16399 (kill-buffer buf)
16400 (delete-file tmpfile)
16401 rtn))
16403 (defun org-closest-date (start current change prefer show-all)
16404 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16405 When PREFER is `past', return a date that is either CURRENT or past.
16406 When PREFER is `future', return a date that is either CURRENT or future.
16407 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16408 ;; Make the proper lists from the dates
16409 (catch 'exit
16410 (let ((a1 '(("h" . hour)
16411 ("d" . day)
16412 ("w" . week)
16413 ("m" . month)
16414 ("y" . year)))
16415 (shour (nth 2 (org-parse-time-string start)))
16416 dn dw sday cday n1 n2 n0
16417 d m y y1 y2 date1 date2 nmonths nm ny m2)
16419 (setq start (org-date-to-gregorian start)
16420 current (org-date-to-gregorian
16421 (if show-all
16422 current
16423 (time-to-days (current-time))))
16424 sday (calendar-absolute-from-gregorian start)
16425 cday (calendar-absolute-from-gregorian current))
16427 (if (<= cday sday) (throw 'exit sday))
16429 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16430 (setq dn (string-to-number (match-string 1 change))
16431 dw (cdr (assoc (match-string 2 change) a1)))
16432 (error "Invalid change specifier: %s" change))
16433 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16434 (cond
16435 ((eq dw 'hour)
16436 (let ((missing-hours
16437 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16438 dn)))
16439 (setq n1 (if (zerop missing-hours) cday
16440 (- cday (1+ (floor (/ missing-hours 24)))))
16441 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16442 ((eq dw 'day)
16443 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16444 n2 (+ n1 dn)))
16445 ((eq dw 'year)
16446 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16447 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16448 (setq date1 (list m d y1)
16449 n1 (calendar-absolute-from-gregorian date1)
16450 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16451 n2 (calendar-absolute-from-gregorian date2)))
16452 ((eq dw 'month)
16453 ;; approx number of month between the two dates
16454 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16455 ;; How often does dn fit in there?
16456 (setq d (nth 1 start) m (car start) y (nth 2 start)
16457 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16458 m (+ m nm)
16459 ny (floor (/ m 12))
16460 y (+ y ny)
16461 m (- m (* ny 12)))
16462 (while (> m 12) (setq m (- m 12) y (1+ y)))
16463 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16464 (setq m2 (+ m dn) y2 y)
16465 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16466 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16467 (while (<= n2 cday)
16468 (setq n1 n2 m m2 y y2)
16469 (setq m2 (+ m dn) y2 y)
16470 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16471 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16472 ;; Make sure n1 is the earlier date
16473 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16474 (if show-all
16475 (cond
16476 ((eq prefer 'past) (if (= cday n2) n2 n1))
16477 ((eq prefer 'future) (if (= cday n1) n1 n2))
16478 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16479 (cond
16480 ((eq prefer 'past) (if (= cday n2) n2 n1))
16481 ((eq prefer 'future) (if (= cday n1) n1 n2))
16482 (t (if (= cday n1) n1 n2)))))))
16484 (defun org-date-to-gregorian (date)
16485 "Turn any specification of DATE into a Gregorian date for the calendar."
16486 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16487 ((and (listp date) (= (length date) 3)) date)
16488 ((stringp date)
16489 (setq date (org-parse-time-string date))
16490 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16491 ((listp date)
16492 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16494 (defun org-parse-time-string (s &optional nodefault)
16495 "Parse the standard Org-mode time string.
16496 This should be a lot faster than the normal `parse-time-string'.
16497 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16498 hour and minute fields will be nil if not given."
16499 (if (string-match org-ts-regexp0 s)
16500 (list 0
16501 (if (or (match-beginning 8) (not nodefault))
16502 (string-to-number (or (match-string 8 s) "0")))
16503 (if (or (match-beginning 7) (not nodefault))
16504 (string-to-number (or (match-string 7 s) "0")))
16505 (string-to-number (match-string 4 s))
16506 (string-to-number (match-string 3 s))
16507 (string-to-number (match-string 2 s))
16508 nil nil nil)
16509 (error "Not a standard Org-mode time string: %s" s)))
16511 (defun org-timestamp-up (&optional arg)
16512 "Increase the date item at the cursor by one.
16513 If the cursor is on the year, change the year. If it is on the month,
16514 the day or the time, change that.
16515 With prefix ARG, change by that many units."
16516 (interactive "p")
16517 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16519 (defun org-timestamp-down (&optional arg)
16520 "Decrease the date item at the cursor by one.
16521 If the cursor is on the year, change the year. If it is on the month,
16522 the day or the time, change that.
16523 With prefix ARG, change by that many units."
16524 (interactive "p")
16525 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16527 (defun org-timestamp-up-day (&optional arg)
16528 "Increase the date in the time stamp by one day.
16529 With prefix ARG, change that many days."
16530 (interactive "p")
16531 (if (and (not (org-at-timestamp-p t))
16532 (org-at-heading-p))
16533 (org-todo 'up)
16534 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16536 (defun org-timestamp-down-day (&optional arg)
16537 "Decrease the date in the time stamp by one day.
16538 With prefix ARG, change that many days."
16539 (interactive "p")
16540 (if (and (not (org-at-timestamp-p t))
16541 (org-at-heading-p))
16542 (org-todo 'down)
16543 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16545 (defun org-at-timestamp-p (&optional inactive-ok)
16546 "Determine if the cursor is in or at a timestamp."
16547 (interactive)
16548 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16549 (pos (point))
16550 (ans (or (looking-at tsr)
16551 (save-excursion
16552 (skip-chars-backward "^[<\n\r\t")
16553 (if (> (point) (point-min)) (backward-char 1))
16554 (and (looking-at tsr)
16555 (> (- (match-end 0) pos) -1))))))
16556 (and ans
16557 (boundp 'org-ts-what)
16558 (setq org-ts-what
16559 (cond
16560 ((= pos (match-beginning 0)) 'bracket)
16561 ;; Point is considered to be "on the bracket" whether
16562 ;; it's really on it or right after it.
16563 ((= pos (1- (match-end 0))) 'bracket)
16564 ((= pos (match-end 0)) 'after)
16565 ((org-pos-in-match-range pos 2) 'year)
16566 ((org-pos-in-match-range pos 3) 'month)
16567 ((org-pos-in-match-range pos 7) 'hour)
16568 ((org-pos-in-match-range pos 8) 'minute)
16569 ((or (org-pos-in-match-range pos 4)
16570 (org-pos-in-match-range pos 5)) 'day)
16571 ((and (> pos (or (match-end 8) (match-end 5)))
16572 (< pos (match-end 0)))
16573 (- pos (or (match-end 8) (match-end 5))))
16574 (t 'day))))
16575 ans))
16577 (defun org-toggle-timestamp-type ()
16578 "Toggle the type (<active> or [inactive]) of a time stamp."
16579 (interactive)
16580 (when (org-at-timestamp-p t)
16581 (let ((beg (match-beginning 0)) (end (match-end 0))
16582 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16583 (save-excursion
16584 (goto-char beg)
16585 (while (re-search-forward "[][<>]" end t)
16586 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16587 t t)))
16588 (message "Timestamp is now %sactive"
16589 (if (equal (char-after beg) ?<) "" "in")))))
16591 (defvar org-clock-history) ; defined in org-clock.el
16592 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16593 (defun org-timestamp-change (n &optional what updown)
16594 "Change the date in the time stamp at point.
16595 The date will be changed by N times WHAT. WHAT can be `day', `month',
16596 `year', `minute', `second'. If WHAT is not given, the cursor position
16597 in the timestamp determines what will be changed."
16598 (let ((origin (point)) origin-cat
16599 with-hm inactive
16600 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16601 org-ts-what
16602 extra rem
16603 ts time time0 fixnext clrgx)
16604 (if (not (org-at-timestamp-p t))
16605 (error "Not at a timestamp"))
16606 (if (and (not what) (eq org-ts-what 'bracket))
16607 (org-toggle-timestamp-type)
16608 ;; Point isn't on brackets. Remember the part of the time-stamp
16609 ;; the point was in. Indeed, size of time-stamps may change,
16610 ;; but point must be kept in the same category nonetheless.
16611 (setq origin-cat org-ts-what)
16612 (if (and (not what) (not (eq org-ts-what 'day))
16613 org-display-custom-times
16614 (get-text-property (point) 'display)
16615 (not (get-text-property (1- (point)) 'display)))
16616 (setq org-ts-what 'day))
16617 (setq org-ts-what (or what org-ts-what)
16618 inactive (= (char-after (match-beginning 0)) ?\[)
16619 ts (match-string 0))
16620 (replace-match "")
16621 (if (string-match
16622 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16624 (setq extra (match-string 1 ts)))
16625 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16626 (setq with-hm t))
16627 (setq time0 (org-parse-time-string ts))
16628 (when (and updown
16629 (eq org-ts-what 'minute)
16630 (not current-prefix-arg))
16631 ;; This looks like s-up and s-down. Change by one rounding step.
16632 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16633 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16634 (setcar (cdr time0) (+ (nth 1 time0)
16635 (if (> n 0) (- rem) (- dm rem))))))
16636 (setq time
16637 (encode-time (or (car time0) 0)
16638 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16639 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16640 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16641 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16642 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16643 (nthcdr 6 time0)))
16644 (when (and (member org-ts-what '(hour minute))
16645 extra
16646 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16647 (setq extra (org-modify-ts-extra
16648 extra
16649 (if (eq org-ts-what 'hour) 2 5)
16650 n dm)))
16651 (when (integerp org-ts-what)
16652 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16653 (if (eq what 'calendar)
16654 (let ((cal-date (org-get-date-from-calendar)))
16655 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16656 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16657 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16658 (setcar time0 (or (car time0) 0))
16659 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16660 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16661 (setq time (apply 'encode-time time0))))
16662 ;; Insert the new time-stamp, and ensure point stays in the same
16663 ;; category as before (i.e. not after the last position in that
16664 ;; category).
16665 (let ((pos (point)))
16666 ;; Stay before inserted string. `save-excursion' is of no use.
16667 (setq org-last-changed-timestamp
16668 (org-insert-time-stamp time with-hm inactive nil nil extra))
16669 (goto-char pos))
16670 (save-match-data
16671 (looking-at org-ts-regexp3)
16672 (goto-char (cond
16673 ;; `day' category ends before `hour' if any, or at
16674 ;; the end of the day name.
16675 ((eq origin-cat 'day)
16676 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16677 ((eq origin-cat 'hour) (min (match-end 7) origin))
16678 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16679 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16680 ;; `year' and `month' have both fixed size: point
16681 ;; couldn't have moved into another part.
16682 (t origin))))
16683 ;; Update clock if on a CLOCK line.
16684 (org-clock-update-time-maybe)
16685 ;; Maybe adjust the closest clock in `org-clock-history'
16686 (when org-clock-adjust-closest
16687 (if (not (and (org-at-clock-log-p)
16688 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16689 org-clock-history))))))
16690 (message "No clock to adjust")
16691 (cond ((save-excursion ; fix previous clock?
16692 (re-search-backward org-ts-regexp0 nil t)
16693 (org-looking-back (concat org-clock-string " \\[")))
16694 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16695 ((save-excursion ; fix next clock?
16696 (re-search-backward org-ts-regexp0 nil t)
16697 (looking-at (concat org-ts-regexp0 "\\] =>")))
16698 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16699 (save-window-excursion
16700 ;; Find closest clock to point, adjust the previous/next one in history
16701 (let* ((p (save-excursion (org-back-to-heading t)))
16702 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16703 (clfixnth
16704 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16705 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16706 (if (not clfixpos)
16707 (message "No clock to adjust")
16708 (save-excursion
16709 (org-goto-marker-or-bmk clfixpos)
16710 (org-show-subtree)
16711 (when (re-search-forward clrgx nil t)
16712 (goto-char (match-beginning 1))
16713 (let (org-clock-adjust-closest)
16714 (org-timestamp-change n org-ts-what updown))
16715 (message "Clock adjusted in %s for heading: %s"
16716 (file-name-nondirectory (buffer-file-name))
16717 (org-get-heading t t)))))))))
16718 ;; Try to recenter the calendar window, if any.
16719 (if (and org-calendar-follow-timestamp-change
16720 (get-buffer-window "*Calendar*" t)
16721 (memq org-ts-what '(day month year)))
16722 (org-recenter-calendar (time-to-days time))))))
16724 (defun org-modify-ts-extra (s pos n dm)
16725 "Change the different parts of the lead-time and repeat fields in timestamp."
16726 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16727 ng h m new rem)
16728 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16729 (cond
16730 ((or (org-pos-in-match-range pos 2)
16731 (org-pos-in-match-range pos 3))
16732 (setq m (string-to-number (match-string 3 s))
16733 h (string-to-number (match-string 2 s)))
16734 (if (org-pos-in-match-range pos 2)
16735 (setq h (+ h n))
16736 (setq n (* dm (org-no-warnings (signum n))))
16737 (when (not (= 0 (setq rem (% m dm))))
16738 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16739 (setq m (+ m n)))
16740 (if (< m 0) (setq m (+ m 60) h (1- h)))
16741 (if (> m 59) (setq m (- m 60) h (1+ h)))
16742 (setq h (min 24 (max 0 h)))
16743 (setq ng 1 new (format "-%02d:%02d" h m)))
16744 ((org-pos-in-match-range pos 6)
16745 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16746 ((org-pos-in-match-range pos 5)
16747 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16749 ((org-pos-in-match-range pos 9)
16750 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16751 ((org-pos-in-match-range pos 8)
16752 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16754 (when ng
16755 (setq s (concat
16756 (substring s 0 (match-beginning ng))
16758 (substring s (match-end ng))))))
16761 (defun org-recenter-calendar (date)
16762 "If the calendar is visible, recenter it to DATE."
16763 (let ((cwin (get-buffer-window "*Calendar*" t)))
16764 (when cwin
16765 (let ((calendar-move-hook nil))
16766 (with-selected-window cwin
16767 (calendar-goto-date (if (listp date) date
16768 (calendar-gregorian-from-absolute date))))))))
16770 (defun org-goto-calendar (&optional arg)
16771 "Go to the Emacs calendar at the current date.
16772 If there is a time stamp in the current line, go to that date.
16773 A prefix ARG can be used to force the current date."
16774 (interactive "P")
16775 (let ((tsr org-ts-regexp) diff
16776 (calendar-move-hook nil)
16777 (calendar-view-holidays-initially-flag nil)
16778 (calendar-view-diary-initially-flag nil))
16779 (if (or (org-at-timestamp-p)
16780 (save-excursion
16781 (beginning-of-line 1)
16782 (looking-at (concat ".*" tsr))))
16783 (let ((d1 (time-to-days (current-time)))
16784 (d2 (time-to-days
16785 (org-time-string-to-time (match-string 1)))))
16786 (setq diff (- d2 d1))))
16787 (calendar)
16788 (calendar-goto-today)
16789 (if (and diff (not arg)) (calendar-forward-day diff))))
16791 (defun org-get-date-from-calendar ()
16792 "Return a list (month day year) of date at point in calendar."
16793 (with-current-buffer "*Calendar*"
16794 (save-match-data
16795 (calendar-cursor-to-date))))
16797 (defun org-date-from-calendar ()
16798 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16799 If there is already a time stamp at the cursor position, update it."
16800 (interactive)
16801 (if (org-at-timestamp-p t)
16802 (org-timestamp-change 0 'calendar)
16803 (let ((cal-date (org-get-date-from-calendar)))
16804 (org-insert-time-stamp
16805 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16807 (defun org-minutes-to-clocksum-string (m)
16808 "Format number of minutes as a clocksum string.
16809 The format is determined by `org-time-clocksum-format',
16810 `org-time-clocksum-use-fractional' and
16811 `org-time-clocksum-fractional-format'."
16812 (let ((clocksum "") fmt n)
16813 ;; fractional format
16814 (if org-time-clocksum-use-fractional
16815 (cond
16816 ;; single format string
16817 ((stringp org-time-clocksum-fractional-format)
16818 (format org-time-clocksum-fractional-format (/ m 60.0)))
16819 ;; choice of fractional formats for different time units
16820 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
16821 (> (/ (truncate m) (* 365 24 60)) 0))
16822 (format fmt (/ m (* 365 24 60.0))))
16823 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
16824 (> (/ (truncate m) (* 30 24 60)) 0))
16825 (format fmt (/ m (* 30 24 60.0))))
16826 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16827 (> (/ (truncate m) (* 7 24 60)) 0))
16828 (format fmt (/ m (* 7 24 60.0))))
16829 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
16830 (> (/ (truncate m) (* 24 60)) 0))
16831 (format fmt (/ m (* 24 60.0))))
16832 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16833 (> (/ (truncate m) 60) 0))
16834 (format fmt (/ m 60.0)))
16835 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
16836 (format fmt m))
16837 ;; fall back to smallest time unit with a format
16838 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16839 (format fmt (/ m 60.0)))
16840 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
16841 (format fmt (/ m (* 24 60.0))))
16842 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16843 (format fmt (/ m (* 7 24 60.0))))
16844 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
16845 (format fmt (/ m (* 30 24 60.0))))
16846 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
16847 (format fmt (/ m (* 365 24 60.0)))))
16848 ;; standard (non-fractional) format, with single format string
16849 (if (stringp org-time-clocksum-format)
16850 (format org-time-clocksum-format (setq n (/ m 60)) (- m (* 60 n)))
16851 ;; separate formats components
16852 (and (setq fmt (plist-get org-time-clocksum-format :years))
16853 (or (> (setq n (/ (truncate m) (* 365 24 60))) 0)
16854 (plist-get org-time-clocksum-format :require-years))
16855 (setq clocksum (concat clocksum (format fmt n))
16856 m (- m (* n 365 24 60))))
16857 (and (setq fmt (plist-get org-time-clocksum-format :months))
16858 (or (> (setq n (/ (truncate m) (* 30 24 60))) 0)
16859 (plist-get org-time-clocksum-format :require-months))
16860 (setq clocksum (concat clocksum (format fmt n))
16861 m (- m (* n 30 24 60))))
16862 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
16863 (or (> (setq n (/ (truncate m) (* 7 24 60))) 0)
16864 (plist-get org-time-clocksum-format :require-weeks))
16865 (setq clocksum (concat clocksum (format fmt n))
16866 m (- m (* n 7 24 60))))
16867 (and (setq fmt (plist-get org-time-clocksum-format :days))
16868 (or (> (setq n (/ (truncate m) (* 24 60))) 0)
16869 (plist-get org-time-clocksum-format :require-days))
16870 (setq clocksum (concat clocksum (format fmt n))
16871 m (- m (* n 24 60))))
16872 (and (setq fmt (plist-get org-time-clocksum-format :hours))
16873 (or (> (setq n (/ (truncate m) 60)) 0)
16874 (plist-get org-time-clocksum-format :require-hours))
16875 (setq clocksum (concat clocksum (format fmt n))
16876 m (- m (* n 60))))
16877 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
16878 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
16879 (setq clocksum (concat clocksum (format fmt m))))
16880 ;; return formatted time duration
16881 clocksum))))
16883 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
16884 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
16885 "Org mode version 8.0")
16887 (defun org-hours-to-clocksum-string (n)
16888 (org-minutes-to-clocksum-string (* n 60)))
16890 (defun org-hh:mm-string-to-minutes (s)
16891 "Convert a string H:MM to a number of minutes.
16892 If the string is just a number, interpret it as minutes.
16893 In fact, the first hh:mm or number in the string will be taken,
16894 there can be extra stuff in the string.
16895 If no number is found, the return value is 0."
16896 (cond
16897 ((integerp s) s)
16898 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16899 (+ (* (string-to-number (match-string 1 s)) 60)
16900 (string-to-number (match-string 2 s))))
16901 ((string-match "\\([0-9]+\\)" s)
16902 (string-to-number (match-string 1 s)))
16903 (t 0)))
16905 (defcustom org-effort-durations
16906 `(("h" . 60)
16907 ("d" . ,(* 60 8))
16908 ("w" . ,(* 60 8 5))
16909 ("m" . ,(* 60 8 5 4))
16910 ("y" . ,(* 60 8 5 40)))
16911 "Conversion factor to minutes for an effort modifier.
16913 Each entry has the form (MODIFIER . MINUTES).
16915 In an effort string, a number followed by MODIFIER is multiplied
16916 by the specified number of MINUTES to obtain an effort in
16917 minutes.
16919 For example, if the value of this variable is ((\"hours\" . 60)), then an
16920 effort string \"2hours\" is equivalent to 120 minutes."
16921 :group 'org-agenda
16922 :version "24.1"
16923 :type '(alist :key-type (string :tag "Modifier")
16924 :value-type (number :tag "Minutes")))
16926 (defcustom org-image-actual-width t
16927 "Should we use the actual width of images when inlining them?
16929 When set to `t', always use the image width.
16931 When set to a number, use imagemagick (when available) to set
16932 the image's width to this value.
16934 When set to a number in a list, try to get the width from the
16935 #+ATTR.* keyword if it matches a width specification like
16936 width=\"[0-9]+\", and fall back on that number if none is found.
16938 When set to nil, try to get the width from an #+ATTR.* keyword
16939 and fall back on the original width if none is found.
16941 This requires Emacs >= 24.1, build with imagemagick support."
16942 :group 'org-appearance
16943 :version "24.3"
16944 :type '(choice
16945 (const :tag "Use the image width" t)
16946 (integer :tag "Use a number of pixels")
16947 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16948 (const :tag "Use #+ATTR* or don't resize" nil)))
16950 (defun org-duration-string-to-minutes (s &optional output-to-string)
16951 "Convert a duration string S to minutes.
16953 A bare number is interpreted as minutes, modifiers can be set by
16954 customizing `org-effort-durations' (which see).
16956 Entries containing a colon are interpreted as H:MM by
16957 `org-hh:mm-string-to-minutes'."
16958 (let ((result 0)
16959 (re (concat "\\([0-9.]+\\) *\\("
16960 (regexp-opt (mapcar 'car org-effort-durations))
16961 "\\)")))
16962 (while (string-match re s)
16963 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16964 (string-to-number (match-string 1 s))))
16965 (setq s (replace-match "" nil t s)))
16966 (setq result (floor result))
16967 (incf result (org-hh:mm-string-to-minutes s))
16968 (if output-to-string (number-to-string result) result)))
16970 ;;;; Files
16972 (defun org-save-all-org-buffers ()
16973 "Save all Org-mode buffers without user confirmation."
16974 (interactive)
16975 (message "Saving all Org-mode buffers...")
16976 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16977 (when (featurep 'org-id) (org-id-locations-save))
16978 (message "Saving all Org-mode buffers... done"))
16980 (defun org-revert-all-org-buffers ()
16981 "Revert all Org-mode buffers.
16982 Prompt for confirmation when there are unsaved changes.
16983 Be sure you know what you are doing before letting this function
16984 overwrite your changes.
16986 This function is useful in a setup where one tracks org files
16987 with a version control system, to revert on one machine after pulling
16988 changes from another. I believe the procedure must be like this:
16990 1. M-x org-save-all-org-buffers
16991 2. Pull changes from the other machine, resolve conflicts
16992 3. M-x org-revert-all-org-buffers"
16993 (interactive)
16994 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16995 (error "Abort"))
16996 (save-excursion
16997 (save-window-excursion
16998 (mapc
16999 (lambda (b)
17000 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17001 (with-current-buffer b buffer-file-name))
17002 (org-pop-to-buffer-same-window b)
17003 (revert-buffer t 'no-confirm)))
17004 (buffer-list))
17005 (when (and (featurep 'org-id) org-id-track-globally)
17006 (org-id-locations-load)))))
17008 ;;;; Agenda files
17010 ;;;###autoload
17011 (defun org-switchb (&optional arg)
17012 "Switch between Org buffers.
17013 With one prefix argument, restrict available buffers to files.
17014 With two prefix arguments, restrict available buffers to agenda files.
17016 Defaults to `iswitchb' for buffer name completion.
17017 Set `org-completion-use-ido' to make it use ido instead."
17018 (interactive "P")
17019 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17020 ((equal arg '(16)) (org-buffer-list 'agenda))
17021 (t (org-buffer-list))))
17022 (org-completion-use-iswitchb org-completion-use-iswitchb)
17023 (org-completion-use-ido org-completion-use-ido))
17024 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17025 (setq org-completion-use-iswitchb t))
17026 (org-pop-to-buffer-same-window
17027 (org-icompleting-read "Org buffer: "
17028 (mapcar 'list (mapcar 'buffer-name blist))
17029 nil t))))
17031 ;;; Define some older names previously used for this functionality
17032 ;;;###autoload
17033 (defalias 'org-ido-switchb 'org-switchb)
17034 ;;;###autoload
17035 (defalias 'org-iswitchb 'org-switchb)
17037 (defun org-buffer-list (&optional predicate exclude-tmp)
17038 "Return a list of Org buffers.
17039 PREDICATE can be `export', `files' or `agenda'.
17041 export restrict the list to Export buffers.
17042 files restrict the list to buffers visiting Org files.
17043 agenda restrict the list to buffers visiting agenda files.
17045 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17046 (let* ((bfn nil)
17047 (agenda-files (and (eq predicate 'agenda)
17048 (mapcar 'file-truename (org-agenda-files t))))
17049 (filter
17050 (cond
17051 ((eq predicate 'files)
17052 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17053 ((eq predicate 'export)
17054 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17055 ((eq predicate 'agenda)
17056 (lambda (b)
17057 (with-current-buffer b
17058 (and (derived-mode-p 'org-mode)
17059 (setq bfn (buffer-file-name b))
17060 (member (file-truename bfn) agenda-files)))))
17061 (t (lambda (b) (with-current-buffer b
17062 (or (derived-mode-p 'org-mode)
17063 (string-match "\*Org .*Export"
17064 (buffer-name b)))))))))
17065 (delq nil
17066 (mapcar
17067 (lambda(b)
17068 (if (and (funcall filter b)
17069 (or (not exclude-tmp)
17070 (not (string-match "tmp" (buffer-name b)))))
17072 nil))
17073 (buffer-list)))))
17075 (defun org-agenda-files (&optional unrestricted archives)
17076 "Get the list of agenda files.
17077 Optional UNRESTRICTED means return the full list even if a restriction
17078 is currently in place.
17079 When ARCHIVES is t, include all archive files that are really being
17080 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17081 `org-agenda-archives-mode' is t."
17082 (let ((files
17083 (cond
17084 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17085 ((stringp org-agenda-files) (org-read-agenda-file-list))
17086 ((listp org-agenda-files) org-agenda-files)
17087 (t (error "Invalid value of `org-agenda-files'")))))
17088 (setq files (apply 'append
17089 (mapcar (lambda (f)
17090 (if (file-directory-p f)
17091 (directory-files
17092 f t org-agenda-file-regexp)
17093 (list f)))
17094 files)))
17095 (when org-agenda-skip-unavailable-files
17096 (setq files (delq nil
17097 (mapcar (function
17098 (lambda (file)
17099 (and (file-readable-p file) file)))
17100 files))))
17101 (when (or (eq archives t)
17102 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17103 (setq files (org-add-archive-files files)))
17104 files))
17106 (defun org-agenda-file-p (&optional file)
17107 "Return non-nil, if FILE is an agenda file.
17108 If FILE is omitted, use the file associated with the current
17109 buffer."
17110 (member (or file (buffer-file-name))
17111 (org-agenda-files t)))
17113 (defun org-edit-agenda-file-list ()
17114 "Edit the list of agenda files.
17115 Depending on setup, this either uses customize to edit the variable
17116 `org-agenda-files', or it visits the file that is holding the list. In the
17117 latter case, the buffer is set up in a way that saving it automatically kills
17118 the buffer and restores the previous window configuration."
17119 (interactive)
17120 (if (stringp org-agenda-files)
17121 (let ((cw (current-window-configuration)))
17122 (find-file org-agenda-files)
17123 (org-set-local 'org-window-configuration cw)
17124 (org-add-hook 'after-save-hook
17125 (lambda ()
17126 (set-window-configuration
17127 (prog1 org-window-configuration
17128 (kill-buffer (current-buffer))))
17129 (org-install-agenda-files-menu)
17130 (message "New agenda file list installed"))
17131 nil 'local)
17132 (message "%s" (substitute-command-keys
17133 "Edit list and finish with \\[save-buffer]")))
17134 (customize-variable 'org-agenda-files)))
17136 (defun org-store-new-agenda-file-list (list)
17137 "Set new value for the agenda file list and save it correctly."
17138 (if (stringp org-agenda-files)
17139 (let ((fe (org-read-agenda-file-list t)) b u)
17140 (while (setq b (find-buffer-visiting org-agenda-files))
17141 (kill-buffer b))
17142 (with-temp-file org-agenda-files
17143 (insert
17144 (mapconcat
17145 (lambda (f) ;; Keep un-expanded entries.
17146 (if (setq u (assoc f fe))
17147 (cdr u)
17149 list "\n")
17150 "\n")))
17151 (let ((org-mode-hook nil) (org-inhibit-startup t)
17152 (org-insert-mode-line-in-empty-file nil))
17153 (setq org-agenda-files list)
17154 (customize-save-variable 'org-agenda-files org-agenda-files))))
17156 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17157 "Read the list of agenda files from a file.
17158 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17159 filenames, used by `org-store-new-agenda-file-list' to write back
17160 un-expanded file names."
17161 (when (file-directory-p org-agenda-files)
17162 (error "`org-agenda-files' cannot be a single directory"))
17163 (when (stringp org-agenda-files)
17164 (with-temp-buffer
17165 (insert-file-contents org-agenda-files)
17166 (mapcar
17167 (lambda (f)
17168 (let ((e (expand-file-name (substitute-in-file-name f)
17169 org-directory)))
17170 (if pair-with-expansion
17171 (cons e f)
17172 e)))
17173 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17175 ;;;###autoload
17176 (defun org-cycle-agenda-files ()
17177 "Cycle through the files in `org-agenda-files'.
17178 If the current buffer visits an agenda file, find the next one in the list.
17179 If the current buffer does not, find the first agenda file."
17180 (interactive)
17181 (let* ((fs (org-agenda-files t))
17182 (files (append fs (list (car fs))))
17183 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17184 file)
17185 (unless files (error "No agenda files"))
17186 (catch 'exit
17187 (while (setq file (pop files))
17188 (if (equal (file-truename file) tcf)
17189 (when (car files)
17190 (find-file (car files))
17191 (throw 'exit t))))
17192 (find-file (car fs)))
17193 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17195 (defun org-agenda-file-to-front (&optional to-end)
17196 "Move/add the current file to the top of the agenda file list.
17197 If the file is not present in the list, it is added to the front. If it is
17198 present, it is moved there. With optional argument TO-END, add/move to the
17199 end of the list."
17200 (interactive "P")
17201 (let ((org-agenda-skip-unavailable-files nil)
17202 (file-alist (mapcar (lambda (x)
17203 (cons (file-truename x) x))
17204 (org-agenda-files t)))
17205 (ctf (file-truename
17206 (or buffer-file-name
17207 (error "Please save the current buffer to a file"))))
17208 x had)
17209 (setq x (assoc ctf file-alist) had x)
17211 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17212 (if to-end
17213 (setq file-alist (append (delq x file-alist) (list x)))
17214 (setq file-alist (cons x (delq x file-alist))))
17215 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17216 (org-install-agenda-files-menu)
17217 (message "File %s to %s of agenda file list"
17218 (if had "moved" "added") (if to-end "end" "front"))))
17220 (defun org-remove-file (&optional file)
17221 "Remove current file from the list of files in variable `org-agenda-files'.
17222 These are the files which are being checked for agenda entries.
17223 Optional argument FILE means use this file instead of the current."
17224 (interactive)
17225 (let* ((org-agenda-skip-unavailable-files nil)
17226 (file (or file buffer-file-name
17227 (error "Current buffer does not visit a file")))
17228 (true-file (file-truename file))
17229 (afile (abbreviate-file-name file))
17230 (files (delq nil (mapcar
17231 (lambda (x)
17232 (if (equal true-file
17233 (file-truename x))
17234 nil x))
17235 (org-agenda-files t)))))
17236 (if (not (= (length files) (length (org-agenda-files t))))
17237 (progn
17238 (org-store-new-agenda-file-list files)
17239 (org-install-agenda-files-menu)
17240 (message "Removed file: %s" afile))
17241 (message "File was not in list: %s (not removed)" afile))))
17243 (defun org-file-menu-entry (file)
17244 (vector file (list 'find-file file) t))
17246 (defun org-check-agenda-file (file)
17247 "Make sure FILE exists. If not, ask user what to do."
17248 (when (not (file-exists-p file))
17249 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17250 (abbreviate-file-name file))
17251 (let ((r (downcase (read-char-exclusive))))
17252 (cond
17253 ((equal r ?r)
17254 (org-remove-file file)
17255 (throw 'nextfile t))
17256 (t (error "Abort"))))))
17258 (defun org-get-agenda-file-buffer (file)
17259 "Get a buffer visiting FILE. If the buffer needs to be created, add
17260 it to the list of buffers which might be released later."
17261 (let ((buf (org-find-base-buffer-visiting file)))
17262 (if buf
17263 buf ; just return it
17264 ;; Make a new buffer and remember it
17265 (setq buf (find-file-noselect file))
17266 (if buf (push buf org-agenda-new-buffers))
17267 buf)))
17269 (defun org-release-buffers (blist)
17270 "Release all buffers in list, asking the user for confirmation when needed.
17271 When a buffer is unmodified, it is just killed. When modified, it is saved
17272 \(if the user agrees) and then killed."
17273 (let (buf file)
17274 (while (setq buf (pop blist))
17275 (setq file (buffer-file-name buf))
17276 (when (and (buffer-modified-p buf)
17277 file
17278 (y-or-n-p (format "Save file %s? " file)))
17279 (with-current-buffer buf (save-buffer)))
17280 (kill-buffer buf))))
17282 (defun org-agenda-prepare-buffers (files)
17283 "Create buffers for all agenda files, protect archived trees and comments."
17284 (interactive)
17285 (let ((pa '(:org-archived t))
17286 (pc '(:org-comment t))
17287 (pall '(:org-archived t :org-comment t))
17288 (inhibit-read-only t)
17289 (rea (concat ":" org-archive-tag ":"))
17290 bmp file re)
17291 (save-excursion
17292 (save-restriction
17293 (while (setq file (pop files))
17294 (catch 'nextfile
17295 (if (bufferp file)
17296 (set-buffer file)
17297 (org-check-agenda-file file)
17298 (set-buffer (org-get-agenda-file-buffer file)))
17299 (widen)
17300 (setq bmp (buffer-modified-p))
17301 (org-refresh-category-properties)
17302 (setq org-todo-keywords-for-agenda
17303 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17304 (setq org-done-keywords-for-agenda
17305 (append org-done-keywords-for-agenda org-done-keywords))
17306 (setq org-todo-keyword-alist-for-agenda
17307 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17308 (setq org-drawers-for-agenda
17309 (append org-drawers-for-agenda org-drawers))
17310 (setq org-tag-alist-for-agenda
17311 (append org-tag-alist-for-agenda org-tag-alist))
17313 (save-excursion
17314 (remove-text-properties (point-min) (point-max) pall)
17315 (when org-agenda-skip-archived-trees
17316 (goto-char (point-min))
17317 (while (re-search-forward rea nil t)
17318 (if (org-at-heading-p t)
17319 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17320 (goto-char (point-min))
17321 (setq re (format org-heading-keyword-regexp-format
17322 org-comment-string))
17323 (while (re-search-forward re nil t)
17324 (add-text-properties
17325 (match-beginning 0) (org-end-of-subtree t) pc)))
17326 (set-buffer-modified-p bmp)))))
17327 (setq org-todo-keywords-for-agenda
17328 (org-uniquify org-todo-keywords-for-agenda))
17329 (setq org-todo-keyword-alist-for-agenda
17330 (org-uniquify org-todo-keyword-alist-for-agenda)
17331 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17333 ;;;; Embedded LaTeX
17335 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17336 "Keymap for the minor `org-cdlatex-mode'.")
17338 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17339 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17340 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17341 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17342 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17344 (defvar org-cdlatex-texmathp-advice-is-done nil
17345 "Flag remembering if we have applied the advice to texmathp already.")
17347 (define-minor-mode org-cdlatex-mode
17348 "Toggle the minor `org-cdlatex-mode'.
17349 This mode supports entering LaTeX environment and math in LaTeX fragments
17350 in Org-mode.
17351 \\{org-cdlatex-mode-map}"
17352 nil " OCDL" nil
17353 (when org-cdlatex-mode
17354 (require 'cdlatex)
17355 (run-hooks 'cdlatex-mode-hook)
17356 (cdlatex-compute-tables))
17357 (unless org-cdlatex-texmathp-advice-is-done
17358 (setq org-cdlatex-texmathp-advice-is-done t)
17359 (defadvice texmathp (around org-math-always-on activate)
17360 "Always return t in org-mode buffers.
17361 This is because we want to insert math symbols without dollars even outside
17362 the LaTeX math segments. If Orgmode thinks that point is actually inside
17363 an embedded LaTeX fragment, let texmathp do its job.
17364 \\[org-cdlatex-mode-map]"
17365 (interactive)
17366 (let (p)
17367 (cond
17368 ((not (derived-mode-p 'org-mode)) ad-do-it)
17369 ((eq this-command 'cdlatex-math-symbol)
17370 (setq ad-return-value t
17371 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17373 (let ((p (org-inside-LaTeX-fragment-p)))
17374 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17375 (setq ad-return-value t
17376 texmathp-why '("Org-mode embedded math" . 0))
17377 (if p ad-do-it)))))))))
17379 (defun turn-on-org-cdlatex ()
17380 "Unconditionally turn on `org-cdlatex-mode'."
17381 (org-cdlatex-mode 1))
17383 (defun org-inside-LaTeX-fragment-p ()
17384 "Test if point is inside a LaTeX fragment.
17385 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17386 sequence appearing also before point.
17387 Even though the matchers for math are configurable, this function assumes
17388 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17389 delimiters are skipped when they have been removed by customization.
17390 The return value is nil, or a cons cell with the delimiter and the
17391 position of this delimiter.
17393 This function does a reasonably good job, but can locally be fooled by
17394 for example currency specifications. For example it will assume being in
17395 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17396 fragments that are properly closed, but during editing, we have to live
17397 with the uncertainty caused by missing closing delimiters. This function
17398 looks only before point, not after."
17399 (catch 'exit
17400 (let ((pos (point))
17401 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17402 (lim (progn
17403 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17404 (point)))
17405 dd-on str (start 0) m re)
17406 (goto-char pos)
17407 (when dodollar
17408 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17409 re (nth 1 (assoc "$" org-latex-regexps)))
17410 (while (string-match re str start)
17411 (cond
17412 ((= (match-end 0) (length str))
17413 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17414 ((= (match-end 0) (- (length str) 5))
17415 (throw 'exit nil))
17416 (t (setq start (match-end 0))))))
17417 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17418 (goto-char pos)
17419 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17420 (and (match-beginning 2) (throw 'exit nil))
17421 ;; count $$
17422 (while (re-search-backward "\\$\\$" lim t)
17423 (setq dd-on (not dd-on)))
17424 (goto-char pos)
17425 (if dd-on (cons "$$" m))))))
17427 (defun org-inside-latex-macro-p ()
17428 "Is point inside a LaTeX macro or its arguments?"
17429 (save-match-data
17430 (org-in-regexp
17431 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17433 (defun org-try-cdlatex-tab ()
17434 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17435 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17436 - inside a LaTeX fragment, or
17437 - after the first word in a line, where an abbreviation expansion could
17438 insert a LaTeX environment."
17439 (when org-cdlatex-mode
17440 (cond
17441 ;; Before any word on the line: No expansion possible.
17442 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17443 ;; Just after first word on the line: Expand it. Make sure it
17444 ;; cannot happen on headlines, though.
17445 ((save-excursion
17446 (skip-chars-backward "a-zA-Z0-9*")
17447 (skip-chars-backward " \t")
17448 (and (bolp) (not (org-at-heading-p))))
17449 (cdlatex-tab) t)
17450 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17452 (defun org-cdlatex-underscore-caret (&optional arg)
17453 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17454 Revert to the normal definition outside of these fragments."
17455 (interactive "P")
17456 (if (org-inside-LaTeX-fragment-p)
17457 (call-interactively 'cdlatex-sub-superscript)
17458 (let (org-cdlatex-mode)
17459 (call-interactively (key-binding (vector last-input-event))))))
17461 (defun org-cdlatex-math-modify (&optional arg)
17462 "Execute `cdlatex-math-modify' in LaTeX fragments.
17463 Revert to the normal definition outside of these fragments."
17464 (interactive "P")
17465 (if (org-inside-LaTeX-fragment-p)
17466 (call-interactively 'cdlatex-math-modify)
17467 (let (org-cdlatex-mode)
17468 (call-interactively (key-binding (vector last-input-event))))))
17470 (defvar org-latex-fragment-image-overlays nil
17471 "List of overlays carrying the images of latex fragments.")
17472 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17474 (defun org-remove-latex-fragment-image-overlays ()
17475 "Remove all overlays with LaTeX fragment images in current buffer."
17476 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17477 (setq org-latex-fragment-image-overlays nil))
17479 (defun org-preview-latex-fragment (&optional subtree)
17480 "Preview the LaTeX fragment at point, or all locally or globally.
17481 If the cursor is in a LaTeX fragment, create the image and overlay
17482 it over the source code. If there is no fragment at point, display
17483 all fragments in the current text, from one headline to the next. With
17484 prefix SUBTREE, display all fragments in the current subtree. With a
17485 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17486 the cursor is before the first headline,
17487 display all fragments in the buffer.
17488 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17489 (interactive "P")
17490 (unless buffer-file-name
17491 (error "Can't preview LaTeX fragment in a non-file buffer"))
17492 (org-remove-latex-fragment-image-overlays)
17493 (save-excursion
17494 (save-restriction
17495 (let (beg end at msg)
17496 (cond
17497 ((or (equal subtree '(16))
17498 (not (save-excursion
17499 (re-search-backward org-outline-regexp-bol nil t))))
17500 (setq beg (point-min) end (point-max)
17501 msg "Creating images for buffer...%s"))
17502 ((equal subtree '(4))
17503 (org-back-to-heading)
17504 (setq beg (point) end (org-end-of-subtree t)
17505 msg "Creating images for subtree...%s"))
17507 (if (setq at (org-inside-LaTeX-fragment-p))
17508 (goto-char (max (point-min) (- (cdr at) 2)))
17509 (org-back-to-heading))
17510 (setq beg (point) end (progn (outline-next-heading) (point))
17511 msg (if at "Creating image...%s"
17512 "Creating images for entry...%s"))))
17513 (message msg "")
17514 (narrow-to-region beg end)
17515 (goto-char beg)
17516 (org-format-latex
17517 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17518 (file-name-nondirectory
17519 buffer-file-name)))
17520 default-directory 'overlays msg at 'forbuffer
17521 org-latex-create-formula-image-program)
17522 (message msg "done. Use `C-c C-c' to remove images.")))))
17524 (defvar org-latex-regexps
17525 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17526 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17527 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17528 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17529 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17530 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17531 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17532 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17533 "Regular expressions for matching embedded LaTeX.")
17535 (defvar org-export-have-math nil) ;; dynamic scoping
17536 (defun org-format-latex (prefix &optional dir overlays msg at
17537 forbuffer processing-type)
17538 "Replace LaTeX fragments with links to an image, and produce images.
17539 Some of the options can be changed using the variable
17540 `org-format-latex-options'."
17541 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17542 (let* ((prefixnodir (file-name-nondirectory prefix))
17543 (absprefix (expand-file-name prefix dir))
17544 (todir (file-name-directory absprefix))
17545 (opt org-format-latex-options)
17546 (optnew org-format-latex-options)
17547 (matchers (plist-get opt :matchers))
17548 (re-list org-latex-regexps)
17549 (org-format-latex-header-extra
17550 (plist-get (org-infile-export-plist) :latex-header-extra))
17551 (cnt 0) txt hash link beg end re e checkdir
17552 string
17553 m n block-type block linkfile movefile ov)
17554 ;; Check the different regular expressions
17555 (while (setq e (pop re-list))
17556 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17557 block (if block-type "\n\n" ""))
17558 (when (member m matchers)
17559 (goto-char (point-min))
17560 (while (re-search-forward re nil t)
17561 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17562 (not (get-text-property (match-beginning n)
17563 'org-protected))
17564 (or (not overlays)
17565 (not (eq (get-char-property (match-beginning n)
17566 'org-overlay-type)
17567 'org-latex-overlay))))
17568 (setq org-export-have-math t)
17569 (cond
17570 ((eq processing-type 'verbatim)
17571 ;; Leave the text verbatim, just protect it
17572 (add-text-properties (match-beginning n) (match-end n)
17573 '(org-protected t)))
17574 ((eq processing-type 'mathjax)
17575 ;; Prepare for MathJax processing
17576 (setq string (match-string n))
17577 (if (member m '("$" "$1"))
17578 (save-excursion
17579 (delete-region (match-beginning n) (match-end n))
17580 (goto-char (match-beginning n))
17581 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17582 "\\)")
17583 '(org-protected t))))
17584 (add-text-properties (match-beginning n) (match-end n)
17585 '(org-protected t))))
17586 ((or (eq processing-type 'dvipng)
17587 (eq processing-type 'imagemagick))
17588 ;; Process to an image
17589 (setq txt (match-string n)
17590 beg (match-beginning n) end (match-end n)
17591 cnt (1+ cnt))
17592 (let ((face (face-at-point))
17593 (fg (plist-get opt :foreground))
17594 (bg (plist-get opt :background))
17595 print-length print-level) ; make sure full list is printed
17596 (when forbuffer
17597 ; Get the colors from the face at point
17598 (goto-char beg)
17599 (when (eq fg 'auto)
17600 (setq fg (face-attribute face :foreground nil 'default)))
17601 (when (eq bg 'auto)
17602 (setq bg (face-attribute face :background nil 'default)))
17603 (setq optnew (copy-sequence opt))
17604 (plist-put optnew :foreground fg)
17605 (plist-put optnew :background bg))
17606 (setq hash (sha1 (prin1-to-string
17607 (list org-format-latex-header
17608 org-format-latex-header-extra
17609 org-export-latex-default-packages-alist
17610 org-export-latex-packages-alist
17611 org-format-latex-options
17612 forbuffer txt fg bg)))
17613 linkfile (format "%s_%s.png" prefix hash)
17614 movefile (format "%s_%s.png" absprefix hash)))
17615 (setq link (concat block "[[file:" linkfile "]]" block))
17616 (if msg (message msg cnt))
17617 (goto-char beg)
17618 (unless checkdir ; make sure the directory exists
17619 (setq checkdir t)
17620 (or (file-directory-p todir) (make-directory todir t)))
17621 (org-create-formula-image
17622 txt movefile optnew forbuffer processing-type)
17623 (if overlays
17624 (progn
17625 (mapc (lambda (o)
17626 (if (eq (overlay-get o 'org-overlay-type)
17627 'org-latex-overlay)
17628 (delete-overlay o)))
17629 (overlays-in beg end))
17630 (setq ov (make-overlay beg end))
17631 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17632 (if (featurep 'xemacs)
17633 (progn
17634 (overlay-put ov 'invisible t)
17635 (overlay-put
17636 ov 'end-glyph
17637 (make-glyph (vector 'png :file movefile))))
17638 (overlay-put
17639 ov 'display
17640 (list 'image :type 'png :file movefile :ascent 'center)))
17641 (push ov org-latex-fragment-image-overlays)
17642 (goto-char end))
17643 (delete-region beg end)
17644 (insert (org-add-props link
17645 (list 'org-latex-src
17646 (replace-regexp-in-string
17647 "\"" "" txt)
17648 'org-latex-src-embed-type
17649 (if block-type 'paragraph 'character))))))
17650 ((eq processing-type 'mathml)
17651 ;; Process to MathML
17652 (unless (save-match-data (org-format-latex-mathml-available-p))
17653 (error "LaTeX to MathML converter not configured"))
17654 (setq txt (match-string n)
17655 beg (match-beginning n) end (match-end n)
17656 cnt (1+ cnt))
17657 (if msg (message msg cnt))
17658 (goto-char beg)
17659 (delete-region beg end)
17660 (insert (org-format-latex-as-mathml
17661 txt block-type prefix dir)))
17663 (error "Unknown conversion type %s for latex fragments"
17664 processing-type)))))))))
17666 (defun org-create-math-formula (latex-frag &optional mathml-file)
17667 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17668 Use `org-latex-to-mathml-convert-command'. If the conversion is
17669 sucessful, return the portion between \"<math...> </math>\"
17670 elements otherwise return nil. When MATHML-FILE is specified,
17671 write the results in to that file. When invoked as an
17672 interactive command, prompt for LATEX-FRAG, with initial value
17673 set to the current active region and echo the results for user
17674 inspection."
17675 (interactive (list (let ((frag (when (org-region-active-p)
17676 (buffer-substring-no-properties
17677 (region-beginning) (region-end)))))
17678 (read-string "LaTeX Fragment: " frag nil frag))))
17679 (unless latex-frag (error "Invalid latex-frag"))
17680 (let* ((tmp-in-file (file-relative-name
17681 (make-temp-name (expand-file-name "ltxmathml-in"))))
17682 (ignore (write-region latex-frag nil tmp-in-file))
17683 (tmp-out-file (file-relative-name
17684 (make-temp-name (expand-file-name "ltxmathml-out"))))
17685 (cmd (format-spec
17686 org-latex-to-mathml-convert-command
17687 `((?j . ,(shell-quote-argument
17688 (expand-file-name org-latex-to-mathml-jar-file)))
17689 (?I . ,(shell-quote-argument tmp-in-file))
17690 (?o . ,(shell-quote-argument tmp-out-file)))))
17691 mathml shell-command-output)
17692 (when (org-called-interactively-p 'any)
17693 (unless (org-format-latex-mathml-available-p)
17694 (error "LaTeX to MathML converter not configured")))
17695 (message "Running %s" cmd)
17696 (setq shell-command-output (shell-command-to-string cmd))
17697 (setq mathml
17698 (when (file-readable-p tmp-out-file)
17699 (with-current-buffer (find-file-noselect tmp-out-file t)
17700 (goto-char (point-min))
17701 (when (re-search-forward
17702 (concat
17703 (regexp-quote
17704 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17705 "\\(.\\|\n\\)*"
17706 (regexp-quote "</math>")) nil t)
17707 (prog1 (match-string 0) (kill-buffer))))))
17708 (cond
17709 (mathml
17710 (setq mathml
17711 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17712 (when mathml-file
17713 (write-region mathml nil mathml-file))
17714 (when (org-called-interactively-p 'any)
17715 (message mathml)))
17716 ((message "LaTeX to MathML conversion failed")
17717 (message shell-command-output)))
17718 (delete-file tmp-in-file)
17719 (when (file-exists-p tmp-out-file)
17720 (delete-file tmp-out-file))
17721 mathml))
17723 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17724 prefix &optional dir)
17725 "Use `org-create-math-formula' but check local cache first."
17726 (let* ((absprefix (expand-file-name prefix dir))
17727 (print-length nil) (print-level nil)
17728 (formula-id (concat
17729 "formula-"
17730 (sha1
17731 (prin1-to-string
17732 (list latex-frag
17733 org-latex-to-mathml-convert-command)))))
17734 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17735 (formula-cache-dir (file-name-directory formula-cache)))
17737 (unless (file-directory-p formula-cache-dir)
17738 (make-directory formula-cache-dir t))
17740 (unless (file-exists-p formula-cache)
17741 (org-create-math-formula latex-frag formula-cache))
17743 (if (file-exists-p formula-cache)
17744 ;; Successful conversion. Return the link to MathML file.
17745 (org-add-props
17746 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17747 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17748 'org-latex-src-embed-type (if latex-frag-type
17749 'paragraph 'character)))
17750 ;; Failed conversion. Return the LaTeX fragment verbatim
17751 (add-text-properties
17752 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17753 latex-frag)))
17755 (defun org-create-formula-image (string tofile options buffer &optional type)
17756 "Create an image from LaTeX source using dvipng or convert.
17757 This function calls either `org-create-formula-image-with-dvipng'
17758 or `org-create-formula-image-with-imagemagick' depending on the
17759 value of `org-latex-create-formula-image-program' or on the value
17760 of the optional TYPE variable.
17762 Note: ultimately these two function should be combined as they
17763 share a good deal of logic."
17764 (org-check-external-command
17765 "latex" "needed to convert LaTeX fragments to images")
17766 (funcall
17767 (case (or type org-latex-create-formula-image-program)
17768 ('dvipng
17769 (org-check-external-command
17770 "dvipng" "needed to convert LaTeX fragments to images")
17771 #'org-create-formula-image-with-dvipng)
17772 ('imagemagick
17773 (org-check-external-command
17774 "convert" "you need to install imagemagick")
17775 #'org-create-formula-image-with-imagemagick)
17776 (t (error
17777 "invalid value of `org-latex-create-formula-image-program'")))
17778 string tofile options buffer))
17780 ;; This function borrows from Ganesh Swami's latex2png.el
17781 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17782 "This calls dvipng."
17783 (require 'org-latex)
17784 (let* ((tmpdir (if (featurep 'xemacs)
17785 (temp-directory)
17786 temporary-file-directory))
17787 (texfilebase (make-temp-name
17788 (expand-file-name "orgtex" tmpdir)))
17789 (texfile (concat texfilebase ".tex"))
17790 (dvifile (concat texfilebase ".dvi"))
17791 (pngfile (concat texfilebase ".png"))
17792 (fnh (if (featurep 'xemacs)
17793 (font-height (face-font 'default))
17794 (face-attribute 'default :height nil)))
17795 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17796 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17797 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17798 "Black"))
17799 (bg (or (plist-get options (if buffer :background :html-background))
17800 "Transparent")))
17801 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17802 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17803 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17804 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17805 (with-temp-file texfile
17806 (insert (org-splice-latex-header
17807 org-format-latex-header
17808 org-export-latex-default-packages-alist
17809 org-export-latex-packages-alist t
17810 org-format-latex-header-extra))
17811 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17812 (require 'org-latex)
17813 (org-export-latex-fix-inputenc))
17814 (let ((dir default-directory))
17815 (condition-case nil
17816 (progn
17817 (cd tmpdir)
17818 (call-process "latex" nil nil nil texfile))
17819 (error nil))
17820 (cd dir))
17821 (if (not (file-exists-p dvifile))
17822 (progn (message "Failed to create dvi file from %s" texfile) nil)
17823 (condition-case nil
17824 (if (featurep 'xemacs)
17825 (call-process "dvipng" nil nil nil
17826 "-fg" fg "-bg" bg
17827 "-T" "tight"
17828 "-o" pngfile
17829 dvifile)
17830 (call-process "dvipng" nil nil nil
17831 "-fg" fg "-bg" bg
17832 "-D" dpi
17833 ;;"-x" scale "-y" scale
17834 "-T" "tight"
17835 "-o" pngfile
17836 dvifile))
17837 (error nil))
17838 (if (not (file-exists-p pngfile))
17839 (if org-format-latex-signal-error
17840 (error "Failed to create png file from %s" texfile)
17841 (message "Failed to create png file from %s" texfile)
17842 nil)
17843 ;; Use the requested file name and clean up
17844 (copy-file pngfile tofile 'replace)
17845 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17846 (if (file-exists-p (concat texfilebase e))
17847 (delete-file (concat texfilebase e))))
17848 pngfile))))
17850 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17851 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17852 "This calls convert, which is included into imagemagick."
17853 (require 'org-latex)
17854 (let* ((tmpdir (if (featurep 'xemacs)
17855 (temp-directory)
17856 temporary-file-directory))
17857 (texfilebase (make-temp-name
17858 (expand-file-name "orgtex" tmpdir)))
17859 (texfile (concat texfilebase ".tex"))
17860 (pdffile (concat texfilebase ".pdf"))
17861 (pngfile (concat texfilebase ".png"))
17862 (fnh (if (featurep 'xemacs)
17863 (font-height (face-font 'default))
17864 (face-attribute 'default :height nil)))
17865 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17866 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17867 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17868 "black"))
17869 (bg (or (plist-get options (if buffer :background :html-background))
17870 "white")))
17871 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17872 (setq fg (org-latex-color-format fg)))
17873 (if (eq bg 'default) (setq bg (org-latex-color :background))
17874 (setq bg (org-latex-color-format
17875 (if (string= bg "Transparent") "white" bg))))
17876 (with-temp-file texfile
17877 (insert (org-splice-latex-header
17878 org-format-latex-header
17879 org-export-latex-default-packages-alist
17880 org-export-latex-packages-alist t
17881 org-format-latex-header-extra))
17882 (insert "\n\\begin{document}\n"
17883 "\\definecolor{fg}{rgb}{" fg "}\n"
17884 "\\definecolor{bg}{rgb}{" bg "}\n"
17885 "\n\\pagecolor{bg}\n"
17886 "\n{\\color{fg}\n"
17887 string
17888 "\n}\n"
17889 "\n\\end{document}\n" )
17890 (require 'org-latex)
17891 (org-export-latex-fix-inputenc))
17892 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17893 (condition-case nil
17894 (progn
17895 (cd tmpdir)
17896 (setq cmds org-latex-to-pdf-process)
17897 (while cmds
17898 (setq latex-frags-cmds (pop cmds))
17899 (if (listp latex-frags-cmds)
17900 (setq cmds nil)
17901 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17902 (while latex-frags-cmds
17903 (setq cmd (pop latex-frags-cmds))
17904 (while (string-match "%b" cmd)
17905 (setq cmd (replace-match
17906 (save-match-data
17907 (shell-quote-argument texfile))
17908 t t cmd)))
17909 (while (string-match "%f" cmd)
17910 (setq cmd (replace-match
17911 (save-match-data
17912 (shell-quote-argument (file-name-nondirectory texfile)))
17913 t t cmd)))
17914 (while (string-match "%o" cmd)
17915 (setq cmd (replace-match
17916 (save-match-data
17917 (shell-quote-argument (file-name-directory texfile)))
17918 t t cmd)))
17919 (setq cmd (split-string cmd))
17920 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17921 (error nil))
17922 (cd dir))
17923 (if (not (file-exists-p pdffile))
17924 (progn (message "Failed to create pdf file from %s" texfile) nil)
17925 (condition-case nil
17926 (if (featurep 'xemacs)
17927 (call-process "convert" nil nil nil
17928 "-density" "96"
17929 "-trim"
17930 "-antialias"
17931 pdffile
17932 "-quality" "100"
17933 ;; "-sharpen" "0x1.0"
17934 pngfile)
17935 (call-process "convert" nil nil nil
17936 "-density" dpi
17937 "-trim"
17938 "-antialias"
17939 pdffile
17940 "-quality" "100"
17941 ; "-sharpen" "0x1.0"
17942 pngfile))
17943 (error nil))
17944 (if (not (file-exists-p pngfile))
17945 (if org-format-latex-signal-error
17946 (error "Failed to create png file from %s" texfile)
17947 (message "Failed to create png file from %s" texfile)
17948 nil)
17949 ;; Use the requested file name and clean up
17950 (copy-file pngfile tofile 'replace)
17951 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17952 (if (file-exists-p (concat texfilebase e))
17953 (delete-file (concat texfilebase e))))
17954 pngfile))))
17956 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17957 "Fill a LaTeX header template TPL.
17958 In the template, the following place holders will be recognized:
17960 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17961 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17962 [PACKAGES] \\usepackage statements for PKG
17963 [NO-PACKAGES] do not include PKG
17964 [EXTRA] the string EXTRA
17965 [NO-EXTRA] do not include EXTRA
17967 For backward compatibility, if both the positive and the negative place
17968 holder is missing, the positive one (without the \"NO-\") will be
17969 assumed to be present at the end of the template.
17970 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17971 EXTRA is a string.
17972 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17973 (let (rpl (end ""))
17974 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17975 (setq rpl (if (or (match-end 1) (not def-pkg))
17976 "" (org-latex-packages-to-string def-pkg snippets-p t))
17977 tpl (replace-match rpl t t tpl))
17978 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17980 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17981 (setq rpl (if (or (match-end 1) (not pkg))
17982 "" (org-latex-packages-to-string pkg snippets-p t))
17983 tpl (replace-match rpl t t tpl))
17984 (if pkg (setq end
17985 (concat end "\n"
17986 (org-latex-packages-to-string pkg snippets-p)))))
17988 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17989 (setq rpl (if (or (match-end 1) (not extra))
17990 "" (concat extra "\n"))
17991 tpl (replace-match rpl t t tpl))
17992 (if (and extra (string-match "\\S-" extra))
17993 (setq end (concat end "\n" extra))))
17995 (if (string-match "\\S-" end)
17996 (concat tpl "\n" end)
17997 tpl)))
17999 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18000 "Turn an alist of packages into a string with the \\usepackage macros."
18001 (setq pkg (mapconcat (lambda(p)
18002 (cond
18003 ((stringp p) p)
18004 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18005 (format "%% Package %s omitted" (cadr p)))
18006 ((equal "" (car p))
18007 (format "\\usepackage{%s}" (cadr p)))
18009 (format "\\usepackage[%s]{%s}"
18010 (car p) (cadr p)))))
18012 "\n"))
18013 (if newline (concat pkg "\n") pkg))
18015 (defun org-dvipng-color (attr)
18016 "Return a RGB color specification for dvipng."
18017 (apply 'format "rgb %s %s %s"
18018 (mapcar 'org-normalize-color
18019 (if (featurep 'xemacs)
18020 (color-rgb-components
18021 (face-property 'default
18022 (cond ((eq attr :foreground) 'foreground)
18023 ((eq attr :background) 'background))))
18024 (color-values (face-attribute 'default attr nil))))))
18026 (defun org-dvipng-color-format (color-name)
18027 "Convert COLOR-NAME to a RGB color value for dvipng."
18028 (apply 'format "rgb %s %s %s"
18029 (mapcar 'org-normalize-color
18030 (color-values color-name))))
18032 (defun org-latex-color (attr)
18033 "Return a RGB color for the LaTeX color package."
18034 (apply 'format "%s,%s,%s"
18035 (mapcar 'org-normalize-color
18036 (if (featurep 'xemacs)
18037 (color-rgb-components
18038 (face-property 'default
18039 (cond ((eq attr :foreground) 'foreground)
18040 ((eq attr :background) 'background))))
18041 (color-values (face-attribute 'default attr nil))))))
18043 (defun org-latex-color-format (color-name)
18044 "Convert COLOR-NAME to a RGB color value."
18045 (apply 'format "%s,%s,%s"
18046 (mapcar 'org-normalize-color
18047 (color-values color-name))))
18049 (defun org-normalize-color (value)
18050 "Return string to be used as color value for an RGB component."
18051 (format "%g" (/ value 65535.0)))
18053 ;; Image display
18056 (defvar org-inline-image-overlays nil)
18057 (make-variable-buffer-local 'org-inline-image-overlays)
18059 (defun org-toggle-inline-images (&optional include-linked)
18060 "Toggle the display of inline images.
18061 INCLUDE-LINKED is passed to `org-display-inline-images'."
18062 (interactive "P")
18063 (if org-inline-image-overlays
18064 (progn
18065 (org-remove-inline-images)
18066 (message "Inline image display turned off"))
18067 (org-display-inline-images include-linked)
18068 (if (and (org-called-interactively-p)
18069 org-inline-image-overlays)
18070 (message "%d images displayed inline"
18071 (length org-inline-image-overlays))
18072 (message "No images to display inline"))))
18074 (defun org-redisplay-inline-images ()
18075 "Refresh the display of inline images."
18076 (interactive)
18077 (if (not org-inline-image-overlays)
18078 (org-toggle-inline-images)
18079 (org-toggle-inline-images)
18080 (org-toggle-inline-images)))
18082 (defun org-display-inline-images (&optional include-linked refresh beg end)
18083 "Display inline images.
18084 Normally only links without a description part are inlined, because this
18085 is how it will work for export. When INCLUDE-LINKED is set, also links
18086 with a description part will be inlined. This can be nice for a quick
18087 look at those images, but it does not reflect what exported files will look
18088 like.
18089 When REFRESH is set, refresh existing images between BEG and END.
18090 This will create new image displays only if necessary.
18091 BEG and END default to the buffer boundaries."
18092 (interactive "P")
18093 (unless refresh
18094 (org-remove-inline-images)
18095 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18096 (save-excursion
18097 (save-restriction
18098 (widen)
18099 (setq beg (or beg (point-min)) end (or end (point-max)))
18100 (goto-char beg)
18101 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18102 (substring (org-image-file-name-regexp) 0 -2)
18103 "\\)\\]" (if include-linked "" "\\]")))
18104 old file ov img type attrwidth width)
18105 (while (re-search-forward re end t)
18106 (setq old (get-char-property-and-overlay (match-beginning 1)
18107 'org-image-overlay)
18108 file (expand-file-name
18109 (concat (or (match-string 3) "") (match-string 4))))
18110 (when (image-type-available-p 'imagemagick)
18111 (setq attrwidth (if (or (listp org-image-actual-width)
18112 (null org-image-actual-width))
18113 (save-excursion
18114 (save-match-data
18115 (when (re-search-backward
18116 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18117 (save-excursion
18118 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18119 (string-to-number (match-string 1))))))
18120 width (cond ((eq org-image-actual-width t) nil)
18121 ((null org-image-actual-width) attrwidth)
18122 ((numberp org-image-actual-width)
18123 org-image-actual-width)
18124 ((listp org-image-actual-width)
18125 (or attrwidth (car org-image-actual-width))))
18126 type (if width 'imagemagick)))
18127 (when (file-exists-p file)
18128 (if (and (car-safe old) refresh)
18129 (image-refresh (overlay-get (cdr old) 'display))
18130 (setq img (save-match-data (create-image file type nil :width width)))
18131 (when img
18132 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18133 (overlay-put ov 'display img)
18134 (overlay-put ov 'face 'default)
18135 (overlay-put ov 'org-image-overlay t)
18136 (overlay-put ov 'modification-hooks
18137 (list 'org-display-inline-remove-overlay))
18138 (push ov org-inline-image-overlays)))))))))
18140 (define-obsolete-function-alias
18141 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18143 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18144 "Remove inline-display overlay if a corresponding region is modified."
18145 (let ((inhibit-modification-hooks t))
18146 (when (and ov after)
18147 (delete ov org-inline-image-overlays)
18148 (delete-overlay ov))))
18150 (defun org-remove-inline-images ()
18151 "Remove inline display of images."
18152 (interactive)
18153 (mapc 'delete-overlay org-inline-image-overlays)
18154 (setq org-inline-image-overlays nil))
18156 ;;;; Key bindings
18158 ;; Outline functions from `outline-mode-prefix-map'
18159 ;; that can be remapped in Org:
18160 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18161 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18162 (define-key org-mode-map [remap outline-forward-same-level]
18163 'org-forward-heading-same-level)
18164 (define-key org-mode-map [remap outline-backward-same-level]
18165 'org-backward-heading-same-level)
18166 (define-key org-mode-map [remap show-branches]
18167 'org-kill-note-or-show-branches)
18168 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18169 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18170 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18172 ;; Outline functions from `outline-mode-prefix-map' that can not
18173 ;; be remapped in Org:
18175 ;; - the column "key binding" shows whether the Outline function is still
18176 ;; available in Org mode on the same key that it has been bound to in
18177 ;; Outline mode:
18178 ;; - "overridden": key used for a different functionality in Org mode
18179 ;; - else: key still bound to the same Outline function in Org mode
18181 ;; | Outline function | key binding | Org replacement |
18182 ;; |------------------------------------+-------------+-----------------------|
18183 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18184 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18185 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18186 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18187 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18188 ;; | `show-entry' | overridden | no replacement |
18189 ;; | `show-children' | `C-c C-i' | visibility cycling |
18190 ;; | `show-branches' | `C-c C-k' | still same function |
18191 ;; | `show-subtree' | overridden | visibility cycling |
18192 ;; | `show-all' | overridden | no replacement |
18193 ;; | `hide-subtree' | overridden | visibility cycling |
18194 ;; | `hide-body' | overridden | no replacement |
18195 ;; | `hide-entry' | overridden | visibility cycling |
18196 ;; | `hide-leaves' | overridden | no replacement |
18197 ;; | `hide-sublevels' | overridden | no replacement |
18198 ;; | `hide-other' | overridden | no replacement |
18200 ;; Make `C-c C-x' a prefix key
18201 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18203 ;; TAB key with modifiers
18204 (org-defkey org-mode-map "\C-i" 'org-cycle)
18205 (org-defkey org-mode-map [(tab)] 'org-cycle)
18206 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18207 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18208 ;; The following line is necessary under Suse GNU/Linux
18209 (unless (featurep 'xemacs)
18210 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18211 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18212 (define-key org-mode-map [backtab] 'org-shifttab)
18214 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18215 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18216 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18218 ;; Cursor keys with modifiers
18219 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18220 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18221 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18222 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18224 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18225 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18226 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18227 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18229 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18230 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18231 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18232 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18234 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18235 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18236 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18237 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18239 ;; Babel keys
18240 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18241 (mapc (lambda (pair)
18242 (define-key org-babel-map (car pair) (cdr pair)))
18243 org-babel-key-bindings)
18245 ;;; Extra keys for tty access.
18246 ;; We only set them when really needed because otherwise the
18247 ;; menus don't show the simple keys
18249 (when (or org-use-extra-keys
18250 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18251 (not window-system))
18252 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18253 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18254 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18255 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18256 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18257 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18258 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18259 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18260 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18261 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18262 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18263 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18264 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18265 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18266 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18267 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18268 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18269 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18270 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18271 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18272 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18273 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18274 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18275 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18276 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18277 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18278 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18279 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18281 ;; All the other keys
18283 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18284 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18285 (if (boundp 'narrow-map)
18286 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18287 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18288 (if (boundp 'narrow-map)
18289 (org-defkey narrow-map "b" 'org-narrow-to-block)
18290 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18291 (if (boundp 'narrow-map)
18292 (org-defkey narrow-map "e" 'org-narrow-to-element)
18293 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18294 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18295 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18296 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18297 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18298 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18299 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18300 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18301 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18302 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18303 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18304 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18305 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18306 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18307 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18308 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18309 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18310 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18311 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18312 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18313 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18314 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18315 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18316 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18317 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18318 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18319 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18320 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18321 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18322 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18323 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18324 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18325 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18326 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18327 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18328 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18329 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18330 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18331 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18332 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18333 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18334 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18335 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18336 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18337 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18338 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18339 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18340 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18341 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18342 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18343 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18344 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18345 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18346 (org-defkey org-mode-map "\C-c^" 'org-sort)
18347 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18348 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18349 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18350 (org-defkey org-mode-map "\C-m" 'org-return)
18351 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18352 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18353 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18354 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18355 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18356 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18357 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18358 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18359 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18360 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18361 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18362 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18363 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18364 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18365 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18366 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18367 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18368 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18369 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18370 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18371 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18372 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18373 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18375 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18376 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18377 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18379 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18380 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18381 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18382 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18383 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18384 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18385 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18386 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18387 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18388 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18389 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18390 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18391 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18392 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18393 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18394 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18395 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18396 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18397 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18398 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18399 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18400 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18402 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18403 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18404 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18405 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18406 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18408 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18410 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18412 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18413 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18415 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18418 (when (featurep 'xemacs)
18419 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18422 (defconst org-speed-commands-default
18424 ("Outline Navigation")
18425 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18426 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18427 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18428 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18429 ("u" . (org-speed-move-safe 'outline-up-heading))
18430 ("j" . org-goto)
18431 ("g" . (org-refile t))
18432 ("Outline Visibility")
18433 ("c" . org-cycle)
18434 ("C" . org-shifttab)
18435 (" " . org-display-outline-path)
18436 (":" . org-columns)
18437 ("Outline Structure Editing")
18438 ("U" . org-shiftmetaup)
18439 ("D" . org-shiftmetadown)
18440 ("r" . org-metaright)
18441 ("l" . org-metaleft)
18442 ("R" . org-shiftmetaright)
18443 ("L" . org-shiftmetaleft)
18444 ("i" . (progn (forward-char 1) (call-interactively
18445 'org-insert-heading-respect-content)))
18446 ("^" . org-sort)
18447 ("w" . org-refile)
18448 ("a" . org-archive-subtree-default-with-confirmation)
18449 ("." . org-mark-subtree)
18450 ("#" . org-toggle-comment)
18451 ("Clock Commands")
18452 ("I" . org-clock-in)
18453 ("O" . org-clock-out)
18454 ("Meta Data Editing")
18455 ("t" . org-todo)
18456 ("," . (org-priority))
18457 ("0" . (org-priority ?\ ))
18458 ("1" . (org-priority ?A))
18459 ("2" . (org-priority ?B))
18460 ("3" . (org-priority ?C))
18461 (";" . org-set-tags-command)
18462 ("e" . org-set-effort)
18463 ("E" . org-inc-effort)
18464 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18465 (org-entry-put (point) "APPT_WARNTIME" m)))
18466 ("Agenda Views etc")
18467 ("v" . org-agenda)
18468 ("/" . org-sparse-tree)
18469 ("Misc")
18470 ("o" . org-open-at-point)
18471 ("?" . org-speed-command-help)
18472 ("<" . (org-agenda-set-restriction-lock 'subtree))
18473 (">" . (org-agenda-remove-restriction-lock))
18475 "The default speed commands.")
18477 (defun org-print-speed-command (e)
18478 (if (> (length (car e)) 1)
18479 (progn
18480 (princ "\n")
18481 (princ (car e))
18482 (princ "\n")
18483 (princ (make-string (length (car e)) ?-))
18484 (princ "\n"))
18485 (princ (car e))
18486 (princ " ")
18487 (if (symbolp (cdr e))
18488 (princ (symbol-name (cdr e)))
18489 (prin1 (cdr e)))
18490 (princ "\n")))
18492 (defun org-speed-command-help ()
18493 "Show the available speed commands."
18494 (interactive)
18495 (if (not org-use-speed-commands)
18496 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18497 (with-output-to-temp-buffer "*Help*"
18498 (princ "User-defined Speed commands\n===========================\n")
18499 (mapc 'org-print-speed-command org-speed-commands-user)
18500 (princ "\n")
18501 (princ "Built-in Speed commands\n=======================\n")
18502 (mapc 'org-print-speed-command org-speed-commands-default))
18503 (with-current-buffer "*Help*"
18504 (setq truncate-lines t))))
18506 (defun org-speed-move-safe (cmd)
18507 "Execute CMD, but make sure that the cursor always ends up in a headline.
18508 If not, return to the original position and throw an error."
18509 (interactive)
18510 (let ((pos (point)))
18511 (call-interactively cmd)
18512 (unless (and (bolp) (org-at-heading-p))
18513 (goto-char pos)
18514 (error "Boundary reached while executing %s" cmd))))
18516 (defvar org-self-insert-command-undo-counter 0)
18518 (defvar org-table-auto-blank-field) ; defined in org-table.el
18519 (defvar org-speed-command nil)
18521 (define-obsolete-function-alias
18522 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18524 (defun org-speed-command-activate (keys)
18525 "Hook for activating single-letter speed commands.
18526 `org-speed-commands-default' specifies a minimal command set.
18527 Use `org-speed-commands-user' for further customization."
18528 (when (or (and (bolp) (looking-at org-outline-regexp))
18529 (and (functionp org-use-speed-commands)
18530 (funcall org-use-speed-commands)))
18531 (cdr (assoc keys (append org-speed-commands-user
18532 org-speed-commands-default)))))
18534 (define-obsolete-function-alias
18535 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18537 (defun org-babel-speed-command-activate (keys)
18538 "Hook for activating single-letter code block commands."
18539 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18540 (cdr (assoc keys org-babel-key-bindings))))
18542 (defcustom org-speed-command-hook
18543 '(org-speed-command-default-hook org-babel-speed-command-hook)
18544 "Hook for activating speed commands at strategic locations.
18545 Hook functions are called in sequence until a valid handler is
18546 found.
18548 Each hook takes a single argument, a user-pressed command key
18549 which is also a `self-insert-command' from the global map.
18551 Within the hook, examine the cursor position and the command key
18552 and return nil or a valid handler as appropriate. Handler could
18553 be one of an interactive command, a function, or a form.
18555 Set `org-use-speed-commands' to non-nil value to enable this
18556 hook. The default setting is `org-speed-command-activate'."
18557 :group 'org-structure
18558 :version "24.1"
18559 :type 'hook)
18561 (defun org-self-insert-command (N)
18562 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18563 If the cursor is in a table looking at whitespace, the whitespace is
18564 overwritten, and the table is not marked as requiring realignment."
18565 (interactive "p")
18566 (org-check-before-invisible-edit 'insert)
18567 (cond
18568 ((and org-use-speed-commands
18569 (setq org-speed-command
18570 (run-hook-with-args-until-success
18571 'org-speed-command-hook (this-command-keys))))
18572 (cond
18573 ((commandp org-speed-command)
18574 (setq this-command org-speed-command)
18575 (call-interactively org-speed-command))
18576 ((functionp org-speed-command)
18577 (funcall org-speed-command))
18578 ((and org-speed-command (listp org-speed-command))
18579 (eval org-speed-command))
18580 (t (let (org-use-speed-commands)
18581 (call-interactively 'org-self-insert-command)))))
18582 ((and
18583 (org-table-p)
18584 (progn
18585 ;; check if we blank the field, and if that triggers align
18586 (and (featurep 'org-table) org-table-auto-blank-field
18587 (member last-command
18588 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18589 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18590 ;; got extra space, this field does not determine column width
18591 (let (org-table-may-need-update) (org-table-blank-field))
18592 ;; no extra space, this field may determine column width
18593 (org-table-blank-field)))
18595 (eq N 1)
18596 (looking-at "[^|\n]* |"))
18597 (let (org-table-may-need-update)
18598 (goto-char (1- (match-end 0)))
18599 (backward-delete-char 1)
18600 (goto-char (match-beginning 0))
18601 (self-insert-command N)))
18603 (setq org-table-may-need-update t)
18604 (self-insert-command N)
18605 (org-fix-tags-on-the-fly)
18606 (if org-self-insert-cluster-for-undo
18607 (if (not (eq last-command 'org-self-insert-command))
18608 (setq org-self-insert-command-undo-counter 1)
18609 (if (>= org-self-insert-command-undo-counter 20)
18610 (setq org-self-insert-command-undo-counter 1)
18611 (and (> org-self-insert-command-undo-counter 0)
18612 buffer-undo-list (listp buffer-undo-list)
18613 (not (cadr buffer-undo-list)) ; remove nil entry
18614 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18615 (setq org-self-insert-command-undo-counter
18616 (1+ org-self-insert-command-undo-counter))))))))
18618 (defun org-check-before-invisible-edit (kind)
18619 "Check is editing if kind KIND would be dangerous with invisible text around.
18620 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18621 ;; First, try to get out of here as quickly as possible, to reduce overhead
18622 (if (and org-catch-invisible-edits
18623 (or (not (boundp 'visible-mode)) (not visible-mode))
18624 (or (get-char-property (point) 'invisible)
18625 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18626 ;; OK, we need to take a closer look
18627 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18628 (invisible-before-point (if (bobp) nil (get-char-property
18629 (1- (point)) 'invisible)))
18630 (border-and-ok-direction
18632 ;; Check if we are acting predictably before invisible text
18633 (and invisible-at-point (not invisible-before-point)
18634 (memq kind '(insert delete-backward)))
18635 ;; Check if we are acting predictably after invisible text
18636 ;; This works not well, and I have turned it off. It seems
18637 ;; better to always show and stop after invisible text.
18638 ;; (and (not invisible-at-point) invisible-before-point
18639 ;; (memq kind '(insert delete)))
18641 (when (or (memq invisible-at-point '(outline org-hide-block t))
18642 (memq invisible-before-point '(outline org-hide-block t)))
18643 (if (eq org-catch-invisible-edits 'error)
18644 (error "Editing in invisible areas is prohibited - make visible first"))
18645 (if (and org-custom-properties-overlays
18646 (y-or-n-p "Display invisible properties in this buffer? "))
18647 (org-toggle-custom-properties-visibility)
18648 ;; Make the area visible
18649 (save-excursion
18650 (if invisible-before-point
18651 (goto-char (previous-single-char-property-change
18652 (point) 'invisible)))
18653 (org-cycle))
18654 (cond
18655 ((eq org-catch-invisible-edits 'show)
18656 ;; That's it, we do the edit after showing
18657 (message
18658 "Unfolding invisible region around point before editing")
18659 (sit-for 1))
18660 ((and (eq org-catch-invisible-edits 'smart)
18661 border-and-ok-direction)
18662 (message "Unfolding invisible region around point before editing"))
18664 ;; Don't do the edit, make the user repeat it in full visibility
18665 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18667 (defun org-fix-tags-on-the-fly ()
18668 (when (and (equal (char-after (point-at-bol)) ?*)
18669 (org-at-heading-p))
18670 (org-align-tags-here org-tags-column)))
18672 (defun org-delete-backward-char (N)
18673 "Like `delete-backward-char', insert whitespace at field end in tables.
18674 When deleting backwards, in tables this function will insert whitespace in
18675 front of the next \"|\" separator, to keep the table aligned. The table will
18676 still be marked for re-alignment if the field did fill the entire column,
18677 because, in this case the deletion might narrow the column."
18678 (interactive "p")
18679 (org-check-before-invisible-edit 'delete-backward)
18680 (if (and (org-table-p)
18681 (eq N 1)
18682 (string-match "|" (buffer-substring (point-at-bol) (point)))
18683 (looking-at ".*?|"))
18684 (let ((pos (point))
18685 (noalign (looking-at "[^|\n\r]* |"))
18686 (c org-table-may-need-update))
18687 (backward-delete-char N)
18688 (if (not overwrite-mode)
18689 (progn
18690 (skip-chars-forward "^|")
18691 (insert " ")
18692 (goto-char (1- pos))))
18693 ;; noalign: if there were two spaces at the end, this field
18694 ;; does not determine the width of the column.
18695 (if noalign (setq org-table-may-need-update c)))
18696 (backward-delete-char N)
18697 (org-fix-tags-on-the-fly)))
18699 (defun org-delete-char (N)
18700 "Like `delete-char', but insert whitespace at field end in tables.
18701 When deleting characters, in tables this function will insert whitespace in
18702 front of the next \"|\" separator, to keep the table aligned. The table will
18703 still be marked for re-alignment if the field did fill the entire column,
18704 because, in this case the deletion might narrow the column."
18705 (interactive "p")
18706 (org-check-before-invisible-edit 'delete)
18707 (if (and (org-table-p)
18708 (not (bolp))
18709 (not (= (char-after) ?|))
18710 (eq N 1))
18711 (if (looking-at ".*?|")
18712 (let ((pos (point))
18713 (noalign (looking-at "[^|\n\r]* |"))
18714 (c org-table-may-need-update))
18715 (replace-match (concat
18716 (substring (match-string 0) 1 -1)
18717 " |"))
18718 (goto-char pos)
18719 ;; noalign: if there were two spaces at the end, this field
18720 ;; does not determine the width of the column.
18721 (if noalign (setq org-table-may-need-update c)))
18722 (delete-char N))
18723 (delete-char N)
18724 (org-fix-tags-on-the-fly)))
18726 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18727 (put 'org-self-insert-command 'delete-selection t)
18728 (put 'orgtbl-self-insert-command 'delete-selection t)
18729 (put 'org-delete-char 'delete-selection 'supersede)
18730 (put 'org-delete-backward-char 'delete-selection 'supersede)
18731 (put 'org-yank 'delete-selection 'yank)
18733 ;; Make `flyspell-mode' delay after some commands
18734 (put 'org-self-insert-command 'flyspell-delayed t)
18735 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18736 (put 'org-delete-char 'flyspell-delayed t)
18737 (put 'org-delete-backward-char 'flyspell-delayed t)
18739 ;; Make pabbrev-mode expand after org-mode commands
18740 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18741 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18743 ;; How to do this: Measure non-white length of current string
18744 ;; If equal to column width, we should realign.
18746 (defun org-remap (map &rest commands)
18747 "In MAP, remap the functions given in COMMANDS.
18748 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18749 (let (new old)
18750 (while commands
18751 (setq old (pop commands) new (pop commands))
18752 (if (fboundp 'command-remapping)
18753 (org-defkey map (vector 'remap old) new)
18754 (substitute-key-definition old new map global-map)))))
18756 (when (eq org-enable-table-editor 'optimized)
18757 ;; If the user wants maximum table support, we need to hijack
18758 ;; some standard editing functions
18759 (org-remap org-mode-map
18760 'self-insert-command 'org-self-insert-command
18761 'delete-char 'org-delete-char
18762 'delete-backward-char 'org-delete-backward-char)
18763 (org-defkey org-mode-map "|" 'org-force-self-insert))
18765 (defvar org-ctrl-c-ctrl-c-hook nil
18766 "Hook for functions attaching themselves to `C-c C-c'.
18768 This can be used to add additional functionality to the C-c C-c
18769 key which executes context-dependent commands. This hook is run
18770 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18771 run after the last test.
18773 Each function will be called with no arguments. The function
18774 must check if the context is appropriate for it to act. If yes,
18775 it should do its thing and then return a non-nil value. If the
18776 context is wrong, just do nothing and return nil.")
18778 (defvar org-ctrl-c-ctrl-c-final-hook nil
18779 "Hook for functions attaching themselves to `C-c C-c'.
18781 This can be used to add additional functionality to the C-c C-c
18782 key which executes context-dependent commands. This hook is run
18783 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18784 before the first test.
18786 Each function will be called with no arguments. The function
18787 must check if the context is appropriate for it to act. If yes,
18788 it should do its thing and then return a non-nil value. If the
18789 context is wrong, just do nothing and return nil.")
18791 (defvar org-tab-first-hook nil
18792 "Hook for functions to attach themselves to TAB.
18793 See `org-ctrl-c-ctrl-c-hook' for more information.
18794 This hook runs as the first action when TAB is pressed, even before
18795 `org-cycle' messes around with the `outline-regexp' to cater for
18796 inline tasks and plain list item folding.
18797 If any function in this hook returns t, any other actions that
18798 would have been caused by TAB (such as table field motion or visibility
18799 cycling) will not occur.")
18801 (defvar org-tab-after-check-for-table-hook nil
18802 "Hook for functions to attach themselves to TAB.
18803 See `org-ctrl-c-ctrl-c-hook' for more information.
18804 This hook runs after it has been established that the cursor is not in a
18805 table, but before checking if the cursor is in a headline or if global cycling
18806 should be done.
18807 If any function in this hook returns t, not other actions like visibility
18808 cycling will be done.")
18810 (defvar org-tab-after-check-for-cycling-hook nil
18811 "Hook for functions to attach themselves to TAB.
18812 See `org-ctrl-c-ctrl-c-hook' for more information.
18813 This hook runs after it has been established that not table field motion and
18814 not visibility should be done because of current context. This is probably
18815 the place where a package like yasnippets can hook in.")
18817 (defvar org-tab-before-tab-emulation-hook nil
18818 "Hook for functions to attach themselves to TAB.
18819 See `org-ctrl-c-ctrl-c-hook' for more information.
18820 This hook runs after every other options for TAB have been exhausted, but
18821 before indentation and \t insertion takes place.")
18823 (defvar org-metaleft-hook nil
18824 "Hook for functions attaching themselves to `M-left'.
18825 See `org-ctrl-c-ctrl-c-hook' for more information.")
18826 (defvar org-metaright-hook nil
18827 "Hook for functions attaching themselves to `M-right'.
18828 See `org-ctrl-c-ctrl-c-hook' for more information.")
18829 (defvar org-metaup-hook nil
18830 "Hook for functions attaching themselves to `M-up'.
18831 See `org-ctrl-c-ctrl-c-hook' for more information.")
18832 (defvar org-metadown-hook nil
18833 "Hook for functions attaching themselves to `M-down'.
18834 See `org-ctrl-c-ctrl-c-hook' for more information.")
18835 (defvar org-shiftmetaleft-hook nil
18836 "Hook for functions attaching themselves to `M-S-left'.
18837 See `org-ctrl-c-ctrl-c-hook' for more information.")
18838 (defvar org-shiftmetaright-hook nil
18839 "Hook for functions attaching themselves to `M-S-right'.
18840 See `org-ctrl-c-ctrl-c-hook' for more information.")
18841 (defvar org-shiftmetaup-hook nil
18842 "Hook for functions attaching themselves to `M-S-up'.
18843 See `org-ctrl-c-ctrl-c-hook' for more information.")
18844 (defvar org-shiftmetadown-hook nil
18845 "Hook for functions attaching themselves to `M-S-down'.
18846 See `org-ctrl-c-ctrl-c-hook' for more information.")
18847 (defvar org-metareturn-hook nil
18848 "Hook for functions attaching themselves to `M-RET'.
18849 See `org-ctrl-c-ctrl-c-hook' for more information.")
18850 (defvar org-shiftup-hook nil
18851 "Hook for functions attaching themselves to `S-up'.
18852 See `org-ctrl-c-ctrl-c-hook' for more information.")
18853 (defvar org-shiftup-final-hook nil
18854 "Hook for functions attaching themselves to `S-up'.
18855 This one runs after all other options except shift-select have been excluded.
18856 See `org-ctrl-c-ctrl-c-hook' for more information.")
18857 (defvar org-shiftdown-hook nil
18858 "Hook for functions attaching themselves to `S-down'.
18859 See `org-ctrl-c-ctrl-c-hook' for more information.")
18860 (defvar org-shiftdown-final-hook nil
18861 "Hook for functions attaching themselves to `S-down'.
18862 This one runs after all other options except shift-select have been excluded.
18863 See `org-ctrl-c-ctrl-c-hook' for more information.")
18864 (defvar org-shiftleft-hook nil
18865 "Hook for functions attaching themselves to `S-left'.
18866 See `org-ctrl-c-ctrl-c-hook' for more information.")
18867 (defvar org-shiftleft-final-hook nil
18868 "Hook for functions attaching themselves to `S-left'.
18869 This one runs after all other options except shift-select have been excluded.
18870 See `org-ctrl-c-ctrl-c-hook' for more information.")
18871 (defvar org-shiftright-hook nil
18872 "Hook for functions attaching themselves to `S-right'.
18873 See `org-ctrl-c-ctrl-c-hook' for more information.")
18874 (defvar org-shiftright-final-hook nil
18875 "Hook for functions attaching themselves to `S-right'.
18876 This one runs after all other options except shift-select have been excluded.
18877 See `org-ctrl-c-ctrl-c-hook' for more information.")
18879 (defun org-modifier-cursor-error ()
18880 "Throw an error, a modified cursor command was applied in wrong context."
18881 (error "This command is active in special context like tables, headlines or items"))
18883 (defun org-shiftselect-error ()
18884 "Throw an error because Shift-Cursor command was applied in wrong context."
18885 (if (and (boundp 'shift-select-mode) shift-select-mode)
18886 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18887 (error "This command works only in special context like headlines or timestamps")))
18889 (defun org-call-for-shift-select (cmd)
18890 (let ((this-command-keys-shift-translated t))
18891 (call-interactively cmd)))
18893 (defun org-shifttab (&optional arg)
18894 "Global visibility cycling or move to previous table field.
18895 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18896 on context.
18897 See the individual commands for more information."
18898 (interactive "P")
18899 (cond
18900 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18901 ((integerp arg)
18902 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18903 (message "Content view to level: %d" arg)
18904 (org-content (prefix-numeric-value arg2))
18905 (setq org-cycle-global-status 'overview)))
18906 (t (call-interactively 'org-global-cycle))))
18908 (defun org-shiftmetaleft ()
18909 "Promote subtree or delete table column.
18910 Calls `org-promote-subtree', `org-outdent-item-tree', or
18911 `org-table-delete-column', depending on context. See the
18912 individual commands for more information."
18913 (interactive)
18914 (cond
18915 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18916 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18917 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18918 ((if (not (org-region-active-p)) (org-at-item-p)
18919 (save-excursion (goto-char (region-beginning))
18920 (org-at-item-p)))
18921 (call-interactively 'org-outdent-item-tree))
18922 (t (org-modifier-cursor-error))))
18924 (defun org-shiftmetaright ()
18925 "Demote subtree or insert table column.
18926 Calls `org-demote-subtree', `org-indent-item-tree', or
18927 `org-table-insert-column', depending on context. See the
18928 individual commands for more information."
18929 (interactive)
18930 (cond
18931 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18932 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18933 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18934 ((if (not (org-region-active-p)) (org-at-item-p)
18935 (save-excursion (goto-char (region-beginning))
18936 (org-at-item-p)))
18937 (call-interactively 'org-indent-item-tree))
18938 (t (org-modifier-cursor-error))))
18940 (defun org-shiftmetaup (&optional arg)
18941 "Move subtree up or kill table row.
18942 Calls `org-move-subtree-up' or `org-table-kill-row' or
18943 `org-move-item-up' or `org-timestamp-up', depending on context.
18944 See the individual commands for more information."
18945 (interactive "P")
18946 (cond
18947 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18948 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18949 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18950 ((org-at-item-p) (call-interactively 'org-move-item-up))
18951 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18952 (call-interactively 'org-timestamp-up)))
18953 (t (org-modifier-cursor-error))))
18955 (defun org-shiftmetadown (&optional arg)
18956 "Move subtree down or insert table row.
18957 Calls `org-move-subtree-down' or `org-table-insert-row' or
18958 `org-move-item-down' or `org-timestamp-up', depending on context.
18959 See the individual commands for more information."
18960 (interactive "P")
18961 (cond
18962 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18963 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18964 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18965 ((org-at-item-p) (call-interactively 'org-move-item-down))
18966 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18967 (call-interactively 'org-timestamp-down)))
18968 (t (org-modifier-cursor-error))))
18970 (defsubst org-hidden-tree-error ()
18971 (error
18972 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18974 (defun org-metaleft (&optional arg)
18975 "Promote heading or move table column to left.
18976 Calls `org-do-promote' or `org-table-move-column', depending on context.
18977 With no specific context, calls the Emacs default `backward-word'.
18978 See the individual commands for more information."
18979 (interactive "P")
18980 (cond
18981 ((run-hook-with-args-until-success 'org-metaleft-hook))
18982 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18983 ((org-with-limited-levels
18984 (or (org-at-heading-p)
18985 (and (org-region-active-p)
18986 (save-excursion
18987 (goto-char (region-beginning))
18988 (org-at-heading-p)))))
18989 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18990 (call-interactively 'org-do-promote))
18991 ;; At an inline task.
18992 ((org-at-heading-p)
18993 (call-interactively 'org-inlinetask-promote))
18994 ((or (org-at-item-p)
18995 (and (org-region-active-p)
18996 (save-excursion
18997 (goto-char (region-beginning))
18998 (org-at-item-p))))
18999 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19000 (call-interactively 'org-outdent-item))
19001 (t (call-interactively 'backward-word))))
19003 (defun org-metaright (&optional arg)
19004 "Demote a subtree, a list item or move table column to right.
19005 In front of a drawer or a block keyword, indent it correctly.
19006 With no specific context, calls the Emacs default `forward-word'.
19007 See the individual commands for more information."
19008 (interactive "P")
19009 (cond
19010 ((run-hook-with-args-until-success 'org-metaright-hook))
19011 ((org-at-table-p) (call-interactively 'org-table-move-column))
19012 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19013 ((org-at-block-p) (call-interactively 'org-indent-block))
19014 ((org-with-limited-levels
19015 (or (org-at-heading-p)
19016 (and (org-region-active-p)
19017 (save-excursion
19018 (goto-char (region-beginning))
19019 (org-at-heading-p)))))
19020 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19021 (call-interactively 'org-do-demote))
19022 ;; At an inline task.
19023 ((org-at-heading-p)
19024 (call-interactively 'org-inlinetask-demote))
19025 ((or (org-at-item-p)
19026 (and (org-region-active-p)
19027 (save-excursion
19028 (goto-char (region-beginning))
19029 (org-at-item-p))))
19030 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19031 (call-interactively 'org-indent-item))
19032 (t (call-interactively 'forward-word))))
19034 (defun org-check-for-hidden (what)
19035 "Check if there are hidden headlines/items in the current visual line.
19036 WHAT can be either `headlines' or `items'. If the current line is
19037 an outline or item heading and it has a folded subtree below it,
19038 this function returns t, nil otherwise."
19039 (let ((re (cond
19040 ((eq what 'headlines) org-outline-regexp-bol)
19041 ((eq what 'items) (org-item-beginning-re))
19042 (t (error "This should not happen"))))
19043 beg end)
19044 (save-excursion
19045 (catch 'exit
19046 (unless (org-region-active-p)
19047 (setq beg (point-at-bol))
19048 (beginning-of-line 2)
19049 (while (and (not (eobp)) ;; this is like `next-line'
19050 (get-char-property (1- (point)) 'invisible))
19051 (beginning-of-line 2))
19052 (setq end (point))
19053 (goto-char beg)
19054 (goto-char (point-at-eol))
19055 (setq end (max end (point)))
19056 (while (re-search-forward re end t)
19057 (if (get-char-property (match-beginning 0) 'invisible)
19058 (throw 'exit t))))
19059 nil))))
19061 (defun org-metaup (&optional arg)
19062 "Move subtree up or move table row up.
19063 Calls `org-move-subtree-up' or `org-table-move-row' or
19064 `org-move-item-up', depending on context. See the individual commands
19065 for more information."
19066 (interactive "P")
19067 (cond
19068 ((run-hook-with-args-until-success 'org-metaup-hook))
19069 ((org-region-active-p)
19070 (let* ((a (min (region-beginning) (region-end)))
19071 (b (1- (max (region-beginning) (region-end))))
19072 (c (save-excursion (goto-char a)
19073 (move-beginning-of-line 0)))
19074 (d (save-excursion (goto-char a)
19075 (move-end-of-line 0) (point))))
19076 (transpose-regions a b c d)
19077 (goto-char c)))
19078 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19079 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19080 ((org-at-item-p) (call-interactively 'org-move-item-up))
19081 (t (org-drag-element-backward))))
19083 (defun org-metadown (&optional arg)
19084 "Move subtree down or move table row down.
19085 Calls `org-move-subtree-down' or `org-table-move-row' or
19086 `org-move-item-down', depending on context. See the individual
19087 commands for more information."
19088 (interactive "P")
19089 (cond
19090 ((run-hook-with-args-until-success 'org-metadown-hook))
19091 ((org-region-active-p)
19092 (let* ((a (min (region-beginning) (region-end)))
19093 (b (max (region-beginning) (region-end)))
19094 (c (save-excursion (goto-char b)
19095 (move-beginning-of-line 1)))
19096 (d (save-excursion (goto-char b)
19097 (move-end-of-line 1) (1+ (point)))))
19098 (transpose-regions a b c d)
19099 (goto-char d)))
19100 ((org-at-table-p) (call-interactively 'org-table-move-row))
19101 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19102 ((org-at-item-p) (call-interactively 'org-move-item-down))
19103 (t (org-drag-element-forward))))
19105 (defun org-shiftup (&optional arg)
19106 "Increase item in timestamp or increase priority of current headline.
19107 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19108 depending on context. See the individual commands for more information."
19109 (interactive "P")
19110 (cond
19111 ((run-hook-with-args-until-success 'org-shiftup-hook))
19112 ((and org-support-shift-select (org-region-active-p))
19113 (org-call-for-shift-select 'previous-line))
19114 ((org-at-timestamp-p t)
19115 (call-interactively (if org-edit-timestamp-down-means-later
19116 'org-timestamp-down 'org-timestamp-up)))
19117 ((and (not (eq org-support-shift-select 'always))
19118 org-enable-priority-commands
19119 (org-at-heading-p))
19120 (call-interactively 'org-priority-up))
19121 ((and (not org-support-shift-select) (org-at-item-p))
19122 (call-interactively 'org-previous-item))
19123 ((org-clocktable-try-shift 'up arg))
19124 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19125 (org-support-shift-select
19126 (org-call-for-shift-select 'previous-line))
19127 (t (org-shiftselect-error))))
19129 (defun org-shiftdown (&optional arg)
19130 "Decrease item in timestamp or decrease priority of current headline.
19131 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19132 depending on context. See the individual commands for more information."
19133 (interactive "P")
19134 (cond
19135 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19136 ((and org-support-shift-select (org-region-active-p))
19137 (org-call-for-shift-select 'next-line))
19138 ((org-at-timestamp-p t)
19139 (call-interactively (if org-edit-timestamp-down-means-later
19140 'org-timestamp-up 'org-timestamp-down)))
19141 ((and (not (eq org-support-shift-select 'always))
19142 org-enable-priority-commands
19143 (org-at-heading-p))
19144 (call-interactively 'org-priority-down))
19145 ((and (not org-support-shift-select) (org-at-item-p))
19146 (call-interactively 'org-next-item))
19147 ((org-clocktable-try-shift 'down arg))
19148 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19149 (org-support-shift-select
19150 (org-call-for-shift-select 'next-line))
19151 (t (org-shiftselect-error))))
19153 (defun org-shiftright (&optional arg)
19154 "Cycle the thing at point or in the current line, depending on context.
19155 Depending on context, this does one of the following:
19157 - switch a timestamp at point one day into the future
19158 - on a headline, switch to the next TODO keyword.
19159 - on an item, switch entire list to the next bullet type
19160 - on a property line, switch to the next allowed value
19161 - on a clocktable definition line, move time block into the future"
19162 (interactive "P")
19163 (cond
19164 ((run-hook-with-args-until-success 'org-shiftright-hook))
19165 ((and org-support-shift-select (org-region-active-p))
19166 (org-call-for-shift-select 'forward-char))
19167 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19168 ((and (not (eq org-support-shift-select 'always))
19169 (org-at-heading-p))
19170 (let ((org-inhibit-logging
19171 (not org-treat-S-cursor-todo-selection-as-state-change))
19172 (org-inhibit-blocking
19173 (not org-treat-S-cursor-todo-selection-as-state-change)))
19174 (org-call-with-arg 'org-todo 'right)))
19175 ((or (and org-support-shift-select
19176 (not (eq org-support-shift-select 'always))
19177 (org-at-item-bullet-p))
19178 (and (not org-support-shift-select) (org-at-item-p)))
19179 (org-call-with-arg 'org-cycle-list-bullet nil))
19180 ((and (not (eq org-support-shift-select 'always))
19181 (org-at-property-p))
19182 (call-interactively 'org-property-next-allowed-value))
19183 ((org-clocktable-try-shift 'right arg))
19184 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19185 (org-support-shift-select
19186 (org-call-for-shift-select 'forward-char))
19187 (t (org-shiftselect-error))))
19189 (defun org-shiftleft (&optional arg)
19190 "Cycle the thing at point or in the current line, depending on context.
19191 Depending on context, this does one of the following:
19193 - switch a timestamp at point one day into the past
19194 - on a headline, switch to the previous TODO keyword.
19195 - on an item, switch entire list to the previous bullet type
19196 - on a property line, switch to the previous allowed value
19197 - on a clocktable definition line, move time block into the past"
19198 (interactive "P")
19199 (cond
19200 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19201 ((and org-support-shift-select (org-region-active-p))
19202 (org-call-for-shift-select 'backward-char))
19203 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19204 ((and (not (eq org-support-shift-select 'always))
19205 (org-at-heading-p))
19206 (let ((org-inhibit-logging
19207 (not org-treat-S-cursor-todo-selection-as-state-change))
19208 (org-inhibit-blocking
19209 (not org-treat-S-cursor-todo-selection-as-state-change)))
19210 (org-call-with-arg 'org-todo 'left)))
19211 ((or (and org-support-shift-select
19212 (not (eq org-support-shift-select 'always))
19213 (org-at-item-bullet-p))
19214 (and (not org-support-shift-select) (org-at-item-p)))
19215 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19216 ((and (not (eq org-support-shift-select 'always))
19217 (org-at-property-p))
19218 (call-interactively 'org-property-previous-allowed-value))
19219 ((org-clocktable-try-shift 'left arg))
19220 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19221 (org-support-shift-select
19222 (org-call-for-shift-select 'backward-char))
19223 (t (org-shiftselect-error))))
19225 (defun org-shiftcontrolright ()
19226 "Switch to next TODO set."
19227 (interactive)
19228 (cond
19229 ((and org-support-shift-select (org-region-active-p))
19230 (org-call-for-shift-select 'forward-word))
19231 ((and (not (eq org-support-shift-select 'always))
19232 (org-at-heading-p))
19233 (org-call-with-arg 'org-todo 'nextset))
19234 (org-support-shift-select
19235 (org-call-for-shift-select 'forward-word))
19236 (t (org-shiftselect-error))))
19238 (defun org-shiftcontrolleft ()
19239 "Switch to previous TODO set."
19240 (interactive)
19241 (cond
19242 ((and org-support-shift-select (org-region-active-p))
19243 (org-call-for-shift-select 'backward-word))
19244 ((and (not (eq org-support-shift-select 'always))
19245 (org-at-heading-p))
19246 (org-call-with-arg 'org-todo 'previousset))
19247 (org-support-shift-select
19248 (org-call-for-shift-select 'backward-word))
19249 (t (org-shiftselect-error))))
19251 (defun org-shiftcontrolup (&optional n)
19252 "Change timestamps synchronously up in CLOCK log lines.
19253 Optional argument N tells to change by that many units."
19254 (interactive "P")
19255 (cond ((and (not org-support-shift-select)
19256 (org-at-clock-log-p)
19257 (org-at-timestamp-p t))
19258 (org-clock-timestamps-up n))
19259 (t (org-shiftselect-error))))
19261 (defun org-shiftcontroldown (&optional n)
19262 "Change timestamps synchronously down in CLOCK log lines.
19263 Optional argument N tells to change by that many units."
19264 (interactive "P")
19265 (cond ((and (not org-support-shift-select)
19266 (org-at-clock-log-p)
19267 (org-at-timestamp-p t))
19268 (org-clock-timestamps-down n))
19269 (t (org-shiftselect-error))))
19271 (defun org-ctrl-c-ret ()
19272 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19273 (interactive)
19274 (cond
19275 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19276 (t (call-interactively 'org-insert-heading))))
19278 (defun org-find-visible ()
19279 (let ((s (point)))
19280 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19281 (get-char-property s 'invisible)))
19283 (defun org-find-invisible ()
19284 (let ((s (point)))
19285 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19286 (not (get-char-property s 'invisible))))
19289 (defun org-copy-visible (beg end)
19290 "Copy the visible parts of the region."
19291 (interactive "r")
19292 (let (snippets s)
19293 (save-excursion
19294 (save-restriction
19295 (narrow-to-region beg end)
19296 (setq s (goto-char (point-min)))
19297 (while (not (= (point) (point-max)))
19298 (goto-char (org-find-invisible))
19299 (push (buffer-substring s (point)) snippets)
19300 (setq s (goto-char (org-find-visible))))))
19301 (kill-new (apply 'concat (nreverse snippets)))))
19303 (defun org-copy-special ()
19304 "Copy region in table or copy current subtree.
19305 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19306 See the individual commands for more information."
19307 (interactive)
19308 (call-interactively
19309 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19311 (defun org-cut-special ()
19312 "Cut region in table or cut current subtree.
19313 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19314 See the individual commands for more information."
19315 (interactive)
19316 (call-interactively
19317 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19319 (defun org-paste-special (arg)
19320 "Paste rectangular region into table, or past subtree relative to level.
19321 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19322 See the individual commands for more information."
19323 (interactive "P")
19324 (if (org-at-table-p)
19325 (org-table-paste-rectangle)
19326 (org-paste-subtree arg)))
19328 (defsubst org-in-fixed-width-region-p ()
19329 "Is point in a fixed-width region?"
19330 (save-match-data
19331 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19333 (defun org-edit-special (&optional arg)
19334 "Call a special editor for the stuff at point.
19335 When at a table, call the formula editor with `org-table-edit-formulas'.
19336 When in a source code block, call `org-edit-src-code'.
19337 When in a fixed-width region, call `org-edit-fixed-width-region'.
19338 When in an #+include line, visit the included file.
19339 On a link, call `ffap' to visit the link at point.
19340 Otherwise, return a user error."
19341 (interactive)
19342 ;; possibly prep session before editing source
19343 (when (and (org-in-src-block-p) arg)
19344 (let* ((info (org-babel-get-src-block-info))
19345 (lang (nth 0 info))
19346 (params (nth 2 info))
19347 (session (cdr (assoc :session params))))
19348 (when (and info session) ;; we are in a source-code block with a session
19349 (funcall
19350 (intern (concat "org-babel-prep-session:" lang)) session params))))
19351 (cond ;; proceed with `org-edit-special'
19352 ((save-excursion
19353 (beginning-of-line 1)
19354 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19355 (find-file (org-trim (match-string 1))))
19356 ((or (org-at-table-p)
19357 (save-excursion
19358 (beginning-of-line 1)
19359 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19360 (call-interactively 'org-table-edit-formulas))
19361 ((or (org-in-src-block-p) (org-at-table.el-p)) (org-edit-src-code))
19362 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19363 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19364 (t (user-error "No special environment to edit here"))))
19366 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19367 (defun org-ctrl-c-ctrl-c (&optional arg)
19368 "Set tags in headline, or update according to changed information at point.
19370 This command does many different things, depending on context:
19372 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19373 this is what we do.
19375 - If the cursor is on a statistics cookie, update it.
19377 - If the cursor is in a headline, prompt for tags and insert them
19378 into the current line, aligned to `org-tags-column'. When called
19379 with prefix arg, realign all tags in the current buffer.
19381 - If the cursor is in one of the special #+KEYWORD lines, this
19382 triggers scanning the buffer for these lines and updating the
19383 information.
19385 - If the cursor is inside a table, realign the table. This command
19386 works even if the automatic table editor has been turned off.
19388 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19389 the entire table.
19391 - If the cursor is at a footnote reference or definition, jump to
19392 the corresponding definition or references, respectively.
19394 - If the cursor is a the beginning of a dynamic block, update it.
19396 - If the current buffer is a capture buffer, close note and file it.
19398 - If the cursor is on a <<<target>>>, update radio targets and
19399 corresponding links in this buffer.
19401 - If the cursor is on a numbered item in a plain list, renumber the
19402 ordered list.
19404 - If the cursor is on a checkbox, toggle it.
19406 - If the cursor is on a code block, evaluate it. The variable
19407 `org-confirm-babel-evaluate' can be used to control prompting
19408 before code block evaluation, by default every code block
19409 evaluation requires confirmation. Code block evaluation can be
19410 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19411 (interactive "P")
19412 (let ((org-enable-table-editor t))
19413 (cond
19414 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19415 org-occur-highlights
19416 org-latex-fragment-image-overlays)
19417 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19418 (org-remove-occur-highlights)
19419 (org-remove-latex-fragment-image-overlays)
19420 (message "Temporary highlights/overlays removed from current buffer"))
19421 ((and (local-variable-p 'org-finish-function (current-buffer))
19422 (fboundp org-finish-function))
19423 (funcall org-finish-function))
19424 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19425 ((org-in-regexp org-ts-regexp-both)
19426 (org-timestamp-change 0 'day))
19427 ((or (looking-at org-property-start-re)
19428 (org-at-property-p))
19429 (call-interactively 'org-property-action))
19430 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19431 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19432 (or (org-at-heading-p) (org-at-item-p)))
19433 (call-interactively 'org-update-statistics-cookies))
19434 ((org-at-heading-p) (call-interactively 'org-set-tags))
19435 ((org-at-table.el-p)
19436 (message "Use C-c ' to edit table.el tables"))
19437 ((org-at-table-p)
19438 (org-table-maybe-eval-formula)
19439 (if arg
19440 (call-interactively 'org-table-recalculate)
19441 (org-table-maybe-recalculate-line))
19442 (call-interactively 'org-table-align)
19443 (orgtbl-send-table 'maybe))
19444 ((or (org-footnote-at-reference-p)
19445 (org-footnote-at-definition-p))
19446 (call-interactively 'org-footnote-action))
19447 ((org-at-item-checkbox-p)
19448 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19449 ;; list only if at top item.
19450 (let* ((cbox (match-string 1))
19451 (struct (org-list-struct))
19452 (old-struct (copy-tree struct))
19453 (parents (org-list-parents-alist struct))
19454 (orderedp (org-entry-get nil "ORDERED"))
19455 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19456 block-item)
19457 ;; Use a light version of `org-toggle-checkbox' to avoid
19458 ;; computing list structure twice.
19459 (let ((new-box (cond
19460 ((equal arg '(16)) "[-]")
19461 ((equal arg '(4)) nil)
19462 ((equal "[X]" cbox) "[ ]")
19463 (t "[X]"))))
19464 (if (and firstp arg)
19465 ;; If at first item of sub-list, remove check-box from
19466 ;; every item at the same level.
19467 (mapc
19468 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19469 (org-list-get-all-items
19470 (point-at-bol) struct (org-list-prevs-alist struct)))
19471 (org-list-set-checkbox (point-at-bol) struct new-box)))
19472 ;; Replicate `org-list-write-struct', while grabbing a return
19473 ;; value from `org-list-struct-fix-box'.
19474 (org-list-struct-fix-ind struct parents 2)
19475 (org-list-struct-fix-item-end struct)
19476 (let ((prevs (org-list-prevs-alist struct)))
19477 (org-list-struct-fix-bul struct prevs)
19478 (org-list-struct-fix-ind struct parents)
19479 (setq block-item
19480 (org-list-struct-fix-box struct parents prevs orderedp)))
19481 (org-list-struct-apply-struct struct old-struct)
19482 (org-update-checkbox-count-maybe)
19483 (when block-item
19484 (message
19485 "Checkboxes were removed due to unchecked box at line %d"
19486 (org-current-line block-item)))
19487 (when firstp (org-list-send-list 'maybe))))
19488 ((org-at-item-p)
19489 ;; Cursor at an item: repair list. Do checkbox related actions
19490 ;; only if function was called with an argument. Send list only
19491 ;; if at top item.
19492 (let* ((struct (org-list-struct))
19493 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19494 old-struct)
19495 (when arg
19496 (setq old-struct (copy-tree struct))
19497 (if firstp
19498 ;; If at first item of sub-list, add check-box to every
19499 ;; item at the same level.
19500 (mapc
19501 (lambda (pos)
19502 (unless (org-list-get-checkbox pos struct)
19503 (org-list-set-checkbox pos struct "[ ]")))
19504 (org-list-get-all-items
19505 (point-at-bol) struct (org-list-prevs-alist struct)))
19506 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19507 (org-list-write-struct
19508 struct (org-list-parents-alist struct) old-struct)
19509 (when arg (org-update-checkbox-count-maybe))
19510 (when firstp (org-list-send-list 'maybe))))
19511 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19512 ;; Dynamic block
19513 (beginning-of-line 1)
19514 (save-excursion (org-update-dblock)))
19515 ((save-excursion
19516 (let ((case-fold-search t))
19517 (beginning-of-line 1)
19518 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19519 (cond
19520 ((or (equal (match-string 1) "TBLFM")
19521 (equal (match-string 1) "tblfm"))
19522 ;; Recalculate the table before this line
19523 (save-excursion
19524 (beginning-of-line 1)
19525 (skip-chars-backward " \r\n\t")
19526 (if (org-at-table-p)
19527 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19529 (let ((org-inhibit-startup-visibility-stuff t)
19530 (org-startup-align-all-tables nil))
19531 (when (boundp 'org-table-coordinate-overlays)
19532 (mapc 'delete-overlay org-table-coordinate-overlays)
19533 (setq org-table-coordinate-overlays nil))
19534 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19535 (message "Local setup has been refreshed"))))
19536 ((org-clock-update-time-maybe))
19538 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19539 (error "C-c C-c can do nothing useful at this location"))))))
19541 (defun org-mode-restart ()
19542 "Restart Org-mode, to scan again for special lines.
19543 Also updates the keyword regular expressions."
19544 (interactive)
19545 (org-mode)
19546 (message "Org-mode restarted"))
19548 (defun org-kill-note-or-show-branches ()
19549 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19550 (interactive)
19551 (if (not org-finish-function)
19552 (progn
19553 (hide-subtree)
19554 (call-interactively 'show-branches))
19555 (let ((org-note-abort t))
19556 (funcall org-finish-function))))
19558 (defun org-return (&optional indent)
19559 "Goto next table row or insert a newline.
19560 Calls `org-table-next-row' or `newline', depending on context.
19561 See the individual commands for more information."
19562 (interactive)
19563 (let (org-ts-what)
19564 (cond
19565 ((or (bobp) (org-in-src-block-p))
19566 (if indent (newline-and-indent) (newline)))
19567 ((org-at-table-p)
19568 (org-table-justify-field-maybe)
19569 (call-interactively 'org-table-next-row))
19570 ;; when `newline-and-indent' is called within a list, make sure
19571 ;; text moved stays inside the item.
19572 ((and (org-in-item-p) indent)
19573 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19574 (progn
19575 (save-match-data (newline))
19576 (org-indent-line-to (length (match-string 0))))
19577 (let ((ind (org-get-indentation)))
19578 (newline)
19579 (if (org-looking-back org-list-end-re)
19580 (org-indent-line)
19581 (org-indent-line-to ind)))))
19582 ((and org-return-follows-link
19583 (org-at-timestamp-p t)
19584 (not (eq org-ts-what 'after)))
19585 (org-follow-timestamp-link))
19586 ((and org-return-follows-link
19587 (let ((tprop (get-text-property (point) 'face)))
19588 (or (eq tprop 'org-link)
19589 (and (listp tprop) (memq 'org-link tprop)))))
19590 (call-interactively 'org-open-at-point))
19591 ((and (org-at-heading-p)
19592 (looking-at
19593 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19594 (org-show-entry)
19595 (end-of-line 1)
19596 (newline))
19597 (t (if indent (newline-and-indent) (newline))))))
19599 (defun org-return-indent ()
19600 "Goto next table row or insert a newline and indent.
19601 Calls `org-table-next-row' or `newline-and-indent', depending on
19602 context. See the individual commands for more information."
19603 (interactive)
19604 (org-return t))
19606 (defun org-ctrl-c-star ()
19607 "Compute table, or change heading status of lines.
19608 Calls `org-table-recalculate' or `org-toggle-heading',
19609 depending on context."
19610 (interactive)
19611 (cond
19612 ((org-at-table-p)
19613 (call-interactively 'org-table-recalculate))
19615 ;; Convert all lines in region to list items
19616 (call-interactively 'org-toggle-heading))))
19618 (defun org-ctrl-c-minus ()
19619 "Insert separator line in table or modify bullet status of line.
19620 Also turns a plain line or a region of lines into list items.
19621 Calls `org-table-insert-hline', `org-toggle-item', or
19622 `org-cycle-list-bullet', depending on context."
19623 (interactive)
19624 (cond
19625 ((org-at-table-p)
19626 (call-interactively 'org-table-insert-hline))
19627 ((org-region-active-p)
19628 (call-interactively 'org-toggle-item))
19629 ((org-in-item-p)
19630 (call-interactively 'org-cycle-list-bullet))
19632 (call-interactively 'org-toggle-item))))
19634 (defun org-toggle-item (arg)
19635 "Convert headings or normal lines to items, items to normal lines.
19636 If there is no active region, only the current line is considered.
19638 If the first non blank line in the region is an headline, convert
19639 all headlines to items, shifting text accordingly.
19641 If it is an item, convert all items to normal lines.
19643 If it is normal text, change region into an item. With a prefix
19644 argument ARG, change each line in region into an item."
19645 (interactive "P")
19646 (let ((shift-text
19647 (function
19648 ;; Shift text in current section to IND, from point to END.
19649 ;; The function leaves point to END line.
19650 (lambda (ind end)
19651 (let ((min-i 1000) (end (copy-marker end)))
19652 ;; First determine the minimum indentation (MIN-I) of
19653 ;; the text.
19654 (save-excursion
19655 (catch 'exit
19656 (while (< (point) end)
19657 (let ((i (org-get-indentation)))
19658 (cond
19659 ;; Skip blank lines and inline tasks.
19660 ((looking-at "^[ \t]*$"))
19661 ((looking-at org-outline-regexp-bol))
19662 ;; We can't find less than 0 indentation.
19663 ((zerop i) (throw 'exit (setq min-i 0)))
19664 ((< i min-i) (setq min-i i))))
19665 (forward-line))))
19666 ;; Then indent each line so that a line indented to
19667 ;; MIN-I becomes indented to IND. Ignore blank lines
19668 ;; and inline tasks in the process.
19669 (let ((delta (- ind min-i)))
19670 (while (< (point) end)
19671 (unless (or (looking-at "^[ \t]*$")
19672 (looking-at org-outline-regexp-bol))
19673 (org-indent-line-to (+ (org-get-indentation) delta)))
19674 (forward-line)))))))
19675 (skip-blanks
19676 (function
19677 ;; Return beginning of first non-blank line, starting from
19678 ;; line at POS.
19679 (lambda (pos)
19680 (save-excursion
19681 (goto-char pos)
19682 (skip-chars-forward " \r\t\n")
19683 (point-at-bol)))))
19684 beg end)
19685 ;; Determine boundaries of changes.
19686 (if (org-region-active-p)
19687 (setq beg (funcall skip-blanks (region-beginning))
19688 end (copy-marker (region-end)))
19689 (setq beg (funcall skip-blanks (point-at-bol))
19690 end (copy-marker (point-at-eol))))
19691 ;; Depending on the starting line, choose an action on the text
19692 ;; between BEG and END.
19693 (org-with-limited-levels
19694 (save-excursion
19695 (goto-char beg)
19696 (cond
19697 ;; Case 1. Start at an item: de-itemize. Note that it only
19698 ;; happens when a region is active: `org-ctrl-c-minus'
19699 ;; would call `org-cycle-list-bullet' otherwise.
19700 ((org-at-item-p)
19701 (while (< (point) end)
19702 (when (org-at-item-p)
19703 (skip-chars-forward " \t")
19704 (delete-region (point) (match-end 0)))
19705 (forward-line)))
19706 ;; Case 2. Start at an heading: convert to items.
19707 ((org-at-heading-p)
19708 (let* ((bul (org-list-bullet-string "-"))
19709 (bul-len (length bul))
19710 ;; Indentation of the first heading. It should be
19711 ;; relative to the indentation of its parent, if any.
19712 (start-ind (save-excursion
19713 (cond
19714 ((not org-adapt-indentation) 0)
19715 ((not (outline-previous-heading)) 0)
19716 (t (length (match-string 0))))))
19717 ;; Level of first heading. Further headings will be
19718 ;; compared to it to determine hierarchy in the list.
19719 (ref-level (org-reduced-level (org-outline-level))))
19720 (while (< (point) end)
19721 (let* ((level (org-reduced-level (org-outline-level)))
19722 (delta (max 0 (- level ref-level))))
19723 ;; If current headline is less indented than the first
19724 ;; one, set it as reference, in order to preserve
19725 ;; subtrees.
19726 (when (< level ref-level) (setq ref-level level))
19727 (replace-match bul t t)
19728 (org-indent-line-to (+ start-ind (* delta bul-len)))
19729 ;; Ensure all text down to END (or SECTION-END) belongs
19730 ;; to the newly created item.
19731 (let ((section-end (save-excursion
19732 (or (outline-next-heading) (point)))))
19733 (forward-line)
19734 (funcall shift-text
19735 (+ start-ind (* (1+ delta) bul-len))
19736 (min end section-end)))))))
19737 ;; Case 3. Normal line with ARG: turn each non-item line into
19738 ;; an item.
19739 (arg
19740 (while (< (point) end)
19741 (unless (or (org-at-heading-p) (org-at-item-p))
19742 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19743 (replace-match
19744 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19745 (forward-line)))
19746 ;; Case 4. Normal line without ARG: make the first line of
19747 ;; region an item, and shift indentation of others
19748 ;; lines to set them as item's body.
19749 (t (let* ((bul (org-list-bullet-string "-"))
19750 (bul-len (length bul))
19751 (ref-ind (org-get-indentation)))
19752 (skip-chars-forward " \t")
19753 (insert bul)
19754 (forward-line)
19755 (while (< (point) end)
19756 ;; Ensure that lines less indented than first one
19757 ;; still get included in item body.
19758 (funcall shift-text
19759 (+ ref-ind bul-len)
19760 (min end (save-excursion (or (outline-next-heading)
19761 (point)))))
19762 (forward-line)))))))))
19764 (defun org-toggle-heading (&optional nstars)
19765 "Convert headings to normal text, or items or text to headings.
19766 If there is no active region, only the current line is considered.
19768 With a \\[universal-argument] prefix, convert the whole list at
19769 point into heading.
19771 In a region:
19773 - If the first non blank line is an headline, remove the stars
19774 from all headlines in the region.
19776 - If it is a normal line turn each and every normal line (i.e. not an
19777 heading or an item) in the region into a heading.
19779 - If it is a plain list item, turn all plain list items into headings.
19781 When converting a line into a heading, the number of stars is chosen
19782 such that the lines become children of the current entry. However,
19783 when a prefix argument is given, its value determines the number of
19784 stars to add."
19785 (interactive "P")
19786 (let ((skip-blanks
19787 (function
19788 ;; Return beginning of first non-blank line, starting from
19789 ;; line at POS.
19790 (lambda (pos)
19791 (save-excursion
19792 (goto-char pos)
19793 (while (org-at-comment-p) (forward-line))
19794 (skip-chars-forward " \r\t\n")
19795 (point-at-bol)))))
19796 beg end toggled)
19797 ;; Determine boundaries of changes. If a universal prefix has
19798 ;; been given, put the list in a region. If region ends at a bol,
19799 ;; do not consider the last line to be in the region.
19801 (when (and current-prefix-arg (org-at-item-p))
19802 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19803 (org-mark-element))
19805 (if (org-region-active-p)
19806 (setq beg (funcall skip-blanks (region-beginning))
19807 end (copy-marker (save-excursion
19808 (goto-char (region-end))
19809 (if (bolp) (point) (point-at-eol)))))
19810 (setq beg (funcall skip-blanks (point-at-bol))
19811 end (copy-marker (point-at-eol))))
19812 ;; Ensure inline tasks don't count as headings.
19813 (org-with-limited-levels
19814 (save-excursion
19815 (goto-char beg)
19816 (cond
19817 ;; Case 1. Started at an heading: de-star headings.
19818 ((org-at-heading-p)
19819 (while (< (point) end)
19820 (when (org-at-heading-p t)
19821 (looking-at org-outline-regexp) (replace-match "")
19822 (setq toggled t))
19823 (forward-line)))
19824 ;; Case 2. Started at an item: change items into headlines.
19825 ;; One star will be added by `org-list-to-subtree'.
19826 ((org-at-item-p)
19827 (let* ((stars (make-string
19828 (if nstars
19829 ;; subtract the star that will be added again by
19830 ;; `org-list-to-subtree'
19831 (1- (prefix-numeric-value current-prefix-arg))
19832 (or (org-current-level) 0))
19833 ?*))
19834 (add-stars
19835 (cond (nstars "") ; stars from prefix only
19836 ((equal stars "") "") ; before first heading
19837 (org-odd-levels-only "*") ; inside heading, odd
19838 (t "")))) ; inside heading, oddeven
19839 (while (< (point) end)
19840 (when (org-at-item-p)
19841 ;; Pay attention to cases when region ends before list.
19842 (let* ((struct (org-list-struct))
19843 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19844 (save-restriction
19845 (narrow-to-region (point) list-end)
19846 (insert
19847 (org-list-to-subtree
19848 (org-list-parse-list t)
19849 '(:istart (concat stars add-stars (funcall get-stars depth))
19850 :icount (concat stars add-stars (funcall get-stars depth)))))))
19851 (setq toggled t))
19852 (forward-line))))
19853 ;; Case 3. Started at normal text: make every line an heading,
19854 ;; skipping headlines and items.
19855 (t (let* ((stars (make-string
19856 (if nstars
19857 (prefix-numeric-value current-prefix-arg)
19858 (or (org-current-level) 0))
19859 ?*))
19860 (add-stars
19861 (cond (nstars "") ; stars from prefix only
19862 ((equal stars "") "*") ; before first heading
19863 (org-odd-levels-only "**") ; inside heading, odd
19864 (t "*"))) ; inside heading, oddeven
19865 (rpl (concat stars add-stars " ")))
19866 (while (< (point) end)
19867 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19868 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19869 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19870 (forward-line)))))))
19871 (unless toggled (message "Cannot toggle heading from here"))))
19873 (defun org-meta-return (&optional arg)
19874 "Insert a new heading or wrap a region in a table.
19875 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19876 See the individual commands for more information."
19877 (interactive "P")
19878 (cond
19879 ((run-hook-with-args-until-success 'org-metareturn-hook))
19880 ((or (org-at-drawer-p) (org-at-property-p))
19881 (newline-and-indent))
19882 ((org-at-table-p)
19883 (call-interactively 'org-table-wrap-region))
19884 (t (call-interactively 'org-insert-heading))))
19886 ;;; Menu entries
19888 (defsubst org-in-subtree-not-table-p ()
19889 "Are we in a subtree and not in a table?"
19890 (and (not (org-before-first-heading-p))
19891 (not (org-at-table-p))))
19893 ;; Define the Org-mode menus
19894 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19895 '("Tbl"
19896 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19897 ["Next Field" org-cycle (org-at-table-p)]
19898 ["Previous Field" org-shifttab (org-at-table-p)]
19899 ["Next Row" org-return (org-at-table-p)]
19900 "--"
19901 ["Blank Field" org-table-blank-field (org-at-table-p)]
19902 ["Edit Field" org-table-edit-field (org-at-table-p)]
19903 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19904 "--"
19905 ("Column"
19906 ["Move Column Left" org-metaleft (org-at-table-p)]
19907 ["Move Column Right" org-metaright (org-at-table-p)]
19908 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19909 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19910 ("Row"
19911 ["Move Row Up" org-metaup (org-at-table-p)]
19912 ["Move Row Down" org-metadown (org-at-table-p)]
19913 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19914 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19915 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19916 "--"
19917 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19918 ("Rectangle"
19919 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19920 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19921 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19922 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19923 "--"
19924 ("Calculate"
19925 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19926 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19927 ["Edit Formulas" org-edit-special (org-at-table-p)]
19928 "--"
19929 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19930 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19931 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19932 "--"
19933 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19934 "--"
19935 ["Sum Column/Rectangle" org-table-sum
19936 (or (org-at-table-p) (org-region-active-p))]
19937 ["Which Column?" org-table-current-column (org-at-table-p)])
19938 ["Debug Formulas"
19939 org-table-toggle-formula-debugger
19940 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19941 ["Show Col/Row Numbers"
19942 org-table-toggle-coordinate-overlays
19943 :style toggle
19944 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19945 "--"
19946 ["Create" org-table-create (and (not (org-at-table-p))
19947 org-enable-table-editor)]
19948 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19949 ["Import from File" org-table-import (not (org-at-table-p))]
19950 ["Export to File" org-table-export (org-at-table-p)]
19951 "--"
19952 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19954 (easy-menu-define org-org-menu org-mode-map "Org menu"
19955 '("Org"
19956 ("Show/Hide"
19957 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19958 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19959 ["Sparse Tree..." org-sparse-tree t]
19960 ["Reveal Context" org-reveal t]
19961 ["Show All" show-all t]
19962 "--"
19963 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19964 "--"
19965 ["New Heading" org-insert-heading t]
19966 ("Navigate Headings"
19967 ["Up" outline-up-heading t]
19968 ["Next" outline-next-visible-heading t]
19969 ["Previous" outline-previous-visible-heading t]
19970 ["Next Same Level" outline-forward-same-level t]
19971 ["Previous Same Level" outline-backward-same-level t]
19972 "--"
19973 ["Jump" org-goto t])
19974 ("Edit Structure"
19975 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19976 "--"
19977 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19978 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19979 "--"
19980 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19981 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19982 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19983 "--"
19984 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19985 "--"
19986 ["Copy visible text" org-copy-visible t]
19987 "--"
19988 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19989 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19990 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19991 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19992 "--"
19993 ["Sort Region/Children" org-sort t]
19994 "--"
19995 ["Convert to odd levels" org-convert-to-odd-levels t]
19996 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19997 ("Editing"
19998 ["Emphasis..." org-emphasize t]
19999 ["Edit Source Example" org-edit-special t]
20000 "--"
20001 ["Footnote new/jump" org-footnote-action t]
20002 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20003 ("Archive"
20004 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20005 "--"
20006 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20007 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20008 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20010 "--"
20011 ("Hyperlinks"
20012 ["Store Link (Global)" org-store-link t]
20013 ["Find existing link to here" org-occur-link-in-agenda-files t]
20014 ["Insert Link" org-insert-link t]
20015 ["Follow Link" org-open-at-point t]
20016 "--"
20017 ["Next link" org-next-link t]
20018 ["Previous link" org-previous-link t]
20019 "--"
20020 ["Descriptive Links"
20021 org-toggle-link-display
20022 :style radio
20023 :selected org-descriptive-links
20025 ["Literal Links"
20026 org-toggle-link-display
20027 :style radio
20028 :selected (not org-descriptive-links)])
20029 "--"
20030 ("TODO Lists"
20031 ["TODO/DONE/-" org-todo t]
20032 ("Select keyword"
20033 ["Next keyword" org-shiftright (org-at-heading-p)]
20034 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20035 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20036 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20037 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20038 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20039 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20040 "--"
20041 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20042 :selected org-enforce-todo-dependencies :style toggle :active t]
20043 "Settings for tree at point"
20044 ["Do Children sequentially" org-toggle-ordered-property :style radio
20045 :selected (org-entry-get nil "ORDERED")
20046 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20047 ["Do Children parallel" org-toggle-ordered-property :style radio
20048 :selected (not (org-entry-get nil "ORDERED"))
20049 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20050 "--"
20051 ["Set Priority" org-priority t]
20052 ["Priority Up" org-shiftup t]
20053 ["Priority Down" org-shiftdown t]
20054 "--"
20055 ["Get news from all feeds" org-feed-update-all t]
20056 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20057 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20058 ("TAGS and Properties"
20059 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20060 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20061 "--"
20062 ["Set property" org-set-property (not (org-before-first-heading-p))]
20063 ["Column view of properties" org-columns t]
20064 ["Insert Column View DBlock" org-insert-columns-dblock t])
20065 ("Dates and Scheduling"
20066 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20067 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20068 ("Change Date"
20069 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20070 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20071 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20072 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20073 ["Compute Time Range" org-evaluate-time-range t]
20074 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20075 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20076 "--"
20077 ["Custom time format" org-toggle-time-stamp-overlays
20078 :style radio :selected org-display-custom-times]
20079 "--"
20080 ["Goto Calendar" org-goto-calendar t]
20081 ["Date from Calendar" org-date-from-calendar t]
20082 "--"
20083 ["Start/Restart Timer" org-timer-start t]
20084 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20085 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20086 ["Insert Timer String" org-timer t]
20087 ["Insert Timer Item" org-timer-item t])
20088 ("Logging work"
20089 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20090 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20091 ["Clock out" org-clock-out t]
20092 ["Clock cancel" org-clock-cancel t]
20093 "--"
20094 ["Mark as default task" org-clock-mark-default-task t]
20095 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20096 ["Goto running clock" org-clock-goto t]
20097 "--"
20098 ["Display times" org-clock-display t]
20099 ["Create clock table" org-clock-report t]
20100 "--"
20101 ["Record DONE time"
20102 (progn (setq org-log-done (not org-log-done))
20103 (message "Switching to %s will %s record a timestamp"
20104 (car org-done-keywords)
20105 (if org-log-done "automatically" "not")))
20106 :style toggle :selected org-log-done])
20107 "--"
20108 ["Agenda Command..." org-agenda t]
20109 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20110 ("File List for Agenda")
20111 ("Special views current file"
20112 ["TODO Tree" org-show-todo-tree t]
20113 ["Check Deadlines" org-check-deadlines t]
20114 ["Timeline" org-timeline t]
20115 ["Tags/Property tree" org-match-sparse-tree t])
20116 "--"
20117 ["Export/Publish..." org-export t]
20118 ("LaTeX"
20119 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20120 :selected org-cdlatex-mode]
20121 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20122 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20123 ["Modify math symbol" org-cdlatex-math-modify
20124 (org-inside-LaTeX-fragment-p)]
20125 ["Insert citation" org-reftex-citation t]
20126 "--"
20127 ["Template for BEAMER" (progn (require 'org-beamer)
20128 (org-insert-beamer-options-template)) t])
20129 "--"
20130 ("MobileOrg"
20131 ["Push Files and Views" org-mobile-push t]
20132 ["Get Captured and Flagged" org-mobile-pull t]
20133 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20134 "--"
20135 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20136 "--"
20137 ("Documentation"
20138 ["Show Version" org-version t]
20139 ["Info Documentation" org-info t])
20140 ("Customize"
20141 ["Browse Org Group" org-customize t]
20142 "--"
20143 ["Expand This Menu" org-create-customize-menu
20144 (fboundp 'customize-menu-create)])
20145 ["Send bug report" org-submit-bug-report t]
20146 "--"
20147 ("Refresh/Reload"
20148 ["Refresh setup current buffer" org-mode-restart t]
20149 ["Reload Org (after update)" org-reload t]
20150 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20153 (defun org-info (&optional node)
20154 "Read documentation for Org-mode in the info system.
20155 With optional NODE, go directly to that node."
20156 (interactive)
20157 (info (format "(org)%s" (or node ""))))
20159 ;;;###autoload
20160 (defun org-submit-bug-report ()
20161 "Submit a bug report on Org-mode via mail.
20163 Don't hesitate to report any problems or inaccurate documentation.
20165 If you don't have setup sending mail from (X)Emacs, please copy the
20166 output buffer into your mail program, as it gives us important
20167 information about your Org-mode version and configuration."
20168 (interactive)
20169 (require 'reporter)
20170 (org-load-modules-maybe)
20171 (org-require-autoloaded-modules)
20172 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20173 (reporter-submit-bug-report
20174 "emacs-orgmode@gnu.org"
20175 (org-version nil 'full)
20176 (let (list)
20177 (save-window-excursion
20178 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20179 (delete-other-windows)
20180 (erase-buffer)
20181 (insert "You are about to submit a bug report to the Org-mode mailing list.
20183 We would like to add your full Org-mode and Outline configuration to the
20184 bug report. This greatly simplifies the work of the maintainer and
20185 other experts on the mailing list.
20187 HOWEVER, some variables you have customized may contain private
20188 information. The names of customers, colleagues, or friends, might
20189 appear in the form of file names, tags, todo states, or search strings.
20190 If you answer yes to the prompt, you might want to check and remove
20191 such private information before sending the email.")
20192 (add-text-properties (point-min) (point-max) '(face org-warning))
20193 (when (yes-or-no-p "Include your Org-mode configuration ")
20194 (mapatoms
20195 (lambda (v)
20196 (and (boundp v)
20197 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20198 (or (and (symbol-value v)
20199 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20200 (and
20201 (get v 'custom-type) (get v 'standard-value)
20202 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20203 (push v list)))))
20204 (kill-buffer (get-buffer "*Warn about privacy*"))
20205 list))
20206 nil nil
20207 "Remember to cover the basics, that is, what you expected to happen and
20208 what in fact did happen. You don't know how to make a good report? See
20210 http://orgmode.org/manual/Feedback.html#Feedback
20212 Your bug report will be posted to the Org-mode mailing list.
20213 ------------------------------------------------------------------------")
20214 (save-excursion
20215 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20216 (replace-match "\\1Bug: \\3 [\\2]")))))
20219 (defun org-install-agenda-files-menu ()
20220 (let ((bl (buffer-list)))
20221 (save-excursion
20222 (while bl
20223 (set-buffer (pop bl))
20224 (if (derived-mode-p 'org-mode) (setq bl nil)))
20225 (when (derived-mode-p 'org-mode)
20226 (easy-menu-change
20227 '("Org") "File List for Agenda"
20228 (append
20229 (list
20230 ["Edit File List" (org-edit-agenda-file-list) t]
20231 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20232 ["Remove Current File from List" org-remove-file t]
20233 ["Cycle through agenda files" org-cycle-agenda-files t]
20234 ["Occur in all agenda files" org-occur-in-agenda-files t]
20235 "--")
20236 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20238 ;;;; Documentation
20240 (defun org-require-autoloaded-modules ()
20241 (interactive)
20242 (mapc 'require
20243 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20244 org-docbook org-exp org-html org-icalendar
20245 org-id org-latex
20246 org-publish org-remember org-table
20247 org-timer org-xoxo)))
20249 ;;;###autoload
20250 (defun org-reload (&optional uncompiled)
20251 "Reload all org lisp files.
20252 With prefix arg UNCOMPILED, load the uncompiled versions."
20253 (interactive "P")
20254 (require 'loadhist)
20255 (let* ((org-dir (org-find-library-dir "org"))
20256 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20257 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20258 (remove-re (mapconcat 'identity
20259 (mapcar (lambda (f) (concat "^" f "$"))
20260 (list (if (featurep 'xemacs)
20261 "org-colview"
20262 "org-colview-xemacs")
20263 "org" "org-loaddefs" "org-version"))
20264 "\\|"))
20265 (feats (delete-dups
20266 (mapcar 'file-name-sans-extension
20267 (mapcar 'file-name-nondirectory
20268 (delq nil
20269 (mapcar 'feature-file
20270 features))))))
20271 (lfeat (append
20272 (sort
20273 (setq feats
20274 (delq nil (mapcar
20275 (lambda (f)
20276 (if (and (string-match feature-re f)
20277 (not (string-match remove-re f)))
20278 f nil))
20279 feats)))
20280 'string-lessp)
20281 (list "org-version" "org")))
20282 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20283 load-uncore load-misses)
20284 (setq load-misses
20285 (delq 't
20286 (mapcar (lambda (f)
20287 (or (load (concat org-dir f) 'noerror nil nil 'mustsuffix)
20288 (and (string= org-dir contrib-dir)
20289 (load (concat contrib-dir f) 'noerror nil nil 'mustsuffix))
20290 (and (load (concat (org-find-library-dir f) f) 'noerror nil nil 'mustsuffix)
20291 (add-to-list 'load-uncore f 'append)
20294 lfeat)))
20295 (if load-uncore
20296 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20297 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20298 (if load-misses
20299 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20300 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20301 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20303 ;;;###autoload
20304 (defun org-customize ()
20305 "Call the customize function with org as argument."
20306 (interactive)
20307 (org-load-modules-maybe)
20308 (org-require-autoloaded-modules)
20309 (customize-browse 'org))
20311 (defun org-create-customize-menu ()
20312 "Create a full customization menu for Org-mode, insert it into the menu."
20313 (interactive)
20314 (org-load-modules-maybe)
20315 (org-require-autoloaded-modules)
20316 (if (fboundp 'customize-menu-create)
20317 (progn
20318 (easy-menu-change
20319 '("Org") "Customize"
20320 `(["Browse Org group" org-customize t]
20321 "--"
20322 ,(customize-menu-create 'org)
20323 ["Set" Custom-set t]
20324 ["Save" Custom-save t]
20325 ["Reset to Current" Custom-reset-current t]
20326 ["Reset to Saved" Custom-reset-saved t]
20327 ["Reset to Standard Settings" Custom-reset-standard t]))
20328 (message "\"Org\"-menu now contains full customization menu"))
20329 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20331 ;;;; Miscellaneous stuff
20333 ;;; Generally useful functions
20335 (defun org-get-at-bol (property)
20336 "Get text property PROPERTY at beginning of line."
20337 (get-text-property (point-at-bol) property))
20339 (defun org-find-text-property-in-string (prop s)
20340 "Return the first non-nil value of property PROP in string S."
20341 (or (get-text-property 0 prop s)
20342 (get-text-property (or (next-single-property-change 0 prop s) 0)
20343 prop s)))
20345 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20346 "Display the given MESSAGE as a warning."
20347 (if (fboundp 'display-warning)
20348 (display-warning 'org message
20349 (if (featurep 'xemacs) 'warning :warning))
20350 (let ((buf (get-buffer-create "*Org warnings*")))
20351 (with-current-buffer buf
20352 (goto-char (point-max))
20353 (insert "Warning (Org): " message)
20354 (unless (bolp)
20355 (newline)))
20356 (display-buffer buf)
20357 (sit-for 0))))
20359 (defun org-eval (form)
20360 "Eval FORM and return result."
20361 (condition-case error
20362 (eval form)
20363 (error (format "%%![Error: %s]" error))))
20365 (defun org-in-clocktable-p ()
20366 "Check if the cursor is in a clocktable."
20367 (let ((pos (point)) start)
20368 (save-excursion
20369 (end-of-line 1)
20370 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20371 (setq start (match-beginning 0))
20372 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20373 (>= (match-end 0) pos)
20374 start))))
20376 (defun org-in-commented-line ()
20377 "Is point in a line starting with `#'?"
20378 (equal (char-after (point-at-bol)) ?#))
20380 (defun org-in-indented-comment-line ()
20381 "Is point in a line starting with `#' after some white space?"
20382 (save-excursion
20383 (save-match-data
20384 (goto-char (point-at-bol))
20385 (looking-at "[ \t]*#"))))
20387 (defun org-in-verbatim-emphasis ()
20388 (save-match-data
20389 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20391 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20392 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20393 (if (and marker (marker-buffer marker)
20394 (buffer-live-p (marker-buffer marker)))
20395 (progn
20396 (org-pop-to-buffer-same-window (marker-buffer marker))
20397 (if (or (> marker (point-max)) (< marker (point-min)))
20398 (widen))
20399 (goto-char marker)
20400 (org-show-context 'org-goto))
20401 (if bookmark
20402 (bookmark-jump bookmark)
20403 (error "Cannot find location"))))
20405 (defun org-quote-csv-field (s)
20406 "Quote field for inclusion in CSV material."
20407 (if (string-match "[\",]" s)
20408 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20411 (defun org-force-self-insert (N)
20412 "Needed to enforce self-insert under remapping."
20413 (interactive "p")
20414 (self-insert-command N))
20416 (defun org-string-width (s)
20417 "Compute width of string, ignoring invisible characters.
20418 This ignores character with invisibility property `org-link', and also
20419 characters with property `org-cwidth', because these will become invisible
20420 upon the next fontification round."
20421 (let (b l)
20422 (when (or (eq t buffer-invisibility-spec)
20423 (assq 'org-link buffer-invisibility-spec))
20424 (while (setq b (text-property-any 0 (length s)
20425 'invisible 'org-link s))
20426 (setq s (concat (substring s 0 b)
20427 (substring s (or (next-single-property-change
20428 b 'invisible s) (length s)))))))
20429 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20430 (setq s (concat (substring s 0 b)
20431 (substring s (or (next-single-property-change
20432 b 'org-cwidth s) (length s))))))
20433 (setq l (string-width s) b -1)
20434 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20435 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20438 (defun org-shorten-string (s maxlength)
20439 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20440 If the string is shorter or has length MAXLENGTH, just return the
20441 original string. If it is longer, the functions finds a space in the
20442 string, breaks this string off at that locations and adds three dots
20443 as ellipsis. Including the ellipsis, the string will not be longer
20444 than MAXLENGTH. If finding a good breaking point in the string does
20445 not work, the string is just chopped off in the middle of a word
20446 if necessary."
20447 (if (<= (length s) maxlength)
20449 (let* ((n (max (- maxlength 4) 1))
20450 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20451 (if (string-match re s)
20452 (concat (match-string 1 s) "...")
20453 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20455 (defun org-get-indentation (&optional line)
20456 "Get the indentation of the current line, interpreting tabs.
20457 When LINE is given, assume it represents a line and compute its indentation."
20458 (if line
20459 (if (string-match "^ *" (org-remove-tabs line))
20460 (match-end 0))
20461 (save-excursion
20462 (beginning-of-line 1)
20463 (skip-chars-forward " \t")
20464 (current-column))))
20466 (defun org-get-string-indentation (s)
20467 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20468 (let ((n -1) (i 0) (w tab-width) c)
20469 (catch 'exit
20470 (while (< (setq n (1+ n)) (length s))
20471 (setq c (aref s n))
20472 (cond ((= c ?\ ) (setq i (1+ i)))
20473 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20474 (t (throw 'exit t)))))
20477 (defun org-remove-tabs (s &optional width)
20478 "Replace tabulators in S with spaces.
20479 Assumes that s is a single line, starting in column 0."
20480 (setq width (or width tab-width))
20481 (while (string-match "\t" s)
20482 (setq s (replace-match
20483 (make-string
20484 (- (* width (/ (+ (match-beginning 0) width) width))
20485 (match-beginning 0)) ?\ )
20486 t t s)))
20489 (defun org-fix-indentation (line ind)
20490 "Fix indentation in LINE.
20491 IND is a cons cell with target and minimum indentation.
20492 If the current indentation in LINE is smaller than the minimum,
20493 leave it alone. If it is larger than ind, set it to the target."
20494 (let* ((l (org-remove-tabs line))
20495 (i (org-get-indentation l))
20496 (i1 (car ind)) (i2 (cdr ind)))
20497 (if (>= i i2) (setq l (substring line i2)))
20498 (if (> i1 0)
20499 (concat (make-string i1 ?\ ) l)
20500 l)))
20502 (defun org-remove-indentation (code &optional n)
20503 "Remove the maximum common indentation from the lines in CODE.
20504 N may optionally be the number of spaces to remove."
20505 (with-temp-buffer
20506 (insert code)
20507 (org-do-remove-indentation n)
20508 (buffer-string)))
20510 (defun org-do-remove-indentation (&optional n)
20511 "Remove the maximum common indentation from the buffer."
20512 (untabify (point-min) (point-max))
20513 (let ((min 10000) re)
20514 (if n
20515 (setq min n)
20516 (goto-char (point-min))
20517 (while (re-search-forward "^ *[^ \n]" nil t)
20518 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20519 (unless (or (= min 0) (= min 10000))
20520 (setq re (format "^ \\{%d\\}" min))
20521 (goto-char (point-min))
20522 (while (re-search-forward re nil t)
20523 (replace-match "")
20524 (end-of-line 1))
20525 min)))
20527 (defun org-fill-template (template alist)
20528 "Find each %key of ALIST in TEMPLATE and replace it."
20529 (let ((case-fold-search nil)
20530 entry key value)
20531 (setq alist (sort (copy-sequence alist)
20532 (lambda (a b) (< (length (car a)) (length (car b))))))
20533 (while (setq entry (pop alist))
20534 (setq template
20535 (replace-regexp-in-string
20536 (concat "%" (regexp-quote (car entry)))
20537 (or (cdr entry) "") template t t)))
20538 template))
20540 (defun org-base-buffer (buffer)
20541 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20542 (if (not buffer)
20543 buffer
20544 (or (buffer-base-buffer buffer)
20545 buffer)))
20547 (defun org-trim (s)
20548 "Remove whitespace at beginning and end of string."
20549 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20550 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20553 (defun org-wrap (string &optional width lines)
20554 "Wrap string to either a number of lines, or a width in characters.
20555 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20556 that costs. If there is a word longer than WIDTH, the text is actually
20557 wrapped to the length of that word.
20558 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20559 many lines, whatever width that takes.
20560 The return value is a list of lines, without newlines at the end."
20561 (let* ((words (org-split-string string "[ \t\n]+"))
20562 (maxword (apply 'max (mapcar 'org-string-width words)))
20563 w ll)
20564 (cond (width
20565 (org-do-wrap words (max maxword width)))
20566 (lines
20567 (setq w maxword)
20568 (setq ll (org-do-wrap words maxword))
20569 (if (<= (length ll) lines)
20571 (setq ll words)
20572 (while (> (length ll) lines)
20573 (setq w (1+ w))
20574 (setq ll (org-do-wrap words w)))
20575 ll))
20576 (t (error "Cannot wrap this")))))
20578 (defun org-do-wrap (words width)
20579 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20580 (let (lines line)
20581 (while words
20582 (setq line (pop words))
20583 (while (and words (< (+ (length line) (length (car words))) width))
20584 (setq line (concat line " " (pop words))))
20585 (setq lines (push line lines)))
20586 (nreverse lines)))
20588 (defun org-split-string (string &optional separators)
20589 "Splits STRING into substrings at SEPARATORS.
20590 No empty strings are returned if there are matches at the beginning
20591 and end of string."
20592 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20593 (start 0)
20594 notfirst
20595 (list nil))
20596 (while (and (string-match rexp string
20597 (if (and notfirst
20598 (= start (match-beginning 0))
20599 (< start (length string)))
20600 (1+ start) start))
20601 (< (match-beginning 0) (length string)))
20602 (setq notfirst t)
20603 (or (eq (match-beginning 0) 0)
20604 (and (eq (match-beginning 0) (match-end 0))
20605 (eq (match-beginning 0) start))
20606 (setq list
20607 (cons (substring string start (match-beginning 0))
20608 list)))
20609 (setq start (match-end 0)))
20610 (or (eq start (length string))
20611 (setq list
20612 (cons (substring string start)
20613 list)))
20614 (nreverse list)))
20616 (defun org-quote-vert (s)
20617 "Replace \"|\" with \"\\vert\"."
20618 (while (string-match "|" s)
20619 (setq s (replace-match "\\vert" t t s)))
20622 (defun org-uuidgen-p (s)
20623 "Is S an ID created by UUIDGEN?"
20624 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20626 (defun org-in-src-block-p (&optional inside)
20627 "Whether point is in a code source block.
20628 When INSIDE is non-nil, don't consider we are within a src block
20629 when point is at #+BEGIN_SRC or #+END_SRC."
20630 (let ((case-fold-search t) ov)
20631 (or (and (setq ov (overlays-at (point)))
20632 (memq 'org-block-background
20633 (overlay-properties (car ov))))
20634 (and (not inside)
20635 (save-match-data
20636 (save-excursion
20637 (beginning-of-line)
20638 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20640 (defun org-context ()
20641 "Return a list of contexts of the current cursor position.
20642 If several contexts apply, all are returned.
20643 Each context entry is a list with a symbol naming the context, and
20644 two positions indicating start and end of the context. Possible
20645 contexts are:
20647 :headline anywhere in a headline
20648 :headline-stars on the leading stars in a headline
20649 :todo-keyword on a TODO keyword (including DONE) in a headline
20650 :tags on the TAGS in a headline
20651 :priority on the priority cookie in a headline
20652 :item on the first line of a plain list item
20653 :item-bullet on the bullet/number of a plain list item
20654 :checkbox on the checkbox in a plain list item
20655 :table in an org-mode table
20656 :table-special on a special filed in a table
20657 :table-table in a table.el table
20658 :clocktable in a clocktable
20659 :src-block in a source block
20660 :link on a hyperlink
20661 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20662 :target on a <<target>>
20663 :radio-target on a <<<radio-target>>>
20664 :latex-fragment on a LaTeX fragment
20665 :latex-preview on a LaTeX fragment with overlaid preview image
20667 This function expects the position to be visible because it uses font-lock
20668 faces as a help to recognize the following contexts: :table-special, :link,
20669 and :keyword."
20670 (let* ((f (get-text-property (point) 'face))
20671 (faces (if (listp f) f (list f)))
20672 (case-fold-search t)
20673 (p (point)) clist o)
20674 ;; First the large context
20675 (cond
20676 ((org-at-heading-p t)
20677 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20678 (when (progn
20679 (beginning-of-line 1)
20680 (looking-at org-todo-line-tags-regexp))
20681 (push (org-point-in-group p 1 :headline-stars) clist)
20682 (push (org-point-in-group p 2 :todo-keyword) clist)
20683 (push (org-point-in-group p 4 :tags) clist))
20684 (goto-char p)
20685 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20686 (if (looking-at "\\[#[A-Z0-9]\\]")
20687 (push (org-point-in-group p 0 :priority) clist)))
20689 ((org-at-item-p)
20690 (push (org-point-in-group p 2 :item-bullet) clist)
20691 (push (list :item (point-at-bol)
20692 (save-excursion (org-end-of-item) (point)))
20693 clist)
20694 (and (org-at-item-checkbox-p)
20695 (push (org-point-in-group p 0 :checkbox) clist)))
20697 ((org-at-table-p)
20698 (push (list :table (org-table-begin) (org-table-end)) clist)
20699 (if (memq 'org-formula faces)
20700 (push (list :table-special
20701 (previous-single-property-change p 'face)
20702 (next-single-property-change p 'face)) clist)))
20703 ((org-at-table-p 'any)
20704 (push (list :table-table) clist)))
20705 (goto-char p)
20707 (let ((case-fold-search t))
20708 ;; New the "medium" contexts: clocktables, source blocks
20709 (cond ((org-in-clocktable-p)
20710 (push (list :clocktable
20711 (and (or (looking-at "#\\+BEGIN: clocktable")
20712 (search-backward "#+BEGIN: clocktable" nil t))
20713 (match-beginning 0))
20714 (and (re-search-forward "#\\+END:?" nil t)
20715 (match-end 0))) clist))
20716 ((org-in-src-block-p)
20717 (push (list :src-block
20718 (and (or (looking-at "#\\+BEGIN_SRC")
20719 (search-backward "#+BEGIN_SRC" nil t))
20720 (match-beginning 0))
20721 (and (search-forward "#+END_SRC" nil t)
20722 (match-beginning 0))) clist))))
20723 (goto-char p)
20725 ;; Now the small context
20726 (cond
20727 ((org-at-timestamp-p)
20728 (push (org-point-in-group p 0 :timestamp) clist))
20729 ((memq 'org-link faces)
20730 (push (list :link
20731 (previous-single-property-change p 'face)
20732 (next-single-property-change p 'face)) clist))
20733 ((memq 'org-special-keyword faces)
20734 (push (list :keyword
20735 (previous-single-property-change p 'face)
20736 (next-single-property-change p 'face)) clist))
20737 ((org-at-target-p)
20738 (push (org-point-in-group p 0 :target) clist)
20739 (goto-char (1- (match-beginning 0)))
20740 (if (looking-at org-radio-target-regexp)
20741 (push (org-point-in-group p 0 :radio-target) clist))
20742 (goto-char p))
20743 ((setq o (car (delq nil
20744 (mapcar
20745 (lambda (x)
20746 (if (memq x org-latex-fragment-image-overlays) x))
20747 (overlays-at (point))))))
20748 (push (list :latex-fragment
20749 (overlay-start o) (overlay-end o)) clist)
20750 (push (list :latex-preview
20751 (overlay-start o) (overlay-end o)) clist))
20752 ((org-inside-LaTeX-fragment-p)
20753 ;; FIXME: positions wrong.
20754 (push (list :latex-fragment (point) (point)) clist)))
20756 (setq clist (nreverse (delq nil clist)))
20757 clist))
20759 ;; FIXME: Compare with at-regexp-p Do we need both?
20760 (defun org-in-regexp (re &optional nlines visually)
20761 "Check if point is inside a match of regexp.
20762 Normally only the current line is checked, but you can include NLINES extra
20763 lines both before and after point into the search.
20764 If VISUALLY is set, require that the cursor is not after the match but
20765 really on, so that the block visually is on the match."
20766 (catch 'exit
20767 (let ((pos (point))
20768 (eol (point-at-eol (+ 1 (or nlines 0))))
20769 (inc (if visually 1 0)))
20770 (save-excursion
20771 (beginning-of-line (- 1 (or nlines 0)))
20772 (while (re-search-forward re eol t)
20773 (if (and (<= (match-beginning 0) pos)
20774 (>= (+ inc (match-end 0)) pos))
20775 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20777 (defun org-at-regexp-p (regexp)
20778 "Is point inside a match of REGEXP in the current line?"
20779 (catch 'exit
20780 (save-excursion
20781 (let ((pos (point)) (end (point-at-eol)))
20782 (beginning-of-line 1)
20783 (while (re-search-forward regexp end t)
20784 (if (and (<= (match-beginning 0) pos)
20785 (>= (match-end 0) pos))
20786 (throw 'exit t)))
20787 nil))))
20789 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20790 "Non-nil when point is between matches of START-RE and END-RE.
20792 Also return a non-nil value when point is on one of the matches.
20794 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20795 buffer positions. Default values are the positions of headlines
20796 surrounding the point.
20798 The functions returns a cons cell whose car (resp. cdr) is the
20799 position before START-RE (resp. after END-RE)."
20800 (save-match-data
20801 (let ((pos (point))
20802 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20803 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20804 beg end)
20805 (save-excursion
20806 ;; Point is on a block when on START-RE or if START-RE can be
20807 ;; found before it...
20808 (and (or (org-at-regexp-p start-re)
20809 (re-search-backward start-re limit-up t))
20810 (setq beg (match-beginning 0))
20811 ;; ... and END-RE after it...
20812 (goto-char (match-end 0))
20813 (re-search-forward end-re limit-down t)
20814 (> (setq end (match-end 0)) pos)
20815 ;; ... without another START-RE in-between.
20816 (goto-char (match-beginning 0))
20817 (not (re-search-backward start-re (1+ beg) t))
20818 ;; Return value.
20819 (cons beg end))))))
20821 (defun org-in-block-p (names)
20822 "Non-nil when point belongs to a block whose name belongs to NAMES.
20824 NAMES is a list of strings containing names of blocks.
20826 Return first block name matched, or nil. Beware that in case of
20827 nested blocks, the returned name may not belong to the closest
20828 block from point."
20829 (save-match-data
20830 (catch 'exit
20831 (let ((case-fold-search t)
20832 (lim-up (save-excursion (outline-previous-heading)))
20833 (lim-down (save-excursion (outline-next-heading))))
20834 (mapc (lambda (name)
20835 (let ((n (regexp-quote name)))
20836 (when (org-between-regexps-p
20837 (concat "^[ \t]*#\\+begin_" n)
20838 (concat "^[ \t]*#\\+end_" n)
20839 lim-up lim-down)
20840 (throw 'exit n))))
20841 names))
20842 nil)))
20844 (defun org-occur-in-agenda-files (regexp &optional nlines)
20845 "Call `multi-occur' with buffers for all agenda files."
20846 (interactive "sOrg-files matching: \np")
20847 (let* ((files (org-agenda-files))
20848 (tnames (mapcar 'file-truename files))
20849 (extra org-agenda-text-search-extra-files)
20851 (when (eq (car extra) 'agenda-archives)
20852 (setq extra (cdr extra))
20853 (setq files (org-add-archive-files files)))
20854 (while (setq f (pop extra))
20855 (unless (member (file-truename f) tnames)
20856 (add-to-list 'files f 'append)
20857 (add-to-list 'tnames (file-truename f) 'append)))
20858 (multi-occur
20859 (mapcar (lambda (x)
20860 (with-current-buffer
20861 (or (get-file-buffer x) (find-file-noselect x))
20862 (widen)
20863 (current-buffer)))
20864 files)
20865 regexp)))
20867 (if (boundp 'occur-mode-find-occurrence-hook)
20868 ;; Emacs 23
20869 (add-hook 'occur-mode-find-occurrence-hook
20870 (lambda ()
20871 (when (derived-mode-p 'org-mode)
20872 (org-reveal))))
20873 ;; Emacs 22
20874 (defadvice occur-mode-goto-occurrence
20875 (after org-occur-reveal activate)
20876 (and (derived-mode-p 'org-mode) (org-reveal)))
20877 (defadvice occur-mode-goto-occurrence-other-window
20878 (after org-occur-reveal activate)
20879 (and (derived-mode-p 'org-mode) (org-reveal)))
20880 (defadvice occur-mode-display-occurrence
20881 (after org-occur-reveal activate)
20882 (when (derived-mode-p 'org-mode)
20883 (let ((pos (occur-mode-find-occurrence)))
20884 (with-current-buffer (marker-buffer pos)
20885 (save-excursion
20886 (goto-char pos)
20887 (org-reveal)))))))
20889 (defun org-occur-link-in-agenda-files ()
20890 "Create a link and search for it in the agendas.
20891 The link is not stored in `org-stored-links', it is just created
20892 for the search purpose."
20893 (interactive)
20894 (let ((link (condition-case nil
20895 (org-store-link nil)
20896 (error "Unable to create a link to here"))))
20897 (org-occur-in-agenda-files (regexp-quote link))))
20899 (defun org-uniquify (list)
20900 "Remove duplicate elements from LIST."
20901 (let (res)
20902 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20903 res))
20905 (defun org-delete-all (elts list)
20906 "Remove all elements in ELTS from LIST."
20907 (while elts
20908 (setq list (delete (pop elts) list)))
20909 list)
20911 (defun org-count (cl-item cl-seq)
20912 "Count the number of occurrences of ITEM in SEQ.
20913 Taken from `count' in cl-seq.el with all keyword arguments removed."
20914 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20915 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20916 (while (< cl-start cl-end)
20917 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20918 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20919 (setq cl-start (1+ cl-start)))
20920 cl-count))
20922 (defun org-remove-if (predicate seq)
20923 "Remove everything from SEQ that fulfills PREDICATE."
20924 (let (res e)
20925 (while seq
20926 (setq e (pop seq))
20927 (if (not (funcall predicate e)) (push e res)))
20928 (nreverse res)))
20930 (defun org-remove-if-not (predicate seq)
20931 "Remove everything from SEQ that does not fulfill PREDICATE."
20932 (let (res e)
20933 (while seq
20934 (setq e (pop seq))
20935 (if (funcall predicate e) (push e res)))
20936 (nreverse res)))
20938 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20939 "Reduce two-argument FUNCTION across SEQ.
20940 Taken from `reduce' in cl-seq.el with all keyword arguments but
20941 \":initial-value\" removed."
20942 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20943 (cadr (memq :initial-value cl-keys)))
20944 (cl-seq (pop cl-seq))
20945 (t (funcall cl-func)))))
20946 (while cl-seq
20947 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20948 cl-accum))
20950 (defun org-back-over-empty-lines ()
20951 "Move backwards over whitespace, to the beginning of the first empty line.
20952 Returns the number of empty lines passed."
20953 (let ((pos (point)))
20954 (if (cdr (assoc 'heading org-blank-before-new-entry))
20955 (skip-chars-backward " \t\n\r")
20956 (unless (eobp)
20957 (forward-line -1)))
20958 (beginning-of-line 2)
20959 (goto-char (min (point) pos))
20960 (count-lines (point) pos)))
20962 (defun org-skip-whitespace ()
20963 (skip-chars-forward " \t\n\r"))
20965 (defun org-point-in-group (point group &optional context)
20966 "Check if POINT is in match-group GROUP.
20967 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20968 match. If the match group does not exist or point is not inside it,
20969 return nil."
20970 (and (match-beginning group)
20971 (>= point (match-beginning group))
20972 (<= point (match-end group))
20973 (if context
20974 (list context (match-beginning group) (match-end group))
20975 t)))
20977 (defun org-switch-to-buffer-other-window (&rest args)
20978 "Switch to buffer in a second window on the current frame.
20979 In particular, do not allow pop-up frames.
20980 Returns the newly created buffer."
20981 (org-no-popups
20982 (apply 'switch-to-buffer-other-window args)))
20984 (defun org-combine-plists (&rest plists)
20985 "Create a single property list from all plists in PLISTS.
20986 The process starts by copying the first list, and then setting properties
20987 from the other lists. Settings in the last list are the most significant
20988 ones and overrule settings in the other lists."
20989 (let ((rtn (copy-sequence (pop plists)))
20990 p v ls)
20991 (while plists
20992 (setq ls (pop plists))
20993 (while ls
20994 (setq p (pop ls) v (pop ls))
20995 (setq rtn (plist-put rtn p v))))
20996 rtn))
20998 (defun org-replace-escapes (string table)
20999 "Replace %-escapes in STRING with values in TABLE.
21000 TABLE is an association list with keys like \"%a\" and string values.
21001 The sequences in STRING may contain normal field width and padding information,
21002 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21003 so values can contain further %-escapes if they are define later in TABLE."
21004 (let ((tbl (copy-alist table))
21005 (case-fold-search nil)
21006 (pchg 0)
21007 e re rpl)
21008 (while (setq e (pop tbl))
21009 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21010 (when (and (cdr e) (string-match re (cdr e)))
21011 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21012 (safe "SREF"))
21013 (add-text-properties 0 3 (list 'sref sref) safe)
21014 (setcdr e (replace-match safe t t (cdr e)))))
21015 (while (string-match re string)
21016 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21017 (cdr e)))
21018 (setq string (replace-match rpl t t string))))
21019 (while (setq pchg (next-property-change pchg string))
21020 (let ((sref (get-text-property pchg 'sref string)))
21021 (when (and sref (string-match "SREF" string pchg))
21022 (setq string (replace-match sref t t string)))))
21023 string))
21025 (defun org-sublist (list start end)
21026 "Return a section of LIST, from START to END.
21027 Counting starts at 1."
21028 (let (rtn (c start))
21029 (setq list (nthcdr (1- start) list))
21030 (while (and list (<= c end))
21031 (push (pop list) rtn)
21032 (setq c (1+ c)))
21033 (nreverse rtn)))
21035 (defun org-find-base-buffer-visiting (file)
21036 "Like `find-buffer-visiting' but always return the base buffer and
21037 not an indirect buffer."
21038 (let ((buf (or (get-file-buffer file)
21039 (find-buffer-visiting file))))
21040 (if buf
21041 (or (buffer-base-buffer buf) buf)
21042 nil)))
21044 (defun org-image-file-name-regexp (&optional extensions)
21045 "Return regexp matching the file names of images.
21046 If EXTENSIONS is given, only match these."
21047 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21048 (image-file-name-regexp)
21049 (let ((image-file-name-extensions
21050 (or extensions
21051 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21052 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21053 (concat "\\."
21054 (regexp-opt (nconc (mapcar 'upcase
21055 image-file-name-extensions)
21056 image-file-name-extensions)
21058 "\\'"))))
21060 (defun org-file-image-p (file &optional extensions)
21061 "Return non-nil if FILE is an image."
21062 (save-match-data
21063 (string-match (org-image-file-name-regexp extensions) file)))
21065 (defun org-get-cursor-date (&optional with-time)
21066 "Return the date at cursor in as a time.
21067 This works in the calendar and in the agenda, anywhere else it just
21068 returns the current time.
21069 If WITH-TIME is non-nil, returns the time of the event at point (in
21070 the agenda) or the current time of the day."
21071 (let (date day defd tp tm hod mod)
21072 (when with-time
21073 (setq tp (get-text-property (point) 'time))
21074 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21075 (setq hod (string-to-number (match-string 1 tp))
21076 mod (string-to-number (match-string 2 tp))))
21077 (or tp (setq hod (nth 2 (decode-time (current-time)))
21078 mod (nth 1 (decode-time (current-time))))))
21079 (cond
21080 ((eq major-mode 'calendar-mode)
21081 (setq date (calendar-cursor-to-date)
21082 defd (encode-time 0 (or mod 0) (or hod 0)
21083 (nth 1 date) (nth 0 date) (nth 2 date))))
21084 ((eq major-mode 'org-agenda-mode)
21085 (setq day (get-text-property (point) 'day))
21086 (if day
21087 (setq date (calendar-gregorian-from-absolute day)
21088 defd (encode-time 0 (or mod 0) (or hod 0)
21089 (nth 1 date) (nth 0 date) (nth 2 date))))))
21090 (or defd (current-time))))
21092 (defun org-mark-subtree (&optional up)
21093 "Mark the current subtree.
21094 This puts point at the start of the current subtree, and mark at
21095 the end. If a numeric prefix UP is given, move up into the
21096 hierarchy of headlines by UP levels before marking the subtree."
21097 (interactive "P")
21098 (org-with-limited-levels
21099 (cond ((org-at-heading-p) (beginning-of-line))
21100 ((org-before-first-heading-p) (error "Not in a subtree"))
21101 (t (outline-previous-visible-heading 1))))
21102 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21103 (if (org-called-interactively-p 'any)
21104 (call-interactively 'org-mark-element)
21105 (org-mark-element)))
21108 ;;; Macros
21110 ;; Macros are expanded with `org-macro-replace-all', which relies
21111 ;; internally on `org-macro-expand'.
21113 ;; Default templates for expansion are stored in the buffer-local
21114 ;; variable `org-macro-templates'. This variable is updated by
21115 ;; `org-macro-initialize-templates'.
21117 ;; Along with macros defined through #+MACRO: keyword, default
21118 ;; templates include the following hard-coded macros:
21119 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21120 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21122 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21123 ;; {{{title}}} will also be provided.
21126 (defvar org-macro-templates nil
21127 "Alist containing all macro templates in current buffer.
21128 Associations are in the shape of (NAME . TEMPLATE) where NAME
21129 stands for macro's name and template for its replacement value,
21130 both as strings. This is an internal variable. Do not set it
21131 directly, use instead:
21133 #+MACRO: name template")
21134 (make-variable-buffer-local 'org-macro-templates)
21136 (defun org-macro-expand (macro templates)
21137 "Return expanded MACRO, as a string.
21138 MACRO is an object, obtained, for example, with
21139 `org-element-context'. TEMPLATES is an alist of templates used
21140 for expansion. See `org-macro-templates' for a buffer-local
21141 default value. Return nil if no template was found."
21142 (let ((template
21143 ;; Macro names are case-insensitive.
21144 (cdr (assoc-string (org-element-property :key macro) templates t))))
21145 (when template
21146 (let ((value (replace-regexp-in-string
21147 "\\$[0-9]+"
21148 (lambda (arg)
21149 (or (nth (1- (string-to-number (substring arg 1)))
21150 (org-element-property :args macro))
21151 ;; No argument provided: remove
21152 ;; place-holder.
21153 ""))
21154 template)))
21155 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21156 (when (string-match "\\`(eval\\>" value)
21157 (setq value (eval (read value))))
21158 ;; Return string.
21159 (format "%s" (or value ""))))))
21161 (defun org-macro-replace-all (templates)
21162 "Replace all macros in current buffer by their expansion.
21163 TEMPLATES is an alist of templates used for expansion. See
21164 `org-macro-templates' for a buffer-local default value."
21165 (save-excursion
21166 (goto-char (point-min))
21167 (let (record)
21168 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21169 (let ((object (org-element-context)))
21170 (when (eq (org-element-type object) 'macro)
21171 (let* ((value (org-macro-expand object templates))
21172 (begin (org-element-property :begin object))
21173 (signature (list begin
21174 object
21175 (org-element-property :args object))))
21176 ;; Avoid circular dependencies by checking if the same
21177 ;; macro with the same arguments is expanded at the same
21178 ;; position twice.
21179 (if (member signature record)
21180 (error "Circular macro expansion: %s"
21181 (org-element-property :key object))
21182 (when value
21183 (push signature record)
21184 (delete-region
21185 begin
21186 ;; Preserve white spaces after the macro.
21187 (progn (goto-char (org-element-property :end object))
21188 (skip-chars-backward " \t")
21189 (point)))
21190 ;; Leave point before replacement in case of recursive
21191 ;; expansions.
21192 (save-excursion (insert value)))))))))))
21194 (defun org-macro-initialize-templates ()
21195 "Collect macro templates defined in current buffer.
21196 Templates are stored in buffer-local variable
21197 `org-macro-templates'. In addition to buffer-defined macros, the
21198 function installs the following ones: \"property\",
21199 \"time\". and, if the buffer is associated to a file,
21200 \"input-file\" and \"modification-time\"."
21201 (let ((case-fold-search t)
21202 (set-template
21203 (lambda (cell)
21204 ;; Add CELL to `org-macro-templates' if there's no
21205 ;; association matching its name already. Otherwise,
21206 ;; replace old association with the new one in that
21207 ;; variable.
21208 (let ((old-template (assoc (car cell) org-macro-templates)))
21209 (if old-template (setcdr old-template (cdr cell))
21210 (push cell org-macro-templates))))))
21211 ;; Install buffer-local macros.
21212 (org-with-wide-buffer
21213 (goto-char (point-min))
21214 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21215 (let ((element (org-element-at-point)))
21216 (when (eq (org-element-type element) 'keyword)
21217 (let ((value (org-element-property :value element)))
21218 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21219 (funcall set-template
21220 (cons (match-string 1 value)
21221 (or (match-string 2 value) "")))))))))
21222 ;; Install hard-coded macros.
21223 (mapc (lambda (cell) (funcall set-template cell))
21224 (list
21225 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21226 (cons "time" "(eval (format-time-string \"$1\"))")))
21227 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21228 (when (and visited-file (file-exists-p visited-file))
21229 (mapc (lambda (cell) (funcall set-template cell))
21230 (list
21231 (cons "input-file" (file-name-nondirectory visited-file))
21232 (cons "modification-time"
21233 (format "(eval (format-time-string \"$1\" '%s))"
21234 (prin1-to-string
21235 (nth 5 (file-attributes visited-file)))))))))))
21238 ;;; Indentation
21240 (defun org-indent-line ()
21241 "Indent line depending on context."
21242 (interactive)
21243 (let* ((pos (point))
21244 (itemp (org-at-item-p))
21245 (case-fold-search t)
21246 (org-drawer-regexp (or org-drawer-regexp "\000"))
21247 (inline-task-p (and (featurep 'org-inlinetask)
21248 (org-inlinetask-in-task-p)))
21249 (inline-re (and inline-task-p
21250 (org-inlinetask-outline-regexp)))
21251 column)
21252 (if (and orgstruct-is-++ (eq pos (point)))
21253 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21254 (indent-according-to-mode))
21255 (beginning-of-line 1)
21256 (cond
21257 ;; Headings
21258 ((looking-at org-outline-regexp) (setq column 0))
21259 ;; Included files
21260 ((looking-at "#\\+include:") (setq column 0))
21261 ;; Footnote definition
21262 ((looking-at org-footnote-definition-re) (setq column 0))
21263 ;; Literal examples
21264 ((looking-at "[ \t]*:\\( \\|$\\)")
21265 (setq column (org-get-indentation))) ; do nothing
21266 ;; Lists
21267 ((ignore-errors (goto-char (org-in-item-p)))
21268 (setq column (if itemp
21269 (org-get-indentation)
21270 (org-list-item-body-column (point))))
21271 (goto-char pos))
21272 ;; Drawers
21273 ((and (looking-at "[ \t]*:END:")
21274 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21275 (save-excursion
21276 (goto-char (1- (match-beginning 1)))
21277 (setq column (current-column))))
21278 ;; Special blocks
21279 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21280 (save-excursion
21281 (re-search-backward
21282 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21283 (setq column (org-get-indentation (match-string 0))))
21284 ((and (not (looking-at "[ \t]*#\\+begin_"))
21285 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21286 (save-excursion
21287 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21288 (setq column
21289 (cond ((equal (downcase (match-string 1)) "src")
21290 ;; src blocks: let `org-edit-src-exit' handle them
21291 (org-get-indentation))
21292 ((equal (downcase (match-string 1)) "example")
21293 (max (org-get-indentation)
21294 (org-get-indentation (match-string 0))))
21296 (org-get-indentation (match-string 0))))))
21297 ;; This line has nothing special, look at the previous relevant
21298 ;; line to compute indentation
21300 (beginning-of-line 0)
21301 (while (and (not (bobp))
21302 (not (looking-at org-drawer-regexp))
21303 ;; When point started in an inline task, do not move
21304 ;; above task starting line.
21305 (not (and inline-task-p (looking-at inline-re)))
21306 ;; Skip drawers, blocks, empty lines, verbatim,
21307 ;; comments, tables, footnotes definitions, lists,
21308 ;; inline tasks.
21309 (or (and (looking-at "[ \t]*:END:")
21310 (re-search-backward org-drawer-regexp nil t))
21311 (and (looking-at "[ \t]*#\\+end_")
21312 (re-search-backward "[ \t]*#\\+begin_"nil t))
21313 (looking-at "[ \t]*[\n:#|]")
21314 (looking-at org-footnote-definition-re)
21315 (and (ignore-errors (goto-char (org-in-item-p)))
21316 (goto-char
21317 (org-list-get-top-point (org-list-struct))))
21318 (and (not inline-task-p)
21319 (featurep 'org-inlinetask)
21320 (org-inlinetask-in-task-p)
21321 (or (org-inlinetask-goto-beginning) t))))
21322 (beginning-of-line 0))
21323 (cond
21324 ;; There was an heading above.
21325 ((looking-at "\\*+[ \t]+")
21326 (if (not org-adapt-indentation)
21327 (setq column 0)
21328 (goto-char (match-end 0))
21329 (setq column (current-column))))
21330 ;; A drawer had started and is unfinished
21331 ((looking-at org-drawer-regexp)
21332 (goto-char (1- (match-beginning 1)))
21333 (setq column (current-column)))
21334 ;; Else, nothing noticeable found: get indentation and go on.
21335 (t (setq column (org-get-indentation))))))
21336 ;; Now apply indentation and move cursor accordingly
21337 (goto-char pos)
21338 (if (<= (current-column) (current-indentation))
21339 (org-indent-line-to column)
21340 (save-excursion (org-indent-line-to column)))
21341 ;; Special polishing for properties, see `org-property-format'
21342 (setq column (current-column))
21343 (beginning-of-line 1)
21344 (if (looking-at
21345 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21346 (replace-match (concat (match-string 1)
21347 (format org-property-format
21348 (match-string 2) (match-string 3)))
21349 t t))
21350 (org-move-to-column column))))
21352 (defun org-indent-drawer ()
21353 "Indent the drawer at point."
21354 (interactive)
21355 (let ((p (point))
21356 (e (and (save-excursion (re-search-forward ":END:" nil t))
21357 (match-end 0)))
21358 (folded
21359 (save-excursion
21360 (end-of-line)
21361 (when (overlays-at (point))
21362 (member 'invisible (overlay-properties
21363 (car (overlays-at (point)))))))))
21364 (when folded (org-cycle))
21365 (indent-for-tab-command)
21366 (while (and (move-beginning-of-line 2) (< (point) e))
21367 (indent-for-tab-command))
21368 (goto-char p)
21369 (when folded (org-cycle)))
21370 (message "Drawer at point indented"))
21372 (defun org-indent-block ()
21373 "Indent the block at point."
21374 (interactive)
21375 (let ((p (point))
21376 (case-fold-search t)
21377 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21378 (match-end 0)))
21379 (folded
21380 (save-excursion
21381 (end-of-line)
21382 (when (overlays-at (point))
21383 (member 'invisible (overlay-properties
21384 (car (overlays-at (point)))))))))
21385 (when folded (org-cycle))
21386 (indent-for-tab-command)
21387 (while (and (move-beginning-of-line 2) (< (point) e))
21388 (indent-for-tab-command))
21389 (goto-char p)
21390 (when folded (org-cycle)))
21391 (message "Block at point indented"))
21393 (defun org-indent-region (start end)
21394 "Indent region."
21395 (interactive "r")
21396 (save-excursion
21397 (let ((line-end (org-current-line end)))
21398 (goto-char start)
21399 (while (< (org-current-line) line-end)
21400 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21401 (t (call-interactively 'org-indent-line)))
21402 (move-beginning-of-line 2)))))
21405 ;;; Filling
21407 ;; We use our own fill-paragraph and auto-fill functions.
21409 ;; `org-fill-paragraph' relies on adaptive filling and context
21410 ;; checking. Appropriate `fill-prefix' is computed with
21411 ;; `org-adaptive-fill-function'.
21413 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21414 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21415 ;; `org-adaptive-fill-function' value. Internally,
21416 ;; `org-comment-line-break-function' breaks the line.
21418 ;; `org-setup-filling' installs filling and auto-filling related
21419 ;; variables during `org-mode' initialization.
21421 (defun org-setup-filling ()
21422 (interactive)
21423 ;; Prevent auto-fill from inserting unwanted new items.
21424 (when (boundp 'fill-nobreak-predicate)
21425 (org-set-local
21426 'fill-nobreak-predicate
21427 (org-uniquify
21428 (append fill-nobreak-predicate
21429 '(org-fill-paragraph-separate-nobreak-p
21430 org-fill-line-break-nobreak-p)))))
21431 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21432 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21433 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21434 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21436 (defvar org-element-paragraph-separate) ; org-element.el
21437 (defun org-fill-paragraph-separate-nobreak-p ()
21438 "Non-nil when a line break at point would insert a new item."
21439 (looking-at (substring org-element-paragraph-separate 1)))
21441 (defun org-fill-line-break-nobreak-p ()
21442 "Non-nil when a line break at point would create an Org line break."
21443 (save-excursion
21444 (skip-chars-backward "[ \t]")
21445 (skip-chars-backward "\\\\")
21446 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21448 (declare-function message-in-body-p "message" ())
21449 (defun org-adaptive-fill-function ()
21450 "Compute a fill prefix for the current line.
21451 Return fill prefix, as a string, or nil if current line isn't
21452 meant to be filled."
21453 (org-with-wide-buffer
21454 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21455 ;; FIXME: This is really the job of orgstruct++-mode
21456 (let* ((p (line-beginning-position))
21457 (element (save-excursion (beginning-of-line)
21458 (org-element-at-point)))
21459 (type (org-element-type element))
21460 (post-affiliated (org-element-property :post-affiliated element)))
21461 (unless (and post-affiliated (< p post-affiliated))
21462 (case type
21463 (comment (looking-at "[ \t]*# ?") (match-string 0))
21464 (footnote-definition "")
21465 ((item plain-list)
21466 (make-string (org-list-item-body-column
21467 (or post-affiliated
21468 (org-element-property :begin element)))
21469 ? ))
21470 (paragraph
21471 ;; Fill prefix is usually the same as the current line,
21472 ;; except if the paragraph is at the beginning of an item.
21473 (let ((parent (org-element-property :parent element)))
21474 (cond ((eq (org-element-type parent) 'item)
21475 (make-string (org-list-item-body-column
21476 (org-element-property :begin parent))
21477 ? ))
21478 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21479 (match-string 0))
21480 (t ""))))
21481 (comment-block
21482 ;; Only fill contents if P is within block boundaries.
21483 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21484 (forward-line)
21485 (point)))
21486 (cend (save-excursion
21487 (goto-char (org-element-property :end element))
21488 (skip-chars-backward " \r\t\n")
21489 (line-beginning-position))))
21490 (when (and (>= p cbeg) (< p cend))
21491 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21492 (match-string 0)
21493 ""))))))))))
21495 (declare-function message-goto-body "message" ())
21496 (defvar message-cite-prefix-regexp) ; From message.el
21497 (defvar org-element-all-objects) ; From org-element.el
21498 (defun org-fill-paragraph (&optional justify)
21499 "Fill element at point, when applicable.
21501 This function only applies to comment blocks, comments, example
21502 blocks and paragraphs. Also, as a special case, re-align table
21503 when point is at one.
21505 If JUSTIFY is non-nil (interactively, with prefix argument),
21506 justify as well. If `sentence-end-double-space' is non-nil, then
21507 period followed by one space does not end a sentence, so don't
21508 break a line there. The variable `fill-column' controls the
21509 width for filling.
21511 For convenience, when point is at a plain list, an item or
21512 a footnote definition, try to fill the first paragraph within."
21513 (interactive)
21514 (if (and (derived-mode-p 'message-mode)
21515 (or (not (message-in-body-p))
21516 (save-excursion (move-beginning-of-line 1)
21517 (looking-at message-cite-prefix-regexp))))
21518 ;; First ensure filling is correct in message-mode.
21519 (let ((fill-paragraph-function
21520 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21521 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21522 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21523 (paragraph-separate
21524 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21525 (fill-paragraph nil))
21526 (save-excursion
21527 ;; Move to end of line in order to get the first paragraph
21528 ;; within a plain list or a footnote definition.
21529 (end-of-line)
21530 (let ((element (org-element-at-point)))
21531 ;; First check if point is in a blank line at the beginning of
21532 ;; the buffer. In that case, ignore filling.
21533 (if (< (point) (org-element-property :begin element)) t
21534 (case (org-element-type element)
21535 ;; Use major mode filling function is src blocks.
21536 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21537 ;; Align Org tables, leave table.el tables as-is.
21538 (table-row (org-table-align) t)
21539 (table
21540 (when (eq (org-element-property :type element) 'org)
21541 (org-table-align))
21543 (paragraph
21544 ;; Paragraphs may contain `line-break' type objects.
21545 (let ((beg (max (point-min)
21546 (org-element-property :contents-begin element)))
21547 (end (min (point-max)
21548 (org-element-property :contents-end element))))
21549 ;; Do nothing if point is at an affiliated keyword.
21550 (if (< (point) beg) t
21551 (when (derived-mode-p 'message-mode)
21552 ;; In `message-mode', do not fill following
21553 ;; citation in current paragraph nor text before
21554 ;; message body.
21555 (let ((body-start (save-excursion (message-goto-body))))
21556 (when body-start (setq beg (max body-start beg))))
21557 (when (save-excursion
21558 (re-search-forward
21559 (concat "^" message-cite-prefix-regexp) end t))
21560 (setq end (match-beginning 0))))
21561 ;; Fill paragraph, taking line breaks into
21562 ;; consideration. For that, slice the paragraph
21563 ;; using line breaks as separators, and fill the
21564 ;; parts in reverse order to avoid messing with
21565 ;; markers.
21566 (save-excursion
21567 (goto-char end)
21568 (mapc
21569 (lambda (pos)
21570 (fill-region-as-paragraph pos (point) justify)
21571 (goto-char pos))
21572 ;; Find the list of ending positions for line
21573 ;; breaks in the current paragraph. Add paragraph
21574 ;; beginning to include first slice.
21575 (nreverse
21576 (cons
21578 (org-element-map
21579 (org-element--parse-objects
21580 beg end nil org-element-all-objects)
21581 'line-break
21582 (lambda (lb) (org-element-property :end lb)))))))
21583 t)))
21584 ;; Contents of `comment-block' type elements should be
21585 ;; filled as plain text, but only if point is within block
21586 ;; markers.
21587 (comment-block
21588 (let* ((case-fold-search t)
21589 (beg (save-excursion
21590 (goto-char (org-element-property :begin element))
21591 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21592 (forward-line)
21593 (point)))
21594 (end (save-excursion
21595 (goto-char (org-element-property :end element))
21596 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21597 (line-beginning-position))))
21598 (when (and (>= (point) beg) (< (point) end))
21599 (fill-region-as-paragraph
21600 (save-excursion
21601 (end-of-line)
21602 (re-search-backward "^[ \t]*$" beg 'move)
21603 (line-beginning-position))
21604 (save-excursion
21605 (beginning-of-line)
21606 (re-search-forward "^[ \t]*$" end 'move)
21607 (line-beginning-position))
21608 justify)))
21610 ;; Fill comments.
21611 (comment (fill-comment-paragraph justify))
21612 ;; Ignore every other element.
21613 (otherwise t)))))))
21615 (defun org-auto-fill-function ()
21616 "Auto-fill function."
21617 ;; Check if auto-filling is meaningful.
21618 (let ((fc (current-fill-column)))
21619 (when (and fc (> (current-column) fc))
21620 (let* ((fill-prefix (org-adaptive-fill-function))
21621 ;; Enforce empty fill prefix, if required. Otherwise, it
21622 ;; will be computed again.
21623 (adaptive-fill-mode (not (equal fill-prefix ""))))
21624 (when fill-prefix (do-auto-fill))))))
21626 (defun org-comment-line-break-function (&optional soft)
21627 "Break line at point and indent, continuing comment if within one.
21628 The inserted newline is marked hard if variable
21629 `use-hard-newlines' is true, unless optional argument SOFT is
21630 non-nil."
21631 (if soft (insert-and-inherit ?\n) (newline 1))
21632 (save-excursion (forward-char -1) (delete-horizontal-space))
21633 (delete-horizontal-space)
21634 (indent-to-left-margin)
21635 (insert-before-markers-and-inherit fill-prefix))
21638 ;;; Comments
21640 ;; Org comments syntax is quite complex. It requires the entire line
21641 ;; to be just a comment. Also, even with the right syntax at the
21642 ;; beginning of line, some some elements (i.e. verse-block or
21643 ;; example-block) don't accept comments. Usual Emacs comment commands
21644 ;; cannot cope with those requirements. Therefore, Org replaces them.
21646 ;; Org still relies on `comment-dwim', but cannot trust
21647 ;; `comment-only-p'. So, `comment-region-function' and
21648 ;; `uncomment-region-function' both point
21649 ;; to`org-comment-or-uncomment-region'. Eventually,
21650 ;; `org-insert-comment' takes care of insertion of comments at the
21651 ;; beginning of line.
21653 ;; `org-setup-comments-handling' install comments related variables
21654 ;; during `org-mode' initialization.
21656 (defun org-setup-comments-handling ()
21657 (interactive)
21658 (org-set-local 'comment-use-syntax nil)
21659 (org-set-local 'comment-start "# ")
21660 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21661 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21662 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21663 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21665 (defun org-insert-comment ()
21666 "Insert an empty comment above current line.
21667 If the line is empty, insert comment at its beginning."
21668 (beginning-of-line)
21669 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21670 (org-indent-line)
21671 (insert "# "))
21673 (defvar comment-empty-lines) ; From newcomment.el.
21674 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21675 "Comment or uncomment each non-blank line in the region.
21676 Uncomment each non-blank line between BEG and END if it only
21677 contains commented lines. Otherwise, comment them."
21678 (save-restriction
21679 ;; Restrict region
21680 (narrow-to-region (save-excursion (goto-char beg)
21681 (skip-chars-forward " \r\t\n" end)
21682 (line-beginning-position))
21683 (save-excursion (goto-char end)
21684 (skip-chars-backward " \r\t\n" beg)
21685 (line-end-position)))
21686 (let ((uncommentp
21687 ;; UNCOMMENTP is non-nil when every non blank line between
21688 ;; BEG and END is a comment.
21689 (save-excursion
21690 (goto-char (point-min))
21691 (while (and (not (eobp))
21692 (let ((element (org-element-at-point)))
21693 (and (eq (org-element-type element) 'comment)
21694 (goto-char (min (point-max)
21695 (org-element-property
21696 :end element)))))))
21697 (eobp))))
21698 (if uncommentp
21699 ;; Only blank lines and comments in region: uncomment it.
21700 (save-excursion
21701 (goto-char (point-min))
21702 (while (not (eobp))
21703 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21704 (replace-match "" nil nil nil 1))
21705 (forward-line)))
21706 ;; Comment each line in region.
21707 (let ((min-indent (point-max)))
21708 ;; First find the minimum indentation across all lines.
21709 (save-excursion
21710 (goto-char (point-min))
21711 (while (and (not (eobp)) (not (zerop min-indent)))
21712 (unless (looking-at "[ \t]*$")
21713 (setq min-indent (min min-indent (current-indentation))))
21714 (forward-line)))
21715 ;; Then loop over all lines.
21716 (save-excursion
21717 (goto-char (point-min))
21718 (while (not (eobp))
21719 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21720 (org-move-to-column min-indent t)
21721 (insert comment-start))
21722 (forward-line))))))))
21725 ;;; Other stuff.
21727 (defun org-toggle-fixed-width-section (arg)
21728 "Toggle the fixed-width export.
21729 If there is no active region, the QUOTE keyword at the current headline is
21730 inserted or removed. When present, it causes the text between this headline
21731 and the next to be exported as fixed-width text, and unmodified.
21732 If there is an active region, this command adds or removes a colon as the
21733 first character of this line. If the first character of a line is a colon,
21734 this line is also exported in fixed-width font."
21735 (interactive "P")
21736 (let* ((cc 0)
21737 (regionp (org-region-active-p))
21738 (beg (if regionp (region-beginning) (point)))
21739 (end (if regionp (region-end)))
21740 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21741 (case-fold-search nil)
21742 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21743 off)
21744 (if regionp
21745 (save-excursion
21746 (goto-char beg)
21747 (setq cc (current-column))
21748 (beginning-of-line 1)
21749 (setq off (looking-at re))
21750 (while (> nlines 0)
21751 (setq nlines (1- nlines))
21752 (beginning-of-line 1)
21753 (cond
21754 (arg
21755 (org-move-to-column cc t)
21756 (insert ": \n")
21757 (forward-line -1))
21758 ((and off (looking-at re))
21759 (replace-match "" t t nil 1))
21760 ((not off) (org-move-to-column cc t) (insert ": ")))
21761 (forward-line 1)))
21762 (save-excursion
21763 (org-back-to-heading)
21764 (cond
21765 ((looking-at (format org-heading-keyword-regexp-format
21766 org-quote-string))
21767 (goto-char (match-end 1))
21768 (looking-at (concat " +" org-quote-string))
21769 (replace-match "" t t)
21770 (when (eolp) (insert " ")))
21771 ((looking-at org-outline-regexp)
21772 (goto-char (match-end 0))
21773 (insert org-quote-string " ")))))))
21775 (defun org-reftex-citation ()
21776 "Use reftex-citation to insert a citation into the buffer.
21777 This looks for a line like
21779 #+BIBLIOGRAPHY: foo plain option:-d
21781 and derives from it that foo.bib is the bibliography file relevant
21782 for this document. It then installs the necessary environment for RefTeX
21783 to work in this buffer and calls `reftex-citation' to insert a citation
21784 into the buffer.
21786 Export of such citations to both LaTeX and HTML is handled by the contributed
21787 package org-exp-bibtex by Taru Karttunen."
21788 (interactive)
21789 (let ((reftex-docstruct-symbol 'rds)
21790 (reftex-cite-format "\\cite{%l}")
21791 rds bib)
21792 (save-excursion
21793 (save-restriction
21794 (widen)
21795 (let ((case-fold-search t)
21796 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21797 (if (not (save-excursion
21798 (or (re-search-forward re nil t)
21799 (re-search-backward re nil t))))
21800 (error "No bibliography defined in file")
21801 (setq bib (concat (match-string 1) ".bib")
21802 rds (list (list 'bib bib)))))))
21803 (call-interactively 'reftex-citation)))
21805 ;;;; Functions extending outline functionality
21807 (defun org-beginning-of-line (&optional arg)
21808 "Go to the beginning of the current line. If that is invisible, continue
21809 to a visible line beginning. This makes the function of C-a more intuitive.
21810 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21811 first attempt, and only move to after the tags when the cursor is already
21812 beyond the end of the headline."
21813 (interactive "P")
21814 (let ((pos (point))
21815 (special (if (consp org-special-ctrl-a/e)
21816 (car org-special-ctrl-a/e)
21817 org-special-ctrl-a/e))
21818 refpos)
21819 (if (org-bound-and-true-p visual-line-mode)
21820 (beginning-of-visual-line 1)
21821 (beginning-of-line 1))
21822 (if (and arg (fboundp 'move-beginning-of-line))
21823 (call-interactively 'move-beginning-of-line)
21824 (if (bobp)
21826 (backward-char 1)
21827 (if (org-truely-invisible-p)
21828 (while (and (not (bobp)) (org-truely-invisible-p))
21829 (backward-char 1)
21830 (beginning-of-line 1))
21831 (forward-char 1))))
21832 (when special
21833 (cond
21834 ((and (looking-at org-complex-heading-regexp)
21835 (= (char-after (match-end 1)) ?\ ))
21836 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21837 (point-at-eol)))
21838 (goto-char
21839 (if (eq special t)
21840 (cond ((> pos refpos) refpos)
21841 ((= pos (point)) refpos)
21842 (t (point)))
21843 (cond ((> pos (point)) (point))
21844 ((not (eq last-command this-command)) (point))
21845 (t refpos)))))
21846 ((org-at-item-p)
21847 ;; Being at an item and not looking at an the item means point
21848 ;; was previously moved to beginning of a visual line, which
21849 ;; doesn't contain the item. Therefore, do nothing special,
21850 ;; just stay here.
21851 (when (looking-at org-list-full-item-re)
21852 ;; Set special position at first white space character after
21853 ;; bullet, and check-box, if any.
21854 (let ((after-bullet
21855 (let ((box (match-end 3)))
21856 (if (not box) (match-end 1)
21857 (let ((after (char-after box)))
21858 (if (and after (= after ? )) (1+ box) box))))))
21859 ;; Special case: Move point to special position when
21860 ;; currently after it or at beginning of line.
21861 (if (eq special t)
21862 (when (or (> pos after-bullet) (= (point) pos))
21863 (goto-char after-bullet))
21864 ;; Reversed case: Move point to special position when
21865 ;; point was already at beginning of line and command is
21866 ;; repeated.
21867 (when (and (= (point) pos) (eq last-command this-command))
21868 (goto-char after-bullet))))))))
21869 (org-no-warnings
21870 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21872 (defun org-end-of-line (&optional arg)
21873 "Go to the end of the line.
21874 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21875 tags on the first attempt, and only move to after the tags when
21876 the cursor is already beyond the end of the headline."
21877 (interactive "P")
21878 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21879 org-special-ctrl-a/e))
21880 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21881 'end-of-visual-line)
21882 ((fboundp 'move-end-of-line) 'move-end-of-line)
21883 (t 'end-of-line))))
21884 (if (or (not special) arg) (call-interactively move-fun)
21885 (let* ((element (save-excursion (beginning-of-line)
21886 (org-element-at-point)))
21887 (type (org-element-type element)))
21888 (cond
21889 ((memq type '(headline inlinetask))
21890 (let ((pos (point)))
21891 (beginning-of-line 1)
21892 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21893 (if (eq special t)
21894 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21895 (goto-char (match-beginning 1))
21896 (goto-char (match-end 0)))
21897 (if (or (< pos (match-end 0))
21898 (not (eq this-command last-command)))
21899 (goto-char (match-end 0))
21900 (goto-char (match-beginning 1))))
21901 (call-interactively move-fun))))
21902 ((org-element-property :hiddenp element)
21903 ;; If element is hidden, `move-end-of-line' would put point
21904 ;; after it. Use `end-of-line' to stay on current line.
21905 (call-interactively 'end-of-line))
21906 (t (call-interactively move-fun)))))
21907 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21909 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21910 (define-key org-mode-map "\C-e" 'org-end-of-line)
21912 (defun org-backward-sentence (&optional arg)
21913 "Go to beginning of sentence, or beginning of table field.
21914 This will call `backward-sentence' or `org-table-beginning-of-field',
21915 depending on context."
21916 (interactive "P")
21917 (cond
21918 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21919 (t (call-interactively 'backward-sentence))))
21921 (defun org-forward-sentence (&optional arg)
21922 "Go to end of sentence, or end of table field.
21923 This will call `forward-sentence' or `org-table-end-of-field',
21924 depending on context."
21925 (interactive "P")
21926 (cond
21927 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21928 (t (call-interactively 'forward-sentence))))
21930 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21931 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21933 (defun org-kill-line (&optional arg)
21934 "Kill line, to tags or end of line."
21935 (interactive "P")
21936 (cond
21937 ((or (not org-special-ctrl-k)
21938 (bolp)
21939 (not (org-at-heading-p)))
21940 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21941 org-ctrl-k-protect-subtree)
21942 (if (or (eq org-ctrl-k-protect-subtree 'error)
21943 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21944 (error "C-k aborted - would kill hidden subtree")))
21945 (call-interactively
21946 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21947 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21948 (kill-region (point) (match-beginning 1))
21949 (org-set-tags nil t))
21950 (t (kill-region (point) (point-at-eol)))))
21952 (define-key org-mode-map "\C-k" 'org-kill-line)
21954 (defun org-yank (&optional arg)
21955 "Yank. If the kill is a subtree, treat it specially.
21956 This command will look at the current kill and check if is a single
21957 subtree, or a series of subtrees[1]. If it passes the test, and if the
21958 cursor is at the beginning of a line or after the stars of a currently
21959 empty headline, then the yank is handled specially. How exactly depends
21960 on the value of the following variables, both set by default.
21962 org-yank-folded-subtrees
21963 When set, the subtree(s) will be folded after insertion, but only
21964 if doing so would now swallow text after the yanked text.
21966 org-yank-adjusted-subtrees
21967 When set, the subtree will be promoted or demoted in order to
21968 fit into the local outline tree structure, which means that the level
21969 will be adjusted so that it becomes the smaller one of the two
21970 *visible* surrounding headings.
21972 Any prefix to this command will cause `yank' to be called directly with
21973 no special treatment. In particular, a simple \\[universal-argument] prefix \
21974 will just
21975 plainly yank the text as it is.
21977 \[1] The test checks if the first non-white line is a heading
21978 and if there are no other headings with fewer stars."
21979 (interactive "P")
21980 (org-yank-generic 'yank arg))
21982 (defun org-yank-generic (command arg)
21983 "Perform some yank-like command.
21985 This function implements the behavior described in the `org-yank'
21986 documentation. However, it has been generalized to work for any
21987 interactive command with similar behavior."
21989 ;; pretend to be command COMMAND
21990 (setq this-command command)
21992 (if arg
21993 (call-interactively command)
21995 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21996 (and (org-kill-is-subtree-p)
21997 (or (bolp)
21998 (and (looking-at "[ \t]*$")
21999 (string-match
22000 "\\`\\*+\\'"
22001 (buffer-substring (point-at-bol) (point)))))))
22002 swallowp)
22003 (cond
22004 ((and subtreep org-yank-folded-subtrees)
22005 (let ((beg (point))
22006 end)
22007 (if (and subtreep org-yank-adjusted-subtrees)
22008 (org-paste-subtree nil nil 'for-yank)
22009 (call-interactively command))
22011 (setq end (point))
22012 (goto-char beg)
22013 (when (and (bolp) subtreep
22014 (not (setq swallowp
22015 (org-yank-folding-would-swallow-text beg end))))
22016 (org-with-limited-levels
22017 (or (looking-at org-outline-regexp)
22018 (re-search-forward org-outline-regexp-bol end t))
22019 (while (and (< (point) end) (looking-at org-outline-regexp))
22020 (hide-subtree)
22021 (org-cycle-show-empty-lines 'folded)
22022 (condition-case nil
22023 (outline-forward-same-level 1)
22024 (error (goto-char end))))))
22025 (when swallowp
22026 (message
22027 "Inserted text not folded because that would swallow text"))
22029 (goto-char end)
22030 (skip-chars-forward " \t\n\r")
22031 (beginning-of-line 1)
22032 (push-mark beg 'nomsg)))
22033 ((and subtreep org-yank-adjusted-subtrees)
22034 (let ((beg (point-at-bol)))
22035 (org-paste-subtree nil nil 'for-yank)
22036 (push-mark beg 'nomsg)))
22038 (call-interactively command))))))
22040 (defun org-yank-folding-would-swallow-text (beg end)
22041 "Would hide-subtree at BEG swallow any text after END?"
22042 (let (level)
22043 (org-with-limited-levels
22044 (save-excursion
22045 (goto-char beg)
22046 (when (or (looking-at org-outline-regexp)
22047 (re-search-forward org-outline-regexp-bol end t))
22048 (setq level (org-outline-level)))
22049 (goto-char end)
22050 (skip-chars-forward " \t\r\n\v\f")
22051 (if (or (eobp)
22052 (and (bolp) (looking-at org-outline-regexp)
22053 (<= (org-outline-level) level)))
22054 nil ; Nothing would be swallowed
22055 t))))) ; something would swallow
22057 (define-key org-mode-map "\C-y" 'org-yank)
22059 (defun org-truely-invisible-p ()
22060 "Check if point is at a character currently not visible.
22061 This version does not only check the character property, but also
22062 `visible-mode'."
22063 ;; Early versions of noutline don't have `outline-invisible-p'.
22064 (if (org-bound-and-true-p visible-mode)
22066 (outline-invisible-p)))
22068 (defun org-invisible-p2 ()
22069 "Check if point is at a character currently not visible."
22070 (save-excursion
22071 (if (and (eolp) (not (bobp))) (backward-char 1))
22072 ;; Early versions of noutline don't have `outline-invisible-p'.
22073 (outline-invisible-p)))
22075 (defun org-back-to-heading (&optional invisible-ok)
22076 "Call `outline-back-to-heading', but provide a better error message."
22077 (condition-case nil
22078 (outline-back-to-heading invisible-ok)
22079 (error (error "Before first headline at position %d in buffer %s"
22080 (point) (current-buffer)))))
22082 (defun org-before-first-heading-p ()
22083 "Before first heading?"
22084 (save-excursion
22085 (end-of-line)
22086 (null (re-search-backward org-outline-regexp-bol nil t))))
22088 (defun org-at-heading-p (&optional ignored)
22089 (outline-on-heading-p t))
22090 ;; Compatibility alias with Org versions < 7.8.03
22091 (defalias 'org-on-heading-p 'org-at-heading-p)
22093 (defun org-at-comment-p nil
22094 "Is cursor in a line starting with a # character?"
22095 (save-excursion
22096 (beginning-of-line)
22097 (looking-at "^#")))
22099 (defun org-at-drawer-p nil
22100 "Is cursor at a drawer keyword?"
22101 (save-excursion
22102 (move-beginning-of-line 1)
22103 (looking-at org-drawer-regexp)))
22105 (defun org-at-block-p nil
22106 "Is cursor at a block keyword?"
22107 (save-excursion
22108 (move-beginning-of-line 1)
22109 (looking-at org-block-regexp)))
22111 (defun org-point-at-end-of-empty-headline ()
22112 "If point is at the end of an empty headline, return t, else nil.
22113 If the heading only contains a TODO keyword, it is still still considered
22114 empty."
22115 (and (looking-at "[ \t]*$")
22116 (when org-todo-line-regexp
22117 (save-excursion
22118 (beginning-of-line 1)
22119 (let ((case-fold-search nil))
22120 (looking-at org-todo-line-regexp)
22121 (string= (match-string 3) ""))))))
22123 (defun org-at-heading-or-item-p ()
22124 (or (org-at-heading-p) (org-at-item-p)))
22126 (defun org-at-target-p ()
22127 (or (org-in-regexp org-radio-target-regexp)
22128 (org-in-regexp org-target-regexp)))
22129 ;; Compatibility alias with Org versions < 7.8.03
22130 (defalias 'org-on-target-p 'org-at-target-p)
22132 (defun org-up-heading-all (arg)
22133 "Move to the heading line of which the present line is a subheading.
22134 This function considers both visible and invisible heading lines.
22135 With argument, move up ARG levels."
22136 (if (fboundp 'outline-up-heading-all)
22137 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22138 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22140 (defun org-up-heading-safe ()
22141 "Move to the heading line of which the present line is a subheading.
22142 This version will not throw an error. It will return the level of the
22143 headline found, or nil if no higher level is found.
22145 Also, this function will be a lot faster than `outline-up-heading',
22146 because it relies on stars being the outline starters. This can really
22147 make a significant difference in outlines with very many siblings."
22148 (let (start-level re)
22149 (org-back-to-heading t)
22150 (setq start-level (funcall outline-level))
22151 (if (equal start-level 1)
22153 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22154 (if (re-search-backward re nil t)
22155 (funcall outline-level)))))
22157 (defun org-first-sibling-p ()
22158 "Is this heading the first child of its parents?"
22159 (interactive)
22160 (let ((re org-outline-regexp-bol)
22161 level l)
22162 (unless (org-at-heading-p t)
22163 (error "Not at a heading"))
22164 (setq level (funcall outline-level))
22165 (save-excursion
22166 (if (not (re-search-backward re nil t))
22168 (setq l (funcall outline-level))
22169 (< l level)))))
22171 (defun org-goto-sibling (&optional previous)
22172 "Goto the next sibling, even if it is invisible.
22173 When PREVIOUS is set, go to the previous sibling instead. Returns t
22174 when a sibling was found. When none is found, return nil and don't
22175 move point."
22176 (let ((fun (if previous 're-search-backward 're-search-forward))
22177 (pos (point))
22178 (re org-outline-regexp-bol)
22179 level l)
22180 (when (condition-case nil (org-back-to-heading t) (error nil))
22181 (setq level (funcall outline-level))
22182 (catch 'exit
22183 (or previous (forward-char 1))
22184 (while (funcall fun re nil t)
22185 (setq l (funcall outline-level))
22186 (when (< l level) (goto-char pos) (throw 'exit nil))
22187 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22188 (goto-char pos)
22189 nil))))
22191 (defun org-show-siblings ()
22192 "Show all siblings of the current headline."
22193 (save-excursion
22194 (while (org-goto-sibling) (org-flag-heading nil)))
22195 (save-excursion
22196 (while (org-goto-sibling 'previous)
22197 (org-flag-heading nil))))
22199 (defun org-goto-first-child ()
22200 "Goto the first child, even if it is invisible.
22201 Return t when a child was found. Otherwise don't move point and
22202 return nil."
22203 (let (level (pos (point)) (re org-outline-regexp-bol))
22204 (when (condition-case nil (org-back-to-heading t) (error nil))
22205 (setq level (outline-level))
22206 (forward-char 1)
22207 (if (and (re-search-forward re nil t) (> (outline-level) level))
22208 (progn (goto-char (match-beginning 0)) t)
22209 (goto-char pos) nil))))
22211 (defun org-show-hidden-entry ()
22212 "Show an entry where even the heading is hidden."
22213 (save-excursion
22214 (org-show-entry)))
22216 (defun org-flag-heading (flag &optional entry)
22217 "Flag the current heading. FLAG non-nil means make invisible.
22218 When ENTRY is non-nil, show the entire entry."
22219 (save-excursion
22220 (org-back-to-heading t)
22221 ;; Check if we should show the entire entry
22222 (if entry
22223 (progn
22224 (org-show-entry)
22225 (save-excursion
22226 (and (outline-next-heading)
22227 (org-flag-heading nil))))
22228 (outline-flag-region (max (point-min) (1- (point)))
22229 (save-excursion (outline-end-of-heading) (point))
22230 flag))))
22232 (defun org-get-next-sibling ()
22233 "Move to next heading of the same level, and return point.
22234 If there is no such heading, return nil.
22235 This is like outline-next-sibling, but invisible headings are ok."
22236 (let ((level (funcall outline-level)))
22237 (outline-next-heading)
22238 (while (and (not (eobp)) (> (funcall outline-level) level))
22239 (outline-next-heading))
22240 (if (or (eobp) (< (funcall outline-level) level))
22242 (point))))
22244 (defun org-get-last-sibling ()
22245 "Move to previous heading of the same level, and return point.
22246 If there is no such heading, return nil."
22247 (let ((opoint (point))
22248 (level (funcall outline-level)))
22249 (outline-previous-heading)
22250 (when (and (/= (point) opoint) (outline-on-heading-p t))
22251 (while (and (> (funcall outline-level) level)
22252 (not (bobp)))
22253 (outline-previous-heading))
22254 (if (< (funcall outline-level) level)
22256 (point)))))
22258 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22259 "Goto to the end of a subtree."
22260 ;; This contains an exact copy of the original function, but it uses
22261 ;; `org-back-to-heading', to make it work also in invisible
22262 ;; trees. And is uses an invisible-ok argument.
22263 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22264 ;; Furthermore, when used inside Org, finding the end of a large subtree
22265 ;; with many children and grandchildren etc, this can be much faster
22266 ;; than the outline version.
22267 (org-back-to-heading invisible-ok)
22268 (let ((first t)
22269 (level (funcall outline-level)))
22270 (if (and (derived-mode-p 'org-mode) (< level 1000))
22271 ;; A true heading (not a plain list item), in Org-mode
22272 ;; This means we can easily find the end by looking
22273 ;; only for the right number of stars. Using a regexp to do
22274 ;; this is so much faster than using a Lisp loop.
22275 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22276 (forward-char 1)
22277 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22278 ;; something else, do it the slow way
22279 (while (and (not (eobp))
22280 (or first (> (funcall outline-level) level)))
22281 (setq first nil)
22282 (outline-next-heading)))
22283 (unless to-heading
22284 (if (memq (preceding-char) '(?\n ?\^M))
22285 (progn
22286 ;; Go to end of line before heading
22287 (forward-char -1)
22288 (if (memq (preceding-char) '(?\n ?\^M))
22289 ;; leave blank line before heading
22290 (forward-char -1))))))
22291 (point))
22293 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22294 "Use Org version in org-mode, for dramatic speed-up."
22295 (if (derived-mode-p 'org-mode)
22296 (progn
22297 (org-end-of-subtree nil t)
22298 (unless (eobp) (backward-char 1)))
22299 ad-do-it))
22301 (defun org-end-of-meta-data-and-drawers ()
22302 "Jump to the first text after meta data and drawers in the current entry.
22303 This will move over empty lines, lines with planning time stamps,
22304 clocking lines, and drawers."
22305 (org-back-to-heading t)
22306 (let ((end (save-excursion (outline-next-heading) (point)))
22307 (re (concat "\\(" org-drawer-regexp "\\)"
22308 "\\|" "[ \t]*" org-keyword-time-regexp)))
22309 (forward-line 1)
22310 (while (re-search-forward re end t)
22311 (if (not (match-end 1))
22312 ;; empty or planning line
22313 (forward-line 1)
22314 ;; a drawer, find the end
22315 (re-search-forward "^[ \t]*:END:" end 'move)
22316 (forward-line 1)))
22317 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22318 (point)))
22320 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22321 "Move forward to the arg'th subheading at same level as this one.
22322 Stop at the first and last subheadings of a superior heading.
22323 Normally this only looks at visible headings, but when INVISIBLE-OK is
22324 non-nil it will also look at invisible ones."
22325 (interactive "p")
22326 (org-back-to-heading invisible-ok)
22327 (org-at-heading-p)
22328 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22329 (re (format "^\\*\\{1,%d\\} " level))
22331 (forward-char 1)
22332 (while (> arg 0)
22333 (while (and (re-search-forward re nil 'move)
22334 (setq l (- (match-end 0) (match-beginning 0) 1))
22335 (= l level)
22336 (not invisible-ok)
22337 (progn (backward-char 1) (outline-invisible-p)))
22338 (if (< l level) (setq arg 1)))
22339 (setq arg (1- arg)))
22340 (beginning-of-line 1)))
22342 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22343 "Move backward to the arg'th subheading at same level as this one.
22344 Stop at the first and last subheadings of a superior heading."
22345 (interactive "p")
22346 (org-back-to-heading)
22347 (org-at-heading-p)
22348 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22349 (re (format "^\\*\\{1,%d\\} " level))
22351 (while (> arg 0)
22352 (while (and (re-search-backward re nil 'move)
22353 (setq l (- (match-end 0) (match-beginning 0) 1))
22354 (= l level)
22355 (not invisible-ok)
22356 (outline-invisible-p))
22357 (if (< l level) (setq arg 1)))
22358 (setq arg (1- arg)))))
22360 (defun org-forward-element ()
22361 "Move forward by one element.
22362 Move to the next element at the same level, when possible."
22363 (interactive)
22364 (cond ((eobp) (error "Cannot move further down"))
22365 ((org-with-limited-levels (org-at-heading-p))
22366 (let ((origin (point)))
22367 (org-forward-heading-same-level 1)
22368 (unless (org-with-limited-levels (org-at-heading-p))
22369 (goto-char origin)
22370 (error "Cannot move further down"))))
22372 (let* ((elem (org-element-at-point))
22373 (end (org-element-property :end elem))
22374 (parent (org-element-property :parent elem)))
22375 (if (and parent (= (org-element-property :contents-end parent) end))
22376 (goto-char (org-element-property :end parent))
22377 (goto-char end))))))
22379 (defun org-backward-element ()
22380 "Move backward by one element.
22381 Move to the previous element at the same level, when possible."
22382 (interactive)
22383 (cond ((bobp) (error "Cannot move further up"))
22384 ((org-with-limited-levels (org-at-heading-p))
22385 ;; At an headline, move to the previous one, if any, or stay
22386 ;; here.
22387 (let ((origin (point)))
22388 (org-backward-heading-same-level 1)
22389 (unless (org-with-limited-levels (org-at-heading-p))
22390 (goto-char origin)
22391 (error "Cannot move further up"))))
22393 (let* ((trail (org-element-at-point 'keep-trail))
22394 (elem (car trail))
22395 (prev-elem (nth 1 trail))
22396 (beg (org-element-property :begin elem)))
22397 (cond
22398 ;; Move to beginning of current element if point isn't
22399 ;; there already.
22400 ((/= (point) beg) (goto-char beg))
22401 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22402 ((org-before-first-heading-p) (goto-char (point-min)))
22403 (t (org-back-to-heading)))))))
22405 (defun org-up-element ()
22406 "Move to upper element."
22407 (interactive)
22408 (if (org-with-limited-levels (org-at-heading-p))
22409 (unless (org-up-heading-safe) (error "No surrounding element"))
22410 (let* ((elem (org-element-at-point))
22411 (parent (org-element-property :parent elem)))
22412 (if parent (goto-char (org-element-property :begin parent))
22413 (if (org-with-limited-levels (org-before-first-heading-p))
22414 (error "No surrounding element")
22415 (org-with-limited-levels (org-back-to-heading)))))))
22417 (defvar org-element-greater-elements)
22418 (defun org-down-element ()
22419 "Move to inner element."
22420 (interactive)
22421 (let ((element (org-element-at-point)))
22422 (cond
22423 ((memq (org-element-type element) '(plain-list table))
22424 (goto-char (org-element-property :contents-begin element))
22425 (forward-char))
22426 ((memq (org-element-type element) org-element-greater-elements)
22427 ;; If contents are hidden, first disclose them.
22428 (when (org-element-property :hiddenp element) (org-cycle))
22429 (goto-char (or (org-element-property :contents-begin element)
22430 (error "No content for this element"))))
22431 (t (error "No inner element")))))
22433 (defun org-drag-element-backward ()
22434 "Move backward element at point."
22435 (interactive)
22436 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22437 (let* ((trail (org-element-at-point 'keep-trail))
22438 (elem (car trail))
22439 (prev-elem (nth 1 trail)))
22440 ;; Error out if no previous element or previous element is
22441 ;; a parent of the current one.
22442 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22443 (error "Cannot drag element backward")
22444 (let ((pos (point)))
22445 (org-element-swap-A-B prev-elem elem)
22446 (goto-char (+ (org-element-property :begin prev-elem)
22447 (- pos (org-element-property :begin elem)))))))))
22449 (defun org-drag-element-forward ()
22450 "Move forward element at point."
22451 (interactive)
22452 (let* ((pos (point))
22453 (elem (org-element-at-point)))
22454 (when (= (point-max) (org-element-property :end elem))
22455 (error "Cannot drag element forward"))
22456 (goto-char (org-element-property :end elem))
22457 (let ((next-elem (org-element-at-point)))
22458 (when (or (org-element-nested-p elem next-elem)
22459 (and (eq (org-element-type next-elem) 'headline)
22460 (not (eq (org-element-type elem) 'headline))))
22461 (goto-char pos)
22462 (error "Cannot drag element forward"))
22463 ;; Compute new position of point: it's shifted by NEXT-ELEM
22464 ;; body's length (without final blanks) and by the length of
22465 ;; blanks between ELEM and NEXT-ELEM.
22466 (let ((size-next (- (save-excursion
22467 (goto-char (org-element-property :end next-elem))
22468 (skip-chars-backward " \r\t\n")
22469 (forward-line)
22470 ;; Small correction if buffer doesn't end
22471 ;; with a newline character.
22472 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22473 (org-element-property :begin next-elem)))
22474 (size-blank (- (org-element-property :end elem)
22475 (save-excursion
22476 (goto-char (org-element-property :end elem))
22477 (skip-chars-backward " \r\t\n")
22478 (forward-line)
22479 (point)))))
22480 (org-element-swap-A-B elem next-elem)
22481 (goto-char (+ pos size-next size-blank))))))
22483 (defun org-mark-element ()
22484 "Put point at beginning of this element, mark at end.
22486 Interactively, if this command is repeated or (in Transient Mark
22487 mode) if the mark is active, it marks the next element after the
22488 ones already marked."
22489 (interactive)
22490 (let (deactivate-mark)
22491 (if (and (org-called-interactively-p 'any)
22492 (or (and (eq last-command this-command) (mark t))
22493 (and transient-mark-mode mark-active)))
22494 (set-mark
22495 (save-excursion
22496 (goto-char (mark))
22497 (goto-char (org-element-property :end (org-element-at-point)))))
22498 (let ((element (org-element-at-point)))
22499 (end-of-line)
22500 (push-mark (org-element-property :end element) t t)
22501 (goto-char (org-element-property :begin element))))))
22503 (defun org-narrow-to-element ()
22504 "Narrow buffer to current element."
22505 (interactive)
22506 (let ((elem (org-element-at-point)))
22507 (cond
22508 ((eq (car elem) 'headline)
22509 (narrow-to-region
22510 (org-element-property :begin elem)
22511 (org-element-property :end elem)))
22512 ((memq (car elem) org-element-greater-elements)
22513 (narrow-to-region
22514 (org-element-property :contents-begin elem)
22515 (org-element-property :contents-end elem)))
22517 (narrow-to-region
22518 (org-element-property :begin elem)
22519 (org-element-property :end elem))))))
22521 (defun org-transpose-element ()
22522 "Transpose current and previous elements, keeping blank lines between.
22523 Point is moved after both elements."
22524 (interactive)
22525 (org-skip-whitespace)
22526 (let ((end (org-element-property :end (org-element-at-point))))
22527 (org-drag-element-backward)
22528 (goto-char end)))
22530 (defun org-unindent-buffer ()
22531 "Un-indent the visible part of the buffer.
22532 Relative indentation (between items, inside blocks, etc.) isn't
22533 modified."
22534 (interactive)
22535 (unless (eq major-mode 'org-mode)
22536 (error "Cannot un-indent a buffer not in Org mode"))
22537 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22538 unindent-tree ; For byte-compiler.
22539 (unindent-tree
22540 (function
22541 (lambda (contents)
22542 (mapc
22543 (lambda (element)
22544 (if (memq (org-element-type element) '(headline section))
22545 (funcall unindent-tree (org-element-contents element))
22546 (save-excursion
22547 (save-restriction
22548 (narrow-to-region
22549 (org-element-property :begin element)
22550 (org-element-property :end element))
22551 (org-do-remove-indentation)))))
22552 (reverse contents))))))
22553 (funcall unindent-tree (org-element-contents parse-tree))))
22555 (defun org-show-subtree ()
22556 "Show everything after this heading at deeper levels."
22557 (interactive)
22558 (outline-flag-region
22559 (point)
22560 (save-excursion
22561 (org-end-of-subtree t t))
22562 nil))
22564 (defun org-show-entry ()
22565 "Show the body directly following this heading.
22566 Show the heading too, if it is currently invisible."
22567 (interactive)
22568 (save-excursion
22569 (condition-case nil
22570 (progn
22571 (org-back-to-heading t)
22572 (outline-flag-region
22573 (max (point-min) (1- (point)))
22574 (save-excursion
22575 (if (re-search-forward
22576 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22577 (match-beginning 1)
22578 (point-max)))
22579 nil)
22580 (org-cycle-hide-drawers 'children))
22581 (error nil))))
22583 (defun org-make-options-regexp (kwds &optional extra)
22584 "Make a regular expression for keyword lines."
22585 (concat
22586 "^#\\+\\("
22587 (mapconcat 'regexp-quote kwds "\\|")
22588 (if extra (concat "\\|" extra))
22589 "\\):[ \t]*\\(.*\\)"))
22591 ;; Make isearch reveal the necessary context
22592 (defun org-isearch-end ()
22593 "Reveal context after isearch exits."
22594 (when isearch-success ; only if search was successful
22595 (if (featurep 'xemacs)
22596 ;; Under XEmacs, the hook is run in the correct place,
22597 ;; we directly show the context.
22598 (org-show-context 'isearch)
22599 ;; In Emacs the hook runs *before* restoring the overlays.
22600 ;; So we have to use a one-time post-command-hook to do this.
22601 ;; (Emacs 22 has a special variable, see function `org-mode')
22602 (unless (and (boundp 'isearch-mode-end-hook-quit)
22603 isearch-mode-end-hook-quit)
22604 ;; Only when the isearch was not quitted.
22605 (org-add-hook 'post-command-hook 'org-isearch-post-command
22606 'append 'local)))))
22608 (defun org-isearch-post-command ()
22609 "Remove self from hook, and show context."
22610 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22611 (org-show-context 'isearch))
22614 ;;;; Integration with and fixes for other packages
22616 ;;; Imenu support
22618 (defvar org-imenu-markers nil
22619 "All markers currently used by Imenu.")
22620 (make-variable-buffer-local 'org-imenu-markers)
22622 (defun org-imenu-new-marker (&optional pos)
22623 "Return a new marker for use by Imenu, and remember the marker."
22624 (let ((m (make-marker)))
22625 (move-marker m (or pos (point)))
22626 (push m org-imenu-markers)
22629 (defun org-imenu-get-tree ()
22630 "Produce the index for Imenu."
22631 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22632 (setq org-imenu-markers nil)
22633 (let* ((n org-imenu-depth)
22634 (re (concat "^" (org-get-limited-outline-regexp)))
22635 (subs (make-vector (1+ n) nil))
22636 (last-level 0)
22637 m level head)
22638 (save-excursion
22639 (save-restriction
22640 (widen)
22641 (goto-char (point-max))
22642 (while (re-search-backward re nil t)
22643 (setq level (org-reduced-level (funcall outline-level)))
22644 (when (and (<= level n)
22645 (looking-at org-complex-heading-regexp))
22646 (setq head (org-link-display-format
22647 (org-match-string-no-properties 4))
22648 m (org-imenu-new-marker))
22649 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22650 (if (>= level last-level)
22651 (push (cons head m) (aref subs level))
22652 (push (cons head (aref subs (1+ level))) (aref subs level))
22653 (loop for i from (1+ level) to n do (aset subs i nil)))
22654 (setq last-level level)))))
22655 (aref subs 1)))
22657 (eval-after-load "imenu"
22658 '(progn
22659 (add-hook 'imenu-after-jump-hook
22660 (lambda ()
22661 (if (derived-mode-p 'org-mode)
22662 (org-show-context 'org-goto))))))
22664 (defun org-link-display-format (link)
22665 "Replace a link with either the description, or the link target
22666 if no description is present"
22667 (save-match-data
22668 (if (string-match org-bracket-link-analytic-regexp link)
22669 (replace-match (if (match-end 5)
22670 (match-string 5 link)
22671 (concat (match-string 1 link)
22672 (match-string 3 link)))
22673 nil t link)
22674 link)))
22676 (defun org-toggle-link-display ()
22677 "Toggle the literal or descriptive display of links."
22678 (interactive)
22679 (if org-descriptive-links
22680 (progn (org-remove-from-invisibility-spec '(org-link))
22681 (org-restart-font-lock)
22682 (setq org-descriptive-links nil))
22683 (progn (add-to-invisibility-spec '(org-link))
22684 (org-restart-font-lock)
22685 (setq org-descriptive-links t))))
22687 ;; Speedbar support
22689 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22690 "Overlay marking the agenda restriction line in speedbar.")
22691 (overlay-put org-speedbar-restriction-lock-overlay
22692 'face 'org-agenda-restriction-lock)
22693 (overlay-put org-speedbar-restriction-lock-overlay
22694 'help-echo "Agendas are currently limited to this item.")
22695 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22697 (defun org-speedbar-set-agenda-restriction ()
22698 "Restrict future agenda commands to the location at point in speedbar.
22699 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22700 (interactive)
22701 (require 'org-agenda)
22702 (let (p m tp np dir txt)
22703 (cond
22704 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22705 'org-imenu t))
22706 (setq m (get-text-property p 'org-imenu-marker))
22707 (with-current-buffer (marker-buffer m)
22708 (goto-char m)
22709 (org-agenda-set-restriction-lock 'subtree)))
22710 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22711 'speedbar-function 'speedbar-find-file))
22712 (setq tp (previous-single-property-change
22713 (1+ p) 'speedbar-function)
22714 np (next-single-property-change
22715 tp 'speedbar-function)
22716 dir (speedbar-line-directory)
22717 txt (buffer-substring-no-properties (or tp (point-min))
22718 (or np (point-max))))
22719 (with-current-buffer (find-file-noselect
22720 (let ((default-directory dir))
22721 (expand-file-name txt)))
22722 (unless (derived-mode-p 'org-mode)
22723 (error "Cannot restrict to non-Org-mode file"))
22724 (org-agenda-set-restriction-lock 'file)))
22725 (t (error "Don't know how to restrict Org-mode's agenda")))
22726 (move-overlay org-speedbar-restriction-lock-overlay
22727 (point-at-bol) (point-at-eol))
22728 (setq current-prefix-arg nil)
22729 (org-agenda-maybe-redo)))
22731 (eval-after-load "speedbar"
22732 '(progn
22733 (speedbar-add-supported-extension ".org")
22734 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22735 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22736 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22737 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22738 (add-hook 'speedbar-visiting-tag-hook
22739 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22741 ;;; Fixes and Hacks for problems with other packages
22743 ;; Make flyspell not check words in links, to not mess up our keymap
22744 (defun org-mode-flyspell-verify ()
22745 "Don't let flyspell put overlays at active buttons, or on
22746 {todo,all-time,additional-option-like}-keywords."
22747 (let ((pos (max (1- (point)) (point-min)))
22748 (word (thing-at-point 'word)))
22749 (and (not (get-text-property pos 'keymap))
22750 (not (get-text-property pos 'org-no-flyspell))
22751 (not (member word org-todo-keywords-1))
22752 (not (member word org-all-time-keywords))
22753 (not (member word org-options-keywords))
22754 (not (member word (mapcar 'car org-startup-options)))
22755 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22757 (defun org-remove-flyspell-overlays-in (beg end)
22758 "Remove flyspell overlays in region."
22759 (and (org-bound-and-true-p flyspell-mode)
22760 (fboundp 'flyspell-delete-region-overlays)
22761 (flyspell-delete-region-overlays beg end))
22762 (add-text-properties beg end '(org-no-flyspell t)))
22764 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22765 (eval-after-load "bookmark"
22766 '(if (boundp 'bookmark-after-jump-hook)
22767 ;; We can use the hook
22768 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22769 ;; Hook not available, use advice
22770 (defadvice bookmark-jump (after org-make-visible activate)
22771 "Make the position visible."
22772 (org-bookmark-jump-unhide))))
22774 ;; Make sure saveplace shows the location if it was hidden
22775 (eval-after-load "saveplace"
22776 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22777 "Make the position visible."
22778 (org-bookmark-jump-unhide)))
22780 ;; Make sure ecb shows the location if it was hidden
22781 (eval-after-load "ecb"
22782 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22783 "Make hierarchy visible when jumping into location from ECB tree buffer."
22784 (if (derived-mode-p 'org-mode)
22785 (org-show-context))))
22787 (defun org-bookmark-jump-unhide ()
22788 "Unhide the current position, to show the bookmark location."
22789 (and (derived-mode-p 'org-mode)
22790 (or (outline-invisible-p)
22791 (save-excursion (goto-char (max (point-min) (1- (point))))
22792 (outline-invisible-p)))
22793 (org-show-context 'bookmark-jump)))
22795 ;; Make session.el ignore our circular variable
22796 (eval-after-load "session"
22797 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22799 ;;;; Experimental code
22801 (defun org-closed-in-range ()
22802 "Sparse tree of items closed in a certain time range.
22803 Still experimental, may disappear in the future."
22804 (interactive)
22805 ;; Get the time interval from the user.
22806 (let* ((time1 (org-float-time
22807 (org-read-date nil 'to-time nil "Starting date: ")))
22808 (time2 (org-float-time
22809 (org-read-date nil 'to-time nil "End date:")))
22810 ;; callback function
22811 (callback (lambda ()
22812 (let ((time
22813 (org-float-time
22814 (apply 'encode-time
22815 (org-parse-time-string
22816 (match-string 1))))))
22817 ;; check if time in interval
22818 (and (>= time time1) (<= time time2))))))
22819 ;; make tree, check each match with the callback
22820 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22822 ;;;; Finish up
22824 (provide 'org)
22826 (run-hooks 'org-load-hook)
22828 ;;; org.el ends here